aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBob Badour <bbadour@google.com>2020-05-06 16:12:09 -0700
committerBob Badour <bbadour@google.com>2020-05-06 19:00:34 -0700
commit3a9e2b2b7b2e695d60979ecb3b72e49ec97ca27b (patch)
treec4efb96abd28c58f6dc220fdcc8ee8ab69f7ca38
parentfc7cda06f54946e3a03ea008c1ba086d90aeef84 (diff)
downloadsdk-3a9e2b2b7b2e695d60979ecb3b72e49ec97ca27b.tar.gz
Remove all non-Apache2 licensed files from sdk
Remove MODULE_LICENSE_APACHE2 Repositories containing third-party code need a METADATA and a license_type. Repositories containing only first-party code no longer need a MODULE_LICENSE_* file. Remove EPL-licensed eclipse plugin and attribute_stats. Remove CC-BY-SA licensed typos files. Bug: 68860345 Bug: 69058154 Bug: 151953481 Test: treehugger Test: https://android-build.googleplex.com/builds/forrest/run/L63500000550775268 Exempt-From-Owner-Approval: janitorial work Change-Id: I5fafa76de21fb0b46c82a2c07ac048afbee3df25
-rw-r--r--attribute_stats/.classpath6
-rw-r--r--attribute_stats/.gitignore1
-rw-r--r--attribute_stats/.project17
-rw-r--r--attribute_stats/.settings/org.eclipse.jdt.core.prefs98
-rw-r--r--attribute_stats/README.txt13
-rw-r--r--attribute_stats/src/Analyzer.java663
-rw-r--r--eclipse/.gitignore3
-rw-r--r--eclipse/artifacts/bundles/.project11
-rw-r--r--eclipse/artifacts/bundles/monitor.product61
-rw-r--r--eclipse/artifacts/bundles/pom.xml58
-rw-r--r--eclipse/build.gradle205
-rw-r--r--eclipse/buildConfig/allElements.xml112
-rw-r--r--eclipse/buildConfig/build.properties239
-rw-r--r--eclipse/buildConfig/buildUpdateSite.xml13
-rw-r--r--eclipse/buildConfig/customTargets.xml195
-rw-r--r--eclipse/changes.txt868
-rw-r--r--eclipse/dictionary.txt362
-rw-r--r--eclipse/features/com.android.ide.eclipse.adt.package/.project17
-rw-r--r--eclipse/features/com.android.ide.eclipse.adt.package/build.properties3
-rw-r--r--eclipse/features/com.android.ide.eclipse.adt.package/feature.xml45
-rw-r--r--eclipse/features/com.android.ide.eclipse.adt.package/p2.inf9
-rw-r--r--eclipse/features/com.android.ide.eclipse.adt.package/pom.xml17
-rw-r--r--eclipse/features/com.android.ide.eclipse.adt/.project17
-rw-r--r--eclipse/features/com.android.ide.eclipse.adt/build.properties1
-rw-r--r--eclipse/features/com.android.ide.eclipse.adt/feature.xml161
-rw-r--r--eclipse/features/com.android.ide.eclipse.adt/pom.xml17
-rw-r--r--eclipse/features/com.android.ide.eclipse.ddms/.project17
-rw-r--r--eclipse/features/com.android.ide.eclipse.ddms/build.properties1
-rw-r--r--eclipse/features/com.android.ide.eclipse.ddms/feature.xml253
-rw-r--r--eclipse/features/com.android.ide.eclipse.ddms/pom.xml17
-rw-r--r--eclipse/features/com.android.ide.eclipse.gldebugger/.project17
-rw-r--r--eclipse/features/com.android.ide.eclipse.gldebugger/build.properties1
-rw-r--r--eclipse/features/com.android.ide.eclipse.gldebugger/feature.xml232
-rw-r--r--eclipse/features/com.android.ide.eclipse.gldebugger/pom.xml17
-rw-r--r--eclipse/features/com.android.ide.eclipse.hierarchyviewer/.project17
-rw-r--r--eclipse/features/com.android.ide.eclipse.hierarchyviewer/build.properties1
-rw-r--r--eclipse/features/com.android.ide.eclipse.hierarchyviewer/feature.xml239
-rw-r--r--eclipse/features/com.android.ide.eclipse.hierarchyviewer/pom.xml17
-rw-r--r--eclipse/features/com.android.ide.eclipse.monitor/.project17
-rw-r--r--eclipse/features/com.android.ide.eclipse.monitor/build.properties1
-rw-r--r--eclipse/features/com.android.ide.eclipse.monitor/feature.xml233
-rw-r--r--eclipse/features/com.android.ide.eclipse.monitor/pom.xml17
-rw-r--r--eclipse/features/com.android.ide.eclipse.ndk/.project17
-rw-r--r--eclipse/features/com.android.ide.eclipse.ndk/build.properties1
-rw-r--r--eclipse/features/com.android.ide.eclipse.ndk/feature.xml117
-rw-r--r--eclipse/features/com.android.ide.eclipse.ndk/pom.xml17
-rw-r--r--eclipse/features/com.android.ide.eclipse.pdt/.project17
-rw-r--r--eclipse/features/com.android.ide.eclipse.pdt/build.properties1
-rw-r--r--eclipse/features/com.android.ide.eclipse.pdt/feature.xml245
-rw-r--r--eclipse/features/com.android.ide.eclipse.tests/.project17
-rw-r--r--eclipse/features/com.android.ide.eclipse.tests/build.properties1
-rw-r--r--eclipse/features/com.android.ide.eclipse.tests/feature.xml24
-rw-r--r--eclipse/features/com.android.ide.eclipse.traceview/.project17
-rw-r--r--eclipse/features/com.android.ide.eclipse.traceview/build.properties1
-rw-r--r--eclipse/features/com.android.ide.eclipse.traceview/feature.xml239
-rw-r--r--eclipse/features/com.android.ide.eclipse.traceview/pom.xml17
-rw-r--r--eclipse/monitor/build.gradle111
-rwxr-xr-xeclipse/monitor/monitor44
-rwxr-xr-xeclipse/monitor/monitor.bat32
-rw-r--r--eclipse/plugins/.gitignore7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.overlay/.classpath6
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.overlay/.project28
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.overlay/.settings/org.eclipse.jdt.core.prefs98
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.overlay/META-INF/MANIFEST.MF19
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.overlay/MODULE_LICENSE_EPL0
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.overlay/NOTICE221
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.overlay/README.txt14
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.overlay/build.properties4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.overlay/plugin.xml10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.overlay/pom.xml17
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.package/.project22
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.package/META-INF/MANIFEST.MF10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.package/about.ini5
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.package/about.properties6
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.package/adt-about.pngbin30784 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.package/build.properties11
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.package/icons/adt.icnsbin211430 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.package/icons/adt.icobin22486 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.package/icons/adt.pngbin66648 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.package/icons/adt16.pngbin1778 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.package/icons/adt32.pngbin2074 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.package/icons/adt48.pngbin3487 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.package/plugin.xml71
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.package/plugin_customization.ini8
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.package/pom.xml17
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt.package/splash.bmpbin450054 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/.classpath22
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/.gitignore1
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/.project30
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/.settings/org.eclipse.core.resources.prefs1
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/.settings/org.eclipse.jdt.core.prefs98
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/.settings/org.moreunit.prefs4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/META-INF/MANIFEST.MF140
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/MODULE_LICENSE_EPL0
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/NOTICE224
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/about.html108
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/about.ini2
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/about.properties7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/adt-platform-juno-sr2.target25
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/adt.launch33
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/build.properties12
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/AbsoluteLayout.pngbin1090 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/AdapterViewFlipper.pngbin550 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/AnalogClock.pngbin1409 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/AutoCompleteTextView.pngbin1215 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/Button.pngbin1333 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/CalendarView.pngbin190 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/CheckBox.pngbin1395 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/CheckedTextView.pngbin1152 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/Chronometer.pngbin1439 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/DatePicker.pngbin1205 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/DialerFilter.pngbin1247 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/DigitalClock.pngbin1302 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/EditText.pngbin1204 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/ExpandableListView.pngbin1104 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/FrameLayout.pngbin1068 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/Gallery.pngbin1251 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/GestureOverlayView.pngbin1570 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/GridLayout.pngbin248 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/GridView.pngbin1036 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/HorizontalScrollView.pngbin1063 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/ImageButton.pngbin1267 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/ImageSwitcher.pngbin1240 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/ImageView.pngbin1265 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/LinearLayout.pngbin1022 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/ListView.pngbin1053 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/MediaController.pngbin1204 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/MultiAutoCompleteTextView.pngbin1234 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/NumberPicker.pngbin441 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/ProgressBar.pngbin1187 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/QuickContactBadge.pngbin1266 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/RadioButton.pngbin1581 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/RadioGroup.pngbin1353 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/RatingBar.pngbin1595 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/RelativeLayout.pngbin1076 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/ScrollView.pngbin1067 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/SearchView.pngbin795 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/SeekBar.pngbin1349 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/SlidingDrawer.pngbin1104 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/Space.pngbin248 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/Spinner.pngbin1292 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/StackView.pngbin481 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/SurfaceView.pngbin1409 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/Switch.pngbin383 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/TabHost.pngbin1216 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/TabWidget.pngbin1226 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/TableLayout.pngbin1041 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/TableRow.pngbin1065 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/TextSwitcher.pngbin1174 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/TextView.pngbin1141 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/TextureView.pngbin560 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/TimePicker.pngbin1162 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/ToggleButton.pngbin1300 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/TwoLineListItem.pngbin1053 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/VerticalLinearLayout.pngbin236 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/VideoView.pngbin1230 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/View.pngbin1022 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/ViewAnimator.pngbin1156 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/ViewFlipper.pngbin1143 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/ViewStub.pngbin1033 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/ViewSwitcher.pngbin1105 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/WebView.pngbin1451 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/ZoomButton.pngbin1617 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/ZoomControls.pngbin1517 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/activity.pngbin590 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/add.pngbin146 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/android-32.pngbin2446 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/android-64.pngbin6502 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/android.pngbin197 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/android_app.pngbin454 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/android_file.pngbin519 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/android_project.pngbin146 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/androidjunit.pngbin393 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/attribute.pngbin370 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/avd_manager.pngbin269 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/az_sort.pngbin363 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/bidi.pngbin162 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/checker.pngbin1889 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/clipping.pngbin167 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/close.pngbin158 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/closed-folder.pngbin321 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/columns.pngbin535 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/components_view.pngbin340 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/customView.pngbin1512 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/default_template.pngbin20742 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/delete.pngbin107 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/dimension.pngbin320 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/display.pngbin345 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/dockmode.pngbin214 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/down.pngbin1134 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/dpi.pngbin302 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/draw9patch-16.pngbin1826 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/editPreview.pngbin243 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/editor_page_design.pngbin445 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/editor_page_source.pngbin488 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/element.pngbin449 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/error-badge.pngbin332 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/error.pngbin194 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/expandall-disabled.pngbin265 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/expandall.pngbin268 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/explode.pngbin216 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/filter_advanced_properties.pngbin331 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/flip_landscape.pngbin375 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/flip_portrait.pngbin377 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/fragment.pngbin1111 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/globe.pngbin906 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/goto_definition.pngbin241 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/gradle.pngbin841 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/height.pngbin271 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-all-disabled.pngbin392 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-all.pngbin635 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-file-disabled.pngbin378 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-file.pngbin651 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-project-disabled.pngbin354 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-project.pngbin587 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-this-disabled.pngbin332 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-this.pngbin509 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/include.pngbin1098 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/keyboard.pngbin307 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/landscape.pngbin247 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/language.pngbin287 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/lint1.pngbin322 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/lint2.pngbin422 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/lint3.pngbin424 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/lint4.pngbin372 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/lint5.pngbin404 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/lint6.pngbin442 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/lint7.pngbin387 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/lint8.pngbin430 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/lint9.pngbin421 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/lint9p.pngbin486 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/lintrun.pngbin422 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/lintview.pngbin545 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/mainLaunchTab.pngbin308 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/match.pngbin138 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/match_multiple.pngbin256 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/mcc.pngbin463 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/merge.pngbin1122 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/minimizePreview.pngbin181 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/mnc.pngbin265 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/navpad.pngbin308 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/newConfig.pngbin681 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/newCustomView.pngbin730 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/newJunit.pngbin530 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/new_adt_project.pngbin664 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/new_asset_set.pngbin907 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/new_xml.pngbin539 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/newannotation.pngbin472 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/nightmode.pngbin296 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/open-folder.pngbin383 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/options.pngbin401 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/orientation.pngbin175 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/outline.pngbin153 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/palette.pngbin804 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/portrait.pngbin228 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/properties_default.pngbin584 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/properties_view.pngbin454 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/quickfix-disabled.pngbin505 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/quickfix.pngbin495 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/quickfix_error.pngbin403 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/quickfix_warning.pngbin473 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/ratio.pngbin163 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/refresh.pngbin377 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/refreshPreview.pngbin3817 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/region.pngbin445 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/renderError.pngbin1077 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/requestFocus.pngbin1603 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/restorePreview.pngbin186 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/sdk_manager.pngbin219 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow-b.pngbin215 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow-bl.pngbin397 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow-br.pngbin406 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow-r.pngbin207 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow-tr.pngbin397 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow2-b.pngbin195 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow2-bl.pngbin277 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow2-br.pngbin282 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow2-r.pngbin192 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow2-tr.pngbin286 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/size.pngbin179 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/sort_alpha.pngbin277 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/square.pngbin226 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/swidth.pngbin287 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/text_input.pngbin321 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/themes.pngbin635 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/touch.pngbin344 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/up.pngbin1139 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/version.pngbin197 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/view_menu.pngbin205 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/warning-badge.pngbin345 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/warning.pngbin147 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/width.pngbin273 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/zoom100.pngbin1381 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/zoomfit.pngbin1383 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/zoomminus.pngbin1380 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/zoomplus.pngbin1383 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/icons/zoomreal.pngbin1390 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/plugin.xml1340
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/pom.xml17
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/AbsListViewRule.java28
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/AbsoluteLayoutRule.java254
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/AdapterViewRule.java62
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/BaseLayoutRule.java878
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/BaseViewRule.java996
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/CalendarViewRule.java44
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/DatePickerRule.java22
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/DialerFilterRule.java63
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/EditTextRule.java139
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/FragmentRule.java46
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/FrameLayoutRule.java195
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/GravityHelper.java233
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/GridLayoutRule.java676
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/GridViewRule.java41
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/HorizontalScrollViewRule.java96
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/IgnoredLayoutRule.java46
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ImageButtonRule.java54
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ImageViewRule.java57
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/IncludeRule.java46
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/LinearLayoutRule.java1092
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ListViewRule.java42
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/MapViewRule.java46
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/MergeRule.java38
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/PropertyCallback.java82
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/PropertySettingNodeHandler.java42
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/QuickContactBadgeRule.java34
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/RadioGroupRule.java50
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/RelativeLayoutRule.java413
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ResizeState.java131
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ScrollViewRule.java96
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/SeekBarRule.java42
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/SlidingDrawerRule.java68
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/TabHostRule.java82
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/TabWidgetRule.java27
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/TableLayoutRule.java218
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/TableRowRule.java80
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/TimePickerRule.java27
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ViewRule.java31
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ViewTagRule.java49
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/WebViewRule.java46
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ZoomButtonRule.java35
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ZoomControlsRule.java27
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/addcol.pngbin479 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/addrow.pngbin442 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/allweight.pngbin460 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/baseline.pngbin602 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/centerHorizontally.pngbin505 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/centerVertically.pngbin501 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/clearweights.pngbin573 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/constraints.pngbin507 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/distribute.pngbin460 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/fillheight.pngbin483 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/fillwidth.pngbin476 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/gravity.pngbin563 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/grid/GridDropHandler.java840
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/grid/GridLayoutPainter.java370
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/grid/GridMatch.java154
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/grid/GridModel.java2384
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/gridmode.pngbin519 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/hlinear.pngbin403 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/margins.pngbin503 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/ConstraintPainter.java783
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/ConstraintType.java241
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/DeletionHandler.java267
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/DependencyGraph.java326
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/GuidelineHandler.java839
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/GuidelinePainter.java208
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/Match.java100
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/MoveHandler.java299
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/ResizeHandler.java265
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/removecol.pngbin469 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/removerow.pngbin442 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/showgrid.pngbin477 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/snap.pngbin575 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/structure.pngbin546 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/vlinear.pngbin369 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/weights.pngbin520 -> 0 bytes
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/resources/platform/AttributeInfo.java355
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/resources/platform/AttrsXmlParser.java698
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/resources/platform/DeclareStyleableInfo.java102
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/resources/platform/ViewClassInfo.java158
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/AdtConstants.java242
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/AdtPlugin.java2045
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/AdtUtils.java1561
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/AndroidPrintStream.java89
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/DebuggerConnector.java159
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/Messages.java44
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/SourceRevealer.java465
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/ToolsLocator.java41
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/VersionCheck.java189
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/actions/AddSupportJarAction.java626
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/actions/AvdManagerAction.java78
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/actions/DexDumpAction.java276
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/actions/FixProjectAction.java154
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/actions/SdkManagerAction.java354
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/assetstudio/AssetType.java88
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/assetstudio/ChooseAssetTypePage.java225
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/assetstudio/ConfigureAssetSetPage.java1251
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/assetstudio/CreateAssetSetWizard.java312
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/assetstudio/CreateAssetSetWizardState.java258
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/assetstudio/OpenCreateAssetSetWizardAction.java58
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/AaptExecException.java29
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/AaptParser.java783
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/AaptQuickFix.java431
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/AaptResultException.java29
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/AidlProcessor.java484
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/BuildHelper.java1225
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/ConvertSwitchDialog.java144
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/ConvertSwitchQuickFixProcessor.java224
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/DefaultSourceChangeHandler.java105
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/DexException.java33
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/DexWrapper.java218
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/ExecResultException.java72
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/Messages.java150
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/NativeLibInJarException.java61
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/ProguardExecException.java30
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/ProguardResultException.java34
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/RenderScriptLauncher.java244
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/RsSourceChangeHandler.java90
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/SourceChangeHandler.java25
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/SourceFileData.java132
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/SourceProcessor.java454
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/build_messages.properties67
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/BaseBuilder.java483
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/ChangedFileSet.java70
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/ChangedFileSetHelper.java200
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/JavaResChangedSet.java46
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/PatternBasedDeltaVisitor.java139
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/PostCompilerBuilder.java946
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/PreCompilerBuilder.java1401
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/PreCompilerDeltaVisitor.java417
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/ResourceManagerBuilder.java317
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidContentAssist.java1331
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidDoubleClickStrategy.java92
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidOutlineConfiguration.java37
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidQuickOutlineConfiguration.java35
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidSourceViewerConfig.java243
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidTextEditor.java591
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidXmlAutoEditStrategy.java460
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidXmlCharacterMatcher.java238
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidXmlEditor.java1709
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/CompletionProposal.java229
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/Hyperlinks.java1893
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/IPageImageProvider.java33
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/IconFactory.java448
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/OutlineLabelProvider.java117
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/XmlEditorMultiOutline.java221
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/animator/AnimDescriptors.java124
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/animator/AnimationContentAssist.java168
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/animator/AnimationEditorDelegate.java173
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/animator/AnimatorDescriptors.java184
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/binaryxml/BinaryXMLDescriber.java80
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/binaryxml/BinaryXMLMultiPageEditorPart.java85
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/binaryxml/FileStorage.java120
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/binaryxml/XmlStorageEditorInput.java119
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/color/ColorContentAssist.java31
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/color/ColorDescriptors.java98
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/color/ColorEditorDelegate.java116
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/common/CommonActionContributor.java40
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/common/CommonMatchingStrategy.java84
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/common/CommonSourceViewerConfig.java66
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/common/CommonXmlDelegate.java249
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/common/CommonXmlEditor.java467
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/AttributeDescriptor.java121
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/AttributeDescriptorLabelProvider.java87
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/BooleanAttributeDescriptor.java33
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/DescriptorsUtils.java961
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/DocumentDescriptor.java57
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/ElementDescriptor.java485
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/EnumAttributeDescriptor.java42
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/FlagAttributeDescriptor.java92
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/IDescriptorProvider.java24
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/ITextAttributeCreator.java47
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/IUnknownDescriptorProvider.java38
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/ListAttributeDescriptor.java89
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/ReferenceAttributeDescriptor.java108
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/SeparatorAttributeDescriptor.java45
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/TextAttributeDescriptor.java290
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/TextValueDescriptor.java50
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/XmlnsAttributeDescriptor.java77
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/Draw9PatchEditor.java233
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/graphics/GraphicsUtilities.java169
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/graphics/NinePatchedImage.java882
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/ui/ImageEditorPanel.java97
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/ui/ImageViewer.java774
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/ui/MainFrame.java79
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/ui/StatusPanel.java357
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/ui/StretchesViewer.java267
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/drawable/DrawableContentAssist.java31
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/drawable/DrawableDescriptors.java301
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/drawable/DrawableEditorDelegate.java153
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/export/AbstractPropertiesFieldsPart.java356
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/export/ExportEditor.java107
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/export/ExportFieldsPart.java100
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/export/ExportLinksPart.java124
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/export/ExportPropertiesPage.java113
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/formatting/AndroidXmlFormatter.java83
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/formatting/AndroidXmlFormattingStrategy.java754
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/formatting/EclipseXmlFormatPreferences.java144
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/formatting/EclipseXmlPrettyPrinter.java249
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/formatting/XmlFormatProcessor.java58
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/formatting/XmlQuickAssistManager.java106
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/ActionBarHandler.java95
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/BasePullParser.java244
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/ContextPullParser.java166
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/ExplodedRenderingHelper.java421
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/LayoutContentAssist.java234
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/LayoutEditorDelegate.java1001
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/LayoutEditorMatchingStrategy.java81
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/LayoutReloadMonitor.java375
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/ProjectCallback.java693
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/UiElementPullParser.java661
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/WidgetPullParser.java174
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ActivityMenuListener.java162
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/Configuration.java1091
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ConfigurationChooser.java2096
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ConfigurationClient.java129
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ConfigurationDescription.java395
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ConfigurationMatcher.java843
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ConfigurationMenuListener.java290
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/DeviceMenuListener.java199
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/FlagManager.java215
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/LayoutCreatorDialog.java149
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/Locale.java184
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/LocaleMenuListener.java124
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/NestedConfiguration.java506
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/OrientationMenuAction.java180
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/SelectThemeAction.java50
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/TargetMenuListener.java126
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ThemeMenuAction.java318
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/VaryingConfiguration.java509
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/descriptors/CustomViewDescriptorService.java621
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/descriptors/LayoutDescriptors.java597
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/descriptors/ViewElementDescriptor.java249
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/AccordionControl.java396
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/BinPacker.java352
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/CanvasAlternateSelection.java73
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/CanvasTransform.java215
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/CanvasViewInfo.java1178
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ClipboardSupport.java429
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ControlPoint.java195
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/CreateNewConfigJob.java132
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/CustomViewFinder.java395
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/DelegatingAction.java203
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/DomUtilities.java915
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/DropGesture.java87
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/DynamicContextMenu.java654
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/EmptyViewsOverlay.java96
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ExportScreenshotAction.java82
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/FragmentMenu.java304
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/GCWrapper.java645
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/Gesture.java156
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/GestureManager.java930
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/GestureToolTip.java217
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/GlobalCanvasDragInfo.java182
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/GraphicalEditorPart.java2937
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/HoverOverlay.java187
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ImageControl.java241
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ImageOverlay.java447
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ImageUtils.java979
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/IncludeFinder.java1111
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/IncludeOverlay.java150
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutActionBar.java732
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutCanvas.java1720
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutCanvasViewer.java165
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutMetadata.java413
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutPoint.java156
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutWindowCoordinator.java394
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LintOverlay.java140
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LintTooltip.java94
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LintTooltipManager.java181
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ListViewTypeMenu.java220
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/MarqueeGesture.java160
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/MoveGesture.java852
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/OutlineDragListener.java129
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/OutlineDropListener.java217
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/OutlineOverlay.java107
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/OutlinePage.java1439
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/Overlay.java91
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/PaletteControl.java1265
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/PlayAnimationMenu.java247
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/PreviewIconFactory.java642
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderLogger.java327
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderPreview.java1333
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderPreviewList.java222
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderPreviewManager.java1696
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderPreviewMode.java43
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderService.java668
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ResizeGesture.java279
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SelectionHandle.java141
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SelectionHandles.java140
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SelectionItem.java252
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SelectionManager.java1262
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SelectionOverlay.java247
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ShowWithinMenu.java82
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SimpleAttribute.java124
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SimpleElement.java370
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SimpleXmlTransfer.java154
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SubmenuAction.java75
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SwtDrawingStyle.java319
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SwtUtils.java457
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ViewHierarchy.java771
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/ClientRulesEngine.java762
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/NodeFactory.java86
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/NodeProxy.java517
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/PaletteMetadataDescriptor.java120
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/RuleLoader.java192
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/RulesEngine.java876
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/ViewMetadataRepository.java856
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/extra-view-metadata.xml452
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/rendering-configs.xml382
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/BooleanXmlPropertyEditor.java118
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/EnumXmlPropertyEditor.java77
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/FlagXmlPropertyDialog.java217
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/PropertyFactory.java750
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/PropertyMetadata.java329
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/PropertySheetPage.java403
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/PropertyValueCompleter.java41
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/ResourceValueCompleter.java182
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/StringXmlPropertyDialog.java47
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/ValueCompleter.java186
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/XmlProperty.java278
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/XmlPropertyComposite.java121
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/XmlPropertyEditor.java548
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeLayoutAction.java47
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeLayoutContribution.java40
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeLayoutRefactoring.java657
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeLayoutWizard.java195
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeViewAction.java47
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeViewContribution.java40
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeViewRefactoring.java298
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeViewWizard.java199
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractIncludeAction.java47
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractIncludeContribution.java40
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractIncludeRefactoring.java670
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractIncludeWizard.java126
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractStyleAction.java47
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractStyleContribution.java40
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractStyleRefactoring.java579
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractStyleWizard.java440
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/GridLayoutConverter.java988
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/JavaQuickAssistant.java73
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/RefactoringAssistant.java336
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/RelativeLayoutConversionHelper.java1633
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UnwrapAction.java47
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UnwrapContribution.java40
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UnwrapRefactoring.java246
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UnwrapWizard.java31
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UseCompoundDrawableAction.java48
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UseCompoundDrawableRefactoring.java452
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UseCompoundDrawableWizard.java31
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/VisualRefactoring.java1403
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/VisualRefactoringAction.java170
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/VisualRefactoringWizard.java76
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/WrapInAction.java47
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/WrapInContribution.java40
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/WrapInRefactoring.java439
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/WrapInWizard.java268
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/uimodel/UiViewElementNode.java208
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/ManifestContentAssist.java94
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/ManifestEditor.java578
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/ManifestEditorContributor.java100
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/ManifestInfo.java957
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/ManifestSourceViewerConfig.java43
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/AndroidManifestDescriptors.java628
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/ClassAttributeDescriptor.java106
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/ManifestElementDescriptor.java123
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/ManifestPkgAttrDescriptor.java56
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/PackageAttributeDescriptor.java41
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/PostActivityCreationAction.java89
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/PostReceiverCreationAction.java89
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/ThemeAttributeDescriptor.java57
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/model/UiClassAttributeNode.java736
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/model/UiManifestElementNode.java132
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/model/UiManifestPkgAttrNode.java331
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/model/UiPackageAttributeNode.java321
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/ApplicationAttributesPart.java175
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/ApplicationPage.java136
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/ApplicationToggle.java312
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/InstrumentationPage.java102
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/OverviewExportPart.java123
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/OverviewInfoPart.java87
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/OverviewLinksPart.java124
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/OverviewPage.java165
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/PermissionPage.java111
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/menu/MenuContentAssist.java33
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/menu/MenuEditorDelegate.java175
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/menu/MenuTreePage.java71
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/menu/descriptors/MenuDescriptors.java199
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/otherxml/OtherXmlContentAssist.java33
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/otherxml/OtherXmlEditorDelegate.java135
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/otherxml/OtherXmlTreePage.java71
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/otherxml/PlainXmlEditorDelegate.java50
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/otherxml/descriptors/OtherXmlDescriptors.java373
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/EditableDialogCellEditor.java490
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/ErrorImageComposite.java72
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/FlagValueCellEditor.java58
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/ListValueCellEditor.java76
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/ResourceValueCellEditor.java59
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/SectionHelper.java364
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/TextValueCellEditor.java43
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/UiElementPart.java284
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/CopyCutAction.java221
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/ICommitXml.java28
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/NewItemSelectionDialog.java415
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/PasteAction.java129
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/UiActions.java598
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/UiElementDetail.java494
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/UiModelTreeContentProvider.java120
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/UiModelTreeLabelProvider.java106
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/UiTreeBlock.java946
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/IUiSettableAttributeNode.java32
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/IUiUpdateListener.java47
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiAbstractTextAttributeNode.java120
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiAttributeNode.java174
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiDocumentNode.java160
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiElementNode.java2160
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiFlagAttributeNode.java310
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiListAttributeNode.java220
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiResourceAttributeNode.java523
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiSeparatorAttributeNode.java146
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiTextAttributeNode.java196
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiTextValueNode.java118
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/ValuesContentAssist.java242
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/ValuesEditorDelegate.java144
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/ValuesTreePage.java108
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/descriptors/ColorValueDescriptor.java41
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/descriptors/ItemElementDescriptor.java55
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/descriptors/ValuesDescriptors.java337
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/uimodel/UiColorValueNode.java82
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/uimodel/UiItemElementNode.java58
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AMReceiver.java161
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/ActivityLaunchAction.java124
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AndroidLaunch.java57
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AndroidLaunchConfiguration.java192
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AndroidLaunchController.java1872
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AvdCompatibility.java58
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/DelayedLaunchInfo.java244
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/DeviceChooserDialog.java824
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/EmptyLaunchAction.java49
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/EmulatorConfigTab.java596
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/IAndroidLaunchAction.java43
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/ILaunchController.java40
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/JUnitLaunchConfigDelegate.java156
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/LaunchConfigDelegate.java424
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/LaunchConfigTabGroup.java42
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/LaunchMessages.java60
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/LaunchShortcut.java104
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/MainLaunchConfigTab.java494
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/AndroidJUnitLaunchAction.java293
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/AndroidJUnitLaunchConfigDelegate.java286
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/AndroidJUnitLaunchConfigurationTab.java1061
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/AndroidJUnitLaunchShortcut.java56
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/AndroidJUnitPropertyTester.java131
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/AndroidJUnitTabGroup.java44
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/InstrumentationRunnerValidator.java159
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/runtime/AndroidJUnitLaunchInfo.java148
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/runtime/AndroidTestReference.java65
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/runtime/RemoteAdtTestRunner.java524
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/runtime/TestCaseReference.java67
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/runtime/TestCollector.java136
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/runtime/TestSuiteReference.java92
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/messages.properties43
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/AddPrefixFix.java69
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/AddSuppressAnnotation.java424
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/AddSuppressAttribute.java237
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/ClearLintMarkersAction.java44
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/ColumnDialog.java124
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/ConvertToDpFix.java113
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/DocumentFix.java63
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/DosLineEndingsFix.java64
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/EclipseLintClient.java1306
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/EclipseLintIssueRegistry.java65
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/EclipseLintRunner.java238
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/ExtractStringFix.java90
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/GlobalLintConfiguration.java176
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/InputDensityDialog.java118
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LinearLayoutWeightFix.java78
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintColumn.java532
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintDeltaProcessor.java201
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintEditAction.java49
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintFix.java226
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintFixGenerator.java563
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintJob.java201
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintList.java979
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintListDialog.java303
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintViewPart.java657
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/ObsoleteLayoutParamsFix.java80
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/ProjectLintConfiguration.java90
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/RemoveUselessViewFix.java99
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/RunLintAction.java232
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/SetAttributeFix.java151
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/SetPropertyFix.java140
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/SetScrollViewSizeFix.java73
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/TypoFix.java123
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/TypographyFix.java94
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/UseCompoundDrawableDetectorFix.java95
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/AdtPrefs.java647
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/AndroidPreferencePage.java266
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/BuildPreferencePage.java386
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/EditorsPage.java182
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/LaunchPreferencePage.java52
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/LintPreferencePage.java752
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/Messages.java51
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/messages.properties18
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/AndroidClasspathContainer.java69
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/AndroidClasspathContainerInitializer.java823
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/AndroidClasspathContainerPage.java200
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/AndroidExportNature.java96
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/AndroidManifestHelper.java203
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/AndroidNature.java299
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/ApkInstallManager.java278
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/BaseClasspathContainerInitializer.java103
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/BaseProjectHelper.java527
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/ExportHelper.java448
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/FixLaunchConfig.java156
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/FolderDecorator.java109
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/LibraryClasspathContainerInitializer.java641
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/ProjectChooserHelper.java304
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/ProjectHelper.java1153
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/SupportLibraryHelper.java176
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/XmlErrorHandler.java175
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/properties/AndroidPropertyPage.java191
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/properties/LibraryProperties.java374
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/AndroidPackageRenameParticipant.java547
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/AndroidTypeMoveParticipant.java362
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/AndroidTypeRenameParticipant.java529
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/FixImportsJob.java148
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RefactoringUtil.java224
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourcePage.java177
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourceParticipant.java752
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourceProcessor.java211
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourceWizard.java157
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourceXmlTextAction.java410
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResult.java163
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/EnabledTextEditGroup.java40
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringAction.java184
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringContribution.java53
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringDescriptor.java71
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringInputPage.java606
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringProposal.java185
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringRefactoring.java1933
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringWizard.java50
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ReplaceStringsVisitor.java480
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/XmlStringFileHelper.java187
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/renamepackage/ApplicationPackageNameRefactoring.java586
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/renamepackage/ApplicationPackageNameRefactoringWizard.java35
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/renamepackage/RenamePackageAction.java174
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/CyclicDependencyValidator.java66
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/ResourceHelper.java628
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/ResourceNameValidator.java242
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/CompiledResourcesMonitor.java313
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/DynamicIdMap.java75
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/GlobalProjectMonitor.java546
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/IdeScanningContext.java234
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ProjectClassLoader.java376
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ProjectResources.java271
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ResourceManager.java655
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/AdtConsoleSdkLog.java59
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/AdtManifestMergeCallback.java46
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/AndroidJarLoader.java458
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/AndroidTargetData.java417
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/AndroidTargetParser.java605
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/IAndroidClassLoader.java81
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/LayoutParamsParser.java378
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/ProjectState.java740
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/Sdk.java1620
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/WidgetClassLoader.java343
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/layout-devices.xsd345
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sourcelookup/AdtSourceLookupDirector.java119
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ConfigurationSelector.java1989
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/EclipseUiHelper.java64
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/IUpdateWizardDialog.java30
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/MarginChooser.java229
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ReferenceChooserDialog.java396
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ResourceChooser.java958
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ResourceContentProvider.java124
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ResourceExplorerView.java353
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ResourceLabelProvider.java142
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ResourcePreviewHelper.java195
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/WizardDialogEx.java46
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/utils/FingerprintUtils.java63
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/welcome/AdtStartup.java366
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/welcome/UsagePermissionPage.java148
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/welcome/WelcomeWizard.java207
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/welcome/WelcomeWizardPage.java302
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/actions/ExportAction.java85
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/actions/ExportWizardAction.java94
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/actions/NewProjectAction.java36
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/actions/NewTestProjectAction.java34
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/actions/NewXmlFileAction.java36
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/actions/OpenWizardAction.java183
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/export/ExportWizard.java626
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/export/KeyCheckPage.java378
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/export/KeyCreationPage.java339
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/export/KeySelectionPage.java268
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/export/KeystoreSelectionPage.java264
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/export/ProjectCheckPage.java291
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/BuildFileCreator.java642
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ConfirmationPage.java275
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ExportMessages.java43
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ExportMessages.properties27
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ExportStatus.java56
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/FinalPage.java112
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/GradleExportWizard.java111
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/GradleModule.java90
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ImportInsteadPage.java55
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ProjectSelectionPage.java275
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ProjectSetupBuilder.java425
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/ApplicationInfoPage.java809
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/FileStoreAdapter.java160
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/ImportPage.java512
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/ImportProjectWizard.java94
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/ImportedProject.java256
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/NewProjectCreator.java1520
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/NewProjectWizard.java181
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/NewProjectWizardState.java412
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/NewSampleProjectWizard.java32
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/NewTestProjectWizard.java32
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/ProjectNamePage.java606
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/SampleSelectionPage.java271
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/SdkSelectionPage.java487
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/TestTargetPage.java293
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/WorkingSetGroup.java109
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/WorkingSetHelper.java130
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newxmlfile/AddTranslationDialog.java653
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newxmlfile/ChooseConfigurationPage.java282
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newxmlfile/NewXmlFileCreationPage.java1163
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newxmlfile/NewXmlFileWizard.java431
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/ActivityPage.java326
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/CreateFileChange.java107
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmActivityToLayoutMethod.java64
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmCamelCaseToUnderscoreMethod.java38
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmClassNameToResourceMethod.java67
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmEscapeXmlAttributeMethod.java40
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmEscapeXmlStringMethod.java43
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmEscapeXmlTextMethod.java40
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmExtractLettersMethod.java45
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmLayoutToActivityMethod.java61
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmSlashedPackageNameMethod.java39
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmUnderscoreToCamelCaseMethod.java39
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/InstallDependencyPage.java298
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewActivityWizard.java187
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewProjectPage.java931
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewProjectWizard.java456
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewProjectWizardState.java125
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewTemplatePage.java946
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewTemplateWizard.java212
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewTemplateWizardState.java215
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/Parameter.java417
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/ProjectContentsPage.java380
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/StringEvaluator.java101
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateHandler.java1239
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateManager.java261
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateMetadata.java468
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplatePreviewPage.java46
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateTestPage.java161
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateTestWizard.java78
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateWizard.java222
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TypedVariable.java50
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/UpdateToolsPage.java94
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/io/IFileWrapper.java159
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/io/IFolderWrapper.java200
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/messages.properties14
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/templates/AndroidManifest.template12
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/templates/activity.template7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/templates/ic_launcher_hdpi.pngbin9397 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/templates/ic_launcher_ldpi.pngbin2729 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/templates/ic_launcher_mdpi.pngbin5237 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/templates/ic_launcher_xhdpi.pngbin14383 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/templates/java_file.template13
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/templates/launcher_intent_filter.template1
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/templates/layout.template15
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/templates/preference_intent_filter.template1
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/templates/string.template1
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/templates/strings.template5
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/templates/test_instrumentation.template1
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.adt/templates/test_uses-library.template1
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.adt/templates/uses-sdk.template1
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.base/.classpath21
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.base/.gitignore1
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.base/.project28
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.base/.settings/org.eclipse.jdt.core.prefs98
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.base/META-INF/MANIFEST.MF157
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.base/build.properties7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.base/plugin.xml14
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.base/pom.xml17
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.base/src/com/android/ide/eclipse/base/InstallDetails.java41
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.base/src/com/android/ide/eclipse/base/internal/preferences/UsagePreferencePage.java123
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/.classpath13
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/.gitignore1
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/.project28
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/.settings/org.eclipse.jdt.core.prefs98
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/META-INF/MANIFEST.MF43
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/MODULE_LICENSE_APACHE20
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/about.html226
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/about.ini2
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.ddms/about.properties7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/build.properties13
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/icons/android.pngbin197 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/icons/ddms-16.pngbin1894 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/icons/ddms-32.pngbin2244 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/icons/device.pngbin135 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/icons/emulator-16.pngbin1766 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/icons/heap.pngbin222 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/icons/logcat.pngbin1160 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/icons/networkstats.pngbin476 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/icons/systrace.pngbin459 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/icons/thread.pngbin121 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/icons/uiautomator.pngbin1226 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/plugin.properties21
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/plugin.xml156
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/pom.xml17
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/schema/clientAction.exsd94
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/schema/debuggerConnector.exsd104
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/schema/sourceRevealer.exsd96
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/schema/toolsLocator.exsd104
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/schema/traceviewLauncher.exsd100
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/CommonAction.java70
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/DdmsPlugin.java876
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/IClientAction.java26
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/IDebuggerConnector.java45
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/ISourceRevealer.java43
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/IToolsLocator.java41
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/ITraceviewLauncher.java25
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/JavaSourceRevealer.java83
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/LogCatMonitor.java277
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/LogCatMonitorDialog.java118
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/Perspective.java89
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/editors/UiAutomatorViewer.java172
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/i18n/Messages.java121
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/i18n/messages.properties107
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/preferences/LogCatColorsPage.java65
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/preferences/LogCatPreferencePage.java159
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/preferences/PreferenceInitializer.java155
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/preferences/PreferencePage.java152
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/ISystraceOptions.java25
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/ISystraceOptionsDialog.java23
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/SystraceOptionsDialogV1.java445
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/SystraceOptionsDialogV2.java369
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/SystraceOutputParser.java169
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/SystraceTag.java27
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/SystraceTask.java101
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/SystraceVersionDetector.java100
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/AllocTrackerView.java47
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/DeviceView.java877
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/EmulatorControlView.java42
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/EventLogView.java111
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/FileExplorerView.java181
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/HeapView.java47
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/LogCatView.java120
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/NativeHeapView.java47
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/NetworkStatisticsView.java47
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/OldLogCatView.java385
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/SelectionDependentViewPart.java71
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/SysInfoView.java29
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/TableView.java101
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/ThreadView.java47
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/.classpath11
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/.project28
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/META-INF/MANIFEST.MF10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/build.properties4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/pom.xml17
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/src/com/android/ide/eclipse/gltrace/format/GLAPISpecTest.java74
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/src/com/android/ide/eclipse/gltrace/format/GLMessageFormatterTest.java195
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.gldebugger/.classpath9
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.gldebugger/.project28
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/.settings/org.eclipse.jdt.core.prefs98
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/META-INF/MANIFEST.MF23
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/build.properties8
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/entries.in549
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/icons/connect.pngbin294 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/icons/expandall.pngbin268 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/icons/opengl.pngbin487 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/icons/sample.gifbin983 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/icons/zoomfit.pngbin542 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/plugin.xml99
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/pom.xml17
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/CollectTraceAction.java428
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/DeviceViewAction.java113
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/FileUtils.java42
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GLEnum.java1017
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GLProtoBuf.java3119
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GLTraceCollectorDialog.java228
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GLTraceOptionsDialog.java403
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GLTracePerspective.java56
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GLUtils.java110
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GlTracePlugin.java130
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/OpenGLTraceAction.java88
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/ProtoBufUtils.java86
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/SwtUtils.java33
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/TraceCommandWriter.java60
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/TraceFileInfo.java41
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/TraceFileParserTask.java254
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/TraceFileReader.java66
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/TraceFileWriter.java156
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/TraceOptions.java55
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/editors/DurationMinimap.java541
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/editors/GLCallGroups.java202
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/editors/GLFunctionTraceViewer.java984
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/editors/StateContentProvider.java75
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/editors/StateLabelProvider.java103
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/editors/StateViewPage.java372
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/format/GLAPISpec.java134
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/format/GLDataTypeSpec.java75
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/format/GLMessageFormatter.java166
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/model/GLCall.java183
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/model/GLFrame.java51
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/model/GLTrace.java120
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/DisplayRadix.java21
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLAbstractAtomicProperty.java65
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLBooleanProperty.java64
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLCompositeProperty.java136
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLEnumProperty.java64
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLFloatProperty.java63
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLIntegerProperty.java73
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLListProperty.java182
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLLongProperty.java73
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLObjectProperty.java66
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLSparseArrayProperty.java170
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLState.java402
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLStateType.java187
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLStringProperty.java62
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/IGLProperty.java63
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/StatePrettyPrinter.java67
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/BufferSubDataTransform.java76
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/CurrentProgramPropertyAccessor.java67
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/CurrentVboPropertyAccessor.java71
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/GLPropertyAccessor.java139
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/IGLPropertyAccessor.java31
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/IPredicate.java21
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/IStateTransform.java34
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/ListElementAddTransform.java69
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/Predicates.java36
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/PropertyChangeTransform.java103
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/SparseArrayElementAddTransform.java77
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/SparseArrayElementRemoveTransform.java49
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/StateTransformFactory.java1384
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/TexImageTransform.java342
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/TexturePropertyAccessor.java86
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/TextureUnitPropertyAccessor.java64
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/FitToCanvasAction.java40
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/FrameSummaryView.java53
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/FrameSummaryViewPage.java442
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/GLPageBookView.java83
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/SaveImageAction.java59
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/StateView.java57
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/DetailsPage.java232
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/DetailsView.java52
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/GlDrawCallDetailProvider.java82
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/ICallDetailProvider.java31
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/IDetailProvider.java38
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/IStateDetailProvider.java27
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/ShaderSourceDetailsProvider.java103
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/ShaderUniformDetailsProvider.java173
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/TextureImageDetailsProvider.java158
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/VboDetailProvider.java189
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/VertexAttribPointerDataDetailProvider.java72
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/widgets/ImageCanvas.java250
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/.classpath10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/.project28
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/.settings/org.eclipse.jdt.core.prefs98
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/META-INF/MANIFEST.MF18
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/MODULE_LICENSE_APACHE20
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/about.html218
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/about.ini2
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.hierarchyviewer/about.properties7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/build.properties10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/icons/device.pngbin135 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/icons/hierarchyviewer-16.pngbin1831 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/icons/hierarchyviewer-32.pngbin2268 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/icons/pixel-perfect.pngbin412 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/icons/tree-view.pngbin288 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/plugin.xml91
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/pom.xml17
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/HierarchyViewerPlugin.java200
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/HierarchyViewerPluginDirector.java122
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/PixelPerfectPespective.java62
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/TreeViewPerspective.java66
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/DeviceSelectorView.java119
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/LayoutView.java160
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/PixelPerfectLoupeView.java171
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/PixelPerfectTreeView.java61
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/PixelPerfectView.java67
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/PropertyView.java43
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/TreeOverviewView.java43
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/TreeViewView.java103
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/.classpath10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/.project28
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/.settings/org.eclipse.jdt.core.prefs98
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/META-INF/MANIFEST.MF17
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/build.properties10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/images/avd_manager.pngbin269 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/images/ddms-128.pngbin17692 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/images/ddms-16.pngbin854 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/images/ddms-32.pngbin2402 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/images/ddms.icnsbin99171 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/images/sdk_manager.pngbin219 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/monitor.launch32
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/plugin.properties8
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/plugin.xml132
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/plugin_customization.ini6
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/pom.xml17
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/splash.bmpbin90998 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/AndroidPreferencePage.java43
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/MonitorActionBarAdvisor.java105
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/MonitorApplication.java179
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/MonitorPlugin.java65
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/MonitorStartup.java87
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/MonitorWorkbenchAdvisor.java43
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/MonitorWorkbenchWindowAdvisor.java41
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/SdkLocationChooserDialog.java122
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/SdkToolsLocator.java116
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/SwtUtils.java29
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/ToolsLocator.java42
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/actions/AvdManagerAction.java24
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/actions/SdkManagerAction.java79
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/ddms/DebugPortProvider.java165
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/ddms/StaticPortConfigDialog.java396
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/ddms/StaticPortEditDialog.java334
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/handlers/StaticPortConfigHandler.java33
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/.classpath10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/.project28
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/.settings/org.eclipse.jdt.core.prefs98
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/META-INF/MANIFEST.MF28
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/MODULE_LICENSE_EPL0
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/NOTICE224
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/about.html106
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/about.ini2
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.ndk/about.properties7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/build.properties12
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/discovery/test.c0
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/discovery/test.cpp0
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/icons/android-32.pngbin2446 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/icons/android_app.pngbin454 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/icons/obj16/c_app.gifbin606 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/icons/view16/debugger_tab.gifbin348 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/icons/view16/startup_tab.gifbin527 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/plugin.xml208
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/pom.xml17
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/Activator.java84
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/Messages.java63
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/NativeAbi.java46
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/NdkHelper.java184
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/NdkManager.java74
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/NdkVariables.java31
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/actions/AddNativeAction.java69
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/build/NdkCommandLauncher.java133
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/build/NdkEnvSupplier.java121
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/discovery/NdkDiscoveredPathInfo.java203
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/discovery/NdkDiscoveryUpdater.java314
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/discovery/NdkScannerInfoCollector.java103
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/GdbServerTask.java118
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/Messages.java62
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/NdkDebuggerTab.java311
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/NdkGdbLaunchConfigTabGroups.java39
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/NdkGdbLaunchDelegate.java506
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/NdkGdbLaunchShortcut.java127
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/NdkLaunchConstants.java44
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/NdkMainLaunchConfigTab.java61
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/messages.properties32
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/messages.properties16
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/preferences/NdkPreferenceInitializer.java33
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/preferences/NdkPreferencePage.java93
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/templates/SetFolders.java105
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/templates/SimpleFile.java125
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/templates/TemplatedInputStream.java87
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/wizards/AddNativeWizard.java130
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/wizards/AddNativeWizardPage.java82
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/wizards/NdkWizardHandler.java41
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/templates/addNdkSupport.xml33
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/templates/resources/main.cpp1
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.ndk/templates/resources/tAndroid.mk8
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.pdt/.classpath7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.pdt/.project28
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.pdt/.settings/org.eclipse.jdt.core.prefs98
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.pdt/META-INF/MANIFEST.MF21
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.pdt/build.properties5
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.pdt/plugin.xml30
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.pdt/src/com/android/ide/eclipse/pdt/PdtPlugin.java146
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.pdt/src/com/android/ide/eclipse/pdt/internal/DebuggerConnector.java155
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.pdt/src/com/android/ide/eclipse/pdt/internal/DevTreeProjectProvider.java140
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.pdt/src/com/android/ide/eclipse/pdt/internal/SourceRevealer.java180
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.pdt/src/com/android/ide/eclipse/pdt/internal/ToolsLocator.java41
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.pdt/src/com/android/ide/eclipse/pdt/internal/preferences/PrefPage.java63
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/.classpath24
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/.project29
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/.settings/org.eclipse.jdt.core.prefs98
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/META-INF/MANIFEST.MF16
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/MODULE_LICENSE_EPL0
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/NOTICE224
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/README.txt101
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/build.properties17
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/not_source_folder/jar/example/Class1.java35
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/not_source_folder/jar/example/Class2.java21
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/pom.xml17
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/prefs.template3
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/build/AaptParserTest.java200
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/build/AaptQuickFixTest.java289
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/AndroidContentAssistTest.java990
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/AndroidXmlAutoEditStrategyTest.java473
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/AndroidXmlCharacterMatcherTest.java144
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/HyperlinksTest.java320
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/formatting/EclipseXmlPrettyPrinterTest.java978
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutMetadataTest.java109
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/AdtProjectTest.java495
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeLayoutRefactoringTest.java136
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeViewRefactoringTest.java59
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractIncludeRefactoringTest.java170
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractStyleRefactoringTest.java232
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/RefactoringAssistantTest.java128
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/RefactoringTest.java334
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UnwrapRefactoringTest.java58
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UseCompoundDrawableRefactoringTest.java114
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/WrapInRefactoringTest.java59
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/TestFragment.java.txt15
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror1.xml12
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror2.xml9
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror3.xml6
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror4.xml7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror5.xml6
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror6.xml11
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror7.xml10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/anim1-expected-completion53.txt6
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/anim1-expected-completion54.txt6
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/anim1-expected-completion55.txt16
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/anim1-expected-completion56.txt14
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/anim1-expected-completion57.txt3
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/anim1.xml20
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/animator1-expected-completion58.txt4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/animator1-expected-completion59.txt10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/animator1-expected-completion60.txt3
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/animator1-expected-completion61.txt19
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/animator1.xml27
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken1-expected-applyCompletion15.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken1-expected-completion20.txt2
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken1.xml12
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken2-expected-applyCompletion16.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken2-expected-completion21.txt7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken2.xml12
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken3-expected-applyCompletion14.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken3-expected-completion19.txt2
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken3.xml12
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/color1-expected-completion45.txt2
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/color1-expected-completion46a.txt2
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/color1-expected-completion46b.txt20
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/color1.xml6
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-actual-applyCompletion1.xml19
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion1.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion10.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion11a.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion11b.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion12.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion2.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion3.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion39.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion4.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion5.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion6.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion7a.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion7b.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion8.diff2
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion9.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion1.txt3
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion10.txt11
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion11.txt67
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion12.txt67
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion2.txt4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion3.txt2
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion39.txt156
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion4.txt7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion5.txt2
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion6.txt23
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion7a.txt2
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion7b.txt2
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion8.txt2
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion9.txt4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1.xml19
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion10-expected-applyCompletion42.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion10-expected-applyCompletion43.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion10-expected-completion65.txt4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion10.xml10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion11-expected-applyCompletion46.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion11-expected-complation79.txt10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion11-expected-completion72.txt3
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion11-expected-completion73.txt16
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion11-expected-completion74.txt2
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion11.xml15
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion12-expected-completion75.txt96
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion12.xml7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2-expected-applyCompletion13a.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2-expected-applyCompletion13b.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2-expected-applyCompletion13c.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2-expected-completion13a.txt15
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2-expected-completion13b.txt4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2-expected-completion13c.txt14
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2.xml5
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion3-expected-applyCompletion17.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion3-expected-applyCompletion18.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion3.xml5
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion4-expected-completion22.txt2
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion4.xml11
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion5-expected-applyCompletion19.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion5-expected-applyCompletion20.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion5-expected-applyCompletion21.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion5-expected-applyCompletion40.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion5-expected-completion40.txt156
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion5.xml23
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion6-expected-applyCompletion22.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion6.xml7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion7-expected-applyCompletion23.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion7.xml7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion8-expected-applyCompletion41.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion8-expected-completion41.txt9
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion8-expected-completion42.txt4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion8-expected-completion43.txt9
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion8-expected-completion44.txt13
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion8.xml10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion9-expected-completion62.txt2
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion9-expected-completion63.txt1
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion9-expected-completion64.txt68
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion9.xml10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion24a.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion24b.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion25.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion26.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion27.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion28.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion29.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion30.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion31.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion32.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion33.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion34.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion35.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion36.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion37.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion38.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion44.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion23.txt7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion24.txt7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion25.txt8
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion26.txt2
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion27.txt15
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion28.txt15
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion29.txt3
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion30.txt8
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion31.txt2
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion32.txt317
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion33.txt3
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion34.txt3
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion35.txt3
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion36.txt2
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion37.txt2
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion38.txt6
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion66.txt7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion67.txt7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion68.txt3
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1.xml20
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues2-expected-applyCompletion45.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues2-expected-completion70.txt3
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues2-expected-completion71.txt2
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues2.xml8
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable1-expected-completion47.txt12
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable1-expected-completion48.txt3
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable1-expected-completion49.txt7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable1-expected-completion50.txt12
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable1.xml5
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable2-expected-completion51.txt10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable2-expected-completion52.txt7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable2.xml5
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/edithandling.xml3
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract1b.diff34
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract1c.diff31
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract1d.diff32
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract2.diff32
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract3.diff32
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract4.diff33
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract5.diff33
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract6.diff6
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract8.diff31
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1.info3
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1.xml11
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle2-expected-extract7.diff33
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle2.info3
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle2.xml11
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/fragmentlayout-expected-applyCompletion47.diff4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/fragmentlayout-expected-complation77.txt5
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/fragmentlayout-expected-complation78.txt5
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/fragmentlayout-expected-navigate13.txt12
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/fragmentlayout-expected-navigate14.txt12
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/fragmentlayout.xml19
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-complation80.txt8
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-completion14.txt10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-completion15.txt3
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-completion16.txt15
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-completion17.txt8
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-completion18.txt29
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-completion69.txt18
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-navigate10.txt6
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-navigate11a.txt6
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-navigate11g.txt6
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-navigate9a.txt6
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest.xml19
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/metadata.xml10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-complation76.txt76
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate1.txt7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate12.txt6
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate15.txt7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate16.txt7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate2.txt7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate3.txt7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate4.txt89
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1.xml18
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigationstyles-expected-extract2.diff5
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigationstyles-expected-navigate5.txt7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigationstyles-expected-navigate6.txt7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigationstyles-expected-navigate7.txt7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigationstyles-expected-navigate8.txt7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigationstyles.xml28
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout1-expected-extract1.xml2
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout2-expected-extract2.xml6
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout3-expected-extract3.xml2
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout3-expected-extract4.xml2
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout3-expected-extract5.xml6
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout6-expected-extract6.diff12
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout6-expected-extract7.diff29
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles-expected-extract1.diff10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles2-expected-extract1b.diff10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles3-expected-extract1c.diff10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles3-expected-extract8.diff10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles4-expected-extract1d.diff10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles4-expected-extract3.diff10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles5-expected-extract4.diff9
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles6-expected-extract5.diff9
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles7-expected-extract6.diff13
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles8-expected-extract7.diff10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/quickfix1-expected-quickFix1.xml7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/quickfix1-expected-quickFix2.xml4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/quickfix1-expected-quickFix3.xml8
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/quickfix1.xml16
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/quickfix2-expected-quickFix4.xml4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/quickfix2.xml5
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound1-expected-1.xml16
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound1.info4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound1.xml25
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound2-expected-2.xml16
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound2.info5
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound2.xml25
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound3-expected-3.xml16
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound3.info4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound3.xml25
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound4-expected-4.xml16
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound4.info4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound4.xml25
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound5-expected-7.xml9
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound5.info3
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound5.xml18
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound6-expected-8.xml17
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound6.info4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound6.xml25
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound7-expected-9.xml17
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound7.info4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound7.xml27
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound_all-expected-5.xml73
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound_all-expected-6.xml74
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound_all.info13
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound_all.xml83
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample10-expected-convertFromGrid.xml35
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample10-expected-initialAttributes.xml35
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample10.info5
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample10.xml28
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample11-expected-insertSpacer.xml59
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample11.info11
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample11.xml92
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-assistant1.txt3
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-assistant2.txt7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-assistant3.txt7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-assistant4.txt3
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-changeLayout1a.xml75
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-changeView1.xml21
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-extract6.diff9
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-extract7.diff84
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-gridLayout1.xml61
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a.info13
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a.xml21
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1b-expected-changeLayout1b.xml75
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1b.info14
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1b.xml70
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample2-expected-changeLayout2.xml62
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample2-expected-changeView2.xml13
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample2-expected-extract3.xml13
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample2-expected-gridLayout2.xml67
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample2.info9
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample2.xml13
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-changeLayout3.xml38
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-extract1.xml7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-extract2.xml6
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-extract4.xml7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-extract5.xml6
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-wrapIn1.xml36
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-wrapIn2.xml36
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-wrapIn3.xml36
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-variation1-expected-extract4.xml9
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-variation1-expected-extract5.xml8
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-variation1.xml10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-variation2-expected-extract4.xml7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-variation2-expected-extract5.xml6
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-variation2.xml8
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3.info5
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3.xml7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample4-expected-changeLayout4.xml26
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample4.info5
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample4.xml8
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample5-expected-changeLayout5.xml70
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample5-expected-gridLayout5.xml51
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample5.info9
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample5.xml12
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample6-expected-changeLayout6.xml37
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample6.info5
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample6.xml7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample7-expected-extract6.diff10
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample7-expected-extract7.diff69
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample7.info11
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample7.xml19
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample8-expected-extract6.diff15
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample8-expected-extract7.diff85
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample8.info12
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample8.xml40
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample9-expected-convertToGrid.xml37
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample9.info6
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample9.xml39
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/unwrap-expected-unwrap1.xml20
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/unwrap-expected-unwrap2.xml20
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/unwrap-expected-unwrap3.xml19
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/unwrap.info4
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/unwrap.xml26
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/manifest/ManifestInfoTest.java424
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/launch/JUnitLaunchConfigDelegateTest.java114
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/lint/ProjectLintConfigurationTest.java218
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/refactorings/core/AndroidPackageRenameParticipantTest.java293
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/refactorings/core/RefactoringTestBase.java757
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourceParticipantTest.java402
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/refactorings/renamepackage/ApplicationPackageNameRefactoringTest.java128
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ExportGradleTest.java303
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateHandlerTest.java901
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/AdtTestData.java135
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/AllTests.java40
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/EclipseTestCollector.java121
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/FuncTests.java48
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/SdkLoadingTestCase.java117
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/UnitTests.java61
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/functests/layoutRendering/ApiDemosRenderingTest.java328
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/functests/sampleProjects/AndroidManifestWriter.java131
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/functests/sampleProjects/SampleProjectTest.java263
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/test.xml76
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittest.xml54
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/api/PointTest.java123
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/api/RectTest.java301
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/AbsoluteLayoutRuleTest.java77
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/BaseLayoutRuleTest.java245
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/BaseViewRuleTest.java42
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/FrameLayoutRuleTest.java63
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/GravityHelperTest.java127
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/GridLayoutRuleTest.java23
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/LayoutTestBase.java375
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/LinearLayoutRuleTest.java466
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/RelativeLayoutRuleTest.java167
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/TestAttribute.java61
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/TestAttributeInfo.java81
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/TestColor.java36
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/TestDragElement.java158
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/TestGraphics.java181
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/TestNode.java477
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/ZoomControlsRuleTest.java50
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/grid/GridModelTest.java852
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/relative/DeletionHandlerTest.java445
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/resources/platform/AttributeInfoTest.java382
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/resources/platform/AttrsXmlParserManifestTest.java94
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/resources/platform/AttrsXmlParserTest.java120
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/AdtPluginTest.java49
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/AdtUtilsTest.java127
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/build/BaseBuilderTest.java37
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/AndroidDoubleClickStrategyTest.java71
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/descriptors/DescriptorsUtilsTest.java297
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/draw9patch/graphics/GraphicsUtilitiesTest.java313
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/draw9patch/graphics/NinePatchedImageTest.java914
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/formatting/AndroidXmlFormattingStrategyTest.java335
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/ExplodeRenderingHelperTest.java256
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/UiElementPullParserTest.java256
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ConfigurationTest.java143
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/configuration/FlagManagerTest.java185
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/configuration/LocaleTest.java99
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/CanvasViewInfoTest.java797
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ControlPointTest.java73
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/DomUtilitiesTest.java206
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ImageUtilsTest.java368
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/IncludeFinderTest.java128
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/IncludeOverlayTest.java75
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutPointTest.java64
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/PointTestCases.java107
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderLoggerTest.java82
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SelectionManagerTest.java120
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SimpleAttributeTest.java109
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SimpleElementTest.java343
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SwtUtilsTest.java343
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gre/MockNodeProxy.java68
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gre/NodeFactoryTest.java123
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gre/RulesEngineTest.java37
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gre/ViewMetadataRepositoryTest.java77
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/properties/ValueCompleterTest.java151
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/manifest/model/UiElementNodeTest.java284
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/mock/MockNamedNodeMap.java112
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/mock/MockNodeList.java62
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/mock/MockXmlNode.java319
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/resources/manager/ConfigMatchTest.java297
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/project/ProjectHelperTest.java66
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/refactorings/core/AndroidTypeMoveParticipantTest.java135
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/refactorings/core/AndroidTypeRenameParticipantTest.java160
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourceXmlTextActionTest.java110
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/resources/ResourceHelperTest.java183
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/resources/ResourceNameValidatorTest.java101
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/resources/manager/IdeScanningContextTest.java22
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/sdk/AndroidJarLoaderTest.java166
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/sdk/LayoutParamsParserTest.java182
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmActivityToLayoutMethodTest.java50
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmCamelCaseToUnderscoreMethodTest.java58
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmClassNameToResourceMethodTest.java66
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmEscapeXmlAttributeMethodTest.java50
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmEscapeXmlStringMethodTest.java66
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmEscapeXmlTextMethodTest.java46
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmExtractLettersMethodTest.java46
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmLayoutToActivityMethodTest.java54
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmSlashedPackageNameMethodTest.java50
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmUnderscoreToCamelCaseMethodTest.java58
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/mock/Mocks.java189
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/mock/TestLogger.java54
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/content-area-one-dot.9.pngbin206 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/content-area-two-dots.9.pngbin214 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/content-area.9.pngbin210 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched1.9.pngbin2923 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched2.9.pngbin2913 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched3.9.pngbin2914 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched4.9.pngbin2914 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched5.9.pngbin2929 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched6.9.pngbin2920 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched7.9.pngbin2916 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched8.9.pngbin2923 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/layout-bounds-only.9.pngbin1466 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/no-patched-interlace.pngbin3138 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/no-patched.pngbin2906 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/patched-with-badpatches.9.pngbin214 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/patched1.9.pngbin210 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/patched2.9.pngbin217 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/patched3.9.pngbin214 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/jar_example.jarbin1829 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/jar_example.jardesc16
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/mock_attrs.xml340
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/mock_manifest_attrs.xml180
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/mock_android/view/View.java21
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/mock_android/view/ViewGroup.java29
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/mock_android/widget/LinearLayout.java27
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.tests/unittests/mock_android/widget/TableLayout.java27
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.traceview/.classpath8
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.traceview/.project28
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.traceview/.settings/org.eclipse.jdt.core.prefs98
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.traceview/META-INF/MANIFEST.MF17
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.traceview/about.ini2
-rwxr-xr-xeclipse/plugins/com.android.ide.eclipse.traceview/about.properties7
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.traceview/build.properties9
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.traceview/icons/android.pngbin197 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.traceview/icons/traceview-32.pngbin2267 -> 0 bytes
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.traceview/plugin.xml22
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.traceview/pom.xml17
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.traceview/src/com/android/ide/eclipse/traceview/TraceviewLauncher.java77
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.traceview/src/com/android/ide/eclipse/traceview/TraceviewPlugin.java67
-rw-r--r--eclipse/plugins/com.android.ide.eclipse.traceview/src/com/android/ide/eclipse/traceview/editors/TraceviewEditor.java316
-rw-r--r--eclipse/pom.xml168
-rwxr-xr-xeclipse/scripts/_mk_icons.sh55
-rwxr-xr-xeclipse/scripts/build_adt.sh49
-rwxr-xr-xeclipse/scripts/build_update_site.sh34
-rwxr-xr-xeclipse/scripts/collect_sources_for_sdk.py180
-rwxr-xr-xeclipse/scripts/gen_icon.py71
-rwxr-xr-xeclipse/scripts/update_version.sh80
-rw-r--r--eclipse/settings.xml8
-rw-r--r--eclipse/sites/external/.gitignore2
-rw-r--r--eclipse/sites/external/.project17
-rw-r--r--eclipse/sites/external/index.html60
-rw-r--r--eclipse/sites/external/site.xml34
-rw-r--r--eclipse/sites/external/web/site.css12
-rw-r--r--eclipse/sites/external/web/site.xsl214
-rw-r--r--eclipse/sites/internal/.gitignore2
-rw-r--r--eclipse/sites/internal/.project17
-rw-r--r--eclipse/sites/internal/index.html60
-rw-r--r--eclipse/sites/internal/site.xml50
-rw-r--r--eclipse/sites/internal/web/site.css12
-rw-r--r--eclipse/sites/internal/web/site.xsl214
-rw-r--r--files/typos/typos-de.txt2219
-rw-r--r--files/typos/typos-en.txt4576
-rw-r--r--files/typos/typos-es.txt733
-rw-r--r--files/typos/typos-hu.txt431
-rw-r--r--files/typos/typos-it.txt665
-rw-r--r--files/typos/typos-nb.txt449
-rw-r--r--files/typos/typos-pt.txt1647
-rw-r--r--files/typos/typos-tr.txt604
-rw-r--r--hierarchyviewer/MODULE_LICENSE_APACHE20
1805 files changed, 0 insertions, 286078 deletions
diff --git a/attribute_stats/.classpath b/attribute_stats/.classpath
deleted file mode 100644
index fb5011632..000000000
--- a/attribute_stats/.classpath
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="src" path="src"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
diff --git a/attribute_stats/.gitignore b/attribute_stats/.gitignore
deleted file mode 100644
index ba077a403..000000000
--- a/attribute_stats/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-bin
diff --git a/attribute_stats/.project b/attribute_stats/.project
deleted file mode 100644
index 2f2cff145..000000000
--- a/attribute_stats/.project
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>attribute_stats</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
diff --git a/attribute_stats/.settings/org.eclipse.jdt.core.prefs b/attribute_stats/.settings/org.eclipse.jdt.core.prefs
deleted file mode 100644
index ea661960a..000000000
--- a/attribute_stats/.settings/org.eclipse.jdt.core.prefs
+++ /dev/null
@@ -1,98 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore
-org.eclipse.jdt.core.compiler.annotation.nonnull=com.android.annotations.NonNull
-org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=com.android.annotations.NonNullByDefault
-org.eclipse.jdt.core.compiler.annotation.nonnullisdefault=disabled
-org.eclipse.jdt.core.compiler.annotation.nullable=com.android.annotations.Nullable
-org.eclipse.jdt.core.compiler.annotation.nullanalysis=enabled
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
-org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
-org.eclipse.jdt.core.compiler.compliance=1.6
-org.eclipse.jdt.core.compiler.debug.lineNumber=generate
-org.eclipse.jdt.core.compiler.debug.localVariable=generate
-org.eclipse.jdt.core.compiler.debug.sourceFile=generate
-org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
-org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
-org.eclipse.jdt.core.compiler.problem.deadCode=warning
-org.eclipse.jdt.core.compiler.problem.deprecation=warning
-org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
-org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
-org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
-org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore
-org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning
-org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled
-org.eclipse.jdt.core.compiler.problem.fieldHiding=warning
-org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
-org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
-org.eclipse.jdt.core.compiler.problem.forbiddenReference=error
-org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
-org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=enabled
-org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
-org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning
-org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
-org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning
-org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
-org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore
-org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled
-org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=warning
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=error
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
-org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
-org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
-org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
-org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
-org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
-org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=warning
-org.eclipse.jdt.core.compiler.problem.nullReference=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecInsufficientInfo=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecViolation=warning
-org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=ignore
-org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
-org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
-org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullSpecViolation=error
-org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=warning
-org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=warning
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
-org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
-org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
-org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=enabled
-org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
-org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
-org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning
-org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=disabled
-org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
-org.eclipse.jdt.core.compiler.problem.unclosedCloseable=error
-org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
-org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
-org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning
-org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
-org.eclipse.jdt.core.compiler.problem.unusedImport=warning
-org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
-org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
-org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=warning
-org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
-org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
-org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
-org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
-org.eclipse.jdt.core.compiler.source=1.6
diff --git a/attribute_stats/README.txt b/attribute_stats/README.txt
deleted file mode 100644
index 15f51c2cb..000000000
--- a/attribute_stats/README.txt
+++ /dev/null
@@ -1,13 +0,0 @@
-Attribute Statistics
----------------------
-
-This program gathers statistics about attribute usage in layout
-files. This is how the "topAttrs" attributes listed in ADT's
-extra-view-metadata.xml file (which drives the common attributes
-listed in the top of the context menu) is determined by running this
-script on a body of sample Android code, such as the AOSP repository.
-
-This program takes one or more directory paths, and then it searches
-all of them recursively for layout files that are not in folders
-containing the string "test", and computes and prints frequency
-statistics.
diff --git a/attribute_stats/src/Analyzer.java b/attribute_stats/src/Analyzer.java
deleted file mode 100644
index 8da53ea38..000000000
--- a/attribute_stats/src/Analyzer.java
+++ /dev/null
@@ -1,663 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.Reader;
-import java.io.StringReader;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-
-/**
- * Gathers statistics about attribute usage in layout files. This is how the "topAttrs"
- * attributes listed in ADT's extra-view-metadata.xml (which drives the common attributes
- * listed in the top of the context menu) is determined by running this script on a body
- * of sample layout code.
- * <p>
- * This program takes one or more directory paths, and then it searches all of them recursively
- * for layout files that are not in folders containing the string "test", and computes and
- * prints frequency statistics.
- */
-public class Analyzer {
- /** Number of attributes to print for each view */
- public static final int ATTRIBUTE_COUNT = 6;
- /** Separate out any attributes that constitute less than N percent of the total */
- public static final int THRESHOLD = 10; // percent
-
- private List<File> mDirectories;
- private File mCurrentFile;
- private boolean mListAdvanced;
-
- /** Map from view id to map from attribute to frequency count */
- private Map<String, Map<String, Usage>> mFrequencies =
- new HashMap<String, Map<String, Usage>>(100);
-
- private Map<String, Map<String, Usage>> mLayoutAttributeFrequencies =
- new HashMap<String, Map<String, Usage>>(100);
-
- private Map<String, String> mTopAttributes = new HashMap<String, String>(100);
- private Map<String, String> mTopLayoutAttributes = new HashMap<String, String>(100);
-
- private int mFileVisitCount;
- private int mLayoutFileCount;
- private File mXmlMetadataFile;
-
- private Analyzer(List<File> directories, File xmlMetadataFile, boolean listAdvanced) {
- mDirectories = directories;
- mXmlMetadataFile = xmlMetadataFile;
- mListAdvanced = listAdvanced;
- }
-
- public static void main(String[] args) {
- if (args.length < 1) {
- System.err.println("Usage: " + Analyzer.class.getSimpleName()
- + " <directory1> [directory2 [directory3 ...]]\n");
- System.err.println("Recursively scans for layouts in the given directory and");
- System.err.println("computes statistics about attribute frequencies.");
- System.exit(-1);
- }
-
- File metadataFile = null;
- List<File> directories = new ArrayList<File>();
- boolean listAdvanced = false;
- for (int i = 0, n = args.length; i < n; i++) {
- String arg = args[i];
-
- if (arg.equals("--list")) {
- // List ALL encountered attributes
- listAdvanced = true;
- continue;
- }
-
- // The -metadata flag takes a pointer to an ADT extra-view-metadata.xml file
- // and attempts to insert topAttrs attributes into it (and saves it as same
- // file +.mod as an extension). This isn't listed on the usage flag because
- // it's pretty brittle and requires some manual fixups to the file afterwards.
- if (arg.equals("--metadata")) {
- i++;
- File file = new File(args[i]);
- if (!file.exists()) {
- System.err.println(file.getName() + " does not exist");
- System.exit(-5);
- }
- if (!file.isFile() || !file.getName().endsWith(".xml")) {
- System.err.println(file.getName() + " must be an XML file");
- System.exit(-4);
- }
- metadataFile = file;
- continue;
- }
- File directory = new File(arg);
- if (!directory.exists()) {
- System.err.println(directory.getName() + " does not exist");
- System.exit(-2);
- }
-
- if (!directory.isDirectory()) {
- System.err.println(directory.getName() + " is not a directory");
- System.exit(-3);
- }
-
- directories.add(directory);
- }
-
- new Analyzer(directories, metadataFile, listAdvanced).analyze();
- }
-
- private void analyze() {
- for (File directory : mDirectories) {
- scanDirectory(directory);
- }
-
- if (mListAdvanced) {
- listAdvanced();
- }
-
- printStatistics();
-
- if (mXmlMetadataFile != null) {
- printMergedMetadata();
- }
- }
-
- private void scanDirectory(File directory) {
- File[] files = directory.listFiles();
- if (files == null) {
- return;
- }
-
- for (File file : files) {
- mFileVisitCount++;
- if (mFileVisitCount % 50000 == 0) {
- System.out.println("Analyzed " + mFileVisitCount + " files...");
- }
-
- if (file.isFile()) {
- scanFile(file);
- } else if (file.isDirectory()) {
- // Skip stuff related to tests
- if (file.getName().contains("test")) {
- continue;
- }
-
- // Recurse over subdirectories
- scanDirectory(file);
- }
- }
- }
-
- private void scanFile(File file) {
- if (file.getName().endsWith(".xml")) {
- File parent = file.getParentFile();
- if (parent.getName().startsWith("layout")) {
- analyzeLayout(file);
- }
- }
-
- }
-
- private void analyzeLayout(File file) {
- mCurrentFile = file;
- mLayoutFileCount++;
- Document document = null;
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- InputSource is = new InputSource(new StringReader(readFile(file)));
- try {
- factory.setNamespaceAware(true);
- factory.setValidating(false);
- DocumentBuilder builder = factory.newDocumentBuilder();
- document = builder.parse(is);
-
- analyzeDocument(document);
-
- } catch (ParserConfigurationException e) {
- // pass -- ignore files we can't parse
- } catch (SAXException e) {
- // pass -- ignore files we can't parse
- } catch (IOException e) {
- // pass -- ignore files we can't parse
- }
- }
-
-
- private void analyzeDocument(Document document) {
- analyzeElement(document.getDocumentElement());
- }
-
- private void analyzeElement(Element element) {
- if (element.getTagName().equals("item")) {
- // Resource files shouldn't be in the layout/ folder but I came across
- // some cases
- System.out.println("Warning: found <item> tag in a layout file in "
- + mCurrentFile.getPath());
- return;
- }
-
- countAttributes(element);
- countLayoutAttributes(element);
-
- // Recurse over children
- NodeList childNodes = element.getChildNodes();
- for (int i = 0, n = childNodes.getLength(); i < n; i++) {
- Node child = childNodes.item(i);
- if (child.getNodeType() == Node.ELEMENT_NODE) {
- analyzeElement((Element) child);
- }
- }
- }
-
- private void countAttributes(Element element) {
- String tag = element.getTagName();
- Map<String, Usage> attributeMap = mFrequencies.get(tag);
- if (attributeMap == null) {
- attributeMap = new HashMap<String, Usage>(70);
- mFrequencies.put(tag, attributeMap);
- }
-
- NamedNodeMap attributes = element.getAttributes();
- for (int i = 0, n = attributes.getLength(); i < n; i++) {
- Node attribute = attributes.item(i);
- String name = attribute.getNodeName();
-
- if (name.startsWith("android:layout_")) {
- // Skip layout attributes; they are a function of the parent layout that this
- // view is embedded within, not the view itself.
- // TODO: Consider whether we should incorporate this info or make statistics
- // about that as well?
- continue;
- }
-
- if (name.equals("android:id")) {
- // Skip ids: they are (mostly) unrelated to the view type and the tool
- // already offers id editing prominently
- continue;
- }
-
- if (name.startsWith("xmlns:")) {
- // Unrelated to frequency counts
- continue;
- }
-
- Usage usage = attributeMap.get(name);
- if (usage == null) {
- usage = new Usage(name);
- } else {
- usage.incrementCount();
- }
- attributeMap.put(name, usage);
- }
- }
-
- private void countLayoutAttributes(Element element) {
- String parentTag = element.getParentNode().getNodeName();
- Map<String, Usage> attributeMap = mLayoutAttributeFrequencies.get(parentTag);
- if (attributeMap == null) {
- attributeMap = new HashMap<String, Usage>(70);
- mLayoutAttributeFrequencies.put(parentTag, attributeMap);
- }
-
- NamedNodeMap attributes = element.getAttributes();
- for (int i = 0, n = attributes.getLength(); i < n; i++) {
- Node attribute = attributes.item(i);
- String name = attribute.getNodeName();
-
- if (!name.startsWith("android:layout_")) {
- continue;
- }
-
- // Skip layout_width and layout_height; they are mandatory in all but GridLayout so not
- // very interesting
- if (name.equals("android:layout_width") || name.equals("android:layout_height")) {
- continue;
- }
-
- Usage usage = attributeMap.get(name);
- if (usage == null) {
- usage = new Usage(name);
- } else {
- usage.incrementCount();
- }
- attributeMap.put(name, usage);
- }
- }
-
- // Copied from AdtUtils
- private static String readFile(File file) {
- try {
- return readFile(new FileReader(file));
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- }
-
- return null;
- }
-
- private static String readFile(Reader inputStream) {
- BufferedReader reader = null;
- try {
- reader = new BufferedReader(inputStream);
- StringBuilder sb = new StringBuilder(2000);
- while (true) {
- int c = reader.read();
- if (c == -1) {
- return sb.toString();
- } else {
- sb.append((char)c);
- }
- }
- } catch (IOException e) {
- // pass -- ignore files we can't read
- } finally {
- try {
- if (reader != null) {
- reader.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
-
- return null;
- }
-
- private void printStatistics() {
- System.out.println("Analyzed " + mLayoutFileCount
- + " layouts (in a directory trees containing " + mFileVisitCount + " files)");
- System.out.println("Top " + ATTRIBUTE_COUNT
- + " for each view (excluding layout_ attributes) :");
- System.out.println("\n");
- System.out.println(" Rank Count Share Attribute");
- System.out.println("=========================================================");
- List<String> views = new ArrayList<String>(mFrequencies.keySet());
- Collections.sort(views);
- for (String view : views) {
- String top = processUageMap(view, mFrequencies.get(view));
- if (top != null) {
- mTopAttributes.put(view, top);
- }
- }
-
- System.out.println("\n\n\nTop " + ATTRIBUTE_COUNT + " layout attributes (excluding "
- + "mandatory layout_width and layout_height):");
- System.out.println("\n");
- System.out.println(" Rank Count Share Attribute");
- System.out.println("=========================================================");
- views = new ArrayList<String>(mLayoutAttributeFrequencies.keySet());
- Collections.sort(views);
- for (String view : views) {
- String top = processUageMap(view, mLayoutAttributeFrequencies.get(view));
- if (top != null) {
- mTopLayoutAttributes.put(view, top);
- }
- }
- }
-
- private static String processUageMap(String view, Map<String, Usage> map) {
- if (map == null) {
- return null;
- }
-
- if (view.indexOf('.') != -1 && !view.startsWith("android.")) {
- // Skip custom views
- return null;
- }
-
- List<Usage> values = new ArrayList<Usage>(map.values());
- if (values.size() == 0) {
- return null;
- }
-
- Collections.sort(values);
- int totalCount = 0;
- for (Usage usage : values) {
- totalCount += usage.count;
- }
-
- System.out.println("\n<" + view + ">:");
- if (view.equals("#document")) {
- System.out.println("(Set on root tag, probably intended for included context)");
- }
-
- int place = 1;
- int count = 0;
- int prevCount = -1;
- float prevPercentage = 0f;
- StringBuilder sb = new StringBuilder();
- for (Usage usage : values) {
- if (count++ >= ATTRIBUTE_COUNT && usage.count < prevCount) {
- break;
- }
-
- float percentage = 100 * usage.count/(float)totalCount;
- if (percentage < THRESHOLD && prevPercentage >= THRESHOLD) {
- System.out.println(" -----Less than 10%-------------------------------------");
- }
- System.out.printf(" %1d. %5d %5.1f%% %s\n", place, usage.count,
- percentage, usage.attribute);
-
- prevPercentage = percentage;
- if (prevCount != usage.count) {
- prevCount = usage.count;
- place++;
- }
-
- if (percentage >= THRESHOLD /*&& usage.count > 1*/) { // 1:Ignore when not enough data?
- if (sb.length() > 0) {
- sb.append(',');
- }
- String name = usage.attribute;
- if (name.startsWith("android:")) {
- name = name.substring("android:".length());
- }
- sb.append(name);
- }
- }
-
- return sb.length() > 0 ? sb.toString() : null;
- }
-
- private void printMergedMetadata() {
- assert mXmlMetadataFile != null;
- String metadata = readFile(mXmlMetadataFile);
- if (metadata == null || metadata.length() == 0) {
- System.err.println("Invalid metadata file");
- System.exit(-6);
- }
-
- System.err.flush();
- System.out.println("\n\nUpdating layout metadata file...");
- System.out.flush();
-
- StringBuilder sb = new StringBuilder((int) (2 * mXmlMetadataFile.length()));
- String[] lines = metadata.split("\n");
- for (int i = 0; i < lines.length; i++) {
- String line = lines[i];
- sb.append(line).append('\n');
- int classIndex = line.indexOf("class=\"");
- if (classIndex != -1) {
- int start = classIndex + "class=\"".length();
- int end = line.indexOf('"', start + 1);
- if (end != -1) {
- String view = line.substring(start, end);
- if (view.startsWith("android.widget.")) {
- view = view.substring("android.widget.".length());
- } else if (view.startsWith("android.view.")) {
- view = view.substring("android.view.".length());
- } else if (view.startsWith("android.webkit.")) {
- view = view.substring("android.webkit.".length());
- }
- String top = mTopAttributes.get(view);
- if (top == null) {
- System.err.println("Warning: No frequency data for view " + view);
- } else {
- sb.append(line.substring(0, classIndex)); // Indentation
-
- sb.append("topAttrs=\"");
- sb.append(top);
- sb.append("\"\n");
- }
-
- top = mTopLayoutAttributes.get(view);
- if (top != null) {
- // It's a layout attribute
- sb.append(line.substring(0, classIndex)); // Indentation
-
- sb.append("topLayoutAttrs=\"");
- sb.append(top);
- sb.append("\"\n");
- }
- }
- }
- }
-
- System.out.println("\nTop attributes:");
- System.out.println("--------------------------");
- List<String> views = new ArrayList<String>(mTopAttributes.keySet());
- Collections.sort(views);
- for (String view : views) {
- String top = mTopAttributes.get(view);
- System.out.println(view + ": " + top);
- }
-
- System.out.println("\nTop layout attributes:");
- System.out.println("--------------------------");
- views = new ArrayList<String>(mTopLayoutAttributes.keySet());
- Collections.sort(views);
- for (String view : views) {
- String top = mTopLayoutAttributes.get(view);
- System.out.println(view + ": " + top);
- }
-
- System.out.println("\nModified XML metadata file:\n");
- String newContent = sb.toString();
- File output = new File(mXmlMetadataFile.getParentFile(), mXmlMetadataFile.getName() + ".mod");
- if (output.exists()) {
- output.delete();
- }
- try {
- BufferedWriter writer = new BufferedWriter(new FileWriter(output));
- writer.write(newContent);
- writer.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- System.out.println("Done - wrote " + output.getPath());
- }
-
- //private File mPublicFile = new File(location, "data/res/values/public.xml");
- private File mPublicFile = new File("/Volumes/AndroidWork/git/frameworks/base/core/res/res/values/public.xml");
-
- private void listAdvanced() {
- Set<String> keys = new HashSet<String>(1000);
-
- // Merged usages across view types
- Map<String, Usage> mergedUsages = new HashMap<String, Usage>(100);
-
- for (Entry<String,Map<String,Usage>> entry : mFrequencies.entrySet()) {
- String view = entry.getKey();
- if (view.indexOf('.') != -1 && !view.startsWith("android.")) {
- // Skip custom views etc
- continue;
- }
- Map<String, Usage> map = entry.getValue();
- for (Usage usage : map.values()) {
-// if (usage.count == 1) {
-// System.out.println("Only found *one* usage of " + usage.attribute);
-// }
-// if (usage.count < 4) {
-// System.out.println("Only found " + usage.count + " usage of " + usage.attribute);
-// }
-
- String attribute = usage.attribute;
- int index = attribute.indexOf(':');
- if (index == -1 || attribute.startsWith("android:")) {
- Usage merged = mergedUsages.get(attribute);
- if (merged == null) {
- merged = new Usage(attribute);
- merged.count = usage.count;
- mergedUsages.put(attribute, merged);
- } else {
- merged.count += usage.count;
- }
- }
- }
- }
-
- for (Usage usage : mergedUsages.values()) {
- String attribute = usage.attribute;
- if (usage.count < 4) {
- System.out.println("Only found " + usage.count + " usage of " + usage.attribute);
- continue;
- }
- int index = attribute.indexOf(':');
- if (index != -1) {
- attribute = attribute.substring(index + 1); // +1: skip ':'
- }
- keys.add(attribute);
- }
-
- List<String> sorted = new ArrayList<String>(keys);
- Collections.sort(sorted);
- System.out.println("\nEncountered Attributes");
- System.out.println("-----------------------------");
- for (String attribute : sorted) {
- System.out.println(attribute);
- }
-
- System.out.println();
- }
-
- private static class Usage implements Comparable<Usage> {
- public String attribute;
- public int count;
-
-
- public Usage(String attribute) {
- super();
- this.attribute = attribute;
-
- count = 1;
- }
-
- public void incrementCount() {
- count++;
- }
-
- @Override
- public int compareTo(Usage o) {
- // Sort by decreasing frequency, then sort alphabetically
- int frequencyDelta = o.count - count;
- if (frequencyDelta != 0) {
- return frequencyDelta;
- } else {
- return attribute.compareTo(o.attribute);
- }
- }
-
- @Override
- public String toString() {
- return attribute + ": " + count;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((attribute == null) ? 0 : attribute.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- Usage other = (Usage) obj;
- if (attribute == null) {
- if (other.attribute != null)
- return false;
- } else if (!attribute.equals(other.attribute))
- return false;
- return true;
- }
- }
-}
diff --git a/eclipse/.gitignore b/eclipse/.gitignore
deleted file mode 100644
index 78dbaee0a..000000000
--- a/eclipse/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-*.iml
-plugins/*/libs
-plugins/*/*.target
diff --git a/eclipse/artifacts/bundles/.project b/eclipse/artifacts/bundles/.project
deleted file mode 100644
index 91740876a..000000000
--- a/eclipse/artifacts/bundles/.project
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>tycho-bundles</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- </buildSpec>
- <natures>
- </natures>
-</projectDescription>
diff --git a/eclipse/artifacts/bundles/monitor.product b/eclipse/artifacts/bundles/monitor.product
deleted file mode 100644
index c8c0f380b..000000000
--- a/eclipse/artifacts/bundles/monitor.product
+++ /dev/null
@@ -1,61 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<?pde version="3.5"?>
-
-<product name="monitor" uid="monitorproduct" id="com.android.ide.eclipse.monitor.product" application="com.android.ide.eclipse.monitor.Application" version="24.3.3.qualifier" useFeatures="true" includeLaunchers="true">
-
-
- <configIni use="default">
- </configIni>
-
- <launcherArgs>
- <programArgs>-data @noDefault</programArgs>
- <vmArgs>-XX:MaxPermSize=256m
--Xms512m
--Xmx1024m</vmArgs>
- <vmArgsMac>-XstartOnFirstThread -Dorg.eclipse.swt.internal.carbon.smallFonts</vmArgsMac>
- </launcherArgs>
-
- <windowImages/>
-
- <splash
- location="com.android.ide.eclipse.monitor" />
- <launcher name="monitor">
- <solaris/>
- <win useIco="false">
- <bmp/>
- </win>
- </launcher>
-
-
- <vm>
- </vm>
-
-
- <plugins>
- </plugins>
-
- <features>
- <feature id="com.android.ide.eclipse.ddms.feature"/>
- <feature id="com.android.ide.eclipse.gldebugger.feature"/>
- <feature id="com.android.ide.eclipse.hierarchyviewer.feature"/>
- <feature id="com.android.ide.eclipse.traceview.feature"/>
- <feature id="com.android.ide.eclipse.monitor.feature"/>
- <feature id="org.eclipse.rcp"/>
- <feature id="org.eclipse.emf.ecore"/>
- <feature id="org.eclipse.e4.rcp"/>
- <feature id="org.eclipse.emf.common"/>
- <feature id="org.eclipse.platform"/>
- <feature id="org.eclipse.equinox.p2.core.feature"/>
- <feature id="org.eclipse.help"/>
- <feature id="org.eclipse.equinox.p2.rcp.feature"/>
- <feature id="org.eclipse.equinox.p2.extras.feature"/>
- <feature id="org.eclipse.equinox.p2.user.ui"/>
- </features>
-
- <configurations>
- <plugin id="org.eclipse.core.runtime" autoStart="true" startLevel="2" />
- <plugin id="org.eclipse.equinox.common" autoStart="true" startLevel="2" />
- <plugin id="org.eclipse.equinox.ds" autoStart="true" startLevel="2" />
- </configurations>
-
-</product>
diff --git a/eclipse/artifacts/bundles/pom.xml b/eclipse/artifacts/bundles/pom.xml
deleted file mode 100644
index 3e8df67f0..000000000
--- a/eclipse/artifacts/bundles/pom.xml
+++ /dev/null
@@ -1,58 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <version>24.3.3-SNAPSHOT</version>
- <artifactId>bundles</artifactId>
- <packaging>eclipse-repository</packaging>
- <name>bundles</name>
-
- <parent>
- <relativePath>../../pom.xml</relativePath>
- <groupId>adt.group</groupId>
- <artifactId>parent</artifactId>
- <version>1.0.0-SNAPSHOT</version>
- </parent>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.eclipse.tycho</groupId>
- <artifactId>tycho-p2-director-plugin</artifactId>
- <version>${tycho-version}</version>
- <executions>
- <!-- install the product for all configured os/ws/arch environments
- using p2 director -->
- <execution>
- <id>materialize-products</id>
- <goals>
- <goal>materialize-products</goal>
- </goals>
- </execution>
- <!-- create product zips (one per os/ws/arch) -->
- <execution>
- <id>archive-products</id>
- <goals>
- <goal>archive-products</goal>
- </goals>
- </execution>
- </executions>
- <configuration>
- <formats>
- <win32>zip</win32>
- <linux>zip</linux>
- <macosx>zip</macosx>
- </formats>
- <products>
- <product>
- <id>monitorproduct</id>
- <attachId>com.android.ide.eclipse.monitor.product</attachId>
- <rootFolder>monitor</rootFolder>
- </product>
- </products>
- </configuration>
- </plugin>
- </plugins>
- </build>
-</project>
diff --git a/eclipse/build.gradle b/eclipse/build.gradle
deleted file mode 100644
index 5624821f4..000000000
--- a/eclipse/build.gradle
+++ /dev/null
@@ -1,205 +0,0 @@
-// Script used to build ADT plugins, IDE and monitor
-// There are 2 major tasks done by this plugin:
-// copydeps: copies tools/base, tools/swt and prebuilt jars into plugins' libs folder
-// buildEclipse: builds Eclipse by running Tycho from the commandline
-//
-// Usage: $ ANDROID_SRC/tools/gradlew -i -b /path/to/this/build.gradle copydeps|buildEclipse
-
-// get tools/base version
-apply from: "../../tools/buildSrc/base/version.gradle"
-
-ext.outPath = System.env.OUT_DIR
-if (outPath != null) {
- ext.outFile = new File(outPath)
-} else {
- outPath = '../../out'
- ext.outFile = new File(projectDir, outPath)
-}
-
-repositories {
- maven { url '../../prebuilts/tools/common/m2/repository' }
- maven { url outPath + '/repo' }
-}
-
-ext {
- // list of plugins whose manifest should be examined to identify dependencies
- adtPlugins = new File(projectDir, 'plugins').listFiles().findAll { it.name.startsWith("com.android") }
-
- //
- def eclipseBuildDeps = new File(projectDir, "../../prebuilts/eclipse-build-deps").getCanonicalFile()
- targetComponents = [
- "platform": new File(eclipseBuildDeps, "platform/org.eclipse.platform-4.2.2.zip"),
- "cdt" : new File(eclipseBuildDeps, "cdt/cdt-master-8.0.2.zip"),
- "emf" : new File(eclipseBuildDeps, "emf/emf-xsd-Update-2.9.1.zip"),
- "jdt" : new File(eclipseBuildDeps, "jdt/org.eclipse.jdt.source-4.2.2.zip"),
- "wtp" : new File(eclipseBuildDeps, "wtp/wtp-repo-R-3.3.2-20120210195245.zip"),
- "gef" : new File(eclipseBuildDeps, "gef/GEF-Update-3.9.1.zip"),
- "pde" : new File(eclipseBuildDeps, "pde/org.eclipse.pde-3.8.zip"),
- "egit" : new File(eclipseBuildDeps, "egit/org.eclipse.egit.repository-2.2.0.201212191850-r.zip"),
- ]
-
- buildNumber = System.getenv("BUILD_NUMBER")
- if (buildNumber == null) {
- buildNumber = "SNAPSHOT"
- }
-}
-
-// a mapping from the library names as used inside the plugin's MANIFEST.MF to the Maven artifact id
-def artifacts = [
- // tools/base and tools/swt dependencies
- 'manifest-merger' : "com.android.tools.build:manifest-merger:$ext.baseVersion",
- 'ddmlib' : "com.android.tools.ddms:ddmlib:$ext.baseVersion",
- 'ddmuilib' : "com.android.tools.ddms:ddmuilib:$ext.baseVersion",
- 'layoutlib-api' : "com.android.tools.layoutlib:layoutlib-api:$ext.baseVersion",
- 'lint-api' : "com.android.tools.lint:lint-api:$ext.baseVersion",
- 'lint-checks' : "com.android.tools.lint:lint-checks:$ext.baseVersion",
- 'asset-studio' : "com.android.tools:asset-studio:$ext.baseVersion",
- 'annotations' : "com.android.tools:annotations:$ext.baseVersion",
- 'common' : "com.android.tools:common:$ext.baseVersion",
- 'dvlib' : "com.android.tools:dvlib:$ext.baseVersion",
- 'hierarchyviewer2lib' : "com.android.tools:hierarchyviewer2lib:$ext.baseVersion",
- 'ninepatch' : "com.android.tools:ninepatch:$ext.baseVersion",
- 'rule-api' : "com.android.tools:rule-api:$ext.baseVersion",
- 'sdk-common' : "com.android.tools:sdk-common:$ext.baseVersion",
- 'sdklib' : "com.android.tools:sdklib:$ext.baseVersion",
- 'sdkstats' : "com.android.tools:sdkstats:$ext.baseVersion",
- 'sdkuilib' : "com.android.tools:sdkuilib:$ext.baseVersion",
- 'swtmenubar' : "com.android.tools:swtmenubar:$ext.baseVersion",
- 'testutils' : "com.android.tools:testutils:$ext.baseVersion",
- 'traceview' : "com.android.tools:traceview:$ext.baseVersion",
- 'uiautomatorviewer' : "com.android.tools:uiautomatorviewer:$ext.baseVersion",
-
- // prebuilts
- 'ant-glob' : 'com.android.tools.external:ant-glob:1.0',
- 'asm-5.0.3' : 'org.ow2.asm:asm:5.0.3',
- 'asm-analysis-5.0.3' : 'org.ow2.asm:asm-analysis:5.0.3',
- 'asm-tree-5.0.3' : 'org.ow2.asm:asm-tree:5.0.3',
- 'commons-codec-1.4' : 'commons-codec:commons-codec:1.4',
- 'commons-compress-1.0' : 'org.apache.commons:commons-compress:1.8.1',
- 'commons-logging-1.1.1' : 'commons-logging:commons-logging:1.1.1',
- 'easymock' : 'org.easymock:easymock:3.3',
- 'freemarker-2.3.20' : 'org.freemarker:freemarker:2.3.20',
- 'guava-17.0' : 'com.google.guava:guava:17.0',
- 'host-libprotobuf-java-2.3.0-lite' : 'com.android.tools.external:libprotobuf-java-lite:2.3.0',
- 'httpclient-4.1.1' : 'org.apache.httpcomponents:httpclient:4.1.1',
- 'httpcore-4.1' : 'org.apache.httpcomponents:httpcore:4.1',
- 'httpmime-4.1' : 'org.apache.httpcomponents:httpmime:4.1',
- 'jcommon-1.0.12' : 'jfree:jcommon:1.0.12',
- 'jfreechart-1.0.9' : 'jfree:jfreechart:1.0.9',
- 'jfreechart-swt-1.0.9' : 'jfree:jfreechart-swt:1.0.9',
- 'kxml2-2.3.0' : 'net.sf.kxml:kxml2:2.3.0',
- 'liblzf-1.0' : 'com.android.tools.external:liblzf:1.0',
- 'lombok-ast-0.2.3' : 'com.android.tools.external.lombok:lombok-ast:0.2.3',
- 'propertysheet' : 'com.android.tools.external:propertysheet:1.0',
-]
-
-configurations {
- compile
-}
-
-dependencies {
- compile artifacts.values()
-}
-
-task copydeps << {
- // get the resolved dependencies from the compile configuration
- def resolvedDependencies = configurations.compile.resolvedConfiguration.firstLevelModuleDependencies
-
- // generate a map from "xy.jar" -> "/path/to/xy-1.0.jar"
- def artifactMap = [:]
- resolvedDependencies.each { dependency ->
- def dependencyId = dependency.getName()
- def artifactName = artifacts.find{ it.value == dependencyId}?.key
-
- // get the jar file corresponding to the dependency
- def artifact = getArtifact(dependency)
- artifactMap.put(artifactName + ".jar", artifact)
- }
-
- project.adtPlugins.each { File pluginFile ->
- def manifestDeps = getManifestDependencies(new File(pluginFile, "META-INF/MANIFEST.MF"))
- logger.info("Dependencies for " + pluginFile.toString() + ": " + manifestDeps.join(","))
-
- File dest = new File(pluginFile, "libs")
- if (!manifestDeps.isEmpty() && !dest.isDirectory()) {
- dest.mkdirs()
- }
-
- manifestDeps.each {
- if (!artifactMap.containsKey(it)) {
- throw new RuntimeException("No resolved artifact for: " + it + ", required for: "
- + pluginFile.getPath())
- }
-
- String destName = artifactMap.get(it)
- logger.info("\tCopying " + destName + " to " + dest)
- ant.copy(file: destName, tofile: new File(dest, it))
- }
- }
-}
-
-// unzip eclipse prebuilts into the out folder to create a target platform for the build
-task unzipTargetPlatform << {
- File targetDir = new File(outFile, "/host/maven/target").getCanonicalFile()
- targetDir.mkdirs()
-
- project.targetComponents.each { String k, File v ->
- File d = new File(targetDir, k)
- logger.info("Unzipping " + v.getPath() + " into: " + d.getPath())
- ant.unzip(src: v, dest: d)
- }
-}
-
-task buildEclipse(type: Exec, dependsOn: unzipTargetPlatform) {
- def maven = new File(projectDir, "../../prebuilts/eclipse/maven/apache-maven-3.2.1/bin/mvn").getCanonicalFile()
- def androidOut = outFile.getCanonicalPath()
- environment("M2_HOME", maven.getParentFile().getParentFile().getCanonicalPath())
- workingDir projectDir
- commandLine maven.getCanonicalPath(), "-s", "settings.xml", "-DforceContextQualifier=$project.buildNumber", "-DANDROID_OUT=$androidOut", "package"
-}
-
-private File getArtifact(ResolvedDependency dependency) {
- if (dependency.moduleArtifacts.size() != 1) {
- String msg = String.format("Each dependency is expected to map to a single jar file, " +
- "but %s maps to the following artifacts: %s",
- dependency,
- dependency.moduleArtifacts.collect { it.file })
- throw new RuntimeException(msg);
- }
-
- return dependency.moduleArtifacts.iterator().next().file
-}
-
-// parse a plugin's manifest file and return the list of jar dependencies expected to be
-// bundled inside
-private List<String> getManifestDependencies(File manifest) {
- if (manifest == null || !manifest.exists()) {
- return []
- }
-
- def entries = []
-
- def fis = new FileInputStream(manifest)
- try {
- java.util.jar.Manifest m = new java.util.jar.Manifest(fis)
- def classPath = m.getMainAttributes().getValue("Bundle-ClassPath")
- if (classPath == null) {
- return []
- }
-
- classPath.split(',').each {
- if (!it.equals(".")) {
- if (!it.startsWith("libs/") || !it.endsWith(".jar")) {
- throw new RuntimeException(
- "Unexpected classpath entry: " + it + " in file: " + manifest)
- }
-
- entries.add(it.substring("libs/".length()))
- }
- }
- } finally {
- fis.close()
- }
-
- return entries
-}
diff --git a/eclipse/buildConfig/allElements.xml b/eclipse/buildConfig/allElements.xml
deleted file mode 100644
index b3b5c4e1c..000000000
--- a/eclipse/buildConfig/allElements.xml
+++ /dev/null
@@ -1,112 +0,0 @@
-<!-- ========================================================================= -->
-<!-- Feature build ant targets -->
-<!-- Template obtained from org.eclipse.pde.build/templates/headless-build -->
-<!-- ========================================================================= -->
-<project name="allElements Delegator">
-
- <!-- ===================================================================== -->
- <!-- Run a given ${target} on all elements being built -->
- <!-- Replace element.id with the id of the top level element being built. -->
- <!-- If element.id does not exist in ${buildDirectory}/features/element.id -->
- <!-- or ${baseLocation}/features/element.id, then you must provide the -->
- <!-- location by setting the property "pluginPath" -->
- <!-- Add on <ant> task for each top level element being built. -->
- <!-- ===================================================================== -->
- <target name="allElementsDelegator">
-
- <ant antfile="${genericTargets}" target="${target}">
- <property name="type" value="feature" />
- <property name="id" value="com.android.ide.eclipse.ddms" />
- </ant>
-
- <ant antfile="${genericTargets}" target="${target}">
- <property name="type" value="feature" />
- <property name="id" value="com.android.ide.eclipse.hierarchyviewer" />
- </ant>
-
- <ant antfile="${genericTargets}" target="${target}">
- <property name="type" value="feature" />
- <property name="id" value="com.android.ide.eclipse.adt" />
- </ant>
-
- <ant antfile="${genericTargets}" target="${target}">
- <property name="type" value="feature" />
- <property name="id" value="com.android.ide.eclipse.ndk" />
- </ant>
-
- <ant antfile="${genericTargets}" target="${target}">
- <property name="type" value="feature" />
- <property name="id" value="com.android.ide.eclipse.traceview" />
- </ant>
-
- <ant antfile="${genericTargets}" target="${target}">
- <property name="type" value="feature" />
- <property name="id" value="com.android.ide.eclipse.gldebugger" />
- </ant>
-
- <antcall target="buildInternalFeatures"/>
- </target>
-
- <!-- ===================================================================== -->
- <!-- Conditional target for building the internal features -->
- <!-- Builds if property internalSite is set -->
- <!-- ===================================================================== -->
- <target name="buildInternalFeatures" if="internalSite">
- <ant antfile="${genericTargets}" target="${target}">
- <property name="type" value="feature" />
- <property name="id" value="com.android.ide.eclipse.tests" />
- </ant>
-
- <ant antfile="${genericTargets}" target="${target}">
- <property name="type" value="feature" />
- <property name="id" value="com.android.ide.eclipse.pdt" />
- </ant>
- </target>
-
- <!-- ===================================================================== -->
- <!-- Targets to assemble the built elements for particular configurations -->
- <!-- These generally call the generated assemble scripts (named in -->
- <!-- ${assembleScriptName}) but may also add pre and post processing -->
- <!-- Add one target for each root element and each configuration -->
- <!-- Replace element.id with the id of the top level element being built -->
- <!-- ===================================================================== -->
- <target name="assemble.com.android.ide.eclipse.base">
- <ant antfile="${assembleScriptName}" dir="${buildDirectory}"/>
- </target>
-
- <target name="assemble.com.android.ide.eclipse.adt">
- <ant antfile="${assembleScriptName}" dir="${buildDirectory}"/>
- </target>
-
- <target name="assemble.com.android.ide.eclipse.adt.overlay">
- <ant antfile="${assembleScriptName}" dir="${buildDirectory}"/>
- </target>
-
- <target name="assemble.com.android.ide.eclipse.ndk">
- <ant antfile="${assembleScriptName}" dir="${buildDirectory}"/>
- </target>
-
- <target name="assemble.com.android.ide.eclipse.ddms">
- <ant antfile="${assembleScriptName}" dir="${buildDirectory}"/>
- </target>
-
- <target name="assemble.com.android.ide.eclipse.tests">
- <ant antfile="${assembleScriptName}" dir="${buildDirectory}"/>
- </target>
-
- <target name="assemble.com.android.ide.eclipse.hierarchyviewer">
- <ant antfile="${assembleScriptName}" dir="${buildDirectory}"/>
- </target>
-
- <target name="assemble.com.android.ide.eclipse.pdt">
- <ant antfile="${assembleScriptName}" dir="${buildDirectory}"/>
- </target>
-
- <target name="assemble.com.android.ide.eclipse.traceview">
- <ant antfile="${assembleScriptName}" dir="${buildDirectory}"/>
- </target>
-
- <target name="assemble.com.android.ide.eclipse.gldebugger">
- <ant antfile="${assembleScriptName}" dir="${buildDirectory}"/>
- </target>
-</project>
diff --git a/eclipse/buildConfig/build.properties b/eclipse/buildConfig/build.properties
deleted file mode 100644
index 4c1d471dc..000000000
--- a/eclipse/buildConfig/build.properties
+++ /dev/null
@@ -1,239 +0,0 @@
-###############################################################################
-# Copyright (c) 2003, 2006 IBM Corporation and others.
-# All rights reserved. This program and the accompanying materials
-# are made available under the terms of the Eclipse Public License v1.0
-# which accompanies this distribution, and is available at
-# http://www.eclipse.org/legal/epl-v10.html
-#
-# Contributors:
-# IBM Corporation - initial API and implementation
-###############################################################################
-
-
-# This file was generated per the instructions located in Eclipse Help>Plug-in Development
-# Environment > Guide > Tasks > Building features and customized for building the
-# Android Eclipse plugins.
-
-#####################
-# Parameters describing how and where to execute the build.
-# Typical users need only update the following properties:
-# baseLocation - where things you are building against are installed
-# bootclasspath - The base jars to compile against (typicaly rt.jar)
-# configs - the list of {os, ws, arch} configurations to build.
-#
-# Of course any of the settings here can be overridden by spec'ing
-# them on the command line (e.g., -DbaseLocation=d:/eclipse
-
-############# PRODUCT/PACKAGING CONTROL #############
-product=/plugin or feature id/path/to/.product
-runPackager=true
-
-#Set the name of the archive that will result from the product build.
-#archiveNamePrefix=
-
-# The prefix that will be used in the generated archive.
-# override default of "eclipse" to aid for external site generation
-archivePrefix=android-eclipse
-
-# The location underwhich all of the build output will be collected.
-collectingFolder=${archivePrefix}
-
-# The list of {os, ws, arch} configurations to build. This
-# value is a '&' separated list of ',' separate triples. For example,
-# configs=win32,win32,x86 & linux,motif,x86
-# By default the value is *,*,*
-configs = *, *, *
-#configs=win32, win32, x86 & \
-# linux, gtk, ppc &\
-# linux, gtk, x86 & \
-# linux, gtk, x86_64 & \
-# linux, motif, x86 & \
-# solaris, motif, sparc & \
-# solaris, gtk, sparc & \
-# aix, motif, ppc & \
-# hpux, motif, PA_RISC & \
-# macosx, carbon, ppc
-
-# By default PDE creates one archive (result) per entry listed in the configs property.
-# Setting this value to try will cause PDE to only create one output containing all
-# artifacts for all the platforms listed in the configs property.
-#groupConfigurations=true
-
-#The format of the archive. By default a zip is created using antZip.
-#The list can only contain the configuration for which the desired format is different than zip.
-#archivesFormat=win32, win32, x86 - antZip& \
-# linux, gtk, ppc - antZip &\
-# linux, gtk, x86 - antZip& \
-# linux, gtk, x86_64 - antZip& \
-# linux, motif, x86 - antZip& \
-# solaris, motif, sparc - antZip& \
-# solaris, gtk, sparc - antZip& \
-# aix, motif, ppc - antZip& \
-# hpux, motif, PA_RISC - antZip& \
-# macosx, carbon, ppc - antZip
-
-#Set to true if you want the output to be ready for an update jar (no site.xml generated)
-outputUpdateJars = true
-
-#Set to true for Jnlp generation
-#codebase should be a URL that will be used as the root of all relative URLs in the output.
-#generateJnlp=false
-#jnlp.codebase=<codebase url>
-#jnlp.j2se=<j2se version>
-#jnlp.locale=<a locale>
-#jnlp.generateOfflineAllowed=true or false generate <offlineAllowed/> attribute in the generated features
-#jnlp.configs=${configs} #uncomment to filter the content of the generated jnlp files based on the configuration being built
-
-#Set to true if you want to sign jars
-#signJars=false
-#sign.alias=<alias>
-#sign.keystore=<keystore location>
-#sign.storepass=<keystore password>
-
-#Arguments to send to the zip executable
-zipargs=
-
-#Arguments to send to the tar executable
-tarargs=
-
-#Control the creation of a file containing the version included in each configuration - on by default
-#generateVersionsLists=false
-
-############## BUILD NAMING CONTROL ################
-# The directory into which the build elements are fetched and where
-# the build takes place.
-buildDirectory=.
-
-# Type of build. Used in naming the build output. Typically this value is
-# one of I, N, M, S, ...
-buildType=build
-
-# ID of the build. Used in naming the build output.
-# forceContextQualifer = build label
-buildId=${forceContextQualifier}
-
-# Label for the build. Used in naming the build output
-buildLabel=${buildId}
-
-# Timestamp for the build. Used in naming the build output
-timestamp=007
-
-#The value to be used for the qualifier of a plugin or feature when you want to override the value computed by pde.
-#The value will only be applied to plugin or features indicating build.properties, qualifier = context
-#forceContextQualifier=<the value for the qualifier>
-
-#Enable / disable the generation of a suffix for the features that use .qualifier.
-#The generated suffix is computed according to the content of the feature
-#generateFeatureVersionSuffix=true
-
-############# BASE CONTROL #############
-# Settings for the base Eclipse components and Java class libraries
-# against which you are building.
-# Base location for anything the build needs to compile against. For example,
-# in most RCP app or a plug-in, the baseLocation should be the location of a previously
-# installed Eclipse against which the application or plug-in code will be compiled and the RCP delta pack.
-
-baseLocation=${ECLIPSE_HOME}
-#Os/Ws/Arch/nl of the eclipse specified by baseLocation
-# Note: These default values may be overridden by the build_plugins script
-baseos=linux
-basews=gtk
-basearch=x86
-
-#this property indicates whether you want the set of plug-ins and features to be considered during the build to be limited to the ones reachable from the features / plugins being built
-filteredDependencyCheck=false
-
-#this property indicates whether the resolution should be done in development mode (i.e. ignore multiple bundles with singletons)
-resolution.devMode=false
-
-#pluginPath is a list of locations in which to find plugins and features. This list is separated by the platform file separator (; or :)
-#a location is one of:
-#- the location of the jar or folder that is the plugin or feature : /path/to/foo.jar or /path/to/foo
-#- a directory that contains a /plugins or /features subdirectory
-#- the location of a feature.xml, or for 2.1 style plugins, the plugin.xml or fragment.xml
-#pluginPath=
-
-skipBase=true
-eclipseURL=<url for eclipse download site>
-eclipseBuildId=<Id of Eclipse build to get>
-eclipseBaseURL=${eclipseURL}/eclipse-platform-${eclipseBuildId}-win32.zip
-
-
-############# MAP FILE CONTROL ################
-# This section defines CVS tags to use when fetching the map files from the repository.
-# If you want to fetch the map file from repository / location, change the getMapFiles target in the customTargets.xml
-
-skipMaps=true
-mapsRepo=:pserver:anonymous@example.com/path/to/repo
-mapsRoot=path/to/maps
-mapsCheckoutTag=HEAD
-
-#tagMaps=true
-mapsTagTag=v${buildId}
-
-
-############ REPOSITORY CONTROL ###############
-# This section defines properties parameterizing the repositories where plugins, fragments
-# bundles and features are being obtained from.
-
-# The tags to use when fetching elements to build.
-# By default thebuilder will use whatever is in the maps.
-# This value takes the form of a comma separated list of repository identifier (like used in the map files) and the
-# overriding value
-# For example fetchTag=CVS=HEAD, SVN=v20050101
-# fetchTag=HEAD
-skipFetch=true
-
-
-############# JAVA COMPILER OPTIONS ##############
-# The location of the Java jars to compile against. Typically the rt.jar for your JDK/JRE
-#bootclasspath=${java.home}/lib/rt.jar
-
-# specific JRE locations to compile against. These values are used to compile bundles specifying a
-# Bundle-RequiredExecutionEnvironment. Uncomment and set values for environments that you support
-#CDC-1.0/Foundation-1.0= /path/to/rt.jar
-#CDC-1.1/Foundation-1.1=
-#OSGi/Minimum-1.0=
-#OSGi/Minimum-1.1=
-#JRE-1.1=
-#J2SE-1.2=
-#J2SE-1.3=
-#J2SE-1.4=
-#J2SE-1.5=
-#JavaSE-1.6=
-#PersonalJava-1.1=
-#PersonalJava-1.2=
-#CDC-1.0/PersonalBasis-1.0=
-#CDC-1.0/PersonalJava-1.0=
-#CDC-1.1/PersonalBasis-1.1=
-#CDC-1.1/PersonalJava-1.1=
-
-# Specify the output format of the compiler log when eclipse jdt is used
-logExtension=.log
-
-# Whether or not to include debug info in the output jars
-javacDebugInfo=true
-
-# Whether or not to fail the build if there are compiler errors
-javacFailOnError=true
-
-# Enable or disable verbose mode of the compiler
-javacVerbose=true
-
-# Extra arguments for the compiler. These are specific to the java compiler being used.
-compilerArg=-warn:none
-
-# Default value for the version of the source code. This value is used when compiling plug-ins that do not set the Bundle-RequiredExecutionEnvironment or set javacSource in build.properties
-javacSource=1.6
-
-# Default value for the version of the byte code targeted. This value is used when compiling plug-ins that do not set the Bundle-RequiredExecutionEnvironment or set javacTarget in build.properties.
-javacTarget=1.6
-
-################### CUSTOM PROPERTIES #######################################
-# repository location for update site
-# comment out - this is passed in from command line
-#updateSiteSource=${buildDirectory}/sites/external
-# where to place update site build
-updateSiteRoot=${user.home}/www/no_crawl/
-updateSiteFolder=${archivePrefix}
-updateSiteDestination=${updateSiteRoot}/${updateSiteFolder}
diff --git a/eclipse/buildConfig/buildUpdateSite.xml b/eclipse/buildConfig/buildUpdateSite.xml
deleted file mode 100644
index 1ab7c99a0..000000000
--- a/eclipse/buildConfig/buildUpdateSite.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-<project name="update site">
- <!-- ========================================================================= -->
- <!-- Extracts feature zip for update site -->
- <!-- expected properties: -->
- <!-- id - feature id to extract -->
- <!-- buildDirectory - base directgory where build takes place -->
- <!-- buildLabel - build id label -->
- <!-- updateSiteRoot - where to extract feature zip -->
- <!-- ========================================================================= -->
- <target name="extractFeature">
- <unzip src="${buildDirectory}/${buildLabel}/${id}-${buildLabel}.zip" dest="${updateSiteRoot}"/>
- </target>
-</project>
diff --git a/eclipse/buildConfig/customTargets.xml b/eclipse/buildConfig/customTargets.xml
deleted file mode 100644
index 5a46bfc66..000000000
--- a/eclipse/buildConfig/customTargets.xml
+++ /dev/null
@@ -1,195 +0,0 @@
-<!-- ========================================================================= -->
-<!-- Eclipse template file for PDE builds -->
-<!-- template originally obtained from org.eclipse.pde.build/templates/headless-build -->
-<!-- ========================================================================= -->
-<project name="Build specific targets and properties" default="noDefault">
-
- <!-- ===================================================================== -->
- <!-- Run a given ${target} on all elements being built -->
- <!-- Add on <ant> task for each top level element being built. -->
- <!-- ===================================================================== -->
- <property name="allElementsFile" value="${builder}/allElements.xml"/>
- <import file="${allElementsFile}" />
- <target name="allElements">
- <antcall target="allElementsDelegator" />
- </target>
-
- <!-- ===================================================================== -->
- <!-- ===================================================================== -->
- <target name="getBaseComponents" depends="checkLocalBase" unless="skipBase">
- <get src="${eclipseBaseURL}" dest="${buildDirectory}/../temp-base.zip" />
- <unzip dest="${base}" overwrite="true" src="${buildDirectory}/../temp-base.zip" />
- </target>
-
- <target name="checkLocalBase">
- <available file="${base}" property="skipBase" />
- </target>
-
- <!-- ===================================================================== -->
- <!-- Check out map files from correct repository -->
- <!-- Replace values for mapsCheckoutTag as desired. -->
- <!-- ===================================================================== -->
- <target name="getMapFiles" depends="checkLocalMaps" unless="skipMaps">
- <property name="mapsCheckoutTag" value="HEAD" />
- <cvs cvsRoot="${mapsRepo}" package="${mapsRoot}" dest="${buildDirectory}/maps" tag="${mapsCheckoutTag}" />
- </target>
-
- <target name="checkLocalMaps">
- <available property="skipMaps" file="${buildDirectory}/maps" />
- </target>
-
- <target name="tagMapFiles" if="tagMaps">
- <cvs dest="${buildDirectory}/maps/${mapsRoot}" command="tag ${mapsTagTag}" />
- </target>
-
- <!-- ===================================================================== -->
-
- <target name="clean" unless="noclean">
- <antcall target="allElements">
- <param name="target" value="cleanElement" />
- </antcall>
- </target>
-
- <target name="gatherLogs">
- <mkdir dir="${buildDirectory}/${buildLabel}/compilelogs" />
- <antcall target="allElements">
- <param name="target" value="gatherLogs" />
- </antcall>
- <unzip dest="${buildDirectory}/${buildLabel}/compilelogs" overwrite="true">
- <fileset dir="${buildDirectory}/features">
- <include name="**/*.log.zip" />
- </fileset>
- </unzip>
- </target>
-
- <!-- ===================================================================== -->
- <!-- Steps to do before setup -->
- <!-- ===================================================================== -->
- <target name="preSetup">
- </target>
-
- <!-- ===================================================================== -->
- <!-- Steps to do after setup but before starting the build proper -->
- <!-- ===================================================================== -->
- <target name="postSetup">
- <antcall target="getBaseComponents" />
- </target>
-
- <!-- ===================================================================== -->
- <!-- Steps to do before fetching the build elements -->
- <!-- ===================================================================== -->
- <target name="preFetch">
- </target>
-
- <!-- ===================================================================== -->
- <!-- Steps to do after fetching the build elements -->
- <!-- ===================================================================== -->
- <target name="postFetch">
- </target>
-
- <!-- ===================================================================== -->
- <!-- Steps to do before generating the build scripts. -->
- <!-- ===================================================================== -->
- <target name="preGenerate">
- </target>
-
- <!-- ===================================================================== -->
- <!-- Steps to do after generating the build scripts. -->
- <!-- ===================================================================== -->
- <target name="postGenerate">
- <antcall target="clean" />
- </target>
-
- <!-- ===================================================================== -->
- <!-- Steps to do before running the build.xmls for the elements being built. -->
- <!-- ===================================================================== -->
- <target name="preProcess">
- </target>
-
- <!-- ===================================================================== -->
- <!-- Steps to do after running the build.xmls for the elements being built. -->
- <!-- ===================================================================== -->
- <target name="postProcess">
- </target>
-
- <!-- ===================================================================== -->
- <!-- Steps to do before running assemble. -->
- <!-- ===================================================================== -->
- <target name="preAssemble">
- </target>
-
- <!-- ===================================================================== -->
- <!-- Steps to do after running assemble. -->
- <!-- ===================================================================== -->
- <target name="postAssemble">
- </target>
-
- <!-- ===================================================================== -->
- <!-- Steps to do before running package. -->
- <!-- ===================================================================== -->
- <target name="prePackage">
- </target>
-
- <!-- ===================================================================== -->
- <!-- Steps to do after running package. -->
- <!-- ===================================================================== -->
- <target name="postPackage">
- </target>
-
- <!-- ===================================================================== -->
- <!-- Steps to do after the build is done. -->
- <!-- ===================================================================== -->
- <target name="postBuild">
- <antcall target="gatherLogs" />
- <!-- Added this custom target ! -->
- <antcall target="generateUpdateSite" />
- </target>
-
- <!-- ===================================================================== -->
- <!-- Steps to do to test the build results -->
- <!-- ===================================================================== -->
- <target name="test">
- </target>
-
- <!-- ===================================================================== -->
- <!-- Steps to do to publish the build results -->
- <!-- ===================================================================== -->
- <target name="publish">
-
- </target>
-
- <!-- ===================================================================== -->
- <!-- Default target -->
- <!-- ===================================================================== -->
- <target name="noDefault">
- <echo message="You must specify a target when invoking this file" />
- </target>
-
- <!-- ===================================================================== -->
- <!-- Custom target: -->
- <!-- Steps to do to generate the update site -->
- <!-- ===================================================================== -->
- <target name="generateUpdateSite">
- <echo message="Copying update site source ${updateSiteSource} to destination"/>
-
- <copy file="${updateSiteSource}/site.xml" overwrite="true" todir="${updateSiteDestination}"/>
- <copy file="${updateSiteSource}/index.html" overwrite="true" todir="${updateSiteDestination}"/>
- <copy file="${updateSiteSource}/web/site.css" overwrite="true" todir="${updateSiteDestination}/web"/>
- <copy file="${updateSiteSource}/web/site.xsl" overwrite="true" todir="${updateSiteDestination}/web"/>
-
- <!-- replace qualifier version references with build label -->
- <replace file="${updateSiteDestination}/site.xml" token="qualifier" value="${buildId}"/>
-
- <!-- now extract each features zip to update site -->
- <antcall target="allElements">
- <param name="genericTargets" value="${builder}/buildUpdateSite.xml"/>
- <param name="target" value="extractFeature" />
- </antcall>
-
- <chmod perm="755" type="both">
- <fileset dir="${updateSiteDestination}">
- </fileset>
- </chmod>
- </target>
-
-</project>
diff --git a/eclipse/changes.txt b/eclipse/changes.txt
deleted file mode 100644
index aeec5cccb..000000000
--- a/eclipse/changes.txt
+++ /dev/null
@@ -1,868 +0,0 @@
-21.0.0
-* Bug fixes.
-* JUnit test runner allows a test to be run on all devices
-* XML code completion can now complete (and show documentation for)
- theme references, such as ?android:attr/dividerHeight
-* Improved flag and locale data in the configuration chooser
-* New lint checks:
- * Find misspellings in English string files
- * Detect certain types of wakelock mistakes leading to unnecessary
- battery usage
- * Find private key files placed in directories where they end up
- getting bundled with the .apk
- * Find usages of "dp" units with the font property textSize
- * Find invalid selector files where a later state is fully covered
- by an earlier state and is therefore unreachable
- * Find incorrect use of the SecureRandom object (where it is
- initialized with a fixed seed)
- Various lint infrastructure improvements.
-
-20.0.0
-* A lot of bug fixes, performance fixes and memory fixes.
-* Support for Eclipse 4.x.
-* Build System
- * Automatic merging of library project manifest files into the
- including project's manifest. Enable with the
- manifestmerger.enabled property.
- * Automatic ProGuard support for the aapt -G flag. This means that
- the build system will generate a temporary ProGuard keep-rules
- file containing classes to keep that are referenced from XML files
- (such as custom views) and pass this to ProGuard at
- shrink-time. This can make the resulting APK much smaller when
- using just a small portion of a large library project (such as the
- Android Support library), since we have also removed the catch-all
- rules to keep all custom views from the default ProGuard
- configuration file.
- * Aidl files from library projects are now in the import list.
- * Fixes in Ant:
- * Test projects now have access to the full classpath from the
- tested projects, including Library Projects and 3rd party jar
- * Applications embedding tests can now be deployed and tested,
- including with code coverage, like test applications.
-* Lint
- * Tighter integration with the layout editor (error and warning
- icons overlaid views with errors, lint error messages shown as
- tooltips in the layout canvas and in the outline, error count
- displayed in the layout actions bar.)
- * Lint is run incrementally in Java files on save, just like XML
- files already are.
- * New lint rules:
- * Detect usages of Toast.makeText() without calling show() on the
- result, as well as passing invalid duration parameters (e.g. a
- number instead of one of the two allowed constants.)
- * Detect incorrect manifest registrations (where elements such as
- <uses-library>, <activity> etc are placed under the wrong parent.)
- * Several security checks: Look for exported content providers
- without required permissions, look for creation of world readable
- files and preferences, look for calls to
- android.webkit.WebSettings.setJavaScriptEnabled.
- * Check to make sure that Fragment classes are instantiatable. If
- you accidentally make a fragment innerclass non-static, or forget
- to have a default constructor, you can hit runtime errors when the
- system attempts to reinstantiate your fragment after a
- configuration change.
- * Look for handler leaks: This check makes sure that a handler inner
- class does not hold an implicit reference to its outer class.
- * Duplicate Activity registrations in the manifest. This can lead to
- subtle errors that can be difficult to understand.
- * Lint check ensuring that when you edit() a SharedPreference object
- you call commit()
-* Layout Editor
- * New property sheet implementation, which offers:
- * Highlighting (in bold) for important attributes.
- * Inline preview of colors and images, as well as the
- corresponding resource name.
- * Displays default values, when available.
- * Completion of resource values and enum and flag constants.
- * Support for showing and hiding "advanced" properties.
- * Nested properties (and collapse all and expand all) for better
- categorization. For example, layout params are listed first as a
- single nested property.
- * Tooltips over the attribute names, not values, so they never
- obscure the value column.
- * Checkbox support for boolean values.
- * Support for switching between alphabetical and natural sort
- orders.
- * New window management. The propertysheet is now automatically
- docked into the Outline view, and the outline can appear in a
- maximized editor. The structure and palette views can be minimized
- and appear temporarily on flyover.
- * New configuration chooser above the layout editor, which in
- addition to a visual refresh offers an activity chooser, a nested
- theme chooser, a single button to flip orientation, better
- wrapping behavior, etc.
-* SDK Manager:
- * Cache to avoid downloading repository definitions all the time.
- * New "Tools > Manage Add-on Sites" option that allows deactivating
- 3rd party sites (e.g. if one or more are temporarily slow to
- load.)
-* NDK integration (alpha):
- * Initial support for building and debugging projects with C/C++
- code.
- * To enable this, install the NDK feature (depends on CDT), and then
- set the path to NDK in Android Preferences.
- * Add NDK nature to an Android project by right clicking on the
- project and select "Android Tools -> Add Native Support".
- * To debug an NDK project, just right click and select "Debug As
- Android Native Application".
-* Execution
- * LogCat: Allow users to set colors for different priorities
- * LogCat: Ctrl + F now brings up a Find dialog to find items (rather
- than filter)
- * Allow running on multiple devices with a single launch. The target
- tab in the launch configuration dialog adds a new option which
- allows launching on all connected devices, and a drop down allows
- the user to further narrow down the list to just physical devices
- or just emulators. (This applies only to Run configurations, not
- to Debug/JUnit tests.)
-* XML Editing
- * Code completion support for custom attributes on custom views.
- * Go to Declaration now works for theme references (?android:attr,
- ?attr: etc,)
- * Completion of the minSdkVersion and targetSdkVersion attributes in
- manifest files now include version descriptions for each of the
- API levels
- * Support XML editor outlines for layout files. Switching back and
- forth between the text editor and graphical editor will alternate
- between the two outlines, and in particular the XML editor outline
- will keep up to date with edits in the editor, and selection will
- follow the mouse cursor etc.
-* The Asset Studio Wizard now supports padding and disabling
- background shapes
-
-19.0.0 (does not exist)
-
-18.0.0
-* Fix bug 27940 where exporting release package doesn't recompile libraries
- in release mode.
-
-17.0.0:
-* ADT 17 requires Java 6 and Eclipse 3.6.2.
-* Improved Lint UI.
- * Many new lint checks: See the tools changes.txt for details.
- * New "Run Lint" toolbar action with a dropdown menu for selecting
- specific (or all) projects, clearing results, etc.
- * The results window is now organized as a tree rather than a flat
- list. Each issue type has a single top level item, which makes it
- easier to quickly scan through the reported issues and narrow
- down to issues you are most interested in.
- * The results window contains many new toolbar actions, including
- expand/collapse, ignore in file, ignore in project, ignore
- everywhere, show options, and configure columns.
- * There are new columns available, such as category, priority,
- project, file and line. The column selection (as well as the
- column sizes) are persisted. You can click on columns to sort by
- that column.
- * The Lint Options dialog has Enable All and Disable All buttons,
- and a search filter textbox to filter by issue id, summary and
- severity.
-* New Quick Outline for XML editors (Ctrl-O, Command-O). This shows
- the structure of the current file including icons and ids, and lets
- you filter and quickly jump to specific ids.
-* The resource chooser now shows the resolved value for resources
- (e.g. when selecting @string/hello it displays that the resolved value
- is "Hello World"). It also allows editing the chosen value directly.
-* The layout editor no longer assigns default ids to layouts, includes
- and merge tags. This tended to pollute the namespace with a lot of
- unused resources since layouts aren't usually manipulated via code,
- or referenced from XML. (The RelativeLayout editor automatically
- assigns ids to views without ids when pointing to them.)
-* Export Screenshot from the Layout Editor
-* Layout editor fix for SlidingDrawer which on some platforms could
- not be dragged into the layout. Also fix preview rendering for
- SlidingDrawer and TabHost (issue 23022).
-* New default application icons, including an xhdpi version.
-* Important bug fixes:
- * Fix bug in resource chooser which made some types of framework
- resources impossible to select (issue 20589)
- * Fix a bug in the formatter where a certain whitespace pattern
- could result in a non-space character getting deleted (issue
- 23940)
- * Fix locale bug affecting Turkish locales in particular (issue
- 23747)
-
-16.0.0:
-* New "lint" feature which scans the Android projects for potential
- problems such as missing translations, duplicate ids between layouts
- that include each other, using px instead of dp units, hardcoded
- strings, missing contentDescriptions, obsolete Proguard
- configuration files, etc. Lint can be run on the command line, but
- it is also integrated into the Problems view in Eclipse, and there
- are also quickfixes available for many of the reported errors.
-
-15.0.0
-Critical bug fixes only.
-
-14.0.0
-- Build system:
- - (TODO: More info) Improved library projects
- - Improved incremental builds
- - Resource compilation is run much less frequently. It is no
- longer run when strings are edited, or when layouts are edited
- (unless a new id is introduced), and it is no longer run once
- per library project (!)
- - Resource compilation is no longer done for normal save
- operations, only when running or debugging (option added in ADT
- 12 now on by default.)
- - There is a new "PNG crunch cache", which means image crunching
- is only done once, not once per build which is significant for
- projects with many resources
- - Incremental ant builds
- - ADT now uses bin/classes to output the java compilation
- and bin/ for Android specific classes. This will make bin show up
- in the package explorer.
-- DDMS
- - Brand new logcat view. Fixes bugs, displays and filters by
- application names instead of just pids, fronts when application
- runs.
-- XML Editing
- - New XML formatter which formats all XML files according to the
- standard Android coding style. The formatter can also reorder
- attributes to follow the recommended order.
- - Improved "smart indent": automatic indentation and un-indentation
- when pressing Return in XML editors
- - Go to Matching (Ctrl-Shift-P) in XML files can now jump between
- opening and closing tags
- - Changes made by the layout editor are automatically run through
- the new XML formatter.
- - Select Enclosing Element should now work on the Mac as well.
-- Java Editing
- - Quickfix for extracting Strings when the caret is inside a String
-- Layout Editor
- - New GridLayout support
- - Tooltip feedback for resizing and dragging operations. For
- example, when dragging in a relative layout, the proposed
- constraints are shown, and when resizing the new dimensions are
- shown.
- - New "Remove Container" visual refactoring which removes the
- children of a container up to the top level and transfers
- namespace and layout attributes if necessary.
- - Improved access to properties in the context menu: The most
- frequently set attributes for each view are listed at the top of
- the menu, and the properties menu offers access to the most
- recently set attributes, attributes organized by their defining
- view, and layout attributes only or all attributes alphabetically.
- - The context menu now also contains pull-right menus for accessing
- properties of the parents, which is useful when the children fully
- cover the parent making it hard to select on its own.
- - Ability to suppress rendering fidelity warnings.
-- Asset Studio integration: Wizard creation of launcher icons, menu
- icons, tab icons, etc.
-- New Welcome Wizard to help installing and configuring the SDK
- platforms.
-- The New Project and the New XML File wizards have been reworked into
- multiple pages. Sample Projects are now copied into the workspace
- such that they can be modified and deleted without affecting the
- master copy.
-- The dependency on Eclipse GEF was removed.
-- Many bug fixes, and in particular some critical bug fixes on Linux
-
-13.0.0
-- Tools release only (command line tools)
-
-12.0.0 (July 6th, 2011)
-- Many bug fixes!
-- Visual Layout Editor:
- - New RelativeLayout drop support with guideline suggestions for
- attachments and cycle prevention.
- - Resize support in most layouts. In LinearLayout, sizes are mapped
- to weights. Guideline snapping to wrap_content and match_parent.
- - Previews of drawables and colors in the resource chooser dialogs.
- - Improved error messages and links for rendering errors, including
- detection of misspellings of class names.
-- Build system: Delay post compiler phase until actual export or debug
- to speed up interactive file saves. (This is off by default but can
- be enabled in the ADT options panel.)
-
-11.0.0 (June 6th, 2011)
-- Visual Refactoring:
- - The new "Extract Style" refactoring pulls out style constants and
- defines them as style rules instead.
- - The new "Wrap in Container" refactoring surrounds the selected
- views with a new layout, and transfers namespace and layout
- parameters to the new parent
- - The new "Change Widget Type" refactoring changes the type of the
- selected views to a new type. (Also, a new selection context menu
- in the visual layout editor makes it easy to select siblings as
- well as views anywhere in the layout that have the same type).
- - The new "Change Layout" refactoring changes layouts from one type
- to another, and can also flatten a layout hierarchy.
- - The "Extract as Include" refactoring now finds identical fragments
- in other layouts and offers to combine all into a single include.
- - There is a new Refactoring Quick Assistant which can be invoked
- from the XML editor (with Ctrl-1) to apply any of the above
- refactorings (and Extract String) to the current selection.
-- Visual Layout Editor:
- - Improved "rendering fidelity": The layout preview has been
- improved and should more closely match the rendering on actual
- devices.
- - The visual editor now previews ListViews at designtime. By
- default, a two-line list item is shown, but with a context menu
- you can pick any arbitrary layout to be used for the list items,
- and you can also pick the header and footer layouts.
- - The palette now supports "configurations" where a single view is
- presented in various different configurations. For example, there
- is a whole "Textfields" palette category where the EditText view
- can be dragged in as a password field, an e-mail field, a phone
- field, and so on. Similarly, TextViews are offered preconfigured
- with large, normal and small theme sizes, and LinearLayouts are
- offered both in horizontal and vertical configurations.
- - The palette supports custom views, picking up any custom
- implementations of the View class in your project source folders
- or in included libraries, and these can be dragged into layouts.
- - Fragments support: Fragments are available in the palette, and in
- the tool you can choose which layout to show rendered for a given
- fragment tag. Go to declaration works for fragment classes.
- - The layout editor automatically applies a "zoom to fit" for newly
- opened files as well as on device size and orientation changes to
- ensure that large layouts are always fully visible unless you
- manually zoom in.
- - You can drop an "include" tag from the palette, which will pop up
- a layout chooser, and the chosen layout is added as an include.
- Similarly, dropping images or image buttons will pop up image
- resource choosers to initialize the new image with.
- - The configuration chooser now applies the "Render Target" and
- "Locale" settings project wide, making it trivial to check the
- layouts for different languages or render targets without having
- to configure these individually for each layout.
- - The layout editor is smarter about picking a default theme to
- render a layout with, consulting factors like theme registrations
- in the manifest, the SDK version, etc.
- - The layout editor is also smarter about picking a default
- configuration to render a layout with, defaulting to the currently
- visible configuration in the previous file. It also considers the
- SDK target to determine whether to default to a tablet or phone
- screen size.
- - Basic focus support: The first text field dropped in a layout is
- assigned focus, and there are "Request Focus" and "Clear Focus"
- context menu items on text fields to change the focus.
-- XML editors:
- - Code completion has been significantly improved. It now works
- within <style> elements, it completes dimensional units,
- it sorts resource paths in values based on the attribute name,
- etc. There are also many fixes to handle text replacement.
- - AAPT errors are handled better. They are now underlined for the
- relevant range in the editor, and a new quickfix makes it trivial
- to create missing resources.
- - Code completion for drawable, animation and color XML files.
-- DDMS:
- - "New Folder" action in the File Explorer
- - The screenshot dialog will add timestamps to the filenames, and
- preserve the orientation on snapshot refresh
-- TraceView: Mouse-wheel zoom support in the timeline
-- The New Android Project wizard now supports Eclipse working sets
-- Most of the tools have improved integration with the Mac OSX
- system menu bar.
-- Most of the tools have new launcher icons.
-
-10.0.1 (March, 2011)
-- Temporary work-around to resolve the rare cases in which the layout
- editor will not open.
-- Fix issue in which ADT 10.0.0 would install on Eclipse 3.4 and
- lower, even though ADT requires Eclipse 3.5 or higher (as of
- 10.0.0).
-
-10.0.0 (February 22nd, 2011)
-- The tools now automatically generate Java Programming Language
- source files (in the gen/ directory) and bytecode (in the res/raw/
- directory) from your .rs files.
-- A Binary XML editor has been added.
-- Traceview is now integrated into the Eclipse UI.
-- The "Go To Declaration" feature for XML and .java files quickly show
- all the matches in the project and allows you jump to specific items
- such as string translations or onClick handlers.
-- The Resource Chooser can create items such as dimensions, integers,
- ids, and booleans.
-- Improvements to the Visual Layout Editor:
- - A new Palette with categories and rendering previews.
- - A Layout Actions bar that provides quick access to common layout
- operations.
- - When the Android 3.0 rendering library is selected, layouts render
- more like they do on devices. This includes rendering of status
- and title bars to more accurately reflect the actual screen space
- available to applications.
- - Zoom improvements such as fit to view, persistent scale, and
- keyboard access..
- - Further improvements to <merge> layouts, as well as layouts with
- gesture overlays.
- - Improved rendering error diagnostics.
-
-9.0.0 (January 26, 2011)
-- Visual Layout Editor
- - Empty layouts with 0,0 size are now automatically expanded when
- selected and during drag and drop
- - Rendering target can now be changed from the default (project
- target)
- - When choosing resources for rendering, the API level is properly
- handled
- - Improved support for rendering <include> and <merge> views
- - "Extract as Include" refactoring to extract selected views into
- a separate included layout.
- - String and reference properties can be edited from the layout
- editor's context menu
- - Rewritten outline drag & drop handling, improved label colors
- and content
- - The generated XML will be better formatted. Full XML formatter
- can be enabled in the preferences (under Android > Editors), but
- will touch part of the XML that isn't modified.
- - Automatic configuration of many widgets on drop, such as
- automatically filling a TextView in a vertical LinearLayout,
- adding rows to new tables, etc.
- - Double click views to jump to the corresponding XML declaration,
- or for included views, to the included layout file
- - Improved support for various views (such as TabHosts and
- SlidingDrawers) when rendered using Honeycomb
-- Go to Declaration hyperlinks for navigating from @resource
- references to their XML declarations, from the manifest file to
- activity and service classes, from Java access of resource R fields
- to the XML declarations, etc.
-- Logcat view in DDMS now properly displays UTF-8 characters.
-
-8.0.1 (October 2010)
-- Fix compilation issue in Android projects referencing standard Java
- projects.
-- Better error reporting when exporting applications for release.
-
-8.0.0 (October 2010)
-- New version number scheme following the SDK Tools revision number.
-- Support for true debug build. No need to change the value of
- debuggable in the Android Manifest. Incremental build will
- automatically insert debuggable==true while using the "export
- signed/unsigned application package" will not. If debuggable=true
- is set, then release builds will actually do a debug build.
-- Automatic Proguard support in release builds. Only need to have a
- proguard.config property in default.properties that points to a
- proguard config file.
-- Completely rewritten Visual Layout Editor. This is very much a work
- in progress.
- - full drag and drop from palette to layout for all Layout
- classes.
- - Move widgets inside a Layout view, from one Layout view to
- another and from one layout file to another.
- - Contextual menu with enum/flag type properties.
- - New zoom controls.
-- New HierarchyViewer plug-in integrated in Eclipse.
-- Android launch configurations don't recompile the whole workspace on
- launch anymore.
-- android.jar source and javadoc location can now be configured.
-
-0.9.9:
-- Fix bug where ADT would delete the source folder of projects
- imported from version control.
-
-0.9.8:
-- New Action "Rename Application Package" (under the "Android Tools"
- contextual menu) will do a full application package refatoring.
-- Fixed issue with library project names containing characters that
- aren't compatible with Eclipse path variable. The link between the
- main project and the library would fail to create.
-- Added support for library projects that don't have a source folder
- called "src". There is now support for any number of source folder,
- with no name restriction. They can even be in sub folder such as
- "src/java".
-- Added support for libraries with library dependencies.
-- added support for new resource qualifiers: car/desk, night/notnight
- and navexposed/navhidden
-- Added more device screen types for the layout editor. All screen
- resolution/density combinations from
- http://developer.android.com/guide/practices/screens_support.html#range
- is now available.
-
-0.9.7:
-- Support for library projects
-- Updated Property panel for Android project to edit library
- dependencies.
-
-0.9.6:
-- Editing default.properties outside of eclipse will automatically
- update the project
-- Fix issue when launching ADT the first time with the SDK Usage panel
- that could create a deadlock between modal dialogs
-- Launched applications from ADT now behave as if they were clicked
- from the Home screen of the emulator.
-- AVD creation dialog now enforce sd card of 9MB or higher
-- Fixed issue where add-on with no optional library would not show up
- as valid targets for application launches.
-- Loads the SDK content only when a project requires it. This will
- make Eclipse use less resources when the SDK contains many versions
- of Android.
-- DDMS plug-in now contains the Allocation Tracker view.
-- Lots of fixes in the configuration selector of the Visual Layout
- Editor.
-- Explode mode in the Visual Layout Editor adds a margin to all layout
- objects so that it's easier to see embedded layouts
-- Outline mode in the Visual Layout Editor draws layout outline to
- make it easier to see layout objects.
-- Fixed issues with the New Project Wizard when selecting samples.
-- Fixed possible crash when launching applications
-- New action in the Logcat view: "Go to problem" lets you go directly
- from an exception trace output to the code.
-
-0.9.5:
-- Misc fixes in the SDK Updater
-
-0.9.4:
-- New "Create project from sample" choice in the New Project Wizard.
-- Improvements to the SDK Updater.
-- improvements to the AVD Manager (creation and launch dialogs)
-- new configuration selector in the Graphical Layout Editor
-
-0.9.3:
-- New wizard to create Android JUnit Test Projects.
-- New AVD wizard.
-- SDK Updater
-- zipalign support
-
-0.9.1:
-
-- Added an AVD creation wizard to ADT. It is automatically displayed
- during a launch if no compatible AVDs are found.
-- Fixed issue with libs/ folder where files with no extension would
- prevent the build from finishing.
-- Improved error handling during the final steps of the build to mark
- the project if an unexpected error prevent the build from finishing.
-- Fixed issue when launching ADT on a clean install would trigger
- org.eclipse.swt.SWTError: Not implemented [multiple displays].
-
-
-
-0.9.0:
-
-- Projects now store generated Java files (R.java/Manifest.java and
- output from aidl) in a 'gen' source folder.
-- Support for the new Android SDK with support for multiple versions
- of the Android platform and for vendor supplied add-ons.
- * New Project Wizard lets you choose which platform/add-on to
- target.
- * Project properties (right click project in Package Explorer,
- then "Properties"), lets you edit project target.
- * New Launch configuration option to choose debug deployment
- target.
-- Ability to export multiple apk from one project, using resource
- filters. See the 'android' property for Android projects.
-- Support for running JUnit tests on a device/emulator from a new
- "Android JUnit tests" launch configuration.
-
-0.8.1:
-
-- Alternate Layout wizard. In the layout editor, the "create" button
- is now enabled to easily create alternate versions of the current
- layout.
-- Fixed issue with custom themes/styles in the layout editor.
-- Export Wizard: To export an application for release, and sign it
- with a non debug key. Accessible from the export menu, from the
- Android Tools contextual menu, or from the overview page of the
- manifest editor.
-- New XML File Wizard: To easily create new XML resources file in the
- /res directory.
-- New checks on launch when attempting to debug on a device.
-- Basic support for drag'n'drop in Graphical layout editor. You can
- add new items by drag'n'drop from the palette. There is no support
- for moving/resizing yet.
-- Undo/redo support in all XML form editors and Graphical layout
- editor.
-
-0.8.0:
-
-- Fixed issue with using custom classes implementing Parcelable in
- aidl files. Right click the project and choose Android Tools >
- Create aidl preprocess file for Parcelable Classes.
-- Added Custom Themes to theme drop down in the layout editor.
-- Customizable debug signing keystore path in preferences
-- Customizable HOME package name.
-
-0.7.1:
-
-- Layout Editor.
-
-0.6.1:
-- Fixed install issue when project name contains spaces (requires new
- emulator image)
-- Fixed setup of the New class wizard in the manifest (when clicking
- on "name" for a class attribute) in the cases where the class and
- some of its parent packages were missing.
-- Properly kill the application that is about to be reinstalled.
-- Create missing android folder automatically when building
- application (caused a signing error)
-- Manifest editor: support for uses-library node
-- Fixed NPE in editors.xml.descriptors.XmlDescriptors.createPreference
-- Fixed assert in MultiEditorPart.setActivePage
-- Fixed "connect to debugger" button in DeviceView. Also fixed support
- for custom process names.
-
-0.6.0:
-
-- New launch option for activity. Can choose to launch default
- activity (finds an activity configured to show up in the home
- screen), or specific activity, or none.
-- Normal java resources (non java files placed in package folders) are
- now properly packaged in the final package, and can be accessed
- through normal java API such as ClassLoader.getResourceAsStream()
-- Launch configuration now has an option to wipe emulator data on
- launch. This always asks for confirmation.
-- Launch configuration now has an option to disable the boot
- animation. This will let the emulator start faster on older
- computers.
-- Applications are now signed with a debug key (stored in
- debug.keystore in ~/.android).
-- Installation of application is now more robust and will notify of
- installation failure. Also installation is blocking, removing issues
- where ADT tried to launch the activity before the app was installed.
-- Tree-based resource editor + content assist in XML editor for
- layout, menu, preferences, values xml files. Work in progress...
-
-
-0.4.0 (adt 0.4.0, ddms 0.3.0, editors 0.2.0, common 0.1.0)
-
-- New AndroidManifest editor.
-- True multiple device support allowing debugging apps on several
- device at the same time
-- New launch modes for device selection: automatic will launch an
- emulator if no device are present, automatically target the device
- if only one exists, and prompt the user if 2+ are connected. Manual
- mode always prompt the user.
-- New classpath container remove the dependencies on the location of
- android.jar making it easier to share a project through dsvn, cvs,
- etc... You should fix your project (right click project, choose
- Android > Fix Project properties)
-- Fixed a case where pm would fail and would up end outputting the
- "usage" text, which would in turn confuse the plugin during parsing.
-- Fixed an issue with compiling aidl file when they import project
- local files.
-
-
-0.3.4 (adt 0.3.4, ddms 0.2.3, editors 0.1.0)
-
-Internal release only.
-- Enabled device support.
-
-0.3.3 (adt 0.3.3, ddms 0.2.3, editors 0.1.0)
-
-- Support for referenced projects.
-- During launch, display if a package conflict occurs when the new
- application is pushed onto the device.
-- You can now change the font of the logcat view. Also indentation is
- now properly displayed.
-- Plugin generated files are now properly marked as derived. This will
- make Team plugins ignore them.
-
-0.3.2
-
-- XML Highlighting for AndroidManifest.xml (requires WebTools WST plugin)
-- Custom java editor for R.java/Manifest.java to make those files non
- editable. This is to replace the current locking mechanism which
- causes issues on Mac OS.
-- Fixed some issue in the "Restart adb" feature in the device view of
- ddms.
-- Better handling of aidl files and the java files generated from
- them.
-- Plugin now retries to launch the app on the emulator if it fails due
- to timing issues.
-- Skin dropdown in the Emulator/Target tabs is now build from the
- content of the skin directory, to support developer made skins.
-- Emulator control panel. This is a UI on top of the emulator
- console. it allows you to change the state of the network and gsm
- connection, and to initiate incoming voice call.
-
-0.3.1
-
-- Fixed issue on winXP/Eclipse 3.2 where errors in the New Project
- Wizard would not display.
-- Added missing intent definition in the AndroidManifest.xml file
- created by the New Project Wizard.
-- Fixed possible NPE in the debug action from the Process View
-- Support for Eclipse 3.4
-
-0.2.6 / 0.3.0
-
-- New Project Wizard now makes it easy to open Android sample code
-- Plugin will output a warning if the build id of the device/emulator
- does not match the sdk build id.
-- Java/Debug/ddms perspective now contains direct menus to open some
- of the ddms views, and to create a new android project. This will
- require you to reset your perspectives.
-- Error during builds now put an error marker on the project instead
- of displaying an (annoying) dialog box.
-- Custom builders now remember their build state when restarting
- eclipse.
-- Properly parse some aapt warnings and don't abort the build when
- they happen.
-- Abort launch and prompt the user if the project contains errors.
-- New silent/normal/verbose build output.
-
-0.2.5
-
-- Check compiler compliance level before compilation and abort if
- different from 1.5
-- Fix Project Properties will fix the project compiler compliance if
- needed.
-- Fixed an issue with multiple source folders.
-- Added support for new Manifest.java class (it is automatically
- generated with R.java if the content of the AndroidManifest.xml
- requires it)
-- Fixed an issue that could result in not packaging code changes.
-- Automatic fix of the Launch Configurations when the java package in
- the manifest is changed. Also improved Launch Config dialog and
- error alert for erroneous activity names in the Launch
- Configuration.
-- Support for external jars that are not under the project root
- directory.
-- New projects have a default layout.
-- Misc fixes for Windows support.
-
-0.2.4
-
-- Fixed large resource corruption issue.
-
-0.2.3
-
-- Fixed issue related to the integration of dx.
-- Fixed issue related to the package generation that was modified for
- windows support.
-
-0.2.2
-
-- Changing the SDK location in the Preferences does not require to
- restart Eclipse anymore.
-- New SDK-Project sync mode in Android preference pane. Default value
- set to true. If true, all android projects are automatically sync'ed
- to the SDK defined in the preferences.
-- Cases where no emulator is running but a dialog still says "An
- emulator is running..." should be less frequent.
-- Projects do not reference the standard desktop JRE anymore, as
- android.zip contains the core java library. This will solve the case
- where using a core class non present on the platform would not
- generate a compilation error.
-- Changing the package defined in the manifest now deletes the R.java
- class from its previous location. This will require 1 build after
- upgrading the plugin, before it works.
-- Project selection in the Launch Config Dialog now only shows Android
- projects.
-- Launching a debug/run session now checks that the project uses the
- SDK set in the preferences (This is for the non automatic sync
- mode).
-- Removed obsolete wallpaper mode in the New Project Creation Wizard.
-- dx (dalvik code conversion tool) now embedded instead of calling the
- external version.
-- Improvements in the parsing of the aapt errors.
-- Some fixes for windows support.
-
-
-0.2.1
-
-- Fixed bug in logcat search where invalid regexp would cause a crash
-- Minor improvements to the build/launch process.
-
-0.2.0
-
-- Logcat view.
-- File Explorer view.
-- Custom options for emulator. In the Launch configuration dialog you
- can specify custom command line emulator options. See
- "emulator -help" for available options.
-- Android Tools > Export Application Package is now implemented.
-- Misc incremental builder fixes.
-- Including static .jar files as library in your project will
- automatically include them in the final APK. Warning: only the
- .class content is included.
-
-0.1.10
-
-- The res and assets folders now fully refresh before the build,
- ensuring R.java and packaged resources are always up to date. This
- can be disabled in the preferences under "Android" if this becomes
- slow due to too many files.
-
-0.1.9
-
-- New Action in the "Processes" view to debug an application that is
- already running. The source project for this application MUST be
- opened in the current workspace.
-- Building the project now force refreshes the res folder. This should
- help rebuilding the resources when only binary files were changed
- from outside eclipse.
-- Clean/full builds now compile all aidl files found in the build path
- (previously only incremental builds would compile them). Also, misc
- improvements to the incremental builders.
-- Starting a run/debug session now asks to save the files and forces a
- new build to ensure that the latest package is pushed on the device.
-- Plugin should be less aggressive when waiting for the emulator to be
- ready. This should translate in fewer failed launches.
-
-0.1.8
-
-- Fixed Debugger issue introduced in 0.1.6
-- Added Log level preferences for DDMS. Look under Android > DDMS >
- Advanced. Default error level is Error.
-
-0.1.7
-
-- Fixed issue where java warnings wouldn't trigger a new package. Now
- only errors stop the packaging like it should be.
-- Added more error output in the console during launch.
-
-0.1.6
-
-- New "Android" Console. It receives the error output from external
- tools such and aidl, dx, and aapt (only when they can't be
- parsed). Any error force the console to be displayed.
-- The Activity Manager on the device/emulator now outputs some
- messages in the "Android" console when asked to start an
- activity. This should help you figure out what is wrong if the
- application doesn't start.
-- Fixed a case where the .apk file would be updated with broken
- code. Now if there are java compile error, the .apk is not touched.
-- Added support for manifest with non fully qualified activity java
- name, yet not starting with a dot.
-- Fixed creation of manifest files (through New Project wizard) to use
- proper namespace for attributes.
-- Better error reporting for namespace issue in the manifest.
-- "Reset Adb" action from the device view. Use this is the plugin
- tells you an emulator is running when there are none.
-- New "ddms" Console which receives the standard output of ddms.
-
-0.1.5
-
-- Support for new activity declaration inside AndroidManifest.xml
-- fixed issue that prevented bin/ to be removed from the buildpath
- when converting project.
-
-0.1.4
-
-- Changes in the Manifest, now properly trigger a new package of the
- resources.
-
-0.1.3
-
-- Fixed the "fix project properties" action to remove old framework
- libraries, just not add new ones.
-
-0.1.2
-
-- aidl builder. The Android Resources PreBuilder now also converts
- aidl files into java files.
-- New Project wizard now allows to make Wallpaper activities instead
- of gadgets (which are obsolete.)
-- Launch shortcuts. Right click in the package explorer allow you to
- launch the application in debug or run mode directly without
- creating launch configurations.
-- New project wizard and Project conversion now sets up the java doc
- path for android.zip
-- Package builder now supports custom application assets placed in
- assets/ (which is now created automatically by the New Project
- Wizard).
-- New action: Android Tools > Fix Project Properties, in the package
- explorer contextual menu. This allows you to fix the framework path
- (and its javadoc path) in case you change the sdk location.
-
-0.1.1
-
-- Fixed project convertor to add the framework library if missing.
-
-0.1.0
-
-- New project wizard.
-- Python script-generated project convertor.
-- Incremental builders.
-- XML validation for resource files.
-- Android Launch Configuration.
diff --git a/eclipse/dictionary.txt b/eclipse/dictionary.txt
deleted file mode 100644
index 0dc00fd34..000000000
--- a/eclipse/dictionary.txt
+++ /dev/null
@@ -1,362 +0,0 @@
-&apos;
-aapt
-accessor
-accessors
-adb
-addon
-adt
-aidl
-alt
-android
-anim
-antialias
-antialiased
-apache
-api
-apk
-app
-apps
-arg
-async
-attr
-attrs
-avd
-avds
-backfill
-backport
-backported
-basename
-basenames
-bitmask
-breadcrumb
-builtin
-bytecode
-cairo
-callback
-callbacks
-carlo
-cf
-changeset
-charset
-checkbox
-checkboxes
-classloader
-classpath
-clickable
-clipart
-clipboard
-clipboards
-closeables
-clueless
-codebase
-codename
-codenames
-colspan
-combo
-combobox
-combos
-compositor
-config
-configs
-configurability
-congrats
-coords
-credentials
-cyclical
-dalvik
-ddms
-deactivated
-debuggable
-dedent
-defstyle
-deprecated
-deselect
-deselects
-designtime
-dev
-dex
-dexified
-diff
-diffs
-dir
-dirs
-discoverable
-displayable
-ditto
-div
-docs
-dp
-dpi
-drawable
-drawables
-dropdown
-ed
-editable
-em
-endian
-endpoint
-enum
-enums
-env
-equidistant
-exec
-fallback
-flux
-flyout
-foo
-foreach
-fqcn
-framelayout
-froyo
-gen
-gif
-git
-glob
-globbing
-groovy
-guava
-guillemets
-hardcode
-hardcoded
-hardcodes
-hdpi
-helvetica
-highlighter
-holo
-hotfix
-href
-html
-http
-hyperlink
-hyperlinks
-ids
-ie
-iff
-img
-infos
-init
-inits
-inline
-inlined
-inset
-instanceof
-instantiatable
-int
-inter
-interpolator
-interpolators
-iterable
-javac
-javadoc
-jpg
-keystore
-layoutlib
-ldpi
-leaky
-levenshtein
-lib
-lifecycle
-linebreaks
-linestyle
-linkable
-linux
-locale
-locales
-logo
-lombok
-lopsided
-lowercase
-luminance
-mac
-macs
-malformed
-markup
-marquee
-maven
-mdpi
-memento
-metadata
-micro
-min
-mipmap
-misaligned
-monospace
-monte
-ms
-msg
-multi
-multimap
-multimaps
-namespace
-namespaces
-newfound
-nexus
-ninepatch
-nodpi
-nulling
-num
-ok
-op
-os
-palette
-param
-params
-parented
-pings
-placeholder
-placeholders
-plugin
-plugins
-png
-popup
-popups
-pre
-precompiler
-precompute
-precomputing
-pref
-prefs
-preload
-preloaded
-preloads
-primordial
-printf
-pristine
-programmatic
-programmatically
-proguard
-propertysheet
-proxies
-proxy
-pulldown
-px
-quickfix
-recompilation
-rect
-redo
-refactor
-refactored
-refactoring
-refactorings
-regex
-regexp
-regexps
-registry
-reindent
-reindenting
-remap
-renderable
-reparse
-reparses
-rescales
-residual
-resilient
-resizability
-resizable
-rev
-risky
-rollback
-rowspan
-rowspans
-sandbox
-sans
-scrollable
-scrollbar
-scrollbars
-scrubbing
-sdcard
-sdk
-se
-searchable
-selectable
-semi
-serializer
-settable
-snip
-spec
-src
-standalone
-stash
-stat
-stateful
-stateless
-stderr
-stdout
-stretchable
-stretchiness
-struct
-styleable
-styleables
-stylesheet
-subclassed
-subclassing
-submenu
-submenus
-subregion
-superclasses
-supertype
-symlinks
-synced
-syncs
-synthetically
-tabbed
-tad
-temp
-templated
-textfield
-textfields
-thematically
-themed
-thumbnail
-thumbnails
-timestamp
-timestamps
-tmp
-toolbar
-toolbars
-tooltip
-tooltips
-traceview
-translucency
-trig
-txt
-typo
-ui
-uncomment
-undescribed
-undoable
-unfiltered
-unhide
-unicode
-uninstall
-uninstallation
-uninstalling
-unset
-unweighted
-upcoming
-uppercase
-uri
-url
-urls
-utf
-validator
-validators
-varargs
-verbosity
-viewport
-vs
-wakelock
-wakelocks
-wallpaper
-webtools
-whilst
-wildcard
-workflow
-xdpi
-xhdpi
-xlarge
-xml
-xmlns
-ydpi
-zip
-zipalign
diff --git a/eclipse/features/com.android.ide.eclipse.adt.package/.project b/eclipse/features/com.android.ide.eclipse.adt.package/.project
deleted file mode 100644
index 1024cf0de..000000000
--- a/eclipse/features/com.android.ide.eclipse.adt.package/.project
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>feature-adt-package</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.pde.FeatureBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.FeatureNature</nature>
- </natures>
-</projectDescription>
diff --git a/eclipse/features/com.android.ide.eclipse.adt.package/build.properties b/eclipse/features/com.android.ide.eclipse.adt.package/build.properties
deleted file mode 100644
index 64dc64a07..000000000
--- a/eclipse/features/com.android.ide.eclipse.adt.package/build.properties
+++ /dev/null
@@ -1,3 +0,0 @@
-bin.includes = feature.xml,\
- p2.inf
-includeLaunchers=false
diff --git a/eclipse/features/com.android.ide.eclipse.adt.package/feature.xml b/eclipse/features/com.android.ide.eclipse.adt.package/feature.xml
deleted file mode 100644
index 56eeaafe5..000000000
--- a/eclipse/features/com.android.ide.eclipse.adt.package/feature.xml
+++ /dev/null
@@ -1,45 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<feature
- id="com.android.ide.eclipse.adt.package.feature"
- label="ADT Package"
- version="24.3.3.qualifier"
- provider-name="The Android Open Source Project"
- plugin="com.android.ide.eclipse.adt.package">
-
- <description url="http://developer.android.com">
- Android Developer Tools
- </description>
-
- <copyright>
- Copyright (C) 2007-2014 The Android Open Source Project
- </copyright>
-
- <license url="http://www.eclipse.org/org/documents/epl-v10.php">
- Note: kxml2-2.3.0.jar is under the BSD license rather ...
- </license>
-
- <requires>
- <import plugin="com.android.ide.eclipse.adt" version="22.3.0" match="greaterOrEqual"/>
- <import plugin="com.android.ide.eclipse.base" version="22.3.0" match="greaterOrEqual"/>
- <import plugin="com.android.ide.eclipse.ddms" version="22.3.0" match="greaterOrEqual"/>
- <import plugin="com.android.ide.eclipse.gldebugger" version="22.3.0" match="greaterOrEqual"/>
- <import plugin="com.android.ide.eclipse.hierarchyviewer" version="22.3.0" match="greaterOrEqual"/>
- <import plugin="com.android.ide.eclipse.traceview" version="22.3.0" match="greaterOrEqual"/>
- <import plugin="com.android.ide.eclipse.ndk" version="22.3.0" match="greaterOrEqual"/>
- <import plugin="overlay.com.android.ide.eclipse.adt.overlay"/>
- <import feature="org.eclipse.equinox.p2.user.ui"/>
- <import feature="org.eclipse.platform"/>
- <import feature="org.eclipse.rcp"/>
- <import feature="org.eclipse.egit"/>
- <import feature="org.eclipse.egit.import"/>
- <import feature="org.eclipse.cdt"/>
- <import feature="org.eclipse.jdt"/>
- </requires>
-
- <plugin
- id="com.android.ide.eclipse.adt.package"
- download-size="0"
- install-size="0"
- version="0.0.0"/>
-
-</feature>
diff --git a/eclipse/features/com.android.ide.eclipse.adt.package/p2.inf b/eclipse/features/com.android.ide.eclipse.adt.package/p2.inf
deleted file mode 100644
index 93a365c6f..000000000
--- a/eclipse/features/com.android.ide.eclipse.adt.package/p2.inf
+++ /dev/null
@@ -1,9 +0,0 @@
-#tell pde.build not to generate start levels
-org.eclipse.pde.build.append.startlevels=false
-
-requires.1.namespace=org.eclipse.equinox.p2.iu
-requires.1.name=org.eclipse.platform.ide
-requires.1.greedy=true
-
-instructions.configure=\
-org.eclipse.equinox.p2.touchpoint.eclipse.addRepository(location:https${#58}//dl.google.com/android/eclipse/,type:0,name:Android Developer Tools Update Site,enabled:true);
diff --git a/eclipse/features/com.android.ide.eclipse.adt.package/pom.xml b/eclipse/features/com.android.ide.eclipse.adt.package/pom.xml
deleted file mode 100644
index 2ed50490c..000000000
--- a/eclipse/features/com.android.ide.eclipse.adt.package/pom.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <version>24.3.3-SNAPSHOT</version>
- <artifactId>com.android.ide.eclipse.adt.package.feature</artifactId>
- <packaging>eclipse-feature</packaging>
- <name>adt.package</name>
-
- <parent>
- <relativePath>../../pom.xml</relativePath>
- <groupId>adt.group</groupId>
- <artifactId>parent</artifactId>
- <version>1.0.0-SNAPSHOT</version>
- </parent>
-</project>
diff --git a/eclipse/features/com.android.ide.eclipse.adt/.project b/eclipse/features/com.android.ide.eclipse.adt/.project
deleted file mode 100644
index 513b14bfc..000000000
--- a/eclipse/features/com.android.ide.eclipse.adt/.project
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>feature-adt</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.pde.FeatureBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.FeatureNature</nature>
- </natures>
-</projectDescription>
diff --git a/eclipse/features/com.android.ide.eclipse.adt/build.properties b/eclipse/features/com.android.ide.eclipse.adt/build.properties
deleted file mode 100644
index 64f93a9f0..000000000
--- a/eclipse/features/com.android.ide.eclipse.adt/build.properties
+++ /dev/null
@@ -1 +0,0 @@
-bin.includes = feature.xml
diff --git a/eclipse/features/com.android.ide.eclipse.adt/feature.xml b/eclipse/features/com.android.ide.eclipse.adt/feature.xml
deleted file mode 100644
index 61bfbb0b8..000000000
--- a/eclipse/features/com.android.ide.eclipse.adt/feature.xml
+++ /dev/null
@@ -1,161 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<feature
- id="com.android.ide.eclipse.adt.feature"
- label="Android Development Tools"
- version="24.3.3.qualifier"
- provider-name="The Android Open Source Project"
- plugin="com.android.ide.eclipse.adt">
-
- <description>
- Android Developer Tools.
- </description>
-
- <copyright>
- Copyright (C) 2007-2011 The Android Open Source Project
- </copyright>
-
- <license url="http://www.eclipse.org/org/documents/epl-v10.php">
- Note: kxml2-2.3.0.jar is under the BSD license rather than the EPL. You can find a copy of the BSD License at http://www.opensource.org/licenses/bsd-license.php
-
- Eclipse Public License - v 1.0
-
-THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE (&quot;AGREEMENT&quot;). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT&apos;S ACCEPTANCE OF THIS AGREEMENT.
-
-1. DEFINITIONS
-
-&quot;Contribution&quot; means:
-
-a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and
-
-b) in the case of each subsequent Contributor:
-
-i) changes to the Program, and
-
-ii) additions to the Program;
-
-where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution &apos;originates&apos; from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor&apos;s behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program.
-
-&quot;Contributor&quot; means any person or entity that distributes the Program.
-
-&quot;Licensed Patents&quot; mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program.
-
-&quot;Program&quot; means the Contributions distributed in accordance with this Agreement.
-
-&quot;Recipient&quot; means anyone who receives the Program under this Agreement, including all Contributors.
-
-2. GRANT OF RIGHTS
-
-a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form.
-
-b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.
-
-c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient&apos;s responsibility to acquire that license before distributing the Program.
-
-d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement.
-
-3. REQUIREMENTS
-
-A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that:
-
-a) it complies with the terms and conditions of this Agreement; and
-
-b) its license agreement:
-
-i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;
-
-ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits;
-
-iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and
-
-iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange.
-
-When the Program is made available in source code form:
-
-a) it must be made available under this Agreement; and
-
-b) a copy of this Agreement must be included with each copy of the Program.
-
-Contributors may not remove or alter any copyright notices contained within the Program.
-
-Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution.
-
-4. COMMERCIAL DISTRIBUTION
-
-Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor (&quot;Commercial Contributor&quot;) hereby agrees to defend and indemnify every other Contributor (&quot;Indemnified Contributor&quot;) against any losses, damages and costs (collectively &quot;Losses&quot;) arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense.
-
-For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor&apos;s responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages.
-
-5. NO WARRANTY
-
-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN &quot;AS IS&quot; BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.
-
-6. DISCLAIMER OF LIABILITY
-
-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-
-7. GENERAL
-
-If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
-
-If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient&apos;s patent(s), then such Recipient&apos;s rights granted under Section 2(b) shall terminate as of the date such litigation is filed.
-
-All Recipient&apos;s rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient&apos;s rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient&apos;s obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.
-
-Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved.
-
-This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation.
- </license>
-
- <url>
- <update label="Android Update Site" url="https://dl-ssl.google.com/android/eclipse/"/>
- </url>
-
- <requires>
- <import plugin="com.android.ide.eclipse.base" match="perfect"/>
- <import plugin="com.android.ide.eclipse.ddms" match="perfect"/>
- <import plugin="org.eclipse.core.runtime" version="3.7.0" match="greaterOrEqual"/>
- <import plugin="org.eclipse.core.resources"/>
- <import plugin="org.eclipse.debug.core"/>
- <import plugin="org.eclipse.debug.ui"/>
- <import plugin="org.eclipse.jdt"/>
- <import plugin="org.eclipse.ant.core"/>
- <import plugin="org.eclipse.jdt.core"/>
- <import plugin="org.eclipse.jdt.ui"/>
- <import plugin="org.eclipse.jdt.launching"/>
- <import plugin="org.eclipse.jface.text"/>
- <import plugin="org.eclipse.ui.editors"/>
- <import plugin="org.eclipse.ui.workbench.texteditor"/>
- <import plugin="org.eclipse.ui.console"/>
- <import plugin="org.eclipse.core.filesystem"/>
- <import plugin="org.eclipse.ui" version="3.7" match="greaterOrEqual"/>
- <import plugin="org.eclipse.ui.ide"/>
- <import plugin="org.eclipse.ui.forms"/>
- <import plugin="org.eclipse.ui.browser"/>
- <import plugin="org.eclipse.ui.views"/>
- <import plugin="org.eclipse.wst.sse.core"/>
- <import plugin="org.eclipse.wst.sse.ui"/>
- <import plugin="org.eclipse.wst.xml.core"/>
- <import plugin="org.eclipse.wst.xml.ui"/>
- <import plugin="org.eclipse.jdt.junit"/>
- <import plugin="org.eclipse.jdt.junit.runtime"/>
- <import plugin="org.eclipse.ltk.core.refactoring"/>
- <import plugin="org.eclipse.ltk.ui.refactoring"/>
- <import plugin="org.eclipse.core.expressions"/>
- <import plugin="org.eclipse.compare"/>
- </requires>
-
- <plugin
- id="com.android.ide.eclipse.adt"
- download-size="0"
- install-size="0"
- version="0.0.0"
- unpack="false"/>
-
- <plugin
- id="overlay.com.android.ide.eclipse.adt.overlay"
- download-size="0"
- install-size="0"
- version="0.0.0"
- unpack="false"/>
-
-</feature>
diff --git a/eclipse/features/com.android.ide.eclipse.adt/pom.xml b/eclipse/features/com.android.ide.eclipse.adt/pom.xml
deleted file mode 100644
index 30e504da6..000000000
--- a/eclipse/features/com.android.ide.eclipse.adt/pom.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <version>24.3.3-SNAPSHOT</version>
- <artifactId>com.android.ide.eclipse.adt.feature</artifactId>
- <packaging>eclipse-feature</packaging>
- <name>adt</name>
-
- <parent>
- <relativePath>../../pom.xml</relativePath>
- <groupId>adt.group</groupId>
- <artifactId>parent</artifactId>
- <version>1.0.0-SNAPSHOT</version>
- </parent>
-</project>
diff --git a/eclipse/features/com.android.ide.eclipse.ddms/.project b/eclipse/features/com.android.ide.eclipse.ddms/.project
deleted file mode 100644
index 3a7481901..000000000
--- a/eclipse/features/com.android.ide.eclipse.ddms/.project
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>feature-ddms</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.pde.FeatureBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.FeatureNature</nature>
- </natures>
-</projectDescription>
diff --git a/eclipse/features/com.android.ide.eclipse.ddms/build.properties b/eclipse/features/com.android.ide.eclipse.ddms/build.properties
deleted file mode 100644
index 64f93a9f0..000000000
--- a/eclipse/features/com.android.ide.eclipse.ddms/build.properties
+++ /dev/null
@@ -1 +0,0 @@
-bin.includes = feature.xml
diff --git a/eclipse/features/com.android.ide.eclipse.ddms/feature.xml b/eclipse/features/com.android.ide.eclipse.ddms/feature.xml
deleted file mode 100644
index 812a9f299..000000000
--- a/eclipse/features/com.android.ide.eclipse.ddms/feature.xml
+++ /dev/null
@@ -1,253 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<feature
- id="com.android.ide.eclipse.ddms.feature"
- label="Android DDMS"
- version="24.3.3.qualifier"
- provider-name="The Android Open Source Project"
- plugin="com.android.ide.eclipse.ddms">
-
- <description>
- Android Dalvik Debug Monitor Service
- </description>
-
- <copyright>
- Copyright (C) 2007-2011 The Android Open Source Project
- </copyright>
-
- <license url="http://www.apache.org/licenses/LICENSE-2.0">
- Note: jcommon-1.0.12.jar is under the BSD license rather than the APL. You can find a copy of the BSD License at http://www.opensource.org/licenses/bsd-license.php
-
- jfreechart-1.0.9.jar and jfreechart-1.0.9-swt.jar are under the LGPL rather than the APL. You can find a copy of the LGPL at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt. You can get the source code for these two components at http://android.git.kernel.org/pub/jfreechart-1.0.9.zip
-
-
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- &quot;License&quot; shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- &quot;Licensor&quot; shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- &quot;Legal Entity&quot; shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- &quot;control&quot; means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- &quot;You&quot; (or &quot;Your&quot;) shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- &quot;Source&quot; form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- &quot;Object&quot; form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- &quot;Work&quot; shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- &quot;Derivative Works&quot; shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- &quot;Contribution&quot; shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, &quot;submitted&quot;
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as &quot;Not a Contribution.&quot;
-
- &quot;Contributor&quot; shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a &quot;NOTICE&quot; text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an &quot;AS IS&quot; BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets &quot;[]&quot;
- replaced with your own identifying information. (Don&apos;t include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same &quot;printed page&quot; as the copyright notice for easier
- identification within third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- </license>
-
- <url>
- <update label="Android Update Site" url="https://dl-ssl.google.com/android/eclipse/"/>
- </url>
-
- <requires>
- <import plugin="org.eclipse.ui" version="3.7.0" match="greaterOrEqual"/>
- <import plugin="org.eclipse.core.runtime" version="3.7.0" match="greaterOrEqual"/>
- <import plugin="org.eclipse.ui.console"/>
- <import plugin="org.eclipse.core.resources"/>
- <import plugin="org.eclipse.ui.ide"/>
- <import plugin="org.eclipse.core.filesystem"/>
- </requires>
-
- <plugin
- id="com.android.ide.eclipse.base"
- download-size="0"
- install-size="0"
- version="0.0.0"
- unpack="false"/>
-
- <plugin
- id="com.android.ide.eclipse.ddms"
- download-size="0"
- install-size="0"
- version="0.0.0"
- unpack="false"/>
-
-</feature>
diff --git a/eclipse/features/com.android.ide.eclipse.ddms/pom.xml b/eclipse/features/com.android.ide.eclipse.ddms/pom.xml
deleted file mode 100644
index fc9680d60..000000000
--- a/eclipse/features/com.android.ide.eclipse.ddms/pom.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <version>24.3.3-SNAPSHOT</version>
- <artifactId>com.android.ide.eclipse.ddms.feature</artifactId>
- <packaging>eclipse-feature</packaging>
- <name>ddms</name>
-
- <parent>
- <relativePath>../../pom.xml</relativePath>
- <groupId>adt.group</groupId>
- <artifactId>parent</artifactId>
- <version>1.0.0-SNAPSHOT</version>
- </parent>
-</project>
diff --git a/eclipse/features/com.android.ide.eclipse.gldebugger/.project b/eclipse/features/com.android.ide.eclipse.gldebugger/.project
deleted file mode 100644
index 067a8f413..000000000
--- a/eclipse/features/com.android.ide.eclipse.gldebugger/.project
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>feature-gldebugger</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.pde.FeatureBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.FeatureNature</nature>
- </natures>
-</projectDescription>
diff --git a/eclipse/features/com.android.ide.eclipse.gldebugger/build.properties b/eclipse/features/com.android.ide.eclipse.gldebugger/build.properties
deleted file mode 100644
index 64f93a9f0..000000000
--- a/eclipse/features/com.android.ide.eclipse.gldebugger/build.properties
+++ /dev/null
@@ -1 +0,0 @@
-bin.includes = feature.xml
diff --git a/eclipse/features/com.android.ide.eclipse.gldebugger/feature.xml b/eclipse/features/com.android.ide.eclipse.gldebugger/feature.xml
deleted file mode 100644
index 2259187cd..000000000
--- a/eclipse/features/com.android.ide.eclipse.gldebugger/feature.xml
+++ /dev/null
@@ -1,232 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<feature
- id="com.android.ide.eclipse.gldebugger.feature"
- label="Tracer for OpenGL ES"
- version="24.3.3.qualifier"
- provider-name="The Android Open Source Project">
-
- <description>
- GLESv2 Debugger Client (Alpha status).
- </description>
-
- <copyright>
- Copyright (C) 2011 The Android Open Source Project
- </copyright>
-
- <license url="http://www.apache.org/licenses/LICENSE-2.0">
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- &quot;License&quot; shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- &quot;Licensor&quot; shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- &quot;Legal Entity&quot; shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- &quot;control&quot; means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- &quot;You&quot; (or &quot;Your&quot;) shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- &quot;Source&quot; form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- &quot;Object&quot; form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- &quot;Work&quot; shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- &quot;Derivative Works&quot; shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- &quot;Contribution&quot; shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, &quot;submitted&quot;
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as &quot;Not a Contribution.&quot;
-
- &quot;Contributor&quot; shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a &quot;NOTICE&quot; text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an &quot;AS IS&quot; BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets &quot;[]&quot;
- replaced with your own identifying information. (Don&apos;t include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same &quot;printed page&quot; as the copyright notice for easier
- identification within third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- </license>
-
- <requires>
- <import plugin="org.eclipse.ui"/>
- <import plugin="org.eclipse.core.runtime"/>
- </requires>
-
- <plugin
- id="com.android.ide.eclipse.gldebugger"
- download-size="0"
- install-size="0"
- version="0.0.0"
- unpack="false"/>
-
-</feature>
diff --git a/eclipse/features/com.android.ide.eclipse.gldebugger/pom.xml b/eclipse/features/com.android.ide.eclipse.gldebugger/pom.xml
deleted file mode 100644
index 65f086ff5..000000000
--- a/eclipse/features/com.android.ide.eclipse.gldebugger/pom.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <version>24.3.3-SNAPSHOT</version>
- <artifactId>com.android.ide.eclipse.gldebugger.feature</artifactId>
- <packaging>eclipse-feature</packaging>
- <name>gldebugger</name>
-
- <parent>
- <relativePath>../../pom.xml</relativePath>
- <groupId>adt.group</groupId>
- <artifactId>parent</artifactId>
- <version>1.0.0-SNAPSHOT</version>
- </parent>
-</project>
diff --git a/eclipse/features/com.android.ide.eclipse.hierarchyviewer/.project b/eclipse/features/com.android.ide.eclipse.hierarchyviewer/.project
deleted file mode 100644
index 0c7a096c1..000000000
--- a/eclipse/features/com.android.ide.eclipse.hierarchyviewer/.project
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>feature-hierarchyviewer</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.pde.FeatureBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.FeatureNature</nature>
- </natures>
-</projectDescription>
diff --git a/eclipse/features/com.android.ide.eclipse.hierarchyviewer/build.properties b/eclipse/features/com.android.ide.eclipse.hierarchyviewer/build.properties
deleted file mode 100644
index 64f93a9f0..000000000
--- a/eclipse/features/com.android.ide.eclipse.hierarchyviewer/build.properties
+++ /dev/null
@@ -1 +0,0 @@
-bin.includes = feature.xml
diff --git a/eclipse/features/com.android.ide.eclipse.hierarchyviewer/feature.xml b/eclipse/features/com.android.ide.eclipse.hierarchyviewer/feature.xml
deleted file mode 100644
index b9b3596d2..000000000
--- a/eclipse/features/com.android.ide.eclipse.hierarchyviewer/feature.xml
+++ /dev/null
@@ -1,239 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<feature
- id="com.android.ide.eclipse.hierarchyviewer.feature"
- label="Android Hierarchy Viewer"
- version="24.3.3.qualifier"
- provider-name="The Android Open Source Project"
- plugin="com.android.ide.eclipse.hierarchyviewer">
-
- <description>
- Android Hierarchy Viewer.
- </description>
-
- <copyright>
- Copyright (C) 2010-2011 The Android Open Source Project
- </copyright>
-
- <license url="http://www.apache.org/licenses/LICENSE-2.0.txt">
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- &quot;License&quot; shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- &quot;Licensor&quot; shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- &quot;Legal Entity&quot; shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- &quot;control&quot; means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- &quot;You&quot; (or &quot;Your&quot;) shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- &quot;Source&quot; form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- &quot;Object&quot; form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- &quot;Work&quot; shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- &quot;Derivative Works&quot; shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- &quot;Contribution&quot; shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, &quot;submitted&quot;
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as &quot;Not a Contribution.&quot;
-
- &quot;Contributor&quot; shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a &quot;NOTICE&quot; text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an &quot;AS IS&quot; BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets &quot;[]&quot;
- replaced with your own identifying information. (Don&apos;t include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same &quot;printed page&quot; as the copyright notice for easier
- identification within third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- </license>
-
- <url>
- <update label="Android Update Site" url="https://dl-ssl.google.com/android/eclipse/"/>
- </url>
-
- <requires>
- <import plugin="org.eclipse.ui" version="3.7.0" match="greaterOrEqual"/>
- <import plugin="org.eclipse.core.runtime" version="3.7.0" match="greaterOrEqual"/>
- <import plugin="org.eclipse.ui.console"/>
- <import plugin="com.android.ide.eclipse.ddms" match="perfect"/>
- </requires>
-
- <plugin
- id="com.android.ide.eclipse.hierarchyviewer"
- download-size="0"
- install-size="0"
- version="0.0.0"
- unpack="false"/>
-
-</feature>
diff --git a/eclipse/features/com.android.ide.eclipse.hierarchyviewer/pom.xml b/eclipse/features/com.android.ide.eclipse.hierarchyviewer/pom.xml
deleted file mode 100644
index 119476a16..000000000
--- a/eclipse/features/com.android.ide.eclipse.hierarchyviewer/pom.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <version>24.3.3-SNAPSHOT</version>
- <artifactId>com.android.ide.eclipse.hierarchyviewer.feature</artifactId>
- <packaging>eclipse-feature</packaging>
- <name>hierarchyviewer</name>
-
- <parent>
- <relativePath>../../pom.xml</relativePath>
- <groupId>adt.group</groupId>
- <artifactId>parent</artifactId>
- <version>1.0.0-SNAPSHOT</version>
- </parent>
-</project>
diff --git a/eclipse/features/com.android.ide.eclipse.monitor/.project b/eclipse/features/com.android.ide.eclipse.monitor/.project
deleted file mode 100644
index 347f1dcb7..000000000
--- a/eclipse/features/com.android.ide.eclipse.monitor/.project
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>feature-monitor</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.pde.FeatureBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.FeatureNature</nature>
- </natures>
-</projectDescription>
diff --git a/eclipse/features/com.android.ide.eclipse.monitor/build.properties b/eclipse/features/com.android.ide.eclipse.monitor/build.properties
deleted file mode 100644
index 64f93a9f0..000000000
--- a/eclipse/features/com.android.ide.eclipse.monitor/build.properties
+++ /dev/null
@@ -1 +0,0 @@
-bin.includes = feature.xml
diff --git a/eclipse/features/com.android.ide.eclipse.monitor/feature.xml b/eclipse/features/com.android.ide.eclipse.monitor/feature.xml
deleted file mode 100644
index 57209089e..000000000
--- a/eclipse/features/com.android.ide.eclipse.monitor/feature.xml
+++ /dev/null
@@ -1,233 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<feature
- id="com.android.ide.eclipse.monitor.feature"
- label="Android Monitor"
- version="24.3.3.qualifier"
- provider-name="The Android Open Source Project"
- plugin="com.android.ide.eclipse.monitor">
-
- <description>
- Android Debug Monitor
- </description>
-
- <copyright>
- Copyright (C) 2007-2014 The Android Open Source Project
- </copyright>
-
- <license url="http://www.apache.org/licenses/LICENSE-2.0">
- Note: jcommon-1.0.12.jar is under the BSD license rather than the APL. You can find a copy of the BSD License at http://www.opensource.org/licenses/bsd-license.php
-
- jfreechart-1.0.9.jar and jfreechart-1.0.9-swt.jar are under the LGPL rather than the APL. You can find a copy of the LGPL at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt. You can get the source code for these two components at http://android.git.kernel.org/pub/jfreechart-1.0.9.zip
-
-
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- &quot;License&quot; shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- &quot;Licensor&quot; shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- &quot;Legal Entity&quot; shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- &quot;control&quot; means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- &quot;You&quot; (or &quot;Your&quot;) shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- &quot;Source&quot; form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- &quot;Object&quot; form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- &quot;Work&quot; shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- &quot;Derivative Works&quot; shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- &quot;Contribution&quot; shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, &quot;submitted&quot;
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as &quot;Not a Contribution.&quot;
-
- &quot;Contributor&quot; shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a &quot;NOTICE&quot; text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an &quot;AS IS&quot; BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets &quot;[]&quot;
- replaced with your own identifying information. (Don&apos;t include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same &quot;printed page&quot; as the copyright notice for easier
- identification within third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- </license>
-
- <plugin
- id="com.android.ide.eclipse.monitor"
- download-size="0"
- install-size="0"
- version="0.0.0"
- unpack="false"/>
-
-</feature>
diff --git a/eclipse/features/com.android.ide.eclipse.monitor/pom.xml b/eclipse/features/com.android.ide.eclipse.monitor/pom.xml
deleted file mode 100644
index a59a05f08..000000000
--- a/eclipse/features/com.android.ide.eclipse.monitor/pom.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <version>24.3.3-SNAPSHOT</version>
- <artifactId>com.android.ide.eclipse.monitor.feature</artifactId>
- <packaging>eclipse-feature</packaging>
- <name>monitor</name>
-
- <parent>
- <relativePath>../../pom.xml</relativePath>
- <groupId>adt.group</groupId>
- <artifactId>parent</artifactId>
- <version>1.0.0-SNAPSHOT</version>
- </parent>
-</project>
diff --git a/eclipse/features/com.android.ide.eclipse.ndk/.project b/eclipse/features/com.android.ide.eclipse.ndk/.project
deleted file mode 100644
index 42d189157..000000000
--- a/eclipse/features/com.android.ide.eclipse.ndk/.project
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>feature-ndk</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.pde.FeatureBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.FeatureNature</nature>
- </natures>
-</projectDescription>
diff --git a/eclipse/features/com.android.ide.eclipse.ndk/build.properties b/eclipse/features/com.android.ide.eclipse.ndk/build.properties
deleted file mode 100644
index 64f93a9f0..000000000
--- a/eclipse/features/com.android.ide.eclipse.ndk/build.properties
+++ /dev/null
@@ -1 +0,0 @@
-bin.includes = feature.xml
diff --git a/eclipse/features/com.android.ide.eclipse.ndk/feature.xml b/eclipse/features/com.android.ide.eclipse.ndk/feature.xml
deleted file mode 100644
index 8a8407e15..000000000
--- a/eclipse/features/com.android.ide.eclipse.ndk/feature.xml
+++ /dev/null
@@ -1,117 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<feature
- id="com.android.ide.eclipse.ndk.feature"
- label="Android Native Development Tools"
- version="24.3.3.qualifier"
- provider-name="The Android Open Source Project">
-
- <description>
- Android Native Developer Tools.
- </description>
-
- <license url="http://www.eclipse.org/org/documents/epl-v10.php">
- Eclipse Public License - v 1.0
-
-THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE (&quot;AGREEMENT&quot;). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT&apos;S ACCEPTANCE OF THIS AGREEMENT.
-
-1. DEFINITIONS
-
-&quot;Contribution&quot; means:
-
-a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and
-
-b) in the case of each subsequent Contributor:
-
-i) changes to the Program, and
-
-ii) additions to the Program;
-
-where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution &apos;originates&apos; from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor&apos;s behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program.
-
-&quot;Contributor&quot; means any person or entity that distributes the Program.
-
-&quot;Licensed Patents&quot; mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program.
-
-&quot;Program&quot; means the Contributions distributed in accordance with this Agreement.
-
-&quot;Recipient&quot; means anyone who receives the Program under this Agreement, including all Contributors.
-
-2. GRANT OF RIGHTS
-
-a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form.
-
-b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.
-
-c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient&apos;s responsibility to acquire that license before distributing the Program.
-
-d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement.
-
-3. REQUIREMENTS
-
-A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that:
-
-a) it complies with the terms and conditions of this Agreement; and
-
-b) its license agreement:
-
-i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;
-
-ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits;
-
-iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and
-
-iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange.
-
-When the Program is made available in source code form:
-
-a) it must be made available under this Agreement; and
-
-b) a copy of this Agreement must be included with each copy of the Program.
-
-Contributors may not remove or alter any copyright notices contained within the Program.
-
-Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution.
-
-4. COMMERCIAL DISTRIBUTION
-
-Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor (&quot;Commercial Contributor&quot;) hereby agrees to defend and indemnify every other Contributor (&quot;Indemnified Contributor&quot;) against any losses, damages and costs (collectively &quot;Losses&quot;) arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense.
-
-For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor&apos;s responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages.
-
-5. NO WARRANTY
-
-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN &quot;AS IS&quot; BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.
-
-6. DISCLAIMER OF LIABILITY
-
-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-
-7. GENERAL
-
-If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
-
-If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient&apos;s patent(s), then such Recipient&apos;s rights granted under Section 2(b) shall terminate as of the date such litigation is filed.
-
-All Recipient&apos;s rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient&apos;s rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient&apos;s obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.
-
-Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved.
-
-This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation.
- </license>
-
- <url>
- <update label="Android Update Site" url="https://dl-ssl.google.com/android/eclipse/"/>
- </url>
-
- <requires>
- <import feature="org.eclipse.cdt"/>
- </requires>
-
- <plugin
- id="com.android.ide.eclipse.ndk"
- download-size="0"
- install-size="0"
- version="0.0.0"
- unpack="false"/>
-
-</feature>
diff --git a/eclipse/features/com.android.ide.eclipse.ndk/pom.xml b/eclipse/features/com.android.ide.eclipse.ndk/pom.xml
deleted file mode 100644
index 87da6f32d..000000000
--- a/eclipse/features/com.android.ide.eclipse.ndk/pom.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <version>24.3.3-SNAPSHOT</version>
- <artifactId>com.android.ide.eclipse.ndk.feature</artifactId>
- <packaging>eclipse-feature</packaging>
- <name>ndk</name>
-
- <parent>
- <relativePath>../../pom.xml</relativePath>
- <groupId>adt.group</groupId>
- <artifactId>parent</artifactId>
- <version>1.0.0-SNAPSHOT</version>
- </parent>
-</project>
diff --git a/eclipse/features/com.android.ide.eclipse.pdt/.project b/eclipse/features/com.android.ide.eclipse.pdt/.project
deleted file mode 100644
index 8aa2663d9..000000000
--- a/eclipse/features/com.android.ide.eclipse.pdt/.project
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>feature-pdt</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.pde.FeatureBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.FeatureNature</nature>
- </natures>
-</projectDescription>
diff --git a/eclipse/features/com.android.ide.eclipse.pdt/build.properties b/eclipse/features/com.android.ide.eclipse.pdt/build.properties
deleted file mode 100644
index 64f93a9f0..000000000
--- a/eclipse/features/com.android.ide.eclipse.pdt/build.properties
+++ /dev/null
@@ -1 +0,0 @@
-bin.includes = feature.xml
diff --git a/eclipse/features/com.android.ide.eclipse.pdt/feature.xml b/eclipse/features/com.android.ide.eclipse.pdt/feature.xml
deleted file mode 100644
index 446509ae6..000000000
--- a/eclipse/features/com.android.ide.eclipse.pdt/feature.xml
+++ /dev/null
@@ -1,245 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<feature
- id="com.android.ide.eclipse.pdt"
- label="Android Platform Development Tools"
- version="24.3.3.qualifier"
- provider-name="The Android Open Source Project">
-
- <description>
- Android Platform Developer Tools.
- </description>
-
- <copyright>
- Copyright (C) 2010-2011 The Android Open Source Project
- </copyright>
-
- <license url="http://www.apache.org/licenses/LICENSE-2.0.txt">
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- &quot;License&quot; shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- &quot;Licensor&quot; shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- &quot;Legal Entity&quot; shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- &quot;control&quot; means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- &quot;You&quot; (or &quot;Your&quot;) shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- &quot;Source&quot; form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- &quot;Object&quot; form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- &quot;Work&quot; shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- &quot;Derivative Works&quot; shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- &quot;Contribution&quot; shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, &quot;submitted&quot;
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as &quot;Not a Contribution.&quot;
-
- &quot;Contributor&quot; shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a &quot;NOTICE&quot; text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an &quot;AS IS&quot; BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets &quot;[]&quot;
- replaced with your own identifying information. (Don&apos;t include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same &quot;printed page&quot; as the copyright notice for easier
- identification within third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- </license>
-
- <url>
- <update label="Android Update Site" url="https://dl-ssl.google.com/android/eclipse/"/>
- </url>
-
- <requires>
- <import plugin="org.eclipse.ui"/>
- <import plugin="org.eclipse.core.runtime"/>
- <import plugin="com.android.ide.eclipse.ddms"/>
- <import plugin="org.eclipse.core.resources"/>
- <import plugin="org.eclipse.jdt.core"/>
- <import plugin="org.eclipse.jdt.ui"/>
- <import plugin="org.eclipse.jface.text"/>
- <import plugin="org.eclipse.ui.editors"/>
- <import plugin="org.eclipse.jdt.launching"/>
- <import plugin="org.eclipse.debug.core"/>
- <import plugin="org.eclipse.debug.ui"/>
- </requires>
-
- <plugin
- id="com.android.ide.eclipse.pdt"
- download-size="0"
- install-size="0"
- version="0.0.0"
- unpack="false"/>
-
-</feature>
diff --git a/eclipse/features/com.android.ide.eclipse.tests/.project b/eclipse/features/com.android.ide.eclipse.tests/.project
deleted file mode 100644
index e9a6867b4..000000000
--- a/eclipse/features/com.android.ide.eclipse.tests/.project
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>feature-tests</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.pde.FeatureBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.FeatureNature</nature>
- </natures>
-</projectDescription>
diff --git a/eclipse/features/com.android.ide.eclipse.tests/build.properties b/eclipse/features/com.android.ide.eclipse.tests/build.properties
deleted file mode 100644
index 64f93a9f0..000000000
--- a/eclipse/features/com.android.ide.eclipse.tests/build.properties
+++ /dev/null
@@ -1 +0,0 @@
-bin.includes = feature.xml
diff --git a/eclipse/features/com.android.ide.eclipse.tests/feature.xml b/eclipse/features/com.android.ide.eclipse.tests/feature.xml
deleted file mode 100644
index 965e3ec76..000000000
--- a/eclipse/features/com.android.ide.eclipse.tests/feature.xml
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<feature
- id="com.android.ide.eclipse.tests"
- label="ADT Tests"
- version="24.3.3.qualifier"
- provider-name="The Android Open Source Project">
-
- <copyright>
- Copyright (C) 2007-2011 The Android Open Source Project
- </copyright>
-
- <requires>
- <import plugin="org.junit"/>
- <import plugin="com.android.ide.eclipse.adt" version="10.0.0" match="greaterOrEqual"/>
- </requires>
-
- <plugin
- id="com.android.ide.eclipse.tests"
- download-size="0"
- install-size="0"
- version="0.0.0"
- unpack="false"/>
-
-</feature>
diff --git a/eclipse/features/com.android.ide.eclipse.traceview/.project b/eclipse/features/com.android.ide.eclipse.traceview/.project
deleted file mode 100644
index c6cf73c70..000000000
--- a/eclipse/features/com.android.ide.eclipse.traceview/.project
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>feature-traceview</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.pde.FeatureBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.FeatureNature</nature>
- </natures>
-</projectDescription>
diff --git a/eclipse/features/com.android.ide.eclipse.traceview/build.properties b/eclipse/features/com.android.ide.eclipse.traceview/build.properties
deleted file mode 100644
index 64f93a9f0..000000000
--- a/eclipse/features/com.android.ide.eclipse.traceview/build.properties
+++ /dev/null
@@ -1 +0,0 @@
-bin.includes = feature.xml
diff --git a/eclipse/features/com.android.ide.eclipse.traceview/feature.xml b/eclipse/features/com.android.ide.eclipse.traceview/feature.xml
deleted file mode 100644
index 43793a623..000000000
--- a/eclipse/features/com.android.ide.eclipse.traceview/feature.xml
+++ /dev/null
@@ -1,239 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<feature
- id="com.android.ide.eclipse.traceview.feature"
- label="Android Traceview"
- version="24.3.3.qualifier"
- provider-name="The Android Open Source Project"
- plugin="com.android.ide.eclipse.traceview">
-
- <description>
- Android Traceview
- </description>
-
- <copyright>
- Copyright (C) 2011 The Android Open Source Project
- </copyright>
-
- <license url="http://www.apache.org/licenses/LICENSE-2.0">
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- &quot;License&quot; shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- &quot;Licensor&quot; shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- &quot;Legal Entity&quot; shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- &quot;control&quot; means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- &quot;You&quot; (or &quot;Your&quot;) shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- &quot;Source&quot; form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- &quot;Object&quot; form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- &quot;Work&quot; shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- &quot;Derivative Works&quot; shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- &quot;Contribution&quot; shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, &quot;submitted&quot;
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as &quot;Not a Contribution.&quot;
-
- &quot;Contributor&quot; shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a &quot;NOTICE&quot; text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an &quot;AS IS&quot; BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets &quot;[]&quot;
- replaced with your own identifying information. (Don&apos;t include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same &quot;printed page&quot; as the copyright notice for easier
- identification within third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- </license>
-
- <url>
- <update label="Android Update Site" url="https://dl-ssl.google.com/android/eclipse/"/>
- </url>
-
- <requires>
- <import plugin="org.eclipse.core.runtime" version="3.7.0" match="greaterOrEqual"/>
- <import plugin="com.android.ide.eclipse.ddms" version="10.0.0" match="greaterOrEqual"/>
- <import plugin="org.eclipse.core.filesystem"/>
- <import plugin="org.eclipse.core.resources"/>
- </requires>
-
- <plugin
- id="com.android.ide.eclipse.traceview"
- download-size="0"
- install-size="0"
- version="0.0.0"
- unpack="false"/>
-
-</feature>
diff --git a/eclipse/features/com.android.ide.eclipse.traceview/pom.xml b/eclipse/features/com.android.ide.eclipse.traceview/pom.xml
deleted file mode 100644
index eea0f7fa4..000000000
--- a/eclipse/features/com.android.ide.eclipse.traceview/pom.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <version>24.3.3-SNAPSHOT</version>
- <artifactId>com.android.ide.eclipse.traceview.feature</artifactId>
- <packaging>eclipse-feature</packaging>
- <name>traceview</name>
-
- <parent>
- <relativePath>../../pom.xml</relativePath>
- <groupId>adt.group</groupId>
- <artifactId>parent</artifactId>
- <version>1.0.0-SNAPSHOT</version>
- </parent>
-</project>
diff --git a/eclipse/monitor/build.gradle b/eclipse/monitor/build.gradle
deleted file mode 100644
index da8adcf3e..000000000
--- a/eclipse/monitor/build.gradle
+++ /dev/null
@@ -1,111 +0,0 @@
-apply plugin: 'sdk-files'
-
-def basePath = "../../../out/host/maven/bundles-24.3.3-SNAPSHOT/products/"
-
-sdk {
- linux {
- item('monitor') {
- notice null
- executable true
- }
- item(basePath + 'lin64/monitor') {
- into 'lib/monitor-x86_64'
- notice null
- builtBy 'unzipLinux64'
- }
- item(basePath + 'lin/monitor') {
- into 'lib/monitor-x86'
- notice null
- builtBy 'unzipLinux'
- }
- }
-
- mac {
- item('monitor') {
- notice null
- executable true
- }
- item(basePath + 'mac64/monitor') {
- into 'lib/monitor-x86_64'
- notice null
- builtBy 'unzipMac64'
- }
- }
-
-
- windows {
- item('monitor.bat') {
- notice null
- executable true
- }
- item(basePath + 'win64/monitor') {
- into 'lib/monitor-x86_64'
- notice null
- builtBy 'unzipWin64'
- }
- item(basePath + 'win/monitor') {
- into 'lib/monitor-x86'
- notice null
- builtBy 'unzipWin'
- }
- }
-}
-
-// Using PDE build, the size of monitor was 43M
-// With Tycho, we are at close to 75M. Until we figure out the proper way
-// to exclude unnecessary content, we just remove these plugins from the final build.
-def pluginsToRemove = [
- 'org.eclipse.platform.doc.user_4.2.2.v20130121-200410.jar',
- 'org.eclipse.debug.ui_3.8.2.v20130130-171415.ja',
- 'org.apache.jasper.glassfish_2.2.2.v201205150955.jar',
- 'org.eclipse.team.ui_3.6.201.v20130125-135424.jar',
- 'org.apache.lucene.core_2.9.1.v201101211721.jar',
- 'org.eclipse.help.webapp_3.6.101.v20130116-182509.jar',
- 'org.eclipse.help.ui_3.5.201.v20130108-092756.jar',
- 'org.eclipse.help.base_3.6.101.v201302041200.jar',
- 'org.eclipse.team.core_3.6.100.v20120524-0627.jar',
- 'org.eclipse.jetty.server_8.1.3.v20120522.jar',
- 'org.eclipse.ui.intro_3.4.200.v20120521-2344.jar',
- 'org.eclipse.ui.cheatsheets_3.4.200.v20120521-2344.jar',
- 'org.apache.ant_1.8.3.v201301120609/**'
-]
-
-task unzipLinux64(type: Copy) {
- from zipTree(file(basePath + 'monitorproduct-linux.gtk.x86_64.zip'))
- into file(basePath + 'lin64/')
- pluginsToRemove.each {
- exclude "**/$it"
- }
-}
-
-task unzipLinux(type: Copy) {
- from zipTree(file(basePath + 'monitorproduct-linux.gtk.x86.zip'))
- into file(basePath + 'lin/')
- pluginsToRemove.each {
- exclude "**/$it"
- }
-}
-
-task unzipMac64(type: Copy) {
- from zipTree(file(basePath + 'monitorproduct-macosx.cocoa.x86_64.zip'))
- into file(basePath + 'mac64/')
- pluginsToRemove.each {
- exclude "**/$it"
- }
-}
-
-task unzipWin64(type: Copy) {
- from zipTree(file(basePath + 'monitorproduct-win32.win32.x86_64.zip'))
- into file(basePath + 'win64/')
- pluginsToRemove.each {
- exclude "**/$it"
- }
-}
-
-task unzipWin(type: Copy) {
- from zipTree(file(basePath + 'monitorproduct-win32.win32.x86.zip'))
- into file(basePath + 'win/')
- pluginsToRemove.each {
- exclude "**/$it"
- }
-}
diff --git a/eclipse/monitor/monitor b/eclipse/monitor/monitor
deleted file mode 100755
index 53a2bb512..000000000
--- a/eclipse/monitor/monitor
+++ /dev/null
@@ -1,44 +0,0 @@
-#!/bin/bash
-# Copyright 2012, The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-# Set up prog to be the path of this script, including following symlinks,
-# and set up progdir to be the fully-qualified pathname of its directory.
-prog="$0"
-while [ -h "${prog}" ]; do
- newProg=`/bin/ls -ld "${prog}"`
- newProg=`expr "${newProg}" : ".* -> \(.*\)$"`
- if expr "x${newProg}" : 'x/' >/dev/null; then
- prog="${newProg}"
- else
- progdir=`dirname "${prog}"`
- prog="${progdir}/${newProg}"
- fi
-done
-oldwd=`pwd`
-progdir=`dirname "${prog}"`
-cd "${progdir}"
-
-javaCmd="java"
-
-vmarch=`${javaCmd} -jar lib/archquery.jar`
-
-app=lib/monitor-${vmarch}/monitor
-if [[ "Darwin" == `uname` ]]; then
- app=${app}.app/Contents/MacOS/monitor
-fi
-
-
-exec $app
-
diff --git a/eclipse/monitor/monitor.bat b/eclipse/monitor/monitor.bat
deleted file mode 100755
index aab18ae93..000000000
--- a/eclipse/monitor/monitor.bat
+++ /dev/null
@@ -1,32 +0,0 @@
-@echo off
-rem Copyright (C) 2012 The Android Open Source Project
-rem
-rem Licensed under the Apache License, Version 2.0 (the "License");
-rem you may not use this file except in compliance with the License.
-rem You may obtain a copy of the License at
-rem
-rem http://www.apache.org/licenses/LICENSE-2.0
-rem
-rem Unless required by applicable law or agreed to in writing, software
-rem distributed under the License is distributed on an "AS IS" BASIS,
-rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-rem See the License for the specific language governing permissions and
-rem limitations under the License.
-
-rem don't modify the caller's environment
-setlocal
-
-rem Change current directory and drive to where the script is, to avoid
-rem issues with directories containing whitespaces.
-cd /d %~dp0
-
-rem Check we have a valid Java.exe in the path.
-set java_exe=
-call lib\find_java.bat
-if not defined java_exe goto :EOF
-
-:QueryArch
-for /f "delims=" %%a in ('"%java_exe%" -jar lib\archquery.jar') do set vmarch=%%a
-
-start lib\monitor-%vmarch%\monitor
-
diff --git a/eclipse/plugins/.gitignore b/eclipse/plugins/.gitignore
deleted file mode 100644
index 76afe3e46..000000000
--- a/eclipse/plugins/.gitignore
+++ /dev/null
@@ -1,7 +0,0 @@
-*/bin
-
-com.android.ide.eclipse.tests/unittests/com/android/ddmlib
-com.android.ide.eclipse.tests/unittests/com/android/sdklib
-com.android.ide.eclipse.tests/unittests/com/android/sdkuilib
-com.android.ide.eclipse.tests/unittests/com/android/layoutlib
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.overlay/.classpath b/eclipse/plugins/com.android.ide.eclipse.adt.overlay/.classpath
deleted file mode 100644
index acad1c227..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.overlay/.classpath
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.overlay/.project b/eclipse/plugins/com.android.ide.eclipse.adt.overlay/.project
deleted file mode 100644
index b24d832c8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.overlay/.project
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>plugin-adt-overlay</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.overlay/.settings/org.eclipse.jdt.core.prefs b/eclipse/plugins/com.android.ide.eclipse.adt.overlay/.settings/org.eclipse.jdt.core.prefs
deleted file mode 100644
index ea661960a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.overlay/.settings/org.eclipse.jdt.core.prefs
+++ /dev/null
@@ -1,98 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore
-org.eclipse.jdt.core.compiler.annotation.nonnull=com.android.annotations.NonNull
-org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=com.android.annotations.NonNullByDefault
-org.eclipse.jdt.core.compiler.annotation.nonnullisdefault=disabled
-org.eclipse.jdt.core.compiler.annotation.nullable=com.android.annotations.Nullable
-org.eclipse.jdt.core.compiler.annotation.nullanalysis=enabled
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
-org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
-org.eclipse.jdt.core.compiler.compliance=1.6
-org.eclipse.jdt.core.compiler.debug.lineNumber=generate
-org.eclipse.jdt.core.compiler.debug.localVariable=generate
-org.eclipse.jdt.core.compiler.debug.sourceFile=generate
-org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
-org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
-org.eclipse.jdt.core.compiler.problem.deadCode=warning
-org.eclipse.jdt.core.compiler.problem.deprecation=warning
-org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
-org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
-org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
-org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore
-org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning
-org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled
-org.eclipse.jdt.core.compiler.problem.fieldHiding=warning
-org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
-org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
-org.eclipse.jdt.core.compiler.problem.forbiddenReference=error
-org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
-org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=enabled
-org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
-org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning
-org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
-org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning
-org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
-org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore
-org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled
-org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=warning
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=error
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
-org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
-org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
-org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
-org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
-org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
-org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=warning
-org.eclipse.jdt.core.compiler.problem.nullReference=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecInsufficientInfo=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecViolation=warning
-org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=ignore
-org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
-org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
-org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullSpecViolation=error
-org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=warning
-org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=warning
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
-org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
-org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
-org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=enabled
-org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
-org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
-org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning
-org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=disabled
-org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
-org.eclipse.jdt.core.compiler.problem.unclosedCloseable=error
-org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
-org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
-org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning
-org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
-org.eclipse.jdt.core.compiler.problem.unusedImport=warning
-org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
-org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
-org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=warning
-org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
-org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
-org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
-org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
-org.eclipse.jdt.core.compiler.source=1.6
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.overlay/META-INF/MANIFEST.MF b/eclipse/plugins/com.android.ide.eclipse.adt.overlay/META-INF/MANIFEST.MF
deleted file mode 100644
index d1f897e6f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.overlay/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,19 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: ADT XML Overlay
-Bundle-SymbolicName: overlay.com.android.ide.eclipse.adt.overlay;singleton:=true
-Bundle-Version: 24.3.3.qualifier
-Bundle-Vendor: The Android Open Source Project
-Require-Bundle: org.eclipse.core.runtime,
- org.eclipse.core.resources,
- org.eclipse.ui,
- org.eclipse.debug.core,
- org.eclipse.debug.ui,
- org.eclipse.wst.sse.core,
- org.eclipse.wst.sse.ui,
- org.eclipse.wst.xml.core,
- org.eclipse.wst.xml.ui,
- com.android.ide.eclipse.adt
-Bundle-ActivationPolicy: lazy
-Import-Package: org.eclipse.jface.text.formatter
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.overlay/MODULE_LICENSE_EPL b/eclipse/plugins/com.android.ide.eclipse.adt.overlay/MODULE_LICENSE_EPL
deleted file mode 100644
index e69de29bb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.overlay/MODULE_LICENSE_EPL
+++ /dev/null
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.overlay/NOTICE b/eclipse/plugins/com.android.ide.eclipse.adt.overlay/NOTICE
deleted file mode 100644
index cedb5b4f9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.overlay/NOTICE
+++ /dev/null
@@ -1,221 +0,0 @@
-*Eclipse Public License - v 1.0*
-
-THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE
-PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF
-THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
-
-*1. DEFINITIONS*
-
-"Contribution" means:
-
-a) in the case of the initial Contributor, the initial code and
-documentation distributed under this Agreement, and
-b) in the case of each subsequent Contributor:
-
-i) changes to the Program, and
-
-ii) additions to the Program;
-
-where such changes and/or additions to the Program originate from and
-are distributed by that particular Contributor. A Contribution
-'originates' from a Contributor if it was added to the Program by such
-Contributor itself or anyone acting on such Contributor's behalf.
-Contributions do not include additions to the Program which: (i) are
-separate modules of software distributed in conjunction with the Program
-under their own license agreement, and (ii) are not derivative works of
-the Program.
-
-"Contributor" means any person or entity that distributes the Program.
-
-"Licensed Patents " mean patent claims licensable by a Contributor which
-are necessarily infringed by the use or sale of its Contribution alone
-or when combined with the Program.
-
-"Program" means the Contributions distributed in accordance with this
-Agreement.
-
-"Recipient" means anyone who receives the Program under this Agreement,
-including all Contributors.
-
-*2. GRANT OF RIGHTS*
-
-a) Subject to the terms of this Agreement, each Contributor hereby
-grants Recipient a non-exclusive, worldwide, royalty-free copyright
-license to reproduce, prepare derivative works of, publicly display,
-publicly perform, distribute and sublicense the Contribution of such
-Contributor, if any, and such derivative works, in source code and
-object code form.
-
-b) Subject to the terms of this Agreement, each Contributor hereby
-grants Recipient a non-exclusive, worldwide, royalty-free patent license
-under Licensed Patents to make, use, sell, offer to sell, import and
-otherwise transfer the Contribution of such Contributor, if any, in
-source code and object code form. This patent license shall apply to the
-combination of the Contribution and the Program if, at the time the
-Contribution is added by the Contributor, such addition of the
-Contribution causes such combination to be covered by the Licensed
-Patents. The patent license shall not apply to any other combinations
-which include the Contribution. No hardware per se is licensed hereunder.
-
-c) Recipient understands that although each Contributor grants the
-licenses to its Contributions set forth herein, no assurances are
-provided by any Contributor that the Program does not infringe the
-patent or other intellectual property rights of any other entity. Each
-Contributor disclaims any liability to Recipient for claims brought by
-any other entity based on infringement of intellectual property rights
-or otherwise. As a condition to exercising the rights and licenses
-granted hereunder, each Recipient hereby assumes sole responsibility to
-secure any other intellectual property rights needed, if any. For
-example, if a third party patent license is required to allow Recipient
-to distribute the Program, it is Recipient's responsibility to acquire
-that license before distributing the Program.
-
-d) Each Contributor represents that to its knowledge it has sufficient
-copyright rights in its Contribution, if any, to grant the copyright
-license set forth in this Agreement.
-
-*3. REQUIREMENTS*
-
-A Contributor may choose to distribute the Program in object code form
-under its own license agreement, provided that:
-
-a) it complies with the terms and conditions of this Agreement; and
-
-b) its license agreement:
-
-i) effectively disclaims on behalf of all Contributors all warranties
-and conditions, express and implied, including warranties or conditions
-of title and non-infringement, and implied warranties or conditions of
-merchantability and fitness for a particular purpose;
-
-ii) effectively excludes on behalf of all Contributors all liability for
-damages, including direct, indirect, special, incidental and
-consequential damages, such as lost profits;
-
-iii) states that any provisions which differ from this Agreement are
-offered by that Contributor alone and not by any other party; and
-
-iv) states that source code for the Program is available from such
-Contributor, and informs licensees how to obtain it in a reasonable
-manner on or through a medium customarily used for software exchange.
-
-When the Program is made available in source code form:
-
-a) it must be made available under this Agreement; and
-
-b) a copy of this Agreement must be included with each copy of the Program.
-
-Contributors may not remove or alter any copyright notices contained
-within the Program.
-
-Each Contributor must identify itself as the originator of its
-Contribution, if any, in a manner that reasonably allows subsequent
-Recipients to identify the originator of the Contribution.
-
-*4. COMMERCIAL DISTRIBUTION*
-
-Commercial distributors of software may accept certain responsibilities
-with respect to end users, business partners and the like. While this
-license is intended to facilitate the commercial use of the Program, the
-Contributor who includes the Program in a commercial product offering
-should do so in a manner which does not create potential liability for
-other Contributors. Therefore, if a Contributor includes the Program in
-a commercial product offering, such Contributor ("Commercial
-Contributor") hereby agrees to defend and indemnify every other
-Contributor ("Indemnified Contributor") against any losses, damages and
-costs (collectively "Losses") arising from claims, lawsuits and other
-legal actions brought by a third party against the Indemnified
-Contributor to the extent caused by the acts or omissions of such
-Commercial Contributor in connection with its distribution of the
-Program in a commercial product offering. The obligations in this
-section do not apply to any claims or Losses relating to any actual or
-alleged intellectual property infringement. In order to qualify, an
-Indemnified Contributor must: a) promptly notify the Commercial
-Contributor in writing of such claim, and b) allow the Commercial
-Contributor to control, and cooperate with the Commercial Contributor
-in, the defense and any related settlement negotiations. The Indemnified
-Contributor may participate in any such claim at its own expense.
-
-For example, a Contributor might include the Program in a commercial
-product offering, Product X. That Contributor is then a Commercial
-Contributor. If that Commercial Contributor then makes performance
-claims, or offers warranties related to Product X, those performance
-claims and warranties are such Commercial Contributor's responsibility
-alone. Under this section, the Commercial Contributor would have to
-defend claims against the other Contributors related to those
-performance claims and warranties, and if a court requires any other
-Contributor to pay any damages as a result, the Commercial Contributor
-must pay those damages.
-
-*5. NO WARRANTY*
-
-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED
-ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
-EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES
-OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR
-A PARTICULAR PURPOSE. Each Recipient is solely responsible for
-determining the appropriateness of using and distributing the Program
-and assumes all risks associated with its exercise of rights under this
-Agreement , including but not limited to the risks and costs of program
-errors, compliance with applicable laws, damage to or loss of data,
-programs or equipment, and unavailability or interruption of operations.
-
-*6. DISCLAIMER OF LIABILITY*
-
-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR
-ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT,
-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING
-WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF
-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR
-DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
-HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-
-*7. GENERAL*
-
-If any provision of this Agreement is invalid or unenforceable under
-applicable law, it shall not affect the validity or enforceability of
-the remainder of the terms of this Agreement, and without further action
-by the parties hereto, such provision shall be reformed to the minimum
-extent necessary to make such provision valid and enforceable.
-
-If Recipient institutes patent litigation against any entity (including
-a cross-claim or counterclaim in a lawsuit) alleging that the Program
-itself (excluding combinations of the Program with other software or
-hardware) infringes such Recipient's patent(s), then such Recipient's
-rights granted under Section 2(b) shall terminate as of the date such
-litigation is filed.
-
-All Recipient's rights under this Agreement shall terminate if it fails
-to comply with any of the material terms or conditions of this Agreement
-and does not cure such failure in a reasonable period of time after
-becoming aware of such noncompliance. If all Recipient's rights under
-this Agreement terminate, Recipient agrees to cease use and distribution
-of the Program as soon as reasonably practicable. However, Recipient's
-obligations under this Agreement and any licenses granted by Recipient
-relating to the Program shall continue and survive.
-
-Everyone is permitted to copy and distribute copies of this Agreement,
-but in order to avoid inconsistency the Agreement is copyrighted and may
-only be modified in the following manner. The Agreement Steward reserves
-the right to publish new versions (including revisions) of this
-Agreement from time to time. No one other than the Agreement Steward has
-the right to modify this Agreement. The Eclipse Foundation is the
-initial Agreement Steward. The Eclipse Foundation may assign the
-responsibility to serve as the Agreement Steward to a suitable separate
-entity. Each new version of the Agreement will be given a distinguishing
-version number. The Program (including Contributions) may always be
-distributed subject to the version of the Agreement under which it was
-received. In addition, after a new version of the Agreement is
-published, Contributor may elect to distribute the Program (including
-its Contributions) under the new version. Except as expressly stated in
-Sections 2(a) and 2(b) above, Recipient receives no rights or licenses
-to the intellectual property of any Contributor under this Agreement,
-whether expressly, by implication, estoppel or otherwise. All rights in
-the Program not expressly granted under this Agreement are reserved.
-
-This Agreement is governed by the laws of the State of New York and the
-intellectual property laws of the United States of America. No party to
-this Agreement will bring a legal action under this Agreement more than
-one year after the cause of action arose. Each party waives its rights
-to a jury trial in any resulting litigation.
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.overlay/README.txt b/eclipse/plugins/com.android.ide.eclipse.adt.overlay/README.txt
deleted file mode 100644
index 7b7f0d191..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.overlay/README.txt
+++ /dev/null
@@ -1,14 +0,0 @@
-This plugin provides a minor extension to the ADT plugin to support
-XML formatting via the "Source > Format" action on files.
-
-The reason the plugin package name starts with the word "overlay"
-instead of the normal "com.android.eclipse" package is that the plugin
-name *must* be alphabetically later than "org.eclipse". The reasons
-for this is detailed in issue
- http://code.google.com/p/android/issues/detail?id=20450
-but essentially the plugin registration to override the
-formatProcessor is processed in the alphabetical order of the plugin
-names, so the org.eclipse plugin would clobber the com.android.eclipse
-plugin. To work around this, the specific registration code was moved
-out to a separate plugin, but the formatter itself continues to live
-in ADT.
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.overlay/build.properties b/eclipse/plugins/com.android.ide.eclipse.adt.overlay/build.properties
deleted file mode 100644
index 50668f328..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.overlay/build.properties
+++ /dev/null
@@ -1,4 +0,0 @@
-bin.includes = META-INF/,\
- plugin.xml,\
- NOTICE
-jars.compile.order =
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.overlay/plugin.xml b/eclipse/plugins/com.android.ide.eclipse.adt.overlay/plugin.xml
deleted file mode 100644
index 5b4b5208a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.overlay/plugin.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<?eclipse version="3.5"?>
-<plugin>
- <extension point="org.eclipse.wst.sse.core.formatProcessors">
- <processor
- class="com.android.ide.eclipse.adt.internal.editors.formatting.XmlFormatProcessor"
- contentTypeId="org.eclipse.core.runtime.xml">
- </processor>
- </extension>
-</plugin>
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.overlay/pom.xml b/eclipse/plugins/com.android.ide.eclipse.adt.overlay/pom.xml
deleted file mode 100644
index 6dbe3d295..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.overlay/pom.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <version>24.3.3-SNAPSHOT</version>
- <artifactId>overlay.com.android.ide.eclipse.adt.overlay</artifactId>
- <packaging>eclipse-plugin</packaging>
- <name>adt.overlay</name>
-
- <parent>
- <relativePath>../../pom.xml</relativePath>
- <groupId>adt.group</groupId>
- <artifactId>parent</artifactId>
- <version>1.0.0-SNAPSHOT</version>
- </parent>
-</project>
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.package/.project b/eclipse/plugins/com.android.ide.eclipse.adt.package/.project
deleted file mode 100644
index eedf4c6de..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.package/.project
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>plugin-adt-package</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- </natures>
-</projectDescription>
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.package/META-INF/MANIFEST.MF b/eclipse/plugins/com.android.ide.eclipse.adt.package/META-INF/MANIFEST.MF
deleted file mode 100644
index 999aead82..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.package/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,10 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: ADT Package
-Bundle-SymbolicName: com.android.ide.eclipse.adt.package;singleton:=true
-Bundle-Version: 24.3.3.qualifier
-Bundle-Vendor: The Android Open Source Project
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
-Eclipse-BundleShape: dir
-Require-Bundle: org.eclipse.platform,
- org.eclipse.equinox.app
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.package/about.ini b/eclipse/plugins/com.android.ide.eclipse.adt.package/about.ini
deleted file mode 100644
index 31e848974..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.package/about.ini
+++ /dev/null
@@ -1,5 +0,0 @@
-aboutText=%blurb
-featureImage=icons/adt32.png
-windowImage=icons/adt16.png
-aboutImage=adt-about.png
-appName=ADT \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.package/about.properties b/eclipse/plugins/com.android.ide.eclipse.adt.package/about.properties
deleted file mode 100644
index 4f75169d2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.package/about.properties
+++ /dev/null
@@ -1,6 +0,0 @@
-blurb=Android Developer Tools\n\
-\n\
-Build: {0}\n\
-\n\
-Copyright (c) The Android Open Source Project.\n\
-Visit http://developer.android.com and http://source.android.com
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.package/adt-about.png b/eclipse/plugins/com.android.ide.eclipse.adt.package/adt-about.png
deleted file mode 100644
index 7235e493d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.package/adt-about.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.package/build.properties b/eclipse/plugins/com.android.ide.eclipse.adt.package/build.properties
deleted file mode 100644
index 068895339..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.package/build.properties
+++ /dev/null
@@ -1,11 +0,0 @@
-source.. = src/
-output.. = bin/
-bin.includes = META-INF/,\
- plugin.xml,\
- .,\
- plugin_customization.ini,\
- adt-about.png,\
- splash.bmp,\
- icons/,\
- about.ini,\
- about.properties
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.package/icons/adt.icns b/eclipse/plugins/com.android.ide.eclipse.adt.package/icons/adt.icns
deleted file mode 100644
index b29e329b7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.package/icons/adt.icns
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.package/icons/adt.ico b/eclipse/plugins/com.android.ide.eclipse.adt.package/icons/adt.ico
deleted file mode 100644
index 5ea427544..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.package/icons/adt.ico
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.package/icons/adt.png b/eclipse/plugins/com.android.ide.eclipse.adt.package/icons/adt.png
deleted file mode 100644
index 1f76f8722..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.package/icons/adt.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.package/icons/adt16.png b/eclipse/plugins/com.android.ide.eclipse.adt.package/icons/adt16.png
deleted file mode 100644
index bbd14beb4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.package/icons/adt16.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.package/icons/adt32.png b/eclipse/plugins/com.android.ide.eclipse.adt.package/icons/adt32.png
deleted file mode 100644
index 0ef9fdffc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.package/icons/adt32.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.package/icons/adt48.png b/eclipse/plugins/com.android.ide.eclipse.adt.package/icons/adt48.png
deleted file mode 100644
index ab846e197..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.package/icons/adt48.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.package/plugin.xml b/eclipse/plugins/com.android.ide.eclipse.adt.package/plugin.xml
deleted file mode 100644
index 7974659cc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.package/plugin.xml
+++ /dev/null
@@ -1,71 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<?eclipse version="3.4"?>
-<plugin>
- <extension
- id="adtproduct"
- name="ADT Bundle"
- point="org.eclipse.core.runtime.products">
- <product
- application="org.eclipse.ui.ide.workbench"
- name="Eclipse">
- <property
- name="preferenceCustomization"
- value="plugin_customization.ini" />
- <property
- name="appName"
- value="Eclipse" />
- <property
- name="aboutImage"
- value="adt-about.png">
- </property>
- <property
- name="aboutText"
- value="Android Developer Tools&#x0A;&#x0A;This product includes Eclipse Platform, JDT, CDT, EMF, GEF and WTP, all of which are&#x0A;Copyright (c) Eclipse contributors and others.&#x0A;Visit http://eclipse.org/&#x0A;&#x0A;Android Developer Tools are Copyright (c) The Android Open Source Project.&#x0A;Visit http://developer.android.com">
- </property>
- <property
- name="startupProgressRect"
- value="216,229,170,4" />
- <property
- name="startupMessageRect"
- value="216,240,265,30" />
- <property
- name="startupForegroundColor"
- value="999999" />
- <property
- name="windowImages"
- value="icons/adt16.png,icons/adt32.png,icons/adt48.png">
- </property>
- <property
- name="introBrandingImage"
- value="product:intro-eclipse.png">
- </property>
- <property
- name="introTitle"
- value="Welcome to the Eclipse IDE for Android Developers">
- </property>
- <property
- name="introBrandingImageText"
- value="Eclipse Project">
- </property>
- <property
- name="applicationXMI"
- value="org.eclipse.platform/LegacyIDE.e4xmi">
- </property>
- <property
- name="cssTheme"
- value="org.eclipse.e4.ui.css.theme.e4_default">
- </property>
- <property
- name="applicationCSSResources"
- value="platform:/plugin/org.eclipse.ui.themes/images/">
- </property>
- </product>
- </extension>
- <extension
- point="org.eclipse.ui.intro">
- <introProductBinding
- introId="org.eclipse.ui.intro.universal"
- productId="com.android.ide.eclipse.adt.package.product">
- </introProductBinding>
- </extension>
-</plugin>
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.package/plugin_customization.ini b/eclipse/plugins/com.android.ide.eclipse.adt.package/plugin_customization.ini
deleted file mode 100644
index 5585184d7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.package/plugin_customization.ini
+++ /dev/null
@@ -1,8 +0,0 @@
-org.eclipse.ui/defaultPerspectiveId=org.eclipse.jdt.ui.JavaPerspective
-org.eclipse.ui/SHOW_TRADITIONAL_STYLE_TABS=false
-org.eclipse.ui/DOCK_PERSPECTIVE_BAR=topRight
-org.eclipse.ui/PERSPECTIVE_BAR_EXTRAS=com.android.ide.eclipse.ddms.Perspective
-org.eclipse.ui/PERSPECTIVE_BAR_SIZE=250
-org.eclipse.ui/SHOW_PROGRESS_ON_STARTUP = false
-org.eclipse.ui.workbench/SHOW_BUILDID_ON_STARTUP=true
-org.eclipse.ui/SHOW_MEMORY_MONITOR=true \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.package/pom.xml b/eclipse/plugins/com.android.ide.eclipse.adt.package/pom.xml
deleted file mode 100644
index f6000cecf..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.package/pom.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <version>24.3.3-SNAPSHOT</version>
- <artifactId>com.android.ide.eclipse.adt.package</artifactId>
- <packaging>eclipse-plugin</packaging>
- <name>adt.package</name>
-
- <parent>
- <relativePath>../../pom.xml</relativePath>
- <groupId>adt.group</groupId>
- <artifactId>parent</artifactId>
- <version>1.0.0-SNAPSHOT</version>
- </parent>
-</project>
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt.package/splash.bmp b/eclipse/plugins/com.android.ide.eclipse.adt.package/splash.bmp
deleted file mode 100644
index 0af805859..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt.package/splash.bmp
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/.classpath b/eclipse/plugins/com.android.ide.eclipse.adt/.classpath
deleted file mode 100644
index c5f5919c7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/.classpath
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry excluding="Makefile|resources/" kind="src" path="src"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry exported="true" kind="lib" path="libs/ninepatch.jar" sourcepath="/ninepatch"/>
- <classpathentry exported="true" kind="lib" path="libs/sdkuilib.jar" sourcepath="/sdkuilib"/>
- <classpathentry exported="true" kind="lib" path="libs/rule-api.jar" sourcepath="/rule-api"/>
- <classpathentry exported="true" kind="lib" path="libs/lint-api.jar" sourcepath="/lint-api"/>
- <classpathentry exported="true" kind="lib" path="libs/lint-checks.jar" sourcepath="/lint-checks"/>
- <classpathentry exported="true" kind="lib" path="libs/asset-studio.jar" sourcepath="/asset-studio"/>
- <classpathentry exported="true" kind="lib" path="libs/ant-glob.jar"/>
- <classpathentry exported="true" kind="lib" path="libs/freemarker-2.3.20.jar"/>
- <classpathentry exported="true" kind="lib" path="libs/manifest-merger.jar" sourcepath="/ManifestMerger"/>
- <classpathentry exported="true" kind="lib" path="libs/lombok-ast-0.2.2.jar"/>
- <classpathentry exported="true" kind="lib" path="libs/propertysheet.jar"/>
- <classpathentry exported="true" kind="lib" path="libs/asm-5.0.3.jar"/>
- <classpathentry exported="true" kind="lib" path="libs/asm-analysis-5.0.3.jar"/>
- <classpathentry exported="true" kind="lib" path="libs/asm-tree-5.0.3.jar"/>
- <classpathentry exported="true" kind="lib" path="libs/swtmenubar.jar"/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/.gitignore b/eclipse/plugins/com.android.ide.eclipse.adt/.gitignore
deleted file mode 100644
index 5e56e040e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-/bin
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/.project b/eclipse/plugins/com.android.ide.eclipse.adt/.project
deleted file mode 100644
index 0bc58f943..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/.project
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>plugin-adt</name>
- <comment></comment>
- <projects>
- <project>SdkLib</project>
- <project>SdkUiLib</project>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/.settings/org.eclipse.core.resources.prefs b/eclipse/plugins/com.android.ide.eclipse.adt/.settings/org.eclipse.core.resources.prefs
deleted file mode 100644
index b3c7fded6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/.settings/org.eclipse.core.resources.prefs
+++ /dev/null
@@ -1 +0,0 @@
-eclipse.preferences.version=1
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/.settings/org.eclipse.jdt.core.prefs b/eclipse/plugins/com.android.ide.eclipse.adt/.settings/org.eclipse.jdt.core.prefs
deleted file mode 100644
index ea661960a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/.settings/org.eclipse.jdt.core.prefs
+++ /dev/null
@@ -1,98 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore
-org.eclipse.jdt.core.compiler.annotation.nonnull=com.android.annotations.NonNull
-org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=com.android.annotations.NonNullByDefault
-org.eclipse.jdt.core.compiler.annotation.nonnullisdefault=disabled
-org.eclipse.jdt.core.compiler.annotation.nullable=com.android.annotations.Nullable
-org.eclipse.jdt.core.compiler.annotation.nullanalysis=enabled
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
-org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
-org.eclipse.jdt.core.compiler.compliance=1.6
-org.eclipse.jdt.core.compiler.debug.lineNumber=generate
-org.eclipse.jdt.core.compiler.debug.localVariable=generate
-org.eclipse.jdt.core.compiler.debug.sourceFile=generate
-org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
-org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
-org.eclipse.jdt.core.compiler.problem.deadCode=warning
-org.eclipse.jdt.core.compiler.problem.deprecation=warning
-org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
-org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
-org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
-org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore
-org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning
-org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled
-org.eclipse.jdt.core.compiler.problem.fieldHiding=warning
-org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
-org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
-org.eclipse.jdt.core.compiler.problem.forbiddenReference=error
-org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
-org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=enabled
-org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
-org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning
-org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
-org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning
-org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
-org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore
-org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled
-org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=warning
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=error
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
-org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
-org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
-org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
-org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
-org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
-org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=warning
-org.eclipse.jdt.core.compiler.problem.nullReference=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecInsufficientInfo=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecViolation=warning
-org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=ignore
-org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
-org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
-org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullSpecViolation=error
-org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=warning
-org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=warning
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
-org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
-org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
-org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=enabled
-org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
-org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
-org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning
-org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=disabled
-org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
-org.eclipse.jdt.core.compiler.problem.unclosedCloseable=error
-org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
-org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
-org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning
-org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
-org.eclipse.jdt.core.compiler.problem.unusedImport=warning
-org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
-org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
-org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=warning
-org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
-org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
-org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
-org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
-org.eclipse.jdt.core.compiler.source=1.6
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/.settings/org.moreunit.prefs b/eclipse/plugins/com.android.ide.eclipse.adt/.settings/org.moreunit.prefs
deleted file mode 100644
index c5e8a5e71..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/.settings/org.moreunit.prefs
+++ /dev/null
@@ -1,4 +0,0 @@
-eclipse.preferences.version=1
-org.moreunit.prefixes=
-org.moreunit.unitsourcefolder=plugin-adt\:src\:plugin-tests\:unittests\#plugin-adt\:src\:plugin-tests\:src
-org.moreunit.useprojectsettings=true
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/META-INF/MANIFEST.MF b/eclipse/plugins/com.android.ide.eclipse.adt/META-INF/MANIFEST.MF
deleted file mode 100644
index 3115f79dc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,140 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: Android Development Toolkit
-Bundle-SymbolicName: com.android.ide.eclipse.adt;singleton:=true
-Bundle-Version: 24.3.3.qualifier
-Bundle-ClassPath: .,
- libs/sdkuilib.jar,
- libs/ninepatch.jar,
- libs/freemarker-2.3.20.jar,
- libs/rule-api.jar,
- libs/asset-studio.jar,
- libs/lint-api.jar,
- libs/lint-checks.jar,
- libs/lombok-ast-0.2.3.jar,
- libs/asm-5.0.3.jar,
- libs/asm-tree-5.0.3.jar,
- libs/asm-analysis-5.0.3.jar,
- libs/propertysheet.jar,
- libs/ant-glob.jar,
- libs/swtmenubar.jar,
- libs/manifest-merger.jar
-Bundle-Activator: com.android.ide.eclipse.adt.AdtPlugin
-Bundle-Vendor: The Android Open Source Project
-Require-Bundle: com.android.ide.eclipse.base,
- com.android.ide.eclipse.ddms,
- org.eclipse.core.runtime,
- org.eclipse.core.resources,
- org.eclipse.debug.core,
- org.eclipse.debug.ui,
- org.eclipse.jdt,
- org.eclipse.ant.core,
- org.eclipse.jdt.core,
- org.eclipse.jdt.ui,
- org.eclipse.jdt.launching,
- org.eclipse.jface.text,
- org.eclipse.ui.editors,
- org.eclipse.ui.workbench.texteditor,
- org.eclipse.ui.console,
- org.eclipse.core.filesystem,
- org.eclipse.ui,
- org.eclipse.ui.ide,
- org.eclipse.ui.forms,
- org.eclipse.ui.browser,
- org.eclipse.ui.views,
- org.eclipse.wst.sse.core,
- org.eclipse.wst.sse.ui,
- org.eclipse.wst.xml.core,
- org.eclipse.wst.xml.ui,
- org.eclipse.jdt.junit,
- org.eclipse.jdt.junit.runtime,
- org.eclipse.ltk.core.refactoring,
- org.eclipse.ltk.ui.refactoring,
- org.eclipse.core.expressions,
- org.eclipse.compare
-Bundle-ActivationPolicy: lazy
-Export-Package: com.android.ide.common.layout;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.common.layout.grid;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.common.layout.relative;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.common.resources.platform;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt;x-friends:="com.android.ide.eclipse.tests,com.android.ide.eclipse.adt.package",
- com.android.ide.eclipse.adt.internal;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.actions;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.assetstudio;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.build;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.build.builders;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.animator;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.binaryxml;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.color;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.common;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.descriptors;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.drawable;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.export;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.formatting;x-friends:="overlay.com.android.ide.eclipse.adt.overlay,com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.layout;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.layout.configuration;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.layout.descriptors;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.layout.gle2;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.layout.gre;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.layout.properties;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.layout.refactoring;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.layout.uimodel;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.manifest;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.manifest.descriptors;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.manifest.model;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.manifest.pages;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.menu;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.menu.descriptors;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.otherxml;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.otherxml.descriptors;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.ui;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.ui.tree;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.uimodel;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.values;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.values.descriptors;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.editors.values.uimodel;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.launch;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.launch.junit;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.launch.junit.runtime;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.lint;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.preferences;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.project;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.properties;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.refactorings.core;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.refactorings.extractstring;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.refactorings.renamepackage;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.resources;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.resources.manager;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.sdk;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.sourcelookup;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.ui;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.utils;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.welcome;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.wizards.actions;x-friends:="com.android.ide.eclipse.tests,com.android.ide.eclipse.adt.package",
- com.android.ide.eclipse.adt.internal.wizards.export;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.wizards.exportgradle;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.wizards.newproject;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.wizards.newxmlfile;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.internal.wizards.templates;x-friends:="com.android.ide.eclipse.tests",
- com.android.ide.eclipse.adt.io;x-friends:="com.android.ide.eclipse.tests",
- com.android.manifmerger;x-friends:="com.android.ide.eclipse.tests",
- com.android.ninepatch;x-friends:="com.android.ide.eclipse.tests",
- com.android.sdkuilib.internal.repository;x-friends:="com.android.ide.eclipse.tests",
- com.android.sdkuilib.internal.repository.core;x-friends:="com.android.ide.eclipse.tests",
- com.android.sdkuilib.internal.repository.icons;x-friends:="com.android.ide.eclipse.tests",
- com.android.sdkuilib.internal.repository.ui;x-friends:="com.android.ide.eclipse.tests",
- com.android.sdkuilib.internal.tasks;x-friends:="com.android.ide.eclipse.tests",
- com.android.sdkuilib.internal.widgets;x-friends:="com.android.ide.eclipse.tests",
- com.android.sdkuilib.repository;x-friends:="com.android.ide.eclipse.tests",
- com.android.sdkuilib.ui;x-friends:="com.android.ide.eclipse.tests",
- com.android.tools.lint.checks;x-friends:="com.android.ide.eclipse.tests",
- com.android.tools.lint.client.api;x-friends:="com.android.ide.eclipse.tests",
- com.android.tools.lint.detector.api;x-friends:="com.android.ide.eclipse.tests",
- freemarker.cache;x-friends:="com.android.ide.eclipse.tests",
- freemarker.template;x-friends:="com.android.ide.eclipse.tests"
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
-Import-Package: com.ibm.icu.text,
- org.eclipse.core.variables
-
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/MODULE_LICENSE_EPL b/eclipse/plugins/com.android.ide.eclipse.adt/MODULE_LICENSE_EPL
deleted file mode 100644
index e69de29bb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/MODULE_LICENSE_EPL
+++ /dev/null
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/NOTICE b/eclipse/plugins/com.android.ide.eclipse.adt/NOTICE
deleted file mode 100644
index 49c101df7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/NOTICE
+++ /dev/null
@@ -1,224 +0,0 @@
-*Eclipse Public License - v 1.0*
-
-THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE
-PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF
-THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
-
-*1. DEFINITIONS*
-
-"Contribution" means:
-
-a) in the case of the initial Contributor, the initial code and
-documentation distributed under this Agreement, and
-b) in the case of each subsequent Contributor:
-
-i) changes to the Program, and
-
-ii) additions to the Program;
-
-where such changes and/or additions to the Program originate from and
-are distributed by that particular Contributor. A Contribution
-'originates' from a Contributor if it was added to the Program by such
-Contributor itself or anyone acting on such Contributor's behalf.
-Contributions do not include additions to the Program which: (i) are
-separate modules of software distributed in conjunction with the Program
-under their own license agreement, and (ii) are not derivative works of
-the Program.
-
-"Contributor" means any person or entity that distributes the Program.
-
-"Licensed Patents " mean patent claims licensable by a Contributor which
-are necessarily infringed by the use or sale of its Contribution alone
-or when combined with the Program.
-
-"Program" means the Contributions distributed in accordance with this
-Agreement.
-
-"Recipient" means anyone who receives the Program under this Agreement,
-including all Contributors.
-
-*2. GRANT OF RIGHTS*
-
-a) Subject to the terms of this Agreement, each Contributor hereby
-grants Recipient a non-exclusive, worldwide, royalty-free copyright
-license to reproduce, prepare derivative works of, publicly display,
-publicly perform, distribute and sublicense the Contribution of such
-Contributor, if any, and such derivative works, in source code and
-object code form.
-
-b) Subject to the terms of this Agreement, each Contributor hereby
-grants Recipient a non-exclusive, worldwide, royalty-free patent license
-under Licensed Patents to make, use, sell, offer to sell, import and
-otherwise transfer the Contribution of such Contributor, if any, in
-source code and object code form. This patent license shall apply to the
-combination of the Contribution and the Program if, at the time the
-Contribution is added by the Contributor, such addition of the
-Contribution causes such combination to be covered by the Licensed
-Patents. The patent license shall not apply to any other combinations
-which include the Contribution. No hardware per se is licensed hereunder.
-
-c) Recipient understands that although each Contributor grants the
-licenses to its Contributions set forth herein, no assurances are
-provided by any Contributor that the Program does not infringe the
-patent or other intellectual property rights of any other entity. Each
-Contributor disclaims any liability to Recipient for claims brought by
-any other entity based on infringement of intellectual property rights
-or otherwise. As a condition to exercising the rights and licenses
-granted hereunder, each Recipient hereby assumes sole responsibility to
-secure any other intellectual property rights needed, if any. For
-example, if a third party patent license is required to allow Recipient
-to distribute the Program, it is Recipient's responsibility to acquire
-that license before distributing the Program.
-
-d) Each Contributor represents that to its knowledge it has sufficient
-copyright rights in its Contribution, if any, to grant the copyright
-license set forth in this Agreement.
-
-*3. REQUIREMENTS*
-
-A Contributor may choose to distribute the Program in object code form
-under its own license agreement, provided that:
-
-a) it complies with the terms and conditions of this Agreement; and
-
-b) its license agreement:
-
-i) effectively disclaims on behalf of all Contributors all warranties
-and conditions, express and implied, including warranties or conditions
-of title and non-infringement, and implied warranties or conditions of
-merchantability and fitness for a particular purpose;
-
-ii) effectively excludes on behalf of all Contributors all liability for
-damages, including direct, indirect, special, incidental and
-consequential damages, such as lost profits;
-
-iii) states that any provisions which differ from this Agreement are
-offered by that Contributor alone and not by any other party; and
-
-iv) states that source code for the Program is available from such
-Contributor, and informs licensees how to obtain it in a reasonable
-manner on or through a medium customarily used for software exchange.
-
-When the Program is made available in source code form:
-
-a) it must be made available under this Agreement; and
-
-b) a copy of this Agreement must be included with each copy of the Program.
-
-Contributors may not remove or alter any copyright notices contained
-within the Program.
-
-Each Contributor must identify itself as the originator of its
-Contribution, if any, in a manner that reasonably allows subsequent
-Recipients to identify the originator of the Contribution.
-
-*4. COMMERCIAL DISTRIBUTION*
-
-Commercial distributors of software may accept certain responsibilities
-with respect to end users, business partners and the like. While this
-license is intended to facilitate the commercial use of the Program, the
-Contributor who includes the Program in a commercial product offering
-should do so in a manner which does not create potential liability for
-other Contributors. Therefore, if a Contributor includes the Program in
-a commercial product offering, such Contributor ("Commercial
-Contributor") hereby agrees to defend and indemnify every other
-Contributor ("Indemnified Contributor") against any losses, damages and
-costs (collectively "Losses") arising from claims, lawsuits and other
-legal actions brought by a third party against the Indemnified
-Contributor to the extent caused by the acts or omissions of such
-Commercial Contributor in connection with its distribution of the
-Program in a commercial product offering. The obligations in this
-section do not apply to any claims or Losses relating to any actual or
-alleged intellectual property infringement. In order to qualify, an
-Indemnified Contributor must: a) promptly notify the Commercial
-Contributor in writing of such claim, and b) allow the Commercial
-Contributor to control, and cooperate with the Commercial Contributor
-in, the defense and any related settlement negotiations. The Indemnified
-Contributor may participate in any such claim at its own expense.
-
-For example, a Contributor might include the Program in a commercial
-product offering, Product X. That Contributor is then a Commercial
-Contributor. If that Commercial Contributor then makes performance
-claims, or offers warranties related to Product X, those performance
-claims and warranties are such Commercial Contributor's responsibility
-alone. Under this section, the Commercial Contributor would have to
-defend claims against the other Contributors related to those
-performance claims and warranties, and if a court requires any other
-Contributor to pay any damages as a result, the Commercial Contributor
-must pay those damages.
-
-*5. NO WARRANTY*
-
-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED
-ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
-EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES
-OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR
-A PARTICULAR PURPOSE. Each Recipient is solely responsible for
-determining the appropriateness of using and distributing the Program
-and assumes all risks associated with its exercise of rights under this
-Agreement , including but not limited to the risks and costs of program
-errors, compliance with applicable laws, damage to or loss of data,
-programs or equipment, and unavailability or interruption of operations.
-
-*6. DISCLAIMER OF LIABILITY*
-
-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR
-ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT,
-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING
-WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF
-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR
-DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
-HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-
-*7. GENERAL*
-
-If any provision of this Agreement is invalid or unenforceable under
-applicable law, it shall not affect the validity or enforceability of
-the remainder of the terms of this Agreement, and without further action
-by the parties hereto, such provision shall be reformed to the minimum
-extent necessary to make such provision valid and enforceable.
-
-If Recipient institutes patent litigation against any entity (including
-a cross-claim or counterclaim in a lawsuit) alleging that the Program
-itself (excluding combinations of the Program with other software or
-hardware) infringes such Recipient's patent(s), then such Recipient's
-rights granted under Section 2(b) shall terminate as of the date such
-litigation is filed.
-
-All Recipient's rights under this Agreement shall terminate if it fails
-to comply with any of the material terms or conditions of this Agreement
-and does not cure such failure in a reasonable period of time after
-becoming aware of such noncompliance. If all Recipient's rights under
-this Agreement terminate, Recipient agrees to cease use and distribution
-of the Program as soon as reasonably practicable. However, Recipient's
-obligations under this Agreement and any licenses granted by Recipient
-relating to the Program shall continue and survive.
-
-Everyone is permitted to copy and distribute copies of this Agreement,
-but in order to avoid inconsistency the Agreement is copyrighted and may
-only be modified in the following manner. The Agreement Steward reserves
-the right to publish new versions (including revisions) of this
-Agreement from time to time. No one other than the Agreement Steward has
-the right to modify this Agreement. The Eclipse Foundation is the
-initial Agreement Steward. The Eclipse Foundation may assign the
-responsibility to serve as the Agreement Steward to a suitable separate
-entity. Each new version of the Agreement will be given a distinguishing
-version number. The Program (including Contributions) may always be
-distributed subject to the version of the Agreement under which it was
-received. In addition, after a new version of the Agreement is
-published, Contributor may elect to distribute the Program (including
-its Contributions) under the new version. Except as expressly stated in
-Sections 2(a) and 2(b) above, Recipient receives no rights or licenses
-to the intellectual property of any Contributor under this Agreement,
-whether expressly, by implication, estoppel or otherwise. All rights in
-the Program not expressly granted under this Agreement are reserved.
-
-This Agreement is governed by the laws of the State of New York and the
-intellectual property laws of the United States of America. No party to
-this Agreement will bring a legal action under this Agreement more than
-one year after the cause of action arose. Each party waives its rights
-to a jury trial in any resulting litigation.
-
-
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/about.html b/eclipse/plugins/com.android.ide.eclipse.adt/about.html
deleted file mode 100644
index baa6af194..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/about.html
+++ /dev/null
@@ -1,108 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
-<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
-<title>About</title>
-</head>
-<body lang="EN-US">
-<h2>About This Content</h2>
-
-<p>September 19, 2010</p>
-<h3>License</h3>
-
-<pre>
- Note: kxml2-2.3.0.jar is under the BSD license rather than the EPL. You can find a copy of the BSD License at http://www.opensource.org/licenses/bsd-license.php
-
- Eclipse Public License - v 1.0
-
-THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE (&quot;AGREEMENT&quot;). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT&apos;S ACCEPTANCE OF THIS AGREEMENT.
-
-1. DEFINITIONS
-
-&quot;Contribution&quot; means:
-
-a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and
-
-b) in the case of each subsequent Contributor:
-
-i) changes to the Program, and
-
-ii) additions to the Program;
-
-where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution &apos;originates&apos; from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor&apos;s behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program.
-
-&quot;Contributor&quot; means any person or entity that distributes the Program.
-
-&quot;Licensed Patents&quot; mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program.
-
-&quot;Program&quot; means the Contributions distributed in accordance with this Agreement.
-
-&quot;Recipient&quot; means anyone who receives the Program under this Agreement, including all Contributors.
-
-2. GRANT OF RIGHTS
-
-a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form.
-
-b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.
-
-c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient&apos;s responsibility to acquire that license before distributing the Program.
-
-d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement.
-
-3. REQUIREMENTS
-
-A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that:
-
-a) it complies with the terms and conditions of this Agreement; and
-
-b) its license agreement:
-
-i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;
-
-ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits;
-
-iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and
-
-iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange.
-
-When the Program is made available in source code form:
-
-a) it must be made available under this Agreement; and
-
-b) a copy of this Agreement must be included with each copy of the Program.
-
-Contributors may not remove or alter any copyright notices contained within the Program.
-
-Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution.
-
-4. COMMERCIAL DISTRIBUTION
-
-Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor (&quot;Commercial Contributor&quot;) hereby agrees to defend and indemnify every other Contributor (&quot;Indemnified Contributor&quot;) against any losses, damages and costs (collectively &quot;Losses&quot;) arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense.
-
-For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor&apos;s responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages.
-
-5. NO WARRANTY
-
-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN &quot;AS IS&quot; BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.
-
-6. DISCLAIMER OF LIABILITY
-
-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-
-7. GENERAL
-
-If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
-
-If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient&apos;s patent(s), then such Recipient&apos;s rights granted under Section 2(b) shall terminate as of the date such litigation is filed.
-
-All Recipient&apos;s rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient&apos;s rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient&apos;s obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.
-
-Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved.
-
-This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation.
-
-</pre>
-
-</body>
-</html>
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/about.ini b/eclipse/plugins/com.android.ide.eclipse.adt/about.ini
deleted file mode 100644
index 2d7cdaad6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/about.ini
+++ /dev/null
@@ -1,2 +0,0 @@
-aboutText=%blurb
-featureImage=icons/android-32.png \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/about.properties b/eclipse/plugins/com.android.ide.eclipse.adt/about.properties
deleted file mode 100755
index 34218e997..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/about.properties
+++ /dev/null
@@ -1,7 +0,0 @@
-blurb=Android Development Toolkit\n\
-\n\
-Version\: {featureVersion}\n\
-\n\
-(c) Copyright 2007-2011 The Android Open Source Project. All rights reserved.\n\
-Visit http://developer.android.com/sdk/eclipse-adt.html
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/adt-platform-juno-sr2.target b/eclipse/plugins/com.android.ide.eclipse.adt/adt-platform-juno-sr2.target
deleted file mode 100644
index b63f38214..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/adt-platform-juno-sr2.target
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<?pde version="3.8"?>
-
-<target name="adt-platform-juno-sr2" sequenceNumber="4">
-<locations>
-<location includeAllPlatforms="false" includeConfigurePhase="true" includeMode="planner" includeSource="true" type="InstallableUnit">
-<unit id="org.eclipse.platform.ide" version="4.2.2.M20130204-1200"/>
-<unit id="org.eclipse.gef.feature.group" version="3.9.0.201212170307"/>
-<unit id="org.eclipse.wst.xml_ui.feature.feature.group" version="3.4.2.v201211061806-7H7GFeJDxumUrsn5qkiQgOEhsz0p60HAmPyU6VX"/>
-<unit id="org.eclipse.pde.source.feature.group" version="3.8.2.v20130116-091538-7c7wFj0FFt6Zr9bd4AM1JEQMS"/>
-<unit id="org.eclipse.emf.codegen.feature.group" version="2.8.0.v20130125-0826"/>
-<unit id="org.eclipse.jdt.feature.group" version="3.8.2.v20130116-090414-8-8nFu3FNOfwKLRuqgXKIy9z0I83"/>
-<unit id="org.eclipse.emf.ecore.feature.group" version="2.8.3.v20130125-0546"/>
-<unit id="org.eclipse.emf.common.feature.group" version="2.8.0.v20130125-0546"/>
-<unit id="org.eclipse.jdt.source.feature.group" version="3.8.2.v20130116-090414-8-8nFu3FNOfwKLRuqgXKIy9z0I83"/>
-<unit id="org.eclipse.emf.feature.group" version="2.8.3.v20130125-0826"/>
-<unit id="org.eclipse.cdt.feature.group" version="8.1.2.201302132326"/>
-<unit id="org.eclipse.egit.feature.group" version="2.2.0.201212191850-r"/>
-<unit id="org.eclipse.emf.common.ui.feature.group" version="2.7.0.v20130125-0826"/>
-<unit id="org.eclipse.emf.codegen.ui.feature.group" version="2.7.0.v20130125-0826"/>
-<unit id="org.eclipse.wb.core.xml.feature.feature.group" version="1.5.2.r42x201302111919"/>
-<repository location="http://download.eclipse.org/releases/juno"/>
-</location>
-</locations>
-</target>
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/adt.launch b/eclipse/plugins/com.android.ide.eclipse.adt/adt.launch
deleted file mode 100644
index 56998372a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/adt.launch
+++ /dev/null
@@ -1,33 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<launchConfiguration type="org.eclipse.pde.ui.RuntimeWorkbench">
-<booleanAttribute key="append.args" value="true"/>
-<booleanAttribute key="askclear" value="true"/>
-<booleanAttribute key="automaticAdd" value="true"/>
-<booleanAttribute key="automaticValidate" value="false"/>
-<stringAttribute key="bootstrap" value=""/>
-<stringAttribute key="checked" value="[NONE]"/>
-<booleanAttribute key="clearConfig" value="false"/>
-<booleanAttribute key="clearws" value="false"/>
-<booleanAttribute key="clearwslog" value="false"/>
-<stringAttribute key="configLocation" value="${workspace_loc}/.metadata/.plugins/org.eclipse.pde.core/adt"/>
-<booleanAttribute key="default" value="false"/>
-<stringAttribute key="deselected_workspace_plugins" value="com.android.ide.eclipse.monitor"/>
-<booleanAttribute key="includeOptional" value="true"/>
-<stringAttribute key="location" value="${workspace_loc}/../runtime-adt-idea133-ksr2"/>
-<booleanAttribute key="org.eclipse.jdt.launching.ATTR_USE_START_ON_FIRST_THREAD" value="true"/>
-<stringAttribute key="org.eclipse.jdt.launching.JRE_CONTAINER" value="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
-<stringAttribute key="org.eclipse.jdt.launching.PROGRAM_ARGUMENTS" value="-os ${target.os} -ws ${target.ws} -arch ${target.arch} -nl ${target.nl} -consoleLog"/>
-<stringAttribute key="org.eclipse.jdt.launching.SOURCE_PATH_PROVIDER" value="org.eclipse.pde.ui.workbenchClasspathProvider"/>
-<stringAttribute key="org.eclipse.jdt.launching.VM_ARGUMENTS" value="-XX:MaxPermSize=256m&#10;-Xms128m&#10;-Xmx1024m"/>
-<stringAttribute key="pde.version" value="3.3"/>
-<stringAttribute key="product" value="org.eclipse.platform.ide"/>
-<stringAttribute key="selected_target_plugins" value="com.android.tools.asset-studio@default:default,com.android.tools.build.er-model@default:default,com.android.tools.build.manifest-merger@default:default,com.android.tools.common@default:default,com.android.tools.ddms.ddmlib@default:default,com.android.tools.ddms.ddmuilib@default:default,com.android.tools.dvlib@default:default,com.android.tools.external.ant-glob@default:default,com.android.tools.external.liblzf@default:default,com.android.tools.external.libprotobuf-java-lite@default:default,com.android.tools.external.lombok.ast@default:default,com.android.tools.external.propertysheet@default:default,com.android.tools.hierarchyviewer2lib@default:default,com.android.tools.layoutlib.api@default:default,com.android.tools.lint.api@default:default,com.android.tools.lint.checks@default:default,com.android.tools.ninepatch@default:default,com.android.tools.rule-api@default:default,com.android.tools.sdk-common@default:default,com.android.tools.sdklib@default:default,com.android.tools.sdkstats@default:default,com.android.tools.sdkuilib@default:default,com.android.tools.swtmenubar@default:default,com.android.tools.testutils@default:default,com.android.tools.traceview@default:default,com.android.tools.uiautomatorviewer@default:default,com.google.guava@default:default,com.ibm.icu@default:default,com.jcraft.jsch@default:default,com.sun.el@default:default,commons-logging@default:default,java_cup.runtime@default:default,javax.activation@default:default,javax.annotation@default:default,javax.el@default:default,javax.inject@default:default,javax.jws@default:default,javax.mail@default:default,javax.persistence@default:default,javax.servlet.jsp@default:default,javax.servlet@default:default,javax.wsdl*1.5.1.v201012040544@default:default,javax.wsdl*1.6.2.v201012040545@default:default,javax.xml.bind@default:default,javax.xml.rpc@default:default,javax.xml.soap@default:default,javax.xml.stream@default:default,javax.xml.ws@default:default,javax.xml@default:default,jfree.chart-swt@default:default,jfree.chart@default:default,jfree.jcommon@default:default,junit@default:default,net.sf.kxml.2@default:default,net.sourceforge.lpg.lpgjavaruntime@default:default,org.apache.ant@default:default,org.apache.axis@default:default,org.apache.batik.css@default:default,org.apache.batik.util.gui@default:default,org.apache.batik.util@default:default,org.apache.bcel@default:default,org.apache.commons.codec*1.4.0.v201209201156@default:default,org.apache.commons.codec*1.4.0@default:default,org.apache.commons.collections@default:default,org.apache.commons.compress@default:default,org.apache.commons.discovery@default:default,org.apache.commons.lang@default:default,org.apache.commons.logging*1.0.4.v201101211617@default:default,org.apache.commons.logging*1.1.1.v201101211721@default:default,org.apache.felix.gogo.command@default:default,org.apache.felix.gogo.runtime@default:default,org.apache.felix.gogo.shell@default:default,org.apache.httpcomponents.httpclient*4.1.1@default:default,org.apache.httpcomponents.httpclient*4.1.3.v201209201135@default:default,org.apache.httpcomponents.httpcore*4.1.0@default:default,org.apache.httpcomponents.httpcore*4.1.4.v201203221030@default:default,org.apache.httpcomponents.httpmime@default:default,org.apache.jasper.glassfish@default:default,org.apache.log4j@default:default,org.apache.lucene.analysis@default:default,org.apache.lucene.core@default:default,org.apache.velocity@default:default,org.apache.wsil4j@default:default,org.apache.xalan@default:default,org.apache.xerces@default:default,org.apache.xml.resolver@default:default,org.apache.xml.serializer@default:default,org.eclipse.ant.core@default:default,org.eclipse.ant.launching@default:default,org.eclipse.ant.ui@default:default,org.eclipse.cdt.autotools.core@default:default,org.eclipse.cdt.autotools.docs@default:default,org.eclipse.cdt.autotools.ui@default:default,org.eclipse.cdt.build.crossgcc@default:default,org.eclipse.cdt.codan.checkers.ui@default:default,org.eclipse.cdt.codan.checkers@default:default,org.eclipse.cdt.codan.core.cxx@default:default,org.eclipse.cdt.codan.core@default:default,org.eclipse.cdt.codan.ui.cxx@default:default,org.eclipse.cdt.codan.ui@default:default,org.eclipse.cdt.core.aix@default:false,org.eclipse.cdt.core.linux.ppc64@default:false,org.eclipse.cdt.core.linux.x86@default:false,org.eclipse.cdt.core.linux.x86_64@default:false,org.eclipse.cdt.core.linux@default:false,org.eclipse.cdt.core.lrparser.xlc@default:default,org.eclipse.cdt.core.lrparser@default:default,org.eclipse.cdt.core.macosx@default:false,org.eclipse.cdt.core.parser.upc@default:default,org.eclipse.cdt.core.solaris@default:false,org.eclipse.cdt.core.win32.x86@default:false,org.eclipse.cdt.core.win32.x86_64@default:false,org.eclipse.cdt.core.win32@default:false,org.eclipse.cdt.core@default:default,org.eclipse.cdt.debug.core@default:default,org.eclipse.cdt.debug.gdbjtag.core@default:default,org.eclipse.cdt.debug.gdbjtag.ui@default:default,org.eclipse.cdt.debug.gdbjtag@default:default,org.eclipse.cdt.debug.mi.core@default:default,org.eclipse.cdt.debug.mi.ui@default:default,org.eclipse.cdt.debug.ui.memory.floatingpoint@default:default,org.eclipse.cdt.debug.ui.memory.memorybrowser@default:default,org.eclipse.cdt.debug.ui.memory.search@default:default,org.eclipse.cdt.debug.ui.memory.traditional@default:default,org.eclipse.cdt.debug.ui.memory.transport@default:default,org.eclipse.cdt.debug.ui@default:default,org.eclipse.cdt.doc.isv@default:default,org.eclipse.cdt.doc.user@default:default,org.eclipse.cdt.dsf.gdb.multicorevisualizer.ui@default:default,org.eclipse.cdt.dsf.gdb.ui@default:default,org.eclipse.cdt.dsf.gdb@default:default,org.eclipse.cdt.dsf.ui@default:default,org.eclipse.cdt.dsf@default:default,org.eclipse.cdt.errorparsers.xlc@default:default,org.eclipse.cdt.examples.dsf.pda.ui@default:default,org.eclipse.cdt.examples.dsf.pda@default:default,org.eclipse.cdt.examples.dsf@default:default,org.eclipse.cdt.gdb.ui@default:default,org.eclipse.cdt.gdb@default:default,org.eclipse.cdt.launch.remote@default:default,org.eclipse.cdt.launch@default:default,org.eclipse.cdt.make.core@default:default,org.eclipse.cdt.make.ui@default:default,org.eclipse.cdt.make.xlc.core@default:default,org.eclipse.cdt.managedbuilder.bupc.ui@default:default,org.eclipse.cdt.managedbuilder.core@default:default,org.eclipse.cdt.managedbuilder.gnu.ui@default:default,org.eclipse.cdt.managedbuilder.llvm.ui@default:default,org.eclipse.cdt.managedbuilder.ui@default:default,org.eclipse.cdt.managedbuilder.xlc.core@default:default,org.eclipse.cdt.managedbuilder.xlc.ui@default:default,org.eclipse.cdt.managedbuilder.xlupc.ui@default:default,org.eclipse.cdt.msw.build@default:default,org.eclipse.cdt.qt.core@default:default,org.eclipse.cdt.qt.ui@default:default,org.eclipse.cdt.sdk@default:default,org.eclipse.cdt.testsrunner.boost@default:default,org.eclipse.cdt.testsrunner.gtest@default:default,org.eclipse.cdt.testsrunner.qttest@default:default,org.eclipse.cdt.testsrunner@default:default,org.eclipse.cdt.ui@default:default,org.eclipse.cdt.util@default:default,org.eclipse.cdt.visualizer.core@default:default,org.eclipse.cdt.visualizer.ui@default:default,org.eclipse.cdt@default:default,org.eclipse.compare.core@default:default,org.eclipse.compare@default:default,org.eclipse.core.commands@default:default,org.eclipse.core.contenttype@default:default,org.eclipse.core.databinding.beans@default:default,org.eclipse.core.databinding.observable@default:default,org.eclipse.core.databinding.property@default:default,org.eclipse.core.databinding@default:default,org.eclipse.core.expressions@default:default,org.eclipse.core.externaltools@default:default,org.eclipse.core.filebuffers@default:default,org.eclipse.core.filesystem.linux.x86_64@default:false,org.eclipse.core.filesystem@default:default,org.eclipse.core.jobs@default:default,org.eclipse.core.net.linux.x86_64@default:false,org.eclipse.core.net@default:default,org.eclipse.core.resources@default:default,org.eclipse.core.runtime.compatibility.registry@default:false,org.eclipse.core.runtime.compatibility@default:default,org.eclipse.core.runtime@default:true,org.eclipse.core.variables@default:default,org.eclipse.debug.core@default:default,org.eclipse.debug.ui@default:default,org.eclipse.draw2d.doc.isv@default:default,org.eclipse.draw2d@default:default,org.eclipse.e4.core.commands@default:default,org.eclipse.e4.core.contexts@default:default,org.eclipse.e4.core.di.extensions@default:default,org.eclipse.e4.core.di@default:default,org.eclipse.e4.core.services@default:default,org.eclipse.e4.ui.bindings@default:default,org.eclipse.e4.ui.css.core@default:default,org.eclipse.e4.ui.css.swt.theme@default:default,org.eclipse.e4.ui.css.swt@default:default,org.eclipse.e4.ui.di@default:default,org.eclipse.e4.ui.model.workbench@default:default,org.eclipse.e4.ui.services@default:default,org.eclipse.e4.ui.widgets@default:default,org.eclipse.e4.ui.workbench.addons.swt@default:default,org.eclipse.e4.ui.workbench.renderers.swt@default:default,org.eclipse.e4.ui.workbench.swt@default:default,org.eclipse.e4.ui.workbench3@default:default,org.eclipse.e4.ui.workbench@default:default,org.eclipse.ecf.filetransfer@default:default,org.eclipse.ecf.identity@default:default,org.eclipse.ecf.provider.filetransfer.httpclient4.ssl@default:false,org.eclipse.ecf.provider.filetransfer.httpclient4@default:default,org.eclipse.ecf.provider.filetransfer.ssl@default:false,org.eclipse.ecf.provider.filetransfer@default:default,org.eclipse.ecf.ssl@default:false,org.eclipse.ecf@default:default,org.eclipse.emf.activities@default:default,org.eclipse.emf.ant@default:default,org.eclipse.emf.cheatsheets@default:default,org.eclipse.emf.codegen.ecore.ui@default:default,org.eclipse.emf.codegen.ecore@default:default,org.eclipse.emf.codegen.ui@default:default,org.eclipse.emf.codegen@default:default,org.eclipse.emf.common.ui@default:default,org.eclipse.emf.common@default:default,org.eclipse.emf.converter@default:default,org.eclipse.emf.databinding.edit@default:default,org.eclipse.emf.databinding@default:default,org.eclipse.emf.doc@default:default,org.eclipse.emf.ecore.change.edit@default:default,org.eclipse.emf.ecore.change@default:default,org.eclipse.emf.ecore.edit@default:default,org.eclipse.emf.ecore.editor@default:default,org.eclipse.emf.ecore.xmi@default:default,org.eclipse.emf.ecore@default:default,org.eclipse.emf.edit.ui@default:default,org.eclipse.emf.edit@default:default,org.eclipse.emf.example.installer@default:default,org.eclipse.emf.examples.databinding.project.core.model@default:default,org.eclipse.emf.examples.databinding.project.core@default:default,org.eclipse.emf.examples.databinding.project.ui.rcp@default:default,org.eclipse.emf.examples.generator.validator@default:default,org.eclipse.emf.examples.jet.article2@default:default,org.eclipse.emf.examples.library.edit@default:default,org.eclipse.emf.examples.library.editor@default:default,org.eclipse.emf.examples.library@default:default,org.eclipse.emf.examples@default:default,org.eclipse.emf.exporter.html@default:default,org.eclipse.emf.exporter@default:default,org.eclipse.emf.importer.ecore@default:default,org.eclipse.emf.importer.java@default:default,org.eclipse.emf.importer.rose@default:default,org.eclipse.emf.importer@default:default,org.eclipse.emf.java.edit@default:default,org.eclipse.emf.java.editor@default:default,org.eclipse.emf.java@default:default,org.eclipse.emf.mapping.ecore.editor@default:default,org.eclipse.emf.mapping.ecore2ecore.editor@default:default,org.eclipse.emf.mapping.ecore2ecore@default:default,org.eclipse.emf.mapping.ecore2xml.ui@default:default,org.eclipse.emf.mapping.ecore2xml@default:default,org.eclipse.emf.mapping.ecore@default:default,org.eclipse.emf.mapping.ui@default:default,org.eclipse.emf.mapping.xsd2ecore.editor@default:default,org.eclipse.emf.mapping.xsd2ecore@default:default,org.eclipse.emf.mapping@default:default,org.eclipse.emf@default:default,org.eclipse.equinox.app@default:default,org.eclipse.equinox.bidi@default:default,org.eclipse.equinox.common@2:true,org.eclipse.equinox.console@default:default,org.eclipse.equinox.ds@1:true,org.eclipse.equinox.event@default:default,org.eclipse.equinox.frameworkadmin.equinox@default:default,org.eclipse.equinox.frameworkadmin@default:default,org.eclipse.equinox.http.jetty@default:default,org.eclipse.equinox.http.registry@default:default,org.eclipse.equinox.http.servlet@default:default,org.eclipse.equinox.jsp.jasper.registry@default:default,org.eclipse.equinox.jsp.jasper@default:default,org.eclipse.equinox.launcher.gtk.linux.x86_64@default:false,org.eclipse.equinox.launcher@default:default,org.eclipse.equinox.p2.artifact.repository@default:default,org.eclipse.equinox.p2.console@default:default,org.eclipse.equinox.p2.core@default:default,org.eclipse.equinox.p2.director.app@default:default,org.eclipse.equinox.p2.director@default:default,org.eclipse.equinox.p2.directorywatcher@default:default,org.eclipse.equinox.p2.engine@default:default,org.eclipse.equinox.p2.extensionlocation@default:default,org.eclipse.equinox.p2.garbagecollector@default:default,org.eclipse.equinox.p2.jarprocessor@default:default,org.eclipse.equinox.p2.metadata.repository@default:default,org.eclipse.equinox.p2.metadata@default:default,org.eclipse.equinox.p2.operations@default:default,org.eclipse.equinox.p2.publisher.eclipse@default:default,org.eclipse.equinox.p2.publisher@default:default,org.eclipse.equinox.p2.ql@default:default,org.eclipse.equinox.p2.reconciler.dropins@default:default,org.eclipse.equinox.p2.repository.tools@default:default,org.eclipse.equinox.p2.repository@default:default,org.eclipse.equinox.p2.touchpoint.eclipse@default:default,org.eclipse.equinox.p2.touchpoint.natives@default:default,org.eclipse.equinox.p2.transport.ecf@default:default,org.eclipse.equinox.p2.ui.importexport@default:default,org.eclipse.equinox.p2.ui.sdk.scheduler@default:default,org.eclipse.equinox.p2.ui.sdk@default:default,org.eclipse.equinox.p2.ui@default:default,org.eclipse.equinox.p2.updatechecker@default:default,org.eclipse.equinox.p2.updatesite@default:default,org.eclipse.equinox.preferences@default:default,org.eclipse.equinox.registry@default:default,org.eclipse.equinox.security.ui@default:default,org.eclipse.equinox.security@default:default,org.eclipse.equinox.simpleconfigurator.manipulator@default:default,org.eclipse.equinox.simpleconfigurator@1:true,org.eclipse.equinox.util@default:default,org.eclipse.gef.doc.isv@default:default,org.eclipse.gef.examples.flow@default:default,org.eclipse.gef.examples.logic@default:default,org.eclipse.gef.examples.shapes@default:default,org.eclipse.gef.examples.text@default:default,org.eclipse.gef.examples.ui.pde@default:default,org.eclipse.gef@default:default,org.eclipse.help.base@default:default,org.eclipse.help.ui@default:default,org.eclipse.help.webapp@default:default,org.eclipse.help@default:default,org.eclipse.jdt.annotation@default:default,org.eclipse.jdt.apt.core@default:default,org.eclipse.jdt.apt.pluggable.core@default:default,org.eclipse.jdt.apt.ui@default:default,org.eclipse.jdt.compiler.apt@default:false,org.eclipse.jdt.compiler.tool@default:false,org.eclipse.jdt.core.manipulation@default:default,org.eclipse.jdt.core@default:default,org.eclipse.jdt.debug.ui@default:default,org.eclipse.jdt.debug@default:default,org.eclipse.jdt.doc.isv@default:default,org.eclipse.jdt.doc.user@default:default,org.eclipse.jdt.junit.core@default:default,org.eclipse.jdt.junit.runtime@default:default,org.eclipse.jdt.junit4.runtime@default:default,org.eclipse.jdt.junit@default:default,org.eclipse.jdt.launching@default:default,org.eclipse.jdt.ui@default:default,org.eclipse.jdt@default:default,org.eclipse.jem.beaninfo.vm.common@default:default,org.eclipse.jem.beaninfo.vm@default:default,org.eclipse.jem.beaninfo@default:default,org.eclipse.jem.proxy@default:default,org.eclipse.jem.util@default:default,org.eclipse.jem.workbench@default:default,org.eclipse.jem@default:default,org.eclipse.jetty.continuation@default:default,org.eclipse.jetty.http@default:default,org.eclipse.jetty.io@default:default,org.eclipse.jetty.security@default:default,org.eclipse.jetty.server@default:default,org.eclipse.jetty.servlet@default:default,org.eclipse.jetty.util@default:default,org.eclipse.jetty.webapp@default:default,org.eclipse.jetty.xml@default:default,org.eclipse.jface.databinding@default:default,org.eclipse.jface.text@default:default,org.eclipse.jface@default:default,org.eclipse.jpt.common.branding@default:default,org.eclipse.jpt.common.core@default:default,org.eclipse.jpt.common.eclipselink.branding@default:default,org.eclipse.jpt.common.eclipselink.core@default:default,org.eclipse.jpt.common.ui@default:default,org.eclipse.jpt.common.utility@default:default,org.eclipse.jpt.dbws.eclipselink.branding@default:default,org.eclipse.jpt.dbws.eclipselink.core.gen@default:default,org.eclipse.jpt.dbws.eclipselink.ui@default:default,org.eclipse.jpt.doc.isv@default:default,org.eclipse.jpt.doc.user@default:default,org.eclipse.jpt.jaxb.branding@default:default,org.eclipse.jpt.jaxb.core.schemagen@default:default,org.eclipse.jpt.jaxb.core@default:default,org.eclipse.jpt.jaxb.eclipselink.branding@default:default,org.eclipse.jpt.jaxb.eclipselink.core.schemagen@default:default,org.eclipse.jpt.jaxb.eclipselink.core@default:default,org.eclipse.jpt.jaxb.eclipselink.ui@default:default,org.eclipse.jpt.jaxb.ui@default:default,org.eclipse.jpt.jpa.annotate@default:default,org.eclipse.jpt.jpa.branding@default:default,org.eclipse.jpt.jpa.core@default:default,org.eclipse.jpt.jpa.db.ui@default:default,org.eclipse.jpt.jpa.db@default:default,org.eclipse.jpt.jpa.eclipselink.branding@default:default,org.eclipse.jpt.jpa.eclipselink.core.ddlgen@default:default,org.eclipse.jpt.jpa.eclipselink.core@default:default,org.eclipse.jpt.jpa.eclipselink.ui@default:default,org.eclipse.jpt.jpa.gen@default:default,org.eclipse.jpt.jpa.ui@default:default,org.eclipse.jpt.jpadiagrameditor.branding@default:default,org.eclipse.jpt.jpadiagrameditor.doc.user@default:default,org.eclipse.jpt.jpadiagrameditor.ui@default:default,org.eclipse.jsch.core@default:default,org.eclipse.jsch.ui@default:default,org.eclipse.jsf.branding@default:default,org.eclipse.jst.common.annotations.controller@default:default,org.eclipse.jst.common.annotations.core@default:default,org.eclipse.jst.common.annotations.ui@default:default,org.eclipse.jst.common.fproj.enablement.jdt.sdk@default:default,org.eclipse.jst.common.frameworks@default:default,org.eclipse.jst.common.project.facet.core@default:default,org.eclipse.jst.common.project.facet.ui@default:default,org.eclipse.jst.common.ui@default:default,org.eclipse.jst.ejb.doc.user@default:default,org.eclipse.jst.ejb.ui.infopop@default:default,org.eclipse.jst.ejb.ui@default:default,org.eclipse.jst.j2ee.core@default:default,org.eclipse.jst.j2ee.doc.user@default:default,org.eclipse.jst.j2ee.ejb.annotation.model@default:default,org.eclipse.jst.j2ee.ejb.annotations.emitter@default:default,org.eclipse.jst.j2ee.ejb.annotations.ui@default:default,org.eclipse.jst.j2ee.ejb.annotations.xdoclet@default:default,org.eclipse.jst.j2ee.ejb@default:default,org.eclipse.jst.j2ee.infopop@default:default,org.eclipse.jst.j2ee.jca.ui@default:default,org.eclipse.jst.j2ee.jca@default:default,org.eclipse.jst.j2ee.navigator.ui@default:default,org.eclipse.jst.j2ee.ui@default:default,org.eclipse.jst.j2ee.web@default:default,org.eclipse.jst.j2ee.webservice.ui@default:default,org.eclipse.jst.j2ee.webservice@default:default,org.eclipse.jst.j2ee.xdoclet.runtime@default:default,org.eclipse.jst.j2ee@default:default,org.eclipse.jst.jee.ejb@default:default,org.eclipse.jst.jee.ui@default:default,org.eclipse.jst.jee.web@default:default,org.eclipse.jst.jee@default:default,org.eclipse.jst.jsf.apache.trinidad.tagsupport@default:default,org.eclipse.jst.jsf.common.runtime@default:default,org.eclipse.jst.jsf.common.ui@default:default,org.eclipse.jst.jsf.common@default:default,org.eclipse.jst.jsf.core@default:default,org.eclipse.jst.jsf.doc.dev@default:default,org.eclipse.jst.jsf.doc.user@default:default,org.eclipse.jst.jsf.facelet.core@default:default,org.eclipse.jst.jsf.facelet.ui@default:default,org.eclipse.jst.jsf.facesconfig.ui@default:default,org.eclipse.jst.jsf.facesconfig@default:default,org.eclipse.jst.jsf.standard.tagsupport@default:default,org.eclipse.jst.jsf.ui@default:default,org.eclipse.jst.jsp.core@default:default,org.eclipse.jst.jsp.ui.infopop@default:default,org.eclipse.jst.jsp.ui@default:default,org.eclipse.jst.pagedesigner.jsf.ui@default:default,org.eclipse.jst.pagedesigner.jsp.core@default:default,org.eclipse.jst.pagedesigner@default:default,org.eclipse.jst.server.core@default:default,org.eclipse.jst.server.generic.core@default:default,org.eclipse.jst.server.generic.jboss@default:default,org.eclipse.jst.server.generic.jonas@default:default,org.eclipse.jst.server.generic.ui@default:default,org.eclipse.jst.server.preview.adapter@default:default,org.eclipse.jst.server.tomcat.core@default:default,org.eclipse.jst.server.tomcat.ui@default:default,org.eclipse.jst.server.ui.doc.user@default:default,org.eclipse.jst.server.ui.infopop@default:default,org.eclipse.jst.server.ui@default:default,org.eclipse.jst.servlet.ui.infopop@default:default,org.eclipse.jst.servlet.ui@default:default,org.eclipse.jst.standard.schemas@default:default,org.eclipse.jst.ws.annotations.core@default:default,org.eclipse.jst.ws.axis.consumption.core@default:default,org.eclipse.jst.ws.axis.consumption.ui@default:default,org.eclipse.jst.ws.axis.creation.ui@default:default,org.eclipse.jst.ws.axis.infopop@default:default,org.eclipse.jst.ws.axis.ui.doc.user@default:default,org.eclipse.jst.ws.axis2.consumption.core@default:default,org.eclipse.jst.ws.axis2.consumption.ui@default:default,org.eclipse.jst.ws.axis2.core@default:default,org.eclipse.jst.ws.axis2.creation.core@default:default,org.eclipse.jst.ws.axis2.creation.ui@default:default,org.eclipse.jst.ws.axis2.ui.doc.user@default:default,org.eclipse.jst.ws.axis2.ui@default:default,org.eclipse.jst.ws.consumption.infopop@default:default,org.eclipse.jst.ws.consumption.ui.doc.user@default:default,org.eclipse.jst.ws.consumption.ui@default:default,org.eclipse.jst.ws.consumption@default:default,org.eclipse.jst.ws.creation.ejb.ui@default:default,org.eclipse.jst.ws.creation.ui@default:default,org.eclipse.jst.ws.cxf.consumption.core@default:default,org.eclipse.jst.ws.cxf.consumption.ui@default:default,org.eclipse.jst.ws.cxf.core@default:default,org.eclipse.jst.ws.cxf.creation.core@default:default,org.eclipse.jst.ws.cxf.creation.ui@default:default,org.eclipse.jst.ws.cxf.doc.user@default:default,org.eclipse.jst.ws.cxf.ui@default:default,org.eclipse.jst.ws.doc.user@default:default,org.eclipse.jst.ws.infopop@default:default,org.eclipse.jst.ws.jaxb.core@default:default,org.eclipse.jst.ws.jaxrs.core@default:default,org.eclipse.jst.ws.jaxrs.ui@default:default,org.eclipse.jst.ws.jaxws.core@default:default,org.eclipse.jst.ws.jaxws.doc.isv@default:default,org.eclipse.jst.ws.jaxws.doc.user@default:default,org.eclipse.jst.ws.jaxws.dom.doc.isv@default:default,org.eclipse.jst.ws.jaxws.dom.integration@default:default,org.eclipse.jst.ws.jaxws.dom.runtime@default:default,org.eclipse.jst.ws.jaxws.dom.ui@default:default,org.eclipse.jst.ws.jaxws.ui@default:default,org.eclipse.jst.ws.jaxws.utils@default:default,org.eclipse.jst.ws.uddiregistry@default:default,org.eclipse.jst.ws.ui@default:default,org.eclipse.jst.ws@default:default,org.eclipse.linuxtools.cdt.autotools.core@default:default,org.eclipse.ltk.core.refactoring@default:default,org.eclipse.ltk.ui.refactoring@default:default,org.eclipse.osgi.services@default:default,org.eclipse.osgi.util@default:default,org.eclipse.osgi@-1:true,org.eclipse.persistence.antlr@default:default,org.eclipse.persistence.asm@default:default,org.eclipse.persistence.core@default:default,org.eclipse.persistence.dbws.builder@default:default,org.eclipse.persistence.dbws@default:default,org.eclipse.persistence.jpa.jpql@default:default,org.eclipse.persistence.jpa@default:default,org.eclipse.persistence.moxy@default:default,org.eclipse.platform.doc.user@default:default,org.eclipse.platform@default:default,org.eclipse.rcp@default:default,org.eclipse.search@default:default,org.eclipse.servertools.doc.isv@default:default,org.eclipse.swt.gtk.linux.x86_64@default:false,org.eclipse.swt@default:default,org.eclipse.team.core@default:default,org.eclipse.team.ui@default:default,org.eclipse.text@default:default,org.eclipse.ui.browser@default:default,org.eclipse.ui.cheatsheets@default:default,org.eclipse.ui.console@default:default,org.eclipse.ui.editors@default:default,org.eclipse.ui.externaltools@default:default,org.eclipse.ui.forms@default:default,org.eclipse.ui.ide.application@default:default,org.eclipse.ui.ide@default:default,org.eclipse.ui.intro.universal@default:default,org.eclipse.ui.intro@default:default,org.eclipse.ui.navigator.resources@default:default,org.eclipse.ui.navigator@default:default,org.eclipse.ui.net@default:default,org.eclipse.ui.views.properties.tabbed@default:default,org.eclipse.ui.views@default:default,org.eclipse.ui.workbench.texteditor@default:default,org.eclipse.ui.workbench@default:default,org.eclipse.ui@default:default,org.eclipse.update.configurator@3:true,org.eclipse.wst.command.env.core@default:default,org.eclipse.wst.command.env.doc.user@default:default,org.eclipse.wst.command.env.infopop@default:default,org.eclipse.wst.command.env.ui@default:default,org.eclipse.wst.command.env@default:default,org.eclipse.wst.common.api.doc@default:default,org.eclipse.wst.common.core@default:default,org.eclipse.wst.common.emf@default:default,org.eclipse.wst.common.emfworkbench.integration@default:default,org.eclipse.wst.common.environment@default:default,org.eclipse.wst.common.fproj.sdk@default:default,org.eclipse.wst.common.frameworks.ui@default:default,org.eclipse.wst.common.frameworks@default:default,org.eclipse.wst.common.infopop@default:default,org.eclipse.wst.common.modulecore.ui@default:default,org.eclipse.wst.common.modulecore@default:default,org.eclipse.wst.common.project.facet.core@default:default,org.eclipse.wst.common.project.facet.doc.api@default:default,org.eclipse.wst.common.project.facet.ui@default:default,org.eclipse.wst.common.snippets@default:default,org.eclipse.wst.common.ui@default:default,org.eclipse.wst.common.uriresolver@default:default,org.eclipse.wst.css.core@default:default,org.eclipse.wst.css.ui@default:default,org.eclipse.wst.doc.user@default:default,org.eclipse.wst.dtd.core@default:default,org.eclipse.wst.dtd.ui.infopop@default:default,org.eclipse.wst.dtd.ui@default:default,org.eclipse.wst.dtdeditor.doc.user@default:default,org.eclipse.wst.html.core@default:default,org.eclipse.wst.html.ui.infopop@default:default,org.eclipse.wst.html.ui@default:default,org.eclipse.wst.internet.cache@default:default,org.eclipse.wst.internet.monitor.core@default:default,org.eclipse.wst.internet.monitor.ui@default:default,org.eclipse.wst.jsdt.core@default:default,org.eclipse.wst.jsdt.debug.core@default:default,org.eclipse.wst.jsdt.debug.crossfire@default:default,org.eclipse.wst.jsdt.debug.rhino.debugger@default:default,org.eclipse.wst.jsdt.debug.rhino.ui@default:default,org.eclipse.wst.jsdt.debug.rhino@default:default,org.eclipse.wst.jsdt.debug.transport@default:default,org.eclipse.wst.jsdt.debug.ui@default:default,org.eclipse.wst.jsdt.doc@default:default,org.eclipse.wst.jsdt.manipulation@default:default,org.eclipse.wst.jsdt.support.firefox@default:default,org.eclipse.wst.jsdt.support.ie@default:default,org.eclipse.wst.jsdt.ui@default:default,org.eclipse.wst.jsdt.web.core@default:default,org.eclipse.wst.jsdt.web.support.jsp@default:default,org.eclipse.wst.jsdt.web.ui@default:default,org.eclipse.wst.server.core@default:default,org.eclipse.wst.server.discovery@default:default,org.eclipse.wst.server.http.core@default:default,org.eclipse.wst.server.http.ui@default:default,org.eclipse.wst.server.preview.adapter@default:default,org.eclipse.wst.server.preview@default:default,org.eclipse.wst.server.ui.doc.user@default:default,org.eclipse.wst.server.ui.infopop@default:default,org.eclipse.wst.server.ui@default:default,org.eclipse.wst.sse.core@default:default,org.eclipse.wst.sse.doc.user@default:default,org.eclipse.wst.sse.ui.infopop@default:default,org.eclipse.wst.sse.ui@default:default,org.eclipse.wst.standard.schemas@default:default,org.eclipse.wst.validation.doc.isv@default:default,org.eclipse.wst.validation.infopop@default:default,org.eclipse.wst.validation.ui@default:default,org.eclipse.wst.validation@default:default,org.eclipse.wst.web.ui.infopop@default:default,org.eclipse.wst.web.ui@default:default,org.eclipse.wst.web@default:default,org.eclipse.wst.webtools.doc.user@default:default,org.eclipse.wst.ws.api.doc@default:default,org.eclipse.wst.ws.explorer@default:default,org.eclipse.wst.ws.infopop@default:default,org.eclipse.wst.ws.parser@default:default,org.eclipse.wst.ws.service.policy.ui@default:default,org.eclipse.wst.ws.service.policy@default:default,org.eclipse.wst.ws.ui@default:default,org.eclipse.wst.ws@default:default,org.eclipse.wst.wsdl.doc.isv@default:default,org.eclipse.wst.wsdl.ui.doc.user@default:default,org.eclipse.wst.wsdl.ui@default:default,org.eclipse.wst.wsdl.validation@default:default,org.eclipse.wst.wsdl@default:default,org.eclipse.wst.wsi.ui.doc.user@default:default,org.eclipse.wst.wsi.ui@default:default,org.eclipse.wst.wsi@default:default,org.eclipse.wst.xml.core@default:default,org.eclipse.wst.xml.ui.infopop@default:default,org.eclipse.wst.xml.ui@default:default,org.eclipse.wst.xml.xpath.core@default:default,org.eclipse.wst.xml.xpath.ui@default:default,org.eclipse.wst.xml.xpath2.processor.doc.user@default:default,org.eclipse.wst.xml.xpath2.processor@default:default,org.eclipse.wst.xml.xpath2.wtptypes@default:default,org.eclipse.wst.xml.xpath2@default:default,org.eclipse.wst.xmleditor.doc.user@default:default,org.eclipse.wst.xsd.core@default:default,org.eclipse.wst.xsd.ui@default:default,org.eclipse.wst.xsdeditor.doc.user@default:default,org.eclipse.wst.xsl.core@default:default,org.eclipse.wst.xsl.debug.ui@default:default,org.eclipse.wst.xsl.doc@default:default,org.eclipse.wst.xsl.exslt.core@default:default,org.eclipse.wst.xsl.exslt.ui@default:default,org.eclipse.wst.xsl.jaxp.debug.ui@default:default,org.eclipse.wst.xsl.jaxp.debug@default:default,org.eclipse.wst.xsl.jaxp.launching@default:default,org.eclipse.wst.xsl.launching@default:default,org.eclipse.wst.xsl.saxon@default:default,org.eclipse.wst.xsl.sdk.documentation@default:default,org.eclipse.wst.xsl.ui@default:default,org.eclipse.wst.xsl.xalan@default:default,org.eclipse.wst.xsl@default:default,org.eclipse.xsd.cheatsheets@default:default,org.eclipse.xsd.doc@default:default,org.eclipse.xsd.ecore.converter@default:default,org.eclipse.xsd.ecore.exporter@default:default,org.eclipse.xsd.ecore.importer@default:default,org.eclipse.xsd.edit@default:default,org.eclipse.xsd.editor@default:default,org.eclipse.xsd.example.installer@default:default,org.eclipse.xsd.mapping.editor@default:default,org.eclipse.xsd.mapping@default:default,org.eclipse.xsd@default:default,org.eclipse.zest.core@default:default,org.eclipse.zest.doc.isv@default:default,org.eclipse.zest.layouts@default:default,org.freemarker.freemarker@default:default,org.hamcrest.core@default:default,org.jdom@default:default,org.junit@default:default,org.mozilla.javascript@default:default,org.ow2.asm.analysis@default:default,org.ow2.asm.tree@default:default,org.ow2.asm@default:default,org.sat4j.core@default:default,org.sat4j.pb@default:default,org.uddi4j@default:default,org.w3c.css.sac@default:default,org.w3c.dom.smil@default:default,org.w3c.dom.svg@default:default"/>
-<stringAttribute key="selected_workspace_plugins" value="com.android.ide.eclipse.adt.package@default:default,com.android.ide.eclipse.adt@default:default,com.android.ide.eclipse.base@default:default,com.android.ide.eclipse.ddms@default:default,com.android.ide.eclipse.gldebugger.tests@default:default,com.android.ide.eclipse.gldebugger@default:default,com.android.ide.eclipse.hierarchyviewer@default:default,com.android.ide.eclipse.ndk@default:default,com.android.ide.eclipse.pdt@default:default,com.android.ide.eclipse.tests@default:false,com.android.ide.eclipse.traceview@default:default,overlay.com.android.ide.eclipse.adt.overlay@default:default"/>
-<booleanAttribute key="show_selected_only" value="false"/>
-<stringAttribute key="templateConfig" value="${target_home}/configuration/config.ini"/>
-<booleanAttribute key="tracing" value="false"/>
-<booleanAttribute key="useCustomFeatures" value="false"/>
-<booleanAttribute key="useDefaultConfig" value="true"/>
-<booleanAttribute key="useDefaultConfigArea" value="true"/>
-<booleanAttribute key="useProduct" value="true"/>
-</launchConfiguration>
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/build.properties b/eclipse/plugins/com.android.ide.eclipse.adt/build.properties
deleted file mode 100644
index 32d7d7e75..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/build.properties
+++ /dev/null
@@ -1,12 +0,0 @@
-bin.includes = plugin.xml,\
- META-INF/,\
- icons/,\
- .,\
- libs/,\
- templates/,\
- about.ini,\
- about.properties,\
- NOTICE,\
- about.html
-source.. = src/
-output.. = bin/
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/AbsoluteLayout.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/AbsoluteLayout.png
deleted file mode 100644
index c7d23811b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/AbsoluteLayout.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/AdapterViewFlipper.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/AdapterViewFlipper.png
deleted file mode 100644
index 89f8c638d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/AdapterViewFlipper.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/AnalogClock.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/AnalogClock.png
deleted file mode 100644
index 163939cc0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/AnalogClock.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/AutoCompleteTextView.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/AutoCompleteTextView.png
deleted file mode 100644
index ae7c2844b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/AutoCompleteTextView.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/Button.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/Button.png
deleted file mode 100644
index 3b576c73c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/Button.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/CalendarView.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/CalendarView.png
deleted file mode 100644
index 033c51ca7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/CalendarView.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/CheckBox.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/CheckBox.png
deleted file mode 100644
index 1321e1ebf..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/CheckBox.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/CheckedTextView.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/CheckedTextView.png
deleted file mode 100644
index a8c5f6164..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/CheckedTextView.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/Chronometer.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/Chronometer.png
deleted file mode 100644
index 563f30ccd..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/Chronometer.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/DatePicker.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/DatePicker.png
deleted file mode 100644
index 107529e7a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/DatePicker.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/DialerFilter.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/DialerFilter.png
deleted file mode 100644
index 41652eab9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/DialerFilter.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/DigitalClock.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/DigitalClock.png
deleted file mode 100644
index d3b874019..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/DigitalClock.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/EditText.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/EditText.png
deleted file mode 100644
index bb292ba7d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/EditText.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ExpandableListView.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/ExpandableListView.png
deleted file mode 100644
index fd1069797..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ExpandableListView.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/FrameLayout.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/FrameLayout.png
deleted file mode 100644
index 66bd0421c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/FrameLayout.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/Gallery.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/Gallery.png
deleted file mode 100644
index 36b8ff625..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/Gallery.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/GestureOverlayView.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/GestureOverlayView.png
deleted file mode 100644
index 40acdbfc2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/GestureOverlayView.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/GridLayout.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/GridLayout.png
deleted file mode 100644
index ca64e8c46..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/GridLayout.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/GridView.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/GridView.png
deleted file mode 100644
index 33ae3cb80..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/GridView.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/HorizontalScrollView.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/HorizontalScrollView.png
deleted file mode 100644
index fa142cb90..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/HorizontalScrollView.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ImageButton.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/ImageButton.png
deleted file mode 100644
index 01ef2573e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ImageButton.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ImageSwitcher.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/ImageSwitcher.png
deleted file mode 100644
index c089a2aca..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ImageSwitcher.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ImageView.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/ImageView.png
deleted file mode 100644
index 1f0ff05a4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ImageView.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/LinearLayout.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/LinearLayout.png
deleted file mode 100644
index 6d6a794ac..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/LinearLayout.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ListView.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/ListView.png
deleted file mode 100644
index 09aaea9dd..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ListView.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/MediaController.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/MediaController.png
deleted file mode 100644
index ef30b340a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/MediaController.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/MultiAutoCompleteTextView.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/MultiAutoCompleteTextView.png
deleted file mode 100644
index 94b823f17..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/MultiAutoCompleteTextView.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/NumberPicker.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/NumberPicker.png
deleted file mode 100644
index 755706748..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/NumberPicker.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ProgressBar.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/ProgressBar.png
deleted file mode 100644
index 23a98fce5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ProgressBar.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/QuickContactBadge.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/QuickContactBadge.png
deleted file mode 100644
index b8a7a7710..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/QuickContactBadge.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/RadioButton.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/RadioButton.png
deleted file mode 100644
index 8e55fa7a1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/RadioButton.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/RadioGroup.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/RadioGroup.png
deleted file mode 100644
index 1070b2422..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/RadioGroup.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/RatingBar.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/RatingBar.png
deleted file mode 100644
index 6921212fd..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/RatingBar.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/RelativeLayout.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/RelativeLayout.png
deleted file mode 100644
index 976e55f29..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/RelativeLayout.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ScrollView.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/ScrollView.png
deleted file mode 100644
index 618f082d5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ScrollView.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/SearchView.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/SearchView.png
deleted file mode 100644
index 2b45fc240..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/SearchView.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/SeekBar.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/SeekBar.png
deleted file mode 100644
index eeffbca1c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/SeekBar.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/SlidingDrawer.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/SlidingDrawer.png
deleted file mode 100644
index af1e774c6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/SlidingDrawer.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/Space.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/Space.png
deleted file mode 100644
index 28b2553dc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/Space.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/Spinner.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/Spinner.png
deleted file mode 100644
index 34cdc7cf9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/Spinner.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/StackView.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/StackView.png
deleted file mode 100644
index 203bafc61..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/StackView.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/SurfaceView.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/SurfaceView.png
deleted file mode 100644
index 40b568530..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/SurfaceView.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/Switch.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/Switch.png
deleted file mode 100644
index 45df97907..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/Switch.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/TabHost.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/TabHost.png
deleted file mode 100644
index 9153a8847..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/TabHost.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/TabWidget.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/TabWidget.png
deleted file mode 100644
index 7992fa2d3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/TabWidget.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/TableLayout.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/TableLayout.png
deleted file mode 100644
index 0a4133939..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/TableLayout.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/TableRow.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/TableRow.png
deleted file mode 100644
index 58aeabb7c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/TableRow.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/TextSwitcher.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/TextSwitcher.png
deleted file mode 100644
index 6de1d92e1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/TextSwitcher.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/TextView.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/TextView.png
deleted file mode 100644
index 5eec7649c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/TextView.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/TextureView.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/TextureView.png
deleted file mode 100644
index 353b6b721..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/TextureView.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/TimePicker.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/TimePicker.png
deleted file mode 100644
index 5115f6df7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/TimePicker.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ToggleButton.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/ToggleButton.png
deleted file mode 100644
index 7ee1265ee..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ToggleButton.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/TwoLineListItem.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/TwoLineListItem.png
deleted file mode 100644
index 1000979a6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/TwoLineListItem.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/VerticalLinearLayout.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/VerticalLinearLayout.png
deleted file mode 100644
index 1d676209e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/VerticalLinearLayout.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/VideoView.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/VideoView.png
deleted file mode 100644
index 509b0a33e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/VideoView.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/View.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/View.png
deleted file mode 100644
index f07944f73..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/View.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ViewAnimator.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/ViewAnimator.png
deleted file mode 100644
index 7d6bea602..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ViewAnimator.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ViewFlipper.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/ViewFlipper.png
deleted file mode 100644
index 300ed2d73..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ViewFlipper.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ViewStub.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/ViewStub.png
deleted file mode 100644
index e5036ff27..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ViewStub.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ViewSwitcher.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/ViewSwitcher.png
deleted file mode 100644
index adc0abe98..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ViewSwitcher.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/WebView.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/WebView.png
deleted file mode 100644
index 90b3c06c5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/WebView.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ZoomButton.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/ZoomButton.png
deleted file mode 100644
index 90e0d8b93..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ZoomButton.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ZoomControls.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/ZoomControls.png
deleted file mode 100644
index 7928c65cf..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ZoomControls.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/activity.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/activity.png
deleted file mode 100644
index 361236138..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/activity.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/add.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/add.png
deleted file mode 100644
index eefc2ca30..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/add.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/android-32.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/android-32.png
deleted file mode 100644
index 4e0cc138d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/android-32.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/android-64.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/android-64.png
deleted file mode 100644
index 2c6f149a5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/android-64.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/android.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/android.png
deleted file mode 100644
index a8dc35ec4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/android.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/android_app.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/android_app.png
deleted file mode 100644
index 8ca377009..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/android_app.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/android_file.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/android_file.png
deleted file mode 100644
index be9b8e6b4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/android_file.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/android_project.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/android_project.png
deleted file mode 100644
index 5334568e6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/android_project.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/androidjunit.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/androidjunit.png
deleted file mode 100644
index 25826dce7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/androidjunit.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/attribute.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/attribute.png
deleted file mode 100644
index 04508ea32..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/attribute.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/avd_manager.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/avd_manager.png
deleted file mode 100644
index f8a173ca3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/avd_manager.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/az_sort.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/az_sort.png
deleted file mode 100644
index 5d92f76a4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/az_sort.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/bidi.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/bidi.png
deleted file mode 100644
index 4ffe131c5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/bidi.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/checker.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/checker.png
deleted file mode 100644
index 78908f47e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/checker.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/clipping.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/clipping.png
deleted file mode 100644
index 6f2a35f6a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/clipping.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/close.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/close.png
deleted file mode 100644
index a94d96cd1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/close.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/closed-folder.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/closed-folder.png
deleted file mode 100644
index 3fe8d8be6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/closed-folder.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/columns.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/columns.png
deleted file mode 100644
index 6b49eae2b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/columns.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/components_view.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/components_view.png
deleted file mode 100644
index 9f9755f5a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/components_view.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/customView.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/customView.png
deleted file mode 100644
index 0ff48d35d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/customView.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/default_template.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/default_template.png
deleted file mode 100644
index ddede69f5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/default_template.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/delete.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/delete.png
deleted file mode 100644
index db5fab8e4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/delete.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/dimension.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/dimension.png
deleted file mode 100644
index 10057c88a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/dimension.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/display.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/display.png
deleted file mode 100644
index 8831f8977..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/display.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/dockmode.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/dockmode.png
deleted file mode 100644
index 71d1804f1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/dockmode.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/down.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/down.png
deleted file mode 100644
index 162e736d4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/down.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/dpi.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/dpi.png
deleted file mode 100644
index fae5e96d7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/dpi.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/draw9patch-16.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/draw9patch-16.png
deleted file mode 100644
index cc080e798..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/draw9patch-16.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/editPreview.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/editPreview.png
deleted file mode 100644
index fd36133e5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/editPreview.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/editor_page_design.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/editor_page_design.png
deleted file mode 100644
index a19f3b0ee..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/editor_page_design.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/editor_page_source.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/editor_page_source.png
deleted file mode 100644
index 874cc1eeb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/editor_page_source.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/element.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/element.png
deleted file mode 100644
index e5cd0ca39..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/element.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/error-badge.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/error-badge.png
deleted file mode 100644
index 2e63c3589..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/error-badge.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/error.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/error.png
deleted file mode 100644
index 1eecf2c71..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/error.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/expandall-disabled.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/expandall-disabled.png
deleted file mode 100644
index 0897da3cd..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/expandall-disabled.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/expandall.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/expandall.png
deleted file mode 100644
index 7bdf83d32..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/expandall.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/explode.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/explode.png
deleted file mode 100644
index f25005521..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/explode.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/filter_advanced_properties.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/filter_advanced_properties.png
deleted file mode 100644
index 5f5b078a0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/filter_advanced_properties.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/flip_landscape.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/flip_landscape.png
deleted file mode 100644
index 4940ceaf6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/flip_landscape.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/flip_portrait.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/flip_portrait.png
deleted file mode 100644
index c28a9800f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/flip_portrait.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/fragment.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/fragment.png
deleted file mode 100644
index 4e315461e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/fragment.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/globe.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/globe.png
deleted file mode 100644
index 45e5e0554..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/globe.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/goto_definition.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/goto_definition.png
deleted file mode 100644
index daac537b4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/goto_definition.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/gradle.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/gradle.png
deleted file mode 100644
index 63ba4c2b4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/gradle.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/height.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/height.png
deleted file mode 100644
index 33c0774c0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/height.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-all-disabled.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-all-disabled.png
deleted file mode 100644
index 56f00988f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-all-disabled.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-all.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-all.png
deleted file mode 100644
index 581e32317..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-all.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-file-disabled.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-file-disabled.png
deleted file mode 100644
index e99569946..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-file-disabled.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-file.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-file.png
deleted file mode 100644
index 12d656d8c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-file.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-project-disabled.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-project-disabled.png
deleted file mode 100644
index 33e21a54a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-project-disabled.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-project.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-project.png
deleted file mode 100644
index d8e097590..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-project.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-this-disabled.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-this-disabled.png
deleted file mode 100644
index 05764504f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-this-disabled.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-this.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-this.png
deleted file mode 100644
index 3e66d8235..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ignore-this.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/include.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/include.png
deleted file mode 100644
index d8eecd95b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/include.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/keyboard.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/keyboard.png
deleted file mode 100644
index 7911a8553..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/keyboard.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/landscape.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/landscape.png
deleted file mode 100644
index 4ed5c2e82..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/landscape.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/language.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/language.png
deleted file mode 100644
index a727dd53d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/language.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint1.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint1.png
deleted file mode 100644
index f429164f1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint1.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint2.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint2.png
deleted file mode 100644
index 8434b78b1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint2.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint3.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint3.png
deleted file mode 100644
index 43ab63ed3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint3.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint4.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint4.png
deleted file mode 100644
index 67fee2d79..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint4.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint5.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint5.png
deleted file mode 100644
index 3d0c188ef..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint5.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint6.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint6.png
deleted file mode 100644
index 42a976735..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint6.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint7.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint7.png
deleted file mode 100644
index 743aabc57..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint7.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint8.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint8.png
deleted file mode 100644
index 927067a1f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint8.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint9.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint9.png
deleted file mode 100644
index 44e66a094..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint9.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint9p.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint9p.png
deleted file mode 100644
index 853ace904..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/lint9p.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/lintrun.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/lintrun.png
deleted file mode 100644
index d1a074b00..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/lintrun.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/lintview.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/lintview.png
deleted file mode 100644
index c22d68d73..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/lintview.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/mainLaunchTab.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/mainLaunchTab.png
deleted file mode 100644
index 2540fbbc0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/mainLaunchTab.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/match.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/match.png
deleted file mode 100644
index 7e939c2c0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/match.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/match_multiple.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/match_multiple.png
deleted file mode 100644
index 79ffc2d02..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/match_multiple.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/mcc.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/mcc.png
deleted file mode 100644
index 4dc95d7cf..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/mcc.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/merge.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/merge.png
deleted file mode 100644
index 18087bd13..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/merge.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/minimizePreview.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/minimizePreview.png
deleted file mode 100644
index 4ddc5401e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/minimizePreview.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/mnc.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/mnc.png
deleted file mode 100644
index aefffe4a7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/mnc.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/navpad.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/navpad.png
deleted file mode 100644
index c2bb79aad..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/navpad.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/newConfig.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/newConfig.png
deleted file mode 100644
index d6317df80..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/newConfig.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/newCustomView.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/newCustomView.png
deleted file mode 100644
index dc64f4f90..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/newCustomView.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/newJunit.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/newJunit.png
deleted file mode 100644
index e881e7907..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/newJunit.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/new_adt_project.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/new_adt_project.png
deleted file mode 100644
index 0f0e883f0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/new_adt_project.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/new_asset_set.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/new_asset_set.png
deleted file mode 100644
index 108dcb1bb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/new_asset_set.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/new_xml.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/new_xml.png
deleted file mode 100644
index 59e1891db..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/new_xml.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/newannotation.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/newannotation.png
deleted file mode 100644
index d2e4721fe..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/newannotation.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/nightmode.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/nightmode.png
deleted file mode 100644
index a04e4cf3b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/nightmode.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/open-folder.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/open-folder.png
deleted file mode 100644
index 8c4a2e1b7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/open-folder.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/options.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/options.png
deleted file mode 100644
index 01948a2d5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/options.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/orientation.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/orientation.png
deleted file mode 100644
index 53b5e6263..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/orientation.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/outline.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/outline.png
deleted file mode 100644
index dbfb63b87..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/outline.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/palette.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/palette.png
deleted file mode 100644
index fd7ca1c78..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/palette.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/portrait.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/portrait.png
deleted file mode 100644
index 378615308..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/portrait.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/properties_default.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/properties_default.png
deleted file mode 100644
index 5696a3109..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/properties_default.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/properties_view.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/properties_view.png
deleted file mode 100644
index 8df5d2d74..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/properties_view.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/quickfix-disabled.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/quickfix-disabled.png
deleted file mode 100644
index 262bdac91..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/quickfix-disabled.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/quickfix.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/quickfix.png
deleted file mode 100644
index a43319955..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/quickfix.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/quickfix_error.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/quickfix_error.png
deleted file mode 100644
index 92022eee4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/quickfix_error.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/quickfix_warning.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/quickfix_warning.png
deleted file mode 100644
index bfbde3714..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/quickfix_warning.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ratio.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/ratio.png
deleted file mode 100644
index 8bf07f2f1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/ratio.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/refresh.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/refresh.png
deleted file mode 100644
index 7cbebf415..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/refresh.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/refreshPreview.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/refreshPreview.png
deleted file mode 100644
index d10376378..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/refreshPreview.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/region.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/region.png
deleted file mode 100644
index 9608cd67d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/region.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/renderError.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/renderError.png
deleted file mode 100644
index 95be6414d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/renderError.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/requestFocus.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/requestFocus.png
deleted file mode 100644
index ed239d4b4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/requestFocus.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/restorePreview.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/restorePreview.png
deleted file mode 100644
index d6b3f32da..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/restorePreview.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/sdk_manager.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/sdk_manager.png
deleted file mode 100644
index 08ffda85b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/sdk_manager.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow-b.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow-b.png
deleted file mode 100644
index 68f4f4ba5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow-b.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow-bl.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow-bl.png
deleted file mode 100644
index ee7dbe846..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow-bl.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow-br.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow-br.png
deleted file mode 100644
index c45ad77f8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow-br.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow-r.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow-r.png
deleted file mode 100644
index 4af7a3330..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow-r.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow-tr.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow-tr.png
deleted file mode 100644
index 1fd0c7726..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow-tr.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow2-b.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow2-b.png
deleted file mode 100644
index 963973ea7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow2-b.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow2-bl.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow2-bl.png
deleted file mode 100644
index 761248777..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow2-bl.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow2-br.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow2-br.png
deleted file mode 100644
index 8e20252cb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow2-br.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow2-r.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow2-r.png
deleted file mode 100644
index 8e026f147..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow2-r.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow2-tr.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow2-tr.png
deleted file mode 100644
index 590373c95..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/shadow2-tr.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/size.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/size.png
deleted file mode 100644
index c8a82b071..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/size.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/sort_alpha.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/sort_alpha.png
deleted file mode 100644
index 112e05b3b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/sort_alpha.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/square.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/square.png
deleted file mode 100644
index 7cc8a4c6a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/square.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/swidth.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/swidth.png
deleted file mode 100644
index b74a68f40..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/swidth.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/text_input.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/text_input.png
deleted file mode 100644
index b4ddc874a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/text_input.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/themes.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/themes.png
deleted file mode 100644
index c96394cd8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/themes.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/touch.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/touch.png
deleted file mode 100644
index 65365765a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/touch.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/up.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/up.png
deleted file mode 100644
index fac118b83..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/up.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/version.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/version.png
deleted file mode 100644
index a8dc35ec4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/version.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/view_menu.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/view_menu.png
deleted file mode 100644
index 857510796..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/view_menu.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/warning-badge.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/warning-badge.png
deleted file mode 100644
index d71d6e317..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/warning-badge.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/warning.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/warning.png
deleted file mode 100644
index ca3b6ede8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/warning.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/width.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/width.png
deleted file mode 100644
index e5243fab3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/width.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/zoom100.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/zoom100.png
deleted file mode 100644
index b127559a1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/zoom100.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/zoomfit.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/zoomfit.png
deleted file mode 100644
index 242b24ae7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/zoomfit.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/zoomminus.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/zoomminus.png
deleted file mode 100644
index aa6409ea8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/zoomminus.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/zoomplus.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/zoomplus.png
deleted file mode 100644
index dbbd5c888..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/zoomplus.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/icons/zoomreal.png b/eclipse/plugins/com.android.ide.eclipse.adt/icons/zoomreal.png
deleted file mode 100644
index 2a020e033..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/icons/zoomreal.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/plugin.xml b/eclipse/plugins/com.android.ide.eclipse.adt/plugin.xml
deleted file mode 100644
index 5584914bf..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/plugin.xml
+++ /dev/null
@@ -1,1340 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<?eclipse version="3.2"?>
-<plugin>
- <extension
- id="com.android.ide.eclipse.common.xmlProblem"
- name="Android XML Format Problem"
- point="org.eclipse.core.resources.markers">
- <super type="org.eclipse.core.resources.problemmarker" />
- <super type="org.eclipse.core.resources.textmarker" />
- <persistent value="true" />
- </extension>
- <extension
- id="com.android.ide.eclipse.common.aaptProblem"
- name="Android AAPT Problem"
- point="org.eclipse.core.resources.markers">
- <super type="org.eclipse.core.resources.problemmarker" />
- <super type="org.eclipse.core.resources.textmarker" />
- <persistent value="true" />
- </extension>
- <extension
- id="com.android.ide.eclipse.common.aapt2Problem"
- name="Android AAPT Problem"
- point="org.eclipse.core.resources.markers">
- <super type="org.eclipse.core.resources.problemmarker" />
- <super type="org.eclipse.core.resources.textmarker" />
- <persistent value="true" />
- </extension>
- <extension
- id="com.android.ide.eclipse.common.aidlProblem"
- name="Android AIDL Problem"
- point="org.eclipse.core.resources.markers">
- <super type="org.eclipse.core.resources.problemmarker" />
- <super type="org.eclipse.core.resources.textmarker" />
- <persistent value="true" />
- </extension>
- <extension
- id="com.android.ide.eclipse.common.rsProblem"
- name="Android RenderScript Problem"
- point="org.eclipse.core.resources.markers">
- <super type="org.eclipse.core.resources.problemmarker" />
- <super type="org.eclipse.core.resources.textmarker" />
- <persistent value="true" />
- </extension>
- <extension
- id="com.android.ide.eclipse.common.androidProblem"
- name="Android XML Content Problem"
- point="org.eclipse.core.resources.markers">
- <super type="org.eclipse.core.resources.problemmarker" />
- <super type="org.eclipse.core.resources.textmarker" />
- <persistent value="true" />
- </extension>
- <extension
- id="com.android.ide.eclipse.adt.lintProblem"
- name="Android Lint Problem"
- point="org.eclipse.core.resources.markers">
- <super type="org.eclipse.core.resources.problemmarker" />
- <super type="org.eclipse.core.resources.textmarker" />
- <persistent value="true" />
- </extension>
- <extension
- id="com.android.ide.eclipse.adt.manifMergerProblem"
- name="Android Manifest Merger Problem"
- point="org.eclipse.core.resources.markers">
- <super type="org.eclipse.core.resources.problemmarker" />
- <super type="org.eclipse.core.resources.textmarker" />
- <persistent value="true" />
- </extension>
- <extension
- id="com.android.ide.eclipse.adt.adtProblem"
- name="Android ADT Problem"
- point="org.eclipse.core.resources.markers">
- <super type="org.eclipse.core.resources.problemmarker" />
- <super type="org.eclipse.core.resources.textmarker" />
- <persistent value="true" />
- </extension>
- <extension
- id="com.android.ide.eclipse.adt.targetProblem"
- name="Android Target Problem"
- point="org.eclipse.core.resources.markers">
- <super type="org.eclipse.core.resources.problemmarker" />
- <persistent value="false" />
- </extension>
- <extension
- id="com.android.ide.eclipse.adt.buildToolsProblem"
- name="Android Build Tools Problem"
- point="org.eclipse.core.resources.markers">
- <super type="org.eclipse.core.resources.problemmarker" />
- <persistent value="false" />
- </extension>
- <extension
- id="com.android.ide.eclipse.adt.dependencyProblem"
- name="Android Dependency Problem"
- point="org.eclipse.core.resources.markers">
- <super type="org.eclipse.core.resources.problemmarker" />
- <persistent value="false" />
- </extension>
- <extension
- id="com.android.ide.eclipse.adt.packagingProblem"
- name="Android Packaging Problem"
- point="org.eclipse.core.resources.markers">
- <super type="org.eclipse.core.resources.problemmarker" />
- <persistent value="true" />
- </extension>
- <extension point="org.eclipse.ui.ide.markerResolution">
- <markerResolutionGenerator
- markerType="com.android.ide.eclipse.adt.lintProblem"
- class="com.android.ide.eclipse.adt.internal.lint.LintFixGenerator" />
- <markerResolutionGenerator
- markerType="com.android.ide.eclipse.common.aaptProblem"
- class="com.android.ide.eclipse.adt.internal.build.AaptQuickFix" />
- </extension>
- <extension
- id="ResourceManagerBuilder"
- name="Android Resource Manager"
- point="org.eclipse.core.resources.builders">
- <builder hasNature="true">
- <run class="com.android.ide.eclipse.adt.internal.build.builders.ResourceManagerBuilder" />
- </builder>
- </extension>
- <extension
- id="PreCompilerBuilder"
- name="Android Pre Compiler"
- point="org.eclipse.core.resources.builders">
- <builder hasNature="true">
- <run class="com.android.ide.eclipse.adt.internal.build.builders.PreCompilerBuilder" />
- </builder>
- </extension>
- <extension
- id="ApkBuilder"
- name="Android Package Builder"
- point="org.eclipse.core.resources.builders">
- <builder hasNature="true">
- <run class="com.android.ide.eclipse.adt.internal.build.builders.PostCompilerBuilder" />
- </builder>
- </extension>
- <extension
- id="AndroidNature"
- name="Android Project Nature"
- point="org.eclipse.core.resources.natures">
- <runtime>
- <run class="com.android.ide.eclipse.adt.internal.project.AndroidNature" />
- </runtime>
- <builder id="com.android.ide.eclipse.adt.ResourceManagerBuilder" />
- <builder id="com.android.ide.eclipse.adt.PreCompilerBuilder" />
- <builder id="com.android.ide.eclipse.adt.ApkBuilder" />
- </extension>
- <extension
- id="ExportNature"
- name="Android Export Project Nature"
- point="org.eclipse.core.resources.natures">
- <runtime>
- <run class="com.android.ide.eclipse.adt.internal.project.ExportNature" />
- </runtime>
- </extension>
- <extension
- point="org.eclipse.ui.importWizards">
- <category
- id="com.android.ide.eclipse.wizards.category"
- name="Android" />
- <wizard
- canFinishEarly="false"
- category="com.android.ide.eclipse.wizards.category"
- class="com.android.ide.eclipse.adt.internal.wizards.newproject.ImportProjectWizard"
- finalPerspective="org.eclipse.jdt.ui.JavaPerspective"
- hasPages="true"
- icon="icons/new_adt_project.png"
- id="com.android.ide.eclipse.adt.project.ImportProjectWizard"
- name="Existing Android Code Into Workspace"
- preferredPerspectives="org.eclipse.jdt.ui.JavaPerspective"
- project="true">
- </wizard>
- </extension>
- <extension point="org.eclipse.ui.newWizards">
- <category
- id="com.android.ide.eclipse.wizards.category"
- name="Android" />
- <wizard
- canFinishEarly="false"
- category="com.android.ide.eclipse.wizards.category"
- class="com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard"
- finalPerspective="org.eclipse.jdt.ui.JavaPerspective"
- hasPages="true"
- icon="icons/new_adt_project.png"
- id="com.android.ide.eclipse.adt.project.NewProjectWizard"
- name="Android Application Project"
- preferredPerspectives="org.eclipse.jdt.ui.JavaPerspective"
- project="true" >
- <description>
- Create an Android Application Project
- </description>
- </wizard>
- <wizard
- canFinishEarly="false"
- category="com.android.ide.eclipse.wizards.category"
- class="com.android.ide.eclipse.adt.internal.wizards.newproject.NewTestProjectWizard"
- finalPerspective="org.eclipse.jdt.ui.JavaPerspective"
- hasPages="true"
- icon="icons/newJunit.png"
- id="com.android.ide.eclipse.adt.project.NewTestProjectWizard"
- name="Android Test Project"
- preferredPerspectives="org.eclipse.jdt.ui.JavaPerspective"
- project="true">
- <description>
- Create an Android Test Project
- </description>
- </wizard>
- <wizard
- canFinishEarly="false"
- category="com.android.ide.eclipse.wizards.category"
- class="com.android.ide.eclipse.adt.internal.wizards.newproject.NewSampleProjectWizard"
- finalPerspective="org.eclipse.jdt.ui.JavaPerspective"
- hasPages="true"
- icon="icons/new_adt_project.png"
- id="com.android.ide.eclipse.adt.project.NewSampleProjectWizard"
- name="Android Sample Project"
- preferredPerspectives="org.eclipse.jdt.ui.JavaPerspective"
- project="true">
- <description>
- Create an Android Sample Project
- </description>
- </wizard>
- <wizard
- canFinishEarly="false"
- category="com.android.ide.eclipse.wizards.category"
- class="com.android.ide.eclipse.adt.internal.wizards.newproject.ImportProjectWizard"
- finalPerspective="org.eclipse.jdt.ui.JavaPerspective"
- hasPages="true"
- icon="icons/new_adt_project.png"
- id="com.android.ide.eclipse.adt.project.ImportProjectWizard.NewPrj"
- name="Android Project from Existing Code"
- preferredPerspectives="org.eclipse.jdt.ui.JavaPerspective"
- project="true">
- <description>
- Create one or more Android projects from existing code
- </description>
- </wizard>
- <wizard
- canFinishEarly="false"
- category="com.android.ide.eclipse.wizards.category"
- class="com.android.ide.eclipse.adt.internal.wizards.newxmlfile.NewXmlFileWizard"
- finalPerspective="org.eclipse.jdt.ui.JavaPerspective"
- hasPages="true"
- icon="icons/new_xml.png"
- id="com.android.ide.eclipse.editors.wizards.NewXmlFileWizard"
- name="Android XML File"
- preferredPerspectives="org.eclipse.jdt.ui.JavaPerspective"
- project="false">
- <description>
- Create an Android resource XML file
- </description>
- </wizard>
- <wizard
- canFinishEarly="false"
- category="com.android.ide.eclipse.wizards.category"
- class="com.android.ide.eclipse.adt.internal.wizards.newxmlfile.NewXmlFileWizard$NewLayoutWizard"
- finalPerspective="org.eclipse.jdt.ui.JavaPerspective"
- hasPages="true"
- icon="icons/new_xml.png"
- id="com.android.ide.eclipse.editors.wizards.NewXmlFileWizard.Layout"
- name="Android XML Layout File"
- preferredPerspectives="org.eclipse.jdt.ui.JavaPerspective"
- project="false">
- <description>
- Create an Android layout XML file
- </description>
- </wizard>
- <wizard
- canFinishEarly="false"
- category="com.android.ide.eclipse.wizards.category"
- class="com.android.ide.eclipse.adt.internal.wizards.newxmlfile.NewXmlFileWizard$NewValuesWizard"
- finalPerspective="org.eclipse.jdt.ui.JavaPerspective"
- hasPages="true"
- icon="icons/new_xml.png"
- id="com.android.ide.eclipse.editors.wizards.NewXmlFileWizard.Values"
- name="Android XML Values File"
- preferredPerspectives="org.eclipse.jdt.ui.JavaPerspective"
- project="false">
- <description>
- Create an Android XML values file such as strings.xml
- </description>
- </wizard>
- <wizard
- canFinishEarly="false"
- category="com.android.ide.eclipse.wizards.category"
- class="com.android.ide.eclipse.adt.internal.wizards.templates.NewActivityWizard"
- finalPerspective="org.eclipse.jdt.ui.JavaPerspective"
- hasPages="true"
- icon="icons/new_adt_project.png"
- id="com.android.ide.eclipse.editors.wizards.NewActivityWizard"
- name="Android Activity"
- preferredPerspectives="org.eclipse.jdt.ui.JavaPerspective"
- project="false" >
- <description>
- Create an Android Activity
- </description>
- </wizard>
- <wizard
- canFinishEarly="false"
- category="com.android.ide.eclipse.wizards.category"
- class="com.android.ide.eclipse.adt.internal.wizards.templates.NewActivityWizard$OtherWizard"
- finalPerspective="org.eclipse.jdt.ui.JavaPerspective"
- hasPages="true"
- icon="icons/newCustomView.png"
- id="com.android.ide.eclipse.editors.wizards.NewActivityWizard.OtherWizard"
- name="Android Object"
- preferredPerspectives="org.eclipse.jdt.ui.JavaPerspective"
- project="false" >
- <description>
- Create an Android object such as a Service, an Activity, a Broadcast Receiver, a Notification, etc.
- </description>
- </wizard>
- <!-- Available through generic object list above
- <wizard
- canFinishEarly="false"
- category="com.android.ide.eclipse.wizards.category"
- class="com.android.ide.eclipse.adt.internal.wizards.templates.NewTemplateWizard$NewCustomViewWizard"
- finalPerspective="org.eclipse.jdt.ui.JavaPerspective"
- hasPages="true"
- icon="icons/newCustomView.png"
- id="com.android.ide.eclipse.editors.wizards.NewTemplateWizard.CustomView"
- name="Android Custom View"
- preferredPerspectives="org.eclipse.jdt.ui.JavaPerspective"
- project="false" >
- <description>
- Create an Android custom view
- </description>
- </wizard>
- -->
- <wizard
- canFinishEarly="false"
- category="com.android.ide.eclipse.wizards.category"
- class="com.android.ide.eclipse.adt.internal.assetstudio.CreateAssetSetWizard"
- finalPerspective="org.eclipse.jdt.ui.JavaPerspective"
- hasPages="true"
- icon="icons/new_asset_set.png"
- id="com.android.ide.eclipse.adt.internal.assetstudio.CreateAssetSetWizard"
- name="Android Icon Set"
- preferredPerspectives="org.eclipse.jdt.ui.JavaPerspective"
- project="false" >
- <description>
- Create an Android icon set
- </description>
- </wizard>
-
- <!-- During development only: Support for testing templates -->
- <wizard
- canFinishEarly="false"
- category="com.android.ide.eclipse.wizards.category"
- class="com.android.ide.eclipse.adt.internal.wizards.templates.TemplateTestWizard"
- finalPerspective="org.eclipse.jdt.ui.JavaPerspective"
- hasPages="true"
- icon="icons/androidjunit.png"
- id="com.android.ide.eclipse.editors.wizards.TemplateTestWizard"
- name="Template Development Wizard"
- preferredPerspectives="org.eclipse.jdt.ui.JavaPerspective"
- project="false" />
- </extension>
- <extension point="org.eclipse.debug.core.launchConfigurationTypes">
- <launchConfigurationType
- delegate="com.android.ide.eclipse.adt.internal.launch.LaunchConfigDelegate"
- delegateDescription="The Android Application Launcher supports running and debugging remote Android applications on devices or emulators."
- delegateName="Android Launcher"
- id="com.android.ide.eclipse.adt.debug.LaunchConfigType"
- modes="debug, run"
- name="Android Application"
- public="true"
- sourceLocatorId="com.android.ide.eclipse.adt.internal.sourcelookup.AdtSourceLookupDirector"
- sourcePathComputerId="org.eclipse.jdt.launching.sourceLookup.javaSourcePathComputer">
- </launchConfigurationType>
- </extension>
- <extension point="org.eclipse.debug.ui.launchConfigurationTypeImages">
- <launchConfigurationTypeImage
- configTypeID="com.android.ide.eclipse.adt.debug.LaunchConfigType"
- icon="icons/android_app.png"
- id="com.android.ide.eclipse.adt.debug.LaunchConfigTypeImage" />
- </extension>
- <extension point="org.eclipse.debug.ui.launchConfigurationTabGroups">
- <launchConfigurationTabGroup
- class="com.android.ide.eclipse.adt.internal.launch.LaunchConfigTabGroup"
- description="Android Application"
- id="com.android.ide.eclipse.adt.debug.LaunchConfigTabGroup"
- type="com.android.ide.eclipse.adt.debug.LaunchConfigType" />
- </extension>
- <extension point="org.eclipse.debug.ui.launchShortcuts">
- <shortcut
- class="com.android.ide.eclipse.adt.internal.launch.LaunchShortcut"
- icon="icons/android_app.png"
- id="com.android.ide.eclipse.adt.debug.launching.LaunchShortcut"
- label="Android Application"
- modes="run, debug">
- <contextualLaunch>
- <enablement>
- <with variable="selection">
- <count value="1" />
- <iterate>
- <or>
- <adapt type="org.eclipse.core.resources.IFile">
- <and>
- <test
- property="org.eclipse.core.resources.contentTypeId"
- value="org.eclipse.core.runtime.xml" />
- <test
- property="org.eclipse.core.resources.projectNature"
- value="com.android.ide.eclipse.adt.AndroidNature" />
- </and>
- </adapt>
- <and>
- <test property="org.eclipse.jdt.launching.isContainer" />
- <test
- property="org.eclipse.jdt.launching.hasProjectNature"
- args="com.android.ide.eclipse.adt.AndroidNature" />
- </and>
- </or>
- </iterate>
- </with>
- </enablement>
- </contextualLaunch>
- <perspective id="org.eclipse.jdt.ui.JavaPerspective" />
- <perspective id="org.eclipse.debug.ui.DebugPerspective" />
- <configurationType id="com.android.ide.eclipse.adt.debug.LaunchConfigType">
- </configurationType>
- <description
- description="Runs an Android Application"
- mode="run">
- </description>
- <description
- description="Debugs an Android Application"
- mode="debug">
- </description>
- </shortcut>
- </extension>
- <extension point="org.eclipse.ui.popupMenus">
- <objectContribution
- id="com.android.ide.eclipse.adt.contribution2"
- nameFilter="*"
- objectClass="org.eclipse.core.resources.IProject"
- adaptable="true">
- <menu
- id="com.android.ide.eclipse.adt.AndroidTools"
- label="Android Tools"
- path="additions">
- <separator name="group1" />
- <separator name="group2" />
- <separator name="group3" />
- <separator name="group4" />
- </menu>
- <filter
- name="projectNature"
- value="com.android.ide.eclipse.adt.AndroidNature">
- </filter>
- <action
- class="com.android.ide.eclipse.adt.internal.wizards.actions.NewXmlFileAction"
- enablesFor="1"
- icon="icons/new_xml.png"
- id="com.android.ide.eclipse.adt.wizards.actions.NewXmlFileAction"
- label="New Resource File..."
- menubarPath="com.android.ide.eclipse.adt.AndroidTools/group1"
- tooltip="Opens a wizard to help create a new Android XML Resource file">
- </action>
- <action
- class="com.android.ide.eclipse.adt.internal.wizards.actions.NewTestProjectAction"
- enablesFor="1"
- icon="icons/androidjunit.png"
- id="com.android.ide.eclipse.adt.wizards.actions.NewTestProjectAction"
- label="New Test Project..."
- menubarPath="com.android.ide.eclipse.adt.AndroidTools/group1"
- tooltip="Opens a wizard to help create a new Android Test Project">
- </action>
- <action
- class="com.android.ide.eclipse.adt.internal.wizards.actions.ExportAction"
- enablesFor="1"
- id="com.android.ide.eclipse.adt.project.ExportAction"
- label="Export Unsigned Application Package..."
- menubarPath="com.android.ide.eclipse.adt.AndroidTools/group2" />
- <action
- class="com.android.ide.eclipse.adt.internal.wizards.actions.ExportWizardAction"
- enablesFor="1"
- id="com.android.ide.eclipse.adt.project.ExportWizardAction"
- label="Export Signed Application Package..."
- menubarPath="com.android.ide.eclipse.adt.AndroidTools/group2" />
- <action
- class="com.android.ide.eclipse.adt.internal.actions.FixProjectAction"
- enablesFor="1"
- id="com.android.ide.eclipse.adt.project.FixProjectAction"
- label="Fix Project Properties"
- menubarPath="com.android.ide.eclipse.adt.AndroidTools/group3" />
- <action
- class="com.android.ide.eclipse.adt.internal.actions.AddSupportJarAction"
- enablesFor="1"
- icon="icons/android.png"
- id="com.android.ide.eclipse.adt.wizards.actions.AddCompatibilityJarAction"
- label="Add Support Library..."
- menubarPath="com.android.ide.eclipse.adt.AndroidTools/group3"
- tooltip="Add the Compatibility Library to the project">
- </action>
- <action
- class="com.android.ide.eclipse.adt.internal.refactorings.renamepackage.RenamePackageAction"
- enablesFor="1"
- id="com.android.ide.eclipse.adt.project.RenamePackageAction"
- label="Rename Application Package"
- menubarPath="com.android.ide.eclipse.adt.AndroidTools/group3" />
- <action
- class="com.android.ide.eclipse.adt.internal.actions.DexDumpAction"
- enablesFor="1"
- id="com.android.ide.eclipse.adt.DexDumpAction"
- label="Display dex bytecode"
- menubarPath="com.android.ide.eclipse.adt.AndroidTools/group3" />
- <action
- class="com.android.ide.eclipse.adt.internal.lint.ClearLintMarkersAction"
- enablesFor="1"
- id="com.android.ide.eclipse.adt.internal.lint.ClearLintMarkersAction"
- label="Clear Lint Markers"
- menubarPath="com.android.ide.eclipse.adt.AndroidTools/group4" />
- <action
- class="com.android.ide.eclipse.adt.internal.lint.RunLintAction"
- enablesFor="1"
- id="com.android.ide.eclipse.adt.internal.lint.RunLintAction"
- label="Run Lint: Check for Common Errors"
- icon="icons/lintrun.png"
- menubarPath="com.android.ide.eclipse.adt.AndroidTools/group4" />
- </objectContribution>
- </extension>
- <extension point="org.eclipse.ui.preferencePages">
- <page
- class="com.android.ide.eclipse.adt.internal.preferences.AndroidPreferencePage"
- id="com.android.ide.eclipse.preferences.main"
- name="Android" />
- <page
- category="com.android.ide.eclipse.preferences.main"
- class="com.android.ide.eclipse.adt.internal.preferences.BuildPreferencePage"
- id="com.android.ide.eclipse.adt.preferences.BuildPreferencePage"
- name="Build" />
- <page
- category="com.android.ide.eclipse.preferences.main"
- class="com.android.ide.eclipse.adt.internal.preferences.LaunchPreferencePage"
- id="com.android.ide.eclipse.adt.preferences.LaunchPreferencePage"
- name="Launch" />
- <page
- category="com.android.ide.eclipse.preferences.main"
- class="com.android.ide.eclipse.adt.internal.preferences.EditorsPage"
- id="com.android.ide.eclipse.adt.preferences.EditorsPage"
- name="Editors">
- </page>
- <page
- category="com.android.ide.eclipse.preferences.main"
- class="com.android.ide.eclipse.adt.internal.preferences.LintPreferencePage"
- id="com.android.ide.eclipse.common.preferences.LintPreferencePage"
- name="Lint Error Checking">
- </page>
- </extension>
- <extension point="org.eclipse.core.runtime.preferences">
- <initializer class="com.android.ide.eclipse.adt.internal.preferences.AdtPrefs" />
- </extension>
- <extension point="org.eclipse.ui.perspectiveExtensions">
- <perspectiveExtension targetID="org.eclipse.jdt.ui.JavaPerspective">
- <newWizardShortcut id="com.android.ide.eclipse.adt.project.NewProjectWizard" />
- <newWizardShortcut id="com.android.ide.eclipse.editors.wizards.NewXmlFileWizard" />
- <actionSet id="adt.actionSet.wizards" />
- <actionSet id="adt.actionSet.avdManager" />
- <actionSet id="adt.actionSet.lint" />
- <actionSet id="adt.actionSet.refactorings" />
- </perspectiveExtension>
- <perspectiveExtension targetID="org.eclipse.debug.ui.DebugPerspective">
- <viewShortcut id="com.android.ide.eclipse.ddms.views.LogCatView" />
- <viewShortcut id="com.android.ide.eclipse.ddms.views.DeviceView" />
- </perspectiveExtension>
- </extension>
- <extension point="org.eclipse.ui.ide.projectNatureImages">
- <image
- icon="icons/android_project.png"
- id="com.android.ide.eclipse.adt.AndroidNature.image"
- natureId="com.android.ide.eclipse.adt.AndroidNature">
- </image>
- </extension>
- <extension point="org.eclipse.jdt.core.classpathContainerInitializer">
- <classpathContainerInitializer
- class="com.android.ide.eclipse.adt.internal.project.AndroidClasspathContainerInitializer"
- id="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK">
- </classpathContainerInitializer>
- <classpathContainerInitializer
- class="com.android.ide.eclipse.adt.internal.project.LibraryClasspathContainerInitializer"
- id="com.android.ide.eclipse.adt.LIBRARIES">
- </classpathContainerInitializer>
- <classpathContainerInitializer
- class="com.android.ide.eclipse.adt.internal.project.LibraryClasspathContainerInitializer"
- id="com.android.ide.eclipse.adt.DEPENDENCIES">
- </classpathContainerInitializer>
- </extension>
- <extension point="org.eclipse.jdt.ui.classpathContainerPage">
- <classpathContainerPage
- name="Android Classpath Container"
- class="com.android.ide.eclipse.adt.internal.project.AndroidClasspathContainerPage"
- id="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK">
- </classpathContainerPage>
- </extension>
- <extension point="org.eclipse.ui.exportWizards">
- <category
- id="com.android.ide.eclipse.wizards.category"
- name="Android">
- </category>
- <wizard
- category="com.android.ide.eclipse.wizards.category"
- class="com.android.ide.eclipse.adt.internal.wizards.export.ExportWizard"
- icon="icons/android.png"
- id="com.android.ide.eclipse.adt.project.ExportWizard"
- name="Export Android Application">
- </wizard>
- </extension>
- <extension point="org.eclipse.ui.exportWizards">
- <category
- id="com.android.ide.eclipse.wizards.category"
- name="Android">
- </category>
- <wizard
- category="com.android.ide.eclipse.wizards.category"
- class="com.android.ide.eclipse.adt.internal.wizards.exportgradle.GradleExportWizard"
- icon="icons/gradle.png"
- id="com.android.ide.eclipse.adt.project.ExportGradleWizard"
- name="Generate Gradle build files">
- <selection
- class="org.eclipse.jdt.core.IJavaProject">
- </selection>
- </wizard>
- </extension>
- <extension point="org.eclipse.ui.commands">
- <command
- name="Debug Android Application"
- description="Debug Android Application"
- categoryId="org.eclipse.debug.ui.category.run"
- id="com.android.ide.eclipse.adt.launch.LaunchShortcut.debug">
- </command>
- <command
- name="Run Android Application"
- description="Run Android Application"
- categoryId="org.eclipse.debug.ui.category.run"
- id="com.android.ide.eclipse.adt.launch.LaunchShortcut.run">
- </command>
- </extension>
- <extension point="org.eclipse.ui.decorators">
- <decorator
- adaptable="true"
- class="com.android.ide.eclipse.adt.internal.project.FolderDecorator"
- id="com.android.ide.eclipse.adt.project.FolderDecorator"
- label="Android Decorator"
- lightweight="true"
- location="TOP_RIGHT"
- objectClass="org.eclipse.core.resources.IFolder"
- state="true">
- </decorator>
- </extension>
- <extension point="org.eclipse.ui.editors">
- <editor
- class="com.android.ide.eclipse.adt.internal.editors.export.ExportEditor"
- default="true"
- filenames="export.properties"
- icon="icons/android_file.png"
- id="com.android.ide.eclipse.editors.export.ExportEditor"
- name="Android Export Editor">
- </editor>
-
- <editor
- class="com.android.ide.eclipse.adt.internal.editors.manifest.ManifestEditor"
- default="true"
- filenames="AndroidManifest.xml"
- icon="icons/android_file.png"
- id="com.android.ide.eclipse.editors.manifest.ManifestEditor"
- name="Android Manifest Editor">
- </editor>
-
- <!--
- This is the new generic multi-purpose single XML editor used by ADT.
- It is designed to replace all the other XML editors (layout, manifest, drawable,
- animation, color, values, xml) and does so by using a single common Editor class
- that defers to multiple delegate handlers.
- -->
- <editor
- class="com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor"
- contributorClass="com.android.ide.eclipse.adt.internal.editors.common.CommonActionContributor"
- default="true"
- extensions="xml"
- icon="icons/android_file.png"
- id="com.android.ide.eclipse.editors.CommonXmlEditor"
- matchingStrategy="com.android.ide.eclipse.adt.internal.editors.common.CommonMatchingStrategy"
- name="Android Common XML Editor">
- </editor>
-
- <!--
- For compatibilit with existing ADT installs, we still need to keep the editor
- IDs of the previously defined editors. E.g. for the color editor note that the
- id remains the same but class name changes to the new class. This will make
- Eclipse not complain upon startup of an existing workspace.
- -->
- <editor
- class="com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor"
- contributorClass="com.android.ide.eclipse.adt.internal.editors.common.CommonActionContributor"
- default="false"
- icon="icons/android_file.png"
- id="com.android.ide.eclipse.editors.layout.LayoutEditor"
- matchingStrategy="com.android.ide.eclipse.adt.internal.editors.common.CommonMatchingStrategy"
- name="Legacy Android Layout Editor">
- </editor>
- <editor
- class="com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor"
- default="false"
- icon="icons/android_file.png"
- id="com.android.ide.eclipse.editors.resources.ResourcesEditor"
- name="Legacy Android Resource Editor">
- </editor>
- <editor
- class="com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor"
- default="false"
- icon="icons/android_file.png"
- id="com.android.ide.eclipse.editors.menu.MenuEditor"
- name="Legacy Android Menu Editor">
- </editor>
- <editor
- class="com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor"
- default="false"
- icon="icons/android_file.png"
- id="com.android.ide.eclipse.editors.xml.XmlEditor"
- name="Legacy Android Xml Resources Editor">
- </editor>
- <editor
- class="com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor"
- default="false"
- icon="icons/android_file.png"
- id="com.android.ide.eclipse.editors.animator.AnimationEditor"
- name="Legacy Android Animation Editor">
- </editor>
- <editor
- class="com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor"
- default="false"
- icon="icons/android_file.png"
- id="com.android.ide.eclipse.editors.drawable.DrawableEditor"
- name="Legacy Android Drawable Editor">
- </editor>
- <editor
- class="com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor"
- default="false"
- icon="icons/android_file.png"
- id="com.android.ide.eclipse.editors.color.ColorEditor"
- name="Legacy Android Color Editor">
- </editor>
-
- <editor
- class="com.android.ide.eclipse.adt.internal.editors.binaryxml.BinaryXMLMultiPageEditorPart"
- contributorClass="org.eclipse.wst.xml.ui.internal.tabletree.XMLMultiPageEditorActionBarContributor"
- icon="$nl$/icons/android_file.png"
- id="com.android.ide.eclipse.adt.binedit.BinaryXMLMultiPageEditorPart"
- name="Android Binary XML editor"
- symbolicFontName="org.eclipse.wst.sse.ui.textfont">
- <contentTypeBinding contentTypeId="com.android.ide.eclipse.adt.binaryXml">
- </contentTypeBinding>
- </editor>
- <editor
- class="com.android.ide.eclipse.adt.internal.editors.draw9patch.Draw9PatchEditor"
- contributorClass="com.android.ide.eclipse.adt.internal.editors.common.CommonActionContributor"
- icon="icons/android_file.png"
- id="draw9patchplugin.editors.Draw9PatchEditor"
- name="Android Draw 9-patch Editor"
- extensions="9.png">
- </editor>
- </extension>
- <extension point="org.eclipse.ui.views">
- <view
- allowMultiple="false"
- category="com.android.ide.eclipse.ddms.views.category"
- class="com.android.ide.eclipse.adt.internal.ui.ResourceExplorerView"
- icon="icons/draw9patch-16.png"
- id="com.android.ide.eclipse.editors.resources.explorer.ResourceExplorerView"
- name="Resource Explorer">
- </view>
- <view
- class="com.android.ide.eclipse.adt.internal.lint.LintViewPart"
- category="com.android.ide.eclipse.ddms.views.category"
- id="com.android.ide.eclipse.adt.internal.lint.LintViewPart"
- icon="icons/lintview.png"
- name="Lint Warnings">
- </view>
- </extension>
- <extension point="org.eclipse.wst.sse.ui.editorConfiguration">
- <sourceViewerConfiguration
- class="com.android.ide.eclipse.adt.internal.editors.manifest.ManifestSourceViewerConfig"
- target="com.android.ide.eclipse.editors.manifest.ManifestEditor">
- </sourceViewerConfiguration>
- <sourceViewerConfiguration
- class="com.android.ide.eclipse.adt.internal.editors.common.CommonSourceViewerConfig"
- target="com.android.ide.eclipse.editors.CommonXmlEditor">
- </sourceViewerConfiguration>
- <quickOutlineConfiguration
- class="com.android.ide.eclipse.adt.internal.editors.AndroidQuickOutlineConfiguration"
- target="org.eclipse.core.runtime.xml" />
- <contentOutlineConfiguration
- class="com.android.ide.eclipse.adt.internal.editors.AndroidOutlineConfiguration"
- target="org.eclipse.core.runtime.xml" />
- <doubleClickStrategy
- class="com.android.ide.eclipse.adt.internal.editors.AndroidDoubleClickStrategy"
- target="org.eclipse.wst.xml.XML_DEFAULT" />
- <provisionalConfiguration
- type="org.eclipse.jface.text.quickassist.IQuickAssistProcessor"
- class="com.android.ide.eclipse.adt.internal.editors.formatting.XmlQuickAssistManager"
- target="org.eclipse.wst.xml.XML_DEFAULT" />
- <provisionalConfiguration
- type="characterpairmatcher"
- class="com.android.ide.eclipse.adt.internal.editors.AndroidXmlCharacterMatcher"
- target="org.eclipse.core.runtime.xml" />
- </extension>
- <extension point="org.eclipse.jdt.ui.quickAssistProcessors">
- <quickAssistProcessor
- id="AndroidJavaAssistant"
- name="Android Java Quick Assistant"
- requiredSourceLevel="1.5"
- class="com.android.ide.eclipse.adt.internal.editors.layout.refactoring.JavaQuickAssistant">
- </quickAssistProcessor>
- </extension>
- <extension
- point="org.eclipse.jdt.ui.quickFixProcessors">
- <quickFixProcessor
- name="Android Convert Switch Quickfix Processor"
- class="com.android.ide.eclipse.adt.internal.build.ConvertSwitchQuickFixProcessor"
- id="com.android.ide.eclipse.adt.internal.build.ConvertSwitchQuickFixProcessor">
- <handledMarkerTypes>
- <markerType id="org.eclipse.jdt.core.problem"/>
- </handledMarkerTypes>
- </quickFixProcessor>
- </extension>
- <extension point="org.eclipse.ui.propertyPages">
- <page
- adaptable="true"
- class="com.android.ide.eclipse.adt.internal.properties.AndroidPropertyPage"
- id="com.android.ide.eclipse.adt.project.properties.AndroidPropertyPage"
- name="Android"
- nameFilter="*"
- objectClass="org.eclipse.core.resources.IProject">
- <enabledWhen>
- <test
- property="org.eclipse.jdt.launching.hasProjectNature"
- args="com.android.ide.eclipse.adt.AndroidNature" />
- </enabledWhen>
- </page>
- <page
- class="com.android.ide.eclipse.adt.internal.preferences.LintPreferencePage"
- id="com.android.ide.eclipse.adt.internal.preferences.LintPreferencePage"
- name="Android Lint Preferences">
- <filter
- name="nature"
- value="com.android.ide.eclipse.adt.AndroidNature">
- </filter>
- <enabledWhen>
- <adapt type="org.eclipse.core.resources.IProject" />
- </enabledWhen>
- </page>
- </extension>
- <extension point="org.eclipse.ui.actionSets">
- <actionSet
- description="Android Wizards"
- id="adt.actionSet.wizards"
- label="Android Wizards"
- visible="false">
- <action
- class="com.android.ide.eclipse.adt.internal.wizards.actions.NewXmlFileAction"
- icon="icons/new_xml.png"
- id="com.android.ide.eclipse.adt.wizards.actions.NewXmlFileAction"
- label="New Android XML File"
- style="push"
- toolbarPath="android_project">
- </action>
- </actionSet>
- <actionSet
- description="Refactorings for Android"
- id="adt.actionSet.refactorings"
- label="Android Refactorings"
- visible="false">
-
- <!-- This duplicates the Refactoring Menu definition from the jdt.ui plugin.xml,
- which allows us to insert our contribution even if the JDT is not loaded.
- We overload the definition with our new group.-->
- <menu
- label="Refactor"
- path="edit"
- id="org.eclipse.jdt.ui.refactoring.menu">
- <separator name="undoRedoGroup" />
- <separator name="reorgGroup" />
- <separator name="androidGroup" />
- <separator name="codingGroup" />
- <separator name="reorgGroup2" />
- <separator name="typeGroup" />
- <separator name="typeGroup2" />
- <separator name="codingGroup2" />
- <separator name="typeGroup3" />
- <separator name="scriptGroup" />
- </menu>
- <menu
- label="Android"
- path="org.eclipse.jdt.ui.refactoring.menu/androidGroup"
- id="com.android.ide.eclipse.adt.refactoring.menu">
- <separator name="android" />
- </menu>
- <action
- class="com.android.ide.eclipse.adt.internal.refactorings.extractstring.ExtractStringAction"
- definitionId="com.android.ide.eclipse.adt.refactoring.extract.string"
- id="com.android.ide.eclipse.adt.actions.ExtractString"
- label="Extract Android String..."
- menubarPath="org.eclipse.jdt.ui.refactoring.menu/com.android.ide.eclipse.adt.refactoring.menu/android"
- style="push"
- tooltip="Extracts a string into Android resource string">
- </action>
- <action
- class="com.android.ide.eclipse.adt.internal.editors.layout.refactoring.ExtractIncludeAction"
- definitionId="com.android.ide.eclipse.adt.refactoring.extract.include"
- id="com.android.ide.eclipse.adt.actions.ExtractInclude"
- label="Extract as Include..."
- menubarPath="org.eclipse.jdt.ui.refactoring.menu/com.android.ide.eclipse.adt.refactoring.menu/android"
- style="push"
- tooltip="Extracts Views as Included Layout">
- </action>
- <action
- class="com.android.ide.eclipse.adt.internal.editors.layout.refactoring.ExtractStyleAction"
- definitionId="com.android.ide.eclipse.adt.refactoring.extract.style"
- id="com.android.ide.eclipse.adt.actions.ExtractStyle"
- label="Extract Style..."
- menubarPath="org.eclipse.jdt.ui.refactoring.menu/com.android.ide.eclipse.adt.refactoring.menu/android"
- style="push"
- tooltip="Extracts Styles">
- </action>
- <action
- class="com.android.ide.eclipse.adt.internal.editors.layout.refactoring.WrapInAction"
- definitionId="com.android.ide.eclipse.adt.refactoring.wrapin"
- id="com.android.ide.eclipse.adt.actions.WrapIn"
- label="Wrap In Container..."
- menubarPath="org.eclipse.jdt.ui.refactoring.menu/com.android.ide.eclipse.adt.refactoring.menu/android"
- style="push"
- tooltip="Wraps Views in a new container">
- </action>
- <action
- class="com.android.ide.eclipse.adt.internal.editors.layout.refactoring.UnwrapAction"
- definitionId="com.android.ide.eclipse.adt.refactoring.unwrap"
- id="com.android.ide.eclipse.adt.actions.Unwrap"
- label="Remove Container..."
- menubarPath="org.eclipse.jdt.ui.refactoring.menu/com.android.ide.eclipse.adt.refactoring.menu/android"
- style="push"
- tooltip="Unwraps Views by Removing their container">
- </action>
- <action
- class="com.android.ide.eclipse.adt.internal.editors.layout.refactoring.ChangeLayoutAction"
- definitionId="com.android.ide.eclipse.adt.refactoring.convert"
- id="com.android.ide.eclipse.adt.actions.ChangeLayout"
- label="Change Layout..."
- menubarPath="org.eclipse.jdt.ui.refactoring.menu/com.android.ide.eclipse.adt.refactoring.menu/android"
- style="push"
- tooltip="Changes layouts from one type to another">
- </action>
- <action
- class="com.android.ide.eclipse.adt.internal.editors.layout.refactoring.ChangeViewAction"
- definitionId="com.android.ide.eclipse.adt.refactoring.changeview"
- id="com.android.ide.eclipse.adt.actions.ChangeView"
- label="Change Widget Type..."
- menubarPath="org.eclipse.jdt.ui.refactoring.menu/com.android.ide.eclipse.adt.refactoring.menu/android"
- style="push"
- tooltip="Changes the type of the selected widgets">
- </action>
- <menu
- id="org.eclipse.jdt.ui.refactoring.menu"
- label="Refactor">
- </menu>
- </actionSet>
- <actionSet
- description="Android AVD and SDK Manager"
- id="adt.actionSet.avdManager"
- label="Android SDK and AVD Manager"
- visible="false">
- <action
- class="com.android.ide.eclipse.adt.internal.actions.AvdManagerAction"
- icon="icons/avd_manager.png"
- id="com.android.ide.eclipse.adt.ui.avdmanager"
- label="Android Virtual Device Manager"
- menubarPath="Window/additions"
- style="push"
- toolbarPath="android_project">
- </action>
- <action
- class="com.android.ide.eclipse.adt.internal.actions.SdkManagerAction"
- icon="icons/sdk_manager.png"
- id="com.android.ide.eclipse.adt.ui.sdkmanager"
- label="Android SDK Manager"
- menubarPath="Window/additions"
- style="push"
- toolbarPath="android_project">
- </action>
- </actionSet>
- <actionSet
- description="Android Lint"
- id="adt.actionSet.lint"
- label="Android Lint"
- visible="false">
- <action
- class="com.android.ide.eclipse.adt.internal.lint.RunLintAction"
- style="pulldown"
- icon="icons/lintrun.png"
- id="com.android.ide.eclipse.adt.ui.lintrunner"
- label="Run Android Lint"
- menubarPath="Window/additions"
- toolbarPath="android_project">
- </action>
- </actionSet>
- </extension>
- <extension point="org.eclipse.debug.core.launchDelegates">
- <launchDelegate
- delegate="com.android.ide.eclipse.adt.internal.launch.JUnitLaunchConfigDelegate"
- delegateDescription="Removes the Android JAR from the Bootstrap Classpath"
- id="com.android.ide.eclipse.adt.launch.JUnitLaunchConfigDelegate.launchAndroidJunit"
- modes="run,debug"
- name="Android JUnit Test"
- type="org.eclipse.jdt.junit.launchconfig">
- </launchDelegate>
- </extension>
- <extension point="org.eclipse.debug.core.launchConfigurationTypes">
- <launchConfigurationType
- delegate="com.android.ide.eclipse.adt.internal.launch.junit.AndroidJUnitLaunchConfigDelegate"
- id="com.android.ide.eclipse.adt.junit.launchConfigurationType"
- modes="run,debug"
- name="Android JUnit Test"
- public="true"
- sourceLocatorId="com.android.ide.eclipse.adt.internal.sourcelookup.AdtSourceLookupDirector"
- sourcePathComputerId="org.eclipse.jdt.launching.sourceLookup.javaSourcePathComputer">
- </launchConfigurationType>
- </extension>
- <extension point="org.eclipse.debug.core.sourceLocators">
- <sourceLocator
- id="com.android.ide.eclipse.adt.internal.sourcelookup.AdtSourceLookupDirector"
- class="com.android.ide.eclipse.adt.internal.sourcelookup.AdtSourceLookupDirector"
- name="%sourceLocator.name">
- </sourceLocator>
- </extension>
- <extension point="org.eclipse.debug.ui.launchConfigurationTypeImages">
- <launchConfigurationTypeImage
- configTypeID="com.android.ide.eclipse.adt.junit.launchConfigurationType"
- icon="icons/androidjunit.png"
- id="com.android.ide.eclipse.adt.junit.launchConfigurationTypeImage">
- </launchConfigurationTypeImage>
- </extension>
- <extension point="org.eclipse.debug.ui.launchConfigurationTabGroups">
- <launchConfigurationTabGroup
- class="com.android.ide.eclipse.adt.internal.launch.junit.AndroidJUnitTabGroup"
- description="Android JUnit Test"
- id="com.android.ide.eclipse.adt.junit.AndroidJUnitLaunchConfigTabGroup"
- type="com.android.ide.eclipse.adt.junit.launchConfigurationType" />
- </extension>
- <extension point="org.eclipse.debug.ui.launchShortcuts">
- <shortcut
- class="com.android.ide.eclipse.adt.internal.launch.junit.AndroidJUnitLaunchShortcut"
- icon="icons/androidjunit.png"
- id="com.android.ide.eclipse.adt.junit.launchShortcut"
- label="Android JUnit Test"
- modes="run,debug">
- <contextualLaunch>
- <enablement>
- <with variable="selection">
- <count value="1" />
- <iterate>
- <adapt type="org.eclipse.jdt.core.IJavaElement">
- <test
- property="org.eclipse.jdt.core.isInJavaProjectWithNature"
- value="com.android.ide.eclipse.adt.AndroidNature" />
- <test
- property="org.eclipse.jdt.core.hasTypeOnClasspath"
- value="junit.framework.Test" />
- <test property="com.android.ide.eclipse.adt.canLaunchAsJUnit" />
- </adapt>
- </iterate>
- </with>
- </enablement>
- </contextualLaunch>
- <configurationType id="com.android.ide.eclipse.adt.junit.launchConfigurationType">
- </configurationType>
- </shortcut>
- </extension>
- <extension point="org.eclipse.ui.commands">
- <category
- description="Refactorings for Android Projects"
- id="com.android.ide.eclipse.adt.refactoring.category"
- name="Android Refactorings">
- </category>
- <command
- categoryId="com.android.ide.eclipse.adt.refactoring.category"
- description="Extract Strings into Android String Resources"
- id="com.android.ide.eclipse.adt.refactoring.extract.string"
- name="Extract Android String">
- </command>
- <command
- categoryId="com.android.ide.eclipse.adt.refactoring.category"
- description="Extract Views as Included Layout"
- id="com.android.ide.eclipse.adt.refactoring.extract.include"
- name="Extract as Include">
- </command>
- <command
- categoryId="com.android.ide.eclipse.adt.refactoring.category"
- description="Extract Styles"
- id="com.android.ide.eclipse.adt.refactoring.extract.style"
- name="Extract Styles">
- </command>
- <command
- categoryId="com.android.ide.eclipse.adt.refactoring.category"
- description="Wraps Views in a New Container"
- id="com.android.ide.eclipse.adt.refactoring.wrapin"
- name="Wrap in Container">
- </command>
- <command
- categoryId="com.android.ide.eclipse.adt.refactoring.category"
- description="Unwraps Views From Their Container"
- id="com.android.ide.eclipse.adt.refactoring.unwrap"
- name="Remove Container">
- </command>
- <command
- categoryId="com.android.ide.eclipse.adt.refactoring.category"
- description="Converts Layouts from One Type to Another"
- id="com.android.ide.eclipse.adt.refactoring.convert"
- name="Change Layout">
- </command>
- <command
- categoryId="com.android.ide.eclipse.adt.refactoring.category"
- description="Changes the widget type for the selection"
- id="com.android.ide.eclipse.adt.refactoring.changeview"
- name="Change Widget Type">
- </command>
- </extension>
- <extension point="org.eclipse.ltk.core.refactoring.refactoringContributions">
- <contribution
- class="com.android.ide.eclipse.adt.internal.refactorings.extractstring.ExtractStringContribution"
- id="com.android.ide.eclipse.adt.refactoring.extract.string">
- </contribution>
- <contribution
- class="com.android.ide.eclipse.adt.internal.editors.layout.refactoring.ExtractIncludeContribution"
- id="com.android.ide.eclipse.adt.refactoring.extract.include">
- </contribution>
- <contribution
- class="com.android.ide.eclipse.adt.internal.editors.layout.refactoring.ExtractStyleContribution"
- id="com.android.ide.eclipse.adt.refactoring.extract.style">
- </contribution>
- <contribution
- class="com.android.ide.eclipse.adt.internal.editors.layout.refactoring.WrapInContribution"
- id="com.android.ide.eclipse.adt.refactoring.wrapin">
- </contribution>
- <contribution
- class="com.android.ide.eclipse.adt.internal.editors.layout.refactoring.UnwrapContribution"
- id="com.android.ide.eclipse.adt.refactoring.unwrap">
- </contribution>
- <contribution
- class="com.android.ide.eclipse.adt.internal.editors.layout.refactoring.ChangeLayoutContribution"
- id="com.android.ide.eclipse.adt.refactoring.convert">
- </contribution>
- <contribution
- class="com.android.ide.eclipse.adt.internal.editors.layout.refactoring.ChangeViewContribution"
- id="com.android.ide.eclipse.adt.refactoring.changeview">
- </contribution>
- </extension>
- <extension point="org.eclipse.core.expressions.propertyTesters">
- <propertyTester
- properties="isTest,canLaunchAsJUnit"
- namespace="com.android.ide.eclipse.adt"
- type="org.eclipse.core.runtime.IAdaptable"
- class="com.android.ide.eclipse.adt.internal.launch.junit.AndroidJUnitPropertyTester"
- id="com.android.ide.eclipse.adt.AndroidJUnitPropertyTester">
- </propertyTester>
- </extension>
- <extension point="com.android.ide.eclipse.ddms.toolsLocator">
- <locator class="com.android.ide.eclipse.adt.ToolsLocator">
- </locator>
- </extension>
- <extension point="com.android.ide.eclipse.ddms.debuggerConnector">
- <connector class="com.android.ide.eclipse.adt.DebuggerConnector">
- </connector>
- </extension>
- <extension point="com.android.ide.eclipse.ddms.sourceRevealer">
- <revealer class="com.android.ide.eclipse.adt.SourceRevealer">
- </revealer>
- </extension>
- <extension point="org.eclipse.ltk.core.refactoring.renameParticipants">
- <renameParticipant
- class="com.android.ide.eclipse.adt.internal.refactorings.core.AndroidTypeRenameParticipant"
- id="com.android.ide.eclipse.adt.internal.refactoring.core.AndroidTypeRenameParticipant"
- name="Android Rename Type Participant">
- <enablement>
- <with variable="element">
- <instanceof value="org.eclipse.jdt.core.IType">
- </instanceof>
- </with>
- <with variable="affectedNatures">
- <iterate operator="or">
- <equals value="com.android.ide.eclipse.adt.AndroidNature" />
- </iterate>
- </with>
- </enablement>
- </renameParticipant>
- <renameParticipant
- class="com.android.ide.eclipse.adt.internal.refactorings.core.RenameResourceParticipant"
- id="com.android.ide.eclipse.adt.internal.refactorings.core.RenameResourceParticipant"
- name="Android Rename Resource Participant">
- <enablement>
- <with variable="element">
- <or>
- <instanceof value="org.eclipse.jdt.core.IField"/>
- <instanceof value="org.eclipse.core.resources.IResource" />
- <instanceof value="java.lang.String" />
- </or>
- </with>
- <with variable="affectedNatures">
- <iterate operator="or">
- <equals value="com.android.ide.eclipse.adt.AndroidNature" />
- </iterate>
- </with>
- </enablement>
- </renameParticipant>
- <renameParticipant
- class="com.android.ide.eclipse.adt.internal.refactorings.core.AndroidPackageRenameParticipant"
- id="com.android.ide.eclipse.adt.internal.refactoring.core.AndroidPackageRenameParticipant"
- name="Android Rename Package Participant">
- <enablement>
- <with variable="element">
- <instanceof value="org.eclipse.jdt.core.IPackageFragment">
- </instanceof>
- </with>
- <with variable="affectedNatures">
- <iterate operator="or">
- <equals value="com.android.ide.eclipse.adt.AndroidNature" />
- </iterate>
- </with>
- </enablement>
- </renameParticipant>
- </extension>
- <extension point="org.eclipse.ltk.core.refactoring.moveParticipants">
- <moveParticipant
- class="com.android.ide.eclipse.adt.internal.refactorings.core.AndroidTypeMoveParticipant"
- id="com.android.ide.eclipse.adt.internal.refactoring.core.androidTypeMoveParticipant"
- name="Android Move Type Participant">
- <enablement>
- <with variable="element">
- <instanceof value="org.eclipse.jdt.core.IType">
- </instanceof>
- </with>
- <with variable="affectedNatures">
- <iterate operator="or">
- <equals value="com.android.ide.eclipse.adt.AndroidNature" />
- </iterate>
- </with>
- </enablement>
- </moveParticipant>
- </extension>
- <extension point="org.eclipse.ui.workbench.texteditor.hyperlinkDetectorTargets">
- <target
- id="com.android.ide.eclipse.xmlCode"
- name="XML Editor">
- <context type="org.eclipse.ui.texteditor.ITextEditor" />
- </target>
- </extension>
- <extension point="org.eclipse.ui.workbench.texteditor.hyperlinkDetectors">
- <hyperlinkDetector
- class="com.android.ide.eclipse.adt.internal.editors.Hyperlinks$XmlResolver"
- id="com.android.ide.eclipse.xmlCodeResolver"
- name="Android XML Hyperlink Detector"
- targetId="com.android.ide.eclipse.xmlCode">
- </hyperlinkDetector>
- <hyperlinkDetector
- class="com.android.ide.eclipse.adt.internal.editors.Hyperlinks$JavaResolver"
- id="com.android.ide.eclipse.javaCodeResolver"
- name="Android Java Hyperlink Detector"
- targetId="org.eclipse.jdt.ui.javaCode">
- </hyperlinkDetector>
- <!--
- Register this hyperlink provider TWICE, once without any modifier keys, and
- once with Modifier1+Modifier2. The one without (which will pick up the default
- of M1) will typically duel with the builtin Java hyperlink resolver, so the
- user gets a popup and must choose our resolver with the arrow key or mouse
- action. The second registration adds a quick bypass for that.
- -->
- <hyperlinkDetector
- class="com.android.ide.eclipse.adt.internal.editors.Hyperlinks$JavaResolver"
- id="com.android.ide.eclipse.javaCodeResolver2"
- modifierKeys="M1+M2+M3"
- name="Android Java Hyperlink Detector (Extra Modifier Key)"
- targetId="org.eclipse.jdt.ui.javaCode">
- </hyperlinkDetector>
- </extension>
- <extension point="org.eclipse.ui.bindings">
- <key
- sequence="M3+M2+A S"
- contextId="org.eclipse.ui.contexts.window"
- commandId="com.android.ide.eclipse.adt.refactoring.extract.string"
- schemeId="org.eclipse.ui.defaultAcceleratorConfiguration" />
- <key
- sequence="M3+M2+A D"
- contextId="org.eclipse.ui.contexts.window"
- commandId="com.android.ide.eclipse.adt.launch.LaunchShortcut.debug"
- schemeId="org.eclipse.ui.defaultAcceleratorConfiguration" />
- <key
- sequence="M3+M2+A R"
- contextId="org.eclipse.ui.contexts.window"
- commandId="com.android.ide.eclipse.adt.launch.LaunchShortcut.run"
- schemeId="org.eclipse.ui.defaultAcceleratorConfiguration" />
- <!-- Rebind the select-enclosing actions from WTP's M2+M3 to M2+M4 to be
- consistent with Java files. The contextId is org.eclipse.core.runtime.xml
- instead of org.eclipse.wst.sse.ui.structuredTextEditorScope to avoid
- keyboard conflict warnings (and an action selection dialog.)
- -->
- <key
- platform="carbon"
- sequence="CTRL+SHIFT+ARROW_UP"
- contextId="org.eclipse.core.runtime.xml"
- commandId="org.eclipse.wst.sse.ui.structure.select.enclosing"
- schemeId="org.eclipse.ui.defaultAcceleratorConfiguration" />
- <key
- platform="carbon"
- sequence="CTRL+SHIFT+ARROW_DOWN"
- contextId="org.eclipse.core.runtime.xml"
- commandId="org.eclipse.wst.sse.ui.structure.select.last"
- schemeId="org.eclipse.ui.defaultAcceleratorConfiguration" />
- </extension>
- <extension point="org.eclipse.core.contenttype.contentTypes">
- <content-type
- describer="com.android.ide.eclipse.adt.internal.editors.binaryxml.BinaryXMLDescriber"
- file-extensions="xml"
- id="com.android.ide.eclipse.adt.binaryXml"
- name="Android Binary XML"
- priority="high">
- </content-type>
- </extension>
- <extension point="org.eclipse.ui.startup">
- <startup class="com.android.ide.eclipse.adt.internal.welcome.AdtStartup"/>
- </extension>
-
- <!-- workaround for bug 15003. -->
- <extension
- point="org.eclipse.core.filebuffers.documentCreation"
- id="binaryXmlfactories"
- name="Binary XML Document Factory Extension">
- <factory
- contentTypeId="com.android.ide.eclipse.adt.binaryXml"
- class="org.eclipse.wst.sse.core.internal.filebuffers.BasicStructuredDocumentFactory" />
- </extension>
-</plugin>
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/pom.xml b/eclipse/plugins/com.android.ide.eclipse.adt/pom.xml
deleted file mode 100644
index a0257be28..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/pom.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <version>24.3.3-SNAPSHOT</version>
- <artifactId>com.android.ide.eclipse.adt</artifactId>
- <packaging>eclipse-plugin</packaging>
- <name>adt</name>
-
- <parent>
- <relativePath>../../pom.xml</relativePath>
- <groupId>adt.group</groupId>
- <artifactId>parent</artifactId>
- <version>1.0.0-SNAPSHOT</version>
- </parent>
-</project>
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/AbsListViewRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/AbsListViewRule.java
deleted file mode 100644
index cd1b0fcae..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/AbsListViewRule.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import com.android.ide.common.api.IViewRule;
-
-/**
- * An {@link IViewRule} for android.widget.AbsListViewRule
- */
-public class AbsListViewRule extends IgnoredLayoutRule {
-
- // GridViews and ListViews are not configurable via XML
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/AbsoluteLayoutRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/AbsoluteLayoutRule.java
deleted file mode 100644
index 3ec3b5f1a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/AbsoluteLayoutRule.java
+++ /dev/null
@@ -1,254 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_LAYOUT_X;
-import static com.android.SdkConstants.ATTR_LAYOUT_Y;
-import static com.android.SdkConstants.VALUE_N_DP;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.DrawingStyle;
-import com.android.ide.common.api.DropFeedback;
-import com.android.ide.common.api.IDragElement;
-import com.android.ide.common.api.IFeedbackPainter;
-import com.android.ide.common.api.IGraphics;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.INodeHandler;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.Point;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.api.SegmentType;
-import com.android.utils.Pair;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-/**
- * An {@link IViewRule} for android.widget.AbsoluteLayout and all its derived
- * classes.
- */
-public class AbsoluteLayoutRule extends BaseLayoutRule {
-
- @Override
- public List<String> getSelectionHint(@NonNull INode parentNode, @NonNull INode childNode) {
- List<String> infos = new ArrayList<String>(2);
- infos.add("AbsoluteLayout is deprecated.");
- infos.add("Use other layouts instead.");
- return infos;
- }
-
- // ==== Drag'n'drop support ====
- // The AbsoluteLayout accepts any drag'n'drop anywhere on its surface.
-
- @Override
- public DropFeedback onDropEnter(@NonNull INode targetNode, @Nullable Object targetView,
- final @Nullable IDragElement[] elements) {
-
- if (elements.length == 0) {
- return null;
- }
-
- DropFeedback df = new DropFeedback(null, new IFeedbackPainter() {
- @Override
- public void paint(@NonNull IGraphics gc, @NonNull INode node,
- @NonNull DropFeedback feedback) {
- // Paint callback for the AbsoluteLayout.
- // This is called by the canvas when a draw is needed.
- drawFeedback(gc, node, elements, feedback);
- }
- });
- df.errorMessage = "AbsoluteLayout is deprecated.";
- return df;
- }
-
- void drawFeedback(
- IGraphics gc,
- INode targetNode,
- IDragElement[] elements,
- DropFeedback feedback) {
- Rect b = targetNode.getBounds();
- if (!b.isValid()) {
- return;
- }
-
- // Highlight the receiver
- gc.useStyle(DrawingStyle.DROP_RECIPIENT);
- gc.drawRect(b);
-
- // Get the drop point
- Point p = (Point) feedback.userData;
-
- if (p == null) {
- return;
- }
-
- int x = p.x;
- int y = p.y;
-
- Rect be = elements[0].getBounds();
-
- if (be.isValid()) {
- // At least the first element has a bound. Draw rectangles
- // for all dropped elements with valid bounds, offset at
- // the drop point.
- int offsetX = x - be.x + (feedback.dragBounds != null ? feedback.dragBounds.x : 0);
- int offsetY = y - be.y + (feedback.dragBounds != null ? feedback.dragBounds.y : 0);
- gc.useStyle(DrawingStyle.DROP_PREVIEW);
- for (IDragElement element : elements) {
- drawElement(gc, element, offsetX, offsetY);
- }
- } else {
- // We don't have bounds for new elements. In this case
- // just draw cross hairs to the drop point.
- gc.useStyle(DrawingStyle.GUIDELINE);
- gc.drawLine(x, b.y, x, b.y + b.h);
- gc.drawLine(b.x, y, b.x + b.w, y);
-
- // Use preview lines to indicate the bottom quadrant as well (to
- // indicate that you are looking at the top left position of the
- // drop, not the center for example)
- gc.useStyle(DrawingStyle.DROP_PREVIEW);
- gc.drawLine(x, y, b.x + b.w, y);
- gc.drawLine(x, y, x, b.y + b.h);
- }
- }
-
- @Override
- public DropFeedback onDropMove(@NonNull INode targetNode, @NonNull IDragElement[] elements,
- @Nullable DropFeedback feedback, @NonNull Point p) {
- // Update the data used by the DropFeedback.paintCallback above.
- feedback.userData = p;
- feedback.requestPaint = true;
-
- return feedback;
- }
-
- @Override
- public void onDropLeave(@NonNull INode targetNode, @NonNull IDragElement[] elements,
- @Nullable DropFeedback feedback) {
- // Nothing to do.
- }
-
- @Override
- public void onDropped(final @NonNull INode targetNode, final @NonNull IDragElement[] elements,
- final @Nullable DropFeedback feedback, final @NonNull Point p) {
-
- final Rect b = targetNode.getBounds();
- if (!b.isValid()) {
- return;
- }
-
- // Collect IDs from dropped elements and remap them to new IDs
- // if this is a copy or from a different canvas.
- final Map<String, Pair<String, String>> idMap = getDropIdMap(targetNode, elements,
- feedback.isCopy || !feedback.sameCanvas);
-
- targetNode.editXml("Add elements to AbsoluteLayout", new INodeHandler() {
- @Override
- public void handle(@NonNull INode node) {
- boolean first = true;
- Point offset = null;
-
- // Now write the new elements.
- for (IDragElement element : elements) {
- String fqcn = element.getFqcn();
- Rect be = element.getBounds();
-
- INode newChild = targetNode.appendChild(fqcn);
-
- // Copy all the attributes, modifying them as needed.
- addAttributes(newChild, element, idMap, DEFAULT_ATTR_FILTER);
-
- int deltaX = (feedback.dragBounds != null ? feedback.dragBounds.x : 0);
- int deltaY = (feedback.dragBounds != null ? feedback.dragBounds.y : 0);
-
- int x = p.x - b.x + deltaX;
- int y = p.y - b.y + deltaY;
-
- if (first) {
- first = false;
- if (be.isValid()) {
- offset = new Point(x - be.x, y - be.y);
- }
- } else if (offset != null && be.isValid()) {
- x = offset.x + be.x;
- y = offset.y + be.y;
- } else {
- x += 10;
- y += be.isValid() ? be.h : 10;
- }
-
- double scale = feedback.dipScale;
- if (scale != 1.0) {
- x *= scale;
- y *= scale;
- }
-
- newChild.setAttribute(ANDROID_URI, ATTR_LAYOUT_X,
- String.format(VALUE_N_DP, x));
- newChild.setAttribute(ANDROID_URI, ATTR_LAYOUT_Y,
- String.format(VALUE_N_DP, y));
-
- addInnerElements(newChild, element, idMap);
- }
- }
- });
- }
-
- /**
- * {@inheritDoc}
- * <p>
- * Overridden in this layout in order to let the top left coordinate be affected by
- * the resize operation too. In other words, dragging the top left corner to resize a
- * widget will not only change the size of the widget, it will also move it (though in
- * this case, the bottom right corner will stay fixed).
- */
- @Override
- protected void setNewSizeBounds(ResizeState resizeState, INode node, INode layout,
- Rect previousBounds, Rect newBounds, SegmentType horizontalEdge,
- SegmentType verticalEdge) {
- super.setNewSizeBounds(resizeState, node, layout, previousBounds, newBounds,
- horizontalEdge, verticalEdge);
- if (verticalEdge != null && newBounds.x != previousBounds.x) {
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_X,
- String.format(VALUE_N_DP,
- mRulesEngine.pxToDp(newBounds.x - node.getParent().getBounds().x)));
- }
- if (horizontalEdge != null && newBounds.y != previousBounds.y) {
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_Y,
- String.format(VALUE_N_DP,
- mRulesEngine.pxToDp(newBounds.y - node.getParent().getBounds().y)));
- }
- }
-
- @Override
- protected String getResizeUpdateMessage(ResizeState resizeState, INode child, INode parent,
- Rect newBounds, SegmentType horizontalEdge, SegmentType verticalEdge) {
- Rect parentBounds = parent.getBounds();
- if (horizontalEdge == SegmentType.BOTTOM && verticalEdge == SegmentType.RIGHT) {
- return super.getResizeUpdateMessage(resizeState, child, parent, newBounds,
- horizontalEdge, verticalEdge);
- }
- return String.format("x=%d, y=%d\nwidth=%s, height=%s",
- mRulesEngine.pxToDp(newBounds.x - parentBounds.x),
- mRulesEngine.pxToDp(newBounds.y - parentBounds.y),
- resizeState.getWidthAttribute(), resizeState.getHeightAttribute());
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/AdapterViewRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/AdapterViewRule.java
deleted file mode 100644
index 28f5fc95e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/AdapterViewRule.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.DrawingStyle;
-import com.android.ide.common.api.DropFeedback;
-import com.android.ide.common.api.IDragElement;
-import com.android.ide.common.api.IFeedbackPainter;
-import com.android.ide.common.api.IGraphics;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.Point;
-import com.android.ide.common.api.Rect;
-
-/** Rule for AdapterView subclasses that don't have more specific rules */
-public class AdapterViewRule extends BaseLayoutRule {
- @Override
- public DropFeedback onDropEnter(@NonNull INode targetNode, @Nullable Object targetView,
- @Nullable IDragElement[] elements) {
- // You are not allowed to insert children into AdapterViews; you must
- // use the dedicated addView methods etc dynamically
- DropFeedback dropFeedback = new DropFeedback(null, new IFeedbackPainter() {
- @Override
- public void paint(@NonNull IGraphics gc, @NonNull INode node,
- @NonNull DropFeedback feedback) {
- Rect b = node.getBounds();
- if (b.isValid()) {
- gc.useStyle(DrawingStyle.DROP_RECIPIENT);
- gc.drawRect(b);
- }
- }
- });
- String fqcn = targetNode.getFqcn();
- String name = fqcn.substring(fqcn.lastIndexOf('.') +1);
- dropFeedback.errorMessage = String.format(
- "%s cannot be configured via XML; add content to the AdapterView using Java code",
- name);
- dropFeedback.invalidTarget = true;
- return dropFeedback;
- }
-
- @Override
- public DropFeedback onDropMove(@NonNull INode targetNode, @NonNull IDragElement[] elements,
- @Nullable DropFeedback feedback, @NonNull Point p) {
- feedback.invalidTarget = true;
- return feedback;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/BaseLayoutRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/BaseLayoutRule.java
deleted file mode 100644
index df2c8f473..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/BaseLayoutRule.java
+++ /dev/null
@@ -1,878 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ATTR_LAYOUT_ABOVE;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_BASELINE;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_BOTTOM;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_LEFT;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_PARENT_BOTTOM;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_PARENT_LEFT;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_PARENT_RIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_PARENT_TOP;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_RIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_TOP;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_WITH_PARENT_MISSING;
-import static com.android.SdkConstants.ATTR_LAYOUT_BELOW;
-import static com.android.SdkConstants.ATTR_LAYOUT_CENTER_HORIZONTAL;
-import static com.android.SdkConstants.ATTR_LAYOUT_CENTER_IN_PARENT;
-import static com.android.SdkConstants.ATTR_LAYOUT_CENTER_VERTICAL;
-import static com.android.SdkConstants.ATTR_LAYOUT_COLUMN;
-import static com.android.SdkConstants.ATTR_LAYOUT_COLUMN_SPAN;
-import static com.android.SdkConstants.ATTR_LAYOUT_GRAVITY;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_MARGIN;
-import static com.android.SdkConstants.ATTR_LAYOUT_MARGIN_BOTTOM;
-import static com.android.SdkConstants.ATTR_LAYOUT_MARGIN_LEFT;
-import static com.android.SdkConstants.ATTR_LAYOUT_MARGIN_RIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_MARGIN_TOP;
-import static com.android.SdkConstants.ATTR_LAYOUT_ROW;
-import static com.android.SdkConstants.ATTR_LAYOUT_ROW_SPAN;
-import static com.android.SdkConstants.ATTR_LAYOUT_TO_LEFT_OF;
-import static com.android.SdkConstants.ATTR_LAYOUT_TO_RIGHT_OF;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.ATTR_LAYOUT_X;
-import static com.android.SdkConstants.ATTR_LAYOUT_Y;
-import static com.android.SdkConstants.VALUE_FILL_PARENT;
-import static com.android.SdkConstants.VALUE_MATCH_PARENT;
-import static com.android.SdkConstants.VALUE_WRAP_CONTENT;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.DrawingStyle;
-import com.android.ide.common.api.DropFeedback;
-import com.android.ide.common.api.IAttributeInfo;
-import com.android.ide.common.api.IClientRulesEngine;
-import com.android.ide.common.api.IDragElement;
-import com.android.ide.common.api.IDragElement.IDragAttribute;
-import com.android.ide.common.api.IFeedbackPainter;
-import com.android.ide.common.api.IGraphics;
-import com.android.ide.common.api.IMenuCallback;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.INodeHandler;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.MarginType;
-import com.android.ide.common.api.Point;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.api.RuleAction;
-import com.android.ide.common.api.RuleAction.ChoiceProvider;
-import com.android.ide.common.api.Segment;
-import com.android.ide.common.api.SegmentType;
-import com.android.utils.Pair;
-
-import java.net.URL;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * A {@link IViewRule} for all layouts.
- */
-public class BaseLayoutRule extends BaseViewRule {
- private static final String ACTION_FILL_WIDTH = "_fillW"; //$NON-NLS-1$
- private static final String ACTION_FILL_HEIGHT = "_fillH"; //$NON-NLS-1$
- private static final String ACTION_MARGIN = "_margin"; //$NON-NLS-1$
- private static final URL ICON_MARGINS =
- BaseLayoutRule.class.getResource("margins.png"); //$NON-NLS-1$
- private static final URL ICON_GRAVITY =
- BaseLayoutRule.class.getResource("gravity.png"); //$NON-NLS-1$
- private static final URL ICON_FILL_WIDTH =
- BaseLayoutRule.class.getResource("fillwidth.png"); //$NON-NLS-1$
- private static final URL ICON_FILL_HEIGHT =
- BaseLayoutRule.class.getResource("fillheight.png"); //$NON-NLS-1$
-
- // ==== Layout Actions support ====
-
- // The Margin layout parameters are available for LinearLayout, FrameLayout, RelativeLayout,
- // and their subclasses.
- protected final RuleAction createMarginAction(final INode parentNode,
- final List<? extends INode> children) {
-
- final List<? extends INode> targets = children == null || children.size() == 0 ?
- Collections.singletonList(parentNode)
- : children;
- final INode first = targets.get(0);
-
- IMenuCallback actionCallback = new IMenuCallback() {
- @Override
- public void action(@NonNull RuleAction action,
- @NonNull List<? extends INode> selectedNodes,
- final @Nullable String valueId,
- final @Nullable Boolean newValue) {
- parentNode.editXml("Change Margins", new INodeHandler() {
- @Override
- public void handle(@NonNull INode n) {
- String uri = ANDROID_URI;
- String all = first.getStringAttr(uri, ATTR_LAYOUT_MARGIN);
- String left = first.getStringAttr(uri, ATTR_LAYOUT_MARGIN_LEFT);
- String right = first.getStringAttr(uri, ATTR_LAYOUT_MARGIN_RIGHT);
- String top = first.getStringAttr(uri, ATTR_LAYOUT_MARGIN_TOP);
- String bottom = first.getStringAttr(uri, ATTR_LAYOUT_MARGIN_BOTTOM);
- String[] margins = mRulesEngine.displayMarginInput(all, left,
- right, top, bottom);
- if (margins != null) {
- assert margins.length == 5;
- for (INode child : targets) {
- child.setAttribute(uri, ATTR_LAYOUT_MARGIN, margins[0]);
- child.setAttribute(uri, ATTR_LAYOUT_MARGIN_LEFT, margins[1]);
- child.setAttribute(uri, ATTR_LAYOUT_MARGIN_RIGHT, margins[2]);
- child.setAttribute(uri, ATTR_LAYOUT_MARGIN_TOP, margins[3]);
- child.setAttribute(uri, ATTR_LAYOUT_MARGIN_BOTTOM, margins[4]);
- }
- }
- }
- });
- }
- };
-
- return RuleAction.createAction(ACTION_MARGIN, "Change Margins...", actionCallback,
- ICON_MARGINS, 40, false);
- }
-
- // Both LinearLayout and RelativeLayout have a gravity (but RelativeLayout applies it
- // to the parent whereas for LinearLayout it's on the children)
- protected final RuleAction createGravityAction(final List<? extends INode> targets, final
- String attributeName) {
- if (targets != null && targets.size() > 0) {
- final INode first = targets.get(0);
- ChoiceProvider provider = new ChoiceProvider() {
- @Override
- public void addChoices(@NonNull List<String> titles, @NonNull List<URL> iconUrls,
- @NonNull List<String> ids) {
- IAttributeInfo info = first.getAttributeInfo(ANDROID_URI, attributeName);
- if (info != null) {
- // Generate list of possible gravity value constants
- assert info.getFormats().contains(IAttributeInfo.Format.FLAG);
- for (String name : info.getFlagValues()) {
- titles.add(getAttributeDisplayName(name));
- ids.add(name);
- }
- }
- }
- };
-
- return RuleAction.createChoices("_gravity", "Change Gravity", //$NON-NLS-1$
- new PropertyCallback(targets, "Change Gravity", ANDROID_URI,
- attributeName),
- provider,
- first.getStringAttr(ANDROID_URI, attributeName), ICON_GRAVITY,
- 43, false);
- }
-
- return null;
- }
-
- @Override
- public void addLayoutActions(
- @NonNull List<RuleAction> actions,
- final @NonNull INode parentNode,
- final @NonNull List<? extends INode> children) {
- super.addLayoutActions(actions, parentNode, children);
-
- final List<? extends INode> targets = children == null || children.size() == 0 ?
- Collections.singletonList(parentNode)
- : children;
- final INode first = targets.get(0);
-
- // Shared action callback
- IMenuCallback actionCallback = new IMenuCallback() {
- @Override
- public void action(
- @NonNull RuleAction action,
- @NonNull List<? extends INode> selectedNodes,
- final @Nullable String valueId,
- final @Nullable Boolean newValue) {
- final String actionId = action.getId();
- final String undoLabel;
- if (actionId.equals(ACTION_FILL_WIDTH)) {
- undoLabel = "Change Width Fill";
- } else if (actionId.equals(ACTION_FILL_HEIGHT)) {
- undoLabel = "Change Height Fill";
- } else {
- return;
- }
- parentNode.editXml(undoLabel, new INodeHandler() {
- @Override
- public void handle(@NonNull INode n) {
- String attribute = actionId.equals(ACTION_FILL_WIDTH)
- ? ATTR_LAYOUT_WIDTH : ATTR_LAYOUT_HEIGHT;
- String value;
- if (newValue) {
- if (supportsMatchParent()) {
- value = VALUE_MATCH_PARENT;
- } else {
- value = VALUE_FILL_PARENT;
- }
- } else {
- value = VALUE_WRAP_CONTENT;
- }
- for (INode child : targets) {
- child.setAttribute(ANDROID_URI, attribute, value);
- }
- }
- });
- }
- };
-
- actions.add(RuleAction.createToggle(ACTION_FILL_WIDTH, "Toggle Fill Width",
- isFilled(first, ATTR_LAYOUT_WIDTH), actionCallback, ICON_FILL_WIDTH, 10, false));
- actions.add(RuleAction.createToggle(ACTION_FILL_HEIGHT, "Toggle Fill Height",
- isFilled(first, ATTR_LAYOUT_HEIGHT), actionCallback, ICON_FILL_HEIGHT, 20, false));
- }
-
- // ==== Paste support ====
-
- /**
- * The default behavior for pasting in a layout is to simulate a drop in the
- * top-left corner of the view.
- * <p/>
- * Note that we explicitly do not call super() here -- the BaseViewRule.onPaste handler
- * will call onPasteBeforeChild() instead.
- * <p/>
- * Derived layouts should override this behavior if not appropriate.
- */
- @Override
- public void onPaste(@NonNull INode targetNode, @Nullable Object targetView,
- @NonNull IDragElement[] elements) {
- DropFeedback feedback = onDropEnter(targetNode, targetView, elements);
- if (feedback != null) {
- Point p = targetNode.getBounds().getTopLeft();
- feedback = onDropMove(targetNode, elements, feedback, p);
- if (feedback != null) {
- onDropLeave(targetNode, elements, feedback);
- onDropped(targetNode, elements, feedback, p);
- }
- }
- }
-
- /**
- * The default behavior for pasting in a layout with a specific child target
- * is to simulate a drop right above the top left of the given child target.
- * <p/>
- * This method is invoked by BaseView when onPaste() is called --
- * views don't generally accept children and instead use the target node as
- * a hint to paste "before" it.
- *
- * @param parentNode the parent node we're pasting into
- * @param parentView the view object for the parent layout, or null
- * @param targetNode the first selected node
- * @param elements the elements being pasted
- */
- public void onPasteBeforeChild(INode parentNode, Object parentView, INode targetNode,
- IDragElement[] elements) {
- DropFeedback feedback = onDropEnter(parentNode, parentView, elements);
- if (feedback != null) {
- Point parentP = parentNode.getBounds().getTopLeft();
- Point targetP = targetNode.getBounds().getTopLeft();
- if (parentP.y < targetP.y) {
- targetP.y -= 1;
- }
-
- feedback = onDropMove(parentNode, elements, feedback, targetP);
- if (feedback != null) {
- onDropLeave(parentNode, elements, feedback);
- onDropped(parentNode, elements, feedback, targetP);
- }
- }
- }
-
- // ==== Utility methods used by derived layouts ====
-
- /**
- * Draws the bounds of the given elements and all its children elements in the canvas
- * with the specified offset.
- *
- * @param gc the graphics context
- * @param element the element to be drawn
- * @param offsetX a horizontal delta to add to the current bounds of the element when
- * drawing it
- * @param offsetY a vertical delta to add to the current bounds of the element when
- * drawing it
- */
- public void drawElement(IGraphics gc, IDragElement element, int offsetX, int offsetY) {
- Rect b = element.getBounds();
- if (b.isValid()) {
- gc.drawRect(b.x + offsetX, b.y + offsetY, b.x + offsetX + b.w, b.y + offsetY + b.h);
- }
-
- for (IDragElement inner : element.getInnerElements()) {
- drawElement(gc, inner, offsetX, offsetY);
- }
- }
-
- /**
- * Collect all the "android:id" IDs from the dropped elements. When moving
- * objects within the same canvas, that's all there is to do. However if the
- * objects are moved to a different canvas or are copied then set
- * createNewIds to true to find the existing IDs under targetNode and create
- * a map with new non-conflicting unique IDs as needed. Returns a map String
- * old-id => tuple (String new-id, String fqcn) where fqcn is the FQCN of
- * the element.
- */
- protected static Map<String, Pair<String, String>> getDropIdMap(INode targetNode,
- IDragElement[] elements, boolean createNewIds) {
- Map<String, Pair<String, String>> idMap = new HashMap<String, Pair<String, String>>();
-
- if (createNewIds) {
- collectIds(idMap, elements);
- // Need to remap ids if necessary
- idMap = remapIds(targetNode, idMap);
- }
-
- return idMap;
- }
-
- /**
- * Fills idMap with a map String id => tuple (String id, String fqcn) where
- * fqcn is the FQCN of the element (in case we want to generate new IDs
- * based on the element type.)
- *
- * @see #getDropIdMap
- */
- protected static Map<String, Pair<String, String>> collectIds(
- Map<String, Pair<String, String>> idMap,
- IDragElement[] elements) {
- for (IDragElement element : elements) {
- IDragAttribute attr = element.getAttribute(ANDROID_URI, ATTR_ID);
- if (attr != null) {
- String id = attr.getValue();
- if (id != null && id.length() > 0) {
- idMap.put(id, Pair.of(id, element.getFqcn()));
- }
- }
-
- collectIds(idMap, element.getInnerElements());
- }
-
- return idMap;
- }
-
- /**
- * Used by #getDropIdMap to find new IDs in case of conflict.
- */
- protected static Map<String, Pair<String, String>> remapIds(INode node,
- Map<String, Pair<String, String>> idMap) {
- // Visit the document to get a list of existing ids
- Set<String> existingIdSet = new HashSet<String>();
- collectExistingIds(node.getRoot(), existingIdSet);
-
- Map<String, Pair<String, String>> new_map = new HashMap<String, Pair<String, String>>();
- for (Map.Entry<String, Pair<String, String>> entry : idMap.entrySet()) {
- String key = entry.getKey();
- Pair<String, String> value = entry.getValue();
-
- String id = normalizeId(key);
-
- if (!existingIdSet.contains(id)) {
- // Not a conflict. Use as-is.
- new_map.put(key, value);
- if (!key.equals(id)) {
- new_map.put(id, value);
- }
- } else {
- // There is a conflict. Get a new id.
- String new_id = findNewId(value.getSecond(), existingIdSet);
- value = Pair.of(new_id, value.getSecond());
- new_map.put(id, value);
- new_map.put(id.replaceFirst("@\\+", "@"), value); //$NON-NLS-1$ //$NON-NLS-2$
- }
- }
-
- return new_map;
- }
-
- /**
- * Used by #remapIds to find a new ID for a conflicting element.
- */
- protected static String findNewId(String fqcn, Set<String> existingIdSet) {
- // Get the last component of the FQCN (e.g. "android.view.Button" =>
- // "Button")
- String name = fqcn.substring(fqcn.lastIndexOf('.') + 1);
-
- for (int i = 1; i < 1000000; i++) {
- String id = String.format("@+id/%s%02d", name, i); //$NON-NLS-1$
- if (!existingIdSet.contains(id)) {
- existingIdSet.add(id);
- return id;
- }
- }
-
- // We'll never reach here.
- return null;
- }
-
- /**
- * Used by #getDropIdMap to find existing IDs recursively.
- */
- protected static void collectExistingIds(INode root, Set<String> existingIdSet) {
- if (root == null) {
- return;
- }
-
- String id = root.getStringAttr(ANDROID_URI, ATTR_ID);
- if (id != null) {
- id = normalizeId(id);
-
- if (!existingIdSet.contains(id)) {
- existingIdSet.add(id);
- }
- }
-
- for (INode child : root.getChildren()) {
- collectExistingIds(child, existingIdSet);
- }
- }
-
- /**
- * Transforms @id/name into @+id/name to treat both forms the same way.
- */
- protected static String normalizeId(String id) {
- if (id.indexOf("@+") == -1) { //$NON-NLS-1$
- id = id.replaceFirst("@", "@+"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- return id;
- }
-
- /**
- * For use by {@link BaseLayoutRule#addAttributes} A filter should return a
- * valid replacement string.
- */
- protected static interface AttributeFilter {
- String replace(String attributeUri, String attributeName, String attributeValue);
- }
-
- private static final String[] EXCLUDED_ATTRIBUTES = new String[] {
- // Common
- ATTR_LAYOUT_GRAVITY,
-
- // from AbsoluteLayout
- ATTR_LAYOUT_X,
- ATTR_LAYOUT_Y,
-
- // from RelativeLayout
- ATTR_LAYOUT_ABOVE,
- ATTR_LAYOUT_BELOW,
- ATTR_LAYOUT_TO_LEFT_OF,
- ATTR_LAYOUT_TO_RIGHT_OF,
- ATTR_LAYOUT_ALIGN_BASELINE,
- ATTR_LAYOUT_ALIGN_TOP,
- ATTR_LAYOUT_ALIGN_BOTTOM,
- ATTR_LAYOUT_ALIGN_LEFT,
- ATTR_LAYOUT_ALIGN_RIGHT,
- ATTR_LAYOUT_ALIGN_PARENT_TOP,
- ATTR_LAYOUT_ALIGN_PARENT_BOTTOM,
- ATTR_LAYOUT_ALIGN_PARENT_LEFT,
- ATTR_LAYOUT_ALIGN_PARENT_RIGHT,
- ATTR_LAYOUT_ALIGN_WITH_PARENT_MISSING,
- ATTR_LAYOUT_CENTER_HORIZONTAL,
- ATTR_LAYOUT_CENTER_IN_PARENT,
- ATTR_LAYOUT_CENTER_VERTICAL,
-
- // From GridLayout
- ATTR_LAYOUT_ROW,
- ATTR_LAYOUT_ROW_SPAN,
- ATTR_LAYOUT_COLUMN,
- ATTR_LAYOUT_COLUMN_SPAN
- };
-
- /**
- * Default attribute filter used by the various layouts to filter out some properties
- * we don't want to offer.
- */
- public static final AttributeFilter DEFAULT_ATTR_FILTER = new AttributeFilter() {
- Set<String> mExcludes;
-
- @Override
- public String replace(String uri, String name, String value) {
- if (!ANDROID_URI.equals(uri)) {
- return value;
- }
-
- if (mExcludes == null) {
- mExcludes = new HashSet<String>(EXCLUDED_ATTRIBUTES.length);
- mExcludes.addAll(Arrays.asList(EXCLUDED_ATTRIBUTES));
- }
-
- return mExcludes.contains(name) ? null : value;
- }
- };
-
- /**
- * Copies all the attributes from oldElement to newNode. Uses the idMap to
- * transform the value of all attributes of Format.REFERENCE. If filter is
- * non-null, it's a filter that can rewrite the attribute string.
- */
- protected static void addAttributes(INode newNode, IDragElement oldElement,
- Map<String, Pair<String, String>> idMap, AttributeFilter filter) {
-
- for (IDragAttribute attr : oldElement.getAttributes()) {
- String uri = attr.getUri();
- String name = attr.getName();
- String value = attr.getValue();
-
- IAttributeInfo attrInfo = newNode.getAttributeInfo(uri, name);
- if (attrInfo != null) {
- if (attrInfo.getFormats().contains(IAttributeInfo.Format.REFERENCE)) {
- if (idMap.containsKey(value)) {
- value = idMap.get(value).getFirst();
- }
- }
- }
-
- if (filter != null) {
- value = filter.replace(uri, name, value);
- }
- if (value != null && value.length() > 0) {
- newNode.setAttribute(uri, name, value);
- }
- }
- }
-
- /**
- * Adds all the children elements of oldElement to newNode, recursively.
- * Attributes are adjusted by calling addAttributes with idMap as necessary,
- * with no closure filter.
- */
- protected static void addInnerElements(INode newNode, IDragElement oldElement,
- Map<String, Pair<String, String>> idMap) {
-
- for (IDragElement element : oldElement.getInnerElements()) {
- String fqcn = element.getFqcn();
- INode childNode = newNode.appendChild(fqcn);
-
- addAttributes(childNode, element, idMap, null /* filter */);
- addInnerElements(childNode, element, idMap);
- }
- }
-
- /**
- * Insert the given elements into the given node at the given position
- *
- * @param targetNode the node to insert into
- * @param elements the elements to insert
- * @param createNewIds if true, generate new ids when there is a conflict
- * @param initialInsertPos index among targetnode's children which to insert the
- * children
- */
- public static void insertAt(final INode targetNode, final IDragElement[] elements,
- final boolean createNewIds, final int initialInsertPos) {
-
- // Collect IDs from dropped elements and remap them to new IDs
- // if this is a copy or from a different canvas.
- final Map<String, Pair<String, String>> idMap = getDropIdMap(targetNode, elements,
- createNewIds);
-
- targetNode.editXml("Insert Elements", new INodeHandler() {
-
- @Override
- public void handle(@NonNull INode node) {
- // Now write the new elements.
- int insertPos = initialInsertPos;
- for (IDragElement element : elements) {
- String fqcn = element.getFqcn();
-
- INode newChild = targetNode.insertChildAt(fqcn, insertPos);
-
- // insertPos==-1 means to insert at the end. Otherwise
- // increment the insertion position.
- if (insertPos >= 0) {
- insertPos++;
- }
-
- // Copy all the attributes, modifying them as needed.
- addAttributes(newChild, element, idMap, DEFAULT_ATTR_FILTER);
- addInnerElements(newChild, element, idMap);
- }
- }
- });
- }
-
- // ---- Resizing ----
-
- /** Creates a new {@link ResizeState} object to track resize state */
- protected ResizeState createResizeState(INode layout, Object layoutView, INode node) {
- return new ResizeState(this, layout, layoutView, node);
- }
-
- @Override
- public DropFeedback onResizeBegin(@NonNull INode child, @NonNull INode parent,
- @Nullable SegmentType horizontalEdge, @Nullable SegmentType verticalEdge,
- @Nullable Object childView, @Nullable Object parentView) {
- ResizeState state = createResizeState(parent, parentView, child);
- state.horizontalEdgeType = horizontalEdge;
- state.verticalEdgeType = verticalEdge;
-
- // Compute preferred (wrap_content) size such that we can offer guidelines to
- // snap to the preferred size
- Map<INode, Rect> sizes = mRulesEngine.measureChildren(parent,
- new IClientRulesEngine.AttributeFilter() {
- @Override
- public String getAttribute(@NonNull INode node, @Nullable String namespace,
- @NonNull String localName) {
- // Change attributes to wrap_content
- if (ATTR_LAYOUT_WIDTH.equals(localName)
- && SdkConstants.NS_RESOURCES.equals(namespace)) {
- return VALUE_WRAP_CONTENT;
- }
- if (ATTR_LAYOUT_HEIGHT.equals(localName)
- && SdkConstants.NS_RESOURCES.equals(namespace)) {
- return VALUE_WRAP_CONTENT;
- }
-
- return null;
- }
- });
- if (sizes != null) {
- state.wrapBounds = sizes.get(child);
- }
-
- return new DropFeedback(state, new IFeedbackPainter() {
- @Override
- public void paint(@NonNull IGraphics gc, @NonNull INode node,
- @NonNull DropFeedback feedback) {
- ResizeState resizeState = (ResizeState) feedback.userData;
- if (resizeState != null && resizeState.bounds != null) {
- paintResizeFeedback(gc, node, resizeState);
- }
- }
- });
- }
-
- protected void paintResizeFeedback(IGraphics gc, INode node, ResizeState resizeState) {
- gc.useStyle(DrawingStyle.RESIZE_PREVIEW);
- Rect b = resizeState.bounds;
- gc.drawRect(b);
-
- if (resizeState.horizontalFillSegment != null) {
- gc.useStyle(DrawingStyle.GUIDELINE);
- Segment s = resizeState.horizontalFillSegment;
- gc.drawLine(s.from, s.at, s.to, s.at);
- }
- if (resizeState.verticalFillSegment != null) {
- gc.useStyle(DrawingStyle.GUIDELINE);
- Segment s = resizeState.verticalFillSegment;
- gc.drawLine(s.at, s.from, s.at, s.to);
- }
-
- if (resizeState.wrapBounds != null) {
- gc.useStyle(DrawingStyle.GUIDELINE);
- int wrapWidth = resizeState.wrapBounds.w;
- int wrapHeight = resizeState.wrapBounds.h;
-
- // Show the "wrap_content" guideline.
- // If we are showing both the wrap_width and wrap_height lines
- // then we show at most the rectangle formed by the two lines;
- // otherwise we show the entire width of the line
- if (resizeState.horizontalEdgeType != null) {
- int y = -1;
- switch (resizeState.horizontalEdgeType) {
- case TOP:
- y = b.y + b.h - wrapHeight;
- break;
- case BOTTOM:
- y = b.y + wrapHeight;
- break;
- default: assert false : resizeState.horizontalEdgeType;
- }
- if (resizeState.verticalEdgeType != null) {
- switch (resizeState.verticalEdgeType) {
- case LEFT:
- gc.drawLine(b.x + b.w - wrapWidth, y, b.x + b.w, y);
- break;
- case RIGHT:
- gc.drawLine(b.x, y, b.x + wrapWidth, y);
- break;
- default: assert false : resizeState.verticalEdgeType;
- }
- } else {
- gc.drawLine(b.x, y, b.x + b.w, y);
- }
- }
- if (resizeState.verticalEdgeType != null) {
- int x = -1;
- switch (resizeState.verticalEdgeType) {
- case LEFT:
- x = b.x + b.w - wrapWidth;
- break;
- case RIGHT:
- x = b.x + wrapWidth;
- break;
- default: assert false : resizeState.verticalEdgeType;
- }
- if (resizeState.horizontalEdgeType != null) {
- switch (resizeState.horizontalEdgeType) {
- case TOP:
- gc.drawLine(x, b.y + b.h - wrapHeight, x, b.y + b.h);
- break;
- case BOTTOM:
- gc.drawLine(x, b.y, x, b.y + wrapHeight);
- break;
- default: assert false : resizeState.horizontalEdgeType;
- }
- } else {
- gc.drawLine(x, b.y, x, b.y + b.h);
- }
- }
- }
- }
-
- /**
- * Returns the maximum number of pixels will be considered a "match" when snapping
- * resize or move positions to edges or other constraints
- *
- * @return the maximum number of pixels to consider for snapping
- */
- public static final int getMaxMatchDistance() {
- // TODO - make constant once we're happy with the feel
- return 20;
- }
-
- @Override
- public void onResizeUpdate(@Nullable DropFeedback feedback, @NonNull INode child,
- @NonNull INode parent, @NonNull Rect newBounds, int modifierMask) {
- ResizeState state = (ResizeState) feedback.userData;
- state.bounds = newBounds;
- state.modifierMask = modifierMask;
-
- // Match on wrap bounds
- state.wrapWidth = state.wrapHeight = false;
- if (state.wrapBounds != null) {
- Rect b = state.wrapBounds;
- int maxMatchDistance = getMaxMatchDistance();
- if (state.horizontalEdgeType != null) {
- if (Math.abs(newBounds.h - b.h) < maxMatchDistance) {
- state.wrapHeight = true;
- if (state.horizontalEdgeType == SegmentType.TOP) {
- newBounds.y += newBounds.h - b.h;
- }
- newBounds.h = b.h;
- }
- }
- if (state.verticalEdgeType != null) {
- if (Math.abs(newBounds.w - b.w) < maxMatchDistance) {
- state.wrapWidth = true;
- if (state.verticalEdgeType == SegmentType.LEFT) {
- newBounds.x += newBounds.w - b.w;
- }
- newBounds.w = b.w;
- }
- }
- }
-
- // Match on fill bounds
- state.horizontalFillSegment = null;
- state.fillHeight = false;
- if (state.horizontalEdgeType == SegmentType.BOTTOM && !state.wrapHeight) {
- Rect parentBounds = parent.getBounds();
- state.horizontalFillSegment = new Segment(parentBounds.y2(), newBounds.x,
- newBounds.x2(),
- null /*node*/, null /*id*/, SegmentType.BOTTOM, MarginType.NO_MARGIN);
- if (Math.abs(newBounds.y2() - parentBounds.y2()) < getMaxMatchDistance()) {
- state.fillHeight = true;
- newBounds.h = parentBounds.y2() - newBounds.y;
- }
- }
- state.verticalFillSegment = null;
- state.fillWidth = false;
- if (state.verticalEdgeType == SegmentType.RIGHT && !state.wrapWidth) {
- Rect parentBounds = parent.getBounds();
- state.verticalFillSegment = new Segment(parentBounds.x2(), newBounds.y,
- newBounds.y2(),
- null /*node*/, null /*id*/, SegmentType.RIGHT, MarginType.NO_MARGIN);
- if (Math.abs(newBounds.x2() - parentBounds.x2()) < getMaxMatchDistance()) {
- state.fillWidth = true;
- newBounds.w = parentBounds.x2() - newBounds.x;
- }
- }
-
- feedback.tooltip = getResizeUpdateMessage(state, child, parent,
- newBounds, state.horizontalEdgeType, state.verticalEdgeType);
- }
-
- @Override
- public void onResizeEnd(@Nullable DropFeedback feedback, @NonNull INode child,
- final @NonNull INode parent, final @NonNull Rect newBounds) {
- final Rect oldBounds = child.getBounds();
- if (oldBounds.w != newBounds.w || oldBounds.h != newBounds.h) {
- final ResizeState state = (ResizeState) feedback.userData;
- child.editXml("Resize", new INodeHandler() {
- @Override
- public void handle(@NonNull INode n) {
- setNewSizeBounds(state, n, parent, oldBounds, newBounds,
- state.horizontalEdgeType, state.verticalEdgeType);
- }
- });
- }
- }
-
- /**
- * Returns the message to display to the user during the resize operation
- *
- * @param resizeState the current resize state
- * @param child the child node being resized
- * @param parent the parent of the resized node
- * @param newBounds the new bounds to resize the child to, in pixels
- * @param horizontalEdge the horizontal edge being resized
- * @param verticalEdge the vertical edge being resized
- * @return the message to display for the current resize bounds
- */
- protected String getResizeUpdateMessage(ResizeState resizeState, INode child, INode parent,
- Rect newBounds, SegmentType horizontalEdge, SegmentType verticalEdge) {
- String width = resizeState.getWidthAttribute();
- String height = resizeState.getHeightAttribute();
-
- if (horizontalEdge == null) {
- return width;
- } else if (verticalEdge == null) {
- return height;
- } else {
- // U+00D7: Unicode for multiplication sign
- return String.format("%s \u00D7 %s", width, height);
- }
- }
-
- /**
- * Performs the edit on the node to complete a resizing operation. The actual edit
- * part is pulled out such that subclasses can change/add to the edits and be part of
- * the same undo event
- *
- * @param resizeState the current resize state
- * @param node the child node being resized
- * @param layout the parent of the resized node
- * @param newBounds the new bounds to resize the child to, in pixels
- * @param horizontalEdge the horizontal edge being resized
- * @param verticalEdge the vertical edge being resized
- */
- protected void setNewSizeBounds(ResizeState resizeState, INode node, INode layout,
- Rect oldBounds, Rect newBounds, SegmentType horizontalEdge, SegmentType verticalEdge) {
- if (verticalEdge != null
- && (newBounds.w != oldBounds.w || resizeState.wrapWidth || resizeState.fillWidth)) {
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_WIDTH, resizeState.getWidthAttribute());
- }
- if (horizontalEdge != null
- && (newBounds.h != oldBounds.h || resizeState.wrapHeight || resizeState.fillHeight)) {
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_HEIGHT, resizeState.getHeightAttribute());
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/BaseViewRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/BaseViewRule.java
deleted file mode 100644
index 83ce9ef8f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/BaseViewRule.java
+++ /dev/null
@@ -1,996 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_CLASS;
-import static com.android.SdkConstants.ATTR_HINT;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_RESOURCE_PREFIX;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.ATTR_STYLE;
-import static com.android.SdkConstants.ATTR_TEXT;
-import static com.android.SdkConstants.DOT_LAYOUT_PARAMS;
-import static com.android.SdkConstants.ID_PREFIX;
-import static com.android.SdkConstants.NEW_ID_PREFIX;
-import static com.android.SdkConstants.VALUE_FALSE;
-import static com.android.SdkConstants.VALUE_FILL_PARENT;
-import static com.android.SdkConstants.VALUE_MATCH_PARENT;
-import static com.android.SdkConstants.VALUE_TRUE;
-import static com.android.SdkConstants.VALUE_WRAP_CONTENT;
-import static com.android.SdkConstants.VIEW_FRAGMENT;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.AbstractViewRule;
-import com.android.ide.common.api.IAttributeInfo;
-import com.android.ide.common.api.IAttributeInfo.Format;
-import com.android.ide.common.api.IClientRulesEngine;
-import com.android.ide.common.api.IDragElement;
-import com.android.ide.common.api.IMenuCallback;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IViewMetadata;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.RuleAction;
-import com.android.ide.common.api.RuleAction.ActionProvider;
-import com.android.ide.common.api.RuleAction.ChoiceProvider;
-import com.android.resources.ResourceType;
-import com.android.utils.Pair;
-
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.EnumSet;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
-/**
- * Common IViewRule processing to all view and layout classes.
- */
-public class BaseViewRule extends AbstractViewRule {
- /** List of recently edited properties */
- private static List<String> sRecent = new LinkedList<String>();
-
- /** Maximum number of recent properties to track and list */
- private final static int MAX_RECENT_COUNT = 12;
-
- // Strings used as internal ids, group ids and prefixes for actions
- private static final String FALSE_ID = "false"; //$NON-NLS-1$
- private static final String TRUE_ID = "true"; //$NON-NLS-1$
- private static final String PROP_PREFIX = "@prop@"; //$NON-NLS-1$
- private static final String CLEAR_ID = "clear"; //$NON-NLS-1$
- private static final String ZCUSTOM = "zcustom"; //$NON-NLS-1$
-
- protected IClientRulesEngine mRulesEngine;
-
- // Cache of attributes. Key is FQCN of a node mixed with its view hierarchy
- // parent. Values are a custom map as needed by getContextMenu.
- private Map<String, Map<String, Prop>> mAttributesMap =
- new HashMap<String, Map<String, Prop>>();
-
- @Override
- public boolean onInitialize(@NonNull String fqcn, @NonNull IClientRulesEngine engine) {
- mRulesEngine = engine;
-
- // This base rule can handle any class so we don't need to filter on
- // FQCN. Derived classes should do so if they can handle some
- // subclasses.
-
- // If onInitialize returns false, it means it can't handle the given
- // FQCN and will be unloaded.
-
- return true;
- }
-
- /**
- * Returns the {@link IClientRulesEngine} associated with this {@link IViewRule}
- *
- * @return the {@link IClientRulesEngine} associated with this {@link IViewRule}
- */
- public IClientRulesEngine getRulesEngine() {
- return mRulesEngine;
- }
-
- // === Context Menu ===
-
- /**
- * Generate custom actions for the context menu: <br/>
- * - Explicit layout_width and layout_height attributes.
- * - List of all other simple toggle attributes.
- */
- @Override
- public void addContextMenuActions(@NonNull List<RuleAction> actions,
- final @NonNull INode selectedNode) {
- String width = null;
- String currentWidth = selectedNode.getStringAttr(ANDROID_URI, ATTR_LAYOUT_WIDTH);
-
- String fillParent = getFillParentValueName();
- boolean canMatchParent = supportsMatchParent();
- if (canMatchParent && VALUE_FILL_PARENT.equals(currentWidth)) {
- currentWidth = VALUE_MATCH_PARENT;
- } else if (!canMatchParent && VALUE_MATCH_PARENT.equals(currentWidth)) {
- currentWidth = VALUE_FILL_PARENT;
- } else if (!VALUE_WRAP_CONTENT.equals(currentWidth) && !fillParent.equals(currentWidth)) {
- width = currentWidth;
- }
-
- String height = null;
- String currentHeight = selectedNode.getStringAttr(ANDROID_URI, ATTR_LAYOUT_HEIGHT);
-
- if (canMatchParent && VALUE_FILL_PARENT.equals(currentHeight)) {
- currentHeight = VALUE_MATCH_PARENT;
- } else if (!canMatchParent && VALUE_MATCH_PARENT.equals(currentHeight)) {
- currentHeight = VALUE_FILL_PARENT;
- } else if (!VALUE_WRAP_CONTENT.equals(currentHeight)
- && !fillParent.equals(currentHeight)) {
- height = currentHeight;
- }
- final String newWidth = width;
- final String newHeight = height;
-
- final IMenuCallback onChange = new IMenuCallback() {
- @Override
- public void action(
- final @NonNull RuleAction action,
- final @NonNull List<? extends INode> selectedNodes,
- final @Nullable String valueId, final @Nullable Boolean newValue) {
- String fullActionId = action.getId();
- boolean isProp = fullActionId.startsWith(PROP_PREFIX);
- final String actionId = isProp ?
- fullActionId.substring(PROP_PREFIX.length()) : fullActionId;
-
- if (fullActionId.equals(ATTR_LAYOUT_WIDTH)) {
- final String newAttrValue = getValue(valueId, newWidth);
- if (newAttrValue != null) {
- for (INode node : selectedNodes) {
- node.editXml("Change Attribute " + ATTR_LAYOUT_WIDTH,
- new PropertySettingNodeHandler(ANDROID_URI,
- ATTR_LAYOUT_WIDTH, newAttrValue));
- }
- editedProperty(ATTR_LAYOUT_WIDTH);
- }
- return;
- } else if (fullActionId.equals(ATTR_LAYOUT_HEIGHT)) {
- // Ask the user
- final String newAttrValue = getValue(valueId, newHeight);
- if (newAttrValue != null) {
- for (INode node : selectedNodes) {
- node.editXml("Change Attribute " + ATTR_LAYOUT_HEIGHT,
- new PropertySettingNodeHandler(ANDROID_URI,
- ATTR_LAYOUT_HEIGHT, newAttrValue));
- }
- editedProperty(ATTR_LAYOUT_HEIGHT);
- }
- return;
- } else if (fullActionId.equals(ATTR_ID)) {
- // Ids must be set individually so open the id dialog for each
- // selected node (though allow cancel to break the loop)
- for (INode node : selectedNodes) {
- if (!mRulesEngine.rename(node)) {
- break;
- }
- }
- editedProperty(ATTR_ID);
- return;
- } else if (isProp) {
- INode firstNode = selectedNodes.get(0);
- String key = getPropertyMapKey(selectedNode);
- Map<String, Prop> props = mAttributesMap.get(key);
- final Prop prop = (props != null) ? props.get(actionId) : null;
-
- if (prop != null) {
- editedProperty(actionId);
-
- // For custom values (requiring an input dialog) input the
- // value outside the undo-block.
- // Input the value as a text, unless we know it's the "text" or
- // "style" attributes (where we know we want to ask for specific
- // resource types).
- String uri = ANDROID_URI;
- String v = null;
- if (prop.isStringEdit()) {
- boolean isStyle = actionId.equals(ATTR_STYLE);
- boolean isText = actionId.equals(ATTR_TEXT);
- boolean isHint = actionId.equals(ATTR_HINT);
- if (isStyle || isText || isHint) {
- String resourceTypeName = isStyle
- ? ResourceType.STYLE.getName()
- : ResourceType.STRING.getName();
- String oldValue = selectedNodes.size() == 1
- ? (isStyle ? firstNode.getStringAttr(ATTR_STYLE, actionId)
- : firstNode.getStringAttr(ANDROID_URI, actionId))
- : ""; //$NON-NLS-1$
- oldValue = ensureValidString(oldValue);
- v = mRulesEngine.displayResourceInput(resourceTypeName, oldValue);
- if (isStyle) {
- uri = null;
- }
- } else if (actionId.equals(ATTR_CLASS) && selectedNodes.size() >= 1 &&
- VIEW_FRAGMENT.equals(selectedNodes.get(0).getFqcn())) {
- v = mRulesEngine.displayFragmentSourceInput();
- uri = null;
- } else {
- v = inputAttributeValue(firstNode, actionId);
- }
- }
- final String customValue = v;
-
- for (INode n : selectedNodes) {
- if (prop.isToggle()) {
- // case of toggle
- String value = ""; //$NON-NLS-1$
- if (valueId.equals(TRUE_ID)) {
- value = newValue ? "true" : ""; //$NON-NLS-1$ //$NON-NLS-2$
- } else if (valueId.equals(FALSE_ID)) {
- value = newValue ? "false" : "";//$NON-NLS-1$ //$NON-NLS-2$
- }
- n.setAttribute(uri, actionId, value);
- } else if (prop.isFlag()) {
- // case of a flag
- String values = ""; //$NON-NLS-1$
- if (!valueId.equals(CLEAR_ID)) {
- values = n.getStringAttr(ANDROID_URI, actionId);
- Set<String> newValues = new HashSet<String>();
- if (values != null) {
- newValues.addAll(Arrays.asList(
- values.split("\\|"))); //$NON-NLS-1$
- }
- if (newValue) {
- newValues.add(valueId);
- } else {
- newValues.remove(valueId);
- }
-
- List<String> sorted = new ArrayList<String>(newValues);
- Collections.sort(sorted);
- values = join('|', sorted);
-
- // Special case
- if (valueId.equals("normal")) { //$NON-NLS-1$
- // For textStyle for example, if you have "bold|italic"
- // and you select the "normal" property, this should
- // not behave in the normal flag way and "or" itself in;
- // it should replace the other two.
- // This also applies to imeOptions.
- values = valueId;
- }
- }
- n.setAttribute(uri, actionId, values);
- } else if (prop.isEnum()) {
- // case of an enum
- String value = ""; //$NON-NLS-1$
- if (!valueId.equals(CLEAR_ID)) {
- value = newValue ? valueId : ""; //$NON-NLS-1$
- }
- n.setAttribute(uri, actionId, value);
- } else {
- assert prop.isStringEdit();
- // We've already received the value outside the undo block
- if (customValue != null) {
- n.setAttribute(uri, actionId, customValue);
- }
- }
- }
- }
- }
- }
-
- /**
- * Input the custom value for the given attribute. This will use the Reference
- * Chooser if it is a reference value, otherwise a plain text editor.
- */
- private String inputAttributeValue(final INode node, final String attribute) {
- String oldValue = node.getStringAttr(ANDROID_URI, attribute);
- oldValue = ensureValidString(oldValue);
- IAttributeInfo attributeInfo = node.getAttributeInfo(ANDROID_URI, attribute);
- if (attributeInfo != null
- && attributeInfo.getFormats().contains(Format.REFERENCE)) {
- return mRulesEngine.displayReferenceInput(oldValue);
- } else {
- // A single resource type? If so use a resource chooser initialized
- // to this specific type
- /* This does not work well, because the metadata is a bit misleading:
- * for example a Button's "text" property and a Button's "onClick" property
- * both claim to be of type [string], but @string/ is NOT valid for
- * onClick..
- if (attributeInfo != null && attributeInfo.getFormats().length == 1) {
- // Resource chooser
- Format format = attributeInfo.getFormats()[0];
- return mRulesEngine.displayResourceInput(format.name(), oldValue);
- }
- */
-
- // Fallback: just edit the raw XML string
- String message = String.format("New %1$s Value:", attribute);
- return mRulesEngine.displayInput(message, oldValue, null);
- }
- }
-
- /**
- * Returns the value (which will ask the user if the value is the special
- * {@link #ZCUSTOM} marker
- */
- private String getValue(String valueId, String defaultValue) {
- if (valueId.equals(ZCUSTOM)) {
- if (defaultValue == null) {
- defaultValue = "";
- }
- String value = mRulesEngine.displayInput(
- "Set custom layout attribute value (example: 50dp)",
- defaultValue, null);
- if (value != null && value.trim().length() > 0) {
- return value.trim();
- } else {
- return null;
- }
- }
-
- return valueId;
- }
- };
-
- IAttributeInfo textAttribute = selectedNode.getAttributeInfo(ANDROID_URI, ATTR_TEXT);
- if (textAttribute != null) {
- actions.add(RuleAction.createAction(PROP_PREFIX + ATTR_TEXT, "Edit Text...", onChange,
- null, 10, true));
- }
-
- String editIdLabel = selectedNode.getStringAttr(ANDROID_URI, ATTR_ID) != null ?
- "Edit ID..." : "Assign ID...";
- actions.add(RuleAction.createAction(ATTR_ID, editIdLabel, onChange, null, 20, true));
-
- addCommonPropertyActions(actions, selectedNode, onChange, 21);
-
- // Create width choice submenu
- actions.add(RuleAction.createSeparator(32));
- List<Pair<String, String>> widthChoices = new ArrayList<Pair<String,String>>(4);
- widthChoices.add(Pair.of(VALUE_WRAP_CONTENT, "Wrap Content"));
- if (canMatchParent) {
- widthChoices.add(Pair.of(VALUE_MATCH_PARENT, "Match Parent"));
- } else {
- widthChoices.add(Pair.of(VALUE_FILL_PARENT, "Fill Parent"));
- }
- if (width != null) {
- widthChoices.add(Pair.of(width, width));
- }
- widthChoices.add(Pair.of(ZCUSTOM, "Other..."));
- actions.add(RuleAction.createChoices(
- ATTR_LAYOUT_WIDTH, "Layout Width",
- onChange,
- null /* iconUrls */,
- currentWidth,
- null, 35,
- true, // supportsMultipleNodes
- widthChoices));
-
- // Create height choice submenu
- List<Pair<String, String>> heightChoices = new ArrayList<Pair<String,String>>(4);
- heightChoices.add(Pair.of(VALUE_WRAP_CONTENT, "Wrap Content"));
- if (canMatchParent) {
- heightChoices.add(Pair.of(VALUE_MATCH_PARENT, "Match Parent"));
- } else {
- heightChoices.add(Pair.of(VALUE_FILL_PARENT, "Fill Parent"));
- }
- if (height != null) {
- heightChoices.add(Pair.of(height, height));
- }
- heightChoices.add(Pair.of(ZCUSTOM, "Other..."));
- actions.add(RuleAction.createChoices(
- ATTR_LAYOUT_HEIGHT, "Layout Height",
- onChange,
- null /* iconUrls */,
- currentHeight,
- null, 40,
- true,
- heightChoices));
-
- actions.add(RuleAction.createSeparator(45));
- RuleAction properties = RuleAction.createChoices("properties", "Other Properties", //$NON-NLS-1$
- onChange /*callback*/, null /*icon*/, 50,
- true /*supportsMultipleNodes*/, new ActionProvider() {
- @Override
- public @NonNull List<RuleAction> getNestedActions(@NonNull INode node) {
- List<RuleAction> propertyActionTypes = new ArrayList<RuleAction>();
- propertyActionTypes.add(RuleAction.createChoices(
- "recent", "Recent", //$NON-NLS-1$
- onChange /*callback*/, null /*icon*/, 10,
- true /*supportsMultipleNodes*/, new ActionProvider() {
- @Override
- public @NonNull List<RuleAction> getNestedActions(@NonNull INode n) {
- List<RuleAction> propertyActions = new ArrayList<RuleAction>();
- addRecentPropertyActions(propertyActions, n, onChange);
- return propertyActions;
- }
- }));
-
- propertyActionTypes.add(RuleAction.createSeparator(20));
-
- addInheritedProperties(propertyActionTypes, node, onChange, 30);
-
- propertyActionTypes.add(RuleAction.createSeparator(50));
- propertyActionTypes.add(RuleAction.createChoices(
- "layoutparams", "Layout Parameters", //$NON-NLS-1$
- onChange /*callback*/, null /*icon*/, 60,
- true /*supportsMultipleNodes*/, new ActionProvider() {
- @Override
- public @NonNull List<RuleAction> getNestedActions(@NonNull INode n) {
- List<RuleAction> propertyActions = new ArrayList<RuleAction>();
- addPropertyActions(propertyActions, n, onChange, null, true);
- return propertyActions;
- }
- }));
-
- propertyActionTypes.add(RuleAction.createSeparator(70));
-
- propertyActionTypes.add(RuleAction.createChoices(
- "allprops", "All By Name", //$NON-NLS-1$
- onChange /*callback*/, null /*icon*/, 80,
- true /*supportsMultipleNodes*/, new ActionProvider() {
- @Override
- public @NonNull List<RuleAction> getNestedActions(@NonNull INode n) {
- List<RuleAction> propertyActions = new ArrayList<RuleAction>();
- addPropertyActions(propertyActions, n, onChange, null, false);
- return propertyActions;
- }
- }));
-
- return propertyActionTypes;
- }
- });
-
- actions.add(properties);
- }
-
- @Override
- @Nullable
- public String getDefaultActionId(@NonNull final INode selectedNode) {
- IAttributeInfo textAttribute = selectedNode.getAttributeInfo(ANDROID_URI, ATTR_TEXT);
- if (textAttribute != null) {
- return PROP_PREFIX + ATTR_TEXT;
- }
-
- return null;
- }
-
- private static String getPropertyMapKey(INode node) {
- // Compute the key for mAttributesMap. This depends on the type of this
- // node and its parent in the view hierarchy.
- StringBuilder sb = new StringBuilder();
- sb.append(node.getFqcn());
- sb.append('_');
- INode parent = node.getParent();
- if (parent != null) {
- sb.append(parent.getFqcn());
- }
- return sb.toString();
- }
-
- /**
- * Adds menu items for the inherited attributes, one pull-right menu for each super class
- * that defines attributes.
- *
- * @param propertyActionTypes the actions list to add into
- * @param node the node to apply the attributes to
- * @param onChange the callback to use for setting attributes
- * @param sortPriority the initial sort attribute for the first menu item
- */
- private void addInheritedProperties(List<RuleAction> propertyActionTypes, INode node,
- final IMenuCallback onChange, int sortPriority) {
- List<String> attributeSources = node.getAttributeSources();
- for (final String definedBy : attributeSources) {
- String sourceClass = definedBy;
-
- // Strip package prefixes when necessary
- int index = sourceClass.length();
- if (sourceClass.endsWith(DOT_LAYOUT_PARAMS)) {
- index = sourceClass.length() - DOT_LAYOUT_PARAMS.length() - 1;
- }
- int lastDot = sourceClass.lastIndexOf('.', index);
- if (lastDot != -1) {
- sourceClass = sourceClass.substring(lastDot + 1);
- }
-
- String label;
- if (definedBy.equals(node.getFqcn())) {
- label = String.format("Defined by %1$s", sourceClass);
- } else {
- label = String.format("Inherited from %1$s", sourceClass);
- }
-
- propertyActionTypes.add(RuleAction.createChoices("def_" + definedBy,
- label,
- onChange /*callback*/, null /*icon*/, sortPriority++,
- true /*supportsMultipleNodes*/, new ActionProvider() {
- @Override
- public @NonNull List<RuleAction> getNestedActions(@NonNull INode n) {
- List<RuleAction> propertyActions = new ArrayList<RuleAction>();
- addPropertyActions(propertyActions, n, onChange, definedBy, false);
- return propertyActions;
- }
- }));
- }
- }
-
- /**
- * Creates a list of properties that are commonly edited for views of the
- * selected node's type
- */
- private void addCommonPropertyActions(List<RuleAction> actions, INode selectedNode,
- IMenuCallback onChange, int sortPriority) {
- Map<String, Prop> properties = getPropertyMetadata(selectedNode);
- IViewMetadata metadata = mRulesEngine.getMetadata(selectedNode.getFqcn());
- if (metadata != null) {
- List<String> attributes = metadata.getTopAttributes();
- if (attributes.size() > 0) {
- for (String attribute : attributes) {
- // Text and ID are handled manually in the menu construction code because
- // we want to place them consistently and customize the action label
- if (ATTR_TEXT.equals(attribute) || ATTR_ID.equals(attribute)) {
- continue;
- }
-
- Prop property = properties.get(attribute);
- if (property != null) {
- String title = property.getTitle();
- if (title.endsWith("...")) {
- title = String.format("Edit %1$s", property.getTitle());
- }
- actions.add(createPropertyAction(property, attribute, title,
- selectedNode, onChange, sortPriority));
- sortPriority++;
- }
- }
- }
- }
- }
-
- /**
- * Record that the given property was just edited; adds it to the front of
- * the recently edited property list
- *
- * @param property the name of the property
- */
- static void editedProperty(String property) {
- if (sRecent.contains(property)) {
- sRecent.remove(property);
- } else if (sRecent.size() > MAX_RECENT_COUNT) {
- sRecent.remove(sRecent.size() - 1);
- }
- sRecent.add(0, property);
- }
-
- /**
- * Creates a list of recently modified properties that apply to the given selected node
- */
- private void addRecentPropertyActions(List<RuleAction> actions, INode selectedNode,
- IMenuCallback onChange) {
- int sortPriority = 10;
- Map<String, Prop> properties = getPropertyMetadata(selectedNode);
- for (String attribute : sRecent) {
- Prop property = properties.get(attribute);
- if (property != null) {
- actions.add(createPropertyAction(property, attribute, property.getTitle(),
- selectedNode, onChange, sortPriority));
- sortPriority += 10;
- }
- }
- }
-
- /**
- * Creates a list of nested actions representing the property-setting
- * actions for the given selected node
- */
- private void addPropertyActions(List<RuleAction> actions, INode selectedNode,
- IMenuCallback onChange, String definedBy, boolean layoutParamsOnly) {
-
- Map<String, Prop> properties = getPropertyMetadata(selectedNode);
-
- int sortPriority = 10;
- for (Map.Entry<String, Prop> entry : properties.entrySet()) {
- String id = entry.getKey();
- Prop property = entry.getValue();
- if (layoutParamsOnly) {
- // If we have definedBy information, that is most accurate; all layout
- // params will be defined by a class whose name ends with
- // .LayoutParams:
- if (definedBy != null) {
- if (!definedBy.endsWith(DOT_LAYOUT_PARAMS)) {
- continue;
- }
- } else if (!id.startsWith(ATTR_LAYOUT_RESOURCE_PREFIX)) {
- continue;
- }
- }
- if (definedBy != null && !definedBy.equals(property.getDefinedBy())) {
- continue;
- }
- actions.add(createPropertyAction(property, id, property.getTitle(),
- selectedNode, onChange, sortPriority));
- sortPriority += 10;
- }
-
- // The properties are coming out of map key order which isn't right, so sort
- // alphabetically instead
- Collections.sort(actions, new Comparator<RuleAction>() {
- @Override
- public int compare(RuleAction action1, RuleAction action2) {
- return action1.getTitle().compareTo(action2.getTitle());
- }
- });
- }
-
- private RuleAction createPropertyAction(Prop p, String id, String title, INode selectedNode,
- IMenuCallback onChange, int sortPriority) {
- if (p.isToggle()) {
- // Toggles are handled as a multiple-choice between true, false
- // and nothing (clear)
- String value = selectedNode.getStringAttr(ANDROID_URI, id);
- if (value != null) {
- value = value.toLowerCase(Locale.US);
- }
- if (VALUE_TRUE.equals(value)) {
- value = TRUE_ID;
- } else if (VALUE_FALSE.equals(value)) {
- value = FALSE_ID;
- } else {
- value = CLEAR_ID;
- }
- return RuleAction.createChoices(PROP_PREFIX + id, title,
- onChange, BOOLEAN_CHOICE_PROVIDER,
- value,
- null, sortPriority,
- true);
- } else if (p.getChoices() != null) {
- // Enum or flags. Their possible values are the multiple-choice
- // items, with an extra "clear" option to remove everything.
- String current = selectedNode.getStringAttr(ANDROID_URI, id);
- if (current == null || current.length() == 0) {
- current = CLEAR_ID;
- }
- return RuleAction.createChoices(PROP_PREFIX + id, title,
- onChange, new EnumPropertyChoiceProvider(p),
- current,
- null, sortPriority,
- true);
- } else {
- return RuleAction.createAction(
- PROP_PREFIX + id,
- title,
- onChange,
- null, sortPriority,
- true);
- }
- }
-
- private Map<String, Prop> getPropertyMetadata(final INode selectedNode) {
- String key = getPropertyMapKey(selectedNode);
- Map<String, Prop> props = mAttributesMap.get(key);
- if (props == null) {
- // Prepare the property map
- props = new HashMap<String, Prop>();
- for (IAttributeInfo attrInfo : selectedNode.getDeclaredAttributes()) {
- String id = attrInfo != null ? attrInfo.getName() : null;
- if (id == null || id.equals(ATTR_LAYOUT_WIDTH) || id.equals(ATTR_LAYOUT_HEIGHT)) {
- // Layout width/height are already handled at the root level
- continue;
- }
- if (attrInfo == null) {
- continue;
- }
- EnumSet<Format> formats = attrInfo.getFormats();
-
- String title = getAttributeDisplayName(id);
-
- String definedBy = attrInfo != null ? attrInfo.getDefinedBy() : null;
- if (formats.contains(IAttributeInfo.Format.BOOLEAN)) {
- props.put(id, new Prop(title, true, definedBy));
- } else if (formats.contains(IAttributeInfo.Format.ENUM)) {
- // Convert each enum into a map id=>title
- Map<String, String> values = new HashMap<String, String>();
- if (attrInfo != null) {
- for (String e : attrInfo.getEnumValues()) {
- values.put(e, getAttributeDisplayName(e));
- }
- }
-
- props.put(id, new Prop(title, false, false, values, definedBy));
- } else if (formats.contains(IAttributeInfo.Format.FLAG)) {
- // Convert each flag into a map id=>title
- Map<String, String> values = new HashMap<String, String>();
- if (attrInfo != null) {
- for (String e : attrInfo.getFlagValues()) {
- values.put(e, getAttributeDisplayName(e));
- }
- }
-
- props.put(id, new Prop(title, false, true, values, definedBy));
- } else {
- props.put(id, new Prop(title + "...", false, definedBy));
- }
- }
- mAttributesMap.put(key, props);
- }
- return props;
- }
-
- /**
- * A {@link ChoiceProvder} which provides alternatives suitable for choosing
- * values for a boolean property: true, false, or "default".
- */
- private static ChoiceProvider BOOLEAN_CHOICE_PROVIDER = new ChoiceProvider() {
- @Override
- public void addChoices(@NonNull List<String> titles, @NonNull List<URL> iconUrls,
- @NonNull List<String> ids) {
- titles.add("True");
- ids.add(TRUE_ID);
-
- titles.add("False");
- ids.add(FALSE_ID);
-
- titles.add(RuleAction.SEPARATOR);
- ids.add(RuleAction.SEPARATOR);
-
- titles.add("Default");
- ids.add(CLEAR_ID);
- }
- };
-
- /**
- * A {@link ChoiceProvider} which provides the various available
- * attribute values available for a given {@link Prop} property descriptor.
- */
- private static class EnumPropertyChoiceProvider implements ChoiceProvider {
- private Prop mProperty;
-
- public EnumPropertyChoiceProvider(Prop property) {
- super();
- mProperty = property;
- }
-
- @Override
- public void addChoices(@NonNull List<String> titles, @NonNull List<URL> iconUrls,
- @NonNull List<String> ids) {
- for (Entry<String, String> entry : mProperty.getChoices().entrySet()) {
- ids.add(entry.getKey());
- titles.add(entry.getValue());
- }
-
- titles.add(RuleAction.SEPARATOR);
- ids.add(RuleAction.SEPARATOR);
-
- titles.add("Default");
- ids.add(CLEAR_ID);
- }
- }
-
- /**
- * Returns true if the given node is "filled" (e.g. has layout width set to match
- * parent or fill parent
- */
- protected final boolean isFilled(INode node, String attribute) {
- String value = node.getStringAttr(ANDROID_URI, attribute);
- return VALUE_MATCH_PARENT.equals(value) || VALUE_FILL_PARENT.equals(value);
- }
-
- /**
- * Returns fill_parent or match_parent, depending on whether the minimum supported
- * platform supports match_parent or not
- *
- * @return match_parent or fill_parent depending on which is supported by the project
- */
- protected final String getFillParentValueName() {
- return supportsMatchParent() ? VALUE_MATCH_PARENT : VALUE_FILL_PARENT;
- }
-
- /**
- * Returns true if the project supports match_parent instead of just fill_parent
- *
- * @return true if the project supports match_parent instead of just fill_parent
- */
- protected final boolean supportsMatchParent() {
- // fill_parent was renamed match_parent in API level 8
- return mRulesEngine.getMinApiLevel() >= 8;
- }
-
- /** Join strings into a single string with the given delimiter */
- static String join(char delimiter, Collection<String> strings) {
- StringBuilder sb = new StringBuilder(100);
- for (String s : strings) {
- if (sb.length() > 0) {
- sb.append(delimiter);
- }
- sb.append(s);
- }
- return sb.toString();
- }
-
- static Map<String, String> concatenate(Map<String, String> pre, Map<String, String> post) {
- Map<String, String> result = new HashMap<String, String>(pre.size() + post.size());
- result.putAll(pre);
- result.putAll(post);
- return result;
- }
-
- // Quick utility for building up maps declaratively to minimize the diffs
- static Map<String, String> mapify(String... values) {
- Map<String, String> map = new HashMap<String, String>(values.length / 2);
- for (int i = 0; i < values.length; i += 2) {
- String key = values[i];
- if (key == null) {
- continue;
- }
- String value = values[i + 1];
- map.put(key, value);
- }
-
- return map;
- }
-
- /**
- * Produces a display name for an attribute, usually capitalizing the attribute name
- * and splitting up underscores into new words
- *
- * @param name the attribute name to convert
- * @return a display name for the attribute name
- */
- public static String getAttributeDisplayName(String name) {
- if (name != null && name.length() > 0) {
- StringBuilder sb = new StringBuilder();
- boolean capitalizeNext = true;
- for (int i = 0, n = name.length(); i < n; i++) {
- char c = name.charAt(i);
- if (capitalizeNext) {
- c = Character.toUpperCase(c);
- }
- capitalizeNext = false;
- if (c == '_') {
- c = ' ';
- capitalizeNext = true;
- }
- sb.append(c);
- }
-
- return sb.toString();
- }
-
- return name;
- }
-
-
- // ==== Paste support ====
-
- /**
- * Most views can't accept children so there's nothing to paste on them. In
- * this case, defer the call to the parent layout and use the target node as
- * an indication of where to paste.
- */
- @Override
- public void onPaste(@NonNull INode targetNode, @Nullable Object targetView,
- @NonNull IDragElement[] elements) {
- //
- INode parent = targetNode.getParent();
- if (parent != null) {
- String parentFqcn = parent.getFqcn();
- IViewRule parentRule = mRulesEngine.loadRule(parentFqcn);
-
- if (parentRule instanceof BaseLayoutRule) {
- ((BaseLayoutRule) parentRule).onPasteBeforeChild(parent, targetView, targetNode,
- elements);
- }
- }
- }
-
- /**
- * Support class for the context menu code. Stores state about properties in
- * the context menu.
- */
- private static class Prop {
- private final boolean mToggle;
- private final boolean mFlag;
- private final String mTitle;
- private final Map<String, String> mChoices;
- private String mDefinedBy;
-
- public Prop(String title, boolean isToggle, boolean isFlag, Map<String, String> choices,
- String definedBy) {
- mTitle = title;
- mToggle = isToggle;
- mFlag = isFlag;
- mChoices = choices;
- mDefinedBy = definedBy;
- }
-
- public String getDefinedBy() {
- return mDefinedBy;
- }
-
- public Prop(String title, boolean isToggle, String definedBy) {
- this(title, isToggle, false, null, definedBy);
- }
-
- private boolean isToggle() {
- return mToggle;
- }
-
- private boolean isFlag() {
- return mFlag && mChoices != null;
- }
-
- private boolean isEnum() {
- return !mFlag && mChoices != null;
- }
-
- private String getTitle() {
- return mTitle;
- }
-
- private Map<String, String> getChoices() {
- return mChoices;
- }
-
- private boolean isStringEdit() {
- return mChoices == null && !mToggle;
- }
- }
-
- /**
- * Returns a source attribute value which points to a sample image. This is typically
- * used to provide an initial image shown on ImageButtons, etc. There is no guarantee
- * that the source pointed to by this method actually exists.
- *
- * @return a source attribute to use for sample images, never null
- */
- protected final String getSampleImageSrc() {
- // Builtin graphics available since v1:
- return "@android:drawable/btn_star"; //$NON-NLS-1$
- }
-
- /**
- * Strips the {@code @+id} or {@code @id} prefix off of the given id
- *
- * @param id attribute to be stripped
- * @return the id name without the {@code @+id} or {@code @id} prefix
- */
- @NonNull
- public static String stripIdPrefix(@Nullable String id) {
- if (id == null) {
- return ""; //$NON-NLS-1$
- } else if (id.startsWith(NEW_ID_PREFIX)) {
- return id.substring(NEW_ID_PREFIX.length());
- } else if (id.startsWith(ID_PREFIX)) {
- return id.substring(ID_PREFIX.length());
- }
- return id;
- }
-
- private static String ensureValidString(String value) {
- if (value == null) {
- value = ""; //$NON-NLS-1$
- }
- return value;
- }
- }
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/CalendarViewRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/CalendarViewRule.java
deleted file mode 100644
index 91684e2c5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/CalendarViewRule.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-
-/**
- * An {@link IViewRule} for android.widget.CalendarView.
- */
-public class CalendarViewRule extends BaseViewRule {
-
- @Override
- public void onCreate(@NonNull INode node, @NonNull INode parent,
- @NonNull InsertType insertType) {
- super.onCreate(node, parent, insertType);
-
- // CalendarViews need a lot of space, and the wrapping doesn't seem to work
- // well anyway; it reports a much-to-small size than actually accommodates its
- // content.
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_WIDTH, getFillParentValueName());
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_HEIGHT, getFillParentValueName());
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/DatePickerRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/DatePickerRule.java
deleted file mode 100644
index a635a9ad6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/DatePickerRule.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-public class DatePickerRule extends IgnoredLayoutRule {
- // A DatePicker inherits from FrameLayout but is not a general purpose
- // FrameLayout
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/DialerFilterRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/DialerFilterRule.java
deleted file mode 100644
index 606bbd86c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/DialerFilterRule.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ATTR_LAYOUT_BELOW;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.ATTR_TEXT;
-import static com.android.SdkConstants.FQCN_EDIT_TEXT;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-
-/**
- * An {@link IViewRule} for android.widget.DialerFilterRule.
- */
-public class DialerFilterRule extends BaseViewRule {
-
- @Override
- public void onCreate(@NonNull INode node, @NonNull INode parent,
- @NonNull InsertType insertType) {
- super.onCreate(node, parent, insertType);
-
- // A DialerFilter requires a couple of nested EditTexts with fixed ids:
- if (insertType.isCreate()) {
- String fillParent = getFillParentValueName();
- INode hint = node.appendChild(FQCN_EDIT_TEXT);
- hint.setAttribute(ANDROID_URI, ATTR_TEXT, "Hint");
- hint.setAttribute(ANDROID_URI, ATTR_ID, "@android:id/hint"); //$NON-NLS-1$
- hint.setAttribute(ANDROID_URI, ATTR_LAYOUT_WIDTH, fillParent);
-
- INode primary = node.appendChild(FQCN_EDIT_TEXT);
- primary.setAttribute(ANDROID_URI, ATTR_TEXT, "Primary");
- primary.setAttribute(ANDROID_URI, ATTR_ID, "@android:id/primary"); //$NON-NLS-1$
- primary.setAttribute(ANDROID_URI, ATTR_LAYOUT_BELOW,
- "@android:id/hint"); //$NON-NLS-1$
- primary.setAttribute(ANDROID_URI, ATTR_LAYOUT_WIDTH, fillParent);
-
-
- // What do we initialize the icon to?
- //INode icon = node.appendChild("android.widget.ImageView"); //$NON-NLS-1$
- //icon.setAttribute(ANDROID_URI, ATTR_ID, "@android:id/icon"); //$NON-NLS-1$
- }
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/EditTextRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/EditTextRule.java
deleted file mode 100644
index 03a5bc04e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/EditTextRule.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_EMS;
-import static com.android.SdkConstants.REQUEST_FOCUS;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.IMenuCallback;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.INodeHandler;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-import com.android.ide.common.api.RuleAction;
-
-import java.util.List;
-
-/**
- * An {@link IViewRule} for android.widget.EditText.
- */
-public class EditTextRule extends BaseViewRule {
-
- @Override
- public void onCreate(@NonNull INode node, @NonNull INode parent,
- @NonNull InsertType insertType) {
- super.onCreate(node, parent, insertType);
-
- if (parent != null) {
- INode focus = findFocus(findRoot(parent));
- if (focus == null) {
- // Add <requestFocus>
- node.appendChild(REQUEST_FOCUS);
- }
-
- if (parent.getBounds().w >= 320) {
- node.setAttribute(ANDROID_URI, ATTR_EMS, "10"); //$NON-NLS-1$
- }
- }
- }
-
- /**
- * {@inheritDoc}
- * <p>
- * Adds a "Request Focus" menu item.
- */
- @Override
- public void addContextMenuActions(@NonNull List<RuleAction> actions,
- final @NonNull INode selectedNode) {
- super.addContextMenuActions(actions, selectedNode);
-
- final boolean hasFocus = hasFocus(selectedNode);
- final String label = hasFocus ? "Clear Focus" : "Request Focus";
-
- IMenuCallback onChange = new IMenuCallback() {
- @Override
- public void action(
- @NonNull RuleAction menuAction,
- @NonNull List<? extends INode> selectedNodes,
- @Nullable String valueId,
- @Nullable Boolean newValue) {
- selectedNode.editXml(label, new INodeHandler() {
- @Override
- public void handle(@NonNull INode node) {
- INode focus = findFocus(findRoot(node));
- if (focus != null && focus.getParent() != null) {
- focus.getParent().removeChild(focus);
- }
- if (!hasFocus) {
- node.appendChild(REQUEST_FOCUS);
- }
- }
- });
- }
- };
-
- actions.add(RuleAction.createAction("_setfocus", label, onChange, //$NON-NLS-1$
- null, 5, false /*supportsMultipleNodes*/));
- actions.add(RuleAction.createSeparator(7));
- }
-
- /** Returns true if the given node currently has focus */
- private static boolean hasFocus(INode node) {
- INode focus = findFocus(node);
- if (focus != null) {
- return focus.getParent() == node;
- }
-
- return false;
- }
-
- /** Returns the root/top level node in the view hierarchy that contains the given node */
- private static INode findRoot(INode node) {
- // First find the parent
- INode root = node;
- while (root != null) {
- INode parent = root.getParent();
- if (parent == null) {
- break;
- } else {
- root = parent;
- }
- }
-
- return root;
- }
-
- /** Finds the focus node (not the node containing focus, but the actual request focus node
- * under a given node */
- private static INode findFocus(INode node) {
- if (node.getFqcn().equals(REQUEST_FOCUS)) {
- return node;
- }
-
- for (INode child : node.getChildren()) {
- INode focus = findFocus(child);
- if (focus != null) {
- return focus;
- }
- }
- return null;
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/FragmentRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/FragmentRule.java
deleted file mode 100644
index f99cf0ceb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/FragmentRule.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_NAME;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-
-/**
- * An {@link IViewRule} for the special XML {@code <fragment>} tag.
- */
-public class FragmentRule extends BaseViewRule {
- @Override
- public void onCreate(@NonNull INode node, @NonNull INode parent,
- @NonNull InsertType insertType) {
- // When dropping a fragment tag, ask the user which class to use.
- if (insertType == InsertType.CREATE) { // NOT InsertType.CREATE_PREVIEW
- String fqcn = mRulesEngine.displayFragmentSourceInput();
- if (fqcn != null) {
- node.editXml("Add Fragment",
- new PropertySettingNodeHandler(ANDROID_URI, ATTR_NAME,
- fqcn.length() > 0 ? fqcn : null));
- } else {
- // Remove the view; the insertion was canceled
- parent.removeChild(node);
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/FrameLayoutRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/FrameLayoutRule.java
deleted file mode 100644
index 0f9096294..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/FrameLayoutRule.java
+++ /dev/null
@@ -1,195 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_LAYOUT_GRAVITY;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.DrawingStyle;
-import com.android.ide.common.api.DropFeedback;
-import com.android.ide.common.api.IDragElement;
-import com.android.ide.common.api.IFeedbackPainter;
-import com.android.ide.common.api.IGraphics;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.INodeHandler;
-import com.android.ide.common.api.IViewMetadata;
-import com.android.ide.common.api.IViewMetadata.FillPreference;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-import com.android.ide.common.api.Point;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.api.RuleAction;
-import com.android.utils.Pair;
-
-import java.util.List;
-import java.util.Map;
-
-/**
- * An {@link IViewRule} for android.widget.FrameLayout and all its derived
- * classes.
- */
-public class FrameLayoutRule extends BaseLayoutRule {
-
- // ==== Drag'n'drop support ====
- // The FrameLayout accepts any drag'n'drop anywhere on its surface.
-
- @Override
- public DropFeedback onDropEnter(@NonNull INode targetNode, @Nullable Object targetView,
- final @Nullable IDragElement[] elements) {
- if (elements.length == 0) {
- return null;
- }
-
- return new DropFeedback(null, new IFeedbackPainter() {
- @Override
- public void paint(@NonNull IGraphics gc, @NonNull INode node,
- @NonNull DropFeedback feedback) {
- drawFeedback(gc, node, elements, feedback);
- }
- });
- }
-
- protected void drawFeedback(
- IGraphics gc,
- INode targetNode,
- IDragElement[] elements,
- DropFeedback feedback) {
- Rect b = targetNode.getBounds();
- if (!b.isValid()) {
- return;
- }
-
- gc.useStyle(DrawingStyle.DROP_RECIPIENT);
- gc.drawRect(b);
-
- // Get the drop point
- Point p = (Point) feedback.userData;
-
- if (p == null) {
- return;
- }
-
- Rect be = elements[0].getBounds();
-
- gc.useStyle(DrawingStyle.DROP_PREVIEW);
- if (be.isValid()) {
- // At least the first element has a bound. Draw rectangles
- // for all dropped elements with valid bounds, offset at
- // (0,0)
- for (IDragElement it : elements) {
- Rect currBounds = it.getBounds();
- if (currBounds.isValid()) {
- int offsetX = b.x - currBounds.x;
- int offsetY = b.y - currBounds.y;
- drawElement(gc, it, offsetX, offsetY);
- }
- }
- } else {
- // We don't have bounds for new elements. In this case
- // just draw insert lines indicating the top left corner where
- // the item will be placed
-
- // +1: Place lines fully within the view (the stroke width is 2) to
- // make
- // it even more visually obvious
- gc.drawLine(b.x + 1, b.y, b.x + 1, b.y + b.h);
- gc.drawLine(b.x, b.y + 1, b.x + b.w, b.y + 1);
- }
- }
-
- @Override
- public DropFeedback onDropMove(@NonNull INode targetNode, @NonNull IDragElement[] elements,
- @Nullable DropFeedback feedback, @NonNull Point p) {
- feedback.userData = p;
- feedback.requestPaint = true;
- return feedback;
- }
-
- @Override
- public void onDropLeave(@NonNull INode targetNode, @NonNull IDragElement[] elements,
- @Nullable DropFeedback feedback) {
- // ignore
- }
-
- @Override
- public void onDropped(final @NonNull INode targetNode, final @NonNull IDragElement[] elements,
- final @Nullable DropFeedback feedback, final @NonNull Point p) {
- Rect b = targetNode.getBounds();
- if (!b.isValid()) {
- return;
- }
-
- // Collect IDs from dropped elements and remap them to new IDs
- // if this is a copy or from a different canvas.
- final Map<String, Pair<String, String>> idMap = getDropIdMap(targetNode, elements,
- feedback.isCopy || !feedback.sameCanvas);
-
- targetNode.editXml("Add elements to FrameLayout", new INodeHandler() {
-
- @Override
- public void handle(@NonNull INode node) {
-
- // Now write the new elements.
- for (IDragElement element : elements) {
- String fqcn = element.getFqcn();
-
- INode newChild = targetNode.appendChild(fqcn);
-
- // Copy all the attributes, modifying them as needed.
- addAttributes(newChild, element, idMap, DEFAULT_ATTR_FILTER);
-
- addInnerElements(newChild, element, idMap);
- }
- }
- });
- }
-
- @Override
- public void addLayoutActions(
- @NonNull List<RuleAction> actions,
- final @NonNull INode parentNode,
- final @NonNull List<? extends INode> children) {
- super.addLayoutActions(actions, parentNode, children);
- actions.add(RuleAction.createSeparator(25));
- actions.add(createMarginAction(parentNode, children));
- if (children != null && children.size() > 0) {
- actions.add(createGravityAction(children, ATTR_LAYOUT_GRAVITY));
- }
- }
-
- @Override
- public void onChildInserted(@NonNull INode node, @NonNull INode parent,
- @NonNull InsertType insertType) {
- // Look at the fill preferences and fill embedded layouts etc
- String fqcn = node.getFqcn();
- IViewMetadata metadata = mRulesEngine.getMetadata(fqcn);
- if (metadata != null) {
- FillPreference fill = metadata.getFillPreference();
- String fillParent = getFillParentValueName();
- if (fill.fillHorizontally(true)) {
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_WIDTH, fillParent);
- }
- if (fill.fillVertically(false)) {
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_HEIGHT, fillParent);
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/GravityHelper.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/GravityHelper.java
deleted file mode 100644
index b9aabad3f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/GravityHelper.java
+++ /dev/null
@@ -1,233 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_LAYOUT_GRAVITY;
-import static com.android.SdkConstants.GRAVITY_VALUE_BOTTOM;
-import static com.android.SdkConstants.GRAVITY_VALUE_CENTER;
-import static com.android.SdkConstants.GRAVITY_VALUE_CENTER_HORIZONTAL;
-import static com.android.SdkConstants.GRAVITY_VALUE_CENTER_VERTICAL;
-import static com.android.SdkConstants.GRAVITY_VALUE_FILL;
-import static com.android.SdkConstants.GRAVITY_VALUE_FILL_HORIZONTAL;
-import static com.android.SdkConstants.GRAVITY_VALUE_FILL_VERTICAL;
-import static com.android.SdkConstants.GRAVITY_VALUE_LEFT;
-import static com.android.SdkConstants.GRAVITY_VALUE_RIGHT;
-import static com.android.SdkConstants.GRAVITY_VALUE_TOP;
-
-import org.w3c.dom.Element;
-
-/** Helper class for looking up the gravity masks of gravity attributes */
-public class GravityHelper {
- // From SDK constants; temporary
- public static final String GRAVITY_VALUE_START = "start"; //$NON-NLS-1$
- public static final String GRAVITY_VALUE_END = "end"; //$NON-NLS-1$
-
- /** Bitmask for a gravity which includes left */
- @SuppressWarnings("PointlessBitwiseExpression") // for symmetry with other fields
- public static final int GRAVITY_LEFT = 1 << 0;
-
- /** Bitmask for a gravity which includes right */
- public static final int GRAVITY_RIGHT = 1 << 1;
-
- /** Bitmask for a gravity which includes center horizontal */
- public static final int GRAVITY_CENTER_HORIZ = 1 << 2;
-
- /** Bitmask for a gravity which includes fill horizontal */
- public static final int GRAVITY_FILL_HORIZ = 1 << 3;
-
- /** Bitmask for a gravity which includes center vertical */
- public static final int GRAVITY_CENTER_VERT = 1 << 4;
-
- /** Bitmask for a gravity which includes fill vertical */
- public static final int GRAVITY_FILL_VERT = 1 << 5;
-
- /** Bitmask for a gravity which includes top */
- public static final int GRAVITY_TOP = 1 << 6;
-
- /** Bitmask for a gravity which includes bottom */
- public static final int GRAVITY_BOTTOM = 1 << 7;
-
- /** Bitmask for a gravity which includes start */
- public static final int GRAVITY_START = 1 << 8;
-
- /** Bitmask for a gravity which includes end */
- public static final int GRAVITY_END = 1 << 9;
-
- /** Bitmask for a gravity which includes any horizontal constraint */
- public static final int GRAVITY_HORIZ_MASK = GRAVITY_CENTER_HORIZ | GRAVITY_FILL_HORIZ
- | GRAVITY_LEFT | GRAVITY_RIGHT | GRAVITY_START | GRAVITY_END;
-
- /** Bitmask for a gravity which any vertical constraint */
- public static final int GRAVITY_VERT_MASK = GRAVITY_CENTER_VERT | GRAVITY_FILL_VERT
- | GRAVITY_TOP | GRAVITY_BOTTOM;
-
- /**
- * Returns the gravity of the given element
- *
- * @param element the element to look up the gravity for
- * @return a bit mask corresponding to the selected gravities
- */
- public static int getGravity(Element element) {
- String gravityString = element.getAttributeNS(ANDROID_URI, ATTR_LAYOUT_GRAVITY);
- return getGravity(gravityString, GRAVITY_LEFT | GRAVITY_TOP);
- }
-
- /**
- * Returns the gravity bitmask for the given gravity string description
- *
- * @param gravityString the gravity string description
- * @param defaultMask the default/initial bitmask to start with
- * @return a bitmask corresponding to the gravity description
- */
- public static int getGravity(String gravityString, int defaultMask) {
- int gravity = defaultMask;
- if (gravityString != null && !gravityString.isEmpty()) {
- String[] anchors = gravityString.split("\\|"); //$NON-NLS-1$
- for (String anchor : anchors) {
- if (GRAVITY_VALUE_CENTER.equals(anchor)) {
- gravity = GRAVITY_CENTER_HORIZ | GRAVITY_CENTER_VERT;
- } else if (GRAVITY_VALUE_FILL.equals(anchor)) {
- gravity = GRAVITY_FILL_HORIZ | GRAVITY_FILL_VERT;
- } else if (GRAVITY_VALUE_CENTER_VERTICAL.equals(anchor)) {
- gravity = (gravity & GRAVITY_HORIZ_MASK) | GRAVITY_CENTER_VERT;
- } else if (GRAVITY_VALUE_CENTER_HORIZONTAL.equals(anchor)) {
- gravity = (gravity & GRAVITY_VERT_MASK) | GRAVITY_CENTER_HORIZ;
- } else if (GRAVITY_VALUE_FILL_VERTICAL.equals(anchor)) {
- gravity = (gravity & GRAVITY_HORIZ_MASK) | GRAVITY_FILL_VERT;
- } else if (GRAVITY_VALUE_FILL_HORIZONTAL.equals(anchor)) {
- gravity = (gravity & GRAVITY_VERT_MASK) | GRAVITY_FILL_HORIZ;
- } else if (GRAVITY_VALUE_TOP.equals(anchor)) {
- gravity = (gravity & GRAVITY_HORIZ_MASK) | GRAVITY_TOP;
- } else if (GRAVITY_VALUE_BOTTOM.equals(anchor)) {
- gravity = (gravity & GRAVITY_HORIZ_MASK) | GRAVITY_BOTTOM;
- } else if (GRAVITY_VALUE_LEFT.equals(anchor)) {
- gravity = (gravity & (GRAVITY_VERT_MASK|GRAVITY_START)) | GRAVITY_LEFT;
- } else if (GRAVITY_VALUE_RIGHT.equals(anchor)) {
- gravity = (gravity & (GRAVITY_VERT_MASK|GRAVITY_END)) | GRAVITY_RIGHT;
- } else if (GRAVITY_VALUE_START.equals(anchor)) {
- gravity = (gravity & (GRAVITY_VERT_MASK|GRAVITY_LEFT)) | GRAVITY_START;
- } else if (GRAVITY_VALUE_END.equals(anchor)) {
- gravity = (gravity & (GRAVITY_VERT_MASK|GRAVITY_RIGHT)) | GRAVITY_END;
- } // else: "clip" not supported
- }
- }
-
- return gravity;
- }
-
- /**
- * Returns true if the given gravity bitmask is constrained horizontally
- *
- * @param gravity the gravity bitmask
- * @return true if the given gravity bitmask is constrained horizontally
- */
- public static boolean isConstrainedHorizontally(int gravity) {
- return (gravity & GRAVITY_HORIZ_MASK) != 0;
- }
-
- /**
- * Returns true if the given gravity bitmask is constrained vertically
- *
- * @param gravity the gravity bitmask
- * @return true if the given gravity bitmask is constrained vertically
- */
- public static boolean isConstrainedVertically(int gravity) {
- return (gravity & GRAVITY_VERT_MASK) != 0;
- }
-
- /**
- * Returns true if the given gravity bitmask is left aligned
- *
- * @param gravity the gravity bitmask
- * @return true if the given gravity bitmask is left aligned
- */
- public static boolean isLeftAligned(int gravity) {
- return (gravity & (GRAVITY_LEFT|GRAVITY_START)) != 0;
- }
-
- /**
- * Returns true if the given gravity bitmask is top aligned
- *
- * @param gravity the gravity bitmask
- * @return true if the given gravity bitmask is aligned
- */
- public static boolean isTopAligned(int gravity) {
- return (gravity & GRAVITY_TOP) != 0;
- }
-
- /** Returns a gravity value string from the given gravity bitmask
- *
- * @param gravity the gravity bitmask
- * @return the corresponding gravity string suitable as an XML attribute value
- */
- public static String getGravity(int gravity) {
- if (gravity == 0) {
- return "";
- }
-
- if ((gravity & (GRAVITY_CENTER_HORIZ | GRAVITY_CENTER_VERT)) ==
- (GRAVITY_CENTER_HORIZ | GRAVITY_CENTER_VERT)) {
- return GRAVITY_VALUE_CENTER;
- }
-
- StringBuilder sb = new StringBuilder(30);
- int horizontal = gravity & GRAVITY_HORIZ_MASK;
- int vertical = gravity & GRAVITY_VERT_MASK;
-
- if ((horizontal & (GRAVITY_LEFT|GRAVITY_START)) != 0) {
- if ((horizontal & GRAVITY_LEFT) != 0) {
- sb.append(GRAVITY_VALUE_LEFT);
- }
- if ((horizontal & GRAVITY_START) != 0) {
- if (sb.length() > 0) {
- sb.append('|');
- }
- sb.append(GRAVITY_VALUE_START);
- }
- } else if ((horizontal & (GRAVITY_RIGHT|GRAVITY_END)) != 0) {
- if ((horizontal & GRAVITY_RIGHT) != 0) {
- sb.append(GRAVITY_VALUE_RIGHT);
- }
- if ((horizontal & GRAVITY_END) != 0) {
- if (sb.length() > 0) {
- sb.append('|');
- }
- sb.append(GRAVITY_VALUE_END);
- }
- } else if ((horizontal & GRAVITY_CENTER_HORIZ) != 0) {
- sb.append(GRAVITY_VALUE_CENTER_HORIZONTAL);
- } else if ((horizontal & GRAVITY_FILL_HORIZ) != 0) {
- sb.append(GRAVITY_VALUE_FILL_HORIZONTAL);
- }
-
- if (sb.length() > 0 && vertical != 0) {
- sb.append('|');
- }
-
- if ((vertical & GRAVITY_TOP) != 0) {
- sb.append(GRAVITY_VALUE_TOP);
- } else if ((vertical & GRAVITY_BOTTOM) != 0) {
- sb.append(GRAVITY_VALUE_BOTTOM);
- } else if ((vertical & GRAVITY_CENTER_VERT) != 0) {
- sb.append(GRAVITY_VALUE_CENTER_VERTICAL);
- } else if ((vertical & GRAVITY_FILL_VERT) != 0) {
- sb.append(GRAVITY_VALUE_FILL_VERTICAL);
- }
-
- return sb.toString();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/GridLayoutRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/GridLayoutRule.java
deleted file mode 100644
index 80a23c6db..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/GridLayoutRule.java
+++ /dev/null
@@ -1,676 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_LAYOUT_COLUMN;
-import static com.android.SdkConstants.ATTR_LAYOUT_GRAVITY;
-import static com.android.SdkConstants.ATTR_LAYOUT_ROW;
-import static com.android.SdkConstants.ATTR_ORIENTATION;
-import static com.android.SdkConstants.FQCN_GRID_LAYOUT;
-import static com.android.SdkConstants.FQCN_SPACE;
-import static com.android.SdkConstants.FQCN_SPACE_V7;
-import static com.android.SdkConstants.GRAVITY_VALUE_FILL;
-import static com.android.SdkConstants.GRAVITY_VALUE_FILL_HORIZONTAL;
-import static com.android.SdkConstants.GRAVITY_VALUE_FILL_VERTICAL;
-import static com.android.SdkConstants.GRAVITY_VALUE_LEFT;
-import static com.android.SdkConstants.GRID_LAYOUT;
-import static com.android.SdkConstants.VALUE_HORIZONTAL;
-import static com.android.SdkConstants.VALUE_TRUE;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.DrawingStyle;
-import com.android.ide.common.api.DropFeedback;
-import com.android.ide.common.api.IDragElement;
-import com.android.ide.common.api.IFeedbackPainter;
-import com.android.ide.common.api.IGraphics;
-import com.android.ide.common.api.IMenuCallback;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.INodeHandler;
-import com.android.ide.common.api.IViewMetadata;
-import com.android.ide.common.api.IViewMetadata.FillPreference;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-import com.android.ide.common.api.Point;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.api.RuleAction;
-import com.android.ide.common.api.RuleAction.Choices;
-import com.android.ide.common.api.SegmentType;
-import com.android.ide.common.layout.grid.GridDropHandler;
-import com.android.ide.common.layout.grid.GridLayoutPainter;
-import com.android.ide.common.layout.grid.GridModel;
-import com.android.ide.common.layout.grid.GridModel.ViewData;
-import com.android.utils.Pair;
-
-import java.net.URL;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
-/**
- * An {@link IViewRule} for android.widget.GridLayout which provides designtime
- * interaction with GridLayouts.
- * <p>
- * TODO:
- * <ul>
- * <li>Handle multi-drag: preserving relative positions and alignments among dragged
- * views.
- * <li>Handle GridLayouts that have been configured in a vertical orientation.
- * <li>Handle free-form editing GridLayouts that have been manually edited rather than
- * built up using free-form editing (e.g. they might not follow the same spacing
- * convention, might use weights etc)
- * <li>Avoid setting row and column numbers on the actual elements if they can be skipped
- * to make the XML leaner.
- * </ul>
- */
-public class GridLayoutRule extends BaseLayoutRule {
- /**
- * The size of the visual regular grid that we snap to (if {@link #sSnapToGrid} is set
- */
- public static final int GRID_SIZE = 16;
-
- /** Standard gap between views */
- public static final int SHORT_GAP_DP = 16;
-
- /**
- * The preferred margin size, in pixels
- */
- public static final int MARGIN_SIZE = 32;
-
- /**
- * Size in screen pixels in the IDE of the gutter shown for new rows and columns (in
- * grid mode)
- */
- private static final int NEW_CELL_WIDTH = 10;
-
- /**
- * Maximum size of a widget relative to a cell which is allowed to fit into a cell
- * (and thereby enlarge it) before it is spread with row or column spans.
- */
- public static final double MAX_CELL_DIFFERENCE = 1.2;
-
- /** Whether debugging diagnostics is available in the toolbar */
- private static final boolean CAN_DEBUG =
- VALUE_TRUE.equals(System.getenv("ADT_DEBUG_GRIDLAYOUT")); //$NON-NLS-1$
-
- private static final String ACTION_ADD_ROW = "_addrow"; //$NON-NLS-1$
- private static final String ACTION_REMOVE_ROW = "_removerow"; //$NON-NLS-1$
- private static final String ACTION_ADD_COL = "_addcol"; //$NON-NLS-1$
- private static final String ACTION_REMOVE_COL = "_removecol"; //$NON-NLS-1$
- private static final String ACTION_ORIENTATION = "_orientation"; //$NON-NLS-1$
- private static final String ACTION_SHOW_STRUCTURE = "_structure"; //$NON-NLS-1$
- private static final String ACTION_GRID_MODE = "_gridmode"; //$NON-NLS-1$
- private static final String ACTION_SNAP = "_snap"; //$NON-NLS-1$
- private static final String ACTION_DEBUG = "_debug"; //$NON-NLS-1$
-
- private static final URL ICON_HORIZONTAL = GridLayoutRule.class.getResource("hlinear.png"); //$NON-NLS-1$
- private static final URL ICON_VERTICAL = GridLayoutRule.class.getResource("vlinear.png"); //$NON-NLS-1$
- private static final URL ICON_ADD_ROW = GridLayoutRule.class.getResource("addrow.png"); //$NON-NLS-1$
- private static final URL ICON_REMOVE_ROW = GridLayoutRule.class.getResource("removerow.png"); //$NON-NLS-1$
- private static final URL ICON_ADD_COL = GridLayoutRule.class.getResource("addcol.png"); //$NON-NLS-1$
- private static final URL ICON_REMOVE_COL = GridLayoutRule.class.getResource("removecol.png"); //$NON-NLS-1$
- private static final URL ICON_SHOW_STRUCT = GridLayoutRule.class.getResource("showgrid.png"); //$NON-NLS-1$
- private static final URL ICON_GRID_MODE = GridLayoutRule.class.getResource("gridmode.png"); //$NON-NLS-1$
- private static final URL ICON_SNAP = GridLayoutRule.class.getResource("snap.png"); //$NON-NLS-1$
-
- /**
- * Whether the IDE should show diagnostics for debugging the grid layout - including
- * spacers visibly in the outline, showing row and column numbers, and so on
- */
- public static boolean sDebugGridLayout = CAN_DEBUG;
-
- /** Whether the structure (grid model) should be displayed persistently to the user */
- public static boolean sShowStructure = false;
-
- /** Whether the drop positions should snap to a regular grid */
- public static boolean sSnapToGrid = false;
-
- /**
- * Whether the grid is edited in "grid mode" where the operations are row/column based
- * rather than free-form
- */
- public static boolean sGridMode = true;
-
- /** Constructs a new {@link GridLayoutRule} */
- public GridLayoutRule() {
- }
-
- @Override
- public void addLayoutActions(
- @NonNull List<RuleAction> actions,
- final @NonNull INode parentNode,
- final @NonNull List<? extends INode> children) {
- super.addLayoutActions(actions, parentNode, children);
-
- String namespace = getNamespace(parentNode);
- Choices orientationAction = RuleAction.createChoices(
- ACTION_ORIENTATION,
- "Orientation", //$NON-NLS-1$
- new PropertyCallback(Collections.singletonList(parentNode),
- "Change LinearLayout Orientation", namespace, ATTR_ORIENTATION), Arrays
- .<String> asList("Set Horizontal Orientation", "Set Vertical Orientation"),
- Arrays.<URL> asList(ICON_HORIZONTAL, ICON_VERTICAL), Arrays.<String> asList(
- "horizontal", "vertical"), getCurrentOrientation(parentNode),
- null /* icon */, -10, false);
- orientationAction.setRadio(true);
- actions.add(orientationAction);
-
- // Gravity and margins
- if (children != null && children.size() > 0) {
- actions.add(RuleAction.createSeparator(35));
- actions.add(createMarginAction(parentNode, children));
- actions.add(createGravityAction(children, ATTR_LAYOUT_GRAVITY));
- }
-
- IMenuCallback actionCallback = new IMenuCallback() {
- @Override
- public void action(
- final @NonNull RuleAction action,
- @NonNull List<? extends INode> selectedNodes,
- final @Nullable String valueId,
- final @Nullable Boolean newValue) {
- parentNode.editXml("Add/Remove Row/Column", new INodeHandler() {
- @Override
- public void handle(@NonNull INode n) {
- String id = action.getId();
- if (id.equals(ACTION_SHOW_STRUCTURE)) {
- sShowStructure = !sShowStructure;
- mRulesEngine.redraw();
- return;
- } else if (id.equals(ACTION_GRID_MODE)) {
- sGridMode = !sGridMode;
- mRulesEngine.redraw();
- return;
- } else if (id.equals(ACTION_SNAP)) {
- sSnapToGrid = !sSnapToGrid;
- mRulesEngine.redraw();
- return;
- } else if (id.equals(ACTION_DEBUG)) {
- sDebugGridLayout = !sDebugGridLayout;
- mRulesEngine.layout();
- return;
- }
-
- GridModel grid = GridModel.get(mRulesEngine, parentNode, null);
- if (id.equals(ACTION_ADD_ROW)) {
- grid.addRow(children);
- } else if (id.equals(ACTION_REMOVE_ROW)) {
- grid.removeRows(children);
- } else if (id.equals(ACTION_ADD_COL)) {
- grid.addColumn(children);
- } else if (id.equals(ACTION_REMOVE_COL)) {
- grid.removeColumns(children);
- }
- }
-
- });
- }
- };
-
- actions.add(RuleAction.createSeparator(142));
-
- actions.add(RuleAction.createToggle(ACTION_GRID_MODE, "Grid Model Mode",
- sGridMode, actionCallback, ICON_GRID_MODE, 145, false));
-
- // Add and Remove Column actions only apply in Grid Mode
- if (sGridMode) {
- actions.add(RuleAction.createToggle(ACTION_SHOW_STRUCTURE, "Show Structure",
- sShowStructure, actionCallback, ICON_SHOW_STRUCT, 147, false));
-
- // Add Row and Add Column
- actions.add(RuleAction.createSeparator(150));
- actions.add(RuleAction.createAction(ACTION_ADD_COL, "Add Column", actionCallback,
- ICON_ADD_COL, 160, false /* supportsMultipleNodes */));
- actions.add(RuleAction.createAction(ACTION_ADD_ROW, "Add Row", actionCallback,
- ICON_ADD_ROW, 165, false));
-
- // Remove Row and Remove Column (if something is selected)
- if (children != null && children.size() > 0) {
- // TODO: Add "Merge Columns" and "Merge Rows" ?
-
- actions.add(RuleAction.createAction(ACTION_REMOVE_COL, "Remove Column",
- actionCallback, ICON_REMOVE_COL, 170, false));
- actions.add(RuleAction.createAction(ACTION_REMOVE_ROW, "Remove Row",
- actionCallback, ICON_REMOVE_ROW, 175, false));
- }
-
- actions.add(RuleAction.createSeparator(185));
- } else {
- actions.add(RuleAction.createToggle(ACTION_SHOW_STRUCTURE, "Show Structure",
- sShowStructure, actionCallback, ICON_SHOW_STRUCT, 190, false));
-
- // Snap to Grid and Show Structure are only relevant in free form mode
- actions.add(RuleAction.createToggle(ACTION_SNAP, "Snap to Grid",
- sSnapToGrid, actionCallback, ICON_SNAP, 200, false));
- }
-
- // Temporary: Diagnostics for GridLayout
- if (CAN_DEBUG) {
- actions.add(RuleAction.createToggle(ACTION_DEBUG, "Debug",
- sDebugGridLayout, actionCallback, null, 210, false));
- }
- }
-
- /**
- * Returns the orientation attribute value currently used by the node (even if not
- * defined, in which case the default horizontal value is returned)
- */
- private String getCurrentOrientation(final INode node) {
- String orientation = node.getStringAttr(getNamespace(node), ATTR_ORIENTATION);
- if (orientation == null || orientation.length() == 0) {
- orientation = VALUE_HORIZONTAL;
- }
- return orientation;
- }
-
- @Override
- public DropFeedback onDropEnter(@NonNull INode targetNode, @Nullable Object targetView,
- @Nullable IDragElement[] elements) {
- GridDropHandler userData = new GridDropHandler(this, targetNode, targetView);
- IFeedbackPainter painter = GridLayoutPainter.createDropFeedbackPainter(this, elements);
- return new DropFeedback(userData, painter);
- }
-
- @Override
- public DropFeedback onDropMove(@NonNull INode targetNode, @NonNull IDragElement[] elements,
- @Nullable DropFeedback feedback, @NonNull Point p) {
- if (feedback == null) {
- return null;
- }
- feedback.requestPaint = true;
-
- GridDropHandler handler = (GridDropHandler) feedback.userData;
- handler.computeMatches(feedback, p);
-
- return feedback;
- }
-
- @Override
- public void onDropped(final @NonNull INode targetNode, final @NonNull IDragElement[] elements,
- @Nullable DropFeedback feedback, @NonNull Point p) {
- if (feedback == null) {
- return;
- }
-
- Rect b = targetNode.getBounds();
- if (!b.isValid()) {
- return;
- }
-
- GridDropHandler dropHandler = (GridDropHandler) feedback.userData;
- if (dropHandler.getRowMatch() == null || dropHandler.getColumnMatch() == null) {
- return;
- }
-
- // Collect IDs from dropped elements and remap them to new IDs
- // if this is a copy or from a different canvas.
- Map<String, Pair<String, String>> idMap = getDropIdMap(targetNode, elements,
- feedback.isCopy || !feedback.sameCanvas);
-
- for (IDragElement element : elements) {
- INode newChild;
- if (!sGridMode) {
- newChild = dropHandler.handleFreeFormDrop(targetNode, element);
- } else {
- newChild = dropHandler.handleGridModeDrop(targetNode, element);
- }
-
- // Copy all the attributes, modifying them as needed.
- addAttributes(newChild, element, idMap, DEFAULT_ATTR_FILTER);
-
- addInnerElements(newChild, element, idMap);
- }
- }
-
- @Override
- public void onChildInserted(@NonNull INode node, @NonNull INode parent,
- @NonNull InsertType insertType) {
- if (insertType == InsertType.MOVE_WITHIN) {
- // Don't adjust widths/heights/weights when just moving within a single layout
- return;
- }
-
- if (GridModel.isSpace(node.getFqcn())) {
- return;
- }
-
- // Attempt to set "fill" properties on newly added views such that for example
- // a text field will stretch horizontally.
- String fqcn = node.getFqcn();
- IViewMetadata metadata = mRulesEngine.getMetadata(fqcn);
- FillPreference fill = metadata.getFillPreference();
- String gravity = computeDefaultGravity(fill);
- if (gravity != null) {
- node.setAttribute(getNamespace(parent), ATTR_LAYOUT_GRAVITY, gravity);
- }
- }
-
- /**
- * Returns the namespace URI to use for GridLayout-specific attributes, such
- * as columnCount, layout_column, layout_column_span, layout_gravity etc.
- *
- * @param layout the GridLayout instance to look up the namespace for
- * @return the namespace, never null
- */
- public String getNamespace(INode layout) {
- String namespace = ANDROID_URI;
-
- String fqcn = layout.getFqcn();
- if (!fqcn.equals(GRID_LAYOUT) && !fqcn.equals(FQCN_GRID_LAYOUT)) {
- namespace = mRulesEngine.getAppNameSpace();
- }
-
- return namespace;
- }
-
- /**
- * Computes the default gravity to be used for a widget of the given fill
- * preference when added to a grid layout
- *
- * @param fill the fill preference for the widget
- * @return the gravity value, or null, to be set on the widget
- */
- public static String computeDefaultGravity(FillPreference fill) {
- String horizontal = GRAVITY_VALUE_LEFT;
- String vertical = null;
- if (fill.fillHorizontally(true /*verticalContext*/)) {
- horizontal = GRAVITY_VALUE_FILL_HORIZONTAL;
- }
- if (fill.fillVertically(true /*verticalContext*/)) {
- vertical = GRAVITY_VALUE_FILL_VERTICAL;
- }
- String gravity;
- if (horizontal == GRAVITY_VALUE_FILL_HORIZONTAL
- && vertical == GRAVITY_VALUE_FILL_VERTICAL) {
- gravity = GRAVITY_VALUE_FILL;
- } else if (vertical != null) {
- gravity = horizontal + '|' + vertical;
- } else {
- gravity = horizontal;
- }
-
- return gravity;
- }
-
- @Override
- public void onRemovingChildren(@NonNull List<INode> deleted, @NonNull INode parent,
- boolean moved) {
- super.onRemovingChildren(deleted, parent, moved);
-
- if (!sGridMode) {
- // Attempt to clean up spacer objects for any newly-empty rows or columns
- // as the result of this deletion
- GridModel grid = GridModel.get(mRulesEngine, parent, null);
- grid.onDeleted(deleted);
- }
- }
-
- @Override
- protected void paintResizeFeedback(IGraphics gc, INode node, ResizeState state) {
- if (!sGridMode) {
- GridModel grid = getGrid(state);
- GridLayoutPainter.paintResizeFeedback(gc, state.layout, grid);
- }
-
- if (resizingWidget(state)) {
- super.paintResizeFeedback(gc, node, state);
- } else {
- GridModel grid = getGrid(state);
- int startColumn = grid.getColumn(state.bounds.x);
- int endColumn = grid.getColumn(state.bounds.x2());
- int columnSpan = endColumn - startColumn + 1;
-
- int startRow = grid.getRow(state.bounds.y);
- int endRow = grid.getRow(state.bounds.y2());
- int rowSpan = endRow - startRow + 1;
-
- Rect cellBounds = grid.getCellBounds(startRow, startColumn, rowSpan, columnSpan);
- gc.useStyle(DrawingStyle.RESIZE_PREVIEW);
- gc.drawRect(cellBounds);
- }
- }
-
- /** Returns the grid size cached on the given {@link ResizeState} object */
- private GridModel getGrid(ResizeState resizeState) {
- GridModel grid = (GridModel) resizeState.clientData;
- if (grid == null) {
- grid = GridModel.get(mRulesEngine, resizeState.layout, resizeState.layoutView);
- resizeState.clientData = grid;
- }
-
- return grid;
- }
-
- @Override
- protected void setNewSizeBounds(ResizeState state, INode node, INode layout,
- Rect oldBounds, Rect newBounds, SegmentType horizontalEdge, SegmentType verticalEdge) {
-
- if (resizingWidget(state)) {
- if (state.fillWidth || state.fillHeight || state.wrapWidth || state.wrapHeight) {
- GridModel grid = getGrid(state);
- ViewData view = grid.getView(node);
- if (view != null) {
- String gravityString = grid.getGridAttribute(view.node, ATTR_LAYOUT_GRAVITY);
- int gravity = GravityHelper.getGravity(gravityString, 0);
- if (view.column > 0 && verticalEdge != null && state.fillWidth) {
- state.fillWidth = false;
- state.wrapWidth = true;
- gravity &= ~GravityHelper.GRAVITY_HORIZ_MASK;
- gravity |= GravityHelper.GRAVITY_FILL_HORIZ;
- } else if (verticalEdge != null && state.wrapWidth) {
- gravity &= ~GravityHelper.GRAVITY_HORIZ_MASK;
- gravity |= GravityHelper.GRAVITY_LEFT;
- }
- if (view.row > 0 && horizontalEdge != null && state.fillHeight) {
- state.fillHeight = false;
- state.wrapHeight = true;
- gravity &= ~GravityHelper.GRAVITY_VERT_MASK;
- gravity |= GravityHelper.GRAVITY_FILL_VERT;
- } else if (horizontalEdge != null && state.wrapHeight) {
- gravity &= ~GravityHelper.GRAVITY_VERT_MASK;
- gravity |= GravityHelper.GRAVITY_TOP;
- }
- gravityString = GravityHelper.getGravity(gravity);
- grid.setGridAttribute(view.node, ATTR_LAYOUT_GRAVITY, gravityString);
- // Fall through and set layout_width and/or layout_height to wrap_content
- }
- }
- super.setNewSizeBounds(state, node, layout, oldBounds, newBounds, horizontalEdge,
- verticalEdge);
- } else {
- Pair<Integer, Integer> spans = computeResizeSpans(state);
- int rowSpan = spans.getFirst();
- int columnSpan = spans.getSecond();
- GridModel grid = getGrid(state);
- grid.setColumnSpanAttribute(node, columnSpan);
- grid.setRowSpanAttribute(node, rowSpan);
-
- ViewData view = grid.getView(node);
- if (view != null) {
- String gravityString = grid.getGridAttribute(view.node, ATTR_LAYOUT_GRAVITY);
- int gravity = GravityHelper.getGravity(gravityString, 0);
- if (verticalEdge != null && columnSpan > 1) {
- gravity &= ~GravityHelper.GRAVITY_HORIZ_MASK;
- gravity |= GravityHelper.GRAVITY_FILL_HORIZ;
- }
- if (horizontalEdge != null && rowSpan > 1) {
- gravity &= ~GravityHelper.GRAVITY_VERT_MASK;
- gravity |= GravityHelper.GRAVITY_FILL_VERT;
- }
- gravityString = GravityHelper.getGravity(gravity);
- grid.setGridAttribute(view.node, ATTR_LAYOUT_GRAVITY, gravityString);
- }
- }
- }
-
- @Override
- protected String getResizeUpdateMessage(ResizeState state, INode child, INode parent,
- Rect newBounds, SegmentType horizontalEdge, SegmentType verticalEdge) {
- Pair<Integer, Integer> spans = computeResizeSpans(state);
- if (resizingWidget(state)) {
- String width = state.getWidthAttribute();
- String height = state.getHeightAttribute();
-
- String message;
- if (horizontalEdge == null) {
- message = width;
- } else if (verticalEdge == null) {
- message = height;
- } else {
- // U+00D7: Unicode for multiplication sign
- message = String.format("%s \u00D7 %s", width, height);
- }
-
- // Tack on a tip about using the Shift modifier key
- return String.format("%s\n(Press Shift to resize row/column spans)", message);
- } else {
- int rowSpan = spans.getFirst();
- int columnSpan = spans.getSecond();
- return String.format("ColumnSpan=%d, RowSpan=%d\n(Release Shift to resize widget itself)",
- columnSpan, rowSpan);
- }
- }
-
- /**
- * Returns true if we're resizing the widget, and false if we're resizing the cell
- * spans
- */
- private static boolean resizingWidget(ResizeState state) {
- return (state.modifierMask & DropFeedback.MODIFIER2) == 0;
- }
-
- /**
- * Computes the new column and row spans as the result of the current resizing
- * operation
- */
- private Pair<Integer, Integer> computeResizeSpans(ResizeState state) {
- GridModel grid = getGrid(state);
-
- int startColumn = grid.getColumn(state.bounds.x);
- int endColumn = grid.getColumn(state.bounds.x2());
- int columnSpan = endColumn - startColumn + 1;
-
- int startRow = grid.getRow(state.bounds.y);
- int endRow = grid.getRow(state.bounds.y2());
- int rowSpan = endRow - startRow + 1;
-
- return Pair.of(rowSpan, columnSpan);
- }
-
- /**
- * Returns the size of the new cell gutter in layout coordinates
- *
- * @return the size of the new cell gutter in layout coordinates
- */
- public int getNewCellSize() {
- return mRulesEngine.screenToLayout(NEW_CELL_WIDTH / 2);
- }
-
- @Override
- public void paintSelectionFeedback(@NonNull IGraphics graphics, @NonNull INode parentNode,
- @NonNull List<? extends INode> childNodes, @Nullable Object view) {
- super.paintSelectionFeedback(graphics, parentNode, childNodes, view);
-
- if (sShowStructure) {
- // TODO: Cache the grid
- if (view != null) {
- if (GridLayoutPainter.paintStructure(view, DrawingStyle.GUIDELINE_DASHED,
- parentNode, graphics)) {
- return;
- }
- }
- GridLayoutPainter.paintStructure(DrawingStyle.GUIDELINE_DASHED,
- parentNode, graphics, GridModel.get(mRulesEngine, parentNode, view));
- } else if (sDebugGridLayout) {
- GridLayoutPainter.paintStructure(DrawingStyle.GRID,
- parentNode, graphics, GridModel.get(mRulesEngine, parentNode, view));
- }
-
- // TBD: Highlight the cells around the selection, and display easy controls
- // for for example tweaking the rowspan/colspan of a cell? (but only in grid mode)
- }
-
- /**
- * Paste into a GridLayout. We have several possible behaviors (and many
- * more than are listed here):
- * <ol>
- * <li> Preserve the current positions of the elements (if pasted from another
- * canvas, not just XML markup copied from say a web site) and apply those
- * into the current grid. This might mean "overwriting" (sitting on top of)
- * existing elements.
- * <li> Fill available "holes" in the grid.
- * <li> Lay them out consecutively, row by row, like text.
- * <li> Some hybrid approach, where I attempt to preserve the <b>relative</b>
- * relationships (columns/wrapping, spacing between the pasted views etc)
- * but I append them to the bottom of the layout on one or more new rows.
- * <li> Try to paste at the current mouse position, if known, preserving the
- * relative distances between the existing elements there.
- * </ol>
- * Attempting to preserve the current position isn't possible right now,
- * because the clipboard data contains only the textual representation of
- * the markup. (We'd need to stash position information from a previous
- * layout render along with the clipboard data).
- * <p>
- * Currently, this implementation simply lays out the elements row by row,
- * approach #3 above.
- */
- @Override
- public void onPaste(
- @NonNull INode targetNode,
- @Nullable Object targetView,
- @NonNull IDragElement[] elements) {
- DropFeedback feedback = onDropEnter(targetNode, targetView, elements);
- if (feedback != null) {
- Rect b = targetNode.getBounds();
- if (!b.isValid()) {
- return;
- }
-
- Map<String, Pair<String, String>> idMap = getDropIdMap(targetNode, elements,
- true /* remap id's */);
-
- for (IDragElement element : elements) {
- // Skip <Space> elements and only insert the real elements being
- // copied
- if (elements.length > 1 && (FQCN_SPACE.equals(element.getFqcn())
- || FQCN_SPACE_V7.equals(element.getFqcn()))) {
- continue;
- }
-
- String fqcn = element.getFqcn();
- INode newChild = targetNode.appendChild(fqcn);
- addAttributes(newChild, element, idMap, DEFAULT_ATTR_FILTER);
-
- // Ensure that we reset any potential row/column attributes from a different
- // grid layout being copied from
- GridDropHandler handler = (GridDropHandler) feedback.userData;
- GridModel grid = handler.getGrid();
- grid.setGridAttribute(newChild, ATTR_LAYOUT_COLUMN, null);
- grid.setGridAttribute(newChild, ATTR_LAYOUT_ROW, null);
-
- // TODO: Set columnSpans to avoid making these widgets completely
- // break the layout
- // Alternatively, I could just lay them all out on subsequent lines
- // with a column span of columnSpan5
-
- addInnerElements(newChild, element, idMap);
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/GridViewRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/GridViewRule.java
deleted file mode 100644
index b82f391b4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/GridViewRule.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.ATTR_NUM_COLUMNS;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-
-/**
- * An {@link IViewRule} for android.widget.GridView
- */
-public class GridViewRule extends BaseViewRule {
-
- @Override
- public void onCreate(@NonNull INode node, @NonNull INode parent,
- @NonNull InsertType insertType) {
- super.onCreate(node, parent, insertType);
-
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_WIDTH, getFillParentValueName());
- node.setAttribute(ANDROID_URI, ATTR_NUM_COLUMNS, "3"); //$NON-NLS-1$
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/HorizontalScrollViewRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/HorizontalScrollViewRule.java
deleted file mode 100644
index 722949051..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/HorizontalScrollViewRule.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.ATTR_ORIENTATION;
-import static com.android.SdkConstants.FQCN_LINEAR_LAYOUT;
-import static com.android.SdkConstants.VALUE_HORIZONTAL;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.DrawingStyle;
-import com.android.ide.common.api.DropFeedback;
-import com.android.ide.common.api.IDragElement;
-import com.android.ide.common.api.IGraphics;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-import com.android.ide.common.api.Point;
-import com.android.ide.common.api.Rect;
-
-/**
- * An {@link IViewRule} for android.widget.HorizontalScrollView.
- */
-public class HorizontalScrollViewRule extends FrameLayoutRule {
-
- @Override
- public void onChildInserted(@NonNull INode child, @NonNull INode parent,
- @NonNull InsertType insertType) {
- super.onChildInserted(child, parent, insertType);
-
- // The child of the ScrollView should fill in both directions
- String fillParent = getFillParentValueName();
- child.setAttribute(ANDROID_URI, ATTR_LAYOUT_WIDTH, fillParent);
- child.setAttribute(ANDROID_URI, ATTR_LAYOUT_HEIGHT, fillParent);
- }
-
- @Override
- public void onCreate(@NonNull INode node, @NonNull INode parent,
- @NonNull InsertType insertType) {
- super.onCreate(node, parent, insertType);
-
- if (insertType.isCreate()) {
- // Insert a horizontal linear layout which is commonly used with horizontal scrollbars
- // as described by the documentation for HorizontalScrollbars.
- INode linearLayout = node.appendChild(FQCN_LINEAR_LAYOUT);
- linearLayout.setAttribute(ANDROID_URI, ATTR_ORIENTATION,
- VALUE_HORIZONTAL);
- }
- }
-
- @Override
- public DropFeedback onDropMove(@NonNull INode targetNode, @NonNull IDragElement[] elements,
- @Nullable DropFeedback feedback, @NonNull Point p) {
- DropFeedback f = super.onDropMove(targetNode, elements, feedback, p);
-
- // HorizontalScrollViews only allow a single child
- if (targetNode.getChildren().length > 0) {
- f.invalidTarget = true;
- }
- return f;
- }
-
- @Override
- protected void drawFeedback(
- IGraphics gc,
- INode targetNode,
- IDragElement[] elements,
- DropFeedback feedback) {
- if (targetNode.getChildren().length > 0) {
- Rect b = targetNode.getBounds();
- if (b.isValid()) {
- gc.useStyle(DrawingStyle.DROP_RECIPIENT);
- gc.drawRect(b);
- }
- } else {
- super.drawFeedback(gc, targetNode, elements, feedback);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/IgnoredLayoutRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/IgnoredLayoutRule.java
deleted file mode 100644
index 3a65a8601..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/IgnoredLayoutRule.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.DropFeedback;
-import com.android.ide.common.api.IDragElement;
-import com.android.ide.common.api.INode;
-
-/**
- * An ignored layout is a layout that should not be treated as a layout by the
- * visual editor (usually because the widget extends a layout class we recognize
- * and support, but where the widget is more restrictive in how it manages its
- * children so we don't want to expose the normal configuration options).
- * <p>
- * For example, the ZoomControls widget is not user-configurable as a
- * LinearLayout even though it extends it. Our ZoomControls rule is therefore a
- * subclass of this {@link IgnoredLayoutRule} class.
- */
-public abstract class IgnoredLayoutRule extends BaseLayoutRule {
- @Override
- public DropFeedback onDropEnter(@NonNull INode targetNode, @Nullable Object targetView,
- @Nullable IDragElement[] elements) {
- // Do nothing; this layout rule corresponds to a layout that
- // should not be handled as a layout by the visual editor - usually
- // because some widget is extending a layout for implementation purposes
- // but does not want to expose configurability of the base layout in the
- // editor.
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ImageButtonRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ImageButtonRule.java
deleted file mode 100644
index 990795091..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ImageButtonRule.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_SRC;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-
-/**
- * An {@link IViewRule} for android.widget.ImageButton.
- */
-public class ImageButtonRule extends BaseViewRule {
-
- @Override
- public void onCreate(@NonNull INode node, @NonNull INode parent,
- @NonNull InsertType insertType) {
- super.onCreate(node, parent, insertType);
-
- // When dropping an include tag, ask the user which layout to include.
- if (insertType == InsertType.CREATE) { // NOT InsertType.CREATE_PREVIEW
- String src = mRulesEngine.displayResourceInput("drawable", ""); //$NON-NLS-1$ //$NON-NLS-2$
- if (src != null) {
- node.editXml("Set Image",
- new PropertySettingNodeHandler(ANDROID_URI, ATTR_SRC,
- src.length() > 0 ? src : null));
- return;
- }
- }
-
- // Fallback if dismissed or during previews etc
- if (insertType.isCreate()) {
- node.setAttribute(ANDROID_URI, ATTR_SRC, getSampleImageSrc());
- }
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ImageViewRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ImageViewRule.java
deleted file mode 100644
index bc0184c4f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ImageViewRule.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_SRC;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-
-/**
- * An {@link IViewRule} for android.widget.ImageViewRule.
- */
-public class ImageViewRule extends BaseViewRule {
-
- @Override
- public void onCreate(@NonNull INode node, @NonNull INode parent,
- @NonNull InsertType insertType) {
- super.onCreate(node, parent, insertType);
-
- // When dropping an include tag, ask the user which layout to include.
- if (insertType == InsertType.CREATE) { // NOT InsertType.CREATE_PREVIEW
- String src = mRulesEngine.displayResourceInput("drawable", ""); //$NON-NLS-1$ //$NON-NLS-2$
- if (src != null) {
- node.editXml("Set Image",
- new PropertySettingNodeHandler(ANDROID_URI, ATTR_SRC,
- src.length() > 0 ? src : null));
- return;
- } else {
- // Remove the view; the insertion was canceled
- parent.removeChild(node);
- }
- }
-
- // Fallback if dismissed or during previews etc
- if (insertType.isCreate()) {
- node.setAttribute(ANDROID_URI, ATTR_SRC, getSampleImageSrc());
- }
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/IncludeRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/IncludeRule.java
deleted file mode 100644
index fcb1a6dac..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/IncludeRule.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ATTR_LAYOUT;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-
-/**
- * An {@link IViewRule} for the special XML {@code <include>} tag.
- */
-public class IncludeRule extends BaseViewRule {
- @Override
- public void onCreate(@NonNull INode node, @NonNull INode parent,
- @NonNull InsertType insertType) {
- // When dropping an include tag, ask the user which layout to include.
- if (insertType == InsertType.CREATE) { // NOT InsertType.CREATE_PREVIEW
- String include = mRulesEngine.displayIncludeSourceInput();
- if (include != null) {
- node.editXml("Include Layout",
- // Note -- the layout attribute is NOT in the Android namespace!
- new PropertySettingNodeHandler(null, ATTR_LAYOUT,
- include.length() > 0 ? include : null));
- } else {
- // Remove the view; the insertion was canceled
- parent.removeChild(node);
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/LinearLayoutRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/LinearLayoutRule.java
deleted file mode 100644
index 610fe5d8b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/LinearLayoutRule.java
+++ /dev/null
@@ -1,1092 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_BASELINE_ALIGNED;
-import static com.android.SdkConstants.ATTR_LAYOUT_GRAVITY;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_WEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.ATTR_ORIENTATION;
-import static com.android.SdkConstants.ATTR_WEIGHT_SUM;
-import static com.android.SdkConstants.VALUE_1;
-import static com.android.SdkConstants.VALUE_HORIZONTAL;
-import static com.android.SdkConstants.VALUE_VERTICAL;
-import static com.android.SdkConstants.VALUE_WRAP_CONTENT;
-import static com.android.SdkConstants.VALUE_ZERO_DP;
-import static com.android.ide.eclipse.adt.AdtUtils.formatFloatAttribute;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.DrawingStyle;
-import com.android.ide.common.api.DropFeedback;
-import com.android.ide.common.api.IClientRulesEngine;
-import com.android.ide.common.api.IDragElement;
-import com.android.ide.common.api.IFeedbackPainter;
-import com.android.ide.common.api.IGraphics;
-import com.android.ide.common.api.IMenuCallback;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.INodeHandler;
-import com.android.ide.common.api.IViewMetadata;
-import com.android.ide.common.api.IViewMetadata.FillPreference;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-import com.android.ide.common.api.Point;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.api.RuleAction;
-import com.android.ide.common.api.RuleAction.Choices;
-import com.android.ide.common.api.SegmentType;
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
-/**
- * An {@link IViewRule} for android.widget.LinearLayout and all its derived
- * classes.
- */
-public class LinearLayoutRule extends BaseLayoutRule {
- private static final String ACTION_ORIENTATION = "_orientation"; //$NON-NLS-1$
- private static final String ACTION_WEIGHT = "_weight"; //$NON-NLS-1$
- private static final String ACTION_DISTRIBUTE = "_distribute"; //$NON-NLS-1$
- private static final String ACTION_BASELINE = "_baseline"; //$NON-NLS-1$
- private static final String ACTION_CLEAR = "_clear"; //$NON-NLS-1$
- private static final String ACTION_DOMINATE = "_dominate"; //$NON-NLS-1$
-
- private static final URL ICON_HORIZONTAL =
- LinearLayoutRule.class.getResource("hlinear.png"); //$NON-NLS-1$
- private static final URL ICON_VERTICAL =
- LinearLayoutRule.class.getResource("vlinear.png"); //$NON-NLS-1$
- private static final URL ICON_WEIGHTS =
- LinearLayoutRule.class.getResource("weights.png"); //$NON-NLS-1$
- private static final URL ICON_DISTRIBUTE =
- LinearLayoutRule.class.getResource("distribute.png"); //$NON-NLS-1$
- private static final URL ICON_BASELINE =
- LinearLayoutRule.class.getResource("baseline.png"); //$NON-NLS-1$
- private static final URL ICON_CLEAR_WEIGHTS =
- LinearLayoutRule.class.getResource("clearweights.png"); //$NON-NLS-1$
- private static final URL ICON_DOMINATE =
- LinearLayoutRule.class.getResource("allweight.png"); //$NON-NLS-1$
-
- /**
- * Returns the current orientation, regardless of whether it has been defined in XML
- *
- * @param node The LinearLayout to look up the orientation for
- * @return "horizontal" or "vertical" depending on the current orientation of the
- * linear layout
- */
- private String getCurrentOrientation(final INode node) {
- String orientation = node.getStringAttr(ANDROID_URI, ATTR_ORIENTATION);
- if (orientation == null || orientation.length() == 0) {
- orientation = VALUE_HORIZONTAL;
- }
- return orientation;
- }
-
- /**
- * Returns true if the given node represents a vertical linear layout.
- * @param node the node to check layout orientation for
- * @return true if the layout is in vertical mode, otherwise false
- */
- protected boolean isVertical(INode node) {
- // Horizontal is the default, so if no value is specified it is horizontal.
- return VALUE_VERTICAL.equals(node.getStringAttr(ANDROID_URI,
- ATTR_ORIENTATION));
- }
-
- /**
- * Returns true if this LinearLayout supports switching orientation.
- *
- * @return true if this layout supports orientations
- */
- protected boolean supportsOrientation() {
- return true;
- }
-
- @Override
- public void addLayoutActions(
- @NonNull List<RuleAction> actions,
- final @NonNull INode parentNode,
- final @NonNull List<? extends INode> children) {
- super.addLayoutActions(actions, parentNode, children);
- if (supportsOrientation()) {
- Choices action = RuleAction.createChoices(
- ACTION_ORIENTATION, "Orientation", //$NON-NLS-1$
- new PropertyCallback(Collections.singletonList(parentNode),
- "Change LinearLayout Orientation",
- ANDROID_URI, ATTR_ORIENTATION),
- Arrays.<String>asList("Set Horizontal Orientation","Set Vertical Orientation"),
- Arrays.<URL>asList(ICON_HORIZONTAL, ICON_VERTICAL),
- Arrays.<String>asList("horizontal", "vertical"),
- getCurrentOrientation(parentNode),
- null /* icon */,
- -10,
- false /* supportsMultipleNodes */
- );
- action.setRadio(true);
- actions.add(action);
- }
- if (!isVertical(parentNode)) {
- String current = parentNode.getStringAttr(ANDROID_URI, ATTR_BASELINE_ALIGNED);
- boolean isAligned = current == null || Boolean.valueOf(current);
- actions.add(RuleAction.createToggle(ACTION_BASELINE, "Toggle Baseline Alignment",
- isAligned,
- new PropertyCallback(Collections.singletonList(parentNode),
- "Change Baseline Alignment",
- ANDROID_URI, ATTR_BASELINE_ALIGNED), // TODO: Also set index?
- ICON_BASELINE, 38, false));
- }
-
- // Gravity
- if (children != null && children.size() > 0) {
- actions.add(RuleAction.createSeparator(35));
-
- // Margins
- actions.add(createMarginAction(parentNode, children));
-
- // Gravity
- actions.add(createGravityAction(children, ATTR_LAYOUT_GRAVITY));
-
- // Weights
- IMenuCallback actionCallback = new IMenuCallback() {
- @Override
- public void action(
- final @NonNull RuleAction action,
- @NonNull List<? extends INode> selectedNodes,
- final @Nullable String valueId,
- final @Nullable Boolean newValue) {
- parentNode.editXml("Change Weight", new INodeHandler() {
- @Override
- public void handle(@NonNull INode n) {
- String id = action.getId();
- if (id.equals(ACTION_WEIGHT)) {
- String weight =
- children.get(0).getStringAttr(ANDROID_URI, ATTR_LAYOUT_WEIGHT);
- if (weight == null || weight.length() == 0) {
- weight = "0.0"; //$NON-NLS-1$
- }
- weight = mRulesEngine.displayInput("Enter Weight Value:", weight,
- null);
- if (weight != null) {
- if (weight.isEmpty()) {
- weight = null; // remove attribute
- }
- for (INode child : children) {
- child.setAttribute(ANDROID_URI,
- ATTR_LAYOUT_WEIGHT, weight);
- }
- }
- } else if (id.equals(ACTION_DISTRIBUTE)) {
- distributeWeights(parentNode, parentNode.getChildren());
- } else if (id.equals(ACTION_CLEAR)) {
- clearWeights(parentNode);
- } else if (id.equals(ACTION_CLEAR) || id.equals(ACTION_DOMINATE)) {
- clearWeights(parentNode);
- distributeWeights(parentNode,
- children.toArray(new INode[children.size()]));
- } else {
- assert id.equals(ACTION_BASELINE);
- }
- }
- });
- }
- };
- actions.add(RuleAction.createSeparator(50));
- actions.add(RuleAction.createAction(ACTION_DISTRIBUTE, "Distribute Weights Evenly",
- actionCallback, ICON_DISTRIBUTE, 60, false /*supportsMultipleNodes*/));
- actions.add(RuleAction.createAction(ACTION_DOMINATE, "Assign All Weight",
- actionCallback, ICON_DOMINATE, 70, false));
- actions.add(RuleAction.createAction(ACTION_WEIGHT, "Change Layout Weight",
- actionCallback, ICON_WEIGHTS, 80, false));
- actions.add(RuleAction.createAction(ACTION_CLEAR, "Clear All Weights",
- actionCallback, ICON_CLEAR_WEIGHTS, 90, false));
- }
- }
-
- private void distributeWeights(INode parentNode, INode[] targets) {
- // Any XML to get weight sum?
- String weightSum = parentNode.getStringAttr(ANDROID_URI,
- ATTR_WEIGHT_SUM);
- double sum = -1.0;
- if (weightSum != null) {
- // Distribute
- try {
- sum = Double.parseDouble(weightSum);
- } catch (NumberFormatException nfe) {
- // Just keep using the default
- }
- }
- int numTargets = targets.length;
- double share;
- if (sum <= 0.0) {
- // The sum will be computed from the children, so just
- // use arbitrary amount
- share = 1.0;
- } else {
- share = sum / numTargets;
- }
- String value = formatFloatAttribute((float) share);
- String sizeAttribute = isVertical(parentNode) ?
- ATTR_LAYOUT_HEIGHT : ATTR_LAYOUT_WIDTH;
- for (INode target : targets) {
- target.setAttribute(ANDROID_URI, ATTR_LAYOUT_WEIGHT, value);
- // Also set the width/height to 0dp to ensure actual equal
- // size (without this, only the remaining space is
- // distributed)
- if (VALUE_WRAP_CONTENT.equals(target.getStringAttr(ANDROID_URI, sizeAttribute))) {
- target.setAttribute(ANDROID_URI, sizeAttribute, VALUE_ZERO_DP);
- }
- }
- }
-
- private void clearWeights(INode parentNode) {
- // Clear attributes
- String sizeAttribute = isVertical(parentNode)
- ? ATTR_LAYOUT_HEIGHT : ATTR_LAYOUT_WIDTH;
- for (INode target : parentNode.getChildren()) {
- target.setAttribute(ANDROID_URI, ATTR_LAYOUT_WEIGHT, null);
- String size = target.getStringAttr(ANDROID_URI, sizeAttribute);
- if (size != null && size.startsWith("0")) { //$NON-NLS-1$
- target.setAttribute(ANDROID_URI, sizeAttribute, VALUE_WRAP_CONTENT);
- }
- }
- }
-
- // ==== Drag'n'drop support ====
-
- @Override
- public DropFeedback onDropEnter(final @NonNull INode targetNode, @Nullable Object targetView,
- final @Nullable IDragElement[] elements) {
-
- if (elements.length == 0) {
- return null;
- }
-
- Rect bn = targetNode.getBounds();
- if (!bn.isValid()) {
- return null;
- }
-
- boolean isVertical = isVertical(targetNode);
-
- // Prepare a list of insertion points: X coords for horizontal, Y for
- // vertical.
- List<MatchPos> indexes = new ArrayList<MatchPos>();
-
- int last = isVertical ? bn.y : bn.x;
- int pos = 0;
- boolean lastDragged = false;
- int selfPos = -1;
- for (INode it : targetNode.getChildren()) {
- Rect bc = it.getBounds();
- if (bc.isValid()) {
- // First see if this node looks like it's the same as one of the
- // *dragged* bounds
- boolean isDragged = false;
- for (IDragElement element : elements) {
- // This tries to determine if an INode corresponds to an
- // IDragElement, by comparing their bounds.
- if (element.isSame(it)) {
- isDragged = true;
- break;
- }
- }
-
- // We don't want to insert drag positions before or after the
- // element that is itself being dragged. However, we -do- want
- // to insert a match position here, at the center, such that
- // when you drag near its current position we show a match right
- // where it's already positioned.
- if (isDragged) {
- int v = isVertical ? bc.y + (bc.h / 2) : bc.x + (bc.w / 2);
- selfPos = pos;
- indexes.add(new MatchPos(v, pos++));
- } else if (lastDragged) {
- // Even though we don't want to insert a match below, we
- // need to increment the index counter such that subsequent
- // lines know their correct index in the child list.
- pos++;
- } else {
- // Add an insertion point between the last point and the
- // start of this child
- int v = isVertical ? bc.y : bc.x;
- v = (last + v) / 2;
- indexes.add(new MatchPos(v, pos++));
- }
-
- last = isVertical ? (bc.y + bc.h) : (bc.x + bc.w);
- lastDragged = isDragged;
- } else {
- // We still have to count this position even if it has no bounds, or
- // subsequent children will be inserted at the wrong place
- pos++;
- }
- }
-
- // Finally add an insert position after all the children - unless of
- // course we happened to be dragging the last element
- if (!lastDragged) {
- int v = last + 1;
- indexes.add(new MatchPos(v, pos));
- }
-
- int posCount = targetNode.getChildren().length + 1;
- return new DropFeedback(new LinearDropData(indexes, posCount, isVertical, selfPos),
- new IFeedbackPainter() {
-
- @Override
- public void paint(@NonNull IGraphics gc, @NonNull INode node,
- @NonNull DropFeedback feedback) {
- // Paint callback for the LinearLayout. This is called
- // by the canvas when a draw is needed.
- drawFeedback(gc, node, elements, feedback);
- }
- });
- }
-
- void drawFeedback(IGraphics gc, INode node, IDragElement[] elements, DropFeedback feedback) {
- Rect b = node.getBounds();
- if (!b.isValid()) {
- return;
- }
-
- // Highlight the receiver
- gc.useStyle(DrawingStyle.DROP_RECIPIENT);
- gc.drawRect(b);
-
- gc.useStyle(DrawingStyle.DROP_ZONE);
-
- LinearDropData data = (LinearDropData) feedback.userData;
- boolean isVertical = data.isVertical();
- int selfPos = data.getSelfPos();
-
- for (MatchPos it : data.getIndexes()) {
- int i = it.getDistance();
- int pos = it.getPosition();
- // Don't show insert drop zones for "self"-index since that one goes
- // right through the center of the widget rather than in a sibling
- // position
- if (pos != selfPos) {
- if (isVertical) {
- // draw horizontal lines
- gc.drawLine(b.x, i, b.x + b.w, i);
- } else {
- // draw vertical lines
- gc.drawLine(i, b.y, i, b.y + b.h);
- }
- }
- }
-
- Integer currX = data.getCurrX();
- Integer currY = data.getCurrY();
-
- if (currX != null && currY != null) {
- gc.useStyle(DrawingStyle.DROP_ZONE_ACTIVE);
-
- int x = currX;
- int y = currY;
-
- Rect be = elements[0].getBounds();
-
- // Draw a clear line at the closest drop zone (unless we're over the
- // dragged element itself)
- if (data.getInsertPos() != selfPos || selfPos == -1) {
- gc.useStyle(DrawingStyle.DROP_PREVIEW);
- if (data.getWidth() != null) {
- int width = data.getWidth();
- int fromX = x - width / 2;
- int toX = x + width / 2;
- gc.drawLine(fromX, y, toX, y);
- } else if (data.getHeight() != null) {
- int height = data.getHeight();
- int fromY = y - height / 2;
- int toY = y + height / 2;
- gc.drawLine(x, fromY, x, toY);
- }
- }
-
- if (be.isValid()) {
- boolean isLast = data.isLastPosition();
-
- // At least the first element has a bound. Draw rectangles for
- // all dropped elements with valid bounds, offset at the drop
- // point.
- int offsetX;
- int offsetY;
- if (isVertical) {
- offsetX = b.x - be.x;
- offsetY = currY - be.y - (isLast ? 0 : (be.h / 2));
-
- } else {
- offsetX = currX - be.x - (isLast ? 0 : (be.w / 2));
- offsetY = b.y - be.y;
- }
-
- gc.useStyle(DrawingStyle.DROP_PREVIEW);
- for (IDragElement element : elements) {
- Rect bounds = element.getBounds();
- if (bounds.isValid() && (bounds.w > b.w || bounds.h > b.h) &&
- node.getChildren().length == 0) {
- // The bounds of the child does not fully fit inside the target.
- // Limit the bounds to the layout bounds (but only when there
- // are no children, since otherwise positioning around the existing
- // children gets difficult)
- final int px, py, pw, ph;
- if (bounds.w > b.w) {
- px = b.x;
- pw = b.w;
- } else {
- px = bounds.x + offsetX;
- pw = bounds.w;
- }
- if (bounds.h > b.h) {
- py = b.y;
- ph = b.h;
- } else {
- py = bounds.y + offsetY;
- ph = bounds.h;
- }
- Rect within = new Rect(px, py, pw, ph);
- gc.drawRect(within);
- } else {
- drawElement(gc, element, offsetX, offsetY);
- }
- }
- }
- }
- }
-
- @Override
- public DropFeedback onDropMove(@NonNull INode targetNode, @NonNull IDragElement[] elements,
- @Nullable DropFeedback feedback, @NonNull Point p) {
- Rect b = targetNode.getBounds();
- if (!b.isValid()) {
- return feedback;
- }
-
- LinearDropData data = (LinearDropData) feedback.userData;
- boolean isVertical = data.isVertical();
-
- int bestDist = Integer.MAX_VALUE;
- int bestIndex = Integer.MIN_VALUE;
- Integer bestPos = null;
-
- for (MatchPos index : data.getIndexes()) {
- int i = index.getDistance();
- int pos = index.getPosition();
- int dist = (isVertical ? p.y : p.x) - i;
- if (dist < 0)
- dist = -dist;
- if (dist < bestDist) {
- bestDist = dist;
- bestIndex = i;
- bestPos = pos;
- if (bestDist <= 0)
- break;
- }
- }
-
- if (bestIndex != Integer.MIN_VALUE) {
- Integer oldX = data.getCurrX();
- Integer oldY = data.getCurrY();
-
- if (isVertical) {
- data.setCurrX(b.x + b.w / 2);
- data.setCurrY(bestIndex);
- data.setWidth(b.w);
- data.setHeight(null);
- } else {
- data.setCurrX(bestIndex);
- data.setCurrY(b.y + b.h / 2);
- data.setWidth(null);
- data.setHeight(b.h);
- }
-
- data.setInsertPos(bestPos);
-
- feedback.requestPaint = !equals(oldX, data.getCurrX())
- || !equals(oldY, data.getCurrY());
- }
-
- return feedback;
- }
-
- private static boolean equals(Integer i1, Integer i2) {
- if (i1 == i2) {
- return true;
- } else if (i1 != null) {
- return i1.equals(i2);
- } else {
- // We know i2 != null
- return i2.equals(i1);
- }
- }
-
- @Override
- public void onDropLeave(@NonNull INode targetNode, @NonNull IDragElement[] elements,
- @Nullable DropFeedback feedback) {
- // ignore
- }
-
- @Override
- public void onDropped(final @NonNull INode targetNode, final @NonNull IDragElement[] elements,
- final @Nullable DropFeedback feedback, final @NonNull Point p) {
-
- LinearDropData data = (LinearDropData) feedback.userData;
- final int initialInsertPos = data.getInsertPos();
- insertAt(targetNode, elements, feedback.isCopy || !feedback.sameCanvas, initialInsertPos);
- }
-
- @Override
- public void onChildInserted(@NonNull INode node, @NonNull INode parent,
- @NonNull InsertType insertType) {
- if (insertType == InsertType.MOVE_WITHIN) {
- // Don't adjust widths/heights/weights when just moving within a single
- // LinearLayout
- return;
- }
-
- // Attempt to set fill-properties on newly added views such that for example,
- // in a vertical layout, a text field defaults to filling horizontally, but not
- // vertically.
- String fqcn = node.getFqcn();
- IViewMetadata metadata = mRulesEngine.getMetadata(fqcn);
- if (metadata != null) {
- boolean vertical = isVertical(parent);
- FillPreference fill = metadata.getFillPreference();
- String fillParent = getFillParentValueName();
- if (fill.fillHorizontally(vertical)) {
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_WIDTH, fillParent);
- } else if (!vertical && fill == FillPreference.WIDTH_IN_VERTICAL) {
- // In a horizontal layout, make views that would fill horizontally in a
- // vertical layout have a non-zero weight instead. This will make the item
- // fill but only enough to allow other views to be shown as well.
- // (However, for drags within the same layout we do not touch
- // the weight, since it might already have been tweaked to a particular
- // value)
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_WEIGHT, VALUE_1);
- }
- if (fill.fillVertically(vertical)) {
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_HEIGHT, fillParent);
- }
- }
-
- // If you insert into a layout that already is using layout weights,
- // and all the layout weights are the same (nonzero) value, then use
- // the same weight for this new layout as well. Also duplicate the 0dip/0px/0dp
- // sizes, if used.
- boolean duplicateWeight = true;
- boolean duplicate0dip = true;
- String sameWeight = null;
- String sizeAttribute = isVertical(parent) ? ATTR_LAYOUT_HEIGHT : ATTR_LAYOUT_WIDTH;
- for (INode target : parent.getChildren()) {
- if (target == node) {
- continue;
- }
- String weight = target.getStringAttr(ANDROID_URI, ATTR_LAYOUT_WEIGHT);
- if (weight == null || weight.length() == 0) {
- duplicateWeight = false;
- break;
- } else if (sameWeight != null && !sameWeight.equals(weight)) {
- duplicateWeight = false;
- } else {
- sameWeight = weight;
- }
- String size = target.getStringAttr(ANDROID_URI, sizeAttribute);
- if (size != null && !size.startsWith("0")) { //$NON-NLS-1$
- duplicate0dip = false;
- break;
- }
- }
- if (duplicateWeight && sameWeight != null) {
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_WEIGHT, sameWeight);
- if (duplicate0dip) {
- node.setAttribute(ANDROID_URI, sizeAttribute, VALUE_ZERO_DP);
- }
- }
- }
-
- /** A possible match position */
- private static class MatchPos {
- /** The pixel distance */
- private int mDistance;
- /** The position among siblings */
- private int mPosition;
-
- public MatchPos(int distance, int position) {
- mDistance = distance;
- mPosition = position;
- }
-
- @Override
- public String toString() {
- return "MatchPos [distance=" + mDistance //$NON-NLS-1$
- + ", position=" + mPosition //$NON-NLS-1$
- + "]"; //$NON-NLS-1$
- }
-
- private int getDistance() {
- return mDistance;
- }
-
- private int getPosition() {
- return mPosition;
- }
- }
-
- private static class LinearDropData {
- /** Vertical layout? */
- private final boolean mVertical;
-
- /** Insert points (pixels + index) */
- private final List<MatchPos> mIndexes;
-
- /** Number of insert positions in the target node */
- private final int mNumPositions;
-
- /** Current marker X position */
- private Integer mCurrX;
-
- /** Current marker Y position */
- private Integer mCurrY;
-
- /** Position of the dragged element in this layout (or
- -1 if the dragged element is from elsewhere) */
- private final int mSelfPos;
-
- /** Current drop insert index (-1 for "at the end") */
- private int mInsertPos = -1;
-
- /** width of match line if it's a horizontal one */
- private Integer mWidth;
-
- /** height of match line if it's a vertical one */
- private Integer mHeight;
-
- public LinearDropData(List<MatchPos> indexes, int numPositions,
- boolean isVertical, int selfPos) {
- mIndexes = indexes;
- mNumPositions = numPositions;
- mVertical = isVertical;
- mSelfPos = selfPos;
- }
-
- @Override
- public String toString() {
- return "LinearDropData [currX=" + mCurrX //$NON-NLS-1$
- + ", currY=" + mCurrY //$NON-NLS-1$
- + ", height=" + mHeight //$NON-NLS-1$
- + ", indexes=" + mIndexes //$NON-NLS-1$
- + ", insertPos=" + mInsertPos //$NON-NLS-1$
- + ", isVertical=" + mVertical //$NON-NLS-1$
- + ", selfPos=" + mSelfPos //$NON-NLS-1$
- + ", width=" + mWidth //$NON-NLS-1$
- + "]"; //$NON-NLS-1$
- }
-
- private boolean isVertical() {
- return mVertical;
- }
-
- private void setCurrX(Integer currX) {
- mCurrX = currX;
- }
-
- private Integer getCurrX() {
- return mCurrX;
- }
-
- private void setCurrY(Integer currY) {
- mCurrY = currY;
- }
-
- private Integer getCurrY() {
- return mCurrY;
- }
-
- private int getSelfPos() {
- return mSelfPos;
- }
-
- private void setInsertPos(int insertPos) {
- mInsertPos = insertPos;
- }
-
- private int getInsertPos() {
- return mInsertPos;
- }
-
- private List<MatchPos> getIndexes() {
- return mIndexes;
- }
-
- private void setWidth(Integer width) {
- mWidth = width;
- }
-
- private Integer getWidth() {
- return mWidth;
- }
-
- private void setHeight(Integer height) {
- mHeight = height;
- }
-
- private Integer getHeight() {
- return mHeight;
- }
-
- /**
- * Returns true if we are inserting into the last position
- *
- * @return true if we are inserting into the last position
- */
- public boolean isLastPosition() {
- return mInsertPos == mNumPositions - 1;
- }
- }
-
- /** Custom resize state used during linear layout resizing */
- private class LinearResizeState extends ResizeState {
- /** Whether the node should be assigned a new weight */
- public boolean useWeight;
- /** Weight sum to be applied to the parent */
- private float mNewWeightSum;
- /** The weight to be set on the node (provided {@link #useWeight} is true) */
- private float mWeight;
- /** Map from nodes to preferred bounds of nodes where the weights have been cleared */
- public final Map<INode, Rect> unweightedSizes;
- /** Total required size required by the siblings <b>without</b> weights */
- public int totalLength;
- /** List of nodes which should have their weights cleared */
- public List<INode> mClearWeights;
-
- private LinearResizeState(BaseLayoutRule rule, INode layout, Object layoutView,
- INode node) {
- super(rule, layout, layoutView, node);
-
- unweightedSizes = mRulesEngine.measureChildren(layout,
- new IClientRulesEngine.AttributeFilter() {
- @Override
- public String getAttribute(@NonNull INode n, @Nullable String namespace,
- @NonNull String localName) {
- // Clear out layout weights; we need to measure the unweighted sizes
- // of the children
- if (ATTR_LAYOUT_WEIGHT.equals(localName)
- && SdkConstants.NS_RESOURCES.equals(namespace)) {
- return ""; //$NON-NLS-1$
- }
-
- return null;
- }
- });
-
- // Compute total required size required by the siblings *without* weights
- totalLength = 0;
- final boolean isVertical = isVertical(layout);
- for (Map.Entry<INode, Rect> entry : unweightedSizes.entrySet()) {
- Rect preferredSize = entry.getValue();
- if (isVertical) {
- totalLength += preferredSize.h;
- } else {
- totalLength += preferredSize.w;
- }
- }
- }
-
- /** Resets the computed state */
- void reset() {
- mNewWeightSum = -1;
- useWeight = false;
- mClearWeights = null;
- }
-
- /** Sets a weight to be applied to the node */
- void setWeight(float weight) {
- useWeight = true;
- mWeight = weight;
- }
-
- /** Sets a weight sum to be applied to the parent layout */
- void setWeightSum(float weightSum) {
- mNewWeightSum = weightSum;
- }
-
- /** Marks that the given node should be cleared when applying the new size */
- void clearWeight(INode n) {
- if (mClearWeights == null) {
- mClearWeights = new ArrayList<INode>();
- }
- mClearWeights.add(n);
- }
-
- /** Applies the state to the nodes */
- public void apply() {
- assert useWeight;
-
- String value = mWeight > 0 ? formatFloatAttribute(mWeight) : null;
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_WEIGHT, value);
-
- if (mClearWeights != null) {
- for (INode n : mClearWeights) {
- if (getWeight(n) > 0.0f) {
- n.setAttribute(ANDROID_URI, ATTR_LAYOUT_WEIGHT, null);
- }
- }
- }
-
- if (mNewWeightSum > 0.0) {
- layout.setAttribute(ANDROID_URI, ATTR_WEIGHT_SUM,
- formatFloatAttribute(mNewWeightSum));
- }
- }
- }
-
- @Override
- protected ResizeState createResizeState(INode layout, Object layoutView, INode node) {
- return new LinearResizeState(this, layout, layoutView, node);
- }
-
- protected void updateResizeState(LinearResizeState resizeState, final INode node, INode layout,
- Rect oldBounds, Rect newBounds, SegmentType horizontalEdge,
- SegmentType verticalEdge) {
- // Update the resize state.
- // This method attempts to compute a new layout weight to be used in the direction
- // of the linear layout. If the superclass has already determined that we can snap to
- // a wrap_content or match_parent boundary, we prefer that. Otherwise, we attempt to
- // compute a layout weight - which can fail if the size is too big (not enough room),
- // or if the size is too small (smaller than the natural width of the node), and so on.
- // In that case this method just aborts, which will leave the resize state object
- // in such a state that it will call the superclass to resize instead, which will fall
- // back to device independent pixel sizing.
- resizeState.reset();
-
- if (oldBounds.equals(newBounds)) {
- return;
- }
-
- // If we're setting the width/height to wrap_content/match_parent in the dimension of the
- // linear layout, then just apply wrap_content and clear weights.
- boolean isVertical = isVertical(layout);
- if (!isVertical && verticalEdge != null) {
- if (resizeState.wrapWidth || resizeState.fillWidth) {
- resizeState.clearWeight(node);
- return;
- }
- if (newBounds.w == oldBounds.w) {
- return;
- }
- }
-
- if (isVertical && horizontalEdge != null) {
- if (resizeState.wrapHeight || resizeState.fillHeight) {
- resizeState.clearWeight(node);
- return;
- }
- if (newBounds.h == oldBounds.h) {
- return;
- }
- }
-
- // Compute weight sum
- float sum = getWeightSum(layout);
- if (sum <= 0.0f) {
- sum = 1.0f;
- resizeState.setWeightSum(sum);
- }
-
- // If the new size of the node is smaller than its preferred/wrap_content size,
- // then we cannot use weights to size it; switch to pixel-based sizing instead
- Map<INode, Rect> sizes = resizeState.unweightedSizes;
- Rect nodePreferredSize = sizes.get(node);
- if (nodePreferredSize != null) {
- if (horizontalEdge != null && newBounds.h < nodePreferredSize.h ||
- verticalEdge != null && newBounds.w < nodePreferredSize.w) {
- return;
- }
- }
-
- Rect layoutBounds = layout.getBounds();
- int remaining = (isVertical ? layoutBounds.h : layoutBounds.w) - resizeState.totalLength;
- Rect nodeBounds = sizes.get(node);
- if (nodeBounds == null) {
- return;
- }
-
- if (remaining > 0) {
- int missing = 0;
- if (isVertical) {
- if (newBounds.h > nodeBounds.h) {
- missing = newBounds.h - nodeBounds.h;
- } else if (newBounds.h > resizeState.wrapBounds.h) {
- // The weights concern how much space to ADD to the view.
- // What if we have resized it to a size *smaller* than its current
- // size without the weight delta? This can happen if you for example
- // have set a hardcoded size, such as 500dp, and then size it to some
- // smaller size.
- missing = newBounds.h - resizeState.wrapBounds.h;
- remaining += nodeBounds.h - resizeState.wrapBounds.h;
- resizeState.wrapHeight = true;
- }
- } else {
- if (newBounds.w > nodeBounds.w) {
- missing = newBounds.w - nodeBounds.w;
- } else if (newBounds.w > resizeState.wrapBounds.w) {
- missing = newBounds.w - resizeState.wrapBounds.w;
- remaining += nodeBounds.w - resizeState.wrapBounds.w;
- resizeState.wrapWidth = true;
- }
- }
- if (missing > 0) {
- // (weight / weightSum) * remaining = missing, so
- // weight = missing * weightSum / remaining
- float weight = missing * sum / remaining;
- resizeState.setWeight(weight);
- }
- }
- }
-
- /**
- * {@inheritDoc}
- * <p>
- * Overridden in this layout in order to make resizing affect the layout_weight
- * attribute instead of the layout_width (for horizontal LinearLayouts) or
- * layout_height (for vertical LinearLayouts).
- */
- @Override
- protected void setNewSizeBounds(ResizeState state, final INode node, INode layout,
- Rect oldBounds, Rect newBounds, SegmentType horizontalEdge,
- SegmentType verticalEdge) {
- LinearResizeState resizeState = (LinearResizeState) state;
- updateResizeState(resizeState, node, layout, oldBounds, newBounds,
- horizontalEdge, verticalEdge);
-
- if (resizeState.useWeight) {
- resizeState.apply();
-
- // Handle resizing in the opposite dimension of the layout
- final boolean isVertical = isVertical(layout);
- if (!isVertical && horizontalEdge != null) {
- if (newBounds.h != oldBounds.h || resizeState.wrapHeight
- || resizeState.fillHeight) {
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_HEIGHT,
- resizeState.getHeightAttribute());
- }
- }
- if (isVertical && verticalEdge != null) {
- if (newBounds.w != oldBounds.w || resizeState.wrapWidth || resizeState.fillWidth) {
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_WIDTH,
- resizeState.getWidthAttribute());
- }
- }
- } else {
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_WEIGHT, null);
- super.setNewSizeBounds(resizeState, node, layout, oldBounds, newBounds,
- horizontalEdge, verticalEdge);
- }
- }
-
- @Override
- protected String getResizeUpdateMessage(ResizeState state, INode child, INode parent,
- Rect newBounds, SegmentType horizontalEdge, SegmentType verticalEdge) {
- LinearResizeState resizeState = (LinearResizeState) state;
- updateResizeState(resizeState, child, parent, child.getBounds(), newBounds,
- horizontalEdge, verticalEdge);
-
- if (resizeState.useWeight) {
- String weight = formatFloatAttribute(resizeState.mWeight);
- String dimension = String.format("weight %1$s", weight);
-
- String width;
- String height;
- if (isVertical(parent)) {
- width = resizeState.getWidthAttribute();
- height = dimension;
- } else {
- width = dimension;
- height = resizeState.getHeightAttribute();
- }
-
- if (horizontalEdge == null) {
- return width;
- } else if (verticalEdge == null) {
- return height;
- } else {
- // U+00D7: Unicode for multiplication sign
- return String.format("%s \u00D7 %s", width, height);
- }
- } else {
- return super.getResizeUpdateMessage(state, child, parent, newBounds,
- horizontalEdge, verticalEdge);
- }
- }
-
- /**
- * Returns the layout weight of of the given child of a LinearLayout, or 0.0 if it
- * does not define a weight
- */
- private static float getWeight(INode linearLayoutChild) {
- String weight = linearLayoutChild.getStringAttr(ANDROID_URI, ATTR_LAYOUT_WEIGHT);
- if (weight != null && weight.length() > 0) {
- try {
- return Float.parseFloat(weight);
- } catch (NumberFormatException nfe) {
- AdtPlugin.log(nfe, "Invalid weight %1$s", weight);
- }
- }
-
- return 0.0f;
- }
-
- /**
- * Returns the sum of all the layout weights of the children in the given LinearLayout
- *
- * @param linearLayout the layout to compute the total sum for
- * @return the total sum of all the layout weights in the given layout
- */
- private static float getWeightSum(INode linearLayout) {
- String weightSum = linearLayout.getStringAttr(ANDROID_URI,
- ATTR_WEIGHT_SUM);
- float sum = -1.0f;
- if (weightSum != null) {
- // Distribute
- try {
- sum = Float.parseFloat(weightSum);
- return sum;
- } catch (NumberFormatException nfe) {
- // Just keep using the default
- }
- }
-
- return getSumOfWeights(linearLayout);
- }
-
- private static float getSumOfWeights(INode linearLayout) {
- float sum = 0.0f;
- for (INode child : linearLayout.getChildren()) {
- sum += getWeight(child);
- }
-
- return sum;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ListViewRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ListViewRule.java
deleted file mode 100644
index 70728c81d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ListViewRule.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-
-/**
- * An {@link IViewRule} for android.widget.ListView and all its derived classes such
- * as ExpandableListView.
- * This is the "root" rule, that is used whenever there is not more specific
- * rule to apply.
- */
-public class ListViewRule extends AdapterViewRule {
-
- @Override
- public void onCreate(@NonNull INode node, @NonNull INode parent,
- @NonNull InsertType insertType) {
- super.onCreate(node, parent, insertType);
-
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_WIDTH, getFillParentValueName());
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/MapViewRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/MapViewRule.java
deleted file mode 100644
index 006661e57..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/MapViewRule.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-
-/**
- * An {@link IViewRule} for com.google.android.maps.MapView.
- * <p>
- * TODO: This class should be pulled out of the ADT and bundled with the add ons
- * (not the core jar but an optional tool jar)
- */
-public class MapViewRule extends BaseViewRule {
-
- @Override
- public void onCreate(@NonNull INode node, @NonNull INode parent,
- @NonNull InsertType insertType) {
- super.onCreate(node, parent, insertType);
-
- if (insertType.isCreate()) {
- node.setAttribute(ANDROID_URI, "android:apiKey", //$NON-NLS-1$
- "Your API key: see " + //$NON-NLS-1$
- "http://code.google.com/android/add-ons/google-apis/mapkey.html"); //$NON-NLS-1$
- }
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/MergeRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/MergeRule.java
deleted file mode 100644
index 9cef9c4b3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/MergeRule.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.RuleAction;
-
-import java.util.List;
-
-/**
- * Drop handler for the {@code <merge>} tag
- */
-public class MergeRule extends FrameLayoutRule {
- // The <merge> tag behaves a lot like the FrameLayout; all children are added
- // on top of each other at (0,0)
-
- @Override
- public void addContextMenuActions(@NonNull List<RuleAction> actions,
- final @NonNull INode selectedNode) {
- // Deliberately ignore super.getContextMenu(); we don't want to attempt to list
- // properties for the <merge> tag
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/PropertyCallback.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/PropertyCallback.java
deleted file mode 100644
index da2614eef..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/PropertyCallback.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.IMenuCallback;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.INodeHandler;
-import com.android.ide.common.api.RuleAction;
-
-import java.util.List;
-
-/**
- * Convenience implementation of {@link IMenuCallback} which can be used to set a
- * particular property to the new valueId or newValue passed from the {@link IMenuCallback}
- */
-public class PropertyCallback implements IMenuCallback {
- private final List<? extends INode> mTargetNodes;
- private final String mUndoLabel;
- private final String mUri;
- private final String mAttribute;
-
- /**
- * Creates a new property callback.
- *
- * @param targetNodes the nodes to apply the property to, or null to use the
- * nodes pass into the
- * {@link #action(RuleAction, List, String, Boolean)} method.
- * @param undoLabel the label to use for the undo action
- * @param uri the attribute URI to apply
- * @param attribute the attribute name to apply
- */
- public PropertyCallback(List<? extends INode> targetNodes, String undoLabel,
- String uri, String attribute) {
- super();
- mTargetNodes = targetNodes;
- mUndoLabel = undoLabel;
- mUri = uri;
- mAttribute = attribute;
- }
-
- // ---- Implements IMenuCallback ----
- @Override
- public void action(@NonNull RuleAction action, @NonNull List<? extends INode> selectedNodes,
- final @Nullable String valueId, final @Nullable Boolean newValue) {
- if (mTargetNodes != null && mTargetNodes.size() > 0) {
- selectedNodes = mTargetNodes;
- }
- if (selectedNodes == null || selectedNodes.size() == 0) {
- return;
- }
- final List<? extends INode> nodes = selectedNodes;
- selectedNodes.get(0).editXml(mUndoLabel, new INodeHandler() {
- @Override
- public void handle(@NonNull INode n) {
- for (INode targetNode : nodes) {
- if (valueId != null) {
- targetNode.setAttribute(mUri, mAttribute, valueId);
- } else {
- assert newValue != null;
- targetNode.setAttribute(mUri, mAttribute, Boolean.toString(newValue));
- }
- }
- }
- });
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/PropertySettingNodeHandler.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/PropertySettingNodeHandler.java
deleted file mode 100644
index 13c8842ed..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/PropertySettingNodeHandler.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.INodeHandler;
-
-/**
- * A convenience implementation of {@link INodeHandler} for setting a given attribute to a
- * given value on a particular node.
- */
-class PropertySettingNodeHandler implements INodeHandler {
- private final String mNamespaceUri;
- private final String mAttribute;
- private final String mValue;
-
- PropertySettingNodeHandler(String namespaceUri, String attribute, String value) {
- super();
- mNamespaceUri = namespaceUri;
- mAttribute = attribute;
- mValue = value;
- }
-
- @Override
- public void handle(@NonNull INode node) {
- node.setAttribute(mNamespaceUri, mAttribute, mValue);
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/QuickContactBadgeRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/QuickContactBadgeRule.java
deleted file mode 100644
index 0164794d3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/QuickContactBadgeRule.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-
-/**
- * An {@link IViewRule} for android.widget.QuickContactBadgeRule.
- */
-public class QuickContactBadgeRule extends ImageViewRule {
- @Override
- public void onCreate(@NonNull INode node, @NonNull INode parent,
- @NonNull InsertType insertType) {
- // Deliberately override onCreate such that we don't populate a default
- // image; at design time layoutlib will supply the system default contacts
- // image.
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/RadioGroupRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/RadioGroupRule.java
deleted file mode 100644
index c9aa20768..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/RadioGroupRule.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ATTR_CHECKED;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.VALUE_TRUE;
-
-
-import com.android.SdkConstants;
-import static com.android.SdkConstants.ANDROID_URI;
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-
-/**
- * An {@link IViewRule} for android.widget.RadioGroup which initializes the radio group
- * with some radio buttons
- */
-public class RadioGroupRule extends LinearLayoutRule {
- @Override
- public void onCreate(@NonNull INode node, @NonNull INode parent,
- @NonNull InsertType insertType) {
- super.onCreate(node, parent, insertType);
-
- if (insertType.isCreate()) {
- for (int i = 0; i < 3; i++) {
- INode handle = node.appendChild(SdkConstants.FQCN_RADIO_BUTTON);
- handle.setAttribute(ANDROID_URI, ATTR_ID, String.format("@+id/radio%d", i));
- if (i == 0) {
- handle.setAttribute(ANDROID_URI, ATTR_CHECKED, VALUE_TRUE);
- }
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/RelativeLayoutRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/RelativeLayoutRule.java
deleted file mode 100644
index b4bc86978..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/RelativeLayoutRule.java
+++ /dev/null
@@ -1,413 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_GRAVITY;
-import static com.android.SdkConstants.ATTR_LAYOUT_ABOVE;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_BASELINE;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_BOTTOM;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_LEFT;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_PARENT_BOTTOM;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_PARENT_LEFT;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_PARENT_RIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_PARENT_TOP;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_RIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_TOP;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_WITH_PARENT_MISSING;
-import static com.android.SdkConstants.ATTR_LAYOUT_BELOW;
-import static com.android.SdkConstants.ATTR_LAYOUT_CENTER_HORIZONTAL;
-import static com.android.SdkConstants.ATTR_LAYOUT_CENTER_IN_PARENT;
-import static com.android.SdkConstants.ATTR_LAYOUT_CENTER_VERTICAL;
-import static com.android.SdkConstants.ATTR_LAYOUT_RESOURCE_PREFIX;
-import static com.android.SdkConstants.ATTR_LAYOUT_TO_LEFT_OF;
-import static com.android.SdkConstants.ATTR_LAYOUT_TO_RIGHT_OF;
-import static com.android.SdkConstants.VALUE_TRUE;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.DropFeedback;
-import com.android.ide.common.api.IDragElement;
-import com.android.ide.common.api.IGraphics;
-import com.android.ide.common.api.IMenuCallback;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.INodeHandler;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-import com.android.ide.common.api.Point;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.api.RuleAction;
-import com.android.ide.common.api.SegmentType;
-import com.android.ide.common.layout.relative.ConstraintPainter;
-import com.android.ide.common.layout.relative.DeletionHandler;
-import com.android.ide.common.layout.relative.GuidelinePainter;
-import com.android.ide.common.layout.relative.MoveHandler;
-import com.android.ide.common.layout.relative.ResizeHandler;
-import com.android.utils.Pair;
-
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
-/**
- * An {@link IViewRule} for android.widget.RelativeLayout and all its derived
- * classes.
- */
-public class RelativeLayoutRule extends BaseLayoutRule {
- private static final String ACTION_SHOW_STRUCTURE = "_structure"; //$NON-NLS-1$
- private static final String ACTION_SHOW_CONSTRAINTS = "_constraints"; //$NON-NLS-1$
- private static final String ACTION_CENTER_VERTICAL = "_centerVert"; //$NON-NLS-1$
- private static final String ACTION_CENTER_HORIZONTAL = "_centerHoriz"; //$NON-NLS-1$
- private static final URL ICON_CENTER_VERTICALLY =
- RelativeLayoutRule.class.getResource("centerVertically.png"); //$NON-NLS-1$
- private static final URL ICON_CENTER_HORIZONTALLY =
- RelativeLayoutRule.class.getResource("centerHorizontally.png"); //$NON-NLS-1$
- private static final URL ICON_SHOW_STRUCTURE =
- BaseLayoutRule.class.getResource("structure.png"); //$NON-NLS-1$
- private static final URL ICON_SHOW_CONSTRAINTS =
- BaseLayoutRule.class.getResource("constraints.png"); //$NON-NLS-1$
-
- public static boolean sShowStructure = false;
- public static boolean sShowConstraints = true;
-
- // ==== Selection ====
-
- @Override
- public List<String> getSelectionHint(@NonNull INode parentNode, @NonNull INode childNode) {
- List<String> infos = new ArrayList<String>(18);
- addAttr(ATTR_LAYOUT_ABOVE, childNode, infos);
- addAttr(ATTR_LAYOUT_BELOW, childNode, infos);
- addAttr(ATTR_LAYOUT_TO_LEFT_OF, childNode, infos);
- addAttr(ATTR_LAYOUT_TO_RIGHT_OF, childNode, infos);
- addAttr(ATTR_LAYOUT_ALIGN_BASELINE, childNode, infos);
- addAttr(ATTR_LAYOUT_ALIGN_TOP, childNode, infos);
- addAttr(ATTR_LAYOUT_ALIGN_BOTTOM, childNode, infos);
- addAttr(ATTR_LAYOUT_ALIGN_LEFT, childNode, infos);
- addAttr(ATTR_LAYOUT_ALIGN_RIGHT, childNode, infos);
- addAttr(ATTR_LAYOUT_ALIGN_PARENT_TOP, childNode, infos);
- addAttr(ATTR_LAYOUT_ALIGN_PARENT_BOTTOM, childNode, infos);
- addAttr(ATTR_LAYOUT_ALIGN_PARENT_LEFT, childNode, infos);
- addAttr(ATTR_LAYOUT_ALIGN_PARENT_RIGHT, childNode, infos);
- addAttr(ATTR_LAYOUT_ALIGN_WITH_PARENT_MISSING, childNode, infos);
- addAttr(ATTR_LAYOUT_CENTER_HORIZONTAL, childNode, infos);
- addAttr(ATTR_LAYOUT_CENTER_IN_PARENT, childNode, infos);
- addAttr(ATTR_LAYOUT_CENTER_VERTICAL, childNode, infos);
-
- return infos;
- }
-
- private void addAttr(String propertyName, INode childNode, List<String> infos) {
- String a = childNode.getStringAttr(ANDROID_URI, propertyName);
- if (a != null && a.length() > 0) {
- // Display the layout parameters without the leading layout_ prefix
- // and id references without the @+id/ prefix
- if (propertyName.startsWith(ATTR_LAYOUT_RESOURCE_PREFIX)) {
- propertyName = propertyName.substring(ATTR_LAYOUT_RESOURCE_PREFIX.length());
- }
- a = stripIdPrefix(a);
- String s = propertyName + ": " + a;
- infos.add(s);
- }
- }
-
- @Override
- public void paintSelectionFeedback(@NonNull IGraphics graphics, @NonNull INode parentNode,
- @NonNull List<? extends INode> childNodes, @Nullable Object view) {
- super.paintSelectionFeedback(graphics, parentNode, childNodes, view);
-
- boolean showDependents = true;
- if (sShowStructure) {
- childNodes = Arrays.asList(parentNode.getChildren());
- // Avoid painting twice - both as incoming and outgoing
- showDependents = false;
- } else if (!sShowConstraints) {
- return;
- }
-
- ConstraintPainter.paintSelectionFeedback(graphics, parentNode, childNodes, showDependents);
- }
-
- // ==== Drag'n'drop support ====
-
- @Override
- public DropFeedback onDropEnter(@NonNull INode targetNode, @Nullable Object targetView,
- @Nullable IDragElement[] elements) {
- return new DropFeedback(new MoveHandler(targetNode, elements, mRulesEngine),
- new GuidelinePainter());
- }
-
- @Override
- public DropFeedback onDropMove(@NonNull INode targetNode, @NonNull IDragElement[] elements,
- @Nullable DropFeedback feedback, @NonNull Point p) {
- if (elements == null || elements.length == 0 || feedback == null) {
- return null;
- }
-
- MoveHandler state = (MoveHandler) feedback.userData;
- int offsetX = p.x + (feedback.dragBounds != null ? feedback.dragBounds.x : 0);
- int offsetY = p.y + (feedback.dragBounds != null ? feedback.dragBounds.y : 0);
- state.updateMove(feedback, elements, offsetX, offsetY, feedback.modifierMask);
-
- // Or maybe only do this if the results changed...
- feedback.requestPaint = true;
-
- return feedback;
- }
-
- @Override
- public void onDropLeave(@NonNull INode targetNode, @NonNull IDragElement[] elements,
- @Nullable DropFeedback feedback) {
- }
-
- @Override
- public void onDropped(final @NonNull INode targetNode, final @NonNull IDragElement[] elements,
- final @Nullable DropFeedback feedback, final @NonNull Point p) {
- if (feedback == null) {
- return;
- }
-
- final MoveHandler state = (MoveHandler) feedback.userData;
-
- final Map<String, Pair<String, String>> idMap = getDropIdMap(targetNode, elements,
- feedback.isCopy || !feedback.sameCanvas);
-
- targetNode.editXml("Dropped", new INodeHandler() {
- @Override
- public void handle(@NonNull INode n) {
- int index = -1;
-
- // Remove cycles
- state.removeCycles();
-
- // Now write the new elements.
- INode previous = null;
- for (IDragElement element : elements) {
- String fqcn = element.getFqcn();
-
- // index==-1 means to insert at the end.
- // Otherwise increment the insertion position.
- if (index >= 0) {
- index++;
- }
-
- INode newChild = targetNode.insertChildAt(fqcn, index);
-
- // Copy all the attributes, modifying them as needed.
- addAttributes(newChild, element, idMap, BaseLayoutRule.DEFAULT_ATTR_FILTER);
- addInnerElements(newChild, element, idMap);
-
- if (previous == null) {
- state.applyConstraints(newChild);
- previous = newChild;
- } else {
- // Arrange the nodes next to each other, depending on which
- // edge we are attaching to. For example, if attaching to the
- // top edge, arrange the subsequent nodes in a column below it.
- //
- // TODO: Try to do something smarter here where we detect
- // constraints between the dragged edges, and we preserve these.
- // We have to do this carefully though because if the
- // constraints go through some other nodes not part of the
- // selection, this doesn't work right, and you might be
- // dragging several connected components, which we'd then
- // need to stitch together such that they are all visible.
-
- state.attachPrevious(previous, newChild);
- previous = newChild;
- }
- }
- }
- });
- }
-
- @Override
- public void onChildInserted(@NonNull INode node, @NonNull INode parent,
- @NonNull InsertType insertType) {
- // TODO: Handle more generically some way to ensure that widgets with no
- // intrinsic size get some minimum size until they are attached on multiple
- // opposing sides.
- //String fqcn = node.getFqcn();
- //if (fqcn.equals(FQCN_EDIT_TEXT)) {
- // node.setAttribute(ANDROID_URI, ATTR_LAYOUT_WIDTH, "100dp"); //$NON-NLS-1$
- //}
- }
-
- @Override
- public void onRemovingChildren(@NonNull List<INode> deleted, @NonNull INode parent,
- boolean moved) {
- super.onRemovingChildren(deleted, parent, moved);
-
- if (!moved) {
- DeletionHandler handler = new DeletionHandler(deleted, Collections.<INode>emptyList(),
- parent);
- handler.updateConstraints();
- }
- }
-
- // ==== Resize Support ====
-
- @Override
- public DropFeedback onResizeBegin(@NonNull INode child, @NonNull INode parent,
- @Nullable SegmentType horizontalEdgeType, @Nullable SegmentType verticalEdgeType,
- @Nullable Object childView, @Nullable Object parentView) {
- ResizeHandler state = new ResizeHandler(parent, child, mRulesEngine,
- horizontalEdgeType, verticalEdgeType);
- return new DropFeedback(state, new GuidelinePainter());
- }
-
- @Override
- public void onResizeUpdate(@Nullable DropFeedback feedback, @NonNull INode child,
- @NonNull INode parent, @NonNull Rect newBounds,
- int modifierMask) {
- if (feedback == null) {
- return;
- }
-
- ResizeHandler state = (ResizeHandler) feedback.userData;
- state.updateResize(feedback, child, newBounds, modifierMask);
- }
-
- @Override
- public void onResizeEnd(@Nullable DropFeedback feedback, @NonNull INode child,
- @NonNull INode parent, final @NonNull Rect newBounds) {
- if (feedback == null) {
- return;
- }
- final ResizeHandler state = (ResizeHandler) feedback.userData;
-
- child.editXml("Resize", new INodeHandler() {
- @Override
- public void handle(@NonNull INode n) {
- state.removeCycles();
- state.applyConstraints(n);
- }
- });
- }
-
- // ==== Layout Actions Bar ====
-
- @Override
- public void addLayoutActions(
- @NonNull List<RuleAction> actions,
- final @NonNull INode parentNode,
- final @NonNull List<? extends INode> children) {
- super.addLayoutActions(actions, parentNode, children);
-
- actions.add(createGravityAction(Collections.<INode>singletonList(parentNode),
- ATTR_GRAVITY));
- actions.add(RuleAction.createSeparator(25));
- actions.add(createMarginAction(parentNode, children));
-
- IMenuCallback callback = new IMenuCallback() {
- @Override
- public void action(@NonNull RuleAction action,
- @NonNull List<? extends INode> selectedNodes,
- final @Nullable String valueId,
- final @Nullable Boolean newValue) {
- final String id = action.getId();
- if (id.equals(ACTION_CENTER_VERTICAL)|| id.equals(ACTION_CENTER_HORIZONTAL)) {
- parentNode.editXml("Center", new INodeHandler() {
- @Override
- public void handle(@NonNull INode n) {
- if (id.equals(ACTION_CENTER_VERTICAL)) {
- for (INode child : children) {
- centerVertically(child);
- }
- } else if (id.equals(ACTION_CENTER_HORIZONTAL)) {
- for (INode child : children) {
- centerHorizontally(child);
- }
- }
- mRulesEngine.redraw();
- }
-
- });
- } else if (id.equals(ACTION_SHOW_CONSTRAINTS)) {
- sShowConstraints = !sShowConstraints;
- mRulesEngine.redraw();
- } else {
- assert id.equals(ACTION_SHOW_STRUCTURE);
- sShowStructure = !sShowStructure;
- mRulesEngine.redraw();
- }
- }
- };
-
- // Centering actions
- if (children != null && children.size() > 0) {
- actions.add(RuleAction.createSeparator(150));
- actions.add(RuleAction.createAction(ACTION_CENTER_VERTICAL, "Center Vertically",
- callback, ICON_CENTER_VERTICALLY, 160, false));
- actions.add(RuleAction.createAction(ACTION_CENTER_HORIZONTAL, "Center Horizontally",
- callback, ICON_CENTER_HORIZONTALLY, 170, false));
- }
-
- actions.add(RuleAction.createSeparator(80));
- actions.add(RuleAction.createToggle(ACTION_SHOW_CONSTRAINTS, "Show Constraints",
- sShowConstraints, callback, ICON_SHOW_CONSTRAINTS, 180, false));
- actions.add(RuleAction.createToggle(ACTION_SHOW_STRUCTURE, "Show All Relationships",
- sShowStructure, callback, ICON_SHOW_STRUCTURE, 190, false));
- }
-
- private void centerHorizontally(INode node) {
- // Clear horizontal-oriented attributes from the node
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_ALIGN_PARENT_LEFT, null);
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_ALIGN_LEFT, null);
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_TO_RIGHT_OF, null);
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_CENTER_HORIZONTAL, null);
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_ALIGN_PARENT_RIGHT, null);
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_ALIGN_RIGHT, null);
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_TO_LEFT_OF, null);
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_CENTER_HORIZONTAL, null);
-
- if (VALUE_TRUE.equals(node.getStringAttr(ANDROID_URI, ATTR_LAYOUT_CENTER_IN_PARENT))) {
- // Already done
- } else if (VALUE_TRUE.equals(node.getStringAttr(ANDROID_URI,
- ATTR_LAYOUT_CENTER_VERTICAL))) {
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_CENTER_VERTICAL, null);
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_CENTER_IN_PARENT, VALUE_TRUE);
- } else {
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_CENTER_HORIZONTAL, VALUE_TRUE);
- }
- }
-
- private void centerVertically(INode node) {
- // Clear vertical-oriented attributes from the node
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_ALIGN_PARENT_TOP, null);
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_ALIGN_TOP, null);
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_BELOW, null);
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_ALIGN_PARENT_BOTTOM, null);
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_ALIGN_BOTTOM, null);
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_ABOVE, null);
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_CENTER_VERTICAL, null);
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_ALIGN_BASELINE, null);
-
- // Center vertically
- if (VALUE_TRUE.equals(node.getStringAttr(ANDROID_URI, ATTR_LAYOUT_CENTER_IN_PARENT))) {
- // ALready done
- } else if (VALUE_TRUE.equals(node.getStringAttr(ANDROID_URI,
- ATTR_LAYOUT_CENTER_HORIZONTAL))) {
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_CENTER_HORIZONTAL, null);
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_CENTER_IN_PARENT, VALUE_TRUE);
- } else {
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_CENTER_VERTICAL, VALUE_TRUE);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ResizeState.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ResizeState.java
deleted file mode 100644
index 42b9083ad..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ResizeState.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.VALUE_N_DP;
-import static com.android.SdkConstants.VALUE_WRAP_CONTENT;
-
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.api.Segment;
-import com.android.ide.common.api.SegmentType;
-
-/** State held during resizing operations */
-class ResizeState {
- /**
- * The associated rule
- */
- private final BaseLayoutRule mRule;
-
- /**
- * The node being resized
- */
- public final INode node;
-
- /**
- * The layout containing the resized node
- */
- public final INode layout;
-
- /** The proposed resized bounds of the node */
- public Rect bounds;
-
- /** The preferred wrap_content bounds of the node */
- public Rect wrapBounds;
-
- /** The suggested horizontal fill_parent guideline position */
- public Segment horizontalFillSegment;
-
- /** The suggested vertical fill_parent guideline position */
- public Segment verticalFillSegment;
-
- /** The type of horizontal edge being resized, or null */
- public SegmentType horizontalEdgeType;
-
- /** The type of vertical edge being resized, or null */
- public SegmentType verticalEdgeType;
-
- /** Whether the user has snapped to the wrap_content width */
- public boolean wrapWidth;
-
- /** Whether the user has snapped to the wrap_content height */
- public boolean wrapHeight;
-
- /** Whether the user has snapped to the match_parent width */
- public boolean fillWidth;
-
- /** Whether the user has snapped to the match_parent height */
- public boolean fillHeight;
-
- /** Custom field for use by subclasses */
- public Object clientData;
-
- /** Keyboard mask */
- public int modifierMask;
-
- /**
- * The actual view object for the layout containing the resizing operation,
- * or null if not known
- */
- public Object layoutView;
-
- /**
- * Constructs a new {@link ResizeState}
- *
- * @param rule the associated rule
- * @param layout the parent layout containing the resized node
- * @param layoutView the actual View instance for the layout, or null if not known
- * @param node the node being resized
- */
- ResizeState(BaseLayoutRule rule, INode layout, Object layoutView, INode node) {
- mRule = rule;
-
- this.layout = layout;
- this.node = node;
- this.layoutView = layoutView;
- }
-
- /**
- * Returns the width attribute to be set to match the new bounds
- *
- * @return the width string, never null
- */
- public String getWidthAttribute() {
- if (wrapWidth) {
- return VALUE_WRAP_CONTENT;
- } else if (fillWidth) {
- return mRule.getFillParentValueName();
- } else {
- return String.format(VALUE_N_DP, mRule.mRulesEngine.pxToDp(bounds.w));
- }
- }
-
- /**
- * Returns the height attribute to be set to match the new bounds
- *
- * @return the height string, never null
- */
- public String getHeightAttribute() {
- if (wrapHeight) {
- return VALUE_WRAP_CONTENT;
- } else if (fillHeight) {
- return mRule.getFillParentValueName();
- } else {
- return String.format(VALUE_N_DP, mRule.mRulesEngine.pxToDp(bounds.h));
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ScrollViewRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ScrollViewRule.java
deleted file mode 100644
index 9f2b4ae6f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ScrollViewRule.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.ATTR_ORIENTATION;
-import static com.android.SdkConstants.FQCN_LINEAR_LAYOUT;
-import static com.android.SdkConstants.VALUE_VERTICAL;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.DrawingStyle;
-import com.android.ide.common.api.DropFeedback;
-import com.android.ide.common.api.IDragElement;
-import com.android.ide.common.api.IGraphics;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-import com.android.ide.common.api.Point;
-import com.android.ide.common.api.Rect;
-
-/**
- * An {@link IViewRule} for android.widget.ScrollView.
- */
-public class ScrollViewRule extends FrameLayoutRule {
-
- @Override
- public void onChildInserted(@NonNull INode child, @NonNull INode parent,
- @NonNull InsertType insertType) {
- super.onChildInserted(child, parent, insertType);
-
- // The child of the ScrollView should fill in both directions
- String fillParent = getFillParentValueName();
- child.setAttribute(ANDROID_URI, ATTR_LAYOUT_WIDTH, fillParent);
- child.setAttribute(ANDROID_URI, ATTR_LAYOUT_HEIGHT, fillParent);
- }
-
- @Override
- public void onCreate(@NonNull INode node, @NonNull INode parent,
- @NonNull InsertType insertType) {
- super.onCreate(node, parent, insertType);
-
- if (insertType.isCreate()) {
- // Insert a default linear layout (which will in turn be registered as
- // a child of this node and the create child method above will set its
- // fill parent attributes, its id, etc.
- INode linear = node.appendChild(FQCN_LINEAR_LAYOUT);
- linear.setAttribute(ANDROID_URI, ATTR_ORIENTATION, VALUE_VERTICAL);
- }
- }
-
- @Override
- public DropFeedback onDropMove(@NonNull INode targetNode, @NonNull IDragElement[] elements,
- @Nullable DropFeedback feedback, @NonNull Point p) {
- DropFeedback f = super.onDropMove(targetNode, elements, feedback, p);
-
- // ScrollViews only allow a single child
- if (targetNode.getChildren().length > 0) {
- f.invalidTarget = true;
- }
- return f;
- }
-
- @Override
- protected void drawFeedback(
- IGraphics gc,
- INode targetNode,
- IDragElement[] elements,
- DropFeedback feedback) {
- if (targetNode.getChildren().length > 0) {
- Rect b = targetNode.getBounds();
- if (b.isValid()) {
- gc.useStyle(DrawingStyle.DROP_RECIPIENT);
- gc.drawRect(b);
- }
- } else {
- super.drawFeedback(gc, targetNode, elements, feedback);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/SeekBarRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/SeekBarRule.java
deleted file mode 100644
index b88f8ab25..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/SeekBarRule.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-
-/**
- * An {@link IViewRule} for android.widget.SeekBar
- */
-public class SeekBarRule extends BaseViewRule {
-
- @Override
- public void onCreate(@NonNull INode node, @NonNull INode parent,
- @NonNull InsertType insertType) {
- super.onCreate(node, parent, insertType);
-
- // A SeekBar isn't useful with wrap_content because it packs itself down to
- // almost no usable width -- so just make it grow in all layouts
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_WIDTH, getFillParentValueName());
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/SlidingDrawerRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/SlidingDrawerRule.java
deleted file mode 100644
index e4267bb10..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/SlidingDrawerRule.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ATTR_CONTENT;
-import static com.android.SdkConstants.ATTR_HANDLE;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.ATTR_TEXT;
-
-
-import com.android.SdkConstants;
-import static com.android.SdkConstants.ANDROID_URI;
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-
-/**
- * An {@link IViewRule} for android.widget.SlidingDrawerRule which initializes new sliding
- * drawers with their mandatory children and default sizing attributes
- */
-public class SlidingDrawerRule extends BaseLayoutRule {
-
- @Override
- public void onCreate(@NonNull INode node, @NonNull INode parent,
- @NonNull InsertType insertType) {
- super.onCreate(node, parent, insertType);
-
- if (insertType.isCreate()) {
- String matchParent = getFillParentValueName();
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_WIDTH, matchParent);
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_HEIGHT, matchParent);
-
- // Create mandatory children and reference them from the handle and content
- // attributes of the sliding drawer
- String handleId = "@+id/handle"; //$NON-NLS-1$
- String contentId = "@+id/content"; //$NON-NLS-1$
- node.setAttribute(ANDROID_URI, ATTR_HANDLE, handleId);
- node.setAttribute(ANDROID_URI, ATTR_CONTENT, contentId);
-
- // Handle
- INode handle = node.appendChild(SdkConstants.FQCN_BUTTON);
- handle.setAttribute(ANDROID_URI, ATTR_TEXT, "Handle");
- handle.setAttribute(ANDROID_URI, ATTR_ID, handleId);
-
- // Content
- INode content = node.appendChild(SdkConstants.FQCN_LINEAR_LAYOUT);
- content.setAttribute(ANDROID_URI, ATTR_ID, contentId);
- content.setAttribute(ANDROID_URI, ATTR_LAYOUT_WIDTH, matchParent);
- content.setAttribute(ANDROID_URI, ATTR_LAYOUT_HEIGHT, matchParent);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/TabHostRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/TabHostRule.java
deleted file mode 100644
index cb2153b50..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/TabHostRule.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.ATTR_ORIENTATION;
-import static com.android.SdkConstants.FQCN_FRAME_LAYOUT;
-import static com.android.SdkConstants.FQCN_LINEAR_LAYOUT;
-import static com.android.SdkConstants.FQCN_TAB_WIDGET;
-import static com.android.SdkConstants.VALUE_VERTICAL;
-import static com.android.SdkConstants.VALUE_WRAP_CONTENT;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-
-/**
- * An {@link IViewRule} for android.widget.TabHost.
- */
-public class TabHostRule extends IgnoredLayoutRule {
- // The TabHost layout states in its documentation that you typically
- // manipulate its children via the TabHost rather than directly manipulating
- // the child elements yourself, e.g. via addTab() etc.
-
- @Override
- public void onCreate(@NonNull INode node, @NonNull INode parent,
- @NonNull InsertType insertType) {
- super.onCreate(node, parent, insertType);
-
- if (insertType.isCreate()) {
- String fillParent = getFillParentValueName();
-
- // Configure default Table setup as described in the Table tutorial
- node.setAttribute(ANDROID_URI, ATTR_ID, "@android:id/tabhost"); //$NON-NLS-1$
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_WIDTH, fillParent);
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_HEIGHT, fillParent);
-
- INode linear = node.appendChild(FQCN_LINEAR_LAYOUT);
- linear.setAttribute(ANDROID_URI, ATTR_LAYOUT_WIDTH, fillParent);
- linear.setAttribute(ANDROID_URI, ATTR_LAYOUT_HEIGHT, fillParent);
- linear.setAttribute(ANDROID_URI, ATTR_ORIENTATION,
- VALUE_VERTICAL);
-
- INode tab = linear.appendChild(FQCN_TAB_WIDGET);
- tab.setAttribute(ANDROID_URI, ATTR_LAYOUT_WIDTH, fillParent);
- tab.setAttribute(ANDROID_URI, ATTR_LAYOUT_HEIGHT, VALUE_WRAP_CONTENT);
- tab.setAttribute(ANDROID_URI, ATTR_ID, "@android:id/tabs"); //$NON-NLS-1$
-
- INode frame = linear.appendChild(FQCN_FRAME_LAYOUT);
- frame.setAttribute(ANDROID_URI, ATTR_LAYOUT_WIDTH, fillParent);
- frame.setAttribute(ANDROID_URI, ATTR_LAYOUT_HEIGHT, fillParent);
- frame.setAttribute(ANDROID_URI, ATTR_ID, "@android:id/tabcontent"); //$NON-NLS-1$
-
- for (int i = 0; i < 3; i++) {
- INode child = frame.appendChild(FQCN_LINEAR_LAYOUT);
- child.setAttribute(ANDROID_URI, ATTR_LAYOUT_WIDTH, fillParent);
- child.setAttribute(ANDROID_URI, ATTR_LAYOUT_HEIGHT, fillParent);
- child.setAttribute(ANDROID_URI, ATTR_ID,
- String.format("@+id/tab%d", i + 1)); //$NON-NLS-1$
- }
- }
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/TabWidgetRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/TabWidgetRule.java
deleted file mode 100755
index 7ebaea54d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/TabWidgetRule.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import com.android.ide.common.api.IViewRule;
-
-/**
- * An {@link IViewRule} for android.widget.TabWidget.
- */
-public class TabWidgetRule extends IgnoredLayoutRule {
- // TabWidgets aren't configurable as plain LinearLayout since they
- // are supposed to be manipulated by their parent TabHost.
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/TableLayoutRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/TableLayoutRule.java
deleted file mode 100644
index b6aeeb486..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/TableLayoutRule.java
+++ /dev/null
@@ -1,218 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.FQCN_TABLE_ROW;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.DropFeedback;
-import com.android.ide.common.api.IClientRulesEngine;
-import com.android.ide.common.api.IMenuCallback;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.INodeHandler;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-import com.android.ide.common.api.RuleAction;
-import com.android.ide.common.api.SegmentType;
-
-import java.net.URL;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * An {@link IViewRule} for android.widget.TableLayout.
- */
-public class TableLayoutRule extends LinearLayoutRule {
- // A table is a linear layout, but with a few differences:
- // the default is vertical, not horizontal
- // The fill of all children should be wrap_content
-
- private static final String ACTION_ADD_ROW = "_addrow"; //$NON-NLS-1$
- private static final String ACTION_REMOVE_ROW = "_removerow"; //$NON-NLS-1$
- private static final URL ICON_ADD_ROW =
- TableLayoutRule.class.getResource("addrow.png"); //$NON-NLS-1$
- private static final URL ICON_REMOVE_ROW =
- TableLayoutRule.class.getResource("removerow.png"); //$NON-NLS-1$
-
- @Override
- protected boolean isVertical(INode node) {
- // Tables are always vertical
- return true;
- }
-
- @Override
- protected boolean supportsOrientation() {
- return false;
- }
-
- @Override
- public void onChildInserted(@NonNull INode child, @NonNull INode parent,
- @NonNull InsertType insertType) {
- // Overridden to inhibit the setting of layout_width/layout_height since
- // it should always be match_parent
- }
-
- /**
- * Add an explicit "Add Row" action to the context menu
- */
- @Override
- public void addContextMenuActions(@NonNull List<RuleAction> actions,
- final @NonNull INode selectedNode) {
- super.addContextMenuActions(actions, selectedNode);
-
- IMenuCallback addTab = new IMenuCallback() {
- @Override
- public void action(
- @NonNull RuleAction action,
- @NonNull List<? extends INode> selectedNodes,
- final @Nullable String valueId,
- @Nullable Boolean newValue) {
- final INode node = selectedNode;
- INode newRow = node.appendChild(FQCN_TABLE_ROW);
- mRulesEngine.select(Collections.singletonList(newRow));
- }
- };
- actions.add(RuleAction.createAction("_addrow", "Add Row", addTab, null, 5, false)); //$NON-NLS-1$
- }
-
- @Override
- public void addLayoutActions(
- @NonNull List<RuleAction> actions,
- final @NonNull INode parentNode,
- final @NonNull List<? extends INode> children) {
- super.addLayoutActions(actions, parentNode, children);
- addTableLayoutActions(mRulesEngine, actions, parentNode, children);
- }
-
- /**
- * Adds layout actions to add and remove toolbar items
- */
- static void addTableLayoutActions(final IClientRulesEngine rulesEngine,
- List<RuleAction> actions, final INode parentNode,
- final List<? extends INode> children) {
- IMenuCallback actionCallback = new IMenuCallback() {
- @Override
- public void action(
- final @NonNull RuleAction action,
- @NonNull List<? extends INode> selectedNodes,
- final @Nullable String valueId,
- final @Nullable Boolean newValue) {
- parentNode.editXml("Add/Remove Table Row", new INodeHandler() {
- @Override
- public void handle(@NonNull INode n) {
- if (action.getId().equals(ACTION_ADD_ROW)) {
- // Determine the index of the selection, if any; if there is
- // a selection, insert the row before the current row, otherwise
- // append it to the table.
- int index = -1;
- INode[] rows = parentNode.getChildren();
- if (children != null) {
- findTableIndex:
- for (INode child : children) {
- // Find direct child of table layout
- while (child != null && child.getParent() != parentNode) {
- child = child.getParent();
- }
- if (child != null) {
- // Compute index of direct child of table layout
- for (int i = 0; i < rows.length; i++) {
- if (rows[i] == child) {
- index = i;
- break findTableIndex;
- }
- }
- }
- }
- }
- INode newRow;
- if (index == -1) {
- newRow = parentNode.appendChild(FQCN_TABLE_ROW);
- } else {
- newRow = parentNode.insertChildAt(FQCN_TABLE_ROW, index);
- }
- rulesEngine.select(Collections.singletonList(newRow));
- } else if (action.getId().equals(ACTION_REMOVE_ROW)) {
- // Find the direct children of the TableLayout to delete;
- // this is necessary since TableRow might also use
- // this implementation, so the parentNode is the true
- // TableLayout but the children might be grand children.
- Set<INode> targets = new HashSet<INode>();
- for (INode child : children) {
- while (child != null && child.getParent() != parentNode) {
- child = child.getParent();
- }
- if (child != null) {
- targets.add(child);
- }
- }
- for (INode target : targets) {
- parentNode.removeChild(target);
- }
- }
- }
- });
- }
- };
-
- // Add Row
- actions.add(RuleAction.createSeparator(150));
- actions.add(RuleAction.createAction(ACTION_ADD_ROW, "Add Table Row", actionCallback,
- ICON_ADD_ROW, 160, false));
-
- // Remove Row (if something is selected)
- if (children != null && children.size() > 0) {
- actions.add(RuleAction.createAction(ACTION_REMOVE_ROW, "Remove Table Row",
- actionCallback, ICON_REMOVE_ROW, 170, false));
- }
- }
-
- @Override
- public void onCreate(@NonNull INode node, @NonNull INode parent,
- @NonNull InsertType insertType) {
- super.onCreate(node, parent, insertType);
-
- if (insertType.isCreate()) {
- // Start the table with 4 rows
- for (int i = 0; i < 4; i++) {
- node.appendChild(FQCN_TABLE_ROW);
- }
- }
- }
-
- @Override
- public DropFeedback onResizeBegin(@NonNull INode child, @NonNull INode parent,
- @Nullable SegmentType horizontalEdge, @Nullable SegmentType verticalEdge,
- @Nullable Object childView, @Nullable Object parentView) {
- // Children of a table layout cannot set their widths (it is controlled by column
- // settings on the table). They can set their heights (though for TableRow, the
- // height is always wrap_content).
- if (horizontalEdge == null) { // Widths are edited by vertical edges.
- // The user is not editing a vertical height so don't allow resizing at all
- return null;
- }
- if (child.getFqcn().equals(FQCN_TABLE_ROW)) {
- // TableRows are always WRAP_CONTENT
- return null;
- }
-
- // Allow resizing heights only
- return super.onResizeBegin(child, parent, horizontalEdge, null /*verticalEdge*/,
- childView, parentView);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/TableRowRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/TableRowRule.java
deleted file mode 100644
index 6e3f202ee..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/TableRowRule.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.FQCN_TABLE_LAYOUT;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.DropFeedback;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-import com.android.ide.common.api.RuleAction;
-import com.android.ide.common.api.SegmentType;
-
-import java.util.List;
-
-/**
- * An {@link IViewRule} for android.widget.TableRow.
- */
-public class TableRowRule extends LinearLayoutRule {
- @Override
- protected boolean isVertical(INode node) {
- return false;
- }
-
- @Override
- protected boolean supportsOrientation() {
- return false;
- }
-
- @Override
- public void onChildInserted(@NonNull INode child, @NonNull INode parent,
- @NonNull InsertType insertType) {
- // Overridden to inhibit the setting of layout_width/layout_height since
- // the table row will enforce match_parent and wrap_content for width and height
- // respectively.
- }
-
- @Override
- public void addLayoutActions(
- @NonNull List<RuleAction> actions,
- final @NonNull INode parentNode,
- final @NonNull List<? extends INode> children) {
- super.addLayoutActions(actions, parentNode, children);
-
- // Also apply table-specific actions on the table row such that you can
- // select something in a table row and still get offered actions on the surrounding
- // table.
- if (children != null) {
- INode grandParent = parentNode.getParent();
- if (grandParent != null && grandParent.getFqcn().equals(FQCN_TABLE_LAYOUT)) {
- TableLayoutRule.addTableLayoutActions(mRulesEngine, actions, grandParent,
- children);
- }
- }
- }
-
- @Override
- public DropFeedback onResizeBegin(@NonNull INode child, @NonNull INode parent,
- @Nullable SegmentType horizontalEdge, @Nullable SegmentType verticalEdge,
- @Nullable Object childView, @Nullable Object parentView) {
- // No resizing in TableRows; the width is *always* match_parent and the height is
- // *always* wrap_content.
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/TimePickerRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/TimePickerRule.java
deleted file mode 100755
index 1eb603d43..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/TimePickerRule.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import com.android.ide.common.api.IViewRule;
-
-/**
- * An {@link IViewRule} for android.widget.TimePicker.
- */
-public class TimePickerRule extends IgnoredLayoutRule {
- // A TimePicker inherits from FrameLayout but is not a general purpose
- // FrameLayout
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ViewRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ViewRule.java
deleted file mode 100755
index a7b23ab75..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ViewRule.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import com.android.ide.common.api.IViewRule;
-
-/**
- * An {@link IViewRule} for android.view.View and all its derived classes. This
- * is the "root" rule, that is used whenever there is not more specific rule to
- * apply.
- * <p/>
- * There is no customization here, everything that is common to all views is
- * simply implemented in BaseViewRule.
- */
-public class ViewRule extends BaseViewRule {
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ViewTagRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ViewTagRule.java
deleted file mode 100644
index a89a3d851..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ViewTagRule.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ATTR_CLASS;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-
-/**
- * An {@link IViewRule} for the special XML {@code <view>} tag.
- */
-public class ViewTagRule extends BaseViewRule {
- @Override
- public void onCreate(@NonNull INode node, @NonNull INode parent,
- @NonNull InsertType insertType) {
- // When dropping a view tag, ask the user which custom view class to use
- if (insertType == InsertType.CREATE) { // NOT InsertType.CREATE_PREVIEW
- String fqcn = mRulesEngine.displayCustomViewClassInput();
- if (fqcn != null) {
- if (!ViewElementDescriptor.viewNeedsPackage(fqcn)) {
- fqcn = fqcn.substring(fqcn.lastIndexOf('.') + 1);
- }
- node.editXml("Set Custom View Class",
- new PropertySettingNodeHandler(null, ATTR_CLASS,
- fqcn.length() > 0 ? fqcn : null));
- } else {
- // Remove the view; the insertion was canceled
- parent.removeChild(node);
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/WebViewRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/WebViewRule.java
deleted file mode 100644
index 42b06e65b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/WebViewRule.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-
-/**
- * An {@link IViewRule} for android.widget.ZoomControls.
- */
-public class WebViewRule extends IgnoredLayoutRule {
- // A WebView is not a general purpose AbsoluteLayout you should drop stuff
- // into; it's an AbsoluteLayout for implementation purposes.
-
- @Override
- public void onCreate(@NonNull INode node, @NonNull INode parent,
- @NonNull InsertType insertType) {
- super.onCreate(node, parent, insertType);
-
- if (insertType.isCreate()) {
- String matchParent = getFillParentValueName();
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_WIDTH, matchParent);
- node.setAttribute(ANDROID_URI, ATTR_LAYOUT_HEIGHT, matchParent);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ZoomButtonRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ZoomButtonRule.java
deleted file mode 100644
index 66cbd45f0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ZoomButtonRule.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_SRC;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.InsertType;
-
-public class ZoomButtonRule extends BaseViewRule {
- @Override
- public void onCreate(@NonNull INode node, @NonNull INode parent,
- @NonNull InsertType insertType) {
- super.onCreate(node, parent, insertType);
-
- if (insertType.isCreate()) {
- node.setAttribute(ANDROID_URI, ATTR_SRC, "@android:drawable/btn_plus"); //$NON-NLS-1$
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ZoomControlsRule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ZoomControlsRule.java
deleted file mode 100755
index 226bf4eb5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/ZoomControlsRule.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import com.android.ide.common.api.IViewRule;
-
-/**
- * An {@link IViewRule} for android.widget.ZoomControls.
- */
-public class ZoomControlsRule extends IgnoredLayoutRule {
- // A ZoomControl is only a LinearLayout in terms of borrowing
- // implementation; it does not behave like one in terms of configurability.
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/addcol.png b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/addcol.png
deleted file mode 100644
index 21391ef53..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/addcol.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/addrow.png b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/addrow.png
deleted file mode 100644
index 0faa3e607..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/addrow.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/allweight.png b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/allweight.png
deleted file mode 100644
index 506c66320..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/allweight.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/baseline.png b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/baseline.png
deleted file mode 100644
index acb187ca0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/baseline.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/centerHorizontally.png b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/centerHorizontally.png
deleted file mode 100644
index 5053cdadd..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/centerHorizontally.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/centerVertically.png b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/centerVertically.png
deleted file mode 100644
index ebba8e812..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/centerVertically.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/clearweights.png b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/clearweights.png
deleted file mode 100644
index ad27c174d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/clearweights.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/constraints.png b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/constraints.png
deleted file mode 100644
index 7247d5a09..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/constraints.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/distribute.png b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/distribute.png
deleted file mode 100644
index eac2340f9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/distribute.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/fillheight.png b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/fillheight.png
deleted file mode 100644
index 38e137deb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/fillheight.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/fillwidth.png b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/fillwidth.png
deleted file mode 100644
index f272aab68..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/fillwidth.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/gravity.png b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/gravity.png
deleted file mode 100644
index 4f20928ad..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/gravity.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/grid/GridDropHandler.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/grid/GridDropHandler.java
deleted file mode 100644
index 8bdb56bfe..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/grid/GridDropHandler.java
+++ /dev/null
@@ -1,840 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout.grid;
-
-import static com.android.SdkConstants.ATTR_COLUMN_COUNT;
-import static com.android.SdkConstants.ATTR_LAYOUT_COLUMN;
-import static com.android.SdkConstants.ATTR_LAYOUT_COLUMN_SPAN;
-import static com.android.SdkConstants.ATTR_LAYOUT_GRAVITY;
-import static com.android.SdkConstants.ATTR_LAYOUT_ROW;
-import static com.android.SdkConstants.ATTR_LAYOUT_ROW_SPAN;
-import static com.android.ide.common.layout.GravityHelper.getGravity;
-import static com.android.ide.common.layout.GridLayoutRule.GRID_SIZE;
-import static com.android.ide.common.layout.GridLayoutRule.MARGIN_SIZE;
-import static com.android.ide.common.layout.GridLayoutRule.MAX_CELL_DIFFERENCE;
-import static com.android.ide.common.layout.GridLayoutRule.SHORT_GAP_DP;
-import static com.android.ide.common.layout.grid.GridModel.UNDEFINED;
-import static java.lang.Math.abs;
-
-import com.android.ide.common.api.DropFeedback;
-import com.android.ide.common.api.IDragElement;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IViewMetadata;
-import com.android.ide.common.api.Margins;
-import com.android.ide.common.api.Point;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.api.SegmentType;
-import com.android.ide.common.layout.BaseLayoutRule;
-import com.android.ide.common.layout.GravityHelper;
-import com.android.ide.common.layout.GridLayoutRule;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.ViewMetadataRepository;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Locale;
-
-/**
- * The {@link GridDropHandler} handles drag and drop operations into and within a
- * GridLayout, computing guidelines, handling drops to edit the grid model, and so on.
- */
-public class GridDropHandler {
- private final GridModel mGrid;
- private final GridLayoutRule mRule;
- private GridMatch mColumnMatch;
- private GridMatch mRowMatch;
-
- /**
- * Creates a new {@link GridDropHandler} for
- * @param gridLayoutRule the corresponding {@link GridLayoutRule}
- * @param layout the GridLayout node
- * @param view the view instance of the grid layout receiving the drop
- */
- public GridDropHandler(GridLayoutRule gridLayoutRule, INode layout, Object view) {
- mRule = gridLayoutRule;
- mGrid = GridModel.get(mRule.getRulesEngine(), layout, view);
- }
-
- /**
- * Computes the best horizontal and vertical matches for a drag to the given position.
- *
- * @param feedback a {@link DropFeedback} object containing drag state like the drag
- * bounds and the drag baseline
- * @param p the mouse position
- */
- public void computeMatches(DropFeedback feedback, Point p) {
- mRowMatch = mColumnMatch = null;
- feedback.tooltip = null;
-
- Rect bounds = mGrid.layout.getBounds();
- int x1 = p.x;
- int y1 = p.y;
-
- Rect dragBounds = feedback.dragBounds;
- int w = dragBounds != null ? dragBounds.w : 0;
- int h = dragBounds != null ? dragBounds.h : 0;
- if (!GridLayoutRule.sGridMode) {
- if (dragBounds != null) {
- // Sometimes the items are centered under the mouse so
- // offset by the top left corner distance
- x1 += dragBounds.x;
- y1 += dragBounds.y;
- }
-
- int x2 = x1 + w;
- int y2 = y1 + h;
-
- if (x2 < bounds.x || y2 < bounds.y || x1 > bounds.x2() || y1 > bounds.y2()) {
- return;
- }
-
- List<GridMatch> columnMatches = new ArrayList<GridMatch>();
- List<GridMatch> rowMatches = new ArrayList<GridMatch>();
- int max = BaseLayoutRule.getMaxMatchDistance();
-
- // Column matches:
- addLeftSideMatch(x1, columnMatches, max);
- addRightSideMatch(x2, columnMatches, max);
- addCenterColumnMatch(bounds, x1, y1, x2, y2, columnMatches, max);
-
- // Row matches:
- int row = (mGrid.getViewCount() == 0) ? 0 : mGrid.getClosestRow(y1);
- int rowY = mGrid.getRowY(row);
- addTopMatch(y1, rowMatches, max, row, rowY);
- addBaselineMatch(feedback.dragBaseline, y1, rowMatches, max, row, rowY);
- addBottomMatch(y2, rowMatches, max);
-
- // Look for gap-matches: Predefined spacing between widgets.
- // TODO: Make this use metadata for predefined spacing between
- // pairs of types of components. For example, buttons have certain
- // inserts in their 9-patch files (depending on the theme) that should
- // be considered and subtracted from the overall proposed distance!
- addColumnGapMatch(bounds, x1, x2, columnMatches, max);
- addRowGapMatch(bounds, y1, y2, rowMatches, max);
-
- // Fallback: Split existing cell. Also do snap-to-grid.
- if (GridLayoutRule.sSnapToGrid) {
- x1 = ((x1 - MARGIN_SIZE - bounds.x) / GRID_SIZE) * GRID_SIZE
- + MARGIN_SIZE + bounds.x;
- y1 = ((y1 - MARGIN_SIZE - bounds.y) / GRID_SIZE) * GRID_SIZE
- + MARGIN_SIZE + bounds.y;
- x2 = x1 + w;
- y2 = y1 + h;
- }
-
-
- if (columnMatches.size() == 0 && x1 >= bounds.x) {
- // Split the current cell since we have no matches
- // TODO: Decide whether it should be gravity left or right...
- columnMatches.add(new GridMatch(SegmentType.LEFT, 0, x1, mGrid.getColumn(x1),
- true /* createCell */, UNDEFINED));
- }
- if (rowMatches.size() == 0 && y1 >= bounds.y) {
- rowMatches.add(new GridMatch(SegmentType.TOP, 0, y1, mGrid.getRow(y1),
- true /* createCell */, UNDEFINED));
- }
-
- // Pick best matches
- Collections.sort(rowMatches);
- Collections.sort(columnMatches);
-
- mColumnMatch = null;
- mRowMatch = null;
- String columnDescription = null;
- String rowDescription = null;
- if (columnMatches.size() > 0) {
- mColumnMatch = columnMatches.get(0);
- columnDescription = mColumnMatch.getDisplayName(mGrid.layout);
- }
- if (rowMatches.size() > 0) {
- mRowMatch = rowMatches.get(0);
- rowDescription = mRowMatch.getDisplayName(mGrid.layout);
- }
-
- if (columnDescription != null && rowDescription != null) {
- feedback.tooltip = columnDescription + '\n' + rowDescription;
- }
-
- feedback.invalidTarget = mColumnMatch == null || mRowMatch == null;
- } else {
- // Find which cell we're inside.
-
- // TODO: Find out where within the cell we are, and offer to tweak the gravity
- // based on the position.
- int column = mGrid.getColumn(x1);
- int row = mGrid.getRow(y1);
-
- int leftDistance = mGrid.getColumnDistance(column, x1);
- int rightDistance = mGrid.getColumnDistance(column + 1, x1);
- int topDistance = mGrid.getRowDistance(row, y1);
- int bottomDistance = mGrid.getRowDistance(row + 1, y1);
-
- int SLOP = 2;
- int radius = mRule.getNewCellSize();
- if (rightDistance < radius + SLOP) {
- column = Math.min(column + 1, mGrid.actualColumnCount);
- leftDistance = rightDistance;
- }
- if (bottomDistance < radius + SLOP) {
- row = Math.min(row + 1, mGrid.actualRowCount);
- topDistance = bottomDistance;
- }
-
- boolean createColumn = leftDistance < radius + SLOP;
- boolean createRow = topDistance < radius + SLOP;
- if (x1 >= bounds.x2()) {
- createColumn = true;
- }
- if (y1 >= bounds.y2()) {
- createRow = true;
- }
-
- int cellWidth = leftDistance + rightDistance;
- int cellHeight = topDistance + bottomDistance;
- SegmentType horizontalType = SegmentType.LEFT;
- SegmentType verticalType = SegmentType.TOP;
- int minDistance = 10; // Don't center or right/bottom align in tiny cells
- if (!createColumn && leftDistance > minDistance
- && dragBounds != null && dragBounds.w < cellWidth - 10) {
- if (rightDistance < leftDistance) {
- horizontalType = SegmentType.RIGHT;
- }
-
- int centerDistance = Math.abs(cellWidth / 2 - leftDistance);
- if (centerDistance < leftDistance / 2 && centerDistance < rightDistance / 2) {
- horizontalType = SegmentType.CENTER_HORIZONTAL;
- }
- }
- if (!createRow && topDistance > minDistance
- && dragBounds != null && dragBounds.h < cellHeight - 10) {
- if (bottomDistance < topDistance) {
- verticalType = SegmentType.BOTTOM;
- }
- int centerDistance = Math.abs(cellHeight / 2 - topDistance);
- if (centerDistance < topDistance / 2 && centerDistance < bottomDistance / 2) {
- verticalType = SegmentType.CENTER_VERTICAL;
- }
- }
-
- mColumnMatch = new GridMatch(horizontalType, 0, x1, column, createColumn, 0);
- mRowMatch = new GridMatch(verticalType, 0, y1, row, createRow, 0);
-
- StringBuilder description = new StringBuilder(50);
- String rowString = Integer.toString(mColumnMatch.cellIndex + 1);
- String columnString = Integer.toString(mRowMatch.cellIndex + 1);
- if (mRowMatch.createCell && mRowMatch.cellIndex < mGrid.actualRowCount) {
- description.append(String.format("Shift row %1$d down", mRowMatch.cellIndex + 1));
- description.append('\n');
- }
- if (mColumnMatch.createCell && mColumnMatch.cellIndex < mGrid.actualColumnCount) {
- description.append(String.format("Shift column %1$d right",
- mColumnMatch.cellIndex + 1));
- description.append('\n');
- }
- description.append(String.format("Insert into cell (%1$s,%2$s)",
- rowString, columnString));
- description.append('\n');
- description.append(String.format("Align %1$s, %2$s",
- horizontalType.name().toLowerCase(Locale.US),
- verticalType.name().toLowerCase(Locale.US)));
- feedback.tooltip = description.toString();
- }
- }
-
- /**
- * Adds a match to align the left edge with some other edge.
- */
- private void addLeftSideMatch(int x1, List<GridMatch> columnMatches, int max) {
- int column = (mGrid.getViewCount() == 0) ? 0 : mGrid.getClosestColumn(x1);
- int columnX = mGrid.getColumnX(column);
- int distance = abs(columnX - x1);
- if (distance <= max) {
- columnMatches.add(new GridMatch(SegmentType.LEFT, distance, columnX, column,
- false, UNDEFINED));
- }
- }
-
- /**
- * Adds a match to align the right edge with some other edge.
- */
- private void addRightSideMatch(int x2, List<GridMatch> columnMatches, int max) {
- // TODO: Only match the right hand side if the drag bounds fit fully within the
- // cell! Ditto for match below.
- int columnRight = (mGrid.getViewCount() == 0) ? 0 : mGrid.getClosestColumn(x2);
- int rightDistance = mGrid.getColumnDistance(columnRight, x2);
- if (rightDistance < max) {
- int columnX = mGrid.getColumnX(columnRight);
- if (columnX > mGrid.layout.getBounds().x) {
- columnMatches.add(new GridMatch(SegmentType.RIGHT, rightDistance, columnX,
- columnRight, false, UNDEFINED));
- }
- }
- }
-
- /**
- * Adds a horizontal match with the center axis of the GridLayout
- */
- private void addCenterColumnMatch(Rect bounds, int x1, int y1, int x2, int y2,
- List<GridMatch> columnMatches, int max) {
- Collection<INode> intersectsRow = mGrid.getIntersectsRow(y1, y2);
- if (intersectsRow.size() == 0) {
- // Offer centering on this row since there isn't anything there
- int matchedLine = bounds.centerX();
- int distance = abs((x1 + x2) / 2 - matchedLine);
- if (distance <= 2 * max) {
- boolean createCell = false; // always just put in column 0
- columnMatches.add(new GridMatch(SegmentType.CENTER_HORIZONTAL, distance,
- matchedLine, 0 /* column */, createCell, UNDEFINED));
- }
- }
- }
-
- /**
- * Adds a match to align the top edge with some other edge.
- */
- private void addTopMatch(int y1, List<GridMatch> rowMatches, int max, int row, int rowY) {
- int distance = mGrid.getRowDistance(row, y1);
- if (distance <= max) {
- rowMatches.add(new GridMatch(SegmentType.TOP, distance, rowY, row, false,
- UNDEFINED));
- }
- }
-
- /**
- * Adds a match to align the bottom edge with some other edge.
- */
- private void addBottomMatch(int y2, List<GridMatch> rowMatches, int max) {
- int rowBottom = (mGrid.getViewCount() == 0) ? 0 : mGrid.getClosestRow(y2);
- int distance = mGrid.getRowDistance(rowBottom, y2);
- if (distance < max) {
- int rowY = mGrid.getRowY(rowBottom);
- if (rowY > mGrid.layout.getBounds().y) {
- rowMatches.add(new GridMatch(SegmentType.BOTTOM, distance, rowY,
- rowBottom, false, UNDEFINED));
- }
- }
- }
-
- /**
- * Adds a baseline match, if applicable.
- */
- private void addBaselineMatch(int dragBaseline, int y1, List<GridMatch> rowMatches, int max,
- int row, int rowY) {
- int dragBaselineY = y1 + dragBaseline;
- int rowBaseline = mGrid.getBaseline(row);
- if (rowBaseline != -1) {
- int rowBaselineY = rowY + rowBaseline;
- int distance = abs(dragBaselineY - rowBaselineY);
- if (distance < max) {
- rowMatches.add(new GridMatch(SegmentType.BASELINE, distance, rowBaselineY, row,
- false, UNDEFINED));
- }
- }
- }
-
- /**
- * Computes a horizontal "gap" match - a preferred distance from the nearest edge,
- * including margin edges
- */
- private void addColumnGapMatch(Rect bounds, int x1, int x2, List<GridMatch> columnMatches,
- int max) {
- if (x1 < bounds.x + MARGIN_SIZE + max) {
- int matchedLine = bounds.x + MARGIN_SIZE;
- int distance = abs(matchedLine - x1);
- if (distance <= max) {
- boolean createCell = mGrid.getColumnX(mGrid.getColumn(matchedLine)) != matchedLine;
- columnMatches.add(new GridMatch(SegmentType.LEFT, distance, matchedLine,
- 0, createCell, MARGIN_SIZE));
- }
- } else if (x2 > bounds.x2() - MARGIN_SIZE - max) {
- int matchedLine = bounds.x2() - MARGIN_SIZE;
- int distance = abs(matchedLine - x2);
- if (distance <= max) {
- // This does not yet work properly; we need to use columnWeights to achieve this
- //boolean createCell = mGrid.getColumnX(mGrid.getColumn(matchedLine)) != matchedLine;
- //columnMatches.add(new GridMatch(SegmentType.RIGHT, distance, matchedLine,
- // mGrid.actualColumnCount - 1, createCell, MARGIN_SIZE));
- }
- } else {
- int columnRight = mGrid.getColumn(x1 - SHORT_GAP_DP);
- int columnX = mGrid.getColumnMaxX(columnRight);
- int matchedLine = columnX + SHORT_GAP_DP;
- int distance = abs(matchedLine - x1);
- if (distance <= max) {
- boolean createCell = mGrid.getColumnX(mGrid.getColumn(matchedLine)) != matchedLine;
- columnMatches.add(new GridMatch(SegmentType.LEFT, distance, matchedLine,
- columnRight, createCell, SHORT_GAP_DP));
- }
-
- // Add a column directly adjacent (no gap)
- columnRight = mGrid.getColumn(x1);
- columnX = mGrid.getColumnMaxX(columnRight);
- matchedLine = columnX;
- distance = abs(matchedLine - x1);
-
- // Let's say you have this arrangement:
- // [button1][button2]
- // This is two columns, where the right hand side edge of column 1 is
- // flush with the left side edge of column 2, because in fact the width of
- // button1 is what defines the width of column 1, and that in turn is what
- // defines the left side position of column 2.
- //
- // In this case we don't want to consider inserting a new column at the
- // right hand side of button1 a better match than matching left on column 2.
- // Therefore, to ensure that this doesn't happen, we "penalize" right column
- // matches such that they don't get preferential treatment when the matching
- // line is on the left side of the column.
- distance += 2;
-
- if (distance <= max) {
- boolean createCell = mGrid.getColumnX(mGrid.getColumn(matchedLine)) != matchedLine;
- columnMatches.add(new GridMatch(SegmentType.LEFT, distance, matchedLine,
- columnRight, createCell, 0));
- }
- }
- }
-
- /**
- * Computes a vertical "gap" match - a preferred distance from the nearest edge,
- * including margin edges
- */
- private void addRowGapMatch(Rect bounds, int y1, int y2, List<GridMatch> rowMatches, int max) {
- if (y1 < bounds.y + MARGIN_SIZE + max) {
- int matchedLine = bounds.y + MARGIN_SIZE;
- int distance = abs(matchedLine - y1);
- if (distance <= max) {
- boolean createCell = mGrid.getRowY(mGrid.getRow(matchedLine)) != matchedLine;
- rowMatches.add(new GridMatch(SegmentType.TOP, distance, matchedLine,
- 0, createCell, MARGIN_SIZE));
- }
- } else if (y2 > bounds.y2() - MARGIN_SIZE - max) {
- int matchedLine = bounds.y2() - MARGIN_SIZE;
- int distance = abs(matchedLine - y2);
- if (distance <= max) {
- // This does not yet work properly; we need to use columnWeights to achieve this
- //boolean createCell = mGrid.getRowY(mGrid.getRow(matchedLine)) != matchedLine;
- //rowMatches.add(new GridMatch(SegmentType.BOTTOM, distance, matchedLine,
- // mGrid.actualRowCount - 1, createCell, MARGIN_SIZE));
- }
- } else {
- int rowBottom = mGrid.getRow(y1 - SHORT_GAP_DP);
- int rowY = mGrid.getRowMaxY(rowBottom);
- int matchedLine = rowY + SHORT_GAP_DP;
- int distance = abs(matchedLine - y1);
- if (distance <= max) {
- boolean createCell = mGrid.getRowY(mGrid.getRow(matchedLine)) != matchedLine;
- rowMatches.add(new GridMatch(SegmentType.TOP, distance, matchedLine,
- rowBottom, createCell, SHORT_GAP_DP));
- }
-
- // Add a row directly adjacent (no gap)
- rowBottom = mGrid.getRow(y1);
- rowY = mGrid.getRowMaxY(rowBottom);
- matchedLine = rowY;
- distance = abs(matchedLine - y1);
- distance += 2; // See explanation in addColumnGapMatch
- if (distance <= max) {
- boolean createCell = mGrid.getRowY(mGrid.getRow(matchedLine)) != matchedLine;
- rowMatches.add(new GridMatch(SegmentType.TOP, distance, matchedLine,
- rowBottom, createCell, 0));
- }
-
- }
- }
-
- /**
- * Called when a node is dropped in free-form mode. This will insert the dragged
- * element into the grid and returns the newly created node.
- *
- * @param targetNode the GridLayout node
- * @param element the dragged element
- * @return the newly created {@link INode}
- */
- public INode handleFreeFormDrop(INode targetNode, IDragElement element) {
- assert mRowMatch != null;
- assert mColumnMatch != null;
-
- String fqcn = element.getFqcn();
-
- INode newChild = null;
-
- Rect bounds = element.getBounds();
- int row = mRowMatch.cellIndex;
- int column = mColumnMatch.cellIndex;
-
- if (targetNode.getChildren().length == 0) {
- //
- // Set up the initial structure:
- //
- //
- // Fixed Fixed
- // Size Size
- // Column Expanding Column Column
- // +-----+-------------------------------+-----+
- // | | | |
- // | 0,0 | 0,1 | 0,2 | Fixed Size Row
- // | | | |
- // +-----+-------------------------------+-----+
- // | | | |
- // | | | |
- // | | | |
- // | 1,0 | 1,1 | 1,2 | Expanding Row
- // | | | |
- // | | | |
- // | | | |
- // +-----+-------------------------------+-----+
- // | | | |
- // | 2,0 | 2,1 | 2,2 | Fixed Size Row
- // | | | |
- // +-----+-------------------------------+-----+
- //
- // This is implemented in GridLayout by the following grid, where
- // SC1 has columnWeight=1 and SR1 has rowWeight=1.
- // (SC=Space for Column, SR=Space for Row)
- //
- // +------+-------------------------------+------+
- // | | | |
- // | SCR0 | SC1 | SC2 |
- // | | | |
- // +------+-------------------------------+------+
- // | | | |
- // | | | |
- // | | | |
- // | SR1 | | |
- // | | | |
- // | | | |
- // | | | |
- // +------+-------------------------------+------+
- // | | | |
- // | SR2 | | |
- // | | | |
- // +------+-------------------------------+------+
- //
- // Note that when we split columns and rows here, if splitting the expanding
- // row or column then the row or column weight should be moved to the right or
- // bottom half!
-
-
- //int columnX = mGrid.getColumnX(column);
- //int rowY = mGrid.getRowY(row);
-
- mGrid.setGridAttribute(targetNode, ATTR_COLUMN_COUNT, 2);
- //mGrid.setGridAttribute(targetNode, ATTR_COLUMN_COUNT, 3);
- //INode scr0 = addSpacer(targetNode, -1, 0, 0, 1, 1);
- //INode sc1 = addSpacer(targetNode, -1, 0, 1, 0, 0);
- //INode sc2 = addSpacer(targetNode, -1, 0, 2, 1, 0);
- //INode sr1 = addSpacer(targetNode, -1, 1, 0, 0, 0);
- //INode sr2 = addSpacer(targetNode, -1, 2, 0, 0, 1);
- //mGrid.setGridAttribute(sc1, ATTR_LAYOUT_GRAVITY, VALUE_FILL_HORIZONTAL);
- //mGrid.setGridAttribute(sr1, ATTR_LAYOUT_GRAVITY, VALUE_FILL_VERTICAL);
- //
- //mGrid.loadFromXml();
- //column = mGrid.getColumn(columnX);
- //row = mGrid.getRow(rowY);
- }
-
- int startX, endX;
- if (mColumnMatch.type == SegmentType.RIGHT) {
- endX = mColumnMatch.matchedLine - 1;
- startX = endX - bounds.w;
- column = mGrid.getColumn(startX);
- } else {
- startX = mColumnMatch.matchedLine; // TODO: What happens on type=RIGHT?
- endX = startX + bounds.w;
- }
- int startY, endY;
- if (mRowMatch.type == SegmentType.BOTTOM) {
- endY = mRowMatch.matchedLine - 1;
- startY = endY - bounds.h;
- row = mGrid.getRow(startY);
- } else if (mRowMatch.type == SegmentType.BASELINE) {
- // TODO: The rowSpan should always be 1 for baseline alignments, since
- // otherwise the alignment won't work!
- startY = endY = mRowMatch.matchedLine;
- } else {
- startY = mRowMatch.matchedLine;
- endY = startY + bounds.h;
- }
- int endColumn = mGrid.getColumn(endX);
- int endRow = mGrid.getRow(endY);
- int columnSpan = endColumn - column + 1;
- int rowSpan = endRow - row + 1;
-
- // Make sure my math was right:
- assert mRowMatch.type != SegmentType.BASELINE || rowSpan == 1 : rowSpan;
-
- // If the item almost fits into the row (at most N % bigger) then just enlarge
- // the row; don't add a rowspan since that will defeat baseline alignment etc
- if (!mRowMatch.createCell && bounds.h <= MAX_CELL_DIFFERENCE * mGrid.getRowHeight(
- mRowMatch.type == SegmentType.BOTTOM ? endRow : row, 1)) {
- if (mRowMatch.type == SegmentType.BOTTOM) {
- row += rowSpan - 1;
- }
- rowSpan = 1;
- }
- if (!mColumnMatch.createCell && bounds.w <= MAX_CELL_DIFFERENCE * mGrid.getColumnWidth(
- mColumnMatch.type == SegmentType.RIGHT ? endColumn : column, 1)) {
- if (mColumnMatch.type == SegmentType.RIGHT) {
- column += columnSpan - 1;
- }
- columnSpan = 1;
- }
-
- if (mColumnMatch.type == SegmentType.CENTER_HORIZONTAL) {
- column = 0;
- columnSpan = mGrid.actualColumnCount;
- }
-
- // Temporary: Ensure we don't get in trouble with implicit positions
- mGrid.applyPositionAttributes();
-
- // Split cells to make a new column
- if (mColumnMatch.createCell) {
- int columnWidthPx = mGrid.getColumnDistance(column, mColumnMatch.matchedLine);
- //assert columnWidthPx == columnMatch.distance; // TBD? IF so simplify
- int columnWidthDp = mRule.getRulesEngine().pxToDp(columnWidthPx);
-
- int maxX = mGrid.getColumnMaxX(column);
- boolean insertMarginColumn = false;
- if (mColumnMatch.margin == 0) {
- columnWidthDp = 0;
- } else if (mColumnMatch.margin != UNDEFINED) {
- int distance = abs(mColumnMatch.matchedLine - (maxX + mColumnMatch.margin));
- insertMarginColumn = column > 0 && distance < 2;
- if (insertMarginColumn) {
- int margin = mColumnMatch.margin;
- if (ViewMetadataRepository.INSETS_SUPPORTED) {
- IViewMetadata metadata = mRule.getRulesEngine().getMetadata(fqcn);
- if (metadata != null) {
- Margins insets = metadata.getInsets();
- if (insets != null) {
- // TODO:
- // Consider left or right side attachment
- // TODO: Also consider inset of element on cell to the left
- margin -= insets.left;
- }
- }
- }
-
- columnWidthDp = mRule.getRulesEngine().pxToDp(margin);
- }
- }
-
- column++;
- mGrid.splitColumn(column, insertMarginColumn, columnWidthDp, mColumnMatch.matchedLine);
- if (insertMarginColumn) {
- column++;
- }
- }
-
- // Split cells to make a new row
- if (mRowMatch.createCell) {
- int rowHeightPx = mGrid.getRowDistance(row, mRowMatch.matchedLine);
- //assert rowHeightPx == rowMatch.distance; // TBD? If so simplify
- int rowHeightDp = mRule.getRulesEngine().pxToDp(rowHeightPx);
-
- int maxY = mGrid.getRowMaxY(row);
- boolean insertMarginRow = false;
- if (mRowMatch.margin == 0) {
- rowHeightDp = 0;
- } else if (mRowMatch.margin != UNDEFINED) {
- int distance = abs(mRowMatch.matchedLine - (maxY + mRowMatch.margin));
- insertMarginRow = row > 0 && distance < 2;
- if (insertMarginRow) {
- int margin = mRowMatch.margin;
- IViewMetadata metadata = mRule.getRulesEngine().getMetadata(element.getFqcn());
- if (metadata != null) {
- Margins insets = metadata.getInsets();
- if (insets != null) {
- // TODO:
- // Consider left or right side attachment
- // TODO: Also consider inset of element on cell to the left
- margin -= insets.top;
- }
- }
-
- rowHeightDp = mRule.getRulesEngine().pxToDp(margin);
- }
- }
-
- row++;
- mGrid.splitRow(row, insertMarginRow, rowHeightDp, mRowMatch.matchedLine);
- if (insertMarginRow) {
- row++;
- }
- }
-
- // Figure out where to insert the new child
-
- int index = mGrid.getInsertIndex(row, column);
- if (index == -1) {
- // Couldn't find a later place to insert
- newChild = targetNode.appendChild(fqcn);
- } else {
- GridModel.ViewData next = mGrid.getView(index);
-
- newChild = targetNode.insertChildAt(fqcn, index);
-
- // Must also apply positions to the following child to ensure
- // that the new child doesn't affect the implicit numbering!
- // TODO: We can later check whether the implied number is equal to
- // what it already is such that we don't need this
- next.applyPositionAttributes();
- }
-
- // Set the cell position (gravity) of the new widget
- int gravity = 0;
- if (mColumnMatch.type == SegmentType.RIGHT) {
- gravity |= GravityHelper.GRAVITY_RIGHT;
- } else if (mColumnMatch.type == SegmentType.CENTER_HORIZONTAL) {
- gravity |= GravityHelper.GRAVITY_CENTER_HORIZ;
- }
- mGrid.setGridAttribute(newChild, ATTR_LAYOUT_COLUMN, column);
- if (mRowMatch.type == SegmentType.BASELINE) {
- // There *is* no baseline gravity constant, instead, leave the
- // vertical gravity unspecified and GridLayout will treat it as
- // baseline alignment
- //gravity |= GravityHelper.GRAVITY_BASELINE;
- } else if (mRowMatch.type == SegmentType.BOTTOM) {
- gravity |= GravityHelper.GRAVITY_BOTTOM;
- } else if (mRowMatch.type == SegmentType.CENTER_VERTICAL) {
- gravity |= GravityHelper.GRAVITY_CENTER_VERT;
- }
- // Ensure that we have at least one horizontal and vertical constraint, otherwise
- // the new item will be fixed. As an example, if we have a single button in the
- // table which we inserted *without* a gravity, and we then insert a button
- // above it with a vertical gravity, then only the top column would be considered
- // stretchable, and it will fill all available vertical space and the previous
- // button will jump to the bottom.
- if (!GravityHelper.isConstrainedHorizontally(gravity)) {
- gravity |= GravityHelper.GRAVITY_LEFT;
- }
- /* This causes problems: Try placing two buttons vertically from the top of the layout.
- We need to solve the free column/free row problem first.
- if (!GravityHelper.isConstrainedVertically(gravity)
- // There is no baseline constant, so we have to leave it unconstrained instead
- && mRowMatch.type != SegmentType.BASELINE
- // You also can't baseline align one element with another that has vertical
- // alignment top or bottom, so when we first "freely" place views (e.g.
- // at a particular y location), also place it freely (no constraint).
- && !mRowMatch.createCell) {
- gravity |= GravityHelper.GRAVITY_TOP;
- }
- */
- mGrid.setGridAttribute(newChild, ATTR_LAYOUT_GRAVITY, getGravity(gravity));
-
- mGrid.setGridAttribute(newChild, ATTR_LAYOUT_ROW, row);
-
- // Apply spans to ensure that the widget can fit without pushing columns
- if (columnSpan > 1) {
- mGrid.setGridAttribute(newChild, ATTR_LAYOUT_COLUMN_SPAN, columnSpan);
- }
- if (rowSpan > 1) {
- mGrid.setGridAttribute(newChild, ATTR_LAYOUT_ROW_SPAN, rowSpan);
- }
-
- // Ensure that we don't store columnCount=0
- if (mGrid.actualColumnCount == 0) {
- mGrid.setGridAttribute(mGrid.layout, ATTR_COLUMN_COUNT, Math.max(1, column + 1));
- }
-
- return newChild;
- }
-
- /**
- * Called when a drop is completed and we're in grid-editing mode. This will insert
- * the dragged element into the target cell.
- *
- * @param targetNode the GridLayout node
- * @param element the dragged element
- * @return the newly created node
- */
- public INode handleGridModeDrop(INode targetNode, IDragElement element) {
- String fqcn = element.getFqcn();
- INode newChild = targetNode.appendChild(fqcn);
-
- int column = mColumnMatch.cellIndex;
- if (mColumnMatch.createCell) {
- mGrid.addColumn(column,
- newChild, UNDEFINED, false, UNDEFINED, UNDEFINED);
- }
- int row = mRowMatch.cellIndex;
- if (mRowMatch.createCell) {
- mGrid.addRow(row, newChild, UNDEFINED, false, UNDEFINED, UNDEFINED);
- }
-
- mGrid.setGridAttribute(newChild, ATTR_LAYOUT_COLUMN, column);
- mGrid.setGridAttribute(newChild, ATTR_LAYOUT_ROW, row);
-
- int gravity = 0;
- if (mColumnMatch.type == SegmentType.RIGHT) {
- gravity |= GravityHelper.GRAVITY_RIGHT;
- } else if (mColumnMatch.type == SegmentType.CENTER_HORIZONTAL) {
- gravity |= GravityHelper.GRAVITY_CENTER_HORIZ;
- }
- if (mRowMatch.type == SegmentType.BASELINE) {
- // There *is* no baseline gravity constant, instead, leave the
- // vertical gravity unspecified and GridLayout will treat it as
- // baseline alignment
- //gravity |= GravityHelper.GRAVITY_BASELINE;
- } else if (mRowMatch.type == SegmentType.BOTTOM) {
- gravity |= GravityHelper.GRAVITY_BOTTOM;
- } else if (mRowMatch.type == SegmentType.CENTER_VERTICAL) {
- gravity |= GravityHelper.GRAVITY_CENTER_VERT;
- }
- if (!GravityHelper.isConstrainedHorizontally(gravity)) {
- gravity |= GravityHelper.GRAVITY_LEFT;
- }
- if (!GravityHelper.isConstrainedVertically(gravity)) {
- gravity |= GravityHelper.GRAVITY_TOP;
- }
- mGrid.setGridAttribute(newChild, ATTR_LAYOUT_GRAVITY, getGravity(gravity));
-
- if (mGrid.declaredColumnCount == UNDEFINED || mGrid.declaredColumnCount < column + 1) {
- mGrid.setGridAttribute(mGrid.layout, ATTR_COLUMN_COUNT, column + 1);
- }
-
- return newChild;
- }
-
- /**
- * Returns the best horizontal match
- *
- * @return the best horizontal match, or null if there is no match
- */
- public GridMatch getColumnMatch() {
- return mColumnMatch;
- }
-
- /**
- * Returns the best vertical match
- *
- * @return the best vertical match, or null if there is no match
- */
- public GridMatch getRowMatch() {
- return mRowMatch;
- }
-
- /**
- * Returns the grid used by the drop handler
- *
- * @return the grid used by the drop handler, never null
- */
- public GridModel getGrid() {
- return mGrid;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/grid/GridLayoutPainter.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/grid/GridLayoutPainter.java
deleted file mode 100644
index 7e2d3a799..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/grid/GridLayoutPainter.java
+++ /dev/null
@@ -1,370 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout.grid;
-
-import static com.android.ide.common.layout.GridLayoutRule.GRID_SIZE;
-import static com.android.ide.common.layout.GridLayoutRule.MARGIN_SIZE;
-import static com.android.ide.common.layout.grid.GridModel.UNDEFINED;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.DrawingStyle;
-import com.android.ide.common.api.DropFeedback;
-import com.android.ide.common.api.IDragElement;
-import com.android.ide.common.api.IFeedbackPainter;
-import com.android.ide.common.api.IGraphics;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.api.SegmentType;
-import com.android.ide.common.layout.GridLayoutRule;
-import com.android.utils.Pair;
-
-/**
- * Painter which paints feedback during drag, drop and resizing operations, as well as
- * static selection feedback
- */
-public class GridLayoutPainter {
-
- /**
- * Creates a painter for drop feedback
- *
- * @param rule the corresponding {@link GridLayoutRule}
- * @param elements the dragged elements
- * @return a {@link IFeedbackPainter} which can paint the drop feedback
- */
- public static IFeedbackPainter createDropFeedbackPainter(GridLayoutRule rule,
- IDragElement[] elements) {
- return new DropFeedbackPainter(rule, elements);
- }
-
- /**
- * Paints the structure (the grid model) of the given GridLayout.
- *
- * @param style the drawing style to use to paint the structure lines
- * @param layout the grid layout node
- * @param gc the graphics context to paint into
- * @param grid the grid model to be visualized
- */
- public static void paintStructure(DrawingStyle style, INode layout, IGraphics gc,
- GridModel grid) {
- Rect b = layout.getBounds();
-
- gc.useStyle(style);
- for (int row = 0; row < grid.actualRowCount; row++) {
- int y = grid.getRowY(row);
- gc.drawLine(b.x, y, b.x2(), y);
- }
- for (int column = 0; column < grid.actualColumnCount; column++) {
- int x = grid.getColumnX(column);
- gc.drawLine(x, b.y, x, b.y2());
- }
- }
-
- /**
- * Paints a regular grid according to the {@link GridLayoutRule#GRID_SIZE} and
- * {@link GridLayoutRule#MARGIN_SIZE} dimensions. These are the same lines that
- * snap-to-grid will align with.
- *
- * @param layout the GridLayout node
- * @param gc the graphics context to paint the grid into
- */
- public static void paintGrid(INode layout, IGraphics gc) {
- Rect b = layout.getBounds();
-
- int oldAlpha = gc.getAlpha();
- gc.useStyle(DrawingStyle.GUIDELINE);
- gc.setAlpha(128);
-
- int y1 = b.y + MARGIN_SIZE;
- int y2 = b.y2() - MARGIN_SIZE;
- for (int y = y1; y < y2; y += GRID_SIZE) {
- int x1 = b.x + MARGIN_SIZE;
- int x2 = b.x2() - MARGIN_SIZE;
- for (int x = x1; x < x2; x += GRID_SIZE) {
- gc.drawPoint(x, y);
- }
- }
- gc.setAlpha(oldAlpha);
- }
-
- /**
- * Paint resizing feedback (which currently paints the grid model faintly.)
- *
- * @param gc the graphics context
- * @param layout the GridLayout
- * @param grid the grid model
- */
- public static void paintResizeFeedback(IGraphics gc, INode layout, GridModel grid) {
- paintStructure(DrawingStyle.GRID, layout, gc, grid);
- }
-
- /**
- * A painter which can paint the drop feedback for elements being dragged into or
- * within a GridLayout.
- */
- private static class DropFeedbackPainter implements IFeedbackPainter {
- private final GridLayoutRule mRule;
- private final IDragElement[] mElements;
-
- /** Constructs a new {@link GridLayoutPainter} bound to the given {@link GridLayoutRule}
- * @param rule the corresponding rule
- * @param elements the elements to draw */
- public DropFeedbackPainter(GridLayoutRule rule, IDragElement[] elements) {
- mRule = rule;
- mElements = elements;
- }
-
- // Implements IFeedbackPainter
- @Override
- public void paint(@NonNull IGraphics gc, @NonNull INode node,
- @NonNull DropFeedback feedback) {
- Rect b = node.getBounds();
- if (!b.isValid()) {
- return;
- }
-
- // Highlight the receiver
- gc.useStyle(DrawingStyle.DROP_RECIPIENT);
- gc.drawRect(b);
- GridDropHandler data = (GridDropHandler) feedback.userData;
-
- if (!GridLayoutRule.sGridMode) {
- paintFreeFormDropFeedback(gc, node, feedback, b, data);
- } else {
- paintGridModeDropFeedback(gc, b, data);
- }
- }
-
- /**
- * Paints the drag feedback for a free-form mode drag
- */
- private void paintFreeFormDropFeedback(IGraphics gc, INode node, DropFeedback feedback,
- Rect b, GridDropHandler data) {
- GridModel grid = data.getGrid();
- if (GridLayoutRule.sSnapToGrid) {
- GridLayoutPainter.paintGrid(node, gc);
- }
- GridLayoutPainter.paintStructure(DrawingStyle.GRID, node, gc, grid);
-
- GridMatch rowMatch = data.getRowMatch();
- GridMatch columnMatch = data.getColumnMatch();
-
- if (rowMatch == null || columnMatch == null) {
- return;
- }
-
- IDragElement first = mElements[0];
- Rect dragBounds = first.getBounds();
- int offsetX = 0;
- int offsetY = 0;
- if (rowMatch.type == SegmentType.BOTTOM) {
- offsetY -= dragBounds.h;
- } else if (rowMatch.type == SegmentType.BASELINE) {
- offsetY -= feedback.dragBaseline;
- }
- if (columnMatch.type == SegmentType.RIGHT) {
- offsetX -= dragBounds.w;
- } else if (columnMatch.type == SegmentType.CENTER_HORIZONTAL) {
- offsetX -= dragBounds.w / 2;
- }
-
- // Draw guidelines for matches
- int y = rowMatch.matchedLine;
- int x = columnMatch.matchedLine;
- Rect bounds = first.getBounds();
-
- // Draw margin
- if (rowMatch.margin != UNDEFINED && rowMatch.margin > 0) {
- gc.useStyle(DrawingStyle.DISTANCE);
- int centerX = bounds.w / 2 + offsetX + x;
- int y1;
- int y2;
- if (rowMatch.type == SegmentType.TOP) {
- y1 = offsetY + y - 1;
- y2 = rowMatch.matchedLine - rowMatch.margin;
- } else {
- assert rowMatch.type == SegmentType.BOTTOM;
- y1 = bounds.h + offsetY + y - 1;
- y2 = rowMatch.matchedLine + rowMatch.margin;
- }
- gc.drawLine(b.x, y1, b.x2(), y1);
- gc.drawLine(b.x, y2, b.x2(), y2);
- gc.drawString(Integer.toString(rowMatch.margin),
- centerX - 3, y1 + (y2 - y1 - 16) / 2);
- } else {
- gc.useStyle(rowMatch.margin == 0 ? DrawingStyle.DISTANCE
- : rowMatch.createCell ? DrawingStyle.GUIDELINE_DASHED
- : DrawingStyle.GUIDELINE);
- gc.drawLine(b.x, y, b.x2(), y );
- }
-
- if (columnMatch.margin != UNDEFINED && columnMatch.margin > 0) {
- gc.useStyle(DrawingStyle.DISTANCE);
- int centerY = bounds.h / 2 + offsetY + y;
- int x1;
- int x2;
- if (columnMatch.type == SegmentType.LEFT) {
- x1 = offsetX + x - 1;
- x2 = columnMatch.matchedLine - columnMatch.margin;
- } else {
- assert columnMatch.type == SegmentType.RIGHT;
- x1 = bounds.w + offsetX + x - 1;
- x2 = columnMatch.matchedLine + columnMatch.margin;
- }
- gc.drawLine(x1, b.y, x1, b.y2());
- gc.drawLine(x2, b.y, x2, b.y2());
- gc.drawString(Integer.toString(columnMatch.margin),
- x1 + (x2 - x1 - 16) / 2, centerY - 3);
- } else {
- gc.useStyle(columnMatch.margin == 0 ? DrawingStyle.DISTANCE
- : columnMatch.createCell ? DrawingStyle.GUIDELINE_DASHED
- : DrawingStyle.GUIDELINE);
- gc.drawLine(x, b.y, x, b.y2());
- }
-
- // Draw preview rectangles for all the dragged elements
- gc.useStyle(DrawingStyle.DROP_PREVIEW);
- offsetX += x - bounds.x;
- offsetY += y - bounds.y;
-
- for (IDragElement element : mElements) {
- if (element == first) {
- mRule.drawElement(gc, first, offsetX, offsetY);
- // Preview baseline as well
- if (feedback.dragBaseline != -1) {
- int x1 = dragBounds.x + offsetX;
- int y1 = dragBounds.y + offsetY + feedback.dragBaseline;
- gc.drawLine(x1, y1, x1 + dragBounds.w, y1);
- }
- } else {
- b = element.getBounds();
- if (b.isValid()) {
- gc.drawRect(b.x + offsetX, b.y + offsetY,
- b.x + offsetX + b.w, b.y + offsetY + b.h);
- }
- }
- }
- }
-
- /**
- * Paints the drag feedback for a grid-mode drag
- */
- private void paintGridModeDropFeedback(IGraphics gc, Rect b, GridDropHandler data) {
- int radius = mRule.getNewCellSize();
- GridModel grid = data.getGrid();
-
- gc.useStyle(DrawingStyle.GUIDELINE);
- // Paint grid
- for (int row = 1; row < grid.actualRowCount; row++) {
- int y = grid.getRowY(row);
- gc.drawLine(b.x, y - radius, b.x2(), y - radius);
- gc.drawLine(b.x, y + radius, b.x2(), y + radius);
-
- }
- for (int column = 1; column < grid.actualColumnCount; column++) {
- int x = grid.getColumnX(column);
- gc.drawLine(x - radius, b.y, x - radius, b.y2());
- gc.drawLine(x + radius, b.y, x + radius, b.y2());
- }
- gc.drawRect(b.x, b.y, b.x2(), b.y2());
- gc.drawRect(b.x + 2 * radius, b.y + 2 * radius,
- b.x2() - 2 * radius, b.y2() - 2 * radius);
-
- GridMatch columnMatch = data.getColumnMatch();
- GridMatch rowMatch = data.getRowMatch();
- int column = columnMatch.cellIndex;
- int row = rowMatch.cellIndex;
- boolean createColumn = columnMatch.createCell;
- boolean createRow = rowMatch.createCell;
-
- Rect cellBounds = grid.getCellBounds(row, column, 1, 1);
-
- IDragElement first = mElements[0];
- Rect dragBounds = first.getBounds();
- int offsetX = cellBounds.x - dragBounds.x;
- int offsetY = cellBounds.y - dragBounds.y;
-
- gc.useStyle(DrawingStyle.DROP_ZONE_ACTIVE);
- if (createColumn) {
- gc.fillRect(new Rect(cellBounds.x - radius,
- cellBounds.y + (createRow ? -radius : radius),
- 2 * radius + 1, cellBounds.h - (createRow ? 0 : 2 * radius)));
- offsetX -= radius + dragBounds.w / 2;
- }
- if (createRow) {
- gc.fillRect(new Rect(cellBounds.x + radius, cellBounds.y - radius,
- cellBounds.w - 2 * radius, 2 * radius + 1));
- offsetY -= radius + dragBounds.h / 2;
- } else if (!createColumn) {
- // Choose this cell
- gc.fillRect(new Rect(cellBounds.x + radius, cellBounds.y + radius,
- cellBounds.w - 2 * radius, cellBounds.h - 2 * radius));
- }
-
- gc.useStyle(DrawingStyle.DROP_PREVIEW);
-
- Rect bounds = first.getBounds();
- int x = offsetX;
- int y = offsetY;
- if (columnMatch.type == SegmentType.RIGHT) {
- x += cellBounds.w - bounds.w;
- } else if (columnMatch.type == SegmentType.CENTER_HORIZONTAL) {
- x += cellBounds.w / 2 - bounds.w / 2;
- }
- if (rowMatch.type == SegmentType.BOTTOM) {
- y += cellBounds.h - bounds.h;
- } else if (rowMatch.type == SegmentType.CENTER_VERTICAL) {
- y += cellBounds.h / 2 - bounds.h / 2;
- }
-
- mRule.drawElement(gc, first, x, y);
- }
- }
-
- /**
- * Paints the structure (the row and column boundaries) of the given
- * GridLayout
- *
- * @param view the instance of the GridLayout whose structure should be
- * painted
- * @param style the drawing style to use for the cell boundaries
- * @param layout the layout element
- * @param gc the graphics context
- * @return true if the structure was successfully inferred from the view and
- * painted
- */
- public static boolean paintStructure(Object view, DrawingStyle style, INode layout,
- IGraphics gc) {
- Pair<int[],int[]> cellBounds = GridModel.getAxisBounds(view);
- if (cellBounds != null) {
- int[] xs = cellBounds.getFirst();
- int[] ys = cellBounds.getSecond();
- Rect b = layout.getBounds();
- gc.useStyle(style);
- for (int row = 0; row < ys.length; row++) {
- int y = ys[row] + b.y;
- gc.drawLine(b.x, y, b.x2(), y);
- }
- for (int column = 0; column < xs.length; column++) {
- int x = xs[column] + b.x;
- gc.drawLine(x, b.y, x, b.y2());
- }
-
- return true;
- } else {
- return false;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/grid/GridMatch.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/grid/GridMatch.java
deleted file mode 100644
index 9bee34345..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/grid/GridMatch.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout.grid;
-
-import static com.android.ide.common.layout.grid.GridModel.UNDEFINED;
-
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.SegmentType;
-
-/**
- * A match for a drag within a GridLayout, corresponding to an alignment with another
- * edge, or a margin, or centering, or a gap distance from another edge and so on.
- */
-class GridMatch implements Comparable<GridMatch> {
- /** The distance to the matched edge - used to pick best matches */
- public final int distance;
-
- /** Type of edge that was matched (this refers to the edge on the dragged node,
- * not on the matched node/row/cell etc) */
- public final SegmentType type;
-
- /** Row or column for the match */
- public int cellIndex;
-
- /** If true, create a new row/column */
- public boolean createCell;
-
- /** The actual x or y position of the matched segment */
- public int matchedLine;
-
- /** Amount of margin between the matched edges */
- public int margin;
-
- /**
- * Constructs a match.
- *
- * @param type the edge of the dragged element that was matched
- * @param distance the absolute distance from the ideal match - used to find the best
- * match
- * @param matchedLine the actual X or Y location of the ideal match
- * @param cellIndex the index of the row or column we matched with
- * @param createCell if true, create a new cell by splitting the existing cell at the
- * matchedLine position
- * @param margin a margin distance to add to the actual location from the matched line
- */
- GridMatch(SegmentType type, int distance, int matchedLine, int cellIndex,
- boolean createCell, int margin) {
- super();
- this.type = type;
- this.distance = distance;
- this.matchedLine = matchedLine;
- this.cellIndex = cellIndex;
- this.createCell = createCell;
- this.margin = margin;
- }
-
- // Implements Comparable<GridMatch>
- @Override
- public int compareTo(GridMatch o) {
- // Pick closest matches first
- if (distance != o.distance) {
- return distance - o.distance;
- }
-
- // Prefer some types of matches over other matches
- return getPriority() - o.getPriority();
- }
-
- /**
- * Describes the match for the user
- *
- * @param layout the GridLayout containing the match
- * @return a short description for the user of the match
- */
- public String getDisplayName(INode layout) {
- switch (type) {
- case BASELINE:
- return String.format("Align baseline in row %1$d", cellIndex + 1);
- case CENTER_HORIZONTAL:
- return "Center horizontally";
- case LEFT:
- if (!createCell) {
- return String.format("Insert into column %1$d", cellIndex + 1);
- }
- if (margin != UNDEFINED) {
- if (cellIndex == 0 && margin != 0) {
- return "Add one margin distance from the left";
- }
- return String.format("Add next to column %1$d", cellIndex + 1);
- }
- return String.format("Align left at x=%1$d", matchedLine - layout.getBounds().x);
- case RIGHT:
- if (!createCell) {
- return String.format("Insert right-aligned into column %1$d", cellIndex + 1);
- }
- return String.format("Align right at x=%1$d", matchedLine - layout.getBounds().x);
- case TOP:
- if (!createCell) {
- return String.format("Insert into row %1$d", cellIndex + 1);
- }
- if (margin != UNDEFINED) {
- if (cellIndex == 0 && margin != 0) {
- return "Add one margin distance from the top";
- }
- return String.format("Add below row %1$d", cellIndex + 1);
- }
- return String.format("Align top at y=%1d", matchedLine - layout.getBounds().y);
- case BOTTOM:
- if (!createCell) {
- return String.format("Insert into bottom of row %1$d", cellIndex + 1);
- }
- return String.format("Align bottom at y=%1d", matchedLine - layout.getBounds().y);
- case CENTER_VERTICAL:
- return "Center vertically";
- case UNKNOWN:
- default:
- return null;
- }
- }
-
- /**
- * Computes the sorting priority of this match, giving baseline matches higher
- * precedence than centering which in turn is ordered before external edge matches
- */
- private int getPriority() {
- switch (type) {
- case BASELINE:
- return 0;
- case CENTER_HORIZONTAL:
- case CENTER_VERTICAL:
- return 1;
- case BOTTOM:
- case LEFT:
- case RIGHT:
- case TOP:
- return 2;
- }
-
- return 3;
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/grid/GridModel.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/grid/GridModel.java
deleted file mode 100644
index 46770e82c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/grid/GridModel.java
+++ /dev/null
@@ -1,2384 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout.grid;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_COLUMN_COUNT;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ATTR_LAYOUT_COLUMN;
-import static com.android.SdkConstants.ATTR_LAYOUT_COLUMN_SPAN;
-import static com.android.SdkConstants.ATTR_LAYOUT_GRAVITY;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_ROW;
-import static com.android.SdkConstants.ATTR_LAYOUT_ROW_SPAN;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.ATTR_ORIENTATION;
-import static com.android.SdkConstants.ATTR_ROW_COUNT;
-import static com.android.SdkConstants.FQCN_GRID_LAYOUT;
-import static com.android.SdkConstants.FQCN_SPACE;
-import static com.android.SdkConstants.FQCN_SPACE_V7;
-import static com.android.SdkConstants.GRID_LAYOUT;
-import static com.android.SdkConstants.NEW_ID_PREFIX;
-import static com.android.SdkConstants.SPACE;
-import static com.android.SdkConstants.VALUE_BOTTOM;
-import static com.android.SdkConstants.VALUE_CENTER_VERTICAL;
-import static com.android.SdkConstants.VALUE_N_DP;
-import static com.android.SdkConstants.VALUE_TOP;
-import static com.android.SdkConstants.VALUE_VERTICAL;
-import static com.android.ide.common.layout.GravityHelper.GRAVITY_BOTTOM;
-import static com.android.ide.common.layout.GravityHelper.GRAVITY_CENTER_HORIZ;
-import static com.android.ide.common.layout.GravityHelper.GRAVITY_CENTER_VERT;
-import static com.android.ide.common.layout.GravityHelper.GRAVITY_RIGHT;
-import static java.lang.Math.abs;
-import static java.lang.Math.max;
-import static java.lang.Math.min;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.IClientRulesEngine;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IViewMetadata;
-import com.android.ide.common.api.Margins;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.layout.GravityHelper;
-import com.android.ide.common.layout.GridLayoutRule;
-import com.android.utils.Pair;
-import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.Multimap;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.lang.ref.WeakReference;
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/** Models a GridLayout */
-public class GridModel {
- /** Marker value used to indicate values (rows, columns, etc) which have not been set */
- static final int UNDEFINED = Integer.MIN_VALUE;
-
- /** The size of spacers in the dimension that they are not defining */
- static final int SPACER_SIZE_DP = 1;
-
- /** Attribute value used for {@link #SPACER_SIZE_DP} */
- private static final String SPACER_SIZE = String.format(VALUE_N_DP, SPACER_SIZE_DP);
-
- /** Width assigned to a newly added column with the Add Column action */
- private static final int DEFAULT_CELL_WIDTH = 100;
-
- /** Height assigned to a newly added row with the Add Row action */
- private static final int DEFAULT_CELL_HEIGHT = 15;
-
- /** The GridLayout node, never null */
- public final INode layout;
-
- /** True if this is a vertical layout, and false if it is horizontal (the default) */
- public boolean vertical;
-
- /** The declared count of rows (which may be {@link #UNDEFINED} if not specified) */
- public int declaredRowCount;
-
- /** The declared count of columns (which may be {@link #UNDEFINED} if not specified) */
- public int declaredColumnCount;
-
- /** The actual count of rows found in the grid */
- public int actualRowCount;
-
- /** The actual count of columns found in the grid */
- public int actualColumnCount;
-
- /**
- * Array of positions (indexed by column) of the left edge of table cells; this
- * corresponds to the column positions in the grid
- */
- private int[] mLeft;
-
- /**
- * Array of positions (indexed by row) of the top edge of table cells; this
- * corresponds to the row positions in the grid
- */
- private int[] mTop;
-
- /**
- * Array of positions (indexed by column) of the maximum right hand side bounds of a
- * node in the given column; this represents the visual edge of a column even when the
- * actual column is wider
- */
- private int[] mMaxRight;
-
- /**
- * Array of positions (indexed by row) of the maximum bottom bounds of a node in the
- * given row; this represents the visual edge of a row even when the actual row is
- * taller
- */
- private int[] mMaxBottom;
-
- /**
- * Array of baselines computed for the rows. This array is populated lazily and should
- * not be accessed directly; call {@link #getBaseline(int)} instead.
- */
- private int[] mBaselines;
-
- /** List of all the view data for the children in this layout */
- private List<ViewData> mChildViews;
-
- /** The {@link IClientRulesEngine} */
- private final IClientRulesEngine mRulesEngine;
-
- /**
- * An actual instance of a GridLayout object that this grid model corresponds to.
- */
- private Object mViewObject;
-
- /** The namespace to use for attributes */
- private String mNamespace;
-
- /**
- * Constructs a {@link GridModel} for the given layout
- *
- * @param rulesEngine the associated rules engine
- * @param node the GridLayout node
- * @param viewObject an actual GridLayout instance, or null
- */
- private GridModel(IClientRulesEngine rulesEngine, INode node, Object viewObject) {
- mRulesEngine = rulesEngine;
- layout = node;
- mViewObject = viewObject;
- loadFromXml();
- }
-
- // Factory cache for most recent item (used primarily because during paints and drags
- // the grid model is called repeatedly for the same view object.)
- private static WeakReference<Object> sCachedViewObject = new WeakReference<Object>(null);
- private static WeakReference<GridModel> sCachedViewModel;
-
- /**
- * Factory which returns a grid model for the given node.
- *
- * @param rulesEngine the associated rules engine
- * @param node the GridLayout node
- * @param viewObject an actual GridLayout instance, or null
- * @return a new model
- */
- @NonNull
- public static GridModel get(
- @NonNull IClientRulesEngine rulesEngine,
- @NonNull INode node,
- @Nullable Object viewObject) {
- if (viewObject != null && viewObject == sCachedViewObject.get()) {
- GridModel model = sCachedViewModel.get();
- if (model != null) {
- return model;
- }
- }
-
- GridModel model = new GridModel(rulesEngine, node, viewObject);
- sCachedViewModel = new WeakReference<GridModel>(model);
- sCachedViewObject = new WeakReference<Object>(viewObject);
- return model;
- }
-
- /**
- * Returns the {@link ViewData} for the child at the given index
- *
- * @param index the position of the child node whose view we want to look up
- * @return the corresponding {@link ViewData}
- */
- public ViewData getView(int index) {
- return mChildViews.get(index);
- }
-
- /**
- * Returns the {@link ViewData} for the given child node.
- *
- * @param node the node for which we want the view info
- * @return the view info for the node, or null if not found
- */
- public ViewData getView(INode node) {
- for (ViewData view : mChildViews) {
- if (view.node == node) {
- return view;
- }
- }
-
- return null;
- }
-
- /**
- * Computes the index (among the children nodes) to insert a new node into which
- * should be positioned at the given row and column. This will skip over any nodes
- * that have implicit positions earlier than the given node, and will also ensure that
- * all nodes are placed before the spacer nodes.
- *
- * @param row the target row of the new node
- * @param column the target column of the new node
- * @return the insert position to use or -1 if no preference is found
- */
- public int getInsertIndex(int row, int column) {
- if (vertical) {
- for (ViewData view : mChildViews) {
- if (view.column > column || view.column == column && view.row >= row) {
- return view.index;
- }
- }
- } else {
- for (ViewData view : mChildViews) {
- if (view.row > row || view.row == row && view.column >= column) {
- return view.index;
- }
- }
- }
-
- // Place it before the first spacer
- for (ViewData view : mChildViews) {
- if (view.isSpacer()) {
- return view.index;
- }
- }
-
- return -1;
- }
-
- /**
- * Returns the baseline of the given row, or -1 if none is found. This looks for views
- * in the row which have baseline vertical alignment and also define their own
- * baseline, and returns the first such match.
- *
- * @param row the row to look up a baseline for
- * @return the baseline relative to the row position, or -1 if not defined
- */
- public int getBaseline(int row) {
- if (row < 0 || row >= mBaselines.length) {
- return -1;
- }
-
- int baseline = mBaselines[row];
- if (baseline == UNDEFINED) {
- baseline = -1;
-
- // TBD: Consider stringing together row information in the view data
- // so I can quickly identify the views in a given row instead of searching
- // among all?
- for (ViewData view : mChildViews) {
- // We only count baselines for views with rowSpan=1 because
- // baseline alignment doesn't work for cell spanning views
- if (view.row == row && view.rowSpan == 1) {
- baseline = view.node.getBaseline();
- if (baseline != -1) {
- // Even views that do have baselines do not count towards a row
- // baseline if they have a vertical gravity
- String gravity = getGridAttribute(view.node, ATTR_LAYOUT_GRAVITY);
- if (gravity == null
- || !(gravity.contains(VALUE_TOP)
- || gravity.contains(VALUE_BOTTOM)
- || gravity.contains(VALUE_CENTER_VERTICAL))) {
- // Compute baseline relative to the row, not the view itself
- baseline += view.node.getBounds().y - getRowY(row);
- break;
- }
- }
- }
- }
- mBaselines[row] = baseline;
- }
-
- return baseline;
- }
-
- /** Applies the row and column values into the XML */
- void applyPositionAttributes() {
- for (ViewData view : mChildViews) {
- view.applyPositionAttributes();
- }
-
- // Also fix the columnCount
- if (getGridAttribute(layout, ATTR_COLUMN_COUNT) != null &&
- declaredColumnCount > actualColumnCount) {
- setGridAttribute(layout, ATTR_COLUMN_COUNT, actualColumnCount);
- }
- }
-
- /**
- * Sets the given GridLayout attribute (rowCount, layout_row, etc) to the
- * given value. This automatically handles using the right XML namespace
- * based on whether the GridLayout is the android.widget.GridLayout, or the
- * support library GridLayout, and whether it's in a library project or not
- * etc.
- *
- * @param node the node to apply the attribute to
- * @param name the local name of the attribute
- * @param value the integer value to set the attribute to
- */
- public void setGridAttribute(INode node, String name, int value) {
- setGridAttribute(node, name, Integer.toString(value));
- }
-
- /**
- * Sets the given GridLayout attribute (rowCount, layout_row, etc) to the
- * given value. This automatically handles using the right XML namespace
- * based on whether the GridLayout is the android.widget.GridLayout, or the
- * support library GridLayout, and whether it's in a library project or not
- * etc.
- *
- * @param node the node to apply the attribute to
- * @param name the local name of the attribute
- * @param value the string value to set the attribute to, or null to clear
- * it
- */
- public void setGridAttribute(INode node, String name, String value) {
- node.setAttribute(getNamespace(), name, value);
- }
-
- /**
- * Returns the namespace URI to use for GridLayout-specific attributes, such
- * as columnCount, layout_column, layout_column_span, layout_gravity etc.
- *
- * @return the namespace, never null
- */
- public String getNamespace() {
- if (mNamespace == null) {
- mNamespace = ANDROID_URI;
-
- String fqcn = layout.getFqcn();
- if (!fqcn.equals(GRID_LAYOUT) && !fqcn.equals(FQCN_GRID_LAYOUT)) {
- mNamespace = mRulesEngine.getAppNameSpace();
- }
- }
-
- return mNamespace;
- }
-
- /** Removes the given flag from a flag attribute value and returns the result */
- static String removeFlag(String flag, String value) {
- if (value.equals(flag)) {
- return null;
- }
- // Handle spaces between pipes and flag are a prefix, suffix and interior occurrences
- int index = value.indexOf(flag);
- if (index != -1) {
- int pipe = value.lastIndexOf('|', index);
- int endIndex = index + flag.length();
- if (pipe != -1) {
- value = value.substring(0, pipe).trim() + value.substring(endIndex).trim();
- } else {
- pipe = value.indexOf('|', endIndex);
- if (pipe != -1) {
- value = value.substring(0, index).trim() + value.substring(pipe + 1).trim();
- } else {
- value = value.substring(0, index).trim() + value.substring(endIndex).trim();
- }
- }
- }
-
- return value;
- }
-
- /**
- * Loads a {@link GridModel} from the XML model.
- */
- private void loadFromXml() {
- INode[] children = layout.getChildren();
-
- declaredRowCount = getGridAttribute(layout, ATTR_ROW_COUNT, UNDEFINED);
- declaredColumnCount = getGridAttribute(layout, ATTR_COLUMN_COUNT, UNDEFINED);
- // Horizontal is the default, so if no value is specified it is horizontal.
- vertical = VALUE_VERTICAL.equals(getGridAttribute(layout, ATTR_ORIENTATION));
-
- mChildViews = new ArrayList<ViewData>(children.length);
- int index = 0;
- for (INode child : children) {
- ViewData view = new ViewData(child, index++);
- mChildViews.add(view);
- }
-
- // Assign row/column positions to all cells that do not explicitly define them
- if (!assignRowsAndColumnsFromViews(mChildViews)) {
- assignRowsAndColumnsFromXml(
- declaredRowCount == UNDEFINED ? children.length : declaredRowCount,
- declaredColumnCount == UNDEFINED ? children.length : declaredColumnCount);
- }
-
- assignCellBounds();
-
- for (int i = 0; i <= actualRowCount; i++) {
- mBaselines[i] = UNDEFINED;
- }
- }
-
- private Pair<Map<Integer, Integer>, Map<Integer, Integer>> findCellsOutsideDeclaredBounds() {
- // See if we have any (row,column) pairs that fall outside the declared
- // bounds; for these we identify the number of unique values and assign these
- // consecutive values
- Map<Integer, Integer> extraColumnsMap = null;
- Map<Integer, Integer> extraRowsMap = null;
- if (declaredRowCount != UNDEFINED) {
- Set<Integer> extraRows = null;
- for (ViewData view : mChildViews) {
- if (view.row >= declaredRowCount) {
- if (extraRows == null) {
- extraRows = new HashSet<Integer>();
- }
- extraRows.add(view.row);
- }
- }
- if (extraRows != null && declaredRowCount != UNDEFINED) {
- List<Integer> rows = new ArrayList<Integer>(extraRows);
- Collections.sort(rows);
- int row = declaredRowCount;
- extraRowsMap = new HashMap<Integer, Integer>();
- for (Integer declared : rows) {
- extraRowsMap.put(declared, row++);
- }
- }
- }
- if (declaredColumnCount != UNDEFINED) {
- Set<Integer> extraColumns = null;
- for (ViewData view : mChildViews) {
- if (view.column >= declaredColumnCount) {
- if (extraColumns == null) {
- extraColumns = new HashSet<Integer>();
- }
- extraColumns.add(view.column);
- }
- }
- if (extraColumns != null && declaredColumnCount != UNDEFINED) {
- List<Integer> columns = new ArrayList<Integer>(extraColumns);
- Collections.sort(columns);
- int column = declaredColumnCount;
- extraColumnsMap = new HashMap<Integer, Integer>();
- for (Integer declared : columns) {
- extraColumnsMap.put(declared, column++);
- }
- }
- }
-
- return Pair.of(extraRowsMap, extraColumnsMap);
- }
-
- /**
- * Figure out actual row and column numbers for views that do not specify explicit row
- * and/or column numbers
- * TODO: Consolidate with the algorithm in GridLayout to ensure we get the
- * exact same results!
- */
- private void assignRowsAndColumnsFromXml(int rowCount, int columnCount) {
- Pair<Map<Integer, Integer>, Map<Integer, Integer>> p = findCellsOutsideDeclaredBounds();
- Map<Integer, Integer> extraRowsMap = p.getFirst();
- Map<Integer, Integer> extraColumnsMap = p.getSecond();
-
- if (!vertical) {
- // Horizontal GridLayout: this is the default. Row and column numbers
- // are assigned by assuming that the children are assigned successive
- // column numbers until we get to the column count of the grid, at which
- // point we jump to the next row. If any cell specifies either an explicit
- // row number of column number, we jump to the next available position.
- // Note also that if there are any rowspans on the current row, then the
- // next row we jump to is below the largest such rowspan - in other words,
- // the algorithm does not fill holes in the middle!
-
- // TODO: Ensure that we don't run into trouble if a later element specifies
- // an earlier number... find out what the layout does in that case!
- int row = 0;
- int column = 0;
- int nextRow = 1;
- for (ViewData view : mChildViews) {
- int declaredColumn = view.column;
- if (declaredColumn != UNDEFINED) {
- if (declaredColumn >= columnCount) {
- assert extraColumnsMap != null;
- declaredColumn = extraColumnsMap.get(declaredColumn);
- view.column = declaredColumn;
- }
- if (declaredColumn < column) {
- // Must jump to the next row to accommodate the new row
- assert nextRow > row;
- //row++;
- row = nextRow;
- }
- column = declaredColumn;
- } else {
- view.column = column;
- }
- if (view.row != UNDEFINED) {
- // TODO: Should this adjust the column number too? (If so must
- // also update view.column since we've already processed the local
- // column number)
- row = view.row;
- } else {
- view.row = row;
- }
-
- nextRow = Math.max(nextRow, view.row + view.rowSpan);
-
- // Advance
- column += view.columnSpan;
- if (column >= columnCount) {
- column = 0;
- assert nextRow > row;
- //row++;
- row = nextRow;
- }
- }
- } else {
- // Vertical layout: successive children are assigned to the same column in
- // successive rows.
- int row = 0;
- int column = 0;
- int nextColumn = 1;
- for (ViewData view : mChildViews) {
- int declaredRow = view.row;
- if (declaredRow != UNDEFINED) {
- if (declaredRow >= rowCount) {
- declaredRow = extraRowsMap.get(declaredRow);
- view.row = declaredRow;
- }
- if (declaredRow < row) {
- // Must jump to the next column to accommodate the new column
- assert nextColumn > column;
- column = nextColumn;
- }
- row = declaredRow;
- } else {
- view.row = row;
- }
- if (view.column != UNDEFINED) {
- // TODO: Should this adjust the row number too? (If so must
- // also update view.row since we've already processed the local
- // row number)
- column = view.column;
- } else {
- view.column = column;
- }
-
- nextColumn = Math.max(nextColumn, view.column + view.columnSpan);
-
- // Advance
- row += view.rowSpan;
- if (row >= rowCount) {
- row = 0;
- assert nextColumn > column;
- //row++;
- column = nextColumn;
- }
- }
- }
- }
-
- private static boolean sAttemptSpecReflection = true;
-
- private boolean assignRowsAndColumnsFromViews(List<ViewData> views) {
- if (!sAttemptSpecReflection) {
- return false;
- }
-
- try {
- // Lazily initialized reflection methods
- Field spanField = null;
- Field rowSpecField = null;
- Field colSpecField = null;
- Field minField = null;
- Field maxField = null;
- Method getLayoutParams = null;
-
- for (ViewData view : views) {
- // TODO: If the element *specifies* anything in XML, use that instead
- Object child = mRulesEngine.getViewObject(view.node);
- if (child == null) {
- // Fallback to XML model
- return false;
- }
-
- if (getLayoutParams == null) {
- getLayoutParams = child.getClass().getMethod("getLayoutParams"); //$NON-NLS-1$
- }
- Object layoutParams = getLayoutParams.invoke(child);
- if (rowSpecField == null) {
- Class<? extends Object> layoutParamsClass = layoutParams.getClass();
- rowSpecField = layoutParamsClass.getDeclaredField("rowSpec"); //$NON-NLS-1$
- colSpecField = layoutParamsClass.getDeclaredField("columnSpec"); //$NON-NLS-1$
- rowSpecField.setAccessible(true);
- colSpecField.setAccessible(true);
- }
- assert colSpecField != null;
-
- Object rowSpec = rowSpecField.get(layoutParams);
- Object colSpec = colSpecField.get(layoutParams);
- if (spanField == null) {
- spanField = rowSpec.getClass().getDeclaredField("span"); //$NON-NLS-1$
- spanField.setAccessible(true);
- }
- assert spanField != null;
- Object rowInterval = spanField.get(rowSpec);
- Object colInterval = spanField.get(colSpec);
- if (minField == null) {
- Class<? extends Object> intervalClass = rowInterval.getClass();
- minField = intervalClass.getDeclaredField("min"); //$NON-NLS-1$
- maxField = intervalClass.getDeclaredField("max"); //$NON-NLS-1$
- minField.setAccessible(true);
- maxField.setAccessible(true);
- }
- assert maxField != null;
-
- int row = minField.getInt(rowInterval);
- int col = minField.getInt(colInterval);
- int rowEnd = maxField.getInt(rowInterval);
- int colEnd = maxField.getInt(colInterval);
-
- view.column = col;
- view.row = row;
- view.columnSpan = colEnd - col;
- view.rowSpan = rowEnd - row;
- }
-
- return true;
-
- } catch (Throwable e) {
- sAttemptSpecReflection = false;
- return false;
- }
- }
-
- /**
- * Computes the positions of the column and row boundaries
- */
- private void assignCellBounds() {
- if (!assignCellBoundsFromView()) {
- assignCellBoundsFromBounds();
- }
- initializeMaxBounds();
- mBaselines = new int[actualRowCount + 1];
- }
-
- /**
- * Computes the positions of the column and row boundaries, using actual
- * layout data from the associated GridLayout instance (stored in
- * {@link #mViewObject})
- */
- private boolean assignCellBoundsFromView() {
- if (mViewObject != null) {
- Pair<int[], int[]> cellBounds = GridModel.getAxisBounds(mViewObject);
- if (cellBounds != null) {
- int[] xs = cellBounds.getFirst();
- int[] ys = cellBounds.getSecond();
- Rect layoutBounds = layout.getBounds();
-
- // Handle "blank" grid layouts: insert a fake grid of CELL_COUNT^2 cells
- // where the user can do initial placement
- if (actualColumnCount <= 1 && actualRowCount <= 1 && mChildViews.isEmpty()) {
- final int CELL_COUNT = 1;
- xs = new int[CELL_COUNT + 1];
- ys = new int[CELL_COUNT + 1];
- int cellWidth = layoutBounds.w / CELL_COUNT;
- int cellHeight = layoutBounds.h / CELL_COUNT;
-
- for (int i = 0; i <= CELL_COUNT; i++) {
- xs[i] = i * cellWidth;
- ys[i] = i * cellHeight;
- }
- }
-
- actualColumnCount = xs.length - 1;
- actualRowCount = ys.length - 1;
-
- int layoutBoundsX = layoutBounds.x;
- int layoutBoundsY = layoutBounds.y;
- mLeft = new int[xs.length];
- mTop = new int[ys.length];
- for (int i = 0; i < xs.length; i++) {
- mLeft[i] = xs[i] + layoutBoundsX;
- }
- for (int i = 0; i < ys.length; i++) {
- mTop[i] = ys[i] + layoutBoundsY;
- }
-
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Computes the boundaries of the rows and columns by considering the bounds of the
- * children.
- */
- private void assignCellBoundsFromBounds() {
- Rect layoutBounds = layout.getBounds();
-
- // Compute the actualColumnCount and actualRowCount. This -should- be
- // as easy as declaredColumnCount + extraColumnsMap.size(),
- // but the user doesn't *have* to declare a column count (or a row count)
- // and we need both, so go and find the actual row and column maximums.
- int maxColumn = 0;
- int maxRow = 0;
- for (ViewData view : mChildViews) {
- maxColumn = max(maxColumn, view.column);
- maxRow = max(maxRow, view.row);
- }
- actualColumnCount = maxColumn + 1;
- actualRowCount = maxRow + 1;
-
- mLeft = new int[actualColumnCount + 1];
- for (int i = 1; i < actualColumnCount; i++) {
- mLeft[i] = UNDEFINED;
- }
- mLeft[0] = layoutBounds.x;
- mLeft[actualColumnCount] = layoutBounds.x2();
- mTop = new int[actualRowCount + 1];
- for (int i = 1; i < actualRowCount; i++) {
- mTop[i] = UNDEFINED;
- }
- mTop[0] = layoutBounds.y;
- mTop[actualRowCount] = layoutBounds.y2();
-
- for (ViewData view : mChildViews) {
- Rect bounds = view.node.getBounds();
- if (!bounds.isValid()) {
- continue;
- }
- int column = view.column;
- int row = view.row;
-
- if (mLeft[column] == UNDEFINED) {
- mLeft[column] = bounds.x;
- } else {
- mLeft[column] = Math.min(bounds.x, mLeft[column]);
- }
- if (mTop[row] == UNDEFINED) {
- mTop[row] = bounds.y;
- } else {
- mTop[row] = Math.min(bounds.y, mTop[row]);
- }
- }
-
- // Ensure that any empty columns/rows have a valid boundary value; for now,
- for (int i = actualColumnCount - 1; i >= 0; i--) {
- if (mLeft[i] == UNDEFINED) {
- if (i == 0) {
- mLeft[i] = layoutBounds.x;
- } else if (i < actualColumnCount - 1) {
- mLeft[i] = mLeft[i + 1] - 1;
- if (mLeft[i - 1] != UNDEFINED && mLeft[i] < mLeft[i - 1]) {
- mLeft[i] = mLeft[i - 1];
- }
- } else {
- mLeft[i] = layoutBounds.x2();
- }
- }
- }
- for (int i = actualRowCount - 1; i >= 0; i--) {
- if (mTop[i] == UNDEFINED) {
- if (i == 0) {
- mTop[i] = layoutBounds.y;
- } else if (i < actualRowCount - 1) {
- mTop[i] = mTop[i + 1] - 1;
- if (mTop[i - 1] != UNDEFINED && mTop[i] < mTop[i - 1]) {
- mTop[i] = mTop[i - 1];
- }
- } else {
- mTop[i] = layoutBounds.y2();
- }
- }
- }
-
- // The bounds should be in ascending order now
- if (false && GridLayoutRule.sDebugGridLayout) {
- for (int i = 1; i < actualRowCount; i++) {
- assert mTop[i + 1] >= mTop[i];
- }
- for (int i = 0; i < actualColumnCount; i++) {
- assert mLeft[i + 1] >= mLeft[i];
- }
- }
- }
-
- /**
- * Determine, for each row and column, what the largest x and y edges are
- * within that row or column. This is used to find a natural split point to
- * suggest when adding something "to the right of" or "below" another view.
- */
- private void initializeMaxBounds() {
- mMaxRight = new int[actualColumnCount + 1];
- mMaxBottom = new int[actualRowCount + 1];
-
- for (ViewData view : mChildViews) {
- Rect bounds = view.node.getBounds();
- if (!bounds.isValid()) {
- continue;
- }
-
- if (!view.isSpacer()) {
- int x2 = bounds.x2();
- int y2 = bounds.y2();
- int column = view.column;
- int row = view.row;
- int targetColumn = min(actualColumnCount - 1,
- column + view.columnSpan - 1);
- int targetRow = min(actualRowCount - 1, row + view.rowSpan - 1);
- IViewMetadata metadata = mRulesEngine.getMetadata(view.node.getFqcn());
- if (metadata != null) {
- Margins insets = metadata.getInsets();
- if (insets != null) {
- x2 -= insets.right;
- y2 -= insets.bottom;
- }
- }
- if (mMaxRight[targetColumn] < x2
- && ((view.gravity & (GRAVITY_CENTER_HORIZ | GRAVITY_RIGHT)) == 0)) {
- mMaxRight[targetColumn] = x2;
- }
- if (mMaxBottom[targetRow] < y2
- && ((view.gravity & (GRAVITY_CENTER_VERT | GRAVITY_BOTTOM)) == 0)) {
- mMaxBottom[targetRow] = y2;
- }
- }
- }
- }
-
- /**
- * Looks up the x[] and y[] locations of the columns and rows in the given GridLayout
- * instance.
- *
- * @param view the GridLayout object, which should already have performed layout
- * @return a pair of x[] and y[] integer arrays, or null if it could not be found
- */
- public static Pair<int[], int[]> getAxisBounds(Object view) {
- try {
- Class<?> clz = view.getClass();
- String verticalAxisName = "verticalAxis";
- Field horizontalAxis;
- try {
- horizontalAxis = clz.getDeclaredField("horizontalAxis"); //$NON-NLS-1$
- } catch (NoSuchFieldException e) {
- // Field names changed in KitKat
- horizontalAxis = clz.getDeclaredField("mHorizontalAxis"); //$NON-NLS-1$
- verticalAxisName = "mVerticalAxis";
- }
- Field verticalAxis = clz.getDeclaredField(verticalAxisName);
- horizontalAxis.setAccessible(true);
- verticalAxis.setAccessible(true);
- Object horizontal = horizontalAxis.get(view);
- Object vertical = verticalAxis.get(view);
- Field locations = horizontal.getClass().getDeclaredField("locations"); //$NON-NLS-1$
- assert locations.getType().isArray() : locations.getType();
- locations.setAccessible(true);
- Object horizontalLocations = locations.get(horizontal);
- Object verticalLocations = locations.get(vertical);
- int[] xs = (int[]) horizontalLocations;
- int[] ys = (int[]) verticalLocations;
- return Pair.of(xs, ys);
- } catch (Throwable t) {
- // Probably trying to show a GridLayout on a platform that does not support it.
- // Return null to indicate that the grid bounds must be computed from view bounds.
- return null;
- }
- }
-
- /**
- * Add a new column.
- *
- * @param selectedChildren if null or empty, add the column at the end of the grid,
- * and otherwise add it before the column of the first selected child
- * @return the newly added column spacer
- */
- public INode addColumn(List<? extends INode> selectedChildren) {
- // Determine insert index
- int newColumn = actualColumnCount;
- if (selectedChildren != null && selectedChildren.size() > 0) {
- INode first = selectedChildren.get(0);
- ViewData view = getView(first);
- newColumn = view.column;
- }
-
- INode newView = addColumn(newColumn, null, UNDEFINED, false, UNDEFINED, UNDEFINED);
- if (newView != null) {
- mRulesEngine.select(Collections.singletonList(newView));
- }
-
- return newView;
- }
-
- /**
- * Adds a new column.
- *
- * @param newColumn the column index to insert before
- * @param newView the {@link INode} to insert as the column spacer, which may be null
- * (in which case a spacer is automatically created)
- * @param columnWidthDp the width, in device independent pixels, of the column to be
- * added (which may be {@link #UNDEFINED}
- * @param split if true, split the existing column into two at the given x position
- * @param row the row to add the newView to
- * @param x the x position of the column we're inserting
- * @return the column spacer
- */
- public INode addColumn(int newColumn, INode newView, int columnWidthDp,
- boolean split, int row, int x) {
- // Insert a new column
- actualColumnCount++;
- if (declaredColumnCount != UNDEFINED) {
- declaredColumnCount++;
- setGridAttribute(layout, ATTR_COLUMN_COUNT, declaredColumnCount);
- }
-
- boolean isLastColumn = true;
- for (ViewData view : mChildViews) {
- if (view.column >= newColumn) {
- isLastColumn = false;
- break;
- }
- }
-
- for (ViewData view : mChildViews) {
- boolean columnSpanSet = false;
-
- int endColumn = view.column + view.columnSpan;
- if (view.column >= newColumn || endColumn == newColumn) {
- if (view.column == newColumn || endColumn == newColumn) {
- //if (view.row == 0) {
- if (newView == null && !isLastColumn) {
- // Insert a new spacer
- int index = getChildIndex(layout.getChildren(), view.node);
- assert view.index == index; // TODO: Get rid of getter
- if (endColumn == newColumn) {
- // This cell -ends- at the desired position: insert it after
- index++;
- }
-
- ViewData newViewData = addSpacer(layout, index,
- split ? row : UNDEFINED,
- split ? newColumn - 1 : UNDEFINED,
- columnWidthDp != UNDEFINED ? columnWidthDp : DEFAULT_CELL_WIDTH,
- DEFAULT_CELL_HEIGHT);
- newViewData.column = newColumn - 1;
- newViewData.row = row;
- newView = newViewData.node;
- }
-
- // Set the actual row number on the first cell on the new row.
- // This means we don't really need the spacer above to imply
- // the new row number, but we use the spacer to assign the row
- // some height.
- if (view.column == newColumn) {
- view.column++;
- setGridAttribute(view.node, ATTR_LAYOUT_COLUMN, view.column);
- } // else: endColumn == newColumn: handled below
- } else if (getGridAttribute(view.node, ATTR_LAYOUT_COLUMN) != null) {
- view.column++;
- setGridAttribute(view.node, ATTR_LAYOUT_COLUMN, view.column);
- }
- } else if (endColumn > newColumn) {
- view.columnSpan++;
- setColumnSpanAttribute(view.node, view.columnSpan);
- columnSpanSet = true;
- }
-
- if (split && !columnSpanSet && view.node.getBounds().x2() > x) {
- if (view.node.getBounds().x < x) {
- view.columnSpan++;
- setColumnSpanAttribute(view.node, view.columnSpan);
- }
- }
- }
-
- // Hardcode the row numbers if the last column is a new column such that
- // they don't jump back to backfill the previous row's new last cell
- if (isLastColumn) {
- for (ViewData view : mChildViews) {
- if (view.column == 0 && view.row > 0) {
- setGridAttribute(view.node, ATTR_LAYOUT_ROW, view.row);
- }
- }
- if (split) {
- assert newView == null;
- addSpacer(layout, -1, row, newColumn -1,
- columnWidthDp != UNDEFINED ? columnWidthDp : DEFAULT_CELL_WIDTH,
- SPACER_SIZE_DP);
- }
- }
-
- return newView;
- }
-
- /**
- * Removes the columns containing the given selection
- *
- * @param selectedChildren a list of nodes whose columns should be deleted
- */
- public void removeColumns(List<? extends INode> selectedChildren) {
- if (selectedChildren.size() == 0) {
- return;
- }
-
- // Figure out which columns should be removed
- Set<Integer> removeColumns = new HashSet<Integer>();
- Set<ViewData> removedViews = new HashSet<ViewData>();
- for (INode child : selectedChildren) {
- ViewData view = getView(child);
- removedViews.add(view);
- removeColumns.add(view.column);
- }
- // Sort them in descending order such that we can process each
- // deletion independently
- List<Integer> removed = new ArrayList<Integer>(removeColumns);
- Collections.sort(removed, Collections.reverseOrder());
-
- for (int removedColumn : removed) {
- // Remove column.
- // First, adjust column count.
- // TODO: Don't do this if the column being deleted is outside
- // the declared column range!
- // TODO: Do this under a write lock? / editXml lock?
- actualColumnCount--;
- if (declaredColumnCount != UNDEFINED) {
- declaredColumnCount--;
- }
-
- // Remove any elements that begin in the deleted columns...
- // If they have colspan > 1, then we must insert a spacer instead.
- // For any other elements that overlap, we need to subtract from the span.
-
- for (ViewData view : mChildViews) {
- if (view.column == removedColumn) {
- int index = getChildIndex(layout.getChildren(), view.node);
- assert view.index == index; // TODO: Get rid of getter
- if (view.columnSpan > 1) {
- // Make a new spacer which is the width of the following
- // columns
- int columnWidth = getColumnWidth(removedColumn, view.columnSpan) -
- getColumnWidth(removedColumn, 1);
- int columnWidthDip = mRulesEngine.pxToDp(columnWidth);
- ViewData spacer = addSpacer(layout, index, UNDEFINED, UNDEFINED,
- columnWidthDip, SPACER_SIZE_DP);
- spacer.row = 0;
- spacer.column = removedColumn;
- }
- layout.removeChild(view.node);
- } else if (view.column < removedColumn
- && view.column + view.columnSpan > removedColumn) {
- // Subtract column span to skip this item
- view.columnSpan--;
- setColumnSpanAttribute(view.node, view.columnSpan);
- } else if (view.column > removedColumn) {
- view.column--;
- if (getGridAttribute(view.node, ATTR_LAYOUT_COLUMN) != null) {
- setGridAttribute(view.node, ATTR_LAYOUT_COLUMN, view.column);
- }
- }
- }
- }
-
- // Remove children from child list!
- if (removedViews.size() <= 2) {
- mChildViews.removeAll(removedViews);
- } else {
- List<ViewData> remaining =
- new ArrayList<ViewData>(mChildViews.size() - removedViews.size());
- for (ViewData view : mChildViews) {
- if (!removedViews.contains(view)) {
- remaining.add(view);
- }
- }
- mChildViews = remaining;
- }
-
- //if (declaredColumnCount != UNDEFINED) {
- setGridAttribute(layout, ATTR_COLUMN_COUNT, actualColumnCount);
- //}
-
- }
-
- /**
- * Add a new row.
- *
- * @param selectedChildren if null or empty, add the row at the bottom of the grid,
- * and otherwise add it before the row of the first selected child
- * @return the newly added row spacer
- */
- public INode addRow(List<? extends INode> selectedChildren) {
- // Determine insert index
- int newRow = actualRowCount;
- if (selectedChildren.size() > 0) {
- INode first = selectedChildren.get(0);
- ViewData view = getView(first);
- newRow = view.row;
- }
-
- INode newView = addRow(newRow, null, UNDEFINED, false, UNDEFINED, UNDEFINED);
- if (newView != null) {
- mRulesEngine.select(Collections.singletonList(newView));
- }
-
- return newView;
- }
-
- /**
- * Adds a new column.
- *
- * @param newRow the row index to insert before
- * @param newView the {@link INode} to insert as the row spacer, which may be null (in
- * which case a spacer is automatically created)
- * @param rowHeightDp the height, in device independent pixels, of the row to be added
- * (which may be {@link #UNDEFINED}
- * @param split if true, split the existing row into two at the given y position
- * @param column the column to add the newView to
- * @param y the y position of the row we're inserting
- * @return the row spacer
- */
- public INode addRow(int newRow, INode newView, int rowHeightDp, boolean split,
- int column, int y) {
- actualRowCount++;
- if (declaredRowCount != UNDEFINED) {
- declaredRowCount++;
- setGridAttribute(layout, ATTR_ROW_COUNT, declaredRowCount);
- }
-
- boolean added = false;
- for (ViewData view : mChildViews) {
- if (view.row >= newRow) {
- // Adjust the column count
- if (view.row == newRow && view.column == 0) {
- // Insert a new spacer
- if (newView == null) {
- int index = getChildIndex(layout.getChildren(), view.node);
- assert view.index == index; // TODO: Get rid of getter
- if (declaredColumnCount != UNDEFINED && !split) {
- setGridAttribute(layout, ATTR_COLUMN_COUNT, declaredColumnCount);
- }
- ViewData newViewData = addSpacer(layout, index,
- split ? newRow - 1 : UNDEFINED,
- split ? column : UNDEFINED,
- SPACER_SIZE_DP,
- rowHeightDp != UNDEFINED ? rowHeightDp : DEFAULT_CELL_HEIGHT);
- newViewData.column = column;
- newViewData.row = newRow - 1;
- newView = newViewData.node;
- }
-
- // Set the actual row number on the first cell on the new row.
- // This means we don't really need the spacer above to imply
- // the new row number, but we use the spacer to assign the row
- // some height.
- view.row++;
- setGridAttribute(view.node, ATTR_LAYOUT_ROW, view.row);
-
- added = true;
- } else if (getGridAttribute(view.node, ATTR_LAYOUT_ROW) != null) {
- view.row++;
- setGridAttribute(view.node, ATTR_LAYOUT_ROW, view.row);
- }
- } else {
- int endRow = view.row + view.rowSpan;
- if (endRow > newRow) {
- view.rowSpan++;
- setRowSpanAttribute(view.node, view.rowSpan);
- } else if (split && view.node.getBounds().y2() > y) {
- if (view.node.getBounds().y < y) {
- view.rowSpan++;
- setRowSpanAttribute(view.node, view.rowSpan);
- }
- }
- }
- }
-
- if (!added) {
- // Append a row at the end
- if (newView == null) {
- ViewData newViewData = addSpacer(layout, -1, UNDEFINED, UNDEFINED,
- SPACER_SIZE_DP,
- rowHeightDp != UNDEFINED ? rowHeightDp : DEFAULT_CELL_HEIGHT);
- newViewData.column = column;
- // TODO: MAke sure this row number is right!
- newViewData.row = split ? newRow - 1 : newRow;
- newView = newViewData.node;
- }
- if (declaredColumnCount != UNDEFINED && !split) {
- setGridAttribute(layout, ATTR_COLUMN_COUNT, declaredColumnCount);
- }
- if (split) {
- setGridAttribute(newView, ATTR_LAYOUT_ROW, newRow - 1);
- setGridAttribute(newView, ATTR_LAYOUT_COLUMN, column);
- }
- }
-
- return newView;
- }
-
- /**
- * Removes the rows containing the given selection
- *
- * @param selectedChildren a list of nodes whose rows should be deleted
- */
- public void removeRows(List<? extends INode> selectedChildren) {
- if (selectedChildren.size() == 0) {
- return;
- }
-
- // Figure out which rows should be removed
- Set<ViewData> removedViews = new HashSet<ViewData>();
- Set<Integer> removedRows = new HashSet<Integer>();
- for (INode child : selectedChildren) {
- ViewData view = getView(child);
- removedViews.add(view);
- removedRows.add(view.row);
- }
- // Sort them in descending order such that we can process each
- // deletion independently
- List<Integer> removed = new ArrayList<Integer>(removedRows);
- Collections.sort(removed, Collections.reverseOrder());
-
- for (int removedRow : removed) {
- // Remove row.
- // First, adjust row count.
- // TODO: Don't do this if the row being deleted is outside
- // the declared row range!
- actualRowCount--;
- if (declaredRowCount != UNDEFINED) {
- declaredRowCount--;
- setGridAttribute(layout, ATTR_ROW_COUNT, declaredRowCount);
- }
-
- // Remove any elements that begin in the deleted rows...
- // If they have colspan > 1, then we must hardcode a new row number
- // instead.
- // For any other elements that overlap, we need to subtract from the span.
-
- for (ViewData view : mChildViews) {
- if (view.row == removedRow) {
- // We don't have to worry about a rowSpan > 1 here, because even
- // if it is, those rowspans are not used to assign default row/column
- // positions for other cells
-// TODO: Check this; it differs from the removeColumns logic!
- layout.removeChild(view.node);
- } else if (view.row > removedRow) {
- view.row--;
- if (getGridAttribute(view.node, ATTR_LAYOUT_ROW) != null) {
- setGridAttribute(view.node, ATTR_LAYOUT_ROW, view.row);
- }
- } else if (view.row < removedRow
- && view.row + view.rowSpan > removedRow) {
- // Subtract row span to skip this item
- view.rowSpan--;
- setRowSpanAttribute(view.node, view.rowSpan);
- }
- }
- }
-
- // Remove children from child list!
- if (removedViews.size() <= 2) {
- mChildViews.removeAll(removedViews);
- } else {
- List<ViewData> remaining =
- new ArrayList<ViewData>(mChildViews.size() - removedViews.size());
- for (ViewData view : mChildViews) {
- if (!removedViews.contains(view)) {
- remaining.add(view);
- }
- }
- mChildViews = remaining;
- }
- }
-
- /**
- * Returns the row containing the given y line
- *
- * @param y the vertical position
- * @return the row containing the given line
- */
- public int getRow(int y) {
- int row = Arrays.binarySearch(mTop, y);
- if (row == -1) {
- // Smaller than the first element; just use the first row
- return 0;
- } else if (row < 0) {
- row = -(row + 2);
- }
-
- return row;
- }
-
- /**
- * Returns the column containing the given x line
- *
- * @param x the horizontal position
- * @return the column containing the given line
- */
- public int getColumn(int x) {
- int column = Arrays.binarySearch(mLeft, x);
- if (column == -1) {
- // Smaller than the first element; just use the first column
- return 0;
- } else if (column < 0) {
- column = -(column + 2);
- }
-
- return column;
- }
-
- /**
- * Returns the closest row to the given y line. This is
- * either the row containing the line, or the row below it.
- *
- * @param y the vertical position
- * @return the closest row
- */
- public int getClosestRow(int y) {
- int row = Arrays.binarySearch(mTop, y);
- if (row == -1) {
- // Smaller than the first element; just use the first column
- return 0;
- } else if (row < 0) {
- row = -(row + 2);
- }
-
- if (getRowDistance(row, y) < getRowDistance(row + 1, y)) {
- return row;
- } else {
- return row + 1;
- }
- }
-
- /**
- * Returns the closest column to the given x line. This is
- * either the column containing the line, or the column following it.
- *
- * @param x the horizontal position
- * @return the closest column
- */
- public int getClosestColumn(int x) {
- int column = Arrays.binarySearch(mLeft, x);
- if (column == -1) {
- // Smaller than the first element; just use the first column
- return 0;
- } else if (column < 0) {
- column = -(column + 2);
- }
-
- if (getColumnDistance(column, x) < getColumnDistance(column + 1, x)) {
- return column;
- } else {
- return column + 1;
- }
- }
-
- /**
- * Returns the distance between the given x position and the beginning of the given column
- *
- * @param column the column
- * @param x the x position
- * @return the distance between the two
- */
- public int getColumnDistance(int column, int x) {
- return abs(getColumnX(column) - x);
- }
-
- /**
- * Returns the actual width of the given column. This returns the difference between
- * the rightmost edge of the views (not including spacers) and the left edge of the
- * column.
- *
- * @param column the column
- * @return the actual width of the non-spacer views in the column
- */
- public int getColumnActualWidth(int column) {
- return getColumnMaxX(column) - getColumnX(column);
- }
-
- /**
- * Returns the distance between the given y position and the top of the given row
- *
- * @param row the row
- * @param y the y position
- * @return the distance between the two
- */
- public int getRowDistance(int row, int y) {
- return abs(getRowY(row) - y);
- }
-
- /**
- * Returns the y position of the top of the given row
- *
- * @param row the target row
- * @return the y position of its top edge
- */
- public int getRowY(int row) {
- return mTop[min(mTop.length - 1, max(0, row))];
- }
-
- /**
- * Returns the bottom-most edge of any of the non-spacer children in the given row
- *
- * @param row the target row
- * @return the bottom-most edge of any of the non-spacer children in the row
- */
- public int getRowMaxY(int row) {
- return mMaxBottom[min(mMaxBottom.length - 1, max(0, row))];
- }
-
- /**
- * Returns the actual height of the given row. This returns the difference between
- * the bottom-most edge of the views (not including spacers) and the top edge of the
- * row.
- *
- * @param row the row
- * @return the actual height of the non-spacer views in the row
- */
- public int getRowActualHeight(int row) {
- return getRowMaxY(row) - getRowY(row);
- }
-
- /**
- * Returns a list of all the nodes that intersects the rows in the range
- * {@code y1 <= y <= y2}.
- *
- * @param y1 the starting y, inclusive
- * @param y2 the ending y, inclusive
- * @return a list of nodes intersecting the given rows, never null but possibly empty
- */
- public Collection<INode> getIntersectsRow(int y1, int y2) {
- List<INode> nodes = new ArrayList<INode>();
-
- for (ViewData view : mChildViews) {
- if (!view.isSpacer()) {
- Rect bounds = view.node.getBounds();
- if (bounds.y2() >= y1 && bounds.y <= y2) {
- nodes.add(view.node);
- }
- }
- }
-
- return nodes;
- }
-
- /**
- * Returns the height of the given row or rows (if the rowSpan is greater than 1)
- *
- * @param row the target row
- * @param rowSpan the row span
- * @return the height in pixels of the given rows
- */
- public int getRowHeight(int row, int rowSpan) {
- return getRowY(row + rowSpan) - getRowY(row);
- }
-
- /**
- * Returns the x position of the left edge of the given column
- *
- * @param column the target column
- * @return the x position of its left edge
- */
- public int getColumnX(int column) {
- return mLeft[min(mLeft.length - 1, max(0, column))];
- }
-
- /**
- * Returns the rightmost edge of any of the non-spacer children in the given row
- *
- * @param column the target column
- * @return the rightmost edge of any of the non-spacer children in the column
- */
- public int getColumnMaxX(int column) {
- return mMaxRight[min(mMaxRight.length - 1, max(0, column))];
- }
-
- /**
- * Returns the width of the given column or columns (if the columnSpan is greater than 1)
- *
- * @param column the target column
- * @param columnSpan the column span
- * @return the width in pixels of the given columns
- */
- public int getColumnWidth(int column, int columnSpan) {
- return getColumnX(column + columnSpan) - getColumnX(column);
- }
-
- /**
- * Returns the bounds of the cell at the given row and column position, with the given
- * row and column spans.
- *
- * @param row the target row
- * @param column the target column
- * @param rowSpan the row span
- * @param columnSpan the column span
- * @return the bounds, in pixels, of the given cell
- */
- public Rect getCellBounds(int row, int column, int rowSpan, int columnSpan) {
- return new Rect(getColumnX(column), getRowY(row),
- getColumnWidth(column, columnSpan),
- getRowHeight(row, rowSpan));
- }
-
- /**
- * Produces a display of view contents along with the pixel positions of each
- * row/column, like the following (used for diagnostics only)
- *
- * <pre>
- * |0 |49 |143 |192 |240
- * 36| | |button2 |
- * 72| |radioButton1 |button2 |
- * 74|button1 |radioButton1 |button2 |
- * 108|button1 | |button2 |
- * 110| | |button2 |
- * 149| | | |
- * 320
- * </pre>
- */
- @Override
- public String toString() {
- // Dump out the view table
- int cellWidth = 25;
-
- List<List<List<ViewData>>> rowList = new ArrayList<List<List<ViewData>>>(mTop.length);
- for (int row = 0; row < mTop.length; row++) {
- List<List<ViewData>> columnList = new ArrayList<List<ViewData>>(mLeft.length);
- for (int col = 0; col < mLeft.length; col++) {
- columnList.add(new ArrayList<ViewData>(4));
- }
- rowList.add(columnList);
- }
- for (ViewData view : mChildViews) {
- for (int i = 0; i < view.rowSpan; i++) {
- if (view.row + i > mTop.length) { // Guard against bogus span values
- break;
- }
- if (rowList.size() <= view.row + i) {
- break;
- }
- for (int j = 0; j < view.columnSpan; j++) {
- List<List<ViewData>> columnList = rowList.get(view.row + i);
- if (columnList.size() <= view.column + j) {
- break;
- }
- columnList.get(view.column + j).add(view);
- }
- }
- }
-
- StringWriter stringWriter = new StringWriter();
- PrintWriter out = new PrintWriter(stringWriter);
- out.printf("%" + cellWidth + "s", ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- for (int col = 0; col < actualColumnCount + 1; col++) {
- out.printf("|%-" + (cellWidth - 1) + "d", mLeft[col]); //$NON-NLS-1$ //$NON-NLS-2$
- }
- out.printf("\n"); //$NON-NLS-1$
- for (int row = 0; row < actualRowCount + 1; row++) {
- out.printf("%" + cellWidth + "d", mTop[row]); //$NON-NLS-1$ //$NON-NLS-2$
- if (row == actualRowCount) {
- break;
- }
- for (int col = 0; col < actualColumnCount; col++) {
- List<ViewData> views = rowList.get(row).get(col);
-
- StringBuilder sb = new StringBuilder();
- for (ViewData view : views) {
- String id = view != null ? view.getId() : ""; //$NON-NLS-1$
- if (id.startsWith(NEW_ID_PREFIX)) {
- id = id.substring(NEW_ID_PREFIX.length());
- }
- if (id.length() > cellWidth - 2) {
- id = id.substring(0, cellWidth - 2);
- }
- if (sb.length() > 0) {
- sb.append(',');
- }
- sb.append(id);
- }
- String cellString = sb.toString();
- if (cellString.contains(",") && cellString.length() > cellWidth - 2) { //$NON-NLS-1$
- cellString = cellString.substring(0, cellWidth - 6) + "...,"; //$NON-NLS-1$
- }
- out.printf("|%-" + (cellWidth - 2) + "s ", cellString); //$NON-NLS-1$ //$NON-NLS-2$
- }
- out.printf("\n"); //$NON-NLS-1$
- }
-
- out.flush();
- return stringWriter.toString();
- }
-
- /**
- * Split a cell into two or three columns.
- *
- * @param newColumn The column number to insert before
- * @param insertMarginColumn If false, then the cell at newColumn -1 is split with the
- * left part taking up exactly columnWidthDp dips. If true, then the column
- * is split twice; the left part is the implicit width of the column, the
- * new middle (margin) column is exactly the columnWidthDp size and the
- * right column is the remaining space of the old cell.
- * @param columnWidthDp The width of the column inserted before the new column (or if
- * insertMarginColumn is false, then the width of the margin column)
- * @param x the x coordinate of the new column
- */
- public void splitColumn(int newColumn, boolean insertMarginColumn, int columnWidthDp, int x) {
- actualColumnCount++;
-
- // Insert a new column
- if (declaredColumnCount != UNDEFINED) {
- declaredColumnCount++;
- if (insertMarginColumn) {
- declaredColumnCount++;
- }
- setGridAttribute(layout, ATTR_COLUMN_COUNT, declaredColumnCount);
- }
-
- // Are we inserting a new last column in the grid? That requires some special handling...
- boolean isLastColumn = true;
- for (ViewData view : mChildViews) {
- if (view.column >= newColumn) {
- isLastColumn = false;
- break;
- }
- }
-
- // Hardcode the row numbers if the last column is a new column such that
- // they don't jump back to backfill the previous row's new last cell:
- // TODO: Only do this for horizontal layouts!
- if (isLastColumn) {
- for (ViewData view : mChildViews) {
- if (view.column == 0 && view.row > 0) {
- if (getGridAttribute(view.node, ATTR_LAYOUT_ROW) == null) {
- setGridAttribute(view.node, ATTR_LAYOUT_ROW, view.row);
- }
- }
- }
- }
-
- // Find the spacer which marks this column, and if found, mark it as a split
- ViewData prevColumnSpacer = null;
- for (ViewData view : mChildViews) {
- if (view.column == newColumn - 1 && view.isColumnSpacer()) {
- prevColumnSpacer = view;
- break;
- }
- }
-
- // Process all existing grid elements:
- // * Increase column numbers for all columns that have a hardcoded column number
- // greater than the new column
- // * Set an explicit column=0 where needed (TODO: Implement this)
- // * Increase the columnSpan for all columns that overlap the newly inserted column edge
- // * Split the spacer which defined the size of this column into two
- // (and if not found, create a new spacer)
- //
- for (ViewData view : mChildViews) {
- if (view == prevColumnSpacer) {
- continue;
- }
-
- INode node = view.node;
- int column = view.column;
- if (column > newColumn || (column == newColumn && view.node.getBounds().x2() > x)) {
- // ALWAYS set the column, because
- // (1) if it has been set, it needs to be corrected
- // (2) if it has not been set, it needs to be set to cause this column
- // to skip over the new column (there may be no views for the new
- // column on this row).
- // TODO: Enhance this such that we only set the column to a skip number
- // where necessary, e.g. only on the FIRST view on this row following the
- // skipped column!
-
- //if (getGridAttribute(node, ATTR_LAYOUT_COLUMN) != null) {
- view.column += insertMarginColumn ? 2 : 1;
- setGridAttribute(node, ATTR_LAYOUT_COLUMN, view.column);
- //}
- } else if (!view.isSpacer()) {
- // Adjust the column span? We must increase it if
- // (1) the new column is inside the range [column, column + columnSpan]
- // (2) the new column is within the last cell in the column span,
- // and the exact X location of the split is within the horizontal
- // *bounds* of this node (provided it has gravity=left)
- // (3) the new column is within the last cell and the cell has gravity
- // right or gravity center
- int endColumn = column + view.columnSpan;
- if (endColumn > newColumn
- || endColumn == newColumn && (view.node.getBounds().x2() > x
- || GravityHelper.isConstrainedHorizontally(view.gravity)
- && !GravityHelper.isLeftAligned(view.gravity))) {
- // This cell spans the new insert position, so increment the column span
- view.columnSpan += insertMarginColumn ? 2 : 1;
- setColumnSpanAttribute(node, view.columnSpan);
- }
- }
- }
-
- // Insert new spacer:
- if (prevColumnSpacer != null) {
- int px = getColumnWidth(newColumn - 1, 1);
- if (insertMarginColumn || columnWidthDp == 0) {
- px -= getColumnActualWidth(newColumn - 1);
- }
- int dp = mRulesEngine.pxToDp(px);
- int remaining = dp - columnWidthDp;
- if (remaining > 0) {
- prevColumnSpacer.node.setAttribute(ANDROID_URI, ATTR_LAYOUT_WIDTH,
- String.format(VALUE_N_DP, remaining));
- prevColumnSpacer.column = insertMarginColumn ? newColumn + 1 : newColumn;
- setGridAttribute(prevColumnSpacer.node, ATTR_LAYOUT_COLUMN,
- prevColumnSpacer.column);
- }
- }
-
- if (columnWidthDp > 0) {
- int index = prevColumnSpacer != null ? prevColumnSpacer.index : -1;
-
- addSpacer(layout, index, 0, insertMarginColumn ? newColumn : newColumn - 1,
- columnWidthDp, SPACER_SIZE_DP);
- }
- }
-
- /**
- * Split a cell into two or three rows.
- *
- * @param newRow The row number to insert before
- * @param insertMarginRow If false, then the cell at newRow -1 is split with the above
- * part taking up exactly rowHeightDp dips. If true, then the row is split
- * twice; the top part is the implicit height of the row, the new middle
- * (margin) row is exactly the rowHeightDp size and the bottom column is
- * the remaining space of the old cell.
- * @param rowHeightDp The height of the row inserted before the new row (or if
- * insertMarginRow is false, then the height of the margin row)
- * @param y the y coordinate of the new row
- */
- public void splitRow(int newRow, boolean insertMarginRow, int rowHeightDp, int y) {
- actualRowCount++;
-
- // Insert a new row
- if (declaredRowCount != UNDEFINED) {
- declaredRowCount++;
- if (insertMarginRow) {
- declaredRowCount++;
- }
- setGridAttribute(layout, ATTR_ROW_COUNT, declaredRowCount);
- }
-
- // Find the spacer which marks this row, and if found, mark it as a split
- ViewData prevRowSpacer = null;
- for (ViewData view : mChildViews) {
- if (view.row == newRow - 1 && view.isRowSpacer()) {
- prevRowSpacer = view;
- break;
- }
- }
-
- // Se splitColumn() for details
- for (ViewData view : mChildViews) {
- if (view == prevRowSpacer) {
- continue;
- }
-
- INode node = view.node;
- int row = view.row;
- if (row > newRow || (row == newRow && view.node.getBounds().y2() > y)) {
- //if (getGridAttribute(node, ATTR_LAYOUT_ROW) != null) {
- view.row += insertMarginRow ? 2 : 1;
- setGridAttribute(node, ATTR_LAYOUT_ROW, view.row);
- //}
- } else if (!view.isSpacer()) {
- int endRow = row + view.rowSpan;
- if (endRow > newRow
- || endRow == newRow && (view.node.getBounds().y2() > y
- || GravityHelper.isConstrainedVertically(view.gravity)
- && !GravityHelper.isTopAligned(view.gravity))) {
- // This cell spans the new insert position, so increment the row span
- view.rowSpan += insertMarginRow ? 2 : 1;
- setRowSpanAttribute(node, view.rowSpan);
- }
- }
- }
-
- // Insert new spacer:
- if (prevRowSpacer != null) {
- int px = getRowHeight(newRow - 1, 1);
- if (insertMarginRow || rowHeightDp == 0) {
- px -= getRowActualHeight(newRow - 1);
- }
- int dp = mRulesEngine.pxToDp(px);
- int remaining = dp - rowHeightDp;
- if (remaining > 0) {
- prevRowSpacer.node.setAttribute(ANDROID_URI, ATTR_LAYOUT_HEIGHT,
- String.format(VALUE_N_DP, remaining));
- prevRowSpacer.row = insertMarginRow ? newRow + 1 : newRow;
- setGridAttribute(prevRowSpacer.node, ATTR_LAYOUT_ROW, prevRowSpacer.row);
- }
- }
-
- if (rowHeightDp > 0) {
- int index = prevRowSpacer != null ? prevRowSpacer.index : -1;
- addSpacer(layout, index, insertMarginRow ? newRow : newRow - 1,
- 0, SPACER_SIZE_DP, rowHeightDp);
- }
- }
-
- /**
- * Data about a view in a table; this is not the same as a cell because multiple views
- * can share a single cell, and a view can span many cells.
- */
- public class ViewData {
- public final INode node;
- public final int index;
- public int row;
- public int column;
- public int rowSpan;
- public int columnSpan;
- public int gravity;
-
- ViewData(INode n, int index) {
- node = n;
- this.index = index;
-
- column = getGridAttribute(n, ATTR_LAYOUT_COLUMN, UNDEFINED);
- columnSpan = getGridAttribute(n, ATTR_LAYOUT_COLUMN_SPAN, 1);
- row = getGridAttribute(n, ATTR_LAYOUT_ROW, UNDEFINED);
- rowSpan = getGridAttribute(n, ATTR_LAYOUT_ROW_SPAN, 1);
- gravity = GravityHelper.getGravity(getGridAttribute(n, ATTR_LAYOUT_GRAVITY), 0);
- }
-
- /** Applies the column and row fields into the XML model */
- void applyPositionAttributes() {
- setGridAttribute(node, ATTR_LAYOUT_COLUMN, column);
- setGridAttribute(node, ATTR_LAYOUT_ROW, row);
- }
-
- /** Returns the id of this node, or makes one up for display purposes */
- String getId() {
- String id = node.getStringAttr(ANDROID_URI, ATTR_ID);
- if (id == null) {
- id = "<unknownid>"; //$NON-NLS-1$
- String fqn = node.getFqcn();
- fqn = fqn.substring(fqn.lastIndexOf('.') + 1);
- id = fqn + "-"
- + Integer.toString(System.identityHashCode(node)).substring(0, 3);
- }
-
- return id;
- }
-
- /** Returns true if this {@link ViewData} represents a spacer */
- boolean isSpacer() {
- return isSpace(node.getFqcn());
- }
-
- /**
- * Returns true if this {@link ViewData} represents a column spacer
- */
- boolean isColumnSpacer() {
- return isSpacer() &&
- // Any spacer not found in column 0 is a column spacer since we
- // place all horizontal spacers in column 0
- ((column > 0)
- // TODO: Find a cleaner way. Maybe set ids on the elements in (0,0) and
- // for column distinguish by id. Or at least only do this for column 0!
- || !SPACER_SIZE.equals(node.getStringAttr(ANDROID_URI, ATTR_LAYOUT_WIDTH)));
- }
-
- /**
- * Returns true if this {@link ViewData} represents a row spacer
- */
- boolean isRowSpacer() {
- return isSpacer() &&
- // Any spacer not found in row 0 is a row spacer since we
- // place all vertical spacers in row 0
- ((row > 0)
- // TODO: Find a cleaner way. Maybe set ids on the elements in (0,0) and
- // for column distinguish by id. Or at least only do this for column 0!
- || !SPACER_SIZE.equals(node.getStringAttr(ANDROID_URI, ATTR_LAYOUT_HEIGHT)));
- }
- }
-
- /**
- * Sets the column span of the given node to the given value (or if the value is 1,
- * removes it)
- *
- * @param node the target node
- * @param span the new column span
- */
- public void setColumnSpanAttribute(INode node, int span) {
- setGridAttribute(node, ATTR_LAYOUT_COLUMN_SPAN, span > 1 ? Integer.toString(span) : null);
- }
-
- /**
- * Sets the row span of the given node to the given value (or if the value is 1,
- * removes it)
- *
- * @param node the target node
- * @param span the new row span
- */
- public void setRowSpanAttribute(INode node, int span) {
- setGridAttribute(node, ATTR_LAYOUT_ROW_SPAN, span > 1 ? Integer.toString(span) : null);
- }
-
- /** Returns the index of the given target node in the given child node array */
- static int getChildIndex(INode[] children, INode target) {
- int index = 0;
- for (INode child : children) {
- if (child == target) {
- return index;
- }
- index++;
- }
-
- return -1;
- }
-
- /**
- * Update the model to account for the given nodes getting deleted. The nodes
- * are not actually deleted by this method; that is assumed to be performed by the
- * caller. Instead this method performs whatever model updates are necessary to
- * preserve the grid structure.
- *
- * @param nodes the nodes to be deleted
- */
- public void onDeleted(@NonNull List<INode> nodes) {
- if (nodes.size() == 0) {
- return;
- }
-
- // Attempt to clean up spacer objects for any newly-empty rows or columns
- // as the result of this deletion
-
- Set<INode> deleted = new HashSet<INode>();
-
- for (INode child : nodes) {
- // We don't care about deletion of spacers
- String fqcn = child.getFqcn();
- if (fqcn.equals(FQCN_SPACE) || fqcn.equals(FQCN_SPACE_V7)) {
- continue;
- }
- deleted.add(child);
- }
-
- Set<Integer> usedColumns = new HashSet<Integer>(actualColumnCount);
- Set<Integer> usedRows = new HashSet<Integer>(actualRowCount);
- Multimap<Integer, ViewData> columnSpacers = ArrayListMultimap.create(actualColumnCount, 2);
- Multimap<Integer, ViewData> rowSpacers = ArrayListMultimap.create(actualRowCount, 2);
- Set<ViewData> removedViews = new HashSet<ViewData>();
-
- for (ViewData view : mChildViews) {
- if (deleted.contains(view.node)) {
- removedViews.add(view);
- } else if (view.isColumnSpacer()) {
- columnSpacers.put(view.column, view);
- } else if (view.isRowSpacer()) {
- rowSpacers.put(view.row, view);
- } else {
- usedColumns.add(Integer.valueOf(view.column));
- usedRows.add(Integer.valueOf(view.row));
- }
- }
-
- if (usedColumns.size() == 0 || usedRows.size() == 0) {
- // No more views - just remove all the spacers
- for (ViewData spacer : columnSpacers.values()) {
- layout.removeChild(spacer.node);
- }
- for (ViewData spacer : rowSpacers.values()) {
- layout.removeChild(spacer.node);
- }
- mChildViews.clear();
- actualColumnCount = 0;
- declaredColumnCount = 2;
- actualRowCount = 0;
- declaredRowCount = UNDEFINED;
- setGridAttribute(layout, ATTR_COLUMN_COUNT, 2);
-
- return;
- }
-
- // Determine columns to introduce spacers into:
- // This is tricky; I should NOT combine spacers if there are cells tied to
- // individual ones
-
- // TODO: Invalidate column sizes too! Otherwise repeated updates might get confused!
- // Similarly, inserts need to do the same!
-
- // Produce map of old column numbers to new column numbers
- // Collapse regions of consecutive space and non-space ranges together
- int[] columnMap = new int[actualColumnCount + 1]; // +1: Easily handle columnSpans as well
- int newColumn = 0;
- boolean prevUsed = usedColumns.contains(0);
- for (int column = 1; column < actualColumnCount; column++) {
- boolean used = usedColumns.contains(column);
- if (used || prevUsed != used) {
- newColumn++;
- prevUsed = used;
- }
- columnMap[column] = newColumn;
- }
- newColumn++;
- columnMap[actualColumnCount] = newColumn;
- assert columnMap[0] == 0;
-
- int[] rowMap = new int[actualRowCount + 1]; // +1: Easily handle rowSpans as well
- int newRow = 0;
- prevUsed = usedRows.contains(0);
- for (int row = 1; row < actualRowCount; row++) {
- boolean used = usedRows.contains(row);
- if (used || prevUsed != used) {
- newRow++;
- prevUsed = used;
- }
- rowMap[row] = newRow;
- }
- newRow++;
- rowMap[actualRowCount] = newRow;
- assert rowMap[0] == 0;
-
-
- // Adjust column and row numbers to account for deletions: for a given cell, if it
- // is to the right of a deleted column, reduce its column number, and if it only
- // spans across the deleted column, reduce its column span.
- for (ViewData view : mChildViews) {
- if (removedViews.contains(view)) {
- continue;
- }
- int newColumnStart = columnMap[Math.min(columnMap.length - 1, view.column)];
- // Gracefully handle rogue/invalid columnSpans in the XML
- int newColumnEnd = columnMap[Math.min(columnMap.length - 1,
- view.column + view.columnSpan)];
- if (newColumnStart != view.column) {
- view.column = newColumnStart;
- setGridAttribute(view.node, ATTR_LAYOUT_COLUMN, view.column);
- }
-
- int columnSpan = newColumnEnd - newColumnStart;
- if (columnSpan != view.columnSpan) {
- if (columnSpan >= 1) {
- view.columnSpan = columnSpan;
- setColumnSpanAttribute(view.node, view.columnSpan);
- } // else: merging spacing columns together
- }
-
-
- int newRowStart = rowMap[Math.min(rowMap.length - 1, view.row)];
- int newRowEnd = rowMap[Math.min(rowMap.length - 1, view.row + view.rowSpan)];
- if (newRowStart != view.row) {
- view.row = newRowStart;
- setGridAttribute(view.node, ATTR_LAYOUT_ROW, view.row);
- }
-
- int rowSpan = newRowEnd - newRowStart;
- if (rowSpan != view.rowSpan) {
- if (rowSpan >= 1) {
- view.rowSpan = rowSpan;
- setRowSpanAttribute(view.node, view.rowSpan);
- } // else: merging spacing rows together
- }
- }
-
- // Merge spacers (and add spacers for newly empty columns)
- int start = 0;
- while (start < actualColumnCount) {
- // Find next unused span
- while (start < actualColumnCount && usedColumns.contains(start)) {
- start++;
- }
- if (start == actualColumnCount) {
- break;
- }
- assert !usedColumns.contains(start);
- // Find the next span of unused columns and produce a SINGLE
- // spacer for that range (unless it's a zero-sized columns)
- int end = start + 1;
- for (; end < actualColumnCount; end++) {
- if (usedColumns.contains(end)) {
- break;
- }
- }
-
- // Add up column sizes
- int width = getColumnWidth(start, end - start);
-
- // Find all spacers: the first one found should be moved to the start column
- // and assigned to the full height of the columns, and
- // the column count reduced by the corresponding amount
-
- // TODO: if width = 0, fully remove
-
- boolean isFirstSpacer = true;
- for (int column = start; column < end; column++) {
- Collection<ViewData> spacers = columnSpacers.get(column);
- if (spacers != null && !spacers.isEmpty()) {
- // Avoid ConcurrentModificationException since we're inserting into the
- // map within this loop (always at a different index, but the map doesn't
- // know that)
- spacers = new ArrayList<ViewData>(spacers);
- for (ViewData spacer : spacers) {
- if (isFirstSpacer) {
- isFirstSpacer = false;
- spacer.column = columnMap[start];
- setGridAttribute(spacer.node, ATTR_LAYOUT_COLUMN, spacer.column);
- if (end - start > 1) {
- // Compute a merged width for all the spacers (not needed if
- // there's just one spacer; it should already have the correct width)
- int columnWidthDp = mRulesEngine.pxToDp(width);
- spacer.node.setAttribute(ANDROID_URI, ATTR_LAYOUT_WIDTH,
- String.format(VALUE_N_DP, columnWidthDp));
- }
- columnSpacers.put(start, spacer);
- } else {
- removedViews.add(spacer); // Mark for model removal
- layout.removeChild(spacer.node);
- }
- }
- }
- }
-
- if (isFirstSpacer) {
- // No spacer: create one
- int columnWidthDp = mRulesEngine.pxToDp(width);
- addSpacer(layout, -1, UNDEFINED, columnMap[start], columnWidthDp, DEFAULT_CELL_HEIGHT);
- }
-
- start = end;
- }
- actualColumnCount = newColumn;
-//if (usedColumns.contains(newColumn)) {
-// // TODO: This may be totally wrong for right aligned content!
-// actualColumnCount++;
-//}
-
- // Merge spacers for rows
- start = 0;
- while (start < actualRowCount) {
- // Find next unused span
- while (start < actualRowCount && usedRows.contains(start)) {
- start++;
- }
- if (start == actualRowCount) {
- break;
- }
- assert !usedRows.contains(start);
- // Find the next span of unused rows and produce a SINGLE
- // spacer for that range (unless it's a zero-sized rows)
- int end = start + 1;
- for (; end < actualRowCount; end++) {
- if (usedRows.contains(end)) {
- break;
- }
- }
-
- // Add up row sizes
- int height = getRowHeight(start, end - start);
-
- // Find all spacers: the first one found should be moved to the start row
- // and assigned to the full height of the rows, and
- // the row count reduced by the corresponding amount
-
- // TODO: if width = 0, fully remove
-
- boolean isFirstSpacer = true;
- for (int row = start; row < end; row++) {
- Collection<ViewData> spacers = rowSpacers.get(row);
- if (spacers != null && !spacers.isEmpty()) {
- // Avoid ConcurrentModificationException since we're inserting into the
- // map within this loop (always at a different index, but the map doesn't
- // know that)
- spacers = new ArrayList<ViewData>(spacers);
- for (ViewData spacer : spacers) {
- if (isFirstSpacer) {
- isFirstSpacer = false;
- spacer.row = rowMap[start];
- setGridAttribute(spacer.node, ATTR_LAYOUT_ROW, spacer.row);
- if (end - start > 1) {
- // Compute a merged width for all the spacers (not needed if
- // there's just one spacer; it should already have the correct height)
- int rowHeightDp = mRulesEngine.pxToDp(height);
- spacer.node.setAttribute(ANDROID_URI, ATTR_LAYOUT_HEIGHT,
- String.format(VALUE_N_DP, rowHeightDp));
- }
- rowSpacers.put(start, spacer);
- } else {
- removedViews.add(spacer); // Mark for model removal
- layout.removeChild(spacer.node);
- }
- }
- }
- }
-
- if (isFirstSpacer) {
- // No spacer: create one
- int rowWidthDp = mRulesEngine.pxToDp(height);
- addSpacer(layout, -1, rowMap[start], UNDEFINED, DEFAULT_CELL_WIDTH, rowWidthDp);
- }
-
- start = end;
- }
- actualRowCount = newRow;
-// if (usedRows.contains(newRow)) {
-// actualRowCount++;
-// }
-
- // Update the model: remove removed children from the view data list
- if (removedViews.size() <= 2) {
- mChildViews.removeAll(removedViews);
- } else {
- List<ViewData> remaining =
- new ArrayList<ViewData>(mChildViews.size() - removedViews.size());
- for (ViewData view : mChildViews) {
- if (!removedViews.contains(view)) {
- remaining.add(view);
- }
- }
- mChildViews = remaining;
- }
-
- // Update the final column and row declared attributes
- if (declaredColumnCount != UNDEFINED) {
- declaredColumnCount = actualColumnCount;
- setGridAttribute(layout, ATTR_COLUMN_COUNT, actualColumnCount);
- }
- if (declaredRowCount != UNDEFINED) {
- declaredRowCount = actualRowCount;
- setGridAttribute(layout, ATTR_ROW_COUNT, actualRowCount);
- }
- }
-
- /**
- * Adds a spacer to the given parent, at the given index.
- *
- * @param parent the GridLayout
- * @param index the index to insert the spacer at, or -1 to append
- * @param row the row to add the spacer to (or {@link #UNDEFINED} to not set a row yet
- * @param column the column to add the spacer to (or {@link #UNDEFINED} to not set a
- * column yet
- * @param widthDp the width in device independent pixels to assign to the spacer
- * @param heightDp the height in device independent pixels to assign to the spacer
- * @return the newly added spacer
- */
- ViewData addSpacer(INode parent, int index, int row, int column,
- int widthDp, int heightDp) {
- INode spacer;
-
- String tag = FQCN_SPACE;
- String gridLayout = parent.getFqcn();
- if (!gridLayout.equals(GRID_LAYOUT) && gridLayout.length() > GRID_LAYOUT.length()) {
- String pkg = gridLayout.substring(0, gridLayout.length() - GRID_LAYOUT.length());
- tag = pkg + SPACE;
- }
- if (index != -1) {
- spacer = parent.insertChildAt(tag, index);
- } else {
- spacer = parent.appendChild(tag);
- }
-
- ViewData view = new ViewData(spacer, index != -1 ? index : mChildViews.size());
- mChildViews.add(view);
-
- if (row != UNDEFINED) {
- view.row = row;
- setGridAttribute(spacer, ATTR_LAYOUT_ROW, row);
- }
- if (column != UNDEFINED) {
- view.column = column;
- setGridAttribute(spacer, ATTR_LAYOUT_COLUMN, column);
- }
- if (widthDp > 0) {
- spacer.setAttribute(ANDROID_URI, ATTR_LAYOUT_WIDTH,
- String.format(VALUE_N_DP, widthDp));
- }
- if (heightDp > 0) {
- spacer.setAttribute(ANDROID_URI, ATTR_LAYOUT_HEIGHT,
- String.format(VALUE_N_DP, heightDp));
- }
-
- // Temporary hack
- if (GridLayoutRule.sDebugGridLayout) {
- //String id = NEW_ID_PREFIX + "s";
- //if (row == 0) {
- // id += "c";
- //}
- //if (column == 0) {
- // id += "r";
- //}
- //if (row > 0) {
- // id += Integer.toString(row);
- //}
- //if (column > 0) {
- // id += Integer.toString(column);
- //}
- String id = NEW_ID_PREFIX + "spacer_" //$NON-NLS-1$
- + Integer.toString(System.identityHashCode(spacer)).substring(0, 3);
- spacer.setAttribute(ANDROID_URI, ATTR_ID, id);
- }
-
-
- return view;
- }
-
- /**
- * Returns the string value of the given attribute, or null if it does not
- * exist. This only works for attributes that are GridLayout specific, such
- * as columnCount, layout_column, layout_row_span, etc.
- *
- * @param node the target node
- * @param name the attribute name (which must be in the android: namespace)
- * @return the attribute value or null
- */
-
- public String getGridAttribute(INode node, String name) {
- return node.getStringAttr(getNamespace(), name);
- }
-
- /**
- * Returns the integer value of the given attribute, or the given defaultValue if the
- * attribute was not set. This only works for attributes that are GridLayout specific,
- * such as columnCount, layout_column, layout_row_span, etc.
- *
- * @param node the target node
- * @param attribute the attribute name (which must be in the android: namespace)
- * @param defaultValue the default value to use if the value is not set
- * @return the attribute integer value
- */
- private int getGridAttribute(INode node, String attribute, int defaultValue) {
- String valueString = node.getStringAttr(getNamespace(), attribute);
- if (valueString != null) {
- try {
- return Integer.decode(valueString);
- } catch (NumberFormatException nufe) {
- // Ignore - error in user's XML
- }
- }
-
- return defaultValue;
- }
-
- /**
- * Returns the number of children views in the GridLayout
- *
- * @return the number of children views in the GridLayout
- */
- public int getViewCount() {
- return mChildViews.size();
- }
-
- /**
- * Returns true if the given class name represents a spacer
- *
- * @param fqcn the fully qualified class name
- * @return true if this is a spacer
- */
- public static boolean isSpace(String fqcn) {
- return FQCN_SPACE.equals(fqcn) || FQCN_SPACE_V7.equals(fqcn);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/gridmode.png b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/gridmode.png
deleted file mode 100644
index 59e0a4511..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/gridmode.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/hlinear.png b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/hlinear.png
deleted file mode 100644
index b293fe7c5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/hlinear.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/margins.png b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/margins.png
deleted file mode 100644
index b0d814116..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/margins.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/ConstraintPainter.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/ConstraintPainter.java
deleted file mode 100644
index 447d2d880..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/ConstraintPainter.java
+++ /dev/null
@@ -1,783 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout.relative;
-
-import static com.android.ide.common.api.DrawingStyle.DEPENDENCY;
-import static com.android.ide.common.api.DrawingStyle.GUIDELINE;
-import static com.android.ide.common.api.DrawingStyle.GUIDELINE_DASHED;
-import static com.android.ide.common.api.SegmentType.BASELINE;
-import static com.android.ide.common.api.SegmentType.BOTTOM;
-import static com.android.ide.common.api.SegmentType.CENTER_HORIZONTAL;
-import static com.android.ide.common.api.SegmentType.CENTER_VERTICAL;
-import static com.android.ide.common.api.SegmentType.LEFT;
-import static com.android.ide.common.api.SegmentType.RIGHT;
-import static com.android.ide.common.api.SegmentType.TOP;
-import static com.android.ide.common.api.SegmentType.UNKNOWN;
-import static com.android.ide.common.layout.relative.ConstraintType.ALIGN_BASELINE;
-import static com.android.ide.common.layout.relative.ConstraintType.ALIGN_BOTTOM;
-import static com.android.ide.common.layout.relative.ConstraintType.LAYOUT_ABOVE;
-import static com.android.ide.common.layout.relative.ConstraintType.LAYOUT_BELOW;
-import static com.android.ide.common.layout.relative.ConstraintType.LAYOUT_LEFT_OF;
-import static com.android.ide.common.layout.relative.ConstraintType.LAYOUT_RIGHT_OF;
-
-import com.android.ide.common.api.DrawingStyle;
-import com.android.ide.common.api.IGraphics;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.Margins;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.api.SegmentType;
-import com.android.ide.common.layout.relative.DependencyGraph.Constraint;
-import com.android.ide.common.layout.relative.DependencyGraph.ViewData;
-
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * The {@link ConstraintPainter} is responsible for painting relative layout constraints -
- * such as a source node having its top edge constrained to a target node with a given margin.
- * This painter is used both to show static constraints, as well as visualizing proposed
- * constraints during a move or resize operation.
- */
-public class ConstraintPainter {
- /** The size of the arrow head */
- private static final int ARROW_SIZE = 5;
- /** Size (height for horizontal, and width for vertical) parent feedback rectangles */
- private static final int PARENT_RECT_SIZE = 12;
-
- /**
- * Paints a given match as a constraint.
- *
- * @param graphics the graphics context
- * @param sourceBounds the source bounds
- * @param match the match
- */
- static void paintConstraint(IGraphics graphics, Rect sourceBounds, Match match) {
- Rect targetBounds = match.edge.node.getBounds();
- ConstraintType type = match.type;
- assert type != null;
- paintConstraint(graphics, type, match.with.node, sourceBounds, match.edge.node,
- targetBounds, null /* allConstraints */, true /* highlightTargetEdge */);
- }
-
- /**
- * Paints a constraint.
- * <p>
- * TODO: when there are multiple links originating in the same direction from
- * center, maybe offset them slightly from each other?
- *
- * @param graphics the graphics context to draw into
- * @param constraint The constraint to be drawn
- */
- private static void paintConstraint(IGraphics graphics, Constraint constraint,
- Set<Constraint> allConstraints) {
- ViewData source = constraint.from;
- ViewData target = constraint.to;
-
- INode sourceNode = source.node;
- INode targetNode = target.node;
- if (sourceNode == targetNode) {
- // Self reference - don't visualize
- return;
- }
-
- Rect sourceBounds = sourceNode.getBounds();
- Rect targetBounds = targetNode.getBounds();
- paintConstraint(graphics, constraint.type, sourceNode, sourceBounds, targetNode,
- targetBounds, allConstraints, false /* highlightTargetEdge */);
- }
-
- /**
- * Paint selection feedback by painting constraints for the selected nodes
- *
- * @param graphics the graphics context
- * @param parentNode the parent relative layout
- * @param childNodes the nodes whose constraints should be painted
- * @param showDependents whether incoming constraints should be shown as well
- */
- public static void paintSelectionFeedback(IGraphics graphics, INode parentNode,
- List<? extends INode> childNodes, boolean showDependents) {
-
- DependencyGraph dependencyGraph = new DependencyGraph(parentNode);
- Set<INode> horizontalDeps = dependencyGraph.dependsOn(childNodes, false /* vertical */);
- Set<INode> verticalDeps = dependencyGraph.dependsOn(childNodes, true /* vertical */);
- Set<INode> deps = new HashSet<INode>(horizontalDeps.size() + verticalDeps.size());
- deps.addAll(horizontalDeps);
- deps.addAll(verticalDeps);
- if (deps.size() > 0) {
- graphics.useStyle(DEPENDENCY);
- for (INode node : deps) {
- // Don't highlight the selected nodes themselves
- if (childNodes.contains(node)) {
- continue;
- }
- Rect bounds = node.getBounds();
- graphics.fillRect(bounds);
- }
- }
-
- graphics.useStyle(GUIDELINE);
- for (INode childNode : childNodes) {
- ViewData view = dependencyGraph.getView(childNode);
- if (view == null) {
- continue;
- }
-
- // Paint all incoming constraints
- if (showDependents) {
- paintConstraints(graphics, view.dependedOnBy);
- }
-
- // Paint all outgoing constraints
- paintConstraints(graphics, view.dependsOn);
- }
- }
-
- /**
- * Paints a set of constraints.
- */
- private static void paintConstraints(IGraphics graphics, List<Constraint> constraints) {
- Set<Constraint> mutableConstraintSet = new HashSet<Constraint>(constraints);
-
- // WORKAROUND! Hide alignBottom attachments if we also have a alignBaseline
- // constraint; this is because we also *add* alignBottom attachments when you add
- // alignBaseline constraints to work around a surprising behavior of baseline
- // constraints.
- for (Constraint constraint : constraints) {
- if (constraint.type == ALIGN_BASELINE) {
- // Remove any baseline
- for (Constraint c : constraints) {
- if (c.type == ALIGN_BOTTOM && c.to.node == constraint.to.node) {
- mutableConstraintSet.remove(c);
- }
- }
- }
- }
-
- for (Constraint constraint : constraints) {
- // paintConstraint can digest more than one constraint, so we need to keep
- // checking to see if the given constraint is still relevant.
- if (mutableConstraintSet.contains(constraint)) {
- paintConstraint(graphics, constraint, mutableConstraintSet);
- }
- }
- }
-
- /**
- * Paints a constraint of the given type from the given source node, to the
- * given target node, with the specified bounds.
- */
- private static void paintConstraint(IGraphics graphics, ConstraintType type, INode sourceNode,
- Rect sourceBounds, INode targetNode, Rect targetBounds,
- Set<Constraint> allConstraints, boolean highlightTargetEdge) {
-
- SegmentType sourceSegmentTypeX = type.sourceSegmentTypeX;
- SegmentType sourceSegmentTypeY = type.sourceSegmentTypeY;
- SegmentType targetSegmentTypeX = type.targetSegmentTypeX;
- SegmentType targetSegmentTypeY = type.targetSegmentTypeY;
-
- // Horizontal center constraint?
- if (sourceSegmentTypeX == CENTER_VERTICAL && targetSegmentTypeX == CENTER_VERTICAL) {
- paintHorizontalCenterConstraint(graphics, sourceBounds, targetBounds);
- return;
- }
-
- // Vertical center constraint?
- if (sourceSegmentTypeY == CENTER_HORIZONTAL && targetSegmentTypeY == CENTER_HORIZONTAL) {
- paintVerticalCenterConstraint(graphics, sourceBounds, targetBounds);
- return;
- }
-
- // Corner constraint?
- if (allConstraints != null
- && (type == LAYOUT_ABOVE || type == LAYOUT_BELOW
- || type == LAYOUT_LEFT_OF || type == LAYOUT_RIGHT_OF)) {
- if (paintCornerConstraint(graphics, type, sourceNode, sourceBounds, targetNode,
- targetBounds, allConstraints)) {
- return;
- }
- }
-
- // Vertical constraint?
- if (sourceSegmentTypeX == UNKNOWN) {
- paintVerticalConstraint(graphics, type, sourceNode, sourceBounds, targetNode,
- targetBounds, highlightTargetEdge);
- return;
- }
-
- // Horizontal constraint?
- if (sourceSegmentTypeY == UNKNOWN) {
- paintHorizontalConstraint(graphics, type, sourceNode, sourceBounds, targetNode,
- targetBounds, highlightTargetEdge);
- return;
- }
-
- // This shouldn't happen - it means we have a constraint that defines all sides
- // and is not a centering constraint
- assert false;
- }
-
- /**
- * Paints a corner constraint, or returns false if this constraint is not a corner.
- * A corner is one where there are two constraints from this source node to the
- * same target node, one horizontal and one vertical, to the closest edges on
- * the target node.
- * <p>
- * Corners are a common occurrence. If we treat the horizontal and vertical
- * constraints separately (below & toRightOf), then we end up with a lot of
- * extra lines and arrows -- e.g. two shared edges and arrows pointing to these
- * shared edges:
- *
- * <pre>
- * +--------+ |
- * | Target -->
- * +----|---+ |
- * v
- * - - - - - -|- - - - - -
- * ^
- * | +---|----+
- * <-- Source |
- * | +--------+
- *
- * Instead, we can simply draw a diagonal arrow here to represent BOTH constraints and
- * reduce clutter:
- *
- * +---------+
- * | Target _|
- * +-------|\+
- * \
- * \--------+
- * | Source |
- * +--------+
- * </pre>
- *
- * @param graphics the graphics context to draw
- * @param type the constraint to be drawn
- * @param sourceNode the source node
- * @param sourceBounds the bounds of the source node
- * @param targetNode the target node
- * @param targetBounds the bounds of the target node
- * @param allConstraints the set of all constraints; if a corner is found and painted the
- * matching corner constraint is removed from the set
- * @return true if the constraint was handled and painted as a corner, false otherwise
- */
- private static boolean paintCornerConstraint(IGraphics graphics, ConstraintType type,
- INode sourceNode, Rect sourceBounds, INode targetNode, Rect targetBounds,
- Set<Constraint> allConstraints) {
-
- SegmentType sourceSegmentTypeX = type.sourceSegmentTypeX;
- SegmentType sourceSegmentTypeY = type.sourceSegmentTypeY;
- SegmentType targetSegmentTypeX = type.targetSegmentTypeX;
- SegmentType targetSegmentTypeY = type.targetSegmentTypeY;
-
- ConstraintType opposite1 = null, opposite2 = null;
- switch (type) {
- case LAYOUT_BELOW:
- case LAYOUT_ABOVE:
- opposite1 = LAYOUT_LEFT_OF;
- opposite2 = LAYOUT_RIGHT_OF;
- break;
- case LAYOUT_LEFT_OF:
- case LAYOUT_RIGHT_OF:
- opposite1 = LAYOUT_ABOVE;
- opposite2 = LAYOUT_BELOW;
- break;
- default:
- return false;
- }
- Constraint pair = null;
- for (Constraint constraint : allConstraints) {
- if ((constraint.type == opposite1 || constraint.type == opposite2) &&
- constraint.to.node == targetNode && constraint.from.node == sourceNode) {
- pair = constraint;
- break;
- }
- }
-
- // TODO -- ensure that the nodes are adjacent! In other words, that
- // their bounds are within N pixels.
-
- if (pair != null) {
- // Visualize the corner constraint
- if (sourceSegmentTypeX == UNKNOWN) {
- sourceSegmentTypeX = pair.type.sourceSegmentTypeX;
- }
- if (sourceSegmentTypeY == UNKNOWN) {
- sourceSegmentTypeY = pair.type.sourceSegmentTypeY;
- }
- if (targetSegmentTypeX == UNKNOWN) {
- targetSegmentTypeX = pair.type.targetSegmentTypeX;
- }
- if (targetSegmentTypeY == UNKNOWN) {
- targetSegmentTypeY = pair.type.targetSegmentTypeY;
- }
-
- int x1, y1, x2, y2;
- if (sourceSegmentTypeX == LEFT) {
- x1 = sourceBounds.x + 1 * sourceBounds.w / 4;
- } else {
- x1 = sourceBounds.x + 3 * sourceBounds.w / 4;
- }
- if (sourceSegmentTypeY == TOP) {
- y1 = sourceBounds.y + 1 * sourceBounds.h / 4;
- } else {
- y1 = sourceBounds.y + 3 * sourceBounds.h / 4;
- }
- if (targetSegmentTypeX == LEFT) {
- x2 = targetBounds.x + 1 * targetBounds.w / 4;
- } else {
- x2 = targetBounds.x + 3 * targetBounds.w / 4;
- }
- if (targetSegmentTypeY == TOP) {
- y2 = targetBounds.y + 1 * targetBounds.h / 4;
- } else {
- y2 = targetBounds.y + 3 * targetBounds.h / 4;
- }
-
- graphics.useStyle(GUIDELINE);
- graphics.drawArrow(x1, y1, x2, y2, ARROW_SIZE);
-
- // Don't process this constraint on its own later.
- allConstraints.remove(pair);
-
- return true;
- }
-
- return false;
- }
-
- /**
- * Paints a vertical constraint, handling the various scenarios where there are
- * margins, or where the two nodes overlap horizontally and where they don't, etc.
- * <p>
- * Here's an example of what will be shown for a "below" constraint where the
- * nodes do not overlap horizontally and the target node has a bottom margin:
- * <pre>
- * +--------+
- * | Target |
- * +--------+
- * |
- * v
- * - - - - - - - - - - - - - -
- * ^
- * |
- * +--------+
- * | Source |
- * +--------+
- * </pre>
- */
- private static void paintVerticalConstraint(IGraphics graphics, ConstraintType type,
- INode sourceNode, Rect sourceBounds, INode targetNode, Rect targetBounds,
- boolean highlightTargetEdge) {
- SegmentType sourceSegmentTypeY = type.sourceSegmentTypeY;
- SegmentType targetSegmentTypeY = type.targetSegmentTypeY;
- Margins targetMargins = targetNode.getMargins();
-
- assert sourceSegmentTypeY != UNKNOWN;
- assert targetBounds != null;
-
- int sourceY = sourceSegmentTypeY.getY(sourceNode, sourceBounds);
- int targetY = targetSegmentTypeY ==
- UNKNOWN ? sourceY : targetSegmentTypeY.getY(targetNode, targetBounds);
-
- if (highlightTargetEdge && type.isRelativeToParentEdge()) {
- graphics.useStyle(DrawingStyle.DROP_ZONE_ACTIVE);
- graphics.fillRect(targetBounds.x, targetY - PARENT_RECT_SIZE / 2,
- targetBounds.x2(), targetY + PARENT_RECT_SIZE / 2);
- }
-
- // First see if the two views overlap horizontally. If so, we can just draw a direct
- // arrow from the source up to (or down to) the target.
- //
- // +--------+
- // | Target |
- // +--------+
- // ^
- // |
- // |
- // +--------+
- // | Source |
- // +--------+
- //
- int maxLeft = Math.max(sourceBounds.x, targetBounds.x);
- int minRight = Math.min(sourceBounds.x2(), targetBounds.x2());
-
- int center = (maxLeft + minRight) / 2;
- if (center > sourceBounds.x && center < sourceBounds.x2()) {
- // Yes, the lines overlap -- just draw a straight arrow
- //
- //
- // If however there is a margin on the target edge, it should be drawn like this:
- //
- // +--------+
- // | Target |
- // +--------+
- // |
- // |
- // v
- // - - - - - - -
- // ^
- // |
- // |
- // +--------+
- // | Source |
- // +--------+
- //
- // Use a minimum threshold for this visualization since it doesn't look good
- // for small margins
- if (targetSegmentTypeY == BOTTOM && targetMargins.bottom > 5) {
- int sharedY = targetY + targetMargins.bottom;
- if (sourceY > sharedY + 2) { // Skip when source falls on the margin line
- graphics.useStyle(GUIDELINE_DASHED);
- graphics.drawLine(targetBounds.x, sharedY, targetBounds.x2(), sharedY);
- graphics.useStyle(GUIDELINE);
- graphics.drawArrow(center, sourceY, center, sharedY + 2, ARROW_SIZE);
- graphics.drawArrow(center, targetY, center, sharedY - 3, ARROW_SIZE);
- } else {
- graphics.useStyle(GUIDELINE);
- // Draw reverse arrow to make it clear the node is as close
- // at it can be
- graphics.drawArrow(center, targetY, center, sourceY, ARROW_SIZE);
- }
- return;
- } else if (targetSegmentTypeY == TOP && targetMargins.top > 5) {
- int sharedY = targetY - targetMargins.top;
- if (sourceY < sharedY - 2) {
- graphics.useStyle(GUIDELINE_DASHED);
- graphics.drawLine(targetBounds.x, sharedY, targetBounds.x2(), sharedY);
- graphics.useStyle(GUIDELINE);
- graphics.drawArrow(center, sourceY, center, sharedY - 3, ARROW_SIZE);
- graphics.drawArrow(center, targetY, center, sharedY + 3, ARROW_SIZE);
- } else {
- graphics.useStyle(GUIDELINE);
- graphics.drawArrow(center, targetY, center, sourceY, ARROW_SIZE);
- }
- return;
- }
-
- // TODO: If the center falls smack in the center of the sourceBounds,
- // AND the source node is part of the selection, then adjust the
- // center location such that it is off to the side, let's say 1/4 or 3/4 of
- // the overlap region, to ensure that it does not overlap the center selection
- // handle
-
- // When the constraint is for two immediately adjacent edges, we
- // need to make some adjustments to make sure the arrow points in the right
- // direction
- if (sourceY == targetY) {
- if (sourceSegmentTypeY == BOTTOM || sourceSegmentTypeY == BASELINE) {
- sourceY -= 2 * ARROW_SIZE;
- } else if (sourceSegmentTypeY == TOP) {
- sourceY += 2 * ARROW_SIZE;
- } else {
- assert sourceSegmentTypeY == CENTER_HORIZONTAL : sourceSegmentTypeY;
- sourceY += sourceBounds.h / 2 - 2 * ARROW_SIZE;
- }
- } else if (sourceSegmentTypeY == BASELINE) {
- sourceY = targetY - 2 * ARROW_SIZE;
- }
-
- // Center the vertical line in the overlap region
- graphics.useStyle(GUIDELINE);
- graphics.drawArrow(center, sourceY, center, targetY, ARROW_SIZE);
-
- return;
- }
-
- // If there is no horizontal overlap in the vertical constraints, then we
- // will show the attachment relative to a dashed line that extends beyond
- // the target bounds, like this:
- //
- // +--------+
- // | Target |
- // +--------+ - - - - - - - - -
- // ^
- // |
- // +--------+
- // | Source |
- // +--------+
- //
- // However, if the target node has a vertical margin, we may need to offset
- // the line:
- //
- // +--------+
- // | Target |
- // +--------+
- // |
- // v
- // - - - - - - - - - - - - - -
- // ^
- // |
- // +--------+
- // | Source |
- // +--------+
- //
- // If not, we'll need to indicate a shared edge. This is the edge that separate
- // them (but this will require me to evaluate margins!)
-
- // Compute overlap region and pick the middle
- int sharedY = targetSegmentTypeY ==
- UNKNOWN ? sourceY : targetSegmentTypeY.getY(targetNode, targetBounds);
- if (type.relativeToMargin) {
- if (targetSegmentTypeY == TOP) {
- sharedY -= targetMargins.top;
- } else if (targetSegmentTypeY == BOTTOM) {
- sharedY += targetMargins.bottom;
- }
- }
-
- int startX;
- int endX;
- if (center <= sourceBounds.x) {
- startX = targetBounds.x + targetBounds.w / 4;
- endX = sourceBounds.x2();
- } else {
- assert (center >= sourceBounds.x2());
- startX = sourceBounds.x;
- endX = targetBounds.x + 3 * targetBounds.w / 4;
- }
- // Must draw segmented line instead
- // Place the arrow 1/4 instead of 1/2 in the source to avoid overlapping with the
- // selection handles
- graphics.useStyle(GUIDELINE_DASHED);
- graphics.drawLine(startX, sharedY, endX, sharedY);
-
- // Adjust position of source arrow such that it does not sit across edge; it
- // should point directly at the edge
- if (Math.abs(sharedY - sourceY) < 2 * ARROW_SIZE) {
- if (sourceSegmentTypeY == BASELINE) {
- sourceY = sharedY - 2 * ARROW_SIZE;
- } else if (sourceSegmentTypeY == TOP) {
- sharedY = sourceY;
- sourceY = sharedY + 2 * ARROW_SIZE;
- } else {
- sharedY = sourceY;
- sourceY = sharedY - 2 * ARROW_SIZE;
- }
- }
-
- graphics.useStyle(GUIDELINE);
-
- // Draw the line from the source anchor to the shared edge
- int x = sourceBounds.x + ((sourceSegmentTypeY == BASELINE) ?
- sourceBounds.w / 2 : sourceBounds.w / 4);
- graphics.drawArrow(x, sourceY, x, sharedY, ARROW_SIZE);
-
- // Draw the line from the target to the horizontal shared edge
- int tx = targetBounds.centerX();
- if (targetSegmentTypeY == TOP) {
- int ty = targetBounds.y;
- int margin = targetMargins.top;
- if (margin == 0 || !type.relativeToMargin) {
- graphics.drawArrow(tx, ty + 2 * ARROW_SIZE, tx, ty, ARROW_SIZE);
- } else {
- graphics.drawArrow(tx, ty, tx, ty - margin, ARROW_SIZE);
- }
- } else if (targetSegmentTypeY == BOTTOM) {
- int ty = targetBounds.y2();
- int margin = targetMargins.bottom;
- if (margin == 0 || !type.relativeToMargin) {
- graphics.drawArrow(tx, ty - 2 * ARROW_SIZE, tx, ty, ARROW_SIZE);
- } else {
- graphics.drawArrow(tx, ty, tx, ty + margin, ARROW_SIZE);
- }
- } else {
- assert targetSegmentTypeY == BASELINE : targetSegmentTypeY;
- int ty = targetSegmentTypeY.getY(targetNode, targetBounds);
- graphics.drawArrow(tx, ty - 2 * ARROW_SIZE, tx, ty, ARROW_SIZE);
- }
-
- return;
- }
-
- /**
- * Paints a horizontal constraint, handling the various scenarios where there are margins,
- * or where the two nodes overlap horizontally and where they don't, etc.
- */
- private static void paintHorizontalConstraint(IGraphics graphics, ConstraintType type,
- INode sourceNode, Rect sourceBounds, INode targetNode, Rect targetBounds,
- boolean highlightTargetEdge) {
- SegmentType sourceSegmentTypeX = type.sourceSegmentTypeX;
- SegmentType targetSegmentTypeX = type.targetSegmentTypeX;
- Margins targetMargins = targetNode.getMargins();
-
- assert sourceSegmentTypeX != UNKNOWN;
- assert targetBounds != null;
-
- // See paintVerticalConstraint for explanations of the various cases.
-
- int sourceX = sourceSegmentTypeX.getX(sourceNode, sourceBounds);
- int targetX = targetSegmentTypeX == UNKNOWN ?
- sourceX : targetSegmentTypeX.getX(targetNode, targetBounds);
-
- if (highlightTargetEdge && type.isRelativeToParentEdge()) {
- graphics.useStyle(DrawingStyle.DROP_ZONE_ACTIVE);
- graphics.fillRect(targetX - PARENT_RECT_SIZE / 2, targetBounds.y,
- targetX + PARENT_RECT_SIZE / 2, targetBounds.y2());
- }
-
- int maxTop = Math.max(sourceBounds.y, targetBounds.y);
- int minBottom = Math.min(sourceBounds.y2(), targetBounds.y2());
-
- // First see if the two views overlap vertically. If so, we can just draw a direct
- // arrow from the source over to the target.
- int center = (maxTop + minBottom) / 2;
- if (center > sourceBounds.y && center < sourceBounds.y2()) {
- // See if we should draw a margin line
- if (targetSegmentTypeX == RIGHT && targetMargins.right > 5) {
- int sharedX = targetX + targetMargins.right;
- if (sourceX > sharedX + 2) { // Skip when source falls on the margin line
- graphics.useStyle(GUIDELINE_DASHED);
- graphics.drawLine(sharedX, targetBounds.y, sharedX, targetBounds.y2());
- graphics.useStyle(GUIDELINE);
- graphics.drawArrow(sourceX, center, sharedX + 2, center, ARROW_SIZE);
- graphics.drawArrow(targetX, center, sharedX - 3, center, ARROW_SIZE);
- } else {
- graphics.useStyle(GUIDELINE);
- // Draw reverse arrow to make it clear the node is as close
- // at it can be
- graphics.drawArrow(targetX, center, sourceX, center, ARROW_SIZE);
- }
- return;
- } else if (targetSegmentTypeX == LEFT && targetMargins.left > 5) {
- int sharedX = targetX - targetMargins.left;
- if (sourceX < sharedX - 2) {
- graphics.useStyle(GUIDELINE_DASHED);
- graphics.drawLine(sharedX, targetBounds.y, sharedX, targetBounds.y2());
- graphics.useStyle(GUIDELINE);
- graphics.drawArrow(sourceX, center, sharedX - 3, center, ARROW_SIZE);
- graphics.drawArrow(targetX, center, sharedX + 3, center, ARROW_SIZE);
- } else {
- graphics.useStyle(GUIDELINE);
- graphics.drawArrow(targetX, center, sourceX, center, ARROW_SIZE);
- }
- return;
- }
-
- if (sourceX == targetX) {
- if (sourceSegmentTypeX == RIGHT) {
- sourceX -= 2 * ARROW_SIZE;
- } else if (sourceSegmentTypeX == LEFT ) {
- sourceX += 2 * ARROW_SIZE;
- } else {
- assert sourceSegmentTypeX == CENTER_VERTICAL : sourceSegmentTypeX;
- sourceX += sourceBounds.w / 2 - 2 * ARROW_SIZE;
- }
- }
-
- graphics.useStyle(GUIDELINE);
- graphics.drawArrow(sourceX, center, targetX, center, ARROW_SIZE);
- return;
- }
-
- // Segment line
-
- // Compute overlap region and pick the middle
- int sharedX = targetSegmentTypeX == UNKNOWN ?
- sourceX : targetSegmentTypeX.getX(targetNode, targetBounds);
- if (type.relativeToMargin) {
- if (targetSegmentTypeX == LEFT) {
- sharedX -= targetMargins.left;
- } else if (targetSegmentTypeX == RIGHT) {
- sharedX += targetMargins.right;
- }
- }
-
- int startY, endY;
- if (center <= sourceBounds.y) {
- startY = targetBounds.y + targetBounds.h / 4;
- endY = sourceBounds.y2();
- } else {
- assert (center >= sourceBounds.y2());
- startY = sourceBounds.y;
- endY = targetBounds.y + 3 * targetBounds.h / 2;
- }
-
- // Must draw segmented line instead
- // Place at 1/4 instead of 1/2 to avoid overlapping with selection handles
- int y = sourceBounds.y + sourceBounds.h / 4;
- graphics.useStyle(GUIDELINE_DASHED);
- graphics.drawLine(sharedX, startY, sharedX, endY);
-
- // Adjust position of source arrow such that it does not sit across edge; it
- // should point directly at the edge
- if (Math.abs(sharedX - sourceX) < 2 * ARROW_SIZE) {
- if (sourceSegmentTypeX == LEFT) {
- sharedX = sourceX;
- sourceX = sharedX + 2 * ARROW_SIZE;
- } else {
- sharedX = sourceX;
- sourceX = sharedX - 2 * ARROW_SIZE;
- }
- }
-
- graphics.useStyle(GUIDELINE);
-
- // Draw the line from the source anchor to the shared edge
- graphics.drawArrow(sourceX, y, sharedX, y, ARROW_SIZE);
-
- // Draw the line from the target to the horizontal shared edge
- int ty = targetBounds.centerY();
- if (targetSegmentTypeX == LEFT) {
- int tx = targetBounds.x;
- int margin = targetMargins.left;
- if (margin == 0 || !type.relativeToMargin) {
- graphics.drawArrow(tx + 2 * ARROW_SIZE, ty, tx, ty, ARROW_SIZE);
- } else {
- graphics.drawArrow(tx, ty, tx - margin, ty, ARROW_SIZE);
- }
- } else {
- assert targetSegmentTypeX == RIGHT;
- int tx = targetBounds.x2();
- int margin = targetMargins.right;
- if (margin == 0 || !type.relativeToMargin) {
- graphics.drawArrow(tx - 2 * ARROW_SIZE, ty, tx, ty, ARROW_SIZE);
- } else {
- graphics.drawArrow(tx, ty, tx + margin, ty, ARROW_SIZE);
- }
- }
-
- return;
- }
-
- /**
- * Paints a vertical center constraint. The constraint is shown as a dashed line
- * through the vertical view, and a solid line over the node bounds.
- */
- private static void paintVerticalCenterConstraint(IGraphics graphics, Rect sourceBounds,
- Rect targetBounds) {
- graphics.useStyle(GUIDELINE_DASHED);
- graphics.drawLine(targetBounds.x, targetBounds.centerY(),
- targetBounds.x2(), targetBounds.centerY());
- graphics.useStyle(GUIDELINE);
- graphics.drawLine(sourceBounds.x, sourceBounds.centerY(),
- sourceBounds.x2(), sourceBounds.centerY());
- }
-
- /**
- * Paints a horizontal center constraint. The constraint is shown as a dashed line
- * through the horizontal view, and a solid line over the node bounds.
- */
- private static void paintHorizontalCenterConstraint(IGraphics graphics, Rect sourceBounds,
- Rect targetBounds) {
- graphics.useStyle(GUIDELINE_DASHED);
- graphics.drawLine(targetBounds.centerX(), targetBounds.y,
- targetBounds.centerX(), targetBounds.y2());
- graphics.useStyle(GUIDELINE);
- graphics.drawLine(sourceBounds.centerX(), sourceBounds.y,
- sourceBounds.centerX(), sourceBounds.y2());
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/ConstraintType.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/ConstraintType.java
deleted file mode 100644
index ed4ac1bf4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/ConstraintType.java
+++ /dev/null
@@ -1,241 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout.relative;
-
-import static com.android.ide.common.api.SegmentType.BASELINE;
-import static com.android.ide.common.api.SegmentType.BOTTOM;
-import static com.android.ide.common.api.SegmentType.CENTER_HORIZONTAL;
-import static com.android.ide.common.api.SegmentType.CENTER_VERTICAL;
-import static com.android.ide.common.api.SegmentType.LEFT;
-import static com.android.ide.common.api.SegmentType.RIGHT;
-import static com.android.ide.common.api.SegmentType.TOP;
-import static com.android.ide.common.api.SegmentType.UNKNOWN;
-import static com.android.SdkConstants.ATTR_LAYOUT_ABOVE;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_BASELINE;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_BOTTOM;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_LEFT;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_PARENT_BOTTOM;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_PARENT_LEFT;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_PARENT_RIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_PARENT_TOP;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_RIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_TOP;
-import static com.android.SdkConstants.ATTR_LAYOUT_BELOW;
-import static com.android.SdkConstants.ATTR_LAYOUT_CENTER_HORIZONTAL;
-import static com.android.SdkConstants.ATTR_LAYOUT_CENTER_IN_PARENT;
-import static com.android.SdkConstants.ATTR_LAYOUT_CENTER_VERTICAL;
-import static com.android.SdkConstants.ATTR_LAYOUT_TO_LEFT_OF;
-import static com.android.SdkConstants.ATTR_LAYOUT_TO_RIGHT_OF;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.SegmentType;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Each constraint type corresponds to a type of constraint available for the
- * RelativeLayout; for example, {@link #LAYOUT_ABOVE} corresponds to the layout_above constraint.
- */
-enum ConstraintType {
- LAYOUT_ABOVE(ATTR_LAYOUT_ABOVE,
- null /* sourceX */, BOTTOM, null /* targetX */, TOP,
- false /* targetParent */, true /* horizontalEdge */, false /* verticalEdge */,
- true /* relativeToMargin */),
-
- LAYOUT_BELOW(ATTR_LAYOUT_BELOW, null, TOP, null, BOTTOM, false, true, false, true),
- ALIGN_TOP(ATTR_LAYOUT_ALIGN_TOP, null, TOP, null, TOP, false, true, false, false),
- ALIGN_BOTTOM(ATTR_LAYOUT_ALIGN_BOTTOM, null, BOTTOM, null, BOTTOM, false, true, false, false),
- ALIGN_LEFT(ATTR_LAYOUT_ALIGN_LEFT, LEFT, null, LEFT, null, false, false, true, false),
- ALIGN_RIGHT(ATTR_LAYOUT_ALIGN_RIGHT, RIGHT, null, RIGHT, null, false, false, true, false),
- LAYOUT_LEFT_OF(ATTR_LAYOUT_TO_LEFT_OF, RIGHT, null, LEFT, null, false, false, true, true),
- LAYOUT_RIGHT_OF(ATTR_LAYOUT_TO_RIGHT_OF, LEFT, null, RIGHT, null, false, false, true, true),
- ALIGN_PARENT_TOP(ATTR_LAYOUT_ALIGN_PARENT_TOP, null, TOP, null, TOP, true, true, false, false),
- ALIGN_BASELINE(ATTR_LAYOUT_ALIGN_BASELINE, null, BASELINE, null, BASELINE, false, true, false,
- false),
- ALIGN_PARENT_LEFT(ATTR_LAYOUT_ALIGN_PARENT_LEFT, LEFT, null, LEFT, null, true, false, true,
- false),
- ALIGN_PARENT_RIGHT(ATTR_LAYOUT_ALIGN_PARENT_RIGHT, RIGHT, null, RIGHT, null, true, false, true,
- false),
- ALIGN_PARENT_BOTTOM(ATTR_LAYOUT_ALIGN_PARENT_BOTTOM, null, BOTTOM, null, BOTTOM, true, true,
- false, false),
- LAYOUT_CENTER_HORIZONTAL(ATTR_LAYOUT_CENTER_HORIZONTAL, CENTER_VERTICAL, null, CENTER_VERTICAL,
- null, true, true, false, false),
- LAYOUT_CENTER_VERTICAL(ATTR_LAYOUT_CENTER_VERTICAL, null, CENTER_HORIZONTAL, null,
- CENTER_HORIZONTAL, true, false, true, false),
- LAYOUT_CENTER_IN_PARENT(ATTR_LAYOUT_CENTER_IN_PARENT, CENTER_VERTICAL, CENTER_HORIZONTAL,
- CENTER_VERTICAL, CENTER_HORIZONTAL, true, true, true, false);
-
- private ConstraintType(String name, SegmentType sourceSegmentTypeX,
- SegmentType sourceSegmentTypeY, SegmentType targetSegmentTypeX,
- SegmentType targetSegmentTypeY, boolean targetParent, boolean horizontalEdge,
- boolean verticalEdge, boolean relativeToMargin) {
- assert horizontalEdge || verticalEdge;
-
- this.name = name;
- this.sourceSegmentTypeX = sourceSegmentTypeX != null ? sourceSegmentTypeX : UNKNOWN;
- this.sourceSegmentTypeY = sourceSegmentTypeY != null ? sourceSegmentTypeY : UNKNOWN;
- this.targetSegmentTypeX = targetSegmentTypeX != null ? targetSegmentTypeX : UNKNOWN;
- this.targetSegmentTypeY = targetSegmentTypeY != null ? targetSegmentTypeY : UNKNOWN;
- this.targetParent = targetParent;
- this.horizontalEdge = horizontalEdge;
- this.verticalEdge = verticalEdge;
- this.relativeToMargin = relativeToMargin;
- }
-
- /** The attribute name of the constraint */
- public final String name;
-
- /** The horizontal position of the source of the constraint */
- public final SegmentType sourceSegmentTypeX;
-
- /** The vertical position of the source of the constraint */
- public final SegmentType sourceSegmentTypeY;
-
- /** The horizontal position of the target of the constraint */
- public final SegmentType targetSegmentTypeX;
-
- /** The vertical position of the target of the constraint */
- public final SegmentType targetSegmentTypeY;
-
- /**
- * If true, the constraint targets the parent layout, otherwise it targets another
- * view
- */
- public final boolean targetParent;
-
- /** If true, this constraint affects the horizontal dimension */
- public final boolean horizontalEdge;
-
- /** If true, this constraint affects the vertical dimension */
- public final boolean verticalEdge;
-
- /**
- * Whether this constraint is relative to the margin bounds of the node rather than
- * the node's actual bounds
- */
- public final boolean relativeToMargin;
-
- /** Map from attribute name to constraint type */
- private static Map<String, ConstraintType> sNameToType;
-
- /**
- * Returns the {@link ConstraintType} corresponding to the given attribute name, or
- * null if not found.
- *
- * @param attribute the name of the attribute to look up
- * @return the corresponding {@link ConstraintType}
- */
- @Nullable
- public static ConstraintType fromAttribute(@NonNull String attribute) {
- if (sNameToType == null) {
- ConstraintType[] types = ConstraintType.values();
- Map<String, ConstraintType> map = new HashMap<String, ConstraintType>(types.length);
- for (ConstraintType type : types) {
- map.put(type.name, type);
- }
- sNameToType = map;
- }
- return sNameToType.get(attribute);
- }
-
- /**
- * Returns true if this constraint type represents a constraint where the target edge
- * is one of the parent edges (actual edge, not center/baseline segments)
- *
- * @return true if the target segment is a parent edge
- */
- public boolean isRelativeToParentEdge() {
- return this == ALIGN_PARENT_LEFT || this == ALIGN_PARENT_RIGHT || this == ALIGN_PARENT_TOP
- || this == ALIGN_PARENT_BOTTOM;
- }
-
- /**
- * Returns a {@link ConstraintType} for a potential match of edges.
- *
- * @param withParent if true, the target is the parent
- * @param from the source edge
- * @param to the target edge
- * @return a {@link ConstraintType}, or null
- */
- @Nullable
- public static ConstraintType forMatch(boolean withParent, SegmentType from, SegmentType to) {
- // Attached to parent edge?
- if (withParent) {
- switch (from) {
- case TOP:
- return ALIGN_PARENT_TOP;
- case BOTTOM:
- return ALIGN_PARENT_BOTTOM;
- case LEFT:
- return ALIGN_PARENT_LEFT;
- case RIGHT:
- return ALIGN_PARENT_RIGHT;
- case CENTER_HORIZONTAL:
- return LAYOUT_CENTER_VERTICAL;
- case CENTER_VERTICAL:
- return LAYOUT_CENTER_HORIZONTAL;
- }
-
- return null;
- }
-
- // Attached to some other node.
- switch (from) {
- case TOP:
- switch (to) {
- case TOP:
- return ALIGN_TOP;
- case BOTTOM:
- return LAYOUT_BELOW;
- case BASELINE:
- return ALIGN_BASELINE;
- }
- break;
- case BOTTOM:
- switch (to) {
- case TOP:
- return LAYOUT_ABOVE;
- case BOTTOM:
- return ALIGN_BOTTOM;
- case BASELINE:
- return ALIGN_BASELINE;
- }
- break;
- case LEFT:
- switch (to) {
- case LEFT:
- return ALIGN_LEFT;
- case RIGHT:
- return LAYOUT_RIGHT_OF;
- }
- break;
- case RIGHT:
- switch (to) {
- case LEFT:
- return LAYOUT_LEFT_OF;
- case RIGHT:
- return ALIGN_RIGHT;
- }
- break;
- case BASELINE:
- return ALIGN_BASELINE;
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/DeletionHandler.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/DeletionHandler.java
deleted file mode 100644
index 3eac510df..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/DeletionHandler.java
+++ /dev/null
@@ -1,267 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout.relative;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ATTR_LAYOUT_MARGIN;
-import static com.android.SdkConstants.ATTR_LAYOUT_RESOURCE_PREFIX;
-import static com.android.SdkConstants.ID_PREFIX;
-import static com.android.SdkConstants.NEW_ID_PREFIX;
-import static com.android.ide.common.layout.BaseViewRule.stripIdPrefix;
-import static com.android.ide.common.layout.relative.ConstraintType.LAYOUT_CENTER_HORIZONTAL;
-import static com.android.ide.common.layout.relative.ConstraintType.LAYOUT_CENTER_VERTICAL;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.INode.IAttribute;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Handles deletions in a relative layout, transferring constraints across
- * deleted nodes
- * <p>
- * TODO: Consider adding the
- * {@link SdkConstants#ATTR_LAYOUT_ALIGN_WITH_PARENT_MISSING} attribute to a
- * node if it's pointing to a node which is deleted and which has no transitive
- * reference to another node.
- */
-public class DeletionHandler {
- private final INode mLayout;
- private final INode[] mChildren;
- private final List<INode> mDeleted;
- private final Set<String> mDeletedIds;
- private final Map<String, INode> mNodeMap;
- private final List<INode> mMoved;
-
- /**
- * Creates a new {@link DeletionHandler}
- *
- * @param deleted the deleted nodes
- * @param moved nodes that were moved (e.g. deleted, but also inserted elsewhere)
- * @param layout the parent layout of the deleted nodes
- */
- public DeletionHandler(@NonNull List<INode> deleted, @NonNull List<INode> moved,
- @NonNull INode layout) {
- mDeleted = deleted;
- mMoved = moved;
- mLayout = layout;
-
- mChildren = mLayout.getChildren();
- mNodeMap = Maps.newHashMapWithExpectedSize(mChildren.length);
- for (INode child : mChildren) {
- String id = child.getStringAttr(ANDROID_URI, ATTR_ID);
- if (id != null) {
- mNodeMap.put(stripIdPrefix(id), child);
- }
- }
-
- mDeletedIds = Sets.newHashSetWithExpectedSize(mDeleted.size());
- for (INode node : mDeleted) {
- String id = node.getStringAttr(ANDROID_URI, ATTR_ID);
- if (id != null) {
- mDeletedIds.add(stripIdPrefix(id));
- }
- }
-
- // Any widgets that remain (e.g. typically because they were moved) should
- // keep their incoming dependencies
- for (INode node : mMoved) {
- String id = node.getStringAttr(ANDROID_URI, ATTR_ID);
- if (id != null) {
- mDeletedIds.remove(stripIdPrefix(id));
- }
- }
- }
-
- @Nullable
- private static String getId(@NonNull IAttribute attribute) {
- if (attribute.getName().startsWith(ATTR_LAYOUT_RESOURCE_PREFIX)
- && ANDROID_URI.equals(attribute.getUri())
- && !attribute.getName().startsWith(ATTR_LAYOUT_MARGIN)) {
- String id = attribute.getValue();
- // It might not be an id reference, so check manually rather than just
- // calling stripIdPrefix():
- if (id.startsWith(NEW_ID_PREFIX)) {
- return id.substring(NEW_ID_PREFIX.length());
- } else if (id.startsWith(ID_PREFIX)) {
- return id.substring(ID_PREFIX.length());
- }
- }
-
- return null;
- }
-
- /**
- * Updates the constraints in the layout to handle deletion of a set of
- * nodes. This ensures that any constraints pointing to one of the deleted
- * nodes are changed properly to point to a non-deleted node with similar
- * constraints.
- */
- public void updateConstraints() {
- if (mChildren.length == mDeleted.size()) {
- // Deleting everything: Nothing to be done
- return;
- }
-
- // Now remove incoming edges to any views that were deleted. If possible,
- // don't just delete them but replace them with a transitive constraint, e.g.
- // if we have "A <= B <= C" and "B" is removed, then we end up with "A <= C",
-
- for (INode child : mChildren) {
- if (mDeleted.contains(child)) {
- continue;
- }
-
- for (IAttribute attribute : child.getLiveAttributes()) {
- String id = getId(attribute);
- if (id != null) {
- if (mDeletedIds.contains(id)) {
- // Unset this reference to a deleted widget. It might be
- // replaced if the pointed to node points to some other node
- // on the same side, but it may use a different constraint name,
- // or have none at all (e.g. parent).
- String name = attribute.getName();
- child.setAttribute(ANDROID_URI, name, null);
-
- INode deleted = mNodeMap.get(id);
- if (deleted != null) {
- ConstraintType type = ConstraintType.fromAttribute(name);
- if (type != null) {
- transfer(deleted, child, type, 0);
- }
- }
- }
- }
- }
- }
- }
-
- private void transfer(INode deleted, INode target, ConstraintType targetType, int depth) {
- if (depth == 20) {
- // Prevent really deep flow or unbounded recursion in case there is a bug in
- // the cycle detection code
- return;
- }
-
- assert mDeleted.contains(deleted);
-
- for (IAttribute attribute : deleted.getLiveAttributes()) {
- String name = attribute.getName();
- ConstraintType type = ConstraintType.fromAttribute(name);
- if (type == null) {
- continue;
- }
-
- ConstraintType transfer = getCompatibleConstraint(type, targetType);
- if (transfer != null) {
- String id = getId(attribute);
- if (id != null) {
- if (mDeletedIds.contains(id)) {
- INode nextDeleted = mNodeMap.get(id);
- if (nextDeleted != null) {
- // Points to another deleted node: recurse
- transfer(nextDeleted, target, targetType, depth + 1);
- }
- } else {
- // Found an undeleted node destination: point to it directly.
- // Note that we're using the
- target.setAttribute(ANDROID_URI, transfer.name, attribute.getValue());
- }
- } else {
- // Pointing to parent or center etc (non-id ref): replicate this on the target
- target.setAttribute(ANDROID_URI, name, attribute.getValue());
- }
- }
- }
- }
-
- /**
- * Determines if two constraints are in the same direction and if so returns
- * the constraint in the same direction. Rather than returning boolean true
- * or false, this returns the constraint which is sometimes modified. For
- * example, if you have a node which points left to a node which is centered
- * in parent, then the constraint is turned into center horizontal.
- */
- @Nullable
- private static ConstraintType getCompatibleConstraint(
- @NonNull ConstraintType first, @NonNull ConstraintType second) {
- if (first == second) {
- return first;
- }
-
- switch (second) {
- case ALIGN_LEFT:
- case LAYOUT_RIGHT_OF:
- switch (first) {
- case LAYOUT_CENTER_HORIZONTAL:
- case LAYOUT_LEFT_OF:
- case ALIGN_LEFT:
- return first;
- case LAYOUT_CENTER_IN_PARENT:
- return LAYOUT_CENTER_HORIZONTAL;
- }
- return null;
-
- case ALIGN_RIGHT:
- case LAYOUT_LEFT_OF:
- switch (first) {
- case LAYOUT_CENTER_HORIZONTAL:
- case ALIGN_RIGHT:
- case LAYOUT_LEFT_OF:
- return first;
- case LAYOUT_CENTER_IN_PARENT:
- return LAYOUT_CENTER_HORIZONTAL;
- }
- return null;
-
- case ALIGN_TOP:
- case LAYOUT_BELOW:
- case ALIGN_BASELINE:
- switch (first) {
- case LAYOUT_CENTER_VERTICAL:
- case ALIGN_TOP:
- case LAYOUT_BELOW:
- case ALIGN_BASELINE:
- return first;
- case LAYOUT_CENTER_IN_PARENT:
- return LAYOUT_CENTER_VERTICAL;
- }
- return null;
- case ALIGN_BOTTOM:
- case LAYOUT_ABOVE:
- switch (first) {
- case LAYOUT_CENTER_VERTICAL:
- case ALIGN_BOTTOM:
- case LAYOUT_ABOVE:
- case ALIGN_BASELINE:
- return first;
- case LAYOUT_CENTER_IN_PARENT:
- return LAYOUT_CENTER_VERTICAL;
- }
- return null;
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/DependencyGraph.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/DependencyGraph.java
deleted file mode 100644
index 43d52d137..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/DependencyGraph.java
+++ /dev/null
@@ -1,326 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout.relative;
-
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ATTR_LAYOUT_RESOURCE_PREFIX;
-import static com.android.SdkConstants.VALUE_TRUE;
-
-
-import com.android.SdkConstants;
-import static com.android.SdkConstants.ANDROID_URI;
-import com.android.ide.common.api.IDragElement;
-import com.android.ide.common.api.IDragElement.IDragAttribute;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.INode.IAttribute;
-import com.android.ide.common.layout.BaseLayoutRule;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Data structure about relative layout relationships which makes it possible to:
- * <ul>
- * <li> Quickly determine not just the dependencies on other nodes, but which nodes
- * depend on this node such that they can be visualized for the selection
- * <li> Determine if there are cyclic dependencies, and whether a potential move
- * would result in a cycle
- * <li> Determine the "depth" of a given node (in terms of how many connections it
- * is away from a parent edge) such that we can prioritize connections which
- * minimizes the depth
- * </ul>
- */
-class DependencyGraph {
- /** Format to chain include cycles in: a=>b=>c=>d etc */
- static final String CHAIN_FORMAT = "%1$s=>%2$s"; //$NON-NLS-1$
-
- /** Format to chain constraint dependencies: button 1 above button2 etc */
- private static final String DEPENDENCY_FORMAT = "%1$s %2$s %3$s"; //$NON-NLS-1$
-
- private final Map<String, ViewData> mIdToView = new HashMap<String, ViewData>();
- private final Map<INode, ViewData> mNodeToView = new HashMap<INode, ViewData>();
-
- /** Constructs a new {@link DependencyGraph} for the given relative layout */
- DependencyGraph(INode layout) {
- INode[] nodes = layout.getChildren();
-
- // Parent view:
- String parentId = layout.getStringAttr(ANDROID_URI, ATTR_ID);
- if (parentId != null) {
- parentId = BaseLayoutRule.stripIdPrefix(parentId);
- } else {
- parentId = "RelativeLayout"; // For display purposes; we never reference
- // the parent id from a constraint, only via parent-relative params
- // like centerInParent
- }
- ViewData parentView = new ViewData(layout, parentId);
- mNodeToView.put(layout, parentView);
- if (parentId != null) {
- mIdToView.put(parentId, parentView);
- }
-
- for (INode child : nodes) {
- String id = child.getStringAttr(ANDROID_URI, ATTR_ID);
- if (id != null) {
- id = BaseLayoutRule.stripIdPrefix(id);
- }
- ViewData view = new ViewData(child, id);
- mNodeToView.put(child, view);
- if (id != null) {
- mIdToView.put(id, view);
- }
- }
-
- for (ViewData view : mNodeToView.values()) {
- for (IAttribute attribute : view.node.getLiveAttributes()) {
- String name = attribute.getName();
- ConstraintType type = ConstraintType.fromAttribute(name);
- if (type != null) {
- String value = attribute.getValue();
-
- if (type.targetParent) {
- if (value.equals(VALUE_TRUE)) {
- Constraint constraint = new Constraint(type, view, parentView);
- view.dependsOn.add(constraint);
- parentView.dependedOnBy.add(constraint);
- }
- } else {
- // id-based constraint.
- // NOTE: The id could refer to some widget that is NOT a sibling!
- String targetId = BaseLayoutRule.stripIdPrefix(value);
- ViewData target = mIdToView.get(targetId);
- if (target == view) {
- // Self-reference. RelativeLayout ignores these so it's
- // not an error like a deeper cycle (where RelativeLayout
- // will throw an exception), but we might as well warn
- // the user about it.
- // TODO: Where do we emit this error?
- } else if (target != null) {
- Constraint constraint = new Constraint(type, view, target);
- view.dependsOn.add(constraint);
- target.dependedOnBy.add(constraint);
- } else {
- // This is valid but we might want to warn...
- //System.out.println("Warning: no view data found for " + targetId);
- }
- }
- }
- }
- }
- }
-
- public ViewData getView(IDragElement element) {
- IDragAttribute attribute = element.getAttribute(ANDROID_URI, ATTR_ID);
- if (attribute != null) {
- String id = attribute.getValue();
- id = BaseLayoutRule.stripIdPrefix(id);
- return getView(id);
- }
-
- return null;
- }
-
- public ViewData getView(String id) {
- return mIdToView.get(id);
- }
-
- public ViewData getView(INode node) {
- return mNodeToView.get(node);
- }
-
- /**
- * Returns the set of views that depend on the given node in either the horizontal or
- * vertical direction
- *
- * @param nodes the set of nodes that we want to compute the transitive dependencies
- * for
- * @param vertical if true, look for vertical edge dependencies, otherwise look for
- * horizontal edge dependencies
- * @return the set of nodes that directly or indirectly depend on the given nodes in
- * the given direction
- */
- public Set<INode> dependsOn(Collection<? extends INode> nodes, boolean vertical) {
- List<ViewData> reachable = new ArrayList<ViewData>();
-
- // Traverse the graph of constraints and determine all nodes affected by
- // this node
- Set<ViewData> visiting = new HashSet<ViewData>();
- for (INode node : nodes) {
- ViewData view = mNodeToView.get(node);
- if (view != null) {
- findBackwards(view, visiting, reachable, vertical, view);
- }
- }
-
- Set<INode> dependents = new HashSet<INode>(reachable.size());
-
- for (ViewData v : reachable) {
- dependents.add(v.node);
- }
-
- return dependents;
- }
-
- private void findBackwards(ViewData view,
- Set<ViewData> visiting, List<ViewData> reachable,
- boolean vertical, ViewData start) {
- visiting.add(view);
- reachable.add(view);
-
- for (Constraint constraint : view.dependedOnBy) {
- if (vertical && !constraint.type.verticalEdge) {
- continue;
- } else if (!vertical && !constraint.type.horizontalEdge) {
- continue;
- }
-
- assert constraint.to == view;
- ViewData from = constraint.from;
- if (visiting.contains(from)) {
- // Cycle - what do we do to highlight this?
- List<Constraint> path = getPathTo(start.node, view.node, vertical);
- if (path != null) {
- // TODO: display to the user somehow. We need log access for the
- // view rules.
- System.out.println(Constraint.describePath(path, null, null));
- }
- } else {
- findBackwards(from, visiting, reachable, vertical, start);
- }
- }
-
- visiting.remove(view);
- }
-
- public List<Constraint> getPathTo(INode from, INode to, boolean vertical) {
- // Traverse the graph of constraints and determine all nodes affected by
- // this node
- Set<ViewData> visiting = new HashSet<ViewData>();
- List<Constraint> path = new ArrayList<Constraint>();
- ViewData view = mNodeToView.get(from);
- if (view != null) {
- return findForwards(view, visiting, path, vertical, to);
- }
-
- return null;
- }
-
- private List<Constraint> findForwards(ViewData view, Set<ViewData> visiting,
- List<Constraint> path, boolean vertical, INode target) {
- visiting.add(view);
-
- for (Constraint constraint : view.dependsOn) {
- if (vertical && !constraint.type.verticalEdge) {
- continue;
- } else if (!vertical && !constraint.type.horizontalEdge) {
- continue;
- }
-
- try {
- path.add(constraint);
-
- if (constraint.to.node == target) {
- return new ArrayList<Constraint>(path);
- }
-
- assert constraint.from == view;
- ViewData to = constraint.to;
- if (visiting.contains(to)) {
- // CYCLE!
- continue;
- }
-
- List<Constraint> chain = findForwards(to, visiting, path, vertical, target);
- if (chain != null) {
- return chain;
- }
- } finally {
- path.remove(constraint);
- }
- }
-
- visiting.remove(view);
-
- return null;
- }
-
- /**
- * Info about a specific widget child of a relative layout and its constraints. This
- * is a node in the dependency graph.
- */
- static class ViewData {
- public final INode node;
- public final String id;
- public final List<Constraint> dependsOn = new ArrayList<Constraint>(4);
- public final List<Constraint> dependedOnBy = new ArrayList<Constraint>(8);
-
- ViewData(INode node, String id) {
- this.node = node;
- this.id = id;
- }
- }
-
- /**
- * Info about a specific constraint between two widgets in a relative layout. This is
- * an edge in the dependency graph.
- */
- static class Constraint {
- public final ConstraintType type;
- public final ViewData from;
- public final ViewData to;
-
- // TODO: Initialize depth -- should be computed independently for top, left, etc.
- // We can use this in GuidelineHandler.MatchComparator to prefer matches that
- // are closer to a parent edge:
- //public int depth;
-
- Constraint(ConstraintType type, ViewData from, ViewData to) {
- this.type = type;
- this.from = from;
- this.to = to;
- }
-
- static String describePath(List<Constraint> path, String newName, String newId) {
- String s = "";
- for (int i = path.size() - 1; i >= 0; i--) {
- Constraint constraint = path.get(i);
- String suffix = (i == path.size() -1) ? constraint.to.id : s;
- s = String.format(DEPENDENCY_FORMAT, constraint.from.id,
- stripLayoutAttributePrefix(constraint.type.name), suffix);
- }
-
- if (newName != null) {
- s = String.format(DEPENDENCY_FORMAT, s, stripLayoutAttributePrefix(newName),
- BaseLayoutRule.stripIdPrefix(newId));
- }
-
- return s;
- }
-
- private static String stripLayoutAttributePrefix(String name) {
- if (name.startsWith(ATTR_LAYOUT_RESOURCE_PREFIX)) {
- return name.substring(ATTR_LAYOUT_RESOURCE_PREFIX.length());
- }
-
- return name;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/GuidelineHandler.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/GuidelineHandler.java
deleted file mode 100644
index db08b1857..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/GuidelineHandler.java
+++ /dev/null
@@ -1,839 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout.relative;
-
-import static com.android.ide.common.api.MarginType.NO_MARGIN;
-import static com.android.ide.common.api.MarginType.WITHOUT_MARGIN;
-import static com.android.ide.common.api.MarginType.WITH_MARGIN;
-import static com.android.ide.common.api.SegmentType.BASELINE;
-import static com.android.ide.common.api.SegmentType.BOTTOM;
-import static com.android.ide.common.api.SegmentType.CENTER_HORIZONTAL;
-import static com.android.ide.common.api.SegmentType.CENTER_VERTICAL;
-import static com.android.ide.common.api.SegmentType.LEFT;
-import static com.android.ide.common.api.SegmentType.RIGHT;
-import static com.android.ide.common.api.SegmentType.TOP;
-import static com.android.ide.common.layout.BaseLayoutRule.getMaxMatchDistance;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ATTR_LAYOUT_ABOVE;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_BASELINE;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_BOTTOM;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_LEFT;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_PARENT_BOTTOM;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_PARENT_LEFT;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_PARENT_RIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_PARENT_TOP;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_RIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_TOP;
-import static com.android.SdkConstants.ATTR_LAYOUT_BELOW;
-import static com.android.SdkConstants.ATTR_LAYOUT_CENTER_HORIZONTAL;
-import static com.android.SdkConstants.ATTR_LAYOUT_CENTER_IN_PARENT;
-import static com.android.SdkConstants.ATTR_LAYOUT_CENTER_VERTICAL;
-import static com.android.SdkConstants.ATTR_LAYOUT_MARGIN_BOTTOM;
-import static com.android.SdkConstants.ATTR_LAYOUT_MARGIN_LEFT;
-import static com.android.SdkConstants.ATTR_LAYOUT_MARGIN_RIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_MARGIN_TOP;
-import static com.android.SdkConstants.ATTR_LAYOUT_TO_LEFT_OF;
-import static com.android.SdkConstants.ATTR_LAYOUT_TO_RIGHT_OF;
-import static com.android.SdkConstants.VALUE_N_DP;
-import static com.android.SdkConstants.VALUE_TRUE;
-import static com.android.ide.common.layout.relative.ConstraintType.ALIGN_BASELINE;
-
-import static java.lang.Math.abs;
-
-import com.android.SdkConstants;
-import static com.android.SdkConstants.ANDROID_URI;
-import com.android.ide.common.api.DropFeedback;
-import com.android.ide.common.api.IClientRulesEngine;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.Margins;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.api.Segment;
-import com.android.ide.common.api.SegmentType;
-import com.android.ide.common.layout.BaseLayoutRule;
-import com.android.ide.common.layout.relative.DependencyGraph.Constraint;
-import com.android.ide.common.layout.relative.DependencyGraph.ViewData;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
-import java.util.Set;
-
-/**
- * The {@link GuidelineHandler} class keeps track of state related to a guideline operation
- * like move and resize, and performs various constraint computations.
- */
-public class GuidelineHandler {
- /**
- * A dependency graph for the relative layout recording constraint relationships
- */
- protected DependencyGraph mDependencyGraph;
-
- /** The RelativeLayout we are moving/resizing within */
- public INode layout;
-
- /** The set of nodes being dragged (may be null) */
- protected Collection<INode> mDraggedNodes;
-
- /** The bounds of the primary child node being dragged */
- protected Rect mBounds;
-
- /** Whether the left edge is being moved/resized */
- protected boolean mMoveLeft;
-
- /** Whether the right edge is being moved/resized */
- protected boolean mMoveRight;
-
- /** Whether the top edge is being moved/resized */
- protected boolean mMoveTop;
-
- /** Whether the bottom edge is being moved/resized */
- protected boolean mMoveBottom;
-
- /**
- * Whether the drop/move/resize position should be snapped (which can be turned off
- * with a modifier key during the operation)
- */
- protected boolean mSnap = true;
-
- /**
- * The set of nodes which depend on the currently selected nodes, including
- * transitively, through horizontal constraints (a "horizontal constraint"
- * is a constraint between two horizontal edges)
- */
- protected Set<INode> mHorizontalDeps;
-
- /**
- * The set of nodes which depend on the currently selected nodes, including
- * transitively, through vertical constraints (a "vertical constraint"
- * is a constraint between two vertical edges)
- */
- protected Set<INode> mVerticalDeps;
-
- /** The current list of constraints which result in a horizontal cycle (if applicable) */
- protected List<Constraint> mHorizontalCycle;
-
- /** The current list of constraints which result in a vertical cycle (if applicable) */
- protected List<Constraint> mVerticalCycle;
-
- /**
- * All horizontal segments in the relative layout - top and bottom edges, baseline
- * edges, and top and bottom edges offset by the applicable margins in each direction
- */
- protected List<Segment> mHorizontalEdges;
-
- /**
- * All vertical segments in the relative layout - left and right edges, and left and
- * right edges offset by the applicable margins in each direction
- */
- protected List<Segment> mVerticalEdges;
-
- /**
- * All center vertical segments in the relative layout. These are kept separate since
- * they only match other center edges.
- */
- protected List<Segment> mCenterVertEdges;
-
- /**
- * All center horizontal segments in the relative layout. These are kept separate
- * since they only match other center edges.
- */
- protected List<Segment> mCenterHorizEdges;
-
- /**
- * Suggestions for horizontal matches. There could be more than one, but all matches
- * will be equidistant from the current position (as well as in the same direction,
- * which means that you can't have one match 5 pixels to the left and one match 5
- * pixels to the right since it would be impossible to snap to fit with both; you can
- * however have multiple matches all 5 pixels to the left.)
- * <p
- * The best vertical match will be found in {@link #mCurrentTopMatch} or
- * {@link #mCurrentBottomMatch}.
- */
- protected List<Match> mHorizontalSuggestions;
-
- /**
- * Suggestions for vertical matches.
- * <p
- * The best vertical match will be found in {@link #mCurrentLeftMatch} or
- * {@link #mCurrentRightMatch}.
- */
- protected List<Match> mVerticalSuggestions;
-
- /**
- * The current match on the left edge, or null if no match or if the left edge is not
- * being moved or resized.
- */
- protected Match mCurrentLeftMatch;
-
- /**
- * The current match on the top edge, or null if no match or if the top edge is not
- * being moved or resized.
- */
- protected Match mCurrentTopMatch;
-
- /**
- * The current match on the right edge, or null if no match or if the right edge is
- * not being moved or resized.
- */
- protected Match mCurrentRightMatch;
-
- /**
- * The current match on the bottom edge, or null if no match or if the bottom edge is
- * not being moved or resized.
- */
- protected Match mCurrentBottomMatch;
-
- /**
- * The amount of margin to add to the top edge, or 0
- */
- protected int mTopMargin;
-
- /**
- * The amount of margin to add to the bottom edge, or 0
- */
- protected int mBottomMargin;
-
- /**
- * The amount of margin to add to the left edge, or 0
- */
- protected int mLeftMargin;
-
- /**
- * The amount of margin to add to the right edge, or 0
- */
- protected int mRightMargin;
-
- /**
- * The associated rules engine
- */
- protected IClientRulesEngine mRulesEngine;
-
- /**
- * Construct a new {@link GuidelineHandler} for the given relative layout.
- *
- * @param layout the RelativeLayout to handle
- */
- GuidelineHandler(INode layout, IClientRulesEngine rulesEngine) {
- this.layout = layout;
- mRulesEngine = rulesEngine;
-
- mHorizontalEdges = new ArrayList<Segment>();
- mVerticalEdges = new ArrayList<Segment>();
- mCenterVertEdges = new ArrayList<Segment>();
- mCenterHorizEdges = new ArrayList<Segment>();
- mDependencyGraph = new DependencyGraph(layout);
- }
-
- /**
- * Returns true if the handler has any suggestions to offer
- *
- * @return true if the handler has any suggestions to offer
- */
- public boolean haveSuggestions() {
- return mCurrentLeftMatch != null || mCurrentTopMatch != null
- || mCurrentRightMatch != null || mCurrentBottomMatch != null;
- }
-
- /**
- * Returns the closest match.
- *
- * @return the closest match, or null if nothing matched
- */
- protected Match pickBestMatch(List<Match> matches) {
- int alternatives = matches.size();
- if (alternatives == 0) {
- return null;
- } else if (alternatives == 1) {
- Match match = matches.get(0);
- return match;
- } else {
- assert alternatives > 1;
- Collections.sort(matches, new MatchComparator());
- return matches.get(0);
- }
- }
-
- private boolean checkCycle(DropFeedback feedback, Match match, boolean vertical) {
- if (match != null && match.cycle) {
- for (INode node : mDraggedNodes) {
- INode from = match.edge.node;
- assert match.with.node == null || match.with.node == node;
- INode to = node;
- List<Constraint> path = mDependencyGraph.getPathTo(from, to, vertical);
- if (path != null) {
- if (vertical) {
- mVerticalCycle = path;
- } else {
- mHorizontalCycle = path;
- }
- String desc = Constraint.describePath(path,
- match.type.name, match.edge.id);
-
- feedback.errorMessage = "Constraint creates a cycle: " + desc;
- return true;
- }
- }
- }
-
- return false;
- }
-
- /**
- * Checks for any cycles in the dependencies
- *
- * @param feedback the drop feedback state
- */
- public void checkCycles(DropFeedback feedback) {
- // Deliberate short circuit evaluation -- only list the first cycle
- feedback.errorMessage = null;
- mHorizontalCycle = null;
- mVerticalCycle = null;
-
- if (checkCycle(feedback, mCurrentTopMatch, true /* vertical */)
- || checkCycle(feedback, mCurrentBottomMatch, true)) {
- }
-
- if (checkCycle(feedback, mCurrentLeftMatch, false)
- || checkCycle(feedback, mCurrentRightMatch, false)) {
- }
- }
-
- /** Records the matchable outside edges for the given node to the potential match list */
- protected void addBounds(INode node, String id,
- boolean addHorizontal, boolean addVertical) {
- Rect b = node.getBounds();
- Margins margins = node.getMargins();
- if (addHorizontal) {
- if (margins.top != 0) {
- mHorizontalEdges.add(new Segment(b.y, b.x, b.x2(), node, id, TOP, WITHOUT_MARGIN));
- mHorizontalEdges.add(new Segment(b.y - margins.top, b.x, b.x2(), node, id,
- TOP, WITH_MARGIN));
- } else {
- mHorizontalEdges.add(new Segment(b.y, b.x, b.x2(), node, id, TOP, NO_MARGIN));
- }
- if (margins.bottom != 0) {
- mHorizontalEdges.add(new Segment(b.y2(), b.x, b.x2(), node, id, BOTTOM,
- WITHOUT_MARGIN));
- mHorizontalEdges.add(new Segment(b.y2() + margins.bottom, b.x, b.x2(), node,
- id, BOTTOM, WITH_MARGIN));
- } else {
- mHorizontalEdges.add(new Segment(b.y2(), b.x, b.x2(), node, id,
- BOTTOM, NO_MARGIN));
- }
- }
- if (addVertical) {
- if (margins.left != 0) {
- mVerticalEdges.add(new Segment(b.x, b.y, b.y2(), node, id, LEFT, WITHOUT_MARGIN));
- mVerticalEdges.add(new Segment(b.x - margins.left, b.y, b.y2(), node, id, LEFT,
- WITH_MARGIN));
- } else {
- mVerticalEdges.add(new Segment(b.x, b.y, b.y2(), node, id, LEFT, NO_MARGIN));
- }
-
- if (margins.right != 0) {
- mVerticalEdges.add(new Segment(b.x2(), b.y, b.y2(), node, id,
- RIGHT, WITHOUT_MARGIN));
- mVerticalEdges.add(new Segment(b.x2() + margins.right, b.y, b.y2(), node, id,
- RIGHT, WITH_MARGIN));
- } else {
- mVerticalEdges.add(new Segment(b.x2(), b.y, b.y2(), node, id,
- RIGHT, NO_MARGIN));
- }
- }
- }
-
- /** Records the center edges for the given node to the potential match list */
- protected void addCenter(INode node, String id,
- boolean addHorizontal, boolean addVertical) {
- Rect b = node.getBounds();
-
- if (addHorizontal) {
- mCenterHorizEdges.add(new Segment(b.centerY(), b.x, b.x2(),
- node, id, CENTER_HORIZONTAL, NO_MARGIN));
- }
- if (addVertical) {
- mCenterVertEdges.add(new Segment(b.centerX(), b.y, b.y2(),
- node, id, CENTER_VERTICAL, NO_MARGIN));
- }
- }
-
- /** Records the baseline edge for the given node to the potential match list */
- protected int addBaseLine(INode node, String id) {
- int baselineY = node.getBaseline();
- if (baselineY != -1) {
- Rect b = node.getBounds();
- mHorizontalEdges.add(new Segment(b.y + baselineY, b.x, b.x2(), node, id, BASELINE,
- NO_MARGIN));
- }
-
- return baselineY;
- }
-
- protected void snapVertical(Segment vEdge, int x, Rect newBounds) {
- newBounds.x = x;
- }
-
- protected void snapHorizontal(Segment hEdge, int y, Rect newBounds) {
- newBounds.y = y;
- }
-
- /**
- * Returns whether two edge types are compatible. For example, we only match the
- * center of one object with the center of another.
- *
- * @param edge the first edge type to compare
- * @param dragged the second edge type to compare the first one with
- * @param delta the delta between the two edge locations
- * @return true if the two edge types can be compatibly matched
- */
- protected boolean isEdgeTypeCompatible(SegmentType edge, SegmentType dragged, int delta) {
-
- if (Math.abs(delta) > BaseLayoutRule.getMaxMatchDistance()) {
- if (dragged == LEFT || dragged == TOP) {
- if (delta > 0) {
- return false;
- }
- } else {
- if (delta < 0) {
- return false;
- }
- }
- }
-
- switch (edge) {
- case BOTTOM:
- case TOP:
- return dragged == TOP || dragged == BOTTOM;
- case LEFT:
- case RIGHT:
- return dragged == LEFT || dragged == RIGHT;
-
- // Center horizontal, center vertical and Baseline only matches the same
- // type, and only within the matching distance -- no margins!
- case BASELINE:
- case CENTER_HORIZONTAL:
- case CENTER_VERTICAL:
- return dragged == edge && Math.abs(delta) < getMaxMatchDistance();
- default: assert false : edge;
- }
- return false;
- }
-
- /**
- * Finds the closest matching segments among the given list of edges for the given
- * dragged edge, and returns these as a list of matches
- */
- protected List<Match> findClosest(Segment draggedEdge, List<Segment> edges) {
- List<Match> closest = new ArrayList<Match>();
- addClosest(draggedEdge, edges, closest);
- return closest;
- }
-
- protected void addClosest(Segment draggedEdge, List<Segment> edges,
- List<Match> closest) {
- int at = draggedEdge.at;
- int closestDelta = closest.size() > 0 ? closest.get(0).delta : Integer.MAX_VALUE;
- int closestDistance = abs(closestDelta);
- for (Segment edge : edges) {
- assert draggedEdge.edgeType.isHorizontal() == edge.edgeType.isHorizontal();
-
- int delta = edge.at - at;
- int distance = abs(delta);
- if (distance > closestDistance) {
- continue;
- }
-
- if (!isEdgeTypeCompatible(edge.edgeType, draggedEdge.edgeType, delta)) {
- continue;
- }
-
- boolean withParent = edge.node == layout;
- ConstraintType type = ConstraintType.forMatch(withParent,
- draggedEdge.edgeType, edge.edgeType);
- if (type == null) {
- continue;
- }
-
- // Ensure that the edge match is compatible; for example, a "below"
- // constraint can only apply to the margin bounds and a "bottom"
- // constraint can only apply to the non-margin bounds.
- if (type.relativeToMargin && edge.marginType == WITHOUT_MARGIN) {
- continue;
- } else if (!type.relativeToMargin && edge.marginType == WITH_MARGIN) {
- continue;
- }
-
- Match match = new Match(this, edge, draggedEdge, type, delta);
-
- if (distance < closestDistance) {
- closest.clear();
- closestDistance = distance;
- closestDelta = delta;
- } else if (delta * closestDelta < 0) {
- // They have different signs, e.g. the matches are equal but
- // on opposite sides; can't accept them both
- continue;
- }
- closest.add(match);
- }
- }
-
- protected void clearSuggestions() {
- mHorizontalSuggestions = mVerticalSuggestions = null;
- mCurrentLeftMatch = mCurrentRightMatch = null;
- mCurrentTopMatch = mCurrentBottomMatch = null;
- }
-
- /**
- * Given a node, apply the suggestions by expressing them as relative layout param
- * values
- *
- * @param n the node to apply constraints to
- */
- public void applyConstraints(INode n) {
- // Process each edge separately
- String centerBoth = n.getStringAttr(ANDROID_URI, ATTR_LAYOUT_CENTER_IN_PARENT);
- if (centerBoth != null && centerBoth.equals(VALUE_TRUE)) {
- n.setAttribute(ANDROID_URI, ATTR_LAYOUT_CENTER_IN_PARENT, null);
-
- // If you had a center-in-both-directions attribute, and you're
- // only resizing in one dimension, then leave the other dimension
- // centered, e.g. if you have centerInParent and apply alignLeft,
- // then you should end up with alignLeft and centerVertically
- if (mCurrentTopMatch == null && mCurrentBottomMatch == null) {
- n.setAttribute(ANDROID_URI, ATTR_LAYOUT_CENTER_VERTICAL, VALUE_TRUE);
- }
- if (mCurrentLeftMatch == null && mCurrentRightMatch == null) {
- n.setAttribute(ANDROID_URI, ATTR_LAYOUT_CENTER_HORIZONTAL, VALUE_TRUE);
- }
- }
-
- if (mMoveTop) {
- // Remove top attachments
- n.setAttribute(ANDROID_URI, ATTR_LAYOUT_ALIGN_PARENT_TOP, null);
- n.setAttribute(ANDROID_URI, ATTR_LAYOUT_ALIGN_TOP, null);
- n.setAttribute(ANDROID_URI, ATTR_LAYOUT_BELOW, null);
-
- n.setAttribute(ANDROID_URI, ATTR_LAYOUT_CENTER_VERTICAL, null);
- n.setAttribute(ANDROID_URI, ATTR_LAYOUT_ALIGN_BASELINE, null);
-
- }
-
- if (mMoveBottom) {
- // Remove bottom attachments
- n.setAttribute(ANDROID_URI, ATTR_LAYOUT_ALIGN_PARENT_BOTTOM, null);
- n.setAttribute(ANDROID_URI, ATTR_LAYOUT_ALIGN_BOTTOM, null);
- n.setAttribute(ANDROID_URI, ATTR_LAYOUT_ABOVE, null);
- n.setAttribute(ANDROID_URI, ATTR_LAYOUT_CENTER_VERTICAL, null);
- n.setAttribute(ANDROID_URI, ATTR_LAYOUT_ALIGN_BASELINE, null);
- }
-
- if (mMoveLeft) {
- // Remove left attachments
- n.setAttribute(ANDROID_URI, ATTR_LAYOUT_ALIGN_PARENT_LEFT, null);
- n.setAttribute(ANDROID_URI, ATTR_LAYOUT_ALIGN_LEFT, null);
- n.setAttribute(ANDROID_URI, ATTR_LAYOUT_TO_RIGHT_OF, null);
- n.setAttribute(ANDROID_URI, ATTR_LAYOUT_CENTER_HORIZONTAL, null);
- }
-
- if (mMoveRight) {
- // Remove right attachments
- n.setAttribute(ANDROID_URI, ATTR_LAYOUT_ALIGN_PARENT_RIGHT, null);
- n.setAttribute(ANDROID_URI, ATTR_LAYOUT_ALIGN_RIGHT, null);
- n.setAttribute(ANDROID_URI, ATTR_LAYOUT_TO_LEFT_OF, null);
- n.setAttribute(ANDROID_URI, ATTR_LAYOUT_CENTER_HORIZONTAL, null);
- }
-
- if (mMoveTop && mCurrentTopMatch != null) {
- applyConstraint(n, mCurrentTopMatch.getConstraint(true /* generateId */));
- if (mCurrentTopMatch.type == ALIGN_BASELINE) {
- // HACK! WORKAROUND! Baseline doesn't provide a new bottom edge for attachments
- String c = mCurrentTopMatch.getConstraint(true);
- c = c.replace(ATTR_LAYOUT_ALIGN_BASELINE, ATTR_LAYOUT_ALIGN_BOTTOM);
- applyConstraint(n, c);
- }
- }
-
- if (mMoveBottom && mCurrentBottomMatch != null) {
- applyConstraint(n, mCurrentBottomMatch.getConstraint(true));
- }
-
- if (mMoveLeft && mCurrentLeftMatch != null) {
- applyConstraint(n, mCurrentLeftMatch.getConstraint(true));
- }
-
- if (mMoveRight && mCurrentRightMatch != null) {
- applyConstraint(n, mCurrentRightMatch.getConstraint(true));
- }
-
- if (mMoveLeft) {
- applyMargin(n, ATTR_LAYOUT_MARGIN_LEFT, mLeftMargin);
- }
- if (mMoveRight) {
- applyMargin(n, ATTR_LAYOUT_MARGIN_RIGHT, mRightMargin);
- }
- if (mMoveTop) {
- applyMargin(n, ATTR_LAYOUT_MARGIN_TOP, mTopMargin);
- }
- if (mMoveBottom) {
- applyMargin(n, ATTR_LAYOUT_MARGIN_BOTTOM, mBottomMargin);
- }
- }
-
- private void applyConstraint(INode n, String constraint) {
- assert constraint.contains("=") : constraint;
- String name = constraint.substring(0, constraint.indexOf('='));
- String value = constraint.substring(constraint.indexOf('=') + 1);
- n.setAttribute(ANDROID_URI, name, value);
- }
-
- private void applyMargin(INode n, String marginAttribute, int margin) {
- if (margin > 0) {
- int dp = mRulesEngine.pxToDp(margin);
- n.setAttribute(ANDROID_URI, marginAttribute, String.format(VALUE_N_DP, dp));
- } else if (n.getStringAttr(ANDROID_URI, marginAttribute) != null) {
- // Clear out existing margin
- n.setAttribute(ANDROID_URI, marginAttribute, null);
- }
- }
-
- private void removeRelativeParams(INode node) {
- for (ConstraintType type : ConstraintType.values()) {
- node.setAttribute(ANDROID_URI, type.name, null);
- }
- node.setAttribute(ANDROID_URI,ATTR_LAYOUT_MARGIN_LEFT, null);
- node.setAttribute(ANDROID_URI,ATTR_LAYOUT_MARGIN_RIGHT, null);
- node.setAttribute(ANDROID_URI,ATTR_LAYOUT_MARGIN_TOP, null);
- node.setAttribute(ANDROID_URI,ATTR_LAYOUT_MARGIN_BOTTOM, null);
- }
-
- /**
- * Attach the new child to the previous node
- * @param previous the previous child
- * @param node the new child to attach it to
- */
- public void attachPrevious(INode previous, INode node) {
- removeRelativeParams(node);
-
- String id = previous.getStringAttr(ANDROID_URI, ATTR_ID);
- if (id == null) {
- return;
- }
-
- if (mCurrentTopMatch != null || mCurrentBottomMatch != null) {
- // Attaching the top: arrange below, and for bottom arrange above
- node.setAttribute(ANDROID_URI,
- mCurrentTopMatch != null ? ATTR_LAYOUT_BELOW : ATTR_LAYOUT_ABOVE, id);
- // Apply same left/right constraints as the parent
- if (mCurrentLeftMatch != null) {
- applyConstraint(node, mCurrentLeftMatch.getConstraint(true));
- applyMargin(node, ATTR_LAYOUT_MARGIN_LEFT, mLeftMargin);
- } else if (mCurrentRightMatch != null) {
- applyConstraint(node, mCurrentRightMatch.getConstraint(true));
- applyMargin(node, ATTR_LAYOUT_MARGIN_RIGHT, mRightMargin);
- }
- } else if (mCurrentLeftMatch != null || mCurrentRightMatch != null) {
- node.setAttribute(ANDROID_URI,
- mCurrentLeftMatch != null ? ATTR_LAYOUT_TO_RIGHT_OF : ATTR_LAYOUT_TO_LEFT_OF,
- id);
- // Apply same top/bottom constraints as the parent
- if (mCurrentTopMatch != null) {
- applyConstraint(node, mCurrentTopMatch.getConstraint(true));
- applyMargin(node, ATTR_LAYOUT_MARGIN_TOP, mTopMargin);
- } else if (mCurrentBottomMatch != null) {
- applyConstraint(node, mCurrentBottomMatch.getConstraint(true));
- applyMargin(node, ATTR_LAYOUT_MARGIN_BOTTOM, mBottomMargin);
- }
- } else {
- return;
- }
- }
-
- /** Breaks any cycles detected by the handler */
- public void removeCycles() {
- if (mHorizontalCycle != null) {
- removeCycles(mHorizontalDeps);
- }
- if (mVerticalCycle != null) {
- removeCycles(mVerticalDeps);
- }
- }
-
- private void removeCycles(Set<INode> deps) {
- for (INode node : mDraggedNodes) {
- ViewData view = mDependencyGraph.getView(node);
- if (view != null) {
- for (Constraint constraint : view.dependedOnBy) {
- // For now, remove ALL constraints pointing to this node in this orientation.
- // Later refine this to be smarter. (We can't JUST remove the constraints
- // identified in the cycle since there could be multiple.)
- constraint.from.node.setAttribute(ANDROID_URI, constraint.type.name, null);
- }
- }
- }
- }
-
- /**
- * Comparator used to sort matches such that the first match is the most desirable
- * match (where we prefer attaching to parent bounds, we avoid matches that lead to a
- * cycle, we prefer constraints on closer widgets rather than ones further away, and
- * so on.)
- * <p>
- * There are a number of sorting criteria. One of them is the distance between the
- * matched edges. We may end up with multiple matches that are the same distance. In
- * that case we look at the orientation; on the left side, prefer left-oriented
- * attachments, and on the right-side prefer right-oriented attachments. For example,
- * consider the following scenario:
- *
- * <pre>
- * +--------------------+-------------------------+
- * | Attached on left | |
- * +--------------------+ |
- * | |
- * | +-----+ |
- * | | A | |
- * | +-----+ |
- * | |
- * | +-------------------------+
- * | | Attached on right |
- * +--------------------+-------------------------+
- * </pre>
- *
- * Here, dragging the left edge should attach to the top left attached view, whereas
- * in the following layout dragging the right edge would attach to the bottom view:
- *
- * <pre>
- * +--------------------------+-------------------+
- * | Attached on left | |
- * +--------------------------+ |
- * | |
- * | +-----+ |
- * | | A | |
- * | +-----+ |
- * | |
- * | +-------------------+
- * | | Attached on right |
- * +--------------------------+-------------------+
- *
- * </pre>
- *
- * </ul>
- */
- private final class MatchComparator implements Comparator<Match> {
- @Override
- public int compare(Match m1, Match m2) {
- // Always prefer matching parent bounds
- int parent1 = m1.edge.node == layout ? -1 : 1;
- int parent2 = m2.edge.node == layout ? -1 : 1;
- // unless it's a center bound -- those should always get lowest priority since
- // they overlap with other usually more interesting edges near the center of
- // the layout.
- if (m1.edge.edgeType == CENTER_HORIZONTAL
- || m1.edge.edgeType == CENTER_VERTICAL) {
- parent1 = 2;
- }
- if (m2.edge.edgeType == CENTER_HORIZONTAL
- || m2.edge.edgeType == CENTER_VERTICAL) {
- parent2 = 2;
- }
- if (parent1 != parent2) {
- return parent1 - parent2;
- }
-
- // Avoid matching edges that would lead to a cycle
- if (m1.edge.edgeType.isHorizontal()) {
- int cycle1 = mHorizontalDeps.contains(m1.edge.node) ? 1 : -1;
- int cycle2 = mHorizontalDeps.contains(m2.edge.node) ? 1 : -1;
- if (cycle1 != cycle2) {
- return cycle1 - cycle2;
- }
- } else {
- int cycle1 = mVerticalDeps.contains(m1.edge.node) ? 1 : -1;
- int cycle2 = mVerticalDeps.contains(m2.edge.node) ? 1 : -1;
- if (cycle1 != cycle2) {
- return cycle1 - cycle2;
- }
- }
-
- // TODO: Sort by minimum depth -- do we have the depth anywhere?
-
- // Prefer nodes that are closer
- int distance1, distance2;
- if (m1.edge.to <= m1.with.from) {
- distance1 = m1.with.from - m1.edge.to;
- } else if (m1.edge.from >= m1.with.to) {
- distance1 = m1.edge.from - m1.with.to;
- } else {
- // Some kind of overlap - not sure how to prioritize these yet...
- distance1 = 0;
- }
- if (m2.edge.to <= m2.with.from) {
- distance2 = m2.with.from - m2.edge.to;
- } else if (m2.edge.from >= m2.with.to) {
- distance2 = m2.edge.from - m2.with.to;
- } else {
- // Some kind of overlap - not sure how to prioritize these yet...
- distance2 = 0;
- }
-
- if (distance1 != distance2) {
- return distance1 - distance2;
- }
-
- // Prefer matching on baseline
- int baseline1 = (m1.edge.edgeType == BASELINE) ? -1 : 1;
- int baseline2 = (m2.edge.edgeType == BASELINE) ? -1 : 1;
- if (baseline1 != baseline2) {
- return baseline1 - baseline2;
- }
-
- // Prefer matching top/left edges before matching bottom/right edges
- int orientation1 = (m1.with.edgeType == LEFT ||
- m1.with.edgeType == TOP) ? -1 : 1;
- int orientation2 = (m2.with.edgeType == LEFT ||
- m2.with.edgeType == TOP) ? -1 : 1;
- if (orientation1 != orientation2) {
- return orientation1 - orientation2;
- }
-
- // Prefer opposite-matching over same-matching.
- // In other words, if we have the choice of matching
- // our left edge with another element's left edge,
- // or matching our left edge with another element's right
- // edge, prefer the right edge since that
- // The two matches have identical distance; try to sort by
- // orientation
- int edgeType1 = (m1.edge.edgeType != m1.with.edgeType) ? -1 : 1;
- int edgeType2 = (m2.edge.edgeType != m2.with.edgeType) ? -1 : 1;
- if (edgeType1 != edgeType2) {
- return edgeType1 - edgeType2;
- }
-
- return 0;
- }
- }
-
- /**
- * Returns the {@link IClientRulesEngine} IDE callback
- *
- * @return the {@link IClientRulesEngine} IDE callback, never null
- */
- public IClientRulesEngine getRulesEngine() {
- return mRulesEngine;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/GuidelinePainter.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/GuidelinePainter.java
deleted file mode 100644
index 2fe74768f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/GuidelinePainter.java
+++ /dev/null
@@ -1,208 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout.relative;
-
-import static com.android.SdkConstants.ATTR_LAYOUT_MARGIN_BOTTOM;
-import static com.android.SdkConstants.ATTR_LAYOUT_MARGIN_LEFT;
-import static com.android.SdkConstants.ATTR_LAYOUT_MARGIN_RIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_MARGIN_TOP;
-import static com.android.SdkConstants.ATTR_LAYOUT_RESOURCE_PREFIX;
-import static com.android.SdkConstants.ID_PREFIX;
-import static com.android.SdkConstants.NEW_ID_PREFIX;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.DrawingStyle;
-import com.android.ide.common.api.DropFeedback;
-import com.android.ide.common.api.IFeedbackPainter;
-import com.android.ide.common.api.IGraphics;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.Point;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.api.SegmentType;
-import com.android.ide.common.layout.relative.DependencyGraph.Constraint;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * The {@link GuidelinePainter} is responsible for painting guidelines during an operation
- * which uses a {@link GuidelineHandler} such as a resize operation.
- */
-public final class GuidelinePainter implements IFeedbackPainter {
- // ---- Implements IFeedbackPainter ----
- @Override
- public void paint(@NonNull IGraphics gc, @NonNull INode node, @NonNull DropFeedback feedback) {
- GuidelineHandler state = (GuidelineHandler) feedback.userData;
-
- for (INode dragged : state.mDraggedNodes) {
- gc.useStyle(DrawingStyle.DRAGGED);
- Rect bounds = dragged.getBounds();
- if (bounds.isValid()) {
- gc.fillRect(bounds);
- }
- }
-
- Set<INode> horizontalDeps = state.mHorizontalDeps;
- Set<INode> verticalDeps = state.mVerticalDeps;
- Set<INode> deps = new HashSet<INode>(horizontalDeps.size() + verticalDeps.size());
- deps.addAll(horizontalDeps);
- deps.addAll(verticalDeps);
- if (deps.size() > 0) {
- gc.useStyle(DrawingStyle.DEPENDENCY);
- for (INode n : deps) {
- // Don't highlight the selected nodes themselves
- if (state.mDraggedNodes.contains(n)) {
- continue;
- }
- Rect bounds = n.getBounds();
- gc.fillRect(bounds);
- }
- }
-
- if (state.mBounds != null) {
- if (state instanceof MoveHandler) {
- gc.useStyle(DrawingStyle.DROP_PREVIEW);
- } else {
- // Resizing
- if (state.haveSuggestions()) {
- gc.useStyle(DrawingStyle.RESIZE_PREVIEW);
- } else {
- gc.useStyle(DrawingStyle.RESIZE_FAIL);
- }
- }
- gc.drawRect(state.mBounds);
-
- // Draw baseline preview too
- if (feedback.dragBaseline != -1) {
- int y = state.mBounds.y + feedback.dragBaseline;
- gc.drawLine(state.mBounds.x, y, state.mBounds.x2(), y);
- }
- }
-
- List<String> strings = new ArrayList<String>();
-
- showMatch(gc, state.mCurrentLeftMatch, state, strings,
- state.mLeftMargin, ATTR_LAYOUT_MARGIN_LEFT);
- showMatch(gc, state.mCurrentRightMatch, state, strings,
- state.mRightMargin, ATTR_LAYOUT_MARGIN_RIGHT);
- showMatch(gc, state.mCurrentTopMatch, state, strings,
- state.mTopMargin, ATTR_LAYOUT_MARGIN_TOP);
- showMatch(gc, state.mCurrentBottomMatch, state, strings,
- state.mBottomMargin, ATTR_LAYOUT_MARGIN_BOTTOM);
-
- if (strings.size() > 0) {
- // Update the drag tooltip
- StringBuilder sb = new StringBuilder(200);
- for (String s : strings) {
- if (sb.length() > 0) {
- sb.append('\n');
- }
- sb.append(s);
- }
- feedback.tooltip = sb.toString();
-
- // Set the tooltip orientation to ensure that it does not interfere with
- // the constraint arrows
- if (state.mCurrentLeftMatch != null) {
- feedback.tooltipX = SegmentType.RIGHT;
- } else if (state.mCurrentRightMatch != null) {
- feedback.tooltipX = SegmentType.LEFT;
- }
- if (state.mCurrentTopMatch != null) {
- feedback.tooltipY = SegmentType.BOTTOM;
- } else if (state.mCurrentBottomMatch != null) {
- feedback.tooltipY = SegmentType.TOP;
- }
- } else {
- feedback.tooltip = null;
- }
-
- if (state.mHorizontalCycle != null) {
- paintCycle(gc, state, state.mHorizontalCycle);
- }
- if (state.mVerticalCycle != null) {
- paintCycle(gc, state, state.mVerticalCycle);
- }
- }
-
- /** Paints a particular match constraint */
- private void showMatch(IGraphics gc, Match m, GuidelineHandler state, List<String> strings,
- int margin, String marginAttribute) {
- if (m == null) {
- return;
- }
- ConstraintPainter.paintConstraint(gc, state.mBounds, m);
-
- // Display the constraint. Remove the @id/ and @+id/ prefixes to make the text
- // shorter and easier to read. This doesn't use stripPrefix() because the id is
- // usually not a prefix of the value (for example, 'layout_alignBottom=@+id/foo').
- String constraint = m.getConstraint(false /* generateId */);
- String description = constraint.replace(NEW_ID_PREFIX, "").replace(ID_PREFIX, "");
- if (description.startsWith(ATTR_LAYOUT_RESOURCE_PREFIX)) {
- description = description.substring(ATTR_LAYOUT_RESOURCE_PREFIX.length());
- }
- if (margin > 0) {
- int dp = state.getRulesEngine().pxToDp(margin);
- description = String.format("%1$s, margin=%2$d dp", description, dp);
- }
- strings.add(description);
- }
-
- /** Paints a constraint cycle */
- void paintCycle(IGraphics gc, GuidelineHandler state, List<Constraint> cycle) {
- gc.useStyle(DrawingStyle.CYCLE);
- assert cycle.size() > 0;
-
- INode from = cycle.get(0).from.node;
- Rect fromBounds = from.getBounds();
- if (state.mDraggedNodes.contains(from)) {
- fromBounds = state.mBounds;
- }
- Point fromCenter = fromBounds.center();
- INode to = null;
-
- List<Point> points = new ArrayList<Point>();
- points.add(fromCenter);
-
- for (Constraint constraint : cycle) {
- assert constraint.from.node == from;
- to = constraint.to.node;
- assert from != null && to != null;
-
- Point toCenter = to.getBounds().center();
- points.add(toCenter);
-
- // Also go through the dragged node bounds
- boolean isDragged = state.mDraggedNodes.contains(to);
- if (isDragged) {
- toCenter = state.mBounds.center();
- points.add(toCenter);
- }
-
- from = to;
- fromCenter = toCenter;
- }
-
- points.add(fromCenter);
- points.add(points.get(0));
-
- for (int i = 1, n = points.size(); i < n; i++) {
- gc.drawLine(points.get(i-1), points.get(i));
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/Match.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/Match.java
deleted file mode 100644
index 6f3f0d0f7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/Match.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout.relative;
-
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.VALUE_TRUE;
-
-
-import com.android.SdkConstants;
-import static com.android.SdkConstants.ANDROID_URI;
-import com.android.ide.common.api.Segment;
-
-/** A match is a potential pairing of two segments with a given {@link ConstraintType}. */
-class Match {
- /** the edge of the dragged node that is matched */
- public final Segment with;
-
- /** the "other" edge that the dragged edge is matched with */
- public final Segment edge;
-
- /** the signed distance between the matched edges */
- public final int delta;
-
- /** the type of constraint this is a match for */
- public final ConstraintType type;
-
- /** whether this {@link Match} results in a cycle */
- public boolean cycle;
-
- /** The associated {@link GuidelineHander} which performed the match */
- private final GuidelineHandler mHandler;
-
- /**
- * Create a new match.
- *
- * @param handler the handler which performed the match
- * @param edge the "other" edge that the dragged edge is matched with
- * @param with the edge of the dragged node that is matched
- * @param type the type of constraint this is a match for
- * @param delta the signed distance between the matched edges
- */
- public Match(GuidelineHandler handler, Segment edge, Segment with,
- ConstraintType type, int delta) {
- mHandler = handler;
-
- this.edge = edge;
- this.with = with;
- this.type = type;
- this.delta = delta;
- }
-
- /**
- * Returns the XML constraint attribute value for this match
- *
- * @param generateId whether an id should be generated if one is missing
- * @return the XML constraint attribute value for this match
- */
- public String getConstraint(boolean generateId) {
- if (type.targetParent) {
- return type.name + '=' + VALUE_TRUE;
- } else {
- String id = edge.id;
- if (id == null || id.length() == -1) {
- if (!generateId) {
- // Placeholder to display for the user during dragging
- id = "<generated>";
- } else {
- // Must generate an id on the fly!
- // See if it's been set by a different constraint we've already applied
- // to this same node
- id = edge.node.getStringAttr(ANDROID_URI, ATTR_ID);
- if (id == null || id.length() == 0) {
- id = mHandler.getRulesEngine().getUniqueId(edge.node.getFqcn());
- edge.node.setAttribute(ANDROID_URI, ATTR_ID, id);
- }
- }
- }
- return type.name + '=' + id;
- }
- }
-
- @Override
- public String toString() {
- return "Match [type=" + type + ", delta=" + delta + ", edge=" + edge
- + "]";
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/MoveHandler.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/MoveHandler.java
deleted file mode 100644
index 0fa915d81..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/MoveHandler.java
+++ /dev/null
@@ -1,299 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout.relative;
-
-import static com.android.ide.common.api.MarginType.NO_MARGIN;
-import static com.android.ide.common.api.SegmentType.BASELINE;
-import static com.android.ide.common.api.SegmentType.BOTTOM;
-import static com.android.ide.common.api.SegmentType.CENTER_HORIZONTAL;
-import static com.android.ide.common.api.SegmentType.CENTER_VERTICAL;
-import static com.android.ide.common.api.SegmentType.LEFT;
-import static com.android.ide.common.api.SegmentType.RIGHT;
-import static com.android.ide.common.api.SegmentType.TOP;
-import static com.android.SdkConstants.ATTR_ID;
-
-import static java.lang.Math.abs;
-
-import com.android.SdkConstants;
-import static com.android.SdkConstants.ANDROID_URI;
-import com.android.ide.common.api.DropFeedback;
-import com.android.ide.common.api.IClientRulesEngine;
-import com.android.ide.common.api.IDragElement;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.api.Segment;
-import com.android.ide.common.layout.BaseLayoutRule;
-import com.android.ide.common.layout.relative.DependencyGraph.ViewData;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * A {@link MoveHandler} is a {@link GuidelineHandler} which handles move and drop
- * gestures, and offers guideline suggestions and snapping.
- * <p>
- * Unlike the {@link ResizeHandler}, the {@link MoveHandler} looks for matches for all
- * different segment types -- the left edge, the right edge, the baseline, the center
- * edges, and so on -- and picks the best among these.
- */
-public class MoveHandler extends GuidelineHandler {
- private int mDraggedBaseline;
-
- /**
- * Creates a new {@link MoveHandler}.
- *
- * @param layout the layout element the handler is operating on
- * @param elements the elements being dragged in the move operation
- * @param rulesEngine the corresponding {@link IClientRulesEngine}
- */
- public MoveHandler(INode layout, IDragElement[] elements, IClientRulesEngine rulesEngine) {
- super(layout, rulesEngine);
-
- // Compute list of nodes being dragged within the layout, if any
- List<INode> nodes = new ArrayList<INode>();
- for (IDragElement element : elements) {
- ViewData view = mDependencyGraph.getView(element);
- if (view != null) {
- nodes.add(view.node);
- }
- }
- mDraggedNodes = nodes;
-
- mHorizontalDeps = mDependencyGraph.dependsOn(nodes, false /* verticalEdge */);
- mVerticalDeps = mDependencyGraph.dependsOn(nodes, true /* verticalEdge */);
-
- for (INode child : layout.getChildren()) {
- Rect bc = child.getBounds();
- if (bc.isValid()) {
- // First see if this node looks like it's the same as one of the
- // *dragged* bounds
- boolean isDragged = false;
- for (IDragElement element : elements) {
- // This tries to determine if an INode corresponds to an
- // IDragElement, by comparing their bounds.
- if (bc.equals(element.getBounds())) {
- isDragged = true;
- }
- }
-
- if (!isDragged) {
- String id = child.getStringAttr(ANDROID_URI, ATTR_ID);
- // It's okay for id to be null; if you apply a constraint
- // to a node with a missing id we will generate the id
-
- boolean addHorizontal = !mHorizontalDeps.contains(child);
- boolean addVertical = !mVerticalDeps.contains(child);
-
- addBounds(child, id, addHorizontal, addVertical);
- if (addHorizontal) {
- addBaseLine(child, id);
- }
- }
- }
- }
-
- String id = layout.getStringAttr(ANDROID_URI, ATTR_ID);
- addBounds(layout, id, true, true);
- addCenter(layout, id, true, true);
- }
-
- @Override
- protected void snapVertical(Segment vEdge, int x, Rect newBounds) {
- int maxDistance = BaseLayoutRule.getMaxMatchDistance();
- if (vEdge.edgeType == LEFT) {
- int margin = !mSnap ? 0 : abs(newBounds.x - x);
- if (margin > maxDistance) {
- mLeftMargin = margin;
- } else {
- newBounds.x = x;
- }
- } else if (vEdge.edgeType == RIGHT) {
- int margin = !mSnap ? 0 : abs(newBounds.x - (x - newBounds.w));
- if (margin > maxDistance) {
- mRightMargin = margin;
- } else {
- newBounds.x = x - newBounds.w;
- }
- } else if (vEdge.edgeType == CENTER_VERTICAL) {
- newBounds.x = x - newBounds.w / 2;
- } else {
- assert false : vEdge;
- }
- }
-
- // TODO: Consider unifying this with the snapping logic in ResizeHandler
- @Override
- protected void snapHorizontal(Segment hEdge, int y, Rect newBounds) {
- int maxDistance = BaseLayoutRule.getMaxMatchDistance();
- if (hEdge.edgeType == TOP) {
- int margin = !mSnap ? 0 : abs(newBounds.y - y);
- if (margin > maxDistance) {
- mTopMargin = margin;
- } else {
- newBounds.y = y;
- }
- } else if (hEdge.edgeType == BOTTOM) {
- int margin = !mSnap ? 0 : abs(newBounds.y - (y - newBounds.h));
- if (margin > maxDistance) {
- mBottomMargin = margin;
- } else {
- newBounds.y = y - newBounds.h;
- }
- } else if (hEdge.edgeType == CENTER_HORIZONTAL) {
- int margin = !mSnap ? 0 : abs(newBounds.y - (y - newBounds.h / 2));
- if (margin > maxDistance) {
- mTopMargin = margin;
- // or bottomMargin?
- } else {
- newBounds.y = y - newBounds.h / 2;
- }
- } else if (hEdge.edgeType == BASELINE) {
- newBounds.y = y - mDraggedBaseline;
- } else {
- assert false : hEdge;
- }
- }
-
- /**
- * Updates the handler for the given mouse move
- *
- * @param feedback the feedback handler
- * @param elements the elements being dragged
- * @param offsetX the new mouse X coordinate
- * @param offsetY the new mouse Y coordinate
- * @param modifierMask the keyboard modifiers pressed during the drag
- */
- public void updateMove(DropFeedback feedback, IDragElement[] elements,
- int offsetX, int offsetY, int modifierMask) {
- mSnap = (modifierMask & DropFeedback.MODIFIER2) == 0;
-
- Rect firstBounds = elements[0].getBounds();
- INode firstNode = null;
- if (mDraggedNodes != null && mDraggedNodes.size() > 0) {
- // TODO - this isn't quite right; this could be a different node than we have
- // bounds for!
- firstNode = mDraggedNodes.iterator().next();
- firstBounds = firstNode.getBounds();
- }
-
- mBounds = new Rect(offsetX, offsetY, firstBounds.w, firstBounds.h);
- Rect layoutBounds = layout.getBounds();
- if (mBounds.x2() > layoutBounds.x2()) {
- mBounds.x -= mBounds.x2() - layoutBounds.x2();
- }
- if (mBounds.y2() > layoutBounds.y2()) {
- mBounds.y -= mBounds.y2() - layoutBounds.y2();
- }
- if (mBounds.x < layoutBounds.x) {
- mBounds.x = layoutBounds.x;
- }
- if (mBounds.y < layoutBounds.y) {
- mBounds.y = layoutBounds.y;
- }
-
- clearSuggestions();
-
- Rect b = mBounds;
- Segment edge = new Segment(b.y, b.x, b.x2(), null, null, TOP, NO_MARGIN);
- List<Match> horizontalMatches = findClosest(edge, mHorizontalEdges);
- edge = new Segment(b.y2(), b.x, b.x2(), null, null, BOTTOM, NO_MARGIN);
- addClosest(edge, mHorizontalEdges, horizontalMatches);
-
- edge = new Segment(b.x, b.y, b.y2(), null, null, LEFT, NO_MARGIN);
- List<Match> verticalMatches = findClosest(edge, mVerticalEdges);
- edge = new Segment(b.x2(), b.y, b.y2(), null, null, RIGHT, NO_MARGIN);
- addClosest(edge, mVerticalEdges, verticalMatches);
-
- // Match center
- edge = new Segment(b.centerX(), b.y, b.y2(), null, null, CENTER_VERTICAL, NO_MARGIN);
- addClosest(edge, mCenterVertEdges, verticalMatches);
- edge = new Segment(b.centerY(), b.x, b.x2(), null, null, CENTER_HORIZONTAL, NO_MARGIN);
- addClosest(edge, mCenterHorizEdges, horizontalMatches);
-
- // Match baseline
- if (firstNode != null) {
- int baseline = firstNode.getBaseline();
- if (baseline != -1) {
- mDraggedBaseline = baseline;
- edge = new Segment(b.y + baseline, b.x, b.x2(), firstNode, null, BASELINE,
- NO_MARGIN);
- addClosest(edge, mHorizontalEdges, horizontalMatches);
- }
- } else {
- int baseline = feedback.dragBaseline;
- if (baseline != -1) {
- mDraggedBaseline = baseline;
- edge = new Segment(offsetY + baseline, b.x, b.x2(), null, null, BASELINE,
- NO_MARGIN);
- addClosest(edge, mHorizontalEdges, horizontalMatches);
- }
- }
-
- mHorizontalSuggestions = horizontalMatches;
- mVerticalSuggestions = verticalMatches;
- mTopMargin = mBottomMargin = mLeftMargin = mRightMargin = 0;
-
- Match match = pickBestMatch(mHorizontalSuggestions);
- if (match != null) {
- if (mHorizontalDeps.contains(match.edge.node)) {
- match.cycle = true;
- }
-
- // Reset top AND bottom bounds regardless of whether both are bound
- mMoveTop = true;
- mMoveBottom = true;
-
- // TODO: Consider doing the snap logic on all the possible matches
- // BEFORE sorting, in case this affects the best-pick algorithm (since some
- // edges snap and others don't).
- snapHorizontal(match.with, match.edge.at, mBounds);
-
- if (match.with.edgeType == TOP) {
- mCurrentTopMatch = match;
- } else if (match.with.edgeType == BOTTOM) {
- mCurrentBottomMatch = match;
- } else {
- assert match.with.edgeType == CENTER_HORIZONTAL
- || match.with.edgeType == BASELINE : match.with.edgeType;
- mCurrentTopMatch = match;
- }
- }
-
- match = pickBestMatch(mVerticalSuggestions);
- if (match != null) {
- if (mVerticalDeps.contains(match.edge.node)) {
- match.cycle = true;
- }
-
- // Reset left AND right bounds regardless of whether both are bound
- mMoveLeft = true;
- mMoveRight = true;
-
- snapVertical(match.with, match.edge.at, mBounds);
-
- if (match.with.edgeType == LEFT) {
- mCurrentLeftMatch = match;
- } else if (match.with.edgeType == RIGHT) {
- mCurrentRightMatch = match;
- } else {
- assert match.with.edgeType == CENTER_VERTICAL;
- mCurrentLeftMatch = match;
- }
- }
-
- checkCycles(feedback);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/ResizeHandler.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/ResizeHandler.java
deleted file mode 100644
index a5e071d74..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/relative/ResizeHandler.java
+++ /dev/null
@@ -1,265 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout.relative;
-
-import static com.android.ide.common.api.MarginType.NO_MARGIN;
-import static com.android.ide.common.api.SegmentType.BASELINE;
-import static com.android.ide.common.api.SegmentType.BOTTOM;
-import static com.android.ide.common.api.SegmentType.CENTER_HORIZONTAL;
-import static com.android.ide.common.api.SegmentType.CENTER_VERTICAL;
-import static com.android.ide.common.api.SegmentType.LEFT;
-import static com.android.ide.common.api.SegmentType.RIGHT;
-import static com.android.ide.common.api.SegmentType.TOP;
-import static com.android.SdkConstants.ATTR_ID;
-
-import static java.lang.Math.abs;
-
-import com.android.SdkConstants;
-import static com.android.SdkConstants.ANDROID_URI;
-import com.android.ide.common.api.DropFeedback;
-import com.android.ide.common.api.IClientRulesEngine;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.api.Segment;
-import com.android.ide.common.api.SegmentType;
-import com.android.ide.common.layout.BaseLayoutRule;
-
-import java.util.Collections;
-import java.util.Set;
-
-/**
- * A {@link ResizeHandler} is a {@link GuidelineHandler} which handles resizing of individual
- * edges in a RelativeLayout.
- */
-public class ResizeHandler extends GuidelineHandler {
- private final SegmentType mHorizontalEdgeType;
- private final SegmentType mVerticalEdgeType;
-
- /**
- * Creates a new {@link ResizeHandler}
- *
- * @param layout the layout containing the resized node
- * @param resized the node being resized
- * @param rulesEngine the applicable {@link IClientRulesEngine}
- * @param horizontalEdgeType the type of horizontal edge being resized, or null
- * @param verticalEdgeType the type of vertical edge being resized, or null
- */
- public ResizeHandler(INode layout, INode resized,
- IClientRulesEngine rulesEngine,
- SegmentType horizontalEdgeType, SegmentType verticalEdgeType) {
- super(layout, rulesEngine);
-
- assert horizontalEdgeType != null || verticalEdgeType != null;
- assert horizontalEdgeType != BASELINE && verticalEdgeType != BASELINE;
- assert horizontalEdgeType != CENTER_HORIZONTAL && verticalEdgeType != CENTER_HORIZONTAL;
- assert horizontalEdgeType != CENTER_VERTICAL && verticalEdgeType != CENTER_VERTICAL;
-
- mHorizontalEdgeType = horizontalEdgeType;
- mVerticalEdgeType = verticalEdgeType;
-
- Set<INode> nodes = Collections.singleton(resized);
- mDraggedNodes = nodes;
-
- mHorizontalDeps = mDependencyGraph.dependsOn(nodes, false /* vertical */);
- mVerticalDeps = mDependencyGraph.dependsOn(nodes, true /* vertical */);
-
- if (horizontalEdgeType != null) {
- if (horizontalEdgeType == TOP) {
- mMoveTop = true;
- } else if (horizontalEdgeType == BOTTOM) {
- mMoveBottom = true;
- }
- }
- if (verticalEdgeType != null) {
- if (verticalEdgeType == LEFT) {
- mMoveLeft = true;
- } else if (verticalEdgeType == RIGHT) {
- mMoveRight = true;
- }
- }
-
- for (INode child : layout.getChildren()) {
- if (child != resized) {
- String id = child.getStringAttr(ANDROID_URI, ATTR_ID);
- addBounds(child, id,
- !mHorizontalDeps.contains(child),
- !mVerticalDeps.contains(child));
- }
- }
-
- addBounds(layout, layout.getStringAttr(ANDROID_URI, ATTR_ID), true, true);
- }
-
- @Override
- protected void snapVertical(Segment vEdge, int x, Rect newBounds) {
- int maxDistance = BaseLayoutRule.getMaxMatchDistance();
- if (vEdge.edgeType == LEFT) {
- int margin = mSnap ? 0 : abs(newBounds.x - x);
- if (margin > maxDistance) {
- mLeftMargin = margin;
- } else {
- newBounds.w += newBounds.x - x;
- newBounds.x = x;
- }
- } else if (vEdge.edgeType == RIGHT) {
- int margin = mSnap ? 0 : abs(newBounds.x - (x - newBounds.w));
- if (margin > maxDistance) {
- mRightMargin = margin;
- } else {
- newBounds.w = x - newBounds.x;
- }
- } else {
- assert false : vEdge;
- }
- }
-
- @Override
- protected void snapHorizontal(Segment hEdge, int y, Rect newBounds) {
- int maxDistance = BaseLayoutRule.getMaxMatchDistance();
- if (hEdge.edgeType == TOP) {
- int margin = mSnap ? 0 : abs(newBounds.y - y);
- if (margin > maxDistance) {
- mTopMargin = margin;
- } else {
- newBounds.h += newBounds.y - y;
- newBounds.y = y;
- }
- } else if (hEdge.edgeType == BOTTOM) {
- int margin = mSnap ? 0 : abs(newBounds.y - (y - newBounds.h));
- if (margin > maxDistance) {
- mBottomMargin = margin;
- } else {
- newBounds.h = y - newBounds.y;
- }
- } else {
- assert false : hEdge;
- }
- }
-
- @Override
- protected boolean isEdgeTypeCompatible(SegmentType edge, SegmentType dragged, int delta) {
- boolean compatible = super.isEdgeTypeCompatible(edge, dragged, delta);
-
- // When resizing and not snapping (e.g. using margins to pick a specific pixel
- // width) we cannot use -negative- margins to jump back to a closer edge; we
- // must always use positive margins, so mark closer edges that result in a negative
- // margin as not compatible.
- if (compatible && !mSnap) {
- switch (dragged) {
- case LEFT:
- case TOP:
- return delta <= 0;
- default:
- return delta >= 0;
- }
- }
-
- return compatible;
- }
-
- /**
- * Updates the handler for the given mouse resize
- *
- * @param feedback the feedback handler
- * @param child the node being resized
- * @param newBounds the new bounds of the resize rectangle
- * @param modifierMask the keyboard modifiers pressed during the drag
- */
- public void updateResize(DropFeedback feedback, INode child, Rect newBounds,
- int modifierMask) {
- mSnap = (modifierMask & DropFeedback.MODIFIER2) == 0;
- mBounds = newBounds;
- clearSuggestions();
-
- Rect b = newBounds;
- Segment hEdge = null;
- Segment vEdge = null;
- String childId = child.getStringAttr(ANDROID_URI, ATTR_ID);
-
- // TODO: MarginType=NO_MARGIN may not be right. Consider resizing a widget
- // that has margins and how that should be handled.
-
- if (mHorizontalEdgeType == TOP) {
- hEdge = new Segment(b.y, b.x, b.x2(), child, childId, mHorizontalEdgeType, NO_MARGIN);
- } else if (mHorizontalEdgeType == BOTTOM) {
- hEdge = new Segment(b.y2(), b.x, b.x2(), child, childId, mHorizontalEdgeType,
- NO_MARGIN);
- } else {
- assert mHorizontalEdgeType == null;
- }
-
- if (mVerticalEdgeType == LEFT) {
- vEdge = new Segment(b.x, b.y, b.y2(), child, childId, mVerticalEdgeType, NO_MARGIN);
- } else if (mVerticalEdgeType == RIGHT) {
- vEdge = new Segment(b.x2(), b.y, b.y2(), child, childId, mVerticalEdgeType, NO_MARGIN);
- } else {
- assert mVerticalEdgeType == null;
- }
-
- mTopMargin = mBottomMargin = mLeftMargin = mRightMargin = 0;
-
- if (hEdge != null && mHorizontalEdges.size() > 0) {
- // Compute horizontal matches
- mHorizontalSuggestions = findClosest(hEdge, mHorizontalEdges);
-
- Match match = pickBestMatch(mHorizontalSuggestions);
- if (match != null
- && (!mSnap || Math.abs(match.delta) < BaseLayoutRule.getMaxMatchDistance())) {
- if (mHorizontalDeps.contains(match.edge.node)) {
- match.cycle = true;
- }
-
- snapHorizontal(hEdge, match.edge.at, newBounds);
-
- if (hEdge.edgeType == TOP) {
- mCurrentTopMatch = match;
- } else if (hEdge.edgeType == BOTTOM) {
- mCurrentBottomMatch = match;
- } else {
- assert hEdge.edgeType == CENTER_HORIZONTAL
- || hEdge.edgeType == BASELINE : hEdge;
- mCurrentTopMatch = match;
- }
- }
- }
-
- if (vEdge != null && mVerticalEdges.size() > 0) {
- mVerticalSuggestions = findClosest(vEdge, mVerticalEdges);
-
- Match match = pickBestMatch(mVerticalSuggestions);
- if (match != null
- && (!mSnap || Math.abs(match.delta) < BaseLayoutRule.getMaxMatchDistance())) {
- if (mVerticalDeps.contains(match.edge.node)) {
- match.cycle = true;
- }
-
- // Snap
- snapVertical(vEdge, match.edge.at, newBounds);
-
- if (vEdge.edgeType == LEFT) {
- mCurrentLeftMatch = match;
- } else if (vEdge.edgeType == RIGHT) {
- mCurrentRightMatch = match;
- } else {
- assert vEdge.edgeType == CENTER_VERTICAL;
- mCurrentLeftMatch = match;
- }
- }
- }
-
- checkCycles(feedback);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/removecol.png b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/removecol.png
deleted file mode 100644
index c41261afa..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/removecol.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/removerow.png b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/removerow.png
deleted file mode 100644
index db695a714..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/removerow.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/showgrid.png b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/showgrid.png
deleted file mode 100644
index 6f7bf9160..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/showgrid.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/snap.png b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/snap.png
deleted file mode 100644
index b50a16ed1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/snap.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/structure.png b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/structure.png
deleted file mode 100644
index e5d753885..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/structure.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/vlinear.png b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/vlinear.png
deleted file mode 100644
index e03c16e00..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/vlinear.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/weights.png b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/weights.png
deleted file mode 100644
index cb654a140..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/layout/weights.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/resources/platform/AttributeInfo.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/resources/platform/AttributeInfo.java
deleted file mode 100755
index e246975bb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/resources/platform/AttributeInfo.java
+++ /dev/null
@@ -1,355 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.resources.platform;
-
-import static com.android.SdkConstants.ANDROID_PREFIX;
-import static com.android.SdkConstants.ANDROID_THEME_PREFIX;
-import static com.android.SdkConstants.ID_PREFIX;
-import static com.android.SdkConstants.NEW_ID_PREFIX;
-import static com.android.SdkConstants.PREFIX_THEME_REF;
-import static com.android.SdkConstants.VALUE_FALSE;
-import static com.android.SdkConstants.VALUE_TRUE;
-import static com.android.ide.common.api.IAttributeInfo.Format.BOOLEAN;
-import static com.android.ide.common.api.IAttributeInfo.Format.COLOR;
-import static com.android.ide.common.api.IAttributeInfo.Format.DIMENSION;
-import static com.android.ide.common.api.IAttributeInfo.Format.ENUM;
-import static com.android.ide.common.api.IAttributeInfo.Format.FLAG;
-import static com.android.ide.common.api.IAttributeInfo.Format.FLOAT;
-import static com.android.ide.common.api.IAttributeInfo.Format.FRACTION;
-import static com.android.ide.common.api.IAttributeInfo.Format.INTEGER;
-import static com.android.ide.common.api.IAttributeInfo.Format.STRING;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.IAttributeInfo;
-import com.android.ide.common.resources.ResourceRepository;
-import com.android.resources.ResourceType;
-import com.google.common.base.Splitter;
-
-import java.util.EnumSet;
-import java.util.regex.Pattern;
-
-
-/**
- * Information about an attribute as gathered from the attrs.xml file where
- * the attribute was declared. This must include a format (string, reference, float, etc.),
- * possible flag or enum values, whether it's deprecated and its javadoc.
- */
-public class AttributeInfo implements IAttributeInfo {
- /** XML Name of the attribute */
- private String mName;
-
- /** Formats of the attribute. Cannot be null. Should have at least one format. */
- private EnumSet<Format> mFormats;
- /** Values for enum. null for other types. */
- private String[] mEnumValues;
- /** Values for flag. null for other types. */
- private String[] mFlagValues;
- /** Short javadoc (i.e. the first sentence). */
- private String mJavaDoc;
- /** Documentation for deprecated attributes. Null if not deprecated. */
- private String mDeprecatedDoc;
- /** The source class defining this attribute */
- private String mDefinedBy;
-
- /**
- * @param name The XML Name of the attribute
- * @param formats The formats of the attribute. Cannot be null.
- * Should have at least one format.
- */
- public AttributeInfo(@NonNull String name, @NonNull EnumSet<Format> formats) {
- mName = name;
- mFormats = formats;
- }
-
- /**
- * @param name The XML Name of the attribute
- * @param formats The formats of the attribute. Cannot be null.
- * Should have at least one format.
- * @param javadoc Short javadoc (i.e. the first sentence).
- */
- public AttributeInfo(@NonNull String name, @NonNull EnumSet<Format> formats, String javadoc) {
- mName = name;
- mFormats = formats;
- mJavaDoc = javadoc;
- }
-
- public AttributeInfo(AttributeInfo info) {
- mName = info.mName;
- mFormats = info.mFormats;
- mEnumValues = info.mEnumValues;
- mFlagValues = info.mFlagValues;
- mJavaDoc = info.mJavaDoc;
- mDeprecatedDoc = info.mDeprecatedDoc;
- }
-
- /**
- * Sets the XML Name of the attribute
- *
- * @param name the new name to assign
- */
- public void setName(String name) {
- mName = name;
- }
-
- /** Returns the XML Name of the attribute */
- @Override
- public @NonNull String getName() {
- return mName;
- }
- /** Returns the formats of the attribute. Cannot be null.
- * Should have at least one format. */
- @Override
- public @NonNull EnumSet<Format> getFormats() {
- return mFormats;
- }
- /** Returns the values for enums. null for other types. */
- @Override
- public String[] getEnumValues() {
- return mEnumValues;
- }
- /** Returns the values for flags. null for other types. */
- @Override
- public String[] getFlagValues() {
- return mFlagValues;
- }
- /** Returns a short javadoc, .i.e. the first sentence. */
- @Override
- public @NonNull String getJavaDoc() {
- return mJavaDoc;
- }
- /** Returns the documentation for deprecated attributes. Null if not deprecated. */
- @Override
- public String getDeprecatedDoc() {
- return mDeprecatedDoc;
- }
-
- /** Sets the values for enums. null for other types. */
- public AttributeInfo setEnumValues(String[] values) {
- mEnumValues = values;
- return this;
- }
-
- /** Sets the values for flags. null for other types. */
- public AttributeInfo setFlagValues(String[] values) {
- mFlagValues = values;
- return this;
- }
-
- /** Sets a short javadoc, .i.e. the first sentence. */
- public void setJavaDoc(String javaDoc) {
- mJavaDoc = javaDoc;
- }
-
- /** Sets the documentation for deprecated attributes. Null if not deprecated. */
- public void setDeprecatedDoc(String deprecatedDoc) {
- mDeprecatedDoc = deprecatedDoc;
- }
-
- /**
- * Sets the name of the class (fully qualified class name) which defined
- * this attribute
- *
- * @param definedBy the name of the class (fully qualified class name) which
- * defined this attribute
- */
- public void setDefinedBy(String definedBy) {
- mDefinedBy = definedBy;
- }
-
- /**
- * Returns the name of the class (fully qualified class name) which defined
- * this attribute
- *
- * @return the name of the class (fully qualified class name) which defined
- * this attribute
- */
- @Override
- public @NonNull String getDefinedBy() {
- return mDefinedBy;
- }
-
- private final static Pattern INTEGER_PATTERN = Pattern.compile("-?[0-9]+"); //$NON-NLS-1$
- private final static Pattern FLOAT_PATTERN =
- Pattern.compile("-?[0-9]?(\\.[0-9]+)?"); //$NON-NLS-1$
- private final static Pattern DIMENSION_PATTERN =
- Pattern.compile("-?[0-9]+(\\.[0-9]+)?(dp|dip|sp|px|pt|in|mm)"); //$NON-NLS-1$
-
- /**
- * Checks the given value and returns true only if it is a valid XML value
- * for this attribute.
- *
- * @param value the XML value to check
- * @param projectResources project resources to validate resource URLs with,
- * if any
- * @param frameworkResources framework resources to validate resource URLs
- * with, if any
- * @return true if the value is valid, false otherwise
- */
- public boolean isValid(
- @NonNull String value,
- @Nullable ResourceRepository projectResources,
- @Nullable ResourceRepository frameworkResources) {
-
- if (mFormats.contains(STRING) || mFormats.isEmpty()) {
- // Anything is allowed
- return true;
- }
-
- // All other formats require a nonempty string
- if (value.isEmpty()) {
- // Except for flags
- if (mFormats.contains(FLAG)) {
- return true;
- }
-
- return false;
- }
- char first = value.charAt(0);
-
- // There are many attributes which are incorrectly marked in the attrs.xml
- // file, such as "duration", "minHeight", etc. These are marked as only
- // accepting "integer", but also appear to accept "reference". Therefore,
- // in these cases, be more lenient. (This happens for theme references too,
- // such as ?android:attr/listPreferredItemHeight)
- if ((first == '@' || first == '?') /* && mFormats.contains(REFERENCE)*/) {
- if (value.equals("@null")) {
- return true;
- }
-
- if (value.startsWith(NEW_ID_PREFIX) || value.startsWith(ID_PREFIX)) {
- // These are handled in the IdGeneratingResourceFile; we shouldn't
- // complain about not finding ids in the repository yet since they may
- // not yet have been defined (@+id's can be defined in the same layout,
- // later on.)
- return true;
- }
-
- if (value.startsWith(ANDROID_PREFIX) || value.startsWith(ANDROID_THEME_PREFIX)) {
- if (frameworkResources != null) {
- return frameworkResources.hasResourceItem(value);
- }
- } else if (projectResources != null) {
- return projectResources.hasResourceItem(value);
- }
-
- // Validate resource string
- String url = value;
- int typeEnd = url.indexOf('/', 1);
- if (typeEnd != -1) {
- int typeBegin = url.startsWith("@+") ? 2 : 1; //$NON-NLS-1$
- int colon = url.lastIndexOf(':', typeEnd);
- if (colon != -1) {
- typeBegin = colon + 1;
- }
- String typeName = url.substring(typeBegin, typeEnd);
- ResourceType type = ResourceType.getEnum(typeName);
- if (type != null) {
- // TODO: Validate that the name portion conforms to the rules
- // (is an identifier but not a keyword, etc.)
- // Also validate that the prefix before the colon is either
- // not there or is "android"
-
- //int nameBegin = typeEnd + 1;
- //String name = url.substring(nameBegin);
- return true;
- }
- } else if (value.startsWith(PREFIX_THEME_REF)) {
- if (projectResources != null) {
- return projectResources.hasResourceItem(ResourceType.ATTR,
- value.substring(PREFIX_THEME_REF.length()));
- } else {
- // Until proven otherwise
- return true;
- }
- }
- }
-
- if (mFormats.contains(ENUM) && mEnumValues != null) {
- for (String e : mEnumValues) {
- if (value.equals(e)) {
- return true;
- }
- }
- }
-
- if (mFormats.contains(FLAG) && mFlagValues != null) {
- for (String v : Splitter.on('|').split(value)) {
- for (String e : mFlagValues) {
- if (v.equals(e)) {
- return true;
- }
- }
- }
- }
-
- if (mFormats.contains(DIMENSION)) {
- if (DIMENSION_PATTERN.matcher(value).matches()) {
- return true;
- }
- }
-
- if (mFormats.contains(BOOLEAN)) {
- if (value.equalsIgnoreCase(VALUE_TRUE) || value.equalsIgnoreCase(VALUE_FALSE)) {
- return true;
- }
- }
-
- if (mFormats.contains(FLOAT)) {
- if (Character.isDigit(first) || first == '-' || first == '.') {
- if (FLOAT_PATTERN.matcher(value).matches()) {
- return true;
- }
- // AAPT accepts more general floats, such as ".1",
- try {
- Float.parseFloat(value);
- return true;
- } catch (NumberFormatException nufe) {
- // Not a float
- }
- }
- }
-
- if (mFormats.contains(INTEGER)) {
- if (Character.isDigit(first) || first == '-') {
- if (INTEGER_PATTERN.matcher(value).matches()) {
- return true;
- }
- }
- }
-
- if (mFormats.contains(COLOR)) {
- if (first == '#' && value.length() <= 9) { // Only allowed 32 bit ARGB
- try {
- // Use Long.parseLong rather than Integer.parseInt to not overflow on
- // 32 big hex values like "ff191919"
- Long.parseLong(value.substring(1), 16);
- return true;
- } catch (NumberFormatException nufe) {
- // Not a valid color number
- }
- }
- }
-
- if (mFormats.contains(FRACTION)) {
- // should end with % or %p
- return true;
- }
-
- return false;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/resources/platform/AttrsXmlParser.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/resources/platform/AttrsXmlParser.java
deleted file mode 100644
index 1330c50f3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/resources/platform/AttrsXmlParser.java
+++ /dev/null
@@ -1,698 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.resources.platform;
-
-import static com.android.SdkConstants.DOT_LAYOUT_PARAMS;
-import static com.android.ide.eclipse.adt.AdtConstants.DOC_HIDE;
-
-import com.android.ide.common.api.IAttributeInfo.Format;
-import com.android.ide.common.resources.platform.ViewClassInfo.LayoutParamsInfo;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.utils.ILogger;
-import com.google.common.collect.Maps;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-import org.xml.sax.SAXException;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.EnumSet;
-import java.util.HashMap;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-
-/**
- * Parser for attributes description files.
- */
-public final class AttrsXmlParser {
-
- public static final String ANDROID_MANIFEST_STYLEABLE = "AndroidManifest"; //$NON-NLS-1$
-
- private Document mDocument;
- private String mOsAttrsXmlPath;
-
- // all attributes that have the same name are supposed to have the same
- // parameters so we'll keep a cache of them to avoid processing them twice.
- private Map<String, AttributeInfo> mAttributeMap;
-
- /** Map of all attribute names for a given element */
- private final Map<String, DeclareStyleableInfo> mStyleMap =
- new HashMap<String, DeclareStyleableInfo>();
-
- /** Map from format name (lower case) to the uppercase version */
- private Map<String, Format> mFormatNames = new HashMap<String, Format>(10);
-
- /**
- * Map of all (constant, value) pairs for attributes of format enum or flag.
- * E.g. for attribute name=gravity, this tells us there's an enum/flag called "center"
- * with value 0x11.
- */
- private Map<String, Map<String, Integer>> mEnumFlagValues;
-
- /**
- * A logger object. Must not be null.
- */
- private final ILogger mLog;
-
- /**
- * Creates a new {@link AttrsXmlParser}, set to load things from the given
- * XML file. Nothing has been parsed yet. Callers should call {@link #preload()}
- * next.
- *
- * @param osAttrsXmlPath The path of the <code>attrs.xml</code> file to parse.
- * Must not be null. Should point to an existing valid XML document.
- * @param log A logger object. Must not be null.
- * @param expectedAttributeCount expected number of attributes in the file
- */
- public AttrsXmlParser(String osAttrsXmlPath, ILogger log, int expectedAttributeCount) {
- this(osAttrsXmlPath, null /* inheritableAttributes */, log, expectedAttributeCount);
- }
-
- /**
- * Returns the parsed map of attribute infos
- *
- * @return a map from string name to {@link AttributeInfo}
- */
- public Map<String, AttributeInfo> getAttributeMap() {
- return mAttributeMap;
- }
-
- /**
- * Creates a new {@link AttrsXmlParser} set to load things from the given
- * XML file.
- * <p/>
- * If inheritableAttributes is non-null, it must point to a preloaded
- * {@link AttrsXmlParser} which attributes will be used for this one. Since
- * already defined attributes are not modifiable, they are thus "inherited".
- *
- * @param osAttrsXmlPath The path of the <code>attrs.xml</code> file to parse.
- * Must not be null. Should point to an existing valid XML document.
- * @param inheritableAttributes An optional parser with attributes to inherit. Can be null.
- * If not null, the parser must have had its {@link #preload()} method
- * invoked prior to being used here.
- * @param log A logger object. Must not be null.
- * @param expectedAttributeCount expected number of attributes in the file
- */
- public AttrsXmlParser(
- String osAttrsXmlPath,
- AttrsXmlParser inheritableAttributes,
- ILogger log,
- int expectedAttributeCount) {
- mOsAttrsXmlPath = osAttrsXmlPath;
- mLog = log;
-
- assert osAttrsXmlPath != null;
- assert log != null;
-
- mAttributeMap = Maps.newHashMapWithExpectedSize(expectedAttributeCount);
- if (inheritableAttributes == null) {
- mEnumFlagValues = new HashMap<String, Map<String,Integer>>();
- } else {
- mAttributeMap.putAll(inheritableAttributes.mAttributeMap);
- mEnumFlagValues = new HashMap<String, Map<String,Integer>>(
- inheritableAttributes.mEnumFlagValues);
- }
-
- // Pre-compute the set of format names such that we don't have to compute the uppercase
- // version of the same format string names again and again
- for (Format f : Format.values()) {
- mFormatNames.put(f.name().toLowerCase(Locale.US), f);
- }
- }
-
- /**
- * Returns the OS path of the attrs.xml file parsed.
- */
- public String getOsAttrsXmlPath() {
- return mOsAttrsXmlPath;
- }
-
- /**
- * Preloads the document, parsing all attributes and declared styles.
- *
- * @return Self, for command chaining.
- */
- public AttrsXmlParser preload() {
- Document doc = getDocument();
-
- if (doc == null) {
- mLog.warning("Failed to find %1$s", //$NON-NLS-1$
- mOsAttrsXmlPath);
- return this;
- }
-
- Node res = doc.getFirstChild();
- while (res != null &&
- res.getNodeType() != Node.ELEMENT_NODE &&
- !res.getNodeName().equals("resources")) { //$NON-NLS-1$
- res = res.getNextSibling();
- }
-
- if (res == null) {
- mLog.warning("Failed to find a <resources> node in %1$s", //$NON-NLS-1$
- mOsAttrsXmlPath);
- return this;
- }
-
- parseResources(res);
- return this;
- }
-
- /**
- * Loads all attributes & javadoc for the view class info based on the class name.
- */
- public void loadViewAttributes(ViewClassInfo info) {
- if (getDocument() != null) {
- String xmlName = info.getShortClassName();
- DeclareStyleableInfo style = mStyleMap.get(xmlName);
- if (style != null) {
- String definedBy = info.getFullClassName();
- AttributeInfo[] attributes = style.getAttributes();
- for (AttributeInfo attribute : attributes) {
- if (attribute.getDefinedBy() == null) {
- attribute.setDefinedBy(definedBy);
- }
- }
- info.setAttributes(attributes);
- info.setJavaDoc(style.getJavaDoc());
- }
- }
- }
-
- /**
- * Loads all attributes for the layout data info based on the class name.
- */
- public void loadLayoutParamsAttributes(LayoutParamsInfo info) {
- if (getDocument() != null) {
- // Transforms "LinearLayout" and "LayoutParams" into "LinearLayout_Layout".
- ViewClassInfo viewLayoutClass = info.getViewLayoutClass();
- String xmlName = String.format("%1$s_%2$s", //$NON-NLS-1$
- viewLayoutClass.getShortClassName(),
- info.getShortClassName());
- xmlName = AdtUtils.stripSuffix(xmlName, "Params"); //$NON-NLS-1$
-
- DeclareStyleableInfo style = mStyleMap.get(xmlName);
- if (style != null) {
- // For defined by, use the actual class name, e.g.
- // android.widget.LinearLayout.LayoutParams
- String definedBy = viewLayoutClass.getFullClassName() + DOT_LAYOUT_PARAMS;
- AttributeInfo[] attributes = style.getAttributes();
- for (AttributeInfo attribute : attributes) {
- if (attribute.getDefinedBy() == null) {
- attribute.setDefinedBy(definedBy);
- }
- }
- info.setAttributes(attributes);
- }
- }
- }
-
- /**
- * Returns a list of all <code>declare-styleable</code> found in the XML file.
- */
- public Map<String, DeclareStyleableInfo> getDeclareStyleableList() {
- return Collections.unmodifiableMap(mStyleMap);
- }
-
- /**
- * Returns a map of all enum and flag constants sorted by parent attribute name.
- * The map is attribute_name => (constant_name => integer_value).
- */
- public Map<String, Map<String, Integer>> getEnumFlagValues() {
- return mEnumFlagValues;
- }
-
- //-------------------------
-
- /**
- * Creates an XML document from the attrs.xml OS path.
- * May return null if the file doesn't exist or cannot be parsed.
- */
- private Document getDocument() {
- if (mDocument == null) {
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- factory.setIgnoringComments(false);
- try {
- DocumentBuilder builder = factory.newDocumentBuilder();
- mDocument = builder.parse(new File(mOsAttrsXmlPath));
- } catch (ParserConfigurationException e) {
- mLog.error(e, "Failed to create XML document builder for %1$s", //$NON-NLS-1$
- mOsAttrsXmlPath);
- } catch (SAXException e) {
- mLog.error(e, "Failed to parse XML document %1$s", //$NON-NLS-1$
- mOsAttrsXmlPath);
- } catch (IOException e) {
- mLog.error(e, "Failed to read XML document %1$s", //$NON-NLS-1$
- mOsAttrsXmlPath);
- }
- }
- return mDocument;
- }
-
- /**
- * Finds all the &lt;declare-styleable&gt; and &lt;attr&gt; nodes
- * in the top &lt;resources&gt; node.
- */
- private void parseResources(Node res) {
-
- Map<String, String> unknownParents = new HashMap<String, String>();
-
- Node lastComment = null;
- for (Node node = res.getFirstChild(); node != null; node = node.getNextSibling()) {
- switch (node.getNodeType()) {
- case Node.COMMENT_NODE:
- lastComment = node;
- break;
- case Node.ELEMENT_NODE:
- if (node.getNodeName().equals("declare-styleable")) { //$NON-NLS-1$
- Node nameNode = node.getAttributes().getNamedItem("name"); //$NON-NLS-1$
- if (nameNode != null) {
- String name = nameNode.getNodeValue();
-
- Node parentNode = node.getAttributes().getNamedItem("parent"); //$NON-NLS-1$
- String parents = parentNode == null ? null : parentNode.getNodeValue();
-
- if (name != null && !mStyleMap.containsKey(name)) {
- DeclareStyleableInfo style = parseDeclaredStyleable(name, node);
- if (parents != null) {
- String[] parentsArray =
- parseStyleableParents(parents, mStyleMap, unknownParents);
- style.setParents(parentsArray);
- }
- mStyleMap.put(name, style);
- unknownParents.remove(name);
- if (lastComment != null) {
- String nodeValue = lastComment.getNodeValue();
- if (nodeValue.contains(DOC_HIDE)) {
- mStyleMap.remove(name);
- } else {
- style.setJavaDoc(parseJavadoc(nodeValue));
- }
- }
- }
- }
- } else if (node.getNodeName().equals("attr")) { //$NON-NLS-1$
- parseAttr(node, lastComment);
- }
- lastComment = null;
- break;
- }
- }
-
- // If we have any unknown parent, re-create synthetic styleable for them.
- for (Entry<String, String> entry : unknownParents.entrySet()) {
- String name = entry.getKey();
- String parent = entry.getValue();
-
- DeclareStyleableInfo style = new DeclareStyleableInfo(name, (AttributeInfo[])null);
- if (parent != null) {
- style.setParents(new String[] { parent });
- }
- mStyleMap.put(name, style);
-
- // Simplify parents names. See SDK Bug 3125910.
- // Implementation detail: that since we want to delete and add to the map,
- // we can't just use an iterator.
- for (String key : new ArrayList<String>(mStyleMap.keySet())) {
- if (key.startsWith(name) && !key.equals(name)) {
- // We found a child which name starts with the full name of the
- // parent. Simplify the children name.
- String newName = ANDROID_MANIFEST_STYLEABLE + key.substring(name.length());
-
- DeclareStyleableInfo newStyle =
- new DeclareStyleableInfo(newName, mStyleMap.get(key));
- mStyleMap.remove(key);
- mStyleMap.put(newName, newStyle);
- }
- }
- }
- }
-
- /**
- * Parses the "parents" attribute from a &lt;declare-styleable&gt;.
- * <p/>
- * The syntax is the following:
- * <pre>
- * parent[.parent]* [[space|,] parent[.parent]* ]
- * </pre>
- * <p/>
- * In English: </br>
- * - There can be one or more parents, separated by whitespace or commas. </br>
- * - Whitespace is ignored and trimmed. </br>
- * - A parent name is actually composed of one or more identifiers joined by a dot.
- * <p/>
- * Styleables do not usually need to declare their parent chain (e.g. the grand-parents
- * of a parent.) Parent names are unique, so in most cases a styleable will only declare
- * its immediate parent.
- * <p/>
- * However it is possible for a styleable's parent to not exist, e.g. if you have a
- * styleable "A" that is the root and then styleable "C" declares its parent to be "A.B".
- * In this case we record "B" as the parent, even though it is unknown and will never be
- * known. Any parent that is currently not in the knownParent map is thus added to the
- * unknownParent set. The caller will remove the name from the unknownParent set when it
- * sees a declaration for it.
- *
- * @param parents The parents string to parse. Must not be null or empty.
- * @param knownParents The map of all declared styles known so far.
- * @param unknownParents A map of all unknown parents collected here.
- * @return The array of terminal parent names parsed from the parents string.
- */
- private String[] parseStyleableParents(String parents,
- Map<String, DeclareStyleableInfo> knownParents,
- Map<String, String> unknownParents) {
-
- ArrayList<String> result = new ArrayList<String>();
-
- for (String parent : parents.split("[ \t\n\r\f,|]")) { //$NON-NLS-1$
- parent = parent.trim();
- if (parent.length() == 0) {
- continue;
- }
- if (parent.indexOf('.') >= 0) {
- // This is a grand-parent/parent chain. Make sure we know about the
- // parents and only record the terminal one.
- String last = null;
- for (String name : parent.split("\\.")) { //$NON-NLS-1$
- if (name.length() > 0) {
- if (!knownParents.containsKey(name)) {
- // Record this unknown parent and its grand parent.
- unknownParents.put(name, last);
- }
- last = name;
- }
- }
- parent = last;
- }
-
- result.add(parent);
- }
-
- return result.toArray(new String[result.size()]);
- }
-
- /**
- * Parses an &lt;attr&gt; node and convert it into an {@link AttributeInfo} if it is valid.
- */
- private AttributeInfo parseAttr(Node attrNode, Node lastComment) {
- AttributeInfo info = null;
- Node nameNode = attrNode.getAttributes().getNamedItem("name"); //$NON-NLS-1$
- if (nameNode != null) {
- String name = nameNode.getNodeValue();
- if (name != null) {
- info = mAttributeMap.get(name);
- // If the attribute is unknown yet, parse it.
- // If the attribute is know but its format is unknown, parse it too.
- if (info == null || info.getFormats().size() == 0) {
- info = parseAttributeTypes(attrNode, name);
- if (info != null) {
- mAttributeMap.put(name, info);
- }
- } else if (lastComment != null) {
- info = new AttributeInfo(info);
- }
- if (info != null) {
- if (lastComment != null) {
- String nodeValue = lastComment.getNodeValue();
- if (nodeValue.contains(DOC_HIDE)) {
- return null;
- }
- info.setJavaDoc(parseJavadoc(nodeValue));
- info.setDeprecatedDoc(parseDeprecatedDoc(nodeValue));
- }
- }
- }
- }
- return info;
- }
-
- /**
- * Finds all the attributes for a particular style node,
- * e.g. a declare-styleable of name "TextView" or "LinearLayout_Layout".
- *
- * @param styleName The name of the declare-styleable node
- * @param declareStyleableNode The declare-styleable node itself
- */
- private DeclareStyleableInfo parseDeclaredStyleable(String styleName,
- Node declareStyleableNode) {
- ArrayList<AttributeInfo> attrs = new ArrayList<AttributeInfo>();
- Node lastComment = null;
- for (Node node = declareStyleableNode.getFirstChild();
- node != null;
- node = node.getNextSibling()) {
-
- switch (node.getNodeType()) {
- case Node.COMMENT_NODE:
- lastComment = node;
- break;
- case Node.ELEMENT_NODE:
- if (node.getNodeName().equals("attr")) { //$NON-NLS-1$
- AttributeInfo info = parseAttr(node, lastComment);
- if (info != null) {
- attrs.add(info);
- }
- }
- lastComment = null;
- break;
- }
-
- }
-
- return new DeclareStyleableInfo(styleName, attrs.toArray(new AttributeInfo[attrs.size()]));
- }
-
- /**
- * Returns the {@link AttributeInfo} for a specific <attr> XML node.
- * This gets the javadoc, the type, the name and the enum/flag values if any.
- * <p/>
- * The XML node is expected to have the following attributes:
- * <ul>
- * <li>"name", which is mandatory. The node is skipped if this is missing.</li>
- * <li>"format".</li>
- * </ul>
- * The format may be one type or two types (e.g. "reference|color").
- * An extra format can be implied: "enum" or "flag" are not specified in the "format" attribute,
- * they are implicitly stated by the presence of sub-nodes <enum> or <flag>.
- * <p/>
- * By design, attr nodes of the same name MUST have the same type.
- * Attribute nodes are thus cached by name and reused as much as possible.
- * When reusing a node, it is duplicated and its javadoc reassigned.
- */
- private AttributeInfo parseAttributeTypes(Node attrNode, String name) {
- EnumSet<Format> formats = null;
- String[] enumValues = null;
- String[] flagValues = null;
-
- Node attrFormat = attrNode.getAttributes().getNamedItem("format"); //$NON-NLS-1$
- if (attrFormat != null) {
- for (String f : attrFormat.getNodeValue().split("\\|")) { //$NON-NLS-1$
- Format format = mFormatNames.get(f);
- if (format == null) {
- mLog.info(
- "Unknown format name '%s' in <attr name=\"%s\">, file '%s'.", //$NON-NLS-1$
- f, name, getOsAttrsXmlPath());
- } else if (format != AttributeInfo.Format.ENUM &&
- format != AttributeInfo.Format.FLAG) {
- if (formats == null) {
- formats = format.asSet();
- } else {
- if (formats.size() == 1) {
- formats = EnumSet.copyOf(formats);
- }
- formats.add(format);
- }
- }
- }
- }
-
- // does this <attr> have <enum> children?
- enumValues = parseEnumFlagValues(attrNode, "enum", name); //$NON-NLS-1$
- if (enumValues != null) {
- if (formats == null) {
- formats = Format.ENUM_SET;
- } else {
- if (formats.size() == 1) {
- formats = EnumSet.copyOf(formats);
- }
- formats.add(Format.ENUM);
- }
- }
-
- // does this <attr> have <flag> children?
- flagValues = parseEnumFlagValues(attrNode, "flag", name); //$NON-NLS-1$
- if (flagValues != null) {
- if (formats == null) {
- formats = Format.FLAG_SET;
- } else {
- if (formats.size() == 1) {
- formats = EnumSet.copyOf(formats);
- }
- formats.add(Format.FLAG);
- }
- }
-
- if (formats == null) {
- formats = Format.NONE;
- }
-
- AttributeInfo info = new AttributeInfo(name, formats);
- info.setEnumValues(enumValues);
- info.setFlagValues(flagValues);
- return info;
- }
-
- /**
- * Given an XML node that represents an <attr> node, this method searches
- * if the node has any children nodes named "target" (e.g. "enum" or "flag").
- * Such nodes must have a "name" attribute.
- * <p/>
- * If "attrNode" is null, look for any <attr> that has the given attrNode
- * and the requested children nodes.
- * <p/>
- * This method collects all the possible names of these children nodes and
- * return them.
- *
- * @param attrNode The <attr> XML node
- * @param filter The child node to look for, either "enum" or "flag".
- * @param attrName The value of the name attribute of <attr>
- *
- * @return Null if there are no such children nodes, otherwise an array of length >= 1
- * of all the names of these children nodes.
- */
- private String[] parseEnumFlagValues(Node attrNode, String filter, String attrName) {
- ArrayList<String> names = null;
- for (Node child = attrNode.getFirstChild(); child != null; child = child.getNextSibling()) {
- if (child.getNodeType() == Node.ELEMENT_NODE && child.getNodeName().equals(filter)) {
- Node nameNode = child.getAttributes().getNamedItem("name"); //$NON-NLS-1$
- if (nameNode == null) {
- mLog.warning(
- "Missing name attribute in <attr name=\"%s\"><%s></attr>", //$NON-NLS-1$
- attrName, filter);
- } else {
- if (names == null) {
- names = new ArrayList<String>();
- }
- String name = nameNode.getNodeValue();
- names.add(name);
-
- Node valueNode = child.getAttributes().getNamedItem("value"); //$NON-NLS-1$
- if (valueNode == null) {
- mLog.warning(
- "Missing value attribute in <attr name=\"%s\"><%s name=\"%s\"></attr>", //$NON-NLS-1$
- attrName, filter, name);
- } else {
- String value = valueNode.getNodeValue();
- try {
- // Integer.decode cannot handle "ffffffff", see JDK issue 6624867
- int i = (int) (long) Long.decode(value);
-
- Map<String, Integer> map = mEnumFlagValues.get(attrName);
- if (map == null) {
- map = new HashMap<String, Integer>();
- mEnumFlagValues.put(attrName, map);
- }
- map.put(name, Integer.valueOf(i));
-
- } catch(NumberFormatException e) {
- mLog.error(e,
- "Value in <attr name=\"%s\"><%s name=\"%s\" value=\"%s\"></attr> is not a valid decimal or hexadecimal", //$NON-NLS-1$
- attrName, filter, name, value);
- }
- }
- }
- }
- }
- return names == null ? null : names.toArray(new String[names.size()]);
- }
-
- /**
- * Parses the javadoc comment.
- * Only keeps the first sentence.
- * <p/>
- * This does not remove nor simplify links and references.
- */
- private String parseJavadoc(String comment) {
- if (comment == null) {
- return null;
- }
-
- // sanitize & collapse whitespace
- comment = comment.replaceAll("\\s+", " "); //$NON-NLS-1$ //$NON-NLS-2$
-
- // Explicitly remove any @deprecated tags since they are handled separately.
- comment = comment.replaceAll("(?:\\{@deprecated[^}]*\\}|@deprecated[^@}]*)", "");
-
- // take everything up to the first dot that is followed by a space or the end of the line.
- // I love regexps :-). For the curious, the regexp is:
- // - start of line
- // - ignore whitespace
- // - group:
- // - everything, not greedy
- // - non-capturing group (?: )
- // - end of string
- // or
- // - not preceded by a letter, a dot and another letter (for "i.e" and "e.g" )
- // (<! non-capturing zero-width negative look-behind)
- // - a dot
- // - followed by a space (?= non-capturing zero-width positive look-ahead)
- // - anything else is ignored
- comment = comment.replaceFirst("^\\s*(.*?(?:$|(?<![a-zA-Z]\\.[a-zA-Z])\\.(?=\\s))).*", "$1"); //$NON-NLS-1$ //$NON-NLS-2$
-
- return comment;
- }
-
-
- /**
- * Parses the javadoc and extract the first @deprecated tag, if any.
- * Returns null if there's no @deprecated tag.
- * The deprecated tag can be of two forms:
- * - {+@deprecated ...text till the next bracket }
- * Note: there should be no space or + between { and @. I need one in this comment otherwise
- * this method will be tagged as deprecated ;-)
- * - @deprecated ...text till the next @tag or end of the comment.
- * In both cases the comment can be multi-line.
- */
- private String parseDeprecatedDoc(String comment) {
- // Skip if we can't even find the tag in the comment.
- if (comment == null) {
- return null;
- }
-
- // sanitize & collapse whitespace
- comment = comment.replaceAll("\\s+", " "); //$NON-NLS-1$ //$NON-NLS-2$
-
- int pos = comment.indexOf("{@deprecated");
- if (pos >= 0) {
- comment = comment.substring(pos + 12 /* len of {@deprecated */);
- comment = comment.replaceFirst("^([^}]*).*", "$1");
- } else if ((pos = comment.indexOf("@deprecated")) >= 0) {
- comment = comment.substring(pos + 11 /* len of @deprecated */);
- comment = comment.replaceFirst("^(.*?)(?:@.*|$)", "$1");
- } else {
- return null;
- }
-
- return comment.trim();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/resources/platform/DeclareStyleableInfo.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/resources/platform/DeclareStyleableInfo.java
deleted file mode 100644
index 40111e24e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/resources/platform/DeclareStyleableInfo.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.resources.platform;
-
-
-/**
- * Information needed to represent a View or ViewGroup (aka Layout) item
- * in the layout hierarchy, as extracted from the main android.jar and the
- * associated attrs.xml.
- */
-public class DeclareStyleableInfo {
- /** The style name, never null. */
- private final String mStyleName;
- /** Attributes for this view or view group. Can be empty but never null. */
- private final AttributeInfo[] mAttributes;
- /** Short javadoc. Can be null. */
- private String mJavaDoc;
- /** Optional name of the parents styleable. Can be null. */
- private String[] mParents;
-
- /**
- * Creates a new {@link DeclareStyleableInfo}.
- *
- * @param styleName The name of the style. Should not be empty nor null.
- * @param attributes The initial list of attributes. Can be null.
- */
- public DeclareStyleableInfo(String styleName, AttributeInfo[] attributes) {
- mStyleName = styleName;
- mAttributes = attributes == null ? new AttributeInfo[0] : attributes;
- }
-
- /**
- * Creates a new {@link DeclareStyleableInfo} that has the same attributes
- * as an existing one and only differs by name.
- *
- * @param styleName The name of the style. Should not be empty nor null.
- * @param existing The existing {@link DeclareStyleableInfo} to mirror.
- */
- public DeclareStyleableInfo(String styleName, DeclareStyleableInfo existing) {
- mStyleName = styleName;
-
- mJavaDoc = existing.getJavaDoc();
-
- String[] parents = existing.getParents();
- if (parents != null) {
- mParents = new String[parents.length];
- System.arraycopy(parents, 0, mParents, 0, parents.length);
- }
-
- AttributeInfo[] attrs = existing.getAttributes();
- if (attrs == null || attrs.length == 0) {
- mAttributes = new AttributeInfo[0];
- } else {
- mAttributes = new AttributeInfo[attrs.length];
- System.arraycopy(attrs, 0, mAttributes, 0, attrs.length);
- }
- }
-
- /** Returns style name */
- public String getStyleName() {
- return mStyleName;
- }
-
- /** Returns the attributes for this view or view group. Maybe empty but not null. */
- public AttributeInfo[] getAttributes() {
- return mAttributes;
- }
-
- /** Returns a short javadoc */
- public String getJavaDoc() {
- return mJavaDoc;
- }
-
- /** Sets the javadoc. */
- public void setJavaDoc(String javaDoc) {
- mJavaDoc = javaDoc;
- }
-
- /** Sets the name of the parents styleable. Can be null. */
- public void setParents(String[] parents) {
- mParents = parents;
- }
-
- /** Returns the name of the parents styleable. Can be null. */
- public String[] getParents() {
- return mParents;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/resources/platform/ViewClassInfo.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/resources/platform/ViewClassInfo.java
deleted file mode 100644
index 214eb9cb4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/common/resources/platform/ViewClassInfo.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.resources.platform;
-
-
-/**
- * Information needed to represent a View or ViewGroup (aka Layout) item
- * in the layout hierarchy, as extracted from the main android.jar and the
- * associated attrs.xml.
- */
-public class ViewClassInfo {
- /** Is this a layout class (i.e. ViewGroup) or just a view? */
- private boolean mIsLayout;
- /** FQCN e.g. android.view.View, never null. */
- private String mFullClassName;
- /** Short class name, e.g. View, never null. */
- private String mShortClassName;
- /** Super class. Can be null. */
- private ViewClassInfo mSuperClass;
- /** Short javadoc. Can be null. */
- private String mJavaDoc;
- /** Attributes for this view or view group. Can be empty but never null. */
- private AttributeInfo[] mAttributes;
-
- public static class LayoutParamsInfo {
- /** Short class name, e.g. LayoutData, never null. */
- private String mShortClassName;
- /** ViewLayout class info owning this layout data */
- private ViewClassInfo mViewLayoutClass;
- /** Super class. Can be null. */
- private LayoutParamsInfo mSuperClass;
- /** Layout Data Attributes for layout classes. Can be empty but not null. */
- private AttributeInfo[] mAttributes;
-
- public LayoutParamsInfo(ViewClassInfo enclosingViewClassInfo,
- String shortClassName, LayoutParamsInfo superClassInfo) {
- mShortClassName = shortClassName;
- mViewLayoutClass = enclosingViewClassInfo;
- mSuperClass = superClassInfo;
- mAttributes = new AttributeInfo[0];
- }
-
- /** Returns short class name, e.g. "LayoutData" */
- public String getShortClassName() {
- return mShortClassName;
- }
- /** Returns the ViewLayout class info enclosing this layout data. Cannot null. */
- public ViewClassInfo getViewLayoutClass() {
- return mViewLayoutClass;
- }
- /** Returns the super class info. Can be null. */
- public LayoutParamsInfo getSuperClass() {
- return mSuperClass;
- }
- /** Returns the LayoutData attributes. Can be empty but not null. */
- public AttributeInfo[] getAttributes() {
- return mAttributes;
- }
- /** Sets the LayoutData attributes. Can be empty but not null. */
- public void setAttributes(AttributeInfo[] attributes) {
- mAttributes = attributes;
- }
- }
-
- /** Layout data info for a layout class. Null for all non-layout classes and always
- * non-null for a layout class. */
- public LayoutParamsInfo mLayoutData;
-
- // --------
-
- public ViewClassInfo(boolean isLayout, String fullClassName, String shortClassName) {
- mIsLayout = isLayout;
- mFullClassName = fullClassName;
- mShortClassName = shortClassName;
- mAttributes = new AttributeInfo[0];
- }
-
- /** Returns whether this is a layout class (i.e. ViewGroup) or just a View */
- public boolean isLayout() {
- return mIsLayout;
- }
-
- /** Returns FQCN e.g. "android.view.View" */
- public String getFullClassName() {
- return mFullClassName;
- }
-
- /** Returns short class name, e.g. "View" */
- public String getShortClassName() {
- return mShortClassName;
- }
-
- /** Returns the super class. Can be null. */
- public ViewClassInfo getSuperClass() {
- return mSuperClass;
- }
-
- /** Returns a short javadoc */
- public String getJavaDoc() {
- return mJavaDoc;
- }
-
- /** Returns the attributes for this view or view group. Maybe empty but not null. */
- public AttributeInfo[] getAttributes() {
- return mAttributes;
- }
-
- /** Returns the LayoutData info for layout classes. Null for non-layout view classes. */
- public LayoutParamsInfo getLayoutData() {
- return mLayoutData;
- }
-
- /**
- * Sets a link on the info of the super class of this View or ViewGroup.
- * <p/>
- * The super class info must be of the same kind (i.e. group to group or view to view)
- * except for the top ViewGroup which links to the View info.
- * <p/>
- * The super class cannot be null except for the top View info.
- */
- public void setSuperClass(ViewClassInfo superClass) {
- mSuperClass = superClass;
- }
-
- /** Sets the javadoc for this View or ViewGroup. */
- public void setJavaDoc(String javaDoc) {
- mJavaDoc = javaDoc;
- }
-
- /** Sets the list of attributes for this View or ViewGroup. */
- public void setAttributes(AttributeInfo[] attributes) {
- mAttributes = attributes;
- }
-
- /**
- * Sets the {@link LayoutParamsInfo} for layout classes.
- * Does nothing for non-layout view classes.
- */
- public void setLayoutParams(LayoutParamsInfo layoutData) {
- if (mIsLayout) {
- mLayoutData = layoutData;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/AdtConstants.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/AdtConstants.java
deleted file mode 100644
index 0e3b7839c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/AdtConstants.java
+++ /dev/null
@@ -1,242 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt;
-
-import static com.android.SdkConstants.DOT_AIDL;
-import static com.android.SdkConstants.DOT_DEP;
-import static com.android.SdkConstants.DOT_FS;
-import static com.android.SdkConstants.DOT_JAVA;
-import static com.android.SdkConstants.DOT_RS;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.internal.build.builders.PostCompilerBuilder;
-import com.android.ide.eclipse.adt.internal.build.builders.PreCompilerBuilder;
-import com.android.ide.eclipse.adt.internal.build.builders.ResourceManagerBuilder;
-
-import org.eclipse.jdt.core.JavaCore;
-
-import java.io.File;
-
-/**
- * Constant definition class.<br>
- * <br>
- * Most constants have a prefix defining the content.
- * <ul>
- * <li><code>WS_</code> Workspace path constant. Those are absolute paths,
- * from the project root.</li>
- * <li><code>OS_</code> OS path constant. These paths are different depending on the platform.</li>
- * <li><code>FN_</code> File name constant.</li>
- * <li><code>FD_</code> Folder name constant.</li>
- * <li><code>MARKER_</code> Resource Marker Ids constant.</li>
- * <li><code>EXT_</code> File extension constant. This does NOT include a dot.</li>
- * <li><code>DOT_</code> File extension constant. This start with a dot.</li>
- * <li><code>RE_</code> Regexp constant.</li>
- * <li><code>NS_</code> Namespace constant.</li>
- * <li><code>CLASS_</code> Fully qualified class name.</li>
- * </ul>
- *
- */
-public class AdtConstants {
- /**
- * The old Editors Plugin ID. It is still used in some places for compatibility.
- * Please do not use for new features.
- */
- public static final String EDITORS_NAMESPACE = "com.android.ide.eclipse.editors"; //$NON-NLS-1$
-
- /** Nature of default Android projects */
- public final static String NATURE_DEFAULT = "com.android.ide.eclipse.adt.AndroidNature"; //$NON-NLS-1$
-
- /** The container id for the android framework jar file */
- public final static String CONTAINER_FRAMEWORK =
- "com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"; //$NON-NLS-1$
-
- /** The container id for the libraries */
- public final static String CONTAINER_PRIVATE_LIBRARIES = "com.android.ide.eclipse.adt.LIBRARIES"; //$NON-NLS-1$
- public final static String CONTAINER_DEPENDENCIES = "com.android.ide.eclipse.adt.DEPENDENCIES";
-
-
- /** Separator for workspace path, i.e. "/". */
- public final static String WS_SEP = "/"; //$NON-NLS-1$
- /** Separator character for workspace path, i.e. '/'. */
- public final static char WS_SEP_CHAR = '/';
-
- /** aapt's proguard output */
- public final static String FN_AAPT_PROGUARD = "proguard.txt"; //$NON-NLS-1$
-
- /** Temporary packaged resources file name, i.e. "resources.ap_" */
- public final static String FN_RESOURCES_AP_ = "resources.ap_"; //$NON-NLS-1$
-
- public final static String FN_TRACEVIEW =
- (SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_WINDOWS) ?
- "traceview.bat" : "traceview"; //$NON-NLS-1$ //$NON-NLS-2$
-
- public final static String FN_HPROF_CONV =
- (SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_WINDOWS) ?
- "hprof-conv.exe" : "hprof-conv"; //$NON-NLS-1$ //$NON-NLS-2$
-
- /** Absolute path of the workspace root, i.e. "/" */
- public final static String WS_ROOT = WS_SEP;
-
- /** Absolute path of the resource folder, e.g. "/res".<br> This is a workspace path. */
- public final static String WS_RESOURCES = WS_SEP + SdkConstants.FD_RESOURCES;
-
- public final static String FD_CRUNCH = "crunch"; //$NON-NLS-1$
- public final static String FD_BC = "bc"; //$NON-NLS-1$
-
- /** Path of crunch cache folder relative to the output folder.<br> This is a workspace path. */
- public final static String WS_BIN_RELATIVE_CRUNCHCACHE = SdkConstants.FD_RESOURCES
- + WS_SEP + FD_CRUNCH;
-
- /** Path of bc output folder relative to the output folder.<br> This is a workspace path. */
- public final static String WS_BIN_RELATIVE_BC = SdkConstants.FD_RESOURCES
- + WS_SEP + FD_BC;
-
- /** Path of rs libs output folder relative to the output folder.<br> This is a workspace path. */
- public final static String WS_BIN_RELATIVE_RS_LIBS = SdkConstants.FD_RS_LIBS;
-
- /** Absolute path of the resource folder, e.g. "/assets".<br> This is a workspace path. */
- public final static String WS_ASSETS = WS_SEP + SdkConstants.FD_ASSETS;
-
- /** Absolute path of the layout folder, e.g. "/res/layout".<br> This is a workspace path. */
- public final static String WS_LAYOUTS = WS_RESOURCES + WS_SEP + SdkConstants.FD_RES_LAYOUT;
-
- /** Leaf of the javaDoc folder. Does not start with a separator. */
- public final static String WS_JAVADOC_FOLDER_LEAF = SdkConstants.FD_DOCS + "/" + //$NON-NLS-1$
- SdkConstants.FD_DOCS_REFERENCE;
-
- /** Path of the samples directory relative to the sdk folder.
- * This is an OS path, ending with a separator.
- * FIXME: remove once the NPW is fixed. */
- public final static String OS_SDK_SAMPLES_FOLDER = SdkConstants.FD_SAMPLES + File.separator;
-
- public final static String RE_DOT = "\\."; //$NON-NLS-1$
- /** Regexp for java extension, i.e. "\.java$" */
- public final static String RE_JAVA_EXT = "\\" + DOT_JAVA + "$"; //$NON-NLS-1$ //$NON-NLS-2$
- /** Regexp for aidl extension, i.e. "\.aidl$" */
- public final static String RE_AIDL_EXT = "\\" + DOT_AIDL + "$"; //$NON-NLS-1$ //$NON-NLS-2$
- /** Regexp for rs extension, i.e. "\.rs$" */
- public final static String RE_RS_EXT = "\\" + DOT_RS + "$"; //$NON-NLS-1$ //$NON-NLS-2$
- /** Regexp for rs extension, i.e. "\.fs$" */
- public final static String RE_FS_EXT = "\\" + DOT_FS + "$"; //$NON-NLS-1$ //$NON-NLS-2$
- /** Regexp for .d extension, i.e. "\.d$" */
- public final static String RE_DEP_EXT = "\\" + DOT_DEP + "$"; //$NON-NLS-1$ //$NON-NLS-2$
-
- /**
- * Namespace pattern for the custom resource XML, i.e. "http://schemas.android.com/apk/res/%s"
- * <p/>
- * This string contains a %s. It must be combined with the desired Java package, e.g.:
- * <pre>
- * String.format(SdkConstants.NS_CUSTOM_RESOURCES, "android");
- * String.format(SdkConstants.NS_CUSTOM_RESOURCES, "com.test.mycustomapp");
- * </pre>
- *
- * Note: if you need an URI specifically for the "android" namespace, consider using
- * {@link SdkConstants#NS_RESOURCES} instead.
- */
- // TODO rename NS_CUSTOM_RESOURCES to NS_CUSTOM_RESOURCES_S (denoting it takes a %s) in
- // another CL.
- public final static String NS_CUSTOM_RESOURCES = "http://schemas.android.com/apk/res/%1$s"; //$NON-NLS-1$
-
- /** The old common plug-in ID. Please do not use for new features. */
- private static final String LEGACY_PLUGIN_ID = "com.android.ide.eclipse.common"; //$NON-NLS-1$
-
- /** Generic marker for ADT errors, only to be used in the {@link ResourceManagerBuilder} */
- public final static String MARKER_ADT = AdtPlugin.PLUGIN_ID + ".adtProblem"; //$NON-NLS-1$
-
- /** Marker for Android Target errors.
- * This is not cleared on each build like other markers. Instead, it's cleared
- * when an AndroidClasspathContainerInitializer has succeeded in creating an
- * AndroidClasspathContainer */
- public final static String MARKER_TARGET = AdtPlugin.PLUGIN_ID + ".targetProblem"; //$NON-NLS-1$
- /** Marker for Android Build Tools errors.
- * This is not cleared on each build like other markers. Instead, it's cleared
- * when the build tools are setup in the projectState. */
- public final static String MARKER_BUILD_TOOLS = AdtPlugin.PLUGIN_ID + ".buildToolsProblem"; //$NON-NLS-1$
- /** Marker for Android Dependency errors.
- * This is not cleared on each build like other markers. Instead, it's cleared
- * when a LibraryClasspathContainerInitializer has succeeded in creating a
- * LibraryClasspathContainer */
- public final static String MARKER_DEPENDENCY = AdtPlugin.PLUGIN_ID + ".dependencyProblem"; //$NON-NLS-1$
-
-
- /** aapt marker error when running the compile command, only to be used
- * in {@link PreCompilerBuilder} */
- public final static String MARKER_AAPT_COMPILE = LEGACY_PLUGIN_ID + ".aaptProblem"; //$NON-NLS-1$
-
- /** XML marker error, only to be used in {@link PreCompilerBuilder} */
- public final static String MARKER_XML = LEGACY_PLUGIN_ID + ".xmlProblem"; //$NON-NLS-1$
-
- /** aidl marker error, only to be used in {@link PreCompilerBuilder} */
- public final static String MARKER_AIDL = LEGACY_PLUGIN_ID + ".aidlProblem"; //$NON-NLS-1$
-
- /** renderscript marker error, only to be used in {@link PreCompilerBuilder} */
- public final static String MARKER_RENDERSCRIPT = LEGACY_PLUGIN_ID + ".rsProblem"; //$NON-NLS-1$
-
- /** android marker error, only to be used in the Manifest parsing
- * from the {@link PreCompilerBuilder} */
- public final static String MARKER_ANDROID = LEGACY_PLUGIN_ID + ".androidProblem"; //$NON-NLS-1$
-
-
- /** aapt marker error when running the package command, only to be used in
- * {@link PostCompilerBuilder} */
- public final static String MARKER_AAPT_PACKAGE = LEGACY_PLUGIN_ID + ".aapt2Problem"; //$NON-NLS-1$
-
- /** final packaging error marker, only to be used in {@link PostCompilerBuilder} */
- public final static String MARKER_PACKAGING = AdtPlugin.PLUGIN_ID + ".packagingProblem"; //$NON-NLS-1$
-
- /** manifest merger error, only to be used in {@link PreCompilerBuilder} */
- public final static String MARKER_MANIFMERGER = AdtPlugin.PLUGIN_ID + ".manifMergerProblem"; //$NON-NLS-1$
-
- /** Marker for lint errors */
- public final static String MARKER_LINT = AdtPlugin.PLUGIN_ID + ".lintProblem"; //$NON-NLS-1$
-
- /** Name for the "type" marker attribute */
- public final static String MARKER_ATTR_TYPE = "android.type"; //$NON-NLS-1$
- /** Name for the "class" marker attribute */
- public final static String MARKER_ATTR_CLASS = "android.class"; //$NON-NLS-1$
- /** activity value for marker attribute "type" */
- public final static String MARKER_ATTR_TYPE_ACTIVITY = "activity"; //$NON-NLS-1$
- /** service value for marker attribute "type" */
- public final static String MARKER_ATTR_TYPE_SERVICE = "service"; //$NON-NLS-1$
- /** receiver value for marker attribute "type" */
- public final static String MARKER_ATTR_TYPE_RECEIVER = "receiver"; //$NON-NLS-1$
- /** provider value for marker attribute "type" */
- public final static String MARKER_ATTR_TYPE_PROVIDER = "provider"; //$NON-NLS-1$
-
- /**
- * Preferred compiler level, i.e. "1.6".
- */
- public final static String COMPILER_COMPLIANCE_PREFERRED = JavaCore.VERSION_1_6;
- /**
- * List of valid compiler level, i.e. "1.5" and "1.6"
- */
- public final static String[] COMPILER_COMPLIANCE = {
- JavaCore.VERSION_1_5,
- JavaCore.VERSION_1_6,
- };
-
- /** The base URL where to find the Android class & manifest documentation */
- public static final String CODESITE_BASE_URL = "http://code.google.com/android"; //$NON-NLS-1$
-
- public static final String LIBRARY_TEST_RUNNER = "android.test.runner"; //$NON-NLS-1$
-
- /** Documentation marker for elements, attributes etc that should be hidden */
- public static final String DOC_HIDE = "@hide"; //$NON-NLS-1$
-
- public static final String DEX_OPTIONS_FORCEJUMBO = "dex.force.jumbo"; //$NON-NLS-1$
- public static final String DEX_OPTIONS_DISABLE_MERGER = "dex.disable.merger"; //$NON-NLS-1$
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/AdtPlugin.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/AdtPlugin.java
deleted file mode 100644
index f7ef41fe3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/AdtPlugin.java
+++ /dev/null
@@ -1,2045 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt;
-
-import static com.android.SdkConstants.CURRENT_PLATFORM;
-import static com.android.SdkConstants.PLATFORM_DARWIN;
-import static com.android.SdkConstants.PLATFORM_LINUX;
-import static com.android.SdkConstants.PLATFORM_WINDOWS;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.resources.ResourceFile;
-import com.android.ide.common.sdk.LoadStatus;
-import com.android.ide.eclipse.adt.AdtPlugin.CheckSdkErrorHandler.Solution;
-import com.android.ide.eclipse.adt.internal.VersionCheck;
-import com.android.ide.eclipse.adt.internal.actions.SdkManagerAction;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.IncludeFinder;
-import com.android.ide.eclipse.adt.internal.lint.LintDeltaProcessor;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs.BuildVerbosity;
-import com.android.ide.eclipse.adt.internal.project.AndroidClasspathContainerInitializer;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.project.ProjectHelper;
-import com.android.ide.eclipse.adt.internal.resources.manager.GlobalProjectMonitor;
-import com.android.ide.eclipse.adt.internal.resources.manager.GlobalProjectMonitor.IFileListener;
-import com.android.ide.eclipse.adt.internal.resources.manager.GlobalProjectMonitor.IProjectListener;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk.ITargetChangeListener;
-import com.android.ide.eclipse.adt.internal.ui.EclipseUiHelper;
-import com.android.ide.eclipse.ddms.DdmsPlugin;
-import com.android.io.StreamException;
-import com.android.resources.ResourceFolderType;
-import com.android.sdklib.IAndroidTarget;
-import com.android.utils.ILogger;
-import com.google.common.collect.Sets;
-import com.google.common.io.Closeables;
-
-import org.eclipse.core.commands.Command;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarkerDelta;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.QualifiedName;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubMonitor;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.ui.JavaUI;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.PreferenceDialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorDescriptor;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.browser.IWebBrowser;
-import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
-import org.eclipse.ui.commands.ICommandService;
-import org.eclipse.ui.console.ConsolePlugin;
-import org.eclipse.ui.console.IConsole;
-import org.eclipse.ui.console.IConsoleConstants;
-import org.eclipse.ui.console.MessageConsole;
-import org.eclipse.ui.console.MessageConsoleStream;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.ui.handlers.IHandlerService;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.eclipse.ui.texteditor.AbstractTextEditor;
-import org.eclipse.wb.internal.core.DesignerPlugin;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.Reader;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Set;
-
-/**
- * The activator class controls the plug-in life cycle
- */
-public class AdtPlugin extends AbstractUIPlugin implements ILogger {
- /** The plug-in ID */
- public static final String PLUGIN_ID = "com.android.ide.eclipse.adt"; //$NON-NLS-1$
-
- /** singleton instance */
- private static AdtPlugin sPlugin;
-
- private static Image sAndroidLogo;
- private static ImageDescriptor sAndroidLogoDesc;
-
- /** The global android console */
- private MessageConsole mAndroidConsole;
-
- /** Stream to write in the android console */
- private MessageConsoleStream mAndroidConsoleStream;
-
- /** Stream to write error messages to the android console */
- private MessageConsoleStream mAndroidConsoleErrorStream;
-
- /** Color used in the error console */
- private Color mRed;
-
- /** Load status of the SDK. Any access MUST be in a synchronized(mPostLoadProjects) block */
- private LoadStatus mSdkLoadedStatus = LoadStatus.LOADING;
- /** Project to update once the SDK is loaded.
- * Any access MUST be in a synchronized(mPostLoadProjectsToResolve) block */
- private final Set<IJavaProject> mPostLoadProjectsToResolve = Sets.newHashSet();
- /** Project to check validity of cache vs actual once the SDK is loaded.
- * Any access MUST be in a synchronized(mPostLoadProjectsToResolve) block */
- private final ArrayList<IJavaProject> mPostLoadProjectsToCheck = new ArrayList<IJavaProject>();
-
- private GlobalProjectMonitor mResourceMonitor;
- private ArrayList<ITargetChangeListener> mTargetChangeListeners =
- new ArrayList<ITargetChangeListener>();
-
- /**
- * This variable indicates that the job inside parseSdkContent() is currently
- * trying to load the SDK, to avoid re-entrance.
- * To check whether this succeeds or not, please see {@link #getSdkLoadStatus()}.
- */
- private volatile boolean mParseSdkContentIsRunning;
-
- /**
- * An error handler for checkSdkLocationAndId() that will handle the generated error
- * or warning message. Each method must return a boolean that will in turn be returned by
- * checkSdkLocationAndId.
- */
- public static abstract class CheckSdkErrorHandler {
-
- public enum Solution {
- NONE,
- OPEN_SDK_MANAGER,
- OPEN_ANDROID_PREFS,
- OPEN_P2_UPDATE
- }
-
- /**
- * Handle an error message during sdk location check. Returns whatever
- * checkSdkLocationAndId() should returns.
- */
- public abstract boolean handleError(Solution solution, String message);
-
- /**
- * Handle a warning message during sdk location check. Returns whatever
- * checkSdkLocationAndId() should returns.
- */
- public abstract boolean handleWarning(Solution solution, String message);
- }
-
- /**
- * The constructor
- */
- public AdtPlugin() {
- sPlugin = this;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
-
- // set the default android console.
- mAndroidConsole = new MessageConsole("Android", null); //$NON-NLS-1$
- ConsolePlugin.getDefault().getConsoleManager().addConsoles(
- new IConsole[] { mAndroidConsole });
-
- // get the stream to write in the android console.
- mAndroidConsoleStream = mAndroidConsole.newMessageStream();
- mAndroidConsoleErrorStream = mAndroidConsole.newMessageStream();
-
- // get the eclipse store
- IPreferenceStore eclipseStore = getPreferenceStore();
- AdtPrefs.init(eclipseStore);
-
- // set the listener for the preference change
- eclipseStore.addPropertyChangeListener(new IPropertyChangeListener() {
- @Override
- public void propertyChange(PropertyChangeEvent event) {
- // load the new preferences
- AdtPrefs.getPrefs().loadValues(event);
-
- // if the SDK changed, we have to do some extra work
- if (AdtPrefs.PREFS_SDK_DIR.equals(event.getProperty())) {
-
- // finally restart adb, in case it's a different version
- DdmsPlugin.setToolsLocation(getOsAbsoluteAdb(), true /* startAdb */,
- getOsAbsoluteHprofConv(), getOsAbsoluteTraceview());
-
- // get the SDK location and build id.
- if (checkSdkLocationAndId()) {
- // if sdk if valid, reparse it
-
- reparseSdk();
- }
- }
- }
- });
-
- // load preferences.
- AdtPrefs.getPrefs().loadValues(null /*event*/);
-
- // initialize property-sheet library
- DesignerPlugin.initialize(
- this,
- PLUGIN_ID,
- CURRENT_PLATFORM == PLATFORM_WINDOWS,
- CURRENT_PLATFORM == PLATFORM_DARWIN,
- CURRENT_PLATFORM == PLATFORM_LINUX);
-
- // initialize editors
- startEditors();
-
- // Listen on resource file edits for updates to file inclusion
- IncludeFinder.start();
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- @Override
- public void stop(BundleContext context) throws Exception {
- super.stop(context);
-
- stopEditors();
- IncludeFinder.stop();
-
- DesignerPlugin.dispose();
-
- if (mRed != null) {
- mRed.dispose();
- mRed = null;
- }
-
- synchronized (AdtPlugin.class) {
- sPlugin = null;
- }
- }
-
- /** Called when the workbench has been started */
- public void workbenchStarted() {
- // Parse the SDK content.
- // This is deferred in separate jobs to avoid blocking the bundle start.
- final boolean isSdkLocationValid = checkSdkLocationAndId();
- if (isSdkLocationValid) {
- // parse the SDK resources.
- // Wait 2 seconds before starting the job. This leaves some time to the
- // other bundles to initialize.
- parseSdkContent(2000 /*milliseconds*/);
- }
-
- Display display = getDisplay();
- mRed = new Color(display, 0xFF, 0x00, 0x00);
-
- // because this can be run, in some cases, by a non ui thread, and because
- // changing the console properties update the ui, we need to make this change
- // in the ui thread.
- display.asyncExec(new Runnable() {
- @Override
- public void run() {
- mAndroidConsoleErrorStream.setColor(mRed);
- }
- });
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static synchronized AdtPlugin getDefault() {
- return sPlugin;
- }
-
- /**
- * Returns the current display, if any
- *
- * @return the display
- */
- @NonNull
- public static Display getDisplay() {
- synchronized (AdtPlugin.class) {
- if (sPlugin != null) {
- IWorkbench bench = sPlugin.getWorkbench();
- if (bench != null) {
- Display display = bench.getDisplay();
- if (display != null) {
- return display;
- }
- }
- }
- }
-
- Display display = Display.getCurrent();
- if (display != null) {
- return display;
- }
-
- return Display.getDefault();
- }
-
- /**
- * Returns the shell, if any
- *
- * @return the shell, if any
- */
- @Nullable
- public static Shell getShell() {
- Display display = AdtPlugin.getDisplay();
- Shell shell = display.getActiveShell();
- if (shell == null) {
- Shell[] shells = display.getShells();
- if (shells.length > 0) {
- shell = shells[0];
- }
- }
-
- return shell;
- }
-
- /** Returns the adb path relative to the sdk folder */
- public static String getOsRelativeAdb() {
- return SdkConstants.OS_SDK_PLATFORM_TOOLS_FOLDER + SdkConstants.FN_ADB;
- }
-
- /** Returns the emulator path relative to the sdk folder */
- public static String getOsRelativeEmulator() {
- return SdkConstants.OS_SDK_TOOLS_FOLDER + SdkConstants.FN_EMULATOR;
- }
-
- /** Returns the adb path relative to the sdk folder */
- public static String getOsRelativeProguard() {
- return SdkConstants.OS_SDK_TOOLS_PROGUARD_BIN_FOLDER + SdkConstants.FN_PROGUARD;
- }
-
- /** Returns the absolute adb path */
- public static String getOsAbsoluteAdb() {
- return getOsSdkFolder() + getOsRelativeAdb();
- }
-
- /** Returns the absolute traceview path */
- public static String getOsAbsoluteTraceview() {
- return getOsSdkFolder() + SdkConstants.OS_SDK_TOOLS_FOLDER +
- AdtConstants.FN_TRACEVIEW;
- }
-
- /** Returns the absolute emulator path */
- public static String getOsAbsoluteEmulator() {
- return getOsSdkFolder() + getOsRelativeEmulator();
- }
-
- public static String getOsAbsoluteHprofConv() {
- return getOsSdkFolder() + SdkConstants.OS_SDK_PLATFORM_TOOLS_FOLDER +
- AdtConstants.FN_HPROF_CONV;
- }
-
- /** Returns the absolute proguard path */
- public static String getOsAbsoluteProguard() {
- return getOsSdkFolder() + getOsRelativeProguard();
- }
-
- /**
- * Returns a Url file path to the javaDoc folder.
- */
- public static String getUrlDoc() {
- return ProjectHelper.getJavaDocPath(
- getOsSdkFolder() + AdtConstants.WS_JAVADOC_FOLDER_LEAF);
- }
-
- /**
- * Returns the SDK folder.
- * Guaranteed to be terminated by a platform-specific path separator.
- */
- public static synchronized String getOsSdkFolder() {
- if (sPlugin == null) {
- return null;
- }
-
- return AdtPrefs.getPrefs().getOsSdkFolder();
- }
-
- public static String getOsSdkToolsFolder() {
- return getOsSdkFolder() + SdkConstants.OS_SDK_TOOLS_FOLDER;
- }
-
- /**
- * Returns an image descriptor for the image file at the given
- * plug-in relative path
- *
- * @param path the path
- * @return the image descriptor
- */
- public static ImageDescriptor getImageDescriptor(String path) {
- return imageDescriptorFromPlugin(PLUGIN_ID, path);
- }
-
- /**
- * Reads the contents of an {@link IFile} and return it as a String
- *
- * @param file the file to be read
- * @return the String read from the file, or null if there was an error
- */
- @SuppressWarnings("resource") // Eclipse doesn't understand Closeables.closeQuietly yet
- @Nullable
- public static String readFile(@NonNull IFile file) {
- InputStream contents = null;
- InputStreamReader reader = null;
- try {
- contents = file.getContents();
- String charset = file.getCharset();
- reader = new InputStreamReader(contents, charset);
- return readFile(reader);
- } catch (CoreException e) {
- // pass -- ignore files we can't read
- } catch (IOException e) {
- // pass -- ignore files we can't read.
-
- // Note that IFile.getContents() indicates it throws a CoreException but
- // experience shows that if the file does not exists it really throws
- // IOException.
- // New InputStreamReader() throws UnsupportedEncodingException
- // which is handled by this IOException catch.
-
- } finally {
- Closeables.closeQuietly(reader);
- Closeables.closeQuietly(contents);
- }
-
- return null;
- }
-
- /**
- * Reads the contents of an {@link File} and return it as a String
- *
- * @param file the file to be read
- * @return the String read from the file, or null if there was an error
- */
- public static String readFile(File file) {
- try {
- return readFile(new FileReader(file));
- } catch (FileNotFoundException e) {
- AdtPlugin.log(e, "Can't read file %1$s", file); //$NON-NLS-1$
- }
-
- return null;
- }
-
- /**
- * Writes the given content out to the given {@link File}. The file will be deleted if
- * it already exists.
- *
- * @param file the target file
- * @param content the content to be written into the file
- */
- public static void writeFile(File file, String content) {
- if (file.exists()) {
- file.delete();
- }
- FileWriter fw = null;
- try {
- fw = new FileWriter(file);
- fw.write(content);
- } catch (IOException e) {
- AdtPlugin.log(e, null);
- } finally {
- if (fw != null) {
- try {
- fw.close();
- } catch (IOException e) {
- AdtPlugin.log(e, null);
- }
- }
- }
- }
-
- /**
- * Returns true iff the given file contains the given String.
- *
- * @param file the file to look for the string in
- * @param string the string to be searched for
- * @return true if the file is found and contains the given string anywhere within it
- */
- @SuppressWarnings("resource") // Closed by streamContains
- public static boolean fileContains(IFile file, String string) {
- InputStream contents = null;
- try {
- contents = file.getContents();
- String charset = file.getCharset();
- return streamContains(new InputStreamReader(contents, charset), string);
- } catch (Exception e) {
- AdtPlugin.log(e, "Can't read file %1$s", file); //$NON-NLS-1$
- }
-
- return false;
- }
-
- /**
- * Returns true iff the given file contains the given String.
- *
- * @param file the file to look for the string in
- * @param string the string to be searched for
- * @return true if the file is found and contains the given string anywhere within it
- */
- public static boolean fileContains(File file, String string) {
- try {
- return streamContains(new FileReader(file), string);
- } catch (Exception e) {
- AdtPlugin.log(e, "Can't read file %1$s", file); //$NON-NLS-1$
- }
-
- return false;
- }
-
- /**
- * Returns true iff the given input stream contains the given String.
- *
- * @param r the stream to look for the string in
- * @param string the string to be searched for
- * @return true if the file is found and contains the given string anywhere within it
- */
- public static boolean streamContains(Reader r, String string) {
- if (string.length() == 0) {
- return true;
- }
-
- PushbackReader reader = null;
- try {
- reader = new PushbackReader(r, string.length());
- char first = string.charAt(0);
- while (true) {
- int c = reader.read();
- if (c == -1) {
- return false;
- } else if (c == first) {
- boolean matches = true;
- for (int i = 1; i < string.length(); i++) {
- c = reader.read();
- if (c == -1) {
- return false;
- } else if (string.charAt(i) != (char)c) {
- matches = false;
- // Back up the characters that did not match
- reader.backup(i-1);
- break;
- }
- }
- if (matches) {
- return true;
- }
- }
- }
- } catch (Exception e) {
- AdtPlugin.log(e, "Can't read stream"); //$NON-NLS-1$
- } finally {
- try {
- if (reader != null) {
- reader.close();
- }
- } catch (IOException e) {
- AdtPlugin.log(e, "Can't read stream"); //$NON-NLS-1$
- }
- }
-
- return false;
-
- }
-
- /**
- * A special reader that allows backing up in the input (up to a predefined maximum
- * number of characters)
- * <p>
- * NOTE: This class ONLY works with the {@link #read()} method!!
- */
- private static class PushbackReader extends BufferedReader {
- /**
- * Rolling/circular buffer. Can be a char rather than int since we never store EOF
- * in it.
- */
- private char[] mStorage;
-
- /** Points to the head of the queue. When equal to the tail, the queue is empty. */
- private int mHead;
-
- /**
- * Points to the tail of the queue. This will move with each read of the actual
- * wrapped reader, and the characters previous to it in the circular buffer are
- * the most recently read characters.
- */
- private int mTail;
-
- /**
- * Creates a new reader with a given maximum number of backup characters
- *
- * @param reader the reader to wrap
- * @param max the maximum number of characters to allow rollback for
- */
- public PushbackReader(Reader reader, int max) {
- super(reader);
- mStorage = new char[max + 1];
- }
-
- @Override
- public int read() throws IOException {
- // Have we backed up? If so we should serve characters
- // from the storage
- if (mHead != mTail) {
- char c = mStorage[mHead];
- mHead = (mHead + 1) % mStorage.length;
- return c;
- }
- assert mHead == mTail;
-
- // No backup -- read the next character, but stash it into storage
- // as well such that we can retrieve it if we must.
- int c = super.read();
- mStorage[mHead] = (char) c;
- mHead = mTail = (mHead + 1) % mStorage.length;
- return c;
- }
-
- /**
- * Backs up the reader a given number of characters. The next N reads will yield
- * the N most recently read characters prior to this backup.
- *
- * @param n the number of characters to be backed up
- */
- public void backup(int n) {
- if (n >= mStorage.length) {
- throw new IllegalArgumentException("Exceeded backup limit");
- }
- assert n < mStorage.length;
- mHead -= n;
- if (mHead < 0) {
- mHead += mStorage.length;
- }
- }
- }
-
- /**
- * Reads the contents of a {@link ResourceFile} and returns it as a String
- *
- * @param file the file to be read
- * @return the contents as a String, or null if reading failed
- */
- public static String readFile(ResourceFile file) {
- InputStream contents = null;
- try {
- contents = file.getFile().getContents();
- return readFile(new InputStreamReader(contents));
- } catch (StreamException e) {
- // pass -- ignore files we can't read
- } finally {
- try {
- if (contents != null) {
- contents.close();
- }
- } catch (IOException e) {
- AdtPlugin.log(e, "Can't read layout file"); //$NON-NLS-1$
- }
- }
-
- return null;
- }
-
- /**
- * Reads the contents of a {@link Reader} and return it as a String. This
- * method will close the input reader.
- *
- * @param reader the reader to be read from
- * @return the String read from reader, or null if there was an error
- */
- public static String readFile(Reader reader) {
- BufferedReader bufferedReader = null;
- try {
- bufferedReader = new BufferedReader(reader);
- StringBuilder sb = new StringBuilder(2000);
- while (true) {
- int c = bufferedReader.read();
- if (c == -1) {
- return sb.toString();
- } else {
- sb.append((char)c);
- }
- }
- } catch (IOException e) {
- // pass -- ignore files we can't read
- } finally {
- try {
- if (bufferedReader != null) {
- bufferedReader.close();
- }
- } catch (IOException e) {
- AdtPlugin.log(e, "Can't read input stream"); //$NON-NLS-1$
- }
- }
-
- return null;
- }
-
- /**
- * Reads and returns the content of a text file embedded in the plugin jar
- * file.
- * @param filepath the file path to the text file
- * @return null if the file could not be read
- */
- public static String readEmbeddedTextFile(String filepath) {
- try {
- InputStream is = readEmbeddedFileAsStream(filepath);
- if (is != null) {
- BufferedReader reader = new BufferedReader(new InputStreamReader(is));
- try {
- String line;
- StringBuilder total = new StringBuilder(reader.readLine());
- while ((line = reader.readLine()) != null) {
- total.append('\n');
- total.append(line);
- }
-
- return total.toString();
- } finally {
- reader.close();
- }
- }
- } catch (IOException e) {
- // we'll just return null
- AdtPlugin.log(e, "Failed to read text file '%s'", filepath); //$NON-NLS-1$
- }
-
- return null;
- }
-
- /**
- * Reads and returns the content of a binary file embedded in the plugin jar
- * file.
- * @param filepath the file path to the text file
- * @return null if the file could not be read
- */
- public static byte[] readEmbeddedFile(String filepath) {
- try {
- InputStream is = readEmbeddedFileAsStream(filepath);
- if (is != null) {
- // create a buffered reader to facilitate reading.
- BufferedInputStream stream = new BufferedInputStream(is);
- try {
- // get the size to read.
- int avail = stream.available();
-
- // create the buffer and reads it.
- byte[] buffer = new byte[avail];
- stream.read(buffer);
-
- // and return.
- return buffer;
- } finally {
- stream.close();
- }
- }
- } catch (IOException e) {
- // we'll just return null;.
- AdtPlugin.log(e, "Failed to read binary file '%s'", filepath); //$NON-NLS-1$
- }
-
- return null;
- }
-
- /**
- * Reads and returns the content of a binary file embedded in the plugin jar
- * file.
- * @param filepath the file path to the text file
- * @return null if the file could not be read
- */
- public static InputStream readEmbeddedFileAsStream(String filepath) {
- // attempt to read an embedded file
- try {
- URL url = getEmbeddedFileUrl(AdtConstants.WS_SEP + filepath);
- if (url != null) {
- return url.openStream();
- }
- } catch (MalformedURLException e) {
- // we'll just return null.
- AdtPlugin.log(e, "Failed to read stream '%s'", filepath); //$NON-NLS-1$
- } catch (IOException e) {
- // we'll just return null;.
- AdtPlugin.log(e, "Failed to read stream '%s'", filepath); //$NON-NLS-1$
- }
-
- return null;
- }
-
- /**
- * Returns the URL of a binary file embedded in the plugin jar file.
- * @param filepath the file path to the text file
- * @return null if the file was not found.
- */
- public static URL getEmbeddedFileUrl(String filepath) {
- Bundle bundle = null;
- synchronized (AdtPlugin.class) {
- if (sPlugin != null) {
- bundle = sPlugin.getBundle();
- } else {
- AdtPlugin.log(IStatus.WARNING, "ADT Plugin is missing"); //$NON-NLS-1$
- return null;
- }
- }
-
- // attempt to get a file to one of the template.
- String path = filepath;
- if (!path.startsWith(AdtConstants.WS_SEP)) {
- path = AdtConstants.WS_SEP + path;
- }
-
- URL url = bundle.getEntry(path);
-
- if (url == null) {
- AdtPlugin.log(IStatus.INFO, "Bundle file URL not found at path '%s'", path); //$NON-NLS-1$
- }
-
- return url;
- }
-
- /**
- * Displays an error dialog box. This dialog box is ran asynchronously in the ui thread,
- * therefore this method can be called from any thread.
- * @param title The title of the dialog box
- * @param message The error message
- */
- public final static void displayError(final String title, final String message) {
- // get the current Display
- final Display display = getDisplay();
-
- // dialog box only run in ui thread..
- display.asyncExec(new Runnable() {
- @Override
- public void run() {
- Shell shell = display.getActiveShell();
- MessageDialog.openError(shell, title, message);
- }
- });
- }
-
- /**
- * Displays a warning dialog box. This dialog box is ran asynchronously in the ui thread,
- * therefore this method can be called from any thread.
- * @param title The title of the dialog box
- * @param message The warning message
- */
- public final static void displayWarning(final String title, final String message) {
- // get the current Display
- final Display display = getDisplay();
-
- // dialog box only run in ui thread..
- display.asyncExec(new Runnable() {
- @Override
- public void run() {
- Shell shell = display.getActiveShell();
- MessageDialog.openWarning(shell, title, message);
- }
- });
- }
-
- /**
- * Display a yes/no question dialog box. This dialog is opened synchronously in the ui thread,
- * therefore this message can be called from any thread.
- * @param title The title of the dialog box
- * @param message The error message
- * @return true if OK was clicked.
- */
- public final static boolean displayPrompt(final String title, final String message) {
- // get the current Display and Shell
- final Display display = getDisplay();
-
- // we need to ask the user what he wants to do.
- final boolean[] result = new boolean[1];
- display.syncExec(new Runnable() {
- @Override
- public void run() {
- Shell shell = display.getActiveShell();
- result[0] = MessageDialog.openQuestion(shell, title, message);
- }
- });
- return result[0];
- }
-
- /**
- * Logs a message to the default Eclipse log.
- *
- * @param severity The severity code. Valid values are: {@link IStatus#OK},
- * {@link IStatus#ERROR}, {@link IStatus#INFO}, {@link IStatus#WARNING} or
- * {@link IStatus#CANCEL}.
- * @param format The format string, like for {@link String#format(String, Object...)}.
- * @param args The arguments for the format string, like for
- * {@link String#format(String, Object...)}.
- */
- public static void log(int severity, String format, Object ... args) {
- if (format == null) {
- return;
- }
-
- String message = String.format(format, args);
- Status status = new Status(severity, PLUGIN_ID, message);
-
- if (getDefault() != null) {
- getDefault().getLog().log(status);
- } else {
- // During UnitTests, we generally don't have a plugin object. It's ok
- // to log to stdout or stderr in this case.
- (severity < IStatus.ERROR ? System.out : System.err).println(status.toString());
- }
- }
-
- /**
- * Logs an exception to the default Eclipse log.
- * <p/>
- * The status severity is always set to ERROR.
- *
- * @param exception the exception to log.
- * @param format The format string, like for {@link String#format(String, Object...)}.
- * @param args The arguments for the format string, like for
- * {@link String#format(String, Object...)}.
- */
- public static void log(Throwable exception, String format, Object ... args) {
- String message = null;
- if (format != null) {
- message = String.format(format, args);
- } else {
- message = "";
- }
- Status status = new Status(IStatus.ERROR, PLUGIN_ID, message, exception);
-
- if (getDefault() != null) {
- getDefault().getLog().log(status);
- } else {
- // During UnitTests, we generally don't have a plugin object. It's ok
- // to log to stderr in this case.
- System.err.println(status.toString());
- }
- }
-
- /**
- * This is a mix between log(Throwable) and printErrorToConsole.
- * <p/>
- * This logs the exception with an ERROR severity and the given printf-like format message.
- * The same message is then printed on the Android error console with the associated tag.
- *
- * @param exception the exception to log.
- * @param format The format string, like for {@link String#format(String, Object...)}.
- * @param args The arguments for the format string, like for
- * {@link String#format(String, Object...)}.
- */
- public static synchronized void logAndPrintError(Throwable exception, String tag,
- String format, Object ... args) {
- if (sPlugin != null) {
- String message = String.format(format, args);
- Status status = new Status(IStatus.ERROR, PLUGIN_ID, message, exception);
- getDefault().getLog().log(status);
- printToStream(sPlugin.mAndroidConsoleErrorStream, tag, message);
- showAndroidConsole();
- }
- }
-
- /**
- * Prints one or more error message to the android console.
- * @param tag A tag to be associated with the message. Can be null.
- * @param objects the objects to print through their <code>toString</code> method.
- */
- public static synchronized void printErrorToConsole(String tag, Object... objects) {
- if (sPlugin != null) {
- printToStream(sPlugin.mAndroidConsoleErrorStream, tag, objects);
-
- showAndroidConsole();
- }
- }
-
- /**
- * Prints one or more error message to the android console.
- * @param objects the objects to print through their <code>toString</code> method.
- */
- public static void printErrorToConsole(Object... objects) {
- printErrorToConsole((String)null, objects);
- }
-
- /**
- * Prints one or more error message to the android console.
- * @param project The project to which the message is associated. Can be null.
- * @param objects the objects to print through their <code>toString</code> method.
- */
- public static void printErrorToConsole(IProject project, Object... objects) {
- String tag = project != null ? project.getName() : null;
- printErrorToConsole(tag, objects);
- }
-
- /**
- * Prints one or more build messages to the android console, filtered by Build output verbosity.
- * @param level {@link BuildVerbosity} level of the message.
- * @param project The project to which the message is associated. Can be null.
- * @param objects the objects to print through their <code>toString</code> method.
- * @see BuildVerbosity#ALWAYS
- * @see BuildVerbosity#NORMAL
- * @see BuildVerbosity#VERBOSE
- */
- public static synchronized void printBuildToConsole(BuildVerbosity level, IProject project,
- Object... objects) {
- if (sPlugin != null) {
- if (level.getLevel() <= AdtPrefs.getPrefs().getBuildVerbosity().getLevel()) {
- String tag = project != null ? project.getName() : null;
- printToStream(sPlugin.mAndroidConsoleStream, tag, objects);
- }
- }
- }
-
- /**
- * Prints one or more message to the android console.
- * @param tag The tag to be associated with the message. Can be null.
- * @param objects the objects to print through their <code>toString</code> method.
- */
- public static synchronized void printToConsole(String tag, Object... objects) {
- if (sPlugin != null) {
- printToStream(sPlugin.mAndroidConsoleStream, tag, objects);
- }
- }
-
- /**
- * Prints one or more message to the android console.
- * @param project The project to which the message is associated. Can be null.
- * @param objects the objects to print through their <code>toString</code> method.
- */
- public static void printToConsole(IProject project, Object... objects) {
- String tag = project != null ? project.getName() : null;
- printToConsole(tag, objects);
- }
-
- /** Force the display of the android console */
- public static void showAndroidConsole() {
- // first make sure the console is in the workbench
- EclipseUiHelper.showView(IConsoleConstants.ID_CONSOLE_VIEW, true);
-
- // now make sure it's not docked.
- ConsolePlugin.getDefault().getConsoleManager().showConsoleView(
- AdtPlugin.getDefault().getAndroidConsole());
- }
-
- /**
- * Returns whether the {@link IAndroidTarget}s have been loaded from the SDK.
- */
- public final LoadStatus getSdkLoadStatus() {
- synchronized (Sdk.getLock()) {
- return mSdkLoadedStatus;
- }
- }
-
- /**
- * Sets the given {@link IJavaProject} to have its target resolved again once the SDK finishes
- * to load.
- */
- public final void setProjectToResolve(IJavaProject javaProject) {
- synchronized (Sdk.getLock()) {
- mPostLoadProjectsToResolve.add(javaProject);
- }
- }
-
- /**
- * Sets the given {@link IJavaProject} to have its target checked for consistency
- * once the SDK finishes to load. This is used if the target is resolved using cached
- * information while the SDK is loading.
- */
- public final void setProjectToCheck(IJavaProject javaProject) {
- // only lock on
- synchronized (Sdk.getLock()) {
- mPostLoadProjectsToCheck.add(javaProject);
- }
- }
-
- /**
- * Checks the location of the SDK in the prefs is valid.
- * If it is not, display a warning dialog to the user and try to display
- * some useful link to fix the situation (setup the preferences, perform an
- * update, etc.)
- *
- * @return True if the SDK location points to an SDK.
- * If false, the user has already been presented with a modal dialog explaining that.
- */
- public boolean checkSdkLocationAndId() {
- String sdkLocation = AdtPrefs.getPrefs().getOsSdkFolder();
-
- return checkSdkLocationAndId(sdkLocation, new CheckSdkErrorHandler() {
- private String mTitle = "Android SDK";
-
- /**
- * Handle an error, which is the case where the check did not find any SDK.
- * This returns false to {@link AdtPlugin#checkSdkLocationAndId()}.
- */
- @Override
- public boolean handleError(Solution solution, String message) {
- displayMessage(solution, message, MessageDialog.ERROR);
- return false;
- }
-
- /**
- * Handle an warning, which is the case where the check found an SDK
- * but it might need to be repaired or is missing an expected component.
- *
- * This returns true to {@link AdtPlugin#checkSdkLocationAndId()}.
- */
- @Override
- public boolean handleWarning(Solution solution, String message) {
- displayMessage(solution, message, MessageDialog.WARNING);
- return true;
- }
-
- private void displayMessage(
- final Solution solution,
- final String message,
- final int dialogImageType) {
- final Display disp = getDisplay();
- disp.asyncExec(new Runnable() {
- @Override
- public void run() {
- Shell shell = disp.getActiveShell();
- if (shell == null) {
- shell = AdtPlugin.getShell();
- }
- if (shell == null) {
- return;
- }
-
- String customLabel = null;
- switch(solution) {
- case OPEN_ANDROID_PREFS:
- customLabel = "Open Preferences";
- break;
- case OPEN_P2_UPDATE:
- customLabel = "Check for Updates";
- break;
- case OPEN_SDK_MANAGER:
- customLabel = "Open SDK Manager";
- break;
- }
-
- String btnLabels[] = new String[customLabel == null ? 1 : 2];
- btnLabels[0] = customLabel;
- btnLabels[btnLabels.length - 1] = IDialogConstants.CLOSE_LABEL;
-
- MessageDialog dialog = new MessageDialog(
- shell, // parent
- mTitle,
- null, // dialogTitleImage
- message,
- dialogImageType,
- btnLabels,
- btnLabels.length - 1);
- int index = dialog.open();
-
- if (customLabel != null && index == 0) {
- switch(solution) {
- case OPEN_ANDROID_PREFS:
- openAndroidPrefs();
- break;
- case OPEN_P2_UPDATE:
- openP2Update();
- break;
- case OPEN_SDK_MANAGER:
- openSdkManager();
- break;
- }
- }
- }
- });
- }
-
- private void openSdkManager() {
- // Open the standalone external SDK Manager since we know
- // that ADT on Windows is bound to be locking some SDK folders.
- //
- // Also when this is invoked because SdkManagerAction.run() fails, this
- // test will fail and we'll fallback on using the internal one.
- if (SdkManagerAction.openExternalSdkManager()) {
- return;
- }
-
- // Otherwise open the regular SDK Manager bundled within ADT
- if (!SdkManagerAction.openAdtSdkManager()) {
- // We failed because the SDK location is undefined. In this case
- // let's open the preferences instead.
- openAndroidPrefs();
- }
- }
-
- private void openP2Update() {
- Display disp = getDisplay();
- if (disp == null) {
- return;
- }
- disp.asyncExec(new Runnable() {
- @Override
- public void run() {
- String cmdId = "org.eclipse.equinox.p2.ui.sdk.update"; //$NON-NLS-1$
- IWorkbench wb = PlatformUI.getWorkbench();
- if (wb == null) {
- return;
- }
-
- ICommandService cs = (ICommandService) wb.getService(ICommandService.class);
- IHandlerService is = (IHandlerService) wb.getService(IHandlerService.class);
- if (cs == null || is == null) {
- return;
- }
-
- Command cmd = cs.getCommand(cmdId);
- if (cmd != null && cmd.isDefined()) {
- try {
- is.executeCommand(cmdId, null/*event*/);
- } catch (Exception ignore) {
- AdtPlugin.log(ignore, "Failed to execute command %s", cmdId);
- }
- }
- }
- });
- }
-
- private void openAndroidPrefs() {
- PreferenceDialog dialog = PreferencesUtil.createPreferenceDialogOn(
- getDisplay().getActiveShell(),
- "com.android.ide.eclipse.preferences.main", //$NON-NLS-1$ preferencePageId
- null, // displayedIds
- null); // data
- dialog.open();
- }
- });
- }
-
- /**
- * Internal helper to perform the actual sdk location and id check.
- * <p/>
- * This is useful for callers who want to override what happens when the check
- * fails. Otherwise consider calling {@link #checkSdkLocationAndId()} that will
- * present a modal dialog to the user in case of failure.
- *
- * @param osSdkLocation The sdk directory, an OS path. Can be null.
- * @param errorHandler An checkSdkErrorHandler that can display a warning or an error.
- * @return False if there was an error or the result from the errorHandler invocation.
- */
- public boolean checkSdkLocationAndId(@Nullable String osSdkLocation,
- @NonNull CheckSdkErrorHandler errorHandler) {
- if (osSdkLocation == null || osSdkLocation.trim().length() == 0) {
- return errorHandler.handleError(
- Solution.OPEN_ANDROID_PREFS,
- "Location of the Android SDK has not been setup in the preferences.");
- }
-
- if (!osSdkLocation.endsWith(File.separator)) {
- osSdkLocation = osSdkLocation + File.separator;
- }
-
- File osSdkFolder = new File(osSdkLocation);
- if (osSdkFolder.isDirectory() == false) {
- return errorHandler.handleError(
- Solution.OPEN_ANDROID_PREFS,
- String.format(Messages.Could_Not_Find_Folder, osSdkLocation));
- }
-
- String osTools = osSdkLocation + SdkConstants.OS_SDK_TOOLS_FOLDER;
- File toolsFolder = new File(osTools);
- if (toolsFolder.isDirectory() == false) {
- return errorHandler.handleError(
- Solution.OPEN_ANDROID_PREFS,
- String.format(Messages.Could_Not_Find_Folder_In_SDK,
- SdkConstants.FD_TOOLS, osSdkLocation));
- }
-
- // first check the min plug-in requirement as its error message is easier to figure
- // out for the user
- if (VersionCheck.checkVersion(osSdkLocation, errorHandler) == false) {
- return false;
- }
-
- // check that we have both the tools component and the platform-tools component.
- String platformTools = osSdkLocation + SdkConstants.OS_SDK_PLATFORM_TOOLS_FOLDER;
- if (checkFolder(platformTools) == false) {
- return errorHandler.handleWarning(
- Solution.OPEN_SDK_MANAGER,
- "SDK Platform Tools component is missing!\n" +
- "Please use the SDK Manager to install it.");
- }
-
- String tools = osSdkLocation + SdkConstants.OS_SDK_TOOLS_FOLDER;
- if (checkFolder(tools) == false) {
- return errorHandler.handleError(
- Solution.OPEN_SDK_MANAGER,
- "SDK Tools component is missing!\n" +
- "Please use the SDK Manager to install it.");
- }
-
- // check the path to various tools we use to make sure nothing is missing. This is
- // not meant to be exhaustive.
- String[] filesToCheck = new String[] {
- osSdkLocation + getOsRelativeAdb(),
- osSdkLocation + getOsRelativeEmulator()
- };
- for (String file : filesToCheck) {
- if (checkFile(file) == false) {
- return errorHandler.handleError(
- Solution.OPEN_ANDROID_PREFS,
- String.format(Messages.Could_Not_Find, file));
- }
- }
-
- return true;
- }
-
- /**
- * Checks if a path reference a valid existing file.
- * @param osPath the os path to check.
- * @return true if the file exists and is, in fact, a file.
- */
- private boolean checkFile(String osPath) {
- File file = new File(osPath);
- if (file.isFile() == false) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Checks if a path reference a valid existing folder.
- * @param osPath the os path to check.
- * @return true if the folder exists and is, in fact, a folder.
- */
- private boolean checkFolder(String osPath) {
- File file = new File(osPath);
- if (file.isDirectory() == false) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Parses the SDK resources.
- */
- private void parseSdkContent(long delay) {
- // Perform the update in a thread (here an Eclipse runtime job)
- // since this should never block the caller (especially the start method)
- Job job = new Job(Messages.AdtPlugin_Android_SDK_Content_Loader) {
- @SuppressWarnings("unchecked")
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
-
- if (mParseSdkContentIsRunning) {
- return new Status(IStatus.WARNING, PLUGIN_ID,
- "An Android SDK is already being loaded. Please try again later.");
- }
-
- mParseSdkContentIsRunning = true;
-
- SubMonitor progress = SubMonitor.convert(monitor,
- "Initialize SDK Manager", 100);
-
- Sdk sdk = Sdk.loadSdk(AdtPrefs.getPrefs().getOsSdkFolder());
-
- if (sdk != null) {
- ArrayList<IJavaProject> list = new ArrayList<IJavaProject>();
- synchronized (Sdk.getLock()) {
- mSdkLoadedStatus = LoadStatus.LOADED;
-
- progress.setTaskName("Check Projects");
-
- for (IJavaProject javaProject : mPostLoadProjectsToResolve) {
- IProject iProject = javaProject.getProject();
- if (iProject.isOpen()) {
- // project that have been resolved before the sdk was loaded
- // will have a ProjectState where the IAndroidTarget is null
- // so we load the target now that the SDK is loaded.
- sdk.loadTargetAndBuildTools(Sdk.getProjectState(iProject));
- list.add(javaProject);
- }
- }
-
- // done with this list.
- mPostLoadProjectsToResolve.clear();
- }
-
- // check the projects that need checking.
- // The method modifies the list (it removes the project that
- // do not need to be resolved again).
- AndroidClasspathContainerInitializer.checkProjectsCache(
- mPostLoadProjectsToCheck);
-
- list.addAll(mPostLoadProjectsToCheck);
-
- // update the project that needs recompiling.
- if (list.size() > 0) {
- IJavaProject[] array = list.toArray(
- new IJavaProject[list.size()]);
- ProjectHelper.updateProjects(array);
- }
-
- progress.worked(10);
- } else {
- // SDK failed to Load!
- // Sdk#loadSdk() has already displayed an error.
- synchronized (Sdk.getLock()) {
- mSdkLoadedStatus = LoadStatus.FAILED;
- }
- }
-
- // Notify resource changed listeners
- progress.setTaskName("Refresh UI");
- progress.setWorkRemaining(mTargetChangeListeners.size());
-
- // Clone the list before iterating, to avoid ConcurrentModification
- // exceptions
- final List<ITargetChangeListener> listeners =
- (List<ITargetChangeListener>)mTargetChangeListeners.clone();
- final SubMonitor progress2 = progress;
- AdtPlugin.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- for (ITargetChangeListener listener : listeners) {
- try {
- listener.onSdkLoaded();
- } catch (Exception e) {
- AdtPlugin.log(e, "Failed to update a TargetChangeListener."); //$NON-NLS-1$
- } finally {
- progress2.worked(1);
- }
- }
- }
- });
- } catch (Throwable t) {
- log(t, "Unknown exception in parseSdkContent."); //$NON-NLS-1$
- return new Status(IStatus.ERROR, PLUGIN_ID,
- "parseSdkContent failed", t); //$NON-NLS-1$
-
- } finally {
- mParseSdkContentIsRunning = false;
- if (monitor != null) {
- monitor.done();
- }
- }
-
- return Status.OK_STATUS;
- }
- };
- job.setPriority(Job.BUILD); // build jobs are run after other interactive jobs
- job.setRule(ResourcesPlugin.getWorkspace().getRoot());
- if (delay > 0) {
- job.schedule(delay);
- } else {
- job.schedule();
- }
- }
-
- /** Returns the global android console */
- public MessageConsole getAndroidConsole() {
- return mAndroidConsole;
- }
-
- // ----- Methods for Editors -------
-
- public void startEditors() {
- sAndroidLogoDesc = imageDescriptorFromPlugin(AdtPlugin.PLUGIN_ID,
- "/icons/android.png"); //$NON-NLS-1$
- sAndroidLogo = sAndroidLogoDesc.createImage();
-
- // Add a resource listener to handle compiled resources.
- IWorkspace ws = ResourcesPlugin.getWorkspace();
- mResourceMonitor = GlobalProjectMonitor.startMonitoring(ws);
-
- if (mResourceMonitor != null) {
- try {
- setupEditors(mResourceMonitor);
- ResourceManager.setup(mResourceMonitor);
- LintDeltaProcessor.startListening(mResourceMonitor);
- } catch (Throwable t) {
- log(t, "ResourceManager.setup failed"); //$NON-NLS-1$
- }
- }
- }
-
- /**
- * The <code>AbstractUIPlugin</code> implementation of this <code>Plugin</code>
- * method saves this plug-in's preference and dialog stores and shuts down
- * its image registry (if they are in use). Subclasses may extend this
- * method, but must send super <b>last</b>. A try-finally statement should
- * be used where necessary to ensure that <code>super.shutdown()</code> is
- * always done.
- *
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- public void stopEditors() {
- sAndroidLogo.dispose();
-
- IconFactory.getInstance().dispose();
-
- LintDeltaProcessor.stopListening(mResourceMonitor);
-
- // Remove the resource listener that handles compiled resources.
- IWorkspace ws = ResourcesPlugin.getWorkspace();
- GlobalProjectMonitor.stopMonitoring(ws);
-
- if (mRed != null) {
- mRed.dispose();
- mRed = null;
- }
- }
-
- /**
- * Returns an Image for the small Android logo.
- *
- * Callers should not dispose it.
- */
- public static Image getAndroidLogo() {
- return sAndroidLogo;
- }
-
- /**
- * Returns an {@link ImageDescriptor} for the small Android logo.
- *
- * Callers should not dispose it.
- */
- public static ImageDescriptor getAndroidLogoDesc() {
- return sAndroidLogoDesc;
- }
-
- /**
- * Returns the ResourceMonitor object.
- */
- public GlobalProjectMonitor getResourceMonitor() {
- return mResourceMonitor;
- }
-
- /**
- * Sets up the editor resource listener.
- * <p>
- * The listener handles:
- * <ul>
- * <li> Discovering newly created files, and ensuring that if they are in an Android
- * project, they default to the right XML editor.
- * <li> Discovering deleted files, and closing the corresponding editors if necessary.
- * This is only done for XML files, since other editors such as Java editors handles
- * it on their own.
- * <ul>
- *
- * This is called by the {@link AdtPlugin} during initialization.
- *
- * @param monitor The main Resource Monitor object.
- */
- public void setupEditors(GlobalProjectMonitor monitor) {
- monitor.addFileListener(new IFileListener() {
- @Override
- public void fileChanged(@NonNull IFile file, @NonNull IMarkerDelta[] markerDeltas,
- int kind, @Nullable String extension, int flags, boolean isAndroidProject) {
- if (!isAndroidProject) {
- return;
- }
- if (flags == IResourceDelta.MARKERS || !SdkConstants.EXT_XML.equals(extension)) {
- // ONLY the markers changed, or not XML file: not relevant to this listener
- return;
- }
-
- if (kind == IResourceDelta.REMOVED) {
- AdtUtils.closeEditors(file, false /*save*/);
- return;
- }
-
- // The resources files must have a file path similar to
- // project/res/.../*.xml
- // There is no support for sub folders, so the segment count must be 4
- if (file.getFullPath().segmentCount() == 4) {
- // check if we are inside the res folder.
- String segment = file.getFullPath().segment(1);
- if (segment.equalsIgnoreCase(SdkConstants.FD_RESOURCES)) {
- // we are inside a res/ folder, get the ResourceFolderType of the
- // parent folder.
- String[] folderSegments = file.getParent().getName().split(
- SdkConstants.RES_QUALIFIER_SEP);
-
- // get the enum for the resource type.
- ResourceFolderType type = ResourceFolderType.getTypeByName(
- folderSegments[0]);
-
- if (type != null) {
- if (kind == IResourceDelta.ADDED) {
- // A new file {@code /res/type-config/some.xml} was added.
- // All the /res XML files are handled by the same common editor now.
- IDE.setDefaultEditor(file, CommonXmlEditor.ID);
- }
- } else {
- // if the res folder is null, this means the name is invalid,
- // in this case we remove whatever android editors that was set
- // as the default editor.
- IEditorDescriptor desc = IDE.getDefaultEditor(file);
- String editorId = desc.getId();
- if (editorId.startsWith(AdtConstants.EDITORS_NAMESPACE)) {
- // reset the default editor.
- IDE.setDefaultEditor(file, null);
- }
- }
- }
- }
- }
- }, IResourceDelta.ADDED | IResourceDelta.REMOVED);
-
- monitor.addProjectListener(new IProjectListener() {
- @Override
- public void projectClosed(IProject project) {
- // Close any editors referencing this project
- AdtUtils.closeEditors(project, true /*save*/);
- }
-
- @Override
- public void projectDeleted(IProject project) {
- // Close any editors referencing this project
- AdtUtils.closeEditors(project, false /*save*/);
- }
-
- @Override
- public void projectOpenedWithWorkspace(IProject project) {
- }
-
- @Override
- public void allProjectsOpenedWithWorkspace() {
- }
-
- @Override
- public void projectOpened(IProject project) {
- }
-
- @Override
- public void projectRenamed(IProject project, IPath from) {
- }
- });
- }
-
- /**
- * Adds a new {@link ITargetChangeListener} to be notified when a new SDK is loaded, or when
- * a project has its target changed.
- */
- public void addTargetListener(ITargetChangeListener listener) {
- mTargetChangeListeners.add(listener);
- }
-
- /**
- * Removes an existing {@link ITargetChangeListener}.
- * @see #addTargetListener(ITargetChangeListener)
- */
- public void removeTargetListener(ITargetChangeListener listener) {
- mTargetChangeListeners.remove(listener);
- }
-
- /**
- * Updates all the {@link ITargetChangeListener}s that a target has changed for a given project.
- * <p/>Only editors related to that project should reload.
- */
- @SuppressWarnings("unchecked")
- public void updateTargetListeners(final IProject project) {
- final List<ITargetChangeListener> listeners =
- (List<ITargetChangeListener>)mTargetChangeListeners.clone();
-
- AdtPlugin.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- for (ITargetChangeListener listener : listeners) {
- try {
- listener.onProjectTargetChange(project);
- } catch (Exception e) {
- AdtPlugin.log(e, "Failed to update a TargetChangeListener."); //$NON-NLS-1$
- }
- }
- }
- });
- }
-
- /**
- * Updates all the {@link ITargetChangeListener}s that a target data was loaded.
- * <p/>Only editors related to a project using this target should reload.
- */
- @SuppressWarnings("unchecked")
- public void updateTargetListeners(final IAndroidTarget target) {
- final List<ITargetChangeListener> listeners =
- (List<ITargetChangeListener>)mTargetChangeListeners.clone();
-
- Display display = AdtPlugin.getDisplay();
- if (display == null || display.isDisposed()) {
- return;
- }
- display.asyncExec(new Runnable() {
- @Override
- public void run() {
- for (ITargetChangeListener listener : listeners) {
- try {
- listener.onTargetLoaded(target);
- } catch (Exception e) {
- AdtPlugin.log(e, "Failed to update a TargetChangeListener."); //$NON-NLS-1$
- }
- }
- }
- });
- }
-
- public static synchronized OutputStream getOutStream() {
- return sPlugin.mAndroidConsoleStream;
- }
-
- public static synchronized OutputStream getErrorStream() {
- return sPlugin.mAndroidConsoleErrorStream;
- }
-
- /**
- * Sets the named persistent property for the given file to the given value
- *
- * @param file the file to associate the property with
- * @param qname the name of the property
- * @param value the new value, or null to clear the property
- */
- public static void setFileProperty(IFile file, QualifiedName qname, String value) {
- try {
- file.setPersistentProperty(qname, value);
- } catch (CoreException e) {
- log(e, "Cannot set property %1$s to %2$s", qname, value);
- }
- }
-
- /**
- * Gets the named persistent file property from the given file
- *
- * @param file the file to look up properties for
- * @param qname the name of the property to look up
- * @return the property value, or null
- */
- public static String getFileProperty(IFile file, QualifiedName qname) {
- try {
- return file.getPersistentProperty(qname);
- } catch (CoreException e) {
- log(e, "Cannot get property %1$s", qname);
- }
-
- return null;
- }
-
- /**
- * Conditionally reparses the content of the SDK if it has changed on-disk
- * and updates opened projects.
- * <p/>
- * The operation is asynchronous and happens in a background eclipse job.
- * <p/>
- * This operation is called in multiple places and should be reasonably
- * cheap and conservative. The goal is to automatically refresh the SDK
- * when it is obvious it has changed so when not sure the code should
- * tend to not reload and avoid reloading too often (which is an expensive
- * operation that has a lot of user impact.)
- */
- public void refreshSdk() {
- // SDK can't have changed if we haven't loaded it yet.
- final Sdk sdk = Sdk.getCurrent();
- if (sdk == null) {
- return;
- }
-
- Job job = new Job("Check Android SDK") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- // SDK has changed if its location path is different.
- File location = sdk.getSdkFileLocation();
- boolean changed = location == null || !location.isDirectory();
-
- if (!changed) {
- assert location != null;
- File prefLocation = new File(AdtPrefs.getPrefs().getOsSdkFolder());
- changed = !location.equals(prefLocation);
-
- if (changed) {
- // Basic file path comparison indicates they are not the same.
- // Let's dig a bit deeper.
- try {
- location = location.getCanonicalFile();
- prefLocation = prefLocation.getCanonicalFile();
- changed = !location.equals(prefLocation);
- } catch (IOException ignore) {
- // There's no real reason for the canonicalization to fail
- // if the paths map to actual directories. And if they don't
- // this should have been caught above.
- }
- }
- }
-
- if (!changed) {
- // Check whether the target directories has potentially changed.
- changed = sdk.haveTargetsChanged();
- }
-
- if (changed) {
- monitor.setTaskName("Reload Android SDK");
- reparseSdk();
- }
-
- monitor.done();
- return Status.OK_STATUS;
- }
- };
- job.setRule(ResourcesPlugin.getWorkspace().getRoot());
- job.setPriority(Job.SHORT); // a short background job, not interactive.
- job.schedule();
- }
-
- /**
- * Reparses the content of the SDK and updates opened projects.
- * The operation is asynchronous and happens in a background eclipse job.
- * <p/>
- * This reloads the SDK all the time. To only perform this when it has potentially
- * changed, call {@link #refreshSdk()} instead.
- */
- public void reparseSdk() {
- // add all the opened Android projects to the list of projects to be updated
- // after the SDK is reloaded
- synchronized (Sdk.getLock()) {
- // get the project to refresh.
- IJavaProject[] androidProjects = BaseProjectHelper.getAndroidProjects(null /*filter*/);
- mPostLoadProjectsToResolve.addAll(Arrays.asList(androidProjects));
- }
-
- // parse the SDK resources at the new location
- parseSdkContent(0 /*immediately*/);
- }
-
- /**
- * Prints messages, associated with a project to the specified stream
- * @param stream The stream to write to
- * @param tag The tag associated to the message. Can be null
- * @param objects The objects to print through their toString() method (or directly for
- * {@link String} objects.
- */
- public static synchronized void printToStream(MessageConsoleStream stream, String tag,
- Object... objects) {
- String dateTag = AndroidPrintStream.getMessageTag(tag);
-
- for (Object obj : objects) {
- stream.print(dateTag);
- stream.print(" "); //$NON-NLS-1$
- if (obj instanceof String) {
- stream.println((String)obj);
- } else if (obj == null) {
- stream.println("(null)"); //$NON-NLS-1$
- } else {
- stream.println(obj.toString());
- }
- }
- }
-
- // --------- ILogger methods -----------
-
- @Override
- public void error(@Nullable Throwable t, @Nullable String format, Object... args) {
- if (t != null) {
- log(t, format, args);
- } else {
- log(IStatus.ERROR, format, args);
- }
- }
-
- @Override
- public void info(@NonNull String format, Object... args) {
- log(IStatus.INFO, format, args);
- }
-
- @Override
- public void verbose(@NonNull String format, Object... args) {
- log(IStatus.INFO, format, args);
- }
-
- @Override
- public void warning(@NonNull String format, Object... args) {
- log(IStatus.WARNING, format, args);
- }
-
- /**
- * Opens the given URL in a browser tab
- *
- * @param url the URL to open in a browser
- */
- public static void openUrl(URL url) {
- IWorkbenchBrowserSupport support = PlatformUI.getWorkbench().getBrowserSupport();
- IWebBrowser browser;
- try {
- browser = support.createBrowser(PLUGIN_ID);
- browser.openURL(url);
- } catch (PartInitException e) {
- log(e, null);
- }
- }
-
- /**
- * Opens a Java class for the given fully qualified class name
- *
- * @param project the project containing the class
- * @param fqcn the fully qualified class name of the class to be opened
- * @return true if the class was opened, false otherwise
- */
- public static boolean openJavaClass(IProject project, String fqcn) {
- if (fqcn == null) {
- return false;
- }
-
- // Handle inner classes
- if (fqcn.indexOf('$') != -1) {
- fqcn = fqcn.replaceAll("\\$", "."); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- try {
- if (project.hasNature(JavaCore.NATURE_ID)) {
- IJavaProject javaProject = JavaCore.create(project);
- IJavaElement result = javaProject.findType(fqcn);
- if (result != null) {
- return JavaUI.openInEditor(result) != null;
- }
- }
- } catch (Throwable e) {
- log(e, "Can't open class %1$s", fqcn); //$NON-NLS-1$
- }
-
- return false;
- }
-
- /**
- * For a stack trace entry, specifying a class, method, and optionally
- * fileName and line number, open the corresponding line in the editor.
- *
- * @param fqcn the fully qualified name of the class
- * @param method the method name
- * @param fileName the file name, or null
- * @param lineNumber the line number or -1
- * @return true if the target location could be opened, false otherwise
- */
- public static boolean openStackTraceLine(@Nullable String fqcn,
- @Nullable String method, @Nullable String fileName, int lineNumber) {
- return new SourceRevealer().revealMethod(fqcn + '.' + method, fileName, lineNumber, null);
- }
-
- /**
- * Opens the given file and shows the given (optional) region in the editor (or
- * if no region is specified, opens the editor tab.)
- *
- * @param file the file to be opened
- * @param region an optional region which if set will be selected and shown to the
- * user
- * @throws PartInitException if something goes wrong
- */
- public static void openFile(IFile file, IRegion region) throws PartInitException {
- openFile(file, region, true);
- }
-
- // TODO: Make an openEditor which does the above, and make the above pass false for showEditor
-
- /**
- * Opens the given file and shows the given (optional) region
- *
- * @param file the file to be opened
- * @param region an optional region which if set will be selected and shown to the
- * user
- * @param showEditorTab if true, front the editor tab after opening the file
- * @return the editor that was opened, or null if no editor was opened
- * @throws PartInitException if something goes wrong
- */
- public static IEditorPart openFile(IFile file, IRegion region, boolean showEditorTab)
- throws PartInitException {
- IWorkbenchPage page = AdtUtils.getActiveWorkbenchPage();
- if (page == null) {
- return null;
- }
- IEditorPart targetEditor = IDE.openEditor(page, file, true);
- if (targetEditor instanceof AndroidXmlEditor) {
- AndroidXmlEditor editor = (AndroidXmlEditor) targetEditor;
- if (region != null) {
- editor.show(region.getOffset(), region.getLength(), showEditorTab);
- } else if (showEditorTab) {
- editor.setActivePage(AndroidXmlEditor.TEXT_EDITOR_ID);
- }
- } else if (targetEditor instanceof AbstractTextEditor) {
- AbstractTextEditor editor = (AbstractTextEditor) targetEditor;
- if (region != null) {
- editor.setHighlightRange(region.getOffset(), region.getLength(),
- true /* moveCursor*/);
- }
- }
-
- return targetEditor;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/AdtUtils.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/AdtUtils.java
deleted file mode 100644
index 93cd2da1e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/AdtUtils.java
+++ /dev/null
@@ -1,1561 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt;
-
-import static com.android.SdkConstants.TOOLS_PREFIX;
-import static com.android.SdkConstants.TOOLS_URI;
-import static org.eclipse.ui.IWorkbenchPage.MATCH_INPUT;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.sdklib.SdkVersionInfo;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper.IProjectFilter;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.resources.ResourceFolderType;
-import com.android.resources.ResourceType;
-import com.android.sdklib.AndroidVersion;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.repository.PkgProps;
-import com.android.utils.XmlUtils;
-import com.google.common.io.ByteStreams;
-import com.google.common.io.Closeables;
-
-import org.eclipse.core.filebuffers.FileBuffers;
-import org.eclipse.core.filebuffers.ITextFileBuffer;
-import org.eclipse.core.filebuffers.ITextFileBufferManager;
-import org.eclipse.core.filebuffers.LocationKind;
-import org.eclipse.core.filesystem.URIUtil;
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IEditorReference;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.IURIEditorInput;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.editors.text.TextFileDocumentProvider;
-import org.eclipse.ui.part.FileEditorInput;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.wst.sse.core.StructuredModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-import java.io.File;
-import java.io.InputStream;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-
-
-/** Utility methods for ADT */
-@SuppressWarnings("restriction") // WST API
-public class AdtUtils {
- /**
- * Creates a Java class name out of the given string, if possible. For
- * example, "My Project" becomes "MyProject", "hello" becomes "Hello",
- * "Java's" becomes "Java", and so on.
- *
- * @param string the string to be massaged into a Java class
- * @return the string as a Java class, or null if a class name could not be
- * extracted
- */
- @Nullable
- public static String extractClassName(@NonNull String string) {
- StringBuilder sb = new StringBuilder(string.length());
- int n = string.length();
-
- int i = 0;
- for (; i < n; i++) {
- char c = Character.toUpperCase(string.charAt(i));
- if (Character.isJavaIdentifierStart(c)) {
- sb.append(c);
- i++;
- break;
- }
- }
- if (sb.length() > 0) {
- for (; i < n; i++) {
- char c = string.charAt(i);
- if (Character.isJavaIdentifierPart(c)) {
- sb.append(c);
- }
- }
-
- return sb.toString();
- }
-
- return null;
- }
-
- /**
- * Strips off the last file extension from the given filename, e.g.
- * "foo.backup.diff" will be turned into "foo.backup".
- * <p>
- * Note that dot files (e.g. ".profile") will be left alone.
- *
- * @param filename the filename to be stripped
- * @return the filename without the last file extension.
- */
- public static String stripLastExtension(String filename) {
- int dotIndex = filename.lastIndexOf('.');
- if (dotIndex > 0) { // > 0 instead of != -1: Treat dot files (e.g. .profile) differently
- return filename.substring(0, dotIndex);
- } else {
- return filename;
- }
- }
-
- /**
- * Strips off all extensions from the given filename, e.g. "foo.9.png" will
- * be turned into "foo".
- * <p>
- * Note that dot files (e.g. ".profile") will be left alone.
- *
- * @param filename the filename to be stripped
- * @return the filename without any file extensions
- */
- public static String stripAllExtensions(String filename) {
- int dotIndex = filename.indexOf('.');
- if (dotIndex > 0) { // > 0 instead of != -1: Treat dot files (e.g. .profile) differently
- return filename.substring(0, dotIndex);
- } else {
- return filename;
- }
- }
-
- /**
- * Strips the given suffix from the given string, provided that the string ends with
- * the suffix.
- *
- * @param string the full string to strip from
- * @param suffix the suffix to strip out
- * @return the string without the suffix at the end
- */
- public static String stripSuffix(@NonNull String string, @NonNull String suffix) {
- if (string.endsWith(suffix)) {
- return string.substring(0, string.length() - suffix.length());
- }
-
- return string;
- }
-
- /**
- * Capitalizes the string, i.e. transforms the initial [a-z] into [A-Z].
- * Returns the string unmodified if the first character is not [a-z].
- *
- * @param str The string to capitalize.
- * @return The capitalized string
- */
- public static String capitalize(String str) {
- if (str == null || str.length() < 1 || Character.isUpperCase(str.charAt(0))) {
- return str;
- }
-
- StringBuilder sb = new StringBuilder();
- sb.append(Character.toUpperCase(str.charAt(0)));
- sb.append(str.substring(1));
- return sb.toString();
- }
-
- /**
- * Converts a CamelCase word into an underlined_word
- *
- * @param string the CamelCase version of the word
- * @return the underlined version of the word
- */
- public static String camelCaseToUnderlines(String string) {
- if (string.isEmpty()) {
- return string;
- }
-
- StringBuilder sb = new StringBuilder(2 * string.length());
- int n = string.length();
- boolean lastWasUpperCase = Character.isUpperCase(string.charAt(0));
- for (int i = 0; i < n; i++) {
- char c = string.charAt(i);
- boolean isUpperCase = Character.isUpperCase(c);
- if (isUpperCase && !lastWasUpperCase) {
- sb.append('_');
- }
- lastWasUpperCase = isUpperCase;
- c = Character.toLowerCase(c);
- sb.append(c);
- }
-
- return sb.toString();
- }
-
- /**
- * Converts an underlined_word into a CamelCase word
- *
- * @param string the underlined word to convert
- * @return the CamelCase version of the word
- */
- public static String underlinesToCamelCase(String string) {
- StringBuilder sb = new StringBuilder(string.length());
- int n = string.length();
-
- int i = 0;
- boolean upcaseNext = true;
- for (; i < n; i++) {
- char c = string.charAt(i);
- if (c == '_') {
- upcaseNext = true;
- } else {
- if (upcaseNext) {
- c = Character.toUpperCase(c);
- }
- upcaseNext = false;
- sb.append(c);
- }
- }
-
- return sb.toString();
- }
-
- /**
- * Returns the current editor (the currently visible and active editor), or null if
- * not found
- *
- * @return the current editor, or null
- */
- public static IEditorPart getActiveEditor() {
- IWorkbenchWindow window = getActiveWorkbenchWindow();
- if (window != null) {
- IWorkbenchPage page = window.getActivePage();
- if (page != null) {
- return page.getActiveEditor();
- }
- }
-
- return null;
- }
-
- /**
- * Returns the current active workbench, or null if not found
- *
- * @return the current window, or null
- */
- @Nullable
- public static IWorkbenchWindow getActiveWorkbenchWindow() {
- IWorkbench workbench = PlatformUI.getWorkbench();
- IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
- if (window == null) {
- IWorkbenchWindow[] windows = workbench.getWorkbenchWindows();
- if (windows.length > 0) {
- window = windows[0];
- }
- }
-
- return window;
- }
-
- /**
- * Returns the current active workbench page, or null if not found
- *
- * @return the current page, or null
- */
- @Nullable
- public static IWorkbenchPage getActiveWorkbenchPage() {
- IWorkbenchWindow window = getActiveWorkbenchWindow();
- if (window != null) {
- IWorkbenchPage page = window.getActivePage();
- if (page == null) {
- IWorkbenchPage[] pages = window.getPages();
- if (pages.length > 0) {
- page = pages[0];
- }
- }
-
- return page;
- }
-
- return null;
- }
-
- /**
- * Returns the current active workbench part, or null if not found
- *
- * @return the current active workbench part, or null
- */
- @Nullable
- public static IWorkbenchPart getActivePart() {
- IWorkbenchWindow window = getActiveWorkbenchWindow();
- if (window != null) {
- IWorkbenchPage activePage = window.getActivePage();
- if (activePage != null) {
- return activePage.getActivePart();
- }
- }
- return null;
- }
-
- /**
- * Returns the current text editor (the currently visible and active editor), or null
- * if not found.
- *
- * @return the current text editor, or null
- */
- public static ITextEditor getActiveTextEditor() {
- IEditorPart editor = getActiveEditor();
- if (editor != null) {
- if (editor instanceof ITextEditor) {
- return (ITextEditor) editor;
- } else {
- return (ITextEditor) editor.getAdapter(ITextEditor.class);
- }
- }
-
- return null;
- }
-
- /**
- * Looks through the open editors and returns the editors that have the
- * given file as input.
- *
- * @param file the file to search for
- * @param restore whether editors should be restored (if they have an open
- * tab, but the editor hasn't been restored since the most recent
- * IDE start yet
- * @return a collection of editors
- */
- @NonNull
- public static Collection<IEditorPart> findEditorsFor(@NonNull IFile file, boolean restore) {
- FileEditorInput input = new FileEditorInput(file);
- List<IEditorPart> result = null;
- IWorkbench workbench = PlatformUI.getWorkbench();
- IWorkbenchWindow[] windows = workbench.getWorkbenchWindows();
- for (IWorkbenchWindow window : windows) {
- IWorkbenchPage[] pages = window.getPages();
- for (IWorkbenchPage page : pages) {
- IEditorReference[] editors = page.findEditors(input, null, MATCH_INPUT);
- if (editors != null) {
- for (IEditorReference reference : editors) {
- IEditorPart editor = reference.getEditor(restore);
- if (editor != null) {
- if (result == null) {
- result = new ArrayList<IEditorPart>();
- }
- result.add(editor);
- }
- }
- }
- }
- }
-
- if (result == null) {
- return Collections.emptyList();
- }
-
- return result;
- }
-
- /**
- * Attempts to convert the given {@link URL} into a {@link File}.
- *
- * @param url the {@link URL} to be converted
- * @return the corresponding {@link File}, which may not exist
- */
- @NonNull
- public static File getFile(@NonNull URL url) {
- try {
- // First try URL.toURI(): this will work for URLs that contain %20 for spaces etc.
- // Unfortunately, it *doesn't* work for "broken" URLs where the URL contains
- // spaces, which is often the case.
- return new File(url.toURI());
- } catch (URISyntaxException e) {
- // ...so as a fallback, go to the old url.getPath() method, which handles space paths.
- return new File(url.getPath());
- }
- }
-
- /**
- * Returns the file for the current editor, if any.
- *
- * @return the file for the current editor, or null if none
- */
- public static IFile getActiveFile() {
- IEditorPart editor = getActiveEditor();
- if (editor != null) {
- IEditorInput input = editor.getEditorInput();
- if (input instanceof IFileEditorInput) {
- IFileEditorInput fileInput = (IFileEditorInput) input;
- return fileInput.getFile();
- }
- }
-
- return null;
- }
-
- /**
- * Returns an absolute path to the given resource
- *
- * @param resource the resource to look up a path for
- * @return an absolute file system path to the resource
- */
- @NonNull
- public static IPath getAbsolutePath(@NonNull IResource resource) {
- IPath location = resource.getRawLocation();
- if (location != null) {
- return location.makeAbsolute();
- } else {
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IWorkspaceRoot root = workspace.getRoot();
- IPath workspacePath = root.getLocation();
- return workspacePath.append(resource.getFullPath());
- }
- }
-
- /**
- * Converts a workspace-relative path to an absolute file path
- *
- * @param path the workspace-relative path to convert
- * @return the corresponding absolute file in the file system
- */
- @NonNull
- public static File workspacePathToFile(@NonNull IPath path) {
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- IResource res = root.findMember(path);
- if (res != null) {
- IPath location = res.getLocation();
- if (location != null) {
- return location.toFile();
- }
- return root.getLocation().append(path).toFile();
- }
-
- return path.toFile();
- }
-
- /**
- * Converts a {@link File} to an {@link IFile}, if possible.
- *
- * @param file a file to be converted
- * @return the corresponding {@link IFile}, or null
- */
- public static IFile fileToIFile(File file) {
- if (!file.isAbsolute()) {
- file = file.getAbsoluteFile();
- }
-
- IWorkspaceRoot workspace = ResourcesPlugin.getWorkspace().getRoot();
- IFile[] files = workspace.findFilesForLocationURI(file.toURI());
- if (files.length > 0) {
- return files[0];
- }
-
- IPath filePath = new Path(file.getPath());
- return pathToIFile(filePath);
- }
-
- /**
- * Converts a {@link File} to an {@link IResource}, if possible.
- *
- * @param file a file to be converted
- * @return the corresponding {@link IResource}, or null
- */
- public static IResource fileToResource(File file) {
- if (!file.isAbsolute()) {
- file = file.getAbsoluteFile();
- }
-
- IWorkspaceRoot workspace = ResourcesPlugin.getWorkspace().getRoot();
- IFile[] files = workspace.findFilesForLocationURI(file.toURI());
- if (files.length > 0) {
- return files[0];
- }
-
- IPath filePath = new Path(file.getPath());
- return pathToResource(filePath);
- }
-
- /**
- * Converts a {@link IPath} to an {@link IFile}, if possible.
- *
- * @param path a path to be converted
- * @return the corresponding {@link IFile}, or null
- */
- public static IFile pathToIFile(IPath path) {
- IWorkspaceRoot workspace = ResourcesPlugin.getWorkspace().getRoot();
-
- IFile[] files = workspace.findFilesForLocationURI(URIUtil.toURI(path.makeAbsolute()));
- if (files.length > 0) {
- return files[0];
- }
-
- IPath workspacePath = workspace.getLocation();
- if (workspacePath.isPrefixOf(path)) {
- IPath relativePath = path.makeRelativeTo(workspacePath);
- IResource member = workspace.findMember(relativePath);
- if (member instanceof IFile) {
- return (IFile) member;
- }
- } else if (path.isAbsolute()) {
- return workspace.getFileForLocation(path);
- }
-
- return null;
- }
-
- /**
- * Converts a {@link IPath} to an {@link IResource}, if possible.
- *
- * @param path a path to be converted
- * @return the corresponding {@link IResource}, or null
- */
- public static IResource pathToResource(IPath path) {
- IWorkspaceRoot workspace = ResourcesPlugin.getWorkspace().getRoot();
-
- IFile[] files = workspace.findFilesForLocationURI(URIUtil.toURI(path.makeAbsolute()));
- if (files.length > 0) {
- return files[0];
- }
-
- IPath workspacePath = workspace.getLocation();
- if (workspacePath.isPrefixOf(path)) {
- IPath relativePath = path.makeRelativeTo(workspacePath);
- return workspace.findMember(relativePath);
- } else if (path.isAbsolute()) {
- return workspace.getFileForLocation(path);
- }
-
- return null;
- }
-
- /**
- * Returns all markers in a file/document that fit on the same line as the given offset
- *
- * @param markerType the marker type
- * @param file the file containing the markers
- * @param document the document showing the markers
- * @param offset the offset to be checked
- * @return a list (possibly empty but never null) of matching markers
- */
- @NonNull
- public static List<IMarker> findMarkersOnLine(
- @NonNull String markerType,
- @NonNull IResource file,
- @NonNull IDocument document,
- int offset) {
- List<IMarker> matchingMarkers = new ArrayList<IMarker>(2);
- try {
- IMarker[] markers = file.findMarkers(markerType, true, IResource.DEPTH_ZERO);
-
- // Look for a match on the same line as the caret.
- IRegion lineInfo = document.getLineInformationOfOffset(offset);
- int lineStart = lineInfo.getOffset();
- int lineEnd = lineStart + lineInfo.getLength();
- int offsetLine = document.getLineOfOffset(offset);
-
-
- for (IMarker marker : markers) {
- int start = marker.getAttribute(IMarker.CHAR_START, -1);
- int end = marker.getAttribute(IMarker.CHAR_END, -1);
- if (start >= lineStart && start <= lineEnd && end > start) {
- matchingMarkers.add(marker);
- } else if (start == -1 && end == -1) {
- // Some markers don't set character range, they only set the line
- int line = marker.getAttribute(IMarker.LINE_NUMBER, -1);
- if (line == offsetLine + 1) {
- matchingMarkers.add(marker);
- }
- }
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- } catch (BadLocationException e) {
- AdtPlugin.log(e, null);
- }
-
- return matchingMarkers;
- }
-
- /**
- * Returns the available and open Android projects
- *
- * @return the available and open Android projects, never null
- */
- @NonNull
- public static IJavaProject[] getOpenAndroidProjects() {
- return BaseProjectHelper.getAndroidProjects(new IProjectFilter() {
- @Override
- public boolean accept(IProject project) {
- return project.isAccessible();
- }
- });
- }
-
- /**
- * Returns a unique project name, based on the given {@code base} file name
- * possibly with a {@code conjunction} and a new number behind it to ensure
- * that the project name is unique. For example,
- * {@code getUniqueProjectName("project", "_")} will return
- * {@code "project"} if that name does not already exist, and if it does, it
- * will return {@code "project_2"}.
- *
- * @param base the base name to use, such as "foo"
- * @param conjunction a string to insert between the base name and the
- * number.
- * @return a unique project name based on the given base and conjunction
- */
- public static String getUniqueProjectName(String base, String conjunction) {
- // We're using all workspace projects here rather than just open Android project
- // via getOpenAndroidProjects because the name cannot conflict with non-Android
- // or closed projects either
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
- IProject[] projects = workspaceRoot.getProjects();
-
- for (int i = 1; i < 1000; i++) {
- String name = i == 1 ? base : base + conjunction + Integer.toString(i);
- boolean found = false;
- for (IProject project : projects) {
- // Need to make case insensitive comparison, since otherwise we can hit
- // org.eclipse.core.internal.resources.ResourceException:
- // A resource exists with a different case: '/test'.
- if (project.getName().equalsIgnoreCase(name)) {
- found = true;
- break;
- }
- }
- if (!found) {
- return name;
- }
- }
-
- return base;
- }
-
- /**
- * Returns the name of the parent folder for the given editor input
- *
- * @param editorInput the editor input to check
- * @return the parent folder, which is never null but may be ""
- */
- @NonNull
- public static String getParentFolderName(@Nullable IEditorInput editorInput) {
- if (editorInput instanceof IFileEditorInput) {
- IFile file = ((IFileEditorInput) editorInput).getFile();
- return file.getParent().getName();
- }
-
- if (editorInput instanceof IURIEditorInput) {
- IURIEditorInput urlEditorInput = (IURIEditorInput) editorInput;
- String path = urlEditorInput.getURI().toString();
- int lastIndex = path.lastIndexOf('/');
- if (lastIndex != -1) {
- int lastLastIndex = path.lastIndexOf('/', lastIndex - 1);
- if (lastLastIndex != -1) {
- return path.substring(lastLastIndex + 1, lastIndex);
- }
- }
- }
-
- return "";
- }
-
- /**
- * Returns the XML editor for the given editor part
- *
- * @param part the editor part to look up the editor for
- * @return the editor or null if this part is not an XML editor
- */
- @Nullable
- public static AndroidXmlEditor getXmlEditor(@NonNull IEditorPart part) {
- if (part instanceof AndroidXmlEditor) {
- return (AndroidXmlEditor) part;
- } else if (part instanceof GraphicalEditorPart) {
- ((GraphicalEditorPart) part).getEditorDelegate().getEditor();
- }
-
- return null;
- }
-
- /**
- * Sets the given tools: attribute in the given XML editor document, adding
- * the tools name space declaration if necessary, formatting the affected
- * document region, and optionally comma-appending to an existing value and
- * optionally opening and revealing the attribute.
- *
- * @param editor the associated editor
- * @param element the associated element
- * @param description the description of the attribute (shown in the undo
- * event)
- * @param name the name of the attribute
- * @param value the attribute value
- * @param reveal if true, open the editor and select the given attribute
- * node
- * @param appendValue if true, add this value as a comma separated value to
- * the existing attribute value, if any
- */
- public static void setToolsAttribute(
- @NonNull final AndroidXmlEditor editor,
- @NonNull final Element element,
- @NonNull final String description,
- @NonNull final String name,
- @Nullable final String value,
- final boolean reveal,
- final boolean appendValue) {
- editor.wrapUndoEditXmlModel(description, new Runnable() {
- @Override
- public void run() {
- String prefix = XmlUtils.lookupNamespacePrefix(element, TOOLS_URI, null, true);
- if (prefix == null) {
- // Add in new prefix...
- prefix = XmlUtils.lookupNamespacePrefix(element,
- TOOLS_URI, TOOLS_PREFIX, true /*create*/);
- if (value != null) {
- // ...and ensure that the header is formatted such that
- // the XML namespace declaration is placed in the right
- // position and wrapping is applied etc.
- editor.scheduleNodeReformat(editor.getUiRootNode(),
- true /*attributesOnly*/);
- }
- }
-
- String v = value;
- if (appendValue && v != null) {
- String prev = element.getAttributeNS(TOOLS_URI, name);
- if (prev.length() > 0) {
- v = prev + ',' + value;
- }
- }
-
- // Use the non-namespace form of set attribute since we can't
- // reference the namespace until the model has been reloaded
- if (v != null) {
- element.setAttribute(prefix + ':' + name, v);
- } else {
- element.removeAttribute(prefix + ':' + name);
- }
-
- UiElementNode rootUiNode = editor.getUiRootNode();
- if (rootUiNode != null && v != null) {
- final UiElementNode uiNode = rootUiNode.findXmlNode(element);
- if (uiNode != null) {
- editor.scheduleNodeReformat(uiNode, true /*attributesOnly*/);
-
- if (reveal) {
- // Update editor selection after format
- Display display = AdtPlugin.getDisplay();
- if (display != null) {
- display.asyncExec(new Runnable() {
- @Override
- public void run() {
- Node xmlNode = uiNode.getXmlNode();
- Attr attribute = ((Element) xmlNode).getAttributeNodeNS(
- TOOLS_URI, name);
- if (attribute instanceof IndexedRegion) {
- IndexedRegion region = (IndexedRegion) attribute;
- editor.getStructuredTextEditor().selectAndReveal(
- region.getStartOffset(), region.getLength());
- }
- }
- });
- }
- }
- }
- }
- }
- });
- }
-
- /**
- * Returns a string label for the given target, of the form
- * "API 16: Android 4.1 (Jelly Bean)".
- *
- * @param target the target to generate a string from
- * @return a suitable display string
- */
- @NonNull
- public static String getTargetLabel(@NonNull IAndroidTarget target) {
- if (target.isPlatform()) {
- AndroidVersion version = target.getVersion();
- String codename = target.getProperty(PkgProps.PLATFORM_CODENAME);
- String release = target.getProperty("ro.build.version.release"); //$NON-NLS-1$
- if (codename != null) {
- return String.format("API %1$d: Android %2$s (%3$s)",
- version.getApiLevel(),
- release,
- codename);
- }
- return String.format("API %1$d: Android %2$s", version.getApiLevel(),
- release);
- }
-
- return String.format("%1$s (API %2$s)", target.getFullName(),
- target.getVersion().getApiString());
- }
-
- /**
- * Sets the given tools: attribute in the given XML editor document, adding
- * the tools name space declaration if necessary, and optionally
- * comma-appending to an existing value.
- *
- * @param file the file associated with the element
- * @param element the associated element
- * @param description the description of the attribute (shown in the undo
- * event)
- * @param name the name of the attribute
- * @param value the attribute value
- * @param appendValue if true, add this value as a comma separated value to
- * the existing attribute value, if any
- */
- public static void setToolsAttribute(
- @NonNull final IFile file,
- @NonNull final Element element,
- @NonNull final String description,
- @NonNull final String name,
- @Nullable final String value,
- final boolean appendValue) {
- IModelManager modelManager = StructuredModelManager.getModelManager();
- if (modelManager == null) {
- return;
- }
-
- try {
- IStructuredModel model = null;
- if (model == null) {
- model = modelManager.getModelForEdit(file);
- }
- if (model != null) {
- try {
- model.aboutToChangeModel();
- if (model instanceof IDOMModel) {
- IDOMModel domModel = (IDOMModel) model;
- Document doc = domModel.getDocument();
- if (doc != null && element.getOwnerDocument() == doc) {
- String prefix = XmlUtils.lookupNamespacePrefix(element, TOOLS_URI,
- null, true);
- if (prefix == null) {
- // Add in new prefix...
- prefix = XmlUtils.lookupNamespacePrefix(element,
- TOOLS_URI, TOOLS_PREFIX, true);
- }
-
- String v = value;
- if (appendValue && v != null) {
- String prev = element.getAttributeNS(TOOLS_URI, name);
- if (prev.length() > 0) {
- v = prev + ',' + value;
- }
- }
-
- // Use the non-namespace form of set attribute since we can't
- // reference the namespace until the model has been reloaded
- if (v != null) {
- element.setAttribute(prefix + ':' + name, v);
- } else {
- element.removeAttribute(prefix + ':' + name);
- }
- }
- }
- } finally {
- model.changedModel();
- String updated = model.getStructuredDocument().get();
- model.releaseFromEdit();
- model.save(file);
-
- // Must also force a save on disk since the above model.save(file) often
- // (always?) has no effect.
- ITextFileBufferManager manager = FileBuffers.getTextFileBufferManager();
- NullProgressMonitor monitor = new NullProgressMonitor();
- IPath path = file.getFullPath();
- manager.connect(path, LocationKind.IFILE, monitor);
- try {
- ITextFileBuffer buffer = manager.getTextFileBuffer(path,
- LocationKind.IFILE);
- IDocument currentDocument = buffer.getDocument();
- currentDocument.set(updated);
- buffer.commit(monitor, true);
- } finally {
- manager.disconnect(path, LocationKind.IFILE, monitor);
- }
- }
- }
- } catch (Exception e) {
- AdtPlugin.log(e, null);
- }
- }
-
- /**
- * Returns the Android version and code name of the given API level
- *
- * @param api the api level
- * @return a suitable version display name
- */
- public static String getAndroidName(int api) {
- if (api <= SdkVersionInfo.HIGHEST_KNOWN_API) {
- return SdkVersionInfo.getAndroidName(api);
- }
-
- // Consult SDK manager to see if we know any more (later) names,
- // installed by user
- Sdk sdk = Sdk.getCurrent();
- if (sdk != null) {
- for (IAndroidTarget target : sdk.getTargets()) {
- if (target.isPlatform()) {
- AndroidVersion version = target.getVersion();
- if (version.getApiLevel() == api) {
- return getTargetLabel(target);
- }
- }
- }
- }
-
- return "API " + api;
- }
-
- /**
- * Returns the highest known API level to this version of ADT. The
- * {@link #getAndroidName(int)} method will return real names up to and
- * including this number.
- *
- * @return the highest known API number
- */
- public static int getHighestKnownApiLevel() {
- return SdkVersionInfo.HIGHEST_KNOWN_API;
- }
-
- /**
- * Returns a list of known API names
- *
- * @return a list of string API names, starting from 1 and up through the
- * maximum known versions (with no gaps)
- */
- public static String[] getKnownVersions() {
- int max = getHighestKnownApiLevel();
- Sdk sdk = Sdk.getCurrent();
- if (sdk != null) {
- for (IAndroidTarget target : sdk.getTargets()) {
- if (target.isPlatform()) {
- AndroidVersion version = target.getVersion();
- if (!version.isPreview()) {
- max = Math.max(max, version.getApiLevel());
- }
- }
- }
- }
-
- String[] versions = new String[max];
- for (int api = 1; api <= max; api++) {
- versions[api-1] = getAndroidName(api);
- }
-
- return versions;
- }
-
- /**
- * Returns the Android project(s) that are selected or active, if any. This
- * considers the selection, the active editor, etc.
- *
- * @param selection the current selection
- * @return a list of projects, possibly empty (but never null)
- */
- @NonNull
- public static List<IProject> getSelectedProjects(@Nullable ISelection selection) {
- List<IProject> projects = new ArrayList<IProject>();
-
- if (selection instanceof IStructuredSelection) {
- IStructuredSelection structuredSelection = (IStructuredSelection) selection;
- // get the unique selected item.
- Iterator<?> iterator = structuredSelection.iterator();
- while (iterator.hasNext()) {
- Object element = iterator.next();
-
- // First look up the resource (since some adaptables
- // provide an IResource but not an IProject, and we can
- // always go from IResource to IProject)
- IResource resource = null;
- if (element instanceof IResource) { // may include IProject
- resource = (IResource) element;
- } else if (element instanceof IAdaptable) {
- IAdaptable adaptable = (IAdaptable)element;
- Object adapter = adaptable.getAdapter(IResource.class);
- resource = (IResource) adapter;
- }
-
- // get the project object from it.
- IProject project = null;
- if (resource != null) {
- project = resource.getProject();
- } else if (element instanceof IAdaptable) {
- project = (IProject) ((IAdaptable) element).getAdapter(IProject.class);
- }
-
- if (project != null && !projects.contains(project)) {
- projects.add(project);
- }
- }
- }
-
- if (projects.isEmpty()) {
- // Try to look at the active editor instead
- IFile file = AdtUtils.getActiveFile();
- if (file != null) {
- projects.add(file.getProject());
- }
- }
-
- if (projects.isEmpty()) {
- // If we didn't find a default project based on the selection, check how many
- // open Android projects we can find in the current workspace. If there's only
- // one, we'll just select it by default.
- IJavaProject[] open = AdtUtils.getOpenAndroidProjects();
- for (IJavaProject project : open) {
- projects.add(project.getProject());
- }
- return projects;
- } else {
- // Make sure all the projects are Android projects
- List<IProject> androidProjects = new ArrayList<IProject>(projects.size());
- for (IProject project : projects) {
- if (BaseProjectHelper.isAndroidProject(project)) {
- androidProjects.add(project);
- }
- }
- return androidProjects;
- }
- }
-
- private static Boolean sEclipse4;
-
- /**
- * Returns true if the running Eclipse is version 4.x or later
- *
- * @return true if the current Eclipse version is 4.x or later, false
- * otherwise
- */
- public static boolean isEclipse4() {
- if (sEclipse4 == null) {
- sEclipse4 = Platform.getBundle("org.eclipse.e4.ui.model.workbench") != null; //$NON-NLS-1$
- }
-
- return sEclipse4;
- }
-
- /**
- * Reads the contents of an {@link IFile} and return it as a byte array
- *
- * @param file the file to be read
- * @return the String read from the file, or null if there was an error
- */
- @SuppressWarnings("resource") // Eclipse doesn't understand Closeables.closeQuietly yet
- @Nullable
- public static byte[] readData(@NonNull IFile file) {
- InputStream contents = null;
- try {
- contents = file.getContents();
- return ByteStreams.toByteArray(contents);
- } catch (Exception e) {
- // Pass -- just return null
- } finally {
- Closeables.closeQuietly(contents);
- }
-
- return null;
- }
-
- /**
- * Ensure that a given folder (and all its parents) are created. This implements
- * the equivalent of {@link File#mkdirs()} for {@link IContainer} folders.
- *
- * @param container the container to ensure exists
- * @throws CoreException if an error occurs
- */
- public static void ensureExists(@Nullable IContainer container) throws CoreException {
- if (container == null || container.exists()) {
- return;
- }
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- IFolder folder = root.getFolder(container.getFullPath());
- ensureExists(folder);
- }
-
- private static void ensureExists(IFolder folder) throws CoreException {
- if (folder != null && !folder.exists()) {
- IContainer parent = folder.getParent();
- if (parent instanceof IFolder) {
- ensureExists((IFolder) parent);
- }
- folder.create(false, false, null);
- }
- }
-
- /**
- * Format the given floating value into an XML string, omitting decimals if
- * 0
- *
- * @param value the value to be formatted
- * @return the corresponding XML string for the value
- */
- public static String formatFloatAttribute(float value) {
- if (value != (int) value) {
- // Run String.format without a locale, because we don't want locale-specific
- // conversions here like separating the decimal part with a comma instead of a dot!
- return String.format((Locale) null, "%.2f", value); //$NON-NLS-1$
- } else {
- return Integer.toString((int) value);
- }
- }
-
- /**
- * Creates all the directories required for the given path.
- *
- * @param wsPath the path to create all the parent directories for
- * @return true if all the parent directories were created
- */
- public static boolean createWsParentDirectory(IContainer wsPath) {
- if (wsPath.getType() == IResource.FOLDER) {
- if (wsPath.exists()) {
- return true;
- }
-
- IFolder folder = (IFolder) wsPath;
- try {
- if (createWsParentDirectory(wsPath.getParent())) {
- folder.create(true /* force */, true /* local */, null /* monitor */);
- return true;
- }
- } catch (CoreException e) {
- e.printStackTrace();
- }
- }
-
- return false;
- }
-
- /**
- * Lists the files of the given directory and returns them as an array which
- * is never null. This simplifies processing file listings from for each
- * loops since {@link File#listFiles} can return null. This method simply
- * wraps it and makes sure it returns an empty array instead if necessary.
- *
- * @param dir the directory to list
- * @return the children, or empty if it has no children, is not a directory,
- * etc.
- */
- @NonNull
- public static File[] listFiles(File dir) {
- File[] files = dir.listFiles();
- if (files != null) {
- return files;
- } else {
- return new File[0];
- }
- }
-
- /**
- * Closes all open editors that are showing a file for the given project. This method
- * should be called when a project is closed or deleted.
- * <p>
- * This method can be called from any thread, but if it is not called on the GUI thread
- * the editor will be closed asynchronously.
- *
- * @param project the project to close all editors for
- * @param save whether unsaved editors should be saved first
- */
- public static void closeEditors(@NonNull final IProject project, final boolean save) {
- final Display display = AdtPlugin.getDisplay();
- if (display == null || display.isDisposed()) {
- return;
- }
- if (display.getThread() != Thread.currentThread()) {
- display.asyncExec(new Runnable() {
- @Override
- public void run() {
- closeEditors(project, save);
- }
- });
- return;
- }
-
- // Close editors for removed files
- IWorkbench workbench = PlatformUI.getWorkbench();
- for (IWorkbenchWindow window : workbench.getWorkbenchWindows()) {
- for (IWorkbenchPage page : window.getPages()) {
- List<IEditorReference> matching = null;
- for (IEditorReference ref : page.getEditorReferences()) {
- boolean close = false;
- try {
- IEditorInput input = ref.getEditorInput();
- if (input instanceof IFileEditorInput) {
- IFileEditorInput fileInput = (IFileEditorInput) input;
- if (project.equals(fileInput.getFile().getProject())) {
- close = true;
- }
- }
- } catch (PartInitException ex) {
- close = true;
- }
- if (close) {
- if (matching == null) {
- matching = new ArrayList<IEditorReference>(2);
- }
- matching.add(ref);
- }
- }
- if (matching != null) {
- IEditorReference[] refs = new IEditorReference[matching.size()];
- page.closeEditors(matching.toArray(refs), save);
- }
- }
- }
- }
-
- /**
- * Closes all open editors for the given file. Note that a file can be open in
- * more than one editor, for example by using Open With on the file to choose different
- * editors.
- * <p>
- * This method can be called from any thread, but if it is not called on the GUI thread
- * the editor will be closed asynchronously.
- *
- * @param file the file whose editors should be closed.
- * @param save whether unsaved editors should be saved first
- */
- public static void closeEditors(@NonNull final IFile file, final boolean save) {
- final Display display = AdtPlugin.getDisplay();
- if (display == null || display.isDisposed()) {
- return;
- }
- if (display.getThread() != Thread.currentThread()) {
- display.asyncExec(new Runnable() {
- @Override
- public void run() {
- closeEditors(file, save);
- }
- });
- return;
- }
-
- // Close editors for removed files
- IWorkbench workbench = PlatformUI.getWorkbench();
- for (IWorkbenchWindow window : workbench.getWorkbenchWindows()) {
- for (IWorkbenchPage page : window.getPages()) {
- List<IEditorReference> matching = null;
- for (IEditorReference ref : page.getEditorReferences()) {
- boolean close = false;
- try {
- IEditorInput input = ref.getEditorInput();
- if (input instanceof IFileEditorInput) {
- IFileEditorInput fileInput = (IFileEditorInput) input;
- if (file.equals(fileInput.getFile())) {
- close = true;
- }
- }
- } catch (PartInitException ex) {
- close = true;
- }
- if (close) {
- // Found
- if (matching == null) {
- matching = new ArrayList<IEditorReference>(2);
- }
- matching.add(ref);
- // We don't break here in case the file is
- // opened multiple times with different editors.
- }
- }
- if (matching != null) {
- IEditorReference[] refs = new IEditorReference[matching.size()];
- page.closeEditors(matching.toArray(refs), save);
- }
- }
- }
- }
-
- /**
- * Returns the offset region of the given 0-based line number in the given
- * file
- *
- * @param file the file to look up the line number in
- * @param line the line number (0-based, meaning that the first line is line
- * 0)
- * @return the corresponding offset range, or null
- */
- @Nullable
- public static IRegion getRegionOfLine(@NonNull IFile file, int line) {
- IDocumentProvider provider = new TextFileDocumentProvider();
- try {
- provider.connect(file);
- IDocument document = provider.getDocument(file);
- if (document != null) {
- return document.getLineInformation(line);
- }
- } catch (Exception e) {
- AdtPlugin.log(e, "Can't find range information for %1$s", file.getName());
- } finally {
- provider.disconnect(file);
- }
-
- return null;
- }
-
- /**
- * Returns all resource variations for the given file
- *
- * @param file resource file, which should be an XML file in one of the
- * various resource folders, e.g. res/layout, res/values-xlarge, etc.
- * @param includeSelf if true, include the file itself in the list,
- * otherwise exclude it
- * @return a list of all the resource variations
- */
- public static List<IFile> getResourceVariations(@Nullable IFile file, boolean includeSelf) {
- if (file == null) {
- return Collections.emptyList();
- }
-
- // Compute the set of layout files defining this layout resource
- List<IFile> variations = new ArrayList<IFile>();
- String name = file.getName();
- IContainer parent = file.getParent();
- if (parent != null) {
- IContainer resFolder = parent.getParent();
- if (resFolder != null) {
- String parentName = parent.getName();
- String prefix = parentName;
- int qualifiers = prefix.indexOf('-');
-
- if (qualifiers != -1) {
- parentName = prefix.substring(0, qualifiers);
- prefix = prefix.substring(0, qualifiers + 1);
- } else {
- prefix = prefix + '-';
- }
- try {
- for (IResource resource : resFolder.members()) {
- String n = resource.getName();
- if ((n.startsWith(prefix) || n.equals(parentName))
- && resource instanceof IContainer) {
- IContainer layoutFolder = (IContainer) resource;
- IResource r = layoutFolder.findMember(name);
- if (r instanceof IFile) {
- IFile variation = (IFile) r;
- if (!includeSelf && file.equals(variation)) {
- continue;
- }
- variations.add(variation);
- }
- }
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- }
- }
-
- return variations;
- }
-
- /**
- * Returns whether the current thread is the UI thread
- *
- * @return true if the current thread is the UI thread
- */
- public static boolean isUiThread() {
- return AdtPlugin.getDisplay() != null
- && AdtPlugin.getDisplay().getThread() == Thread.currentThread();
- }
-
- /**
- * Replaces any {@code \\uNNNN} references in the given string with the corresponding
- * unicode characters.
- *
- * @param s the string to perform replacements in
- * @return the string with unicode escapes replaced with actual characters
- */
- @NonNull
- public static String replaceUnicodeEscapes(@NonNull String s) {
- // Handle unicode escapes
- if (s.indexOf("\\u") != -1) { //$NON-NLS-1$
- StringBuilder sb = new StringBuilder(s.length());
- for (int i = 0, n = s.length(); i < n; i++) {
- char c = s.charAt(i);
- if (c == '\\' && i < n - 1) {
- char next = s.charAt(i + 1);
- if (next == 'u' && i < n - 5) { // case sensitive
- String hex = s.substring(i + 2, i + 6);
- try {
- int unicodeValue = Integer.parseInt(hex, 16);
- sb.append((char) unicodeValue);
- i += 5;
- continue;
- } catch (NumberFormatException nufe) {
- // Invalid escape: Just proceed to literally transcribe it
- sb.append(c);
- }
- } else {
- sb.append(c);
- sb.append(next);
- i++;
- continue;
- }
- } else {
- sb.append(c);
- }
- }
- s = sb.toString();
- }
-
- return s;
- }
-
- /**
- * Looks up the {@link ResourceFolderType} corresponding to a given
- * {@link ResourceType}: the folder where those resources can be found.
- * <p>
- * Note that {@link ResourceType#ID} is a special case: it can not just
- * be defined in {@link ResourceFolderType#VALUES}, but it can also be
- * defined inline via {@code @+id} in {@link ResourceFolderType#LAYOUT} and
- * {@link ResourceFolderType#MENU} folders.
- *
- * @param type the resource type
- * @return the corresponding resource folder type
- */
- @NonNull
- public static ResourceFolderType getFolderTypeFor(@NonNull ResourceType type) {
- switch (type) {
- case ANIM:
- return ResourceFolderType.ANIM;
- case ANIMATOR:
- return ResourceFolderType.ANIMATOR;
- case ARRAY:
- return ResourceFolderType.VALUES;
- case COLOR:
- return ResourceFolderType.COLOR;
- case DRAWABLE:
- return ResourceFolderType.DRAWABLE;
- case INTERPOLATOR:
- return ResourceFolderType.INTERPOLATOR;
- case LAYOUT:
- return ResourceFolderType.LAYOUT;
- case MENU:
- return ResourceFolderType.MENU;
- case MIPMAP:
- return ResourceFolderType.MIPMAP;
- case RAW:
- return ResourceFolderType.RAW;
- case XML:
- return ResourceFolderType.XML;
- case ATTR:
- case BOOL:
- case DECLARE_STYLEABLE:
- case DIMEN:
- case FRACTION:
- case ID:
- case INTEGER:
- case PLURALS:
- case PUBLIC:
- case STRING:
- case STYLE:
- case STYLEABLE:
- return ResourceFolderType.VALUES;
- default:
- assert false : type;
- return ResourceFolderType.VALUES;
-
- }
- }
-
- /**
- * Looks up the {@link ResourceType} defined in a given {@link ResourceFolderType}.
- * <p>
- * Note that for {@link ResourceFolderType#VALUES} there are many, many
- * different types of resources that can be defined, so this method returns
- * {@code null} for that scenario.
- * <p>
- * Note also that {@link ResourceType#ID} is a special case: it can not just
- * be defined in {@link ResourceFolderType#VALUES}, but it can also be
- * defined inline via {@code @+id} in {@link ResourceFolderType#LAYOUT} and
- * {@link ResourceFolderType#MENU} folders.
- *
- * @param folderType the resource folder type
- * @return the corresponding resource type, or null if {@code folderType} is
- * {@link ResourceFolderType#VALUES}
- */
- @Nullable
- public static ResourceType getResourceTypeFor(@NonNull ResourceFolderType folderType) {
- switch (folderType) {
- case ANIM:
- return ResourceType.ANIM;
- case ANIMATOR:
- return ResourceType.ANIMATOR;
- case COLOR:
- return ResourceType.COLOR;
- case DRAWABLE:
- return ResourceType.DRAWABLE;
- case INTERPOLATOR:
- return ResourceType.INTERPOLATOR;
- case LAYOUT:
- return ResourceType.LAYOUT;
- case MENU:
- return ResourceType.MENU;
- case MIPMAP:
- return ResourceType.MIPMAP;
- case RAW:
- return ResourceType.RAW;
- case XML:
- return ResourceType.XML;
- case VALUES:
- return null;
- default:
- assert false : folderType;
- return null;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/AndroidPrintStream.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/AndroidPrintStream.java
deleted file mode 100644
index 9eac361f4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/AndroidPrintStream.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt;
-
-import org.eclipse.core.resources.IProject;
-
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.util.Calendar;
-
-/**
- * Custom PrintStream allowing to precede the message with a tag containing data/project info.
- *
- * Additionally, a prefix can be set (and removed) at runtime.
- *
- * Only {@link #println()} is supported.
- */
-public class AndroidPrintStream extends PrintStream {
- private IProject mProject;
- private String mPrefix;
-
- /**
- * Default constructor with project and output stream.
- * The project is used to get the project name for the output tag.
- *
- * @param project The Project
- * @param prefix A prefix to be printed before the actual message. Can be null
- * @param stream The Stream
- */
- public AndroidPrintStream(IProject project, String prefix, OutputStream stream) {
- super(stream);
- mProject = project;
- }
-
- /**
- * Updates the value of the prefix.
- * @param prefix
- */
- public void setPrefix(String prefix) {
- mPrefix = prefix;
- }
-
- @Override
- public void println(String message) {
- // write the date/project tag first.
- String tag = getMessageTag(mProject != null ? mProject.getName() : null);
-
- print(tag);
- print(" "); //$NON-NLS-1$
- if (mPrefix != null) {
- print(mPrefix);
- print(" "); //$NON-NLS-1$
- }
-
- // then write the regular message
- super.println(message);
- }
-
- /**
- * Creates a string containing the current date/time, and the tag.
- * The tag does not end with a whitespace.
- * @param tag The tag associated to the message. Can be null
- * @return The dateTag
- */
- public static String getMessageTag(String tag) {
- Calendar c = Calendar.getInstance();
-
- if (tag == null) {
- return String.format(Messages.Console_Date_Tag, c);
- }
-
- return String.format(Messages.Console_Data_Project_Tag, c, tag);
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/DebuggerConnector.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/DebuggerConnector.java
deleted file mode 100644
index 233ab2ed9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/DebuggerConnector.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt;
-
-import com.android.ide.eclipse.adt.internal.launch.AndroidLaunchController;
-import com.android.ide.eclipse.adt.internal.project.ProjectHelper;
-import com.android.ide.eclipse.adt.internal.resources.manager.GlobalProjectMonitor;
-import com.android.ide.eclipse.adt.internal.resources.manager.GlobalProjectMonitor.IProjectListener;
-import com.android.ide.eclipse.ddms.IDebuggerConnector;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IPath;
-
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
-/**
- * Implementation of the com.android.ide.ddms.debuggerConnector extension point.
- */
-public class DebuggerConnector implements IDebuggerConnector {
- private WorkspaceAppCache mWorkspaceAppCache;
-
- public DebuggerConnector() {
- mWorkspaceAppCache = new WorkspaceAppCache();
- GlobalProjectMonitor.getMonitor().addProjectListener(mWorkspaceAppCache);
- }
-
- @Override
- public boolean connectDebugger(String appName, int appPort, int selectedPort) {
- // search for an android project matching the process name
- IProject project = ProjectHelper.findAndroidProjectByAppName(appName);
- if (project != null) {
- AndroidLaunchController.debugRunningApp(project, appPort);
- return true;
- }
-
- return false;
- }
-
- /** {@inheritDoc} */
- @Override
- public boolean isWorkspaceApp(String appName) {
- return mWorkspaceAppCache.isWorkspaceApp(appName);
- }
-
- /**
- * A cache of Android application name to workspace project name mappings.
- * Users can query whether an application is present in the workspace using
- * {@link #isWorkspaceApp(String)}. The cache listens to workspace changes
- * (project open/close/delete etc), and keeps its internal mappings up-to-date.<br>
- * This class is designed with the following assumptions:
- * <ul>
- * <li> There are a significant number of calls to {@link #isWorkspaceApp(String)}, with
- * a large number of possible application names as arguments. </li>
- * <li> The number of projects actually present in the workspace, and the
- * number of user initiated project changes (project open/close/delete/rename) are both
- * relatively small. </li>
- * </ul>
- */
- static class WorkspaceAppCache implements IProjectListener {
- /** Apps known to be not in the workspace. */
- private Set<String> mAppsNotInWorkspace;
-
- /** Mapping of application name to project name for apps present in the workspace. */
- private Map<String, String> mAppsInWorkspace;
-
- public WorkspaceAppCache() {
- mAppsNotInWorkspace = new HashSet<String>();
- mAppsInWorkspace = new HashMap<String, String>();
- }
-
- public boolean isWorkspaceApp(String appName) {
- if (mAppsNotInWorkspace.contains(appName)) {
- return false;
- }
-
- String projectName = mAppsInWorkspace.get(appName);
- if (projectName == null) {
- IProject p = ProjectHelper.findAndroidProjectByAppName(appName);
- if (p == null) {
- mAppsNotInWorkspace.add(appName);
- } else {
- projectName = p.getName();
- mAppsInWorkspace.put(appName, projectName);
- }
- }
- return projectName != null;
- }
-
- /** {@inheritDoc} */
- @Override
- public void projectRenamed(IProject project, IPath from) {
- // when a project is renamed, ideally we should just update the current
- // known mapping of app name -> project name. However, the projectRenamed
- // callback is called only after projectDeleted() and projectOpened() are called,
- // so there is really nothing we can do here..
- }
-
- /** {@inheritDoc} */
- @Override
- public void projectOpenedWithWorkspace(IProject project) {
- // don't do anything as the cache is lazily initialized
- }
-
- @Override
- public void allProjectsOpenedWithWorkspace() {
- // don't do anything as the cache is lazily initialized
- }
-
- /** {@inheritDoc} */
- @Override
- public void projectOpened(IProject project) {
- // A newly opened project could contribute some Android application.
- // So we invalidate the set of apps that are known to be not in the workspace, as
- // that set could be out of date now.
- mAppsNotInWorkspace.clear();
- }
-
- /** {@inheritDoc} */
- @Override
- public void projectDeleted(IProject project) {
- // Deletion is effectively the same as closing
- projectClosed(project);
- }
-
- /** {@inheritDoc} */
- @Override
- public void projectClosed(IProject project) {
- // When a project is closed, remove all mappings contributed by the project.
- Map<String, String> updatedCache = new HashMap<String, String>();
-
- String name = project.getName();
- for (Entry<String, String> e : mAppsInWorkspace.entrySet()) {
- if (!e.getValue().equals(name)) {
- updatedCache.put(e.getKey(), e.getValue());
- }
- }
-
- mAppsInWorkspace = updatedCache;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/Messages.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/Messages.java
deleted file mode 100644
index 413c792c9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/Messages.java
+++ /dev/null
@@ -1,44 +0,0 @@
-
-package com.android.ide.eclipse.adt;
-
-import org.eclipse.osgi.util.NLS;
-
-public class Messages extends NLS {
- private static final String BUNDLE_NAME = "com.android.ide.eclipse.adt.messages"; //$NON-NLS-1$
-
- public static String AdtPlugin_Android_SDK_Content_Loader;
-
- public static String AdtPlugin_Android_SDK_Resource_Parser;
-
- public static String AdtPlugin_Failed_To_Parse_s;
-
- public static String AdtPlugin_Failed_To_Start_s;
-
- public static String Console_Data_Project_Tag;
-
- public static String Console_Date_Tag;
-
- public static String Could_Not_Find;
-
- public static String Could_Not_Find_Folder;
-
- public static String Could_Not_Find_Folder_In_SDK;
-
- public static String VersionCheck_Plugin_Too_Old;
-
- public static String VersionCheck_Plugin_Version_Failed;
-
- public static String VersionCheck_Build_Tool_Missing;
-
- public static String VersionCheck_Tools_Too_Old;
-
- public static String VersionCheck_Unable_To_Parse_Version_s;
-
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
-
- private Messages() {
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/SourceRevealer.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/SourceRevealer.java
deleted file mode 100644
index b1b5390ee..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/SourceRevealer.java
+++ /dev/null
@@ -1,465 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt;
-
-import static com.android.SdkConstants.CLASS_CONSTRUCTOR;
-import static com.android.SdkConstants.CONSTRUCTOR_NAME;
-
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.project.ProjectHelper;
-import com.android.ide.eclipse.ddms.ISourceRevealer;
-import com.google.common.base.Predicate;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jdt.core.ICompilationUnit;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IMethod;
-import org.eclipse.jdt.core.ISourceRange;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.core.search.IJavaSearchConstants;
-import org.eclipse.jdt.core.search.SearchEngine;
-import org.eclipse.jdt.core.search.SearchMatch;
-import org.eclipse.jdt.core.search.SearchParticipant;
-import org.eclipse.jdt.core.search.SearchPattern;
-import org.eclipse.jdt.core.search.SearchRequestor;
-import org.eclipse.jdt.ui.JavaUI;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.window.Window;
-import org.eclipse.ui.IPerspectiveRegistry;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.WorkbenchException;
-import org.eclipse.ui.dialogs.ListDialog;
-import org.eclipse.ui.ide.IDE;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Implementation of the com.android.ide.ddms.sourceRevealer extension point.
- * Note that this code is duplicated in the PDT plugin's SourceRevealer as well.
- */
-public class SourceRevealer implements ISourceRevealer {
- @Override
- public boolean reveal(String applicationName, String className, int line) {
- IProject project = ProjectHelper.findAndroidProjectByAppName(applicationName);
- if (project != null) {
- return BaseProjectHelper.revealSource(project, className, line);
- }
-
- return false;
- }
-
- /**
- * Reveal the source for given fully qualified method name.<br>
- *
- * The method should take care of the following scenarios:<ol>
- * <li> A search, either by filename/line number, or for fqmn might provide only 1 result.
- * In such a case, just open that result. Give preference to the file name/line # search
- * since that is the most accurate (gets to the line number). </li>
- * <li> The search might not provide any results. e.g, the method name may be of the form
- * "com.x.y$1.methodName". Searches for methods within anonymous classes will fail. In
- * such a case, if the fileName:lineNumber argument is available, a search for that
- * should be made instead. </li>
- * <li> The search might provide multiple results. In such a case, the fileName/lineNumber
- * values should be utilized to narrow down the results.</li>
- * </ol>
- *
- * @param fqmn fully qualified method name
- * @param fileName file name in which the method is present, null if not known
- * @param lineNumber line number in the file which should be given focus, -1 if not known.
- * Line numbers begin at 1, not 0.
- * @param perspective perspective to switch to before the source is revealed, null to not
- * switch perspectives
- */
- @Override
- public boolean revealMethod(String fqmn, String fileName, int lineNumber, String perspective) {
- // Search by filename:linenumber. If there is just one result for it, that would
- // be the correct match that is accurate to the line
- List<SearchMatch> fileMatches = Collections.emptyList();
- if (fileName != null && lineNumber >= 0) {
- fileMatches = searchForFile(fileName);
- if (fileMatches.size() == 1) {
- return revealLineMatch(fileMatches, fileName, lineNumber, perspective);
- }
- }
-
- List<SearchMatch> methodMatches = searchForMethod(fqmn);
-
- // if there is a unique method name match:
- // 1. if there are > 1 file name matches, try to see if they can be narrowed down
- // 2. if not, display the method match
- if (methodMatches.size() == 1) {
- if (fileMatches.size() > 0) {
- List<SearchMatch> filteredMatches = filterMatchByResource(fileMatches,
- methodMatches.get(0).getResource());
- if (filteredMatches.size() == 1) {
- return revealLineMatch(filteredMatches, fileName, lineNumber, perspective);
- }
- } else if (fileName != null && lineNumber > 0) {
- // Couldn't find file match, but we have a filename and line number: attempt
- // to use this to pinpoint the location within the method
- IMethod method = (IMethod) methodMatches.get(0).getElement();
- IJavaElement element = method;
- while (element != null) {
- if (element instanceof ICompilationUnit) {
- ICompilationUnit unit = ((ICompilationUnit) element).getPrimary();
- IResource resource = unit.getResource();
- if (resource instanceof IFile) {
- IFile file = (IFile) resource;
-
- try {
- // See if the line number looks like it's inside the given method
- ISourceRange sourceRange = method.getSourceRange();
- IRegion region = AdtUtils.getRegionOfLine(file, lineNumber - 1);
- // When fields are initialized with code, this logically belongs
- // to the constructor, but the line numbers are outside of the
- // constructor. In this case we'll trust the line number rather
- // than the method range.
- boolean isConstructor = fqmn.endsWith(CONSTRUCTOR_NAME);
- if (isConstructor
- || region != null
- && region.getOffset() >= sourceRange.getOffset()
- && region.getOffset() < sourceRange.getOffset()
- + sourceRange.getLength()) {
- // Yes: use the line number instead
- if (perspective != null) {
- SourceRevealer.switchToPerspective(perspective);
- }
- return displayFile(file, lineNumber);
- }
-
- } catch (JavaModelException e) {
- AdtPlugin.log(e, null);
- }
- }
- }
- element = element.getParent();
- }
-
- }
-
- return displayMethod((IMethod) methodMatches.get(0).getElement(), perspective);
- }
-
- // no matches for search by method, so search by filename
- if (methodMatches.size() == 0) {
- if (fileMatches.size() > 0) {
- return revealLineMatch(fileMatches, fileName, lineNumber, perspective);
- } else {
- // Last ditch effort: attempt to look up the class corresponding to the fqn
- // and jump to the line there
- if (fileMatches.isEmpty() && fqmn.indexOf('.') != -1) {
- String className = fqmn.substring(0, fqmn.lastIndexOf('.'));
- for (IJavaProject project : BaseProjectHelper.getAndroidProjects(null)) {
- IType type;
- try {
- type = project.findType(className);
- if (type != null && type.exists()) {
- IResource resource = type.getResource();
- if (resource instanceof IFile) {
- if (perspective != null) {
- SourceRevealer.switchToPerspective(perspective);
- }
- return displayFile((IFile) resource, lineNumber);
- }
- }
- } catch (JavaModelException e) {
- AdtPlugin.log(e, null);
- }
- }
- }
-
- return false;
- }
- }
-
- // multiple matches for search by method, narrow down by filename
- if (fileName != null) {
- return revealLineMatch(
- filterMatchByFileName(methodMatches, fileName),
- fileName, lineNumber, perspective);
- }
-
- // prompt the user
- SearchMatch match = getMatchToDisplay(methodMatches, fqmn);
- if (match == null) {
- return false;
- } else {
- return displayMethod((IMethod) match.getElement(), perspective);
- }
- }
-
- private boolean revealLineMatch(List<SearchMatch> matches, String fileName, int lineNumber,
- String perspective) {
- SearchMatch match = getMatchToDisplay(matches,
- String.format("%s:%d", fileName, lineNumber));
- if (match == null) {
- return false;
- }
-
- if (perspective != null) {
- SourceRevealer.switchToPerspective(perspective);
- }
-
- return displayFile((IFile) match.getResource(), lineNumber);
- }
-
- private boolean displayFile(IFile file, int lineNumber) {
- try {
- IMarker marker = file.createMarker(IMarker.TEXT);
- marker.setAttribute(IMarker.LINE_NUMBER, lineNumber);
- IDE.openEditor(
- PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(),
- marker);
- marker.delete();
- return true;
- } catch (CoreException e) {
- AdtPlugin.printErrorToConsole(e.getMessage());
- return false;
- }
- }
-
- private boolean displayMethod(IMethod method, String perspective) {
- if (perspective != null) {
- SourceRevealer.switchToPerspective(perspective);
- }
-
- try {
- JavaUI.openInEditor(method);
- return true;
- } catch (Exception e) {
- AdtPlugin.printErrorToConsole(e.getMessage());
- return false;
- }
- }
-
- private List<SearchMatch> filterMatchByFileName(List<SearchMatch> matches, String fileName) {
- if (fileName == null) {
- return matches;
- }
-
- // Use a map to collapse multiple matches in a single file into just one match since
- // we know the line number in the file.
- Map<IResource, SearchMatch> matchesPerFile =
- new HashMap<IResource, SearchMatch>(matches.size());
-
- for (SearchMatch m: matches) {
- if (m.getResource() instanceof IFile
- && m.getResource().getName().startsWith(fileName)) {
- matchesPerFile.put(m.getResource(), m);
- }
- }
-
- List<SearchMatch> filteredMatches = new ArrayList<SearchMatch>(matchesPerFile.values());
-
- // sort results, first by project name, then by file name
- Collections.sort(filteredMatches, new Comparator<SearchMatch>() {
- @Override
- public int compare(SearchMatch m1, SearchMatch m2) {
- String p1 = m1.getResource().getProject().getName();
- String p2 = m2.getResource().getProject().getName();
-
- if (!p1.equals(p2)) {
- return p1.compareTo(p2);
- }
-
- String r1 = m1.getResource().getName();
- String r2 = m2.getResource().getName();
- return r1.compareTo(r2);
- }
- });
- return filteredMatches;
- }
-
- private List<SearchMatch> filterMatchByResource(List<SearchMatch> matches,
- IResource resource) {
- List<SearchMatch> filteredMatches = new ArrayList<SearchMatch>(matches.size());
-
- for (SearchMatch m: matches) {
- if (m.getResource().equals(resource)) {
- filteredMatches.add(m);
- }
- }
-
- return filteredMatches;
- }
-
- private SearchMatch getMatchToDisplay(List<SearchMatch> matches, String searchTerm) {
- // no matches for given search
- if (matches.size() == 0) {
- return null;
- }
-
- // there is only 1 match, so we return that
- if (matches.size() == 1) {
- return matches.get(0);
- }
-
- // multiple matches, prompt the user to select
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- if (window == null) {
- return null;
- }
-
- ListDialog dlg = new ListDialog(window.getShell());
- dlg.setMessage("Multiple files match search: " + searchTerm);
- dlg.setTitle("Select file to open");
- dlg.setInput(matches);
- dlg.setContentProvider(new IStructuredContentProvider() {
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- @Override
- public void dispose() {
- }
-
- @Override
- public Object[] getElements(Object inputElement) {
- return ((List<?>) inputElement).toArray();
- }
- });
- dlg.setLabelProvider(new LabelProvider() {
- @Override
- public String getText(Object element) {
- SearchMatch m = (SearchMatch) element;
- return String.format("/%s/%s", //$NON-NLS-1$
- m.getResource().getProject().getName(),
- m.getResource().getProjectRelativePath().toString());
- }
- });
- dlg.setInitialSelections(new Object[] { matches.get(0) });
- dlg.setHelpAvailable(false);
-
- if (dlg.open() == Window.OK) {
- Object[] selectedMatches = dlg.getResult();
- if (selectedMatches.length > 0) {
- return (SearchMatch) selectedMatches[0];
- }
- }
-
- return null;
- }
-
- private List<SearchMatch> searchForFile(String fileName) {
- return searchForPattern(fileName, IJavaSearchConstants.CLASS, MATCH_IS_FILE_PREDICATE);
- }
-
- private List<SearchMatch> searchForMethod(String fqmn) {
- if (fqmn.endsWith(CONSTRUCTOR_NAME)) {
- fqmn = fqmn.substring(0, fqmn.length() - CONSTRUCTOR_NAME.length() - 1); // -1: dot
- return searchForPattern(fqmn, IJavaSearchConstants.CONSTRUCTOR,
- MATCH_IS_METHOD_PREDICATE);
- }
- if (fqmn.endsWith(CLASS_CONSTRUCTOR)) {
- // Don't try to search for class init methods: Eclipse will throw NPEs if you do
- return Collections.emptyList();
- }
-
- return searchForPattern(fqmn, IJavaSearchConstants.METHOD, MATCH_IS_METHOD_PREDICATE);
- }
-
- private List<SearchMatch> searchForPattern(String pattern, int searchFor,
- Predicate<SearchMatch> filterPredicate) {
- SearchEngine se = new SearchEngine();
- SearchPattern searchPattern = SearchPattern.createPattern(
- pattern,
- searchFor,
- IJavaSearchConstants.DECLARATIONS,
- SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);
- SearchResultAccumulator requestor = new SearchResultAccumulator(filterPredicate);
- try {
- se.search(searchPattern,
- new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
- SearchEngine.createWorkspaceScope(),
- requestor,
- new NullProgressMonitor());
- } catch (CoreException e) {
- AdtPlugin.printErrorToConsole(e.getMessage());
- return Collections.emptyList();
- }
-
- return requestor.getMatches();
- }
-
- private static final Predicate<SearchMatch> MATCH_IS_FILE_PREDICATE =
- new Predicate<SearchMatch>() {
- @Override
- public boolean apply(SearchMatch match) {
- return match.getResource() instanceof IFile;
- }
- };
-
- private static final Predicate<SearchMatch> MATCH_IS_METHOD_PREDICATE =
- new Predicate<SearchMatch>() {
- @Override
- public boolean apply(SearchMatch match) {
- return match.getResource() instanceof IFile;
- }
- };
-
- private static class SearchResultAccumulator extends SearchRequestor {
- private final List<SearchMatch> mSearchMatches = new ArrayList<SearchMatch>();
- private final Predicate<SearchMatch> mPredicate;
-
- public SearchResultAccumulator(Predicate<SearchMatch> filterPredicate) {
- mPredicate = filterPredicate;
- }
-
- public List<SearchMatch> getMatches() {
- return mSearchMatches;
- }
-
- @Override
- public void acceptSearchMatch(SearchMatch match) throws CoreException {
- if (mPredicate.apply(match)) {
- mSearchMatches.add(match);
- }
- }
- }
-
- private static void switchToPerspective(String perspectiveId) {
- IWorkbench workbench = PlatformUI.getWorkbench();
- IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
- IPerspectiveRegistry perspectiveRegistry = workbench.getPerspectiveRegistry();
- if (perspectiveId != null
- && perspectiveId.length() > 0
- && perspectiveRegistry.findPerspectiveWithId(perspectiveId) != null) {
- try {
- workbench.showPerspective(perspectiveId, window);
- } catch (WorkbenchException e) {
- AdtPlugin.printErrorToConsole(e.getMessage());
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/ToolsLocator.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/ToolsLocator.java
deleted file mode 100644
index ee9eea76e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/ToolsLocator.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt;
-
-import com.android.ide.eclipse.ddms.IToolsLocator;
-
-/**
- * Implementation of the com.android.ide.ddms.toolsLocator extension point.
- *
- */
-public class ToolsLocator implements IToolsLocator {
-
- @Override
- public String getAdbLocation() {
- return AdtPlugin.getOsAbsoluteAdb();
- }
-
- @Override
- public String getHprofConvLocation() {
- return AdtPlugin.getOsAbsoluteHprofConv();
- }
-
- @Override
- public String getTraceViewLocation() {
- return AdtPlugin.getOsAbsoluteTraceview();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/VersionCheck.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/VersionCheck.java
deleted file mode 100644
index 576e9c343..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/VersionCheck.java
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtPlugin.CheckSdkErrorHandler;
-import com.android.ide.eclipse.adt.AdtPlugin.CheckSdkErrorHandler.Solution;
-import com.android.ide.eclipse.adt.Messages;
-import com.android.sdklib.repository.FullRevision;
-import com.android.sdklib.repository.FullRevision.PreviewComparison;
-import com.android.sdklib.repository.PkgProps;
-
-import org.osgi.framework.Constants;
-import org.osgi.framework.Version;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * Class handling the version check for the plugin vs. the SDK.<br>
- * The plugin must be able to support all version of the SDK.
- *
- * <p/>An SDK can require a new version of the plugin.
- * <p/>The SDK contains a file with the minimum version for the plugin. This file is inside the
- * <code>tools/lib</code> directory, and is called <code>plugin.prop</code>.<br>
- * Inside that text file, there is a line in the format "plugin.version=#.#.#". This is checked
- * against the current plugin version.<br>
- *
- */
-public final class VersionCheck {
- /**
- * The minimum version of the SDK Tools that this version of ADT requires.
- */
- private final static FullRevision MIN_TOOLS_REV = new FullRevision(24, 0, 2, 0);
-
- /**
- * Pattern to get the minimum plugin version supported by the SDK. This is read from
- * the file <code>$SDK/tools/lib/plugin.prop</code>.
- */
- private final static Pattern sPluginVersionPattern = Pattern.compile(
- "^plugin.version=(\\d+)\\.(\\d+)\\.(\\d+).*$"); //$NON-NLS-1$
- private final static Pattern sSourcePropPattern = Pattern.compile(
- "^" + PkgProps.PKG_REVISION + "=(.*)$"); //$NON-NLS-1$
-
- /**
- * Checks the plugin and the SDK have compatible versions.
- * @param osSdkPath The path to the SDK
- * @return true if compatible.
- */
- public static boolean checkVersion(String osSdkPath, CheckSdkErrorHandler errorHandler) {
- AdtPlugin plugin = AdtPlugin.getDefault();
- String osLibs = osSdkPath + SdkConstants.OS_SDK_TOOLS_LIB_FOLDER;
-
- // get the plugin property file, and grab the minimum plugin version required
- // to work with the sdk
- int minMajorVersion = -1;
- int minMinorVersion = -1;
- int minMicroVersion = -1;
- BufferedReader reader = null;
- try {
- reader = new BufferedReader(new FileReader(osLibs + SdkConstants.FN_PLUGIN_PROP));
- String line;
- while ((line = reader.readLine()) != null) {
- Matcher m = sPluginVersionPattern.matcher(line);
- if (m.matches()) {
- minMajorVersion = Integer.parseInt(m.group(1));
- minMinorVersion = Integer.parseInt(m.group(2));
- minMicroVersion = Integer.parseInt(m.group(3));
- break;
- }
- }
- } catch (FileNotFoundException e) {
- // the build id will be null, and this is handled by the builders.
- } catch (IOException e) {
- // the build id will be null, and this is handled by the builders.
- } finally {
- if (reader != null) {
- try {
- reader.close();
- } catch (IOException e) {
- } finally {
- reader = null;
- }
- }
- }
-
- // Failed to get the min plugin version number?
- if (minMajorVersion == -1 || minMinorVersion == -1 || minMicroVersion ==-1) {
- return errorHandler.handleWarning(
- Solution.OPEN_SDK_MANAGER,
- Messages.VersionCheck_Plugin_Version_Failed);
- }
-
- // Are the build tools installed? We can't query Sdk#getLatestBuildTool yet, since
- // SDK initialization typically hasn't completed yet and Sdk.getCurrent() is null.
- File buildToolsFolder = new File(osSdkPath, SdkConstants.FD_BUILD_TOOLS);
- if (!buildToolsFolder.isDirectory()) {
- return errorHandler.handleWarning(
- Solution.OPEN_SDK_MANAGER,
- Messages.VersionCheck_Build_Tool_Missing);
- }
-
- // test the plugin number
- String versionString = (String) plugin.getBundle().getHeaders().get(
- Constants.BUNDLE_VERSION);
- Version version = new Version(versionString);
-
- boolean valid = true;
- if (version.getMajor() < minMajorVersion) {
- valid = false;
- } else if (version.getMajor() == minMajorVersion) {
- if (version.getMinor() < minMinorVersion) {
- valid = false;
- } else if (version.getMinor() == minMinorVersion) {
- if (version.getMicro() < minMicroVersion) {
- valid = false;
- }
- }
- }
-
- if (valid == false) {
- return errorHandler.handleError(
- Solution.OPEN_P2_UPDATE,
- String.format(Messages.VersionCheck_Plugin_Too_Old,
- minMajorVersion, minMinorVersion, minMicroVersion, versionString));
- }
-
- // now check whether the tools are new enough.
- String osTools = osSdkPath + SdkConstants.OS_SDK_TOOLS_FOLDER;
- FullRevision toolsRevision = new FullRevision(Integer.MAX_VALUE);
- try {
- reader = new BufferedReader(new FileReader(osTools + SdkConstants.FN_SOURCE_PROP));
- String line;
- while ((line = reader.readLine()) != null) {
- Matcher m = sSourcePropPattern.matcher(line);
- if (m.matches()) {
- try {
- toolsRevision = FullRevision.parseRevision(m.group(1));
- } catch (NumberFormatException ignore) {}
- break;
- }
- }
- } catch (FileNotFoundException e) {
- // the build id will be null, and this is handled by the builders.
- } catch (IOException e) {
- // the build id will be null, and this is handled by the builders.
- } finally {
- if (reader != null) {
- try {
- reader.close();
- } catch (IOException e) {
- } finally {
- reader = null;
- }
- }
- }
-
- if (toolsRevision.compareTo(MIN_TOOLS_REV, PreviewComparison.IGNORE) < 0) {
- // this is a warning only as we need to parse the SDK to allow updating
- // of the tools!
- return errorHandler.handleWarning(
- Solution.OPEN_SDK_MANAGER,
- String.format(Messages.VersionCheck_Tools_Too_Old,
- MIN_TOOLS_REV, toolsRevision));
- }
-
- return true; // no error!
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/actions/AddSupportJarAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/actions/AddSupportJarAction.java
deleted file mode 100644
index f0af8bbd2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/actions/AddSupportJarAction.java
+++ /dev/null
@@ -1,626 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.actions;
-
-import com.android.SdkConstants;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.sdk.AdtConsoleSdkLog;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.sdklib.SdkManager;
-import com.android.sdklib.internal.project.ProjectProperties;
-import com.android.sdklib.internal.project.ProjectProperties.PropertyType;
-import com.android.sdklib.internal.project.ProjectPropertiesWorkingCopy;
-import com.android.sdklib.io.FileOp;
-import com.android.sdkuilib.internal.repository.ui.AdtUpdateDialog;
-import com.android.utils.NullLogger;
-import com.android.utils.Pair;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.filesystem.IFileSystem;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IProjectDescription;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IObjectActionDelegate;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Iterator;
-import java.util.Map;
-
-/**
- * An action to add the android-support-v4.jar support library
- * to the selected project.
- * <p/>
- * This should be used by the GLE. The action itself is currently more
- * like an example of how to invoke the new {@link AdtUpdateDialog}.
- * <p/>
- * TODO: make this more configurable.
- */
-public class AddSupportJarAction implements IObjectActionDelegate {
-
- /** The vendor ID of the support library. */
- private static final String VENDOR_ID = "android"; //$NON-NLS-1$
- /** The path ID of the support library. */
- private static final String SUPPORT_ID = "support"; //$NON-NLS-1$
- /** The path ID of the compatibility library (which was its id for releases 1-3). */
- private static final String COMPATIBILITY_ID = "compatibility"; //$NON-NLS-1$
- private static final String FD_GRIDLAYOUT = "gridlayout"; //$NON-NLS-1$
- private static final String FD_V7 = "v7"; //$NON-NLS-1$
- private static final String FD_V4 = "v4"; //$NON-NLS-1$
- private static final String FD_V13 = "v13"; //$NON-NLS-1$
- private static final String FD_APPCOMPAT = "appcompat"; //$NON-NLS-1$
- private static final String FD_LIBS = "libs"; //$NON-NLS-1$
- private static final String ANDROID_SUPPORT_V4_JAR = "android-support-v4.jar"; //$NON-NLS-1$
- private static final String ANDROID_SUPPORT_V13_JAR = "android-support-v13.jar";//$NON-NLS-1$
- private static final String APPCOMPAT_V7_JAR = "android-support-v7-appcompat.jar";//$NON-NLS-1$
- private static final String APP_COMPAT_LIB_NAME = "appcompat_v7"; //$NON-NLS-1$
- private ISelection mSelection;
-
- /**
- * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
- */
- @Override
- public void setActivePart(IAction action, IWorkbenchPart targetPart) {
- }
-
- @Override
- public void run(IAction action) {
- if (mSelection instanceof IStructuredSelection) {
-
- for (Iterator<?> it = ((IStructuredSelection) mSelection).iterator();
- it.hasNext();) {
- Object element = it.next();
- IProject project = null;
- if (element instanceof IProject) {
- project = (IProject) element;
- } else if (element instanceof IAdaptable) {
- project = (IProject) ((IAdaptable) element)
- .getAdapter(IProject.class);
- }
- if (project != null) {
- install(project);
- }
- }
- }
- }
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
- mSelection = selection;
- }
-
- /**
- * Install the support jar into the given project.
- *
- * @param project The Android project to install the support jar into
- * @return true if the installation was successful
- */
- public static boolean install(final IProject project) {
- File jarPath = installSupport(-1);
- if (jarPath != null) {
- try {
- return copyJarIntoProject(project, jarPath) != null;
- } catch (Exception e) {
- AdtPlugin.log(e, null);
- }
- }
-
- return false;
- }
-
- /**
- * Installs the Android Support library into the SDK extras/ folder. If a minimum
- * revision number is specified, this method will check whether the package is already
- * installed, and if the installed revision is at least as high as the requested revision,
- * this method will exit without performing an update.
- *
- * @param minimumRevision a minimum revision, or -1 to upgrade
- * unconditionally. Note that this does <b>NOT</b> specify which
- * revision to install; the latest version will always be
- * installed.
- * @return the location of the support jar file, or null if something went
- * wrong
- */
- @Nullable
- public static File installSupport(int minimumRevision) {
-
- final Sdk sdk = Sdk.getCurrent();
- if (sdk == null) {
- AdtPlugin.printErrorToConsole(
- AddSupportJarAction.class.getSimpleName(), // tag
- "Error: Android SDK is not loaded yet."); //$NON-NLS-1$
- return null;
- }
-
- String sdkLocation = sdk.getSdkOsLocation();
- if (minimumRevision > 0) {
- File path = getSupportJarFile();
- if (path != null) {
- assert path.exists(); // guaranteed by the getSupportJarFile call
- int installedRevision = getInstalledRevision();
- if (installedRevision != -1 && minimumRevision <= installedRevision) {
- return path;
- }
- }
- }
-
- // TODO: For the generic action, check the library isn't in the project already.
-
- // First call the package manager to make sure the package is installed
- // and get the installation path of the library.
-
- AdtUpdateDialog window = new AdtUpdateDialog(
- AdtPlugin.getShell(),
- new AdtConsoleSdkLog(),
- sdkLocation);
-
- Pair<Boolean, File> result = window.installExtraPackage(VENDOR_ID, SUPPORT_ID);
-
- // TODO: Make sure the version is at the required level; we know we need at least one
- // containing the v7 support
-
- if (!result.getFirst().booleanValue()) {
- AdtPlugin.printErrorToConsole("Failed to install Android Support library");
- return null;
- }
-
- // TODO these "v4" values needs to be dynamic, e.g. we could try to match
- // vN/android-support-vN.jar. Eventually we'll want to rely on info from the
- // package manifest anyway so this is irrelevant.
-
- File path = new File(result.getSecond(), FD_V4);
- final File jarPath = new File(path, ANDROID_SUPPORT_V4_JAR);
-
- if (!jarPath.isFile()) {
- AdtPlugin.printErrorToConsole("Android Support Jar not found:",
- jarPath.getAbsolutePath());
- return null;
- }
-
- return jarPath;
- }
-
- /**
- * Returns the installed revision number of the Android Support
- * library, or -1 if the package is not installed.
- *
- * @return the installed revision number, or -1
- */
- public static int getInstalledRevision() {
- final Sdk sdk = Sdk.getCurrent();
- if (sdk != null) {
- String sdkLocation = sdk.getSdkOsLocation();
- SdkManager manager = SdkManager.createManager(sdkLocation, NullLogger.getLogger());
- Map<String, Integer> versions = manager.getExtrasVersions();
- Integer version = versions.get(VENDOR_ID + '/' + SUPPORT_ID);
- if (version == null) {
- // Check the old compatibility library. When the library is updated in-place
- // the manager doesn't change its folder name (since that is a source of
- // endless issues on Windows.)
- version = versions.get(VENDOR_ID + '/' + COMPATIBILITY_ID);
- }
- if (version != null) {
- return version.intValue();
- }
- }
-
- return -1;
- }
-
- /**
- * Similar to {@link #install}, but rather than copy a jar into the given
- * project, it creates a new library project in the workspace for the
- * support library, and adds a library dependency on the newly
- * installed library from the given project.
- *
- * @param project the project to add a dependency on the library to
- * @param waitForFinish If true, block until the task has finished
- * @return true if the installation was successful (or if
- * <code>waitForFinish</code> is false, if the installation is
- * likely to be successful - e.g. the user has at least agreed to
- * all installation prompts.)
- */
- public static boolean installGridLayoutLibrary(final IProject project, boolean waitForFinish) {
- final IJavaProject javaProject = JavaCore.create(project);
- if (javaProject != null) {
-
- File supportPath = getSupportPackageDir();
- if (!supportPath.isDirectory()) {
- File path = installSupport(8); // GridLayout arrived in rev 7 and fixed in rev 8
- if (path == null) {
- return false;
- }
- assert path.equals(supportPath);
- }
- File libraryPath = new File(supportPath, FD_V7 + File.separator + FD_GRIDLAYOUT);
- if (!libraryPath.isDirectory()) {
- // Upgrade support package: it's out of date. The SDK manager will
- // perform an upgrade to the latest version if the package is already installed.
- File path = installSupport(-1);
- if (path == null) {
- return false;
- }
- assert path.equals(libraryPath) : path;
- }
-
- // Create workspace copy of the project and add library dependency
- IProject libraryProject = createLibraryProject(libraryPath, project,
- "gridlayout_v7", waitForFinish); //$NON-NLS-1$
- if (libraryProject != null) {
- return addLibraryDependency(libraryProject, project, waitForFinish);
- }
- }
-
- return false;
- }
-
- /**
- * Similar to {@link #install}, but rather than copy a jar into the given
- * project, it creates a new library project in the workspace for the
- * support library, and adds a library dependency on the newly
- * installed library from the given project.
- *
- * @param project the project to add a dependency on the library to
- * @param waitForFinish If true, block until the task has finished
- * @return true if the installation was successful (or if
- * <code>waitForFinish</code> is false, if the installation is
- * likely to be successful - e.g. the user has at least agreed to
- * all installation prompts.)
- */
- public static boolean installAppCompatLibrary(final IProject project, boolean waitForFinish) {
- final IJavaProject javaProject = JavaCore.create(project);
- if (javaProject != null) {
-
- // Don't add in the library if it already exists
- ProjectState state = Sdk.getProjectState(project);
- ProjectPropertiesWorkingCopy copy = state.getProperties().makeWorkingCopy();
- for (String property : copy.keySet()) {
- if (property.startsWith(ProjectProperties.PROPERTY_LIB_REF)) {
- String libraryReference = copy.getProperty(property);
- if (libraryReference != null && libraryReference.contains(APP_COMPAT_LIB_NAME)) {
- return true;
- }
- }
- }
-
- File supportPath = getSupportPackageDir();
- if (!supportPath.isDirectory()) {
- File path = installSupport(7);
- if (path == null) {
- return false;
- }
- assert path.equals(supportPath);
- }
- File libraryPath = new File(supportPath, FD_V7 + File.separator + FD_APPCOMPAT);
- if (!libraryPath.isDirectory()) {
- // Upgrade support package: it's out of date. The SDK manager will
- // perform an upgrade to the latest version if the package is already installed.
- File path = installSupport(-1);
- if (path == null) {
- return false;
- }
- assert path.equals(libraryPath) : path;
- }
-
- // Check to see if there's already a version of the library available
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IWorkspaceRoot root = workspace.getRoot();
- IProject libraryProject = root.getProject(APP_COMPAT_LIB_NAME);
- if (!libraryProject.exists()) {
- // Create workspace copy of the project and add library dependency
- libraryProject = createLibraryProject(libraryPath, project,
- APP_COMPAT_LIB_NAME, waitForFinish);
- }
- if (libraryProject != null) {
- return addLibraryDependency(libraryProject, project, waitForFinish);
- }
- }
-
- return false;
- }
-
- /**
- * Returns the directory containing the support libraries (v4, v7, v13,
- * ...), which may or may not exist
- *
- * @return a path to the support library or null
- */
- private static File getSupportPackageDir() {
- final Sdk sdk = Sdk.getCurrent();
- if (sdk != null) {
- String sdkLocation = sdk.getSdkOsLocation();
- SdkManager manager = SdkManager.createManager(sdkLocation, NullLogger.getLogger());
- Map<String, Integer> versions = manager.getExtrasVersions();
- Integer version = versions.get(VENDOR_ID + '/' + SUPPORT_ID);
- if (version != null) {
- File supportPath = new File(sdkLocation,
- SdkConstants.FD_EXTRAS + File.separator
- + VENDOR_ID + File.separator
- + SUPPORT_ID);
- return supportPath;
- }
-
- // Check the old compatibility library. When the library is updated in-place
- // the manager doesn't change its folder name (since that is a source of
- // endless issues on Windows.)
- version = versions.get(VENDOR_ID + '/' + COMPATIBILITY_ID);
- if (version != null) {
- File supportPath = new File(sdkLocation,
- SdkConstants.FD_EXTRAS + File.separator
- + VENDOR_ID + File.separator
- + COMPATIBILITY_ID);
- return supportPath;
- }
- }
- return null;
- }
-
- /**
- * Returns a path to the installed jar file for the support library,
- * or null if it does not exist
- *
- * @return a path to the v4.jar or null
- */
- @Nullable
- public static File getSupportJarFile() {
- File supportDir = getSupportPackageDir();
- if (supportDir != null) {
- File path = new File(supportDir, FD_V4 + File.separator + ANDROID_SUPPORT_V4_JAR);
- if (path.exists()) {
- return path;
- }
- }
-
- return null;
- }
-
- /**
- * Returns a path to the installed jar file for the support library,
- * or null if it does not exist
- *
- * @return a path to the v13.jar or null
- */
- @Nullable
- public static File getSupport13JarFile() {
- File supportDir = getSupportPackageDir();
- if (supportDir != null) {
- File path = new File(supportDir, FD_V13 + File.separator + ANDROID_SUPPORT_V13_JAR);
- if (path.exists()) {
- return path;
- }
- }
-
- return null;
- }
-
- /**
- * Creates a library project in the Eclipse workspace out of the grid layout project
- * in the SDK tree.
- *
- * @param libraryPath the path to the directory tree containing the project contents
- * @param project the project to copy the SDK target out of
- * @param waitForFinish whether the operation should finish before this method returns
- * @return a library project, or null if it fails for some reason
- */
- private static IProject createLibraryProject(
- final File libraryPath,
- final IProject project,
- final String libraryName,
- boolean waitForFinish) {
-
- // Install a new library into the workspace. This is a copy rather than
- // a reference to the support library version such that modifications
- // do not modify the pristine copy in the SDK install area.
-
- final IProject newProject;
- try {
- IProgressMonitor monitor = new NullProgressMonitor();
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IWorkspaceRoot root = workspace.getRoot();
-
- String name = AdtUtils.getUniqueProjectName(
- libraryName, "_"); //$NON-NLS-1$
- newProject = root.getProject(name);
- IProjectDescription description = workspace.newProjectDescription(name);
- String[] natures = new String[] { AdtConstants.NATURE_DEFAULT, JavaCore.NATURE_ID };
- description.setNatureIds(natures);
- newProject.create(description, monitor);
-
- // Copy in the files recursively
- IFileSystem fileSystem = EFS.getLocalFileSystem();
- IFileStore sourceDir = fileSystem.getStore(libraryPath.toURI());
- IFileStore destDir = fileSystem.getStore(newProject.getLocationURI());
- sourceDir.copy(destDir, EFS.OVERWRITE, null);
-
- // Make sure the src folder exists
- destDir.getChild(SdkConstants.SRC_FOLDER).mkdir(0, null /*monitor*/);
-
- // Set the android platform to the same level as the calling project
- ProjectState state = Sdk.getProjectState(project);
- String target = state.getProperties().getProperty(ProjectProperties.PROPERTY_TARGET);
- if (target != null && target.length() > 0) {
- ProjectProperties properties = ProjectProperties.load(
- destDir.toLocalFile(EFS.NONE, new NullProgressMonitor()).getPath(),
- PropertyType.PROJECT);
- ProjectPropertiesWorkingCopy copy = properties.makeWorkingCopy();
- copy.setProperty(ProjectProperties.PROPERTY_TARGET, target);
- try {
- copy.save();
- } catch (Exception e) {
- AdtPlugin.log(e, null);
- }
- }
-
- newProject.open(monitor);
-
- return newProject;
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- return null;
- }
- }
-
- /**
- * Adds a library dependency on the given library into the given project.
- *
- * @param libraryProject the library project to depend on
- * @param dependentProject the project to write the dependency into
- * @param waitForFinish whether this method should wait for the job to
- * finish
- * @return true if the operation succeeded
- */
- public static boolean addLibraryDependency(
- final IProject libraryProject,
- final IProject dependentProject,
- boolean waitForFinish) {
-
- // Now add library dependency
-
- // Run an Eclipse asynchronous job to update the project
- Job job = new Job("Add Support Library Dependency to Project") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- monitor.beginTask("Add library dependency to project build path", 3);
- monitor.worked(1);
-
- // TODO: Add library project to the project.properties file!
- ProjectState state = Sdk.getProjectState(dependentProject);
- ProjectPropertiesWorkingCopy mPropertiesWorkingCopy =
- state.getProperties().makeWorkingCopy();
-
- // Get the highest version number of the libraries; there cannot be any
- // gaps so we will assign the next library the next number
- int nextVersion = 1;
- for (String property : mPropertiesWorkingCopy.keySet()) {
- if (property.startsWith(ProjectProperties.PROPERTY_LIB_REF)) {
- String s = property.substring(
- ProjectProperties.PROPERTY_LIB_REF.length());
- int version = Integer.parseInt(s);
- if (version >= nextVersion) {
- nextVersion = version + 1;
- }
- }
- }
-
- IPath relativePath = libraryProject.getLocation().makeRelativeTo(
- dependentProject.getLocation());
-
- mPropertiesWorkingCopy.setProperty(
- ProjectProperties.PROPERTY_LIB_REF + nextVersion,
- relativePath.toString());
- try {
- mPropertiesWorkingCopy.save();
- IResource projectProp = dependentProject.findMember(
- SdkConstants.FN_PROJECT_PROPERTIES);
- projectProp.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor());
- } catch (Exception e) {
- String msg = String.format(
- "Failed to save %1$s for project %2$s",
- SdkConstants.FN_PROJECT_PROPERTIES, dependentProject.getName());
- AdtPlugin.log(e, msg);
- }
-
- // Project fix-ups
- Job fix = FixProjectAction.createFixProjectJob(libraryProject);
- fix.schedule();
- fix.join();
-
- monitor.worked(1);
-
- return Status.OK_STATUS;
- } catch (Exception e) {
- return new Status(Status.ERROR, AdtPlugin.PLUGIN_ID, Status.ERROR,
- "Failed", e); //$NON-NLS-1$
- } finally {
- if (monitor != null) {
- monitor.done();
- }
- }
- }
- };
- job.schedule();
-
- if (waitForFinish) {
- try {
- job.join();
- return job.getState() == IStatus.OK;
- } catch (InterruptedException e) {
- AdtPlugin.log(e, null);
- }
- }
-
- return true;
- }
-
- private static IResource copyJarIntoProject(
- IProject project,
- File jarPath) throws IOException, CoreException {
- IFolder resFolder = project.getFolder(SdkConstants.FD_NATIVE_LIBS);
- if (!resFolder.exists()) {
- resFolder.create(IResource.FORCE, true /*local*/, null);
- }
-
- IFile destFile = resFolder.getFile(jarPath.getName());
- IPath loc = destFile.getLocation();
- File destPath = loc.toFile();
-
- // Only modify the file if necessary so that we don't trigger unnecessary recompilations
- FileOp f = new FileOp();
- if (!f.isFile(destPath) || !f.isSameFile(jarPath, destPath)) {
- f.copyFile(jarPath, destPath);
- // Make sure Eclipse discovers java.io file changes
- resFolder.refreshLocal(1, new NullProgressMonitor());
- }
-
- return destFile;
- }
-
- /**
- * @see IWorkbenchWindowActionDelegate#init
- */
- public void init(IWorkbenchWindow window) {
- // pass
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/actions/AvdManagerAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/actions/AvdManagerAction.java
deleted file mode 100644
index 86f2d3c0a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/actions/AvdManagerAction.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.actions;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.sdk.AdtConsoleSdkLog;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.sdkuilib.repository.AvdManagerWindow;
-import com.android.sdkuilib.repository.AvdManagerWindow.AvdInvocationContext;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.ui.IObjectActionDelegate;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-
-/**
- * Delegate for the toolbar/menu action "AVD Manager".
- * It displays the AVD Manager window.
- */
-public class AvdManagerAction implements IWorkbenchWindowActionDelegate, IObjectActionDelegate {
-
- @Override
- public void dispose() {
- // nothing to dispose.
- }
-
- @Override
- public void init(IWorkbenchWindow window) {
- // no init
- }
-
- @Override
- public void run(IAction action) {
- final Sdk sdk = Sdk.getCurrent();
- if (sdk != null) {
- // Although orthogonal to the avd manager action, this is a good time
- // to check whether the SDK has changed on disk.
- AdtPlugin.getDefault().refreshSdk();
-
- // Runs the updater window, directing all logs to the ADT console.
- AvdManagerWindow window = new AvdManagerWindow(
- AdtPlugin.getShell(),
- new AdtConsoleSdkLog(),
- sdk.getSdkOsLocation(),
- AvdInvocationContext.IDE);
- window.open();
- } else {
- AdtPlugin.displayError("Android SDK",
- "Location of the Android SDK has not been setup in the preferences.");
- }
- }
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
- // nothing related to the current selection.
- }
-
- @Override
- public void setActivePart(IAction action, IWorkbenchPart targetPart) {
- // nothing to do.
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/actions/DexDumpAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/actions/DexDumpAction.java
deleted file mode 100755
index 78fcfd448..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/actions/DexDumpAction.java
+++ /dev/null
@@ -1,276 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.actions;
-
-import com.android.SdkConstants;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs.BuildVerbosity;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.sdklib.BuildToolInfo;
-import com.android.utils.GrabProcessOutput;
-import com.android.utils.GrabProcessOutput.IProcessOutput;
-import com.android.utils.GrabProcessOutput.Wait;
-import com.android.utils.SdkUtils;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IObjectActionDelegate;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.ide.IDE;
-
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.util.Iterator;
-
-/**
- * Runs dexdump on the classes.dex of a selected project.
- */
-public class DexDumpAction implements IObjectActionDelegate {
-
- private ISelection mSelection;
-
- @Override
- public void setActivePart(IAction action, IWorkbenchPart targetPart) {
- // pass
- }
-
- @Override
- public void run(IAction action) {
- if (mSelection instanceof IStructuredSelection) {
- for (Iterator<?> it = ((IStructuredSelection)mSelection).iterator(); it.hasNext();) {
- Object element = it.next();
- IProject project = null;
- if (element instanceof IProject) {
- project = (IProject)element;
- } else if (element instanceof IAdaptable) {
- project = (IProject)((IAdaptable)element).getAdapter(IProject.class);
- }
- if (project != null) {
- dexDumpProject(project);
- }
- }
- }
- }
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
- mSelection = selection;
- }
-
- /**
- * Calls {@link #runDexDump(IProject, IProgressMonitor)} inside a job.
- *
- * @param project on which to run dexdump.
- */
- private void dexDumpProject(final IProject project) {
- new Job("Dexdump") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- return runDexDump(project, monitor);
- }
- }.schedule();
- }
-
- /**
- * Runs <code>dexdump</code> on the classex.dex of the project.
- * Saves the output in a temporary file.
- * On success, opens the file in the default text editor.
- *
- * @param project on which to run dexdump.
- * @param monitor The job's monitor.
- */
- private IStatus runDexDump(final IProject project, IProgressMonitor monitor) {
- File dstFile = null;
- boolean removeDstFile = true;
- try {
- if (monitor != null) {
- monitor.beginTask(String.format("Dump dex of %1$s", project.getName()), 2);
- }
-
- Sdk current = Sdk.getCurrent();
- if (current == null) {
- AdtPlugin.printErrorToConsole(project,
- "DexDump: missing current SDK"); //$NON-NLS-1$
- return Status.OK_STATUS;
- }
-
- BuildToolInfo buildToolInfo = current.getLatestBuildTool();
- if (buildToolInfo == null) {
- AdtPlugin.printErrorToConsole(project,
- "SDK missing build tools. Please install build tools using SDK Manager.");
- return Status.OK_STATUS;
- }
-
- File buildToolsFolder = buildToolInfo.getLocation();
- File dexDumpFile = new File(buildToolsFolder, SdkConstants.FN_DEXDUMP);
-
- IPath binPath = project.getFolder(SdkConstants.FD_OUTPUT).getLocation();
- if (binPath == null) {
- AdtPlugin.printErrorToConsole(project,
- "DexDump: missing project /bin folder. Please compile first."); //$NON-NLS-1$
- return Status.OK_STATUS;
- }
-
- File classesDexFile =
- new File(binPath.toOSString(), SdkConstants.FN_APK_CLASSES_DEX);
- if (!classesDexFile.exists()) {
- AdtPlugin.printErrorToConsole(project,
- "DexDump: missing classex.dex for project. Please compile first.");//$NON-NLS-1$
- return Status.OK_STATUS;
- }
-
- try {
- dstFile = File.createTempFile(
- "dexdump_" + project.getName() + "_", //$NON-NLS-1$ //$NON-NLS-2$
- ".txt"); //$NON-NLS-1$
- } catch (Exception e) {
- AdtPlugin.logAndPrintError(e, project.getName(),
- "DexDump: createTempFile failed."); //$NON-NLS-1$
- return Status.OK_STATUS;
- }
-
- // --- Exec command line and save result to dst file
-
- String[] command = new String[2];
- command[0] = dexDumpFile.getAbsolutePath();
- command[1] = classesDexFile.getAbsolutePath();
-
- try {
- final Process process = Runtime.getRuntime().exec(command);
-
- final BufferedWriter writer = new BufferedWriter(new FileWriter(dstFile));
- try {
- final String lineSep = SdkUtils.getLineSeparator();
-
- int err = GrabProcessOutput.grabProcessOutput(
- process,
- Wait.WAIT_FOR_READERS,
- new IProcessOutput() {
- @Override
- public void out(@Nullable String line) {
- if (line != null) {
- try {
- writer.write(line);
- writer.write(lineSep);
- } catch (IOException ignore) {}
- }
- }
-
- @Override
- public void err(@Nullable String line) {
- if (line != null) {
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE,
- project, line);
- }
- }
- });
-
- if (err == 0) {
- // The command worked. In this case we don't remove the
- // temp file in the finally block.
- removeDstFile = false;
- } else {
- AdtPlugin.printErrorToConsole(project,
- "DexDump failed with code " + Integer.toString(err)); //$NON-NLS-1$
- return Status.OK_STATUS;
- }
- } finally {
- writer.close();
- }
- } catch (InterruptedException e) {
- // ?
- }
-
- if (monitor != null) {
- monitor.worked(1);
- }
-
- // --- Open the temp file in an editor
-
- final String dstPath = dstFile.getAbsolutePath();
- AdtPlugin.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- IFileStore fileStore =
- EFS.getLocalFileSystem().getStore(new Path(dstPath));
- if (!fileStore.fetchInfo().isDirectory() &&
- fileStore.fetchInfo().exists()) {
-
- IWorkbench wb = PlatformUI.getWorkbench();
- IWorkbenchWindow win = wb == null ? null : wb.getActiveWorkbenchWindow();
- final IWorkbenchPage page = win == null ? null : win.getActivePage();
-
- if (page != null) {
- try {
- IDE.openEditorOnFileStore(page, fileStore);
- } catch (PartInitException e) {
- AdtPlugin.logAndPrintError(e, project.getName(),
- "Opening DexDump result failed. Result is available at %1$s", //$NON-NLS-1$
- dstPath);
- }
- }
- }
- }
- });
-
- if (monitor != null) {
- monitor.worked(1);
- }
-
- return Status.OK_STATUS;
-
- } catch (IOException e) {
- AdtPlugin.logAndPrintError(e, project.getName(),
- "DexDump failed."); //$NON-NLS-1$
- return Status.OK_STATUS;
-
- } finally {
- // By default we remove the temp file on failure.
- if (removeDstFile && dstFile != null) {
- try {
- dstFile.delete();
- } catch (Exception e) {
- AdtPlugin.logAndPrintError(e, project.getName(),
- "DexDump: can't delete temp file %1$s.", //$NON-NLS-1$
- dstFile.getAbsoluteFile());
- }
- }
- if (monitor != null) {
- monitor.done();
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/actions/FixProjectAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/actions/FixProjectAction.java
deleted file mode 100644
index 254219fc1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/actions/FixProjectAction.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.actions;
-
-import com.android.annotations.NonNull;
-import com.android.ide.eclipse.adt.internal.project.AndroidNature;
-import com.android.ide.eclipse.adt.internal.project.ProjectHelper;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IObjectActionDelegate;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-
-import java.util.Iterator;
-
-/**
- * Action to fix the project properties:
- * <ul>
- * <li>Make sure the framework archive is present with the link to the java
- * doc</li>
- * </ul>
- */
-public class FixProjectAction implements IObjectActionDelegate {
-
- private ISelection mSelection;
-
- /**
- * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
- */
- @Override
- public void setActivePart(IAction action, IWorkbenchPart targetPart) {
- }
-
- @Override
- public void run(IAction action) {
- if (mSelection instanceof IStructuredSelection) {
-
- for (Iterator<?> it = ((IStructuredSelection) mSelection).iterator();
- it.hasNext();) {
- Object element = it.next();
- IProject project = null;
- if (element instanceof IProject) {
- project = (IProject) element;
- } else if (element instanceof IAdaptable) {
- project = (IProject) ((IAdaptable) element)
- .getAdapter(IProject.class);
- }
- if (project != null) {
- fixProject(project);
- }
- }
- }
- }
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
- mSelection = selection;
- }
-
- private void fixProject(final IProject project) {
- createFixProjectJob(project).schedule();
- }
-
- /**
- * Creates a job to fix the project
- *
- * @param project the project to fix
- * @return a job to perform the fix (not yet scheduled)
- */
- @NonNull
- public static Job createFixProjectJob(@NonNull final IProject project) {
- return new Job("Fix Project Properties") {
-
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- if (monitor != null) {
- monitor.beginTask("Fix Project Properties", 6);
- }
-
- ProjectHelper.fixProject(project);
- if (monitor != null) {
- monitor.worked(1);
- }
-
- // fix the nature order to have the proper project icon
- ProjectHelper.fixProjectNatureOrder(project);
- if (monitor != null) {
- monitor.worked(1);
- }
-
- // now we fix the builders
- AndroidNature.configureResourceManagerBuilder(project);
- if (monitor != null) {
- monitor.worked(1);
- }
-
- AndroidNature.configurePreBuilder(project);
- if (monitor != null) {
- monitor.worked(1);
- }
-
- AndroidNature.configureApkBuilder(project);
- if (monitor != null) {
- monitor.worked(1);
- }
-
- return Status.OK_STATUS;
- } catch (JavaModelException e) {
- return e.getJavaModelStatus();
- } catch (CoreException e) {
- return e.getStatus();
- } finally {
- if (monitor != null) {
- monitor.done();
- }
- }
- }
- };
- }
-
- /**
- * @see IWorkbenchWindowActionDelegate#init
- */
- public void init(IWorkbenchWindow window) {
- // pass
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/actions/SdkManagerAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/actions/SdkManagerAction.java
deleted file mode 100644
index 48667bea0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/actions/SdkManagerAction.java
+++ /dev/null
@@ -1,354 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.actions;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.sdk.AdtConsoleSdkLog;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.sdklib.io.FileOp;
-import com.android.sdklib.repository.ISdkChangeListener;
-import com.android.utils.GrabProcessOutput;
-import com.android.utils.GrabProcessOutput.IProcessOutput;
-import com.android.utils.GrabProcessOutput.Wait;
-import com.android.sdkuilib.repository.SdkUpdaterWindow;
-import com.android.sdkuilib.repository.SdkUpdaterWindow.SdkInvocationContext;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.ProgressMonitorDialog;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IObjectActionDelegate;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-
-import java.io.File;
-import java.lang.reflect.InvocationTargetException;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * Delegate for the toolbar/menu action "Android SDK Manager".
- * It displays the Android SDK Manager.
- */
-public class SdkManagerAction implements IWorkbenchWindowActionDelegate, IObjectActionDelegate {
-
- @Override
- public void dispose() {
- // nothing to dispose.
- }
-
- @Override
- public void init(IWorkbenchWindow window) {
- // no init
- }
-
- @Override
- public void run(IAction action) {
- // Although orthogonal to the sdk manager action, this is a good time
- // to check whether the SDK has changed on disk.
- AdtPlugin.getDefault().refreshSdk();
-
- if (!openExternalSdkManager()) {
- // If we failed to execute the sdk manager, check the SDK location.
- // If it's not properly set, the check will display a dialog to state
- // so to the user and a link to the prefs.
- // Here's it's ok to call checkSdkLocationAndId() since it will not try
- // to run the SdkManagerAction (it might run openExternalSdkManager though.)
- // If checkSdkLocationAndId tries to open the SDK Manager, it end up using
- // the internal one.
- if (AdtPlugin.getDefault().checkSdkLocationAndId()) {
- // The SDK check was successful, yet the sdk manager fail to launch anyway.
- AdtPlugin.displayError(
- "Android SDK",
- "Failed to run the Android SDK Manager. Check the Android Console View for details.");
- }
- }
- }
-
- /**
- * A custom implementation of {@link ProgressMonitorDialog} that allows us
- * to rename the "Cancel" button to "Close" from the internal task.
- */
- private static class CloseableProgressMonitorDialog extends ProgressMonitorDialog {
-
- public CloseableProgressMonitorDialog(Shell parent) {
- super(parent);
- }
-
- public void changeCancelToClose() {
- if (cancel != null && !cancel.isDisposed()) {
- Display display = getShell() == null ? null : getShell().getDisplay();
- if (display != null) {
- display.syncExec(new Runnable() {
- @Override
- public void run() {
- if (cancel != null && !cancel.isDisposed()) {
- cancel.setText(IDialogConstants.CLOSE_LABEL);
- }
- }
- });
- }
- }
- }
- }
-
- /**
- * Opens the SDK Manager as an external application.
- * This call is asynchronous, it doesn't wait for the manager to be closed.
- * <p/>
- * Important: this method must NOT invoke {@link AdtPlugin#checkSdkLocationAndId}
- * (in any of its variations) since the dialog uses this method to invoke the sdk
- * manager if needed.
- *
- * @return True if the application was found and executed. False if it could not
- * be located or could not be launched.
- */
- public static boolean openExternalSdkManager() {
-
- // On windows this takes a couple seconds and it's not clear the launch action
- // has been invoked. To prevent the user from randomly clicking the "open sdk manager"
- // button multiple times, show a progress window that will automatically close
- // after a couple seconds.
-
- // By default openExternalSdkManager will return false.
- final AtomicBoolean returnValue = new AtomicBoolean(false);
-
- final CloseableProgressMonitorDialog p =
- new CloseableProgressMonitorDialog(AdtPlugin.getShell());
- p.setOpenOnRun(true);
- try {
- p.run(true /*fork*/, true /*cancelable*/, new IRunnableWithProgress() {
- @Override
- public void run(IProgressMonitor monitor)
- throws InvocationTargetException, InterruptedException {
-
- // Get the SDK locatiom from the current SDK or as fallback
- // directly from the ADT preferences.
- Sdk sdk = Sdk.getCurrent();
- String osSdkLocation = sdk == null ? null : sdk.getSdkOsLocation();
- if (osSdkLocation == null || !new File(osSdkLocation).isDirectory()) {
- osSdkLocation = AdtPrefs.getPrefs().getOsSdkFolder();
- }
-
- // If there's no SDK location or it's not a valid directory,
- // there's nothing we can do. When this is invoked from run()
- // the checkSdkLocationAndId method call should display a dialog
- // telling the user to configure the preferences.
- if (osSdkLocation == null || !new File(osSdkLocation).isDirectory()) {
- return;
- }
-
- final int numIter = 30; //30*100=3s to wait for window
- final int sleepMs = 100;
- monitor.beginTask("Starting Android SDK Manager", numIter);
-
- File androidBat = FileOp.append(
- osSdkLocation,
- SdkConstants.FD_TOOLS,
- SdkConstants.androidCmdName());
-
- if (!androidBat.exists()) {
- AdtPlugin.printErrorToConsole("SDK Manager",
- "Missing %s file in Android SDK.", SdkConstants.androidCmdName());
- return;
- }
-
- if (monitor.isCanceled()) {
- // Canceled by user; return true as if it succeeded.
- returnValue.set(true);
- return;
- }
-
- p.changeCancelToClose();
-
- try {
- final AdtConsoleSdkLog logger = new AdtConsoleSdkLog();
-
- String command[] = new String[] {
- androidBat.getAbsolutePath(),
- "sdk" //$NON-NLS-1$
- };
- Process process = Runtime.getRuntime().exec(command);
- GrabProcessOutput.grabProcessOutput(
- process,
- Wait.ASYNC,
- new IProcessOutput() {
- @Override
- public void out(@Nullable String line) {
- // Ignore stdout
- }
-
- @Override
- public void err(@Nullable String line) {
- if (line != null) {
- logger.info("[SDK Manager] %s", line);
- }
- }
- });
-
- // Set openExternalSdkManager to return true.
- returnValue.set(true);
- } catch (Exception ignore) {
- }
-
- // This small wait prevents the progress dialog from closing too fast.
- for (int i = 0; i < numIter; i++) {
- if (monitor.isCanceled()) {
- // Canceled by user; return true as if it succeeded.
- returnValue.set(true);
- return;
- }
- if (i == 10) {
- monitor.subTask("Initializing... SDK Manager will show up shortly.");
- }
- try {
- Thread.sleep(sleepMs);
- monitor.worked(1);
- } catch (InterruptedException e) {
- // ignore
- }
- }
-
- monitor.done();
- }
- });
- } catch (Exception e) {
- AdtPlugin.log(e, "SDK Manager exec failed"); //$NON-NLS-1#
- return false;
- }
-
- return returnValue.get();
- }
-
- /**
- * Opens the SDK Manager bundled within ADT.
- * The call is blocking and does not return till the SD Manager window is closed.
- *
- * @return True if the SDK location is known and the SDK Manager was started.
- * False if the SDK location is not set and we can't open a SDK Manager to
- * manage files in an unknown location.
- */
- public static boolean openAdtSdkManager() {
- final Sdk sdk = Sdk.getCurrent();
- if (sdk == null) {
- return false;
- }
-
- // Runs the updater window, directing only warning/errors logs to the ADT console
- // (normal log is just dropped, which is fine since the SDK Manager has its own
- // log window now.)
-
- SdkUpdaterWindow window = new SdkUpdaterWindow(
- AdtPlugin.getShell(),
- new AdtConsoleSdkLog() {
- @Override
- public void info(@NonNull String msgFormat, Object... args) {
- // Do not show non-error/warning log in Eclipse.
- };
- @Override
- public void verbose(@NonNull String msgFormat, Object... args) {
- // Do not show non-error/warning log in Eclipse.
- };
- },
- sdk.getSdkOsLocation(),
- SdkInvocationContext.IDE);
-
- ISdkChangeListener listener = new ISdkChangeListener() {
- @Override
- public void onSdkLoaded() {
- // Ignore initial load of the SDK.
- }
-
- /**
- * Unload all we can from the SDK before new packages are installed.
- * Typically we need to get rid of references to dx from platform-tools
- * and to any platform resource data.
- * <p/>
- * {@inheritDoc}
- */
- @Override
- public void preInstallHook() {
-
- // TODO we need to unload as much of as SDK as possible. Otherwise
- // on Windows we end up with Eclipse locking some files and we can't
- // replace them.
- //
- // At this point, we know what the user wants to install so it would be
- // possible to pass in flags to know what needs to be unloaded. Typically
- // we need to:
- // - unload dex if platform-tools is going to be updated. There's a vague
- // attempt below at removing any references to dex and GCing. Seems
- // to do the trick.
- // - unload any target that is going to be updated since it may have
- // resource data used by a current layout editor (e.g. data/*.ttf
- // and various data/res/*.xml).
- //
- // Most important we need to make sure there isn't a build going on
- // and if there is one, either abort it or wait for it to complete and
- // then we want to make sure we don't get any attempt to use the SDK
- // before the postInstallHook is called.
-
- if (sdk != null) {
- sdk.unloadTargetData(true /*preventReload*/);
- sdk.unloadDexWrappers();
- }
- }
-
- /**
- * Nothing to do. We'll reparse the SDK later in onSdkReload.
- * <p/>
- * {@inheritDoc}
- */
- @Override
- public void postInstallHook() {
- }
-
- /**
- * Reparse the SDK in case anything was add/removed.
- * <p/>
- * {@inheritDoc}
- */
- @Override
- public void onSdkReload() {
- AdtPlugin.getDefault().reparseSdk();
- }
- };
-
- window.addListener(listener);
- window.open();
-
- return true;
- }
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
- // nothing related to the current selection.
- }
-
- @Override
- public void setActivePart(IAction action, IWorkbenchPart targetPart) {
- // nothing to do.
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/assetstudio/AssetType.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/assetstudio/AssetType.java
deleted file mode 100644
index 5cfeebb4b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/assetstudio/AssetType.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.assetstudio;
-
-/**
- * The type of asset to create: launcher icon, menu icon, etc.
- */
-public enum AssetType {
- /** Launcher icon to be shown in the application list */
- LAUNCHER("Launcher Icons", "ic_launcher"), //$NON-NLS-2$
-
- /** Icons shown in the action bar */
- ACTIONBAR("Action Bar and Tab Icons (Android 3.0+)", "ic_action_%s"), //$NON-NLS-2$
-
- /** Icons shown in a notification message */
- NOTIFICATION("Notification Icons", "ic_stat_%s"), //$NON-NLS-2$
-
- /** Icons shown as part of tabs */
- TAB("Pre-Android 3.0 Tab Icons", "ic_tab_%s"), //$NON-NLS-2$
-
- /** Icons shown in menus */
- MENU("Pre-Android 3.0 Menu Icons", "ic_menu_%s"); //$NON-NLS-2$
-
- /** Display name to show to the user in the asset type selection list */
- private final String mDisplayName;
-
- /** Default asset name format */
- private String mDefaultNameFormat;
-
- AssetType(String displayName, String defaultNameFormat) {
- mDisplayName = displayName;
- mDefaultNameFormat = defaultNameFormat;
- }
-
- /**
- * Returns the display name of this asset type to show to the user in the
- * asset wizard selection page etc
- */
- String getDisplayName() {
- return mDisplayName;
- }
-
- /**
- * Returns the default format to use to suggest a name for the asset
- */
- String getDefaultNameFormat() {
- return mDefaultNameFormat;
- }
-
- /** Whether this asset type configures foreground scaling */
- boolean needsForegroundScaling() {
- return this == LAUNCHER;
- }
-
- /** Whether this asset type needs a shape parameter */
- boolean needsShape() {
- return this == LAUNCHER;
- }
-
- /** Whether this asset type needs foreground and background color parameters */
- boolean needsColors() {
- return this == LAUNCHER;
- }
-
- /** Whether this asset type needs an effects parameter */
- boolean needsEffects() {
- return this == LAUNCHER;
- }
-
- /** Whether this asset type needs a theme parameter */
- boolean needsTheme() {
- return this == ACTIONBAR;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/assetstudio/ChooseAssetTypePage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/assetstudio/ChooseAssetTypePage.java
deleted file mode 100644
index a26a22e49..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/assetstudio/ChooseAssetTypePage.java
+++ /dev/null
@@ -1,225 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.assetstudio;
-
-import com.android.ide.eclipse.adt.internal.project.ProjectChooserHelper;
-import com.android.ide.eclipse.adt.internal.project.ProjectChooserHelper.ProjectCombo;
-import com.android.ide.eclipse.adt.internal.resources.ResourceNameValidator;
-import com.android.resources.ResourceFolderType;
-
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-
-/** Page for choosing the type of asset to create, as well as the target project */
-public class ChooseAssetTypePage extends WizardPage implements SelectionListener, ModifyListener {
- private final CreateAssetSetWizardState mValues;
- private ProjectCombo mProjectButton;
- private Button mClipboardButton;
- private Text mNameText;
- private boolean mNameModified;
- private Label mResourceName;
-
- /**
- * Create the wizard.
- */
- public ChooseAssetTypePage(CreateAssetSetWizardState values) {
- super("chooseAssetTypePage");
- mValues = values;
- setTitle("Choose Icon Set Type");
- setDescription("Select the type of icon set to create:");
- }
-
- /**
- * Create contents of the wizard.
- *
- * @param parent the parent composite
- */
- @Override
- public void createControl(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
-
- setControl(container);
- container.setLayout(new GridLayout(3, false));
-
- for (AssetType type : AssetType.values()) {
- Button button = new Button(container, SWT.RADIO);
- button.setData(type);
- button.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 3, 1));
- button.setSelection(type == mValues.type);
- button.setText(type.getDisplayName());
- button.addSelectionListener(this);
- }
-
- Label separator = new Label(container, SWT.SEPARATOR | SWT.HORIZONTAL);
- GridData gdSeparator = new GridData(SWT.FILL, SWT.CENTER, false, false, 3, 1);
- gdSeparator.heightHint = 20;
- separator.setLayoutData(gdSeparator);
-
- Label projectLabel = new Label(container, SWT.NONE);
- projectLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- projectLabel.setText("Project:");
-
- ProjectChooserHelper helper =
- new ProjectChooserHelper(getShell(), null /* filter */);
- mProjectButton = new ProjectCombo(helper, container, mValues.project);
- mProjectButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
- mProjectButton.addSelectionListener(this);
-
- Label assetLabel = new Label(container, SWT.NONE);
- assetLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- assetLabel.setText("Icon Name:");
-
- mNameText = new Text(container, SWT.BORDER);
- mNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
- mNameText.addModifyListener(this);
-
- Label resourceLabel = new Label(container, SWT.NONE);
- resourceLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- resourceLabel.setText("Resource:");
-
- mResourceName = new Label(container, SWT.NONE);
- mResourceName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
-
- mClipboardButton = new Button(container, SWT.FLAT);
- mClipboardButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- mClipboardButton.setText("Copy Name to Clipboard");
-
- mClipboardButton.addSelectionListener(this);
-
- updateAssetType();
- validatePage();
- parent.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- mNameText.setFocus();
- }
- });
- }
-
- private void updateAssetType() {
- if (!mNameModified) {
- // Default name suggestion, possibly as a suffix, e.g. "ic_menu_<name>"
- String replace = "name";
- String suggestedName = String.format(mValues.type.getDefaultNameFormat(), replace);
- mNameText.setText(suggestedName);
- mValues.outputName = suggestedName;
-
- updateResourceLabel();
- mNameModified = false;
- int start = suggestedName.indexOf(replace);
- if (start != -1) {
- mNameText.setSelection(start, start + replace.length());
- } else {
- mNameText.selectAll();
- }
- } else {
- mNameText.selectAll();
- }
- }
-
- private void updateResourceLabel() {
- mResourceName.setText("@drawable/" + getOutputName()); //$NON-NLS-1$
- }
-
- @Override
- public boolean canFlipToNextPage() {
- return mValues.project != null;
- }
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- Object source = e.getSource();
- if (source == mProjectButton) {
- mValues.project = mProjectButton.getSelectedProject();
- validatePage();
- } else if (source == mClipboardButton) {
- Clipboard clipboard = new Clipboard(getShell().getDisplay());
- TextTransfer textTransfer = TextTransfer.getInstance();
- clipboard.setContents(
- new Object[] { mResourceName.getText() },
- new Transfer[] { textTransfer });
- clipboard.dispose();
- } else if (source instanceof Button) {
- // User selected a different asset type to be created
- Object data = ((Button) source).getData();
- if (data instanceof AssetType) {
- mValues.type = (AssetType) data;
- CreateAssetSetWizardState.sLastType = mValues.type;
- updateAssetType();
- }
- }
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
-
- @Override
- public void modifyText(ModifyEvent e) {
- Object source = e.getSource();
- if (source == mNameText) {
- mNameModified = true;
- mValues.outputName = mNameText.getText().trim();
- updateResourceLabel();
- }
-
- validatePage();
- }
-
- private String getOutputName() {
- return mNameText.getText().trim();
- }
-
- private void validatePage() {
- String error = null;
-
- if (mValues.project == null) {
- error = "Please select an Android project.";
- } else {
- String outputName = getOutputName();
- if (outputName == null || outputName.length() == 0) {
- error = "Please enter a name";
- } else {
- ResourceNameValidator validator =
- ResourceNameValidator.create(true, ResourceFolderType.DRAWABLE);
- error = validator.isValid(outputName);
- }
- }
-
- setPageComplete(error == null);
- if (error != null) {
- setMessage(error, IMessageProvider.ERROR);
- } else {
- setErrorMessage(null);
- setMessage(null);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/assetstudio/ConfigureAssetSetPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/assetstudio/ConfigureAssetSetPage.java
deleted file mode 100644
index 17336ad2d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/assetstudio/ConfigureAssetSetPage.java
+++ /dev/null
@@ -1,1251 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.assetstudio;
-
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.DEFAULT_LAUNCHER_ICON;
-import static java.awt.image.BufferedImage.TYPE_INT_ARGB;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.assetstudiolib.ActionBarIconGenerator;
-import com.android.assetstudiolib.GraphicGenerator;
-import com.android.assetstudiolib.GraphicGenerator.Shape;
-import com.android.assetstudiolib.LauncherIconGenerator;
-import com.android.assetstudiolib.MenuIconGenerator;
-import com.android.assetstudiolib.NotificationIconGenerator;
-import com.android.assetstudiolib.TabIconGenerator;
-import com.android.assetstudiolib.TextRenderUtil;
-import com.android.assetstudiolib.Util;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.assetstudio.CreateAssetSetWizardState.SourceType;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.ImageControl;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.ImageUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.SwtUtils;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.utils.Pair;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.ScrolledComposite;
-import org.eclipse.swt.custom.StackLayout;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.MouseAdapter;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.FontData;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.layout.RowData;
-import org.eclipse.swt.layout.RowLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.ColorDialog;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.FontDialog;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Slider;
-import org.eclipse.swt.widgets.Text;
-
-import java.awt.Paint;
-import java.awt.image.BufferedImage;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import javax.imageio.ImageIO;
-
-/**
- * This is normally page 2 of a Create New Asset Set wizard, unless we can offer actions
- * to create a specific asset type, in which case we skip page 1. On this page the user
- * gets to configure the parameters of the asset, and see a preview.
- */
-public class ConfigureAssetSetPage extends WizardPage implements SelectionListener,
- ModifyListener {
- private final CreateAssetSetWizardState mValues;
-
- private static final int PREVIEW_AREA_WIDTH = 144;
-
- private boolean mShown;
-
- private Composite mConfigurationArea;
- private Button mImageRadio;
- private Button mClipartRadio;
- private Button mTextRadio;
- private Button mPickImageButton;
- private Button mTrimCheckBox;
- private Slider mPaddingSlider;
- private Label mPercentLabel;
- private Button mCropRadio;
- private Button mCenterRadio;
- private Button mNoShapeRadio;
- private Button mSquareRadio;
- private Button mCircleButton;
- private Button mBgButton;
- private Button mFgButton;
- private Composite mPreviewArea;
- private Button mFontButton;
- private Composite mForegroundArea;
- private Composite mImageForm;
- private Composite mClipartForm;
- private Composite mTextForm;
- private Text mImagePathText;
-
- private boolean mTimerPending;
- private RGB mBgColor;
- private RGB mFgColor;
- private Text mText;
-
- /** Most recently set image path: preserved across wizard sessions */
- private static String sImagePath;
- private Button mChooseClipart;
- private Composite mClipartPreviewPanel;
- private Label mThemeLabel;
- private Composite mThemeComposite;
- private Button mHoloLightRadio;
- private Button mHoloDarkRadio;
- private Label mScalingLabel;
- private Composite mScalingComposite;
- private Label mShapeLabel;
- private Composite mShapeComposite;
- private Label mBgColorLabel;
- private Label mFgColorLabel;
-
- private boolean mIgnore;
- private SourceType mShowingType;
-
- /**
- * Create the wizard.
- *
- * @param values the wizard state
- */
- public ConfigureAssetSetPage(CreateAssetSetWizardState values) {
- super("configureAssetPage");
- mValues = values;
-
- setTitle("Configure Icon Set");
- setDescription("Configure the attributes of the icon set");
- }
-
- /**
- * Create contents of the wizard.
- *
- * @param parent the parent widget
- */
- @Override
- @SuppressWarnings("unused") // Don't warn about unassigned "new Label(.)": has side-effect
- public void createControl(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
-
- setControl(container);
- GridLayout glContainer = new GridLayout(2, false);
- glContainer.marginWidth = 0;
- glContainer.horizontalSpacing = 0;
- glContainer.marginHeight = 0;
- glContainer.verticalSpacing = 0;
- container.setLayout(glContainer);
-
- ScrolledComposite configurationScrollArea = new ScrolledComposite(container, SWT.V_SCROLL);
- configurationScrollArea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 2));
- configurationScrollArea.setExpandHorizontal(true);
- configurationScrollArea.setExpandVertical(true);
-
- mConfigurationArea = new Composite(configurationScrollArea, SWT.NONE);
- GridLayout glConfigurationArea = new GridLayout(3, false);
- glConfigurationArea.horizontalSpacing = 0;
- glConfigurationArea.marginRight = 15;
- glConfigurationArea.marginWidth = 0;
- glConfigurationArea.marginHeight = 0;
- mConfigurationArea.setLayout(glConfigurationArea);
-
- Label foregroundLabel = new Label(mConfigurationArea, SWT.NONE);
- foregroundLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- foregroundLabel.setText("Foreground:");
-
- Composite foregroundComposite = new Composite(mConfigurationArea, SWT.NONE);
- foregroundComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 2, 1));
- GridLayout glForegroundComposite = new GridLayout(5, false);
- glForegroundComposite.horizontalSpacing = 0;
- foregroundComposite.setLayout(glForegroundComposite);
-
- mImageRadio = new Button(foregroundComposite, SWT.FLAT | SWT.TOGGLE);
- mImageRadio.setSelection(false);
- mImageRadio.addSelectionListener(this);
- mImageRadio.setText("Image");
-
- mClipartRadio = new Button(foregroundComposite, SWT.FLAT | SWT.TOGGLE);
- mClipartRadio.setText("Clipart");
- mClipartRadio.addSelectionListener(this);
-
- mTextRadio = new Button(foregroundComposite, SWT.FLAT | SWT.TOGGLE);
- mTextRadio.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 3, 1));
- mTextRadio.setText("Text");
- mTextRadio.addSelectionListener(this);
- new Label(mConfigurationArea, SWT.NONE);
-
- mForegroundArea = new Composite(mConfigurationArea, SWT.NONE);
- mForegroundArea.setLayout(new StackLayout());
- mForegroundArea.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1));
-
- mImageForm = new Composite(mForegroundArea, SWT.NONE);
- mImageForm.setLayout(new GridLayout(3, false));
-
- Label fileLabel = new Label(mImageForm, SWT.NONE);
- fileLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- fileLabel.setText("Image File:");
-
- mImagePathText = new Text(mImageForm, SWT.BORDER);
- GridData pathLayoutData = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
- pathLayoutData.widthHint = 200;
- mImagePathText.setLayoutData(pathLayoutData);
- mImagePathText.addSelectionListener(this);
- mImagePathText.addModifyListener(this);
-
- mPickImageButton = new Button(mImageForm, SWT.FLAT);
- mPickImageButton.setText("Browse...");
- mPickImageButton.addSelectionListener(this);
-
- mClipartForm = new Composite(mForegroundArea, SWT.NONE);
- mClipartForm.setLayout(new GridLayout(2, false));
-
- mChooseClipart = new Button(mClipartForm, SWT.FLAT);
- mChooseClipart.setText("Choose...");
- mChooseClipart.addSelectionListener(this);
-
- mClipartPreviewPanel = new Composite(mClipartForm, SWT.NONE);
- RowLayout rlClipartPreviewPanel = new RowLayout(SWT.HORIZONTAL);
- rlClipartPreviewPanel.marginBottom = 0;
- rlClipartPreviewPanel.marginTop = 0;
- rlClipartPreviewPanel.center = true;
- mClipartPreviewPanel.setLayout(rlClipartPreviewPanel);
- mClipartPreviewPanel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
-
- mTextForm = new Composite(mForegroundArea, SWT.NONE);
- mTextForm.setLayout(new GridLayout(2, false));
-
- Label textLabel = new Label(mTextForm, SWT.NONE);
- textLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- textLabel.setText("Text:");
-
- mText = new Text(mTextForm, SWT.BORDER);
- mText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- mText.addModifyListener(this);
-
- Label fontLabel = new Label(mTextForm, SWT.NONE);
- fontLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- fontLabel.setText("Font:");
-
- mFontButton = new Button(mTextForm, SWT.FLAT);
- mFontButton.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1));
- mFontButton.addSelectionListener(this);
- mFontButton.setText("Choose Font...");
- new Label(mConfigurationArea, SWT.NONE);
-
- mTrimCheckBox = new Button(mConfigurationArea, SWT.CHECK);
- mTrimCheckBox.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
- mTrimCheckBox.setSelection(false);
- mTrimCheckBox.setText("Trim Surrounding Blank Space");
- mTrimCheckBox.addSelectionListener(this);
- new Label(mConfigurationArea, SWT.NONE);
-
- Label paddingLabel = new Label(mConfigurationArea, SWT.NONE);
- paddingLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
- paddingLabel.setText("Additional Padding:");
- new Label(mConfigurationArea, SWT.NONE);
-
- mPaddingSlider = new Slider(mConfigurationArea, SWT.NONE);
- mPaddingSlider.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- // This doesn't work right -- not sure why. For now just use a plain slider
- // and subtract 10 from it to get the real range.
- //mPaddingSlider.setValues(0, -10, 50, 0, 1, 10);
- //mPaddingSlider.setSelection(10 + 15);
- mPaddingSlider.addSelectionListener(this);
-
- mPercentLabel = new Label(mConfigurationArea, SWT.NONE);
- mPercentLabel.setText(" 15%"); // Enough available space for -10%
- mScalingLabel = new Label(mConfigurationArea, SWT.NONE);
- mScalingLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- mScalingLabel.setText("Foreground Scaling:");
-
- mScalingComposite = new Composite(mConfigurationArea, SWT.NONE);
- mScalingComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 2, 1));
- GridLayout gl_mScalingComposite = new GridLayout(5, false);
- gl_mScalingComposite.horizontalSpacing = 0;
- mScalingComposite.setLayout(gl_mScalingComposite);
-
- mCropRadio = new Button(mScalingComposite, SWT.FLAT | SWT.TOGGLE);
- mCropRadio.setSelection(true);
- mCropRadio.setText("Crop");
- mCropRadio.addSelectionListener(this);
-
- mCenterRadio = new Button(mScalingComposite, SWT.FLAT | SWT.TOGGLE);
- mCenterRadio.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 4, 1));
- mCenterRadio.setText("Center");
- mCenterRadio.addSelectionListener(this);
-
- mShapeLabel = new Label(mConfigurationArea, SWT.NONE);
- mShapeLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- mShapeLabel.setText("Shape");
-
- mShapeComposite = new Composite(mConfigurationArea, SWT.NONE);
- mShapeComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 2, 1));
- GridLayout gl_mShapeComposite = new GridLayout(6, false);
- gl_mShapeComposite.horizontalSpacing = 0;
- mShapeComposite.setLayout(gl_mShapeComposite);
-
- mNoShapeRadio = new Button(mShapeComposite, SWT.FLAT | SWT.TOGGLE);
- mNoShapeRadio.setText("None");
- mNoShapeRadio.addSelectionListener(this);
-
- mSquareRadio = new Button(mShapeComposite, SWT.FLAT | SWT.TOGGLE);
- mSquareRadio.setSelection(true);
- mSquareRadio.setText("Square");
- mSquareRadio.addSelectionListener(this);
-
- mCircleButton = new Button(mShapeComposite, SWT.FLAT | SWT.TOGGLE);
- mCircleButton.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 4, 1));
- mCircleButton.setText("Circle");
- mCircleButton.addSelectionListener(this);
-
- mThemeLabel = new Label(mConfigurationArea, SWT.NONE);
- mThemeLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- mThemeLabel.setText("Theme");
-
- mThemeComposite = new Composite(mConfigurationArea, SWT.NONE);
- mThemeComposite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
- GridLayout gl_mThemeComposite = new GridLayout(2, false);
- gl_mThemeComposite.horizontalSpacing = 0;
- mThemeComposite.setLayout(gl_mThemeComposite);
-
- mHoloLightRadio = new Button(mThemeComposite, SWT.FLAT | SWT.TOGGLE);
- mHoloLightRadio.setText("Holo Light");
- mHoloLightRadio.setSelection(true);
- mHoloLightRadio.addSelectionListener(this);
-
- mHoloDarkRadio = new Button(mThemeComposite, SWT.FLAT | SWT.TOGGLE);
- mHoloDarkRadio.setText("Holo Dark");
- mHoloDarkRadio.addSelectionListener(this);
-
- mBgColorLabel = new Label(mConfigurationArea, SWT.NONE);
- mBgColorLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- mBgColorLabel.setText("Background Color:");
-
- mBgButton = new Button(mConfigurationArea, SWT.FLAT);
- mBgButton.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
- mBgButton.addSelectionListener(this);
- mBgButton.setAlignment(SWT.CENTER);
-
- mFgColorLabel = new Label(mConfigurationArea, SWT.NONE);
- mFgColorLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- mFgColorLabel.setText("Foreground Color:");
-
- mFgButton = new Button(mConfigurationArea, SWT.FLAT);
- mFgButton.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
- mFgButton.setAlignment(SWT.CENTER);
- mFgButton.addSelectionListener(this);
-
- configurationScrollArea.setContent(mConfigurationArea);
- configurationScrollArea.setMinSize(mConfigurationArea.computeSize(SWT.DEFAULT,
- SWT.DEFAULT));
-
- Label previewLabel = new Label(container, SWT.NONE);
- previewLabel.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1));
- previewLabel.setText("Preview:");
-
- mPreviewArea = new Composite(container, SWT.BORDER);
-
- RowLayout rlPreviewAreaPreviewArea = new RowLayout(SWT.HORIZONTAL);
- rlPreviewAreaPreviewArea.wrap = true;
- rlPreviewAreaPreviewArea.pack = true;
- rlPreviewAreaPreviewArea.center = true;
- rlPreviewAreaPreviewArea.spacing = 0;
- rlPreviewAreaPreviewArea.marginBottom = 0;
- rlPreviewAreaPreviewArea.marginTop = 0;
- rlPreviewAreaPreviewArea.marginRight = 0;
- rlPreviewAreaPreviewArea.marginLeft = 0;
- mPreviewArea.setLayout(rlPreviewAreaPreviewArea);
- GridData gdMPreviewArea = new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1);
- gdMPreviewArea.widthHint = PREVIEW_AREA_WIDTH;
- mPreviewArea.setLayoutData(gdMPreviewArea);
-
- // Initial color
- Display display = parent.getDisplay();
- updateColor(display, mValues.background, true /*background*/);
- updateColor(display, mValues.foreground, false /*background*/);
-
- setSourceType(mValues.sourceType);
-
- new Label(mConfigurationArea, SWT.NONE);
- new Label(mConfigurationArea, SWT.NONE);
- new Label(mConfigurationArea, SWT.NONE);
-
- validatePage();
- }
-
- void configureAssetType(AssetType type) {
- if (mValues.sourceType != mShowingType) {
- mShowingType = mValues.sourceType;
- showGroup(type.needsForegroundScaling(), mScalingLabel, mScalingComposite);
- showGroup(type.needsShape(), mShapeLabel, mShapeComposite);
- showGroup(type.needsTheme(), mThemeLabel, mThemeComposite);
- showGroup(type.needsColors(), mBgColorLabel, mBgButton);
- showGroup(type.needsColors() && mValues.sourceType != SourceType.IMAGE,
- mFgColorLabel, mFgButton);
-
- Composite parent = mScalingLabel.getParent();
- parent.pack();
- parent.layout();
- }
- }
-
- private static void showGroup(boolean show, Control control1, Control control2) {
- showControl(show, control1);
- showControl(show, control2);
- }
-
- private static void showControl(boolean show, Control control) {
- Object data = control.getLayoutData();
- if (data instanceof GridData) {
- GridData gridData = (GridData) data;
- gridData.exclude = !show;
- }
- control.setVisible(show);
- }
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
-
- // We update the image selection here rather than in {@link #createControl} because
- // that method is called when the wizard is created, and we want to wait until the
- // user has chosen a project before attempting to look up the right default image to use
- if (visible) {
- mShown = true;
-
- // Clear out old previews - important if the user goes back to page one, changes
- // asset type and steps into page 2 - at that point we arrive here and we might
- // display the old previews for a brief period until the preview delay timer expires.
- for (Control c : mPreviewArea.getChildren()) {
- c.dispose();
- }
- mPreviewArea.layout(true);
-
- // Update asset type configuration: will show/hide parameter controls depending
- // on which asset type is chosen
- AssetType type = mValues.type;
- assert type != null;
- configureAssetType(type);
-
- // Initial image - use the most recently used image, or the default launcher
- // icon created in our default projects, if there
- if (mValues.imagePath != null) {
- sImagePath = mValues.imagePath.getPath();
- }
- if (sImagePath == null) {
- IProject project = mValues.project;
- if (project != null) {
- IResource icon = project.findMember("res/drawable-hdpi/icon.png"); //$NON-NLS-1$
- if (icon != null) {
- IWorkspaceRoot workspace = ResourcesPlugin.getWorkspace().getRoot();
- IPath workspacePath = workspace.getLocation();
- sImagePath = workspacePath.append(icon.getFullPath()).toOSString();
- }
- }
- }
- if (sImagePath != null) {
- mValues.imagePath = new File(sImagePath);
- mImagePathText.setText(sImagePath);
- }
-
- try {
- mIgnore = true;
-
- mTrimCheckBox.setSelection(mValues.trim);
-
- // This doesn't work right -- not sure why. For now just use a plain slider
- // and subtract 10 from it to get the real range.
- //mPaddingSlider.setValues(0, -10, 50, 0, 1, 10);
- //mPaddingSlider.setSelection(10 + 15);
- mPaddingSlider.setSelection(mValues.padding + 10);
- mPercentLabel.setText(Integer.toString(mValues.padding) + '%');
-
- if (mValues.imagePath != null) {
- mImagePathText.setText(mValues.imagePath.getPath());
- }
-
- if (mValues.text != null) {
- mText.setText(mValues.text);
- }
-
- setSourceType(mValues.sourceType);
-
- // Shape=NONE does not apply for notification icons; it's needed for API < 9
- if (mValues.shape == Shape.NONE && mValues.type == AssetType.NOTIFICATION) {
- mValues.shape = Shape.SQUARE;
- }
-
- setShape(mValues.shape);
- mNoShapeRadio.setEnabled(mValues.type != AssetType.NOTIFICATION);
-
- if (mValues.sourceType == SourceType.CLIPART
- && mValues.clipartName != null) {
- updateClipartPreview();
- }
-
- // Initial color
- Display display = mPreviewArea.getDisplay();
- //updateColor(display, new RGB(0xa4, 0xc6, 0x39), true /*background*/);
- updateColor(display, mValues.background, true /*background*/);
- updateColor(display, mValues.foreground, false /*background*/);
-
- updateTrimOptions();
- } finally {
- mIgnore = false;
- }
-
- validatePage();
-
- requestUpdatePreview(true /*quickly*/);
-
- if (mTextRadio.getSelection()) {
- mText.setFocus();
- }
- }
- }
-
- private void setSourceType(CreateAssetSetWizardState.SourceType sourceType) {
- if (sourceType == CreateAssetSetWizardState.SourceType.IMAGE) {
- chooseForegroundTab(mImageRadio, mImageForm);
- } else if (sourceType == CreateAssetSetWizardState.SourceType.CLIPART) {
- chooseForegroundTab(mClipartRadio, mClipartForm);
- mChooseClipart.setFocus();
- } else if (sourceType == CreateAssetSetWizardState.SourceType.TEXT) {
- updateFontLabel();
- chooseForegroundTab(mTextRadio, mTextForm);
- mText.setFocus();
- }
- }
-
- private void updateTrimOptions() {
- // Trimming and padding is not available for clipart images; padding etc is
- // predefined to work well with action bar icons
- if (mValues.sourceType == SourceType.CLIPART
- && mValues.type == AssetType.ACTIONBAR) {
- mTrimCheckBox.setEnabled(false);
- mPaddingSlider.setEnabled(false);
- mValues.trim = false;
- } else if (!mTrimCheckBox.isEnabled()) {
- mTrimCheckBox.setEnabled(true);
- mPaddingSlider.setEnabled(true);
- }
- }
-
- private boolean validatePage() {
- String error = null;
- //String warning = null;
-
- if (mImageRadio.getSelection()) {
- String path = mValues.imagePath != null ? mValues.imagePath.getPath() : null;
- if (path == null || path.length() == 0) {
- error = "Select an image";
- } else if (path.equals(DEFAULT_LAUNCHER_ICON)) {
- // Silent
- } else if (!(new File(path).exists())) {
- error = String.format("%1$s does not exist", path);
- } else {
- // Preserve across wizard sessions
- sImagePath = path;
- }
- } else if (mTextRadio.getSelection()) {
- if (mValues.text.length() == 0) {
- error = "Enter text";
- }
- } else {
- assert mClipartRadio.getSelection();
- if (mValues.clipartName == null) {
- error = "Select clip art";
- }
- }
-
- setPageComplete(error == null);
- if (error != null) {
- setMessage(error, IMessageProvider.ERROR);
- //} else if (warning != null) {
- // setMessage(warning, IMessageProvider.WARNING);
- } else {
- setErrorMessage(null);
- setMessage(null);
- }
-
- return error == null;
- }
-
- @Override
- public boolean isPageComplete() {
- // Force user to reach second page before hitting Finish
- return mShown;
- }
-
- // ---- Implements ModifyListener ----
-
- @Override
- public void modifyText(ModifyEvent e) {
- if (mIgnore) {
- return;
- }
-
- if (e.getSource() == mImagePathText) {
- mValues.imagePath = new File(mImagePathText.getText().trim());
- requestUpdatePreview(false);
- } else if (e.getSource() == mText) {
- mValues.text = mText.getText().trim();
- requestUpdatePreview(false);
- }
-
- validatePage();
- }
-
- // ---- Implements SelectionListener ----
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- // Nothing to do
- }
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (mIgnore) {
- return;
- }
-
- Object source = e.getSource();
- boolean updateQuickly = true;
-
- // Tabs
- if (source == mImageRadio) {
- mValues.sourceType = CreateAssetSetWizardState.SourceType.IMAGE;
- chooseForegroundTab((Button) source, mImageForm);
- configureAssetType(mValues.type);
- updateTrimOptions();
- } else if (source == mClipartRadio) {
- mValues.sourceType = CreateAssetSetWizardState.SourceType.CLIPART;
- chooseForegroundTab((Button) source, mClipartForm);
- configureAssetType(mValues.type);
- updateTrimOptions();
- } else if (source == mTextRadio) {
- mValues.sourceType = CreateAssetSetWizardState.SourceType.TEXT;
- updateFontLabel();
- chooseForegroundTab((Button) source, mTextForm);
- configureAssetType(mValues.type);
- mText.setFocus();
- updateTrimOptions();
- }
-
- // Choose image file
- if (source == mPickImageButton) {
- FileDialog dialog = new FileDialog(mPickImageButton.getShell(), SWT.OPEN);
-
- String curLocation = mImagePathText.getText().trim();
- if (!curLocation.isEmpty()) {
- dialog.setFilterPath(curLocation);
- }
-
- String file = dialog.open();
- if (file != null) {
- mValues.imagePath = new File(file);
- mImagePathText.setText(file);
- }
- }
-
- // Enforce Radio Groups
- if (source == mCropRadio) {
- mCropRadio.setSelection(true); // Ensure that you can't toggle it off
- mCenterRadio.setSelection(false);
- mValues.crop = true;
- } else if (source == mCenterRadio) {
- mCenterRadio.setSelection(true);
- mCropRadio.setSelection(false);
- mValues.crop = false;
- }
- if (source == mSquareRadio) {
- mValues.shape = GraphicGenerator.Shape.SQUARE;
- setShape(mValues.shape);
- } else if (source == mCircleButton) {
- mValues.shape = GraphicGenerator.Shape.CIRCLE;
- setShape(mValues.shape);
- } else if (source == mNoShapeRadio) {
- mValues.shape = GraphicGenerator.Shape.NONE;
- setShape(mValues.shape);
- }
-
- if (source == mTrimCheckBox) {
- mValues.trim = mTrimCheckBox.getSelection();
- }
-
- if (source == mHoloDarkRadio) {
- mHoloDarkRadio.setSelection(true);
- mHoloLightRadio.setSelection(false);
- mValues.holoDark = true;
- } else if (source == mHoloLightRadio) {
- mHoloLightRadio.setSelection(true);
- mHoloDarkRadio.setSelection(false);
- mValues.holoDark = false;
- }
-
- if (source == mChooseClipart) {
- MessageDialog dialog = new MessageDialog(mChooseClipart.getShell(),
- "Choose Clip Art",
- null, "Choose Clip Art Image:", MessageDialog.NONE,
- new String[] { "Close" }, 0) {
- @Override
- protected Control createCustomArea(Composite parent) {
- // Outer form which just establishes a width for the inner form which
- // wraps in a RowLayout
- Composite outer = new Composite(parent, SWT.NONE);
- GridLayout gridLayout = new GridLayout();
- outer.setLayout(gridLayout);
-
- Composite chooserForm = new Composite(outer, SWT.NONE);
- GridData gd = new GridData();
- gd.grabExcessVerticalSpace = true;
- gd.widthHint = 450;
- chooserForm.setLayoutData(gd);
- RowLayout clipartFormLayout = new RowLayout(SWT.HORIZONTAL);
- clipartFormLayout.center = true;
- clipartFormLayout.wrap = true;
- chooserForm.setLayout(clipartFormLayout);
-
- MouseAdapter clickListener = new MouseAdapter() {
- @Override
- public void mouseDown(MouseEvent event) {
- // Clicked on some of the sample art
- if (event.widget instanceof ImageControl) {
- ImageControl image = (ImageControl) event.widget;
- mValues.clipartName = (String) image.getData();
- close();
-
- updateClipartPreview();
- updatePreview();
- }
- }
- };
- Display display = chooserForm.getDisplay();
- Color hoverColor = display.getSystemColor(SWT.COLOR_RED);
- Iterator<String> clipartImages = GraphicGenerator.getClipartNames();
- while (clipartImages.hasNext()) {
- String name = clipartImages.next();
- try {
- BufferedImage icon = GraphicGenerator.getClipartIcon(name);
- if (icon != null) {
- Image swtImage = SwtUtils.convertToSwt(display, icon, true, -1);
- ImageControl img = new ImageControl(chooserForm,
- SWT.NONE, swtImage);
- img.setData(name);
- img.setHoverColor(hoverColor);
- img.addMouseListener(clickListener);
- }
- } catch (IOException e1) {
- AdtPlugin.log(e1, null);
- }
- }
- outer.pack();
- outer.layout();
- return outer;
- }
- };
- dialog.open();
- }
-
- if (source == mBgButton) {
- ColorDialog dlg = new ColorDialog(mBgButton.getShell());
- dlg.setRGB(mBgColor);
- dlg.setText("Choose a new Background Color");
- RGB rgb = dlg.open();
- if (rgb != null) {
- // Dispose the old color, create the
- // new one, and set into the label
- mValues.background = rgb;
- updateColor(mBgButton.getDisplay(), rgb, true /*background*/);
- }
- } else if (source == mFgButton) {
- ColorDialog dlg = new ColorDialog(mFgButton.getShell());
- dlg.setRGB(mFgColor);
- dlg.setText("Choose a new Foreground Color");
- RGB rgb = dlg.open();
- if (rgb != null) {
- // Dispose the old color, create the
- // new one, and set into the label
- mValues.foreground = rgb;
- updateColor(mFgButton.getDisplay(), rgb, false /*background*/);
- }
- }
-
- if (source == mFontButton) {
- FontDialog dialog = new FontDialog(mFontButton.getShell());
- FontData[] fontList;
- if (mFontButton.getData() == null) {
- fontList = mFontButton.getDisplay().getFontList(
- mValues.getTextFont().getFontName(), true /*scalable*/);
- } else {
- fontList = mFontButton.getFont().getFontData();
- }
- dialog.setFontList(fontList);
- FontData data = dialog.open();
- if (data != null) {
- Font font = new Font(mFontButton.getDisplay(), dialog.getFontList());
- mFontButton.setFont(font);
- mFontButton.setData(font);
-
- // Always use a large font for the rendering, even though user is typically
- // picking small font sizes in the font chooser
- //int dpi = mFontButton.getDisplay().getDPI().y;
- //int height = (int) Math.round(fontData.getHeight() * dpi / 72.0);
- int fontHeight = new TextRenderUtil.Options().fontSize;
- FontData fontData = font.getFontData()[0];
- int awtStyle = java.awt.Font.PLAIN;
- int swtStyle = fontData.getStyle();
- if ((swtStyle & SWT.ITALIC) != 0) {
- awtStyle |= java.awt.Font.ITALIC;
- }
- if ((swtStyle & SWT.BOLD) != 0) {
- awtStyle = java.awt.Font.BOLD;
- }
- mValues.setTextFont(new java.awt.Font(fontData.getName(), awtStyle, fontHeight));
-
- updateFontLabel();
- mFontButton.getParent().pack();
- }
- }
-
- if (source == mPaddingSlider) {
- mValues.padding = getPadding();
- mPercentLabel.setText(Integer.toString(getPadding()) + '%');
-
- // When dragging the slider, only do periodic updates
- updateQuickly = false;
- }
-
- requestUpdatePreview(updateQuickly);
- }
-
- @SuppressWarnings("unused") // SWT constructors have side effects and are not unused
- private void updateClipartPreview() {
- for (Control c : mClipartPreviewPanel.getChildren()) {
- c.dispose();
- }
- if (mClipartPreviewPanel.getChildren().length == 0) {
- try {
- BufferedImage icon = GraphicGenerator.getClipartIcon(
- mValues.clipartName);
- if (icon != null) {
- Display display = mClipartForm.getDisplay();
- Image swtImage = SwtUtils.convertToSwt(display, icon,
- true, -1);
- new ImageControl(mClipartPreviewPanel,
- SWT.NONE, swtImage);
- }
- } catch (IOException e1) {
- AdtPlugin.log(e1, null);
- }
- mClipartPreviewPanel.pack();
- mClipartPreviewPanel.layout();
- }
- }
-
- private void setShape(GraphicGenerator.Shape shape) {
- if (shape == GraphicGenerator.Shape.SQUARE) {
- mSquareRadio.setSelection(true);
- mCircleButton.setSelection(false);
- mNoShapeRadio.setSelection(false);
- } else if (shape == GraphicGenerator.Shape.CIRCLE) {
- mCircleButton.setSelection(true);
- mSquareRadio.setSelection(false);
- mNoShapeRadio.setSelection(false);
- } else if (shape == GraphicGenerator.Shape.NONE) {
- mNoShapeRadio.setSelection(true);
- mCircleButton.setSelection(false);
- mSquareRadio.setSelection(false);
- } else {
- assert false : shape;
- }
- }
-
- private void updateFontLabel() {
- mFontButton.setText(mValues.getTextFont().getFontName());
- }
-
- private int getPadding() {
- // Shifted - see comment for mPaddingSlider construction for an explanation
- return mPaddingSlider.getSelection() - 10;
- }
-
- private void chooseForegroundTab(Button newButton, Composite newArea) {
- if (newButton.getSelection()) {
- mImageRadio.setSelection(false);
- mClipartRadio.setSelection(false);
- mTextRadio.setSelection(false);
- newButton.setSelection(true);
- StackLayout stackLayout = (StackLayout) mForegroundArea.getLayout();
- stackLayout.topControl = newArea;
- mForegroundArea.layout();
- } else {
- // Treat it as a radio button: you can't click to turn it off, you have to
- // click on one of the other buttons
- newButton.setSelection(true);
- }
- }
-
- /**
- * Delay updates of the preview, to ensure that the SWT UI acts immediately (to handle
- * radio group selections etc).
- *
- * @param quickly if true, update the previews soon, otherwise schedule one a bit later
- */
- private void requestUpdatePreview(boolean quickly) {
- if (mTimerPending) {
- return;
- }
- mTimerPending = true;
-
- final Runnable timer = new Runnable() {
- @Override
- public void run() {
- mTimerPending = false;
- updatePreview();
- }
- };
-
- mPreviewArea.getDisplay().timerExec(quickly ? 10 : 250, timer);
- }
-
- private void updatePreview() {
- Display display = mPreviewArea.getDisplay();
-
- for (Control c : mPreviewArea.getChildren()) {
- c.dispose();
- }
-
- if (!validatePage()) {
- return;
- }
-
- Map<String, Map<String, BufferedImage>> map = generateImages(mValues,
- true /*previewOnly*/, this);
- for (Entry<String, Map<String, BufferedImage>> categoryEntry : map.entrySet()) {
- String category = categoryEntry.getKey();
- if (category.length() > 0) {
- Label nameLabel = new Label(mPreviewArea, SWT.NONE);
- nameLabel.setText(String.format("%1$s:", category));
- RowData rowData = new RowData();
- nameLabel.setLayoutData(rowData);
- // Ensure these get their own rows
- rowData.width = PREVIEW_AREA_WIDTH;
- }
-
- Map<String, BufferedImage> images = categoryEntry.getValue();
- for (Entry<String, BufferedImage> entry : images.entrySet()) {
- BufferedImage image = entry.getValue();
- Image swtImage = SwtUtils.convertToSwt(display, image, true, -1);
- if (swtImage != null) {
- @SuppressWarnings("unused") // Has side effect
- ImageControl imageControl = new ImageControl(mPreviewArea, SWT.NONE, swtImage);
- }
- }
- }
-
- mPreviewArea.layout(true);
- }
-
- /**
- * Generate images using the given wizard state
- *
- * @param mValues the state to use
- * @param previewOnly whether we are only generating previews
- * @param page if non null, a wizard page to write error messages to
- * @return a map of image objects
- */
- public static Map<String, Map<String, BufferedImage>> generateImages(
- @NonNull CreateAssetSetWizardState mValues,
- boolean previewOnly,
- @Nullable WizardPage page) {
- // Map of ids to images: Preserve insertion order (the densities)
- Map<String, Map<String, BufferedImage>> categoryMap =
- new LinkedHashMap<String, Map<String, BufferedImage>>();
-
- AssetType type = mValues.type;
- boolean trim = mValues.trim;
-
- BufferedImage sourceImage = null;
- switch (mValues.sourceType) {
- case IMAGE: {
- // Load the image
- // TODO: Only do this when the source image type is image
- String path = mValues.imagePath != null ? mValues.imagePath.getPath() : "";
- if (path.length() == 0) {
- if (page != null) {
- page.setErrorMessage("Enter a filename");
- }
- return Collections.emptyMap();
- }
- if (!path.equals(DEFAULT_LAUNCHER_ICON)) {
- File file = new File(path);
- if (!file.isFile()) {
- if (page != null) {
- page.setErrorMessage(String.format("%1$s does not exist", file.getPath()));
- }
- return Collections.emptyMap();
- }
- }
-
- if (page != null) {
- page.setErrorMessage(null);
- }
- try {
- sourceImage = mValues.getCachedImage(path, false);
- if (sourceImage != null) {
- if (trim) {
- sourceImage = ImageUtils.cropBlank(sourceImage, null, TYPE_INT_ARGB);
- }
- if (mValues.padding != 0) {
- sourceImage = Util.paddedImage(sourceImage, mValues.padding);
- }
- }
- } catch (IOException ioe) {
- if (page != null) {
- page.setErrorMessage(ioe.getLocalizedMessage());
- }
- }
- break;
- }
- case CLIPART: {
- try {
- sourceImage = GraphicGenerator.getClipartImage(mValues.clipartName);
-
- boolean isActionBar = mValues.type == AssetType.ACTIONBAR;
- if (trim && !isActionBar) {
- sourceImage = ImageUtils.cropBlank(sourceImage, null, TYPE_INT_ARGB);
- }
-
- if (type.needsColors()) {
- RGB fg = mValues.foreground;
- int color = 0xFF000000 | (fg.red << 16) | (fg.green << 8) | fg.blue;
- Paint paint = new java.awt.Color(color);
- sourceImage = Util.filledImage(sourceImage, paint);
- }
-
- int padding = mValues.padding;
- if (padding != 0 && !isActionBar) {
- sourceImage = Util.paddedImage(sourceImage, padding);
- }
- } catch (IOException e) {
- AdtPlugin.log(e, null);
- return categoryMap;
- }
- break;
- }
- case TEXT: {
- String text = mValues.text;
- TextRenderUtil.Options options = new TextRenderUtil.Options();
- options.font = mValues.getTextFont();
- int color;
- if (type.needsColors()) {
- RGB fg = mValues.foreground;
- color = 0xFF000000 | (fg.red << 16) | (fg.green << 8) | fg.blue;
- } else {
- color = 0xFFFFFFFF;
- }
- options.foregroundColor = color;
- sourceImage = TextRenderUtil.renderTextImage(text, mValues.padding, options);
-
- if (trim) {
- sourceImage = ImageUtils.cropBlank(sourceImage, null, TYPE_INT_ARGB);
- }
-
- int padding = mValues.padding;
- if (padding != 0) {
- sourceImage = Util.paddedImage(sourceImage, padding);
- }
- break;
- }
- }
-
- GraphicGenerator generator = null;
- GraphicGenerator.Options options = null;
- switch (type) {
- case LAUNCHER: {
- generator = new LauncherIconGenerator();
- LauncherIconGenerator.LauncherOptions launcherOptions =
- new LauncherIconGenerator.LauncherOptions();
- launcherOptions.shape = mValues.shape;
- launcherOptions.crop = mValues.crop;
- launcherOptions.style = GraphicGenerator.Style.SIMPLE;
-
- RGB bg = mValues.background;
- int color = (bg.red << 16) | (bg.green << 8) | bg.blue;
- launcherOptions.backgroundColor = color;
- // Flag which tells the generator iterator to include a web graphic
- launcherOptions.isWebGraphic = !previewOnly;
- options = launcherOptions;
-
- break;
- }
- case MENU:
- generator = new MenuIconGenerator();
- options = new GraphicGenerator.Options();
- break;
- case ACTIONBAR: {
- generator = new ActionBarIconGenerator();
- ActionBarIconGenerator.ActionBarOptions actionBarOptions =
- new ActionBarIconGenerator.ActionBarOptions();
- actionBarOptions.theme = mValues.holoDark
- ? ActionBarIconGenerator.Theme.HOLO_DARK
- : ActionBarIconGenerator.Theme.HOLO_LIGHT;
- actionBarOptions.sourceIsClipart = (mValues.sourceType == SourceType.CLIPART);
-
- options = actionBarOptions;
- break;
- }
- case NOTIFICATION: {
- generator = new NotificationIconGenerator();
- options = new NotificationIconGenerator.NotificationOptions();
- break;
- }
- case TAB:
- generator = new TabIconGenerator();
- options = new TabIconGenerator.TabOptions();
- break;
- default:
- AdtPlugin.log(IStatus.ERROR, "Unsupported asset type: %1$s", type);
- return categoryMap;
- }
-
- options.sourceImage = sourceImage;
-
- IProject project = mValues.project;
- if (mValues.minSdk != -1) {
- options.minSdk = mValues.minSdk;
- } else {
- Pair<Integer, Integer> v = ManifestInfo.computeSdkVersions(project);
- options.minSdk = v.getFirst();
- }
-
- String baseName = mValues.outputName;
- generator.generate(null, categoryMap, mValues, options, baseName);
-
- return categoryMap;
- }
-
- /**
- * Generate custom icons into the project based on the asset studio wizard
- * state
- *
- * @param newProject the project to write into
- * @param values the wizard state to read configuration settings from
- * @param previewOnly whether we are only generating a preview. For example,
- * the launcher icons won't generate a huge 512x512 web graphic
- * in preview mode
- * @param page a wizard page to write error messages to, or null
- */
- public static void generateIcons(final IProject newProject,
- @NonNull CreateAssetSetWizardState values,
- boolean previewOnly,
- @Nullable WizardPage page) {
- // Generate the custom icons
- Map<String, Map<String, BufferedImage>> categories = generateImages(values,
- false /*previewOnly*/, page);
- for (Map<String, BufferedImage> previews : categories.values()) {
- for (Map.Entry<String, BufferedImage> entry : previews.entrySet()) {
- String relativePath = entry.getKey();
- IPath dest = new Path(relativePath);
- IFile file = newProject.getFile(dest);
-
- // In case template already created icons (should remove that)
- // remove them first
- if (file.exists()) {
- try {
- file.delete(true, new NullProgressMonitor());
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- }
- AdtUtils.createWsParentDirectory(file.getParent());
- BufferedImage image = entry.getValue();
-
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- try {
- ImageIO.write(image, "PNG", stream); //$NON-NLS-1$
- byte[] bytes = stream.toByteArray();
- InputStream is = new ByteArrayInputStream(bytes);
- file.create(is, true /*force*/, null /*progress*/);
- } catch (IOException e) {
- AdtPlugin.log(e, null);
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
-
- try {
- file.getParent().refreshLocal(1, new NullProgressMonitor());
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- }
- }
- }
-
- private void updateColor(Display display, RGB color, boolean isBackground) {
- // Button.setBackgroundColor does not work (at least not on OSX) so
- // we instead have to use Button.setImage with an image of the given
- // color
- BufferedImage coloredImage = ImageUtils.createColoredImage(60, 20, color);
- Image image = SwtUtils.convertToSwt(display, coloredImage, false, -1);
-
- if (isBackground) {
- mBgColor = color;
- mBgButton.setImage(image);
- } else {
- mFgColor = color;
- mFgButton.setImage(image);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/assetstudio/CreateAssetSetWizard.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/assetstudio/CreateAssetSetWizard.java
deleted file mode 100644
index 6b1001253..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/assetstudio/CreateAssetSetWizard.java
+++ /dev/null
@@ -1,312 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.assetstudio;
-
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.utils.Pair;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.ui.JavaUI;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.TreePath;
-import org.eclipse.jface.viewers.TreeSelection;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.swt.SWT;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.INewWizard;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.part.FileEditorInput;
-
-import java.awt.image.BufferedImage;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
-import javax.imageio.ImageIO;
-
-/**
- * Wizard for creating a new icon set
- */
-public class CreateAssetSetWizard extends Wizard implements INewWizard {
- private ChooseAssetTypePage mChooseAssetPage;
- private ConfigureAssetSetPage mConfigureAssetPage;
- private IProject mInitialProject;
- private List<IResource> mCreatedFiles;
- private CreateAssetSetWizardState mValues = new CreateAssetSetWizardState();
-
- /** Creates a new asset set wizard */
- public CreateAssetSetWizard() {
- setWindowTitle("Create Asset Set");
- }
-
- @Override
- public void addPages() {
- mValues.project = mInitialProject;
-
- mChooseAssetPage = new ChooseAssetTypePage(mValues);
- mConfigureAssetPage = new ConfigureAssetSetPage(mValues);
-
- addPage(mChooseAssetPage);
- addPage(mConfigureAssetPage);
- }
-
- @Override
- public boolean performFinish() {
- Map<String, Map<String, BufferedImage>> categories =
- ConfigureAssetSetPage.generateImages(mValues, false, null);
-
- IProject project = mValues.project;
-
- // Write out the images into the project
- boolean yesToAll = false;
- mCreatedFiles = new ArrayList<IResource>();
-
- for (Map<String, BufferedImage> previews : categories.values()) {
- for (Map.Entry<String, BufferedImage> entry : previews.entrySet()) {
- String relativePath = entry.getKey();
- IPath dest = new Path(relativePath);
- IFile file = project.getFile(dest);
- if (file.exists()) {
- // Warn that the file already exists and ask the user what to do
- if (!yesToAll) {
- MessageDialog dialog = new MessageDialog(null, "File Already Exists", null,
- String.format(
- "%1$s already exists.\nWould you like to replace it?",
- file.getProjectRelativePath().toOSString()),
- MessageDialog.QUESTION, new String[] {
- // Yes will be moved to the end because it's the default
- "Yes", "No", "Cancel", "Yes to All"
- }, 0);
- int result = dialog.open();
- switch (result) {
- case 0:
- // Yes
- break;
- case 3:
- // Yes to all
- yesToAll = true;
- break;
- case 1:
- // No
- continue;
- case SWT.DEFAULT:
- case 2:
- // Cancel
- return false;
- }
- }
-
- try {
- file.delete(true, new NullProgressMonitor());
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- }
-
- AdtUtils.createWsParentDirectory(file.getParent());
- BufferedImage image = entry.getValue();
-
- ByteArrayOutputStream stream = new ByteArrayOutputStream();
- try {
- ImageIO.write(image, "PNG", stream); //$NON-NLS-1$
- byte[] bytes = stream.toByteArray();
- InputStream is = new ByteArrayInputStream(bytes);
- file.create(is, true /*force*/, null /*progress*/);
- mCreatedFiles.add(file);
- } catch (IOException e) {
- AdtPlugin.log(e, null);
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
-
- try {
- file.getParent().refreshLocal(1, new NullProgressMonitor());
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- }
- }
-
- // Finally select the files themselves
- selectFiles(project, mCreatedFiles);
-
- return true;
- }
-
- private void selectFiles(IProject project, List<? extends IResource> createdFiles) {
- // Attempt to select the newly created files in the Package Explorer
- IWorkbench workbench = AdtPlugin.getDefault().getWorkbench();
- IWorkbenchPage page = workbench.getActiveWorkbenchWindow().getActivePage();
- IViewPart viewPart = page.findView(JavaUI.ID_PACKAGES);
- if (viewPart != null) {
- IWorkbenchPartSite site = viewPart.getSite();
- IJavaProject javaProject = null;
- try {
- javaProject = BaseProjectHelper.getJavaProject(project);
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- final ISelectionProvider provider = site.getSelectionProvider();
- if (provider != null) {
- List<TreePath> pathList = new ArrayList<TreePath>();
- for (IResource file : createdFiles) {
- // Create a TreePath for the given file,
- // which should be the JavaProject, followed by the folders down to
- // the final file.
- List<Object> segments = new ArrayList<Object>();
- segments.add(file);
- IContainer folder = file.getParent();
- if (folder != null && !(folder instanceof IProject)) {
- segments.add(folder);
- // res folder
- folder = folder.getParent();
- if (folder != null && !(folder instanceof IProject)) {
- segments.add(folder);
- }
- }
- // project
- segments.add(javaProject);
-
- Collections.reverse(segments);
- TreePath path = new TreePath(segments.toArray());
- pathList.add(path);
-
- // IDEA: Maybe normalize the files backwards (IFile objects aren't unique)
- // by maybe using the package explorer icons instead
- }
-
- TreePath[] paths = pathList.toArray(new TreePath[pathList.size()]);
- final TreeSelection selection = new TreeSelection(paths);
-
- provider.setSelection(selection);
-
- // Workaround: The above doesn't always work; it will frequently select
- // some siblings of the real files. I've tried a number of workarounds:
- // normalizing the IFile objects by looking up the canonical ones via
- // their relative paths from the project; deferring execution with
- // Display.asyncRun; first calling select on the parents, etc.
- // However, it turns out a simple workaround works best: Calling this
- // method TWICE. The first call seems to expand all the necessary parents,
- // and the second call ensures that the correct children are selected!
- provider.setSelection(selection);
-
- viewPart.setFocus();
- }
- }
- }
-
- /** Sets the initial project to be used by the wizard */
- void setProject(IProject project) {
- mInitialProject = project;
- mValues.project = project;
- }
-
- @Override
- public void init(IWorkbench workbench, IStructuredSelection selection) {
- setHelpAvailable(false);
-
- mInitialProject = guessProject(selection);
- mValues.project = mInitialProject;
- }
-
- private IProject guessProject(IStructuredSelection selection) {
- if (selection == null) {
- return null;
- }
-
- for (Object element : selection.toList()) {
- if (element instanceof IAdaptable) {
- IResource res = (IResource) ((IAdaptable) element).getAdapter(IResource.class);
- IProject project = res != null ? res.getProject() : null;
-
- // Is this an Android project?
- try {
- if (project == null || !project.hasNature(AdtConstants.NATURE_DEFAULT)) {
- continue;
- }
- } catch (CoreException e) {
- // checking the nature failed, ignore this resource
- continue;
- }
-
- return project;
- } else if (element instanceof Pair<?, ?>) {
- // Pair of Project/String
- @SuppressWarnings("unchecked")
- Pair<IProject, String> pair = (Pair<IProject, String>) element;
- return pair.getFirst();
- }
- }
-
- // Try to figure out the project from the active editor
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- if (window != null) {
- IWorkbenchPage page = window.getActivePage();
- if (page != null) {
- IEditorPart activeEditor = page.getActiveEditor();
- if (activeEditor instanceof AndroidXmlEditor) {
- Object input = ((AndroidXmlEditor) activeEditor).getEditorInput();
- if (input instanceof FileEditorInput) {
- FileEditorInput fileInput = (FileEditorInput) input;
- return fileInput.getFile().getProject();
- }
- }
- }
- }
-
- IJavaProject[] projects = AdtUtils.getOpenAndroidProjects();
- if (projects != null && projects.length == 1) {
- return projects[0].getProject();
- }
-
- return null;
- }
-
- /**
- * Returns the list of files created by the wizard. This method will return
- * null if {@link #performFinish()} has not yet been called.
- *
- * @return a list of files created by the wizard, or null
- */
- List<IResource> getCreatedFiles() {
- return mCreatedFiles;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/assetstudio/CreateAssetSetWizardState.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/assetstudio/CreateAssetSetWizardState.java
deleted file mode 100644
index d3a0f42e9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/assetstudio/CreateAssetSetWizardState.java
+++ /dev/null
@@ -1,258 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.assetstudio;
-
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.DEFAULT_LAUNCHER_ICON;
-
-import com.android.annotations.NonNull;
-import com.android.assetstudiolib.GraphicGenerator;
-import com.android.assetstudiolib.GraphicGenerator.Shape;
-import com.android.assetstudiolib.GraphicGeneratorContext;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.wizards.templates.TemplateManager;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.swt.graphics.RGB;
-
-import java.awt.Font;
-import java.awt.GraphicsEnvironment;
-import java.awt.image.BufferedImage;
-import java.io.File;
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.imageio.ImageIO;
-
-/**
- * Value object for the AssetStudio wizard. These values are both set by the
- * wizard as well as read by the wizard initially, so passing in a configured
- * {@link CreateAssetSetWizardState} to the icon generator is possible.
- */
-public class CreateAssetSetWizardState implements GraphicGeneratorContext {
- /**
- * The type of asset being created. This field is static such that when you
- * bring up the wizard repeatedly (for example to create multiple
- * notification icons) you don't have to keep selecting the same type over
- * and over.
- */
- public static AssetType sLastType = AssetType.LAUNCHER;
-
- /** The type of asset to be created */
- public AssetType type = sLastType;
-
- /** The base name to use for the created icons */
- public String outputName;
-
- /** The minimum SDK being targeted */
- public int minSdk = -1;
-
- /** The project to create the icons into */
- public IProject project;
-
- /** Whether empty space around the source image should be trimmed */
- public boolean trim = true;
-
- /** The type of source the icon is being created from */
- public SourceType sourceType = SourceType.TEXT;
-
- /** If {@link #sourceType} is a {@link SourceType#CLIPART}, the name of the clipart image */
- public String clipartName;
-
- /** If {@link #sourceType} is a {@link SourceType#IMAGE}, the path to the input image */
- public File imagePath;
-
- /** If {@link #sourceType} is a {@link SourceType#TEXT}, the text to render */
- public String text = "aA";
-
- /** The amount of padding to add around the source image */
- public int padding = 15;
-
- /** The background shape */
- public Shape shape = Shape.SQUARE;
-
- /** Whether the image should be cropped */
- public boolean crop;
-
- /** Whether to use Holo Dark for action bar icons */
- public boolean holoDark;
-
- /** The background color to use for the shape (unless the shape is {@link Shape#NONE} */
- public RGB background = new RGB(0xff, 0x00, 0x00);
-
- /** The background color to use for the text or clipart (unless shape is {@link Shape#NONE} */
- public RGB foreground = new RGB(0x00, 0x00, 0x00);
-
- /** If {@link #sourceType} is a {@link SourceType#TEXT}, the font of the text to render */
- private Font mTextFont;
-
- private Map<String, BufferedImage> mImageCache = null;
-
- /**
- * Gets the text font to be used for text rendering if the
- * {@link #sourceType} is a {@link SourceType#TEXT}
- *
- * @return the text font
- */
- @NonNull
- public Font getTextFont() {
- if (mTextFont == null) {
- GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
- String[] fontNames = env.getAvailableFontFamilyNames();
- for (String familyName : fontNames) {
- if (familyName.equals("Helvetica")) {
- mTextFont = new java.awt.Font(familyName, java.awt.Font.BOLD, 512);
- break;
- }
- }
- if (mTextFont == null) {
- for (String familyName : fontNames) {
- if (familyName.equals("Arial")) {
- mTextFont = new java.awt.Font(familyName, java.awt.Font.BOLD, 512);
- break;
- }
- }
-
- if (mTextFont == null) {
- mTextFont = new java.awt.Font("SansSerif", java.awt.Font.BOLD, 512);
- }
- }
- }
-
- return mTextFont;
- }
-
- /**
- * Sets the text font to be used for text rendering if the
- * {@link #sourceType} is a {@link SourceType#TEXT}
- *
- * @param textFont the font to use
- */
- public void setTextFont(@NonNull Font textFont) {
- mTextFont = textFont;
- }
-
- /** Types of sources that the asset studio can use to generate icons from */
- public enum SourceType {
- /** Generate the icon using the image pointed to by {@link #imagePath} */
- IMAGE,
-
- /** Generate the icon using the clipart named by {@link #clipartName} */
- CLIPART,
-
- /** Generate the icon using the text in {@link #text} */
- TEXT
- }
-
- // ---- Implements GraphicGeneratorContext ----
-
- @Override
- public BufferedImage loadImageResource(String relativeName) {
- try {
- return getCachedImage(relativeName, true);
- } catch (IOException e) {
- AdtPlugin.log(e, null);
- return null;
- }
- }
-
- BufferedImage getCachedImage(String path, boolean isPluginRelative)
- throws IOException {
- BufferedImage image = mImageCache != null ? mImageCache.get(path) : null;
- if (image == null) {
- image = getImage(path, isPluginRelative);
- if (mImageCache == null) {
- mImageCache = new HashMap<String, BufferedImage>();
- }
- mImageCache.put(path, image);
- }
-
- return image;
- }
-
- @NonNull
- static BufferedImage getImage(@NonNull String path, boolean isPluginRelative)
- throws IOException {
- BufferedImage image = null;
- if (isPluginRelative) {
- image = GraphicGenerator.getStencilImage(path);
- } else {
- if (path.equals(DEFAULT_LAUNCHER_ICON)) {
- File file = TemplateManager.getTemplateLocation(
- "projects/NewAndroidApplication/root/res/drawable-xhdpi/ic_launcher.png"); //$NON-NLS-1$
- if (file != null) {
- path = file.getPath();
- } else {
- image = GraphicGenerator.getStencilImage("user.png");
- }
- }
-
- File file = new File(path);
-
- // Requires Batik
- //if (file.getName().endsWith(DOT_SVG)) {
- // image = loadSvgImage(file);
- //}
-
- if (image == null) {
- image = ImageIO.read(file);
- }
- }
-
- if (image == null) {
- image = new BufferedImage(1,1, BufferedImage.TYPE_INT_ARGB);
- }
-
- return image;
- }
-
- // This requires Batik for SVG rendering
- //
- //public static BufferedImage loadSvgImage(File file) {
- // BufferedImageTranscoder transcoder = new BufferedImageTranscoder();
- //
- // String svgURI = file.toURI().toString();
- // TranscoderInput input = new TranscoderInput(svgURI);
- //
- // try {
- // transcoder.transcode(input, null);
- // } catch (TranscoderException e) {
- // e.printStackTrace();
- // return null;
- // }
- //
- // return transcoder.decodedImage;
- //}
- //
- ///**
- // * A dummy implementation of an {@link ImageTranscoder} that simply stores the {@link
- // * BufferedImage} generated by the SVG library.
- // */
- //private static class BufferedImageTranscoder extends ImageTranscoder {
- // public BufferedImage decodedImage;
- //
- // @Override
- // public BufferedImage createImage(int w, int h) {
- // return new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
- // }
- //
- // @Override
- // public void writeImage(BufferedImage image, TranscoderOutput output)
- // throws TranscoderException {
- // this.decodedImage = image;
- // }
- //}
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/assetstudio/OpenCreateAssetSetWizardAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/assetstudio/OpenCreateAssetSetWizardAction.java
deleted file mode 100644
index 09cc32512..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/assetstudio/OpenCreateAssetSetWizardAction.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.assetstudio;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jdt.ui.actions.AbstractOpenWizardAction;
-import org.eclipse.ui.INewWizard;
-
-import java.util.List;
-
-/** An action for opening the Create Icon Set wizard */
-public class OpenCreateAssetSetWizardAction extends AbstractOpenWizardAction {
- private IProject mProject;
- private CreateAssetSetWizard mWizard;
-
- /**
- * Creates a new {@link #OpenCreateAssetSetWizardAction} instance
- *
- * @param project the initial project to associate with the wizard
- */
- public OpenCreateAssetSetWizardAction(IProject project) {
- mProject = project;
- }
-
-
- @Override
- protected INewWizard createWizard() throws CoreException {
- mWizard = new CreateAssetSetWizard();
- mWizard.setProject(mProject);
- return mWizard;
- }
-
- /**
- * Returns the list of files created by the wizard. Must only be called
- * after this action's {@link #run()} method has been called. May return
- * null if the user cancels out of the wizard.
- *
- * @return a list of files created by the wizard, or null
- */
- public List<IResource> getCreatedFiles() {
- return mWizard.getCreatedFiles();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/AaptExecException.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/AaptExecException.java
deleted file mode 100644
index 23b1baa92..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/AaptExecException.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build;
-
-/**
- * Exception thrown when the execution of aapt fails.
- *
- */
-public final class AaptExecException extends Exception {
- private static final long serialVersionUID = 1L;
-
- AaptExecException(String message, Throwable cause) {
- super(message, cause);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/AaptParser.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/AaptParser.java
deleted file mode 100644
index 1f17fb7c6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/AaptParser.java
+++ /dev/null
@@ -1,783 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build;
-
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.FindReplaceDocumentAdapter;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.ui.editors.text.TextFileDocumentProvider;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-
-import java.io.File;
-import java.util.List;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public final class AaptParser {
-
- // TODO: rename the pattern to something that makes sense + javadoc comments.
- /**
- * Single line aapt warning for skipping files.<br>
- * " (skipping hidden file '&lt;file path&gt;'"
- */
- private final static Pattern sPattern0Line1 = Pattern.compile(
- "^\\s+\\(skipping hidden file\\s'(.*)'\\)$"); //$NON-NLS-1$
-
- /**
- * First line of dual line aapt error.<br>
- * "ERROR at line &lt;line&gt;: &lt;error&gt;"<br>
- * " (Occurred while parsing &lt;path&gt;)"
- */
- private final static Pattern sPattern1Line1 = Pattern.compile(
- "^ERROR\\s+at\\s+line\\s+(\\d+):\\s+(.*)$"); //$NON-NLS-1$
- /**
- * Second line of dual line aapt error.<br>
- * "ERROR at line &lt;line&gt;: &lt;error&gt;"<br>
- * " (Occurred while parsing &lt;path&gt;)"<br>
- * @see #sPattern1Line1
- */
- private final static Pattern sPattern1Line2 = Pattern.compile(
- "^\\s+\\(Occurred while parsing\\s+(.*)\\)$"); //$NON-NLS-1$
- /**
- * First line of dual line aapt error.<br>
- * "ERROR: &lt;error&gt;"<br>
- * "Defined at file &lt;path&gt; line &lt;line&gt;"
- */
- private final static Pattern sPattern2Line1 = Pattern.compile(
- "^ERROR:\\s+(.+)$"); //$NON-NLS-1$
- /**
- * Second line of dual line aapt error.<br>
- * "ERROR: &lt;error&gt;"<br>
- * "Defined at file &lt;path&gt; line &lt;line&gt;"<br>
- * @see #sPattern2Line1
- */
- private final static Pattern sPattern2Line2 = Pattern.compile(
- "Defined\\s+at\\s+file\\s+(.+)\\s+line\\s+(\\d+)"); //$NON-NLS-1$
- /**
- * Single line aapt error<br>
- * "&lt;path&gt; line &lt;line&gt;: &lt;error&gt;"
- */
- private final static Pattern sPattern3Line1 = Pattern.compile(
- "^(.+)\\sline\\s(\\d+):\\s(.+)$"); //$NON-NLS-1$
- /**
- * First line of dual line aapt error.<br>
- * "ERROR parsing XML file &lt;path&gt;"<br>
- * "&lt;error&gt; at line &lt;line&gt;"
- */
- private final static Pattern sPattern4Line1 = Pattern.compile(
- "^Error\\s+parsing\\s+XML\\s+file\\s(.+)$"); //$NON-NLS-1$
- /**
- * Second line of dual line aapt error.<br>
- * "ERROR parsing XML file &lt;path&gt;"<br>
- * "&lt;error&gt; at line &lt;line&gt;"<br>
- * @see #sPattern4Line1
- */
- private final static Pattern sPattern4Line2 = Pattern.compile(
- "^(.+)\\s+at\\s+line\\s+(\\d+)$"); //$NON-NLS-1$
-
- /**
- * Single line aapt warning<br>
- * "&lt;path&gt;:&lt;line&gt;: &lt;error&gt;"
- */
- private final static Pattern sPattern5Line1 = Pattern.compile(
- "^(.+?):(\\d+):\\s+WARNING:(.+)$"); //$NON-NLS-1$
-
- /**
- * Single line aapt error<br>
- * "&lt;path&gt;:&lt;line&gt;: &lt;error&gt;"
- */
- private final static Pattern sPattern6Line1 = Pattern.compile(
- "^(.+?):(\\d+):\\s+(.+)$"); //$NON-NLS-1$
-
- /**
- * 4 line aapt error<br>
- * "ERROR: 9-path image &lt;path&gt; malformed"<br>
- * Line 2 and 3 are taken as-is while line 4 is ignored (it repeats with<br>
- * 'ERROR: failure processing &lt;path&gt;)
- */
- private final static Pattern sPattern7Line1 = Pattern.compile(
- "^ERROR:\\s+9-patch\\s+image\\s+(.+)\\s+malformed\\.$"); //$NON-NLS-1$
-
- private final static Pattern sPattern8Line1 = Pattern.compile(
- "^(invalid resource directory name): (.*)$"); //$NON-NLS-1$
-
- /**
- * Portion of the error message which states the context in which the error occurred,
- * such as which property was being processed and what the string value was that
- * caused the error.
- * <p>
- * Example:
- * error: No resource found that matches the given name (at 'text' with value '@string/foo')
- */
- private static final Pattern sValueRangePattern =
- Pattern.compile("\\(at '(.+)' with value '(.*)'\\)"); //$NON-NLS-1$
-
-
- /**
- * Portion of error message which points to the second occurrence of a repeated resource
- * definition.
- * <p>
- * Example:
- * error: Resource entry repeatedStyle1 already has bag item android:gravity.
- */
- private static final Pattern sRepeatedRangePattern =
- Pattern.compile("Resource entry (.+) already has bag item (.+)\\."); //$NON-NLS-1$
-
- /**
- * Error message emitted when aapt skips a file because for example it's name is
- * invalid, such as a layout file name which starts with _.
- * <p>
- * This error message is used by AAPT in Tools 19 and earlier.
- */
- private static final Pattern sSkippingPattern =
- Pattern.compile(" \\(skipping (.+) .+ '(.*)'\\)"); //$NON-NLS-1$
-
- /**
- * Error message emitted when aapt skips a file because for example it's name is
- * invalid, such as a layout file name which starts with _.
- * <p>
- * This error message is used by AAPT in Tools 20 and later.
- */
- private static final Pattern sNewSkippingPattern =
- Pattern.compile(" \\(skipping .+ '(.+)' due to ANDROID_AAPT_IGNORE pattern '.+'\\)"); //$NON-NLS-1$
-
- /**
- * Suffix of error message which points to the first occurrence of a repeated resource
- * definition.
- * Example:
- * Originally defined here.
- */
- private static final String ORIGINALLY_DEFINED_MSG = "Originally defined here."; //$NON-NLS-1$
-
- /**
- * Portion of error message which points to the second occurrence of a repeated resource
- * definition.
- * <p>
- * Example:
- * error: Resource entry repeatedStyle1 already has bag item android:gravity.
- */
- private static final Pattern sNoResourcePattern =
- Pattern.compile("No resource found that matches the given name: attr '(.+)'\\."); //$NON-NLS-1$
-
- /**
- * Portion of error message which points to a missing required attribute in a
- * resource definition.
- * <p>
- * Example:
- * error: error: A 'name' attribute is required for <style>
- */
- private static final Pattern sRequiredPattern =
- Pattern.compile("A '(.+)' attribute is required for <(.+)>"); //$NON-NLS-1$
-
- /**
- * 2 line aapt error<br>
- * "ERROR: Invalid configuration: foo"<br>
- * " ^^^"<br>
- * There's no need to parse the 2nd line.
- */
- private final static Pattern sPattern9Line1 = Pattern.compile(
- "^Invalid configuration: (.+)$"); //$NON-NLS-1$
-
- private final static Pattern sXmlBlockPattern = Pattern.compile(
- "W/ResourceType\\(.*\\): Bad XML block: no root element node found"); //$NON-NLS-1$
-
- /**
- * Parse the output of aapt and mark the incorrect file with error markers
- *
- * @param results the output of aapt
- * @param project the project containing the file to mark
- * @return true if the parsing failed, false if success.
- */
- public static boolean parseOutput(List<String> results, IProject project) {
- int size = results.size();
- if (size > 0) {
- return parseOutput(results.toArray(new String[size]), project);
- }
-
- return false;
- }
-
- /**
- * Parse the output of aapt and mark the incorrect file with error markers
- *
- * @param results the output of aapt
- * @param project the project containing the file to mark
- * @return true if the parsing failed, false if success.
- */
- public static boolean parseOutput(String[] results, IProject project) {
- // nothing to parse? just return false;
- if (results.length == 0) {
- return false;
- }
-
- // get the root of the project so that we can make IFile from full
- // file path
- String osRoot = project.getLocation().toOSString();
-
- Matcher m;
-
- for (int i = 0; i < results.length ; i++) {
- String p = results[i];
-
- m = sPattern0Line1.matcher(p);
- if (m.matches()) {
- // we ignore those (as this is an ignore message from aapt)
- continue;
- }
-
- m = sPattern1Line1.matcher(p);
- if (m.matches()) {
- String lineStr = m.group(1);
- String msg = m.group(2);
-
- // get the matcher for the next line.
- m = getNextLineMatcher(results, ++i, sPattern1Line2);
- if (m == null) {
- return true;
- }
-
- String location = m.group(1);
-
- // check the values and attempt to mark the file.
- if (checkAndMark(location, lineStr, msg, osRoot, project,
- AdtConstants.MARKER_AAPT_COMPILE, IMarker.SEVERITY_ERROR) == false) {
- return true;
- }
- continue;
- }
-
- // this needs to be tested before Pattern2 since they both start with 'ERROR:'
- m = sPattern7Line1.matcher(p);
- if (m.matches()) {
- String location = m.group(1);
- String msg = p; // default msg is the line in case we don't find anything else
-
- if (++i < results.length) {
- msg = results[i].trim();
- if (++i < results.length) {
- msg = msg + " - " + results[i].trim(); //$NON-NLS-1$
-
- // skip the next line
- i++;
- }
- }
-
- // display the error
- if (checkAndMark(location, null, msg, osRoot, project,
- AdtConstants.MARKER_AAPT_COMPILE, IMarker.SEVERITY_ERROR) == false) {
- return true;
- }
-
- // success, go to the next line
- continue;
- }
-
- m = sPattern2Line1.matcher(p);
- if (m.matches()) {
- // get the msg
- String msg = m.group(1);
-
- // get the matcher for the next line.
- m = getNextLineMatcher(results, ++i, sPattern2Line2);
- if (m == null) {
- return true;
- }
-
- String location = m.group(1);
- String lineStr = m.group(2);
-
- // check the values and attempt to mark the file.
- if (checkAndMark(location, lineStr, msg, osRoot, project,
- AdtConstants.MARKER_AAPT_COMPILE, IMarker.SEVERITY_ERROR) == false) {
- return true;
- }
- continue;
- }
-
- m = sPattern3Line1.matcher(p);
- if (m.matches()) {
- String location = m.group(1);
- String lineStr = m.group(2);
- String msg = m.group(3);
-
- // check the values and attempt to mark the file.
- if (checkAndMark(location, lineStr, msg, osRoot, project,
- AdtConstants.MARKER_AAPT_COMPILE, IMarker.SEVERITY_ERROR) == false) {
- return true;
- }
-
- // success, go to the next line
- continue;
- }
-
- m = sPattern4Line1.matcher(p);
- if (m.matches()) {
- // get the filename.
- String location = m.group(1);
-
- // get the matcher for the next line.
- m = getNextLineMatcher(results, ++i, sPattern4Line2);
- if (m == null) {
- return true;
- }
-
- String msg = m.group(1);
- String lineStr = m.group(2);
-
- // check the values and attempt to mark the file.
- if (checkAndMark(location, lineStr, msg, osRoot, project,
- AdtConstants.MARKER_AAPT_COMPILE, IMarker.SEVERITY_ERROR) == false) {
- return true;
- }
-
- // success, go to the next line
- continue;
- }
-
- m = sPattern5Line1.matcher(p);
- if (m.matches()) {
- String location = m.group(1);
- String lineStr = m.group(2);
- String msg = m.group(3);
-
- // check the values and attempt to mark the file.
- if (checkAndMark(location, lineStr, msg, osRoot, project,
- AdtConstants.MARKER_AAPT_COMPILE, IMarker.SEVERITY_WARNING) == false) {
- return true;
- }
-
- // success, go to the next line
- continue;
- }
-
- m = sPattern6Line1.matcher(p);
- if (m.matches()) {
- String location = m.group(1);
- String lineStr = m.group(2);
- String msg = m.group(3);
-
- // check the values and attempt to mark the file.
- if (checkAndMark(location, lineStr, msg, osRoot, project,
- AdtConstants.MARKER_AAPT_COMPILE, IMarker.SEVERITY_ERROR) == false) {
- return true;
- }
-
- // success, go to the next line
- continue;
- }
-
- m = sPattern8Line1.matcher(p);
- if (m.matches()) {
- String location = m.group(2);
- String msg = m.group(1);
-
- // check the values and attempt to mark the file.
- if (checkAndMark(location, null, msg, osRoot, project,
- AdtConstants.MARKER_AAPT_COMPILE, IMarker.SEVERITY_ERROR) == false) {
- return true;
- }
-
- // success, go to the next line
- continue;
- }
-
- m = sPattern9Line1.matcher(p);
- if (m.matches()) {
- String badConfig = m.group(1);
- String msg = String.format("APK Configuration filter '%1$s' is invalid", badConfig);
-
- // skip the next line
- i++;
-
- // check the values and attempt to mark the file.
- if (checkAndMark(null /*location*/, null, msg, osRoot, project,
- AdtConstants.MARKER_AAPT_PACKAGE, IMarker.SEVERITY_ERROR) == false) {
- return true;
- }
-
- // success, go to the next line
- continue;
- }
-
- m = sNewSkippingPattern.matcher(p);
- if (m.matches()) {
- String location = m.group(1);
-
- if (location.startsWith(".") //$NON-NLS-1$
- || location.endsWith("~")) { //$NON-NLS-1$
- continue;
- }
-
- // check the values and attempt to mark the file.
- if (checkAndMark(location, null, p.trim(), osRoot, project,
- AdtConstants.MARKER_AAPT_COMPILE, IMarker.SEVERITY_WARNING) == false) {
- return true;
- }
-
- // success, go to the next line
- continue;
- }
-
- m = sSkippingPattern.matcher(p);
- if (m.matches()) {
- String location = m.group(2);
-
- // Certain files can safely be skipped without marking the project
- // as having errors. See isHidden() in AaptAssets.cpp:
- String type = m.group(1);
- if (type.equals("backup") //$NON-NLS-1$ // main.xml~, etc
- || type.equals("hidden") //$NON-NLS-1$ // .gitignore, etc
- || type.equals("index")) { //$NON-NLS-1$ // thumbs.db, etc
- continue;
- }
-
- // check the values and attempt to mark the file.
- if (checkAndMark(location, null, p.trim(), osRoot, project,
- AdtConstants.MARKER_AAPT_COMPILE, IMarker.SEVERITY_WARNING) == false) {
- return true;
- }
-
- // success, go to the next line
- continue;
- }
-
- m = sXmlBlockPattern.matcher(p);
- if (m.matches()) {
- // W/ResourceType(12345): Bad XML block: no root element node found
- // Sadly there's NO filename reference; this error typically describes the
- // error *after* this line.
- if (results.length == 1) {
- // This is the only error message: dump to console and quit
- return true;
- }
- // Continue: the real culprit is displayed next and should get a marker
- continue;
- }
-
- return true;
- }
-
- return false;
- }
-
- /**
- * Check if the parameters gotten from the error output are valid, and mark
- * the file with an AAPT marker.
- * @param location the full OS path of the error file. If null, the project is marked
- * @param lineStr
- * @param message
- * @param root The root directory of the project, in OS specific format.
- * @param project
- * @param markerId The marker id to put.
- * @param severity The severity of the marker to put (IMarker.SEVERITY_*)
- * @return true if the parameters were valid and the file was marked successfully.
- *
- * @see IMarker
- */
- private static final boolean checkAndMark(String location, String lineStr,
- String message, String root, IProject project, String markerId, int severity) {
- // check this is in fact a file
- if (location != null) {
- File f = new File(location);
- if (f.exists() == false) {
- return false;
- }
- }
-
- // get the line number
- int line = -1; // default value for error with no line.
-
- if (lineStr != null) {
- try {
- line = Integer.parseInt(lineStr);
- } catch (NumberFormatException e) {
- // looks like the string we extracted wasn't a valid
- // file number. Parsing failed and we return true
- return false;
- }
- }
-
- // add the marker
- IResource f2 = project;
- if (location != null) {
- f2 = getResourceFromFullPath(location, root, project);
- if (f2 == null) {
- return false;
- }
- }
-
- // Attempt to determine the exact range of characters affected by this error.
- // This will look up the actual text of the file, go to the particular error line
- // and scan for the specific string mentioned in the error.
- int startOffset = -1;
- int endOffset = -1;
- if (f2 instanceof IFile) {
- IRegion region = findRange((IFile) f2, line, message);
- if (region != null) {
- startOffset = region.getOffset();
- endOffset = startOffset + region.getLength();
- }
- }
-
- // check if there's a similar marker already, since aapt is launched twice
- boolean markerAlreadyExists = false;
- try {
- IMarker[] markers = f2.findMarkers(markerId, true, IResource.DEPTH_ZERO);
-
- for (IMarker marker : markers) {
- if (startOffset != -1) {
- int tmpBegin = marker.getAttribute(IMarker.CHAR_START, -1);
- if (tmpBegin != startOffset) {
- break;
- }
- int tmpEnd = marker.getAttribute(IMarker.CHAR_END, -1);
- if (tmpEnd != startOffset) {
- break;
- }
- }
-
- int tmpLine = marker.getAttribute(IMarker.LINE_NUMBER, -1);
- if (tmpLine != line) {
- break;
- }
-
- int tmpSeverity = marker.getAttribute(IMarker.SEVERITY, -1);
- if (tmpSeverity != severity) {
- break;
- }
-
- String tmpMsg = marker.getAttribute(IMarker.MESSAGE, null);
- if (tmpMsg == null || tmpMsg.equals(message) == false) {
- break;
- }
-
- // if we're here, all the marker attributes are equals, we found it
- // and exit
- markerAlreadyExists = true;
- break;
- }
-
- } catch (CoreException e) {
- // if we couldn't get the markers, then we just mark the file again
- // (since markerAlreadyExists is initialized to false, we do nothing)
- }
-
- if (markerAlreadyExists == false) {
- BaseProjectHelper.markResource(f2, markerId, message, line,
- startOffset, endOffset, severity);
- }
-
- return true;
- }
-
- /**
- * Given an aapt error message in a given file and a given (initial) line number,
- * return the corresponding offset range for the error, or null.
- */
- private static IRegion findRange(IFile file, int line, String message) {
- Matcher matcher = sValueRangePattern.matcher(message);
- if (matcher.find()) {
- String property = matcher.group(1);
- String value = matcher.group(2);
-
- // First find the property. We can't just immediately look for the
- // value, because there could be other attributes in this element
- // earlier than the one in error, and we might accidentally pick
- // up on a different occurrence of the value in a context where
- // it is valid.
- if (value.length() > 0) {
- return findRange(file, line, property, value);
- } else {
- // Find first occurrence of property followed by '' or ""
- IRegion region1 = findRange(file, line, property, "\"\""); //$NON-NLS-1$
- IRegion region2 = findRange(file, line, property, "''"); //$NON-NLS-1$
- if (region1 == null) {
- if (region2 == null) {
- // Highlight the property instead
- return findRange(file, line, property, null);
- }
- return region2;
- } else if (region2 == null) {
- return region1;
- } else if (region1.getOffset() < region2.getOffset()) {
- return region1;
- } else {
- return region2;
- }
- }
- }
-
- matcher = sRepeatedRangePattern.matcher(message);
- if (matcher.find()) {
- String property = matcher.group(2);
- return findRange(file, line, property, null);
- }
-
- matcher = sNoResourcePattern.matcher(message);
- if (matcher.find()) {
- String property = matcher.group(1);
- return findRange(file, line, property, null);
- }
-
- matcher = sRequiredPattern.matcher(message);
- if (matcher.find()) {
- String elementName = matcher.group(2);
- IRegion region = findRange(file, line, '<' + elementName, null);
- if (region != null && region.getLength() > 1) {
- // Skip the opening <
- region = new Region(region.getOffset() + 1, region.getLength() - 1);
- }
- return region;
- }
-
- if (message.endsWith(ORIGINALLY_DEFINED_MSG)) {
- return findLineTextRange(file, line);
- }
-
- return null;
- }
-
- /**
- * Given a file and line number, return the range of the first match starting on the
- * given line. If second is non null, also search for the second string starting at he
- * location of the first string.
- */
- private static IRegion findRange(IFile file, int line, String first,
- String second) {
- IRegion region = null;
- IDocumentProvider provider = new TextFileDocumentProvider();
- try {
- provider.connect(file);
- IDocument document = provider.getDocument(file);
- if (document != null) {
- IRegion lineInfo = document.getLineInformation(line - 1);
- int lineStartOffset = lineInfo.getOffset();
- // The aapt errors will be anchored on the line where the
- // element starts - which means that with formatting where
- // attributes end up on subsequent lines we don't find it on
- // the error line indicated by aapt.
- // Therefore, search forwards in the document.
- FindReplaceDocumentAdapter adapter =
- new FindReplaceDocumentAdapter(document);
-
- region = adapter.find(lineStartOffset, first,
- true /*forwardSearch*/, true /*caseSensitive*/,
- false /*wholeWord*/, false /*regExSearch*/);
- if (region != null && second != null) {
- region = adapter.find(region.getOffset() + first.length(), second,
- true /*forwardSearch*/, true /*caseSensitive*/,
- false /*wholeWord*/, false /*regExSearch*/);
- }
- }
- } catch (Exception e) {
- AdtPlugin.log(e, "Can't find range information for %1$s", file.getName());
- } finally {
- provider.disconnect(file);
- }
- return region;
- }
-
- /** Returns the non-whitespace line range at the given line number. */
- private static IRegion findLineTextRange(IFile file, int line) {
- IDocumentProvider provider = new TextFileDocumentProvider();
- try {
- provider.connect(file);
- IDocument document = provider.getDocument(file);
- if (document != null) {
- IRegion lineInfo = document.getLineInformation(line - 1);
- String lineContents = document.get(lineInfo.getOffset(), lineInfo.getLength());
- int lineBegin = 0;
- int lineEnd = lineContents.length()-1;
-
- for (; lineEnd >= 0; lineEnd--) {
- char c = lineContents.charAt(lineEnd);
- if (!Character.isWhitespace(c)) {
- break;
- }
- }
- lineEnd++;
- for (; lineBegin < lineEnd; lineBegin++) {
- char c = lineContents.charAt(lineBegin);
- if (!Character.isWhitespace(c)) {
- break;
- }
- }
- if (lineBegin < lineEnd) {
- return new Region(lineInfo.getOffset() + lineBegin, lineEnd - lineBegin);
- }
- }
- } catch (Exception e) {
- AdtPlugin.log(e, "Can't find range information for %1$s", file.getName());
- } finally {
- provider.disconnect(file);
- }
-
- return null;
- }
-
- /**
- * Returns a matching matcher for the next line
- * @param lines The array of lines
- * @param nextIndex The index of the next line
- * @param pattern The pattern to match
- * @return null if error or no match, the matcher otherwise.
- */
- private static final Matcher getNextLineMatcher(String[] lines,
- int nextIndex, Pattern pattern) {
- // unless we can't, because we reached the last line
- if (nextIndex == lines.length) {
- // we expected a 2nd line, so we flag as error
- // and we bail
- return null;
- }
-
- Matcher m = pattern.matcher(lines[nextIndex]);
- if (m.matches()) {
- return m;
- }
-
- return null;
- }
-
- private static IResource getResourceFromFullPath(String filename, String root,
- IProject project) {
- if (filename.startsWith(root)) {
- String file = filename.substring(root.length());
-
- // get the resource
- IResource r = project.findMember(file);
-
- // if the resource is valid, we add the marker
- if (r != null && r.exists()) {
- return r;
- }
- }
-
- return null;
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/AaptQuickFix.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/AaptQuickFix.java
deleted file mode 100644
index 3db380832..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/AaptQuickFix.java
+++ /dev/null
@@ -1,431 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.XMLNS_ANDROID;
-import static com.android.SdkConstants.XMLNS_URI;
-
-import com.android.ide.common.resources.ResourceUrl;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.resources.ResourceHelper;
-import com.android.resources.ResourceType;
-import com.android.utils.Pair;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext;
-import org.eclipse.jface.text.quickassist.IQuickAssistProcessor;
-import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.ui.IMarkerResolution;
-import org.eclipse.ui.IMarkerResolution2;
-import org.eclipse.ui.IMarkerResolutionGenerator2;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.editors.text.TextFileDocumentProvider;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.wst.sse.core.StructuredModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-import java.util.List;
-
-/**
- * Shared handler for both quick assist processors (Control key handler) and quick fix
- * marker resolution (Problem view handling), since there is a lot of overlap between
- * these two UI handlers.
- */
-@SuppressWarnings("restriction") // XML model
-public class AaptQuickFix implements IMarkerResolutionGenerator2, IQuickAssistProcessor {
-
- public AaptQuickFix() {
- }
-
- /** Returns the error message from aapt that signals missing resources */
- private static String getTargetMarkerErrorMessage() {
- return "No resource found that matches the given name";
- }
-
- /** Returns the error message from aapt that signals a missing namespace declaration */
- private static String getUnboundErrorMessage() {
- return "Error parsing XML: unbound prefix";
- }
-
- // ---- Implements IMarkerResolution2 ----
-
- @Override
- public boolean hasResolutions(IMarker marker) {
- String message = null;
- try {
- message = (String) marker.getAttribute(IMarker.MESSAGE);
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
-
- return message != null
- && (message.contains(getTargetMarkerErrorMessage())
- || message.contains(getUnboundErrorMessage()));
- }
-
- @Override
- public IMarkerResolution[] getResolutions(IMarker marker) {
- IResource markerResource = marker.getResource();
- IProject project = markerResource.getProject();
- try {
- String message = (String) marker.getAttribute(IMarker.MESSAGE);
- if (message.contains(getUnboundErrorMessage()) && markerResource instanceof IFile) {
- return new IMarkerResolution[] {
- new CreateNamespaceFix((IFile) markerResource)
- };
- }
- } catch (CoreException e1) {
- AdtPlugin.log(e1, null);
- }
-
- int start = marker.getAttribute(IMarker.CHAR_START, 0);
- int end = marker.getAttribute(IMarker.CHAR_END, 0);
- if (end > start) {
- int length = end - start;
- IDocumentProvider provider = new TextFileDocumentProvider();
- try {
- provider.connect(markerResource);
- IDocument document = provider.getDocument(markerResource);
- String resource = document.get(start, length);
- if (ResourceHelper.canCreateResource(resource)) {
- return new IMarkerResolution[] {
- new CreateResourceProposal(project, resource)
- };
- }
- } catch (Exception e) {
- AdtPlugin.log(e, "Can't find range information for %1$s", markerResource);
- } finally {
- provider.disconnect(markerResource);
- }
- }
-
- return null;
- }
-
- // ---- Implements IQuickAssistProcessor ----
-
- @Override
- public boolean canAssist(IQuickAssistInvocationContext invocationContext) {
- return true;
- }
-
- @Override
- public boolean canFix(Annotation annotation) {
- return true;
- }
-
- @Override
- public ICompletionProposal[] computeQuickAssistProposals(
- IQuickAssistInvocationContext invocationContext) {
-
- // We have to find the corresponding project/file (so we can look up the aapt
- // error markers). Unfortunately, an IQuickAssistProcessor only gets
- // access to an ISourceViewer which has no hooks back to the surrounding
- // editor.
- //
- // However, the IQuickAssistProcessor will only be used interactively by a file
- // being edited, so we can cheat like the hyperlink detector and simply
- // look up the currently active file in the IDE. To be on the safe side,
- // we'll make sure that that editor has the same sourceViewer such that
- // we are indeed looking at the right file:
- ISourceViewer sourceViewer = invocationContext.getSourceViewer();
- AndroidXmlEditor editor = AndroidXmlEditor.fromTextViewer(sourceViewer);
- if (editor != null) {
- IFile file = editor.getInputFile();
- if (file == null) {
- return null;
- }
- IDocument document = sourceViewer.getDocument();
- List<IMarker> markers = AdtUtils.findMarkersOnLine(AdtConstants.MARKER_AAPT_COMPILE,
- file, document, invocationContext.getOffset());
- try {
- for (IMarker marker : markers) {
- String message = marker.getAttribute(IMarker.MESSAGE, ""); //$NON-NLS-1$
- if (message.contains(getTargetMarkerErrorMessage())) {
- int start = marker.getAttribute(IMarker.CHAR_START, 0);
- int end = marker.getAttribute(IMarker.CHAR_END, 0);
- int length = end - start;
- String resource = document.get(start, length);
- // Can only offer create value for non-framework value
- // resources
- if (ResourceHelper.canCreateResource(resource)) {
- IProject project = editor.getProject();
- return new ICompletionProposal[] {
- new CreateResourceProposal(project, resource)
- };
- }
- } else if (message.contains(getUnboundErrorMessage())) {
- return new ICompletionProposal[] {
- new CreateNamespaceFix(null)
- };
- }
- }
- } catch (BadLocationException e) {
- AdtPlugin.log(e, null);
- }
- }
-
- return null;
- }
-
- @Override
- public String getErrorMessage() {
- return null;
- }
-
- /** Quick fix to insert namespace binding when missing */
- private final static class CreateNamespaceFix
- implements ICompletionProposal, IMarkerResolution2 {
- private IFile mFile;
-
- public CreateNamespaceFix(IFile file) {
- mFile = file;
- }
-
- private IndexedRegion perform(IDocument doc) {
- IModelManager manager = StructuredModelManager.getModelManager();
- IStructuredModel model = manager.getExistingModelForEdit(doc);
- if (model != null) {
- try {
- perform(model);
- } finally {
- model.releaseFromEdit();
- }
- }
-
- return null;
- }
-
- private IndexedRegion perform(IFile file) {
- IModelManager manager = StructuredModelManager.getModelManager();
- IStructuredModel model;
- try {
- model = manager.getModelForEdit(file);
- if (model != null) {
- try {
- perform(model);
- } finally {
- model.releaseFromEdit();
- }
- }
- } catch (Exception e) {
- AdtPlugin.log(e, "Can't look up XML model");
- }
-
- return null;
- }
-
- private IndexedRegion perform(IStructuredModel model) {
- if (model instanceof IDOMModel) {
- IDOMModel domModel = (IDOMModel) model;
- Document document = domModel.getDocument();
- Element element = document.getDocumentElement();
- Attr attr = document.createAttributeNS(XMLNS_URI, XMLNS_ANDROID);
- attr.setValue(ANDROID_URI);
- element.getAttributes().setNamedItemNS(attr);
- return (IndexedRegion) attr;
- }
-
- return null;
- }
-
- // ---- Implements ICompletionProposal ----
-
- @Override
- public void apply(IDocument document) {
- perform(document);
- }
-
- @Override
- public String getAdditionalProposalInfo() {
- return "Adds an Android namespace declaratiopn to the root element.";
- }
-
- @Override
- public IContextInformation getContextInformation() {
- return null;
- }
-
- @Override
- public String getDisplayString() {
- return "Insert namespace binding";
- }
-
- @Override
- public Image getImage() {
- return AdtPlugin.getAndroidLogo();
- }
-
- @Override
- public Point getSelection(IDocument doc) {
- return null;
- }
-
-
- // ---- Implements MarkerResolution2 ----
-
- @Override
- public String getLabel() {
- return getDisplayString();
- }
-
- @Override
- public void run(IMarker marker) {
- try {
- AdtPlugin.openFile(mFile, null);
- } catch (PartInitException e) {
- AdtPlugin.log(e, "Can't open file %1$s", mFile.getName());
- }
-
- IndexedRegion indexedRegion = perform(mFile);
- if (indexedRegion != null) {
- try {
- IRegion region =
- new Region(indexedRegion.getStartOffset(), indexedRegion.getLength());
- AdtPlugin.openFile(mFile, region);
- } catch (PartInitException e) {
- AdtPlugin.log(e, "Can't open file %1$s", mFile.getName());
- }
- }
- }
-
- @Override
- public String getDescription() {
- return getAdditionalProposalInfo();
- }
- }
-
- private static class CreateResourceProposal
- implements ICompletionProposal, IMarkerResolution2 {
- private final IProject mProject;
- private final String mResource;
-
- CreateResourceProposal(IProject project, String resource) {
- super();
- mProject = project;
- mResource = resource;
- }
-
- private void perform() {
- ResourceUrl resource = ResourceUrl.parse(mResource);
- if (resource == null) {
- return;
- }
- ResourceType type = resource.type;
- String name = resource.name;
- assert !resource.framework;
- String value = ""; //$NON-NLS-1$
-
- // Try to pick a reasonable first guess. The new value will be highlighted and
- // selected for editing, but if we have an initial value then the new file
- // won't show an error.
- switch (type) {
- case STRING: value = "TODO"; break; //$NON-NLS-1$
- case DIMEN: value = "1dp"; break; //$NON-NLS-1$
- case BOOL: value = "true"; break; //$NON-NLS-1$
- case COLOR: value = "#000000"; break; //$NON-NLS-1$
- case INTEGER: value = "1"; break; //$NON-NLS-1$
- case ARRAY: value = "<item>1</item>"; break; //$NON-NLS-1$
- }
-
- Pair<IFile, IRegion> location =
- ResourceHelper.createResource(mProject, type, name, value);
- if (location != null) {
- IFile file = location.getFirst();
- IRegion region = location.getSecond();
- try {
- AdtPlugin.openFile(file, region);
- } catch (PartInitException e) {
- AdtPlugin.log(e, "Can't open file %1$s", file.getName());
- }
- }
- }
-
- // ---- Implements ICompletionProposal ----
-
- @Override
- public void apply(IDocument document) {
- perform();
- }
-
- @Override
- public String getAdditionalProposalInfo() {
- return "Creates an XML file entry for the given missing resource "
- + "and opens it in the editor.";
- }
-
- @Override
- public IContextInformation getContextInformation() {
- return null;
- }
-
- @Override
- public String getDisplayString() {
- return String.format("Create resource %1$s", mResource);
- }
-
- @Override
- public Image getImage() {
- return AdtPlugin.getAndroidLogo();
- }
-
- @Override
- public Point getSelection(IDocument document) {
- return null;
- }
-
- // ---- Implements MarkerResolution2 ----
-
- @Override
- public String getLabel() {
- return getDisplayString();
- }
-
- @Override
- public void run(IMarker marker) {
- perform();
- }
-
- @Override
- public String getDescription() {
- return getAdditionalProposalInfo();
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/AaptResultException.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/AaptResultException.java
deleted file mode 100644
index 8d8fe683f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/AaptResultException.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build;
-
-/**
- * Exception thrown when aapt reports an error in the resources.
- *
- */
-public final class AaptResultException extends ExecResultException {
- private static final long serialVersionUID = 1L;
-
- AaptResultException(int errorCode, String[] output) {
- super(errorCode, output);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/AidlProcessor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/AidlProcessor.java
deleted file mode 100644
index 806fa9c40..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/AidlProcessor.java
+++ /dev/null
@@ -1,484 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.build.builders.BaseBuilder;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs.BuildVerbosity;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.sdklib.BuildToolInfo;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.io.FileOp;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jdt.core.IJavaProject;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * A {@link SourceProcessor} for aidl files.
- *
- */
-public class AidlProcessor extends SourceProcessor {
-
- private static final String PROPERTY_COMPILE_AIDL = "compileAidl"; //$NON-NLS-1$
-
- /**
- * Single line aidl error<br>
- * {@code <path>:<line>: <error>}<br>
- * or<br>
- * {@code <path>:<line> <error>}<br>
- */
- private static Pattern sAidlPattern1 = Pattern.compile("^(.+?):(\\d+):?\\s(.+)$"); //$NON-NLS-1$
-
- private final static Set<String> EXTENSIONS = Collections.singleton(SdkConstants.EXT_AIDL);
-
- private enum AidlType {
- UNKNOWN, INTERFACE, PARCELABLE;
- }
-
- // See comment in #getAidlType()
-// private final static Pattern sParcelablePattern = Pattern.compile(
-// "^\\s*parcelable\\s+([a-zA-Z_][a-zA-Z0-9_]*)\\s*;\\s*$");
-//
-// private final static Pattern sInterfacePattern = Pattern.compile(
-// "^\\s*interface\\s+([a-zA-Z_][a-zA-Z0-9_]*)\\s*(?:\\{.*)?$");
-
-
- public AidlProcessor(@NonNull IJavaProject javaProject, @NonNull BuildToolInfo buildToolInfo,
- @NonNull IFolder genFolder) {
- super(javaProject, buildToolInfo, genFolder);
- }
-
- @Override
- protected Set<String> getExtensions() {
- return EXTENSIONS;
- }
-
- @Override
- protected String getSavePropertyName() {
- return PROPERTY_COMPILE_AIDL;
- }
-
- @Override
- protected void doCompileFiles(List<IFile> sources, BaseBuilder builder,
- IProject project, IAndroidTarget projectTarget,
- List<IPath> sourceFolders, List<IFile> notCompiledOut, List<File> libraryProjectsOut,
- IProgressMonitor monitor) throws CoreException {
- // create the command line
- List<String> commandList = new ArrayList<String>(
- 4 + sourceFolders.size() + libraryProjectsOut.size());
- commandList.add(getBuildToolInfo().getPath(BuildToolInfo.PathId.AIDL));
- commandList.add(quote("-p" + projectTarget.getPath(IAndroidTarget.ANDROID_AIDL))); //$NON-NLS-1$
-
- // since the path are relative to the workspace and not the project itself, we need
- // the workspace root.
- IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();
- for (IPath p : sourceFolders) {
- IFolder f = wsRoot.getFolder(p);
- if (f.exists()) { // if the resource doesn't exist, getLocation will return null.
- commandList.add(quote("-I" + f.getLocation().toOSString())); //$NON-NLS-1$
- }
- }
-
- for (File libOut : libraryProjectsOut) {
- // FIXME: make folder configurable
- File aidlFile = new File(libOut, SdkConstants.FD_AIDL);
- if (aidlFile.isDirectory()) {
- commandList.add(quote("-I" + aidlFile.getAbsolutePath())); //$NON-NLS-1$
- }
- }
-
- // convert to array with 2 extra strings for the in/out file paths.
- int index = commandList.size();
- String[] commands = commandList.toArray(new String[index + 2]);
-
- boolean verbose = AdtPrefs.getPrefs().getBuildVerbosity() == BuildVerbosity.VERBOSE;
-
- // remove the generic marker from the project
- builder.removeMarkersFromResource(project, AdtConstants.MARKER_AIDL);
-
- // prepare the two output folders.
- IFolder genFolder = getGenFolder();
- IFolder projectOut = BaseProjectHelper.getAndroidOutputFolder(project);
- IFolder aidlOutFolder = projectOut.getFolder(SdkConstants.FD_AIDL);
- if (aidlOutFolder.exists() == false) {
- aidlOutFolder.create(true /*force*/, true /*local*/,
- new SubProgressMonitor(monitor, 10));
- }
-
- boolean success = false;
-
- // loop until we've compile them all
- for (IFile sourceFile : sources) {
- if (verbose) {
- String name = sourceFile.getName();
- IPath sourceFolderPath = getSourceFolderFor(sourceFile);
- if (sourceFolderPath != null) {
- // make a path to the source file relative to the source folder.
- IPath relative = sourceFile.getFullPath().makeRelativeTo(sourceFolderPath);
- name = relative.toString();
- }
- AdtPlugin.printToConsole(project, "AIDL: " + name);
- }
-
- // Remove the AIDL error markers from the aidl file
- builder.removeMarkersFromResource(sourceFile, AdtConstants.MARKER_AIDL);
-
- // get the path of the source file.
- IPath sourcePath = sourceFile.getLocation();
- String osSourcePath = sourcePath.toOSString();
-
- // look if we already know the output
- SourceFileData data = getFileData(sourceFile);
- if (data == null) {
- data = new SourceFileData(sourceFile);
- addData(data);
- }
-
- // if there's no output file yet, compute it.
- if (data.getOutput() == null) {
- IFile javaFile = getAidlOutputFile(sourceFile, genFolder,
- true /*replaceExt*/, true /*createFolders*/, monitor);
- data.setOutputFile(javaFile);
- }
-
- // finish to set the command line.
- commands[index] = quote(osSourcePath);
- commands[index + 1] = quote(data.getOutput().getLocation().toOSString());
-
- // launch the process
- if (execAidl(builder, project, commands, sourceFile, verbose) == false) {
- // aidl failed. File should be marked. We add the file to the list
- // of file that will need compilation again.
- notCompiledOut.add(sourceFile);
- } else {
- // Success. we'll return that we generated code
- setCompilationStatus(COMPILE_STATUS_CODE);
- success = true;
-
- // Also copy the file to the bin folder.
- IFile aidlOutFile = getAidlOutputFile(sourceFile, aidlOutFolder,
- false /*replaceExt*/, true /*createFolders*/, monitor);
-
- FileOp op = new FileOp();
- try {
- op.copyFile(sourceFile.getLocation().toFile(),
- aidlOutFile.getLocation().toFile());
- } catch (IOException e) {
- }
- }
- }
-
- if (success) {
- aidlOutFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);
- }
- }
-
- @Override
- protected void loadOutputAndDependencies() {
- IProgressMonitor monitor = new NullProgressMonitor();
- IFolder genFolder = getGenFolder();
-
- Collection<SourceFileData> dataList = getAllFileData();
- for (SourceFileData data : dataList) {
- try {
- IFile javaFile = getAidlOutputFile(data.getSourceFile(), genFolder,
- true /*replaceExt*/, false /*createFolders*/, monitor);
- data.setOutputFile(javaFile);
- } catch (CoreException e) {
- // ignore, we're not asking to create the folder so this won't happen anyway.
- }
-
- }
- }
-
- /**
- * Execute the aidl command line, parse the output, and mark the aidl file
- * with any reported errors.
- * @param command the String array containing the command line to execute.
- * @param file The IFile object representing the aidl file being
- * compiled.
- * @param verbose the build verbosity
- * @return false if the exec failed, and build needs to be aborted.
- */
- private boolean execAidl(BaseBuilder builder, IProject project, String[] command, IFile file,
- boolean verbose) {
- // do the exec
- try {
- if (verbose) {
- StringBuilder sb = new StringBuilder();
- for (String c : command) {
- sb.append(c);
- sb.append(' ');
- }
- String cmd_line = sb.toString();
- AdtPlugin.printToConsole(project, cmd_line);
- }
-
- Process p = Runtime.getRuntime().exec(command);
-
- // list to store each line of stderr
- ArrayList<String> stdErr = new ArrayList<String>();
-
- // get the output and return code from the process
- int returnCode = BuildHelper.grabProcessOutput(project, p, stdErr);
-
- if (stdErr.size() > 0) {
- // attempt to parse the error output
- boolean parsingError = parseAidlOutput(stdErr, file);
-
- // If the process failed and we couldn't parse the output
- // we print a message, mark the project and exit
- if (returnCode != 0) {
-
- if (parsingError || verbose) {
- // display the message in the console.
- if (parsingError) {
- AdtPlugin.printErrorToConsole(project, stdErr.toArray());
-
- // mark the project
- BaseProjectHelper.markResource(project, AdtConstants.MARKER_AIDL,
- Messages.Unparsed_AIDL_Errors, IMarker.SEVERITY_ERROR);
- } else {
- AdtPlugin.printToConsole(project, stdErr.toArray());
- }
- }
- return false;
- }
- } else if (returnCode != 0) {
- // no stderr output but exec failed.
- String msg = String.format(Messages.AIDL_Exec_Error_d, returnCode);
-
- BaseProjectHelper.markResource(project, AdtConstants.MARKER_AIDL,
- msg, IMarker.SEVERITY_ERROR);
-
- return false;
- }
- } catch (IOException e) {
- // mark the project and exit
- String msg = String.format(Messages.AIDL_Exec_Error_s, command[0]);
- BaseProjectHelper.markResource(project, AdtConstants.MARKER_AIDL, msg,
- IMarker.SEVERITY_ERROR);
- return false;
- } catch (InterruptedException e) {
- // mark the project and exit
- String msg = String.format(Messages.AIDL_Exec_Error_s, command[0]);
- BaseProjectHelper.markResource(project, AdtConstants.MARKER_AIDL, msg,
- IMarker.SEVERITY_ERROR);
- return false;
- }
-
- return true;
- }
-
- /**
- * Parse the output of aidl and mark the file with any errors.
- * @param lines The output to parse.
- * @param file The file to mark with error.
- * @return true if the parsing failed, false if success.
- */
- private boolean parseAidlOutput(ArrayList<String> lines, IFile file) {
- // nothing to parse? just return false;
- if (lines.size() == 0) {
- return false;
- }
-
- Matcher m;
-
- for (int i = 0; i < lines.size(); i++) {
- String p = lines.get(i);
-
- m = sAidlPattern1.matcher(p);
- if (m.matches()) {
- // we can ignore group 1 which is the location since we already
- // have a IFile object representing the aidl file.
- String lineStr = m.group(2);
- String msg = m.group(3);
-
- // get the line number
- int line = 0;
- try {
- line = Integer.parseInt(lineStr);
- } catch (NumberFormatException e) {
- // looks like the string we extracted wasn't a valid
- // file number. Parsing failed and we return true
- return true;
- }
-
- // mark the file
- BaseProjectHelper.markResource(file, AdtConstants.MARKER_AIDL, msg, line,
- IMarker.SEVERITY_ERROR);
-
- // success, go to the next line
- continue;
- }
-
- // invalid line format, flag as error, and bail
- return true;
- }
-
- return false;
- }
-
- /**
- * Returns the {@link IFile} handle to the destination file for a given aidl source file
- * ({@link AidlData}).
- * @param sourceFile The source file
- * @param outputFolder the top level output folder (not including the package folders)
- * @param createFolders whether or not the parent folder of the destination should be created
- * if it does not exist.
- * @param monitor the progress monitor
- * @return the handle to the destination file.
- * @throws CoreException
- */
- private IFile getAidlOutputFile(IFile sourceFile, IFolder outputFolder, boolean replaceExt,
- boolean createFolders, IProgressMonitor monitor) throws CoreException {
-
- IPath sourceFolderPath = getSourceFolderFor(sourceFile);
-
- // this really shouldn't happen since the sourceFile must be in a source folder
- // since it comes from the delta visitor
- if (sourceFolderPath != null) {
- // make a path to the source file relative to the source folder.
- IPath relative = sourceFile.getFullPath().makeRelativeTo(sourceFolderPath);
- // remove the file name. This is now the destination folder.
- relative = relative.removeLastSegments(1);
-
- // get an IFolder for this path.
- IFolder destinationFolder = outputFolder.getFolder(relative);
-
- // create it if needed.
- if (destinationFolder.exists() == false && createFolders) {
- createFolder(destinationFolder, monitor);
- }
-
- // Build the Java file name from the aidl name.
- String javaName;
- if (replaceExt) {
- javaName = sourceFile.getName().replaceAll(
- AdtConstants.RE_AIDL_EXT, SdkConstants.DOT_JAVA);
- } else {
- javaName = sourceFile.getName();
- }
-
- // get the resource for the java file.
- IFile javaFile = destinationFolder.getFile(javaName);
- return javaFile;
- }
-
- return null;
- }
-
- /**
- * Creates the destination folder. Because
- * {@link IFolder#create(boolean, boolean, IProgressMonitor)} only works if the parent folder
- * already exists, this goes and ensure that all the parent folders actually exist, or it
- * creates them as well.
- * @param destinationFolder The folder to create
- * @param monitor the {@link IProgressMonitor},
- * @throws CoreException
- */
- private void createFolder(IFolder destinationFolder, IProgressMonitor monitor)
- throws CoreException {
-
- // check the parent exist and create if necessary.
- IContainer parent = destinationFolder.getParent();
- if (parent.getType() == IResource.FOLDER && parent.exists() == false) {
- createFolder((IFolder)parent, monitor);
- }
-
- // create the folder.
- destinationFolder.create(true /*force*/, true /*local*/,
- new SubProgressMonitor(monitor, 10));
- }
-
- /**
- * Returns the type of the aidl file. Aidl files can either declare interfaces, or declare
- * parcelables. This method will attempt to parse the file and return the type. If the type
- * cannot be determined, then it will return {@link AidlType#UNKNOWN}.
- * @param file The aidl file
- * @return the type of the aidl.
- */
- private static AidlType getAidlType(IFile file) {
- // At this time, parsing isn't available, so we return UNKNOWN. This will force
- // a recompilation of all aidl file as soon as one is changed.
- return AidlType.UNKNOWN;
-
- // TODO: properly parse aidl file to determine type and generate dependency graphs.
-//
-// String className = file.getName().substring(0,
-// file.getName().length() - SdkConstants.DOT_AIDL.length());
-//
-// InputStream input = file.getContents(true /* force*/);
-// try {
-// BufferedReader reader = new BufferedReader(new InputStreateader(input));
-// String line;
-// while ((line = reader.readLine()) != null) {
-// if (line.length() == 0) {
-// continue;
-// }
-//
-// Matcher m = sParcelablePattern.matcher(line);
-// if (m.matches() && m.group(1).equals(className)) {
-// return AidlType.PARCELABLE;
-// }
-//
-// m = sInterfacePattern.matcher(line);
-// if (m.matches() && m.group(1).equals(className)) {
-// return AidlType.INTERFACE;
-// }
-// }
-// } catch (IOException e) {
-// throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
-// "Error parsing aidl file", e));
-// } finally {
-// try {
-// input.close();
-// } catch (IOException e) {
-// throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
-// "Error parsing aidl file", e));
-// }
-// }
-//
-// return AidlType.UNKNOWN;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/BuildHelper.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/BuildHelper.java
deleted file mode 100644
index 78d9d94e4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/BuildHelper.java
+++ /dev/null
@@ -1,1225 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AndroidPrintStream;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs.BuildVerbosity;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.prefs.AndroidLocation.AndroidLocationException;
-import com.android.sdklib.BuildToolInfo;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.IAndroidTarget.IOptionalLibrary;
-import com.android.sdklib.build.ApkBuilder;
-import com.android.sdklib.build.ApkBuilder.JarStatus;
-import com.android.sdklib.build.ApkBuilder.SigningInfo;
-import com.android.sdklib.build.ApkCreationException;
-import com.android.sdklib.build.DuplicateFileException;
-import com.android.sdklib.build.RenderScriptProcessor;
-import com.android.sdklib.build.SealedApkException;
-import com.android.sdklib.internal.build.DebugKeyProvider;
-import com.android.sdklib.internal.build.DebugKeyProvider.KeytoolException;
-import com.android.utils.GrabProcessOutput;
-import com.android.utils.GrabProcessOutput.IProcessOutput;
-import com.android.utils.GrabProcessOutput.Wait;
-import com.google.common.base.Charsets;
-import com.google.common.hash.HashCode;
-import com.google.common.hash.HashFunction;
-import com.google.common.hash.Hashing;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jdt.core.IClasspathContainer;
-import org.eclipse.jdt.core.IClasspathEntry;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jface.preference.IPreferenceStore;
-
-import java.io.File;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.PrintStream;
-import java.security.PrivateKey;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-
-/**
- * Helper with methods for the last 3 steps of the generation of an APK.
- *
- * {@link #packageResources(IFile, IProject[], String, int, String, String)} packages the
- * application resources using aapt into a zip file that is ready to be integrated into the apk.
- *
- * {@link #executeDx(IJavaProject, String, String, IJavaProject[])} will convert the Java byte
- * code into the Dalvik bytecode.
- *
- * {@link #finalPackage(String, String, String, boolean, IJavaProject, IProject[], IJavaProject[], String, boolean)}
- * will make the apk from all the previous components.
- *
- * This class only executes the 3 above actions. It does not handle the errors, and simply sends
- * them back as custom exceptions.
- *
- * Warnings are handled by the {@link ResourceMarker} interface.
- *
- * Console output (verbose and non verbose) is handled through the {@link AndroidPrintStream} passed
- * to the constructor.
- *
- */
-public class BuildHelper {
-
- private static final String CONSOLE_PREFIX_DX = "Dx"; //$NON-NLS-1$
- private final static String TEMP_PREFIX = "android_"; //$NON-NLS-1$
-
- private static final String COMMAND_CRUNCH = "crunch"; //$NON-NLS-1$
- private static final String COMMAND_PACKAGE = "package"; //$NON-NLS-1$
-
- @NonNull
- private final ProjectState mProjectState;
- @NonNull
- private final IProject mProject;
- @NonNull
- private final BuildToolInfo mBuildToolInfo;
- @NonNull
- private final AndroidPrintStream mOutStream;
- @NonNull
- private final AndroidPrintStream mErrStream;
- private final boolean mForceJumbo;
- private final boolean mDisableDexMerger;
- private final boolean mVerbose;
- private final boolean mDebugMode;
-
- private final Set<String> mCompiledCodePaths = new HashSet<String>();
-
- public static final boolean BENCHMARK_FLAG = false;
- public static long sStartOverallTime = 0;
- public static long sStartJavaCTime = 0;
-
- private final static int MILLION = 1000000;
- private String mProguardFile;
-
- /**
- * An object able to put a marker on a resource.
- */
- public interface ResourceMarker {
- void setWarning(IResource resource, String message);
- }
-
- /**
- * Creates a new post-compiler helper
- * @param project
- * @param outStream
- * @param errStream
- * @param debugMode whether this is a debug build
- * @param verbose
- * @throws CoreException
- */
- public BuildHelper(@NonNull ProjectState projectState,
- @NonNull BuildToolInfo buildToolInfo,
- @NonNull AndroidPrintStream outStream,
- @NonNull AndroidPrintStream errStream,
- boolean forceJumbo, boolean disableDexMerger, boolean debugMode,
- boolean verbose, ResourceMarker resMarker) throws CoreException {
- mProjectState = projectState;
- mProject = projectState.getProject();
- mBuildToolInfo = buildToolInfo;
- mOutStream = outStream;
- mErrStream = errStream;
- mDebugMode = debugMode;
- mVerbose = verbose;
- mForceJumbo = forceJumbo;
- mDisableDexMerger = disableDexMerger;
-
- gatherPaths(resMarker);
- }
-
- public void updateCrunchCache() throws AaptExecException, AaptResultException {
- // Benchmarking start
- long startCrunchTime = 0;
- if (BENCHMARK_FLAG) {
- String msg = "BENCHMARK ADT: Starting Initial Packaging (.ap_)"; //$NON-NLS-1$
- AdtPlugin.printBuildToConsole(BuildVerbosity.ALWAYS, mProject, msg);
- startCrunchTime = System.nanoTime();
- }
-
- // Get the resources folder to crunch from
- IFolder resFolder = mProject.getFolder(AdtConstants.WS_RESOURCES);
- List<String> resPaths = new ArrayList<String>();
- resPaths.add(resFolder.getLocation().toOSString());
-
- // Get the output folder where the cache is stored.
- IFolder binFolder = BaseProjectHelper.getAndroidOutputFolder(mProject);
- IFolder cacheFolder = binFolder.getFolder(AdtConstants.WS_BIN_RELATIVE_CRUNCHCACHE);
- String cachePath = cacheFolder.getLocation().toOSString();
-
- /* For crunching, we don't need the osManifestPath, osAssetsPath, or the configFilter
- * parameters for executeAapt
- */
- executeAapt(COMMAND_CRUNCH, "", resPaths, "", cachePath, "", 0);
-
- // Benchmarking end
- if (BENCHMARK_FLAG) {
- String msg = "BENCHMARK ADT: Ending Initial Package (.ap_). \nTime Elapsed: " //$NON-NLS-1$
- + ((System.nanoTime() - startCrunchTime)/MILLION) + "ms"; //$NON-NLS-1$
- AdtPlugin.printBuildToConsole(BuildVerbosity.ALWAYS, mProject, msg);
- }
- }
-
- /**
- * Packages the resources of the projet into a .ap_ file.
- * @param manifestFile the manifest of the project.
- * @param libProjects the list of library projects that this project depends on.
- * @param resFilter an optional resource filter to be used with the -c option of aapt. If null
- * no filters are used.
- * @param versionCode an optional versionCode to be inserted in the manifest during packaging.
- * If the value is <=0, no values are inserted.
- * @param outputFolder where to write the resource ap_ file.
- * @param outputFilename the name of the resource ap_ file.
- * @throws AaptExecException
- * @throws AaptResultException
- */
- public void packageResources(IFile manifestFile, List<IProject> libProjects, String resFilter,
- int versionCode, String outputFolder, String outputFilename)
- throws AaptExecException, AaptResultException {
-
- // Benchmarking start
- long startPackageTime = 0;
- if (BENCHMARK_FLAG) {
- String msg = "BENCHMARK ADT: Starting Initial Packaging (.ap_)"; //$NON-NLS-1$
- AdtPlugin.printBuildToConsole(BuildVerbosity.ALWAYS, mProject, msg);
- startPackageTime = System.nanoTime();
- }
-
- // need to figure out some path before we can execute aapt;
- IFolder binFolder = BaseProjectHelper.getAndroidOutputFolder(mProject);
-
- // get the cache folder
- IFolder cacheFolder = binFolder.getFolder(AdtConstants.WS_BIN_RELATIVE_CRUNCHCACHE);
-
- // get the BC folder
- IFolder bcFolder = binFolder.getFolder(AdtConstants.WS_BIN_RELATIVE_BC);
-
- // get the resource folder
- IFolder resFolder = mProject.getFolder(AdtConstants.WS_RESOURCES);
-
- // and the assets folder
- IFolder assetsFolder = mProject.getFolder(AdtConstants.WS_ASSETS);
-
- // we need to make sure this one exists.
- if (assetsFolder.exists() == false) {
- assetsFolder = null;
- }
-
- // list of res folder (main project + maybe libraries)
- ArrayList<String> osResPaths = new ArrayList<String>();
-
- IPath resLocation = resFolder.getLocation();
- IPath manifestLocation = manifestFile.getLocation();
-
- if (resLocation != null && manifestLocation != null) {
-
- // png cache folder first.
- addFolderToList(osResPaths, cacheFolder);
- addFolderToList(osResPaths, bcFolder);
-
- // regular res folder next.
- osResPaths.add(resLocation.toOSString());
-
- // then libraries
- if (libProjects != null) {
- for (IProject lib : libProjects) {
- // png cache folder first
- IFolder libBinFolder = BaseProjectHelper.getAndroidOutputFolder(lib);
-
- IFolder libCacheFolder = libBinFolder.getFolder(AdtConstants.WS_BIN_RELATIVE_CRUNCHCACHE);
- addFolderToList(osResPaths, libCacheFolder);
-
- IFolder libBcFolder = libBinFolder.getFolder(AdtConstants.WS_BIN_RELATIVE_BC);
- addFolderToList(osResPaths, libBcFolder);
-
- // regular res folder next.
- IFolder libResFolder = lib.getFolder(AdtConstants.WS_RESOURCES);
- addFolderToList(osResPaths, libResFolder);
- }
- }
-
- String osManifestPath = manifestLocation.toOSString();
-
- String osAssetsPath = null;
- if (assetsFolder != null) {
- osAssetsPath = assetsFolder.getLocation().toOSString();
- }
-
- // build the default resource package
- executeAapt(COMMAND_PACKAGE, osManifestPath, osResPaths, osAssetsPath,
- outputFolder + File.separator + outputFilename, resFilter,
- versionCode);
- }
-
- // Benchmarking end
- if (BENCHMARK_FLAG) {
- String msg = "BENCHMARK ADT: Ending Initial Package (.ap_). \nTime Elapsed: " //$NON-NLS-1$
- + ((System.nanoTime() - startPackageTime)/MILLION) + "ms"; //$NON-NLS-1$
- AdtPlugin.printBuildToConsole(BuildVerbosity.ALWAYS, mProject, msg);
- }
- }
-
- /**
- * Adds os path of a folder to a list only if the folder actually exists.
- * @param pathList
- * @param folder
- */
- private void addFolderToList(List<String> pathList, IFolder folder) {
- // use a File instead of the IFolder API to ignore workspace refresh issue.
- File testFile = new File(folder.getLocation().toOSString());
- if (testFile.isDirectory()) {
- pathList.add(testFile.getAbsolutePath());
- }
- }
-
- /**
- * Makes a final package signed with the debug key.
- *
- * Packages the dex files, the temporary resource file into the final package file.
- *
- * Whether the package is a debug package is controlled with the <var>debugMode</var> parameter
- * in {@link #PostCompilerHelper(IProject, PrintStream, PrintStream, boolean, boolean)}
- *
- * @param intermediateApk The path to the temporary resource file.
- * @param dex The path to the dex file.
- * @param output The path to the final package file to create.
- * @param libProjects an optional list of library projects (can be null)
- * @return true if success, false otherwise.
- * @throws ApkCreationException
- * @throws AndroidLocationException
- * @throws KeytoolException
- * @throws NativeLibInJarException
- * @throws CoreException
- * @throws DuplicateFileException
- */
- public void finalDebugPackage(String intermediateApk, String dex, String output,
- List<IProject> libProjects, ResourceMarker resMarker)
- throws ApkCreationException, KeytoolException, AndroidLocationException,
- NativeLibInJarException, DuplicateFileException, CoreException {
-
- AdtPlugin adt = AdtPlugin.getDefault();
- if (adt == null) {
- return;
- }
-
- // get the debug keystore to use.
- IPreferenceStore store = adt.getPreferenceStore();
- String keystoreOsPath = store.getString(AdtPrefs.PREFS_CUSTOM_DEBUG_KEYSTORE);
- if (keystoreOsPath == null || new File(keystoreOsPath).isFile() == false) {
- keystoreOsPath = DebugKeyProvider.getDefaultKeyStoreOsPath();
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, mProject,
- Messages.ApkBuilder_Using_Default_Key);
- } else {
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, mProject,
- String.format(Messages.ApkBuilder_Using_s_To_Sign, keystoreOsPath));
- }
-
- // from the keystore, get the signing info
- SigningInfo info = ApkBuilder.getDebugKey(keystoreOsPath, mVerbose ? mOutStream : null);
-
- finalPackage(intermediateApk, dex, output, libProjects,
- info != null ? info.key : null, info != null ? info.certificate : null, resMarker);
- }
-
- /**
- * Makes the final package.
- *
- * Packages the dex files, the temporary resource file into the final package file.
- *
- * Whether the package is a debug package is controlled with the <var>debugMode</var> parameter
- * in {@link #PostCompilerHelper(IProject, PrintStream, PrintStream, boolean, boolean)}
- *
- * @param intermediateApk The path to the temporary resource file.
- * @param dex The path to the dex file.
- * @param output The path to the final package file to create.
- * @param debugSign whether the apk must be signed with the debug key.
- * @param libProjects an optional list of library projects (can be null)
- * @param abiFilter an optional filter. If not null, then only the matching ABI is included in
- * the final archive
- * @return true if success, false otherwise.
- * @throws NativeLibInJarException
- * @throws ApkCreationException
- * @throws CoreException
- * @throws DuplicateFileException
- */
- public void finalPackage(String intermediateApk, String dex, String output,
- List<IProject> libProjects,
- PrivateKey key, X509Certificate certificate, ResourceMarker resMarker)
- throws NativeLibInJarException, ApkCreationException, DuplicateFileException,
- CoreException {
-
- try {
- ApkBuilder apkBuilder = new ApkBuilder(output, intermediateApk, dex,
- key, certificate,
- mVerbose ? mOutStream: null);
- apkBuilder.setDebugMode(mDebugMode);
-
- // either use the full compiled code paths or just the proguard file
- // if present
- Collection<String> pathsCollection = mCompiledCodePaths;
- if (mProguardFile != null) {
- pathsCollection = Collections.singletonList(mProguardFile);
- mProguardFile = null;
- }
-
- // Now we write the standard resources from all the output paths.
- for (String path : pathsCollection) {
- File file = new File(path);
- if (file.isFile()) {
- JarStatus jarStatus = apkBuilder.addResourcesFromJar(file);
-
- // check if we found native libraries in the external library. This
- // constitutes an error or warning depending on if they are in lib/
- if (jarStatus.getNativeLibs().size() > 0) {
- String libName = file.getName();
-
- String msg = String.format(
- "Native libraries detected in '%1$s'. See console for more information.",
- libName);
-
- ArrayList<String> consoleMsgs = new ArrayList<String>();
-
- consoleMsgs.add(String.format(
- "The library '%1$s' contains native libraries that will not run on the device.",
- libName));
-
- if (jarStatus.hasNativeLibsConflicts()) {
- consoleMsgs.add("Additionally some of those libraries will interfer with the installation of the application because of their location in lib/");
- consoleMsgs.add("lib/ is reserved for NDK libraries.");
- }
-
- consoleMsgs.add("The following libraries were found:");
-
- for (String lib : jarStatus.getNativeLibs()) {
- consoleMsgs.add(" - " + lib);
- }
-
- String[] consoleStrings = consoleMsgs.toArray(new String[consoleMsgs.size()]);
-
- // if there's a conflict or if the prefs force error on any native code in jar
- // files, throw an exception
- if (jarStatus.hasNativeLibsConflicts() ||
- AdtPrefs.getPrefs().getBuildForceErrorOnNativeLibInJar()) {
- throw new NativeLibInJarException(jarStatus, msg, libName, consoleStrings);
- } else {
- // otherwise, put a warning, and output to the console also.
- if (resMarker != null) {
- resMarker.setWarning(mProject, msg);
- }
-
- for (String string : consoleStrings) {
- mOutStream.println(string);
- }
- }
- }
- } else if (file.isDirectory()) {
- // this is technically not a source folder (class folder instead) but since we
- // only care about Java resources (ie non class/java files) this will do the
- // same
- apkBuilder.addSourceFolder(file);
- }
- }
-
- // now write the native libraries.
- // First look if the lib folder is there.
- IResource libFolder = mProject.findMember(SdkConstants.FD_NATIVE_LIBS);
- if (libFolder != null && libFolder.exists() &&
- libFolder.getType() == IResource.FOLDER) {
- // get a File for the folder.
- apkBuilder.addNativeLibraries(libFolder.getLocation().toFile());
- }
-
- // next the native libraries for the renderscript support mode.
- if (mProjectState.getRenderScriptSupportMode()) {
- IFolder androidOutputFolder = BaseProjectHelper.getAndroidOutputFolder(mProject);
- IResource rsLibFolder = androidOutputFolder.getFolder(
- AdtConstants.WS_BIN_RELATIVE_RS_LIBS);
- File rsLibFolderFile = rsLibFolder.getLocation().toFile();
- if (rsLibFolderFile.isDirectory()) {
- apkBuilder.addNativeLibraries(rsLibFolderFile);
- }
-
- File rsLibs = RenderScriptProcessor.getSupportNativeLibFolder(
- mBuildToolInfo.getLocation().getAbsolutePath());
- if (rsLibs.isDirectory()) {
- apkBuilder.addNativeLibraries(rsLibs);
- }
- }
-
- // write the native libraries for the library projects.
- if (libProjects != null) {
- for (IProject lib : libProjects) {
- libFolder = lib.findMember(SdkConstants.FD_NATIVE_LIBS);
- if (libFolder != null && libFolder.exists() &&
- libFolder.getType() == IResource.FOLDER) {
- apkBuilder.addNativeLibraries(libFolder.getLocation().toFile());
- }
- }
- }
-
- // seal the APK.
- apkBuilder.sealApk();
- } catch (SealedApkException e) {
- // this won't happen as we control when the apk is sealed.
- }
- }
-
- public void setProguardOutput(String proguardFile) {
- mProguardFile = proguardFile;
- }
-
- public Collection<String> getCompiledCodePaths() {
- return mCompiledCodePaths;
- }
-
- public void runProguard(List<File> proguardConfigs, File inputJar, Collection<String> jarFiles,
- File obfuscatedJar, File logOutput)
- throws ProguardResultException, ProguardExecException, IOException {
- IAndroidTarget target = Sdk.getCurrent().getTarget(mProject);
-
- // prepare the command line for proguard
- List<String> command = new ArrayList<String>();
- command.add(AdtPlugin.getOsAbsoluteProguard());
-
- for (File configFile : proguardConfigs) {
- command.add("-include"); //$NON-NLS-1$
- command.add(quotePath(configFile.getAbsolutePath()));
- }
-
- command.add("-injars"); //$NON-NLS-1$
- StringBuilder sb = new StringBuilder(quotePath(inputJar.getAbsolutePath()));
- for (String jarFile : jarFiles) {
- sb.append(File.pathSeparatorChar);
- sb.append(quotePath(jarFile));
- }
- command.add(quoteWinArg(sb.toString()));
-
- command.add("-outjars"); //$NON-NLS-1$
- command.add(quotePath(obfuscatedJar.getAbsolutePath()));
-
- command.add("-libraryjars"); //$NON-NLS-1$
- sb = new StringBuilder(quotePath(target.getPath(IAndroidTarget.ANDROID_JAR)));
- IOptionalLibrary[] libraries = target.getOptionalLibraries();
- if (libraries != null) {
- for (IOptionalLibrary lib : libraries) {
- sb.append(File.pathSeparatorChar);
- sb.append(quotePath(lib.getJarPath()));
- }
- }
- command.add(quoteWinArg(sb.toString()));
-
- if (logOutput != null) {
- if (logOutput.isDirectory() == false) {
- logOutput.mkdirs();
- }
-
- command.add("-dump"); //$NON-NLS-1$
- command.add(new File(logOutput, "dump.txt").getAbsolutePath()); //$NON-NLS-1$
-
- command.add("-printseeds"); //$NON-NLS-1$
- command.add(new File(logOutput, "seeds.txt").getAbsolutePath()); //$NON-NLS-1$
-
- command.add("-printusage"); //$NON-NLS-1$
- command.add(new File(logOutput, "usage.txt").getAbsolutePath()); //$NON-NLS-1$
-
- command.add("-printmapping"); //$NON-NLS-1$
- command.add(new File(logOutput, "mapping.txt").getAbsolutePath()); //$NON-NLS-1$
- }
-
- String commandArray[] = null;
-
- if (SdkConstants.currentPlatform() == SdkConstants.PLATFORM_WINDOWS) {
- commandArray = createWindowsProguardConfig(command);
- }
-
- if (commandArray == null) {
- // For Mac & Linux, use a regular command string array.
- commandArray = command.toArray(new String[command.size()]);
- }
-
- // Define PROGUARD_HOME to point to $SDK/tools/proguard if it's not yet defined.
- // The Mac/Linux proguard.sh can infer it correctly but not the proguard.bat one.
- String[] envp = null;
- Map<String, String> envMap = new TreeMap<String, String>(System.getenv());
- if (!envMap.containsKey("PROGUARD_HOME")) { //$NON-NLS-1$
- envMap.put("PROGUARD_HOME", Sdk.getCurrent().getSdkOsLocation() + //$NON-NLS-1$
- SdkConstants.FD_TOOLS + File.separator +
- SdkConstants.FD_PROGUARD);
- envp = new String[envMap.size()];
- int i = 0;
- for (Map.Entry<String, String> entry : envMap.entrySet()) {
- envp[i++] = String.format("%1$s=%2$s", //$NON-NLS-1$
- entry.getKey(),
- entry.getValue());
- }
- }
-
- if (AdtPrefs.getPrefs().getBuildVerbosity() == BuildVerbosity.VERBOSE) {
- sb = new StringBuilder();
- for (String c : commandArray) {
- sb.append(c).append(' ');
- }
- AdtPlugin.printToConsole(mProject, sb.toString());
- }
-
- // launch
- int execError = 1;
- try {
- // launch the command line process
- Process process = Runtime.getRuntime().exec(commandArray, envp);
-
- // list to store each line of stderr
- ArrayList<String> results = new ArrayList<String>();
-
- // get the output and return code from the process
- execError = grabProcessOutput(mProject, process, results);
-
- if (mVerbose) {
- for (String resultString : results) {
- mOutStream.println(resultString);
- }
- }
-
- if (execError != 0) {
- throw new ProguardResultException(execError,
- results.toArray(new String[results.size()]));
- }
-
- } catch (IOException e) {
- String msg = String.format(Messages.Proguard_Exec_Error, commandArray[0]);
- throw new ProguardExecException(msg, e);
- } catch (InterruptedException e) {
- String msg = String.format(Messages.Proguard_Exec_Error, commandArray[0]);
- throw new ProguardExecException(msg, e);
- }
- }
-
- /**
- * For tools R8 up to R11, the proguard.bat launcher on Windows only accepts
- * arguments %1..%9. Since we generally have about 15 arguments, we were working
- * around this by generating a temporary config file for proguard and then using
- * that.
- * Starting with tools R12, the proguard.bat launcher has been fixed to take
- * all arguments using %* so we no longer need this hack.
- *
- * @param command
- * @return
- * @throws IOException
- */
- private String[] createWindowsProguardConfig(List<String> command) throws IOException {
-
- // Arg 0 is the proguard.bat path and arg 1 is the user config file
- String launcher = AdtPlugin.readFile(new File(command.get(0)));
- if (launcher.contains("%*")) { //$NON-NLS-1$
- // This is the launcher from Tools R12. Don't work around it.
- return null;
- }
-
- // On Windows, proguard.bat can only pass %1...%9 to the java -jar proguard.jar
- // call, but we have at least 15 arguments here so some get dropped silently
- // and quoting is a big issue. So instead we'll work around that by writing
- // all the arguments to a temporary config file.
-
- String[] commandArray = new String[3];
-
- commandArray[0] = command.get(0);
- commandArray[1] = command.get(1);
-
- // Write all the other arguments to a config file
- File argsFile = File.createTempFile(TEMP_PREFIX, ".pro"); //$NON-NLS-1$
- // TODO FIXME this may leave a lot of temp files around on a long session.
- // Should have a better way to clean up e.g. before each build.
- argsFile.deleteOnExit();
-
- FileWriter fw = new FileWriter(argsFile);
-
- for (int i = 2; i < command.size(); i++) {
- String s = command.get(i);
- fw.write(s);
- fw.write(s.startsWith("-") ? ' ' : '\n'); //$NON-NLS-1$
- }
-
- fw.close();
-
- commandArray[2] = "@" + argsFile.getAbsolutePath(); //$NON-NLS-1$
- return commandArray;
- }
-
- /**
- * Quotes a single path for proguard to deal with spaces.
- *
- * @param path The path to quote.
- * @return The original path if it doesn't contain a space.
- * Or the original path surrounded by single quotes if it contains spaces.
- */
- private String quotePath(String path) {
- if (path.indexOf(' ') != -1) {
- path = '\'' + path + '\'';
- }
- return path;
- }
-
- /**
- * Quotes a compound proguard argument to deal with spaces.
- * <p/>
- * Proguard takes multi-path arguments such as "path1;path2" for some options.
- * When the {@link #quotePath} methods adds quotes for such a path if it contains spaces,
- * the proguard shell wrapper will absorb the quotes, so we need to quote around the
- * quotes.
- *
- * @param path The path to quote.
- * @return The original path if it doesn't contain a single quote.
- * Or on Windows the original path surrounded by double quotes if it contains a quote.
- */
- private String quoteWinArg(String path) {
- if (path.indexOf('\'') != -1 &&
- SdkConstants.currentPlatform() == SdkConstants.PLATFORM_WINDOWS) {
- path = '"' + path + '"';
- }
- return path;
- }
-
-
- /**
- * Execute the Dx tool for dalvik code conversion.
- * @param javaProject The java project
- * @param inputPaths the input paths for DX
- * @param osOutFilePath the path of the dex file to create.
- *
- * @throws CoreException
- * @throws DexException
- */
- public void executeDx(IJavaProject javaProject, Collection<String> inputPaths,
- String osOutFilePath)
- throws CoreException, DexException {
-
- // get the dex wrapper
- Sdk sdk = Sdk.getCurrent();
- DexWrapper wrapper = sdk.getDexWrapper(mBuildToolInfo);
-
- if (wrapper == null) {
- throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- Messages.ApkBuilder_UnableBuild_Dex_Not_loaded));
- }
-
- try {
- // set a temporary prefix on the print streams.
- mOutStream.setPrefix(CONSOLE_PREFIX_DX);
- mErrStream.setPrefix(CONSOLE_PREFIX_DX);
-
- IFolder binFolder = BaseProjectHelper.getAndroidOutputFolder(javaProject.getProject());
- File binFile = binFolder.getLocation().toFile();
- File dexedLibs = new File(binFile, "dexedLibs");
- if (dexedLibs.exists() == false) {
- dexedLibs.mkdir();
- }
-
- // replace the libs by their dexed versions (dexing them if needed.)
- List<String> finalInputPaths = new ArrayList<String>(inputPaths.size());
- if (mDisableDexMerger || inputPaths.size() == 1) {
- // only one input, no need to put a pre-dexed version, even if this path is
- // just a jar file (case for proguard'ed builds)
- finalInputPaths.addAll(inputPaths);
- } else {
-
- for (String input : inputPaths) {
- File inputFile = new File(input);
- if (inputFile.isDirectory()) {
- finalInputPaths.add(input);
- } else if (inputFile.isFile()) {
- String fileName = getDexFileName(inputFile);
-
- File dexedLib = new File(dexedLibs, fileName);
- String dexedLibPath = dexedLib.getAbsolutePath();
-
- if (dexedLib.isFile() == false ||
- dexedLib.lastModified() < inputFile.lastModified()) {
-
- if (mVerbose) {
- mOutStream.println(
- String.format("Pre-Dexing %1$s -> %2$s", input, fileName));
- }
-
- if (dexedLib.isFile()) {
- dexedLib.delete();
- }
-
- int res = wrapper.run(dexedLibPath, Collections.singleton(input),
- mForceJumbo, mVerbose, mOutStream, mErrStream);
-
- if (res != 0) {
- // output error message and mark the project.
- String message = String.format(Messages.Dalvik_Error_d, res);
- throw new DexException(message);
- }
- } else {
- if (mVerbose) {
- mOutStream.println(
- String.format("Using Pre-Dexed %1$s <- %2$s",
- fileName, input));
- }
- }
-
- finalInputPaths.add(dexedLibPath);
- }
- }
- }
-
- if (mVerbose) {
- for (String input : finalInputPaths) {
- mOutStream.println("Input: " + input);
- }
- }
-
- int res = wrapper.run(osOutFilePath,
- finalInputPaths,
- mForceJumbo,
- mVerbose,
- mOutStream, mErrStream);
-
- mOutStream.setPrefix(null);
- mErrStream.setPrefix(null);
-
- if (res != 0) {
- // output error message and marker the project.
- String message = String.format(Messages.Dalvik_Error_d, res);
- throw new DexException(message);
- }
- } catch (DexException e) {
- throw e;
- } catch (Throwable t) {
- String message = t.getMessage();
- if (message == null) {
- message = t.getClass().getCanonicalName();
- }
- message = String.format(Messages.Dalvik_Error_s, message);
-
- throw new DexException(message, t);
- }
- }
-
- private String getDexFileName(File inputFile) {
- // get the filename
- String name = inputFile.getName();
- // remove the extension
- int pos = name.lastIndexOf('.');
- if (pos != -1) {
- name = name.substring(0, pos);
- }
-
- // add a hash of the original file path
- HashFunction hashFunction = Hashing.md5();
- HashCode hashCode = hashFunction.hashString(inputFile.getAbsolutePath(), Charsets.UTF_8);
-
- return name + "-" + hashCode.toString() + ".jar";
- }
-
- /**
- * Executes aapt. If any error happen, files or the project will be marked.
- * @param command The command for aapt to execute. Currently supported: package and crunch
- * @param osManifestPath The path to the manifest file
- * @param osResPath The path to the res folder
- * @param osAssetsPath The path to the assets folder. This can be null.
- * @param osOutFilePath The path to the temporary resource file to create,
- * or in the case of crunching the path to the cache to create/update.
- * @param configFilter The configuration filter for the resources to include
- * (used with -c option, for example "port,en,fr" to include portrait, English and French
- * resources.)
- * @param versionCode optional version code to insert in the manifest during packaging. If <=0
- * then no value is inserted
- * @throws AaptExecException
- * @throws AaptResultException
- */
- private void executeAapt(String aaptCommand, String osManifestPath,
- List<String> osResPaths, String osAssetsPath, String osOutFilePath,
- String configFilter, int versionCode) throws AaptExecException, AaptResultException {
- IAndroidTarget target = Sdk.getCurrent().getTarget(mProject);
-
- String aapt = mBuildToolInfo.getPath(BuildToolInfo.PathId.AAPT);
-
- // Create the command line.
- ArrayList<String> commandArray = new ArrayList<String>();
- commandArray.add(aapt);
- commandArray.add(aaptCommand);
- if (AdtPrefs.getPrefs().getBuildVerbosity() == BuildVerbosity.VERBOSE) {
- commandArray.add("-v"); //$NON-NLS-1$
- }
-
- // Common to all commands
- for (String path : osResPaths) {
- commandArray.add("-S"); //$NON-NLS-1$
- commandArray.add(path);
- }
-
- if (aaptCommand.equals(COMMAND_PACKAGE)) {
- commandArray.add("-f"); //$NON-NLS-1$
- commandArray.add("--no-crunch"); //$NON-NLS-1$
-
- // if more than one res, this means there's a library (or more) and we need
- // to activate the auto-add-overlay
- if (osResPaths.size() > 1) {
- commandArray.add("--auto-add-overlay"); //$NON-NLS-1$
- }
-
- if (mDebugMode) {
- commandArray.add("--debug-mode"); //$NON-NLS-1$
- }
-
- if (versionCode > 0) {
- commandArray.add("--version-code"); //$NON-NLS-1$
- commandArray.add(Integer.toString(versionCode));
- }
-
- if (configFilter != null) {
- commandArray.add("-c"); //$NON-NLS-1$
- commandArray.add(configFilter);
- }
-
- // never compress apks.
- commandArray.add("-0");
- commandArray.add("apk");
-
- commandArray.add("-M"); //$NON-NLS-1$
- commandArray.add(osManifestPath);
-
- if (osAssetsPath != null) {
- commandArray.add("-A"); //$NON-NLS-1$
- commandArray.add(osAssetsPath);
- }
-
- commandArray.add("-I"); //$NON-NLS-1$
- commandArray.add(target.getPath(IAndroidTarget.ANDROID_JAR));
-
- commandArray.add("-F"); //$NON-NLS-1$
- commandArray.add(osOutFilePath);
- } else if (aaptCommand.equals(COMMAND_CRUNCH)) {
- commandArray.add("-C"); //$NON-NLS-1$
- commandArray.add(osOutFilePath);
- }
-
- String command[] = commandArray.toArray(
- new String[commandArray.size()]);
-
- if (AdtPrefs.getPrefs().getBuildVerbosity() == BuildVerbosity.VERBOSE) {
- StringBuilder sb = new StringBuilder();
- for (String c : command) {
- sb.append(c);
- sb.append(' ');
- }
- AdtPlugin.printToConsole(mProject, sb.toString());
- }
-
- // Benchmarking start
- long startAaptTime = 0;
- if (BENCHMARK_FLAG) {
- String msg = "BENCHMARK ADT: Starting " + aaptCommand //$NON-NLS-1$
- + " call to Aapt"; //$NON-NLS-1$
- AdtPlugin.printBuildToConsole(BuildVerbosity.ALWAYS, mProject, msg);
- startAaptTime = System.nanoTime();
- }
-
- // launch
- try {
- // launch the command line process
- Process process = Runtime.getRuntime().exec(command);
-
- // list to store each line of stderr
- ArrayList<String> stdErr = new ArrayList<String>();
-
- // get the output and return code from the process
- int returnCode = grabProcessOutput(mProject, process, stdErr);
-
- if (mVerbose) {
- for (String stdErrString : stdErr) {
- mOutStream.println(stdErrString);
- }
- }
- if (returnCode != 0) {
- throw new AaptResultException(returnCode,
- stdErr.toArray(new String[stdErr.size()]));
- }
- } catch (IOException e) {
- String msg = String.format(Messages.AAPT_Exec_Error_s, command[0]);
- throw new AaptExecException(msg, e);
- } catch (InterruptedException e) {
- String msg = String.format(Messages.AAPT_Exec_Error_s, command[0]);
- throw new AaptExecException(msg, e);
- }
-
- // Benchmarking end
- if (BENCHMARK_FLAG) {
- String msg = "BENCHMARK ADT: Ending " + aaptCommand //$NON-NLS-1$
- + " call to Aapt.\nBENCHMARK ADT: Time Elapsed: " //$NON-NLS-1$
- + ((System.nanoTime() - startAaptTime)/MILLION) + "ms"; //$NON-NLS-1$
- AdtPlugin.printBuildToConsole(BuildVerbosity.ALWAYS, mProject, msg);
- }
- }
-
- /**
- * Computes all the project output and dependencies that must go into building the apk.
- *
- * @param resMarker
- * @throws CoreException
- */
- private void gatherPaths(ResourceMarker resMarker)
- throws CoreException {
- IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();
-
- // get a java project for the project.
- IJavaProject javaProject = JavaCore.create(mProject);
-
-
- // get the output of the main project
- IPath path = javaProject.getOutputLocation();
- IResource outputResource = wsRoot.findMember(path);
- if (outputResource != null && outputResource.getType() == IResource.FOLDER) {
- mCompiledCodePaths.add(outputResource.getLocation().toOSString());
- }
-
- // we could use IJavaProject.getResolvedClasspath directly, but we actually
- // want to see the containers themselves.
- IClasspathEntry[] classpaths = javaProject.readRawClasspath();
- if (classpaths != null) {
- for (IClasspathEntry e : classpaths) {
- // ignore non exported entries, unless they're in the DEPEDENCIES container,
- // in which case we always want it (there may be some older projects that
- // have it as non exported).
- if (e.isExported() ||
- (e.getEntryKind() == IClasspathEntry.CPE_CONTAINER &&
- e.getPath().toString().equals(AdtConstants.CONTAINER_DEPENDENCIES))) {
- handleCPE(e, javaProject, wsRoot, resMarker);
- }
- }
- }
- }
-
- private void handleCPE(IClasspathEntry entry, IJavaProject javaProject,
- IWorkspaceRoot wsRoot, ResourceMarker resMarker) {
-
- // if this is a classpath variable reference, we resolve it.
- if (entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
- entry = JavaCore.getResolvedClasspathEntry(entry);
- }
-
- if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
- IProject refProject = wsRoot.getProject(entry.getPath().lastSegment());
- try {
- // ignore if it's an Android project, or if it's not a Java Project
- if (refProject.hasNature(JavaCore.NATURE_ID) &&
- refProject.hasNature(AdtConstants.NATURE_DEFAULT) == false) {
- IJavaProject refJavaProject = JavaCore.create(refProject);
-
- // get the output folder
- IPath path = refJavaProject.getOutputLocation();
- IResource outputResource = wsRoot.findMember(path);
- if (outputResource != null && outputResource.getType() == IResource.FOLDER) {
- mCompiledCodePaths.add(outputResource.getLocation().toOSString());
- }
- }
- } catch (CoreException exception) {
- // can't query the project nature? ignore
- }
-
- } else if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
- handleClasspathLibrary(entry, wsRoot, resMarker);
- } else if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
- // get the container
- try {
- IClasspathContainer container = JavaCore.getClasspathContainer(
- entry.getPath(), javaProject);
- // ignore the system and default_system types as they represent
- // libraries that are part of the runtime.
- if (container != null && container.getKind() == IClasspathContainer.K_APPLICATION) {
- IClasspathEntry[] entries = container.getClasspathEntries();
- for (IClasspathEntry cpe : entries) {
- handleCPE(cpe, javaProject, wsRoot, resMarker);
- }
- }
- } catch (JavaModelException jme) {
- // can't resolve the container? ignore it.
- AdtPlugin.log(jme, "Failed to resolve ClasspathContainer: %s", entry.getPath());
- }
- }
- }
-
- private void handleClasspathLibrary(IClasspathEntry e, IWorkspaceRoot wsRoot,
- ResourceMarker resMarker) {
- // get the IPath
- IPath path = e.getPath();
-
- IResource resource = wsRoot.findMember(path);
-
- if (resource != null && resource.getType() == IResource.PROJECT) {
- // if it's a project we should just ignore it because it's going to be added
- // later when we add all the referenced projects.
-
- } else if (SdkConstants.EXT_JAR.equalsIgnoreCase(path.getFileExtension())) {
- // case of a jar file (which could be relative to the workspace or a full path)
- if (resource != null && resource.exists() &&
- resource.getType() == IResource.FILE) {
- mCompiledCodePaths.add(resource.getLocation().toOSString());
- } else {
- // if the jar path doesn't match a workspace resource,
- // then we get an OSString and check if this links to a valid file.
- String osFullPath = path.toOSString();
-
- File f = new File(osFullPath);
- if (f.isFile()) {
- mCompiledCodePaths.add(osFullPath);
- } else {
- String message = String.format( Messages.Couldnt_Locate_s_Error,
- path);
- // always output to the console
- mOutStream.println(message);
-
- // put a marker
- if (resMarker != null) {
- resMarker.setWarning(mProject, message);
- }
- }
- }
- } else {
- // this can be the case for a class folder.
- if (resource != null && resource.exists() &&
- resource.getType() == IResource.FOLDER) {
- mCompiledCodePaths.add(resource.getLocation().toOSString());
- } else {
- // if the path doesn't match a workspace resource,
- // then we get an OSString and check if this links to a valid folder.
- String osFullPath = path.toOSString();
-
- File f = new File(osFullPath);
- if (f.isDirectory()) {
- mCompiledCodePaths.add(osFullPath);
- }
- }
- }
- }
-
- /**
- * Checks a {@link IFile} to make sure it should be packaged as standard resources.
- * @param file the IFile representing the file.
- * @return true if the file should be packaged as standard java resources.
- */
- public static boolean checkFileForPackaging(IFile file) {
- String name = file.getName();
-
- String ext = file.getFileExtension();
- return ApkBuilder.checkFileForPackaging(name, ext);
- }
-
- /**
- * Checks whether an {@link IFolder} and its content is valid for packaging into the .apk as
- * standard Java resource.
- * @param folder the {@link IFolder} to check.
- */
- public static boolean checkFolderForPackaging(IFolder folder) {
- String name = folder.getName();
- return ApkBuilder.checkFolderForPackaging(name);
- }
-
- /**
- * Returns a list of {@link IJavaProject} matching the provided {@link IProject} objects.
- * @param projects the IProject objects.
- * @return a new list object containing the IJavaProject object for the given IProject objects.
- * @throws CoreException
- */
- public static List<IJavaProject> getJavaProjects(List<IProject> projects) throws CoreException {
- ArrayList<IJavaProject> list = new ArrayList<IJavaProject>();
-
- for (IProject p : projects) {
- if (p.isOpen() && p.hasNature(JavaCore.NATURE_ID)) {
-
- list.add(JavaCore.create(p));
- }
- }
-
- return list;
- }
-
- /**
- * Get the stderr output of a process and return when the process is done.
- * @param process The process to get the output from
- * @param stderr The array to store the stderr output
- * @return the process return code.
- * @throws InterruptedException
- */
- public final static int grabProcessOutput(
- final IProject project,
- final Process process,
- final ArrayList<String> stderr)
- throws InterruptedException {
-
- return GrabProcessOutput.grabProcessOutput(
- process,
- Wait.WAIT_FOR_READERS, // we really want to make sure we get all the output!
- new IProcessOutput() {
-
- @SuppressWarnings("unused")
- @Override
- public void out(@Nullable String line) {
- if (line != null) {
- // If benchmarking always print the lines that
- // correspond to benchmarking info returned by ADT
- if (BENCHMARK_FLAG && line.startsWith("BENCHMARK:")) { //$NON-NLS-1$
- AdtPlugin.printBuildToConsole(BuildVerbosity.ALWAYS,
- project, line);
- } else {
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE,
- project, line);
- }
- }
- }
-
- @Override
- public void err(@Nullable String line) {
- if (line != null) {
- stderr.add(line);
- if (BuildVerbosity.VERBOSE == AdtPrefs.getPrefs().getBuildVerbosity()) {
- AdtPlugin.printErrorToConsole(project, line);
- }
- }
- }
- });
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/ConvertSwitchDialog.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/ConvertSwitchDialog.java
deleted file mode 100644
index 20bee5dac..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/ConvertSwitchDialog.java
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.build;
-
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.dialogs.TitleAreaDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.browser.IWebBrowser;
-
-import java.net.URL;
-
-/**
- * Dialog shown by the {@link ConvertSwitchQuickFixProcessor}. This is a custom
- * dialog rather than a plain {@link MessageDialog} such that we can show a link
- * and point to a web page for more info.
- */
-class ConvertSwitchDialog extends TitleAreaDialog implements SelectionListener {
- /** URL containing more info */
- private static final String URL = "http://tools.android.com/tips/non-constant-fields"; //$NON-NLS-1$
-
- private final String mField;
-
- private Link mLink;
-
- /**
- * Create the dialog.
- * @param parentShell the parent shell
- * @param field the field name we're warning about
- */
- public ConvertSwitchDialog(Shell parentShell, String field) {
- super(parentShell);
- mField = field;
- Image image = IconFactory.getInstance().getIcon("android-64"); //$NON-NLS-1$
- setTitleImage(image);
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- String text = String.format(
- "As of ADT 14, the resource fields (such as %1$s) are no longer constants " +
- "when defined in library projects. This is necessary to make library " +
- "projects reusable without recompiling them.\n" +
- "\n" +
- "One consequence of this is that you can no longer use the fields directly " +
- "in switch statements. You must use an if-else chain instead.\n" +
- "\n" +
- "Eclipse can automatically convert from a switch statement to an if-else " +
- "statement. Just place the caret on the switch keyword and invoke " +
- "Quick Fix (Ctrl-1 on Windows and Linux, Cmd-1 on Mac), then select " +
- "\"Convert 'switch' to 'if-else'\".\n" +
- "\n" +
- "For more information, see <a href=\"" + URL + "\">" + URL + "</a>",
- mField);
-
- Composite area = (Composite) super.createDialogArea(parent);
- Composite container = new Composite(area, SWT.NONE);
- container.setLayout(new GridLayout(1, false));
- container.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- mLink = new Link(container, SWT.NONE);
- mLink.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1));
- mLink.setText(text);
- mLink.addSelectionListener(this);
-
- setMessage("Non-Constant Expressions: Migration Necessary", IMessageProvider.INFORMATION);
-
- return area;
- }
-
- @Override
- protected void createButtonsForButtonBar(Composite parent) {
- createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
- createButton(parent, IDialogConstants.HELP_ID, IDialogConstants.HELP_LABEL, false);
- }
-
- @Override
- protected Point getInitialSize() {
- return new Point(500, 400);
- }
-
- private void showWebPage() {
- try {
- IWorkbench workbench = PlatformUI.getWorkbench();
- IWebBrowser browser = workbench.getBrowserSupport().getExternalBrowser();
- browser.openURL(new URL(URL));
- } catch (Exception e) {
- String message = String.format("Could not open browser. Vist\n%1$s\ninstead.",
- URL);
- MessageDialog.openError(getShell(), "Browser Error", message);
- }
-
- }
-
- @Override
- protected void buttonPressed(int buttonId) {
- if (buttonId == IDialogConstants.HELP_ID) {
- showWebPage();
- } else {
- super.buttonPressed(buttonId);
- }
- }
-
- // ---- Implements SelectionListener ----
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (e.getSource() == mLink) {
- showWebPage();
- }
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/ConvertSwitchQuickFixProcessor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/ConvertSwitchQuickFixProcessor.java
deleted file mode 100644
index a99dc7601..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/ConvertSwitchQuickFixProcessor.java
+++ /dev/null
@@ -1,224 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jdt.core.IBuffer;
-import org.eclipse.jdt.core.ICompilationUnit;
-import org.eclipse.jdt.core.compiler.IProblem;
-import org.eclipse.jdt.core.dom.ASTNode;
-import org.eclipse.jdt.core.dom.QualifiedName;
-import org.eclipse.jdt.ui.text.java.IInvocationContext;
-import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.jdt.ui.text.java.IProblemLocation;
-import org.eclipse.jdt.ui.text.java.IQuickFixProcessor;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.editors.text.TextFileDocumentProvider;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-
-import java.util.List;
-
-/**
- * A quickfix processor which looks for "case expressions must be constant
- * expressions" errors, and if they apply to fields in a class named R, it
- * assumes this is code related to library projects that are no longer final and
- * will need to be rewritten to use if-else chains instead.
- */
-public class ConvertSwitchQuickFixProcessor implements IQuickFixProcessor {
- /** Constructs a new {@link ConvertSwitchQuickFixProcessor} */
- public ConvertSwitchQuickFixProcessor() {
- }
-
- @Override
- public boolean hasCorrections(ICompilationUnit cu, int problemId) {
- return problemId == IProblem.NonConstantExpression;
- }
-
- @Override
- public IJavaCompletionProposal[] getCorrections(IInvocationContext context,
- IProblemLocation[] location) throws CoreException {
- if (location == null || location.length == 0) {
- return null;
- }
- ASTNode coveringNode = context.getCoveringNode();
- if (coveringNode == null) {
- return null;
- }
-
- // Look up the fully qualified name of the non-constant expression, if any, and
- // make sure it's R-something.
- if (coveringNode.getNodeType() == ASTNode.SIMPLE_NAME) {
- coveringNode = coveringNode.getParent();
- if (coveringNode == null) {
- return null;
- }
- }
- if (coveringNode.getNodeType() != ASTNode.QUALIFIED_NAME) {
- return null;
- }
- QualifiedName name = (QualifiedName) coveringNode;
- if (!name.getFullyQualifiedName().startsWith("R.")) { //$NON-NLS-1$
- return null;
- }
-
- IProblemLocation error = location[0];
- int errorStart = error.getOffset();
- int errorLength = error.getLength();
- int caret = context.getSelectionOffset();
-
- // Even though the hasCorrections() method above will return false for everything
- // other than non-constant expression errors, it turns out this getCorrections()
- // method will ALSO be called on lines where there is no such error. In particular,
- // if you have an invalid cast expression like this:
- // Button button = findViewById(R.id.textView);
- // then this method will be called, and the expression will pass all of the above
- // checks. However, we -don't- want to show a migrate code suggestion in that case!
- // Therefore, we'll need to check if we're *actually* on a line with the given
- // problem.
- //
- // Unfortunately, we don't get passed the problemId again, and there's no access
- // to it. So instead we'll need to look up the markers on the line, and see
- // if we actually have a constant expression warning. This is not pretty!!
-
- boolean foundError = false;
- ICompilationUnit compilationUnit = context.getCompilationUnit();
- IResource file = compilationUnit.getResource();
- if (file != null) {
- IDocumentProvider provider = new TextFileDocumentProvider();
- try {
- provider.connect(file);
- IDocument document = provider.getDocument(file);
- if (document != null) {
- List<IMarker> markers = AdtUtils.findMarkersOnLine(IMarker.PROBLEM,
- file, document, errorStart);
- for (IMarker marker : markers) {
- String message = marker.getAttribute(IMarker.MESSAGE, "");
- // There are no other attributes in the marker we can use to identify
- // the exact error, so we'll need to resort to the actual message
- // text even though that would not work if the messages had been
- // localized... This can also break if the error messages change. Yuck.
- if (message.contains("constant expressions")) { //$NON-NLS-1$
- foundError = true;
- }
- }
- }
- } catch (Exception e) {
- AdtPlugin.log(e, "Can't validate error message in %1$s", file.getName());
- } finally {
- provider.disconnect(file);
- }
- }
- if (!foundError) {
- // Not a constant-expression warning, so do nothing
- return null;
- }
-
- IBuffer buffer = compilationUnit.getBuffer();
- boolean sameLine = false;
- // See if the caret is on the same line as the error
- if (caret <= errorStart) {
- // Search backwards to beginning of line
- for (int i = errorStart; i >= 0; i--) {
- if (i <= caret) {
- sameLine = true;
- break;
- }
- char c = buffer.getChar(i);
- if (c == '\n') {
- break;
- }
- }
- } else {
- // Search forwards to the end of the line
- for (int i = errorStart + errorLength, n = buffer.getLength(); i < n; i++) {
- if (i >= caret) {
- sameLine = true;
- break;
- }
- char c = buffer.getChar(i);
- if (c == '\n') {
- break;
- }
- }
- }
-
- if (sameLine) {
- String expression = buffer.getText(errorStart, errorLength);
- return new IJavaCompletionProposal[] {
- new MigrateProposal(expression)
- };
- }
-
- return null;
- }
-
- /** Proposal for the quick fix which displays an explanation message to the user */
- private class MigrateProposal implements IJavaCompletionProposal {
- private String mExpression;
-
- private MigrateProposal(String expression) {
- mExpression = expression;
- }
-
- @Override
- public void apply(IDocument document) {
- Shell shell = AdtPlugin.getShell();
- ConvertSwitchDialog dialog = new ConvertSwitchDialog(shell, mExpression);
- dialog.open();
- }
-
- @Override
- public Point getSelection(IDocument document) {
- return null;
- }
-
- @Override
- public String getAdditionalProposalInfo() {
- return "As of ADT 14, resource fields cannot be used as switch cases. Invoke this " +
- "fix to get more information.";
- }
-
- @Override
- public String getDisplayString() {
- return "Migrate Android Code";
- }
-
- @Override
- public Image getImage() {
- return AdtPlugin.getAndroidLogo();
- }
-
- @Override
- public IContextInformation getContextInformation() {
- return null;
- }
-
- @Override
- public int getRelevance() {
- return 50;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/DefaultSourceChangeHandler.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/DefaultSourceChangeHandler.java
deleted file mode 100644
index ea0d695d1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/DefaultSourceChangeHandler.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResourceDelta;
-
-import java.util.HashSet;
-import java.util.Set;
-
-/**
- * Base source change handler for the {@link SourceProcessor} classes.
- *
- * It can be used as is, as long as the matching {@link SourceProcessor} properly implements
- * its abstract methods, and the processor does not output resource files,
- * or can be extended to provide custom implementation for:
- * {@link #handleSourceFile(IFile, int)}
- * {@link #handleGeneratedFile(IFile, int)}
- * {@link #handleResourceFile(IFile, int)}
- * {@link #filterResourceFolder(IContainer)}
- *
- */
-public class DefaultSourceChangeHandler implements SourceChangeHandler {
-
- private SourceProcessor mProcessor;
-
- /** List of source files found that are modified or new. */
- private final Set<IFile> mToCompile = new HashSet<IFile>();
-
- /** List of source files that have been removed. */
- private final Set<IFile> mRemoved = new HashSet<IFile>();
-
- @Override
- public boolean handleGeneratedFile(IFile file, int kind) {
- if (kind == IResourceDelta.REMOVED || kind == IResourceDelta.CHANGED) {
- IFile sourceFile = mProcessor.isOutput(file);
- if (sourceFile != null) {
- mToCompile.add(sourceFile);
- return true;
- }
- }
-
- return false;
- }
-
- @Override
- public void handleSourceFile(IFile file, int kind) {
- // first the file itself if this is a match for the processor's extension
- if (mProcessor.getExtensions().contains(file.getFileExtension())) {
- if (kind == IResourceDelta.REMOVED) {
- mRemoved.add(file);
- } else {
- mToCompile.add(file);
- }
- }
-
- // now the dependencies. In all case we compile the files that depend on the
- // added/changed/removed file.
- mToCompile.addAll(mProcessor.isDependency(file));
- }
-
- protected void addFileToCompile(IFile file) {
- mToCompile.add(file);
- }
-
- Set<IFile> getFilesToCompile() {
- return mToCompile;
- }
-
- protected void addRemovedFile(IFile file) {
- mRemoved.add(file);
- }
-
- Set<IFile> getRemovedFiles() {
- return mRemoved;
- }
-
- public void reset() {
- mToCompile.clear();
- mRemoved.clear();
- }
-
- protected SourceProcessor getProcessor() {
- return mProcessor;
- }
-
- void init(SourceProcessor processor) {
- mProcessor = processor;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/DexException.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/DexException.java
deleted file mode 100644
index 032e5e646..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/DexException.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build;
-
-/**
- * Exception throw when dx fails.
- *
- */
-public final class DexException extends Exception {
- private static final long serialVersionUID = 1L;
-
- DexException(String message) {
- super(message);
- }
-
- DexException(String message, Throwable cause) {
- super(message, cause);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/DexWrapper.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/DexWrapper.java
deleted file mode 100644
index 3f882842b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/DexWrapper.java
+++ /dev/null
@@ -1,218 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-
-import java.io.File;
-import java.io.PrintStream;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.util.Collection;
-
-/**
- * Wrapper to access dx.jar through reflection.
- * <p/>Since there is no proper api to call the method in the dex library, this wrapper is going
- * to access it through reflection.
- */
-public final class DexWrapper {
-
- private final static String DEX_MAIN = "com.android.dx.command.dexer.Main"; //$NON-NLS-1$
- private final static String DEX_CONSOLE = "com.android.dx.command.DxConsole"; //$NON-NLS-1$
- private final static String DEX_ARGS = "com.android.dx.command.dexer.Main$Arguments"; //$NON-NLS-1$
-
- private final static String MAIN_RUN = "run"; //$NON-NLS-1$
-
- private Method mRunMethod;
-
- private Constructor<?> mArgConstructor;
- private Field mArgOutName;
- private Field mArgVerbose;
- private Field mArgJarOutput;
- private Field mArgFileNames;
- private Field mArgForceJumbo;
-
- private Field mConsoleOut;
- private Field mConsoleErr;
-
- /**
- * Loads the dex library from a file path.
- *
- * The loaded library can be used via
- * {@link DexWrapper#run(String, String[], boolean, PrintStream, PrintStream)}.
- *
- * @param osFilepath the location of the dx.jar file.
- * @return an IStatus indicating the result of the load.
- */
- public synchronized IStatus loadDex(String osFilepath) {
- try {
- File f = new File(osFilepath);
- if (f.isFile() == false) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, String.format(
- Messages.DexWrapper_s_does_not_exists, osFilepath));
- }
- URL url = f.toURI().toURL();
-
- @SuppressWarnings("resource")
- URLClassLoader loader = new URLClassLoader(new URL[] { url },
- DexWrapper.class.getClassLoader());
-
- // get the classes.
- Class<?> mainClass = loader.loadClass(DEX_MAIN);
- Class<?> consoleClass = loader.loadClass(DEX_CONSOLE);
- Class<?> argClass = loader.loadClass(DEX_ARGS);
-
- try {
- // now get the fields/methods we need
- mRunMethod = mainClass.getMethod(MAIN_RUN, argClass);
-
- mArgConstructor = argClass.getConstructor();
- mArgOutName = argClass.getField("outName"); //$NON-NLS-1$
- mArgJarOutput = argClass.getField("jarOutput"); //$NON-NLS-1$
- mArgFileNames = argClass.getField("fileNames"); //$NON-NLS-1$
- mArgVerbose = argClass.getField("verbose"); //$NON-NLS-1$
- mArgForceJumbo = argClass.getField("forceJumbo"); //$NON-NLS-1$
-
- mConsoleOut = consoleClass.getField("out"); //$NON-NLS-1$
- mConsoleErr = consoleClass.getField("err"); //$NON-NLS-1$
-
- } catch (SecurityException e) {
- return createErrorStatus(Messages.DexWrapper_SecuryEx_Unable_To_Find_API, e);
- } catch (NoSuchMethodException e) {
- return createErrorStatus(Messages.DexWrapper_SecuryEx_Unable_To_Find_Method, e);
- } catch (NoSuchFieldException e) {
- return createErrorStatus(Messages.DexWrapper_SecuryEx_Unable_To_Find_Field, e);
- }
-
- return Status.OK_STATUS;
- } catch (MalformedURLException e) {
- // really this should not happen.
- return createErrorStatus(
- String.format(Messages.DexWrapper_Failed_to_load_s, osFilepath), e);
- } catch (ClassNotFoundException e) {
- return createErrorStatus(
- String.format(Messages.DexWrapper_Failed_to_load_s, osFilepath), e);
- }
- }
-
- /**
- * Removes any reference to the dex library.
- * <p/>
- * {@link #loadDex(String)} must be called on the wrapper
- * before {@link #run(String, String[], boolean, PrintStream, PrintStream)} can
- * be used again.
- */
- public synchronized void unload() {
- mRunMethod = null;
- mArgConstructor = null;
- mArgOutName = null;
- mArgJarOutput = null;
- mArgFileNames = null;
- mArgVerbose = null;
- mConsoleOut = null;
- mConsoleErr = null;
- System.gc();
- }
-
- /**
- * Runs the dex command.
- * The wrapper must have been initialized via {@link #loadDex(String)} first.
- *
- * @param osOutFilePath the OS path to the outputfile (classes.dex
- * @param osFilenames list of input source files (.class and .jar files)
- * @param forceJumbo force jumbo mode.
- * @param verbose verbose mode.
- * @param outStream the stdout console
- * @param errStream the stderr console
- * @return the integer return code of com.android.dx.command.dexer.Main.run()
- * @throws CoreException
- */
- public synchronized int run(String osOutFilePath, Collection<String> osFilenames,
- boolean forceJumbo, boolean verbose,
- PrintStream outStream, PrintStream errStream) throws CoreException {
-
- assert mRunMethod != null;
- assert mArgConstructor != null;
- assert mArgOutName != null;
- assert mArgJarOutput != null;
- assert mArgFileNames != null;
- assert mArgForceJumbo != null;
- assert mArgVerbose != null;
- assert mConsoleOut != null;
- assert mConsoleErr != null;
-
- if (mRunMethod == null) {
- throw new CoreException(createErrorStatus(
- String.format(Messages.DexWrapper_Unable_To_Execute_Dex_s,
- "wrapper was not properly loaded first"),
- null /*exception*/));
- }
-
- try {
- // set the stream
- mConsoleErr.set(null /* obj: static field */, errStream);
- mConsoleOut.set(null /* obj: static field */, outStream);
-
- // create the Arguments object.
- Object args = mArgConstructor.newInstance();
- mArgOutName.set(args, osOutFilePath);
- mArgFileNames.set(args, osFilenames.toArray(new String[osFilenames.size()]));
- mArgJarOutput.set(args, osOutFilePath.endsWith(SdkConstants.DOT_JAR));
- mArgForceJumbo.set(args, forceJumbo);
- mArgVerbose.set(args, verbose);
-
- // call the run method
- Object res = mRunMethod.invoke(null /* obj: static method */, args);
-
- if (res instanceof Integer) {
- return ((Integer)res).intValue();
- }
-
- return -1;
- } catch (Exception e) {
- Throwable t = e;
- while (t.getCause() != null) {
- t = t.getCause();
- }
-
- String msg = t.getMessage();
- if (msg == null) {
- msg = String.format("%s. Check the Eclipse log for stack trace.",
- t.getClass().getName());
- }
-
- throw new CoreException(createErrorStatus(
- String.format(Messages.DexWrapper_Unable_To_Execute_Dex_s, msg), t));
- }
- }
-
- private static IStatus createErrorStatus(String message, Throwable e) {
- AdtPlugin.log(e, message);
- AdtPlugin.printErrorToConsole(Messages.DexWrapper_Dex_Loader, message);
-
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, message, e);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/ExecResultException.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/ExecResultException.java
deleted file mode 100644
index 63a7a6946..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/ExecResultException.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build;
-
-/**
- * Base exception class containing the error code and output of an external tool failed exec.
- *
- */
-class ExecResultException extends Exception {
- private static final long serialVersionUID = 1L;
-
- private final int mErrorCode;
- private final String[] mOutput;
-
- protected ExecResultException(int errorCode, String[] output) {
- mErrorCode = errorCode;
- mOutput = output;
- }
-
- /**
- * Returns the full output of aapt.
- */
- public String[] getOutput() {
- return mOutput;
- }
-
- /**
- * Returns the aapt return code.
- */
- public int getErrorCode() {
- return mErrorCode;
- }
-
- public String getLabel() {
- return "Command-line";
- }
-
- @Override
- public String toString() {
- String result = String.format("%1$s Error %2$d", getLabel(), mErrorCode);
- if (mOutput != null && mOutput.length > 0) {
- // Note : the "error detail" window in Eclipse seem to ignore the \n,
- // so we prefix them with a space. It's not optimal but it's slightly readable.
- result += " \nOutput:";
- for (String o : mOutput) {
- if (o != null) {
- result += " \n" + o;
- }
- }
- }
- return result;
- }
-
- @Override
- public String getMessage() {
- return toString();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/Messages.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/Messages.java
deleted file mode 100644
index 9ceba205d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/Messages.java
+++ /dev/null
@@ -1,150 +0,0 @@
-
-package com.android.ide.eclipse.adt.internal.build;
-
-import org.eclipse.osgi.util.NLS;
-
-public class Messages extends NLS {
- private static final String BUNDLE_NAME = "com.android.ide.eclipse.adt.internal.build.build_messages"; //$NON-NLS-1$
-
- public static String AAPT_Error;
-
- public static String AAPT_Exec_Error_s;
-
- public static String AAPT_Exec_Error_d;
-
- public static String AAPT_Exec_Error_Other_s;
-
- public static String Added_s_s_Needs_Updating;
-
- public static String AIDL_Exec_Error_s;
-
- public static String AIDL_Exec_Error_d;
-
- public static String AIDL_Java_Conflict;
-
- public static String ApkBuilder_Certificate_Expired_on_s;
-
- public static String ApkBuilder_JAVA_HOME_is_s;
-
- public static String ApkBuilder_Packaging_s;
-
- public static String ApkBuilder_Packaging_s_into_s;
-
- public static String ApkBuilder_s_Conflict_with_file_s;
-
- public static String ApkBuilder_Signing_Key_Creation_s;
-
- public static String ApkBuilder_Unable_To_Gey_Key;
-
- public static String ApkBuilder_UnableBuild_Dex_Not_loaded;
-
- public static String ApkBuilder_Update_or_Execute_manually_s;
-
- public static String ApkBuilder_Using_Default_Key;
-
- public static String ApkBuilder_Using_s_To_Sign;
-
- public static String Checking_Package_Change;
-
- public static String Compiler_Compliance_Error;
-
- public static String Couldnt_Locate_s_Error;
-
- public static String Dalvik_Error_d;
-
- public static String Dalvik_Error_s;
-
- public static String Delete_Obsolete_Error;
-
- public static String DexWrapper_Dex_Loader;
-
- public static String DexWrapper_Failed_to_load_s;
-
- public static String DexWrapper_s_does_not_exists;
-
- public static String DexWrapper_SecuryEx_Unable_To_Find_API;
-
- public static String DexWrapper_SecuryEx_Unable_To_Find_Field;
-
- public static String DexWrapper_SecuryEx_Unable_To_Find_Method;
-
- public static String DexWrapper_Unable_To_Execute_Dex_s;
-
- public static String DX_Jar_Error;
-
- public static String Failed_To_Get_Output;
-
- public static String Final_Archive_Error_s;
-
- public static String Incompatible_VM_Warning;
-
- public static String Marker_Delete_Error;
-
- public static String No_SDK_Setup_Error;
-
- public static String Nothing_To_Compile;
-
- public static String Output_Missing;
-
- public static String Package_s_Doesnt_Exist_Error;
-
- public static String Preparing_Generated_Files;
-
- public static String Project_Has_Errors;
-
- public static String Refreshing_Res;
-
- public static String Removing_Generated_Classes;
-
- public static String Requires_1_5_Error;
-
- public static String Requires_Class_Compatibility_s;
-
- public static String Requires_Compiler_Compliance_s;
-
- public static String Requires_Source_Compatibility_s;
-
- public static String s_Contains_Xml_Error;
-
- public static String s_Doesnt_Declare_Package_Error;
-
- public static String s_File_Missing;
-
- public static String s_Missing_Repackaging;
-
- public static String s_Modified_Manually_Recreating_s;
-
- public static String s_Modified_Recreating_s;
-
- public static String s_Removed_Recreating_s;
-
- public static String s_Removed_s_Needs_Updating;
-
- public static String Start_Full_Apk_Build;
-
- public static String Start_Full_Pre_Compiler;
-
- public static String Skip_Post_Compiler;
-
- public static String Start_Full_Post_Compiler;
-
- public static String Start_Inc_Apk_Build;
-
- public static String Start_Inc_Pre_Compiler;
-
- public static String Unparsed_AAPT_Errors;
-
- public static String Unparsed_AIDL_Errors;
-
- public static String Xml_Error;
-
- public static String Proguard_Exec_Error;
-
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
-
- private Messages() {
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/NativeLibInJarException.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/NativeLibInJarException.java
deleted file mode 100644
index 18f4ae7aa..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/NativeLibInJarException.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build;
-
-import com.android.sdklib.build.ApkBuilder.JarStatus;
-
-/**
- * Exception throw when native libraries are detected in jar file.
- *
- */
-public final class NativeLibInJarException extends Exception {
- private static final long serialVersionUID = 1L;
-
- private final JarStatus mStatus;
- private final String mLibName;
- private final String[] mConsoleMsgs;
-
- NativeLibInJarException(JarStatus status, String message, String libName,
- String[] consoleMsgs) {
- super(message);
- mStatus = status;
- mLibName = libName;
- mConsoleMsgs = consoleMsgs;
- }
-
- /**
- * Returns the {@link JarStatus} object containing the information about the libraries that
- * were found.
- */
- public JarStatus getStatus() {
- return mStatus;
- }
-
- /**
- * Returns the name of the jar file containing the native libraries.
- */
- public String getJarName() {
- return mLibName;
- }
-
- /**
- * Returns additional information that should be shown to the user.
- */
- public String[] getAdditionalInfo() {
- return mConsoleMsgs;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/ProguardExecException.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/ProguardExecException.java
deleted file mode 100644
index 3eb688b3e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/ProguardExecException.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build;
-
-/**
- * Exception thrown when the execution of proguard fails.
- *
- */
-public final class ProguardExecException extends Exception {
- private static final long serialVersionUID = 1L;
-
- ProguardExecException(String message, Throwable cause) {
- super(message, cause);
- }
-}
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/ProguardResultException.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/ProguardResultException.java
deleted file mode 100644
index 54246b337..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/ProguardResultException.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build;
-
-/**
- * Exception thrown when aapt reports an error in the resources.
- *
- */
-public final class ProguardResultException extends ExecResultException {
- private static final long serialVersionUID = 1L;
-
- ProguardResultException(int errorCode, String[] output) {
- super(errorCode, output);
- }
-
- @Override
- public String getLabel() {
- return "Proguard";
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/RenderScriptLauncher.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/RenderScriptLauncher.java
deleted file mode 100644
index 1d3c7bd3a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/RenderScriptLauncher.java
+++ /dev/null
@@ -1,244 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build;
-
-import com.android.annotations.NonNull;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.sdklib.build.RenderScriptProcessor.CommandLineLauncher;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * A {@link SourceProcessor} for RenderScript files.
- */
-public class RenderScriptLauncher implements CommandLineLauncher {
-
- /**
- * Single line llvm-rs-cc error: {@code <path>:<line>:<col>: <error>}
- */
- private static Pattern sLlvmPattern1 = Pattern.compile("^(.+?):(\\d+):(\\d+):\\s(.+)$"); //$NON-NLS-1$
-
- @NonNull
- private final IProject mProject;
- @NonNull
- private final IFolder mSourceOutFolder;
- @NonNull
- private final IFolder mResOutFolder;
- @NonNull
- private final IProgressMonitor mMonitor;
- private final boolean mVerbose;
-
- public RenderScriptLauncher(
- @NonNull IProject project,
- @NonNull IFolder sourceOutFolder,
- @NonNull IFolder resOutFolder,
- @NonNull IProgressMonitor monitor,
- boolean verbose) {
- mProject = project;
- mSourceOutFolder = sourceOutFolder;
- mResOutFolder = resOutFolder;
- mMonitor = monitor;
- mVerbose = verbose;
- }
-
- @Override
- public void launch(File executable, List<String> arguments, Map<String, String> envVariableMap)
- throws IOException, InterruptedException {
- // do the exec
- try {
- if (mVerbose) {
- StringBuilder sb = new StringBuilder(executable.getAbsolutePath());
- for (String c : arguments) {
- sb.append(' ').append(c);
- }
- String cmd_line = sb.toString();
- AdtPlugin.printToConsole(mProject, cmd_line);
- }
-
- String[] commandArray = new String[1 + arguments.size()];
- commandArray[0] = executable.getAbsolutePath();
- System.arraycopy(arguments.toArray(), 0, commandArray, 1, arguments.size());
-
- ProcessBuilder processBuilder = new ProcessBuilder(commandArray);
- Map<String, String> processEnvs = processBuilder.environment();
- for (Map.Entry<String, String> entry : envVariableMap.entrySet()) {
- processEnvs.put(entry.getKey(), entry.getValue());
- }
-
- Process p = processBuilder.start();
-
- // list to store each line of stderr
- ArrayList<String> stdErr = new ArrayList<String>();
-
- // get the output and return code from the process
- int returnCode = BuildHelper.grabProcessOutput(mProject, p, stdErr);
-
- if (stdErr.size() > 0) {
- // attempt to parse the error output
- boolean parsingError = parseLlvmOutput(stdErr);
-
- // If the process failed and we couldn't parse the output
- // we print a message, mark the project and exit
- if (returnCode != 0) {
-
- if (parsingError || mVerbose) {
- // display the message in the console.
- if (parsingError) {
- AdtPlugin.printErrorToConsole(mProject, stdErr.toArray());
-
- // mark the project
- BaseProjectHelper.markResource(mProject,
- AdtConstants.MARKER_RENDERSCRIPT,
- "Unparsed Renderscript error! Check the console for output.",
- IMarker.SEVERITY_ERROR);
- } else {
- AdtPlugin.printToConsole(mProject, stdErr.toArray());
- }
- }
- return;
- }
- } else if (returnCode != 0) {
- // no stderr output but exec failed.
- String msg = String.format("Error executing Renderscript: Return code %1$d",
- returnCode);
-
- BaseProjectHelper.markResource(mProject, AdtConstants.MARKER_AIDL,
- msg, IMarker.SEVERITY_ERROR);
-
- return;
- }
- } catch (IOException e) {
- // mark the project and exit
- String msg = String.format(
- "Error executing Renderscript. Please check %1$s is present at %2$s",
- executable.getName(), executable.getAbsolutePath());
- AdtPlugin.log(IStatus.ERROR, msg);
- BaseProjectHelper.markResource(mProject, AdtConstants.MARKER_RENDERSCRIPT, msg,
- IMarker.SEVERITY_ERROR);
- throw e;
- } catch (InterruptedException e) {
- // mark the project and exit
- String msg = String.format(
- "Error executing Renderscript. Please check %1$s is present at %2$s",
- executable.getName(), executable.getAbsolutePath());
- AdtPlugin.log(IStatus.ERROR, msg);
- BaseProjectHelper.markResource(mProject, AdtConstants.MARKER_RENDERSCRIPT, msg,
- IMarker.SEVERITY_ERROR);
- throw e;
- }
-
- try {
- mSourceOutFolder.refreshLocal(IResource.DEPTH_ONE, mMonitor);
- mResOutFolder.refreshLocal(IResource.DEPTH_ONE, mMonitor);
- } catch (CoreException e) {
- AdtPlugin.log(e, "failed to refresh folders");
- }
-
- return;
- }
-
- /**
- * Parse the output of llvm-rs-cc and mark the file with any errors.
- * @param lines The output to parse.
- * @return true if the parsing failed, false if success.
- */
- private boolean parseLlvmOutput(ArrayList<String> lines) {
- // nothing to parse? just return false;
- if (lines.size() == 0) {
- return false;
- }
-
- // get the root folder for the project as we're going to ignore everything that's
- // not in the project
- String rootPath = mProject.getLocation().toOSString();
- int rootPathLength = rootPath.length();
-
- Matcher m;
-
- boolean parsing = false;
-
- for (int i = 0; i < lines.size(); i++) {
- String p = lines.get(i);
-
- m = sLlvmPattern1.matcher(p);
- if (m.matches()) {
- // get the file path. This may, or may not be the main file being compiled.
- String filePath = m.group(1);
- if (filePath.startsWith(rootPath) == false) {
- // looks like the error in a non-project file. Keep parsing, but
- // we'll return true
- parsing = true;
- continue;
- }
-
- // get the actual file.
- filePath = filePath.substring(rootPathLength);
- // remove starting separator since we want the path to be relative
- if (filePath.startsWith(File.separator)) {
- filePath = filePath.substring(1);
- }
-
- // get the file
- IFile f = mProject.getFile(new Path(filePath));
-
- String lineStr = m.group(2);
- // ignore group 3 for now, this is the col number
- String msg = m.group(4);
-
- // get the line number
- int line = 0;
- try {
- line = Integer.parseInt(lineStr);
- } catch (NumberFormatException e) {
- // looks like the string we extracted wasn't a valid
- // file number. Parsing failed and we return true
- return true;
- }
-
- // mark the file
- BaseProjectHelper.markResource(f, AdtConstants.MARKER_RENDERSCRIPT, msg, line,
- IMarker.SEVERITY_ERROR);
-
- // success, go to the next line
- continue;
- }
-
- // invalid line format, flag as error, and keep going
- parsing = true;
- }
-
- return parsing;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/RsSourceChangeHandler.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/RsSourceChangeHandler.java
deleted file mode 100644
index 715895a0c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/RsSourceChangeHandler.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.sdklib.build.RenderScriptChecker;
-
-import org.eclipse.core.resources.IFile;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Set;
-
-public class RsSourceChangeHandler implements SourceChangeHandler {
-
- private final RenderScriptChecker mChecker;
- private boolean mIsCheckerLoaded = false;
-
- private boolean mMustCompile = false;
-
- public RsSourceChangeHandler(@NonNull RenderScriptChecker checker) {
- mChecker = checker;
- }
-
- @Override
- public boolean handleGeneratedFile(IFile file, int kind) {
- if (mMustCompile) {
- return false;
- }
-
- if (!mIsCheckerLoaded) {
- try {
- mChecker.loadDependencies();
- } catch (IOException e) {
- // failed to load the dependency files, force a compilation, log the error.
- AdtPlugin.log(e, "Failed to read dependency files");
- mMustCompile = true;
- return false;
- }
- }
-
- Set<File> oldOutputs = mChecker.getOldOutputs();
- // mustCompile is always false here.
- mMustCompile = oldOutputs.contains(file.getLocation().toFile());
- return mMustCompile;
- }
-
- @Override
- public void handleSourceFile(IFile file, int kind) {
- if (mMustCompile) {
- return;
- }
-
- String ext = file.getFileExtension();
- if (SdkConstants.EXT_RS.equals(ext) ||
- SdkConstants.EXT_FS.equals(ext) ||
- SdkConstants.EXT_RSH.equals(ext)) {
- mMustCompile = true;
- }
- }
-
- public boolean mustCompile() {
- return mMustCompile;
- }
-
- @NonNull
- public RenderScriptChecker getChecker() {
- return mChecker;
- }
-
- public void prepareFullBuild() {
- mMustCompile = true;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/SourceChangeHandler.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/SourceChangeHandler.java
deleted file mode 100644
index 12a055106..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/SourceChangeHandler.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build;
-
-import org.eclipse.core.resources.IFile;
-
-public interface SourceChangeHandler {
-
- boolean handleGeneratedFile(IFile file, int kind);
- void handleSourceFile(IFile file, int kind);
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/SourceFileData.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/SourceFileData.java
deleted file mode 100644
index d06bf1613..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/SourceFileData.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build;
-
-import org.eclipse.core.resources.IFile;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * Data for Android-specific source files. It contains a list of output files and a list
- * of dependencies.
- * The source file itself is a implied dependency and is not meant to be in the dependency list.
- */
-public class SourceFileData {
-
- private final IFile mSourceFile;
- private final List<IFile> mOutputFiles = new ArrayList<IFile>();
- private final List<IFile> mDependencyFiles = new ArrayList<IFile>();
-
- public SourceFileData(IFile sourceFile) {
- this(sourceFile, null, null);
- }
-
- SourceFileData(IFile sourceFile,
- List<IFile> outputFiles, List<IFile> dependencyFiles) {
- mSourceFile = sourceFile;
- if (outputFiles != null) {
- mOutputFiles.addAll(outputFiles);
- }
- if (dependencyFiles != null) {
- mDependencyFiles.addAll(dependencyFiles);
- }
- }
-
- SourceFileData(IFile sourceFile, IFile outputFile) {
- mSourceFile = sourceFile;
- if (outputFile != null) {
- mOutputFiles.add(outputFile);
- }
- }
-
- /**
- * Returns the source file as an {@link IFile}
- */
- public IFile getSourceFile() {
- return mSourceFile;
- }
-
- /**
- * Returns whether the given file is a dependency for this source file.
- * <p/>Note that the source file itself is not tested against. Therefore if
- * {@code file.equals(getSourceFile()} returns {@code true}, this method will return
- * {@code false}.
- * @param file the file to check against
- * @return true if the given file is a dependency for this source file.
- */
- public boolean dependsOn(IFile file) {
- return mDependencyFiles.contains(file);
- }
-
- /**
- * Returns whether the given file is an ouput of this source file.
- * @param file the file to test.
- * @return true if the file is an output file.
- */
- public boolean generated(IFile file) {
- return mOutputFiles.contains(file);
- }
-
- void setOutputFiles(List<IFile> outputFiles) {
- mOutputFiles.clear();
- if (outputFiles != null) {
- mOutputFiles.addAll(outputFiles);
- }
- }
-
- void setOutputFile(IFile outputFile) {
- mOutputFiles.clear();
- if (outputFile != null) {
- mOutputFiles.add(outputFile);
- }
- }
-
- void setDependencyFiles(List<IFile> depFiles) {
- mDependencyFiles.clear();
- if (depFiles != null) {
- mDependencyFiles.addAll(depFiles);
- }
- }
-
- public List<IFile> getDependencyFiles() {
- return mDependencyFiles;
- }
-
- /**
- * Shortcut access to the first output file. This is useful for generator that only output
- * one file.
- */
- public IFile getOutput() {
- if (mOutputFiles.size() > 0) {
- return mOutputFiles.get(0);
- }
-
- return null;
- }
-
- public List<IFile> getOutputFiles() {
- return Collections.unmodifiableList(mOutputFiles);
- }
-
- @Override
- public String toString() {
- return "NonJavaFileBundle [mSourceFile=" + mSourceFile + ", mGeneratedFiles="
- + mOutputFiles + ", mDependencies=" + mDependencyFiles + "]";
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/SourceProcessor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/SourceProcessor.java
deleted file mode 100644
index 1fc3e4e53..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/SourceProcessor.java
+++ /dev/null
@@ -1,454 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.ide.eclipse.adt.internal.build.builders.BaseBuilder;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.project.ProjectHelper;
-import com.android.sdklib.BuildToolInfo;
-import com.android.sdklib.IAndroidTarget;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jdt.core.IJavaProject;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Base class to handle generated java code.
- *
- * It provides management for modified source file list, deleted source file list, reconciliation
- * of previous lists, storing the current state of the build.
- *
- */
-public abstract class SourceProcessor {
-
- public final static int COMPILE_STATUS_NONE = 0;
- public final static int COMPILE_STATUS_CODE = 0x1;
- public final static int COMPILE_STATUS_RES = 0x2;
-
- /** List of all source files, their dependencies, and their output. */
- private final Map<IFile, SourceFileData> mFiles = new HashMap<IFile, SourceFileData>();
-
- private final IJavaProject mJavaProject;
- private BuildToolInfo mBuildToolInfo;
- private final IFolder mGenFolder;
- private final DefaultSourceChangeHandler mDeltaVisitor;
-
- /** List of source files pending compilation at the next build */
- private final List<IFile> mToCompile = new ArrayList<IFile>();
-
- /** List of removed source files pending cleaning at the next build. */
- private final List<IFile> mRemoved = new ArrayList<IFile>();
-
- private int mLastCompilationStatus = COMPILE_STATUS_NONE;
-
- /**
- * Quotes a path inside "". If the platform is not windows, the path is returned as is.
- * @param path the path to quote
- * @return the quoted path.
- */
- public static String quote(String path) {
- if (SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_WINDOWS) {
- if (path.endsWith(File.separator)) {
- path = path.substring(0, path.length() -1);
- }
- return "\"" + path + "\"";
- }
-
- return path;
- }
-
- protected SourceProcessor(
- @NonNull IJavaProject javaProject,
- @NonNull BuildToolInfo buildToolInfo,
- @NonNull IFolder genFolder,
- @NonNull DefaultSourceChangeHandler deltaVisitor) {
- mJavaProject = javaProject;
- mBuildToolInfo = buildToolInfo;
- mGenFolder = genFolder;
- mDeltaVisitor = deltaVisitor;
-
- mDeltaVisitor.init(this);
-
- IProject project = javaProject.getProject();
-
- // get all the source files
- buildSourceFileList();
-
- // load the known dependencies
- loadOutputAndDependencies();
-
- boolean mustCompile = loadState(project);
-
- // if we stored that we have to compile some files, we build the list that will compile them
- // all. For now we have to reuse the full list since we don't know which files needed
- // compilation.
- if (mustCompile) {
- mToCompile.addAll(mFiles.keySet());
- }
- }
-
- protected SourceProcessor(
- @NonNull IJavaProject javaProject,
- @NonNull BuildToolInfo buildToolInfo,
- @NonNull IFolder genFolder) {
- this(javaProject, buildToolInfo, genFolder, new DefaultSourceChangeHandler());
- }
-
- public void setBuildToolInfo(BuildToolInfo buildToolInfo) {
- mBuildToolInfo = buildToolInfo;
- }
-
-
- /**
- * Returns whether the given file is an output of this processor by return the source
- * file that generated it.
- * @param file the file to test.
- * @return the source file that generated the given file or null.
- */
- IFile isOutput(IFile file) {
- for (SourceFileData data : mFiles.values()) {
- if (data.generated(file)) {
- return data.getSourceFile();
- }
- }
-
- return null;
- }
-
- /**
- * Returns whether the given file is a dependency for other files by returning a list
- * of file depending on the given file.
- * @param file the file to test.
- * @return a list of files that depend on the given file or an empty list if there
- * are no matches.
- */
- List<IFile> isDependency(IFile file) {
- ArrayList<IFile> files = new ArrayList<IFile>();
- for (SourceFileData data : mFiles.values()) {
- if (data.dependsOn(file)) {
- files.add(data.getSourceFile());
- }
- }
-
- return files;
- }
-
- void addData(SourceFileData data) {
- mFiles.put(data.getSourceFile(), data);
- }
-
- SourceFileData getFileData(IFile file) {
- return mFiles.get(file);
- }
-
- Collection<SourceFileData> getAllFileData() {
- return mFiles.values();
- }
-
- public final DefaultSourceChangeHandler getChangeHandler() {
- return mDeltaVisitor;
- }
-
- final IJavaProject getJavaProject() {
- return mJavaProject;
- }
-
- final BuildToolInfo getBuildToolInfo() {
- return mBuildToolInfo;
- }
-
- final IFolder getGenFolder() {
- return mGenFolder;
- }
-
- final List<IFile> getToCompile() {
- return mToCompile;
- }
-
- final List<IFile> getRemovedFile() {
- return mRemoved;
- }
-
- final void addFileToCompile(IFile file) {
- mToCompile.add(file);
- }
-
- public final void prepareFullBuild(IProject project) {
- mDeltaVisitor.reset();
-
- mToCompile.clear();
- mRemoved.clear();
-
- // get all the source files
- buildSourceFileList();
-
- mToCompile.addAll(mFiles.keySet());
-
- saveState(project);
- }
-
- public final void doneVisiting(IProject project) {
- // merge the previous file modification lists and the new one.
- mergeFileModifications(mDeltaVisitor);
-
- mDeltaVisitor.reset();
-
- saveState(project);
- }
-
- /**
- * Returns the extension of the source files handled by this processor.
- * @return
- */
- protected abstract Set<String> getExtensions();
-
- protected abstract String getSavePropertyName();
-
- /**
- * Compiles the source files and return a status bitmask of the type of file that was generated.
- *
- */
- public final int compileFiles(BaseBuilder builder,
- IProject project, IAndroidTarget projectTarget,
- List<IPath> sourceFolders, List<File> libraryProjectsOut, IProgressMonitor monitor)
- throws CoreException {
-
- mLastCompilationStatus = COMPILE_STATUS_NONE;
-
- if (mToCompile.size() == 0 && mRemoved.size() == 0) {
- return mLastCompilationStatus;
- }
-
- // if a source file is being removed before we managed to compile it, it'll be in
- // both list. We *need* to remove it from the compile list or it'll never go away.
- for (IFile sourceFile : mRemoved) {
- int pos = mToCompile.indexOf(sourceFile);
- if (pos != -1) {
- mToCompile.remove(pos);
- }
- }
-
- // list of files that have failed compilation.
- List<IFile> stillNeedCompilation = new ArrayList<IFile>();
-
- doCompileFiles(mToCompile, builder, project, projectTarget, sourceFolders,
- stillNeedCompilation, libraryProjectsOut, monitor);
-
- mToCompile.clear();
- mToCompile.addAll(stillNeedCompilation);
-
- // Remove the files created from source files that have been removed.
- for (IFile sourceFile : mRemoved) {
- // look if we already know the output
- SourceFileData data = getFileData(sourceFile);
- if (data != null) {
- doRemoveFiles(data);
- }
- }
-
- // remove the associated file data.
- for (IFile removedFile : mRemoved) {
- mFiles.remove(removedFile);
- }
-
- mRemoved.clear();
-
- // store the build state. If there are any files that failed to compile, we will
- // force a full aidl compile on the next project open. (unless a full compilation succeed
- // before the project is closed/re-opened.)
- saveState(project);
-
- return mLastCompilationStatus;
- }
-
- protected abstract void doCompileFiles(
- List<IFile> filesToCompile, BaseBuilder builder,
- IProject project, IAndroidTarget projectTarget,
- List<IPath> sourceFolders, List<IFile> notCompiledOut,
- List<File> libraryProjectsOut, IProgressMonitor monitor) throws CoreException;
-
- /**
- * Adds a compilation status. It can be any of (in combination too):
- * <p/>
- * {@link #COMPILE_STATUS_CODE} means this processor created source code files.
- * {@link #COMPILE_STATUS_RES} means this process created resources.
- */
- protected void setCompilationStatus(int status) {
- mLastCompilationStatus |= status;
- }
-
- protected void doRemoveFiles(SourceFileData data) throws CoreException {
- List<IFile> outputFiles = data.getOutputFiles();
- for (IFile outputFile : outputFiles) {
- if (outputFile.exists()) {
- outputFile.getLocation().toFile().delete();
- }
- }
- }
-
- public final boolean loadState(IProject project) {
- return ProjectHelper.loadBooleanProperty(project, getSavePropertyName(),
- true /*defaultValue*/);
- }
-
- public final void saveState(IProject project) {
- // TODO: Optimize by saving only the files that need compilation
- ProjectHelper.saveStringProperty(project, getSavePropertyName(),
- Boolean.toString(mToCompile.size() > 0));
- }
-
- protected abstract void loadOutputAndDependencies();
-
-
- protected IPath getSourceFolderFor(IFile file) {
- // find the source folder for the class so that we can infer the package from the
- // difference between the file and its source folder.
- List<IPath> sourceFolders = BaseProjectHelper.getSourceClasspaths(getJavaProject());
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
-
- for (IPath sourceFolderPath : sourceFolders) {
- IFolder sourceFolder = root.getFolder(sourceFolderPath);
- // we don't look in the 'gen' source folder as there will be no source in there.
- if (sourceFolder.exists() && sourceFolder.equals(getGenFolder()) == false) {
- // look for the source file parent, until we find this source folder.
- IResource parent = file;
- while ((parent = parent.getParent()) != null) {
- if (parent.equals(sourceFolder)) {
- return sourceFolderPath;
- }
- }
- }
- }
-
- return null;
- }
-
- /**
- * Goes through the build paths and fills the list of files to compile.
- *
- * @param project The project.
- * @param sourceFolderPathList The list of source folder paths.
- */
- private final void buildSourceFileList() {
- mFiles.clear();
-
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- List<IPath> sourceFolderPathList = BaseProjectHelper.getSourceClasspaths(mJavaProject);
-
- for (IPath sourceFolderPath : sourceFolderPathList) {
- IFolder sourceFolder = root.getFolder(sourceFolderPath);
- // we don't look in the 'gen' source folder as there will be no source in there.
- if (sourceFolder.exists() && sourceFolder.equals(getGenFolder()) == false) {
- scanFolderForSourceFiles(sourceFolder, sourceFolder);
- }
- }
- }
-
- /**
- * Scans a folder and fills the list of files to compile.
- * @param sourceFolder the root source folder.
- * @param folder The folder to scan.
- */
- private void scanFolderForSourceFiles(IFolder sourceFolder, IFolder folder) {
- try {
- IResource[] members = folder.members();
- for (IResource r : members) {
- // get the type of the resource
- switch (r.getType()) {
- case IResource.FILE: {
- // if this a file, check that the file actually exist
- // and that it's the type of of file that's used in this processor
- String extension = r.exists() ? r.getFileExtension() : null;
- if (extension != null &&
- getExtensions().contains(extension.toLowerCase(Locale.US))) {
- mFiles.put((IFile) r, new SourceFileData((IFile) r));
- }
- break;
- }
- case IResource.FOLDER:
- // recursively go through children
- scanFolderForSourceFiles(sourceFolder, (IFolder)r);
- break;
- default:
- // this would mean it's a project or the workspace root
- // which is unlikely to happen. we do nothing
- break;
- }
- }
- } catch (CoreException e) {
- // Couldn't get the members list for some reason. Just return.
- }
- }
-
-
- /**
- * Merge the current list of source file to compile/remove with the one coming from the
- * delta visitor
- * @param visitor the delta visitor.
- */
- private void mergeFileModifications(DefaultSourceChangeHandler visitor) {
- Set<IFile> toRemove = visitor.getRemovedFiles();
- Set<IFile> toCompile = visitor.getFilesToCompile();
-
- // loop through the new toRemove list, and add it to the old one,
- // plus remove any file that was still to compile and that are now
- // removed
- for (IFile r : toRemove) {
- if (mRemoved.indexOf(r) == -1) {
- mRemoved.add(r);
- }
-
- int index = mToCompile.indexOf(r);
- if (index != -1) {
- mToCompile.remove(index);
- }
- }
-
- // now loop through the new files to compile and add it to the list.
- // Also look for them in the remove list, this would mean that they
- // were removed, then added back, and we shouldn't remove them, just
- // recompile them.
- for (IFile r : toCompile) {
- if (mToCompile.indexOf(r) == -1) {
- mToCompile.add(r);
- }
-
- int index = mRemoved.indexOf(r);
- if (index != -1) {
- mRemoved.remove(index);
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/build_messages.properties b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/build_messages.properties
deleted file mode 100644
index f387ab5a9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/build_messages.properties
+++ /dev/null
@@ -1,67 +0,0 @@
-Start_Full_Apk_Build=Starting full Package build.
-Start_Full_Pre_Compiler=Starting full Pre Compiler.
-Skip_Post_Compiler=Skipping over Post Compiler.
-Start_Full_Post_Compiler=Starting full Post Compiler.
-Start_Inc_Apk_Build=Starting incremental Package build: Checking resource changes.
-Start_Inc_Pre_Compiler=Starting incremental Pre Compiler: Checking resource changes.
-Xml_Error=Error in an XML file: aborting build.
-s_Missing_Repackaging=%1$s missing. Repackaging.
-Project_Has_Errors=Project contains error(s). Package Builder aborted.
-Failed_To_Get_Output=Failed to get project output folder\!
-Output_Missing=Output folder missing\! Make sure your project is configured properly.
-s_File_Missing=%1$s file missing\!
-Unparsed_AAPT_Errors=Unparsed aapt error(s)\! Check the console for output.
-Unparsed_AIDL_Errors=Unparsed aidl error\! Check the console for output.
-AAPT_Exec_Error_s=Error executing aapt. Please check aapt is present at %1$s
-AAPT_Exec_Error_d=Error executing aapt: Return code %1$d
-AAPT_Exec_Error_Other_s=Error executing aapt: %1$s
-Dalvik_Error_d=Conversion to Dalvik format failed with error %1$d
-DX_Jar_Error=Dx.jar is not found inside the plugin. Reinstall ADT\!
-Dalvik_Error_s=Conversion to Dalvik format failed: %1$s
-Incompatible_VM_Warning=Note: You may be using an incompatible virtual machine or class library.
-Requires_1_5_Error=This program requires JDK 1.5 compatibility.
-Final_Archive_Error_s=Error generating final archive: %1$s
-Marker_Delete_Error=Failed to delete marker '%1$s' for %2$s
-Couldnt_Locate_s_Error=Could not locate '%1$s'. This will not be added to the package.
-Compiler_Compliance_Error=Compiler compliance level not compatible: Build aborted.
-No_SDK_Setup_Error=SDK directory has not been setup. Please go to the Android preferences and enter the location of the SDK.
-s_Contains_Xml_Error=%1$s contains XML error: Build aborted.
-s_Doesnt_Declare_Package_Error=%1$s does not declare a Java package: Build aborted.
-Checking_Package_Change=Checking Java package value did not change...
-Package_s_Doesnt_Exist_Error=Package '%1$s' does not exist\!
-Preparing_Generated_Files=Preparing generated java files for update/creation.
-AAPT_Error='aapt' error. Pre Compiler Build aborted.
-Nothing_To_Compile=Nothing to pre compile\!
-Removing_Generated_Classes=Removing generated java classes.
-Delete_Obsolete_Error=Failed to delete obsolete %1$s, please delete it manually
-DexWrapper_Dex_Loader=Dex Loader
-AIDL_Java_Conflict=%1$s is in the way of %2$s, remove it or rename of one the files.
-AIDL_Exec_Error_d=Error executing aidl: Return code %1$d
-AIDL_Exec_Error_s=Error executing aidl. Please check aidl is present at %1$s
-s_Removed_Recreating_s=%1$s was removed\! Recreating %1$s\!
-s_Modified_Manually_Recreating_s=%1$s was modified manually\! Reverting to generated version\!
-s_Modified_Recreating_s='%1$s' was modified.
-Added_s_s_Needs_Updating=New resource file: '%1$s', %2$s needs to be updated.
-s_Removed_s_Needs_Updating='%1$s' was removed, %2$s needs to be updated.
-Requires_Compiler_Compliance_s=Android requires compiler compliance level 5.0 or 6.0. Found '%1$s' instead. Please use Android Tools > Fix Project Properties.
-Requires_Source_Compatibility_s=Android requires source compatibility set to 5.0 or 6.0. Found '%1$s' instead. Please use Android Tools > Fix Project Properties.
-Requires_Class_Compatibility_s=Android requires .class compatibility set to 5.0 or 6.0. Found '%1$s' instead. Please use Android Tools > Fix Project Properties.
-Refreshing_Res=Refreshing resource folders.
-DexWrapper_s_does_not_exists=%1$s does not exist or is not a file
-DexWrapper_Failed_to_load_s=Failed to load %1$s
-DexWrapper_Unable_To_Execute_Dex_s=Unable to execute dex: %1$s
-DexWrapper_SecuryEx_Unable_To_Find_API=SecurityException: Unable to find API for dex.jar
-DexWrapper_SecuryEx_Unable_To_Find_Method=SecurityException: Unable to find method for dex.jar
-DexWrapper_SecuryEx_Unable_To_Find_Field=SecurityException: Unable to find field for dex.jar
-ApkBuilder_UnableBuild_Dex_Not_loaded=Unable to build: the file dx.jar was not loaded from the SDK folder\!
-ApkBuilder_Using_Default_Key=Using default debug key to sign package
-ApkBuilder_Using_s_To_Sign=Using '%1$s' to sign package
-ApkBuilder_Signing_Key_Creation_s=Signing Key Creation:
-ApkBuilder_Unable_To_Gey_Key=Unable to get debug signature key
-ApkBuilder_Certificate_Expired_on_s=Debug certificate expired on %1$s\!
-ApkBuilder_Packaging_s=Packaging %1$s
-ApkBuilder_JAVA_HOME_is_s=The Java VM Home used is: %1$s
-ApkBuilder_Update_or_Execute_manually_s=Update it if necessary, or manually execute the following command:
-ApkBuilder_s_Conflict_with_file_s=%1$s conflicts with another file already put at %2$s
-ApkBuilder_Packaging_s_into_s=Packaging %1$s into %2$s
-Proguard_Exec_Error=Error executing Proguard. Please check Proguard is present at %1$s
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/BaseBuilder.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/BaseBuilder.java
deleted file mode 100644
index 162591406..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/BaseBuilder.java
+++ /dev/null
@@ -1,483 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build.builders;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.sdk.LoadStatus;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.build.BuildHelper;
-import com.android.ide.eclipse.adt.internal.build.Messages;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs.BuildVerbosity;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.project.ProjectHelper;
-import com.android.ide.eclipse.adt.internal.project.XmlErrorHandler;
-import com.android.ide.eclipse.adt.internal.project.XmlErrorHandler.XmlErrorListener;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.io.IFileWrapper;
-import com.android.io.IAbstractFile;
-import com.android.io.StreamException;
-import com.android.sdklib.BuildToolInfo;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.repository.FullRevision;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IncrementalProjectBuilder;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jdt.core.IJavaProject;
-import org.xml.sax.SAXException;
-
-import java.util.ArrayList;
-
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
-
-/**
- * Base builder for XML files. This class allows for basic XML parsing with
- * error checking and marking the files for errors/warnings.
- */
-public abstract class BaseBuilder extends IncrementalProjectBuilder {
-
- protected static final boolean DEBUG_LOG = "1".equals( //$NON-NLS-1$
- System.getenv("ANDROID_BUILD_DEBUG")); //$NON-NLS-1$
-
- /** SAX Parser factory. */
- private SAXParserFactory mParserFactory;
-
- /**
- * The build tool to use to build. This is guaranteed to be non null after a call to
- * {@link #abortOnBadSetup(IJavaProject, ProjectState)} since this will throw if it can't be
- * queried.
- */
- protected BuildToolInfo mBuildToolInfo;
-
- /**
- * Base Resource Delta Visitor to handle XML error
- */
- protected static class BaseDeltaVisitor implements XmlErrorListener {
-
- /** The Xml builder used to validate XML correctness. */
- protected BaseBuilder mBuilder;
-
- /**
- * XML error flag. if true, we keep parsing the ResourceDelta but the
- * compilation will not happen (we're putting markers)
- */
- public boolean mXmlError = false;
-
- public BaseDeltaVisitor(BaseBuilder builder) {
- mBuilder = builder;
- }
-
- /**
- * Finds a matching Source folder for the current path. This checks if the current path
- * leads to, or is a source folder.
- * @param sourceFolders The list of source folders
- * @param pathSegments The segments of the current path
- * @return The segments of the source folder, or null if no match was found
- */
- protected static String[] findMatchingSourceFolder(ArrayList<IPath> sourceFolders,
- String[] pathSegments) {
-
- for (IPath p : sourceFolders) {
- // check if we are inside one of those source class path
-
- // get the segments
- String[] srcSegments = p.segments();
-
- // compare segments. We want the path of the resource
- // we're visiting to be
- boolean valid = true;
- int segmentCount = pathSegments.length;
-
- for (int i = 0 ; i < segmentCount; i++) {
- String s1 = pathSegments[i];
- String s2 = srcSegments[i];
-
- if (s1.equalsIgnoreCase(s2) == false) {
- valid = false;
- break;
- }
- }
-
- if (valid) {
- // this folder, or one of this children is a source
- // folder!
- // we return its segments
- return srcSegments;
- }
- }
-
- return null;
- }
-
- /**
- * Sent when an XML error is detected.
- * @see XmlErrorListener
- */
- @Override
- public void errorFound() {
- mXmlError = true;
- }
- }
-
- protected static class AbortBuildException extends Exception {
- private static final long serialVersionUID = 1L;
- }
-
- public BaseBuilder() {
- super();
- mParserFactory = SAXParserFactory.newInstance();
-
- // FIXME when the compiled XML support for namespace is in, set this to true.
- mParserFactory.setNamespaceAware(false);
- }
-
- /**
- * Checks an Xml file for validity. Errors/warnings will be marked on the
- * file
- * @param resource the resource to check
- * @param visitor a valid resource delta visitor
- */
- protected final void checkXML(IResource resource, BaseDeltaVisitor visitor) {
-
- // first make sure this is an xml file
- if (resource instanceof IFile) {
- IFile file = (IFile)resource;
-
- // remove previous markers
- removeMarkersFromResource(file, AdtConstants.MARKER_XML);
-
- // create the error handler
- XmlErrorHandler reporter = new XmlErrorHandler(file, visitor);
- try {
- // parse
- getParser().parse(file.getContents(), reporter);
- } catch (Exception e1) {
- }
- }
- }
-
- /**
- * Returns the SAXParserFactory, instantiating it first if it's not already
- * created.
- * @return the SAXParserFactory object
- * @throws ParserConfigurationException
- * @throws SAXException
- */
- protected final SAXParser getParser() throws ParserConfigurationException,
- SAXException {
- return mParserFactory.newSAXParser();
- }
-
- /**
- * Adds a marker to the current project. This methods catches thrown {@link CoreException},
- * and returns null instead.
- *
- * @param markerId The id of the marker to add.
- * @param message the message associated with the mark
- * @param severity the severity of the marker.
- * @return the marker that was created (or null if failure)
- * @see IMarker
- */
- protected final IMarker markProject(String markerId, String message, int severity) {
- return BaseProjectHelper.markResource(getProject(), markerId, message, severity);
- }
-
- /**
- * Removes markers from a resource and only the resource (not its children).
- * @param file The file from which to delete the markers.
- * @param markerId The id of the markers to remove. If null, all marker of
- * type <code>IMarker.PROBLEM</code> will be removed.
- */
- public final void removeMarkersFromResource(IResource resource, String markerId) {
- try {
- if (resource.exists()) {
- resource.deleteMarkers(markerId, true, IResource.DEPTH_ZERO);
- }
- } catch (CoreException ce) {
- String msg = String.format(Messages.Marker_Delete_Error, markerId, resource.toString());
- AdtPlugin.printErrorToConsole(getProject(), msg);
- }
- }
-
- /**
- * Removes markers from a container and its children.
- * @param folder The container from which to delete the markers.
- * @param markerId The id of the markers to remove. If null, all marker of
- * type <code>IMarker.PROBLEM</code> will be removed.
- */
- protected final void removeMarkersFromContainer(IContainer folder, String markerId) {
- try {
- if (folder.exists()) {
- folder.deleteMarkers(markerId, true, IResource.DEPTH_INFINITE);
- }
- } catch (CoreException ce) {
- String msg = String.format(Messages.Marker_Delete_Error, markerId, folder.toString());
- AdtPlugin.printErrorToConsole(getProject(), msg);
- }
- }
-
- /**
- * Get the stderr output of a process and return when the process is done.
- * @param process The process to get the ouput from
- * @param stdErr The array to store the stderr output
- * @return the process return code.
- * @throws InterruptedException
- */
- protected final int grabProcessOutput(final Process process,
- final ArrayList<String> stdErr) throws InterruptedException {
- return BuildHelper.grabProcessOutput(getProject(), process, stdErr);
- }
-
-
-
- /**
- * Saves a String property into the persistent storage of the project.
- * @param propertyName the name of the property. The id of the plugin is added to this string.
- * @param value the value to save
- * @return true if the save succeeded.
- */
- protected boolean saveProjectStringProperty(String propertyName, String value) {
- IProject project = getProject();
- return ProjectHelper.saveStringProperty(project, propertyName, value);
- }
-
-
- /**
- * Loads a String property from the persistent storage of the project.
- * @param propertyName the name of the property. The id of the plugin is added to this string.
- * @return the property value or null if it was not found.
- */
- protected String loadProjectStringProperty(String propertyName) {
- IProject project = getProject();
- return ProjectHelper.loadStringProperty(project, propertyName);
- }
-
- /**
- * Saves a property into the persistent storage of the project.
- * @param propertyName the name of the property. The id of the plugin is added to this string.
- * @param value the value to save
- * @return true if the save succeeded.
- */
- protected boolean saveProjectBooleanProperty(String propertyName, boolean value) {
- IProject project = getProject();
- return ProjectHelper.saveStringProperty(project, propertyName, Boolean.toString(value));
- }
-
- /**
- * Loads a boolean property from the persistent storage of the project.
- * @param propertyName the name of the property. The id of the plugin is added to this string.
- * @param defaultValue The default value to return if the property was not found.
- * @return the property value or the default value if the property was not found.
- */
- protected boolean loadProjectBooleanProperty(String propertyName, boolean defaultValue) {
- IProject project = getProject();
- return ProjectHelper.loadBooleanProperty(project, propertyName, defaultValue);
- }
-
- /**
- * Aborts the build if the SDK/project setups are broken. This does not
- * display any errors.
- *
- * @param javaProject The {@link IJavaProject} being compiled.
- * @param projectState the project state, optional. will be queried if null.
- * @throws CoreException
- */
- protected void abortOnBadSetup(@NonNull IJavaProject javaProject,
- @Nullable ProjectState projectState) throws AbortBuildException, CoreException {
- IProject iProject = javaProject.getProject();
- // check if we have finished loading the project target.
- Sdk sdk = Sdk.getCurrent();
- if (sdk == null) {
- throw new AbortBuildException();
- }
-
- if (projectState == null) {
- projectState = Sdk.getProjectState(javaProject.getProject());
- }
-
- // get the target for the project
- IAndroidTarget target = projectState.getTarget();
-
- if (target == null) {
- throw new AbortBuildException();
- }
-
- // check on the target data.
- if (sdk.checkAndLoadTargetData(target, javaProject) != LoadStatus.LOADED) {
- throw new AbortBuildException();
- }
-
- mBuildToolInfo = projectState.getBuildToolInfo();
- if (mBuildToolInfo == null) {
- mBuildToolInfo = sdk.getLatestBuildTool();
-
- if (mBuildToolInfo == null) {
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, iProject,
- "No \"Build Tools\" package available; use SDK Manager to install one.");
- throw new AbortBuildException();
- } else {
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, iProject,
- String.format("Using default Build Tools revision %s",
- mBuildToolInfo.getRevision())
- );
- }
- }
-
- // abort if there are TARGET or ADT type markers
- stopOnMarker(iProject, AdtConstants.MARKER_TARGET, IResource.DEPTH_ZERO,
- false /*checkSeverity*/);
- stopOnMarker(iProject, AdtConstants.MARKER_ADT, IResource.DEPTH_ZERO,
- false /*checkSeverity*/);
- }
-
- protected void stopOnMarker(IProject project, String markerType, int depth,
- boolean checkSeverity)
- throws AbortBuildException {
- try {
- IMarker[] markers = project.findMarkers(markerType, false /*includeSubtypes*/, depth);
-
- if (markers.length > 0) {
- if (checkSeverity == false) {
- throw new AbortBuildException();
- } else {
- for (IMarker marker : markers) {
- int severity = marker.getAttribute(IMarker.SEVERITY, -1 /*defaultValue*/);
- if (severity == IMarker.SEVERITY_ERROR) {
- throw new AbortBuildException();
- }
- }
- }
- }
- } catch (CoreException e) {
- // don't stop, something's really screwed up and the build will break later with
- // a better error message.
- }
- }
-
- /**
- * Handles a {@link StreamException} by logging the info and marking the project.
- * This should generally be followed by exiting the build process.
- *
- * @param e the exception
- */
- protected void handleStreamException(StreamException e) {
- IAbstractFile file = e.getFile();
-
- String msg;
-
- IResource target = getProject();
- if (file instanceof IFileWrapper) {
- target = ((IFileWrapper) file).getIFile();
-
- if (e.getError() == StreamException.Error.OUTOFSYNC) {
- msg = "File is Out of sync";
- } else {
- msg = "Error reading file. Read log for details";
- }
-
- } else {
- if (e.getError() == StreamException.Error.OUTOFSYNC) {
- msg = String.format("Out of sync file: %s", file.getOsLocation());
- } else {
- msg = String.format("Error reading file %s. Read log for details",
- file.getOsLocation());
- }
- }
-
- AdtPlugin.logAndPrintError(e, getProject().getName(), msg);
- BaseProjectHelper.markResource(target, AdtConstants.MARKER_ADT, msg,
- IMarker.SEVERITY_ERROR);
- }
-
- /**
- * Handles a generic {@link Throwable} by logging the info and marking the project.
- * This should generally be followed by exiting the build process.
- *
- * @param t the {@link Throwable}.
- * @param message the message to log and to associate with the marker.
- */
- protected void handleException(Throwable t, String message) {
- AdtPlugin.logAndPrintError(t, getProject().getName(), message);
- markProject(AdtConstants.MARKER_ADT, message, IMarker.SEVERITY_ERROR);
- }
-
- /**
- * Recursively delete all the derived resources from a root resource. The root resource is not
- * deleted.
- * @param rootResource the root resource
- * @param monitor a progress monitor.
- * @throws CoreException
- *
- */
- protected void removeDerivedResources(IResource rootResource, IProgressMonitor monitor)
- throws CoreException {
- removeDerivedResources(rootResource, false, monitor);
- }
-
- /**
- * delete a resource and its children. returns true if the root resource was deleted. All
- * sub-folders *will* be deleted if they were emptied (not if they started empty).
- * @param rootResource the root resource
- * @param deleteRoot whether to delete the root folder.
- * @param monitor a progress monitor.
- * @throws CoreException
- */
- private void removeDerivedResources(IResource rootResource, boolean deleteRoot,
- IProgressMonitor monitor) throws CoreException {
- if (rootResource.exists()) {
- // if it's a folder, delete derived member.
- if (rootResource.getType() == IResource.FOLDER) {
- IFolder folder = (IFolder)rootResource;
- IResource[] members = folder.members();
- boolean wasNotEmpty = members.length > 0;
- for (IResource member : members) {
- removeDerivedResources(member, true /*deleteRoot*/, monitor);
- }
-
- // if the folder had content that is now all removed, delete the folder.
- if (deleteRoot && wasNotEmpty && folder.members().length == 0) {
- rootResource.getLocation().toFile().delete();
- }
- }
-
- // if the root resource is derived, delete it.
- if (rootResource.isDerived()) {
- rootResource.getLocation().toFile().delete();
- }
- }
- }
-
- protected void launchJob(Job newJob) {
- newJob.setPriority(Job.BUILD);
- newJob.setRule(ResourcesPlugin.getWorkspace().getRoot());
- newJob.schedule();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/ChangedFileSet.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/ChangedFileSet.java
deleted file mode 100644
index 4f5b47f6d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/ChangedFileSet.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build.builders;
-
-import com.android.annotations.NonNull;
-
-import org.apache.tools.ant.types.selectors.SelectorUtils;
-import org.eclipse.core.runtime.IPath;
-
-/**
- * Collection of file path or path patterns to be checked for changes.
- *
- * All paths should be relative to the project they belong to.
- * Patterns can use Ant-type glob patterns.
- *
- * This is an immutable class that does not store any info beyond the list of paths. This is to
- * be used in conjunction with {@link PatternBasedDeltaVisitor}.
- */
-class ChangedFileSet {
-
- private final String mLogName;
-
- private final String[] mInputs;
- private String mOutput;
-
- ChangedFileSet(String logName, String... inputs) {
- mLogName = logName;
- mInputs = inputs;
- }
-
- public void setOutput(@NonNull String output) {
- mOutput = output;
- }
-
- public boolean isInput(@NonNull String path, @NonNull IPath iPath) {
- for (String i : mInputs) {
- if (SelectorUtils.matchPath(i, path)) {
- return true;
- }
- }
-
- return false;
- }
-
- public boolean isOutput(@NonNull String path, @NonNull IPath iPath) {
- if (mOutput != null) {
- return SelectorUtils.matchPath(mOutput, path);
- }
-
- return false;
- }
-
- public String getLogName() {
- return mLogName;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/ChangedFileSetHelper.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/ChangedFileSetHelper.java
deleted file mode 100644
index 9fc19a7a6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/ChangedFileSetHelper.java
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build.builders;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IPath;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Helper class to generate {@link ChangedFileSet} for given projects.
- *
- * Also contains non project specific {@link ChangedFileSet} such as {@link #MANIFEST}
- * and {@link #NATIVE_LIBS}
- */
-class ChangedFileSetHelper {
-
- final static ChangedFileSet MANIFEST;
- final static ChangedFileSet NATIVE_LIBS;
-
- static {
- MANIFEST = new ChangedFileSet("manifest", //$NON-NLS-1$
- SdkConstants.FN_ANDROID_MANIFEST_XML);
-
- // FIXME: move compiled native libs to bin/libs/
- NATIVE_LIBS = new ChangedFileSet(
- "nativeLibs",
- SdkConstants.FD_NATIVE_LIBS + "/*/*.so", //$NON-NLS-1$
- SdkConstants.FD_NATIVE_LIBS + "/*/" + SdkConstants.FN_GDBSERVER); //$NON-NLS-1$
- }
-
- /**
- * Returns a ChangedFileSet for Java resources inside a given project's source folders.
- * @param project the project.
- * @return a ChangedFileSet
- */
- static ChangedFileSet getJavaResCfs(@NonNull IProject project) {
-
- // get the source folder for the given project.
- IPath projectPath = project.getFullPath();
-
- // get the source folders.
- List<IPath> srcPaths = BaseProjectHelper.getSourceClasspaths(project);
- List<String> paths = new ArrayList<String>(srcPaths.size());
-
- // create a pattern for each of them.
- for (IPath path : srcPaths) {
- paths.add(path.makeRelativeTo(projectPath).toString() + "/**"); //$NON-NLS-1$
- }
-
- // custom ChangedFileSet to ignore .java files.
- return new JavaResChangedSet("javaRes", //$NON-NLS-1$
- paths.toArray(new String[paths.size()]));
- }
-
- /**
- * Returns a {@link ChangedFileSet} for all the resources (included assets), and the output
- * file (compiled resources
- * @param project the project
- * @return a ChangeFileSet
- */
- static ChangedFileSet getResCfs(@NonNull IProject project) {
- // generated res is inside the project's android output folder
- String path = getRelativeAndroidOut(project);
-
- ChangedFileSet set = new ChangedFileSet(
- "resources", //$NON-NLS-1$
- SdkConstants.FD_RES + "/**", //$NON-NLS-1$
- SdkConstants.FD_ASSETS + "/**", //$NON-NLS-1$
- path + '/' + AdtConstants.WS_BIN_RELATIVE_BC + "/**"); //$NON-NLS-1$
-
- // output file is based on the project's android output folder
- set.setOutput(path + '/' + AdtConstants.FN_RESOURCES_AP_);
-
- return set;
- }
-
- /**
- * Returns a {@link ChangedFileSet} for all the resources (included assets), and the output
- * file (compiled resources
- * @param project the project
- * @return a ChangeFileSet
- */
- static ChangedFileSet getMergedManifestCfs(@NonNull IProject project) {
- // input path is inside the project's android output folder
- String path = getRelativeAndroidOut(project);
-
- ChangedFileSet set = new ChangedFileSet(
- "mergedManifest", //$NON-NLS-1$
- path + '/' + SdkConstants.FN_ANDROID_MANIFEST_XML);
-
- return set;
- }
-
- /**
- * Returns a {@link ChangedFileSet} for the generated R.txt file
- * @param project the project
- * @return a ChangeFileSet
- */
- static ChangedFileSet getTextSymbols(@NonNull IProject project) {
- // input path is inside the project's android output folder
- String path = getRelativeAndroidOut(project);
-
- ChangedFileSet set = new ChangedFileSet(
- "textSymbols", //$NON-NLS-1$
- path + '/' + SdkConstants.FN_RESOURCE_TEXT);
-
- return set;
- }
-
- /**
- * Returns a {@link ChangedFileSet} for a project's javac output.
- * @param project the project
- * @return a ChangedFileSet
- */
- static ChangedFileSet getByteCodeCfs(@NonNull IProject project) {
- // input pattern is based on the project's Java compiler's output folder
- String path = getRelativeJavaCOut(project);
-
- ChangedFileSet set = new ChangedFileSet("compiledCode", //$NON-NLS-1$
- path + "/**/*" + SdkConstants.DOT_CLASS); //$NON-NLS-1$
-
- return set;
- }
-
- /**
- * Returns a {@link ChangedFileSet} for a project's complete resources, including
- * generated resources and crunch cache.
- * @param project the project
- * @return a ChangeFileSet
- */
- static ChangedFileSet getFullResCfs(@NonNull IProject project) {
- // generated res are in the project's android output folder
- String path = getRelativeAndroidOut(project);
-
- ChangedFileSet set = new ChangedFileSet("libResources", //$NON-NLS-1$
- SdkConstants.FD_RES + "/**", //$NON-NLS-1$
- path + '/' + SdkConstants.FD_RES + "/**"); //$NON-NLS-1$
-
- return set;
- }
-
- /**
- * Returns a {@link ChangedFileSet} for a project's whole code, including
- * compiled bytecode, 3rd party libs, and the output file containing the Dalvik
- * bytecode file.
- * @param project the project
- * @return a ChangeFileSet
- */
- static ChangedFileSet getCodeCfs(@NonNull IProject project) {
- // input pattern is based on the project's Java compiler's output folder
- String path = getRelativeJavaCOut(project);
-
- ChangedFileSet set = new ChangedFileSet("classAndJars", //$NON-NLS-1$
- path + "/**/*" + SdkConstants.DOT_CLASS, //$NON-NLS-1$
- SdkConstants.FD_NATIVE_LIBS + "/*" + SdkConstants.DOT_JAR); //$NON-NLS-1$
-
- // output file is based on the project's android output folder
- path = getRelativeAndroidOut(project);
- set.setOutput(path + '/' + SdkConstants.FN_APK_CLASSES_DEX);
-
- return set;
- }
-
- private static String getRelativePath(@NonNull IProject project, @NonNull IResource resource) {
- return resource.getFullPath().makeRelativeTo(project.getFullPath()).toString();
- }
-
- private static String getRelativeAndroidOut(@NonNull IProject project) {
- IFolder folder = BaseProjectHelper.getAndroidOutputFolder(project);
- return getRelativePath(project, folder);
- }
-
- private static String getRelativeJavaCOut(@NonNull IProject project) {
- IFolder folder = BaseProjectHelper.getJavaOutputFolder(project);
- return getRelativePath(project, folder);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/JavaResChangedSet.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/JavaResChangedSet.java
deleted file mode 100644
index 6b257efbf..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/JavaResChangedSet.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build.builders;
-
-import com.android.annotations.NonNull;
-import com.android.sdklib.build.ApkBuilder;
-
-import org.eclipse.core.runtime.IPath;
-
-/**
- * Custom {@link ChangedFileSet} for java resources.
- *
- * This builds the set of inputs to be all the source folders of the given project,
- * and excludes files that won't be packaged.
- * This exclusion can't be easily described as a glob-pattern so it's overriding the default
- * behavior instead.
- *
- */
-class JavaResChangedSet extends ChangedFileSet {
-
- JavaResChangedSet(String logName, String... inputs) {
- super(logName, inputs);
- }
-
- @Override
- public boolean isInput(@NonNull String path, @NonNull IPath iPath) {
- if (!ApkBuilder.checkFileForPackaging(iPath.lastSegment(), iPath.getFileExtension())) {
- return false;
- }
- return super.isInput(path, iPath);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/PatternBasedDeltaVisitor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/PatternBasedDeltaVisitor.java
deleted file mode 100644
index b52ede90c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/PatternBasedDeltaVisitor.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build.builders;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.build.BuildHelper;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IResourceDeltaVisitor;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-
-import java.util.ArrayList;
-import java.util.IdentityHashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Delta visitor checking changed files against given glob-patterns.
- *
- * The visitor is given {@link ChangedFileSet} objects which contains patterns to detect change
- * in input and output files. (Output files are only tested if the delta indicate the file
- * was removed).
- *
- * After the visitor has visited the whole delta, it can be queried to see which ChangedFileSet
- * recognized a file change. (ChangedFileSet are immutable and do not record this info).
- */
-class PatternBasedDeltaVisitor implements IResourceDeltaVisitor {
-
- private final static boolean DEBUG_LOG = "1".equals( //$NON-NLS-1$
- System.getenv("ANDROID_VISITOR_DEBUG")); //$NON-NLS-1$
-
- private final IProject mMainProject;
- private final IProject mDeltaProject;
-
- private final List<ChangedFileSet> mSets = new ArrayList<ChangedFileSet>();
- private final Map<ChangedFileSet, Boolean> mResults =
- new IdentityHashMap<ChangedFileSet, Boolean>();
-
- private final String mLogName;
-
- PatternBasedDeltaVisitor(IProject mainProject, IProject deltaProject, String logName) {
- mMainProject = mainProject;
- mDeltaProject = deltaProject;
- mLogName = logName;
- if (DEBUG_LOG) {
- AdtPlugin.log(IStatus.INFO, "%s (%s): Delta for %s", //$NON-NLS-1$
- mMainProject.getName(), mLogName, mDeltaProject.getName());
- }
- }
-
- void addSet(ChangedFileSet bundle) {
- mSets.add(bundle);
- }
-
- boolean checkSet(ChangedFileSet bundle) {
- Boolean r = mResults.get(bundle);
- if (r != null) {
- return r.booleanValue();
- }
-
- return false;
- }
-
- @Override
- public boolean visit(IResourceDelta delta) throws CoreException {
- IResource resource = delta.getResource();
-
- if (resource.getType() == IResource.FOLDER) {
- // always visit the subfolders, unless the folder is not to be included
- return BuildHelper.checkFolderForPackaging((IFolder)resource);
-
- } else if (resource.getType() == IResource.FILE) {
- IPath path = resource.getFullPath().makeRelativeTo(mDeltaProject.getFullPath());
- String pathStr = path.toString();
-
- // FIXME: no need to loop through all the sets once they have all said they need something (return false below and above)
- for (ChangedFileSet set : mSets) {
- // FIXME: should ignore sets that have already returned true.
-
- if (set.isInput(pathStr, path)) {
- mResults.put(set, Boolean.TRUE);
-
- if (DEBUG_LOG) {
- String cfs_logName = set.getLogName();
-
- if (cfs_logName != null) {
- AdtPlugin.log(IStatus.INFO, "%s (%s:%s): %s", //$NON-NLS-1$
- mMainProject.getName(), mLogName, cfs_logName,
- resource.getFullPath().toString());
- } else {
- AdtPlugin.log(IStatus.INFO, "%s (%s): %s", //$NON-NLS-1$
- mMainProject.getName(), mLogName,
- resource.getFullPath().toString());
- }
- }
-
- } else if (delta.getKind() == IResourceDelta.REMOVED &&
- set.isOutput(pathStr, path)) {
- mResults.put(set, Boolean.TRUE);
-
- if (DEBUG_LOG) {
- String cfs_logName = set.getLogName();
-
- if (cfs_logName != null) {
- AdtPlugin.log(IStatus.INFO, "%s (%s:%s): %s", //$NON-NLS-1$
- mMainProject.getName(), mLogName, cfs_logName,
- resource.getFullPath().toString());
- } else {
- AdtPlugin.log(IStatus.INFO, "%s (%s): %s", //$NON-NLS-1$
- mMainProject.getName(), mLogName,
- resource.getFullPath().toString());
- }
- }
- }
- }
- }
-
- return true;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/PostCompilerBuilder.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/PostCompilerBuilder.java
deleted file mode 100644
index 8aacb44ef..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/PostCompilerBuilder.java
+++ /dev/null
@@ -1,946 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build.builders;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AndroidPrintStream;
-import com.android.ide.eclipse.adt.internal.build.AaptExecException;
-import com.android.ide.eclipse.adt.internal.build.AaptParser;
-import com.android.ide.eclipse.adt.internal.build.AaptResultException;
-import com.android.ide.eclipse.adt.internal.build.BuildHelper;
-import com.android.ide.eclipse.adt.internal.build.BuildHelper.ResourceMarker;
-import com.android.ide.eclipse.adt.internal.build.DexException;
-import com.android.ide.eclipse.adt.internal.build.Messages;
-import com.android.ide.eclipse.adt.internal.build.NativeLibInJarException;
-import com.android.ide.eclipse.adt.internal.lint.LintDeltaProcessor;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs.BuildVerbosity;
-import com.android.ide.eclipse.adt.internal.project.ApkInstallManager;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.project.LibraryClasspathContainerInitializer;
-import com.android.ide.eclipse.adt.internal.project.ProjectHelper;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.io.IFileWrapper;
-import com.android.prefs.AndroidLocation.AndroidLocationException;
-import com.android.sdklib.build.ApkBuilder;
-import com.android.sdklib.build.ApkCreationException;
-import com.android.sdklib.build.DuplicateFileException;
-import com.android.sdklib.build.IArchiveBuilder;
-import com.android.sdklib.build.SealedApkException;
-import com.android.sdklib.internal.build.DebugKeyProvider.KeytoolException;
-import com.android.xml.AndroidManifest;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jdt.core.IJavaModelMarker;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.JavaCore;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.jar.Attributes;
-import java.util.jar.JarEntry;
-import java.util.jar.JarOutputStream;
-import java.util.jar.Manifest;
-import java.util.regex.Pattern;
-
-public class PostCompilerBuilder extends BaseBuilder {
-
- /** This ID is used in plugin.xml and in each project's .project file.
- * It cannot be changed even if the class is renamed/moved */
- public static final String ID = "com.android.ide.eclipse.adt.ApkBuilder"; //$NON-NLS-1$
-
- private static final String PROPERTY_CONVERT_TO_DEX = "convertToDex"; //$NON-NLS-1$
- private static final String PROPERTY_PACKAGE_RESOURCES = "packageResources"; //$NON-NLS-1$
- private static final String PROPERTY_BUILD_APK = "buildApk"; //$NON-NLS-1$
-
- /** Flag to pass to PostCompiler builder that sets if it runs or not.
- * Set this flag whenever calling build if PostCompiler is to run
- */
- public final static String POST_C_REQUESTED = "RunPostCompiler"; //$NON-NLS-1$
-
- /**
- * Dex conversion flag. This is set to true if one of the changed/added/removed
- * file is a .class file. Upon visiting all the delta resource, if this
- * flag is true, then we know we'll have to make the "classes.dex" file.
- */
- private boolean mConvertToDex = false;
-
- /**
- * Package resources flag. This is set to true if one of the changed/added/removed
- * file is a resource file. Upon visiting all the delta resource, if
- * this flag is true, then we know we'll have to repackage the resources.
- */
- private boolean mPackageResources = false;
-
- /**
- * Final package build flag.
- */
- private boolean mBuildFinalPackage = false;
-
- private AndroidPrintStream mOutStream = null;
- private AndroidPrintStream mErrStream = null;
-
-
- private ResourceMarker mResourceMarker = new ResourceMarker() {
- @Override
- public void setWarning(IResource resource, String message) {
- BaseProjectHelper.markResource(resource, AdtConstants.MARKER_PACKAGING,
- message, IMarker.SEVERITY_WARNING);
- }
- };
-
-
- public PostCompilerBuilder() {
- super();
- }
-
- @Override
- protected void clean(IProgressMonitor monitor) throws CoreException {
- super.clean(monitor);
-
- // Get the project.
- IProject project = getProject();
-
- if (DEBUG_LOG) {
- AdtPlugin.log(IStatus.INFO, "%s CLEAN(POST)", project.getName());
- }
-
- // Clear the project of the generic markers
- removeMarkersFromContainer(project, AdtConstants.MARKER_AAPT_PACKAGE);
- removeMarkersFromContainer(project, AdtConstants.MARKER_PACKAGING);
-
- // also remove the files in the output folder (but not the Eclipse output folder).
- IFolder javaOutput = BaseProjectHelper.getJavaOutputFolder(project);
- IFolder androidOutput = BaseProjectHelper.getAndroidOutputFolder(project);
-
- if (javaOutput.equals(androidOutput) == false) {
- // get the content
- IResource[] members = androidOutput.members();
- for (IResource member : members) {
- if (member.equals(javaOutput) == false) {
- member.delete(true /*force*/, monitor);
- }
- }
- }
- }
-
- // build() returns a list of project from which this project depends for future compilation.
- @Override
- protected IProject[] build(
- int kind,
- @SuppressWarnings("rawtypes") Map args,
- IProgressMonitor monitor)
- throws CoreException {
- // get a project object
- IProject project = getProject();
-
- if (DEBUG_LOG) {
- AdtPlugin.log(IStatus.INFO, "%s BUILD(POST)", project.getName());
- }
-
- // Benchmarking start
- long startBuildTime = 0;
- if (BuildHelper.BENCHMARK_FLAG) {
- // End JavaC Timer
- String msg = "BENCHMARK ADT: Ending Compilation \n BENCHMARK ADT: Time Elapsed: " + //$NON-NLS-1$
- (System.nanoTime() - BuildHelper.sStartJavaCTime)/Math.pow(10, 6) + "ms"; //$NON-NLS-1$
- AdtPlugin.printBuildToConsole(BuildVerbosity.ALWAYS, project, msg);
- msg = "BENCHMARK ADT: Starting PostCompilation"; //$NON-NLS-1$
- AdtPlugin.printBuildToConsole(BuildVerbosity.ALWAYS, project, msg);
- startBuildTime = System.nanoTime();
- }
-
- // list of referenced projects. This is a mix of java projects and library projects
- // and is computed below.
- IProject[] allRefProjects = null;
-
- try {
- // get the project info
- ProjectState projectState = Sdk.getProjectState(project);
-
- // this can happen if the project has no project.properties.
- if (projectState == null) {
- return null;
- }
-
- boolean isLibrary = projectState.isLibrary();
-
- // get the libraries
- List<IProject> libProjects = projectState.getFullLibraryProjects();
-
- IJavaProject javaProject = JavaCore.create(project);
-
- // get the list of referenced projects.
- List<IProject> javaProjects = ProjectHelper.getReferencedProjects(project);
- List<IJavaProject> referencedJavaProjects = BuildHelper.getJavaProjects(
- javaProjects);
-
- // mix the java project and the library projects
- final int size = libProjects.size() + javaProjects.size();
- ArrayList<IProject> refList = new ArrayList<IProject>(size);
- refList.addAll(libProjects);
- refList.addAll(javaProjects);
- allRefProjects = refList.toArray(new IProject[size]);
-
- // get the android output folder
- IFolder androidOutputFolder = BaseProjectHelper.getAndroidOutputFolder(project);
- IFolder resOutputFolder = androidOutputFolder.getFolder(SdkConstants.FD_RES);
-
- // First thing we do is go through the resource delta to not
- // lose it if we have to abort the build for any reason.
- if (args.containsKey(POST_C_REQUESTED)
- && AdtPrefs.getPrefs().getBuildSkipPostCompileOnFileSave()) {
- // Skip over flag setting
- } else if (kind == FULL_BUILD) {
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project,
- Messages.Start_Full_Apk_Build);
-
- if (DEBUG_LOG) {
- AdtPlugin.log(IStatus.INFO, "%s full build!", project.getName());
- }
-
- // Full build: we do all the steps.
- mPackageResources = true;
- mConvertToDex = true;
- mBuildFinalPackage = true;
- } else {
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project,
- Messages.Start_Inc_Apk_Build);
-
- // go through the resources and see if something changed.
- IResourceDelta delta = getDelta(project);
- if (delta == null) {
- // no delta? Same as full build: we do all the steps.
- mPackageResources = true;
- mConvertToDex = true;
- mBuildFinalPackage = true;
- } else {
-
- if (ResourceManager.isAutoBuilding() && AdtPrefs.getPrefs().isLintOnSave()) {
- // Check for errors on save/build, if enabled
- LintDeltaProcessor.create().process(delta);
- }
-
- PatternBasedDeltaVisitor dv = new PatternBasedDeltaVisitor(
- project, project,
- "POST:Main");
-
- ChangedFileSet manifestCfs = ChangedFileSetHelper.getMergedManifestCfs(project);
- dv.addSet(manifestCfs);
-
- ChangedFileSet resCfs = ChangedFileSetHelper.getResCfs(project);
- dv.addSet(resCfs);
-
- ChangedFileSet androidCodeCfs = ChangedFileSetHelper.getCodeCfs(project);
- dv.addSet(androidCodeCfs);
-
- ChangedFileSet javaResCfs = ChangedFileSetHelper.getJavaResCfs(project);
- dv.addSet(javaResCfs);
- dv.addSet(ChangedFileSetHelper.NATIVE_LIBS);
-
- delta.accept(dv);
-
- // save the state
- mPackageResources |= dv.checkSet(manifestCfs) || dv.checkSet(resCfs);
-
- mConvertToDex |= dv.checkSet(androidCodeCfs);
-
- mBuildFinalPackage |= dv.checkSet(javaResCfs) ||
- dv.checkSet(ChangedFileSetHelper.NATIVE_LIBS);
- }
-
- // check the libraries
- if (libProjects.size() > 0) {
- for (IProject libProject : libProjects) {
- delta = getDelta(libProject);
- if (delta != null) {
- PatternBasedDeltaVisitor visitor = new PatternBasedDeltaVisitor(
- project, libProject,
- "POST:Lib");
-
- ChangedFileSet libResCfs = ChangedFileSetHelper.getFullResCfs(
- libProject);
- visitor.addSet(libResCfs);
- visitor.addSet(ChangedFileSetHelper.NATIVE_LIBS);
- // FIXME: add check on the library.jar?
-
- delta.accept(visitor);
-
- mPackageResources |= visitor.checkSet(libResCfs);
- mBuildFinalPackage |= visitor.checkSet(
- ChangedFileSetHelper.NATIVE_LIBS);
- }
- }
- }
-
- // also go through the delta for all the referenced projects
- final int referencedCount = referencedJavaProjects.size();
- for (int i = 0 ; i < referencedCount; i++) {
- IJavaProject referencedJavaProject = referencedJavaProjects.get(i);
- delta = getDelta(referencedJavaProject.getProject());
- if (delta != null) {
- IProject referencedProject = referencedJavaProject.getProject();
- PatternBasedDeltaVisitor visitor = new PatternBasedDeltaVisitor(
- project, referencedProject,
- "POST:RefedProject");
-
- ChangedFileSet javaResCfs = ChangedFileSetHelper.getJavaResCfs(referencedProject);
- visitor.addSet(javaResCfs);
-
- ChangedFileSet bytecodeCfs = ChangedFileSetHelper.getByteCodeCfs(referencedProject);
- visitor.addSet(bytecodeCfs);
-
- delta.accept(visitor);
-
- // save the state
- mConvertToDex |= visitor.checkSet(bytecodeCfs);
- mBuildFinalPackage |= visitor.checkSet(javaResCfs);
- }
- }
- }
-
- // store the build status in the persistent storage
- saveProjectBooleanProperty(PROPERTY_CONVERT_TO_DEX, mConvertToDex);
- saveProjectBooleanProperty(PROPERTY_PACKAGE_RESOURCES, mPackageResources);
- saveProjectBooleanProperty(PROPERTY_BUILD_APK, mBuildFinalPackage);
-
- // Top level check to make sure the build can move forward. Only do this after recording
- // delta changes.
- abortOnBadSetup(javaProject, projectState);
-
- // Get the output stream. Since the builder is created for the life of the
- // project, they can be kept around.
- if (mOutStream == null) {
- mOutStream = new AndroidPrintStream(project, null /*prefix*/,
- AdtPlugin.getOutStream());
- mErrStream = new AndroidPrintStream(project, null /*prefix*/,
- AdtPlugin.getOutStream());
- }
-
- // remove older packaging markers.
- removeMarkersFromContainer(javaProject.getProject(), AdtConstants.MARKER_PACKAGING);
-
- // finished with the common init and tests. Special case of the library.
- if (isLibrary) {
- // check the jar output file is present, if not create it.
- IFile jarIFile = androidOutputFolder.getFile(
- project.getName().toLowerCase() + SdkConstants.DOT_JAR);
- if (mConvertToDex == false && jarIFile.exists() == false) {
- mConvertToDex = true;
- }
-
- // also update the crunch cache always since aapt does it smartly only
- // on the files that need it.
- if (DEBUG_LOG) {
- AdtPlugin.log(IStatus.INFO, "%s running crunch!", project.getName());
- }
- BuildHelper helper = new BuildHelper(
- projectState,
- mBuildToolInfo,
- mOutStream, mErrStream,
- false /*jumbo mode doesn't matter here*/,
- false /*dex merger doesn't matter here*/,
- true /*debugMode*/,
- AdtPrefs.getPrefs().getBuildVerbosity() == BuildVerbosity.VERBOSE,
- mResourceMarker);
- updateCrunchCache(project, helper);
-
- // refresh recursively bin/res folder
- resOutputFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);
-
- if (mConvertToDex) { // in this case this means some class files changed and
- // we need to update the jar file.
- if (DEBUG_LOG) {
- AdtPlugin.log(IStatus.INFO, "%s updating jar!", project.getName());
- }
-
- // resource to the AndroidManifest.xml file
- IFile manifestFile = project.getFile(SdkConstants.FN_ANDROID_MANIFEST_XML);
- String appPackage = AndroidManifest.getPackage(new IFileWrapper(manifestFile));
-
- IFolder javaOutputFolder = BaseProjectHelper.getJavaOutputFolder(project);
-
- writeLibraryPackage(jarIFile, project, appPackage, javaOutputFolder);
- saveProjectBooleanProperty(PROPERTY_CONVERT_TO_DEX, mConvertToDex = false);
-
- // refresh the bin folder content with no recursion to update the library
- // jar file.
- androidOutputFolder.refreshLocal(IResource.DEPTH_ONE, monitor);
-
- // Also update the projects. The only way to force recompile them is to
- // reset the library container.
- List<ProjectState> parentProjects = projectState.getParentProjects();
- LibraryClasspathContainerInitializer.updateProject(parentProjects);
- }
-
- return allRefProjects;
- }
-
- // Check to see if we're going to launch or export. If not, we can skip
- // the packaging and dexing process.
- if (!args.containsKey(POST_C_REQUESTED)
- && AdtPrefs.getPrefs().getBuildSkipPostCompileOnFileSave()) {
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project,
- Messages.Skip_Post_Compiler);
- return allRefProjects;
- } else {
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project,
- Messages.Start_Full_Post_Compiler);
- }
-
- // first thing we do is check that the SDK directory has been setup.
- String osSdkFolder = AdtPlugin.getOsSdkFolder();
-
- if (osSdkFolder.length() == 0) {
- // this has already been checked in the precompiler. Therefore,
- // while we do have to cancel the build, we don't have to return
- // any error or throw anything.
- return allRefProjects;
- }
-
- // do some extra check, in case the output files are not present. This
- // will force to recreate them.
- IResource tmp = null;
-
- if (mPackageResources == false) {
- // check the full resource package
- tmp = androidOutputFolder.findMember(AdtConstants.FN_RESOURCES_AP_);
- if (tmp == null || tmp.exists() == false) {
- mPackageResources = true;
- }
- }
-
- // check classes.dex is present. If not we force to recreate it.
- if (mConvertToDex == false) {
- tmp = androidOutputFolder.findMember(SdkConstants.FN_APK_CLASSES_DEX);
- if (tmp == null || tmp.exists() == false) {
- mConvertToDex = true;
- }
- }
-
- // also check the final file(s)!
- String finalPackageName = ProjectHelper.getApkFilename(project, null /*config*/);
- if (mBuildFinalPackage == false) {
- tmp = androidOutputFolder.findMember(finalPackageName);
- if (tmp == null || (tmp instanceof IFile &&
- tmp.exists() == false)) {
- String msg = String.format(Messages.s_Missing_Repackaging, finalPackageName);
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project, msg);
- mBuildFinalPackage = true;
- }
- }
-
- // at this point we know if we need to recreate the temporary apk
- // or the dex file, but we don't know if we simply need to recreate them
- // because they are missing
-
- // refresh the output directory first
- IContainer ic = androidOutputFolder.getParent();
- if (ic != null) {
- ic.refreshLocal(IResource.DEPTH_ONE, monitor);
- }
-
- // we need to test all three, as we may need to make the final package
- // but not the intermediary ones.
- if (mPackageResources || mConvertToDex || mBuildFinalPackage) {
- String forceJumboStr = projectState.getProperty(
- AdtConstants.DEX_OPTIONS_FORCEJUMBO);
- Boolean jumbo = Boolean.valueOf(forceJumboStr);
-
- String dexMergerStr = projectState.getProperty(
- AdtConstants.DEX_OPTIONS_DISABLE_MERGER);
- Boolean dexMerger = Boolean.valueOf(dexMergerStr);
-
- BuildHelper helper = new BuildHelper(
- projectState,
- mBuildToolInfo,
- mOutStream, mErrStream,
- jumbo.booleanValue(),
- dexMerger.booleanValue(),
- true /*debugMode*/,
- AdtPrefs.getPrefs().getBuildVerbosity() == BuildVerbosity.VERBOSE,
- mResourceMarker);
-
- IPath androidBinLocation = androidOutputFolder.getLocation();
- if (androidBinLocation == null) {
- markProject(AdtConstants.MARKER_PACKAGING, Messages.Output_Missing,
- IMarker.SEVERITY_ERROR);
- return allRefProjects;
- }
- String osAndroidBinPath = androidBinLocation.toOSString();
-
- // resource to the AndroidManifest.xml file
- IFile manifestFile = androidOutputFolder.getFile(
- SdkConstants.FN_ANDROID_MANIFEST_XML);
-
- if (manifestFile == null || manifestFile.exists() == false) {
- // mark project and exit
- String msg = String.format(Messages.s_File_Missing,
- SdkConstants.FN_ANDROID_MANIFEST_XML);
- markProject(AdtConstants.MARKER_PACKAGING, msg, IMarker.SEVERITY_ERROR);
- return allRefProjects;
- }
-
- // Remove the old .apk.
- // This make sure that if the apk is corrupted, then dx (which would attempt
- // to open it), will not fail.
- String osFinalPackagePath = osAndroidBinPath + File.separator + finalPackageName;
- File finalPackage = new File(osFinalPackagePath);
-
- // if delete failed, this is not really a problem, as the final package generation
- // handle already present .apk, and if that one failed as well, the user will be
- // notified.
- finalPackage.delete();
-
- // Check if we need to package the resources.
- if (mPackageResources) {
- // also update the crunch cache always since aapt does it smartly only
- // on the files that need it.
- if (DEBUG_LOG) {
- AdtPlugin.log(IStatus.INFO, "%s running crunch!", project.getName());
- }
- if (updateCrunchCache(project, helper) == false) {
- return allRefProjects;
- }
-
- // refresh recursively bin/res folder
- resOutputFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);
-
- if (DEBUG_LOG) {
- AdtPlugin.log(IStatus.INFO, "%s packaging resources!", project.getName());
- }
- // remove some aapt_package only markers.
- removeMarkersFromContainer(project, AdtConstants.MARKER_AAPT_PACKAGE);
-
- try {
- helper.packageResources(manifestFile, libProjects, null /*resfilter*/,
- 0 /*versionCode */, osAndroidBinPath,
- AdtConstants.FN_RESOURCES_AP_);
- } catch (AaptExecException e) {
- BaseProjectHelper.markResource(project, AdtConstants.MARKER_PACKAGING,
- e.getMessage(), IMarker.SEVERITY_ERROR);
- return allRefProjects;
- } catch (AaptResultException e) {
- // attempt to parse the error output
- String[] aaptOutput = e.getOutput();
- boolean parsingError = AaptParser.parseOutput(aaptOutput, project);
-
- // if we couldn't parse the output we display it in the console.
- if (parsingError) {
- AdtPlugin.printErrorToConsole(project, (Object[]) aaptOutput);
-
- // if the exec failed, and we couldn't parse the error output (and
- // therefore not all files that should have been marked, were marked),
- // we put a generic marker on the project and abort.
- BaseProjectHelper.markResource(project,
- AdtConstants.MARKER_PACKAGING,
- Messages.Unparsed_AAPT_Errors,
- IMarker.SEVERITY_ERROR);
- }
- }
-
- // build has been done. reset the state of the builder
- mPackageResources = false;
-
- // and store it
- saveProjectBooleanProperty(PROPERTY_PACKAGE_RESOURCES, mPackageResources);
- }
-
- String classesDexPath = osAndroidBinPath + File.separator +
- SdkConstants.FN_APK_CLASSES_DEX;
-
- // then we check if we need to package the .class into classes.dex
- if (mConvertToDex) {
- if (DEBUG_LOG) {
- AdtPlugin.log(IStatus.INFO, "%s running dex!", project.getName());
- }
- try {
- Collection<String> dxInputPaths = helper.getCompiledCodePaths();
-
- helper.executeDx(javaProject, dxInputPaths, classesDexPath);
- } catch (DexException e) {
- String message = e.getMessage();
-
- AdtPlugin.printErrorToConsole(project, message);
- BaseProjectHelper.markResource(project, AdtConstants.MARKER_PACKAGING,
- message, IMarker.SEVERITY_ERROR);
-
- Throwable cause = e.getCause();
-
- if (cause instanceof NoClassDefFoundError
- || cause instanceof NoSuchMethodError) {
- AdtPlugin.printErrorToConsole(project, Messages.Incompatible_VM_Warning,
- Messages.Requires_1_5_Error);
- }
-
- // dx failed, we return
- return allRefProjects;
- }
-
- // build has been done. reset the state of the builder
- mConvertToDex = false;
-
- // and store it
- saveProjectBooleanProperty(PROPERTY_CONVERT_TO_DEX, mConvertToDex);
- }
-
- // now we need to make the final package from the intermediary apk
- // and classes.dex.
- // This is the default package with all the resources.
-
- try {
- if (DEBUG_LOG) {
- AdtPlugin.log(IStatus.INFO, "%s making final package!", project.getName());
- }
- helper.finalDebugPackage(
- osAndroidBinPath + File.separator + AdtConstants.FN_RESOURCES_AP_,
- classesDexPath, osFinalPackagePath, libProjects, mResourceMarker);
- } catch (KeytoolException e) {
- String eMessage = e.getMessage();
-
- // mark the project with the standard message
- String msg = String.format(Messages.Final_Archive_Error_s, eMessage);
- BaseProjectHelper.markResource(project, AdtConstants.MARKER_PACKAGING, msg,
- IMarker.SEVERITY_ERROR);
-
- // output more info in the console
- AdtPlugin.printErrorToConsole(project,
- msg,
- String.format(Messages.ApkBuilder_JAVA_HOME_is_s, e.getJavaHome()),
- Messages.ApkBuilder_Update_or_Execute_manually_s,
- e.getCommandLine());
-
- AdtPlugin.log(e, msg);
-
- return allRefProjects;
- } catch (ApkCreationException e) {
- String eMessage = e.getMessage();
-
- // mark the project with the standard message
- String msg = String.format(Messages.Final_Archive_Error_s, eMessage);
- BaseProjectHelper.markResource(project, AdtConstants.MARKER_PACKAGING, msg,
- IMarker.SEVERITY_ERROR);
-
- AdtPlugin.log(e, msg);
- } catch (AndroidLocationException e) {
- String eMessage = e.getMessage();
-
- // mark the project with the standard message
- String msg = String.format(Messages.Final_Archive_Error_s, eMessage);
- BaseProjectHelper.markResource(project, AdtConstants.MARKER_PACKAGING, msg,
- IMarker.SEVERITY_ERROR);
- AdtPlugin.log(e, msg);
- } catch (NativeLibInJarException e) {
- String msg = e.getMessage();
-
- BaseProjectHelper.markResource(project, AdtConstants.MARKER_PACKAGING,
- msg, IMarker.SEVERITY_ERROR);
-
- AdtPlugin.printErrorToConsole(project, (Object[]) e.getAdditionalInfo());
- } catch (CoreException e) {
- // mark project and return
- String msg = String.format(Messages.Final_Archive_Error_s, e.getMessage());
- AdtPlugin.printErrorToConsole(project, msg);
- BaseProjectHelper.markResource(project, AdtConstants.MARKER_PACKAGING, msg,
- IMarker.SEVERITY_ERROR);
- AdtPlugin.log(e, msg);
- } catch (DuplicateFileException e) {
- String msg1 = String.format(
- "Found duplicate file for APK: %1$s\nOrigin 1: %2$s\nOrigin 2: %3$s",
- e.getArchivePath(), e.getFile1(), e.getFile2());
- String msg2 = String.format(Messages.Final_Archive_Error_s, msg1);
- AdtPlugin.printErrorToConsole(project, msg2);
- BaseProjectHelper.markResource(project, AdtConstants.MARKER_PACKAGING, msg2,
- IMarker.SEVERITY_ERROR);
- }
-
- // we are done.
-
- // refresh the bin folder content with no recursion.
- androidOutputFolder.refreshLocal(IResource.DEPTH_ONE, monitor);
-
- // build has been done. reset the state of the builder
- mBuildFinalPackage = false;
-
- // and store it
- saveProjectBooleanProperty(PROPERTY_BUILD_APK, mBuildFinalPackage);
-
- // reset the installation manager to force new installs of this project
- ApkInstallManager.getInstance().resetInstallationFor(project);
-
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, getProject(),
- "Build Success!");
- }
- } catch (AbortBuildException e) {
- return allRefProjects;
- } catch (Exception exception) {
- // try to catch other exception to actually display an error. This will be useful
- // if we get an NPE or something so that we can at least notify the user that something
- // went wrong.
-
- // first check if this is a CoreException we threw to cancel the build.
- if (exception instanceof CoreException) {
- if (((CoreException)exception).getStatus().getSeverity() == IStatus.CANCEL) {
- // Project is already marked with an error. Nothing to do
- return allRefProjects;
- }
- }
-
- String msg = exception.getMessage();
- if (msg == null) {
- msg = exception.getClass().getCanonicalName();
- }
-
- msg = String.format("Unknown error: %1$s", msg);
- AdtPlugin.logAndPrintError(exception, project.getName(), msg);
- markProject(AdtConstants.MARKER_PACKAGING, msg, IMarker.SEVERITY_ERROR);
- }
-
- // Benchmarking end
- if (BuildHelper.BENCHMARK_FLAG) {
- String msg = "BENCHMARK ADT: Ending PostCompilation. \n BENCHMARK ADT: Time Elapsed: " + //$NON-NLS-1$
- ((System.nanoTime() - startBuildTime)/Math.pow(10, 6)) + "ms"; //$NON-NLS-1$
- AdtPlugin.printBuildToConsole(BuildVerbosity.ALWAYS, project, msg);
- // End Overall Timer
- msg = "BENCHMARK ADT: Done with everything! \n BENCHMARK ADT: Time Elapsed: " + //$NON-NLS-1$
- (System.nanoTime() - BuildHelper.sStartOverallTime)/Math.pow(10, 6) + "ms"; //$NON-NLS-1$
- AdtPlugin.printBuildToConsole(BuildVerbosity.ALWAYS, project, msg);
- }
-
- return allRefProjects;
- }
-
- private static class JarBuilder implements IArchiveBuilder {
-
- private static Pattern R_PATTERN = Pattern.compile("R(\\$.*)?\\.class"); //$NON-NLS-1$
- private static String BUILD_CONFIG_CLASS = "BuildConfig.class"; //$NON-NLS-1$
-
- private final byte[] buffer = new byte[1024];
- private final JarOutputStream mOutputStream;
- private final String mAppPackage;
-
- JarBuilder(JarOutputStream outputStream, String appPackage) {
- mOutputStream = outputStream;
- mAppPackage = appPackage.replace('.', '/');
- }
-
- public void addFile(IFile file, IFolder rootFolder) throws ApkCreationException {
- // we only package class file from the output folder
- if (SdkConstants.EXT_CLASS.equals(file.getFileExtension()) == false) {
- return;
- }
-
- IPath packageApp = file.getParent().getFullPath().makeRelativeTo(
- rootFolder.getFullPath());
-
- String name = file.getName();
- // Ignore the library's R/Manifest/BuildConfig classes.
- if (mAppPackage.equals(packageApp.toString()) &&
- (BUILD_CONFIG_CLASS.equals(name) ||
- R_PATTERN.matcher(name).matches())) {
- return;
- }
-
- IPath path = file.getFullPath().makeRelativeTo(rootFolder.getFullPath());
- try {
- addFile(file.getContents(), file.getLocalTimeStamp(), path.toString());
- } catch (ApkCreationException e) {
- throw e;
- } catch (Exception e) {
- throw new ApkCreationException(e, "Failed to add %s", file);
- }
- }
-
- @Override
- public void addFile(File file, String archivePath) throws ApkCreationException,
- SealedApkException, DuplicateFileException {
- try {
- FileInputStream inputStream = new FileInputStream(file);
- long lastModified = file.lastModified();
- addFile(inputStream, lastModified, archivePath);
- } catch (ApkCreationException e) {
- throw e;
- } catch (Exception e) {
- throw new ApkCreationException(e, "Failed to add %s", file);
- }
- }
-
- private void addFile(InputStream content, long lastModified, String archivePath)
- throws IOException, ApkCreationException {
- // create the jar entry
- JarEntry entry = new JarEntry(archivePath);
- entry.setTime(lastModified);
-
- try {
- // add the entry to the jar archive
- mOutputStream.putNextEntry(entry);
-
- // read the content of the entry from the input stream, and write
- // it into the archive.
- int count;
- while ((count = content.read(buffer)) != -1) {
- mOutputStream.write(buffer, 0, count);
- }
- } finally {
- try {
- if (content != null) {
- content.close();
- }
- } catch (Exception e) {
- throw new ApkCreationException(e, "Failed to close stream");
- }
- }
- }
- }
-
- /**
- * Updates the crunch cache if needed and return true if the build must continue.
- */
- private boolean updateCrunchCache(IProject project, BuildHelper helper) {
- try {
- helper.updateCrunchCache();
- } catch (AaptExecException e) {
- BaseProjectHelper.markResource(project, AdtConstants.MARKER_PACKAGING,
- e.getMessage(), IMarker.SEVERITY_ERROR);
- return false;
- } catch (AaptResultException e) {
- // attempt to parse the error output
- String[] aaptOutput = e.getOutput();
- boolean parsingError = AaptParser.parseOutput(aaptOutput, project);
- // if we couldn't parse the output we display it in the console.
- if (parsingError) {
- AdtPlugin.printErrorToConsole(project, (Object[]) aaptOutput);
- }
- }
-
- return true;
- }
-
- /**
- * Writes the library jar file.
- * @param jarIFile the destination file
- * @param project the library project
- * @param appPackage the library android package
- * @param javaOutputFolder the JDT output folder.
- */
- private void writeLibraryPackage(IFile jarIFile, IProject project, String appPackage,
- IFolder javaOutputFolder) {
-
- JarOutputStream jos = null;
- try {
- Manifest manifest = new Manifest();
- Attributes mainAttributes = manifest.getMainAttributes();
- mainAttributes.put(Attributes.Name.CLASS_PATH, "Android ADT"); //$NON-NLS-1$
- mainAttributes.putValue("Created-By", "1.0 (Android)"); //$NON-NLS-1$ //$NON-NLS-2$
- jos = new JarOutputStream(
- new FileOutputStream(jarIFile.getLocation().toFile()), manifest);
-
- JarBuilder jarBuilder = new JarBuilder(jos, appPackage);
-
- // write the class files
- writeClassFilesIntoJar(jarBuilder, javaOutputFolder, javaOutputFolder);
-
- // now write the standard Java resources from the output folder
- ApkBuilder.addSourceFolder(jarBuilder, javaOutputFolder.getLocation().toFile());
-
- saveProjectBooleanProperty(PROPERTY_CONVERT_TO_DEX, mConvertToDex);
- } catch (Exception e) {
- AdtPlugin.log(e, "Failed to write jar file %s", jarIFile.getLocation().toOSString());
- } finally {
- if (jos != null) {
- try {
- jos.close();
- } catch (IOException e) {
- // pass
- }
- }
- }
- }
-
- private void writeClassFilesIntoJar(JarBuilder builder, IFolder folder, IFolder rootFolder)
- throws CoreException, IOException, ApkCreationException {
- IResource[] members = folder.members();
- for (IResource member : members) {
- if (member.getType() == IResource.FOLDER) {
- writeClassFilesIntoJar(builder, (IFolder) member, rootFolder);
- } else if (member.getType() == IResource.FILE) {
- IFile file = (IFile) member;
- builder.addFile(file, rootFolder);
- }
- }
- }
-
- @Override
- protected void startupOnInitialize() {
- super.startupOnInitialize();
-
- // load the build status. We pass true as the default value to
- // force a recompile in case the property was not found
- mConvertToDex = loadProjectBooleanProperty(PROPERTY_CONVERT_TO_DEX, true);
- mPackageResources = loadProjectBooleanProperty(PROPERTY_PACKAGE_RESOURCES, true);
- mBuildFinalPackage = loadProjectBooleanProperty(PROPERTY_BUILD_APK, true);
- }
-
- @Override
- protected void abortOnBadSetup(
- @NonNull IJavaProject javaProject,
- @Nullable ProjectState projectState) throws AbortBuildException, CoreException {
- super.abortOnBadSetup(javaProject, projectState);
-
- IProject iProject = getProject();
-
- // do a (hopefully quick) search for Precompiler type markers. Those are always only
- // errors.
- stopOnMarker(iProject, AdtConstants.MARKER_AAPT_COMPILE, IResource.DEPTH_INFINITE,
- false /*checkSeverity*/);
- stopOnMarker(iProject, AdtConstants.MARKER_AIDL, IResource.DEPTH_INFINITE,
- false /*checkSeverity*/);
- stopOnMarker(iProject, AdtConstants.MARKER_RENDERSCRIPT, IResource.DEPTH_INFINITE,
- false /*checkSeverity*/);
- stopOnMarker(iProject, AdtConstants.MARKER_ANDROID, IResource.DEPTH_ZERO,
- false /*checkSeverity*/);
-
- // do a search for JDT markers. Those can be errors or warnings
- stopOnMarker(iProject, IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER,
- IResource.DEPTH_INFINITE, true /*checkSeverity*/);
- stopOnMarker(iProject, IJavaModelMarker.BUILDPATH_PROBLEM_MARKER,
- IResource.DEPTH_INFINITE, true /*checkSeverity*/);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/PreCompilerBuilder.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/PreCompilerBuilder.java
deleted file mode 100644
index 0d9ee4897..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/PreCompilerBuilder.java
+++ /dev/null
@@ -1,1401 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build.builders;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.xml.ManifestData;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.build.AaptParser;
-import com.android.ide.eclipse.adt.internal.build.AidlProcessor;
-import com.android.ide.eclipse.adt.internal.build.Messages;
-import com.android.ide.eclipse.adt.internal.build.RenderScriptLauncher;
-import com.android.ide.eclipse.adt.internal.build.RsSourceChangeHandler;
-import com.android.ide.eclipse.adt.internal.build.SourceProcessor;
-import com.android.ide.eclipse.adt.internal.build.builders.BaseBuilder.AbortBuildException;
-import com.android.ide.eclipse.adt.internal.lint.EclipseLintClient;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs.BuildVerbosity;
-import com.android.ide.eclipse.adt.internal.project.AndroidManifestHelper;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.project.FixLaunchConfig;
-import com.android.ide.eclipse.adt.internal.project.ProjectHelper;
-import com.android.ide.eclipse.adt.internal.project.XmlErrorHandler.BasicXmlErrorListener;
-import com.android.ide.eclipse.adt.internal.resources.manager.IdeScanningContext;
-import com.android.ide.eclipse.adt.internal.resources.manager.ProjectResources;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.ide.eclipse.adt.internal.sdk.AdtManifestMergeCallback;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.io.IFileWrapper;
-import com.android.ide.eclipse.adt.io.IFolderWrapper;
-import com.android.io.StreamException;
-import com.android.manifmerger.ManifestMerger;
-import com.android.manifmerger.MergerLog;
-import com.android.sdklib.AndroidVersion;
-import com.android.sdklib.BuildToolInfo;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.build.RenderScriptChecker;
-import com.android.sdklib.build.RenderScriptProcessor;
-import com.android.sdklib.internal.build.BuildConfigGenerator;
-import com.android.sdklib.internal.build.SymbolLoader;
-import com.android.sdklib.internal.build.SymbolWriter;
-import com.android.sdklib.internal.project.ProjectProperties;
-import com.android.sdklib.io.FileOp;
-import com.android.sdklib.repository.FullRevision;
-import com.android.utils.ILogger;
-import com.android.utils.Pair;
-import com.android.xml.AndroidManifest;
-import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Multimap;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.JavaCore;
-import org.xml.sax.SAXException;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-
-import javax.xml.parsers.ParserConfigurationException;
-
-/**
- * Pre Java Compiler.
- * This incremental builder performs 2 tasks:
- * <ul>
- * <li>compiles the resources located in the res/ folder, along with the
- * AndroidManifest.xml file into the R.java class.</li>
- * <li>compiles any .aidl files into a corresponding java file.</li>
- * </ul>
- *
- */
-public class PreCompilerBuilder extends BaseBuilder {
-
- /** This ID is used in plugin.xml and in each project's .project file.
- * It cannot be changed even if the class is renamed/moved */
- public static final String ID = "com.android.ide.eclipse.adt.PreCompilerBuilder"; //$NON-NLS-1$
-
- /** Flag to pass to PreCompiler builder that the build is a release build.
- */
- public final static String RELEASE_REQUESTED = "android.releaseBuild"; //$NON-NLS-1$
-
- private static final String PROPERTY_PACKAGE = "manifestPackage"; //$NON-NLS-1$
- private static final String PROPERTY_MERGE_MANIFEST = "mergeManifest"; //$NON-NLS-1$
- private static final String PROPERTY_COMPILE_RESOURCES = "compileResources"; //$NON-NLS-1$
- private static final String PROPERTY_COMPILE_BUILDCONFIG = "createBuildConfig"; //$NON-NLS-1$
- private static final String PROPERTY_BUILDCONFIG_MODE = "buildConfigMode"; //$NON-NLS-1$
-
- private static final boolean MANIFEST_MERGER_ENABLED_DEFAULT = false;
- private static final String MANIFEST_MERGER_PROPERTY = "manifestmerger.enabled"; //$NON-NLS-1$
-
- /** Merge Manifest Flag. Computed from resource delta, reset after action is taken.
- * Stored persistently in the project. */
- private boolean mMustMergeManifest = false;
- /** Resource compilation Flag. Computed from resource delta, reset after action is taken.
- * Stored persistently in the project. */
- private boolean mMustCompileResources = false;
- /** BuildConfig Flag. Computed from resource delta, reset after action is taken.
- * Stored persistently in the project. */
- private boolean mMustCreateBuildConfig = false;
- /** BuildConfig last more Flag. Computed from resource delta, reset after action is taken.
- * Stored persistently in the project. */
- private boolean mLastBuildConfigMode;
-
- /** cache of the java package defined in the manifest */
- private String mManifestPackage;
-
- /** Output folder for generated Java File. Created on the Builder init
- * @see #startupOnInitialize()
- */
- private IFolder mGenFolder;
-
- /**
- * Progress monitor used at the end of every build to refresh the content of the 'gen' folder
- * and set the generated files as derived.
- */
- private DerivedProgressMonitor mDerivedProgressMonitor;
-
- private AidlProcessor mAidlProcessor;
- private RsSourceChangeHandler mRenderScriptSourceChangeHandler;
-
- /**
- * Progress monitor waiting the end of the process to set a persistent value
- * in a file. This is typically used in conjunction with <code>IResource.refresh()</code>,
- * since this call is asynchronous, and we need to wait for it to finish for the file
- * to be known by eclipse, before we can call <code>resource.setPersistentProperty</code> on
- * a new file.
- */
- private static class DerivedProgressMonitor implements IProgressMonitor {
- private boolean mCancelled = false;
- private boolean mDone = false;
- private final IFolder mGenFolder;
-
- public DerivedProgressMonitor(IFolder genFolder) {
- mGenFolder = genFolder;
- }
-
- void reset() {
- mDone = false;
- }
-
- @Override
- public void beginTask(String name, int totalWork) {
- }
-
- @Override
- public void done() {
- if (mDone == false) {
- mDone = true;
- processChildrenOf(mGenFolder);
- }
- }
-
- private void processChildrenOf(IFolder folder) {
- IResource[] list;
- try {
- list = folder.members();
- } catch (CoreException e) {
- return;
- }
-
- for (IResource member : list) {
- if (member.exists()) {
- if (member.getType() == IResource.FOLDER) {
- processChildrenOf((IFolder) member);
- }
-
- try {
- member.setDerived(true, new NullProgressMonitor());
- } catch (CoreException e) {
- // This really shouldn't happen since we check that the resource
- // exist.
- // Worst case scenario, the resource isn't marked as derived.
- }
- }
- }
- }
-
- @Override
- public void internalWorked(double work) {
- }
-
- @Override
- public boolean isCanceled() {
- return mCancelled;
- }
-
- @Override
- public void setCanceled(boolean value) {
- mCancelled = value;
- }
-
- @Override
- public void setTaskName(String name) {
- }
-
- @Override
- public void subTask(String name) {
- }
-
- @Override
- public void worked(int work) {
- }
- }
-
- public PreCompilerBuilder() {
- super();
- }
-
- // build() returns a list of project from which this project depends for future compilation.
- @Override
- protected IProject[] build(
- int kind,
- @SuppressWarnings("rawtypes") Map args,
- IProgressMonitor monitor)
- throws CoreException {
- // get a project object
- IProject project = getProject();
-
- if (DEBUG_LOG) {
- AdtPlugin.log(IStatus.INFO, "%s BUILD(PRE)", project.getName());
- }
-
- // For the PreCompiler, only the library projects are considered Referenced projects,
- // as only those projects have an impact on what is generated by this builder.
- IProject[] result = null;
-
- IFolder resOutFolder = null;
-
- try {
- assert mDerivedProgressMonitor != null;
-
- mDerivedProgressMonitor.reset();
-
- // get the project info
- ProjectState projectState = Sdk.getProjectState(project);
-
- // this can happen if the project has no project.properties.
- if (projectState == null) {
- return null;
- }
-
- boolean isLibrary = projectState.isLibrary();
-
- IAndroidTarget projectTarget = projectState.getTarget();
-
- // get the libraries
- List<IProject> libProjects = projectState.getFullLibraryProjects();
- result = libProjects.toArray(new IProject[libProjects.size()]);
-
- IJavaProject javaProject = JavaCore.create(project);
-
- // Top level check to make sure the build can move forward.
- abortOnBadSetup(javaProject, projectState);
-
- // now we need to get the classpath list
- List<IPath> sourceFolderPathList = BaseProjectHelper.getSourceClasspaths(javaProject);
-
- IFolder androidOutputFolder = BaseProjectHelper.getAndroidOutputFolder(project);
-
- resOutFolder = getResOutFolder(androidOutputFolder);
-
- setupSourceProcessors(javaProject, projectState, sourceFolderPathList,
- androidOutputFolder);
-
- PreCompilerDeltaVisitor dv = null;
- String javaPackage = null;
- String minSdkVersion = null;
-
- if (kind == FULL_BUILD) {
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project,
- Messages.Start_Full_Pre_Compiler);
-
- if (DEBUG_LOG) {
- AdtPlugin.log(IStatus.INFO, "%s full build!", project.getName());
- }
-
- // do some clean up.
- doClean(project, monitor);
-
- mMustMergeManifest = true;
- mMustCompileResources = true;
- mMustCreateBuildConfig = true;
-
- mAidlProcessor.prepareFullBuild(project);
- mRenderScriptSourceChangeHandler.prepareFullBuild();
- } else {
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project,
- Messages.Start_Inc_Pre_Compiler);
-
- // Go through the resources and see if something changed.
- // Even if the mCompileResources flag is true from a previously aborted
- // build, we need to go through the Resource delta to get a possible
- // list of aidl files to compile/remove.
- IResourceDelta delta = getDelta(project);
- if (delta == null) {
- mMustCompileResources = true;
-
- mAidlProcessor.prepareFullBuild(project);
- mRenderScriptSourceChangeHandler.prepareFullBuild();
- } else {
- dv = new PreCompilerDeltaVisitor(this, sourceFolderPathList,
- mAidlProcessor.getChangeHandler(),
- mRenderScriptSourceChangeHandler);
- delta.accept(dv);
-
- // Check to see if Manifest.xml, Manifest.java, or R.java have changed:
- mMustCompileResources |= dv.getCompileResources();
- mMustMergeManifest |= dv.hasManifestChanged();
-
- // Notify the ResourceManager:
- ResourceManager resManager = ResourceManager.getInstance();
-
- if (ResourceManager.isAutoBuilding()) {
- ProjectResources projectResources = resManager.getProjectResources(project);
-
- IdeScanningContext context = new IdeScanningContext(projectResources,
- project, true);
-
- boolean wasCleared = projectResources.ensureInitialized();
-
- if (!wasCleared) {
- resManager.processDelta(delta, context);
- }
-
- // Check whether this project or its dependencies (libraries) have
- // resources that need compilation
- if (wasCleared || context.needsFullAapt()) {
- mMustCompileResources = true;
-
- // Must also call markAaptRequested on the project to not just
- // store "aapt required" on this project, but also on any projects
- // depending on this project if it's a library project
- ResourceManager.markAaptRequested(project);
- }
-
- // Update error markers in the source editor
- if (!mMustCompileResources) {
- context.updateMarkers(false /* async */);
- }
- } // else: already processed the deltas in ResourceManager's IRawDeltaListener
-
- mAidlProcessor.doneVisiting(project);
-
- // get the java package from the visitor
- javaPackage = dv.getManifestPackage();
- minSdkVersion = dv.getMinSdkVersion();
- }
- }
-
- // Has anyone marked this project as needing aapt? Typically done when
- // one of the library projects this project depends on has changed
- mMustCompileResources |= ResourceManager.isAaptRequested(project);
-
- // if the main manifest didn't change, then we check for the library
- // ones (will trigger manifest merging too)
- if (libProjects.size() > 0) {
- for (IProject libProject : libProjects) {
- IResourceDelta delta = getDelta(libProject);
- if (delta != null) {
- PatternBasedDeltaVisitor visitor = new PatternBasedDeltaVisitor(
- project, libProject,
- "PRE:LibManifest"); //$NON-NLS-1$
- visitor.addSet(ChangedFileSetHelper.MANIFEST);
-
- ChangedFileSet textSymbolCFS = null;
- if (isLibrary == false) {
- textSymbolCFS = ChangedFileSetHelper.getTextSymbols(
- libProject);
- visitor.addSet(textSymbolCFS);
- }
-
- delta.accept(visitor);
-
- mMustMergeManifest |= visitor.checkSet(ChangedFileSetHelper.MANIFEST);
-
- if (textSymbolCFS != null) {
- mMustCompileResources |= visitor.checkSet(textSymbolCFS);
- }
-
- // no need to test others if we have all flags at true.
- if (mMustMergeManifest &&
- (mMustCompileResources || textSymbolCFS == null)) {
- break;
- }
- }
- }
- }
-
- // store the build status in the persistent storage
- saveProjectBooleanProperty(PROPERTY_MERGE_MANIFEST, mMustMergeManifest);
- saveProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES, mMustCompileResources);
- saveProjectBooleanProperty(PROPERTY_COMPILE_BUILDCONFIG, mMustCreateBuildConfig);
-
- // if there was some XML errors, we just return w/o doing
- // anything since we've put some markers in the files anyway.
- if (dv != null && dv.mXmlError) {
- AdtPlugin.printErrorToConsole(project, Messages.Xml_Error);
-
- return result;
- }
-
- if (projectState.getRenderScriptSupportMode()) {
- FullRevision minBuildToolsRev = new FullRevision(19,0,3);
- if (mBuildToolInfo.getRevision().compareTo(minBuildToolsRev) == -1) {
- String msg = "RenderScript support mode requires Build-Tools 19.0.3 or later.";
- AdtPlugin.printErrorToConsole(project, msg);
- markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR);
-
- return result;
- }
- }
-
- // get the manifest file
- IFile manifestFile = ProjectHelper.getManifest(project);
-
- if (manifestFile == null) {
- String msg = String.format(Messages.s_File_Missing,
- SdkConstants.FN_ANDROID_MANIFEST_XML);
- AdtPlugin.printErrorToConsole(project, msg);
- markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR);
-
- return result;
-
- // TODO: document whether code below that uses manifest (which is now guaranteed
- // to be null) will actually be executed or not.
- }
-
- // lets check the XML of the manifest first, if that hasn't been done by the
- // resource delta visitor yet.
- if (dv == null || dv.getCheckedManifestXml() == false) {
- BasicXmlErrorListener errorListener = new BasicXmlErrorListener();
- try {
- ManifestData parser = AndroidManifestHelper.parseUnchecked(
- new IFileWrapper(manifestFile),
- true /*gather data*/,
- errorListener);
-
- if (errorListener.mHasXmlError == true) {
- // There was an error in the manifest, its file has been marked
- // by the XmlErrorHandler. The stopBuild() call below will abort
- // this with an exception.
- String msg = String.format(Messages.s_Contains_Xml_Error,
- SdkConstants.FN_ANDROID_MANIFEST_XML);
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project, msg);
- markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR);
-
- return result;
- }
-
- // Get the java package from the parser.
- // This can be null if the parsing failed because the resource is out of sync,
- // in which case the error will already have been logged anyway.
- if (parser != null) {
- javaPackage = parser.getPackage();
- minSdkVersion = parser.getMinSdkVersionString();
- }
- } catch (StreamException e) {
- handleStreamException(e);
-
- return result;
- } catch (ParserConfigurationException e) {
- String msg = String.format(
- "Bad parser configuration for %s: %s",
- manifestFile.getFullPath(),
- e.getMessage());
-
- handleException(e, msg);
- return result;
-
- } catch (SAXException e) {
- String msg = String.format(
- "Parser exception for %s: %s",
- manifestFile.getFullPath(),
- e.getMessage());
-
- handleException(e, msg);
- return result;
- } catch (IOException e) {
- String msg = String.format(
- "I/O error for %s: %s",
- manifestFile.getFullPath(),
- e.getMessage());
-
- handleException(e, msg);
- return result;
- }
- }
-
- int minSdkValue = -1;
-
- if (minSdkVersion != null) {
- try {
- minSdkValue = Integer.parseInt(minSdkVersion);
- } catch (NumberFormatException e) {
- // it's ok, it means minSdkVersion contains a (hopefully) valid codename.
- }
-
- AndroidVersion targetVersion = projectTarget.getVersion();
-
- // remove earlier marker from the manifest
- removeMarkersFromResource(manifestFile, AdtConstants.MARKER_ADT);
-
- if (minSdkValue != -1) {
- String codename = targetVersion.getCodename();
- if (codename != null) {
- // integer minSdk when the target is a preview => fatal error
- String msg = String.format(
- "Platform %1$s is a preview and requires application manifest to set %2$s to '%1$s'",
- codename, AndroidManifest.ATTRIBUTE_MIN_SDK_VERSION);
- AdtPlugin.printErrorToConsole(project, msg);
- BaseProjectHelper.markResource(manifestFile, AdtConstants.MARKER_ADT,
- msg, IMarker.SEVERITY_ERROR);
- return result;
- } else if (minSdkValue > targetVersion.getApiLevel()) {
- // integer minSdk is too high for the target => warning
- String msg = String.format(
- "Attribute %1$s (%2$d) is higher than the project target API level (%3$d)",
- AndroidManifest.ATTRIBUTE_MIN_SDK_VERSION,
- minSdkValue, targetVersion.getApiLevel());
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project, msg);
- BaseProjectHelper.markResource(manifestFile, AdtConstants.MARKER_ADT,
- msg, IMarker.SEVERITY_WARNING);
- }
- } else {
- // looks like the min sdk is a codename, check it matches the codename
- // of the platform
- String codename = targetVersion.getCodename();
- if (codename == null) {
- // platform is not a preview => fatal error
- String msg = String.format(
- "Manifest attribute '%1$s' is set to '%2$s'. Integer is expected.",
- AndroidManifest.ATTRIBUTE_MIN_SDK_VERSION, minSdkVersion);
- AdtPlugin.printErrorToConsole(project, msg);
- BaseProjectHelper.markResource(manifestFile, AdtConstants.MARKER_ADT,
- msg, IMarker.SEVERITY_ERROR);
- return result;
- } else if (codename.equals(minSdkVersion) == false) {
- // platform and manifest codenames don't match => fatal error.
- String msg = String.format(
- "Value of manifest attribute '%1$s' does not match platform codename '%2$s'",
- AndroidManifest.ATTRIBUTE_MIN_SDK_VERSION, codename);
- AdtPlugin.printErrorToConsole(project, msg);
- BaseProjectHelper.markResource(manifestFile, AdtConstants.MARKER_ADT,
- msg, IMarker.SEVERITY_ERROR);
- return result;
- }
-
- // if we get there, the minSdkVersion is a codename matching the target
- // platform codename. In this case we set minSdkValue to the previous API
- // level, as it's used by source processors.
- minSdkValue = targetVersion.getApiLevel();
- }
- } else if (projectTarget.getVersion().isPreview()) {
- // else the minSdkVersion is not set but we are using a preview target.
- // Display an error
- String codename = projectTarget.getVersion().getCodename();
- String msg = String.format(
- "Platform %1$s is a preview and requires application manifests to set %2$s to '%1$s'",
- codename, AndroidManifest.ATTRIBUTE_MIN_SDK_VERSION);
- AdtPlugin.printErrorToConsole(project, msg);
- BaseProjectHelper.markResource(manifestFile, AdtConstants.MARKER_ADT, msg,
- IMarker.SEVERITY_ERROR);
- return result;
- }
-
- if (javaPackage == null || javaPackage.length() == 0) {
- // looks like the AndroidManifest file isn't valid.
- String msg = String.format(Messages.s_Doesnt_Declare_Package_Error,
- SdkConstants.FN_ANDROID_MANIFEST_XML);
- AdtPlugin.printErrorToConsole(project, msg);
- BaseProjectHelper.markResource(manifestFile, AdtConstants.MARKER_ADT,
- msg, IMarker.SEVERITY_ERROR);
-
- return result;
- } else if (javaPackage.indexOf('.') == -1) {
- // The application package name does not contain 2+ segments!
- String msg = String.format(
- "Application package '%1$s' must have a minimum of 2 segments.",
- SdkConstants.FN_ANDROID_MANIFEST_XML);
- AdtPlugin.printErrorToConsole(project, msg);
- BaseProjectHelper.markResource(manifestFile, AdtConstants.MARKER_ADT,
- msg, IMarker.SEVERITY_ERROR);
-
- return result;
- }
-
- // at this point we have the java package. We need to make sure it's not a different
- // package than the previous one that were built.
- if (javaPackage.equals(mManifestPackage) == false) {
- // The manifest package has changed, the user may want to update
- // the launch configuration
- if (mManifestPackage != null) {
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project,
- Messages.Checking_Package_Change);
-
- FixLaunchConfig flc = new FixLaunchConfig(project, mManifestPackage,
- javaPackage);
- flc.start();
- }
-
- // record the new manifest package, and save it.
- mManifestPackage = javaPackage;
- saveProjectStringProperty(PROPERTY_PACKAGE, mManifestPackage);
-
- // force a clean
- doClean(project, monitor);
- mMustMergeManifest = true;
- mMustCompileResources = true;
- mMustCreateBuildConfig = true;
- mAidlProcessor.prepareFullBuild(project);
- mRenderScriptSourceChangeHandler.prepareFullBuild();
-
- saveProjectBooleanProperty(PROPERTY_MERGE_MANIFEST, mMustMergeManifest);
- saveProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES, mMustCompileResources);
- saveProjectBooleanProperty(PROPERTY_COMPILE_BUILDCONFIG, mMustCreateBuildConfig);
- }
-
- try {
- handleBuildConfig(args);
- } catch (IOException e) {
- handleException(e, "Failed to create BuildConfig class");
- return result;
- }
-
- // merge the manifest
- if (mMustMergeManifest) {
- boolean enabled = MANIFEST_MERGER_ENABLED_DEFAULT;
- String propValue = projectState.getProperty(MANIFEST_MERGER_PROPERTY);
- if (propValue != null) {
- enabled = Boolean.valueOf(propValue);
- }
-
- if (mergeManifest(androidOutputFolder, libProjects, enabled) == false) {
- return result;
- }
- }
-
- List<File> libProjectsOut = new ArrayList<File>(libProjects.size());
- for (IProject libProject : libProjects) {
- libProjectsOut.add(
- BaseProjectHelper.getAndroidOutputFolder(libProject)
- .getLocation().toFile());
- }
-
- // run the source processors
- int processorStatus = SourceProcessor.COMPILE_STATUS_NONE;
-
-
- try {
- processorStatus |= mAidlProcessor.compileFiles(this,
- project, projectTarget, sourceFolderPathList,
- libProjectsOut, monitor);
- } catch (Throwable t) {
- handleException(t, "Failed to run aidl. Check workspace log for detail.");
- return result;
- }
-
- try {
- processorStatus |= compileRs(minSdkValue, projectState, androidOutputFolder,
- resOutFolder, monitor);
- } catch (Throwable t) {
- handleException(t, "Failed to run renderscript. Check workspace log for detail.");
- return result;
- }
-
- // if a processor created some resources file, force recompilation of the resources.
- if ((processorStatus & SourceProcessor.COMPILE_STATUS_RES) != 0) {
- mMustCompileResources = true;
- // save the current state before attempting the compilation
- saveProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES, mMustCompileResources);
- }
-
- // handle the resources, after the processors are run since some (renderscript)
- // generate resources.
- boolean compiledTheResources = mMustCompileResources;
- if (mMustCompileResources) {
- if (DEBUG_LOG) {
- AdtPlugin.log(IStatus.INFO, "%s compiling resources!", project.getName());
- }
-
- IFile proguardFile = null;
- if (projectState.getProperty(ProjectProperties.PROPERTY_PROGUARD_CONFIG) != null) {
- proguardFile = androidOutputFolder.getFile(AdtConstants.FN_AAPT_PROGUARD);
- }
-
- handleResources(project, javaPackage, projectTarget, manifestFile, resOutFolder,
- libProjects, isLibrary, proguardFile);
- }
-
- if (processorStatus == SourceProcessor.COMPILE_STATUS_NONE &&
- compiledTheResources == false) {
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project,
- Messages.Nothing_To_Compile);
- }
- } catch (AbortBuildException e) {
- return result;
- } finally {
- // refresh the 'gen' source folder. Once this is done with the custom progress
- // monitor to mark all new files as derived
- mGenFolder.refreshLocal(IResource.DEPTH_INFINITE, mDerivedProgressMonitor);
- if (resOutFolder != null) {
- resOutFolder.refreshLocal(IResource.DEPTH_INFINITE, mDerivedProgressMonitor);
- }
- }
-
- return result;
- }
-
- private IFolder getResOutFolder(IFolder androidOutputFolder) {
- return androidOutputFolder.getFolder(AdtConstants.WS_BIN_RELATIVE_BC);
- }
-
- @Override
- protected void clean(IProgressMonitor monitor) throws CoreException {
- super.clean(monitor);
-
- if (DEBUG_LOG) {
- AdtPlugin.log(IStatus.INFO, "%s CLEAN(PRE)", getProject().getName());
- }
-
- doClean(getProject(), monitor);
- if (mGenFolder != null) {
- mGenFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);
- }
- }
-
- private void doClean(IProject project, IProgressMonitor monitor) throws CoreException {
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project,
- Messages.Removing_Generated_Classes);
-
- // remove all the derived resources from the 'gen' source folder.
- if (mGenFolder != null && mGenFolder.exists()) {
- // gen folder should not be derived, but previous version could set it to derived
- // so we make sure this isn't the case (or it'll get deleted by the clean)
- mGenFolder.setDerived(false, monitor);
-
- removeDerivedResources(mGenFolder, monitor);
- }
-
- // Clear the project of the generic markers
- removeMarkersFromContainer(project, AdtConstants.MARKER_AAPT_COMPILE);
- removeMarkersFromContainer(project, AdtConstants.MARKER_XML);
- removeMarkersFromContainer(project, AdtConstants.MARKER_AIDL);
- removeMarkersFromContainer(project, AdtConstants.MARKER_RENDERSCRIPT);
- removeMarkersFromContainer(project, AdtConstants.MARKER_MANIFMERGER);
- removeMarkersFromContainer(project, AdtConstants.MARKER_ANDROID);
-
- // Also clean up lint
- EclipseLintClient.clearMarkers(project);
-
- // clean the project repo
- ProjectResources res = ResourceManager.getInstance().getProjectResources(project);
- res.clear();
- }
-
- @Override
- protected void startupOnInitialize() {
- try {
- super.startupOnInitialize();
-
- IProject project = getProject();
-
- // load the previous IFolder and java package.
- mManifestPackage = loadProjectStringProperty(PROPERTY_PACKAGE);
-
- // get the source folder in which all the Java files are created
- mGenFolder = project.getFolder(SdkConstants.FD_GEN_SOURCES);
- mDerivedProgressMonitor = new DerivedProgressMonitor(mGenFolder);
-
- // Load the current compile flags. We ask for true if not found to force a recompile.
- mMustMergeManifest = loadProjectBooleanProperty(PROPERTY_MERGE_MANIFEST, true);
- mMustCompileResources = loadProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES, true);
- mMustCreateBuildConfig = loadProjectBooleanProperty(PROPERTY_COMPILE_BUILDCONFIG, true);
- Boolean v = ProjectHelper.loadBooleanProperty(project, PROPERTY_BUILDCONFIG_MODE);
- if (v == null) {
- // no previous build config mode? force regenerate
- mMustCreateBuildConfig = true;
- } else {
- mLastBuildConfigMode = v;
- }
-
- } catch (Throwable throwable) {
- AdtPlugin.log(throwable, "Failed to finish PrecompilerBuilder#startupOnInitialize()");
- }
- }
-
- private void setupSourceProcessors(@NonNull IJavaProject javaProject,
- @NonNull ProjectState projectState,
- @NonNull List<IPath> sourceFolderPathList,
- @NonNull IFolder androidOutputFolder) {
- if (mAidlProcessor == null) {
- mAidlProcessor = new AidlProcessor(javaProject, mBuildToolInfo, mGenFolder);
- } else {
- mAidlProcessor.setBuildToolInfo(mBuildToolInfo);
- }
-
- List<File> sourceFolders = Lists.newArrayListWithCapacity(sourceFolderPathList.size());
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
-
- for (IPath path : sourceFolderPathList) {
- IResource resource = root.findMember(path);
- if (resource != null && resource.exists() && resource.getType() == IResource.FOLDER) {
- IPath fullPath = resource.getLocation();
- if (fullPath != null) {
- sourceFolders.add(fullPath.toFile());
- }
- }
- }
-
- RenderScriptChecker checker = new RenderScriptChecker(sourceFolders,
- androidOutputFolder.getLocation().toFile());
- mRenderScriptSourceChangeHandler = new RsSourceChangeHandler(checker);
- }
-
- private int compileRs(int minSdkValue,
- @NonNull ProjectState projectState,
- @NonNull IFolder androidOutputFolder,
- @NonNull IFolder resOutFolder,
- @NonNull IProgressMonitor monitor)
- throws IOException, InterruptedException {
- if (!mRenderScriptSourceChangeHandler.mustCompile()) {
- return SourceProcessor.COMPILE_STATUS_NONE;
- }
-
- RenderScriptChecker checker = mRenderScriptSourceChangeHandler.getChecker();
-
- List<File> inputs = checker.findInputFiles();
- List<File> importFolders = checker.getSourceFolders();
- File buildFolder = androidOutputFolder.getLocation().toFile();
-
-
- // get the renderscript target
- int rsTarget = minSdkValue == -1 ? 11 : minSdkValue;
- String rsTargetStr = projectState.getProperty(ProjectProperties.PROPERTY_RS_TARGET);
- if (rsTargetStr != null) {
- try {
- rsTarget = Integer.parseInt(rsTargetStr);
- } catch (NumberFormatException e) {
- handleException(e, String.format(
- "Property %s is not an integer.",
- ProjectProperties.PROPERTY_RS_TARGET));
- return SourceProcessor.COMPILE_STATUS_NONE;
- }
- }
-
- RenderScriptProcessor processor = new RenderScriptProcessor(
- inputs,
- importFolders,
- buildFolder,
- mGenFolder.getLocation().toFile(),
- resOutFolder.getLocation().toFile(),
- new File(buildFolder, SdkConstants.FD_RS_OBJ),
- new File(buildFolder, SdkConstants.FD_RS_LIBS),
- mBuildToolInfo,
- rsTarget,
- false /*debugBuild, always false for now*/,
- 3,
- projectState.getRenderScriptSupportMode());
-
- // clean old dependency files fiest
- checker.cleanDependencies();
-
- // then clean old output files
- processor.cleanOldOutput(checker.getOldOutputs());
-
- RenderScriptLauncher launcher = new RenderScriptLauncher(
- getProject(),
- mGenFolder,
- resOutFolder,
- monitor,
- AdtPrefs.getPrefs().getBuildVerbosity() == BuildVerbosity.VERBOSE /*verbose*/);
-
- // and run the build
- processor.build(launcher);
-
- return SourceProcessor.COMPILE_STATUS_CODE | SourceProcessor.COMPILE_STATUS_RES;
- }
-
- @SuppressWarnings("deprecation")
- private void handleBuildConfig(@SuppressWarnings("rawtypes") Map args)
- throws IOException, CoreException {
- boolean debugMode = !args.containsKey(RELEASE_REQUESTED);
-
- BuildConfigGenerator generator = new BuildConfigGenerator(
- mGenFolder.getLocation().toOSString(), mManifestPackage, debugMode);
-
- if (mMustCreateBuildConfig == false) {
- // check the file is present.
- IFolder folder = getGenManifestPackageFolder();
- if (folder.exists(new Path(BuildConfigGenerator.BUILD_CONFIG_NAME)) == false) {
- mMustCreateBuildConfig = true;
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, getProject(),
- String.format("Class %1$s is missing!",
- BuildConfigGenerator.BUILD_CONFIG_NAME));
- } else if (debugMode != mLastBuildConfigMode) {
- // else if the build mode changed, force creation
- mMustCreateBuildConfig = true;
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, getProject(),
- String.format("Different build mode, must update %1$s!",
- BuildConfigGenerator.BUILD_CONFIG_NAME));
- }
- }
-
- if (mMustCreateBuildConfig) {
- if (DEBUG_LOG) {
- AdtPlugin.log(IStatus.INFO, "%s generating BuilderConfig!", getProject().getName());
- }
-
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, getProject(),
- String.format("Generating %1$s...", BuildConfigGenerator.BUILD_CONFIG_NAME));
- generator.generate();
-
- mMustCreateBuildConfig = false;
- saveProjectBooleanProperty(PROPERTY_COMPILE_BUILDCONFIG, mMustCreateBuildConfig);
- saveProjectBooleanProperty(PROPERTY_BUILDCONFIG_MODE, mLastBuildConfigMode = debugMode);
- }
- }
-
- private boolean mergeManifest(IFolder androidOutFolder, List<IProject> libProjects,
- boolean enabled) throws CoreException {
- if (DEBUG_LOG) {
- AdtPlugin.log(IStatus.INFO, "%s merging manifests!", getProject().getName());
- }
-
- IFile outFile = androidOutFolder.getFile(SdkConstants.FN_ANDROID_MANIFEST_XML);
- IFile manifest = getProject().getFile(SdkConstants.FN_ANDROID_MANIFEST_XML);
-
- // remove existing markers from the manifest.
- // FIXME: only remove from manifest once the markers are put there.
- removeMarkersFromResource(getProject(), AdtConstants.MARKER_MANIFMERGER);
-
- // If the merging is not enabled or if there's no library then we simply copy the
- // manifest over.
- if (enabled == false || libProjects.size() == 0) {
- try {
- new FileOp().copyFile(manifest.getLocation().toFile(),
- outFile.getLocation().toFile());
-
- outFile.refreshLocal(IResource.DEPTH_INFINITE, mDerivedProgressMonitor);
-
- saveProjectBooleanProperty(PROPERTY_MERGE_MANIFEST, mMustMergeManifest = false);
- } catch (IOException e) {
- handleException(e, "Failed to copy Manifest");
- return false;
- }
- } else {
- final ArrayList<String> errors = new ArrayList<String>();
-
- // TODO change MergerLog.wrapSdkLog by a custom IMergerLog that will create
- // and maintain error markers.
- ManifestMerger merger = new ManifestMerger(
- MergerLog.wrapSdkLog(new ILogger() {
- @Override
- public void warning(@NonNull String warningFormat, Object... args) {
- AdtPlugin.printToConsole(getProject(), String.format(warningFormat, args));
- }
-
- @Override
- public void info(@NonNull String msgFormat, Object... args) {
- AdtPlugin.printToConsole(getProject(), String.format(msgFormat, args));
- }
-
- @Override
- public void verbose(@NonNull String msgFormat, Object... args) {
- info(msgFormat, args);
- }
-
- @Override
- public void error(@Nullable Throwable t, @Nullable String errorFormat,
- Object... args) {
- errors.add(String.format(errorFormat, args));
- }
- }),
- new AdtManifestMergeCallback());
-
- File[] libManifests = new File[libProjects.size()];
- int libIndex = 0;
- for (IProject lib : libProjects) {
- libManifests[libIndex++] = lib.getFile(SdkConstants.FN_ANDROID_MANIFEST_XML)
- .getLocation().toFile();
- }
-
- if (merger.process(
- outFile.getLocation().toFile(),
- manifest.getLocation().toFile(),
- libManifests,
- null /*injectAttributes*/, null /*packageOverride*/) == false) {
- if (errors.size() > 1) {
- StringBuilder sb = new StringBuilder();
- for (String s : errors) {
- sb.append(s).append('\n');
- }
-
- markProject(AdtConstants.MARKER_MANIFMERGER, sb.toString(),
- IMarker.SEVERITY_ERROR);
-
- } else if (errors.size() == 1) {
- markProject(AdtConstants.MARKER_MANIFMERGER, errors.get(0),
- IMarker.SEVERITY_ERROR);
- } else {
- markProject(AdtConstants.MARKER_MANIFMERGER, "Unknown error merging manifest",
- IMarker.SEVERITY_ERROR);
- }
- return false;
- }
-
- outFile.refreshLocal(IResource.DEPTH_INFINITE, mDerivedProgressMonitor);
- saveProjectBooleanProperty(PROPERTY_MERGE_MANIFEST, mMustMergeManifest = false);
- }
-
- return true;
- }
-
- /**
- * Handles resource changes and regenerate whatever files need regenerating.
- * @param project the main project
- * @param javaPackage the app package for the main project
- * @param projectTarget the target of the main project
- * @param manifest the {@link IFile} representing the project manifest
- * @param libProjects the library dependencies
- * @param isLibrary if the project is a library project
- * @throws CoreException
- * @throws AbortBuildException
- */
- private void handleResources(IProject project, String javaPackage, IAndroidTarget projectTarget,
- IFile manifest, IFolder resOutFolder, List<IProject> libProjects, boolean isLibrary,
- IFile proguardFile) throws CoreException, AbortBuildException {
- // get the resource folder
- IFolder resFolder = project.getFolder(AdtConstants.WS_RESOURCES);
-
- // get the file system path
- IPath outputLocation = mGenFolder.getLocation();
- IPath resLocation = resFolder.getLocation();
- IPath manifestLocation = manifest == null ? null : manifest.getLocation();
-
- // those locations have to exist for us to do something!
- if (outputLocation != null && resLocation != null
- && manifestLocation != null) {
- String osOutputPath = outputLocation.toOSString();
- String osResPath = resLocation.toOSString();
- String osManifestPath = manifestLocation.toOSString();
-
- // remove the aapt markers
- removeMarkersFromResource(manifest, AdtConstants.MARKER_AAPT_COMPILE);
- removeMarkersFromContainer(resFolder, AdtConstants.MARKER_AAPT_COMPILE);
-
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project,
- Messages.Preparing_Generated_Files);
-
- // we need to figure out where to store the R class.
- // get the parent folder for R.java and update mManifestPackageSourceFolder
- IFolder mainPackageFolder = getGenManifestPackageFolder();
-
- // handle libraries
- ArrayList<IFolder> libResFolders = Lists.newArrayList();
- ArrayList<Pair<File, String>> libRFiles = Lists.newArrayList();
- if (libProjects != null) {
- for (IProject lib : libProjects) {
- IFolder libResFolder = lib.getFolder(SdkConstants.FD_RES);
- if (libResFolder.exists()) {
- libResFolders.add(libResFolder);
- }
-
- try {
- // get the package of the library, and if it's different form the
- // main project, generate the R class for it too.
- String libJavaPackage = AndroidManifest.getPackage(new IFolderWrapper(lib));
- if (libJavaPackage.equals(javaPackage) == false) {
-
- IFolder libOutput = BaseProjectHelper.getAndroidOutputFolder(lib);
- File libOutputFolder = libOutput.getLocation().toFile();
-
- libRFiles.add(Pair.of(
- new File(libOutputFolder, "R.txt"),
- libJavaPackage));
-
- }
- } catch (Exception e) {
- }
- }
- }
-
- String proguardFilePath = proguardFile != null ?
- proguardFile.getLocation().toOSString(): null;
-
- File resOutFile = resOutFolder.getLocation().toFile();
- String resOutPath = resOutFile.isDirectory() ? resOutFile.getAbsolutePath() : null;
-
- execAapt(project, projectTarget, osOutputPath, resOutPath, osResPath, osManifestPath,
- mainPackageFolder, libResFolders, libRFiles, isLibrary, proguardFilePath);
- }
- }
-
- /**
- * Executes AAPT to generate R.java/Manifest.java
- * @param project the main project
- * @param projectTarget the main project target
- * @param osOutputPath the OS output path for the generated file. This is the source folder, not
- * the package folder.
- * @param osResPath the OS path to the res folder for the main project
- * @param osManifestPath the OS path to the manifest of the main project
- * @param packageFolder the IFolder that will contain the generated file. Unlike
- * <var>osOutputPath</var> this is the direct parent of the generated files.
- * If <var>customJavaPackage</var> is not null, this must match the new destination triggered
- * by its value.
- * @param libResFolders the list of res folders for the library.
- * @param libRFiles a list of R files for the libraries.
- * @param isLibrary if the project is a library project
- * @param proguardFile an optional path to store proguard information
- * @throws AbortBuildException
- */
- @SuppressWarnings("deprecation")
- private void execAapt(IProject project, IAndroidTarget projectTarget, String osOutputPath,
- String osBcOutPath, String osResPath, String osManifestPath, IFolder packageFolder,
- ArrayList<IFolder> libResFolders, List<Pair<File, String>> libRFiles,
- boolean isLibrary, String proguardFile)
- throws AbortBuildException {
-
- // We actually need to delete the manifest.java as it may become empty and
- // in this case aapt doesn't generate an empty one, but instead doesn't
- // touch it.
- IFile manifestJavaFile = packageFolder.getFile(SdkConstants.FN_MANIFEST_CLASS);
- manifestJavaFile.getLocation().toFile().delete();
-
- // launch aapt: create the command line
- ArrayList<String> array = new ArrayList<String>();
-
- String aaptPath = mBuildToolInfo.getPath(BuildToolInfo.PathId.AAPT);
-
- array.add(aaptPath);
- array.add("package"); //$NON-NLS-1$
- array.add("-m"); //$NON-NLS-1$
- if (AdtPrefs.getPrefs().getBuildVerbosity() == BuildVerbosity.VERBOSE) {
- array.add("-v"); //$NON-NLS-1$
- }
-
- if (isLibrary) {
- array.add("--non-constant-id"); //$NON-NLS-1$
- }
-
- if (libResFolders.size() > 0) {
- array.add("--auto-add-overlay"); //$NON-NLS-1$
- }
-
- // If a library or has libraries, generate a text version of the R symbols.
- File outputFolder = BaseProjectHelper.getAndroidOutputFolder(project).getLocation()
- .toFile();
-
- if (isLibrary || !libRFiles.isEmpty()) {
- array.add("--output-text-symbols"); //$NON-NLS-1$
- array.add(outputFolder.getAbsolutePath());
- }
-
- array.add("-J"); //$NON-NLS-1$
- array.add(osOutputPath);
- array.add("-M"); //$NON-NLS-1$
- array.add(osManifestPath);
- if (osBcOutPath != null) {
- array.add("-S"); //$NON-NLS-1$
- array.add(osBcOutPath);
- }
- array.add("-S"); //$NON-NLS-1$
- array.add(osResPath);
- for (IFolder libResFolder : libResFolders) {
- array.add("-S"); //$NON-NLS-1$
- array.add(libResFolder.getLocation().toOSString());
- }
-
- array.add("-I"); //$NON-NLS-1$
- array.add(projectTarget.getPath(IAndroidTarget.ANDROID_JAR));
-
- // use the proguard file
- if (proguardFile != null && proguardFile.length() > 0) {
- array.add("-G");
- array.add(proguardFile);
- }
-
- if (AdtPrefs.getPrefs().getBuildVerbosity() == BuildVerbosity.VERBOSE) {
- StringBuilder sb = new StringBuilder();
- for (String c : array) {
- sb.append(c);
- sb.append(' ');
- }
- String cmd_line = sb.toString();
- AdtPlugin.printToConsole(project, cmd_line);
- }
-
- // launch
- try {
- // launch the command line process
- Process process = Runtime.getRuntime().exec(
- array.toArray(new String[array.size()]));
-
- // list to store each line of stderr
- ArrayList<String> stdErr = new ArrayList<String>();
-
- // get the output and return code from the process
- int returnCode = grabProcessOutput(process, stdErr);
-
- // attempt to parse the error output
- boolean parsingError = AaptParser.parseOutput(stdErr, project);
-
- // if we couldn't parse the output we display it in the console.
- if (parsingError) {
- if (returnCode != 0) {
- AdtPlugin.printErrorToConsole(project, stdErr.toArray());
- } else {
- AdtPlugin.printBuildToConsole(BuildVerbosity.NORMAL,
- project, stdErr.toArray());
- }
- }
-
- if (returnCode != 0) {
- // if the exec failed, and we couldn't parse the error output
- // (and therefore not all files that should have been marked,
- // were marked), we put a generic marker on the project and abort.
- if (parsingError) {
- markProject(AdtConstants.MARKER_ADT,
- Messages.Unparsed_AAPT_Errors, IMarker.SEVERITY_ERROR);
- } else if (stdErr.size() == 0) {
- // no parsing error because sdterr was empty. We still need to put
- // a marker otherwise there's no user visible feedback.
- markProject(AdtConstants.MARKER_ADT,
- String.format(Messages.AAPT_Exec_Error_d, returnCode),
- IMarker.SEVERITY_ERROR);
- }
-
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project,
- Messages.AAPT_Error);
-
- // abort if exec failed.
- throw new AbortBuildException();
- }
-
- // now if the project has libraries, R needs to be created for each libraries
- // unless this is a library.
- if (isLibrary == false && !libRFiles.isEmpty()) {
- File rFile = new File(outputFolder, SdkConstants.FN_RESOURCE_TEXT);
- // if the project has no resources, the file could not exist.
- if (rFile.isFile()) {
- // Load the full symbols from the full R.txt file.
- SymbolLoader fullSymbolValues = new SymbolLoader(rFile);
- fullSymbolValues.load();
-
- Multimap<String, SymbolLoader> libMap = ArrayListMultimap.create();
-
- // First pass processing the libraries, collecting them by packageName,
- // and ignoring the ones that have the same package name as the application
- // (since that R class was already created).
-
- for (Pair<File, String> lib : libRFiles) {
- String libPackage = lib.getSecond();
- File rText = lib.getFirst();
-
- if (rText.isFile()) {
- // load the lib symbols
- SymbolLoader libSymbols = new SymbolLoader(rText);
- libSymbols.load();
-
- // store these symbols by associating them with the package name.
- libMap.put(libPackage, libSymbols);
- }
- }
-
- // now loop on all the package names, merge all the symbols to write,
- // and write them
- for (String packageName : libMap.keySet()) {
- Collection<SymbolLoader> symbols = libMap.get(packageName);
-
- SymbolWriter writer = new SymbolWriter(osOutputPath, packageName,
- fullSymbolValues);
- for (SymbolLoader symbolLoader : symbols) {
- writer.addSymbolsToWrite(symbolLoader);
- }
- writer.write();
- }
- }
- }
-
- } catch (IOException e1) {
- // something happen while executing the process,
- // mark the project and exit
- String msg;
- String path = array.get(0);
- if (!new File(path).exists()) {
- msg = String.format(Messages.AAPT_Exec_Error_s, path);
- } else {
- String description = e1.getLocalizedMessage();
- if (e1.getCause() != null && e1.getCause() != e1) {
- description = description + ": " + e1.getCause().getLocalizedMessage();
- }
- msg = String.format(Messages.AAPT_Exec_Error_Other_s, description);
- }
-
- markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR);
-
- // Add workaround for the Linux problem described here:
- // http://developer.android.com/sdk/installing.html#troubleshooting
- // There are various posts on StackOverflow elsewhere where people are asking
- // about aapt failing to run, so even though this is documented in the
- // Troubleshooting section add an error message to help with this
- // scenario.
- if (SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_LINUX
- && System.getProperty("os.arch").endsWith("64") //$NON-NLS-1$ //$NON-NLS-2$
- && new File(aaptPath).exists()
- && new File("/usr/bin/apt-get").exists()) { //$NON-NLS-1$
- markProject(AdtConstants.MARKER_ADT,
- "Hint: On 64-bit systems, make sure the 32-bit libraries are installed: \"sudo apt-get install ia32-libs\" or on some systems, \"sudo apt-get install lib32z1\"",
- IMarker.SEVERITY_ERROR);
- // Note - this uses SEVERITY_ERROR even though it's really SEVERITY_INFO because
- // we want this error message to show up adjacent to the aapt error message
- // (and Eclipse sorts by priority)
- }
-
- // This interrupts the build.
- throw new AbortBuildException();
- } catch (InterruptedException e) {
- // we got interrupted waiting for the process to end...
- // mark the project and exit
- String msg = String.format(Messages.AAPT_Exec_Error_s, array.get(0));
- markProject(AdtConstants.MARKER_ADT, msg, IMarker.SEVERITY_ERROR);
-
- // This interrupts the build.
- throw new AbortBuildException();
- } finally {
- // we've at least attempted to run aapt, save the fact that we don't have to
- // run it again, unless there's a new resource change.
- saveProjectBooleanProperty(PROPERTY_COMPILE_RESOURCES,
- mMustCompileResources = false);
- ResourceManager.clearAaptRequest(project);
- }
- }
-
- /**
- * Creates a relative {@link IPath} from a java package.
- * @param javaPackageName the java package.
- */
- private IPath getJavaPackagePath(String javaPackageName) {
- // convert the java package into path
- String[] segments = javaPackageName.split(AdtConstants.RE_DOT);
-
- StringBuilder path = new StringBuilder();
- for (String s : segments) {
- path.append(AdtConstants.WS_SEP_CHAR);
- path.append(s);
- }
-
- return new Path(path.toString());
- }
-
- /**
- * Returns an {@link IFolder} (located inside the 'gen' source folder), that matches the
- * package defined in the manifest. This {@link IFolder} may not actually exist
- * (aapt will create it anyway).
- * @return the {@link IFolder} that will contain the R class or null if
- * the folder was not found.
- * @throws CoreException
- */
- private IFolder getGenManifestPackageFolder() throws CoreException {
- // get the path for the package
- IPath packagePath = getJavaPackagePath(mManifestPackage);
-
- // get a folder for this path under the 'gen' source folder, and return it.
- // This IFolder may not reference an actual existing folder.
- return mGenFolder.getFolder(packagePath);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/PreCompilerDeltaVisitor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/PreCompilerDeltaVisitor.java
deleted file mode 100644
index 57316f568..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/PreCompilerDeltaVisitor.java
+++ /dev/null
@@ -1,417 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build.builders;
-
-import com.android.SdkConstants;
-import com.android.ide.common.xml.ManifestData;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.build.Messages;
-import com.android.ide.eclipse.adt.internal.build.SourceChangeHandler;
-import com.android.ide.eclipse.adt.internal.build.builders.BaseBuilder.BaseDeltaVisitor;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs.BuildVerbosity;
-import com.android.ide.eclipse.adt.internal.project.AndroidManifestHelper;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.io.IFileWrapper;
-import com.google.common.collect.Lists;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IResourceDeltaVisitor;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-
-import java.util.Arrays;
-import java.util.List;
-
-/**
- * Resource Delta visitor for the pre-compiler.
- * <p/>This delta visitor only cares about files that are the source or the result of actions of the
- * {@link PreCompilerBuilder}:
- * <ul><li>R.java/Manifest.java generated by compiling the resources</li>
- * <li>Any Java files generated by <code>aidl</code></li></ul>.
- *
- * Therefore it looks for the following:
- * <ul><li>Any modification in the resource folder</li>
- * <li>Removed files from the source folder receiving generated Java files</li>
- * <li>Any modification to aidl files.</li>
- *
- */
-class PreCompilerDeltaVisitor extends BaseDeltaVisitor implements IResourceDeltaVisitor {
-
- // Result fields.
- private boolean mChangedManifest = false;
-
- /**
- * Compile flag. This is set to true if one of the changed/added/removed
- * files is Manifest.java, or R.java. All other file changes
- * will be taken care of by ResourceManager.
- */
- private boolean mCompileResources = false;
-
- /** Manifest check/parsing flag. */
- private boolean mCheckedManifestXml = false;
-
- /** Application Package, gathered from the parsing of the manifest */
- private String mJavaPackage = null;
- /** minSDKVersion attribute value, gathered from the parsing of the manifest */
- private String mMinSdkVersion = null;
-
- // Internal usage fields.
- /**
- * In Resource folder flag. This allows us to know if we're in the
- * resource folder.
- */
- private boolean mInRes = false;
-
- /**
- * Current Source folder. This allows us to know if we're in a source
- * folder, and which folder.
- */
- private IFolder mSourceFolder = null;
-
- /** List of source folders. */
- private final List<IPath> mSourceFolders;
- private boolean mIsGenSourceFolder = false;
-
- private final List<SourceChangeHandler> mSourceChangeHandlers = Lists.newArrayList();
- private final IWorkspaceRoot mRoot;
-
- private IFolder mAndroidOutputFolder;
-
- public PreCompilerDeltaVisitor(BaseBuilder builder, List<IPath> sourceFolders,
- SourceChangeHandler... handlers) {
- super(builder);
- mSourceFolders = sourceFolders;
- mRoot = ResourcesPlugin.getWorkspace().getRoot();
-
- mSourceChangeHandlers.addAll(Arrays.asList(handlers));
-
- mAndroidOutputFolder = BaseProjectHelper.getAndroidOutputFolder(builder.getProject());
- }
-
- /**
- * Get whether Manifest.java, Manifest.xml, or R.java have changed
- * @return true if any of Manifest.xml, Manifest.java, or R.java have been modified
- */
- public boolean getCompileResources() {
- return mCompileResources || mChangedManifest;
- }
-
- public boolean hasManifestChanged() {
- return mChangedManifest;
- }
-
- /**
- * Returns whether the manifest file was parsed/checked for error during the resource delta
- * visiting.
- */
- public boolean getCheckedManifestXml() {
- return mCheckedManifestXml;
- }
-
- /**
- * Returns the manifest package if the manifest was checked/parsed.
- * <p/>
- * This can return null in two cases:
- * <ul>
- * <li>The manifest was not part of the resource change delta, and the manifest was
- * not checked/parsed ({@link #getCheckedManifestXml()} returns <code>false</code>)</li>
- * <li>The manifest was parsed ({@link #getCheckedManifestXml()} returns <code>true</code>),
- * but the package declaration is missing</li>
- * </ul>
- * @return the manifest package or null.
- */
- public String getManifestPackage() {
- return mJavaPackage;
- }
-
- /**
- * Returns the minSDkVersion attribute from the manifest if it was checked/parsed.
- * <p/>
- * This can return null in two cases:
- * <ul>
- * <li>The manifest was not part of the resource change delta, and the manifest was
- * not checked/parsed ({@link #getCheckedManifestXml()} returns <code>false</code>)</li>
- * <li>The manifest was parsed ({@link #getCheckedManifestXml()} returns <code>true</code>),
- * but the package declaration is missing</li>
- * </ul>
- * @return the minSdkVersion or null.
- */
- public String getMinSdkVersion() {
- return mMinSdkVersion;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.core.resources.IResourceDeltaVisitor
- * #visit(org.eclipse.core.resources.IResourceDelta)
- */
- @Override
- public boolean visit(IResourceDelta delta) throws CoreException {
- // we are only going to look for changes in res/, source folders and in
- // AndroidManifest.xml since the delta visitor goes through the main
- // folder before its children we can check when the path segment
- // count is 2 (format will be /$Project/folder) and make sure we are
- // processing res/, source folders or AndroidManifest.xml
-
- IResource resource = delta.getResource();
- IPath path = resource.getFullPath();
- String[] segments = path.segments();
-
- // since the delta visitor also visits the root we return true if
- // segments.length = 1
- if (segments.length == 1) {
- // this is always the Android project since we call
- // Builder#getDelta(IProject) on the project itself.
- return true;
- } else if (segments.length == 2) {
- // if we are at an item directly under the root directory,
- // then we are not yet in a source or resource folder
- mInRes = false;
- mSourceFolder = null;
-
- if (SdkConstants.FD_RESOURCES.equalsIgnoreCase(segments[1])) {
- // this is the resource folder that was modified. we want to
- // see its content.
-
- // since we're going to visit its children next, we set the
- // flag
- mInRes = true;
- mSourceFolder = null;
- return true;
- } else if (SdkConstants.FN_ANDROID_MANIFEST_XML.equalsIgnoreCase(segments[1])) {
- // any change in the manifest could trigger a new R.java
- // class, so we don't need to check the delta kind
- if (delta.getKind() != IResourceDelta.REMOVED) {
- // clean the error markers on the file.
- IFile manifestFile = (IFile)resource;
-
- if (manifestFile.exists()) {
- manifestFile.deleteMarkers(AdtConstants.MARKER_XML, true,
- IResource.DEPTH_ZERO);
- manifestFile.deleteMarkers(AdtConstants.MARKER_ANDROID, true,
- IResource.DEPTH_ZERO);
- }
-
- // parse the manifest for data and error
- ManifestData manifestData = AndroidManifestHelper.parse(
- new IFileWrapper(manifestFile), true /*gatherData*/, this);
-
- if (manifestData != null) {
- mJavaPackage = manifestData.getPackage();
- mMinSdkVersion = manifestData.getMinSdkVersionString();
- }
-
- mCheckedManifestXml = true;
- }
- mChangedManifest = true;
-
- // we don't want to go to the children, not like they are
- // any for this resource anyway.
- return false;
- }
- }
-
- // at this point we can either be in the source folder or in the
- // resource folder or in a different folder that contains a source
- // folder.
- // This is due to not all source folder being src/. Some could be
- // something/somethingelse/src/
-
- // so first we test if we already know we are in a source or
- // resource folder.
-
- if (mSourceFolder != null) {
- // if we are in the res folder, we are looking for the following changes:
- // - added/removed/modified aidl files.
- // - missing R.java file
-
- // if the resource is a folder, we just go straight to the children
- if (resource.getType() == IResource.FOLDER) {
- return true;
- }
-
- if (resource.getType() != IResource.FILE) {
- return false;
- }
- IFile file = (IFile)resource;
-
- // get the modification kind
- int kind = delta.getKind();
-
- // we process normal source folder and the 'gen' source folder differently.
- if (mIsGenSourceFolder) {
- // this is the generated java file source folder.
- // - if R.java/Manifest.java are removed/modified, we recompile the resources
- // - if aidl files are removed/modified, we recompile them.
-
- boolean outputWarning = false;
-
- String fileName = resource.getName();
-
- // Special case of R.java/Manifest.java.
- if (SdkConstants.FN_RESOURCE_CLASS.equals(fileName) ||
- SdkConstants.FN_MANIFEST_CLASS.equals(fileName)) {
- // if it was removed, there's a possibility that it was removed due to a
- // package change, or an aidl that was removed, but the only thing
- // that will happen is that we'll have an extra build. Not much of a problem.
- mCompileResources = true;
-
- // we want a warning
- outputWarning = true;
- } else {
- // look to see if this file was generated by a processor.
- for (SourceChangeHandler handler : mSourceChangeHandlers) {
- if (handler.handleGeneratedFile(file, kind)) {
- outputWarning = true;
- break; // there shouldn't be 2 processors that handle the same file.
- }
- }
- }
-
- if (outputWarning) {
- if (kind == IResourceDelta.REMOVED) {
- // We print an error just so that it's red, but it's just a warning really.
- String msg = String.format(Messages.s_Removed_Recreating_s, fileName);
- AdtPlugin.printErrorToConsole(mBuilder.getProject(), msg);
- } else if (kind == IResourceDelta.CHANGED) {
- // the file was modified manually! we can't allow it.
- String msg = String.format(Messages.s_Modified_Manually_Recreating_s,
- fileName);
- AdtPlugin.printErrorToConsole(mBuilder.getProject(), msg);
- }
- }
- } else {
- // this is another source folder.
- for (SourceChangeHandler handler : mSourceChangeHandlers) {
- handler.handleSourceFile(file, kind);
- }
- }
-
- // no children.
- return false;
- } else if (mInRes) {
- // if we are in the res folder, we are looking for the following
- // changes:
- // - added/removed/modified xml files.
- // - added/removed files of any other type
-
- // if the resource is a folder, we just go straight to the
- // children
- if (resource.getType() == IResource.FOLDER) {
- return true;
- }
-
- // get the extension of the resource
- String ext = resource.getFileExtension();
- int kind = delta.getKind();
-
- String p = resource.getProjectRelativePath().toString();
- String message = null;
- switch (kind) {
- case IResourceDelta.CHANGED:
- // display verbose message
- message = String.format(Messages.s_Modified_Recreating_s, p);
- break;
- case IResourceDelta.ADDED:
- // display verbose message
- message = String.format(Messages.Added_s_s_Needs_Updating, p,
- SdkConstants.FN_RESOURCE_CLASS);
- break;
- case IResourceDelta.REMOVED:
- // display verbose message
- message = String.format(Messages.s_Removed_s_Needs_Updating, p,
- SdkConstants.FN_RESOURCE_CLASS);
- break;
- }
- if (message != null) {
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE,
- mBuilder.getProject(), message);
- }
-
- // If it's an XML resource, check the syntax
- if (SdkConstants.EXT_XML.equalsIgnoreCase(ext) && kind != IResourceDelta.REMOVED) {
- // check xml Validity
- mBuilder.checkXML(resource, this);
- }
- // Whether or not to generate R.java for a changed resource is taken care of by the
- // Resource Manager.
- } else if (resource instanceof IFolder) {
- // first check if we are in the android output folder.
- if (resource.equals(mAndroidOutputFolder)) {
- // we want to visit the merged manifest.
- return true;
- }
-
- // in this case we may be inside a folder that contains a source
- // folder, go through the list of known source folders
-
- for (IPath sourceFolderPath : mSourceFolders) {
- // first check if they match exactly.
- if (sourceFolderPath.equals(path)) {
- // this is a source folder!
- mInRes = false;
- mSourceFolder = getFolder(sourceFolderPath); // all non null due to test above
- mIsGenSourceFolder = path.segmentCount() == 2 &&
- path.segment(1).equals(SdkConstants.FD_GEN_SOURCES);
- return true;
- }
-
- // check if we are on the way to a source folder.
- int count = sourceFolderPath.matchingFirstSegments(path);
- if (count == path.segmentCount()) {
- mInRes = false;
- return true;
- }
- }
-
- // if we're here, we are visiting another folder
- // like /$Project/bin/ for instance (we get notified for changes
- // in .class!)
- // This could also be another source folder and we have found
- // R.java in a previous source folder
- // We don't want to visit its children
- return false;
- }
-
- return false;
- }
-
- /**
- * Returns a handle to the folder identified by the given path in this container.
- * <p/>The different with {@link IContainer#getFolder(IPath)} is that this returns a non
- * null object only if the resource actually exists and is a folder (and not a file)
- * @param path the path of the folder to return.
- * @return a handle to the folder if it exists, or null otherwise.
- */
- private IFolder getFolder(IPath path) {
- IResource resource = mRoot.findMember(path);
- if (resource != null && resource.exists() && resource.getType() == IResource.FOLDER) {
- return (IFolder)resource;
- }
-
- return null;
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/ResourceManagerBuilder.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/ResourceManagerBuilder.java
deleted file mode 100644
index 8e01cca29..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/build/builders/ResourceManagerBuilder.java
+++ /dev/null
@@ -1,317 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build.builders;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.build.Messages;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs.BuildVerbosity;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.project.ProjectHelper;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.sdklib.BuildToolInfo;
-import com.android.sdklib.IAndroidTarget;
-import com.android.utils.Pair;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.IncrementalProjectBuilder;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jdt.core.IClasspathEntry;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.JavaCore;
-
-import java.util.List;
-import java.util.Map;
-
-/**
- * Resource manager builder whose only purpose is to refresh the resource folder
- * so that the other builder use an up to date version.
- */
-public class ResourceManagerBuilder extends BaseBuilder {
-
- public static final String ID = "com.android.ide.eclipse.adt.ResourceManagerBuilder"; //$NON-NLS-1$
-
- public ResourceManagerBuilder() {
- super();
- }
-
- @Override
- protected void clean(IProgressMonitor monitor) throws CoreException {
- super.clean(monitor);
-
- // Get the project.
- IProject project = getProject();
-
- // Clear the project of the generic markers
- removeMarkersFromContainer(project, AdtConstants.MARKER_ADT);
- }
-
- // build() returns a list of project from which this project depends for future compilation.
- @SuppressWarnings("unchecked")
- @Override
- protected IProject[] build(int kind, Map args, IProgressMonitor monitor)
- throws CoreException {
- // Get the project.
- final IProject project = getProject();
- IJavaProject javaProject = JavaCore.create(project);
-
- // Clear the project of the generic markers
- removeMarkersFromContainer(project, AdtConstants.MARKER_ADT);
-
- // check for existing target marker, in which case we abort.
- // (this means: no SDK, no target, or unresolvable target.)
- try {
- abortOnBadSetup(javaProject, null);
- } catch (AbortBuildException e) {
- return null;
- }
-
- // Check the compiler compliance level, displaying the error message
- // since this is the first builder.
- Pair<Integer, String> result = ProjectHelper.checkCompilerCompliance(project);
- String errorMessage = null;
- switch (result.getFirst().intValue()) {
- case ProjectHelper.COMPILER_COMPLIANCE_LEVEL:
- errorMessage = Messages.Requires_Compiler_Compliance_s;
- break;
- case ProjectHelper.COMPILER_COMPLIANCE_SOURCE:
- errorMessage = Messages.Requires_Source_Compatibility_s;
- break;
- case ProjectHelper.COMPILER_COMPLIANCE_CODEGEN_TARGET:
- errorMessage = Messages.Requires_Class_Compatibility_s;
- break;
- }
-
- if (errorMessage != null) {
- errorMessage = String.format(errorMessage,
- result.getSecond() == null ? "(no value)" : result.getSecond());
-
- if (JavaCore.VERSION_1_7.equals(result.getSecond())) {
- // If the user is trying to target 1.7 but compiling with something older,
- // the error message can be a bit misleading; instead point them in the
- // direction of updating the project's build target.
- Sdk currentSdk = Sdk.getCurrent();
- if (currentSdk != null) {
- IAndroidTarget target = currentSdk.getTarget(project.getProject());
- if (target != null && target.getVersion().getApiLevel() < 19) {
- errorMessage = "Using 1.7 requires compiling with Android 4.4 " +
- "(KitKat); currently using " + target.getVersion();
- }
-
- ProjectState projectState = Sdk.getProjectState(project);
- if (projectState != null) {
- BuildToolInfo buildToolInfo = projectState.getBuildToolInfo();
- if (buildToolInfo == null) {
- buildToolInfo = currentSdk.getLatestBuildTool();
- }
- if (buildToolInfo != null && buildToolInfo.getRevision().getMajor() < 19) {
- errorMessage = "Using 1.7 requires using Android Build Tools " +
- "version 19 or later; currently using " +
- buildToolInfo.getRevision();
- }
- }
- }
- }
-
- markProject(AdtConstants.MARKER_ADT, errorMessage, IMarker.SEVERITY_ERROR);
- AdtPlugin.printErrorToConsole(project, errorMessage);
-
- return null;
- }
-
- // Check that the SDK directory has been setup.
- String osSdkFolder = AdtPlugin.getOsSdkFolder();
-
- if (osSdkFolder == null || osSdkFolder.length() == 0) {
- AdtPlugin.printErrorToConsole(project, Messages.No_SDK_Setup_Error);
- markProject(AdtConstants.MARKER_ADT, Messages.No_SDK_Setup_Error,
- IMarker.SEVERITY_ERROR);
-
- return null;
- }
-
- // check the 'gen' source folder is present
- boolean hasGenSrcFolder = false; // whether the project has a 'gen' source folder setup
-
- IClasspathEntry[] classpaths = javaProject.readRawClasspath();
- if (classpaths != null) {
- for (IClasspathEntry e : classpaths) {
- if (e.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
- IPath path = e.getPath();
- if (path.segmentCount() == 2 &&
- path.segment(1).equals(SdkConstants.FD_GEN_SOURCES)) {
- hasGenSrcFolder = true;
- break;
- }
- }
- }
- }
-
- boolean genFolderPresent = false; // whether the gen folder actually exists
- IResource resource = project.findMember(SdkConstants.FD_GEN_SOURCES);
- genFolderPresent = resource != null && resource.exists();
-
- if (hasGenSrcFolder == false && genFolderPresent) {
- // No source folder setup for 'gen' in the project, but there's already a
- // 'gen' resource (file or folder).
- String message;
- if (resource.getType() == IResource.FOLDER) {
- // folder exists already! This is an error. If the folder had been created
- // by the NewProjectWizard, it'd be a source folder.
- message = String.format("%1$s already exists but is not a source folder. Convert to a source folder or rename it.",
- resource.getFullPath().toString());
- } else {
- // resource exists but is not a folder.
- message = String.format(
- "Resource %1$s is in the way. ADT needs a source folder called 'gen' to work. Rename or delete resource.",
- resource.getFullPath().toString());
- }
-
- AdtPlugin.printErrorToConsole(project, message);
- markProject(AdtConstants.MARKER_ADT, message, IMarker.SEVERITY_ERROR);
-
- return null;
- } else if (hasGenSrcFolder == false || genFolderPresent == false) {
- // either there is no 'gen' source folder in the project (older SDK),
- // or the folder does not exist (was deleted, or was a fresh svn checkout maybe.)
-
- // In case we are migrating from an older SDK, we go through the current source
- // folders and delete the generated Java files.
- List<IPath> sourceFolders = BaseProjectHelper.getSourceClasspaths(javaProject);
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- for (IPath path : sourceFolders) {
- IResource member = root.findMember(path);
- if (member != null) {
- removeDerivedResources(member, monitor);
- }
- }
-
- // create the new source folder, if needed
- IFolder genFolder = project.getFolder(SdkConstants.FD_GEN_SOURCES);
- if (genFolderPresent == false) {
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project,
- "Creating 'gen' source folder for generated Java files");
- genFolder.create(true /* force */, true /* local */,
- new SubProgressMonitor(monitor, 10));
- }
-
- // add it to the source folder list, if needed only (or it will throw)
- if (hasGenSrcFolder == false) {
- IClasspathEntry[] entries = javaProject.getRawClasspath();
- entries = ProjectHelper.addEntryToClasspath(entries,
- JavaCore.newSourceEntry(genFolder.getFullPath()));
- javaProject.setRawClasspath(entries, new SubProgressMonitor(monitor, 10));
- }
-
- // refresh specifically the gen folder first, as it may break the build
- // if it doesn't arrive in time then refresh the whole project as usual.
- genFolder.refreshLocal(IResource.DEPTH_ZERO, new SubProgressMonitor(monitor, 10));
- project.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 10));
-
- // it seems like doing this fails to properly rebuild the project. the Java builder
- // running right after this builder will not see the gen folder, and will not be
- // restarted after this build. Therefore in this particular case, we start another
- // build asynchronously so that it's rebuilt after this build.
- launchJob(new Job("rebuild") {
- @Override
- protected IStatus run(IProgressMonitor m) {
- try {
- project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, m);
- return Status.OK_STATUS;
- } catch (CoreException e) {
- return e.getStatus();
- }
- }
- });
-
- }
-
- // convert older projects which use bin as the eclipse output folder into projects
- // using bin/classes
- IFolder androidOutput = BaseProjectHelper.getAndroidOutputFolder(project);
- IFolder javaOutput = BaseProjectHelper.getJavaOutputFolder(project);
- if (androidOutput.exists() == false || javaOutput == null ||
- javaOutput.getParent().equals(androidOutput) == false) {
- // get what we want as the new java output.
- IFolder newJavaOutput = androidOutput.getFolder(SdkConstants.FD_CLASSES_OUTPUT);
-
- if (androidOutput.exists() == false) {
- androidOutput.create(true /*force*/, true /*local*/, monitor);
- }
-
- if (newJavaOutput.exists() == false) {
- newJavaOutput.create(true /*force*/, true /*local*/, monitor);
- }
-
- // set the java output to this project.
- javaProject.setOutputLocation(newJavaOutput.getFullPath(), monitor);
-
- // need to do a full build. Can't build while we're already building, so launch a
- // job to build it right after this build
- launchJob(new Job("rebuild") {
- @Override
- protected IStatus run(IProgressMonitor jobMonitor) {
- try {
- project.build(IncrementalProjectBuilder.CLEAN_BUILD, jobMonitor);
- return Status.OK_STATUS;
- } catch (CoreException e) {
- return e.getStatus();
- }
- }
- });
- }
-
- // check that we have bin/res/
- IFolder binResFolder = androidOutput.getFolder(SdkConstants.FD_RESOURCES);
- if (binResFolder.exists() == false) {
- binResFolder.create(true /* force */, true /* local */,
- new SubProgressMonitor(monitor, 10));
- project.refreshLocal(IResource.DEPTH_ONE, new SubProgressMonitor(monitor, 10));
- }
-
- // Check the preference to be sure we are supposed to refresh
- // the folders.
- if (AdtPrefs.getPrefs().getBuildForceResResfresh()) {
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE, project, Messages.Refreshing_Res);
-
- // refresh the res folder.
- IFolder resFolder = project.getFolder(AdtConstants.WS_RESOURCES);
- resFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);
-
- // Also refresh the assets folder to make sure the ApkBuilder
- // will now it's changed and will force a new resource packaging.
- IFolder assetsFolder = project.getFolder(AdtConstants.WS_ASSETS);
- assetsFolder.refreshLocal(IResource.DEPTH_INFINITE, monitor);
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidContentAssist.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidContentAssist.java
deleted file mode 100644
index 5aac51f68..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidContentAssist.java
+++ /dev/null
@@ -1,1331 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_LAYOUT_RESOURCE_PREFIX;
-import static com.android.SdkConstants.PREFIX_ANDROID;
-import static com.android.SdkConstants.PREFIX_RESOURCE_REF;
-import static com.android.SdkConstants.PREFIX_THEME_REF;
-import static com.android.SdkConstants.UNIT_DP;
-import static com.android.SdkConstants.UNIT_IN;
-import static com.android.SdkConstants.UNIT_MM;
-import static com.android.SdkConstants.UNIT_PT;
-import static com.android.SdkConstants.UNIT_PX;
-import static com.android.SdkConstants.UNIT_SP;
-import static com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor.ATTRIBUTE_ICON_FILENAME;
-
-import com.android.ide.common.api.IAttributeInfo;
-import com.android.ide.common.api.IAttributeInfo.Format;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.IDescriptorProvider;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.SeparatorAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.TextValueDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiFlagAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiResourceAttributeNode;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.utils.Pair;
-import com.android.utils.XmlUtils;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.ui.ISharedImages;
-import org.eclipse.jdt.ui.JavaUI;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.contentassist.IContextInformationValidator;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.w3c.dom.Node;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Comparator;
-import java.util.EnumSet;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.regex.Pattern;
-
-/**
- * Content Assist Processor for Android XML files
- * <p>
- * Remaining corner cases:
- * <ul>
- * <li>Completion does not work right if there is a space between the = and the opening
- * quote.
- * <li>Replacement completion does not work right if the caret is to the left of the
- * opening quote, where the opening quote is a single quote, and the replacement items use
- * double quotes.
- * </ul>
- */
-@SuppressWarnings("restriction") // XML model
-public abstract class AndroidContentAssist implements IContentAssistProcessor {
-
- /** Regexp to detect a full attribute after an element tag.
- * <pre>Syntax:
- * name = "..." quoted string with all but < and "
- * or:
- * name = '...' quoted string with all but < and '
- * </pre>
- */
- private static Pattern sFirstAttribute = Pattern.compile(
- "^ *[a-zA-Z_:]+ *= *(?:\"[^<\"]*\"|'[^<']*')"); //$NON-NLS-1$
-
- /** Regexp to detect an element tag name */
- private static Pattern sFirstElementWord = Pattern.compile("^[a-zA-Z0-9_:.-]+"); //$NON-NLS-1$
-
- /** Regexp to detect whitespace */
- private static Pattern sWhitespace = Pattern.compile("\\s+"); //$NON-NLS-1$
-
- protected final static String ROOT_ELEMENT = "";
-
- /** Descriptor of the root of the XML hierarchy. This a "fake" ElementDescriptor which
- * is used to list all the possible roots given by actual implementations.
- * DO NOT USE DIRECTLY. Call {@link #getRootDescriptor()} instead. */
- private ElementDescriptor mRootDescriptor;
-
- private final int mDescriptorId;
-
- protected AndroidXmlEditor mEditor;
-
- /**
- * Constructor for AndroidContentAssist
- * @param descriptorId An id for {@link AndroidTargetData#getDescriptorProvider(int)}.
- * The Id can be one of {@link AndroidTargetData#DESCRIPTOR_MANIFEST},
- * {@link AndroidTargetData#DESCRIPTOR_LAYOUT},
- * {@link AndroidTargetData#DESCRIPTOR_MENU},
- * or {@link AndroidTargetData#DESCRIPTOR_OTHER_XML}.
- * All other values will throw an {@link IllegalArgumentException} later at runtime.
- */
- public AndroidContentAssist(int descriptorId) {
- mDescriptorId = descriptorId;
- }
-
- /**
- * Returns a list of completion proposals based on the
- * specified location within the document that corresponds
- * to the current cursor position within the text viewer.
- *
- * @param viewer the viewer whose document is used to compute the proposals
- * @param offset an offset within the document for which completions should be computed
- * @return an array of completion proposals or <code>null</code> if no proposals are possible
- *
- * @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeCompletionProposals(org.eclipse.jface.text.ITextViewer, int)
- */
- @Override
- public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
- String wordPrefix = extractElementPrefix(viewer, offset);
-
- if (mEditor == null) {
- mEditor = AndroidXmlEditor.fromTextViewer(viewer);
- if (mEditor == null) {
- // This should not happen. Duck and forget.
- AdtPlugin.log(IStatus.ERROR, "Editor not found during completion");
- return null;
- }
- }
-
- // List of proposals, in the order presented to the user.
- List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>(80);
-
- // Look up the caret context - where in an element, or between elements, or
- // within an element's children, is the given caret offset located?
- Pair<Node, Node> context = DomUtilities.getNodeContext(viewer.getDocument(), offset);
- if (context == null) {
- return null;
- }
- Node parentNode = context.getFirst();
- Node currentNode = context.getSecond();
- assert parentNode != null || currentNode != null;
-
- UiElementNode rootUiNode = mEditor.getUiRootNode();
- if (currentNode == null || currentNode.getNodeType() == Node.TEXT_NODE) {
- UiElementNode parentUiNode =
- rootUiNode == null ? null : rootUiNode.findXmlNode(parentNode);
- computeTextValues(proposals, offset, parentNode, currentNode, parentUiNode,
- wordPrefix);
- } else if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
- String parent = currentNode.getNodeName();
- AttribInfo info = parseAttributeInfo(viewer, offset, offset - wordPrefix.length());
- char nextChar = extractChar(viewer, offset);
- if (info != null) {
- // check to see if we can find a UiElementNode matching this XML node
- UiElementNode currentUiNode = rootUiNode == null
- ? null : rootUiNode.findXmlNode(currentNode);
- computeAttributeProposals(proposals, viewer, offset, wordPrefix, currentUiNode,
- parentNode, currentNode, parent, info, nextChar);
- } else {
- computeNonAttributeProposals(viewer, offset, wordPrefix, proposals, parentNode,
- currentNode, parent, nextChar);
- }
- }
-
- return proposals.toArray(new ICompletionProposal[proposals.size()]);
- }
-
- private void computeNonAttributeProposals(ITextViewer viewer, int offset, String wordPrefix,
- List<ICompletionProposal> proposals, Node parentNode, Node currentNode, String parent,
- char nextChar) {
- if (startsWith(parent, wordPrefix)) {
- // We are still editing the element's tag name, not the attributes
- // (the element's tag name may not even be complete)
-
- Object[] choices = getChoicesForElement(parent, currentNode);
- if (choices == null || choices.length == 0) {
- return;
- }
-
- int replaceLength = parent.length() - wordPrefix.length();
- boolean isNew = replaceLength == 0 && nextNonspaceChar(viewer, offset) == '<';
- // Special case: if we are right before the beginning of a new
- // element, wipe out the replace length such that we insert before it,
- // we don't edit the current element.
- if (wordPrefix.length() == 0 && nextChar == '<') {
- replaceLength = 0;
- isNew = true;
- }
-
- // If we found some suggestions, do we need to add an opening "<" bracket
- // for the element? We don't if the cursor is right after "<" or "</".
- // Per XML Spec, there's no whitespace between "<" or "</" and the tag name.
- char needTag = computeElementNeedTag(viewer, offset, wordPrefix);
-
- addMatchingProposals(proposals, choices, offset,
- parentNode != null ? parentNode : null, wordPrefix, needTag,
- false /* isAttribute */, isNew, false /*isComplete*/,
- replaceLength);
- }
- }
-
- private void computeAttributeProposals(List<ICompletionProposal> proposals, ITextViewer viewer,
- int offset, String wordPrefix, UiElementNode currentUiNode, Node parentNode,
- Node currentNode, String parent, AttribInfo info, char nextChar) {
- // We're editing attributes in an element node (either the attributes' names
- // or their values).
-
- if (info.isInValue) {
- if (computeAttributeValues(proposals, offset, parent, info.name, currentNode,
- wordPrefix, info.skipEndTag, info.replaceLength)) {
- return;
- }
- }
-
- // Look up attribute proposals based on descriptors
- Object[] choices = getChoicesForAttribute(parent, currentNode, currentUiNode,
- info, wordPrefix);
- if (choices == null || choices.length == 0) {
- return;
- }
-
- int replaceLength = info.replaceLength;
- if (info.correctedPrefix != null) {
- wordPrefix = info.correctedPrefix;
- }
- char needTag = info.needTag;
- // Look to the right and see if we're followed by whitespace
- boolean isNew = replaceLength == 0
- && (Character.isWhitespace(nextChar) || nextChar == '>' || nextChar == '/');
-
- addMatchingProposals(proposals, choices, offset, parentNode != null ? parentNode : null,
- wordPrefix, needTag, true /* isAttribute */, isNew, info.skipEndTag,
- replaceLength);
- }
-
- private char computeElementNeedTag(ITextViewer viewer, int offset, String wordPrefix) {
- char needTag = 0;
- int offset2 = offset - wordPrefix.length() - 1;
- char c1 = extractChar(viewer, offset2);
- if (!((c1 == '<') || (c1 == '/' && extractChar(viewer, offset2 - 1) == '<'))) {
- needTag = '<';
- }
- return needTag;
- }
-
- protected int computeTextReplaceLength(Node currentNode, int offset) {
- if (currentNode == null) {
- return 0;
- }
-
- assert currentNode != null && currentNode.getNodeType() == Node.TEXT_NODE;
-
- String nodeValue = currentNode.getNodeValue();
- int relativeOffset = offset - ((IndexedRegion) currentNode).getStartOffset();
- int lineEnd = nodeValue.indexOf('\n', relativeOffset);
- if (lineEnd == -1) {
- lineEnd = nodeValue.length();
- }
- return lineEnd - relativeOffset;
- }
-
- /**
- * Gets the choices when the user is editing the name of an XML element.
- * <p/>
- * The user is editing the name of an element (the "parent").
- * Find the grand-parent and if one is found, return its children element list.
- * The name which is being edited should be one of those.
- * <p/>
- * Example: <manifest><applic*cursor* => returns the list of all elements that
- * can be found under <manifest>, of which <application> is one of the choices.
- *
- * @return an ElementDescriptor[] or null if no valid element was found.
- */
- protected Object[] getChoicesForElement(String parent, Node currentNode) {
- ElementDescriptor grandparent = null;
- if (currentNode.getParentNode().getNodeType() == Node.ELEMENT_NODE) {
- grandparent = getDescriptor(currentNode.getParentNode().getNodeName());
- } else if (currentNode.getParentNode().getNodeType() == Node.DOCUMENT_NODE) {
- grandparent = getRootDescriptor();
- }
- if (grandparent != null) {
- for (ElementDescriptor e : grandparent.getChildren()) {
- if (e.getXmlName().startsWith(parent)) {
- return sort(grandparent.getChildren());
- }
- }
- }
-
- return null;
- }
-
- /** Non-destructively sort a list of ElementDescriptors and return the result */
- protected static ElementDescriptor[] sort(ElementDescriptor[] elements) {
- if (elements != null && elements.length > 1) {
- // Sort alphabetically. Must make copy to not destroy original.
- ElementDescriptor[] copy = new ElementDescriptor[elements.length];
- System.arraycopy(elements, 0, copy, 0, elements.length);
-
- Arrays.sort(copy, new Comparator<ElementDescriptor>() {
- @Override
- public int compare(ElementDescriptor e1, ElementDescriptor e2) {
- return e1.getXmlLocalName().compareTo(e2.getXmlLocalName());
- }
- });
-
- return copy;
- }
-
- return elements;
- }
-
- /**
- * Gets the choices when the user is editing an XML attribute.
- * <p/>
- * In input, attrInfo contains details on the analyzed context, namely whether the
- * user is editing an attribute value (isInValue) or an attribute name.
- * <p/>
- * In output, attrInfo also contains two possible new values (this is a hack to circumvent
- * the lack of out-parameters in Java):
- * - AttribInfo.correctedPrefix if the user has been editing an attribute value and it has
- * been detected that what the user typed is different from what extractElementPrefix()
- * predicted. This happens because extractElementPrefix() stops when a character that
- * cannot be an element name appears whereas parseAttributeInfo() uses a grammar more
- * lenient as suitable for attribute values.
- * - AttribInfo.needTag will be non-zero if we find that the attribute completion proposal
- * must be double-quoted.
- * @param currentUiNode
- *
- * @return an AttributeDescriptor[] if the user is editing an attribute name.
- * a String[] if the user is editing an attribute value with some known values,
- * or null if nothing is known about the context.
- */
- private Object[] getChoicesForAttribute(
- String parent, Node currentNode, UiElementNode currentUiNode, AttribInfo attrInfo,
- String wordPrefix) {
- Object[] choices = null;
- if (attrInfo.isInValue) {
- // Editing an attribute's value... Get the attribute name and then the
- // possible choices for the tuple(parent,attribute)
- String value = attrInfo.valuePrefix;
- if (value.startsWith("'") || value.startsWith("\"")) { //$NON-NLS-1$ //$NON-NLS-2$
- value = value.substring(1);
- // The prefix that was found at the beginning only scan for characters
- // valid for tag name. We now know the real prefix for this attribute's
- // value, which is needed to generate the completion choices below.
- attrInfo.correctedPrefix = value;
- } else {
- attrInfo.needTag = '"';
- }
-
- if (currentUiNode != null) {
- // look for an UI attribute matching the current attribute name
- String attrName = attrInfo.name;
- // remove any namespace prefix from the attribute name
- int pos = attrName.indexOf(':');
- if (pos >= 0) {
- attrName = attrName.substring(pos + 1);
- }
-
- UiAttributeNode currAttrNode = null;
- for (UiAttributeNode attrNode : currentUiNode.getAllUiAttributes()) {
- if (attrNode.getDescriptor().getXmlLocalName().equals(attrName)) {
- currAttrNode = attrNode;
- break;
- }
- }
-
- if (currAttrNode != null) {
- choices = getAttributeValueChoices(currAttrNode, attrInfo, value);
- }
- }
-
- if (choices == null) {
- // fallback on the older descriptor-only based lookup.
-
- // in order to properly handle the special case of the name attribute in
- // the action tag, we need the grandparent of the action node, to know
- // what type of actions we need.
- // e.g. activity -> intent-filter -> action[@name]
- String greatGrandParentName = null;
- Node grandParent = currentNode.getParentNode();
- if (grandParent != null) {
- Node greatGrandParent = grandParent.getParentNode();
- if (greatGrandParent != null) {
- greatGrandParentName = greatGrandParent.getLocalName();
- }
- }
-
- AndroidTargetData data = mEditor.getTargetData();
- if (data != null) {
- choices = data.getAttributeValues(parent, attrInfo.name, greatGrandParentName);
- }
- }
- } else {
- // Editing an attribute's name... Get attributes valid for the parent node.
- if (currentUiNode != null) {
- choices = currentUiNode.getAttributeDescriptors();
- } else {
- ElementDescriptor parentDesc = getDescriptor(parent);
- if (parentDesc != null) {
- choices = parentDesc.getAttributes();
- }
- }
- }
- return choices;
- }
-
- protected Object[] getAttributeValueChoices(UiAttributeNode currAttrNode, AttribInfo attrInfo,
- String value) {
- Object[] choices;
- int pos;
- choices = currAttrNode.getPossibleValues(value);
- if (choices != null && currAttrNode instanceof UiResourceAttributeNode) {
- attrInfo.skipEndTag = false;
- }
-
- if (currAttrNode instanceof UiFlagAttributeNode) {
- // A "flag" can consist of several values separated by "or" (|).
- // If the correct prefix contains such a pipe character, we change
- // it so that only the currently edited value is completed.
- pos = value.lastIndexOf('|');
- if (pos >= 0) {
- attrInfo.correctedPrefix = value = value.substring(pos + 1);
- attrInfo.needTag = 0;
- }
-
- attrInfo.skipEndTag = false;
- }
-
- // Should we do suffix completion on dimension units etc?
- choices = completeSuffix(choices, value, currAttrNode);
-
- // Check to see if the user is attempting resource completion
- AttributeDescriptor attributeDescriptor = currAttrNode.getDescriptor();
- IAttributeInfo attributeInfo = attributeDescriptor.getAttributeInfo();
- if (value.startsWith(PREFIX_RESOURCE_REF)
- && !attributeInfo.getFormats().contains(Format.REFERENCE)) {
- // Special case: If the attribute value looks like a reference to a
- // resource, offer to complete it, since in many cases our metadata
- // does not correctly state whether a resource value is allowed. We don't
- // offer these for an empty completion context, but if the user has
- // actually typed "@", in that case list resource matches.
- // For example, for android:minHeight this makes completion on @dimen/
- // possible.
- choices = UiResourceAttributeNode.computeResourceStringMatches(
- mEditor, attributeDescriptor, value);
- attrInfo.skipEndTag = false;
- } else if (value.startsWith(PREFIX_THEME_REF)
- && !attributeInfo.getFormats().contains(Format.REFERENCE)) {
- choices = UiResourceAttributeNode.computeResourceStringMatches(
- mEditor, attributeDescriptor, value);
- attrInfo.skipEndTag = false;
- }
-
- return choices;
- }
-
- /**
- * Compute attribute values. Return true if the complete set of values was
- * added, so addition descriptor information should not be added.
- */
- protected boolean computeAttributeValues(List<ICompletionProposal> proposals, int offset,
- String parentTagName, String attributeName, Node node, String wordPrefix,
- boolean skipEndTag, int replaceLength) {
- return false;
- }
-
- protected void computeTextValues(List<ICompletionProposal> proposals, int offset,
- Node parentNode, Node currentNode, UiElementNode uiParent,
- String wordPrefix) {
-
- if (parentNode != null) {
- // Examine the parent of the text node.
- Object[] choices = getElementChoicesForTextNode(parentNode);
- if (choices != null && choices.length > 0) {
- ISourceViewer viewer = mEditor.getStructuredSourceViewer();
- char needTag = computeElementNeedTag(viewer, offset, wordPrefix);
-
- int replaceLength = 0;
- addMatchingProposals(proposals, choices,
- offset, parentNode, wordPrefix, needTag,
- false /* isAttribute */,
- false /*isNew*/,
- false /*isComplete*/,
- replaceLength);
- }
- }
- }
-
- /**
- * Gets the choices when the user is editing an XML text node.
- * <p/>
- * This means the user is editing outside of any XML element or attribute.
- * Simply return the list of XML elements that can be present there, based on the
- * parent of the current node.
- *
- * @return An ElementDescriptor[] or null.
- */
- protected ElementDescriptor[] getElementChoicesForTextNode(Node parentNode) {
- ElementDescriptor[] choices = null;
- String parent;
- if (parentNode.getNodeType() == Node.ELEMENT_NODE) {
- // We're editing a text node which parent is an element node. Limit
- // content assist to elements valid for the parent.
- parent = parentNode.getNodeName();
- ElementDescriptor desc = getDescriptor(parent);
- if (desc == null && parent.indexOf('.') != -1) {
- // The parent is a custom view and we don't have metadata about its
- // allowable children, so just assume any normal layout tag is
- // legal
- desc = mRootDescriptor;
- }
-
- if (desc != null) {
- choices = sort(desc.getChildren());
- }
- } else if (parentNode.getNodeType() == Node.DOCUMENT_NODE) {
- // We're editing a text node at the first level (i.e. root node).
- // Limit content assist to the only valid root elements.
- choices = sort(getRootDescriptor().getChildren());
- }
-
- return choices;
- }
-
- /**
- * Given a list of choices, adds in any that match the current prefix into the
- * proposals list.
- * <p/>
- * Choices is an object array. Items of the array can be:
- * - ElementDescriptor: a possible element descriptor which XML name should be completed.
- * - AttributeDescriptor: a possible attribute descriptor which XML name should be completed.
- * - String: string values to display as-is to the user. Typically those are possible
- * values for a given attribute.
- * - Pair of Strings: the first value is the keyword to insert, and the second value
- * is the tooltip/help for the value to be displayed in the documentation popup.
- */
- protected void addMatchingProposals(List<ICompletionProposal> proposals, Object[] choices,
- int offset, Node currentNode, String wordPrefix, char needTag,
- boolean isAttribute, boolean isNew, boolean skipEndTag, int replaceLength) {
- if (choices == null) {
- return;
- }
-
- Map<String, String> nsUriMap = new HashMap<String, String>();
- boolean haveLayoutParams = false;
-
- for (Object choice : choices) {
- String keyword = null;
- String nsPrefix = null;
- String nsUri = null;
- Image icon = null;
- String tooltip = null;
- if (choice instanceof ElementDescriptor) {
- keyword = ((ElementDescriptor)choice).getXmlName();
- icon = ((ElementDescriptor)choice).getGenericIcon();
- // Tooltip computed lazily in {@link CompletionProposal}
- } else if (choice instanceof TextValueDescriptor) {
- continue; // Value nodes are not part of the completion choices
- } else if (choice instanceof SeparatorAttributeDescriptor) {
- continue; // not real attribute descriptors
- } else if (choice instanceof AttributeDescriptor) {
- keyword = ((AttributeDescriptor)choice).getXmlLocalName();
- icon = ((AttributeDescriptor)choice).getGenericIcon();
- // Tooltip computed lazily in {@link CompletionProposal}
-
- // Get the namespace URI for the attribute. Note that some attributes
- // do not have a namespace and thus return null here.
- nsUri = ((AttributeDescriptor)choice).getNamespaceUri();
- if (nsUri != null) {
- nsPrefix = nsUriMap.get(nsUri);
- if (nsPrefix == null) {
- nsPrefix = XmlUtils.lookupNamespacePrefix(currentNode, nsUri, false);
- nsUriMap.put(nsUri, nsPrefix);
- }
- }
- if (nsPrefix != null) {
- nsPrefix += ":"; //$NON-NLS-1$
- }
-
- } else if (choice instanceof String) {
- keyword = (String) choice;
- if (isAttribute) {
- icon = IconFactory.getInstance().getIcon(ATTRIBUTE_ICON_FILENAME);
- }
- } else if (choice instanceof Pair<?, ?>) {
- @SuppressWarnings("unchecked")
- Pair<String, String> pair = (Pair<String, String>) choice;
- keyword = pair.getFirst();
- tooltip = pair.getSecond();
- if (isAttribute) {
- icon = IconFactory.getInstance().getIcon(ATTRIBUTE_ICON_FILENAME);
- }
- } else if (choice instanceof IType) {
- IType type = (IType) choice;
- keyword = type.getFullyQualifiedName();
- icon = JavaUI.getSharedImages().getImage(ISharedImages.IMG_OBJS_CUNIT);
- } else {
- continue; // discard unknown choice
- }
-
- String nsKeyword = nsPrefix == null ? keyword : (nsPrefix + keyword);
-
- if (nameStartsWith(nsKeyword, wordPrefix, nsPrefix)) {
- keyword = nsKeyword;
- String endTag = ""; //$NON-NLS-1$
- if (needTag != 0) {
- if (needTag == '"') {
- keyword = needTag + keyword;
- endTag = String.valueOf(needTag);
- } else if (needTag == '<') {
- if (elementCanHaveChildren(choice)) {
- endTag = String.format("></%1$s>", keyword); //$NON-NLS-1$
- } else {
- endTag = "/>"; //$NON-NLS-1$
- }
- keyword = needTag + keyword + ' ';
- } else if (needTag == ' ') {
- keyword = needTag + keyword;
- }
- } else if (!isAttribute && isNew) {
- if (elementCanHaveChildren(choice)) {
- endTag = String.format("></%1$s>", keyword); //$NON-NLS-1$
- } else {
- endTag = "/>"; //$NON-NLS-1$
- }
- keyword = keyword + ' ';
- }
-
- final String suffix;
- int cursorPosition;
- final String displayString;
- if (choice instanceof AttributeDescriptor && isNew) {
- // Special case for attributes: insert ="" stuff and locate caret inside ""
- suffix = "=\"\""; //$NON-NLS-1$
- cursorPosition = keyword.length() + suffix.length() - 1;
- displayString = keyword + endTag; // don't include suffix;
- } else {
- suffix = endTag;
- cursorPosition = keyword.length();
- displayString = null;
- }
-
- if (skipEndTag) {
- assert isAttribute;
- cursorPosition++;
- }
-
- if (nsPrefix != null &&
- keyword.startsWith(ATTR_LAYOUT_RESOURCE_PREFIX, nsPrefix.length())) {
- haveLayoutParams = true;
- }
-
- // For attributes, automatically insert ns:attribute="" and place the cursor
- // inside the quotes.
- // Special case for attributes: insert ="" stuff and locate caret inside ""
- proposals.add(new CompletionProposal(
- this,
- choice,
- keyword + suffix, // String replacementString
- offset - wordPrefix.length(), // int replacementOffset
- wordPrefix.length() + replaceLength,// int replacementLength
- cursorPosition, // cursorPosition
- icon, // Image image
- displayString, // displayString
- null, // IContextInformation contextInformation
- tooltip, // String additionalProposalInfo
- nsPrefix,
- nsUri
- ));
- }
- }
-
- if (wordPrefix.length() > 0 && haveLayoutParams
- && !wordPrefix.startsWith(ATTR_LAYOUT_RESOURCE_PREFIX)) {
- // Sort layout parameters to the front if we automatically inserted some
- // that you didn't request. For example, you typed "width" and we match both
- // "width" and "layout_width" - should match layout_width.
- String nsPrefix = nsUriMap.get(ANDROID_URI);
- if (nsPrefix == null) {
- nsPrefix = PREFIX_ANDROID;
- } else {
- nsPrefix += ':';
- }
- if (!(wordPrefix.startsWith(nsPrefix)
- && wordPrefix.startsWith(ATTR_LAYOUT_RESOURCE_PREFIX, nsPrefix.length()))) {
- int nextLayoutIndex = 0;
- for (int i = 0, n = proposals.size(); i < n; i++) {
- ICompletionProposal proposal = proposals.get(i);
- String keyword = proposal.getDisplayString();
- if (keyword.startsWith(nsPrefix) &&
- keyword.startsWith(ATTR_LAYOUT_RESOURCE_PREFIX, nsPrefix.length())
- && i != nextLayoutIndex) {
- // Swap to front
- ICompletionProposal temp = proposals.get(nextLayoutIndex);
- proposals.set(nextLayoutIndex, proposal);
- proposals.set(i, temp);
- nextLayoutIndex++;
- }
- }
- }
- }
- }
-
- /**
- * Returns true if the given word starts with the given prefix. The comparison is not
- * case sensitive.
- *
- * @param word the word to test
- * @param prefix the prefix the word should start with
- * @return true if the given word starts with the given prefix
- */
- protected static boolean startsWith(String word, String prefix) {
- int prefixLength = prefix.length();
- int wordLength = word.length();
- if (wordLength < prefixLength) {
- return false;
- }
-
- for (int i = 0; i < prefixLength; i++) {
- if (Character.toLowerCase(prefix.charAt(i))
- != Character.toLowerCase(word.charAt(i))) {
- return false;
- }
- }
-
- return true;
- }
-
- /** @return the editor associated with this content assist */
- AndroidXmlEditor getEditor() {
- return mEditor;
- }
-
- /**
- * This method performs a prefix match for the given word and prefix, with a couple of
- * Android code completion specific twists:
- * <ol>
- * <li> The match is not case sensitive, so {word="fOo",prefix="FoO"} is a match.
- * <li>If the word to be matched has a namespace prefix, the typed prefix doesn't have
- * to match it. So {word="android:foo", prefix="foo"} is a match.
- * <li>If the attribute name part starts with "layout_" it can be omitted. So
- * {word="android:layout_marginTop",prefix="margin"} is a match, as is
- * {word="android:layout_marginTop",prefix="android:margin"}.
- * </ol>
- *
- * @param word the full word to be matched, including namespace if any
- * @param prefix the prefix to check
- * @param nsPrefix the namespace prefix (android: or local definition of android
- * namespace prefix)
- * @return true if the prefix matches for code completion
- */
- protected static boolean nameStartsWith(String word, String prefix, String nsPrefix) {
- if (nsPrefix == null) {
- nsPrefix = ""; //$NON-NLS-1$
- }
-
- int wordStart = nsPrefix.length();
- int prefixStart = 0;
-
- if (startsWith(prefix, nsPrefix)) {
- // Already matches up through the namespace prefix:
- prefixStart = wordStart;
- } else if (startsWith(nsPrefix, prefix)) {
- return true;
- }
-
- int prefixLength = prefix.length();
- int wordLength = word.length();
-
- if (wordLength - wordStart < prefixLength - prefixStart) {
- return false;
- }
-
- boolean matches = true;
- for (int i = prefixStart, j = wordStart; i < prefixLength; i++, j++) {
- char c1 = Character.toLowerCase(prefix.charAt(i));
- char c2 = Character.toLowerCase(word.charAt(j));
- if (c1 != c2) {
- matches = false;
- break;
- }
- }
-
- if (!matches && word.startsWith(ATTR_LAYOUT_RESOURCE_PREFIX, wordStart)
- && !prefix.startsWith(ATTR_LAYOUT_RESOURCE_PREFIX, prefixStart)) {
- wordStart += ATTR_LAYOUT_RESOURCE_PREFIX.length();
-
- if (wordLength - wordStart < prefixLength - prefixStart) {
- return false;
- }
-
- for (int i = prefixStart, j = wordStart; i < prefixLength; i++, j++) {
- char c1 = Character.toLowerCase(prefix.charAt(i));
- char c2 = Character.toLowerCase(word.charAt(j));
- if (c1 != c2) {
- return false;
- }
- }
-
- return true;
- }
-
- return matches;
- }
-
- /**
- * Indicates whether this descriptor describes an element that can potentially
- * have children (either sub-elements or text value). If an element can have children,
- * we want to explicitly write an opening and a separate closing tag.
- * <p/>
- * Elements can have children if the descriptor has children element descriptors
- * or if one of the attributes is a TextValueDescriptor.
- *
- * @param descriptor An ElementDescriptor or an AttributeDescriptor
- * @return True if the descriptor is an ElementDescriptor that can have children or a text
- * value
- */
- private boolean elementCanHaveChildren(Object descriptor) {
- if (descriptor instanceof ElementDescriptor) {
- ElementDescriptor desc = (ElementDescriptor) descriptor;
- if (desc.hasChildren()) {
- return true;
- }
- for (AttributeDescriptor attrDesc : desc.getAttributes()) {
- if (attrDesc instanceof TextValueDescriptor) {
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * Returns the element descriptor matching a given XML node name or null if it can't be
- * found.
- * <p/>
- * This is simplistic; ideally we should consider the parent's chain to make sure we
- * can differentiate between different hierarchy trees. Right now the first match found
- * is returned.
- */
- private ElementDescriptor getDescriptor(String nodeName) {
- return getRootDescriptor().findChildrenDescriptor(nodeName, true /* recursive */);
- }
-
- @Override
- public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) {
- return null;
- }
-
- /**
- * Returns the characters which when entered by the user should
- * automatically trigger the presentation of possible completions.
- *
- * In our case, we auto-activate on opening tags and attributes namespace.
- *
- * @return the auto activation characters for completion proposal or <code>null</code>
- * if no auto activation is desired
- */
- @Override
- public char[] getCompletionProposalAutoActivationCharacters() {
- return new char[]{ '<', ':', '=' };
- }
-
- @Override
- public char[] getContextInformationAutoActivationCharacters() {
- return null;
- }
-
- @Override
- public IContextInformationValidator getContextInformationValidator() {
- return null;
- }
-
- @Override
- public String getErrorMessage() {
- return null;
- }
-
- /**
- * Heuristically extracts the prefix used for determining template relevance
- * from the viewer's document. The default implementation returns the String from
- * offset backwards that forms a potential XML element name, attribute name or
- * attribute value.
- *
- * The part were we access the document was extracted from
- * org.eclipse.jface.text.templatesTemplateCompletionProcessor and adapted to our needs.
- *
- * @param viewer the viewer
- * @param offset offset into document
- * @return the prefix to consider
- */
- protected String extractElementPrefix(ITextViewer viewer, int offset) {
- int i = offset;
- IDocument document = viewer.getDocument();
- if (i > document.getLength()) return ""; //$NON-NLS-1$
-
- try {
- for (; i > 0; --i) {
- char ch = document.getChar(i - 1);
-
- // We want all characters that can form a valid:
- // - element name, e.g. anything that is a valid Java class/variable literal.
- // - attribute name, including : for the namespace
- // - attribute value.
- // Before we were inclusive and that made the code fragile. So now we're
- // going to be exclusive: take everything till we get one of:
- // - any form of whitespace
- // - any xml separator, e.g. < > ' " and =
- if (Character.isWhitespace(ch) ||
- ch == '<' || ch == '>' || ch == '\'' || ch == '"' || ch == '=') {
- break;
- }
- }
-
- return document.get(i, offset - i);
- } catch (BadLocationException e) {
- return ""; //$NON-NLS-1$
- }
- }
-
- /**
- * Extracts the character at the given offset.
- * Returns 0 if the offset is invalid.
- */
- protected char extractChar(ITextViewer viewer, int offset) {
- IDocument document = viewer.getDocument();
- if (offset > document.getLength()) return 0;
-
- try {
- return document.getChar(offset);
- } catch (BadLocationException e) {
- return 0;
- }
- }
-
- /**
- * Search forward and find the first non-space character and return it. Returns 0 if no
- * such character was found.
- */
- private char nextNonspaceChar(ITextViewer viewer, int offset) {
- IDocument document = viewer.getDocument();
- int length = document.getLength();
- for (; offset < length; offset++) {
- try {
- char c = document.getChar(offset);
- if (!Character.isWhitespace(c)) {
- return c;
- }
- } catch (BadLocationException e) {
- return 0;
- }
- }
-
- return 0;
- }
-
- /**
- * Information about the current edit of an attribute as reported by parseAttributeInfo.
- */
- protected static class AttribInfo {
- public AttribInfo() {
- }
-
- /** True if the cursor is located in an attribute's value, false if in an attribute name */
- public boolean isInValue = false;
- /** The attribute name. Null when not set. */
- public String name = null;
- /** The attribute value top the left of the cursor. Null when not set. The value
- * *may* start with a quote (' or "), in which case we know we don't need to quote
- * the string for the user */
- public String valuePrefix = null;
- /** String typed by the user so far (i.e. right before requesting code completion),
- * which will be corrected if we find a possible completion for an attribute value.
- * See the long comment in getChoicesForAttribute(). */
- public String correctedPrefix = null;
- /** Non-zero if an attribute value need a start/end tag (i.e. quotes or brackets) */
- public char needTag = 0;
- /** Number of characters to replace after the prefix */
- public int replaceLength = 0;
- /** Should the cursor advance through the end tag when inserted? */
- public boolean skipEndTag = false;
- }
-
- /**
- * Try to guess if the cursor is editing an element's name or an attribute following an
- * element. If it's an attribute, try to find if an attribute name is being defined or
- * its value.
- * <br/>
- * This is currently *only* called when we know the cursor is after a complete element
- * tag name, so it should never return null.
- * <br/>
- * Reference for XML syntax: http://www.w3.org/TR/2006/REC-xml-20060816/#sec-starttags
- * <br/>
- * @return An AttribInfo describing which attribute is being edited or null if the cursor is
- * not editing an attribute (in which case it must be an element's name).
- */
- private AttribInfo parseAttributeInfo(ITextViewer viewer, int offset, int prefixStartOffset) {
- AttribInfo info = new AttribInfo();
- int originalOffset = offset;
-
- IDocument document = viewer.getDocument();
- int n = document.getLength();
- if (offset <= n) {
- try {
- // Look to the right to make sure we aren't sitting on the boundary of the
- // beginning of a new element with whitespace before it
- if (offset < n && document.getChar(offset) == '<') {
- return null;
- }
-
- n = offset;
- for (;offset > 0; --offset) {
- char ch = document.getChar(offset - 1);
- if (ch == '>') break;
- if (ch == '<') break;
- }
-
- // text will contain the full string of the current element,
- // i.e. whatever is after the "<" to the current cursor
- String text = document.get(offset, n - offset);
-
- // Normalize whitespace to single spaces
- text = sWhitespace.matcher(text).replaceAll(" "); //$NON-NLS-1$
-
- // Remove the leading element name. By spec, it must be after the < without
- // any whitespace. If there's nothing left, no attribute has been defined yet.
- // Be sure to keep any whitespace after the initial word if any, as it matters.
- text = sFirstElementWord.matcher(text).replaceFirst(""); //$NON-NLS-1$
-
- // There MUST be space after the element name. If not, the cursor is still
- // defining the element name.
- if (!text.startsWith(" ")) { //$NON-NLS-1$
- return null;
- }
-
- // Remove full attributes:
- // Syntax:
- // name = "..." quoted string with all but < and "
- // or:
- // name = '...' quoted string with all but < and '
- String temp;
- do {
- temp = text;
- text = sFirstAttribute.matcher(temp).replaceFirst(""); //$NON-NLS-1$
- } while(!temp.equals(text));
-
- IRegion lineInfo = document.getLineInformationOfOffset(originalOffset);
- int lineStart = lineInfo.getOffset();
- String line = document.get(lineStart, lineInfo.getLength());
- int cursorColumn = originalOffset - lineStart;
- int prefixLength = originalOffset - prefixStartOffset;
-
- // Now we're left with 3 cases:
- // - nothing: either there is no attribute definition or the cursor located after
- // a completed attribute definition.
- // - a string with no =: the user is writing an attribute name. This case can be
- // merged with the previous one.
- // - string with an = sign, optionally followed by a quote (' or "): the user is
- // writing the value of the attribute.
- int posEqual = text.indexOf('=');
- if (posEqual == -1) {
- info.isInValue = false;
- info.name = text.trim();
-
- // info.name is currently just the prefix of the attribute name.
- // Look at the text buffer to find the complete name (since we need
- // to know its bounds in order to replace it when a different attribute
- // that matches this prefix is chosen)
- int nameStart = cursorColumn;
- for (int nameEnd = nameStart; nameEnd < line.length(); nameEnd++) {
- char c = line.charAt(nameEnd);
- if (!(Character.isLetter(c) || c == ':' || c == '_')) {
- String nameSuffix = line.substring(nameStart, nameEnd);
- info.name = text.trim() + nameSuffix;
- break;
- }
- }
-
- info.replaceLength = info.name.length() - prefixLength;
-
- if (info.name.length() == 0 && originalOffset > 0) {
- // Ensure that attribute names are properly separated
- char prevChar = extractChar(viewer, originalOffset - 1);
- if (prevChar == '"' || prevChar == '\'') {
- // Ensure that the attribute is properly separated from the
- // previous element
- info.needTag = ' ';
- }
- }
- info.skipEndTag = false;
- } else {
- info.isInValue = true;
- info.name = text.substring(0, posEqual).trim();
- info.valuePrefix = text.substring(posEqual + 1);
-
- char quoteChar = '"'; // Does " or ' surround the XML value?
- for (int i = posEqual + 1; i < text.length(); i++) {
- if (!Character.isWhitespace(text.charAt(i))) {
- quoteChar = text.charAt(i);
- break;
- }
- }
-
- // Must compute the complete value
- int valueStart = cursorColumn;
- int valueEnd = valueStart;
- for (; valueEnd < line.length(); valueEnd++) {
- char c = line.charAt(valueEnd);
- if (c == quoteChar) {
- // Make sure this isn't the *opening* quote of the value,
- // which is the case if we invoke code completion with the
- // caret between the = and the opening quote; in that case
- // we consider it value completion, and offer items including
- // the quotes, but we shouldn't bail here thinking we have found
- // the end of the value.
- // Look backwards to make sure we find another " before
- // we find a =
- boolean isFirst = false;
- for (int j = valueEnd - 1; j >= 0; j--) {
- char pc = line.charAt(j);
- if (pc == '=') {
- isFirst = true;
- break;
- } else if (pc == quoteChar) {
- valueStart = j;
- break;
- }
- }
- if (!isFirst) {
- info.skipEndTag = true;
- break;
- }
- }
- }
- int valueEndOffset = valueEnd + lineStart;
- info.replaceLength = valueEndOffset - (prefixStartOffset + prefixLength);
- // Is the caret to the left of the value quote? If so, include it in
- // the replace length.
- int valueStartOffset = valueStart + lineStart;
- if (valueStartOffset == prefixStartOffset && valueEnd > valueStart) {
- info.replaceLength++;
- }
- }
- return info;
- } catch (BadLocationException e) {
- // pass
- }
- }
-
- return null;
- }
-
- /** Returns the root descriptor id to use */
- protected int getRootDescriptorId() {
- return mDescriptorId;
- }
-
- /**
- * Computes (if needed) and returns the root descriptor.
- */
- protected ElementDescriptor getRootDescriptor() {
- if (mRootDescriptor == null) {
- AndroidTargetData data = mEditor.getTargetData();
- if (data != null) {
- IDescriptorProvider descriptorProvider =
- data.getDescriptorProvider(getRootDescriptorId());
-
- if (descriptorProvider != null) {
- mRootDescriptor = new ElementDescriptor("", //$NON-NLS-1$
- descriptorProvider.getRootElementDescriptors());
- }
- }
- }
-
- return mRootDescriptor;
- }
-
- /**
- * Fixed list of dimension units, along with user documentation, for use by
- * {@link #completeSuffix}.
- */
- private static final String[] sDimensionUnits = new String[] {
- UNIT_DP,
- "<b>Density-independent Pixels</b> - an abstract unit that is based on the physical "
- + "density of the screen.",
-
- UNIT_SP,
- "<b>Scale-independent Pixels</b> - this is like the dp unit, but it is also scaled by "
- + "the user's font size preference.",
-
- UNIT_PT,
- "<b>Points</b> - 1/72 of an inch based on the physical size of the screen.",
-
- UNIT_MM,
- "<b>Millimeters</b> - based on the physical size of the screen.",
-
- UNIT_IN,
- "<b>Inches</b> - based on the physical size of the screen.",
-
- UNIT_PX,
- "<b>Pixels</b> - corresponds to actual pixels on the screen. Not recommended.",
- };
-
- /**
- * Fixed list of fractional units, along with user documentation, for use by
- * {@link #completeSuffix}
- */
- private static final String[] sFractionUnits = new String[] {
- "%", //$NON-NLS-1$
- "<b>Fraction</b> - a percentage of the base size",
-
- "%p", //$NON-NLS-1$
- "<b>Fraction</b> - a percentage relative to parent container",
- };
-
- /**
- * Completes suffixes for applicable types (like dimensions and fractions) such that
- * after a dimension number you get completion on unit types like "px".
- */
- private Object[] completeSuffix(Object[] choices, String value, UiAttributeNode currAttrNode) {
- IAttributeInfo attributeInfo = currAttrNode.getDescriptor().getAttributeInfo();
- EnumSet<Format> formats = attributeInfo.getFormats();
- List<Object> suffixes = new ArrayList<Object>();
-
- if (value.length() > 0 && Character.isDigit(value.charAt(0))) {
- boolean hasDimension = formats.contains(Format.DIMENSION);
- boolean hasFraction = formats.contains(Format.FRACTION);
-
- if (hasDimension || hasFraction) {
- // Split up the value into a numeric part (the prefix) and the
- // unit part (the suffix)
- int suffixBegin = 0;
- for (; suffixBegin < value.length(); suffixBegin++) {
- if (!Character.isDigit(value.charAt(suffixBegin))) {
- break;
- }
- }
- String number = value.substring(0, suffixBegin);
- String suffix = value.substring(suffixBegin);
-
- // Add in the matching dimension and/or fraction units, if any
- if (hasDimension) {
- // Each item has two entries in the array of strings: the first odd numbered
- // ones are the unit names and the second even numbered ones are the
- // corresponding descriptions.
- for (int i = 0; i < sDimensionUnits.length; i += 2) {
- String unit = sDimensionUnits[i];
- if (startsWith(unit, suffix)) {
- String description = sDimensionUnits[i + 1];
- suffixes.add(Pair.of(number + unit, description));
- }
- }
-
- // Allow "dip" completion but don't offer it ("dp" is preferred)
- if (startsWith(suffix, "di") || startsWith(suffix, "dip")) { //$NON-NLS-1$ //$NON-NLS-2$
- suffixes.add(Pair.of(number + "dip", "Alternative name for \"dp\"")); //$NON-NLS-1$
- }
- }
- if (hasFraction) {
- for (int i = 0; i < sFractionUnits.length; i += 2) {
- String unit = sFractionUnits[i];
- if (startsWith(unit, suffix)) {
- String description = sFractionUnits[i + 1];
- suffixes.add(Pair.of(number + unit, description));
- }
- }
- }
- }
- }
-
- boolean hasFlag = formats.contains(Format.FLAG);
- if (hasFlag) {
- boolean isDone = false;
- String[] flagValues = attributeInfo.getFlagValues();
- for (String flagValue : flagValues) {
- if (flagValue.equals(value)) {
- isDone = true;
- break;
- }
- }
- if (isDone) {
- // Add in all the new values with a separator of |
- String currentValue = currAttrNode.getCurrentValue();
- for (String flagValue : flagValues) {
- if (currentValue == null || !currentValue.contains(flagValue)) {
- suffixes.add(value + '|' + flagValue);
- }
- }
- }
- }
-
- if (suffixes.size() > 0) {
- // Merge previously added choices (from attribute enums etc) with the new matches
- List<Object> all = new ArrayList<Object>();
- if (choices != null) {
- for (Object s : choices) {
- all.add(s);
- }
- }
- all.addAll(suffixes);
- choices = all.toArray();
- }
-
- return choices;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidDoubleClickStrategy.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidDoubleClickStrategy.java
deleted file mode 100644
index 87164871f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidDoubleClickStrategy.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors;
-
-import static com.android.SdkConstants.PREFIX_RESOURCE_REF;
-import static com.android.SdkConstants.PREFIX_THEME_REF;
-
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.wst.xml.core.internal.regions.DOMRegionContext;
-import org.eclipse.wst.xml.ui.internal.doubleclick.XMLDoubleClickStrategy;
-
-/**
- * Custom version of {@link XMLDoubleClickStrategy} which is smarter about
- * selecting portions of resource references, etc.
- */
-@SuppressWarnings("restriction") // XML API
-public class AndroidDoubleClickStrategy extends XMLDoubleClickStrategy {
- /**
- * Creates a new {@linkplain AndroidDoubleClickStrategy}
- */
- public AndroidDoubleClickStrategy() {
- }
-
- @Override
- protected void processElementDoubleClicked() {
- // Special case: if you click on the local name portion of an attribute pair,
- // select only the local name. For example, if you click anywhere in the "text" region
- // of "android:text", select just the "text" portion.
- if (fTextRegion.getType() == DOMRegionContext.XML_TAG_ATTRIBUTE_NAME) {
- String regionText = fStructuredDocumentRegion.getText(fTextRegion);
- int cursor = fCaretPosition - fStructuredDocumentRegion.getStartOffset(fTextRegion);
- int ns = regionText.indexOf(':');
- if (cursor > ns) {
- int start = ns + 1;
- fTextViewer.setSelectedRange(fStructuredDocumentRegion.getStartOffset(fTextRegion)
- + start, fTextRegion.getTextLength() - start);
- return;
- }
- }
-
- super.processElementDoubleClicked();
- }
-
- @Override
- protected Point getWord(String string, int cursor) {
- if (string == null) {
- return null;
- }
-
- // Default implementation will strip off the surrounding quotes etc:
- Point position = super.getWord(string, cursor);
-
- assert cursor >= position.x && cursor <= position.y;
-
- // Special case: when you click on a resource identifier name, only select the
- // name portion
- if (string.startsWith(PREFIX_RESOURCE_REF, position.x) ||
- string.startsWith(PREFIX_THEME_REF, position.x)) {
- int nameStart = string.indexOf('/', position.x + 1);
- if (nameStart != -1 && nameStart < cursor) {
- position.x = nameStart + 1;
- return position;
- }
- }
-
- // Special case: when you have a dotted name, such as com.android.tools.MyClass,
- // and you click on the last part, select only that part
- int lastDot = string.lastIndexOf('.', cursor);
- if (lastDot >= position.x && lastDot < position.y - 1) {
- int next = string.indexOf('.', cursor);
- if (next == -1 || next > position.y) {
- position.x = lastDot + 1;
- }
- }
-
- return position;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidOutlineConfiguration.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidOutlineConfiguration.java
deleted file mode 100644
index 6061d929c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidOutlineConfiguration.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors;
-
-
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.wst.xml.ui.views.contentoutline.XMLContentOutlineConfiguration;
-
-/**
- * Custom version of {@link XMLContentOutlineConfiguration} which adds in icons and
- * details such as id or name, to the labels.
- */
-public class AndroidOutlineConfiguration extends XMLContentOutlineConfiguration {
- /** Constructs a new {@link AndroidOutlineConfiguration} */
- public AndroidOutlineConfiguration() {
- }
-
- @Override
- public ILabelProvider getLabelProvider(TreeViewer viewer) {
- return new OutlineLabelProvider();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidQuickOutlineConfiguration.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidQuickOutlineConfiguration.java
deleted file mode 100644
index 0a8e9dc12..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidQuickOutlineConfiguration.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors;
-
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.wst.xml.ui.internal.quickoutline.XMLQuickOutlineConfiguration;
-
-/**
- * Custom version of {@link XMLQuickOutlineConfiguration} which adds in icons and
- * details such as id or name, to the labels.
- */
-public class AndroidQuickOutlineConfiguration extends XMLQuickOutlineConfiguration {
- /** Constructs a new {@link AndroidQuickOutlineConfiguration} */
- public AndroidQuickOutlineConfiguration() {
- }
-
- @Override
- public ILabelProvider getLabelProvider() {
- return new OutlineLabelProvider();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidSourceViewerConfig.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidSourceViewerConfig.java
deleted file mode 100644
index b2c10ec3b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidSourceViewerConfig.java
+++ /dev/null
@@ -1,243 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors;
-
-
-import com.android.ide.eclipse.adt.internal.editors.formatting.AndroidXmlFormatter;
-import com.android.ide.eclipse.adt.internal.editors.formatting.AndroidXmlFormattingStrategy;
-
-import org.eclipse.jface.text.DefaultAutoIndentStrategy;
-import org.eclipse.jface.text.IAutoEditStrategy;
-import org.eclipse.jface.text.ITextHover;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
-import org.eclipse.jface.text.contentassist.IContentAssistant;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.contentassist.IContextInformationValidator;
-import org.eclipse.jface.text.formatter.IContentFormatter;
-import org.eclipse.jface.text.formatter.MultiPassContentFormatter;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.wst.sse.core.text.IStructuredPartitions;
-import org.eclipse.wst.xml.core.text.IXMLPartitions;
-import org.eclipse.wst.xml.ui.StructuredTextViewerConfigurationXML;
-import org.eclipse.wst.xml.ui.internal.contentassist.XMLContentAssistProcessor;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Base Source Viewer Configuration for Android resources.
- */
-@SuppressWarnings({"restriction", "deprecation"}) // XMLContentAssistProcessor etc
-public abstract class AndroidSourceViewerConfig extends StructuredTextViewerConfigurationXML {
-
- public AndroidSourceViewerConfig() {
- super();
- }
-
- @Override
- public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
- return super.getContentAssistant(sourceViewer);
- }
-
- /**
- * Returns the IContentAssistProcessor that
- * {@link #getContentAssistProcessors(ISourceViewer, String)} should use
- * for XML and default/unknown partitions.
- *
- * @return An {@link IContentAssistProcessor} or null.
- */
- public abstract IContentAssistProcessor getAndroidContentAssistProcessor(
- ISourceViewer sourceViewer,
- String partitionType);
-
- /**
- * Returns the content assist processors that will be used for content
- * assist in the given source viewer and for the given partition type.
- *
- * @param sourceViewer the source viewer to be configured by this
- * configuration
- * @param partitionType the partition type for which the content assist
- * processors are applicable
- * @return IContentAssistProcessors or null if should not be supported
- */
- @Override
- protected IContentAssistProcessor[] getContentAssistProcessors(
- ISourceViewer sourceViewer, String partitionType) {
- ArrayList<IContentAssistProcessor> processors = new ArrayList<IContentAssistProcessor>();
- if (partitionType == IStructuredPartitions.UNKNOWN_PARTITION ||
- partitionType == IStructuredPartitions.DEFAULT_PARTITION ||
- partitionType == IXMLPartitions.XML_DEFAULT) {
-
- IContentAssistProcessor processor =
- getAndroidContentAssistProcessor(sourceViewer, partitionType);
-
- if (processor != null) {
- processors.add(processor);
- }
- }
-
- IContentAssistProcessor[] others = super.getContentAssistProcessors(sourceViewer,
- partitionType);
- if (others != null && others.length > 0) {
- for (IContentAssistProcessor p : others) {
- // Builtin Eclipse WTP code completion assistant? If so,
- // wrap it with our own filter which hides some unwanted completions.
- if (p instanceof XMLContentAssistProcessor
- // On Eclipse 3.7, XMLContentAssistProcessor is no longer used,
- // and instead org.eclipse.wst.xml.ui.internal.contentassist.
- // XMLStructuredContentAssistProcessor is used - which isn't available
- // at compile time in 3.5.
- || p.getClass().getSimpleName().equals(
- "XMLStructuredContentAssistProcessor")) { //$NON-NLS-1$
- processors.add(new FilteringContentAssistProcessor(p));
- } else {
- processors.add(p);
- }
- }
- }
-
- if (processors.size() > 0) {
- return processors.toArray(new IContentAssistProcessor[processors.size()]);
- } else {
- return null;
- }
- }
-
- @Override
- public ITextHover getTextHover(ISourceViewer sourceViewer, String contentType) {
- // TODO text hover for android xml
- return super.getTextHover(sourceViewer, contentType);
- }
-
- @Override
- public IAutoEditStrategy[] getAutoEditStrategies(
- ISourceViewer sourceViewer, String contentType) {
- IAutoEditStrategy[] strategies = super.getAutoEditStrategies(sourceViewer, contentType);
- List<IAutoEditStrategy> s = new ArrayList<IAutoEditStrategy>(strategies.length + 1);
- s.add(new AndroidXmlAutoEditStrategy());
-
- // Add other registered strategies, except the builtin indentation strategy which is
- // now handled by the above AndroidXmlAutoEditStrategy
- for (IAutoEditStrategy strategy : strategies) {
- if (strategy instanceof DefaultAutoIndentStrategy) {
- continue;
- }
- s.add(strategy);
- }
-
- return s.toArray(new IAutoEditStrategy[s.size()]);
- }
-
- @Override
- public IContentFormatter getContentFormatter(ISourceViewer sourceViewer) {
- IContentFormatter formatter = super.getContentFormatter(sourceViewer);
-
- if (formatter instanceof MultiPassContentFormatter) {
- ((MultiPassContentFormatter) formatter).setMasterStrategy(
- new AndroidXmlFormattingStrategy());
- return formatter;
- } else {
- return new AndroidXmlFormatter();
- }
- }
-
- @Override
- protected Map<String, ?> getHyperlinkDetectorTargets(final ISourceViewer sourceViewer) {
- @SuppressWarnings("unchecked")
- Map<String, ?> targets = super.getHyperlinkDetectorTargets(sourceViewer);
- // If we want to look up more context in our HyperlinkDetector via the
- // getAdapter method, we should place an IAdaptable object into the map here.
- targets.put("com.android.ide.eclipse.xmlCode", null); //$NON-NLS-1$
- return targets;
- }
-
- /**
- * A delegating {@link IContentAssistProcessor} whose purpose is to filter out some
- * default Eclipse XML completions which are distracting in Android XML files
- */
- private static class FilteringContentAssistProcessor implements IContentAssistProcessor {
- private IContentAssistProcessor mDelegate;
-
- public FilteringContentAssistProcessor(IContentAssistProcessor delegate) {
- super();
- mDelegate = delegate;
- }
-
- @Override
- public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
- ICompletionProposal[] result = mDelegate.computeCompletionProposals(viewer, offset);
- if (result == null) {
- return null;
- }
-
- List<ICompletionProposal> proposals =
- new ArrayList<ICompletionProposal>(result.length);
- for (ICompletionProposal proposal : result) {
- String replacement = proposal.getDisplayString();
- if (replacement.charAt(0) == '"' &&
- replacement.charAt(replacement.length() - 1) == '"') {
- // Filter out attribute values. In Android XML files (where there is no DTD
- // etc) the default Eclipse XML code completion simply provides the
- // existing value as a completion. This is often misleading, since if you
- // for example have a typo, completion will show your current (wrong)
- // value as a valid completion.
- } else if (replacement.contains("Namespace") //$NON-NLS-1$
- || replacement.startsWith("XSL ") //$NON-NLS-1$
- || replacement.contains("Schema")) { //$NON-NLS-1$
- // Eclipse adds in a number of namespace and schema related completions which
- // are not usually applicable in our files.
- } else {
- proposals.add(proposal);
- }
- }
-
- if (proposals.size() == result.length) {
- return result;
- } else {
- return proposals.toArray(new ICompletionProposal[proposals.size()]);
- }
- }
-
- @Override
- public IContextInformation[] computeContextInformation(ITextViewer viewer, int offset) {
- return mDelegate.computeContextInformation(viewer, offset);
- }
-
- @Override
- public char[] getCompletionProposalAutoActivationCharacters() {
- return mDelegate.getCompletionProposalAutoActivationCharacters();
- }
-
- @Override
- public char[] getContextInformationAutoActivationCharacters() {
- return mDelegate.getContextInformationAutoActivationCharacters();
- }
-
- @Override
- public IContextInformationValidator getContextInformationValidator() {
- return mDelegate.getContextInformationValidator();
- }
-
- @Override
- public String getErrorMessage() {
- return mDelegate.getErrorMessage();
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidTextEditor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidTextEditor.java
deleted file mode 100644
index 2e60df5bf..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidTextEditor.java
+++ /dev/null
@@ -1,591 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import org.eclipse.core.internal.filebuffers.SynchronizableDocument;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.QualifiedName;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.jface.text.DocumentRewriteSession;
-import org.eclipse.jface.text.DocumentRewriteSessionType;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IDocumentExtension4;
-import org.eclipse.jface.text.IDocumentListener;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
-import org.eclipse.ui.editors.text.TextEditor;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormEditor;
-import org.eclipse.ui.forms.editor.IFormPage;
-import org.eclipse.ui.forms.events.HyperlinkAdapter;
-import org.eclipse.ui.forms.events.HyperlinkEvent;
-import org.eclipse.ui.forms.events.IHyperlinkListener;
-import org.eclipse.ui.forms.widgets.FormText;
-import org.eclipse.ui.internal.browser.WorkbenchBrowserSupport;
-import org.eclipse.ui.part.FileEditorInput;
-import org.eclipse.ui.part.MultiPageEditorPart;
-import org.eclipse.ui.part.WorkbenchPart;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.wst.sse.ui.StructuredTextEditor;
-
-import java.net.MalformedURLException;
-import java.net.URL;
-
-/**
- * Multi-page form editor for Android text files.
- * <p/>
- * It is designed to work with a {@link TextEditor} that will display a text file.
- * <br/>
- * Derived classes must implement createFormPages to create the forms before the
- * source editor. This can be a no-op if desired.
- */
-@SuppressWarnings("restriction")
-public abstract class AndroidTextEditor extends FormEditor implements IResourceChangeListener {
-
- /** Preference name for the current page of this file */
- private static final String PREF_CURRENT_PAGE = "_current_page";
-
- /** Id string used to create the Android SDK browser */
- private static String BROWSER_ID = "android"; //$NON-NLS-1$
-
- /** Page id of the XML source editor, used for switching tabs programmatically */
- public final static String TEXT_EDITOR_ID = "editor_part"; //$NON-NLS-1$
-
- /** Width hint for text fields. Helps the grid layout resize properly on smaller screens */
- public static final int TEXT_WIDTH_HINT = 50;
-
- /** Page index of the text editor (always the last page) */
- private int mTextPageIndex;
-
- /** The text editor */
- private TextEditor mTextEditor;
-
- /** flag set during page creation */
- private boolean mIsCreatingPage = false;
-
- private IDocument mDocument;
-
- /**
- * Creates a form editor.
- */
- public AndroidTextEditor() {
- super();
- }
-
- // ---- Abstract Methods ----
-
- /**
- * Creates the various form pages.
- * <p/>
- * Derived classes must implement this to add their own specific tabs.
- */
- abstract protected void createFormPages();
-
- /**
- * Called by the base class {@link AndroidTextEditor} once all pages (custom form pages
- * as well as text editor page) have been created. This give a chance to deriving
- * classes to adjust behavior once the text page has been created.
- */
- protected void postCreatePages() {
- // Nothing in the base class.
- }
-
- /**
- * Subclasses should override this method to process the new text model.
- * This is called after the document has been edited.
- *
- * The base implementation is empty.
- *
- * @param event Specification of changes applied to document.
- */
- protected void onDocumentChanged(DocumentEvent event) {
- // pass
- }
-
- // ---- Base Class Overrides, Interfaces Implemented ----
-
- /**
- * Creates the pages of the multi-page editor.
- */
- @Override
- protected void addPages() {
- createAndroidPages();
- selectDefaultPage(null /* defaultPageId */);
- }
-
- /**
- * Creates the page for the Android Editors
- */
- protected void createAndroidPages() {
- mIsCreatingPage = true;
- createFormPages();
- createTextEditor();
- createUndoRedoActions();
- postCreatePages();
- mIsCreatingPage = false;
- }
-
- /**
- * Returns whether the editor is currently creating its pages.
- */
- public boolean isCreatingPages() {
- return mIsCreatingPage;
- }
-
- /**
- * Creates undo redo actions for the editor site (so that it works for any page of this
- * multi-page editor) by re-using the actions defined by the {@link TextEditor}
- * (aka the XML text editor.)
- */
- private void createUndoRedoActions() {
- IActionBars bars = getEditorSite().getActionBars();
- if (bars != null) {
- IAction action = mTextEditor.getAction(ActionFactory.UNDO.getId());
- bars.setGlobalActionHandler(ActionFactory.UNDO.getId(), action);
-
- action = mTextEditor.getAction(ActionFactory.REDO.getId());
- bars.setGlobalActionHandler(ActionFactory.REDO.getId(), action);
-
- bars.updateActionBars();
- }
- }
-
- /**
- * Selects the default active page.
- * @param defaultPageId the id of the page to show. If <code>null</code> the editor attempts to
- * find the default page in the properties of the {@link IResource} object being edited.
- */
- protected void selectDefaultPage(String defaultPageId) {
- if (defaultPageId == null) {
- if (getEditorInput() instanceof IFileEditorInput) {
- IFile file = ((IFileEditorInput) getEditorInput()).getFile();
-
- QualifiedName qname = new QualifiedName(AdtPlugin.PLUGIN_ID,
- getClass().getSimpleName() + PREF_CURRENT_PAGE);
- String pageId;
- try {
- pageId = file.getPersistentProperty(qname);
- if (pageId != null) {
- defaultPageId = pageId;
- }
- } catch (CoreException e) {
- // ignored
- }
- }
- }
-
- if (defaultPageId != null) {
- try {
- setActivePage(Integer.parseInt(defaultPageId));
- } catch (Exception e) {
- // We can get NumberFormatException from parseInt but also
- // AssertionError from setActivePage when the index is out of bounds.
- // Generally speaking we just want to ignore any exception and fall back on the
- // first page rather than crash the editor load. Logging the error is enough.
- AdtPlugin.log(e, "Selecting page '%s' in AndroidXmlEditor failed", defaultPageId);
- }
- }
- }
-
- /**
- * Removes all the pages from the editor.
- */
- protected void removePages() {
- int count = getPageCount();
- for (int i = count - 1 ; i >= 0 ; i--) {
- removePage(i);
- }
- }
-
- /**
- * Overrides the parent's setActivePage to be able to switch to the xml editor.
- *
- * If the special pageId TEXT_EDITOR_ID is given, switches to the mTextPageIndex page.
- * This is needed because the editor doesn't actually derive from IFormPage and thus
- * doesn't have the get-by-page-id method. In this case, the method returns null since
- * IEditorPart does not implement IFormPage.
- */
- @Override
- public IFormPage setActivePage(String pageId) {
- if (pageId.equals(TEXT_EDITOR_ID)) {
- super.setActivePage(mTextPageIndex);
- return null;
- } else {
- return super.setActivePage(pageId);
- }
- }
-
-
- /**
- * Notifies this multi-page editor that the page with the given id has been
- * activated. This method is called when the user selects a different tab.
- *
- * @see MultiPageEditorPart#pageChange(int)
- */
- @Override
- protected void pageChange(int newPageIndex) {
- super.pageChange(newPageIndex);
-
- // Do not record page changes during creation of pages
- if (mIsCreatingPage) {
- return;
- }
-
- if (getEditorInput() instanceof IFileEditorInput) {
- IFile file = ((IFileEditorInput) getEditorInput()).getFile();
-
- QualifiedName qname = new QualifiedName(AdtPlugin.PLUGIN_ID,
- getClass().getSimpleName() + PREF_CURRENT_PAGE);
- try {
- file.setPersistentProperty(qname, Integer.toString(newPageIndex));
- } catch (CoreException e) {
- // ignore
- }
- }
- }
-
- /**
- * Notifies this listener that some resource changes
- * are happening, or have already happened.
- *
- * Closes all project files on project close.
- * @see IResourceChangeListener
- */
- @Override
- public void resourceChanged(final IResourceChangeEvent event) {
- if (event.getType() == IResourceChangeEvent.PRE_CLOSE) {
- Display.getDefault().asyncExec(new Runnable() {
- @Override
- public void run() {
- @SuppressWarnings("hiding")
- IWorkbenchPage[] pages = getSite().getWorkbenchWindow().getPages();
- for (int i = 0; i < pages.length; i++) {
- if (((FileEditorInput)mTextEditor.getEditorInput())
- .getFile().getProject().equals(
- event.getResource())) {
- IEditorPart editorPart = pages[i].findEditor(mTextEditor
- .getEditorInput());
- pages[i].closeEditor(editorPart, true);
- }
- }
- }
- });
- }
- }
-
- /**
- * Initializes the editor part with a site and input.
- * <p/>
- * Checks that the input is an instance of {@link IFileEditorInput}.
- *
- * @see FormEditor
- */
- @Override
- public void init(IEditorSite site, IEditorInput editorInput) throws PartInitException {
- if (!(editorInput instanceof IFileEditorInput))
- throw new PartInitException("Invalid Input: Must be IFileEditorInput");
- super.init(site, editorInput);
- }
-
- /**
- * Returns the {@link IFile} matching the editor's input or null.
- * <p/>
- * By construction, the editor input has to be an {@link IFileEditorInput} so it must
- * have an associated {@link IFile}. Null can only be returned if this editor has no
- * input somehow.
- */
- public IFile getFile() {
- if (getEditorInput() instanceof IFileEditorInput) {
- return ((IFileEditorInput) getEditorInput()).getFile();
- }
- return null;
- }
-
- /**
- * Removes attached listeners.
- *
- * @see WorkbenchPart
- */
- @Override
- public void dispose() {
- ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
-
- super.dispose();
- }
-
- /**
- * Commit all dirty pages then saves the contents of the text editor.
- * <p/>
- * This works by committing all data to the XML model and then
- * asking the Structured XML Editor to save the XML.
- *
- * @see IEditorPart
- */
- @Override
- public void doSave(IProgressMonitor monitor) {
- commitPages(true /* onSave */);
-
- // The actual "save" operation is done by the Structured XML Editor
- getEditor(mTextPageIndex).doSave(monitor);
- }
-
- /* (non-Javadoc)
- * Saves the contents of this editor to another object.
- * <p>
- * Subclasses must override this method to implement the open-save-close lifecycle
- * for an editor. For greater details, see <code>IEditorPart</code>
- * </p>
- *
- * @see IEditorPart
- */
- @Override
- public void doSaveAs() {
- commitPages(true /* onSave */);
-
- IEditorPart editor = getEditor(mTextPageIndex);
- editor.doSaveAs();
- setPageText(mTextPageIndex, editor.getTitle());
- setInput(editor.getEditorInput());
- }
-
- /**
- * Commits all dirty pages in the editor. This method should
- * be called as a first step of a 'save' operation.
- * <p/>
- * This is the same implementation as in {@link FormEditor}
- * except it fixes two bugs: a cast to IFormPage is done
- * from page.get(i) <em>before</em> being tested with instanceof.
- * Another bug is that the last page might be a null pointer.
- * <p/>
- * The incorrect casting makes the original implementation crash due
- * to our {@link StructuredTextEditor} not being an {@link IFormPage}
- * so we have to override and duplicate to fix it.
- *
- * @param onSave <code>true</code> if commit is performed as part
- * of the 'save' operation, <code>false</code> otherwise.
- * @since 3.3
- */
- @Override
- public void commitPages(boolean onSave) {
- if (pages != null) {
- for (int i = 0; i < pages.size(); i++) {
- Object page = pages.get(i);
- if (page != null && page instanceof IFormPage) {
- IFormPage form_page = (IFormPage) page;
- IManagedForm managed_form = form_page.getManagedForm();
- if (managed_form != null && managed_form.isDirty()) {
- managed_form.commit(onSave);
- }
- }
- }
- }
- }
-
- /* (non-Javadoc)
- * Returns whether the "save as" operation is supported by this editor.
- * <p>
- * Subclasses must override this method to implement the open-save-close lifecycle
- * for an editor. For greater details, see <code>IEditorPart</code>
- * </p>
- *
- * @see IEditorPart
- */
- @Override
- public boolean isSaveAsAllowed() {
- return false;
- }
-
- // ---- Local methods ----
-
-
- /**
- * Helper method that creates a new hyper-link Listener.
- * Used by derived classes which need active links in {@link FormText}.
- * <p/>
- * This link listener handles two kinds of URLs:
- * <ul>
- * <li> Links starting with "http" are simply sent to a local browser.
- * <li> Links starting with "file:/" are simply sent to a local browser.
- * <li> Links starting with "page:" are expected to be an editor page id to switch to.
- * <li> Other links are ignored.
- * </ul>
- *
- * @return A new hyper-link listener for FormText to use.
- */
- public final IHyperlinkListener createHyperlinkListener() {
- return new HyperlinkAdapter() {
- /**
- * Switch to the page corresponding to the link that has just been clicked.
- * For this purpose, the HREF of the &lt;a&gt; tags above is the page ID to switch to.
- */
- @Override
- public void linkActivated(HyperlinkEvent e) {
- super.linkActivated(e);
- String link = e.data.toString();
- if (link.startsWith("http") || //$NON-NLS-1$
- link.startsWith("file:/")) { //$NON-NLS-1$
- openLinkInBrowser(link);
- } else if (link.startsWith("page:")) { //$NON-NLS-1$
- // Switch to an internal page
- setActivePage(link.substring(5 /* strlen("page:") */));
- }
- }
- };
- }
-
- /**
- * Open the http link into a browser
- *
- * @param link The URL to open in a browser
- */
- private void openLinkInBrowser(String link) {
- try {
- IWorkbenchBrowserSupport wbs = WorkbenchBrowserSupport.getInstance();
- wbs.createBrowser(BROWSER_ID).openURL(new URL(link));
- } catch (PartInitException e1) {
- // pass
- } catch (MalformedURLException e1) {
- // pass
- }
- }
-
- /**
- * Creates the XML source editor.
- * <p/>
- * Memorizes the index page of the source editor (it's always the last page, but the number
- * of pages before can change.)
- * <br/>
- * Retrieves the underlying XML model from the StructuredEditor and attaches a listener to it.
- * Finally triggers modelChanged() on the model listener -- derived classes can use this
- * to initialize the model the first time.
- * <p/>
- * Called only once <em>after</em> createFormPages.
- */
- private void createTextEditor() {
- try {
- mTextEditor = new TextEditor();
- int index = addPage(mTextEditor, getEditorInput());
- mTextPageIndex = index;
- setPageText(index, mTextEditor.getTitle());
-
- IDocumentProvider provider = mTextEditor.getDocumentProvider();
- mDocument = provider.getDocument(getEditorInput());
-
- mDocument.addDocumentListener(new IDocumentListener() {
- @Override
- public void documentChanged(DocumentEvent event) {
- onDocumentChanged(event);
- }
-
- @Override
- public void documentAboutToBeChanged(DocumentEvent event) {
- // ignore
- }
- });
-
-
- } catch (PartInitException e) {
- ErrorDialog.openError(getSite().getShell(),
- "Android Text Editor Error", null, e.getStatus());
- }
- }
-
- /**
- * Gives access to the {@link IDocument} from the {@link TextEditor}, corresponding to
- * the current file input.
- * <p/>
- * All edits should be wrapped in a {@link #wrapRewriteSession(Runnable)}.
- * The actual document instance is a {@link SynchronizableDocument}, which creates a lock
- * around read/set operations. The base API provided by {@link IDocument} provides ways to
- * manipulate the document line per line or as a bulk.
- */
- public IDocument getDocument() {
- return mDocument;
- }
-
- /**
- * Returns the {@link IProject} for the edited file.
- */
- public IProject getProject() {
- if (mTextEditor != null) {
- IEditorInput input = mTextEditor.getEditorInput();
- if (input instanceof FileEditorInput) {
- FileEditorInput fileInput = (FileEditorInput)input;
- IFile inputFile = fileInput.getFile();
-
- if (inputFile != null) {
- return inputFile.getProject();
- }
- }
- }
-
- return null;
- }
-
- /**
- * Runs the given operation in the context of a document RewriteSession.
- * Takes care of properly starting and stopping the operation.
- * <p/>
- * The operation itself should just access {@link #getDocument()} and use the
- * normal document's API to manipulate it.
- *
- * @see #getDocument()
- */
- public void wrapRewriteSession(Runnable operation) {
- if (mDocument instanceof IDocumentExtension4) {
- IDocumentExtension4 doc4 = (IDocumentExtension4) mDocument;
-
- DocumentRewriteSession session = null;
- try {
- session = doc4.startRewriteSession(DocumentRewriteSessionType.UNRESTRICTED_SMALL);
-
- operation.run();
- } catch(IllegalStateException e) {
- AdtPlugin.log(e, "wrapRewriteSession failed");
- e.printStackTrace();
- } finally {
- if (session != null) {
- doc4.stopRewriteSession(session);
- }
- }
-
- } else {
- // Not an IDocumentExtension4? Unlikely. Try the operation anyway.
- operation.run();
- }
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidXmlAutoEditStrategy.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidXmlAutoEditStrategy.java
deleted file mode 100644
index 8a078efc2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidXmlAutoEditStrategy.java
+++ /dev/null
@@ -1,460 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors;
-
-import static org.eclipse.wst.xml.core.internal.regions.DOMRegionContext.XML_CONTENT;
-import static org.eclipse.wst.xml.core.internal.regions.DOMRegionContext.XML_EMPTY_TAG_CLOSE;
-import static org.eclipse.wst.xml.core.internal.regions.DOMRegionContext.XML_END_TAG_OPEN;
-import static org.eclipse.wst.xml.core.internal.regions.DOMRegionContext.XML_TAG_CLOSE;
-import static org.eclipse.wst.xml.core.internal.regions.DOMRegionContext.XML_TAG_NAME;
-import static org.eclipse.wst.xml.core.internal.regions.DOMRegionContext.XML_TAG_OPEN;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.formatting.EclipseXmlFormatPreferences;
-import com.android.utils.Pair;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.DocumentCommand;
-import org.eclipse.jface.text.IAutoEditStrategy;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.ITextEditorExtension3;
-import org.eclipse.wst.sse.core.StructuredModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList;
-
-/**
- * Edit strategy for Android XML files. It attempts a number of edit
- * enhancements:
- * <ul>
- * <li> Auto indentation. The default XML indentation scheme is to just copy the
- * indentation of the previous line. This edit strategy improves on that situation
- * by considering the tag and bracket balance on the current line and using it
- * to determine whether the next line should be indented or use the same
- * indentation as the parent, or even the indentation of an earlier line
- * (when for example the current line closes an element which was started on an
- * earlier line.)
- * <li> Newline handling. In addition to indenting, it can also adjust the following text
- * appropriately when a newline is inserted. For example, it will reformat
- * the following (where | represents the caret position):
- * <pre>
- * {@code <item name="a">|</item>}
- * </pre>
- * into
- * <pre>
- * {@code <item name="a">}
- * |
- * {@code </item>}
- * </pre>
- * </ul>
- * In the future we might consider other editing enhancements here as well, such as
- * refining the comment handling, or reindenting when you type the / of a closing tag,
- * or even making the bracket matcher more resilient.
- */
-@SuppressWarnings("restriction") // XML model
-public class AndroidXmlAutoEditStrategy implements IAutoEditStrategy {
-
- @Override
- public void customizeDocumentCommand(IDocument document, DocumentCommand c) {
- if (!isSmartInsertMode()) {
- return;
- }
-
- if (!(document instanceof IStructuredDocument)) {
- // This shouldn't happen unless this strategy is used on an invalid document
- return;
- }
- IStructuredDocument doc = (IStructuredDocument) document;
-
- // Handle newlines/indentation
- if (c.length == 0 && c.text != null
- && TextUtilities.endsWith(doc.getLegalLineDelimiters(), c.text) != -1) {
-
- IModelManager modelManager = StructuredModelManager.getModelManager();
- IStructuredModel model = modelManager.getModelForRead(doc);
- if (model != null) {
- try {
- final int offset = c.offset;
- int lineStart = findLineStart(doc, offset);
- int textStart = findTextStart(doc, lineStart, offset);
-
- IStructuredDocumentRegion region = doc.getRegionAtCharacterOffset(textStart);
- if (region != null && region.getType().equals(XML_TAG_NAME)) {
- Pair<Integer,Integer> balance = getBalance(doc, textStart, offset);
- int tagBalance = balance.getFirst();
- int bracketBalance = balance.getSecond();
-
- String lineIndent = ""; //$NON-NLS-1$
- if (textStart > lineStart) {
- lineIndent = doc.get(lineStart, textStart - lineStart);
- }
-
- // We only care if tag or bracket balance is greater than 0;
- // we never *dedent* on negative balances
- boolean addIndent = false;
- if (bracketBalance < 0) {
- // Handle
- // <foo
- // ></foo>^
- // and
- // <foo
- // />^
- ITextRegion left = getRegionAt(doc, offset, true /*biasLeft*/);
- if (left != null
- && (left.getType().equals(XML_TAG_CLOSE)
- || left.getType().equals(XML_EMPTY_TAG_CLOSE))) {
-
- // Find the corresponding open tag...
- // The org.eclipse.wst.xml.ui.gotoMatchingTag frequently
- // doesn't work, it just says "No matching brace found"
- // (or I would use that here).
-
- int targetBalance = 0;
- ITextRegion right = getRegionAt(doc, offset, false /*biasLeft*/);
- if (right != null && right.getType().equals(XML_END_TAG_OPEN)) {
- targetBalance = -1;
- }
- int openTag = AndroidXmlCharacterMatcher.findTagBackwards(doc,
- offset, targetBalance);
- if (openTag != -1) {
- // Look up the indentation of the given line
- lineIndent = AndroidXmlEditor.getIndentAtOffset(doc, openTag);
- }
- }
- } else if (tagBalance > 0 || bracketBalance > 0) {
- // Add indentation
- addIndent = true;
- }
-
- StringBuilder sb = new StringBuilder(c.text);
- sb.append(lineIndent);
- String oneIndentUnit = EclipseXmlFormatPreferences.create().getOneIndentUnit();
- if (addIndent) {
- sb.append(oneIndentUnit);
- }
-
- // Handle
- // <foo>^</foo>
- // turning into
- // <foo>
- // ^
- // </foo>
- ITextRegion left = getRegionAt(doc, offset, true /*biasLeft*/);
- ITextRegion right = getRegionAt(doc, offset, false /*biasLeft*/);
- if (left != null && right != null
- && left.getType().equals(XML_TAG_CLOSE)
- && right.getType().equals(XML_END_TAG_OPEN)) {
- // Move end tag
- if (tagBalance > 0 && bracketBalance < 0) {
- sb.append(oneIndentUnit);
- }
- c.caretOffset = offset + sb.length();
- c.shiftsCaret = false;
- sb.append(TextUtilities.getDefaultLineDelimiter(doc));
- sb.append(lineIndent);
- }
- c.text = sb.toString();
- } else if (region != null && region.getType().equals(XML_CONTENT)) {
- // Indenting in text content. If you're in the middle of editing
- // text, just copy the current line indentation.
- // However, if you're editing in leading whitespace (e.g. you press
- // newline on a blank line following say an element) then figure
- // out the indentation as if the newline had been pressed at the
- // end of the element, and insert that amount of indentation.
- // In this case we need to also make sure to subtract any existing
- // whitespace on the current line such that if we have
- //
- // <foo>
- // ^ <bar/>
- // </foo>
- //
- // you end up with
- //
- // <foo>
- //
- // ^<bar/>
- // </foo>
- //
- String text = region.getText();
- int regionStart = region.getStartOffset();
- int delta = offset - regionStart;
- boolean inWhitespacePrefix = true;
- for (int i = 0, n = Math.min(delta, text.length()); i < n; i++) {
- char ch = text.charAt(i);
- if (!Character.isWhitespace(ch)) {
- inWhitespacePrefix = false;
- break;
- }
- }
- if (inWhitespacePrefix) {
- IStructuredDocumentRegion previous = region.getPrevious();
- if (previous != null && previous.getType() == XML_TAG_NAME) {
- ITextRegionList subRegions = previous.getRegions();
- ITextRegion last = subRegions.get(subRegions.size() - 1);
- if (last.getType() == XML_TAG_CLOSE ||
- last.getType() == XML_EMPTY_TAG_CLOSE) {
- // See if the last tag was a closing tag
- boolean wasClose = last.getType() == XML_EMPTY_TAG_CLOSE;
- if (!wasClose) {
- // Search backwards to see if the XML_TAG_CLOSE
- // is the end of an </endtag>
- for (int i = subRegions.size() - 2; i >= 0; i--) {
- ITextRegion current = subRegions.get(i);
- String type = current.getType();
- if (type != XML_TAG_NAME) {
- wasClose = type == XML_END_TAG_OPEN;
- break;
- }
- }
- }
-
- int begin = AndroidXmlCharacterMatcher.findTagBackwards(doc,
- previous.getStartOffset() + last.getStart(), 0);
- int prevLineStart = findLineStart(doc, begin);
- int prevTextStart = findTextStart(doc, prevLineStart, begin);
-
- String lineIndent = ""; //$NON-NLS-1$
- if (prevTextStart > prevLineStart) {
- lineIndent = doc.get(prevLineStart,
- prevTextStart - prevLineStart);
- }
- StringBuilder sb = new StringBuilder(c.text);
- sb.append(lineIndent);
-
- // See if there is whitespace on the insert line that
- // we should also remove
- for (int i = delta, n = text.length(); i < n; i++) {
- char ch = text.charAt(i);
- if (ch == ' ') {
- c.length++;
- } else {
- break;
- }
- }
-
- boolean addIndent = (last.getType() == XML_TAG_CLOSE)
- && !wasClose;
-
- // Is there just whitespace left of this text tag
- // until we reach an end tag?
- boolean whitespaceToEndTag = true;
- for (int i = delta; i < text.length(); i++) {
- char ch = text.charAt(i);
- if (ch == '\n' || !Character.isWhitespace(ch)) {
- whitespaceToEndTag = false;
- break;
- }
- }
- if (whitespaceToEndTag) {
- IStructuredDocumentRegion next = region.getNext();
- if (next != null && next.getType() == XML_TAG_NAME) {
- String nextType = next.getRegions().get(0).getType();
- if (nextType == XML_END_TAG_OPEN) {
- addIndent = false;
- }
- }
- }
-
- if (addIndent) {
- sb.append(EclipseXmlFormatPreferences.create()
- .getOneIndentUnit());
- }
- c.text = sb.toString();
-
- return;
- }
- }
- }
- copyPreviousLineIndentation(doc, c);
- } else {
- copyPreviousLineIndentation(doc, c);
- }
- } catch (BadLocationException e) {
- AdtPlugin.log(e, null);
- } finally {
- model.releaseFromRead();
- }
- }
- }
- }
-
- /**
- * Returns the offset of the start of the line (which might be whitespace)
- *
- * @param document the document
- * @param offset an offset for a character anywhere on the line
- * @return the offset of the first character on the line
- * @throws BadLocationException if the offset is invalid
- */
- public static int findLineStart(IDocument document, int offset) throws BadLocationException {
- offset = Math.max(0, Math.min(offset, document.getLength() - 1));
- IRegion info = document.getLineInformationOfOffset(offset);
- return info.getOffset();
- }
-
- /**
- * Finds the first non-whitespace character on the given line
- *
- * @param document the document to search
- * @param lineStart the offset of the beginning of the line
- * @param lineEnd the offset of the end of the line, or the maximum position on the
- * line to search
- * @return the offset of the first non whitespace character, or the maximum position,
- * whichever is smallest
- * @throws BadLocationException if the offsets are invalid
- */
- public static int findTextStart(IDocument document, int lineStart, int lineEnd)
- throws BadLocationException {
- for (int offset = lineStart; offset < lineEnd; offset++) {
- char c = document.getChar(offset);
- if (c != ' ' && c != '\t') {
- return offset;
- }
- }
-
- return lineEnd;
- }
-
- /**
- * Indent the new line the same way as the current line.
- *
- * @param doc the document to indent in
- * @param command the document command to customize
- * @throws BadLocationException if the offsets are invalid
- */
- private void copyPreviousLineIndentation(IDocument doc, DocumentCommand command)
- throws BadLocationException {
-
- if (command.offset == -1 || doc.getLength() == 0) {
- return;
- }
-
- int lineStart = findLineStart(doc, command.offset);
- int textStart = findTextStart(doc, lineStart, command.offset);
-
- StringBuilder sb = new StringBuilder(command.text);
- if (textStart > lineStart) {
- sb.append(doc.get(lineStart, textStart - lineStart));
- }
-
- command.text = sb.toString();
- }
-
-
- /**
- * Returns the subregion at the given offset, with a bias to the left or a bias to the
- * right. In other words, if | represents the caret position, in the XML
- * {@code <foo>|</bar>} then the subregion with bias left is the closing {@code >} and
- * the subregion with bias right is the opening {@code </}.
- *
- * @param doc the document
- * @param offset the offset in the document
- * @param biasLeft whether we should look at the token on the left or on the right
- * @return the subregion at the given offset, or null if not found
- */
- private static ITextRegion getRegionAt(IStructuredDocument doc, int offset,
- boolean biasLeft) {
- if (biasLeft) {
- offset--;
- }
- IStructuredDocumentRegion region =
- doc.getRegionAtCharacterOffset(offset);
- if (region != null) {
- return region.getRegionAtCharacterOffset(offset);
- }
-
- return null;
- }
-
- /**
- * Returns a pair of (tag-balance,bracket-balance) for the range textStart to offset.
- *
- * @param doc the document
- * @param start the offset of the starting character (inclusive)
- * @param end the offset of the ending character (exclusive)
- * @return the balance of tags and brackets
- */
- private static Pair<Integer, Integer> getBalance(IStructuredDocument doc,
- int start, int end) {
- // Balance of open and closing tags
- // <foo></foo> has tagBalance = 0, <foo> has tagBalance = 1
- int tagBalance = 0;
- // Balance of open and closing brackets
- // <foo attr1="value1"> has bracketBalance = 1, <foo has bracketBalance = 1
- int bracketBalance = 0;
- IStructuredDocumentRegion region = doc.getRegionAtCharacterOffset(start);
-
- if (region != null) {
- boolean inOpenTag = true;
- while (region != null && region.getStartOffset() < end) {
- int regionStart = region.getStartOffset();
- ITextRegionList subRegions = region.getRegions();
- for (int i = 0, n = subRegions.size(); i < n; i++) {
- ITextRegion subRegion = subRegions.get(i);
- int subRegionStart = regionStart + subRegion.getStart();
- int subRegionEnd = regionStart + subRegion.getEnd();
- if (subRegionEnd < start || subRegionStart >= end) {
- continue;
- }
- String type = subRegion.getType();
-
- if (XML_TAG_OPEN.equals(type)) {
- bracketBalance++;
- inOpenTag = true;
- } else if (XML_TAG_CLOSE.equals(type)) {
- bracketBalance--;
- if (inOpenTag) {
- tagBalance++;
- } else {
- tagBalance--;
- }
- } else if (XML_END_TAG_OPEN.equals(type)) {
- bracketBalance++;
- inOpenTag = false;
- } else if (XML_EMPTY_TAG_CLOSE.equals(type)) {
- bracketBalance--;
- }
- }
-
- region = region.getNext();
- }
- }
-
- return Pair.of(tagBalance, bracketBalance);
- }
-
- /**
- * Determine if we're in smart insert mode (if so, don't do any edit magic)
- *
- * @return true if the editor is in smart mode (or if it's an unknown editor type)
- */
- private static boolean isSmartInsertMode() {
- ITextEditor textEditor = AdtUtils.getActiveTextEditor();
- if (textEditor instanceof ITextEditorExtension3) {
- ITextEditorExtension3 editor = (ITextEditorExtension3) textEditor;
- return editor.getInsertMode() == ITextEditorExtension3.SMART_INSERT;
- }
-
- return true;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidXmlCharacterMatcher.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidXmlCharacterMatcher.java
deleted file mode 100644
index 8a12fe03b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidXmlCharacterMatcher.java
+++ /dev/null
@@ -1,238 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors;
-
-import static org.eclipse.wst.xml.core.internal.regions.DOMRegionContext.XML_EMPTY_TAG_CLOSE;
-import static org.eclipse.wst.xml.core.internal.regions.DOMRegionContext.XML_END_TAG_OPEN;
-import static org.eclipse.wst.xml.core.internal.regions.DOMRegionContext.XML_TAG_CLOSE;
-import static org.eclipse.wst.xml.core.internal.regions.DOMRegionContext.XML_TAG_NAME;
-import static org.eclipse.wst.xml.core.internal.regions.DOMRegionContext.XML_TAG_OPEN;
-
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList;
-import org.eclipse.wst.xml.ui.internal.text.XMLDocumentRegionEdgeMatcher;
-
-/**
- * Custom version of the character matcher for XML files which adds the ability to
- * jump between open and close tags in the XML file.
- */
-@SuppressWarnings("restriction")
-public class AndroidXmlCharacterMatcher extends XMLDocumentRegionEdgeMatcher {
- /**
- * Constructs a new character matcher for Android XML files
- */
- public AndroidXmlCharacterMatcher() {
- }
-
- @Override
- public IRegion match(IDocument doc, int offset) {
- if (offset < 0 || offset >= doc.getLength()) {
- return null;
- }
-
- IRegion match = findOppositeTag(doc, offset);
- if (match != null) {
- return match;
- }
-
- return super.match(doc, offset);
- }
-
- private IRegion findOppositeTag(IDocument document, int offset) {
- if (!(document instanceof IStructuredDocument)) {
- return null;
- }
- IStructuredDocument doc = (IStructuredDocument) document;
-
- IStructuredDocumentRegion region = doc.getRegionAtCharacterOffset(offset);
- if (region == null) {
- return null;
- }
-
- ITextRegion subRegion = region.getRegionAtCharacterOffset(offset);
- if (subRegion == null) {
- return null;
- }
- ITextRegionList subRegions = region.getRegions();
- int index = subRegions.indexOf(subRegion);
-
- String type = subRegion.getType();
- boolean isOpenTag = false;
- boolean isCloseTag = false;
-
- if (type.equals(XML_TAG_OPEN)) {
- isOpenTag = true;
- } else if (type.equals(XML_END_TAG_OPEN)) {
- isCloseTag = true;
- } else if (!(type.equals(XML_TAG_CLOSE) || type.equals(XML_TAG_NAME)) &&
- (subRegion.getStart() + region.getStartOffset() == offset)) {
- // Look to the left one character; we may have the case where you're
- // pointing to the right of a tag, e.g.
- // <foo>^text
- offset--;
- region = doc.getRegionAtCharacterOffset(offset);
- if (region == null) {
- return null;
- }
- subRegion = region.getRegionAtCharacterOffset(offset);
- if (subRegion == null) {
- return null;
- }
- type = subRegion.getType();
-
- subRegions = region.getRegions();
- index = subRegions.indexOf(subRegion);
- }
-
- if (type.equals(XML_TAG_CLOSE) || type.equals(XML_TAG_NAME)) {
- for (int i = index; i >= 0; i--) {
- subRegion = subRegions.get(i);
- type = subRegion.getType();
- if (type.equals(XML_TAG_OPEN)) {
- isOpenTag = true;
- break;
- } else if (type.equals(XML_END_TAG_OPEN)) {
- isCloseTag = true;
- break;
- }
- }
- }
-
- if (isOpenTag) {
- // Find closing tag
- int target = findTagForwards(doc, subRegion.getStart() + region.getStartOffset(), 0);
- // Note - there is no point in looking up the whole region for the matching
- // tag, because even if you pass a length greater than 1 here, the paint highlighter
- // will only highlight a single character -- the *last* character of the region,
- // not the whole region itself.
- return new Region(target, 1);
- } else if (isCloseTag) {
- // Find open tag
- int target = findTagBackwards(doc, subRegion.getStart() + region.getStartOffset(), -1);
- return new Region(target, 1);
- }
-
- return null;
- }
-
- /**
- * Finds the corresponding open tag by searching backwards until the tag balance
- * reaches a given target.
- *
- * @param doc the document
- * @param offset the ending offset (where the search begins searching backwards from)
- * @param targetTagBalance the balance to end the search at
- * @return the offset of the beginning of the open tag
- */
- public static int findTagBackwards(IStructuredDocument doc, int offset, int targetTagBalance) {
- // Balance of open and closing tags
- int tagBalance = 0;
- // Balance of open and closing brackets
- IStructuredDocumentRegion region = doc.getRegionAtCharacterOffset(offset);
- if (region != null) {
- boolean inEmptyTag = true;
-
- while (region != null) {
- int regionStart = region.getStartOffset();
- ITextRegionList subRegions = region.getRegions();
- for (int i = subRegions.size() - 1; i >= 0; i--) {
- ITextRegion subRegion = subRegions.get(i);
- int subRegionStart = regionStart + subRegion.getStart();
- if (subRegionStart >= offset) {
- continue;
- }
- String type = subRegion.getType();
-
- // Iterate backwards and keep track of the tag balance such that
- // we can find the corresponding opening tag
-
- if (XML_TAG_OPEN.equals(type)) {
- if (!inEmptyTag) {
- tagBalance--;
- }
- if (tagBalance == targetTagBalance) {
- return subRegionStart;
- }
- } else if (XML_END_TAG_OPEN.equals(type)) {
- tagBalance++;
- } else if (XML_EMPTY_TAG_CLOSE.equals(type)) {
- inEmptyTag = true;
- } else if (XML_TAG_CLOSE.equals(type)) {
- inEmptyTag = false;
- }
- }
-
- region = region.getPrevious();
- }
- }
-
- return -1;
- }
-
- /**
- * Finds the corresponding closing tag by searching forwards until the tag balance
- * reaches a given target.
- *
- * @param doc the document
- * @param start the starting offset (where the search begins searching forwards from)
- * @param targetTagBalance the balance to end the search at
- * @return the offset of the beginning of the closing tag
- */
- public static int findTagForwards(IStructuredDocument doc, int start, int targetTagBalance) {
- int tagBalance = 0;
- IStructuredDocumentRegion region = doc.getRegionAtCharacterOffset(start);
-
- if (region != null) {
- while (region != null) {
- int regionStart = region.getStartOffset();
- ITextRegionList subRegions = region.getRegions();
- for (int i = 0, n = subRegions.size(); i < n; i++) {
- ITextRegion subRegion = subRegions.get(i);
- int subRegionStart = regionStart + subRegion.getStart();
- int subRegionEnd = regionStart + subRegion.getEnd();
- if (subRegionEnd < start) {
- continue;
- }
- String type = subRegion.getType();
-
- if (XML_TAG_OPEN.equals(type)) {
- tagBalance++;
- } else if (XML_END_TAG_OPEN.equals(type)) {
- tagBalance--;
- if (tagBalance == targetTagBalance) {
- return subRegionStart;
- }
- } else if (XML_EMPTY_TAG_CLOSE.equals(type)) {
- tagBalance--;
- if (tagBalance == targetTagBalance) {
- // We don't jump to matching tags within a self-closed tag
- return -1;
- }
- }
- }
-
- region = region.getNext();
- }
- }
-
- return -1;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidXmlEditor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidXmlEditor.java
deleted file mode 100644
index 1d4e133b6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/AndroidXmlEditor.java
+++ /dev/null
@@ -1,1709 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors;
-
-import static org.eclipse.wst.sse.ui.internal.actions.StructuredTextEditorActionConstants.ACTION_NAME_FORMAT_DOCUMENT;
-
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.lint.EclipseLintRunner;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.refactorings.core.RenameResourceXmlTextAction;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk.ITargetChangeListener;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk.TargetChangeListener;
-import com.android.sdklib.IAndroidTarget;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.QualifiedName;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IEditorReference;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.IURIEditorInput;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.browser.IWorkbenchBrowserSupport;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormEditor;
-import org.eclipse.ui.forms.editor.IFormPage;
-import org.eclipse.ui.forms.events.HyperlinkAdapter;
-import org.eclipse.ui.forms.events.HyperlinkEvent;
-import org.eclipse.ui.forms.events.IHyperlinkListener;
-import org.eclipse.ui.forms.widgets.FormText;
-import org.eclipse.ui.ide.IDEActionFactory;
-import org.eclipse.ui.ide.IGotoMarker;
-import org.eclipse.ui.internal.browser.WorkbenchBrowserSupport;
-import org.eclipse.ui.part.MultiPageEditorPart;
-import org.eclipse.ui.part.WorkbenchPart;
-import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
-import org.eclipse.wst.sse.core.StructuredModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IModelStateListener;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.eclipse.wst.sse.ui.StructuredTextEditor;
-import org.eclipse.wst.sse.ui.internal.StructuredTextViewer;
-import org.eclipse.wst.xml.core.internal.document.NodeContainer;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.Collections;
-
-/**
- * Multi-page form editor for Android XML files.
- * <p/>
- * It is designed to work with a {@link StructuredTextEditor} that will display an XML file.
- * <br/>
- * Derived classes must implement createFormPages to create the forms before the
- * source editor. This can be a no-op if desired.
- */
-@SuppressWarnings("restriction") // Uses XML model, which has no non-restricted replacement yet
-public abstract class AndroidXmlEditor extends FormEditor {
-
- /** Icon used for the XML source page. */
- public static final String ICON_XML_PAGE = "editor_page_source"; //$NON-NLS-1$
-
- /** Preference name for the current page of this file */
- private static final String PREF_CURRENT_PAGE = "_current_page"; //$NON-NLS-1$
-
- /** Id string used to create the Android SDK browser */
- private static String BROWSER_ID = "android"; //$NON-NLS-1$
-
- /** Page id of the XML source editor, used for switching tabs programmatically */
- public final static String TEXT_EDITOR_ID = "editor_part"; //$NON-NLS-1$
-
- /** Width hint for text fields. Helps the grid layout resize properly on smaller screens */
- public static final int TEXT_WIDTH_HINT = 50;
-
- /** Page index of the text editor (always the last page) */
- protected int mTextPageIndex;
- /** The text editor */
- private StructuredTextEditor mTextEditor;
- /** Listener for the XML model from the StructuredEditor */
- private XmlModelStateListener mXmlModelStateListener;
- /** Listener to update the root node if the target of the file is changed because of a
- * SDK location change or a project target change */
- private TargetChangeListener mTargetListener = null;
-
- /** flag set during page creation */
- private boolean mIsCreatingPage = false;
-
- /**
- * Flag used to ignore XML model updates. For example, the flag is set during
- * formatting. A format operation should completely preserve the semantics of the XML
- * so the document listeners can use this flag to skip updating the model when edits
- * are observed during a formatting operation
- */
- private boolean mIgnoreXmlUpdate;
-
- /**
- * Flag indicating we're inside {@link #wrapEditXmlModel(Runnable)}.
- * This is a counter, which allows us to nest the edit XML calls.
- * There is no pending operation when the counter is at zero.
- */
- private int mIsEditXmlModelPending;
-
- /**
- * Usually null, but during an editing operation, represents the highest
- * node which should be formatted when the editing operation is complete.
- */
- private UiElementNode mFormatNode;
-
- /**
- * Whether {@link #mFormatNode} should be formatted recursively, or just
- * the node itself (its arguments)
- */
- private boolean mFormatChildren;
-
- /**
- * Creates a form editor.
- * <p/>
- * Some derived classes will want to use {@link #addDefaultTargetListener()}
- * to setup the default listener to monitor SDK target changes. This
- * is no longer the default.
- */
- public AndroidXmlEditor() {
- super();
- }
-
- @Override
- public void init(IEditorSite site, IEditorInput input) throws PartInitException {
- super.init(site, input);
- // Trigger a check to see if the SDK needs to be reloaded (which will
- // invoke onSdkLoaded or ITargetChangeListener asynchronously as needed).
- AdtPlugin.getDefault().refreshSdk();
- }
-
- /**
- * Setups a default {@link ITargetChangeListener} that will call
- * {@link #initUiRootNode(boolean)} when the SDK or the target changes.
- */
- public void addDefaultTargetListener() {
- if (mTargetListener == null) {
- mTargetListener = new TargetChangeListener() {
- @Override
- public IProject getProject() {
- return AndroidXmlEditor.this.getProject();
- }
-
- @Override
- public void reload() {
- commitPages(false /* onSave */);
-
- // recreate the ui root node always
- initUiRootNode(true /*force*/);
- }
- };
- AdtPlugin.getDefault().addTargetListener(mTargetListener);
- }
- }
-
- // ---- Abstract Methods ----
-
- /**
- * Returns the root node of the UI element hierarchy manipulated by the current
- * UI node editor.
- */
- abstract public UiElementNode getUiRootNode();
-
- /**
- * Creates the various form pages.
- * <p/>
- * Derived classes must implement this to add their own specific tabs.
- */
- abstract protected void createFormPages();
-
- /**
- * Called by the base class {@link AndroidXmlEditor} once all pages (custom form pages
- * as well as text editor page) have been created. This give a chance to deriving
- * classes to adjust behavior once the text page has been created.
- */
- protected void postCreatePages() {
- // Nothing in the base class.
- }
-
- /**
- * Creates the initial UI Root Node, including the known mandatory elements.
- * @param force if true, a new UiManifestNode is recreated even if it already exists.
- */
- abstract protected void initUiRootNode(boolean force);
-
- /**
- * Subclasses should override this method to process the new XML Model, which XML
- * root node is given.
- *
- * The base implementation is empty.
- *
- * @param xml_doc The XML document, if available, or null if none exists.
- */
- abstract protected void xmlModelChanged(Document xml_doc);
-
- /**
- * Controls whether XML models are ignored or not.
- *
- * @param ignore when true, ignore all subsequent XML model updates, when false start
- * processing XML model updates again
- */
- public void setIgnoreXmlUpdate(boolean ignore) {
- mIgnoreXmlUpdate = ignore;
- }
-
- /**
- * Returns whether XML model events are ignored or not. This is the case
- * when we are deliberately modifying the document in a way which does not
- * change the semantics (such as formatting), or when we have already
- * directly updated the model ourselves.
- *
- * @return true if XML events should be ignored
- */
- public boolean getIgnoreXmlUpdate() {
- return mIgnoreXmlUpdate;
- }
-
- // ---- Base Class Overrides, Interfaces Implemented ----
-
- @Override
- public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
- Object result = super.getAdapter(adapter);
-
- if (result != null && adapter.equals(IGotoMarker.class) ) {
- final IGotoMarker gotoMarker = (IGotoMarker) result;
- return new IGotoMarker() {
- @Override
- public void gotoMarker(IMarker marker) {
- gotoMarker.gotoMarker(marker);
- try {
- // Lint markers should always jump to XML text
- if (marker.getType().equals(AdtConstants.MARKER_LINT)) {
- IEditorPart editor = AdtUtils.getActiveEditor();
- if (editor instanceof AndroidXmlEditor) {
- AndroidXmlEditor xmlEditor = (AndroidXmlEditor) editor;
- xmlEditor.setActivePage(AndroidXmlEditor.TEXT_EDITOR_ID);
- }
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- }
- };
- }
-
- if (result == null && adapter == IContentOutlinePage.class) {
- return getStructuredTextEditor().getAdapter(adapter);
- }
-
- return result;
- }
-
- /**
- * Creates the pages of the multi-page editor.
- */
- @Override
- protected void addPages() {
- createAndroidPages();
- selectDefaultPage(null /* defaultPageId */);
- }
-
- /**
- * Creates the page for the Android Editors
- */
- public void createAndroidPages() {
- mIsCreatingPage = true;
- createFormPages();
- createTextEditor();
- updateActionBindings();
- postCreatePages();
- mIsCreatingPage = false;
- }
-
- /**
- * Returns whether the editor is currently creating its pages.
- */
- public boolean isCreatingPages() {
- return mIsCreatingPage;
- }
-
- /**
- * {@inheritDoc}
- * <p/>
- * If the page is an instance of {@link IPageImageProvider}, the image returned by
- * by {@link IPageImageProvider#getPageImage()} will be set on the page's tab.
- */
- @Override
- public int addPage(IFormPage page) throws PartInitException {
- int index = super.addPage(page);
- if (page instanceof IPageImageProvider) {
- setPageImage(index, ((IPageImageProvider) page).getPageImage());
- }
- return index;
- }
-
- /**
- * {@inheritDoc}
- * <p/>
- * If the editor is an instance of {@link IPageImageProvider}, the image returned by
- * by {@link IPageImageProvider#getPageImage()} will be set on the page's tab.
- */
- @Override
- public int addPage(IEditorPart editor, IEditorInput input) throws PartInitException {
- int index = super.addPage(editor, input);
- if (editor instanceof IPageImageProvider) {
- setPageImage(index, ((IPageImageProvider) editor).getPageImage());
- }
- return index;
- }
-
- /**
- * Creates undo redo (etc) actions for the editor site (so that it works for any page of this
- * multi-page editor) by re-using the actions defined by the {@link StructuredTextEditor}
- * (aka the XML text editor.)
- */
- protected void updateActionBindings() {
- IActionBars bars = getEditorSite().getActionBars();
- if (bars != null) {
- IAction action = mTextEditor.getAction(ActionFactory.UNDO.getId());
- bars.setGlobalActionHandler(ActionFactory.UNDO.getId(), action);
-
- action = mTextEditor.getAction(ActionFactory.REDO.getId());
- bars.setGlobalActionHandler(ActionFactory.REDO.getId(), action);
-
- bars.setGlobalActionHandler(ActionFactory.DELETE.getId(),
- mTextEditor.getAction(ActionFactory.DELETE.getId()));
- bars.setGlobalActionHandler(ActionFactory.CUT.getId(),
- mTextEditor.getAction(ActionFactory.CUT.getId()));
- bars.setGlobalActionHandler(ActionFactory.COPY.getId(),
- mTextEditor.getAction(ActionFactory.COPY.getId()));
- bars.setGlobalActionHandler(ActionFactory.PASTE.getId(),
- mTextEditor.getAction(ActionFactory.PASTE.getId()));
- bars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(),
- mTextEditor.getAction(ActionFactory.SELECT_ALL.getId()));
- bars.setGlobalActionHandler(ActionFactory.FIND.getId(),
- mTextEditor.getAction(ActionFactory.FIND.getId()));
- bars.setGlobalActionHandler(IDEActionFactory.BOOKMARK.getId(),
- mTextEditor.getAction(IDEActionFactory.BOOKMARK.getId()));
-
- bars.updateActionBars();
- }
- }
-
- /**
- * Clears the action bindings for the editor site.
- */
- protected void clearActionBindings(boolean includeUndoRedo) {
- IActionBars bars = getEditorSite().getActionBars();
- if (bars != null) {
- // For some reason, undo/redo doesn't seem to work in the form editor.
- // This appears to be the case for pure Eclipse form editors too, e.g. see
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=68423
- // However, as a workaround we can use the *text* editor's underlying undo
- // to revert operations being done in the UI, and the form automatically updates.
- // Therefore, to work around this, we simply leave the text editor bindings
- // in place if {@code includeUndoRedo} is not set
- if (includeUndoRedo) {
- bars.setGlobalActionHandler(ActionFactory.UNDO.getId(), null);
- bars.setGlobalActionHandler(ActionFactory.REDO.getId(), null);
- }
- bars.setGlobalActionHandler(ActionFactory.DELETE.getId(), null);
- bars.setGlobalActionHandler(ActionFactory.CUT.getId(), null);
- bars.setGlobalActionHandler(ActionFactory.COPY.getId(), null);
- bars.setGlobalActionHandler(ActionFactory.PASTE.getId(), null);
- bars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), null);
- bars.setGlobalActionHandler(ActionFactory.FIND.getId(), null);
- bars.setGlobalActionHandler(IDEActionFactory.BOOKMARK.getId(), null);
-
- bars.updateActionBars();
- }
- }
-
- /**
- * Selects the default active page.
- * @param defaultPageId the id of the page to show. If <code>null</code> the editor attempts to
- * find the default page in the properties of the {@link IResource} object being edited.
- */
- public void selectDefaultPage(String defaultPageId) {
- if (defaultPageId == null) {
- IFile file = getInputFile();
- if (file != null) {
- QualifiedName qname = new QualifiedName(AdtPlugin.PLUGIN_ID,
- getClass().getSimpleName() + PREF_CURRENT_PAGE);
- String pageId;
- try {
- pageId = file.getPersistentProperty(qname);
- if (pageId != null) {
- defaultPageId = pageId;
- }
- } catch (CoreException e) {
- // ignored
- }
- }
- }
-
- if (defaultPageId != null) {
- try {
- setActivePage(Integer.parseInt(defaultPageId));
- } catch (Exception e) {
- // We can get NumberFormatException from parseInt but also
- // AssertionError from setActivePage when the index is out of bounds.
- // Generally speaking we just want to ignore any exception and fall back on the
- // first page rather than crash the editor load. Logging the error is enough.
- AdtPlugin.log(e, "Selecting page '%s' in AndroidXmlEditor failed", defaultPageId);
- }
- } else if (AdtPrefs.getPrefs().isXmlEditorPreferred(getPersistenceCategory())) {
- setActivePage(mTextPageIndex);
- }
- }
-
- /** The layout editor */
- public static final int CATEGORY_LAYOUT = 1 << 0;
- /** The manifest editor */
- public static final int CATEGORY_MANIFEST = 1 << 1;
- /** Any other XML editor */
- public static final int CATEGORY_OTHER = 1 << 2;
-
- /**
- * Returns the persistence category to use for this editor; this should be
- * one of the {@code CATEGORY_} constants such as {@link #CATEGORY_MANIFEST},
- * {@link #CATEGORY_LAYOUT}, {@link #CATEGORY_OTHER}, ...
- * <p>
- * The persistence category is used to group editors together when it comes
- * to certain types of persistence metadata. For example, whether this type
- * of file was most recently edited graphically or with an XML text editor.
- * We'll open new files in the same text or graphical mode as the last time
- * the user edited a file of the same persistence category.
- * <p>
- * Before we added the persistence category, we had a single boolean flag
- * recording whether the XML files were most recently edited graphically or
- * not. However, this meant that users can't for example prefer to edit
- * Manifest files graphically and string files via XML. By splitting the
- * editors up into categories, we can track the mode at a finer granularity,
- * and still allow similar editors such as those used for animations and
- * colors to be treated the same way.
- *
- * @return the persistence category constant
- */
- protected int getPersistenceCategory() {
- return CATEGORY_OTHER;
- }
-
- /**
- * Removes all the pages from the editor.
- */
- protected void removePages() {
- int count = getPageCount();
- for (int i = count - 1 ; i >= 0 ; i--) {
- removePage(i);
- }
- }
-
- /**
- * Overrides the parent's setActivePage to be able to switch to the xml editor.
- *
- * If the special pageId TEXT_EDITOR_ID is given, switches to the mTextPageIndex page.
- * This is needed because the editor doesn't actually derive from IFormPage and thus
- * doesn't have the get-by-page-id method. In this case, the method returns null since
- * IEditorPart does not implement IFormPage.
- */
- @Override
- public IFormPage setActivePage(String pageId) {
- if (pageId.equals(TEXT_EDITOR_ID)) {
- super.setActivePage(mTextPageIndex);
- return null;
- } else {
- return super.setActivePage(pageId);
- }
- }
-
- /**
- * Notifies this multi-page editor that the page with the given id has been
- * activated. This method is called when the user selects a different tab.
- *
- * @see MultiPageEditorPart#pageChange(int)
- */
- @Override
- protected void pageChange(int newPageIndex) {
- super.pageChange(newPageIndex);
-
- // Do not record page changes during creation of pages
- if (mIsCreatingPage) {
- return;
- }
-
- IFile file = getInputFile();
- if (file != null) {
- QualifiedName qname = new QualifiedName(AdtPlugin.PLUGIN_ID,
- getClass().getSimpleName() + PREF_CURRENT_PAGE);
- try {
- file.setPersistentProperty(qname, Integer.toString(newPageIndex));
- } catch (CoreException e) {
- // ignore
- }
- }
-
- boolean isTextPage = newPageIndex == mTextPageIndex;
- AdtPrefs.getPrefs().setXmlEditorPreferred(getPersistenceCategory(), isTextPage);
- }
-
- /**
- * Returns true if the active page is the editor page
- *
- * @return true if the active page is the editor page
- */
- public boolean isEditorPageActive() {
- return getActivePage() == mTextPageIndex;
- }
-
- /**
- * Returns the {@link IFile} matching the editor's input or null.
- */
- @Nullable
- public IFile getInputFile() {
- IEditorInput input = getEditorInput();
- if (input instanceof IFileEditorInput) {
- return ((IFileEditorInput) input).getFile();
- }
- return null;
- }
-
- /**
- * Removes attached listeners.
- *
- * @see WorkbenchPart
- */
- @Override
- public void dispose() {
- IStructuredModel xml_model = getModelForRead();
- if (xml_model != null) {
- try {
- if (mXmlModelStateListener != null) {
- xml_model.removeModelStateListener(mXmlModelStateListener);
- }
-
- } finally {
- xml_model.releaseFromRead();
- }
- }
-
- if (mTargetListener != null) {
- AdtPlugin.getDefault().removeTargetListener(mTargetListener);
- mTargetListener = null;
- }
-
- super.dispose();
- }
-
- /**
- * Commit all dirty pages then saves the contents of the text editor.
- * <p/>
- * This works by committing all data to the XML model and then
- * asking the Structured XML Editor to save the XML.
- *
- * @see IEditorPart
- */
- @Override
- public void doSave(IProgressMonitor monitor) {
- commitPages(true /* onSave */);
-
- if (AdtPrefs.getPrefs().isFormatOnSave()) {
- IAction action = mTextEditor.getAction(ACTION_NAME_FORMAT_DOCUMENT);
- if (action != null) {
- try {
- mIgnoreXmlUpdate = true;
- action.run();
- } finally {
- mIgnoreXmlUpdate = false;
- }
- }
- }
-
- // The actual "save" operation is done by the Structured XML Editor
- getEditor(mTextPageIndex).doSave(monitor);
-
- // Check for errors on save, if enabled
- if (AdtPrefs.getPrefs().isLintOnSave()) {
- runLint();
- }
- }
-
- /**
- * Tells the editor to start a Lint check.
- * It's up to the caller to check whether this should be done depending on preferences.
- * <p/>
- * The default implementation is to call {@link #startLintJob()}.
- *
- * @return The Job started by {@link EclipseLintRunner} or null if no job was started.
- */
- protected Job runLint() {
- return startLintJob();
- }
-
- /**
- * Utility method that creates a Job to run Lint on the current document.
- * Does not wait for the job to finish - just returns immediately.
- *
- * @return a new job, or null
- * @see EclipseLintRunner#startLint(java.util.List, IResource, IDocument,
- * boolean, boolean)
- */
- @Nullable
- public Job startLintJob() {
- IFile file = getInputFile();
- if (file != null) {
- return EclipseLintRunner.startLint(Collections.singletonList(file), file,
- getStructuredDocument(), false /*fatalOnly*/, false /*show*/);
- }
-
- return null;
- }
-
- /* (non-Javadoc)
- * Saves the contents of this editor to another object.
- * <p>
- * Subclasses must override this method to implement the open-save-close lifecycle
- * for an editor. For greater details, see <code>IEditorPart</code>
- * </p>
- *
- * @see IEditorPart
- */
- @Override
- public void doSaveAs() {
- commitPages(true /* onSave */);
-
- IEditorPart editor = getEditor(mTextPageIndex);
- editor.doSaveAs();
- setPageText(mTextPageIndex, editor.getTitle());
- setInput(editor.getEditorInput());
- }
-
- /**
- * Commits all dirty pages in the editor. This method should
- * be called as a first step of a 'save' operation.
- * <p/>
- * This is the same implementation as in {@link FormEditor}
- * except it fixes two bugs: a cast to IFormPage is done
- * from page.get(i) <em>before</em> being tested with instanceof.
- * Another bug is that the last page might be a null pointer.
- * <p/>
- * The incorrect casting makes the original implementation crash due
- * to our {@link StructuredTextEditor} not being an {@link IFormPage}
- * so we have to override and duplicate to fix it.
- *
- * @param onSave <code>true</code> if commit is performed as part
- * of the 'save' operation, <code>false</code> otherwise.
- * @since 3.3
- */
- @Override
- public void commitPages(boolean onSave) {
- if (pages != null) {
- for (int i = 0; i < pages.size(); i++) {
- Object page = pages.get(i);
- if (page != null && page instanceof IFormPage) {
- IFormPage form_page = (IFormPage) page;
- IManagedForm managed_form = form_page.getManagedForm();
- if (managed_form != null && managed_form.isDirty()) {
- managed_form.commit(onSave);
- }
- }
- }
- }
- }
-
- /* (non-Javadoc)
- * Returns whether the "save as" operation is supported by this editor.
- * <p>
- * Subclasses must override this method to implement the open-save-close lifecycle
- * for an editor. For greater details, see <code>IEditorPart</code>
- * </p>
- *
- * @see IEditorPart
- */
- @Override
- public boolean isSaveAsAllowed() {
- return false;
- }
-
- /**
- * Returns the page index of the text editor (always the last page)
-
- * @return the page index of the text editor (always the last page)
- */
- public int getTextPageIndex() {
- return mTextPageIndex;
- }
-
- // ---- Local methods ----
-
-
- /**
- * Helper method that creates a new hyper-link Listener.
- * Used by derived classes which need active links in {@link FormText}.
- * <p/>
- * This link listener handles two kinds of URLs:
- * <ul>
- * <li> Links starting with "http" are simply sent to a local browser.
- * <li> Links starting with "file:/" are simply sent to a local browser.
- * <li> Links starting with "page:" are expected to be an editor page id to switch to.
- * <li> Other links are ignored.
- * </ul>
- *
- * @return A new hyper-link listener for FormText to use.
- */
- public final IHyperlinkListener createHyperlinkListener() {
- return new HyperlinkAdapter() {
- /**
- * Switch to the page corresponding to the link that has just been clicked.
- * For this purpose, the HREF of the &lt;a&gt; tags above is the page ID to switch to.
- */
- @Override
- public void linkActivated(HyperlinkEvent e) {
- super.linkActivated(e);
- String link = e.data.toString();
- if (link.startsWith("http") || //$NON-NLS-1$
- link.startsWith("file:/")) { //$NON-NLS-1$
- openLinkInBrowser(link);
- } else if (link.startsWith("page:")) { //$NON-NLS-1$
- // Switch to an internal page
- setActivePage(link.substring(5 /* strlen("page:") */));
- }
- }
- };
- }
-
- /**
- * Open the http link into a browser
- *
- * @param link The URL to open in a browser
- */
- private void openLinkInBrowser(String link) {
- try {
- IWorkbenchBrowserSupport wbs = WorkbenchBrowserSupport.getInstance();
- wbs.createBrowser(BROWSER_ID).openURL(new URL(link));
- } catch (PartInitException e1) {
- // pass
- } catch (MalformedURLException e1) {
- // pass
- }
- }
-
- /**
- * Creates the XML source editor.
- * <p/>
- * Memorizes the index page of the source editor (it's always the last page, but the number
- * of pages before can change.)
- * <br/>
- * Retrieves the underlying XML model from the StructuredEditor and attaches a listener to it.
- * Finally triggers modelChanged() on the model listener -- derived classes can use this
- * to initialize the model the first time.
- * <p/>
- * Called only once <em>after</em> createFormPages.
- */
- private void createTextEditor() {
- try {
- mTextEditor = new StructuredTextEditor() {
- @Override
- protected void createActions() {
- super.createActions();
-
- Action action = new RenameResourceXmlTextAction(mTextEditor);
- action.setActionDefinitionId(IJavaEditorActionDefinitionIds.RENAME_ELEMENT);
- setAction(IJavaEditorActionDefinitionIds.RENAME_ELEMENT, action);
- }
- };
- int index = addPage(mTextEditor, getEditorInput());
- mTextPageIndex = index;
- setPageText(index, mTextEditor.getTitle());
- setPageImage(index,
- IconFactory.getInstance().getIcon(ICON_XML_PAGE));
-
- if (!(mTextEditor.getTextViewer().getDocument() instanceof IStructuredDocument)) {
- Status status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "Error opening the Android XML editor. Is the document an XML file?");
- throw new RuntimeException("Android XML Editor Error", new CoreException(status));
- }
-
- IStructuredModel xml_model = getModelForRead();
- if (xml_model != null) {
- try {
- mXmlModelStateListener = new XmlModelStateListener();
- xml_model.addModelStateListener(mXmlModelStateListener);
- mXmlModelStateListener.modelChanged(xml_model);
- } catch (Exception e) {
- AdtPlugin.log(e, "Error while loading editor"); //$NON-NLS-1$
- } finally {
- xml_model.releaseFromRead();
- }
- }
- } catch (PartInitException e) {
- ErrorDialog.openError(getSite().getShell(),
- "Android XML Editor Error", null, e.getStatus());
- }
- }
-
- /**
- * Returns the ISourceViewer associated with the Structured Text editor.
- */
- public final ISourceViewer getStructuredSourceViewer() {
- if (mTextEditor != null) {
- // We can't access mDelegate.getSourceViewer() because it is protected,
- // however getTextViewer simply returns the SourceViewer casted, so we
- // can use it instead.
- return mTextEditor.getTextViewer();
- }
- return null;
- }
-
- /**
- * Return the {@link StructuredTextEditor} associated with this XML editor
- *
- * @return the associated {@link StructuredTextEditor}
- */
- public StructuredTextEditor getStructuredTextEditor() {
- return mTextEditor;
- }
-
- /**
- * Returns the {@link IStructuredDocument} used by the StructuredTextEditor (aka Source
- * Editor) or null if not available.
- */
- public IStructuredDocument getStructuredDocument() {
- if (mTextEditor != null && mTextEditor.getTextViewer() != null) {
- return (IStructuredDocument) mTextEditor.getTextViewer().getDocument();
- }
- return null;
- }
-
- /**
- * Returns a version of the model that has been shared for read.
- * <p/>
- * Callers <em>must</em> call model.releaseFromRead() when done, typically
- * in a try..finally clause.
- *
- * Portability note: this uses getModelManager which is part of wst.sse.core; however
- * the interface returned is part of wst.sse.core.internal.provisional so we can
- * expect it to change in a distant future if they start cleaning their codebase,
- * however unlikely that is.
- *
- * @return The model for the XML document or null if cannot be obtained from the editor
- */
- public IStructuredModel getModelForRead() {
- IStructuredDocument document = getStructuredDocument();
- if (document != null) {
- IModelManager mm = StructuredModelManager.getModelManager();
- if (mm != null) {
- // TODO simplify this by not using the internal IStructuredDocument.
- // Instead we can now use mm.getModelForRead(getFile()).
- // However we must first check that SSE for Eclipse 3.3 or 3.4 has this
- // method. IIRC 3.3 didn't have it.
-
- return mm.getModelForRead(document);
- }
- }
- return null;
- }
-
- /**
- * Returns a version of the model that has been shared for edit.
- * <p/>
- * Callers <em>must</em> call model.releaseFromEdit() when done, typically
- * in a try..finally clause.
- * <p/>
- * Because of this, it is mandatory to use the wrapper
- * {@link #wrapEditXmlModel(Runnable)} which executes a runnable into a
- * properly configured model and then performs whatever cleanup is necessary.
- *
- * @return The model for the XML document or null if cannot be obtained from the editor
- */
- private IStructuredModel getModelForEdit() {
- IStructuredDocument document = getStructuredDocument();
- if (document != null) {
- IModelManager mm = StructuredModelManager.getModelManager();
- if (mm != null) {
- // TODO simplify this by not using the internal IStructuredDocument.
- // Instead we can now use mm.getModelForRead(getFile()).
- // However we must first check that SSE for Eclipse 3.3 or 3.4 has this
- // method. IIRC 3.3 didn't have it.
-
- return mm.getModelForEdit(document);
- }
- }
- return null;
- }
-
- /**
- * Helper class to perform edits on the XML model whilst making sure the
- * model has been prepared to be changed.
- * <p/>
- * It first gets a model for edition using {@link #getModelForEdit()},
- * then calls {@link IStructuredModel#aboutToChangeModel()},
- * then performs the requested action
- * and finally calls {@link IStructuredModel#changedModel()}
- * and {@link IStructuredModel#releaseFromEdit()}.
- * <p/>
- * The method is synchronous. As soon as the {@link IStructuredModel#changedModel()} method
- * is called, XML model listeners will be triggered.
- * <p/>
- * Calls can be nested: only the first outer call will actually start and close the edit
- * session.
- * <p/>
- * This method is <em>not synchronized</em> and is not thread safe.
- * Callers must be using it from the the main UI thread.
- *
- * @param editAction Something that will change the XML.
- */
- public final void wrapEditXmlModel(Runnable editAction) {
- wrapEditXmlModel(editAction, null);
- }
-
- /**
- * Perform any editor-specific hooks after applying an edit. When edits are
- * nested, the hooks will only run after the final top level edit has been
- * performed.
- * <p>
- * Note that the edit hooks are performed outside of the edit lock so
- * the hooks should not perform edits on the model without acquiring
- * a lock first.
- */
- public void runEditHooks() {
- if (!mIgnoreXmlUpdate) {
- // Check for errors, if enabled
- if (AdtPrefs.getPrefs().isLintOnSave()) {
- runLint();
- }
- }
- }
-
- /**
- * Executor which performs the given action under an edit lock (and optionally as a
- * single undo event).
- *
- * @param editAction the action to be executed
- * @param undoLabel if non null, the edit action will be run as a single undo event
- * and the label used as the name of the undoable action
- */
- private final void wrapEditXmlModel(final Runnable editAction, final String undoLabel) {
- Display display = mTextEditor.getSite().getShell().getDisplay();
- if (display.getThread() != Thread.currentThread()) {
- display.syncExec(new Runnable() {
- @Override
- public void run() {
- if (!mTextEditor.getTextViewer().getControl().isDisposed()) {
- wrapEditXmlModel(editAction, undoLabel);
- }
- }
- });
- return;
- }
-
- IStructuredModel model = null;
- int undoReverseCount = 0;
- try {
-
- if (mIsEditXmlModelPending == 0) {
- try {
- model = getModelForEdit();
- if (undoLabel != null) {
- // Run this action as an undoable unit.
- // We have to do it more than once, because in some scenarios
- // Eclipse WTP decides to cancel the current undo command on its
- // own -- see http://code.google.com/p/android/issues/detail?id=15901
- // for one such call chain. By nesting these calls several times
- // we've incrementing the command count such that a couple of
- // cancellations are ignored. Interfering with this mechanism may
- // sound dangerous, but it appears that this undo-termination is
- // done for UI reasons to anticipate what the user wants, and we know
- // that in *our* scenarios we want the entire unit run as a single
- // unit. Here's what the documentation for
- // IStructuredTextUndoManager#forceEndOfPendingCommand says
- // "Normally, the undo manager can figure out the best
- // times when to end a pending command and begin a new
- // one ... to the structure of a structured
- // document. There are times, however, when clients may
- // wish to override those algorithms and end one earlier
- // than normal. The one known case is for multi-page
- // editors. If a user is on one page, and type '123' as
- // attribute value, then click around to other parts of
- // page, or different pages, then return to '123|' and
- // type 456, then "undo" they typically expect the undo
- // to just undo what they just typed, the 456, not the
- // whole attribute value."
- for (int i = 0; i < 4; i++) {
- model.beginRecording(this, undoLabel);
- undoReverseCount++;
- }
- }
- model.aboutToChangeModel();
- } catch (Throwable t) {
- // This is never supposed to happen unless we suddenly don't have a model.
- // If it does, we don't want to even try to modify anyway.
- AdtPlugin.log(t, "XML Editor failed to get model to edit"); //$NON-NLS-1$
- return;
- }
- }
- mIsEditXmlModelPending++;
- editAction.run();
- } finally {
- mIsEditXmlModelPending--;
- if (model != null) {
- try {
- boolean oldIgnore = mIgnoreXmlUpdate;
- try {
- mIgnoreXmlUpdate = true;
-
- if (AdtPrefs.getPrefs().getFormatGuiXml() && mFormatNode != null) {
- if (mFormatNode == getUiRootNode()) {
- reformatDocument();
- } else {
- Node node = mFormatNode.getXmlNode();
- if (node instanceof IndexedRegion) {
- IndexedRegion region = (IndexedRegion) node;
- int begin = region.getStartOffset();
- int end = region.getEndOffset();
-
- if (!mFormatChildren) {
- // This will format just the attribute list
- end = begin + 1;
- }
-
- if (mFormatChildren
- && node == node.getOwnerDocument().getDocumentElement()) {
- reformatDocument();
- } else {
- reformatRegion(begin, end);
- }
- }
- }
- mFormatNode = null;
- mFormatChildren = false;
- }
-
- // Notify the model we're done modifying it. This must *always* be executed.
- model.changedModel();
-
- // Clean up the undo unit. This is done more than once as explained
- // above for beginRecording.
- for (int i = 0; i < undoReverseCount; i++) {
- model.endRecording(this);
- }
- } finally {
- mIgnoreXmlUpdate = oldIgnore;
- }
- } catch (Exception e) {
- AdtPlugin.log(e, "Failed to clean up undo unit");
- }
- model.releaseFromEdit();
-
- if (mIsEditXmlModelPending < 0) {
- AdtPlugin.log(IStatus.ERROR,
- "wrapEditXmlModel finished with invalid nested counter==%1$d", //$NON-NLS-1$
- mIsEditXmlModelPending);
- mIsEditXmlModelPending = 0;
- }
-
- runEditHooks();
-
- // Notify listeners
- IStructuredModel readModel = getModelForRead();
- if (readModel != null) {
- try {
- mXmlModelStateListener.modelChanged(readModel);
- } catch (Exception e) {
- AdtPlugin.log(e, "Error while notifying changes"); //$NON-NLS-1$
- } finally {
- readModel.releaseFromRead();
- }
- }
- }
- }
- }
-
- /**
- * Does this editor participate in the "format GUI editor changes" option?
- *
- * @return true if this editor supports automatically formatting XML
- * affected by GUI changes
- */
- public boolean supportsFormatOnGuiEdit() {
- return false;
- }
-
- /**
- * Mark the given node as needing to be formatted when the current edits are
- * done, provided the user has turned that option on (see
- * {@link AdtPrefs#getFormatGuiXml()}).
- *
- * @param node the node to be scheduled for formatting
- * @param attributesOnly if true, only update the attributes list of the
- * node, otherwise update the node recursively (e.g. all children
- * too)
- */
- public void scheduleNodeReformat(UiElementNode node, boolean attributesOnly) {
- if (!supportsFormatOnGuiEdit()) {
- return;
- }
-
- if (node == mFormatNode) {
- if (!attributesOnly) {
- mFormatChildren = true;
- }
- } else if (mFormatNode == null) {
- mFormatNode = node;
- mFormatChildren = !attributesOnly;
- } else {
- if (mFormatNode.isAncestorOf(node)) {
- mFormatChildren = true;
- } else if (node.isAncestorOf(mFormatNode)) {
- mFormatNode = node;
- mFormatChildren = true;
- } else {
- // Two independent nodes; format their closest common ancestor.
- // Later we could consider having a small number of independent nodes
- // and formatting those, and only switching to formatting the common ancestor
- // when the number of individual nodes gets large.
- mFormatChildren = true;
- mFormatNode = UiElementNode.getCommonAncestor(mFormatNode, node);
- }
- }
- }
-
- /**
- * Creates an "undo recording" session by calling the undoableAction runnable
- * under an undo session.
- * <p/>
- * This also automatically starts an edit XML session, as if
- * {@link #wrapEditXmlModel(Runnable)} had been called.
- * <p>
- * You can nest several calls to {@link #wrapUndoEditXmlModel(String, Runnable)}, only one
- * recording session will be created.
- *
- * @param label The label for the undo operation. Can be null. Ideally we should really try
- * to put something meaningful if possible.
- * @param undoableAction the action to be run as a single undoable unit
- */
- public void wrapUndoEditXmlModel(String label, Runnable undoableAction) {
- assert label != null : "All undoable actions should have a label";
- wrapEditXmlModel(undoableAction, label == null ? "" : label); //$NON-NLS-1$
- }
-
- /**
- * Returns true when the runnable of {@link #wrapEditXmlModel(Runnable)} is currently
- * being executed. This means it is safe to actually edit the XML model.
- *
- * @return true if the XML model is already locked for edits
- */
- public boolean isEditXmlModelPending() {
- return mIsEditXmlModelPending > 0;
- }
-
- /**
- * Returns the XML {@link Document} or null if we can't get it
- */
- public final Document getXmlDocument(IStructuredModel model) {
- if (model == null) {
- AdtPlugin.log(IStatus.WARNING, "Android Editor: No XML model for root node."); //$NON-NLS-1$
- return null;
- }
-
- if (model instanceof IDOMModel) {
- IDOMModel dom_model = (IDOMModel) model;
- return dom_model.getDocument();
- }
- return null;
- }
-
- /**
- * Returns the {@link IProject} for the edited file.
- */
- @Nullable
- public IProject getProject() {
- IFile file = getInputFile();
- if (file != null) {
- return file.getProject();
- }
-
- return null;
- }
-
- /**
- * Returns the {@link AndroidTargetData} for the edited file.
- */
- @Nullable
- public AndroidTargetData getTargetData() {
- IProject project = getProject();
- if (project != null) {
- Sdk currentSdk = Sdk.getCurrent();
- if (currentSdk != null) {
- IAndroidTarget target = currentSdk.getTarget(project);
-
- if (target != null) {
- return currentSdk.getTargetData(target);
- }
- }
- }
-
- IEditorInput input = getEditorInput();
- if (input instanceof IURIEditorInput) {
- IURIEditorInput urlInput = (IURIEditorInput) input;
- Sdk currentSdk = Sdk.getCurrent();
- if (currentSdk != null) {
- try {
- String path = AdtUtils.getFile(urlInput.getURI().toURL()).getPath();
- IAndroidTarget[] targets = currentSdk.getTargets();
- for (IAndroidTarget target : targets) {
- if (path.startsWith(target.getLocation())) {
- return currentSdk.getTargetData(target);
- }
- }
- } catch (MalformedURLException e) {
- // File might be in some other weird random location we can't
- // handle: Just ignore these
- }
- }
- }
-
- return null;
- }
-
- /**
- * Shows the editor range corresponding to the given XML node. This will
- * front the editor and select the text range.
- *
- * @param xmlNode The DOM node to be shown. The DOM node should be an XML
- * node from the existing XML model used by the structured XML
- * editor; it will not do attribute matching to find a
- * "corresponding" element in the document from some foreign DOM
- * tree.
- * @return True if the node was shown.
- */
- public boolean show(Node xmlNode) {
- if (xmlNode instanceof IndexedRegion) {
- IndexedRegion region = (IndexedRegion)xmlNode;
-
- IEditorPart textPage = getEditor(mTextPageIndex);
- if (textPage instanceof StructuredTextEditor) {
- StructuredTextEditor editor = (StructuredTextEditor) textPage;
-
- setActivePage(AndroidXmlEditor.TEXT_EDITOR_ID);
-
- // Note - we cannot use region.getLength() because that seems to
- // always return 0.
- int regionLength = region.getEndOffset() - region.getStartOffset();
- editor.selectAndReveal(region.getStartOffset(), regionLength);
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Selects and reveals the given range in the text editor
- *
- * @param start the beginning offset
- * @param length the length of the region to show
- * @param frontTab if true, front the tab, otherwise just make the selection but don't
- * change the active tab
- */
- public void show(int start, int length, boolean frontTab) {
- IEditorPart textPage = getEditor(mTextPageIndex);
- if (textPage instanceof StructuredTextEditor) {
- StructuredTextEditor editor = (StructuredTextEditor) textPage;
- if (frontTab) {
- setActivePage(AndroidXmlEditor.TEXT_EDITOR_ID);
- }
- editor.selectAndReveal(start, length);
- if (frontTab) {
- editor.setFocus();
- }
- }
- }
-
- /**
- * Returns true if this editor has more than one page (usually a graphical view and an
- * editor)
- *
- * @return true if this editor has multiple pages
- */
- public boolean hasMultiplePages() {
- return getPageCount() > 1;
- }
-
- /**
- * Get the XML text directly from the editor.
- *
- * @param xmlNode The node whose XML text we want to obtain.
- * @return The XML representation of the {@link Node}, or null if there was an error.
- */
- public String getXmlText(Node xmlNode) {
- String data = null;
- IStructuredModel model = getModelForRead();
- try {
- IStructuredDocument document = getStructuredDocument();
- if (xmlNode instanceof NodeContainer) {
- // The easy way to get the source of an SSE XML node.
- data = ((NodeContainer) xmlNode).getSource();
- } else if (xmlNode instanceof IndexedRegion && document != null) {
- // Try harder.
- IndexedRegion region = (IndexedRegion) xmlNode;
- int start = region.getStartOffset();
- int end = region.getEndOffset();
-
- if (end > start) {
- data = document.get(start, end - start);
- }
- }
- } catch (BadLocationException e) {
- // the region offset was invalid. ignore.
- } finally {
- model.releaseFromRead();
- }
- return data;
- }
-
- /**
- * Formats the text around the given caret range, using the current Eclipse
- * XML formatter settings.
- *
- * @param begin The starting offset of the range to be reformatted.
- * @param end The ending offset of the range to be reformatted.
- */
- public void reformatRegion(int begin, int end) {
- ISourceViewer textViewer = getStructuredSourceViewer();
-
- // Clamp text range to valid offsets.
- IDocument document = textViewer.getDocument();
- int documentLength = document.getLength();
- end = Math.min(end, documentLength);
- begin = Math.min(begin, end);
-
- if (!AdtPrefs.getPrefs().getUseCustomXmlFormatter()) {
- // Workarounds which only apply to the builtin Eclipse formatter:
- //
- // It turns out the XML formatter does *NOT* format things correctly if you
- // select just a region of text. You *MUST* also include the leading whitespace
- // on the line, or it will dedent all the content to column 0. Therefore,
- // we must figure out the offset of the start of the line that contains the
- // beginning of the tag.
- try {
- IRegion lineInformation = document.getLineInformationOfOffset(begin);
- if (lineInformation != null) {
- int lineBegin = lineInformation.getOffset();
- if (lineBegin != begin) {
- begin = lineBegin;
- } else if (begin > 0) {
- // Trick #2: It turns out that, if an XML element starts in column 0,
- // then the XML formatter will NOT indent it (even if its parent is
- // indented). If you on the other hand include the end of the previous
- // line (the newline), THEN the formatter also correctly inserts the
- // element. Therefore, we adjust the beginning range to include the
- // previous line (if we are not already in column 0 of the first line)
- // in the case where the element starts the line.
- begin--;
- }
- }
- } catch (BadLocationException e) {
- // This cannot happen because we already clamped the offsets
- AdtPlugin.log(e, e.toString());
- }
- }
-
- if (textViewer instanceof StructuredTextViewer) {
- StructuredTextViewer structuredTextViewer = (StructuredTextViewer) textViewer;
- int operation = ISourceViewer.FORMAT;
- boolean canFormat = structuredTextViewer.canDoOperation(operation);
- if (canFormat) {
- StyledText textWidget = textViewer.getTextWidget();
- textWidget.setSelection(begin, end);
-
- boolean oldIgnore = mIgnoreXmlUpdate;
- try {
- // Formatting does not affect the XML model so ignore notifications
- // about model edits from this
- mIgnoreXmlUpdate = true;
- structuredTextViewer.doOperation(operation);
- } finally {
- mIgnoreXmlUpdate = oldIgnore;
- }
-
- textWidget.setSelection(0, 0);
- }
- }
- }
-
- /**
- * Invokes content assist in this editor at the given offset
- *
- * @param offset the offset to invoke content assist at, or -1 to leave
- * caret alone
- */
- public void invokeContentAssist(int offset) {
- ISourceViewer textViewer = getStructuredSourceViewer();
- if (textViewer instanceof StructuredTextViewer) {
- StructuredTextViewer structuredTextViewer = (StructuredTextViewer) textViewer;
- int operation = ISourceViewer.CONTENTASSIST_PROPOSALS;
- boolean allowed = structuredTextViewer.canDoOperation(operation);
- if (allowed) {
- if (offset != -1) {
- StyledText textWidget = textViewer.getTextWidget();
- // Clamp text range to valid offsets.
- IDocument document = textViewer.getDocument();
- int documentLength = document.getLength();
- offset = Math.max(0, Math.min(offset, documentLength));
- textWidget.setSelection(offset, offset);
- }
- structuredTextViewer.doOperation(operation);
- }
- }
- }
-
- /**
- * Formats the XML region corresponding to the given node.
- *
- * @param node The node to be formatted.
- */
- public void reformatNode(Node node) {
- if (mIsCreatingPage) {
- return;
- }
-
- if (node instanceof IndexedRegion) {
- IndexedRegion region = (IndexedRegion) node;
- int begin = region.getStartOffset();
- int end = region.getEndOffset();
- reformatRegion(begin, end);
- }
- }
-
- /**
- * Formats the XML document according to the user's XML formatting settings.
- */
- public void reformatDocument() {
- ISourceViewer textViewer = getStructuredSourceViewer();
- if (textViewer instanceof StructuredTextViewer) {
- StructuredTextViewer structuredTextViewer = (StructuredTextViewer) textViewer;
- int operation = StructuredTextViewer.FORMAT_DOCUMENT;
- boolean canFormat = structuredTextViewer.canDoOperation(operation);
- if (canFormat) {
- boolean oldIgnore = mIgnoreXmlUpdate;
- try {
- // Formatting does not affect the XML model so ignore notifications
- // about model edits from this
- mIgnoreXmlUpdate = true;
- structuredTextViewer.doOperation(operation);
- } finally {
- mIgnoreXmlUpdate = oldIgnore;
- }
- }
- }
- }
-
- /**
- * Returns the indentation String of the given node.
- *
- * @param xmlNode The node whose indentation we want.
- * @return The indent-string of the given node, or "" if the indentation for some reason could
- * not be computed.
- */
- public String getIndent(Node xmlNode) {
- return getIndent(getStructuredDocument(), xmlNode);
- }
-
- /**
- * Returns the indentation String of the given node.
- *
- * @param document The Eclipse document containing the XML
- * @param xmlNode The node whose indentation we want.
- * @return The indent-string of the given node, or "" if the indentation for some reason could
- * not be computed.
- */
- public static String getIndent(IDocument document, Node xmlNode) {
- if (xmlNode instanceof IndexedRegion) {
- IndexedRegion region = (IndexedRegion)xmlNode;
- int startOffset = region.getStartOffset();
- return getIndentAtOffset(document, startOffset);
- }
-
- return ""; //$NON-NLS-1$
- }
-
- /**
- * Returns the indentation String at the line containing the given offset
- *
- * @param document the document containing the offset
- * @param offset The offset of a character on a line whose indentation we seek
- * @return The indent-string of the given node, or "" if the indentation for some
- * reason could not be computed.
- */
- public static String getIndentAtOffset(IDocument document, int offset) {
- try {
- IRegion lineInformation = document.getLineInformationOfOffset(offset);
- if (lineInformation != null) {
- int lineBegin = lineInformation.getOffset();
- if (lineBegin != offset) {
- String prefix = document.get(lineBegin, offset - lineBegin);
-
- // It's possible that the tag whose indentation we seek is not
- // at the beginning of the line. In that case we'll just return
- // the indentation of the line itself.
- for (int i = 0; i < prefix.length(); i++) {
- if (!Character.isWhitespace(prefix.charAt(i))) {
- return prefix.substring(0, i);
- }
- }
-
- return prefix;
- }
- }
- } catch (BadLocationException e) {
- AdtPlugin.log(e, "Could not obtain indentation"); //$NON-NLS-1$
- }
-
- return ""; //$NON-NLS-1$
- }
-
- /**
- * Returns the active {@link AndroidXmlEditor}, provided it matches the given source
- * viewer
- *
- * @param viewer the source viewer to ensure the active editor is associated with
- * @return the active editor provided it matches the given source viewer or null.
- */
- public static AndroidXmlEditor fromTextViewer(ITextViewer viewer) {
- IWorkbenchWindow wwin = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- if (wwin != null) {
- // Try the active editor first.
- IWorkbenchPage page = wwin.getActivePage();
- if (page != null) {
- IEditorPart editor = page.getActiveEditor();
- if (editor instanceof AndroidXmlEditor) {
- ISourceViewer ssviewer =
- ((AndroidXmlEditor) editor).getStructuredSourceViewer();
- if (ssviewer == viewer) {
- return (AndroidXmlEditor) editor;
- }
- }
- }
-
- // If that didn't work, try all the editors
- for (IWorkbenchPage page2 : wwin.getPages()) {
- if (page2 != null) {
- for (IEditorReference editorRef : page2.getEditorReferences()) {
- IEditorPart editor = editorRef.getEditor(false /*restore*/);
- if (editor instanceof AndroidXmlEditor) {
- ISourceViewer ssviewer =
- ((AndroidXmlEditor) editor).getStructuredSourceViewer();
- if (ssviewer == viewer) {
- return (AndroidXmlEditor) editor;
- }
- }
- }
- }
- }
- }
-
- return null;
- }
-
- /** Called when this editor is activated */
- public void activated() {
- if (getActivePage() == mTextPageIndex) {
- updateActionBindings();
- }
- }
-
- /** Called when this editor is deactivated */
- public void deactivated() {
- }
-
- /**
- * Listen to changes in the underlying XML model in the structured editor.
- */
- private class XmlModelStateListener implements IModelStateListener {
-
- /**
- * A model is about to be changed. This typically is initiated by one
- * client of the model, to signal a large change and/or a change to the
- * model's ID or base Location. A typical use might be if a client might
- * want to suspend processing until all changes have been made.
- * <p/>
- * This AndroidXmlEditor implementation of IModelChangedListener is empty.
- */
- @Override
- public void modelAboutToBeChanged(IStructuredModel model) {
- // pass
- }
-
- /**
- * Signals that the changes foretold by modelAboutToBeChanged have been
- * made. A typical use might be to refresh, or to resume processing that
- * was suspended as a result of modelAboutToBeChanged.
- * <p/>
- * This AndroidXmlEditor implementation calls the xmlModelChanged callback.
- */
- @Override
- public void modelChanged(IStructuredModel model) {
- if (mIgnoreXmlUpdate) {
- return;
- }
- xmlModelChanged(getXmlDocument(model));
- }
-
- /**
- * Notifies that a model's dirty state has changed, and passes that state
- * in isDirty. A model becomes dirty when any change is made, and becomes
- * not-dirty when the model is saved.
- * <p/>
- * This AndroidXmlEditor implementation of IModelChangedListener is empty.
- */
- @Override
- public void modelDirtyStateChanged(IStructuredModel model, boolean isDirty) {
- // pass
- }
-
- /**
- * A modelDeleted means the underlying resource has been deleted. The
- * model itself is not removed from model management until all have
- * released it. Note: baseLocation is not (necessarily) changed in this
- * event, but may not be accurate.
- * <p/>
- * This AndroidXmlEditor implementation of IModelChangedListener is empty.
- */
- @Override
- public void modelResourceDeleted(IStructuredModel model) {
- // pass
- }
-
- /**
- * A model has been renamed or copied (as in saveAs..). In the renamed
- * case, the two parameters are the same instance, and only contain the
- * new info for id and base location.
- * <p/>
- * This AndroidXmlEditor implementation of IModelChangedListener is empty.
- */
- @Override
- public void modelResourceMoved(IStructuredModel oldModel, IStructuredModel newModel) {
- // pass
- }
-
- /**
- * This AndroidXmlEditor implementation of IModelChangedListener is empty.
- */
- @Override
- public void modelAboutToBeReinitialized(IStructuredModel structuredModel) {
- // pass
- }
-
- /**
- * This AndroidXmlEditor implementation of IModelChangedListener is empty.
- */
- @Override
- public void modelReinitialized(IStructuredModel structuredModel) {
- // pass
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/CompletionProposal.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/CompletionProposal.java
deleted file mode 100644
index 2d4467799..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/CompletionProposal.java
+++ /dev/null
@@ -1,229 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors;
-
-import static com.android.SdkConstants.XMLNS;
-
-import com.android.ide.common.api.IAttributeInfo;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.IDescriptorProvider;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.TextAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.utils.XmlUtils;
-
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jdt.core.ISourceRange;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.Position;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * Just like {@link org.eclipse.jface.text.contentassist.CompletionProposal},
- * but computes the documentation string lazily since they are typically only
- * displayed for a small subset (the currently focused item) of the available
- * proposals, and producing the strings requires some computation.
- * <p>
- * It also attempts to compute documentation for value strings like
- * ?android:attr/dividerHeight.
- * <p>
- * TODO: Enhance this to compute documentation for additional values, such as
- * the various enum values (which are available in the attrs.xml file, but not
- * in the AttributeInfo objects for each enum value). To do this, I should
- * basically keep around the maps computed by the attrs.xml parser.
- */
-class CompletionProposal implements ICompletionProposal {
- private static final Pattern ATTRIBUTE_PATTERN =
- Pattern.compile("[@?]android:attr/(.*)"); //$NON-NLS-1$
-
- private final AndroidContentAssist mAssist;
- private final Object mChoice;
- private final int mCursorPosition;
- private int mReplacementOffset;
- private final int mReplacementLength;
- private final String mReplacementString;
- private final Image mImage;
- private final String mDisplayString;
- private final IContextInformation mContextInformation;
- private final String mNsPrefix;
- private final String mNsUri;
- private String mAdditionalProposalInfo;
-
- CompletionProposal(AndroidContentAssist assist,
- Object choice, String replacementString, int replacementOffset,
- int replacementLength, int cursorPosition, Image image, String displayString,
- IContextInformation contextInformation, String additionalProposalInfo,
- String nsPrefix, String nsUri) {
- assert replacementString != null;
- assert replacementOffset >= 0;
- assert replacementLength >= 0;
- assert cursorPosition >= 0;
-
- mAssist = assist;
- mChoice = choice;
- mCursorPosition = cursorPosition;
- mReplacementOffset = replacementOffset;
- mReplacementLength = replacementLength;
- mReplacementString = replacementString;
- mImage = image;
- mDisplayString = displayString;
- mContextInformation = contextInformation;
- mAdditionalProposalInfo = additionalProposalInfo;
- mNsPrefix = nsPrefix;
- mNsUri = nsUri;
- }
-
- @Override
- public Point getSelection(IDocument document) {
- return new Point(mReplacementOffset + mCursorPosition, 0);
- }
-
- @Override
- public IContextInformation getContextInformation() {
- return mContextInformation;
- }
-
- @Override
- public Image getImage() {
- return mImage;
- }
-
- @Override
- public String getDisplayString() {
- if (mDisplayString != null) {
- return mDisplayString;
- }
- return mReplacementString;
- }
-
- @Override
- public String getAdditionalProposalInfo() {
- if (mAdditionalProposalInfo == null) {
- if (mChoice instanceof ElementDescriptor) {
- String tooltip = ((ElementDescriptor)mChoice).getTooltip();
- mAdditionalProposalInfo = DescriptorsUtils.formatTooltip(tooltip);
- } else if (mChoice instanceof TextAttributeDescriptor) {
- mAdditionalProposalInfo = ((TextAttributeDescriptor) mChoice).getTooltip();
- } else if (mChoice instanceof String) {
- // Try to produce it lazily for strings like @android
- String value = (String) mChoice;
- Matcher matcher = ATTRIBUTE_PATTERN.matcher(value);
- if (matcher.matches()) {
- String attrName = matcher.group(1);
- AndroidTargetData data = mAssist.getEditor().getTargetData();
- if (data != null) {
- IDescriptorProvider descriptorProvider =
- data.getDescriptorProvider(mAssist.getRootDescriptorId());
- if (descriptorProvider != null) {
- ElementDescriptor[] rootElementDescriptors =
- descriptorProvider.getRootElementDescriptors();
- for (ElementDescriptor elementDesc : rootElementDescriptors) {
- for (AttributeDescriptor desc : elementDesc.getAttributes()) {
- String name = desc.getXmlLocalName();
- if (attrName.equals(name)) {
- IAttributeInfo attributeInfo = desc.getAttributeInfo();
- if (attributeInfo != null) {
- return attributeInfo.getJavaDoc();
- }
- }
- }
- }
- }
- }
-
- }
- } else if (mChoice instanceof IType) {
- IType type = (IType) mChoice;
- try {
- ISourceRange javadocRange = type.getJavadocRange();
- if (javadocRange != null && javadocRange.getLength() > 0) {
- ISourceRange sourceRange = type.getSourceRange();
- if (sourceRange != null) {
- String source = type.getSource();
- int start = javadocRange.getOffset() - sourceRange.getOffset();
- int length = javadocRange.getLength();
- String doc = source.substring(start, start + length);
- return doc;
- }
- }
- return type.getAttachedJavadoc(new NullProgressMonitor());
- } catch (JavaModelException e) {
- AdtPlugin.log(e, null);
- }
- }
- }
-
- return mAdditionalProposalInfo;
- }
-
- @Override
- public void apply(IDocument document) {
- try {
- Position position = new Position(mReplacementOffset);
- document.addPosition(position);
-
- // Ensure that the namespace is defined in the document
- String prefix = mNsPrefix;
- if (mNsUri != null && prefix != null) {
- Document dom = DomUtilities.getDocument(mAssist.getEditor());
- if (dom != null) {
- Element root = dom.getDocumentElement();
- if (root != null) {
- // Is the namespace already defined?
- boolean found = false;
- NamedNodeMap attributes = root.getAttributes();
- for (int i = 0, n = attributes.getLength(); i < n; i++) {
- Attr attribute = (Attr) attributes.item(i);
- String name = attribute.getName();
- if (name.startsWith(XMLNS) && mNsUri.equals(attribute.getValue())) {
- found = true;
- break;
- }
- }
- if (!found) {
- if (prefix.endsWith(":")) { //$NON-NLS-1$
- prefix = prefix.substring(0, prefix.length() - 1);
- }
- XmlUtils.lookupNamespacePrefix(root, mNsUri, prefix, true);
- }
- }
- }
- }
-
- mReplacementOffset = position.getOffset();
- document.removePosition(position);
- document.replace(mReplacementOffset, mReplacementLength, mReplacementString);
- } catch (BadLocationException x) {
- // ignore
- }
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/Hyperlinks.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/Hyperlinks.java
deleted file mode 100644
index 95cec47e6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/Hyperlinks.java
+++ /dev/null
@@ -1,1893 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors;
-
-import static com.android.SdkConstants.ANDROID_PKG;
-import static com.android.SdkConstants.ANDROID_PREFIX;
-import static com.android.SdkConstants.ANDROID_STYLE_RESOURCE_PREFIX;
-import static com.android.SdkConstants.ANDROID_THEME_PREFIX;
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_CLASS;
-import static com.android.SdkConstants.ATTR_CONTEXT;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ATTR_NAME;
-import static com.android.SdkConstants.ATTR_ON_CLICK;
-import static com.android.SdkConstants.CLASS_ACTIVITY;
-import static com.android.SdkConstants.EXT_XML;
-import static com.android.SdkConstants.FD_DOCS;
-import static com.android.SdkConstants.FD_DOCS_REFERENCE;
-import static com.android.SdkConstants.FN_RESOURCE_BASE;
-import static com.android.SdkConstants.FN_RESOURCE_CLASS;
-import static com.android.SdkConstants.NEW_ID_PREFIX;
-import static com.android.SdkConstants.PREFIX_RESOURCE_REF;
-import static com.android.SdkConstants.PREFIX_THEME_REF;
-import static com.android.SdkConstants.STYLE_RESOURCE_PREFIX;
-import static com.android.SdkConstants.TAG_RESOURCES;
-import static com.android.SdkConstants.TAG_STYLE;
-import static com.android.SdkConstants.TOOLS_URI;
-import static com.android.SdkConstants.VIEW;
-import static com.android.SdkConstants.VIEW_FRAGMENT;
-import static com.android.xml.AndroidManifest.ATTRIBUTE_NAME;
-import static com.android.xml.AndroidManifest.ATTRIBUTE_PACKAGE;
-import static com.android.xml.AndroidManifest.NODE_ACTIVITY;
-import static com.android.xml.AndroidManifest.NODE_SERVICE;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.annotations.VisibleForTesting;
-import com.android.ide.common.resources.ResourceFile;
-import com.android.ide.common.resources.ResourceFolder;
-import com.android.ide.common.resources.ResourceRepository;
-import com.android.ide.common.resources.ResourceUrl;
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestEditor;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.resources.ResourceHelper;
-import com.android.ide.eclipse.adt.internal.resources.manager.ProjectResources;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.io.IFileWrapper;
-import com.android.ide.eclipse.adt.io.IFolderWrapper;
-import com.android.io.FileWrapper;
-import com.android.io.IAbstractFile;
-import com.android.io.IAbstractFolder;
-import com.android.resources.ResourceFolderType;
-import com.android.resources.ResourceType;
-import com.android.sdklib.IAndroidTarget;
-import com.android.utils.Pair;
-
-import org.apache.xerces.parsers.DOMParser;
-import org.apache.xerces.xni.Augmentations;
-import org.apache.xerces.xni.NamespaceContext;
-import org.apache.xerces.xni.QName;
-import org.apache.xerces.xni.XMLAttributes;
-import org.apache.xerces.xni.XMLLocator;
-import org.apache.xerces.xni.XNIException;
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jdt.core.Flags;
-import org.eclipse.jdt.core.ICodeAssist;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IMethod;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.core.search.IJavaSearchConstants;
-import org.eclipse.jdt.core.search.IJavaSearchScope;
-import org.eclipse.jdt.core.search.SearchEngine;
-import org.eclipse.jdt.core.search.SearchMatch;
-import org.eclipse.jdt.core.search.SearchParticipant;
-import org.eclipse.jdt.core.search.SearchPattern;
-import org.eclipse.jdt.core.search.SearchRequestor;
-import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.jdt.internal.ui.text.JavaWordFinder;
-import org.eclipse.jdt.ui.JavaUI;
-import org.eclipse.jdt.ui.actions.SelectionDispatchAction;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IStatusLineManager;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextViewer;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.hyperlink.AbstractHyperlinkDetector;
-import org.eclipse.jface.text.hyperlink.IHyperlink;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IEditorReference;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.ui.part.FileEditorInput;
-import org.eclipse.ui.part.MultiPageEditorPart;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.wst.sse.core.StructuredModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion;
-import org.eclipse.wst.sse.ui.StructuredTextEditor;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
-import org.eclipse.wst.xml.core.internal.regions.DOMRegionContext;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * Class containing hyperlink resolvers for XML and Java files to jump to associated
- * resources -- Java Activity and Service classes, XML layout and string declarations,
- * image drawables, etc.
- */
-@SuppressWarnings("restriction")
-public class Hyperlinks {
- private static final String CATEGORY = "category"; //$NON-NLS-1$
- private static final String ACTION = "action"; //$NON-NLS-1$
- private static final String PERMISSION = "permission"; //$NON-NLS-1$
- private static final String USES_PERMISSION = "uses-permission"; //$NON-NLS-1$
- private static final String CATEGORY_PKG_PREFIX = "android.intent.category."; //$NON-NLS-1$
- private static final String ACTION_PKG_PREFIX = "android.intent.action."; //$NON-NLS-1$
- private static final String PERMISSION_PKG_PREFIX = "android.permission."; //$NON-NLS-1$
-
- private Hyperlinks() {
- // Not instantiatable. This is a container class containing shared code
- // for the various inner classes that are actual hyperlink resolvers.
- }
-
- /**
- * Returns whether a string represents a valid fully qualified name for a view class.
- * Does not check for existence.
- */
- @VisibleForTesting
- static boolean isViewClassName(String name) {
- int length = name.length();
- if (length < 2 || name.indexOf('.') == -1) {
- return false;
- }
-
- boolean lastWasDot = true;
- for (int i = 0; i < length; i++) {
- char c = name.charAt(i);
- if (lastWasDot) {
- if (!Character.isJavaIdentifierStart(c)) {
- return false;
- }
- lastWasDot = false;
- } else {
- if (c == '.') {
- lastWasDot = true;
- } else if (!Character.isJavaIdentifierPart(c)) {
- return false;
- }
- }
- }
-
- return !lastWasDot;
- }
-
- /** Determines whether the given attribute <b>name</b> is linkable */
- private static boolean isAttributeNameLink(XmlContext context) {
- // We could potentially allow you to link to builtin Android properties:
- // ANDROID_URI.equals(attribute.getNamespaceURI())
- // and then jump into the res/values/attrs.xml document that is available
- // in the SDK data directory (path found via
- // IAndroidTarget.getPath(IAndroidTarget.ATTRIBUTES)).
- //
- // For now, we're not doing that.
- //
- // We could also allow to jump into custom attributes in custom view
- // classes. Not yet implemented.
-
- return false;
- }
-
- /** Determines whether the given attribute <b>value</b> is linkable */
- private static boolean isAttributeValueLink(XmlContext context) {
- // Everything else here is attribute based
- Attr attribute = context.getAttribute();
- if (attribute == null) {
- return false;
- }
-
- if (isClassAttribute(context) || isOnClickAttribute(context)
- || isManifestName(context) || isStyleAttribute(context)) {
- return true;
- }
-
- String value = attribute.getValue();
- if (value.startsWith(NEW_ID_PREFIX)) {
- // It's a value -declaration-, nowhere else to jump
- // (though we could consider jumping to the R-file; would that
- // be helpful?)
- return !ATTR_ID.equals(attribute.getLocalName());
- }
-
- ResourceUrl resource = ResourceUrl.parse(value);
- if (resource != null) {
- return true;
- }
-
- return false;
- }
-
- /** Determines whether the given element <b>name</b> is linkable */
- private static boolean isElementNameLink(XmlContext context) {
- if (isClassElement(context)) {
- return true;
- }
-
- return false;
- }
-
- /**
- * Returns true if this node/attribute pair corresponds to a manifest reference to
- * an activity.
- */
- private static boolean isActivity(XmlContext context) {
- // Is this an <activity> or <service> in an AndroidManifest.xml file? If so, jump
- // to it
- Attr attribute = context.getAttribute();
- String tagName = context.getElement().getTagName();
- if (NODE_ACTIVITY.equals(tagName) && ATTRIBUTE_NAME.equals(attribute.getLocalName())
- && ANDROID_URI.equals(attribute.getNamespaceURI())) {
- return true;
- }
-
- return false;
- }
-
- /**
- * Returns true if this node/attribute pair corresponds to a manifest android:name reference
- */
- private static boolean isManifestName(XmlContext context) {
- Attr attribute = context.getAttribute();
- if (attribute != null && ATTRIBUTE_NAME.equals(attribute.getLocalName())
- && ANDROID_URI.equals(attribute.getNamespaceURI())) {
- if (getEditor() instanceof ManifestEditor) {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Opens the declaration corresponding to an android:name reference in the
- * AndroidManifest.xml file
- */
- private static boolean openManifestName(IProject project, XmlContext context) {
- if (isActivity(context)) {
- String fqcn = getActivityClassFqcn(context);
- return AdtPlugin.openJavaClass(project, fqcn);
- } else if (isService(context)) {
- String fqcn = getServiceClassFqcn(context);
- return AdtPlugin.openJavaClass(project, fqcn);
- } else if (isBuiltinPermission(context)) {
- String permission = context.getAttribute().getValue();
- // Mutate something like android.permission.ACCESS_CHECKIN_PROPERTIES
- // into relative doc url android/Manifest.permission.html#ACCESS_CHECKIN_PROPERTIES
- assert permission.startsWith(PERMISSION_PKG_PREFIX);
- String relative = "android/Manifest.permission.html#" //$NON-NLS-1$
- + permission.substring(PERMISSION_PKG_PREFIX.length());
-
- URL url = getDocUrl(relative);
- if (url != null) {
- AdtPlugin.openUrl(url);
- return true;
- } else {
- return false;
- }
- } else if (isBuiltinIntent(context)) {
- String intent = context.getAttribute().getValue();
- // Mutate something like android.intent.action.MAIN into
- // into relative doc url android/content/Intent.html#ACTION_MAIN
- String relative;
- if (intent.startsWith(ACTION_PKG_PREFIX)) {
- relative = "android/content/Intent.html#ACTION_" //$NON-NLS-1$
- + intent.substring(ACTION_PKG_PREFIX.length());
- } else if (intent.startsWith(CATEGORY_PKG_PREFIX)) {
- relative = "android/content/Intent.html#CATEGORY_" //$NON-NLS-1$
- + intent.substring(CATEGORY_PKG_PREFIX.length());
- } else {
- return false;
- }
- URL url = getDocUrl(relative);
- if (url != null) {
- AdtPlugin.openUrl(url);
- return true;
- } else {
- return false;
- }
- }
-
- return false;
- }
-
- /** Returns true if this represents a style attribute */
- private static boolean isStyleAttribute(XmlContext context) {
- String tag = context.getElement().getTagName();
- return TAG_STYLE.equals(tag);
- }
-
- /**
- * Returns true if this represents a {@code <view class="foo.bar.Baz">} class
- * attribute, or a {@code <fragment android:name="foo.bar.Baz">} class attribute
- */
- private static boolean isClassAttribute(XmlContext context) {
- Attr attribute = context.getAttribute();
- if (attribute == null) {
- return false;
- }
- String tag = context.getElement().getTagName();
- String attributeName = attribute.getLocalName();
- return ATTR_CLASS.equals(attributeName) && (VIEW.equals(tag) || VIEW_FRAGMENT.equals(tag))
- || ATTR_NAME.equals(attributeName) && VIEW_FRAGMENT.equals(tag)
- || (ATTR_CONTEXT.equals(attributeName)
- && TOOLS_URI.equals(attribute.getNamespaceURI()));
- }
-
- /** Returns true if this represents an onClick attribute specifying a method handler */
- private static boolean isOnClickAttribute(XmlContext context) {
- Attr attribute = context.getAttribute();
- if (attribute == null) {
- return false;
- }
- return ATTR_ON_CLICK.equals(attribute.getLocalName()) && attribute.getValue().length() > 0;
- }
-
- /** Returns true if this represents a {@code <foo.bar.Baz>} custom view class element */
- private static boolean isClassElement(XmlContext context) {
- if (context.getAttribute() != null) {
- // Don't match the outer element if the user is hovering over a specific attribute
- return false;
- }
- // If the element looks like a fully qualified class name (e.g. it's a custom view
- // element) offer it as a link
- String tag = context.getElement().getTagName();
- return isViewClassName(tag);
- }
-
- /** Returns the FQCN for a class declaration at the given context */
- private static String getClassFqcn(XmlContext context) {
- if (isClassAttribute(context)) {
- String value = context.getAttribute().getValue();
- if (!value.isEmpty() && value.charAt(0) == '.') {
- IProject project = getProject();
- if (project != null) {
- ManifestInfo info = ManifestInfo.get(project);
- String pkg = info.getPackage();
- if (pkg != null) {
- value = pkg + value;
- }
- }
- }
- return value;
- } else if (isClassElement(context)) {
- return context.getElement().getTagName();
- }
-
- return null;
- }
-
- /**
- * Returns true if this node/attribute pair corresponds to a manifest reference to
- * an service.
- */
- private static boolean isService(XmlContext context) {
- Attr attribute = context.getAttribute();
- Element node = context.getElement();
-
- // Is this an <activity> or <service> in an AndroidManifest.xml file? If so, jump to it
- String nodeName = node.getNodeName();
- if (NODE_SERVICE.equals(nodeName) && ATTRIBUTE_NAME.equals(attribute.getLocalName())
- && ANDROID_URI.equals(attribute.getNamespaceURI())) {
- return true;
- }
-
- return false;
- }
-
- /**
- * Returns a URL pointing to the Android reference documentation, either installed
- * locally or the one on android.com
- *
- * @param relative a relative url to append to the root url
- * @return a URL pointing to the documentation
- */
- private static URL getDocUrl(String relative) {
- // First try to find locally installed documentation
- File sdkLocation = new File(Sdk.getCurrent().getSdkOsLocation());
- File docs = new File(sdkLocation, FD_DOCS + File.separator + FD_DOCS_REFERENCE);
- try {
- if (docs.exists()) {
- String s = docs.toURI().toURL().toExternalForm();
- if (!s.endsWith("/")) { //$NON-NLS-1$
- s += "/"; //$NON-NLS-1$
- }
- return new URL(s + relative);
- }
- // If not, fallback to the online documentation
- return new URL("http://developer.android.com/reference/" + relative); //$NON-NLS-1$
- } catch (MalformedURLException e) {
- AdtPlugin.log(e, "Can't create URL for %1$s", docs);
- return null;
- }
- }
-
- /** Returns true if the context is pointing to a permission name reference */
- private static boolean isBuiltinPermission(XmlContext context) {
- Attr attribute = context.getAttribute();
- Element node = context.getElement();
-
- // Is this an <activity> or <service> in an AndroidManifest.xml file? If so, jump to it
- String nodeName = node.getNodeName();
- if ((USES_PERMISSION.equals(nodeName) || PERMISSION.equals(nodeName))
- && ATTRIBUTE_NAME.equals(attribute.getLocalName())
- && ANDROID_URI.equals(attribute.getNamespaceURI())) {
- String value = attribute.getValue();
- if (value.startsWith(PERMISSION_PKG_PREFIX)) {
- return true;
- }
- }
-
- return false;
- }
-
- /** Returns true if the context is pointing to an intent reference */
- private static boolean isBuiltinIntent(XmlContext context) {
- Attr attribute = context.getAttribute();
- Element node = context.getElement();
-
- // Is this an <activity> or <service> in an AndroidManifest.xml file? If so, jump to it
- String nodeName = node.getNodeName();
- if ((ACTION.equals(nodeName) || CATEGORY.equals(nodeName))
- && ATTRIBUTE_NAME.equals(attribute.getLocalName())
- && ANDROID_URI.equals(attribute.getNamespaceURI())) {
- String value = attribute.getValue();
- if (value.startsWith(ACTION_PKG_PREFIX) || value.startsWith(CATEGORY_PKG_PREFIX)) {
- return true;
- }
- }
-
- return false;
- }
-
-
- /**
- * Returns the fully qualified class name of an activity referenced by the given
- * AndroidManifest.xml node
- */
- private static String getActivityClassFqcn(XmlContext context) {
- Attr attribute = context.getAttribute();
- Element node = context.getElement();
- StringBuilder sb = new StringBuilder();
- Element root = node.getOwnerDocument().getDocumentElement();
- String pkg = root.getAttribute(ATTRIBUTE_PACKAGE);
- String className = attribute.getValue();
- if (className.startsWith(".")) { //$NON-NLS-1$
- sb.append(pkg);
- } else if (className.indexOf('.') == -1) {
- // According to the <activity> manifest element documentation, this is not
- // valid ( http://developer.android.com/guide/topics/manifest/activity-element.html )
- // but it appears in manifest files and appears to be supported by the runtime
- // so handle this in code as well:
- sb.append(pkg);
- sb.append('.');
- } // else: the class name is already a fully qualified class name
- sb.append(className);
- return sb.toString();
- }
-
- /**
- * Returns the fully qualified class name of a service referenced by the given
- * AndroidManifest.xml node
- */
- private static String getServiceClassFqcn(XmlContext context) {
- // Same logic
- return getActivityClassFqcn(context);
- }
-
- /**
- * Returns the XML tag containing an element description for value items of the given
- * resource type
- *
- * @param type the resource type to query the XML tag name for
- * @return the tag name used for value declarations in XML of resources of the given
- * type
- */
- public static String getTagName(ResourceType type) {
- if (type == ResourceType.ID) {
- // Ids are recorded in <item> tags instead of <id> tags
- return SdkConstants.TAG_ITEM;
- }
-
- return type.getName();
- }
-
- /**
- * Computes the actual exact location to jump to for a given XML context.
- *
- * @param context the XML context to be opened
- * @return true if the request was handled successfully
- */
- private static boolean open(XmlContext context) {
- IProject project = getProject();
- if (project == null) {
- return false;
- }
-
- if (isManifestName(context)) {
- return openManifestName(project, context);
- } else if (isClassElement(context) || isClassAttribute(context)) {
- return AdtPlugin.openJavaClass(project, getClassFqcn(context));
- } else if (isOnClickAttribute(context)) {
- return openOnClickMethod(project, context.getAttribute().getValue());
- } else {
- return false;
- }
- }
-
- /** Opens a path (which may not be in the workspace) */
- private static void openPath(IPath filePath, IRegion region, int offset) {
- IEditorPart sourceEditor = getEditor();
- IWorkbenchPage page = sourceEditor.getEditorSite().getPage();
-
- IFile file = AdtUtils.pathToIFile(filePath);
- if (file != null && file.exists()) {
- try {
- AdtPlugin.openFile(file, region);
- return;
- } catch (PartInitException ex) {
- AdtPlugin.log(ex, "Can't open %$1s", filePath); //$NON-NLS-1$
- }
- } else {
- // It's not a path in the workspace; look externally
- // (this is probably an @android: path)
- if (filePath.isAbsolute()) {
- IFileStore fileStore = EFS.getLocalFileSystem().getStore(filePath);
- if (!fileStore.fetchInfo().isDirectory() && fileStore.fetchInfo().exists()) {
- try {
- IEditorPart target = IDE.openEditorOnFileStore(page, fileStore);
- if (target instanceof MultiPageEditorPart) {
- MultiPageEditorPart part = (MultiPageEditorPart) target;
- IEditorPart[] editors = part.findEditors(target.getEditorInput());
- if (editors != null) {
- for (IEditorPart editor : editors) {
- if (editor instanceof StructuredTextEditor) {
- StructuredTextEditor ste = (StructuredTextEditor) editor;
- part.setActiveEditor(editor);
- ste.selectAndReveal(offset, 0);
- break;
- }
- }
- }
- }
-
- return;
- } catch (PartInitException ex) {
- AdtPlugin.log(ex, "Can't open %$1s", filePath); //$NON-NLS-1$
- }
- }
- }
- }
-
- // Failed: display message to the user
- displayError(String.format("Could not find resource %1$s", filePath));
- }
-
- private static void displayError(String message) {
- // Failed: display message to the user
- IEditorSite editorSite = getEditor().getEditorSite();
- IStatusLineManager status = editorSite.getActionBars().getStatusLineManager();
- status.setErrorMessage(message);
- }
-
- /**
- * Opens a Java method referenced by the given on click attribute method name
- *
- * @param project the project containing the click handler
- * @param method the method name of the on click handler
- * @return true if the method was opened, false otherwise
- */
- public static boolean openOnClickMethod(IProject project, String method) {
- // Search for the method in the Java index, filtering by the required click handler
- // method signature (public and has a single View parameter), and narrowing the scope
- // first to Activity classes, then to the whole workspace.
- final AtomicBoolean success = new AtomicBoolean(false);
- SearchRequestor requestor = new SearchRequestor() {
- @Override
- public void acceptSearchMatch(SearchMatch match) throws CoreException {
- Object element = match.getElement();
- if (element instanceof IMethod) {
- IMethod methodElement = (IMethod) element;
- String[] parameterTypes = methodElement.getParameterTypes();
- if (parameterTypes != null
- && parameterTypes.length == 1
- && ("Qandroid.view.View;".equals(parameterTypes[0]) //$NON-NLS-1$
- || "QView;".equals(parameterTypes[0]))) { //$NON-NLS-1$
- // Check that it's public
- if (Flags.isPublic(methodElement.getFlags())) {
- JavaUI.openInEditor(methodElement);
- success.getAndSet(true);
- }
- }
- }
- }
- };
- try {
- IJavaSearchScope scope = null;
- IType activityType = null;
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
- if (javaProject != null) {
- activityType = javaProject.findType(CLASS_ACTIVITY);
- if (activityType != null) {
- scope = SearchEngine.createHierarchyScope(activityType);
- }
- }
- if (scope == null) {
- scope = SearchEngine.createWorkspaceScope();
- }
-
- SearchParticipant[] participants = new SearchParticipant[] {
- SearchEngine.getDefaultSearchParticipant()
- };
- int matchRule = SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE;
- SearchPattern pattern = SearchPattern.createPattern("*." + method,
- IJavaSearchConstants.METHOD, IJavaSearchConstants.DECLARATIONS, matchRule);
- SearchEngine engine = new SearchEngine();
- engine.search(pattern, participants, scope, requestor, new NullProgressMonitor());
-
- boolean ok = success.get();
- if (!ok && activityType != null) {
- // TODO: Create a project+dependencies scope and search only that scope
-
- // Try searching again with a complete workspace scope this time
- scope = SearchEngine.createWorkspaceScope();
- engine.search(pattern, participants, scope, requestor, new NullProgressMonitor());
-
- // TODO: There could be more than one match; add code to consider them all
- // and pick the most likely candidate and open only that one.
-
- ok = success.get();
- }
- return ok;
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- return false;
- }
-
- /**
- * Returns the current configuration, if the associated UI editor has been initialized
- * and has an associated configuration
- *
- * @return the configuration for this file, or null
- */
- private static FolderConfiguration getConfiguration() {
- IEditorPart editor = getEditor();
- if (editor != null) {
- LayoutEditorDelegate delegate = LayoutEditorDelegate.fromEditor(editor);
- GraphicalEditorPart graphicalEditor =
- delegate == null ? null : delegate.getGraphicalEditor();
-
- if (graphicalEditor != null) {
- return graphicalEditor.getConfiguration();
- } else {
- // TODO: Could try a few more things to get the configuration:
- // (1) try to look at the file.getPersistentProperty(NAME_CONFIG_STATE)
- // which will return previously saved state. This isn't necessary today
- // since no editors seem to be lazily initialized.
- // (2) attempt to use the configuration from any of the other open
- // files, especially files in the same directory as this one.
- }
-
- // Create a configuration from the current file
- IProject project = null;
- IEditorInput editorInput = editor.getEditorInput();
- if (editorInput instanceof FileEditorInput) {
- IFile file = ((FileEditorInput) editorInput).getFile();
- project = file.getProject();
- ProjectResources pr = ResourceManager.getInstance().getProjectResources(project);
- IContainer parent = file.getParent();
- if (parent instanceof IFolder) {
- ResourceFolder resFolder = pr.getResourceFolder((IFolder) parent);
- if (resFolder != null) {
- return resFolder.getConfiguration();
- }
- }
- }
-
- // Might be editing a Java file, where there is no configuration context.
- // Instead look at surrounding files in the workspace and obtain one valid
- // configuration.
- for (IEditorReference reference : editor.getSite().getPage().getEditorReferences()) {
- IEditorPart part = reference.getEditor(false /*restore*/);
-
- LayoutEditorDelegate refDelegate = LayoutEditorDelegate.fromEditor(part);
- if (refDelegate != null) {
- IProject refProject = refDelegate.getEditor().getProject();
- if (project == null || project == refProject) {
- GraphicalEditorPart refGraphicalEditor = refDelegate.getGraphicalEditor();
- if (refGraphicalEditor != null) {
- return refGraphicalEditor.getConfiguration();
- }
- }
- }
- }
- }
-
- return null;
- }
-
- /** Returns the {@link IAndroidTarget} to be used for looking up system resources */
- private static IAndroidTarget getTarget(IProject project) {
- IEditorPart editor = getEditor();
- LayoutEditorDelegate delegate = LayoutEditorDelegate.fromEditor(editor);
- if (delegate != null) {
- GraphicalEditorPart graphicalEditor = delegate.getGraphicalEditor();
- if (graphicalEditor != null) {
- return graphicalEditor.getRenderingTarget();
- }
- }
-
- Sdk currentSdk = Sdk.getCurrent();
- if (currentSdk == null) {
- return null;
- }
-
- return currentSdk.getTarget(project);
- }
-
- /** Return either the project resources or the framework resources (or null) */
- private static ResourceRepository getResources(IProject project, boolean framework) {
- if (framework) {
- IAndroidTarget target = getTarget(project);
-
- if (target == null && project == null && framework) {
- // No current project: probably jumped into some of the framework XML resource
- // files and attempting to jump around. Attempt to figure out which target
- // we're dealing with and continue looking within the same framework.
- IEditorPart editor = getEditor();
- Sdk sdk = Sdk.getCurrent();
- if (sdk != null && editor instanceof AndroidXmlEditor) {
- AndroidTargetData data = ((AndroidXmlEditor) editor).getTargetData();
- if (data != null) {
- return data.getFrameworkResources();
- }
- }
- }
-
- if (target == null) {
- return null;
- }
- AndroidTargetData data = Sdk.getCurrent().getTargetData(target);
- if (data == null) {
- return null;
- }
- return data.getFrameworkResources();
- } else {
- return ResourceManager.getInstance().getProjectResources(project);
- }
- }
-
- /**
- * Finds a definition of an id attribute in layouts. (Ids can also be defined as
- * resources; use {@link #findValueInXml} or {@link #findValueInDocument} to locate it there.)
- */
- private static Pair<IFile, IRegion> findIdDefinition(IProject project, String id) {
- // FIRST look in the same file as the originating request, that's where you usually
- // want to jump
- IFile self = AdtUtils.getActiveFile();
- if (self != null && EXT_XML.equals(self.getFileExtension())) {
- Pair<IFile, IRegion> target = findIdInXml(id, self);
- if (target != null) {
- return target;
- }
- }
-
- // Look in the configuration folder: Search compatible configurations
- ResourceRepository resources = getResources(project, false /* isFramework */);
- FolderConfiguration configuration = getConfiguration();
- if (configuration != null) { // Not the case when searching from Java files for example
- List<ResourceFolder> folders = resources.getFolders(ResourceFolderType.LAYOUT);
- if (folders != null) {
- for (ResourceFolder folder : folders) {
- if (folder.getConfiguration().isMatchFor(configuration)) {
- IAbstractFolder wrapper = folder.getFolder();
- if (wrapper instanceof IFolderWrapper) {
- IFolder iFolder = ((IFolderWrapper) wrapper).getIFolder();
- Pair<IFile, IRegion> target = findIdInFolder(iFolder, id);
- if (target != null) {
- return target;
- }
- }
- }
- }
- return null;
- }
- }
-
- // Ugh. Search ALL layout files in the project!
- List<ResourceFolder> folders = resources.getFolders(ResourceFolderType.LAYOUT);
- if (folders != null) {
- for (ResourceFolder folder : folders) {
- IAbstractFolder wrapper = folder.getFolder();
- if (wrapper instanceof IFolderWrapper) {
- IFolder iFolder = ((IFolderWrapper) wrapper).getIFolder();
- Pair<IFile, IRegion> target = findIdInFolder(iFolder, id);
- if (target != null) {
- return target;
- }
- }
- }
- }
-
- return null;
- }
-
- /**
- * Finds a definition of an id attribute in a particular layout folder.
- */
- private static Pair<IFile, IRegion> findIdInFolder(IContainer f, String id) {
- try {
- // Check XML files in values/
- for (IResource resource : f.members()) {
- if (resource.exists() && !resource.isDerived() && resource instanceof IFile) {
- IFile file = (IFile) resource;
- // Must have an XML extension
- if (EXT_XML.equals(file.getFileExtension())) {
- Pair<IFile, IRegion> target = findIdInXml(id, file);
- if (target != null) {
- return target;
- }
- }
- }
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, ""); //$NON-NLS-1$
- }
-
- return null;
- }
-
- /** Parses the given file and locates a definition of the given resource */
- private static Pair<IFile, IRegion> findValueInXml(
- ResourceType type, String name, IFile file) {
- IStructuredModel model = null;
- try {
- model = StructuredModelManager.getModelManager().getExistingModelForRead(file);
- if (model == null) {
- // There is no open or cached model for the file; see if the file looks
- // like it's interesting (content contains the String name we are looking for)
- if (AdtPlugin.fileContains(file, name)) {
- // Yes, so parse content
- model = StructuredModelManager.getModelManager().getModelForRead(file);
- }
- }
- if (model instanceof IDOMModel) {
- IDOMModel domModel = (IDOMModel) model;
- Document document = domModel.getDocument();
- return findValueInDocument(type, name, file, document);
- }
- } catch (IOException e) {
- AdtPlugin.log(e, "Can't parse %1$s", file); //$NON-NLS-1$
- } catch (CoreException e) {
- AdtPlugin.log(e, "Can't parse %1$s", file); //$NON-NLS-1$
- } finally {
- if (model != null) {
- model.releaseFromRead();
- }
- }
-
- return null;
- }
-
- /** Looks within an XML DOM document for the given resource name and returns it */
- private static Pair<IFile, IRegion> findValueInDocument(
- ResourceType type, String name, IFile file, Document document) {
- String targetTag = getTagName(type);
- Element root = document.getDocumentElement();
- if (root.getTagName().equals(TAG_RESOURCES)) {
- NodeList topLevel = root.getChildNodes();
- Pair<IFile, IRegion> value = findValueInChildren(name, file, targetTag, topLevel);
- if (value == null && type == ResourceType.ATTR) {
- for (int i = 0, n = topLevel.getLength(); i < n; i++) {
- Node child = topLevel.item(i);
- if (child.getNodeType() == Node.ELEMENT_NODE) {
- Element element = (Element)child;
- String tagName = element.getTagName();
- if (tagName.equals("declare-styleable")) {
- NodeList children = element.getChildNodes();
- value = findValueInChildren(name, file, targetTag, children);
- if (value != null) {
- return value;
- }
- }
- }
- }
- }
-
- return value;
- }
-
- return null;
- }
-
- private static Pair<IFile, IRegion> findValueInChildren(String name, IFile file,
- String targetTag, NodeList children) {
- for (int i = 0, n = children.getLength(); i < n; i++) {
- Node child = children.item(i);
- if (child.getNodeType() == Node.ELEMENT_NODE) {
- Element element = (Element)child;
- String tagName = element.getTagName();
- if (tagName.equals(targetTag)) {
- String elementName = element.getAttribute(ATTR_NAME);
- if (elementName.equals(name)) {
- IRegion region = null;
- if (element instanceof IndexedRegion) {
- IndexedRegion r = (IndexedRegion) element;
- // IndexedRegion.getLength() returns bogus values
- int length = r.getEndOffset() - r.getStartOffset();
- region = new Region(r.getStartOffset(), length);
- }
-
- return Pair.of(file, region);
- }
- }
- }
- }
-
- return null;
- }
-
- /** Parses the given file and locates a definition of the given resource */
- private static Pair<IFile, IRegion> findIdInXml(String id, IFile file) {
- IStructuredModel model = null;
- try {
- model = StructuredModelManager.getModelManager().getExistingModelForRead(file);
- if (model == null) {
- // There is no open or cached model for the file; see if the file looks
- // like it's interesting (content contains the String name we are looking for)
- if (AdtPlugin.fileContains(file, id)) {
- // Yes, so parse content
- model = StructuredModelManager.getModelManager().getModelForRead(file);
- }
- }
- if (model instanceof IDOMModel) {
- IDOMModel domModel = (IDOMModel) model;
- Document document = domModel.getDocument();
- return findIdInDocument(id, file, document);
- }
- } catch (IOException e) {
- AdtPlugin.log(e, "Can't parse %1$s", file); //$NON-NLS-1$
- } catch (CoreException e) {
- AdtPlugin.log(e, "Can't parse %1$s", file); //$NON-NLS-1$
- } finally {
- if (model != null) {
- model.releaseFromRead();
- }
- }
-
- return null;
- }
-
- /** Looks within an XML DOM document for the given resource name and returns it */
- private static Pair<IFile, IRegion> findIdInDocument(String id, IFile file,
- Document document) {
- String targetAttribute = NEW_ID_PREFIX + id;
- Element root = document.getDocumentElement();
- Pair<IFile, IRegion> result = findIdInElement(root, file, targetAttribute,
- true /*requireId*/);
- if (result == null) {
- result = findIdInElement(root, file, targetAttribute, false /*requireId*/);
- }
- return result;
- }
-
- private static Pair<IFile, IRegion> findIdInElement(
- Element root, IFile file, String targetAttribute, boolean requireIdAttribute) {
- NamedNodeMap attributes = root.getAttributes();
- for (int i = 0, n = attributes.getLength(); i < n; i++) {
- Node item = attributes.item(i);
- if (item instanceof Attr) {
- Attr attribute = (Attr) item;
- if (requireIdAttribute && !ATTR_ID.equals(attribute.getLocalName())) {
- continue;
- }
- String value = attribute.getValue();
- if (value.equals(targetAttribute)) {
- // Select the element -containing- the id rather than the attribute itself
- IRegion region = null;
- Node element = attribute.getOwnerElement();
- //if (attribute instanceof IndexedRegion) {
- if (element instanceof IndexedRegion) {
- IndexedRegion r = (IndexedRegion) element;
- int length = r.getEndOffset() - r.getStartOffset();
- region = new Region(r.getStartOffset(), length);
- }
-
- return Pair.of(file, region);
- }
- }
- }
-
- NodeList children = root.getChildNodes();
- for (int i = 0, n = children.getLength(); i < n; i++) {
- Node child = children.item(i);
- if (child.getNodeType() == Node.ELEMENT_NODE) {
- Element element = (Element)child;
- Pair<IFile, IRegion> result = findIdInElement(element, file, targetAttribute,
- requireIdAttribute);
- if (result != null) {
- return result;
- }
- }
- }
-
- return null;
- }
-
- /** Parses the given file and locates a definition of the given resource */
- private static Pair<File, Integer> findValueInXml(ResourceType type, String name, File file) {
- // We can't use the StructureModelManager on files outside projects
- // There is no open or cached model for the file; see if the file looks
- // like it's interesting (content contains the String name we are looking for)
- if (AdtPlugin.fileContains(file, name)) {
- try {
- InputSource is = new InputSource(new FileInputStream(file));
- OffsetTrackingParser parser = new OffsetTrackingParser();
- parser.parse(is);
- Document document = parser.getDocument();
-
- return findValueInDocument(type, name, file, parser, document);
- } catch (SAXException e) {
- // pass -- ignore files we can't parse
- } catch (IOException e) {
- // pass -- ignore files we can't parse
- }
- }
-
- return null;
- }
-
- /** Looks within an XML DOM document for the given resource name and returns it */
- private static Pair<File, Integer> findValueInDocument(ResourceType type, String name,
- File file, OffsetTrackingParser parser, Document document) {
- String targetTag = type.getName();
- if (type == ResourceType.ID) {
- // Ids are recorded in <item> tags instead of <id> tags
- targetTag = "item"; //$NON-NLS-1$
- }
-
- Pair<File, Integer> result = findTag(name, file, parser, document, targetTag);
- if (result == null && type == ResourceType.ATTR) {
- // Attributes seem to be defined in <public> tags
- targetTag = "public"; //$NON-NLS-1$
- result = findTag(name, file, parser, document, targetTag);
- }
- return result;
- }
-
- private static Pair<File, Integer> findTag(String name, File file, OffsetTrackingParser parser,
- Document document, String targetTag) {
- NodeList children = document.getElementsByTagName(targetTag);
- for (int i = 0, n = children.getLength(); i < n; i++) {
- Node child = children.item(i);
- if (child.getNodeType() == Node.ELEMENT_NODE) {
- Element element = (Element) child;
- if (element.getTagName().equals(targetTag)) {
- String elementName = element.getAttribute(ATTR_NAME);
- if (elementName.equals(name)) {
- return Pair.of(file, parser.getOffset(element));
- }
- }
- }
- }
-
- return null;
- }
-
- private static IHyperlink[] getStyleLinks(XmlContext context, IRegion range, String url) {
- Attr attribute = context.getAttribute();
- if (attribute != null) {
- // Split up theme resource urls to the nearest dot forwards, such that you
- // can point to "Theme.Light" by placing the caret anywhere after the dot,
- // and point to just "Theme" by pointing before it.
- int caret = context.getInnerRegionCaretOffset();
- String value = attribute.getValue();
- int index = value.indexOf('.', caret);
- if (index != -1) {
- url = url.substring(0, index);
- range = new Region(range.getOffset(),
- range.getLength() - (value.length() - index));
- }
- }
-
- ResourceUrl resource = ResourceUrl.parse(url);
- if (resource == null) {
- String androidStyle = ANDROID_STYLE_RESOURCE_PREFIX;
- if (url.startsWith(ANDROID_PREFIX)) {
- url = androidStyle + url.substring(ANDROID_PREFIX.length());
- } else if (url.startsWith(ANDROID_THEME_PREFIX)) {
- url = androidStyle + url.substring(ANDROID_THEME_PREFIX.length());
- } else if (url.startsWith(ANDROID_PKG + ':')) {
- url = androidStyle + url.substring(ANDROID_PKG.length() + 1);
- } else {
- url = STYLE_RESOURCE_PREFIX + url;
- }
- }
- return getResourceLinks(range, url);
- }
-
- private static IHyperlink[] getResourceLinks(@Nullable IRegion range, @NonNull String url) {
- IProject project = Hyperlinks.getProject();
- FolderConfiguration configuration = getConfiguration();
- return getResourceLinks(range, url, project, configuration);
- }
-
- /**
- * Computes hyperlinks to resource definitions for resource urls (e.g.
- * {@code @android:string/ok} or {@code @layout/foo}. May create multiple links.
- * @param range TBD
- * @param url the resource url
- * @param project the relevant project
- * @param configuration the applicable configuration
- * @return an array of hyperlinks, or null
- */
- @Nullable
- public static IHyperlink[] getResourceLinks(@Nullable IRegion range, @NonNull String url,
- @Nullable IProject project, @Nullable FolderConfiguration configuration) {
- List<IHyperlink> links = new ArrayList<IHyperlink>();
-
- ResourceUrl resource = ResourceUrl.parse(url);
- if (resource == null) {
- return null;
- }
- ResourceType type = resource.type;
- String name = resource.name;
- boolean isFramework = resource.framework;
- if (project == null) {
- // Local reference *within* a framework
- isFramework = true;
- }
-
- ResourceRepository resources = getResources(project, isFramework);
- if (resources == null) {
- return null;
- }
- List<ResourceFile> sourceFiles = resources.getSourceFiles(type, name,
- null /*configuration*/);
- if (sourceFiles == null) {
- ProjectState projectState = Sdk.getProjectState(project);
- if (projectState != null) {
- List<IProject> libraries = projectState.getFullLibraryProjects();
- if (libraries != null && !libraries.isEmpty()) {
- for (IProject library : libraries) {
- resources = ResourceManager.getInstance().getProjectResources(library);
- sourceFiles = resources.getSourceFiles(type, name, null /*configuration*/);
- if (sourceFiles != null && !sourceFiles.isEmpty()) {
- break;
- }
- }
- }
- }
- }
-
- ResourceFile best = null;
- if (configuration != null && sourceFiles != null && sourceFiles.size() > 0) {
- List<ResourceFile> bestFiles = resources.getSourceFiles(type, name, configuration);
- if (bestFiles != null && bestFiles.size() > 0) {
- best = bestFiles.get(0);
- }
- }
- if (sourceFiles != null) {
- List<ResourceFile> matches = new ArrayList<ResourceFile>();
- for (ResourceFile resourceFile : sourceFiles) {
- matches.add(resourceFile);
- }
-
- if (matches.size() > 0) {
- final ResourceFile fBest = best;
- Collections.sort(matches, new Comparator<ResourceFile>() {
- @Override
- public int compare(ResourceFile rf1, ResourceFile rf2) {
- // Sort best item to the front
- if (rf1 == fBest) {
- return -1;
- } else if (rf2 == fBest) {
- return 1;
- } else {
- return getFileName(rf1).compareTo(getFileName(rf2));
- }
- }
- });
-
- // Is this something found in a values/ folder?
- boolean valueResource = ResourceHelper.isValueBasedResourceType(type);
-
- for (ResourceFile file : matches) {
- String folderName = file.getFolder().getFolder().getName();
- String label = String.format("Open Declaration in %1$s/%2$s",
- folderName, getFileName(file));
-
- // Only search for resource type within the file if it's an
- // XML file and it is a value resource
- ResourceLink link = new ResourceLink(label, range, file,
- valueResource ? type : null, name);
- links.add(link);
- }
- }
- }
-
- // Id's are handled specially because they are typically defined
- // inline (though they -can- be defined in the values folder above as
- // well, in which case we will prefer that definition)
- if (!isFramework && type == ResourceType.ID && links.size() == 0) {
- // Must compute these lazily...
- links.add(new ResourceLink("Open XML Declaration", range, null, type, name));
- }
-
- if (links.size() > 0) {
- return links.toArray(new IHyperlink[links.size()]);
- } else {
- return null;
- }
- }
-
- private static String getFileName(ResourceFile file) {
- return file.getFile().getName();
- }
-
- /** Detector for finding Android references in XML files */
- public static class XmlResolver extends AbstractHyperlinkDetector {
-
- @Override
- public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region,
- boolean canShowMultipleHyperlinks) {
-
- if (region == null || textViewer == null) {
- return null;
- }
-
- IDocument document = textViewer.getDocument();
-
- XmlContext context = XmlContext.find(document, region.getOffset());
- if (context == null) {
- return null;
- }
-
- IRegion range = context.getInnerRange(document);
- boolean isLinkable = false;
- String type = context.getInnerRegion().getType();
- if (type == DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE) {
- if (isAttributeValueLink(context)) {
- isLinkable = true;
- // Strip out quotes
- range = new Region(range.getOffset() + 1, range.getLength() - 2);
-
- Attr attribute = context.getAttribute();
- if (isStyleAttribute(context)) {
- return getStyleLinks(context, range, attribute.getValue());
- }
- if (attribute != null
- && (attribute.getValue().startsWith(PREFIX_RESOURCE_REF)
- || attribute.getValue().startsWith(PREFIX_THEME_REF))) {
- // Instantly create links for resources since we can use the existing
- // resolved maps for this and offer multiple choices for the user
- String url = attribute.getValue();
- return getResourceLinks(range, url);
- }
- }
- } else if (type == DOMRegionContext.XML_TAG_ATTRIBUTE_NAME) {
- if (isAttributeNameLink(context)) {
- isLinkable = true;
- }
- } else if (type == DOMRegionContext.XML_TAG_NAME) {
- if (isElementNameLink(context)) {
- isLinkable = true;
- }
- } else if (type == DOMRegionContext.XML_CONTENT) {
- Node parentNode = context.getNode().getParentNode();
- if (parentNode != null && parentNode.getNodeType() == Node.ELEMENT_NODE) {
- // Try to complete resources defined inline as text, such as
- // style definitions
- ITextRegion outer = context.getElementRegion();
- ITextRegion inner = context.getInnerRegion();
- int innerOffset = outer.getStart() + inner.getStart();
- int caretOffset = innerOffset + context.getInnerRegionCaretOffset();
- try {
- IRegion lineInfo = document.getLineInformationOfOffset(caretOffset);
- int lineStart = lineInfo.getOffset();
- int lineEnd = Math.min(lineStart + lineInfo.getLength(),
- innerOffset + inner.getLength());
-
- // Compute the resource URL
- int urlStart = -1;
- int offset = caretOffset;
- while (offset > lineStart) {
- char c = document.getChar(offset);
- if (c == '@' || c == '?') {
- urlStart = offset;
- break;
- } else if (!isValidResourceUrlChar(c)) {
- break;
- }
- offset--;
- }
-
- if (urlStart != -1) {
- offset = caretOffset;
- while (offset < lineEnd) {
- if (!isValidResourceUrlChar(document.getChar(offset))) {
- break;
- }
- offset++;
- }
-
- int length = offset - urlStart;
- String url = document.get(urlStart, length);
- range = new Region(urlStart, length);
- return getResourceLinks(range, url);
- }
- } catch (BadLocationException e) {
- AdtPlugin.log(e, null);
- }
- }
- }
-
- if (isLinkable) {
- IHyperlink hyperlink = new DeferredResolutionLink(context, range);
- if (hyperlink != null) {
- return new IHyperlink[] {
- hyperlink
- };
- }
- }
-
- return null;
- }
- }
-
- private static boolean isValidResourceUrlChar(char c) {
- return Character.isJavaIdentifierPart(c) || c == ':' || c == '/' || c == '.' || c == '+';
-
- }
-
- /** Detector for finding Android references in Java files */
- public static class JavaResolver extends AbstractHyperlinkDetector {
-
- @Override
- public IHyperlink[] detectHyperlinks(ITextViewer textViewer, IRegion region,
- boolean canShowMultipleHyperlinks) {
- // Most of this is identical to the builtin JavaElementHyperlinkDetector --
- // everything down to the Android R filtering below
-
- ITextEditor textEditor = (ITextEditor) getAdapter(ITextEditor.class);
- if (region == null || !(textEditor instanceof JavaEditor))
- return null;
-
- IAction openAction = textEditor.getAction("OpenEditor"); //$NON-NLS-1$
- if (!(openAction instanceof SelectionDispatchAction))
- return null;
-
- int offset = region.getOffset();
-
- IJavaElement input = EditorUtility.getEditorInputJavaElement(textEditor, false);
- if (input == null)
- return null;
-
- try {
- IDocument document = textEditor.getDocumentProvider().getDocument(
- textEditor.getEditorInput());
- IRegion wordRegion = JavaWordFinder.findWord(document, offset);
- if (wordRegion == null || wordRegion.getLength() == 0)
- return null;
-
- IJavaElement[] elements = null;
- elements = ((ICodeAssist) input).codeSelect(wordRegion.getOffset(), wordRegion
- .getLength());
-
- // Specific Android R class filtering:
- if (elements.length > 0) {
- IJavaElement element = elements[0];
- if (element.getElementType() == IJavaElement.FIELD) {
- IJavaElement unit = element.getAncestor(IJavaElement.COMPILATION_UNIT);
- if (unit == null) {
- // Probably in a binary; see if this is an android.R resource
- IJavaElement type = element.getAncestor(IJavaElement.TYPE);
- if (type != null && type.getParent() != null) {
- IJavaElement parentType = type.getParent();
- if (parentType.getElementType() == IJavaElement.CLASS_FILE) {
- String pn = parentType.getElementName();
- String prefix = FN_RESOURCE_BASE + "$"; //$NON-NLS-1$
- if (pn.startsWith(prefix)) {
- return createTypeLink(element, type, wordRegion, true);
- }
- }
- }
- } else if (FN_RESOURCE_CLASS.equals(unit.getElementName())) {
- // Yes, we're referencing the project R class.
- // Offer hyperlink navigation to XML resource files for
- // the various definitions
- IJavaElement type = element.getAncestor(IJavaElement.TYPE);
- if (type != null) {
- return createTypeLink(element, type, wordRegion, false);
- }
- }
- }
-
- }
- return null;
- } catch (JavaModelException e) {
- return null;
- }
- }
-
- private IHyperlink[] createTypeLink(IJavaElement element, IJavaElement type,
- IRegion wordRegion, boolean isFrameworkResource) {
- String typeName = type.getElementName();
- // typeName will be "id", "layout", "string", etc
- if (isFrameworkResource) {
- typeName = ANDROID_PKG + ':' + typeName;
- }
- String elementName = element.getElementName();
- String url = '@' + typeName + '/' + elementName;
- return getResourceLinks(wordRegion, url);
- }
- }
-
- /** Returns the editor applicable to this hyperlink detection */
- private static IEditorPart getEditor() {
- // I would like to be able to find this via getAdapter(TextEditor.class) but
- // couldn't find a way to initialize the editor context from
- // AndroidSourceViewerConfig#getHyperlinkDetectorTargets (which only has
- // a TextViewer, not a TextEditor, instance).
- //
- // Therefore, for now, use a hack. This hack is reasonable because hyperlink
- // resolvers are only run for the front-most visible window in the active
- // workbench.
- return AdtUtils.getActiveEditor();
- }
-
- /** Returns the project applicable to this hyperlink detection */
- @Nullable
- private static IProject getProject() {
- IFile file = AdtUtils.getActiveFile();
- if (file != null) {
- return file.getProject();
- }
-
- return null;
- }
-
- /**
- * Hyperlink implementation which delays computing the actual file and offset target
- * until it is asked to open the hyperlink
- */
- private static class DeferredResolutionLink implements IHyperlink {
- private XmlContext mXmlContext;
- private IRegion mRegion;
-
- public DeferredResolutionLink(XmlContext xmlContext, IRegion mRegion) {
- super();
- this.mXmlContext = xmlContext;
- this.mRegion = mRegion;
- }
-
- @Override
- public IRegion getHyperlinkRegion() {
- return mRegion;
- }
-
- @Override
- public String getHyperlinkText() {
- return "Open XML Declaration";
- }
-
- @Override
- public String getTypeLabel() {
- return null;
- }
-
- @Override
- public void open() {
- // Lazily compute the location to open
- if (mXmlContext != null && !Hyperlinks.open(mXmlContext)) {
- // Failed: display message to the user
- displayError("Could not open link");
- }
- }
- }
-
- /**
- * Hyperlink implementation which provides a link for a resource; the actual file name
- * is known, but the value location within XML files is deferred until the link is
- * actually opened.
- */
- static class ResourceLink implements IHyperlink {
- private final String mLinkText;
- private final IRegion mLinkRegion;
- private final ResourceType mType;
- private final String mName;
- private final ResourceFile mFile;
-
- /**
- * Constructs a new {@link ResourceLink}.
- *
- * @param linkText the description of the link to be shown in a popup when there
- * is more than one match
- * @param linkRegion the region corresponding to the link source highlight
- * @param file the target resource file containing the link definition
- * @param type the type of resource being linked to
- * @param name the name of the resource being linked to
- */
- public ResourceLink(String linkText, IRegion linkRegion, ResourceFile file,
- ResourceType type, String name) {
- super();
- mLinkText = linkText;
- mLinkRegion = linkRegion;
- mType = type;
- mName = name;
- mFile = file;
- }
-
- @Override
- public IRegion getHyperlinkRegion() {
- return mLinkRegion;
- }
-
- @Override
- public String getHyperlinkText() {
- // return "Open XML Declaration";
- return mLinkText;
- }
-
- @Override
- public String getTypeLabel() {
- return null;
- }
-
- @Override
- public void open() {
- // We have to defer computation of ids until the link is clicked since we
- // don't have a fast map lookup for these
- if (mFile == null && mType == ResourceType.ID) {
- // Id's are handled specially because they are typically defined
- // inline (though they -can- be defined in the values folder above as well,
- // in which case we will prefer that definition)
- IProject project = getProject();
- Pair<IFile,IRegion> def = findIdDefinition(project, mName);
- if (def != null) {
- try {
- AdtPlugin.openFile(def.getFirst(), def.getSecond());
- } catch (PartInitException e) {
- AdtPlugin.log(e, null);
- }
- return;
- }
-
- displayError(String.format("Could not find id %1$s", mName));
- return;
- }
-
- IAbstractFile wrappedFile = mFile != null ? mFile.getFile() : null;
- if (wrappedFile instanceof IFileWrapper) {
- IFile file = ((IFileWrapper) wrappedFile).getIFile();
- try {
- // Lazily search for the target?
- IRegion region = null;
- String extension = file.getFileExtension();
- if (mType != null && mName != null && EXT_XML.equals(extension)) {
- Pair<IFile, IRegion> target;
- if (mType == ResourceType.ID) {
- target = findIdInXml(mName, file);
- } else {
- target = findValueInXml(mType, mName, file);
- }
- if (target != null) {
- region = target.getSecond();
- }
- }
- AdtPlugin.openFile(file, region);
- } catch (PartInitException e) {
- AdtPlugin.log(e, null);
- }
- } else if (wrappedFile instanceof FileWrapper) {
- File file = ((FileWrapper) wrappedFile);
- IPath path = new Path(file.getAbsolutePath());
- int offset = 0;
- // Lazily search for the target?
- if (mType != null && mName != null && EXT_XML.equals(path.getFileExtension())) {
- if (file.exists()) {
- Pair<File, Integer> target = findValueInXml(mType, mName, file);
- if (target != null && target.getSecond() != null) {
- offset = target.getSecond();
- }
- }
- }
- openPath(path, null, offset);
- } else {
- throw new IllegalArgumentException("Invalid link parameters");
- }
- }
-
- ResourceFile getFile() {
- return mFile;
- }
- }
-
- /**
- * XML context containing node, potentially attribute, and text regions surrounding a
- * particular caret offset
- */
- private static class XmlContext {
- private final Node mNode;
- private final Element mElement;
- private final Attr mAttribute;
- private final IStructuredDocumentRegion mOuterRegion;
- private final ITextRegion mInnerRegion;
- private final int mInnerRegionOffset;
-
- public XmlContext(Node node, Element element, Attr attribute,
- IStructuredDocumentRegion outerRegion,
- ITextRegion innerRegion, int innerRegionOffset) {
- super();
- mNode = node;
- mElement = element;
- mAttribute = attribute;
- mOuterRegion = outerRegion;
- mInnerRegion = innerRegion;
- mInnerRegionOffset = innerRegionOffset;
- }
-
- /**
- * Gets the current node, never null
- *
- * @return the surrounding node
- */
- public Node getNode() {
- return mNode;
- }
-
-
- /**
- * Gets the current node, may be null
- *
- * @return the surrounding node
- */
- public Element getElement() {
- return mElement;
- }
-
- /**
- * Returns the current attribute, or null if we are not over an attribute
- *
- * @return the attribute, or null
- */
- public Attr getAttribute() {
- return mAttribute;
- }
-
- /**
- * Gets the region of the element
- *
- * @return the region of the surrounding element, never null
- */
- public ITextRegion getElementRegion() {
- return mOuterRegion;
- }
-
- /**
- * Gets the inner region, which can be the tag name, an attribute name, an
- * attribute value, or some other portion of an XML element
- * @return the inner region, never null
- */
- public ITextRegion getInnerRegion() {
- return mInnerRegion;
- }
-
- /**
- * Gets the caret offset relative to the inner region
- *
- * @return the offset relative to the inner region
- */
- public int getInnerRegionCaretOffset() {
- return mInnerRegionOffset;
- }
-
- /**
- * Returns a range with suffix whitespace stripped out
- *
- * @param document the document containing the regions
- * @return the range of the inner region, minus any whitespace at the end
- */
- public IRegion getInnerRange(IDocument document) {
- int start = mOuterRegion.getStart() + mInnerRegion.getStart();
- int length = mInnerRegion.getLength();
- try {
- String s = document.get(start, length);
- for (int i = s.length() - 1; i >= 0; i--) {
- if (Character.isWhitespace(s.charAt(i))) {
- length--;
- }
- }
- } catch (BadLocationException e) {
- AdtPlugin.log(e, ""); //$NON-NLS-1$
- }
- return new Region(start, length);
- }
-
- /**
- * Returns the node the cursor is currently on in the document. null if no node is
- * selected
- */
- private static XmlContext find(IDocument document, int offset) {
- // Loosely based on getCurrentNode and getCurrentAttr in the WST's
- // XMLHyperlinkDetector.
- IndexedRegion inode = null;
- IStructuredModel model = null;
- try {
- model = StructuredModelManager.getModelManager().getExistingModelForRead(document);
- if (model != null) {
- inode = model.getIndexedRegion(offset);
- if (inode == null) {
- inode = model.getIndexedRegion(offset - 1);
- }
-
- if (inode instanceof Element) {
- Element element = (Element) inode;
- Attr attribute = null;
- if (element.hasAttributes()) {
- NamedNodeMap attrs = element.getAttributes();
- // go through each attribute in node and if attribute contains
- // offset, return that attribute
- for (int i = 0; i < attrs.getLength(); ++i) {
- // assumption that if parent node is of type IndexedRegion,
- // then its attributes will also be of type IndexedRegion
- IndexedRegion attRegion = (IndexedRegion) attrs.item(i);
- if (attRegion.contains(offset)) {
- attribute = (Attr) attrs.item(i);
- break;
- }
- }
- }
-
- IStructuredDocument doc = model.getStructuredDocument();
- IStructuredDocumentRegion region = doc.getRegionAtCharacterOffset(offset);
- if (region != null
- && DOMRegionContext.XML_TAG_NAME.equals(region.getType())) {
- ITextRegion subRegion = region.getRegionAtCharacterOffset(offset);
- if (subRegion == null) {
- return null;
- }
- int regionStart = region.getStartOffset();
- int subregionStart = subRegion.getStart();
- int relativeOffset = offset - (regionStart + subregionStart);
- return new XmlContext(element, element, attribute, region, subRegion,
- relativeOffset);
- }
- } else if (inode instanceof Node) {
- IStructuredDocument doc = model.getStructuredDocument();
- IStructuredDocumentRegion region = doc.getRegionAtCharacterOffset(offset);
- if (region != null
- && DOMRegionContext.XML_CONTENT.equals(region.getType())) {
- ITextRegion subRegion = region.getRegionAtCharacterOffset(offset);
- int regionStart = region.getStartOffset();
- int subregionStart = subRegion.getStart();
- int relativeOffset = offset - (regionStart + subregionStart);
- return new XmlContext((Node) inode, null, null, region, subRegion,
- relativeOffset);
- }
-
- }
- }
- } finally {
- if (model != null) {
- model.releaseFromRead();
- }
- }
-
- return null;
- }
- }
-
- /**
- * DOM parser which records offsets in the element nodes such that it can return
- * offsets for elements later
- */
- private static final class OffsetTrackingParser extends DOMParser {
-
- private static final String KEY_OFFSET = "offset"; //$NON-NLS-1$
-
- private static final String KEY_NODE =
- "http://apache.org/xml/properties/dom/current-element-node"; //$NON-NLS-1$
-
- private XMLLocator mLocator;
-
- public OffsetTrackingParser() throws SAXException {
- this.setFeature("http://apache.org/xml/features/dom/defer-node-expansion",//$NON-NLS-1$
- false);
- }
-
- public int getOffset(Node node) {
- Integer offset = (Integer) node.getUserData(KEY_OFFSET);
- if (offset != null) {
- return offset;
- }
-
- return -1;
- }
-
- @Override
- public void startElement(QName elementQName, XMLAttributes attrList, Augmentations augs)
- throws XNIException {
- int offset = mLocator.getCharacterOffset();
- super.startElement(elementQName, attrList, augs);
-
- try {
- Node node = (Node) this.getProperty(KEY_NODE);
- if (node != null) {
- node.setUserData(KEY_OFFSET, offset, null);
- }
- } catch (org.xml.sax.SAXException ex) {
- AdtPlugin.log(ex, ""); //$NON-NLS-1$
- }
- }
-
- @Override
- public void startDocument(XMLLocator locator, String encoding,
- NamespaceContext namespaceContext, Augmentations augs) throws XNIException {
- super.startDocument(locator, encoding, namespaceContext, augs);
- mLocator = locator;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/IPageImageProvider.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/IPageImageProvider.java
deleted file mode 100755
index 7cd80ec1d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/IPageImageProvider.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors;
-
-import org.eclipse.swt.graphics.Image;
-
-/**
- * Interface that editor pages can implement to provide an icon
- * for the page tab in the XML editor.
- */
-public interface IPageImageProvider {
-
- /**
- * Returns an {@link Image} that the editor will display in the page's tab.
- *
- * @return An {@link Image} for the editor tab for this page. Null for no image.
- */
- Image getPageImage();
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/IconFactory.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/IconFactory.java
deleted file mode 100644
index 41807f82b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/IconFactory.java
+++ /dev/null
@@ -1,448 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.ui.ErrorImageComposite;
-import com.google.common.collect.Maps;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.FontData;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.ImageData;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-
-import java.net.URL;
-import java.util.IdentityHashMap;
-import java.util.Map;
-
-/**
- * Factory to generate icons for Android Editors.
- * <p/>
- * Icons are kept here and reused.
- */
-public class IconFactory {
- public static final int COLOR_RED = SWT.COLOR_DARK_RED;
- public static final int COLOR_GREEN = SWT.COLOR_DARK_GREEN;
- public static final int COLOR_BLUE = SWT.COLOR_DARK_BLUE;
- public static final int COLOR_DEFAULT = SWT.COLOR_BLACK;
-
- public static final int SHAPE_CIRCLE = 'C';
- public static final int SHAPE_RECT = 'R';
- public static final int SHAPE_DEFAULT = SHAPE_CIRCLE;
-
- private static IconFactory sInstance;
-
- private Map<String, Image> mIconMap = Maps.newHashMap();
- private Map<URL, Image> mUrlMap = Maps.newHashMap();
- private Map<String, ImageDescriptor> mImageDescMap = Maps.newHashMap();
- private Map<Image, Image> mErrorIcons;
- private Map<Image, Image> mWarningIcons;
-
- private IconFactory() {
- }
-
- public static synchronized IconFactory getInstance() {
- if (sInstance == null) {
- sInstance = new IconFactory();
- }
- return sInstance;
- }
-
- public void dispose() {
- // Dispose icons
- for (Image icon : mIconMap.values()) {
- // The map can contain null values
- if (icon != null) {
- icon.dispose();
- }
- }
- mIconMap.clear();
- for (Image icon : mUrlMap.values()) {
- // The map can contain null values
- if (icon != null) {
- icon.dispose();
- }
- }
- mUrlMap.clear();
- if (mErrorIcons != null) {
- for (Image icon : mErrorIcons.values()) {
- // The map can contain null values
- if (icon != null) {
- icon.dispose();
- }
- }
- mErrorIcons = null;
- }
- if (mWarningIcons != null) {
- for (Image icon : mWarningIcons.values()) {
- // The map can contain null values
- if (icon != null) {
- icon.dispose();
- }
- }
- mWarningIcons = null;
- }
- }
-
- /**
- * Returns an Image for a given icon name.
- * <p/>
- * Callers should not dispose it.
- *
- * @param osName The leaf name, without the extension, of an existing icon in the
- * editor's "icons" directory. If it doesn't exists, a default icon will be
- * generated automatically based on the name.
- */
- public Image getIcon(String osName) {
- return getIcon(osName, COLOR_DEFAULT, SHAPE_DEFAULT);
- }
-
- /**
- * Returns an Image for a given icon name.
- * <p/>
- * Callers should not dispose it.
- *
- * @param osName The leaf name, without the extension, of an existing icon in the
- * editor's "icons" directory. If it doesn't exist, a default icon will be
- * generated automatically based on the name.
- * @param color The color of the text in the automatically generated icons,
- * one of COLOR_DEFAULT, COLOR_RED, COLOR_BLUE or COLOR_RED.
- * @param shape The shape of the icon in the automatically generated icons,
- * one of SHAPE_DEFAULT, SHAPE_CIRCLE or SHAPE_RECT.
- */
- public Image getIcon(String osName, int color, int shape) {
- String key = Character.toString((char) shape) + Integer.toString(color) + osName;
- Image icon = mIconMap.get(key);
- if (icon == null && !mIconMap.containsKey(key)) {
- ImageDescriptor id = getImageDescriptor(osName, color, shape);
- if (id != null) {
- icon = id.createImage();
- }
- // Note that we store null references in the icon map, to avoid looking them
- // up every time. If it didn't exist once, it will not exist later.
- mIconMap.put(key, icon);
- }
- return icon;
- }
-
- /**
- * Returns an ImageDescriptor for a given icon name.
- * <p/>
- * Callers should not dispose it.
- *
- * @param osName The leaf name, without the extension, of an existing icon in the
- * editor's "icons" directory. If it doesn't exists, a default icon will be
- * generated automatically based on the name.
- */
- public ImageDescriptor getImageDescriptor(String osName) {
- return getImageDescriptor(osName, COLOR_DEFAULT, SHAPE_DEFAULT);
- }
-
- /**
- * Returns an ImageDescriptor for a given icon name.
- * <p/>
- * Callers should not dispose it.
- *
- * @param osName The leaf name, without the extension, of an existing icon in the
- * editor's "icons" directory. If it doesn't exists, a default icon will be
- * generated automatically based on the name.
- * @param color The color of the text in the automatically generated icons.
- * one of COLOR_DEFAULT, COLOR_RED, COLOR_BLUE or COLOR_RED.
- * @param shape The shape of the icon in the automatically generated icons,
- * one of SHAPE_DEFAULT, SHAPE_CIRCLE or SHAPE_RECT.
- */
- public ImageDescriptor getImageDescriptor(String osName, int color, int shape) {
- String key = Character.toString((char) shape) + Integer.toString(color) + osName;
- ImageDescriptor id = mImageDescMap.get(key);
- if (id == null && !mImageDescMap.containsKey(key)) {
- id = AbstractUIPlugin.imageDescriptorFromPlugin(
- AdtPlugin.PLUGIN_ID,
- String.format("/icons/%1$s.png", osName)); //$NON-NLS-1$
-
- if (id == null) {
- id = new LetterImageDescriptor(osName.charAt(0), color, shape);
- }
-
- // Note that we store null references in the icon map, to avoid looking them
- // up every time. If it didn't exist once, it will not exist later.
- mImageDescMap.put(key, id);
- }
- return id;
- }
-
- /**
- * Returns an Image for a given icon name.
- * <p/>
- * Callers should not dispose it.
- *
- * @param osName The leaf name, without the extension, of an existing icon
- * in the editor's "icons" directory. If it doesn't exist, the
- * fallback will be used instead.
- * @param fallback the fallback icon name to use if the primary icon does
- * not exist, or null if the method should return null if the
- * image does not exist
- * @return the icon, which should not be disposed by the caller, or null
- * if the image does not exist *and*
- */
- @Nullable
- public Image getIcon(@NonNull String osName, @Nullable String fallback) {
- String key = osName;
- Image icon = mIconMap.get(key);
- if (icon == null && !mIconMap.containsKey(key)) {
- ImageDescriptor id = getImageDescriptor(osName, fallback);
- if (id != null) {
- icon = id.createImage();
- }
- // Note that we store null references in the icon map, to avoid looking them
- // up every time. If it didn't exist once, it will not exist later.
- mIconMap.put(key, icon);
- }
- return icon;
- }
-
- /**
- * Returns an icon of the given name, or if that image does not exist and
- * icon of the given fallback name.
- *
- * @param key the icon name
- * @param fallbackKey the fallback image to use if the primary key does not
- * exist
- * @return the image descriptor, or null if the image does not exist and the
- * fallbackKey is null
- */
- @Nullable
- public ImageDescriptor getImageDescriptor(@NonNull String key, @Nullable String fallbackKey) {
- ImageDescriptor id = mImageDescMap.get(key);
- if (id == null && !mImageDescMap.containsKey(key)) {
- id = AbstractUIPlugin.imageDescriptorFromPlugin(
- AdtPlugin.PLUGIN_ID,
- String.format("/icons/%1$s.png", key)); //$NON-NLS-1$
- if (id == null) {
- if (fallbackKey == null) {
- return null;
- }
- id = getImageDescriptor(fallbackKey);
- }
-
- // Place the fallback image for this key as well such that we don't keep trying
- // to load the failed image
- mImageDescMap.put(key, id);
- }
-
- return id;
- }
-
- /**
- * Returns the image indicated by the given URL
- *
- * @param url the url to the image resources
- * @return the image for the url, or null if it cannot be initialized
- */
- public Image getIcon(URL url) {
- Image image = mUrlMap.get(url);
- if (image == null) {
- ImageDescriptor descriptor = ImageDescriptor.createFromURL(url);
- image = descriptor.createImage();
- mUrlMap.put(url, image);
- }
-
- return image;
- }
-
- /**
- * Returns an image with an error icon overlaid on it. The icons are cached,
- * so the base image should be cached as well, or this method will keep
- * storing new overlays into its cache.
- *
- * @param image the base image
- * @return the combined image
- */
- @NonNull
- public Image addErrorIcon(@NonNull Image image) {
- if (mErrorIcons != null) {
- Image combined = mErrorIcons.get(image);
- if (combined != null) {
- return combined;
- }
- } else {
- mErrorIcons = new IdentityHashMap<Image, Image>();
- }
-
- Image combined = new ErrorImageComposite(image, false).createImage();
- mErrorIcons.put(image, combined);
-
- return combined;
- }
-
- /**
- * Returns an image with a warning icon overlaid on it. The icons are
- * cached, so the base image should be cached as well, or this method will
- * keep storing new overlays into its cache.
- *
- * @param image the base image
- * @return the combined image
- */
- @NonNull
- public Image addWarningIcon(@NonNull Image image) {
- if (mWarningIcons != null) {
- Image combined = mWarningIcons.get(image);
- if (combined != null) {
- return combined;
- }
- } else {
- mWarningIcons = new IdentityHashMap<Image, Image>();
- }
-
- Image combined = new ErrorImageComposite(image, true).createImage();
- mWarningIcons.put(image, combined);
-
- return combined;
- }
-
- /**
- * A simple image description that generates a 16x16 image which consists
- * of a colored letter inside a black & white circle.
- */
- private static class LetterImageDescriptor extends ImageDescriptor {
-
- private final char mLetter;
- private final int mColor;
- private final int mShape;
-
- public LetterImageDescriptor(char letter, int color, int shape) {
- mLetter = Character.toUpperCase(letter);
- mColor = color;
- mShape = shape;
- }
-
- @Override
- public ImageData getImageData() {
-
- final int SX = 15;
- final int SY = 15;
- final int RX = 4;
- final int RY = 4;
-
- Display display = Display.getCurrent();
- if (display == null) {
- return null;
- }
-
- Image image = new Image(display, SX, SY);
-
- GC gc = new GC(image);
- gc.setAdvanced(true);
- gc.setAntialias(SWT.ON);
- gc.setTextAntialias(SWT.ON);
-
- // image.setBackground() does not appear to have any effect; we must explicitly
- // paint into the image the background color we want masked out later.
- // HOWEVER, alpha transparency does not work; we only get to mark a single color
- // as transparent. You might think we could pick a system color (to avoid having
- // to allocate and dispose the color), or a wildly unique color (to make sure we
- // don't accidentally pick up any extra pixels in the image as transparent), but
- // this has the very unfortunate side effect of making neighbor pixels in the
- // antialiased rendering of the circle pick up shades of that alternate color,
- // which looks bad. Therefore we pick a color which is similar to one of our
- // existing colors but hopefully different from most pixels. A visual check
- // confirms that this seems to work pretty well:
- RGB backgroundRgb = new RGB(254, 254, 254);
- Color backgroundColor = new Color(display, backgroundRgb);
- gc.setBackground(backgroundColor);
- gc.fillRectangle(0, 0, SX, SY);
-
- gc.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
- if (mShape == SHAPE_CIRCLE) {
- gc.fillOval(0, 0, SX - 1, SY - 1);
- } else if (mShape == SHAPE_RECT) {
- gc.fillRoundRectangle(0, 0, SX - 1, SY - 1, RX, RY);
- }
-
- gc.setForeground(display.getSystemColor(SWT.COLOR_BLACK));
- gc.setLineWidth(1);
- if (mShape == SHAPE_CIRCLE) {
- gc.drawOval(0, 0, SX - 1, SY - 1);
- } else if (mShape == SHAPE_RECT) {
- gc.drawRoundRectangle(0, 0, SX - 1, SY - 1, RX, RY);
- }
-
- // Get a bold version of the default system font, if possible.
- Font font = display.getSystemFont();
- FontData[] fds = font.getFontData();
- fds[0].setStyle(SWT.BOLD);
- // use 3/4th of the circle diameter for the font size (in pixels)
- // and convert it to "font points" (font points in SWT are hardcoded in an
- // arbitrary 72 dpi and then converted in real pixels using whatever is
- // indicated by getDPI -- at least that's how it works under Win32).
- fds[0].setHeight((int) ((SY + 1) * 3./4. * 72./display.getDPI().y));
- // Note: win32 implementation always uses fds[0] so we change just that one.
- // getFontData indicates that the array of fd is really an unusual thing for X11.
- font = new Font(display, fds);
- gc.setFont(font);
- gc.setForeground(display.getSystemColor(mColor));
-
- // Text measurement varies so slightly depending on the platform
- int ofx = 0;
- int ofy = 0;
- if (SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_WINDOWS) {
- ofx = +1;
- ofy = -1;
- } else if (SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_DARWIN) {
- // Tweak pixel positioning of some letters that don't look good on the Mac
- if (mLetter != 'T' && mLetter != 'V') {
- ofy = -1;
- }
- if (mLetter == 'I') {
- ofx = -2;
- }
- }
-
- String s = Character.toString(mLetter);
- Point p = gc.textExtent(s);
- int tx = (SX + ofx - p.x) / 2;
- int ty = (SY + ofy - p.y) / 2;
- gc.drawText(s, tx, ty, true /* isTransparent */);
-
- font.dispose();
- gc.dispose();
-
- ImageData data = image.getImageData();
- image.dispose();
- backgroundColor.dispose();
-
- // Set transparent pixel in the palette such that on paint (over palette,
- // which has a background of SWT.COLOR_WIDGET_BACKGROUND, and over the tree
- // which has a white background) we will substitute the background in for
- // the backgroundPixel.
- int backgroundPixel = data.palette.getPixel(backgroundRgb);
- data.transparentPixel = backgroundPixel;
-
- return data;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/OutlineLabelProvider.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/OutlineLabelProvider.java
deleted file mode 100644
index bb5d1ba01..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/OutlineLabelProvider.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ATTR_LAYOUT;
-import static com.android.SdkConstants.ATTR_NAME;
-import static com.android.SdkConstants.ATTR_SRC;
-import static com.android.SdkConstants.ATTR_TEXT;
-import static com.android.SdkConstants.DRAWABLE_PREFIX;
-import static com.android.SdkConstants.LAYOUT_RESOURCE_PREFIX;
-import static com.android.SdkConstants.VIEW;
-import static com.android.SdkConstants.VIEW_TAG;
-
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wst.xml.ui.internal.contentoutline.JFaceNodeLabelProvider;
-import org.w3c.dom.DOMException;
-import org.w3c.dom.Element;
-
-/**
- * Label provider for the XML outlines and quick outlines: Use our own icons,
- * when available, and and include the most important attribute (id, name, or
- * text)
- */
-@SuppressWarnings("restriction")
-// XML UI API
-class OutlineLabelProvider extends JFaceNodeLabelProvider {
- @Override
- public Image getImage(Object element) {
- if (element instanceof Element) {
- Element e = (Element) element;
- String tagName = e.getTagName();
- if (VIEW_TAG.equals(tagName)) {
- // Can't have both view.png and View.png; issues on case sensitive vs
- // case insensitive file systems
- tagName = VIEW;
- }
- IconFactory factory = IconFactory.getInstance();
- Image img = factory.getIcon(tagName, null);
- if (img != null) {
- return img;
- }
- }
- return super.getImage(element);
- }
-
- @Override
- public String getText(Object element) {
- String text = super.getText(element);
- if (element instanceof Element) {
- Element e = (Element) element;
- String id = getAttributeNS(e, ANDROID_URI, ATTR_ID);
- if (id == null || id.length() == 0) {
- id = getAttributeNS(e, ANDROID_URI, ATTR_NAME);
- if (id == null || id.length() == 0) {
- id = e.getAttribute(ATTR_NAME);
- if (id == null || id.length() == 0) {
- id = getAttributeNS(e, ANDROID_URI, ATTR_TEXT);
- if (id != null && id.length() > 15) {
- id = id.substring(0, 12) + "...";
- }
- if (id == null || id.length() == 0) {
- id = getAttributeNS(e, ANDROID_URI, ATTR_SRC);
- if (id != null && id.length() > 0) {
- if (id.startsWith(DRAWABLE_PREFIX)) {
- id = id.substring(DRAWABLE_PREFIX.length());
- }
- } else {
- id = e.getAttribute(ATTR_LAYOUT);
- if (id != null && id.length() > 0) {
- if (id.startsWith(LAYOUT_RESOURCE_PREFIX)) {
- id = id.substring(LAYOUT_RESOURCE_PREFIX.length());
- }
- }
- }
- }
- }
- }
- }
- if (id != null && id.length() > 0) {
- return text + ": " + id; //$NON-NLS-1$
- }
- }
- return text;
- }
-
- /**
- * Wrapper around {@link Element#getAttributeNS(String, String)}.
- * <p/>
- * The implementation used in Eclipse's XML editor sometimes internally
- * throws an NPE instead of politely returning null.
- *
- * @see Element#getAttributeNS(String, String)
- */
- private String getAttributeNS(Element e, String uri, String name) throws DOMException {
- try {
- return e.getAttributeNS(uri, name);
- } catch (NullPointerException ignore) {
- return null;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/XmlEditorMultiOutline.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/XmlEditorMultiOutline.java
deleted file mode 100644
index 61db9f313..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/XmlEditorMultiOutline.java
+++ /dev/null
@@ -1,221 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IStatusLineManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.part.IPageBookViewPage;
-import org.eclipse.ui.part.Page;
-import org.eclipse.ui.part.PageBook;
-import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Outline used for XML editors that have multiple pages with separate outlines:
- * switches between them
- * <p>
- * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=1917
- * <p>
- * Modeled after .org.eclipse.pde.internal.ui.editor.PDEMultiPageContentOutline
- */
-public class XmlEditorMultiOutline extends Page implements IContentOutlinePage,
- ISelectionChangedListener {
- private boolean mDisposed;
- private PageBook mPageBook;
- private IContentOutlinePage mCurrentPage;
- private IActionBars mActionBars;
- private IContentOutlinePage mEmptyPage;
- private List<ISelectionChangedListener> mListeners;
- private ISelection mSelection;
-
- public XmlEditorMultiOutline() {
- }
-
- @Override
- public Control getControl() {
- return mPageBook;
- }
-
- @Override
- public void createControl(Composite parent) {
- mPageBook = new PageBook(parent, SWT.NONE);
- }
-
- @Override
- public void dispose() {
- mDisposed = true;
- mListeners = null;
- if (mPageBook != null && !mPageBook.isDisposed()) {
- mPageBook.dispose();
- mPageBook = null;
- }
- if (mEmptyPage != null) {
- mEmptyPage.dispose();
- mEmptyPage = null;
- }
- }
-
- public boolean isDisposed() {
- return mDisposed;
- }
-
- @Override
- public void makeContributions(IMenuManager menuManager, IToolBarManager toolBarManager,
- IStatusLineManager statusLineManager) {
- }
-
- @Override
- public void setActionBars(IActionBars actionBars) {
- mActionBars = actionBars;
- if (mCurrentPage != null) {
- setPageActive(mCurrentPage);
- }
- }
-
- @Override
- public void setFocus() {
- if (mCurrentPage != null) {
- mCurrentPage.setFocus();
- }
- }
-
- @Override
- public void addSelectionChangedListener(ISelectionChangedListener listener) {
- if (mListeners == null) {
- mListeners = new ArrayList<ISelectionChangedListener>(2);
- }
- mListeners.add(listener);
- }
-
- @Override
- public void removeSelectionChangedListener(ISelectionChangedListener listener) {
- mListeners.remove(listener);
- }
-
- @Override
- public ISelection getSelection() {
- return mSelection;
- }
-
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- setSelection(event.getSelection());
- }
-
- public void setPageActive(IContentOutlinePage page) {
- if (page == null) {
- if (mEmptyPage == null) {
- mEmptyPage = new EmptyPage();
- }
- page = mEmptyPage;
- }
- if (mCurrentPage != null) {
- mCurrentPage.removeSelectionChangedListener(this);
- }
- page.addSelectionChangedListener(this);
- mCurrentPage = page;
- // Still initializing?
- if (mPageBook == null) {
- return;
- }
- Control control = page.getControl();
- if (control == null || control.isDisposed()) {
- if (page instanceof IPageBookViewPage) {
- try {
- ((IPageBookViewPage) page).init(getSite());
- } catch (PartInitException e) {
- AdtPlugin.log(e, null);
- }
- }
- page.createControl(mPageBook);
- page.setActionBars(mActionBars);
- control = page.getControl();
- }
- mPageBook.showPage(control);
- }
-
- @Override
- public void setSelection(ISelection selection) {
- mSelection = selection;
- if (mListeners != null) {
- SelectionChangedEvent e = new SelectionChangedEvent(this, selection);
- for (int i = 0; i < mListeners.size(); i++) {
- mListeners.get(i).selectionChanged(e);
- }
- }
- }
-
- private static class EmptyPage implements IContentOutlinePage {
- private Composite mControl;
-
- private EmptyPage() {
- }
-
- @Override
- public void createControl(Composite parent) {
- mControl = new Composite(parent, SWT.NULL);
- }
-
- @Override
- public void dispose() {
- }
-
- @Override
- public Control getControl() {
- return mControl;
- }
-
- @Override
- public void setActionBars(IActionBars actionBars) {
- }
-
- @Override
- public void setFocus() {
- }
-
- @Override
- public void addSelectionChangedListener(ISelectionChangedListener listener) {
- }
-
- @Override
- public ISelection getSelection() {
- return StructuredSelection.EMPTY;
- }
-
- @Override
- public void removeSelectionChangedListener(ISelectionChangedListener listener) {
- }
-
- @Override
- public void setSelection(ISelection selection) {
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/animator/AnimDescriptors.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/animator/AnimDescriptors.java
deleted file mode 100644
index 2489cf57f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/animator/AnimDescriptors.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.animator;
-
-import com.android.SdkConstants;
-import com.android.ide.common.resources.platform.DeclareStyleableInfo;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.IDescriptorProvider;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.XmlnsAttributeDescriptor;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/** Descriptors for the res/anim resources */
-public class AnimDescriptors implements IDescriptorProvider {
- /** The root element descriptor */
- private ElementDescriptor mDescriptor;
- /** The root element descriptors */
- private ElementDescriptor[] mRootDescriptors;
- private Map<String, ElementDescriptor> nameToDescriptor;
-
- /** @return the root descriptor. */
- @Override
- public ElementDescriptor getDescriptor() {
- if (mDescriptor == null) {
- mDescriptor = new ElementDescriptor("", getRootElementDescriptors()); //$NON-NLS-1$
- }
-
- return mDescriptor;
- }
-
- @Override
- public ElementDescriptor[] getRootElementDescriptors() {
- return mRootDescriptors;
- }
-
- public ElementDescriptor getElementDescriptor(String mRootTag) {
- if (nameToDescriptor == null) {
- nameToDescriptor = new HashMap<String, ElementDescriptor>();
- for (ElementDescriptor descriptor : getRootElementDescriptors()) {
- nameToDescriptor.put(descriptor.getXmlName(), descriptor);
- }
- }
-
- ElementDescriptor descriptor = nameToDescriptor.get(mRootTag);
- if (descriptor == null) {
- descriptor = getDescriptor();
- }
- return descriptor;
- }
-
- public synchronized void updateDescriptors(Map<String, DeclareStyleableInfo> styleMap) {
- if (styleMap == null) {
- return;
- }
-
- XmlnsAttributeDescriptor xmlns = new XmlnsAttributeDescriptor(SdkConstants.ANDROID_NS_NAME,
- SdkConstants.ANDROID_URI);
-
- List<ElementDescriptor> descriptors = new ArrayList<ElementDescriptor>();
-
- String sdkUrl =
- "http://developer.android.com/guide/topics/graphics/view-animation.html"; //$NON-NLS-1$
- ElementDescriptor set = AnimatorDescriptors.addElement(descriptors, styleMap,
- "set", "Set", "AnimationSet", "Animation", //$NON-NLS-1$ //$NON-NLS-3$ //$NON-NLS-4$
- "A container that holds other animation elements (<alpha>, <scale>, "
- + "<translate>, <rotate>) or other <set> elements. ",
- sdkUrl,
- xmlns, null, true /*mandatory*/);
-
- AnimatorDescriptors.addElement(descriptors, styleMap,
- "alpha", "Alpha", "AlphaAnimation", "Animation", //$NON-NLS-1$ //$NON-NLS-3$ //$NON-NLS-4$
- "A fade-in or fade-out animation.",
- sdkUrl,
- xmlns, null, true /*mandatory*/);
-
- AnimatorDescriptors.addElement(descriptors, styleMap,
- "scale", "Scale", "ScaleAnimation", "Animation", //$NON-NLS-1$ //$NON-NLS-3$ //$NON-NLS-4$
- "A resizing animation. You can specify the center point of the image from "
- + "which it grows outward (or inward) by specifying pivotX and pivotY. "
- + "For example, if these values are 0, 0 (top-left corner), all growth "
- + "will be down and to the right.",
- sdkUrl,
- xmlns, null, true /*mandatory*/);
-
- AnimatorDescriptors.addElement(descriptors, styleMap,
- "rotate", "Rotate", "RotateAnimation", "Animation", //$NON-NLS-1$ //$NON-NLS-3$ //$NON-NLS-4$
- "A rotation animation.",
- sdkUrl,
- xmlns, null, true /*mandatory*/);
-
- AnimatorDescriptors.addElement(descriptors, styleMap,
- "translate", "Translate", "TranslateAnimation", "Animation", //$NON-NLS-1$ //$NON-NLS-3$ //$NON-NLS-4$
- "A vertical and/or horizontal motion. Supports the following attributes in "
- + "any of the following three formats: values from -100 to 100 ending "
- + "with \"%\", indicating a percentage relative to itself; values from "
- + "-100 to 100 ending in \"%p\", indicating a percentage relative to its "
- + "parent; a float value with no suffix, indicating an absolute value.",
- sdkUrl,
- xmlns, null, true /*mandatory*/);
-
- mRootDescriptors = descriptors.toArray(new ElementDescriptor[descriptors.size()]);
-
- // Allow <set> to nest the others (and other sets)
- if (set != null) {
- set.setChildren(mRootDescriptors);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/animator/AnimationContentAssist.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/animator/AnimationContentAssist.java
deleted file mode 100644
index 8a4cf2384..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/animator/AnimationContentAssist.java
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.animator;
-
-import static com.android.SdkConstants.ANDROID_NS_NAME_PREFIX;
-import static com.android.SdkConstants.ANDROID_PKG;
-
-import com.android.annotations.VisibleForTesting;
-import com.android.ide.common.api.IAttributeInfo.Format;
-import com.android.ide.common.resources.ResourceItem;
-import com.android.ide.common.resources.ResourceRepository;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.AndroidContentAssist;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.IDescriptorProvider;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.SeparatorAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.resources.ResourceFolderType;
-import com.android.resources.ResourceType;
-import com.android.utils.Pair;
-
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.w3c.dom.Node;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.EnumSet;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Content Assist Processor for /res/drawable XML files
- */
-@VisibleForTesting
-public final class AnimationContentAssist extends AndroidContentAssist {
- private static final String OBJECT_ANIMATOR = "objectAnimator"; //$NON-NLS-1$
- private static final String PROPERTY_NAME = "propertyName"; //$NON-NLS-1$
- private static final String INTERPOLATOR_PROPERTY_NAME = "interpolator"; //$NON-NLS-1$
- private static final String INTERPOLATOR_NAME_SUFFIX = "_interpolator"; //$NON-NLS-1$
-
- public AnimationContentAssist() {
- super(AndroidTargetData.DESCRIPTOR_ANIMATOR);
- }
-
- @Override
- protected int getRootDescriptorId() {
- String folderName = AdtUtils.getParentFolderName(mEditor.getEditorInput());
- ResourceFolderType folderType = ResourceFolderType.getFolderType(folderName);
- if (folderType == ResourceFolderType.ANIM) {
- return AndroidTargetData.DESCRIPTOR_ANIM;
- } else {
- return AndroidTargetData.DESCRIPTOR_ANIMATOR;
- }
- }
-
- @Override
- protected boolean computeAttributeValues(List<ICompletionProposal> proposals, int offset,
- String parentTagName, String attributeName, Node node, String wordPrefix,
- boolean skipEndTag, int replaceLength) {
-
- // Add value completion for the interpolator and propertyName attributes
-
- if (attributeName.endsWith(INTERPOLATOR_PROPERTY_NAME)) {
- if (!wordPrefix.startsWith("@android:anim/")) { //$NON-NLS-1$
- // List all framework interpolators with full path first
- AndroidTargetData data = mEditor.getTargetData();
- ResourceRepository repository = data.getFrameworkResources();
- List<String> interpolators = new ArrayList<String>();
- String base = '@' + ANDROID_PKG + ':' + ResourceType.ANIM.getName() + '/';
- for (ResourceItem item : repository.getResourceItemsOfType(ResourceType.ANIM)) {
- String name = item.getName();
- if (name.endsWith(INTERPOLATOR_NAME_SUFFIX)) {
- interpolators.add(base + item.getName());
- }
- }
- addMatchingProposals(proposals, interpolators.toArray(), offset, node, wordPrefix,
- (char) 0 /* needTag */, true /* isAttribute */, false /* isNew */,
- skipEndTag /* skipEndTag */, replaceLength);
- }
-
-
- return super.computeAttributeValues(proposals, offset, parentTagName, attributeName,
- node, wordPrefix, skipEndTag, replaceLength);
- } else if (parentTagName.equals(OBJECT_ANIMATOR)
- && attributeName.endsWith(PROPERTY_NAME)) {
-
- // Special case: the user is code completing inside
- // <objectAnimator propertyName="^">
- // In this case, offer ALL attribute names that make sense for animation
- // (e.g. all numeric ones)
-
- String attributePrefix = wordPrefix;
- if (startsWith(attributePrefix, ANDROID_NS_NAME_PREFIX)) {
- attributePrefix = attributePrefix.substring(ANDROID_NS_NAME_PREFIX.length());
- }
-
- AndroidTargetData data = mEditor.getTargetData();
- if (data != null) {
- IDescriptorProvider descriptorProvider =
- data.getDescriptorProvider(AndroidTargetData.DESCRIPTOR_LAYOUT);
- if (descriptorProvider != null) {
- ElementDescriptor[] rootElementDescriptors =
- descriptorProvider.getRootElementDescriptors();
- Map<String, AttributeDescriptor> matches =
- new HashMap<String, AttributeDescriptor>(180);
- for (ElementDescriptor elementDesc : rootElementDescriptors) {
- for (AttributeDescriptor desc : elementDesc.getAttributes()) {
- if (desc instanceof SeparatorAttributeDescriptor) {
- continue;
- }
- String name = desc.getXmlLocalName();
- if (startsWith(name, attributePrefix)) {
- EnumSet<Format> formats = desc.getAttributeInfo().getFormats();
- if (formats.contains(Format.INTEGER)
- || formats.contains(Format.FLOAT)) {
- // TODO: Filter out some common properties
- // that the user probably isn't trying to
- // animate:
- // num*, min*, max*, *Index, *Threshold,
- // *Duration, *Id, *Limit
- matches.put(name, desc);
- }
- }
- }
- }
-
- List<AttributeDescriptor> sorted =
- new ArrayList<AttributeDescriptor>(matches.size());
- sorted.addAll(matches.values());
- Collections.sort(sorted);
- // Extract just the name+description pairs, since we don't want to
- // use the full attribute descriptor (which forces the namespace
- // prefix to be included)
- List<Pair<String, String>> pairs =
- new ArrayList<Pair<String, String>>(sorted.size());
- for (AttributeDescriptor d : sorted) {
- pairs.add(Pair.of(d.getXmlLocalName(), d.getAttributeInfo().getJavaDoc()));
- }
-
- addMatchingProposals(proposals, pairs.toArray(), offset, node, wordPrefix,
- (char) 0 /* needTag */, true /* isAttribute */, false /* isNew */,
- skipEndTag /* skipEndTag */, replaceLength);
- }
- }
-
- return false;
- } else {
- return super.computeAttributeValues(proposals, offset, parentTagName, attributeName,
- node, wordPrefix, skipEndTag, replaceLength);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/animator/AnimationEditorDelegate.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/animator/AnimationEditorDelegate.java
deleted file mode 100644
index 7c7051de7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/animator/AnimationEditorDelegate.java
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.animator;
-
-import static com.android.ide.eclipse.adt.AdtConstants.EDITORS_NAMESPACE;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlDelegate;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DocumentDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.resources.ResourceFolderType;
-
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-/**
- * Editor for /res/animator XML files.
- */
-@SuppressWarnings("restriction")
-public class AnimationEditorDelegate extends CommonXmlDelegate {
-
- public static class Creator implements IDelegateCreator {
- @Override
- @SuppressWarnings("unchecked")
- public AnimationEditorDelegate createForFile(
- @NonNull CommonXmlEditor delegator,
- @Nullable ResourceFolderType type) {
- if (ResourceFolderType.ANIM == type || ResourceFolderType.ANIMATOR == type) {
- return new AnimationEditorDelegate(delegator);
- }
-
- return null;
- }
- }
-
- /**
- * Old standalone-editor ID.
- * Use {@link CommonXmlEditor#ID} instead.
- */
- public static final String LEGACY_EDITOR_ID =
- EDITORS_NAMESPACE + ".animator.AnimationEditor"; //$NON-NLS-1$
-
- /** The tag used at the root */
- private String mRootTag;
-
- private AnimationEditorDelegate(CommonXmlEditor editor) {
- super(editor, new AnimationContentAssist());
- editor.addDefaultTargetListener();
- }
-
- @Override
- public void delegateCreateFormPages() {
- /* Disabled for now; doesn't work quite right
- try {
- addPage(new AnimatorTreePage(this));
- } catch (PartInitException e) {
- AdtPlugin.log(IStatus.ERROR, "Error creating nested page"); //$NON-NLS-1$
- AdtPlugin.getDefault().getLog().log(e.getStatus());
- }
- */
- }
-
- /**
- * Processes the new XML Model.
- *
- * @param xmlDoc The XML document, if available, or null if none exists.
- */
- @Override
- public void delegateXmlModelChanged(Document xmlDoc) {
- Element rootElement = xmlDoc.getDocumentElement();
- if (rootElement != null) {
- mRootTag = rootElement.getTagName();
- }
-
- // create the ui root node on demand.
- delegateInitUiRootNode(false /*force*/);
-
- if (mRootTag != null
- && !mRootTag.equals(getUiRootNode().getDescriptor().getXmlLocalName())) {
- AndroidTargetData data = getEditor().getTargetData();
- if (data != null) {
- ElementDescriptor descriptor;
- if (getFolderType() == ResourceFolderType.ANIM) {
- descriptor = data.getAnimDescriptors().getElementDescriptor(mRootTag);
- } else {
- descriptor = data.getAnimatorDescriptors().getElementDescriptor(mRootTag);
- }
- // Replace top level node now that we know the actual type
-
- // Disconnect from old
- getUiRootNode().setEditor(null);
- getUiRootNode().setXmlDocument(null);
-
- // Create new
- setUiRootNode(descriptor.createUiNode());
- getUiRootNode().setXmlDocument(xmlDoc);
- getUiRootNode().setEditor(getEditor());
- }
- }
-
- if (getUiRootNode().getDescriptor() instanceof DocumentDescriptor) {
- getUiRootNode().loadFromXmlNode(xmlDoc);
- } else {
- getUiRootNode().loadFromXmlNode(rootElement);
- }
- }
-
- @Override
- public void delegateInitUiRootNode(boolean force) {
- // The manifest UI node is always created, even if there's no corresponding XML node.
- if (getUiRootNode() == null || force) {
- ElementDescriptor descriptor;
- boolean reload = false;
- AndroidTargetData data = getEditor().getTargetData();
- if (data == null) {
- descriptor = new DocumentDescriptor("temp", null /*children*/);
- } else {
- if (getFolderType() == ResourceFolderType.ANIM) {
- descriptor = data.getAnimDescriptors().getElementDescriptor(mRootTag);
- } else {
- descriptor = data.getAnimatorDescriptors().getElementDescriptor(mRootTag);
- }
- reload = true;
- }
- setUiRootNode(descriptor.createUiNode());
- getUiRootNode().setEditor(getEditor());
-
- if (reload) {
- onDescriptorsChanged();
- }
- }
- }
-
- private ResourceFolderType getFolderType() {
- String folderName = AdtUtils.getParentFolderName(getEditor().getEditorInput());
- if (folderName.length() > 0) {
- return ResourceFolderType.getFolderType(folderName);
- }
- return ResourceFolderType.ANIMATOR;
- }
-
- private void onDescriptorsChanged() {
- IStructuredModel model = getEditor().getModelForRead();
- if (model != null) {
- try {
- Node node = getEditor().getXmlDocument(model).getDocumentElement();
- getUiRootNode().reloadFromXmlNode(node);
- } finally {
- model.releaseFromRead();
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/animator/AnimatorDescriptors.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/animator/AnimatorDescriptors.java
deleted file mode 100644
index 713f6d92e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/animator/AnimatorDescriptors.java
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.animator;
-
-import static com.android.SdkConstants.ANDROID_NS_NAME;
-import static com.android.SdkConstants.ANDROID_URI;
-
-import com.android.ide.common.resources.platform.DeclareStyleableInfo;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.IDescriptorProvider;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.XmlnsAttributeDescriptor;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Descriptors for /res/animator XML files.
- */
-public class AnimatorDescriptors implements IDescriptorProvider {
- /** The root element descriptor */
- private ElementDescriptor mDescriptor;
- /** The root element descriptors */
- private ElementDescriptor[] mRootDescriptors;
- private Map<String, ElementDescriptor> nameToDescriptor;
-
- /** @return the root descriptor. */
- @Override
- public ElementDescriptor getDescriptor() {
- if (mDescriptor == null) {
- mDescriptor = new ElementDescriptor("", getRootElementDescriptors()); //$NON-NLS-1$
- }
-
- return mDescriptor;
- }
-
- @Override
- public ElementDescriptor[] getRootElementDescriptors() {
- return mRootDescriptors;
- }
-
- ElementDescriptor getElementDescriptor(String rootTag) {
- if (nameToDescriptor == null) {
- nameToDescriptor = new HashMap<String, ElementDescriptor>();
- for (ElementDescriptor descriptor : getRootElementDescriptors()) {
- nameToDescriptor.put(descriptor.getXmlName(), descriptor);
- }
- }
-
- ElementDescriptor descriptor = nameToDescriptor.get(rootTag);
- if (descriptor == null) {
- descriptor = getDescriptor();
- }
- return descriptor;
- }
-
- public synchronized void updateDescriptors(Map<String, DeclareStyleableInfo> styleMap) {
- if (styleMap == null) {
- return;
- }
-
- XmlnsAttributeDescriptor xmlns = new XmlnsAttributeDescriptor(ANDROID_NS_NAME,
- ANDROID_URI);
-
- List<ElementDescriptor> descriptors = new ArrayList<ElementDescriptor>();
-
- String sdkUrl =
- "http://developer.android.com/guide/topics/graphics/animation.html"; //$NON-NLS-1$
-
- ElementDescriptor set = addElement(descriptors, styleMap,
- "set", "Animator Set", "AnimatorSet", null, //$NON-NLS-1$ //$NON-NLS-3$
- null /* tooltip */, sdkUrl,
- xmlns, null, true /*mandatory*/);
-
- ElementDescriptor objectAnimator = addElement(descriptors, styleMap,
- "objectAnimator", "Object Animator", //$NON-NLS-1$
- "PropertyAnimator", "Animator", //$NON-NLS-1$ //$NON-NLS-2$
- null /* tooltip */, sdkUrl,
- xmlns, null, true /*mandatory*/);
-
- ElementDescriptor animator = addElement(descriptors, styleMap,
- "animator", "Animator", "Animator", null, //$NON-NLS-1$ //$NON-NLS-3$
- null /* tooltip */, sdkUrl,
- xmlns, null, true /*mandatory*/);
-
- mRootDescriptors = descriptors.toArray(new ElementDescriptor[descriptors.size()]);
-
- // Allow arbitrary nesting: the children of all of these element can include
- // any of the others
- if (objectAnimator != null) {
- objectAnimator.setChildren(mRootDescriptors);
- }
- if (animator != null) {
- animator.setChildren(mRootDescriptors);
- }
- if (set != null) {
- set.setChildren(mRootDescriptors);
- }
- }
-
- /**
- * Looks up the given style, and if found creates a new {@link ElementDescriptor}
- * corresponding to the style. It can optionally take an extra style to merge in
- * additional attributes from, and an extra attribute to add in as well. The new
- * element, if it exists, can also be optionally added into a list.
- *
- * @param descriptors an optional list to add the element into, or null
- * @param styleMap The map style => attributes from the attrs.xml file
- * @param xmlName the XML tag name to use for the element
- * @param uiName the UI name to display the element as
- * @param styleName the name of the style which must exist for this style
- * @param extraStyle an optional extra style to merge in attributes from, or null
- * @param tooltip the tooltip or documentation for this element, or null
- * @param sdkUrl an optional SDK url to display for the element, or null
- * @param extraAttribute an extra attribute to add to the attributes list, or null
- * @param childrenElements an array of children allowed by this element, or null
- * @param mandatory if true, this element is mandatory
- * @return a newly created element, or null if the style does not exist
- */
- public static ElementDescriptor addElement(
- List<ElementDescriptor> descriptors,
- Map<String, DeclareStyleableInfo> styleMap,
- String xmlName, String uiName, String styleName, String extraStyle,
- String tooltip, String sdkUrl,
- AttributeDescriptor extraAttribute,
- ElementDescriptor[] childrenElements,
- boolean mandatory) {
- DeclareStyleableInfo style = styleMap.get(styleName);
- if (style == null) {
- return null;
- }
- ElementDescriptor element = new ElementDescriptor(xmlName, uiName, tooltip, sdkUrl,
- null, childrenElements, mandatory);
-
- ArrayList<AttributeDescriptor> descs = new ArrayList<AttributeDescriptor>();
-
- DescriptorsUtils.appendAttributes(descs,
- null, // elementName
- ANDROID_URI,
- style.getAttributes(),
- null, // requiredAttributes
- null); // overrides
- element.setTooltip(style.getJavaDoc());
-
- if (extraStyle != null) {
- style = styleMap.get(extraStyle);
- if (style != null) {
- DescriptorsUtils.appendAttributes(descs,
- null, // elementName
- ANDROID_URI,
- style.getAttributes(),
- null, // requiredAttributes
- null); // overrides
- }
- }
-
- if (extraAttribute != null) {
- descs.add(extraAttribute);
- }
-
- element.setAttributes(descs.toArray(new AttributeDescriptor[descs.size()]));
- if (descriptors != null) {
- descriptors.add(element);
- }
-
- return element;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/binaryxml/BinaryXMLDescriber.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/binaryxml/BinaryXMLDescriber.java
deleted file mode 100644
index 00bf7b0ac..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/binaryxml/BinaryXMLDescriber.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.binaryxml;
-
-import org.eclipse.core.runtime.QualifiedName;
-import org.eclipse.core.runtime.content.IContentDescriber;
-import org.eclipse.core.runtime.content.IContentDescription;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-
-/**
- * A content describer for Android binary xml files
- *
- * <p>
- * This class referenced by the "describer" configuration element in
- * extensions to the <code>org.eclipse.core.runtime.contentTypes</code>
- * extension point.
- * </p>
- *
- * References :
- * <a>http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob;
- * f=include/utils/ResourceTypes.h</a>
- *
- */
-public class BinaryXMLDescriber implements IContentDescriber {
-
- private static final int RES_XML_HEADER_SIZE = 8;
- private final static short RES_XML_TYPE = 0x0003;
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.core.runtime.content.IContentDescriber#describe(java.io.
- * InputStream, org.eclipse.core.runtime.content.IContentDescription)
- */
- @Override
- public int describe(InputStream contents, IContentDescription description) throws IOException {
- int status = INVALID;
- int length = 8;
- byte[] bytes = new byte[length];
- if (contents.read(bytes, 0, length) == length) {
- ByteBuffer buf = ByteBuffer.wrap(bytes);
- buf.order(ByteOrder.LITTLE_ENDIAN);
- short type = buf.getShort();
- short headerSize = buf.getShort();
- int size = buf.getInt(); // chunk size
- if (type == RES_XML_TYPE && headerSize == RES_XML_HEADER_SIZE) {
- status = VALID;
- }
- }
- return status;
- }
-
- /*
- * (non-Javadoc)
- * @see
- * org.eclipse.core.runtime.content.IContentDescriber#getSupportedOptions()
- */
- @Override
- public QualifiedName[] getSupportedOptions() {
- return new QualifiedName[0];
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/binaryxml/BinaryXMLMultiPageEditorPart.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/binaryxml/BinaryXMLMultiPageEditorPart.java
deleted file mode 100644
index ae6a35d08..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/binaryxml/BinaryXMLMultiPageEditorPart.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.binaryxml;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import org.eclipse.core.resources.IStorage;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jdt.core.IPackageFragmentRoot;
-import org.eclipse.jdt.internal.core.JarEntryFile;
-import org.eclipse.jdt.internal.ui.javaeditor.JarEntryEditorInput;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.wst.xml.ui.internal.tabletree.XMLMultiPageEditorPart;
-
-import java.io.File;
-
-/**
- * The XML editor is an editor that open Android xml files from the android.jar file
- * <p>
- * The editor checks if the file is contained in jar and is so,
- * convert editor input to XmlStorageEditorInput that handles
- * corresponding file from Android SDK.
- *
- */
-public class BinaryXMLMultiPageEditorPart extends XMLMultiPageEditorPart {
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.part.EditorPart#setInput(org.eclipse.ui.IEditorInput)
- */
- @Override
- protected void setInput(IEditorInput input) {
- if (input instanceof JarEntryEditorInput) {
- JarEntryEditorInput jarInput = (JarEntryEditorInput) input;
- IStorage storage = jarInput.getStorage();
- if (storage instanceof JarEntryFile) {
- JarEntryFile jarEntryFile = (JarEntryFile) storage;
- IPackageFragmentRoot fragmentRoot = jarEntryFile.getPackageFragmentRoot();
- if (fragmentRoot == null) {
- super.setInput(input);
- return;
- }
- IPath path = fragmentRoot.getPath();
- if (path == null) {
- super.setInput(input);
- return;
- }
- path = path.removeLastSegments(1);
- IPath filePath = path.append(SdkConstants.FD_DATA).append(
- jarEntryFile.getFullPath().toPortableString());
- File file = new File(filePath.toOSString());
- if (!(file.isFile())) {
- super.setInput(input);
- return;
- }
- try {
- XmlStorageEditorInput newInput = new XmlStorageEditorInput(
- new FileStorage(file));
- super.setInput(newInput);
- return;
- } catch (Exception e) {
- AdtPlugin.log(e, e.getMessage(), null);
- }
- }
- }
- super.setInput(input);
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/binaryxml/FileStorage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/binaryxml/FileStorage.java
deleted file mode 100644
index a8c918283..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/binaryxml/FileStorage.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.binaryxml;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import org.eclipse.core.resources.IStorage;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Status;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.InputStream;
-
-/**
- * Implementation of storage for a local file
- * (<code>java.io.File</code>).
- *
- * @see org.eclipse.core.resources.IStorage
- */
-
-public class FileStorage implements IStorage {
-
- /**
- * The file this storage refers to.
- */
- private File mFile = null;
-
- /**
- * Constructs and returns storage for the given file.
- *
- * @param file a local file
- */
- public FileStorage(File file) {
- mFile = file;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.core.resources.IStorage#getContents()
- */
- @Override
- public InputStream getContents() throws CoreException {
- InputStream stream = null;
- try {
- stream = new FileInputStream(mFile);
- } catch (Exception e) {
- throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.getDefault().getBundle()
- .getSymbolicName(), IStatus.ERROR, mFile.getAbsolutePath(), e));
- }
- return stream;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.core.resources.IStorage#getFullPath()
- */
- @Override
- public IPath getFullPath() {
- return new Path(mFile.getAbsolutePath());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.core.resources.IStorage#getName()
- */
- @Override
- public String getName() {
- return mFile.getName();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.core.resources.IStorage#isReadOnly()
- */
- @Override
- public boolean isReadOnly() {
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.core.runtime.IAdaptable#getAdapter(Class)
- */
- @Override
- public Object getAdapter(Class adapter) {
- return null;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#equals(java.lang.Object)
- */
- @Override
- public boolean equals(Object obj) {
- if (obj instanceof FileStorage) {
- return mFile.equals(((FileStorage) obj).mFile);
- }
- return super.equals(obj);
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#hashCode()
- */
- @Override
- public int hashCode() {
- return mFile.hashCode();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/binaryxml/XmlStorageEditorInput.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/binaryxml/XmlStorageEditorInput.java
deleted file mode 100644
index 646c67587..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/binaryxml/XmlStorageEditorInput.java
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.binaryxml;
-
-import org.eclipse.core.resources.IStorage;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.IPersistableElement;
-import org.eclipse.ui.IStorageEditorInput;
-
-/**
- * An editor input for a local file.
- */
-public class XmlStorageEditorInput implements IStorageEditorInput {
-
- /**
- * Storage associated with this editor input
- */
- IStorage mStorage = null;
-
- /**
- * Constructs an editor input on the given storage
- *
- * @param storage
- */
- public XmlStorageEditorInput(IStorage storage) {
- mStorage = storage;
- }
-
- /* (non-Javadoc)
- * @see IStorageEditorInput#getStorage()
- */
- @Override
- public IStorage getStorage() throws CoreException {
- return mStorage;
- }
-
- /* (non-Javadoc)
- * @see IInput#getStorage()
- */
- @Override
- public boolean exists() {
- return mStorage != null;
- }
-
- /* (non-Javadoc)
- * @see IEditorInput#getImageDescriptor()
- */
- @Override
- public ImageDescriptor getImageDescriptor() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see IEditorInput#getName()
- */
- @Override
- public String getName() {
- return mStorage.getName();
- }
-
- /* (non-Javadoc)
- * @see IEditorInput#getPersistable()
- */
- @Override
- public IPersistableElement getPersistable() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see IEditorInput#getToolTipText()
- */
- @Override
- public String getToolTipText() {
- return mStorage.getFullPath() != null ? mStorage.getFullPath().toString() : mStorage
- .getName();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.core.runtime.IAdaptable#getAdapter(Class)
- */
- @Override
- public Object getAdapter(Class adapter) {
- return null;
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#equals(java.lang.Object)
- */
- @Override
- public boolean equals(Object obj) {
- if (obj instanceof XmlStorageEditorInput) {
- return mStorage.equals(((XmlStorageEditorInput) obj).mStorage);
- }
- return super.equals(obj);
- }
-
- /* (non-Javadoc)
- * @see java.lang.Object#hashCode()
- */
- @Override
- public int hashCode() {
- return mStorage.hashCode();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/color/ColorContentAssist.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/color/ColorContentAssist.java
deleted file mode 100644
index 15704393e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/color/ColorContentAssist.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.color;
-
-import com.android.annotations.VisibleForTesting;
-import com.android.ide.eclipse.adt.internal.editors.AndroidContentAssist;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-
-/**
- * Content Assist Processor for /res/color XML files
- */
-@VisibleForTesting
-public final class ColorContentAssist extends AndroidContentAssist {
- public ColorContentAssist() {
- super(AndroidTargetData.DESCRIPTOR_COLOR);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/color/ColorDescriptors.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/color/ColorDescriptors.java
deleted file mode 100644
index 16add3ec9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/color/ColorDescriptors.java
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.color;
-
-import static com.android.SdkConstants.ANDROID_NS_NAME;
-import static com.android.SdkConstants.ANDROID_URI;
-
-import com.android.ide.common.api.IAttributeInfo.Format;
-import com.android.ide.common.resources.platform.AttributeInfo;
-import com.android.ide.common.resources.platform.DeclareStyleableInfo;
-import com.android.ide.eclipse.adt.internal.editors.animator.AnimatorDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.IDescriptorProvider;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ReferenceAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.XmlnsAttributeDescriptor;
-import com.android.resources.ResourceType;
-
-import java.util.Map;
-
-/** Descriptors for /res/color XML files */
-public class ColorDescriptors implements IDescriptorProvider {
- private static final String SDK_URL =
- "http://d.android.com/guide/topics/resources/color-list-resource.html"; //$NON-NLS-1$
-
- public static final String SELECTOR_TAG = "selector"; //$NON-NLS-1$
- public static final String ATTR_COLOR = "color"; //$NON-NLS-1$
-
- /** The root element descriptor */
- private ElementDescriptor mDescriptor = new ElementDescriptor(
- SELECTOR_TAG, "Selector",
- "Required. This must be the root element. Contains one or more <item> elements.",
- SDK_URL,
- new AttributeDescriptor[] {
- new XmlnsAttributeDescriptor(ANDROID_NS_NAME, ANDROID_URI) },
- null /*children: added later*/, true /*mandatory*/);
-
- /** @return the root descriptor. */
- @Override
- public ElementDescriptor getDescriptor() {
- if (mDescriptor == null) {
- mDescriptor = new ElementDescriptor("", getRootElementDescriptors()); //$NON-NLS-1$
- }
-
- return mDescriptor;
- }
-
- @Override
- public ElementDescriptor[] getRootElementDescriptors() {
- return new ElementDescriptor[] { mDescriptor };
- }
-
- public synchronized void updateDescriptors(Map<String, DeclareStyleableInfo> styleMap) {
- if (styleMap == null) {
- return;
- }
-
- // Selector children
- ElementDescriptor selectorItem = AnimatorDescriptors.addElement(null, styleMap,
- "item", "Item", "DrawableStates", null, //$NON-NLS-1$ //$NON-NLS-3$
- "Defines a drawable to use during certain states, as described by "
- + "its attributes. Must be a child of a <selector> element.",
- SDK_URL,
- new ReferenceAttributeDescriptor(
- ResourceType.COLOR, ATTR_COLOR,
- ANDROID_URI,
- new AttributeInfo(ATTR_COLOR, Format.COLOR_SET)).setTooltip(
- "Hexadeximal color. Required. The color is specified with an RGB value and "
- + "optional alpha channel.\n"
- + "The value always begins with a pound (#) character and then "
- + "followed by the Alpha-Red-Green-Blue information in one of "
- + "the following formats:\n"
- + "* RGB\n"
- + "* ARGB\n"
- + "* RRGGBB\n"
- + "* AARRGGBB"),
- null, /* This is wrong -- we can now embed any above drawable
- (but without xmlns as extra) */
- false /*mandatory*/);
-
- if (selectorItem != null) {
- mDescriptor.setChildren(new ElementDescriptor[] { selectorItem });
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/color/ColorEditorDelegate.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/color/ColorEditorDelegate.java
deleted file mode 100644
index 33896834c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/color/ColorEditorDelegate.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.color;
-
-import static com.android.ide.eclipse.adt.AdtConstants.EDITORS_NAMESPACE;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlDelegate;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.resources.ResourceFolderType;
-
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-/**
- * Editor for /res/color XML files.
- */
-@SuppressWarnings("restriction")
-public class ColorEditorDelegate extends CommonXmlDelegate {
-
- public static class Creator implements IDelegateCreator {
- @Override
- @SuppressWarnings("unchecked")
- public ColorEditorDelegate createForFile(
- @NonNull CommonXmlEditor delegator,
- @Nullable ResourceFolderType type) {
- if (ResourceFolderType.COLOR == type) {
- return new ColorEditorDelegate(delegator);
- }
-
- return null;
- }
- }
-
- /**
- * Old standalone-editor ID.
- * Use {@link CommonXmlEditor#ID} instead.
- */
- public static final String LEGACY_EDITOR_ID =
- EDITORS_NAMESPACE + ".color.ColorEditor"; //$NON-NLS-1$
-
-
- private ColorEditorDelegate(CommonXmlEditor editor) {
- super(editor, new ColorContentAssist());
- editor.addDefaultTargetListener();
- }
-
- @Override
- public void delegateCreateFormPages() {
- /* Disabled for now; doesn't work quite right
- try {
- addPage(new ColorTreePage(this));
- } catch (PartInitException e) {
- AdtPlugin.log(IStatus.ERROR, "Error creating nested page"); //$NON-NLS-1$
- AdtPlugin.getDefault().getLog().log(e.getStatus());
- }
- */
- }
-
- @Override
- public void delegateXmlModelChanged(Document xmlDoc) {
- // create the ui root node on demand.
- delegateInitUiRootNode(false /*force*/);
-
- Element rootElement = xmlDoc.getDocumentElement();
- getUiRootNode().loadFromXmlNode(rootElement);
- }
-
- @Override
- public void delegateInitUiRootNode(boolean force) {
- // The manifest UI node is always created, even if there's no corresponding XML node.
- if (getUiRootNode() == null || force) {
- ElementDescriptor descriptor;
- AndroidTargetData data = getEditor().getTargetData();
- if (data == null) {
- descriptor = new ColorDescriptors().getDescriptor();
- } else {
- descriptor = data.getColorDescriptors().getDescriptor();
- }
- setUiRootNode(descriptor.createUiNode());
- getUiRootNode().setEditor(getEditor());
- onDescriptorsChanged();
- }
- }
-
- private void onDescriptorsChanged() {
- IStructuredModel model = getEditor().getModelForRead();
- if (model != null) {
- try {
- Node node = getEditor().getXmlDocument(model).getDocumentElement();
- getUiRootNode().reloadFromXmlNode(node);
- } finally {
- model.releaseFromRead();
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/common/CommonActionContributor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/common/CommonActionContributor.java
deleted file mode 100755
index 5857b1532..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/common/CommonActionContributor.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.common;
-
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.part.EditorActionBarContributor;
-
-/**
- * Action contributor for the editors.
- * This delegates to editor-specific action contributors.
- */
-public class CommonActionContributor extends EditorActionBarContributor {
-
- public CommonActionContributor() {
- super();
- }
-
- @Override
- public void setActiveEditor(IEditorPart part) {
- LayoutEditorDelegate delegate = LayoutEditorDelegate.fromEditor(part);
- if (delegate != null) {
- delegate.setActiveEditor(part, getActionBars());
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/common/CommonMatchingStrategy.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/common/CommonMatchingStrategy.java
deleted file mode 100755
index 224c28fff..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/common/CommonMatchingStrategy.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.common;
-
-import static com.android.SdkConstants.FD_RES_LAYOUT;
-
-import com.android.ide.common.resources.ResourceFolder;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorMatchingStrategy;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.resources.ResourceFolderType;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorMatchingStrategy;
-import org.eclipse.ui.IEditorReference;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.part.FileEditorInput;
-
-/**
- * Matching strategy for the editors.
- * This finds the right MatchingStrategy and delegates to it.
- */
-public class CommonMatchingStrategy implements IEditorMatchingStrategy {
-
- @Override
- public boolean matches(IEditorReference editorRef, IEditorInput input) {
- if (input instanceof FileEditorInput) {
- FileEditorInput fileInput = (FileEditorInput)input;
-
- // get the IFile object and check it's in one of the layout folders.
- IFile file = fileInput.getFile();
- if (file.getParent().getName().startsWith(FD_RES_LAYOUT)) {
- ResourceFolder resFolder = ResourceManager.getInstance().getResourceFolder(file);
- if (resFolder != null && resFolder.getType() == ResourceFolderType.LAYOUT) {
- if (AdtPrefs.getPrefs().isSharedLayoutEditor()) {
- LayoutEditorMatchingStrategy m = new LayoutEditorMatchingStrategy();
- return m.matches(editorRef, fileInput);
- } else {
- // Skip files that don't match by name (see below). However, for
- // layout files we can't just use editorRef.getName(), since
- // the name sometimes includes the parent folder name (when the
- // files are in layout- folders.
- if (!(editorRef.getName().endsWith(file.getName()) &&
- editorRef.getId().equals(CommonXmlEditor.ID))) {
- return false;
- }
- }
- }
- } else {
- // Per the IEditorMatchingStrategy documentation, editorRef.getEditorInput()
- // is expensive so try exclude files that definitely don't match, such
- // as those with the wrong extension or wrong file name
- if (!(file.getName().equals(editorRef.getName()) &&
- editorRef.getId().equals(CommonXmlEditor.ID))) {
- return false;
- }
- }
-
- try {
- return input.equals(editorRef.getEditorInput());
- } catch (PartInitException e) {
- AdtPlugin.log(e, null);
- }
- }
-
- return false;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/common/CommonSourceViewerConfig.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/common/CommonSourceViewerConfig.java
deleted file mode 100755
index be31040c3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/common/CommonSourceViewerConfig.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.common;
-
-import com.android.ide.eclipse.adt.internal.editors.AndroidSourceViewerConfig;
-
-import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
-import org.eclipse.jface.text.source.ISourceViewer;
-
-
-
-/**
- * Source Viewer Configuration for the Common XML editor.
- * Everything is already generic and done in the base class.
- * The base class will use the delegate to find out the proper content assist to use.
- */
-public final class CommonSourceViewerConfig extends AndroidSourceViewerConfig {
-
- private final IContentAssistProcessor mContentAssist;
-
- public CommonSourceViewerConfig() {
- super();
- mContentAssist = null;
- }
-
- public CommonSourceViewerConfig(IContentAssistProcessor contentAssist) {
- super();
- mContentAssist = contentAssist;
- }
-
-
- /**
- * @return The {@link IContentAssistProcessor} passed to the constructor or null.
- */
- @Override
- public IContentAssistProcessor getAndroidContentAssistProcessor(
- ISourceViewer sourceViewer,
- String partitionType) {
- // You may think you could use AndroidXmlEditor.fromTextViewer(sourceViewer)
- // to find the editor associated with the sourceViewer and then access the
- // delegate and query the content assist specific to a given delegate.
- // Unfortunately this is invoked whilst the editor part is being created
- // so we can't match an existing editor to the source view -- since there
- // is no such "existing" editor. It's just being created.
- //
- // As a workaround, CommonXmlEditor#addPages() will unconfigure the
- // default sourceViewerConfig and reconfigure it with one that really
- // knows which content assist it should be using.
-
- return mContentAssist;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/common/CommonXmlDelegate.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/common/CommonXmlDelegate.java
deleted file mode 100755
index d9ee8a5d8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/common/CommonXmlDelegate.java
+++ /dev/null
@@ -1,249 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.common;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.resources.ResourceFolderType;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IURIEditorInput;
-import org.eclipse.ui.forms.editor.IFormPage;
-import org.eclipse.ui.part.EditorActionBarContributor;
-import org.eclipse.ui.part.FileEditorInput;
-import org.eclipse.ui.part.MultiPageEditorPart;
-import org.w3c.dom.Document;
-
-/**
- * Implementation of form editor for /res XML files.
- * <p/>
- * All delegates must have one {@link IDelegateCreator} instance
- * registered in the {@code DELEGATES[]} array of {@link CommonXmlEditor}.
- */
-public abstract class CommonXmlDelegate {
-
- /** The editor that created the delegate. Never null. */
- private final CommonXmlEditor mEditor;
-
- /** Root node of the UI element hierarchy. Can be null. */
- private UiElementNode mUiRootNode;
-
- private IContentAssistProcessor mContentAssist;
-
- /**
- * Static creator for {@link CommonXmlDelegate}s. Delegates implement a method
- * that will decide whether this delegate can be created for the given file input.
- */
- public interface IDelegateCreator {
- /**
- * Determines whether this delegate can handle the given file, typically
- * based on its resource path (e.g. ResourceManager#getResourceFolder).
- *
- * @param delegator The non-null instance of {@link CommonXmlEditor}.
- * @param type The {@link ResourceFolderType} of the folder containing the file,
- * if it can be determined. Null otherwise.
- * @return A new delegate that can handle that file or null.
- */
- public @Nullable <T extends CommonXmlDelegate> T createForFile(
- @NonNull CommonXmlEditor delegator,
- @Nullable ResourceFolderType type);
- }
-
- /** Implemented by delegates that need to support {@link EditorActionBarContributor} */
- public interface IActionContributorDelegate {
- /** Called from {@link EditorActionBarContributor#setActiveEditor(IEditorPart)}. */
- public void setActiveEditor(IEditorPart part, IActionBars bars);
- }
-
- protected CommonXmlDelegate(
- CommonXmlEditor editor,
- IContentAssistProcessor contentAssist) {
- mEditor = editor;
- mContentAssist = contentAssist;
- }
-
- public void dispose() {
- }
-
- /**
- * Returns the editor that created this delegate.
- *
- * @return the editor that created this delegate. Never null.
- */
- public @NonNull CommonXmlEditor getEditor() {
- return mEditor;
- }
-
- /**
- * @return The root node of the UI element hierarchy
- */
- public UiElementNode getUiRootNode() {
- return mUiRootNode;
- }
-
- protected void setUiRootNode(UiElementNode uiRootNode) {
- mUiRootNode = uiRootNode;
- }
-
- /** Called to compute the initial {@code UiRootNode}. */
- public abstract void delegateInitUiRootNode(boolean force);
-
- /**
- * Returns true, indicating the "save as" operation is supported by this editor.
- */
- public boolean isSaveAsAllowed() {
- return true;
- }
-
- /**
- * Create the various form pages.
- */
- public abstract void delegateCreateFormPages();
-
- public void delegatePostCreatePages() {
- // pass
- }
-
- /**
- * Changes the tab/title name to include the project name.
- */
- public void delegateSetInput(IEditorInput input) {
- if (input instanceof FileEditorInput) {
- FileEditorInput fileInput = (FileEditorInput) input;
- IFile file = fileInput.getFile();
- getEditor().setPartName(file.getName());
- } else if (input instanceof IURIEditorInput) {
- IURIEditorInput uriInput = (IURIEditorInput) input;
- String name = uriInput.getName();
- getEditor().setPartName(name);
- }
- }
-
- /**
- * Processes the new XML Model, which XML root node is given.
- *
- * @param xml_doc The XML document, if available, or null if none exists.
- */
- public abstract void delegateXmlModelChanged(Document xml_doc);
-
- public void delegatePageChange(int newPageIndex) {
- // pass
- }
-
- public void delegatePostPageChange(int newPageIndex) {
- // pass
- }
- /**
- * Save the XML.
- * <p/>
- * The actual save operation is done in the super class by committing
- * all data to the XML model and then having the Structured XML Editor
- * save the XML.
- * <p/>
- * Here we just need to tell the graphical editor that the model has
- * been saved.
- */
- public void delegateDoSave(IProgressMonitor monitor) {
- // pass
- }
-
- /**
- * Tells the editor to start a Lint check.
- * It's up to the caller to check whether this should be done depending on preferences.
- */
- public Job delegateRunLint() {
- return getEditor().startLintJob();
- }
-
-
- /**
- * Returns the custom IContentOutlinePage or IPropertySheetPage when asked for it.
- */
- public Object delegateGetAdapter(Class<?> adapter) {
- return null;
- }
-
- /**
- * Returns the {@link IContentAssistProcessor} associated with this editor.
- * Most implementations should lazily allocate one processor and always return the
- * same instance.
- * Must return null if there's no specific content assist processor for this editor.
- */
- public IContentAssistProcessor getAndroidContentAssistProcessor() {
- return mContentAssist;
- }
-
- /**
- * Does this editor participate in the "format GUI editor changes" option?
- *
- * @return false since editors do not support automatically formatting XML
- * affected by GUI changes unless they explicitly opt in to it.
- */
- public boolean delegateSupportsFormatOnGuiEdit() {
- return false;
- }
-
- /**
- * Called after the editor's active page has been set.
- *
- * @param superReturned the return value from
- * {@link MultiPageEditorPart#setActivePage(int)}
- * @param pageIndex the index of the page to be activated; the index must be
- * valid
- * @return the page, or null
- * @see MultiPageEditorPart#setActivePage(int)
- */
- public IFormPage delegatePostSetActivePage(IFormPage superReturned, String pageIndex) {
- return superReturned;
- }
-
- /** Called after an editor has been activated */
- public void delegateActivated() {
- }
-
- /** Called after an editor has been deactivated */
- public void delegateDeactivated() {
- }
-
- /**
- * Returns the name of the editor to be shown in the editor tab etc. Return
- * null to keep the default.
- *
- * @return the part name, or null to use the default
- */
- public String delegateGetPartName() {
- return null;
- }
-
- /**
- * Returns the persistence category, as described in
- * {@link AndroidXmlEditor#getPersistenceCategory}.
- *
- * @return the persistence category to use for this editor
- */
- public int delegateGetPersistenceCategory() {
- return AndroidXmlEditor.CATEGORY_OTHER;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/common/CommonXmlEditor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/common/CommonXmlEditor.java
deleted file mode 100755
index be06d38e2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/common/CommonXmlEditor.java
+++ /dev/null
@@ -1,467 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.common;
-
-import com.android.ide.common.resources.ResourceFolder;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.animator.AnimationEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.color.ColorEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlDelegate.IDelegateCreator;
-import com.android.ide.eclipse.adt.internal.editors.drawable.DrawableEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.menu.MenuEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.otherxml.OtherXmlEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.otherxml.PlainXmlEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.editors.values.ValuesEditorDelegate;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.resources.ResourceFolderType;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.text.source.ISourceViewerExtension2;
-import org.eclipse.ui.IEditorDescriptor;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.IShowEditorInput;
-import org.eclipse.ui.IURIEditorInput;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.forms.editor.IFormPage;
-import org.eclipse.ui.ide.IDE;
-import org.w3c.dom.Document;
-
-/**
- * Multi-page form editor for ALL /res XML files.
- * <p/>
- * This editor doesn't actually do anything. Instead, it defers actual implementation
- * to {@link CommonXmlDelegate} instances.
- */
-public class CommonXmlEditor extends AndroidXmlEditor implements IShowEditorInput {
-
- public static final String ID = AdtConstants.EDITORS_NAMESPACE + ".CommonXmlEditor"; //$NON-NLS-1$
-
- /**
- * Registered {@link CommonXmlDelegate}s.
- * All delegates must have a {@code Creator} class which is instantiated
- * once here statically. All the creators are invoked in the order they
- * are defined and the first one to return a non-null delegate is used.
- */
- private static final IDelegateCreator[] DELEGATES = {
- new LayoutEditorDelegate.Creator(),
- new ValuesEditorDelegate.Creator(),
- new AnimationEditorDelegate.Creator(),
- new ColorEditorDelegate.Creator(),
- new DrawableEditorDelegate.Creator(),
- new MenuEditorDelegate.Creator(),
- new OtherXmlEditorDelegate.Creator(),
- };
-
- /**
- * IDs of legacy editors replaced by the {@link CommonXmlEditor}.
- */
- public static final String[] LEGACY_EDITOR_IDS = {
- LayoutEditorDelegate.LEGACY_EDITOR_ID,
- ValuesEditorDelegate.LEGACY_EDITOR_ID,
- AnimationEditorDelegate.LEGACY_EDITOR_ID,
- ColorEditorDelegate.LEGACY_EDITOR_ID,
- DrawableEditorDelegate.LEGACY_EDITOR_ID,
- MenuEditorDelegate.LEGACY_EDITOR_ID,
- OtherXmlEditorDelegate.LEGACY_EDITOR_ID,
- };
-
- private CommonXmlDelegate mDelegate = null;
-
- /**
- * Creates the form editor for resources XML files.
- */
- public CommonXmlEditor() {
- super();
- }
-
- @Override
- public void init(IEditorSite site, final IEditorInput editorInput)
- throws PartInitException {
- if (editorInput instanceof IFileEditorInput) {
-
- IFileEditorInput fileInput = (IFileEditorInput) editorInput;
- IFile file = fileInput.getFile();
-
- // Adjust the default file editor ID
-
- IEditorDescriptor file_desc = IDE.getDefaultEditor(file);
- String id = file_desc == null ? null : file_desc.getId();
- boolean mustChange = id != null &&
- !id.equals(ID) &&
- id.startsWith(AdtConstants.EDITORS_NAMESPACE);
- if (!mustChange) {
- // Maybe this was opened by a manual Open With with a legacy ID?
- id = site.getId();
- mustChange = id != null &&
- !id.equals(ID) &&
- id.startsWith(AdtConstants.EDITORS_NAMESPACE);
- }
-
- if (mustChange) {
- // It starts by our editor namespace but it's not the right ID.
- // This is an old Android XML ID. Change it to our new ID.
- IDE.setDefaultEditor(file, ID);
- AdtPlugin.log(IStatus.INFO,
- "Changed legacy editor ID %s for %s", //$NON-NLS-1$
- id,
- file.getFullPath());
- }
-
- // Now find the delegate for the file.
-
- ResourceFolder resFolder = ResourceManager.getInstance().getResourceFolder(file);
- ResourceFolderType type = resFolder == null ? null : resFolder.getType();
-
- if (type == null) {
- // We lack any real resource information about that file.
- // Let's take a guess using the actual path.
- String folderName = AdtUtils.getParentFolderName(editorInput);
- type = ResourceFolderType.getFolderType(folderName);
- }
-
- if (type != null) {
- for (IDelegateCreator creator : DELEGATES) {
- mDelegate = creator.createForFile(this, type);
- if (mDelegate != null) {
- break;
- }
- }
- }
-
- if (mDelegate == null) {
- // We didn't find any editor.
- // We'll use the PlainXmlEditorDelegate as a catch-all editor.
- AdtPlugin.log(IStatus.INFO,
- "No valid Android XML Editor Delegate found for file %1$s [Res %2$s, type %3$s]",
- file.getFullPath(),
- resFolder,
- type);
- mDelegate = new PlainXmlEditorDelegate(this);
- }
- } else if (editorInput instanceof IURIEditorInput) {
- String folderName = AdtUtils.getParentFolderName(editorInput);
- ResourceFolderType type = ResourceFolderType.getFolderType(folderName);
- if (type == ResourceFolderType.LAYOUT) {
- // The layout editor has a lot of hardcoded requirements for real IFiles
- // and IProjects so for now just use a plain XML editor for project-less layout
- // files
- mDelegate = new OtherXmlEditorDelegate(this);
- } else if (type != null) {
- for (IDelegateCreator creator : DELEGATES) {
- mDelegate = creator.createForFile(this, type);
- if (mDelegate != null) {
- break;
- }
- }
- }
-
- if (mDelegate == null) {
- // We didn't find any editor.
- // We'll use the PlainXmlEditorDelegate as a catch-all editor.
- AdtPlugin.log(IStatus.INFO,
- "No valid Android XML Editor Delegate found for file %1$s [Res %2$s, type %3$s]",
- ((IURIEditorInput) editorInput).getURI().toString(),
- folderName,
- type);
- mDelegate = new PlainXmlEditorDelegate(this);
- }
- }
-
- if (mDelegate == null) {
- // We can't do anything if we don't have a valid file.
- AdtPlugin.log(IStatus.INFO,
- "Android XML Editor cannot process non-file input %1$s", //$NON-NLS-1$
- (editorInput == null ? "null" : editorInput.toString())); //$NON-NLS-1$
- throw new PartInitException("Android XML Editor cannot process this input.");
- } else {
- // Invoke the editor's init after setting up the delegate. This will call setInput().
- super.init(site, editorInput);
- }
- }
-
- /**
- * @return The root node of the UI element hierarchy
- */
- @Override
- public UiElementNode getUiRootNode() {
- return mDelegate == null ? null : mDelegate.getUiRootNode();
- }
-
- public CommonXmlDelegate getDelegate() {
- return mDelegate;
- }
-
- // ---- Base Class Overrides ----
-
- @Override
- public void dispose() {
- if (mDelegate != null) {
- mDelegate.dispose();
- }
-
- super.dispose();
- }
-
- /**
- * Save the XML.
- * <p/>
- * The actual save operation is done in the super class by committing
- * all data to the XML model and then having the Structured XML Editor
- * save the XML.
- * <p/>
- * Here we just need to tell the delegate that the model has
- * been saved.
- */
- @Override
- public void doSave(IProgressMonitor monitor) {
- super.doSave(monitor);
- if (mDelegate != null) {
- mDelegate.delegateDoSave(monitor);
- }
- }
-
- /**
- * Returns whether the "save as" operation is supported by this editor.
- * <p/>
- * Save-As is a valid operation for the ManifestEditor since it acts on a
- * single source file.
- *
- * @see IEditorPart
- */
- @Override
- public boolean isSaveAsAllowed() {
- return mDelegate == null ? false : mDelegate.isSaveAsAllowed();
- }
-
- /**
- * Create the various form pages.
- */
- @Override
- protected void createFormPages() {
- if (mDelegate != null) {
- mDelegate.delegateCreateFormPages();
- }
- }
-
- @Override
- protected void postCreatePages() {
- super.postCreatePages();
-
- if (mDelegate != null) {
- mDelegate.delegatePostCreatePages();
- }
- }
-
- @Override
- protected void addPages() {
- // Create the editor pages.
- // This will also create the EditorPart.
- super.addPages();
-
- // When the EditorPart is being created, it configures the SourceViewer
- // and will try to use our CommonSourceViewerConfig. Our config needs to
- // know which ContentAssist processor to use (since we have one per resource
- // folder type) but it doesn't have the necessary info to do so.
- // Consequently, once the part is created, we can now unconfigure the source
- // viewer and reconfigure it with the right settings.
- ISourceViewer ssv = getStructuredSourceViewer();
- if (mDelegate != null && ssv instanceof ISourceViewerExtension2) {
- ((ISourceViewerExtension2) ssv).unconfigure();
- ssv.configure(new CommonSourceViewerConfig(
- mDelegate.getAndroidContentAssistProcessor()));
- }
- }
-
- /* (non-java doc)
- * Change the tab/title name to include the name of the layout.
- */
- @Override
- protected void setInput(IEditorInput input) {
- super.setInput(input);
- assert mDelegate != null;
- if (mDelegate != null) {
- mDelegate.delegateSetInput(input);
- }
- }
-
- @Override
- public void setInputWithNotify(IEditorInput input) {
- super.setInputWithNotify(input);
- if (mDelegate instanceof LayoutEditorDelegate) {
- ((LayoutEditorDelegate) mDelegate).delegateSetInputWithNotify(input);
- }
- }
-
- /**
- * Processes the new XML Model, which XML root node is given.
- *
- * @param xml_doc The XML document, if available, or null if none exists.
- */
- @Override
- protected void xmlModelChanged(Document xml_doc) {
- if (mDelegate != null) {
- mDelegate.delegateXmlModelChanged(xml_doc);
- }
- }
-
- @Override
- protected Job runLint() {
- if (mDelegate != null && getEditorInput() instanceof IFileEditorInput) {
- return mDelegate.delegateRunLint();
- }
- return null;
- }
-
- /**
- * Returns the custom IContentOutlinePage or IPropertySheetPage when asked for it.
- */
- @Override
- public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
- if (mDelegate != null) {
- Object value = mDelegate.delegateGetAdapter(adapter);
- if (value != null) {
- return value;
- }
- }
-
- // return default
- return super.getAdapter(adapter);
- }
-
- @Override
- protected void pageChange(int newPageIndex) {
- if (mDelegate != null) {
- mDelegate.delegatePageChange(newPageIndex);
- }
-
- super.pageChange(newPageIndex);
-
- if (mDelegate != null) {
- mDelegate.delegatePostPageChange(newPageIndex);
- }
- }
-
- @Override
- protected int getPersistenceCategory() {
- if (mDelegate != null) {
- return mDelegate.delegateGetPersistenceCategory();
- }
- return CATEGORY_OTHER;
- }
-
- @Override
- public void initUiRootNode(boolean force) {
- if (mDelegate != null) {
- mDelegate.delegateInitUiRootNode(force);
- }
- }
-
- @Override
- public IFormPage setActivePage(String pageId) {
- IFormPage page = super.setActivePage(pageId);
-
- if (mDelegate != null) {
- return mDelegate.delegatePostSetActivePage(page, pageId);
- }
-
- return page;
- }
-
- /* Implements showEditorInput(...) in IShowEditorInput */
- @Override
- public void showEditorInput(IEditorInput editorInput) {
- if (mDelegate instanceof LayoutEditorDelegate) {
- ((LayoutEditorDelegate) mDelegate).showEditorInput(editorInput);
- }
- }
-
- @Override
- public boolean supportsFormatOnGuiEdit() {
- if (mDelegate != null) {
- return mDelegate.delegateSupportsFormatOnGuiEdit();
- }
- return super.supportsFormatOnGuiEdit();
- }
-
- @Override
- public void activated() {
- super.activated();
- if (mDelegate != null) {
- mDelegate.delegateActivated();
- }
- }
-
- @Override
- public void deactivated() {
- super.deactivated();
- if (mDelegate != null) {
- mDelegate.delegateDeactivated();
- }
- }
-
- @Override
- public String getPartName() {
- if (mDelegate != null) {
- String name = mDelegate.delegateGetPartName();
- if (name != null) {
- return name;
- }
- }
-
- return super.getPartName();
- }
-
- // --------------------
- // Base methods exposed so that XmlEditorDelegate can access them
-
- @Override
- public void setPartName(String partName) {
- super.setPartName(partName);
- }
-
- @Override
- public void setPageText(int pageIndex, String text) {
- super.setPageText(pageIndex, text);
- }
-
- @Override
- public void firePropertyChange(int propertyId) {
- super.firePropertyChange(propertyId);
- }
-
- @Override
- public int getPageCount() {
- return super.getPageCount();
- }
-
- @Override
- public int getCurrentPage() {
- return super.getCurrentPage();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/AttributeDescriptor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/AttributeDescriptor.java
deleted file mode 100644
index 345a109e6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/AttributeDescriptor.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.descriptors;
-
-import com.android.SdkConstants;
-import com.android.ide.common.api.IAttributeInfo;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-import org.eclipse.swt.graphics.Image;
-
-/**
- * {@link AttributeDescriptor} describes an XML attribute with its XML attribute name.
- * <p/>
- * An attribute descriptor also knows which UI node should be instantiated to represent
- * this particular attribute (e.g. text field, icon chooser, class selector, etc.)
- * Some attributes may be hidden and have no user interface at all.
- * <p/>
- * This is an abstract class. Derived classes must implement data description and return
- * the correct UiAttributeNode-derived class.
- */
-public abstract class AttributeDescriptor implements Comparable<AttributeDescriptor> {
- public static final String ATTRIBUTE_ICON_FILENAME = "attribute"; //$NON-NLS-1$
-
- private final String mXmlLocalName;
- private final String mNsUri;
- private final IAttributeInfo mAttrInfo;
- private ElementDescriptor mParent;
-
- /**
- * Creates a new {@link AttributeDescriptor}
- *
- * @param xmlLocalName The XML name of the attribute (case sensitive)
- * @param nsUri The URI of the attribute. Can be null if attribute has no namespace.
- * See {@link SdkConstants#NS_RESOURCES} for a common value.
- * @param attrInfo The {@link IAttributeInfo} of this attribute. Can't be null for a "real"
- * attribute representing a View element's attribute. Can be null for some
- * specialized internal attribute descriptors (e.g. hidden descriptors, XMLNS,
- * or attribute separator, all of which do not represent any real attribute.)
- */
- public AttributeDescriptor(String xmlLocalName, String nsUri, IAttributeInfo attrInfo) {
- assert xmlLocalName != null;
- mXmlLocalName = xmlLocalName;
- mNsUri = nsUri;
- mAttrInfo = attrInfo;
- }
-
- /** Returns the XML local name of the attribute (case sensitive). */
- public final String getXmlLocalName() {
- return mXmlLocalName;
- }
-
- /** Returns the namespace URI of this attribute. */
- public final String getNamespaceUri() {
- return mNsUri;
- }
-
- /** Sets the element descriptor to which this attribute is attached. */
- final void setParent(ElementDescriptor parent) {
- mParent = parent;
- }
-
- /** Returns the element descriptor to which this attribute is attached. */
- public final ElementDescriptor getParent() {
- return mParent;
- }
-
- /** Returns whether this attribute is deprecated (based on its attrs.xml javadoc.) */
- public boolean isDeprecated() {
- return mAttrInfo == null ? false : mAttrInfo.getDeprecatedDoc() != null;
- }
-
- /**
- * Returns the {@link IAttributeInfo} of this attribute.
- * Can't be null for real attributes.
- * Can be null for specialized internal attribute descriptors that do not correspond to
- * any real XML attribute.
- */
- public IAttributeInfo getAttributeInfo() {
- return mAttrInfo;
- }
-
- /**
- * Returns an optional icon for the attribute.
- * This icon is generic, that is all attribute descriptors have the same icon
- * no matter what they represent.
- *
- * @return An icon for this element or null.
- */
- public Image getGenericIcon() {
- return IconFactory.getInstance().getIcon(ATTRIBUTE_ICON_FILENAME);
- }
-
- /**
- * @param uiParent The {@link UiElementNode} parent of this UI attribute.
- * @return A new {@link UiAttributeNode} linked to this descriptor or null if this
- * attribute has no user interface.
- */
- public abstract UiAttributeNode createUiNode(UiElementNode uiParent);
-
- // Implements Comparable<AttributeDescriptor>
- @Override
- public int compareTo(AttributeDescriptor other) {
- return mXmlLocalName.compareTo(other.mXmlLocalName);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/AttributeDescriptorLabelProvider.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/AttributeDescriptorLabelProvider.java
deleted file mode 100644
index 32def6456..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/AttributeDescriptorLabelProvider.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.descriptors;
-
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAbstractTextAttributeNode;
-
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.swt.graphics.Image;
-
-/**
- * Label provider for {@link UiAbstractTextAttributeNode}.
- */
-public class AttributeDescriptorLabelProvider implements ILabelProvider {
-
- private final static AttributeDescriptorLabelProvider sThis =
- new AttributeDescriptorLabelProvider();
-
- public static ILabelProvider getProvider() {
- return sThis;
- }
-
- @Override
- public Image getImage(Object element) {
- if (element instanceof UiAbstractTextAttributeNode) {
- UiAbstractTextAttributeNode node = (UiAbstractTextAttributeNode) element;
- if (node.getDescriptor().isDeprecated()) {
- String v = node.getCurrentValue();
- if (v != null && v.length() > 0) {
- IconFactory factory = IconFactory.getInstance();
- return factory.getIcon("warning"); //$NON-NLS-1$
- }
- }
- }
-
- return null;
- }
-
- @Override
- public String getText(Object element) {
- if (element instanceof UiAbstractTextAttributeNode) {
- return ((UiAbstractTextAttributeNode)element).getCurrentValue();
- }
-
- return null;
- }
-
- @Override
- public void addListener(ILabelProviderListener listener) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public void dispose() {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public boolean isLabelProperty(Object element, String property) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public void removeListener(ILabelProviderListener listener) {
- // TODO Auto-generated method stub
-
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/BooleanAttributeDescriptor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/BooleanAttributeDescriptor.java
deleted file mode 100644
index 7d76687c2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/BooleanAttributeDescriptor.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.descriptors;
-
-import com.android.ide.common.api.IAttributeInfo;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiListAttributeNode;
-
-/**
- * Describes a text attribute that can only contain boolean values.
- * It is displayed by a {@link UiListAttributeNode}.
- */
-public class BooleanAttributeDescriptor extends ListAttributeDescriptor {
- private static final String[] VALUES = new String[] { "true", "false" }; //$NON-NLS-1$ //$NON-NLS-2$
-
- public BooleanAttributeDescriptor(String xmlLocalName, String nsUri, IAttributeInfo attrInfo) {
- super(xmlLocalName, nsUri, attrInfo, VALUES);
- }
-}
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/DescriptorsUtils.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/DescriptorsUtils.java
deleted file mode 100644
index da3a1856c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/DescriptorsUtils.java
+++ /dev/null
@@ -1,961 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.descriptors;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ATTR_LAYOUT_BELOW;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.ATTR_TEXT;
-import static com.android.SdkConstants.EDIT_TEXT;
-import static com.android.SdkConstants.EXPANDABLE_LIST_VIEW;
-import static com.android.SdkConstants.FQCN_ADAPTER_VIEW;
-import static com.android.SdkConstants.GALLERY;
-import static com.android.SdkConstants.GRID_LAYOUT;
-import static com.android.SdkConstants.GRID_VIEW;
-import static com.android.SdkConstants.GT_ENTITY;
-import static com.android.SdkConstants.ID_PREFIX;
-import static com.android.SdkConstants.LIST_VIEW;
-import static com.android.SdkConstants.LT_ENTITY;
-import static com.android.SdkConstants.NEW_ID_PREFIX;
-import static com.android.SdkConstants.RELATIVE_LAYOUT;
-import static com.android.SdkConstants.REQUEST_FOCUS;
-import static com.android.SdkConstants.SPACE;
-import static com.android.SdkConstants.VALUE_FILL_PARENT;
-import static com.android.SdkConstants.VALUE_WRAP_CONTENT;
-import static com.android.SdkConstants.VIEW_INCLUDE;
-import static com.android.SdkConstants.VIEW_MERGE;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.IAttributeInfo.Format;
-import com.android.ide.common.resources.platform.AttributeInfo;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiDocumentNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.resources.ResourceType;
-
-import org.eclipse.swt.graphics.Image;
-
-import java.util.ArrayList;
-import java.util.EnumSet;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-
-/**
- * Utility methods related to descriptors handling.
- */
-public final class DescriptorsUtils {
- private static final String DEFAULT_WIDGET_PREFIX = "widget";
-
- private static final int JAVADOC_BREAK_LENGTH = 60;
-
- /**
- * The path in the online documentation for the manifest description.
- * <p/>
- * This is NOT a complete URL. To be used, it needs to be appended
- * to {@link AdtConstants#CODESITE_BASE_URL} or to the local SDK
- * documentation.
- */
- public static final String MANIFEST_SDK_URL = "/reference/android/R.styleable.html#"; //$NON-NLS-1$
-
- public static final String IMAGE_KEY = "image"; //$NON-NLS-1$
-
- private static final String CODE = "$code"; //$NON-NLS-1$
- private static final String LINK = "$link"; //$NON-NLS-1$
- private static final String ELEM = "$elem"; //$NON-NLS-1$
- private static final String BREAK = "$break"; //$NON-NLS-1$
-
- /**
- * Add all {@link AttributeInfo} to the the array of {@link AttributeDescriptor}.
- *
- * @param attributes The list of {@link AttributeDescriptor} to append to
- * @param elementXmlName Optional XML local name of the element to which attributes are
- * being added. When not null, this is used to filter overrides.
- * @param nsUri The URI of the attribute. Can be null if attribute has no namespace.
- * See {@link SdkConstants#NS_RESOURCES} for a common value.
- * @param infos The array of {@link AttributeInfo} to read and append to attributes
- * @param requiredAttributes An optional set of attributes to mark as "required" (i.e. append
- * a "*" to their UI name as a hint for the user.) If not null, must contains
- * entries in the form "elem-name/attr-name". Elem-name can be "*".
- * @param overrides A map [attribute name => ITextAttributeCreator creator].
- */
- public static void appendAttributes(List<AttributeDescriptor> attributes,
- String elementXmlName,
- String nsUri, AttributeInfo[] infos,
- Set<String> requiredAttributes,
- Map<String, ITextAttributeCreator> overrides) {
- for (AttributeInfo info : infos) {
- boolean required = false;
- if (requiredAttributes != null) {
- String attr_name = info.getName();
- if (requiredAttributes.contains("*/" + attr_name) ||
- requiredAttributes.contains(elementXmlName + "/" + attr_name)) {
- required = true;
- }
- }
- appendAttribute(attributes, elementXmlName, nsUri, info, required, overrides);
- }
- }
-
- /**
- * Add an {@link AttributeInfo} to the the array of {@link AttributeDescriptor}.
- *
- * @param attributes The list of {@link AttributeDescriptor} to append to
- * @param elementXmlName Optional XML local name of the element to which attributes are
- * being added. When not null, this is used to filter overrides.
- * @param info The {@link AttributeInfo} to append to attributes
- * @param nsUri The URI of the attribute. Can be null if attribute has no namespace.
- * See {@link SdkConstants#NS_RESOURCES} for a common value.
- * @param required True if the attribute is to be marked as "required" (i.e. append
- * a "*" to its UI name as a hint for the user.)
- * @param overrides A map [attribute name => ITextAttributeCreator creator].
- */
- public static void appendAttribute(List<AttributeDescriptor> attributes,
- String elementXmlName,
- String nsUri,
- AttributeInfo info, boolean required,
- Map<String, ITextAttributeCreator> overrides) {
- TextAttributeDescriptor attr = null;
-
- String xmlLocalName = info.getName();
-
- // Add the known types to the tooltip
- EnumSet<Format> formats_set = info.getFormats();
- int flen = formats_set.size();
- if (flen > 0) {
- // Create a specialized attribute if we can
- if (overrides != null) {
- for (Entry<String, ITextAttributeCreator> entry: overrides.entrySet()) {
- // The override key can have the following formats:
- // */xmlLocalName
- // element/xmlLocalName
- // element1,element2,...,elementN/xmlLocalName
- String key = entry.getKey();
- String elements[] = key.split("/"); //$NON-NLS-1$
- String overrideAttrLocalName = null;
- if (elements.length < 1) {
- continue;
- } else if (elements.length == 1) {
- overrideAttrLocalName = elements[0];
- elements = null;
- } else {
- overrideAttrLocalName = elements[elements.length - 1];
- elements = elements[0].split(","); //$NON-NLS-1$
- }
-
- if (overrideAttrLocalName == null ||
- !overrideAttrLocalName.equals(xmlLocalName)) {
- continue;
- }
-
- boolean ok_element = elements != null && elements.length < 1;
- if (!ok_element && elements != null) {
- for (String element : elements) {
- if (element.equals("*") //$NON-NLS-1$
- || element.equals(elementXmlName)) {
- ok_element = true;
- break;
- }
- }
- }
-
- if (!ok_element) {
- continue;
- }
-
- ITextAttributeCreator override = entry.getValue();
- if (override != null) {
- attr = override.create(xmlLocalName, nsUri, info);
- }
- }
- } // if overrides
-
- // Create a specialized descriptor if we can, based on type
- if (attr == null) {
- if (formats_set.contains(Format.REFERENCE)) {
- // This is either a multi-type reference or a generic reference.
- attr = new ReferenceAttributeDescriptor(
- xmlLocalName, nsUri, info);
- } else if (formats_set.contains(Format.ENUM)) {
- attr = new ListAttributeDescriptor(
- xmlLocalName, nsUri, info);
- } else if (formats_set.contains(Format.FLAG)) {
- attr = new FlagAttributeDescriptor(
- xmlLocalName, nsUri, info);
- } else if (formats_set.contains(Format.BOOLEAN)) {
- attr = new BooleanAttributeDescriptor(
- xmlLocalName, nsUri, info);
- } else if (formats_set.contains(Format.STRING)) {
- attr = new ReferenceAttributeDescriptor(
- ResourceType.STRING, xmlLocalName, nsUri, info);
- }
- }
- }
-
- // By default a simple text field is used
- if (attr == null) {
- attr = new TextAttributeDescriptor(xmlLocalName, nsUri, info);
- }
-
- if (required) {
- attr.setRequired(true);
- }
-
- attributes.add(attr);
- }
-
- /**
- * Indicates the the given {@link AttributeInfo} already exists in the ArrayList of
- * {@link AttributeDescriptor}. This test for the presence of a descriptor with the same
- * XML name.
- *
- * @param attributes The list of {@link AttributeDescriptor} to compare to.
- * @param nsUri The URI of the attribute. Can be null if attribute has no namespace.
- * See {@link SdkConstants#NS_RESOURCES} for a common value.
- * @param info The {@link AttributeInfo} to know whether it is included in the above list.
- * @return True if this {@link AttributeInfo} is already present in
- * the {@link AttributeDescriptor} list.
- */
- public static boolean containsAttribute(ArrayList<AttributeDescriptor> attributes,
- String nsUri,
- AttributeInfo info) {
- String xmlLocalName = info.getName();
- for (AttributeDescriptor desc : attributes) {
- if (desc.getXmlLocalName().equals(xmlLocalName)) {
- if (nsUri == desc.getNamespaceUri() ||
- (nsUri != null && nsUri.equals(desc.getNamespaceUri()))) {
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * Create a pretty attribute UI name from an XML name.
- * <p/>
- * The original xml name starts with a lower case and is camel-case,
- * e.g. "maxWidthForView". The pretty name starts with an upper case
- * and has space separators, e.g. "Max width for view".
- */
- public static String prettyAttributeUiName(String name) {
- if (name.length() < 1) {
- return name;
- }
- StringBuilder buf = new StringBuilder(2 * name.length());
-
- char c = name.charAt(0);
- // Use upper case initial letter
- buf.append(Character.toUpperCase(c));
- int len = name.length();
- for (int i = 1; i < len; i++) {
- c = name.charAt(i);
- if (Character.isUpperCase(c)) {
- // Break camel case into separate words
- buf.append(' ');
- // Use a lower case initial letter for the next word, except if the
- // word is solely X, Y or Z.
- if (c >= 'X' && c <= 'Z' &&
- (i == len-1 ||
- (i < len-1 && Character.isUpperCase(name.charAt(i+1))))) {
- buf.append(c);
- } else {
- buf.append(Character.toLowerCase(c));
- }
- } else if (c == '_') {
- buf.append(' ');
- } else {
- buf.append(c);
- }
- }
-
- name = buf.toString();
-
- name = replaceAcronyms(name);
-
- return name;
- }
-
- /**
- * Similar to {@link #prettyAttributeUiName(String)}, but it will capitalize
- * all words, not just the first one.
- * <p/>
- * The original xml name starts with a lower case and is camel-case, e.g.
- * "maxWidthForView". The corresponding return value is
- * "Max Width For View".
- *
- * @param name the attribute name, which should be a camel case name, e.g.
- * "maxWidth"
- * @return the corresponding display name, e.g. "Max Width"
- */
- @NonNull
- public static String capitalize(@NonNull String name) {
- if (name.isEmpty()) {
- return name;
- }
- StringBuilder buf = new StringBuilder(2 * name.length());
-
- char c = name.charAt(0);
- // Use upper case initial letter
- buf.append(Character.toUpperCase(c));
- int len = name.length();
- for (int i = 1; i < len; i++) {
- c = name.charAt(i);
- if (Character.isUpperCase(c)) {
- // Break camel case into separate words
- buf.append(' ');
- // Use a lower case initial letter for the next word, except if the
- // word is solely X, Y or Z.
- buf.append(c);
- } else if (c == '_') {
- buf.append(' ');
- if (i < len -1 && Character.isLowerCase(name.charAt(i + 1))) {
- buf.append(Character.toUpperCase(name.charAt(i + 1)));
- i++;
- }
- } else {
- buf.append(c);
- }
- }
-
- name = buf.toString();
-
- name = replaceAcronyms(name);
-
- return name;
- }
-
- private static String replaceAcronyms(String name) {
- // Replace these acronyms by upper-case versions
- // - (?<=^| ) means "if preceded by a space or beginning of string"
- // - (?=$| ) means "if followed by a space or end of string"
- if (name.contains("sdk") || name.contains("Sdk")) {
- name = name.replaceAll("(?<=^| )[sS]dk(?=$| )", "SDK");
- }
- if (name.contains("uri") || name.contains("Uri")) {
- name = name.replaceAll("(?<=^| )[uU]ri(?=$| )", "URI");
- }
- if (name.contains("ime") || name.contains("Ime")) {
- name = name.replaceAll("(?<=^| )[iI]me(?=$| )", "IME");
- }
- if (name.contains("vm") || name.contains("Vm")) {
- name = name.replaceAll("(?<=^| )[vV]m(?=$| )", "VM");
- }
- if (name.contains("ui") || name.contains("Ui")) {
- name = name.replaceAll("(?<=^| )[uU]i(?=$| )", "UI");
- }
- return name;
- }
-
- /**
- * Formats the javadoc tooltip to be usable in a tooltip.
- */
- public static String formatTooltip(String javadoc) {
- ArrayList<String> spans = scanJavadoc(javadoc);
-
- StringBuilder sb = new StringBuilder();
- boolean needBreak = false;
-
- for (int n = spans.size(), i = 0; i < n; ++i) {
- String s = spans.get(i);
- if (CODE.equals(s)) {
- s = spans.get(++i);
- if (s != null) {
- sb.append('"').append(s).append('"');
- }
- } else if (LINK.equals(s)) {
- String base = spans.get(++i);
- String anchor = spans.get(++i);
- String text = spans.get(++i);
-
- if (base != null) {
- base = base.trim();
- }
- if (anchor != null) {
- anchor = anchor.trim();
- }
- if (text != null) {
- text = text.trim();
- }
-
- // If there's no text, use the anchor if there's one
- if (text == null || text.length() == 0) {
- text = anchor;
- }
-
- if (base != null && base.length() > 0) {
- if (text == null || text.length() == 0) {
- // If we still have no text, use the base as text
- text = base;
- }
- }
-
- if (text != null) {
- sb.append(text);
- }
-
- } else if (ELEM.equals(s)) {
- s = spans.get(++i);
- if (s != null) {
- sb.append(s);
- }
- } else if (BREAK.equals(s)) {
- needBreak = true;
- } else if (s != null) {
- if (needBreak && s.trim().length() > 0) {
- sb.append('\n');
- }
- sb.append(s);
- needBreak = false;
- }
- }
-
- return sb.toString();
- }
-
- /**
- * Formats the javadoc tooltip to be usable in a FormText.
- * <p/>
- * If the descriptor can provide an icon, the caller should provide
- * elementsDescriptor.getIcon() as "image" to FormText, e.g.:
- * <code>formText.setImage(IMAGE_KEY, elementsDescriptor.getIcon());</code>
- *
- * @param javadoc The javadoc to format. Cannot be null.
- * @param elementDescriptor The element descriptor parent of the javadoc. Cannot be null.
- * @param androidDocBaseUrl The base URL for the documentation. Cannot be null. Should be
- * <code>FrameworkResourceManager.getInstance().getDocumentationBaseUrl()</code>
- */
- public static String formatFormText(String javadoc,
- ElementDescriptor elementDescriptor,
- String androidDocBaseUrl) {
- ArrayList<String> spans = scanJavadoc(javadoc);
-
- String fullSdkUrl = androidDocBaseUrl + MANIFEST_SDK_URL;
- String sdkUrl = elementDescriptor.getSdkUrl();
- if (sdkUrl != null && sdkUrl.startsWith(MANIFEST_SDK_URL)) {
- fullSdkUrl = androidDocBaseUrl + sdkUrl;
- }
-
- StringBuilder sb = new StringBuilder();
-
- Image icon = elementDescriptor.getCustomizedIcon();
- if (icon != null) {
- sb.append("<form><li style=\"image\" value=\"" + //$NON-NLS-1$
- IMAGE_KEY + "\">"); //$NON-NLS-1$
- } else {
- sb.append("<form><p>"); //$NON-NLS-1$
- }
-
- for (int n = spans.size(), i = 0; i < n; ++i) {
- String s = spans.get(i);
- if (CODE.equals(s)) {
- s = spans.get(++i);
- if (elementDescriptor.getXmlName().equals(s) && fullSdkUrl != null) {
- sb.append("<a href=\""); //$NON-NLS-1$
- sb.append(fullSdkUrl);
- sb.append("\">"); //$NON-NLS-1$
- sb.append(s);
- sb.append("</a>"); //$NON-NLS-1$
- } else if (s != null) {
- sb.append('"').append(s).append('"');
- }
- } else if (LINK.equals(s)) {
- String base = spans.get(++i);
- String anchor = spans.get(++i);
- String text = spans.get(++i);
-
- if (base != null) {
- base = base.trim();
- }
- if (anchor != null) {
- anchor = anchor.trim();
- }
- if (text != null) {
- text = text.trim();
- }
-
- // If there's no text, use the anchor if there's one
- if (text == null || text.length() == 0) {
- text = anchor;
- }
-
- // TODO specialize with a base URL for views, menus & other resources
- // Base is empty for a local page anchor, in which case we'll replace it
- // by the element SDK URL if it exists.
- if ((base == null || base.length() == 0) && fullSdkUrl != null) {
- base = fullSdkUrl;
- }
-
- String url = null;
- if (base != null && base.length() > 0) {
- if (base.startsWith("http")) { //$NON-NLS-1$
- // If base looks an URL, use it, with the optional anchor
- url = base;
- if (anchor != null && anchor.length() > 0) {
- // If the base URL already has an anchor, it needs to be
- // removed first. If there's no anchor, we need to add "#"
- int pos = url.lastIndexOf('#');
- if (pos < 0) {
- url += "#"; //$NON-NLS-1$
- } else if (pos < url.length() - 1) {
- url = url.substring(0, pos + 1);
- }
-
- url += anchor;
- }
- } else if (text == null || text.length() == 0) {
- // If we still have no text, use the base as text
- text = base;
- }
- }
-
- if (url != null && text != null) {
- sb.append("<a href=\""); //$NON-NLS-1$
- sb.append(url);
- sb.append("\">"); //$NON-NLS-1$
- sb.append(text);
- sb.append("</a>"); //$NON-NLS-1$
- } else if (text != null) {
- sb.append("<b>").append(text).append("</b>"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- } else if (ELEM.equals(s)) {
- s = spans.get(++i);
- if (sdkUrl != null && s != null) {
- sb.append("<a href=\""); //$NON-NLS-1$
- sb.append(sdkUrl);
- sb.append("\">"); //$NON-NLS-1$
- sb.append(s);
- sb.append("</a>"); //$NON-NLS-1$
- } else if (s != null) {
- sb.append("<b>").append(s).append("</b>"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- } else if (BREAK.equals(s)) {
- // ignore line breaks in pseudo-HTML rendering
- } else if (s != null) {
- sb.append(s);
- }
- }
-
- if (icon != null) {
- sb.append("</li></form>"); //$NON-NLS-1$
- } else {
- sb.append("</p></form>"); //$NON-NLS-1$
- }
- return sb.toString();
- }
-
- private static ArrayList<String> scanJavadoc(String javadoc) {
- ArrayList<String> spans = new ArrayList<String>();
-
- // Standardize all whitespace in the javadoc to single spaces.
- if (javadoc != null) {
- javadoc = javadoc.replaceAll("[ \t\f\r\n]+", " "); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- // Detects {@link <base>#<name> <text>} where all 3 are optional
- Pattern p_link = Pattern.compile("\\{@link\\s+([^#\\}\\s]*)(?:#([^\\s\\}]*))?(?:\\s*([^\\}]*))?\\}(.*)"); //$NON-NLS-1$
- // Detects <code>blah</code>
- Pattern p_code = Pattern.compile("<code>(.+?)</code>(.*)"); //$NON-NLS-1$
- // Detects @blah@, used in hard-coded tooltip descriptors
- Pattern p_elem = Pattern.compile("@([\\w -]+)@(.*)"); //$NON-NLS-1$
- // Detects a buffer that starts by @@ (request for a break)
- Pattern p_break = Pattern.compile("@@(.*)"); //$NON-NLS-1$
- // Detects a buffer that starts by @ < or { (one that was not matched above)
- Pattern p_open = Pattern.compile("([@<\\{])(.*)"); //$NON-NLS-1$
- // Detects everything till the next potential separator, i.e. @ < or {
- Pattern p_text = Pattern.compile("([^@<\\{]+)(.*)"); //$NON-NLS-1$
-
- int currentLength = 0;
- String text = null;
-
- while(javadoc != null && javadoc.length() > 0) {
- Matcher m;
- String s = null;
- if ((m = p_code.matcher(javadoc)).matches()) {
- spans.add(CODE);
- spans.add(text = cleanupJavadocHtml(m.group(1))); // <code> text
- javadoc = m.group(2);
- if (text != null) {
- currentLength += text.length();
- }
- } else if ((m = p_link.matcher(javadoc)).matches()) {
- spans.add(LINK);
- spans.add(m.group(1)); // @link base
- spans.add(m.group(2)); // @link anchor
- spans.add(text = cleanupJavadocHtml(m.group(3))); // @link text
- javadoc = m.group(4);
- if (text != null) {
- currentLength += text.length();
- }
- } else if ((m = p_elem.matcher(javadoc)).matches()) {
- spans.add(ELEM);
- spans.add(text = cleanupJavadocHtml(m.group(1))); // @text@
- javadoc = m.group(2);
- if (text != null) {
- currentLength += text.length() - 2;
- }
- } else if ((m = p_break.matcher(javadoc)).matches()) {
- spans.add(BREAK);
- currentLength = 0;
- javadoc = m.group(1);
- } else if ((m = p_open.matcher(javadoc)).matches()) {
- s = m.group(1);
- javadoc = m.group(2);
- } else if ((m = p_text.matcher(javadoc)).matches()) {
- s = m.group(1);
- javadoc = m.group(2);
- } else {
- // This is not supposed to happen. In case of, just use everything.
- s = javadoc;
- javadoc = null;
- }
- if (s != null && s.length() > 0) {
- s = cleanupJavadocHtml(s);
-
- if (currentLength >= JAVADOC_BREAK_LENGTH) {
- spans.add(BREAK);
- currentLength = 0;
- }
- while (currentLength + s.length() > JAVADOC_BREAK_LENGTH) {
- int pos = s.indexOf(' ', JAVADOC_BREAK_LENGTH - currentLength);
- if (pos <= 0) {
- break;
- }
- spans.add(s.substring(0, pos + 1));
- spans.add(BREAK);
- currentLength = 0;
- s = s.substring(pos + 1);
- }
-
- spans.add(s);
- currentLength += s.length();
- }
- }
-
- return spans;
- }
-
- /**
- * Remove anything that looks like HTML from a javadoc snippet, as it is supported
- * neither by FormText nor a standard text tooltip.
- */
- private static String cleanupJavadocHtml(String s) {
- if (s != null) {
- s = s.replaceAll(LT_ENTITY, "\""); //$NON-NLS-1$ $NON-NLS-2$
- s = s.replaceAll(GT_ENTITY, "\""); //$NON-NLS-1$ $NON-NLS-2$
- s = s.replaceAll("<[^>]+>", ""); //$NON-NLS-1$ $NON-NLS-2$
- }
- return s;
- }
-
- /**
- * Returns the basename for the given fully qualified class name. It is okay to pass
- * a basename to this method which will just be returned back.
- *
- * @param fqcn The fully qualified class name to convert
- * @return the basename of the class name
- */
- public static String getBasename(String fqcn) {
- String name = fqcn;
- int lastDot = name.lastIndexOf('.');
- if (lastDot != -1) {
- name = name.substring(lastDot + 1);
- }
-
- return name;
- }
-
- /**
- * Sets the default layout attributes for the a new UiElementNode.
- * <p/>
- * Note that ideally the node should already be part of a hierarchy so that its
- * parent layout and previous sibling can be determined, if any.
- * <p/>
- * This does not override attributes which are not empty.
- */
- public static void setDefaultLayoutAttributes(UiElementNode node, boolean updateLayout) {
- // if this ui_node is a layout and we're adding it to a document, use match_parent for
- // both W/H. Otherwise default to wrap_layout.
- ElementDescriptor descriptor = node.getDescriptor();
-
- String name = descriptor.getXmlLocalName();
- if (name.equals(REQUEST_FOCUS)) {
- // Don't add ids, widths and heights etc to <requestFocus>
- return;
- }
-
- // Width and height are mandatory in all layouts except GridLayout
- boolean setSize = !node.getUiParent().getDescriptor().getXmlName().equals(GRID_LAYOUT);
- if (setSize) {
- boolean fill = descriptor.hasChildren() &&
- node.getUiParent() instanceof UiDocumentNode;
- node.setAttributeValue(
- ATTR_LAYOUT_WIDTH,
- ANDROID_URI,
- fill ? VALUE_FILL_PARENT : VALUE_WRAP_CONTENT,
- false /* override */);
- node.setAttributeValue(
- ATTR_LAYOUT_HEIGHT,
- ANDROID_URI,
- fill ? VALUE_FILL_PARENT : VALUE_WRAP_CONTENT,
- false /* override */);
- }
-
- if (needsDefaultId(node.getDescriptor())) {
- String freeId = getFreeWidgetId(node);
- if (freeId != null) {
- node.setAttributeValue(
- ATTR_ID,
- ANDROID_URI,
- freeId,
- false /* override */);
- }
- }
-
- // Set a text attribute on textual widgets -- but only on those that define a text
- // attribute
- if (descriptor.definesAttribute(ANDROID_URI, ATTR_TEXT)
- // Don't set default text value into edit texts - they typically start out blank
- && !descriptor.getXmlLocalName().equals(EDIT_TEXT)) {
- String type = getBasename(descriptor.getUiName());
- node.setAttributeValue(
- ATTR_TEXT,
- ANDROID_URI,
- type,
- false /*override*/);
- }
-
- if (updateLayout) {
- UiElementNode parent = node.getUiParent();
- if (parent != null &&
- parent.getDescriptor().getXmlLocalName().equals(
- RELATIVE_LAYOUT)) {
- UiElementNode previous = node.getUiPreviousSibling();
- if (previous != null) {
- String id = previous.getAttributeValue(ATTR_ID);
- if (id != null && id.length() > 0) {
- id = id.replace("@+", "@"); //$NON-NLS-1$ //$NON-NLS-2$
- node.setAttributeValue(
- ATTR_LAYOUT_BELOW,
- ANDROID_URI,
- id,
- false /* override */);
- }
- }
- }
- }
- }
-
- /**
- * Determines whether new views of the given type should be assigned a
- * default id.
- *
- * @param descriptor a descriptor describing the view to look up
- * @return true if new views of the given type should be assigned a default
- * id
- */
- public static boolean needsDefaultId(ElementDescriptor descriptor) {
- // By default, layouts do not need ids.
- String tag = descriptor.getXmlLocalName();
- if (tag.endsWith("Layout") //$NON-NLS-1$
- || tag.equals(VIEW_INCLUDE)
- || tag.equals(VIEW_MERGE)
- || tag.equals(SPACE)
- || tag.endsWith(SPACE) && tag.length() > SPACE.length() &&
- tag.charAt(tag.length() - SPACE.length()) == '.') {
- return false;
- }
-
- return true;
- }
-
- /**
- * Given a UI node, returns the first available id that matches the
- * pattern "prefix%d".
- * <p/>TabWidget is a special case and the method will always return "@android:id/tabs".
- *
- * @param uiNode The UI node that gives the prefix to match.
- * @return A suitable generated id in the attribute form needed by the XML id tag
- * (e.g. "@+id/something")
- */
- public static String getFreeWidgetId(UiElementNode uiNode) {
- String name = getBasename(uiNode.getDescriptor().getXmlLocalName());
- return getFreeWidgetId(uiNode.getUiRoot(), name);
- }
-
- /**
- * Given a UI root node and a potential XML node name, returns the first available
- * id that matches the pattern "prefix%d".
- * <p/>TabWidget is a special case and the method will always return "@android:id/tabs".
- *
- * @param uiRoot The root UI node to search for name conflicts from
- * @param name The XML node prefix name to look for
- * @return A suitable generated id in the attribute form needed by the XML id tag
- * (e.g. "@+id/something")
- */
- public static String getFreeWidgetId(UiElementNode uiRoot, String name) {
- if ("TabWidget".equals(name)) { //$NON-NLS-1$
- return "@android:id/tabs"; //$NON-NLS-1$
- }
-
- return NEW_ID_PREFIX + getFreeWidgetId(uiRoot,
- new Object[] { name, null, null, null });
- }
-
- /**
- * Given a UI root node, returns the first available id that matches the
- * pattern "prefix%d".
- *
- * For recursion purposes, a "context" is given. Since Java doesn't have in-out parameters
- * in methods and we're not going to do a dedicated type, we just use an object array which
- * must contain one initial item and several are built on the fly just for internal storage:
- * <ul>
- * <li> prefix(String): The prefix of the generated id, i.e. "widget". Cannot be null.
- * <li> index(Integer): The minimum index of the generated id. Must start with null.
- * <li> generated(String): The generated widget currently being searched. Must start with null.
- * <li> map(Set<String>): A set of the ids collected so far when walking through the widget
- * hierarchy. Must start with null.
- * </ul>
- *
- * @param uiRoot The Ui root node where to start searching recursively. For the initial call
- * you want to pass the document root.
- * @param params An in-out context of parameters used during recursion, as explained above.
- * @return A suitable generated id
- */
- @SuppressWarnings("unchecked")
- private static String getFreeWidgetId(UiElementNode uiRoot,
- Object[] params) {
-
- Set<String> map = (Set<String>)params[3];
- if (map == null) {
- params[3] = map = new HashSet<String>();
- }
-
- int num = params[1] == null ? 0 : ((Integer)params[1]).intValue();
-
- String generated = (String) params[2];
- String prefix = (String) params[0];
- if (generated == null) {
- int pos = prefix.indexOf('.');
- if (pos >= 0) {
- prefix = prefix.substring(pos + 1);
- }
- pos = prefix.indexOf('$');
- if (pos >= 0) {
- prefix = prefix.substring(pos + 1);
- }
- prefix = prefix.replaceAll("[^a-zA-Z]", ""); //$NON-NLS-1$ $NON-NLS-2$
- if (prefix.length() == 0) {
- prefix = DEFAULT_WIDGET_PREFIX;
- } else {
- // Lowercase initial character
- prefix = Character.toLowerCase(prefix.charAt(0)) + prefix.substring(1);
- }
-
- // Note that we perform locale-independent lowercase checks; in "Image" we
- // want the lowercase version to be "image", not "?mage" where ? is
- // the char LATIN SMALL LETTER DOTLESS I.
- do {
- num++;
- generated = String.format("%1$s%2$d", prefix, num); //$NON-NLS-1$
- } while (map.contains(generated.toLowerCase(Locale.US)));
-
- params[0] = prefix;
- params[1] = num;
- params[2] = generated;
- }
-
- String id = uiRoot.getAttributeValue(ATTR_ID);
- if (id != null) {
- id = id.replace(NEW_ID_PREFIX, ""); //$NON-NLS-1$
- id = id.replace(ID_PREFIX, ""); //$NON-NLS-1$
- if (map.add(id.toLowerCase(Locale.US))
- && map.contains(generated.toLowerCase(Locale.US))) {
-
- do {
- num++;
- generated = String.format("%1$s%2$d", prefix, num); //$NON-NLS-1$
- } while (map.contains(generated.toLowerCase(Locale.US)));
-
- params[1] = num;
- params[2] = generated;
- }
- }
-
- for (UiElementNode uiChild : uiRoot.getUiChildren()) {
- getFreeWidgetId(uiChild, params);
- }
-
- // Note: return params[2] (not "generated") since it could have changed during recursion.
- return (String) params[2];
- }
-
- /**
- * Returns true if the given descriptor represents a view that not only can have
- * children but which allows us to <b>insert</b> children. Some views, such as
- * ListView (and in general all AdapterViews), disallow children to be inserted except
- * through the dedicated AdapterView interface to do it.
- *
- * @param descriptor the descriptor for the view in question
- * @param viewObject an actual instance of the view, or null if not available
- * @return true if the descriptor describes a view which allows insertion of child
- * views
- */
- public static boolean canInsertChildren(ElementDescriptor descriptor, Object viewObject) {
- if (descriptor.hasChildren()) {
- if (viewObject != null) {
- // We have a view object; see if it derives from an AdapterView
- Class<?> clz = viewObject.getClass();
- while (clz != null) {
- if (clz.getName().equals(FQCN_ADAPTER_VIEW)) {
- return false;
- }
- clz = clz.getSuperclass();
- }
- } else {
- // No view object, so we can't easily look up the class and determine
- // whether it's an AdapterView; instead, look at the fixed list of builtin
- // concrete subclasses of AdapterView
- String viewName = descriptor.getXmlLocalName();
- if (viewName.equals(LIST_VIEW) || viewName.equals(EXPANDABLE_LIST_VIEW)
- || viewName.equals(GALLERY) || viewName.equals(GRID_VIEW)) {
-
- // We should really also enforce that
- // XmlUtils.ANDROID_URI.equals(descriptor.getNameSpace())
- // here and if not, return true, but it turns out the getNameSpace()
- // for elements are often "".
-
- return false;
- }
- }
-
- return true;
- }
-
- return false;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/DocumentDescriptor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/DocumentDescriptor.java
deleted file mode 100644
index 695327847..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/DocumentDescriptor.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.descriptors;
-
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiDocumentNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-/**
- * {@link DocumentDescriptor} describes the properties expected for an XML document node.
- *
- * Compared to ElementDescriptor, {@link DocumentDescriptor} does not have XML name nor UI name,
- * tooltip, SDK url and attributes list.
- * <p/>
- * It has a children list which represent all the possible roots of the document.
- * <p/>
- * The document nodes are "mandatory", meaning the UI node is never deleted and it may lack
- * an actual XML node attached.
- */
-public class DocumentDescriptor extends ElementDescriptor {
-
- /**
- * Constructs a new {@link DocumentDescriptor} based on its XML name and children list.
- * The UI name is build by capitalizing the XML name.
- * The UI nodes will be non-mandatory.
- * <p/>
- * The XML name is never shown in the UI directly. It is however used when an icon
- * needs to be found for the node.
- *
- * @param xml_name The XML element node name. Case sensitive.
- * @param children The list of allowed children. Can be null or empty.
- */
- public DocumentDescriptor(String xml_name, ElementDescriptor[] children) {
- super(xml_name, children, Mandatory.MANDATORY);
- }
-
- /**
- * @return A new {@link UiElementNode} linked to this descriptor.
- */
- @Override
- public UiElementNode createUiNode() {
- return new UiDocumentNode(this);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/ElementDescriptor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/ElementDescriptor.java
deleted file mode 100644
index 0d62ec00c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/ElementDescriptor.java
+++ /dev/null
@@ -1,485 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.descriptors;
-
-import static com.android.SdkConstants.ANDROID_NS_NAME_PREFIX;
-import static com.android.SdkConstants.ANDROID_URI;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.graphics.Image;
-
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Set;
-
-/**
- * {@link ElementDescriptor} describes the properties expected for a given XML element node.
- *
- * {@link ElementDescriptor} have an XML name, UI name, a tooltip, an SDK url,
- * an attributes list and a children list.
- *
- * An UI node can be "mandatory", meaning the UI node is never deleted and it may lack
- * an actual XML node attached. A non-mandatory UI node MUST have an XML node attached
- * and it will cease to exist when the XML node ceases to exist.
- */
-public class ElementDescriptor implements Comparable<ElementDescriptor> {
- private static final String ELEMENT_ICON_FILENAME = "element"; //$NON-NLS-1$
-
- /** The XML element node name. Case sensitive. */
- protected final String mXmlName;
- /** The XML element name for the user interface, typically capitalized. */
- private final String mUiName;
- /** The list of allowed attributes. */
- private AttributeDescriptor[] mAttributes;
- /** The list of allowed children */
- private ElementDescriptor[] mChildren;
- /* An optional tooltip. Can be empty. */
- private String mTooltip;
- /** An optional SKD URL. Can be empty. */
- private String mSdkUrl;
- /** Whether this UI node must always exist (even for empty models). */
- private final Mandatory mMandatory;
-
- public enum Mandatory {
- NOT_MANDATORY,
- MANDATORY,
- MANDATORY_LAST
- }
-
- /**
- * Constructs a new {@link ElementDescriptor} based on its XML name, UI name,
- * tooltip, SDK url, attributes list, children list and mandatory.
- *
- * @param xml_name The XML element node name. Case sensitive.
- * @param ui_name The XML element name for the user interface, typically capitalized.
- * @param tooltip An optional tooltip. Can be null or empty.
- * @param sdk_url An optional SKD URL. Can be null or empty.
- * @param attributes The list of allowed attributes. Can be null or empty.
- * @param children The list of allowed children. Can be null or empty.
- * @param mandatory Whether this node must always exist (even for empty models). A mandatory
- * UI node is never deleted and it may lack an actual XML node attached. A non-mandatory
- * UI node MUST have an XML node attached and it will cease to exist when the XML node
- * ceases to exist.
- */
- public ElementDescriptor(String xml_name, String ui_name, String tooltip, String sdk_url,
- AttributeDescriptor[] attributes,
- ElementDescriptor[] children,
- Mandatory mandatory) {
- mMandatory = mandatory;
- mXmlName = xml_name;
- mUiName = ui_name;
- mTooltip = (tooltip != null && tooltip.length() > 0) ? tooltip : null;
- mSdkUrl = (sdk_url != null && sdk_url.length() > 0) ? sdk_url : null;
- setAttributes(attributes != null ? attributes : new AttributeDescriptor[]{});
- mChildren = children != null ? children : new ElementDescriptor[]{};
- }
-
- /**
- * Constructs a new {@link ElementDescriptor} based on its XML name, UI name,
- * tooltip, SDK url, attributes list, children list and mandatory.
- *
- * @param xml_name The XML element node name. Case sensitive.
- * @param ui_name The XML element name for the user interface, typically capitalized.
- * @param tooltip An optional tooltip. Can be null or empty.
- * @param sdk_url An optional SKD URL. Can be null or empty.
- * @param attributes The list of allowed attributes. Can be null or empty.
- * @param children The list of allowed children. Can be null or empty.
- * @param mandatory Whether this node must always exist (even for empty models). A mandatory
- * UI node is never deleted and it may lack an actual XML node attached. A non-mandatory
- * UI node MUST have an XML node attached and it will cease to exist when the XML node
- * ceases to exist.
- */
- public ElementDescriptor(String xml_name, String ui_name, String tooltip, String sdk_url,
- AttributeDescriptor[] attributes,
- ElementDescriptor[] children,
- boolean mandatory) {
- mMandatory = mandatory ? Mandatory.MANDATORY : Mandatory.NOT_MANDATORY;
- mXmlName = xml_name;
- mUiName = ui_name;
- mTooltip = (tooltip != null && tooltip.length() > 0) ? tooltip : null;
- mSdkUrl = (sdk_url != null && sdk_url.length() > 0) ? sdk_url : null;
- setAttributes(attributes != null ? attributes : new AttributeDescriptor[]{});
- mChildren = children != null ? children : new ElementDescriptor[]{};
- }
-
- /**
- * Constructs a new {@link ElementDescriptor} based on its XML name and children list.
- * The UI name is build by capitalizing the XML name.
- * The UI nodes will be non-mandatory.
- *
- * @param xml_name The XML element node name. Case sensitive.
- * @param children The list of allowed children. Can be null or empty.
- * @param mandatory Whether this node must always exist (even for empty models). A mandatory
- * UI node is never deleted and it may lack an actual XML node attached. A non-mandatory
- * UI node MUST have an XML node attached and it will cease to exist when the XML node
- * ceases to exist.
- */
- public ElementDescriptor(String xml_name, ElementDescriptor[] children, Mandatory mandatory) {
- this(xml_name, prettyName(xml_name), null, null, null, children, mandatory);
- }
-
- /**
- * Constructs a new {@link ElementDescriptor} based on its XML name and children list.
- * The UI name is build by capitalizing the XML name.
- * The UI nodes will be non-mandatory.
- *
- * @param xml_name The XML element node name. Case sensitive.
- * @param children The list of allowed children. Can be null or empty.
- */
- public ElementDescriptor(String xml_name, ElementDescriptor[] children) {
- this(xml_name, prettyName(xml_name), null, null, null, children, false);
- }
-
- /**
- * Constructs a new {@link ElementDescriptor} based on its XML name.
- * The UI name is build by capitalizing the XML name.
- * The UI nodes will be non-mandatory.
- *
- * @param xml_name The XML element node name. Case sensitive.
- */
- public ElementDescriptor(String xml_name) {
- this(xml_name, prettyName(xml_name), null, null, null, null, false);
- }
-
- /** Returns whether this node must always exist (even for empty models) */
- public Mandatory getMandatory() {
- return mMandatory;
- }
-
- @Override
- public String toString() {
- return String.format("%s [%s, attr %d, children %d%s]", //$NON-NLS-1$
- this.getClass().getSimpleName(),
- mXmlName,
- mAttributes != null ? mAttributes.length : 0,
- mChildren != null ? mChildren.length : 0,
- mMandatory != Mandatory.NOT_MANDATORY ? ", " + mMandatory.toString() : "" //$NON-NLS-1$ //$NON-NLS-2$
- );
- }
-
- /**
- * Returns the XML element node local name (case sensitive)
- */
- public final String getXmlLocalName() {
- int pos = mXmlName.indexOf(':');
- if (pos != -1) {
- return mXmlName.substring(pos+1);
- }
- return mXmlName;
- }
-
- /**
- * Returns the XML element node name, including the prefix.
- * Case sensitive.
- * <p/>
- * In Android resources, the element node name for Android resources typically does not
- * have a prefix and is typically the simple Java class name (e.g. "View"), whereas for
- * custom views it is generally the fully qualified class name of the view (e.g.
- * "com.mycompany.myapp.MyView").
- * <p/>
- * Most of the time you'll probably want to use {@link #getXmlLocalName()} to get a local
- * name guaranteed without a prefix.
- * <p/>
- * Note that the prefix that <em>may</em> be available in this descriptor has nothing to
- * do with the actual prefix the node might have (or needs to have) in the actual XML file
- * since descriptors are fixed and do not depend on any current namespace defined in the
- * target XML.
- */
- public String getXmlName() {
- return mXmlName;
- }
-
- /**
- * Returns the namespace of the attribute.
- */
- public final String getNamespace() {
- // For now we hard-code the prefix as being "android"
- if (mXmlName.startsWith(ANDROID_NS_NAME_PREFIX)) {
- return ANDROID_URI;
- }
-
- return ""; //$NON-NLs-1$
- }
-
-
- /** Returns the XML element name for the user interface, typically capitalized. */
- public String getUiName() {
- return mUiName;
- }
-
- /**
- * Returns an icon for the element.
- * This icon is generic, that is all element descriptors have the same icon
- * no matter what they represent.
- *
- * @return An icon for this element or null.
- * @see #getCustomizedIcon()
- */
- public Image getGenericIcon() {
- return IconFactory.getInstance().getIcon(ELEMENT_ICON_FILENAME);
- }
-
- /**
- * Returns an optional icon for the element, typically to be used in XML form trees.
- * <p/>
- * This icon is customized to the given descriptor, that is different elements
- * will have different icons.
- * <p/>
- * By default this tries to return an icon based on the XML name of the element.
- * If this fails, it tries to return the default Android logo as defined in the
- * plugin. If all fails, it returns null.
- *
- * @return An icon for this element. This is never null.
- */
- public Image getCustomizedIcon() {
- IconFactory factory = IconFactory.getInstance();
- int color = hasChildren() ? IconFactory.COLOR_BLUE
- : IconFactory.COLOR_GREEN;
- int shape = hasChildren() ? IconFactory.SHAPE_RECT
- : IconFactory.SHAPE_CIRCLE;
- String name = mXmlName;
-
- int pos = name.lastIndexOf('.');
- if (pos != -1) {
- // If the user uses a fully qualified name, such as
- // "android.gesture.GestureOverlayView" in their XML, we need to
- // look up only by basename
- name = name.substring(pos + 1);
- }
- Image icon = factory.getIcon(name, color, shape);
- if (icon == null) {
- icon = getGenericIcon();
- }
- if (icon == null) {
- icon = AdtPlugin.getAndroidLogo();
- }
- return icon;
- }
-
- /**
- * Returns an optional ImageDescriptor for the element.
- * <p/>
- * By default this tries to return an image based on the XML name of the element.
- * If this fails, it tries to return the default Android logo as defined in the
- * plugin. If all fails, it returns null.
- *
- * @return An ImageDescriptor for this element or null.
- */
- public ImageDescriptor getImageDescriptor() {
- IconFactory factory = IconFactory.getInstance();
- int color = hasChildren() ? IconFactory.COLOR_BLUE : IconFactory.COLOR_GREEN;
- int shape = hasChildren() ? IconFactory.SHAPE_RECT : IconFactory.SHAPE_CIRCLE;
- ImageDescriptor id = factory.getImageDescriptor(mXmlName, color, shape);
- return id != null ? id : AdtPlugin.getAndroidLogoDesc();
- }
-
- /* Returns the list of allowed attributes. */
- public AttributeDescriptor[] getAttributes() {
- return mAttributes;
- }
-
- /** Sets the list of allowed attributes. */
- public void setAttributes(AttributeDescriptor[] attributes) {
- mAttributes = attributes;
- for (AttributeDescriptor attribute : attributes) {
- attribute.setParent(this);
- }
- }
-
- /** Returns the list of allowed children */
- public ElementDescriptor[] getChildren() {
- return mChildren;
- }
-
- /** @return True if this descriptor has children available */
- public boolean hasChildren() {
- return mChildren.length > 0;
- }
-
- /**
- * Checks whether this descriptor can accept the given descriptor type
- * as a direct child.
- *
- * @return True if this descriptor can accept children of the given descriptor type.
- * False if not accepted, no children allowed, or target is null.
- */
- public boolean acceptChild(ElementDescriptor target) {
- if (target != null && mChildren.length > 0) {
- String targetXmlName = target.getXmlName();
- for (ElementDescriptor child : mChildren) {
- if (child.getXmlName().equals(targetXmlName)) {
- return true;
- }
- }
- }
-
- return false;
- }
-
- /** Sets the list of allowed children. */
- public void setChildren(ElementDescriptor[] newChildren) {
- mChildren = newChildren;
- }
-
- /**
- * Sets the list of allowed children.
- * <p/>
- * This is just a convenience method that converts a Collection into an array and
- * calls {@link #setChildren(ElementDescriptor[])}.
- * <p/>
- * This means a <em>copy</em> of the collection is made. The collection is not
- * stored by the recipient and can thus be altered by the caller.
- */
- public void setChildren(Collection<ElementDescriptor> newChildren) {
- setChildren(newChildren.toArray(new ElementDescriptor[newChildren.size()]));
- }
-
- /**
- * Returns an optional tooltip. Will be null if not present.
- * <p/>
- * The tooltip is based on the Javadoc of the element and already processed via
- * {@link DescriptorsUtils#formatTooltip(String)} to be displayed right away as
- * a UI tooltip.
- */
- public String getTooltip() {
- return mTooltip;
- }
-
- /** Returns an optional SKD URL. Will be null if not present. */
- public String getSdkUrl() {
- return mSdkUrl;
- }
-
- /** Sets the optional tooltip. Can be null or empty. */
- public void setTooltip(String tooltip) {
- mTooltip = tooltip;
- }
-
- /** Sets the optional SDK URL. Can be null or empty. */
- public void setSdkUrl(String sdkUrl) {
- mSdkUrl = sdkUrl;
- }
-
- /**
- * @return A new {@link UiElementNode} linked to this descriptor.
- */
- public UiElementNode createUiNode() {
- return new UiElementNode(this);
- }
-
- /**
- * Returns the first children of this descriptor that describes the given XML element name.
- * <p/>
- * In recursive mode, searches the direct children first before descending in the hierarchy.
- *
- * @return The ElementDescriptor matching the requested XML node element name or null.
- */
- public ElementDescriptor findChildrenDescriptor(String element_name, boolean recursive) {
- return findChildrenDescriptorInternal(element_name, recursive, null);
- }
-
- private ElementDescriptor findChildrenDescriptorInternal(String element_name,
- boolean recursive,
- Set<ElementDescriptor> visited) {
- if (recursive && visited == null) {
- visited = new HashSet<ElementDescriptor>();
- }
-
- for (ElementDescriptor e : getChildren()) {
- if (e.getXmlName().equals(element_name)) {
- return e;
- }
- }
-
- if (visited != null) {
- visited.add(this);
- }
-
- if (recursive) {
- for (ElementDescriptor e : getChildren()) {
- if (visited != null) {
- if (!visited.add(e)) { // Set.add() returns false if element is already present
- continue;
- }
- }
- ElementDescriptor f = e.findChildrenDescriptorInternal(element_name,
- recursive, visited);
- if (f != null) {
- return f;
- }
- }
- }
-
- return null;
- }
-
- /**
- * Utility helper than pretty-formats an XML Name for the UI.
- * This is used by the simplified constructor that takes only an XML element name.
- *
- * @param xml_name The XML name to convert.
- * @return The XML name with dashes replaced by spaces and capitalized.
- */
- private static String prettyName(String xml_name) {
- char c[] = xml_name.toCharArray();
- if (c.length > 0) {
- c[0] = Character.toUpperCase(c[0]);
- }
- return new String(c).replace("-", " "); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- /**
- * Returns true if this node defines the given attribute
- *
- * @param namespaceUri the namespace URI of the target attribute
- * @param attributeName the attribute name
- * @return true if this element defines an attribute of the given name and namespace
- */
- public boolean definesAttribute(String namespaceUri, String attributeName) {
- for (AttributeDescriptor desc : mAttributes) {
- if (desc.getXmlLocalName().equals(attributeName) &&
- desc.getNamespaceUri().equals(namespaceUri)) {
- return true;
- }
- }
-
- return false;
- }
-
- // Implements Comparable<ElementDescriptor>:
- @Override
- public int compareTo(ElementDescriptor o) {
- return mUiName.compareToIgnoreCase(o.mUiName);
- }
-
- /**
- * Ensures that this view descriptor's attribute list is up to date. This is
- * always the case for all the builtin descriptors, but for example for a
- * custom view, it could be changing dynamically so caches may have to be
- * recomputed. This method will return true if nothing changed, and false if
- * it recomputed its info.
- *
- * @return true if the attributes are already up to date and nothing changed
- */
- public boolean syncAttributes() {
- return true;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/EnumAttributeDescriptor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/EnumAttributeDescriptor.java
deleted file mode 100644
index 29233571b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/EnumAttributeDescriptor.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.descriptors;
-
-import com.android.ide.common.api.IAttributeInfo;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiListAttributeNode;
-
-/**
- * Describes a text attribute that can only contains some predefined values.
- * It is displayed by a {@link UiListAttributeNode}.
- */
-public class EnumAttributeDescriptor extends ListAttributeDescriptor {
-
- public EnumAttributeDescriptor(String xmlLocalName, String uiName, String nsUri,
- String tooltip, IAttributeInfo attrInfo) {
- super(xmlLocalName, nsUri, attrInfo);
- }
-
- /**
- * @return A new {@link UiListAttributeNode} linked to this descriptor.
- */
- @Override
- public UiAttributeNode createUiNode(UiElementNode uiParent) {
- return new UiListAttributeNode(this, uiParent);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/FlagAttributeDescriptor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/FlagAttributeDescriptor.java
deleted file mode 100644
index 4f4b21569..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/FlagAttributeDescriptor.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.descriptors;
-
-import com.android.ide.common.api.IAttributeInfo;
-import com.android.ide.eclipse.adt.internal.editors.ui.FlagValueCellEditor;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiFlagAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiListAttributeNode;
-
-import org.eclipse.jface.viewers.CellEditor;
-import org.eclipse.swt.widgets.Composite;
-
-/**
- * Describes a text attribute that can only contains some predefined values.
- * It is displayed by a {@link UiListAttributeNode}.
- *
- * Note: in Android resources, a "flag" is a list of fixed values where one or
- * more values can be selected using an "or", e.g. "align='left|top'".
- * By contrast, an "enum" is a list of fixed values of which only one can be
- * selected at a given time, e.g. "gravity='right'".
- * <p/>
- * This class handles the "flag" case.
- * The "enum" case is done using {@link ListAttributeDescriptor}.
- */
-public class FlagAttributeDescriptor extends TextAttributeDescriptor {
-
- private String[] mNames;
-
- /**
- * Creates a new {@link FlagAttributeDescriptor}.
- * <p/>
- * If <code>attrInfo</code> is not null and has non-null flag values, these will be
- * used for the list.
- * Otherwise values are automatically extracted from the FrameworkResourceManager.
- */
- public FlagAttributeDescriptor(String xmlLocalName, String nsUri, IAttributeInfo attrInfo) {
- super(xmlLocalName, nsUri, attrInfo);
- if (attrInfo != null) {
- mNames = attrInfo.getFlagValues();
- }
- }
-
- /**
- * Creates a new {@link FlagAttributeDescriptor} which uses the provided values
- * and does not lookup the content of <code>attrInfo</code>.
- */
- public FlagAttributeDescriptor(String xmlLocalName, String uiName, String nsUri,
- String tooltip, IAttributeInfo attrInfo, String[] names) {
- super(xmlLocalName, nsUri, attrInfo);
- mNames = names;
- }
-
- /**
- * @return The initial names of the flags. Can be null, in which case the Framework
- * resource parser should be checked.
- */
- public String[] getNames() {
- return mNames;
- }
-
- /**
- * @return A new {@link UiListAttributeNode} linked to this descriptor.
- */
- @Override
- public UiAttributeNode createUiNode(UiElementNode uiParent) {
- return new UiFlagAttributeNode(this, uiParent);
- }
-
- // ------- IPropertyDescriptor Methods
-
- @Override
- public CellEditor createPropertyEditor(Composite parent) {
- return new FlagValueCellEditor(parent);
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/IDescriptorProvider.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/IDescriptorProvider.java
deleted file mode 100644
index 860ed394e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/IDescriptorProvider.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.descriptors;
-
-public interface IDescriptorProvider {
-
- ElementDescriptor[] getRootElementDescriptors();
-
- ElementDescriptor getDescriptor();
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/ITextAttributeCreator.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/ITextAttributeCreator.java
deleted file mode 100755
index 1fc662364..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/ITextAttributeCreator.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.descriptors;
-
-import com.android.SdkConstants;
-import com.android.ide.common.api.IAttributeInfo;
-
-
-/**
- * The {@link ITextAttributeCreator} interface is used by the appendAttribute(...) in
- * {@link DescriptorsUtils} to allows callers to override the kind of
- * {@link TextAttributeDescriptor} created for a given XML attribute name.
- * <p/>
- * The <code>create()</code> method must take arguments that are similar to the
- * single constructor for {@link TextAttributeDescriptor}.
- */
-public interface ITextAttributeCreator {
-
- /**
- * Creates a new {@link TextAttributeDescriptor} instance for the given XML name,
- * UI name and tooltip.
- *
- * @param xmlLocalName The XML name of the attribute (case sensitive)
- * @param nsUri The URI of the attribute. Can be null if attribute has no namespace.
- * See {@link SdkConstants#NS_RESOURCES} for a common value.
- * @param attrInfo The {@link IAttributeInfo} of this attribute. Can't be null.
- * @return A new {@link TextAttributeDescriptor} (or derived) instance.
- */
- public TextAttributeDescriptor create(
- String xmlLocalName,
- String nsUri,
- IAttributeInfo attrInfo);
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/IUnknownDescriptorProvider.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/IUnknownDescriptorProvider.java
deleted file mode 100755
index 931c1b726..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/IUnknownDescriptorProvider.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.descriptors;
-
-import com.android.ide.eclipse.adt.internal.editors.values.uimodel.UiItemElementNode;
-
-/**
- * {@link UiItemElementNode} is the main class that creates the UI Model hierarchy based
- * on an XML DOM hierarchy, matching XML names to the {@link ElementDescriptor} names.
- * <p/>
- * This interface declares a provider that can provide an {@link ElementDescriptor}
- * for an unknown XML local name.
- */
-public interface IUnknownDescriptorProvider {
-
- /**
- * Returns an instance of {@link ElementDescriptor} matching the given XML Local Name.
- *
- * @param xmlLocalName The XML local name.
- * @return A new or existing {@link ElementDescriptor} or derived instance. Must not be null.
- */
- ElementDescriptor getDescriptor(String xmlLocalName);
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/ListAttributeDescriptor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/ListAttributeDescriptor.java
deleted file mode 100644
index 16b0d55f1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/ListAttributeDescriptor.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.descriptors;
-
-import com.android.ide.common.api.IAttributeInfo;
-import com.android.ide.eclipse.adt.internal.editors.ui.ListValueCellEditor;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiListAttributeNode;
-
-import org.eclipse.jface.viewers.CellEditor;
-import org.eclipse.swt.widgets.Composite;
-
-/**
- * Describes a text attribute that can contains some predefined values.
- * It is displayed by a {@link UiListAttributeNode}.
- */
-public class ListAttributeDescriptor extends TextAttributeDescriptor {
-
- private String[] mValues = null;
-
- /**
- * Used by {@link DescriptorsUtils} to create instances of this descriptor.
- */
- public static final ITextAttributeCreator CREATOR = new ITextAttributeCreator() {
- @Override
- public TextAttributeDescriptor create(String xmlLocalName,
- String nsUri, IAttributeInfo attrInfo) {
- return new ListAttributeDescriptor(xmlLocalName, nsUri, attrInfo);
- }
- };
-
- /**
- * Creates a new {@link ListAttributeDescriptor}.
- * <p/>
- * If <code>attrInfo</code> is not null and has non-null enum values, these will be
- * used for the list.
- * Otherwise values are automatically extracted from the FrameworkResourceManager.
- */
- public ListAttributeDescriptor(String xmlLocalName, String nsUri, IAttributeInfo attrInfo) {
- super(xmlLocalName, nsUri, attrInfo);
- if (attrInfo != null) {
- mValues = attrInfo.getEnumValues();
- }
- }
-
- /**
- * Creates a new {@link ListAttributeDescriptor} which uses the provided values
- * and does not lookup the content of <code>attrInfo</code>.
- */
- public ListAttributeDescriptor(String xmlLocalName, String nsUri, IAttributeInfo attrInfo,
- String[] values) {
- super(xmlLocalName, nsUri, attrInfo);
- mValues = values;
- }
-
- public String[] getValues() {
- return mValues;
- }
-
- /**
- * @return A new {@link UiListAttributeNode} linked to this descriptor.
- */
- @Override
- public UiAttributeNode createUiNode(UiElementNode uiParent) {
- return new UiListAttributeNode(this, uiParent);
- }
-
- // ------- IPropertyDescriptor Methods
-
- @Override
- public CellEditor createPropertyEditor(Composite parent) {
- return new ListValueCellEditor(parent);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/ReferenceAttributeDescriptor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/ReferenceAttributeDescriptor.java
deleted file mode 100644
index 0f146c198..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/ReferenceAttributeDescriptor.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.descriptors;
-
-import com.android.SdkConstants;
-import com.android.ide.common.api.IAttributeInfo;
-import com.android.ide.common.api.IAttributeInfo.Format;
-import com.android.ide.common.resources.platform.AttributeInfo;
-import com.android.ide.eclipse.adt.internal.editors.ui.ResourceValueCellEditor;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiResourceAttributeNode;
-import com.android.resources.ResourceType;
-
-import org.eclipse.jface.viewers.CellEditor;
-import org.eclipse.swt.widgets.Composite;
-
-/**
- * Describes an XML attribute displayed containing a value or a reference to a resource.
- * It is displayed by a {@link UiResourceAttributeNode}.
- */
-public final class ReferenceAttributeDescriptor extends TextAttributeDescriptor {
-
- /**
- * The {@link ResourceType} that this reference attribute can accept. It can be null,
- * in which case any reference type can be used.
- */
- private ResourceType mResourceType;
-
- /**
- * Used by {@link DescriptorsUtils} to create instances of this descriptor.
- */
- public static final ITextAttributeCreator CREATOR = new ITextAttributeCreator() {
- @Override
- public TextAttributeDescriptor create(String xmlLocalName,
- String nsUri, IAttributeInfo attrInfo) {
- return new ReferenceAttributeDescriptor(
- ResourceType.DRAWABLE,
- xmlLocalName, nsUri,
- new AttributeInfo(xmlLocalName, Format.REFERENCE_SET));
- }
- };
-
- /**
- * Creates a reference attributes that can contain any type of resources.
- * @param xmlLocalName The XML name of the attribute (case sensitive)
- * @param nsUri The URI of the attribute. Can be null if attribute has no namespace.
- * See {@link SdkConstants#NS_RESOURCES} for a common value.
- * @param attrInfo The {@link IAttributeInfo} of this attribute. Can't be null.
- */
- public ReferenceAttributeDescriptor(String xmlLocalName, String nsUri,
- IAttributeInfo attrInfo) {
- super(xmlLocalName, nsUri, attrInfo);
- }
-
- /**
- * Creates a reference attributes that can contain a reference to a specific
- * {@link ResourceType}.
- * @param resourceType The specific {@link ResourceType} that this reference attribute supports.
- * It can be <code>null</code>, in which case, all resource types are supported.
- * @param xmlLocalName The XML name of the attribute (case sensitive)
- * @param nsUri The URI of the attribute. Can be null if attribute has no namespace.
- * See {@link SdkConstants#NS_RESOURCES} for a common value.
- * @param attrInfo The {@link IAttributeInfo} of this attribute. Can't be null.
- */
- public ReferenceAttributeDescriptor(ResourceType resourceType,
- String xmlLocalName, String nsUri, IAttributeInfo attrInfo) {
- super(xmlLocalName, nsUri, attrInfo);
- mResourceType = resourceType;
- }
-
-
- /** Returns the {@link ResourceType} that this reference attribute can accept.
- * It can be null, in which case any reference type can be used. */
- public ResourceType getResourceType() {
- return mResourceType;
- }
-
- /**
- * @return A new {@link UiResourceAttributeNode} linked to this reference descriptor.
- */
- @Override
- public UiAttributeNode createUiNode(UiElementNode uiParent) {
- return new UiResourceAttributeNode(mResourceType, this, uiParent);
- }
-
- // ------- IPropertyDescriptor Methods
-
- @Override
- public CellEditor createPropertyEditor(Composite parent) {
- return new ResourceValueCellEditor(parent);
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/SeparatorAttributeDescriptor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/SeparatorAttributeDescriptor.java
deleted file mode 100644
index 034bf8eb0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/SeparatorAttributeDescriptor.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.descriptors;
-
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiSeparatorAttributeNode;
-
-/**
- * {@link SeparatorAttributeDescriptor} does not represent any real attribute.
- * <p/>
- * It is used to separate groups of attributes visually.
- */
-public class SeparatorAttributeDescriptor extends AttributeDescriptor {
-
- /**
- * Creates a new {@link SeparatorAttributeDescriptor}
- */
- public SeparatorAttributeDescriptor(String label) {
- super(label /* xmlLocalName */, null /* nsUri */, null /* info */);
- }
-
- /**
- * @return A new {@link UiAttributeNode} linked to this descriptor or null if this
- * attribute has no user interface.
- */
- @Override
- public UiAttributeNode createUiNode(UiElementNode uiParent) {
- return new UiSeparatorAttributeNode(this, uiParent);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/TextAttributeDescriptor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/TextAttributeDescriptor.java
deleted file mode 100644
index f8c7806ae..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/TextAttributeDescriptor.java
+++ /dev/null
@@ -1,290 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.descriptors;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.IAttributeInfo;
-import com.android.ide.common.api.IAttributeInfo.Format;
-import com.android.ide.eclipse.adt.internal.editors.ui.TextValueCellEditor;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiTextAttributeNode;
-
-import org.eclipse.jface.viewers.CellEditor;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.views.properties.IPropertyDescriptor;
-
-import java.util.EnumSet;
-import java.util.Locale;
-
-
-/**
- * Describes a textual XML attribute.
- * <p/>
- * Such an attribute has a tooltip and would typically be displayed by
- * {@link UiTextAttributeNode} using a label widget and text field.
- * <p/>
- * This is the "default" kind of attribute. If in doubt, use this.
- */
-public class TextAttributeDescriptor extends AttributeDescriptor implements IPropertyDescriptor {
- public static final String DEPRECATED_CATEGORY = "Deprecated";
-
- private String mUiName;
- private String mTooltip;
- private boolean mRequired;
-
- /**
- * Creates a new {@link TextAttributeDescriptor}
- *
- * @param xmlLocalName The XML name of the attribute (case sensitive)
- * @param nsUri The URI of the attribute. Can be null if attribute has no namespace.
- * See {@link SdkConstants#NS_RESOURCES} for a common value.
- * @param attrInfo The {@link IAttributeInfo} of this attribute. Can't be null.
- */
- public TextAttributeDescriptor(
- String xmlLocalName,
- String nsUri,
- IAttributeInfo attrInfo) {
- super(xmlLocalName, nsUri, attrInfo);
- }
-
- /**
- * @return The UI name of the attribute. Cannot be an empty string and cannot be null.
- */
- @NonNull
- public String getUiName() {
- if (mUiName == null) {
- IAttributeInfo info = getAttributeInfo();
- if (info != null) {
- mUiName = DescriptorsUtils.prettyAttributeUiName(info.getName());
- if (mRequired) {
- mUiName += "*"; //$NON-NLS-1$
- }
- } else {
- mUiName = getXmlLocalName();
- }
- }
-
- return mUiName;
- }
-
-
- /**
- * Sets the UI name to be associated with this descriptor. This is usually
- * computed lazily from the {@link #getAttributeInfo()} data, but for some
- * hardcoded/builtin descriptor this is manually initialized.
- *
- * @param uiName the new UI name to be used
- * @return this, for constructor setter chaining
- */
- public TextAttributeDescriptor setUiName(String uiName) {
- mUiName = uiName;
-
- return this;
- }
-
- /**
- * Sets the tooltip to be associated with this descriptor. This is usually
- * computed lazily from the {@link #getAttributeInfo()} data, but for some
- * hardcoded/builtin descriptor this is manually initialized.
- *
- * @param tooltip the new tooltip to be used
- * @return this, for constructor setter chaining
- */
- public TextAttributeDescriptor setTooltip(String tooltip) {
- mTooltip = tooltip;
-
- return this;
- }
-
- /**
- * Sets whether this attribute is required
- *
- * @param required whether this attribute is required
- * @return this, for constructor setter chaining
- */
- public TextAttributeDescriptor setRequired(boolean required) {
- mRequired = required;
-
- return this;
- }
-
- /**
- * Returns whether this attribute is required
- *
- * @return whether this attribute is required
- */
- public boolean isRequired() {
- return mRequired;
- }
-
- /**
- * The tooltip string is either null or a non-empty string.
- * <p/>
- * The tooltip is based on the Javadoc of the attribute and already processed via
- * {@link DescriptorsUtils#formatTooltip(String)} to be displayed right away as
- * a UI tooltip.
- * <p/>
- * An empty string is converted to null, to match the behavior of setToolTipText() in
- * {@link Control}.
- *
- * @return A non-empty tooltip string or null
- */
- @Nullable
- public String getTooltip() {
- if (mTooltip == null) {
- IAttributeInfo info = getAttributeInfo();
- if (info == null) {
- mTooltip = "";
- return mTooltip;
- }
-
- String tooltip = null;
- String rawTooltip = info.getJavaDoc();
- if (rawTooltip == null) {
- rawTooltip = "";
- }
-
- String deprecated = info.getDeprecatedDoc();
- if (deprecated != null) {
- if (rawTooltip.length() > 0) {
- rawTooltip += "@@"; //$NON-NLS-1$ insert a break
- }
- rawTooltip += "* Deprecated";
- if (deprecated.length() != 0) {
- rawTooltip += ": " + deprecated; //$NON-NLS-1$
- }
- if (deprecated.length() == 0 || !deprecated.endsWith(".")) { //$NON-NLS-1$
- rawTooltip += "."; //$NON-NLS-1$
- }
- }
-
- // Add the known types to the tooltip
- EnumSet<Format> formats_list = info.getFormats();
- int flen = formats_list.size();
- if (flen > 0) {
- StringBuilder sb = new StringBuilder();
- if (rawTooltip != null && rawTooltip.length() > 0) {
- sb.append(rawTooltip);
- sb.append(" "); //$NON-NLS-1$
- }
- if (sb.length() > 0) {
- sb.append("@@"); //$NON-NLS-1$ @@ inserts a break before the types
- }
- sb.append("["); //$NON-NLS-1$
- boolean isFirst = true;
- for (Format f : formats_list) {
- if (isFirst) {
- isFirst = false;
- } else {
- sb.append(", ");
- }
- sb.append(f.toString().toLowerCase(Locale.US));
- }
- // The extra space at the end makes the tooltip more readable on Windows.
- sb.append("]"); //$NON-NLS-1$
-
- if (mRequired) {
- // Note: this string is split in 2 to make it translatable.
- sb.append(".@@"); //$NON-NLS-1$ @@ inserts a break and is not translatable
- sb.append("* Required.");
- }
-
- // The extra space at the end makes the tooltip more readable on Windows.
- sb.append(" "); //$NON-NLS-1$
-
- rawTooltip = sb.toString();
- tooltip = DescriptorsUtils.formatTooltip(rawTooltip);
- }
-
- if (tooltip == null) {
- tooltip = DescriptorsUtils.formatTooltip(rawTooltip);
- }
- mTooltip = tooltip;
- }
-
- return mTooltip.isEmpty() ? null : mTooltip;
- }
-
- /**
- * @return A new {@link UiTextAttributeNode} linked to this descriptor.
- */
- @Override
- public UiAttributeNode createUiNode(UiElementNode uiParent) {
- return new UiTextAttributeNode(this, uiParent);
- }
-
- // ------- IPropertyDescriptor Methods
-
- @Override
- public CellEditor createPropertyEditor(Composite parent) {
- return new TextValueCellEditor(parent);
- }
-
- @Override
- public String getCategory() {
- if (isDeprecated()) {
- return DEPRECATED_CATEGORY;
- }
-
- ElementDescriptor parent = getParent();
- if (parent != null) {
- return parent.getUiName();
- }
-
- return null;
- }
-
- @Override
- public String getDescription() {
- return getTooltip();
- }
-
- @Override
- public String getDisplayName() {
- return getUiName();
- }
-
- @Override
- public String[] getFilterFlags() {
- return null;
- }
-
- @Override
- public Object getHelpContextIds() {
- return null;
- }
-
- @Override
- public Object getId() {
- return this;
- }
-
- @Override
- public ILabelProvider getLabelProvider() {
- return AttributeDescriptorLabelProvider.getProvider();
- }
-
- @Override
- public boolean isCompatibleWith(IPropertyDescriptor anotherProperty) {
- return anotherProperty == this;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/TextValueDescriptor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/TextValueDescriptor.java
deleted file mode 100644
index 6bfe4c778..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/TextValueDescriptor.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.descriptors;
-
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiTextValueNode;
-
-
-/**
- * Describes the value of an XML element.
- * <p/>
- * The value is a simple text string, displayed by an {@link UiTextValueNode}.
- */
-public class TextValueDescriptor extends TextAttributeDescriptor {
-
- /**
- * Creates a new {@link TextValueDescriptor}
- *
- * @param uiName The UI name of the attribute. Cannot be an empty string and cannot be null.
- * @param tooltip A non-empty tooltip string or null
- */
- public TextValueDescriptor(String uiName, String tooltip) {
- super("#text" /* xmlLocalName */, null /* nsUri */, null /* info */);
- setUiName(uiName);
- setTooltip(tooltip);
- }
-
- /**
- * @return A new {@link UiTextValueNode} linked to this descriptor.
- */
- @Override
- public UiAttributeNode createUiNode(UiElementNode uiParent) {
- return new UiTextValueNode(this, uiParent);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/XmlnsAttributeDescriptor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/XmlnsAttributeDescriptor.java
deleted file mode 100644
index 39bb0f5f8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/descriptors/XmlnsAttributeDescriptor.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.descriptors;
-
-import static com.android.SdkConstants.XMLNS;
-import static com.android.SdkConstants.XMLNS_URI;
-
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-
-/**
- * Describes an XMLNS attribute that is hidden.
- * <p/>
- * Such an attribute has no user interface and no corresponding {@link UiAttributeNode}.
- * It also has a single constant default value.
- * <p/>
- * When loading an XML, we'll ignore this attribute.
- * However when writing a new XML, we should always write this attribute.
- * <p/>
- * Currently this is used for the xmlns:android attribute in the manifest element.
- */
-public final class XmlnsAttributeDescriptor extends AttributeDescriptor {
-
- private String mValue;
-
- public XmlnsAttributeDescriptor(String defaultPrefix, String value) {
- super(defaultPrefix, XMLNS_URI, null /* info */);
- mValue = value;
- }
-
- /**
- * Returns the value of this specialized attribute descriptor, which is the URI associated
- * to the declared namespace prefix.
- */
- public String getValue() {
- return mValue;
- }
-
- /**
- * Returns the "xmlns" prefix that is always used by this node for its namespace URI.
- * This is defined by the XML specification.
- */
- public String getXmlNsPrefix() {
- return XMLNS;
- }
-
- /**
- * Returns the fully-qualified attribute name, namely "xmlns:xxx" where xxx is
- * the defaultPrefix passed in the constructor.
- */
- public String getXmlNsName() {
- return getXmlNsPrefix() + ":" + getXmlLocalName(); //$NON-NLS-1$
- }
-
- /**
- * @return Always returns null. {@link XmlnsAttributeDescriptor} has no user interface.
- */
- @Override
- public UiAttributeNode createUiNode(UiElementNode uiParent) {
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/Draw9PatchEditor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/Draw9PatchEditor.java
deleted file mode 100644
index 48ef7c366..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/Draw9PatchEditor.java
+++ /dev/null
@@ -1,233 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.draw9patch;
-
-import static com.android.SdkConstants.DOT_9PNG;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.draw9patch.graphics.NinePatchedImage;
-import com.android.ide.eclipse.adt.internal.editors.draw9patch.ui.ImageViewer;
-import com.android.ide.eclipse.adt.internal.editors.draw9patch.ui.MainFrame;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.ImageData;
-import org.eclipse.swt.graphics.ImageLoader;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.dialogs.SaveAsDialog;
-import org.eclipse.ui.part.EditorPart;
-import org.eclipse.ui.part.FileEditorInput;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-
-/**
- * Draw9Patch editor part.
- */
-public class Draw9PatchEditor extends EditorPart implements ImageViewer.UpdateListener {
-
- private IProject mProject = null;
-
- private FileEditorInput mFileEditorInput = null;
-
- private String mFileName = null;
-
- private NinePatchedImage mNinePatchedImage = null;
-
- private MainFrame mMainFrame = null;
-
- @Override
- public void init(IEditorSite site, IEditorInput input) throws PartInitException {
- setSite(site);
- setInput(input);
- setPartName(input.getName());
-
- // The contract of init() mentions we need to fail if we can't
- // understand the input.
- if (input instanceof FileEditorInput) {
- // We try to open a file that is part of the current workspace
- mFileEditorInput = (FileEditorInput) input;
- mFileName = mFileEditorInput.getName();
- mProject = mFileEditorInput.getFile().getProject();
- } else {
- throw new PartInitException("Input is not of type FileEditorInput " + //$NON-NLS-1$
- "nor FileStoreEditorInput: " + //$NON-NLS-1$
- input == null ? "null" : input.toString()); //$NON-NLS-1$
- }
-
- }
-
- @Override
- public boolean isSaveAsAllowed() {
- return true;
- }
-
- @Override
- public void doSaveAs() {
- IPath relativePath = null;
- if ((relativePath = showSaveAsDialog()) != null) {
- mFileEditorInput = new FileEditorInput(ResourcesPlugin.getWorkspace().getRoot()
- .getFile(relativePath));
- mFileName = mFileEditorInput.getName();
- setInput(mFileEditorInput);
-
- doSave(new NullProgressMonitor());
- }
- }
-
- @Override
- public void doSave(final IProgressMonitor monitor) {
- boolean hasNinePatchExtension = mFileName.endsWith(DOT_9PNG);
- boolean doConvert = false;
-
- if (!hasNinePatchExtension) {
- String patchedName = NinePatchedImage.getNinePatchedFileName(mFileName);
- doConvert = MessageDialog
- .openQuestion(AdtPlugin.getDisplay().getActiveShell(),
- "Warning",
- String.format(
- "The file \"%s\" doesn't seem to be a 9-patch file. \n"
- + "Do you want to convert and save as \"%s\" ?",
- mFileName, patchedName));
-
- if (doConvert) {
- IFile destFile = mProject.getFile(NinePatchedImage.getNinePatchedFileName(
- mFileEditorInput.getFile().getProjectRelativePath().toOSString()));
- if (!destFile.exists()) {
- mFileEditorInput = new FileEditorInput(destFile);
- mFileName = mFileEditorInput.getName();
- } else {
- IPath relativePath = null;
- if ((relativePath = showSaveAsDialog()) != null) {
- mFileEditorInput = new FileEditorInput(ResourcesPlugin.getWorkspace()
- .getRoot().getFile(relativePath));
- mFileName = mFileEditorInput.getName();
- } else {
- doConvert = false;
- }
- }
- }
- }
-
- if (hasNinePatchExtension || doConvert) {
- ImageLoader loader = new ImageLoader();
- loader.data = new ImageData[] {
- mNinePatchedImage.getRawImageData()
- };
-
- IFile file = mFileEditorInput.getFile();
-
- ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
- loader.save(outputStream, SWT.IMAGE_PNG);
- byte[] byteArray = outputStream.toByteArray();
-
- try {
- if (file.exists()) {
- file.setContents(new ByteArrayInputStream(byteArray), true, false, monitor);
- } else {
- file.create(new ByteArrayInputStream(byteArray), true, monitor);
- }
-
- mNinePatchedImage.clearDirtyFlag();
-
- AdtPlugin.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- setPartName(mFileName);
- firePropertyChange(PROP_DIRTY);
- }
- });
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- }
- }
-
- @Override
- public void createPartControl(Composite parent) {
- mMainFrame = new MainFrame(parent, SWT.NULL);
-
- ImageViewer imageViewer = mMainFrame.getImageEditorPanel().getImageViewer();
- imageViewer.addUpdateListener(this);
-
- mNinePatchedImage = imageViewer.loadFile(mFileEditorInput.getPath().toOSString());
- if (mNinePatchedImage.hasNinePatchExtension()) {
- if (!mNinePatchedImage.ensure9Patch() && showConvertMessageBox(mFileName)) {
- // Reload image
- mNinePatchedImage = imageViewer.loadFile(mFileEditorInput.getPath().toOSString());
- mNinePatchedImage.convertToNinePatch();
- }
- } else {
- mNinePatchedImage.convertToNinePatch();
- }
-
- imageViewer.startDisplay();
-
- parent.layout();
- }
-
- @Override
- public void setFocus() {
- mMainFrame.forceFocus();
- }
-
- @Override
- public boolean isDirty() {
- return mNinePatchedImage.isDirty();
- }
-
- @Override
- public void update(NinePatchedImage image) {
- if (image.isDirty()) {
- firePropertyChange(PROP_DIRTY);
- }
- }
-
- private IPath showSaveAsDialog() {
- SaveAsDialog dialog = new SaveAsDialog(AdtPlugin.getDisplay().getActiveShell());
-
- IFile dest = mProject.getFile(NinePatchedImage.getNinePatchedFileName(
- mFileEditorInput.getFile().getProjectRelativePath().toOSString()));
- dialog.setOriginalFile(dest);
-
- dialog.create();
-
- if (dialog.open() == Window.CANCEL) {
- return null;
- }
-
- return dialog.getResult();
- }
-
- private static boolean showConvertMessageBox(String fileName) {
- return MessageDialog.openQuestion(
- AdtPlugin.getDisplay().getActiveShell(),
- "Warning",
- String.format("The file \"%s\" doesn't seem to be a 9-patch file. \n"
- + "Do you want to convert?", fileName));
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/graphics/GraphicsUtilities.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/graphics/GraphicsUtilities.java
deleted file mode 100644
index 74c2f043e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/graphics/GraphicsUtilities.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.draw9patch.graphics;
-
-import org.eclipse.swt.graphics.ImageData;
-
-/**
- * The utility class for SWT Image and ImageData manipulation.
- */
-public class GraphicsUtilities {
-
- /**
- * Convert normal image to 9-patched.
- * @return Returns 9-patched ImageData object. If image is null, returns null.
- */
- public static ImageData convertToNinePatch(ImageData image) {
- if (image == null) {
- return null;
- }
- ImageData result = new ImageData(image.width + 2, image.height + 2, image.depth,
- image.palette);
-
- final int[] colors = new int[image.width];
- final byte[] alpha = new byte[image.width];
-
- for (int y = 0; y < image.height; y++) {
-
- // Copy pixels
- image.getPixels(0, y, image.width, colors, 0);
- result.setPixels(1, y + 1, image.width, colors, 0);
-
- // Copy alpha
- image.getAlphas(0, y, image.width, alpha, 0);
- result.setAlphas(1, y + 1, image.width, alpha, 0);
- }
-
- return result;
- }
-
- /**
- * Wipe all color and alpha pixels.
- */
- public static void clearImageData(ImageData imageData) {
- if (imageData == null) {
- throw new IllegalArgumentException("image data must not be null");
- }
- int width = imageData.width;
- int height = imageData.height;
- for (int y = 0; y < height; y++) {
- for (int x = 0; x < width; x++) {
- imageData.setPixel(x, y, 0x00000000);
- imageData.setAlpha(x, y, 0x00);
- }
- }
- }
-
- /**
- * Duplicate the image data.
- * @return If image is null, return null.
- */
- public static ImageData copy(ImageData image) {
- if (image == null) {
- return null;
- }
- ImageData result = new ImageData(image.width, image.height, image.depth,
- image.palette);
-
- final int[] colors = new int[image.width];
- final byte[] alpha = new byte[image.width];
-
- for (int y = 0; y < image.height; y++) {
-
- // Copy pixels
- image.getPixels(0, y, image.width, colors, 0);
- result.setPixels(0, y, image.width, colors, 0);
-
- // Copy alpha
- image.getAlphas(0, y, image.width, alpha, 0);
- result.setAlphas(0, y, image.width, alpha, 0);
- }
-
- return result;
- }
-
- /**
- * Get column pixels.
- * @return length of obtained pixels.
- */
- public static int getVerticalPixels(ImageData data, int x, int y, int height, int[] out) {
- if (data == null) {
- throw new IllegalArgumentException("data must not be null");
- }
- if (out == null) {
- throw new IllegalArgumentException("out array must not be null");
- }
- if (height > out.length) {
- throw new IllegalArgumentException("out array length must be > height");
- }
- if (data.height < (y + height)) {
- throw new IllegalArgumentException("image height must be > (y + height)");
- }
- if (x < 0 || y < 0) {
- throw new IllegalArgumentException("argument x, y must be >= 0");
- }
- if (x >= data.width) {
- throw new IllegalArgumentException("argument x must be < data.width");
- }
- if (y >= data.height) {
- throw new IllegalArgumentException("argument y must be < data.height");
- }
- if (height <= 0) {
- throw new IllegalArgumentException("argument height must be > 0");
- }
-
- int idx = 0;
- while (idx < height) {
- data.getPixels(x, (y + idx), 1, out, idx);
- idx++;
- }
- return idx;
- }
-
- /**
- * Get row pixels.
- */
- public static void getHorizontalPixels(ImageData data, int x, int y, int width, int[] out) {
- if (data == null) {
- throw new IllegalArgumentException("data must not be null");
- }
- if (out == null) {
- throw new IllegalArgumentException("out array must not be null");
- }
- if (width > out.length) {
- throw new IllegalArgumentException("out array length must be > width");
- }
- if (data.width < (x + width)) {
- throw new IllegalArgumentException("image height must be > (x + width)");
- }
- if (x < 0 || y < 0) {
- throw new IllegalArgumentException("argument x, y must be >= 0");
- }
- if (x >= data.width) {
- throw new IllegalArgumentException("argument x must be < data.width");
- }
- if (y >= data.height) {
- throw new IllegalArgumentException("argument y must be < data.height");
- }
- if (width <= 0) {
- throw new IllegalArgumentException("argument width must be > 0");
- }
-
- data.getPixels(x, y, width, out, 0);
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/graphics/NinePatchedImage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/graphics/NinePatchedImage.java
deleted file mode 100644
index f1022c3a2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/graphics/NinePatchedImage.java
+++ /dev/null
@@ -1,882 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.draw9patch.graphics;
-
-import static com.android.SdkConstants.DOT_9PNG;
-import static com.android.SdkConstants.DOT_PNG;
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.ImageData;
-import org.eclipse.swt.graphics.Rectangle;
-
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-/**
- * The model of 9-patched image.
- */
-public class NinePatchedImage {
- private static final boolean DEBUG = false;
-
- /**
- * Get 9-patched filename as like image.9.png .
- */
- public static String getNinePatchedFileName(String fileName) {
- if (fileName.endsWith(DOT_9PNG)) {
- return fileName;
- }
- return fileName.substring(0, fileName.lastIndexOf(DOT_PNG)) + DOT_9PNG;
- }
-
- // For stretch regions and padding
- public static final int BLACK_TICK = 0xFF000000;
- // For Layout Bounds
- public static final int RED_TICK = 0xFFFF0000;
- // Blank
- public static final int TRANSPARENT_TICK = 0x00000000;
-
- private ImageData mBaseImageData;
-
- private Image mBaseImage = null;
-
- private boolean mHasNinePatchExtension = false;
-
- private boolean mDirtyFlag = false;
-
- private int[] mHorizontalPatchPixels = null;
- private int[] mVerticalPatchPixels = null;
-
- private int[] mHorizontalContentPixels = null;
- private int[] mVerticalContentPixels = null;
-
- // for Prevent unexpected stretch in StretchsView
- private boolean mRedTickOnlyInHorizontalFlag = false;
- private boolean mRedTickOnlyInVerticalFlag = false;
-
- private final List<Tick> mHorizontalPatches = new ArrayList<Tick>();
- private final List<Tick> mVerticalPatches = new ArrayList<Tick>();
-
- private final List<Tick> mHorizontalContents = new ArrayList<Tick>();
- private final List<Tick> mVerticalContents = new ArrayList<Tick>();
-
-
- private static final int CHUNK_BIN_SIZE = 100;
- private final List<Chunk> mChunkBin = new ArrayList<Chunk>(CHUNK_BIN_SIZE);
-
- private int mHorizontalFixedPatchSum = 0;
- private int mVerticalFixedPatchSum = 0;
-
- private static final int PROJECTION_BIN_SIZE = 100;
- private final List<Projection> mProjectionBin = new ArrayList<Projection>(PROJECTION_BIN_SIZE);
-
- private Chunk[][] mPatchChunks = null;
-
- public ImageData getImageData() {
- return mBaseImageData;
- }
-
- public int getWidth() {
- return mBaseImageData.width;
- }
-
- public int getHeight() {
- return mBaseImageData.height;
- }
-
- public Image getImage() {
- if (mBaseImage == null) {
- mBaseImage = new Image(AdtPlugin.getDisplay(), mBaseImageData);
- }
- return mBaseImage;
- }
-
- public boolean hasNinePatchExtension() {
- return mHasNinePatchExtension;
- }
-
- /**
- * Get the image has/hasn't been edited flag.
- * @return If has been edited, return true
- */
- public boolean isDirty() {
- return mDirtyFlag;
- }
-
- /**
- * Clear dirty(edited) flag.
- */
- public void clearDirtyFlag() {
- mDirtyFlag = false;
- }
-
- public NinePatchedImage(String fileName) {
- boolean hasNinePatchExtension = fileName.endsWith(DOT_9PNG);
- ImageData data = new ImageData(fileName);
-
- initNinePatchedImage(data, hasNinePatchExtension);
- }
-
- public NinePatchedImage(InputStream inputStream, String fileName) {
- boolean hasNinePatchExtension = fileName.endsWith(DOT_9PNG);
- ImageData data = new ImageData(inputStream);
-
- initNinePatchedImage(data, hasNinePatchExtension);
- }
-
- private Chunk getChunk() {
- if (mChunkBin.size() > 0) {
- Chunk chunk = mChunkBin.remove(0);
- chunk.init();
- return chunk;
- }
- return new Chunk();
- }
-
- private static final void recycleChunks(Chunk[][] patchChunks, List<Chunk> bin) {
- int yLen = patchChunks.length;
- int xLen = patchChunks[0].length;
-
- for (int y = 0; y < yLen; y++) {
- for (int x = 0; x < xLen; x++) {
- if (bin.size() < CHUNK_BIN_SIZE) {
- bin.add(patchChunks[y][x]);
- }
- patchChunks[y][x] = null;
- }
- }
- }
-
- private Projection getProjection() {
- if (mProjectionBin.size() > 0) {
- Projection projection = mProjectionBin.remove(0);
- return projection;
- }
- return new Projection();
- }
-
- private static final void recycleProjections(Projection[][] projections, List<Projection> bin) {
- int yLen = projections.length;
- int xLen = 0;
- if (yLen > 0) {
- xLen = projections[0].length;
- }
-
- for (int y = 0; y < yLen; y++) {
- for (int x = 0; x < xLen; x++) {
- if (bin.size() < CHUNK_BIN_SIZE) {
- bin.add(projections[y][x]);
- }
- projections[y][x] = null;
- }
- }
- }
-
- private static final int[] initArray(int[] array) {
- int len = array.length;
- for (int i = 0; i < len; i++) {
- array[i] = TRANSPARENT_TICK;
- }
- return array;
- }
-
- /**
- * Get one pixel with alpha from the image.
- * @return packed integer value as ARGB8888
- */
- private static final int getPixel(ImageData image, int x, int y) {
- return (image.getAlpha(x, y) << 24) + image.getPixel(x, y);
- }
-
- private static final boolean isTransparentPixel(ImageData image, int x, int y) {
- return image.getAlpha(x, y) == 0x0;
- }
-
- private static final boolean isValidTickColor(int pixel) {
- return (pixel == BLACK_TICK || pixel == RED_TICK);
- }
-
- private void initNinePatchedImage(ImageData imageData, boolean hasNinePatchExtension) {
- mBaseImageData = imageData;
- mHasNinePatchExtension = hasNinePatchExtension;
- }
-
- private boolean ensurePixel(int x, int y, int[] pixels, int index) {
- boolean isValid = true;
- int pixel = getPixel(mBaseImageData, x, y);
- if (!isTransparentPixel(mBaseImageData, x, y)) {
- if (index == 0 || index == pixels.length - 1) {
- isValid = false;
- }
- if (isValidTickColor(pixel)) {
- pixels[index] = pixel;
- } else {
- isValid = false;
- }
- // clear pixel
- mBaseImageData.setAlpha(x, y, 0x0);
- }
- return isValid;
- }
-
- private boolean ensureHorizontalPixel(int x, int y, int[] pixels) {
- return ensurePixel(x, y, pixels, x);
- }
-
- private boolean ensureVerticalPixel(int x, int y, int[] pixels) {
- return ensurePixel(x, y, pixels, y);
- }
-
- /**
- * Ensure that image data is 9-patch.
- */
- public boolean ensure9Patch() {
- boolean isValid = true;
-
- int width = mBaseImageData.width;
- int height = mBaseImageData.height;
-
- createPatchArray();
- createContentArray();
-
- // horizontal
- for (int x = 0; x < width; x++) {
- // top row
- if (!ensureHorizontalPixel(x, 0, mHorizontalPatchPixels)) {
- isValid = false;
- }
- // bottom row
- if (!ensureHorizontalPixel(x, height - 1, mHorizontalContentPixels)) {
- isValid = false;
- }
- }
- // vertical
- for (int y = 0; y < height; y++) {
- // left column
- if (!ensureVerticalPixel(0, y, mVerticalPatchPixels)) {
- isValid = false;
- }
- // right column
- if (!ensureVerticalPixel(width -1, y, mVerticalContentPixels)) {
- isValid = false;
- }
- }
- findPatches();
- findContentsArea();
-
- return isValid;
- }
-
- private void createPatchArray() {
- mHorizontalPatchPixels = initArray(new int[mBaseImageData.width]);
- mVerticalPatchPixels = initArray(new int[mBaseImageData.height]);
- }
-
- private void createContentArray() {
- mHorizontalContentPixels = initArray(new int[mBaseImageData.width]);
- mVerticalContentPixels = initArray(new int[mBaseImageData.height]);
- }
-
- /**
- * Convert to 9-patch image.
- * <p>
- * This method doesn't consider that target image is already 9-patched or
- * not.
- * </p>
- */
- public void convertToNinePatch() {
- mBaseImageData = GraphicsUtilities.convertToNinePatch(mBaseImageData);
- mHasNinePatchExtension = true;
-
- createPatchArray();
- createContentArray();
-
- findPatches();
- findContentsArea();
- }
-
- public boolean isValid(int x, int y) {
- return (x == 0) ^ (y == 0)
- ^ (x == mBaseImageData.width - 1) ^ (y == mBaseImageData.height - 1);
- }
-
- /**
- * Set patch or content.
- */
- public void setPatch(int x, int y, int color) {
- if (isValid(x, y)) {
- if (x == 0) {
- mVerticalPatchPixels[y] = color;
- } else if (y == 0) {
- mHorizontalPatchPixels[x] = color;
- } else if (x == mBaseImageData.width - 1) {
- mVerticalContentPixels[y] = color;
- } else if (y == mBaseImageData.height - 1) {
- mHorizontalContentPixels[x] = color;
- }
-
- // Mark as dirty
- mDirtyFlag = true;
- }
- }
-
- /**
- * Erase the pixel.
- */
- public void erase(int x, int y) {
- if (isValid(x, y)) {
- int color = TRANSPARENT_TICK;
- if (x == 0) {
- mVerticalPatchPixels[y] = color;
- } else if (y == 0) {
- mHorizontalPatchPixels[x] = color;
- } else if (x == mBaseImageData.width - 1) {
- mVerticalContentPixels[y] = color;
- } else if (y == mBaseImageData.height - 1) {
- mHorizontalContentPixels[x] = color;
- }
-
- // Mark as dirty
- mDirtyFlag = true;
- }
- }
-
- public List<Tick> getHorizontalPatches() {
- return mHorizontalPatches;
- }
-
- public List<Tick> getVerticalPatches() {
- return mVerticalPatches;
- }
-
- /**
- * Find patches from pixels array.
- * @param pixels Target of seeking ticks.
- * @param out Add the found ticks.
- * @return If BlackTick is not found but only RedTick is found, returns true
- */
- private static boolean findPatches(int[] pixels, List<Tick> out) {
- boolean redTickOnly = true;
- Tick patch = null;
- int len = 0;
-
- // find patches
- out.clear();
- len = pixels.length - 1;
- for (int i = 1; i < len; i++) {
- int pixel = pixels[i];
-
- if (redTickOnly && pixel != TRANSPARENT_TICK && pixel != RED_TICK) {
- redTickOnly = false;
- }
-
- if (patch != null) {
- if (patch.color != pixel) {
- patch.end = i;
- out.add(patch);
- patch = null;
- }
- }
- if (patch == null) {
- patch = new Tick(pixel);
- patch.start = i;
- }
- }
-
- if (patch != null) {
- patch.end = len;
- out.add(patch);
- }
- return redTickOnly;
- }
-
- public void findPatches() {
-
- // find horizontal patches
- mRedTickOnlyInHorizontalFlag = findPatches(mHorizontalPatchPixels, mHorizontalPatches);
-
- // find vertical patches
- mRedTickOnlyInVerticalFlag = findPatches(mVerticalPatchPixels, mVerticalPatches);
- }
-
- public Rectangle getContentArea() {
- Tick horizontal = getContentArea(mHorizontalContents);
- Tick vertical = getContentArea(mVerticalContents);
-
- Rectangle rect = new Rectangle(0, 0, 0, 0);
- rect.x = 1;
- rect.width = mBaseImageData.width - 1;
- rect.y = 1;
- rect.height = mBaseImageData.height - 1;
-
- if (horizontal != null) {
- rect.x = horizontal.start;
- rect.width = horizontal.getLength();
- }
- if (vertical != null) {
- rect.y = vertical.start;
- rect.height = vertical.getLength();
- }
-
- return rect;
- }
-
- private Tick getContentArea(List<Tick> list) {
- int size = list.size();
- if (size == 0) {
- return null;
- }
- if (size == 1) {
- return list.get(0);
- }
-
- Tick start = null;
- Tick end = null;
-
- for (int i = 0; i < size; i++) {
- Tick t = list.get(i);
- if (t.color == BLACK_TICK) {
- if (start == null) {
- start = t;
- end = t;
- } else {
- end = t;
- }
- }
- }
-
- // red tick only
- if (start == null) {
- return null;
- }
-
- Tick result = new Tick(start.color);
- result.start = start.start;
- result.end = end.end;
-
- return result;
- }
-
- /**
- * This is for unit test use only.
- * @see com.android.ide.eclipse.adt.internal.editors.draw9patch.graphics.NinePatchedImageTest
- */
- public List<Tick> getHorizontalContents() {
- return mHorizontalContents;
- }
-
- /**
- * This is for unit test use only.
- * @see com.android.ide.eclipse.adt.internal.editors.draw9patch.graphics.NinePatchedImageTest
- */
- public List<Tick> getVerticalContents() {
- return mVerticalContents;
- }
-
- private static void findContentArea(int[] pixels, List<Tick> out) {
- Tick contents = null;
- int len = 0;
-
- // find horizontal contents area
- out.clear();
- len = pixels.length - 1;
- for (int x = 1; x < len; x++) {
- if (contents != null) {
- if (contents.color != pixels[x]) {
- contents.end = x;
- out.add(contents);
- contents = null;
- }
- }
- if (contents == null) {
- contents = new Tick(pixels[x]);
- contents.start = x;
- }
- }
-
- if (contents != null) {
- contents.end = len;
- out.add(contents);
- }
- }
-
- public void findContentsArea() {
-
- // find horizontal contents area
- findContentArea(mHorizontalContentPixels, mHorizontalContents);
-
- // find vertical contents area
- findContentArea(mVerticalContentPixels, mVerticalContents);
- }
-
- /**
- * Get raw image data.
- * <p>
- * The raw image data is applicable for save.
- * </p>
- */
- public ImageData getRawImageData() {
- ImageData image = GraphicsUtilities.copy(mBaseImageData);
-
- final int width = image.width;
- final int height = image.height;
- int len = 0;
-
- len = mHorizontalPatchPixels.length;
- for (int x = 0; x < len; x++) {
- int pixel = mHorizontalPatchPixels[x];
- if (pixel != TRANSPARENT_TICK) {
- image.setAlpha(x, 0, 0xFF);
- image.setPixel(x, 0, pixel);
- }
- }
-
- len = mVerticalPatchPixels.length;
- for (int y = 0; y < len; y++) {
- int pixel = mVerticalPatchPixels[y];
- if (pixel != TRANSPARENT_TICK) {
- image.setAlpha(0, y, 0xFF);
- image.setPixel(0, y, pixel);
- }
- }
-
- len = mHorizontalContentPixels.length;
- for (int x = 0; x < len; x++) {
- int pixel = mHorizontalContentPixels[x];
- if (pixel != TRANSPARENT_TICK) {
- image.setAlpha(x, height - 1, 0xFF);
- image.setPixel(x, height - 1, pixel);
- }
- }
-
- len = mVerticalContentPixels.length;
- for (int y = 0; y < len; y++) {
- int pixel = mVerticalContentPixels[y];
- if (pixel != TRANSPARENT_TICK) {
- image.setAlpha(width - 1, y, 0xFF);
- image.setPixel(width - 1, y, pixel);
- }
- }
-
- return image;
- }
-
- public Chunk[][] getChunks(Chunk[][] chunks) {
- int lenY = mVerticalPatches.size();
- int lenX = mHorizontalPatches.size();
-
- if (lenY == 0 || lenX == 0) {
- return null;
- }
-
- if (chunks == null) {
- chunks = new Chunk[lenY][lenX];
- } else {
- int y = chunks.length;
- int x = chunks[0].length;
- if (lenY != y || lenX != x) {
- recycleChunks(chunks, mChunkBin);
- chunks = new Chunk[lenY][lenX];
- }
- }
-
- // for calculate weights
- float horizontalPatchSum = 0;
- float verticalPatchSum = 0;
-
- mVerticalFixedPatchSum = 0;
- mHorizontalFixedPatchSum = 0;
-
- for (int y = 0; y < lenY; y++) {
- Tick yTick = mVerticalPatches.get(y);
-
- for (int x = 0; x < lenX; x++) {
- Tick xTick = mHorizontalPatches.get(x);
- Chunk t = getChunk();
- chunks[y][x] = t;
-
- t.rect.x = xTick.start;
- t.rect.width = xTick.getLength();
- t.rect.y = yTick.start;
- t.rect.height = yTick.getLength();
-
- if (mRedTickOnlyInHorizontalFlag
- || xTick.color == BLACK_TICK || lenX == 1) {
- t.type += Chunk.TYPE_HORIZONTAL;
- if (y == 0) {
- horizontalPatchSum += t.rect.width;
- }
- }
- if (mRedTickOnlyInVerticalFlag
- || yTick.color == BLACK_TICK || lenY == 1) {
- t.type += Chunk.TYPE_VERTICAL;
- if (x == 0) {
- verticalPatchSum += t.rect.height;
- }
- }
-
- if ((t.type & Chunk.TYPE_HORIZONTAL) == 0 && lenX > 1 && y == 0) {
- mHorizontalFixedPatchSum += t.rect.width;
- }
- if ((t.type & Chunk.TYPE_VERTICAL) == 0 && lenY > 1 && x == 0) {
- mVerticalFixedPatchSum += t.rect.height;
- }
-
- }
- }
-
- // calc weights
- for (int y = 0; y < lenY; y++) {
- for (int x = 0; x < lenX; x++) {
- Chunk chunk = chunks[y][x];
- if ((chunk.type & Chunk.TYPE_HORIZONTAL) != 0) {
- chunk.horizontalWeight = chunk.rect.width / horizontalPatchSum;
- }
- if ((chunk.type & Chunk.TYPE_VERTICAL) != 0) {
- chunk.verticalWeight = chunk.rect.height / verticalPatchSum;
-
- }
- }
- }
-
- return chunks;
- }
-
- public Chunk[][] getCorruptedChunks(Chunk[][] chunks) {
- chunks = getChunks(chunks);
-
- if (chunks != null) {
- int yLen = chunks.length;
- int xLen = chunks[0].length;
-
- for (int yPos = 0; yPos < yLen; yPos++) {
- for (int xPos = 0; xPos < xLen; xPos++) {
- Chunk c = chunks[yPos][xPos];
- Rectangle r = c.rect;
- if ((c.type & Chunk.TYPE_HORIZONTAL) != 0
- && isHorizontalCorrupted(mBaseImageData, r)) {
- c.type |= Chunk.TYPE_CORRUPT;
- }
- if ((c.type & Chunk.TYPE_VERTICAL) != 0
- && isVerticalCorrupted(mBaseImageData, r)) {
- c.type |= Chunk.TYPE_CORRUPT;
- }
- }
- }
- }
- return chunks;
- }
-
- private static boolean isVerticalCorrupted(ImageData data, Rectangle r) {
- int[] column = new int[r.width];
- int[] sample = new int[r.width];
-
- GraphicsUtilities.getHorizontalPixels(data, r.x, r.y, r.width, column);
-
- int lenY = r.y + r.height;
- for (int y = r.y; y < lenY; y++) {
- GraphicsUtilities.getHorizontalPixels(data, r.x, y, r.width, sample);
- if (!Arrays.equals(column, sample)) {
- return true;
- }
- }
- return false;
- }
-
- private static boolean isHorizontalCorrupted(ImageData data, Rectangle r) {
- int[] column = new int[r.height];
- int[] sample = new int[r.height];
- GraphicsUtilities.getVerticalPixels(data, r.x, r.y, r.height, column);
-
- int lenX = r.x + r.width;
- for (int x = r.x; x < lenX; x++) {
- GraphicsUtilities.getVerticalPixels(data, x, r.y, r.height, sample);
- if (!Arrays.equals(column, sample)) {
- return true;
- }
- }
- return false;
- }
-
- public Projection[][] getProjections(int width, int height, Projection[][] projections) {
- mPatchChunks = getChunks(mPatchChunks);
- if (mPatchChunks == null) {
- return null;
- }
-
- if (DEBUG) {
- System.out.println(String.format("width:%d, height:%d", width, height));
- }
-
- int lenY = mPatchChunks.length;
- int lenX = mPatchChunks[0].length;
-
- if (projections == null) {
- projections = new Projection[lenY][lenX];
- } else {
- int y = projections.length;
- int x = projections[0].length;
- if (lenY != y || lenX != x) {
- recycleProjections(projections, mProjectionBin);
- projections = new Projection[lenY][lenX];
- }
- }
-
- float xZoom = ((float) width / mBaseImageData.width);
- float yZoom = ((float) height / mBaseImageData.height);
-
- if (DEBUG) {
- System.out.println(String.format("xZoom:%f, yZoom:%f", xZoom, yZoom));
- }
-
- int destX = 0;
- int destY = 0;
- int streatchableWidth = width - mHorizontalFixedPatchSum;
- streatchableWidth = streatchableWidth > 0 ? streatchableWidth : 1;
-
- int streatchableHeight = height - mVerticalFixedPatchSum;
- streatchableHeight = streatchableHeight > 0 ? streatchableHeight : 1;
-
- if (DEBUG) {
- System.out.println(String.format("streatchable %d %d", streatchableWidth,
- streatchableHeight));
- }
-
- for (int yPos = 0; yPos < lenY; yPos++) {
- destX = 0;
- Projection p = null;
- for (int xPos = 0; xPos < lenX; xPos++) {
- Chunk chunk = mPatchChunks[yPos][xPos];
-
- if (DEBUG) {
- System.out.println(String.format("Tile[%d, %d] = %s",
- yPos, xPos, chunk.toString()));
- }
-
- p = getProjection();
- projections[yPos][xPos] = p;
-
- p.chunk = chunk;
- p.src = chunk.rect;
- p.dest.x = destX;
- p.dest.y = destY;
-
- // fixed size
- p.dest.width = chunk.rect.width;
- p.dest.height = chunk.rect.height;
-
- // horizontal stretch
- if ((chunk.type & Chunk.TYPE_HORIZONTAL) != 0) {
- p.dest.width = Math.round(streatchableWidth * chunk.horizontalWeight);
- }
- // vertical stretch
- if ((chunk.type & Chunk.TYPE_VERTICAL) != 0) {
- p.dest.height = Math.round(streatchableHeight * chunk.verticalWeight);
- }
-
- destX += p.dest.width;
- }
- destY += p.dest.height;
- }
- return projections;
- }
-
- /**
- * Projection class for make relation between chunked image and resized image.
- */
- public static class Projection {
- public Chunk chunk = null;
- public Rectangle src = null;
- public final Rectangle dest = new Rectangle(0, 0, 0, 0);
-
- @Override
- public String toString() {
- return String.format("src[%d, %d, %d, %d] => dest[%d, %d, %d, %d]",
- src.x, src.y, src.width, src.height,
- dest.x, dest.y, dest.width, dest.height);
- }
- }
-
- public static class Chunk {
- public static final int TYPE_FIXED = 0x0;
- public static final int TYPE_HORIZONTAL = 0x1;
- public static final int TYPE_VERTICAL = 0x2;
- public static final int TYPE_CORRUPT = 0x80000000;
-
- public int type = TYPE_FIXED;
-
- public Rectangle rect = new Rectangle(0, 0, 0, 0);
-
- public float horizontalWeight = 0.0f;
- public float verticalWeight = 0.0f;
-
- void init() {
- type = Chunk.TYPE_FIXED;
- horizontalWeight = 0.0f;
- verticalWeight = 0.0f;
- rect.x = 0;
- rect.y = 0;
- rect.width = 0;
- rect.height = 0;
- }
-
- private String typeToString() {
- switch (type) {
- case TYPE_FIXED:
- return "FIXED";
- case TYPE_HORIZONTAL:
- return "HORIZONTAL";
- case TYPE_VERTICAL:
- return "VERTICAL";
- case TYPE_HORIZONTAL + TYPE_VERTICAL:
- return "BOTH";
- default:
- return "UNKNOWN";
- }
- }
-
- @Override
- public String toString() {
- return String.format("%s %f/%f %s", typeToString(), horizontalWeight, verticalWeight,
- rect.toString());
- }
- }
-
- public static class Tick {
- public int start;
- public int end;
- public int color;
-
- /**
- * Get the tick length.
- */
- public int getLength() {
- return end - start;
- }
-
- public Tick(int tickColor) {
- color = tickColor;
- }
-
- @Override
- public String toString() {
- return String.format("%d tick: %d to %d", color, start, end);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/ui/ImageEditorPanel.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/ui/ImageEditorPanel.java
deleted file mode 100644
index 7c4523024..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/ui/ImageEditorPanel.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.draw9patch.ui;
-
-import com.android.ide.eclipse.adt.internal.editors.draw9patch.graphics.NinePatchedImage;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.SashForm;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DropTarget;
-import org.eclipse.swt.dnd.DropTargetListener;
-import org.eclipse.swt.dnd.FileTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.widgets.Composite;
-
-/**
- * Image editor pane.
- */
-public class ImageEditorPanel extends Composite implements ImageViewer.UpdateListener,
- StatusPanel.StatusChangedListener {
-
- private static final int WEIGHT_VIEWER = 3;
- private static final int WEIGHT_PREVIEW = 1;
-
- private final ImageViewer mImageViewer;
- private final StretchesViewer mStretchesViewer;
-
- public ImageViewer getImageViewer() {
- return mImageViewer;
- }
-
- public ImageEditorPanel(Composite parent, int style) {
- super(parent, style);
-
- setLayout(new FillLayout());
- SashForm sashForm = new SashForm(this, SWT.HORIZONTAL);
-
- mImageViewer = new ImageViewer(sashForm, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
- mImageViewer.addUpdateListener(this);
-
- mStretchesViewer = new StretchesViewer(sashForm, SWT.BORDER);
-
- sashForm.setWeights(new int[] {
- WEIGHT_VIEWER, WEIGHT_PREVIEW
- });
- }
-
- @Override
- public void zoomChanged(int zoom) {
- mImageViewer.setZoom(zoom);
- }
-
- @Override
- public void scaleChanged(int scale) {
- mStretchesViewer.setScale(scale);
- }
-
- @Override
- public void lockVisibilityChanged(boolean visible) {
- mImageViewer.setShowLock(visible);
- }
-
- @Override
- public void patchesVisibilityChanged(boolean visible) {
- mImageViewer.setShowPatchesArea(visible);
- }
-
- @Override
- public void badPatchesVisibilityChanged(boolean visible) {
- mImageViewer.setShowBadPatchesArea(visible);
- }
-
- @Override
- public void contentAreaVisibilityChanged(boolean visible) {
- mStretchesViewer.setShowContentArea(visible);
- }
-
- @Override
- public void update(NinePatchedImage image) {
- mStretchesViewer.updatePreview(image);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/ui/ImageViewer.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/ui/ImageViewer.java
deleted file mode 100644
index 2414a39d7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/ui/ImageViewer.java
+++ /dev/null
@@ -1,774 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.draw9patch.ui;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.draw9patch.graphics.NinePatchedImage;
-import com.android.ide.eclipse.adt.internal.editors.draw9patch.graphics.NinePatchedImage.Chunk;
-import com.android.ide.eclipse.adt.internal.editors.draw9patch.graphics.NinePatchedImage.Tick;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.KeyListener;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseListener;
-import org.eclipse.swt.events.MouseMoveListener;
-import org.eclipse.swt.events.PaintEvent;
-import org.eclipse.swt.events.PaintListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.ImageData;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Canvas;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.ScrollBar;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.ArrayBlockingQueue;
-
-/**
- * View and edit Draw 9-patch image.
- */
-public class ImageViewer extends Canvas implements PaintListener, KeyListener, MouseListener,
- MouseMoveListener {
- private static final boolean DEBUG = false;
-
- public static final String HELP_MESSAGE_KEY_TIPS = "Press Shift to erase pixels."
- + " Press Control to draw layout bounds.";
-
- public static final String HELP_MESSAGE_KEY_TIPS2 = "Release Shift to draw pixels.";
-
- private static final Color BLACK_COLOR = AdtPlugin.getDisplay().getSystemColor(SWT.COLOR_BLACK);
- private static final Color RED_COLOR = AdtPlugin.getDisplay().getSystemColor(SWT.COLOR_RED);
-
- private static final Color BACK_COLOR
- = new Color(AdtPlugin.getDisplay(), new RGB(0x00, 0xFF, 0x00));
- private static final Color LOCK_COLOR
- = new Color(AdtPlugin.getDisplay(), new RGB(0xFF, 0x00, 0x00));
- private static final Color PATCH_COLOR
- = new Color(AdtPlugin.getDisplay(), new RGB(0xFF, 0xFF, 0x00));
- private static final Color PATCH_ONEWAY_COLOR
- = new Color(AdtPlugin.getDisplay(), new RGB(0x00, 0x00, 0xFF));
- private static final Color CORRUPTED_COLOR
- = new Color(AdtPlugin.getDisplay(), new RGB(0xFF, 0x00, 0x00));
-
- private static final int NONE_ALPHA = 0xFF;
- private static final int LOCK_ALPHA = 50;
- private static final int PATCH_ALPHA = 50;
- private static final int GUIDE_ALPHA = 60;
-
- private static final int MODE_NONE = 0x00;
- private static final int MODE_BLACK_TICK = 0x01;
- private static final int MODE_RED_TICK = 0x02;
- private static final int MODE_ERASE = 0xFF;
-
- private int mDrawMode = MODE_NONE;
-
- private static final int MARGIN = 5;
- private static final String CHECKER_PNG_PATH = "/icons/checker.png";
-
- private Image mBackgroundLayer = null;
-
- private NinePatchedImage mNinePatchedImage = null;
-
- private Chunk[][] mChunks = null;
- private Chunk[][] mBadChunks = null;
-
- private boolean mIsLockShown = true;
- private boolean mIsPatchesShown = false;
- private boolean mIsBadPatchesShown = false;
-
- private ScrollBar mHorizontalBar;
- private ScrollBar mVerticalBar;
-
- private int mZoom = 500;
-
- private int mHorizontalScroll = 0;
- private int mVerticalScroll = 0;
-
- private final Rectangle mPadding = new Rectangle(0, 0, 0, 0);
-
- // one pixel size that considered zoom
- private int mZoomedPixelSize = 1;
-
- private Image mBufferImage = null;
-
- private boolean isCtrlPressed = false;
- private boolean isShiftPressed = false;
-
- private final List<UpdateListener> mUpdateListenerList
- = new ArrayList<UpdateListener>();
-
- private final Point mCursorPoint = new Point(0, 0);
-
- private static final int DEFAULT_UPDATE_QUEUE_SIZE = 10;
-
- private final ArrayBlockingQueue<NinePatchedImage> mUpdateQueue
- = new ArrayBlockingQueue<NinePatchedImage>(DEFAULT_UPDATE_QUEUE_SIZE);
-
- private final Runnable mUpdateRunnable = new Runnable() {
- @Override
- public void run() {
- if (isDisposed()) {
- return;
- }
-
- redraw();
-
- fireUpdateEvent();
- }
- };
-
- private final Thread mUpdateThread = new Thread() {
- @Override
- public void run() {
- while (!isDisposed()) {
- try {
- mUpdateQueue.take();
- mNinePatchedImage.findPatches();
- mNinePatchedImage.findContentsArea();
-
- mChunks = mNinePatchedImage.getChunks(mChunks);
- mBadChunks = mNinePatchedImage.getCorruptedChunks(mBadChunks);
-
- AdtPlugin.getDisplay().asyncExec(mUpdateRunnable);
-
- } catch (InterruptedException e) {
- }
- }
- }
- };
-
- private StatusChangedListener mStatusChangedListener = null;
-
- public void addUpdateListener(UpdateListener l) {
- mUpdateListenerList.add(l);
- }
-
- public void removeUpdateListener(UpdateListener l) {
- mUpdateListenerList.remove(l);
- }
-
- private void fireUpdateEvent() {
- int len = mUpdateListenerList.size();
- for(int i=0; i < len; i++) {
- mUpdateListenerList.get(i).update(mNinePatchedImage);
- }
- }
-
- public void setStatusChangedListener(StatusChangedListener l) {
- mStatusChangedListener = l;
- if (mStatusChangedListener != null) {
- mStatusChangedListener.helpTextChanged(HELP_MESSAGE_KEY_TIPS);
- }
- }
-
- void setShowLock(boolean show) {
- mIsLockShown = show;
- redraw();
- }
-
- void setShowPatchesArea(boolean show) {
- mIsPatchesShown = show;
- redraw();
- }
-
- void setShowBadPatchesArea(boolean show) {
- mIsBadPatchesShown = show;
- redraw();
- }
-
- void setZoom(int zoom) {
- mZoom = zoom;
- mZoomedPixelSize = getZoomedPixelSize(1);
- redraw();
- }
-
- public ImageViewer(Composite parent, int style) {
- super(parent, style);
-
- mUpdateThread.start();
-
- mBackgroundLayer = AdtPlugin.getImageDescriptor(CHECKER_PNG_PATH).createImage();
-
- addMouseListener(this);
- addMouseMoveListener(this);
- addPaintListener(this);
-
- mHorizontalBar = getHorizontalBar();
- mHorizontalBar.setThumb(1);
- mHorizontalBar.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent event) {
- super.widgetSelected(event);
- ScrollBar bar = (ScrollBar) event.widget;
- if (mHorizontalBar.isVisible()
- && mHorizontalScroll != bar.getSelection()) {
- mHorizontalScroll = bar.getSelection();
- redraw();
- }
- }
- });
-
- mVerticalBar = getVerticalBar();
- mVerticalBar.setThumb(1);
- mVerticalBar.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent event) {
- super.widgetSelected(event);
- ScrollBar bar = (ScrollBar) event.widget;
- if (mVerticalBar.isVisible()
- && mVerticalScroll != bar.getSelection()) {
- mVerticalScroll = bar.getSelection();
- redraw();
- }
- }
- });
- }
-
- /**
- * Load the image file.
- *
- * @param fileName must be absolute path
- */
- public NinePatchedImage loadFile(String fileName) {
- mNinePatchedImage = new NinePatchedImage(fileName);
-
- return mNinePatchedImage;
- }
-
- /**
- * Start displaying the image.
- */
- public void startDisplay() {
- mZoomedPixelSize = getZoomedPixelSize(1);
-
- scheduleUpdate();
- }
-
- private void draw(int x, int y, int drawMode) {
- if (drawMode == MODE_ERASE) {
- erase(x, y);
- } else {
- int color = (drawMode == MODE_RED_TICK) ? NinePatchedImage.RED_TICK
- : NinePatchedImage.BLACK_TICK;
- mNinePatchedImage.setPatch(x, y, color);
- redraw();
-
- scheduleUpdate();
- }
- }
-
- private void erase(int x, int y) {
- mNinePatchedImage.erase(x, y);
- redraw();
-
- scheduleUpdate();
- }
-
- private void scheduleUpdate() {
- try {
- mUpdateQueue.put(mNinePatchedImage);
- } catch (InterruptedException e) {
- }
- }
-
- @Override
- public void mouseDown(MouseEvent event) {
- if (event.button == 1 && !isShiftPressed) {
- mDrawMode = !isCtrlPressed ? MODE_BLACK_TICK : MODE_RED_TICK;
- draw(mCursorPoint.x, mCursorPoint.y, mDrawMode);
- } else if (event.button == 3 || isShiftPressed) {
- mDrawMode = MODE_ERASE;
- erase(mCursorPoint.x, mCursorPoint.y);
- }
- }
-
- @Override
- public void mouseUp(MouseEvent event) {
- mDrawMode = MODE_NONE;
- }
-
- @Override
- public void mouseDoubleClick(MouseEvent event) {
- }
-
- private int getLogicalPositionX(int x) {
- return Math.round((x - mPadding.x + mHorizontalScroll) / ((float) mZoom / 100));
- }
-
- private int getLogicalPositionY(int y) {
- return Math.round((y - mPadding.y + mVerticalScroll) / ((float) mZoom / 100));
- }
-
- @Override
- public void mouseMove(MouseEvent event) {
- int posX = getLogicalPositionX(event.x);
- int posY = getLogicalPositionY(event.y);
-
- int width = mNinePatchedImage.getWidth();
- int height = mNinePatchedImage.getHeight();
-
- if (posX < 0) {
- posX = 0;
- }
- if (posX >= width) {
- posX = width - 1;
- }
- if (posY < 0) {
- posY = 0;
- }
- if (posY >= height) {
- posY = height - 1;
- }
-
- if (mDrawMode != MODE_NONE) {
- int drawMode = mDrawMode;
- if (isShiftPressed) {
- drawMode = MODE_ERASE;
- } else if (mDrawMode != MODE_ERASE) {
- drawMode = !isCtrlPressed ? MODE_BLACK_TICK : MODE_RED_TICK;
- }
-
- /*
- * Consider the previous cursor position because mouseMove events are
- * scatter.
- */
- int x = mCursorPoint.x;
- int y = mCursorPoint.y;
- for (; y != posY; y += (y > posY) ? -1 : 1) {
- draw(x, y, drawMode);
- }
-
- x = mCursorPoint.x;
- y = mCursorPoint.y;
- for (; x != posX; x += (x > posX) ? -1 : 1) {
- draw(x, y, drawMode);
- }
- }
- mCursorPoint.x = posX;
- mCursorPoint.y = posY;
-
- redraw();
-
- if (mStatusChangedListener != null) {
- // Update position on status panel if position is in logical size.
- if (posX >= 0 && posY >= 0
- && posX <= mNinePatchedImage.getWidth()
- && posY <= mNinePatchedImage.getHeight()) {
- mStatusChangedListener.cursorPositionChanged(posX + 1, posY + 1);
- }
- }
- }
-
- private synchronized void calcPaddings(int width, int height) {
- Point canvasSize = getSize();
-
- mPadding.width = getZoomedPixelSize(width);
- mPadding.height = getZoomedPixelSize(height);
-
- int margin = getZoomedPixelSize(MARGIN);
-
- if (mPadding.width < canvasSize.x) {
- mPadding.x = (canvasSize.x - mPadding.width) / 2;
- } else {
- mPadding.x = margin;
- }
-
- if (mPadding.height < canvasSize.y) {
- mPadding.y = (canvasSize.y - mPadding.height) / 2;
- } else {
- mPadding.y = margin;
- }
- }
-
- private void calcScrollBarSettings() {
- Point size = getSize();
- int screenWidth = size.x;
- int screenHeight = size.y;
-
- int imageWidth = getZoomedPixelSize(mNinePatchedImage.getWidth() + 1);
- int imageHeight = getZoomedPixelSize(mNinePatchedImage.getHeight() + 1);
-
- // consider the scroll bar sizes
- int verticalBarSize = mVerticalBar.getSize().x;
- int horizontalBarSize = mHorizontalBar.getSize().y;
-
- int horizontalScroll = imageWidth - (screenWidth - verticalBarSize);
- int verticalScroll = imageHeight - (screenHeight - horizontalBarSize);
-
- int margin = getZoomedPixelSize(MARGIN) * 2;
-
- if (horizontalScroll > 0) {
- mHorizontalBar.setVisible(true);
-
- // horizontal maximum
- int max = horizontalScroll + verticalBarSize + margin;
- mHorizontalBar.setMaximum(max);
-
- // set corrected scroll size
- int value = mHorizontalBar.getSelection();
- value = max < value ? max : value;
-
- mHorizontalBar.setSelection(value);
- mHorizontalScroll = value;
-
- } else {
- mHorizontalBar.setSelection(0);
- mHorizontalBar.setMaximum(0);
- mHorizontalBar.setVisible(false);
- }
-
- if (verticalScroll > 0) {
- mVerticalBar.setVisible(true);
-
- // vertical maximum
- int max = verticalScroll + horizontalBarSize + margin;
- mVerticalBar.setMaximum(max);
-
- // set corrected scroll size
- int value = mVerticalBar.getSelection();
- value = max < value ? max : value;
-
- mVerticalBar.setSelection(value);
- mVerticalScroll = value;
-
- } else {
- mVerticalBar.setSelection(0);
- mVerticalBar.setMaximum(0);
- mVerticalBar.setVisible(false);
- }
- }
-
- private int getZoomedPixelSize(int val) {
- return Math.round(val * (float) mZoom / 100);
- }
-
- @Override
- public void paintControl(PaintEvent pe) {
- if (mNinePatchedImage == null) {
- return;
- }
-
- // Use buffer
- GC bufferGc = null;
- if (mBufferImage == null) {
- mBufferImage = new Image(AdtPlugin.getDisplay(), pe.width, pe.height);
- } else {
- int width = mBufferImage.getBounds().width;
- int height = mBufferImage.getBounds().height;
- if (width != pe.width || height != pe.height) {
- mBufferImage = new Image(AdtPlugin.getDisplay(), pe.width, pe.height);
- }
- }
-
- // Draw previous image once for prevent flicking
- pe.gc.drawImage(mBufferImage, 0, 0);
-
- bufferGc = new GC(mBufferImage);
- bufferGc.setAdvanced(true);
-
- // Make interpolation disable
- bufferGc.setInterpolation(SWT.NONE);
-
- // clear buffer
- bufferGc.fillRectangle(0, 0, pe.width, pe.height);
-
- calcScrollBarSettings();
-
- // padding from current zoom
- int width = mNinePatchedImage.getWidth();
- int height = mNinePatchedImage.getHeight();
- calcPaddings(width, height);
-
- int baseX = mPadding.x - mHorizontalScroll;
- int baseY = mPadding.y - mVerticalScroll;
-
- // draw checker image
- bufferGc.drawImage(mBackgroundLayer,
- 0, 0, mBackgroundLayer.getImageData().width,
- mBackgroundLayer.getImageData().height,
- baseX, baseY, mPadding.width, mPadding.height);
-
- if (DEBUG) {
- System.out.println(String.format("%d,%d %d,%d %d,%d",
- width, height, baseX, baseY, mPadding.width, mPadding.height));
- }
-
- // draw image
- /* TODO: Do not draw invisible area, for better performance. */
- bufferGc.drawImage(mNinePatchedImage.getImage(), 0, 0, width, height, baseX, baseY,
- mPadding.width, mPadding.height);
-
- bufferGc.setBackground(BLACK_COLOR);
-
- // draw patch ticks
- drawHorizontalPatches(bufferGc, baseX, baseY);
- drawVerticalPatches(bufferGc, baseX, baseY);
-
- // draw content ticks
- drawHorizontalContentArea(bufferGc, baseX, baseY);
- drawVerticalContentArea(bufferGc, baseX, baseY);
-
- if (mNinePatchedImage.isValid(mCursorPoint.x, mCursorPoint.y)) {
- bufferGc.setForeground(BLACK_COLOR);
- } else if (mIsLockShown) {
- drawLockArea(bufferGc, baseX, baseY);
- }
-
- // Patches
- if (mIsPatchesShown) {
- drawPatchAreas(bufferGc, baseX, baseY);
- }
-
- // Bad patches
- if (mIsBadPatchesShown) {
- drawBadPatchAreas(bufferGc, baseX, baseY);
- }
-
- if (mNinePatchedImage.isValid(mCursorPoint.x, mCursorPoint.y)) {
- bufferGc.setForeground(BLACK_COLOR);
- } else {
- bufferGc.setForeground(RED_COLOR);
- }
-
- drawGuideLine(bufferGc, baseX, baseY);
-
- bufferGc.dispose();
-
- pe.gc.drawImage(mBufferImage, 0, 0);
- }
-
- private static final Color getColor(int color) {
- switch (color) {
- case NinePatchedImage.RED_TICK:
- return RED_COLOR;
- default:
- return BLACK_COLOR;
- }
- }
-
- private void drawVerticalPatches(GC gc, int baseX, int baseY) {
- List<Tick> verticalPatches = mNinePatchedImage.getVerticalPatches();
- for (Tick t : verticalPatches) {
- if (t.color != NinePatchedImage.TRANSPARENT_TICK) {
- gc.setBackground(getColor(t.color));
- gc.fillRectangle(
- baseX,
- baseY + getZoomedPixelSize(t.start),
- mZoomedPixelSize,
- getZoomedPixelSize(t.getLength()));
- }
- }
- }
-
- private void drawHorizontalPatches(GC gc, int baseX, int baseY) {
- List<Tick> horizontalPatches = mNinePatchedImage.getHorizontalPatches();
- for (Tick t : horizontalPatches) {
- if (t.color != NinePatchedImage.TRANSPARENT_TICK) {
- gc.setBackground(getColor(t.color));
- gc.fillRectangle(
- baseX + getZoomedPixelSize(t.start),
- baseY,
- getZoomedPixelSize(t.getLength()),
- mZoomedPixelSize);
- }
- }
- }
-
- private void drawHorizontalContentArea(GC gc, int baseX, int baseY) {
- List<Tick> horizontalContentArea = mNinePatchedImage.getHorizontalContents();
- for (Tick t : horizontalContentArea) {
- if (t.color != NinePatchedImage.TRANSPARENT_TICK) {
- gc.setBackground(getColor(t.color));
- gc.fillRectangle(
- baseX + getZoomedPixelSize(t.start),
- baseY + getZoomedPixelSize(mNinePatchedImage.getHeight() - 1),
- getZoomedPixelSize(t.getLength()),
- mZoomedPixelSize);
- }
- }
-
- }
-
- private void drawVerticalContentArea(GC gc, int baseX, int baseY) {
- List<Tick> verticalContentArea = mNinePatchedImage.getVerticalContents();
- for (Tick t : verticalContentArea) {
- if (t.color != NinePatchedImage.TRANSPARENT_TICK) {
- gc.setBackground(getColor(t.color));
- gc.fillRectangle(
- baseX + getZoomedPixelSize(mNinePatchedImage.getWidth() - 1),
- baseY + getZoomedPixelSize(t.start),
- mZoomedPixelSize,
- getZoomedPixelSize(t.getLength()));
- }
- }
- }
-
- private void drawLockArea(GC gc, int baseX, int baseY) {
- gc.setAlpha(LOCK_ALPHA);
- gc.setForeground(LOCK_COLOR);
- gc.setBackground(LOCK_COLOR);
-
- gc.fillRectangle(
- baseX + mZoomedPixelSize,
- baseY + mZoomedPixelSize,
- getZoomedPixelSize(mNinePatchedImage.getWidth() - 2),
- getZoomedPixelSize(mNinePatchedImage.getHeight() - 2));
- gc.setAlpha(NONE_ALPHA);
-
- }
-
- private void drawPatchAreas(GC gc, int baseX, int baseY) {
- if (mChunks != null) {
- int yLen = mChunks.length;
- int xLen = mChunks[0].length;
-
- gc.setAlpha(PATCH_ALPHA);
-
- for (int yPos = 0; yPos < yLen; yPos++) {
- for (int xPos = 0; xPos < xLen; xPos++) {
- Chunk c = mChunks[yPos][xPos];
-
- if (c.type == Chunk.TYPE_FIXED) {
- gc.setBackground(BACK_COLOR);
- } else if (c.type == Chunk.TYPE_HORIZONTAL) {
- gc.setBackground(PATCH_ONEWAY_COLOR);
- } else if (c.type == Chunk.TYPE_VERTICAL) {
- gc.setBackground(PATCH_ONEWAY_COLOR);
- } else if (c.type == Chunk.TYPE_HORIZONTAL + Chunk.TYPE_VERTICAL) {
- gc.setBackground(PATCH_COLOR);
- }
- Rectangle r = c.rect;
- gc.fillRectangle(
- baseX + getZoomedPixelSize(r.x),
- baseY + getZoomedPixelSize(r.y),
- getZoomedPixelSize(r.width),
- getZoomedPixelSize(r.height));
- }
- }
- }
- gc.setAlpha(NONE_ALPHA);
- }
-
- private void drawBadPatchAreas(GC gc, int baseX, int baseY) {
- if (mBadChunks != null) {
- int yLen = mBadChunks.length;
- int xLen = mBadChunks[0].length;
-
- gc.setAlpha(NONE_ALPHA);
- gc.setForeground(CORRUPTED_COLOR);
- gc.setBackground(CORRUPTED_COLOR);
-
- for (int yPos = 0; yPos < yLen; yPos++) {
- for (int xPos = 0; xPos < xLen; xPos++) {
- Chunk c = mBadChunks[yPos][xPos];
- if ((c.type & Chunk.TYPE_CORRUPT) != 0) {
- Rectangle r = c.rect;
- gc.drawRectangle(
- baseX + getZoomedPixelSize(r.x),
- baseY + getZoomedPixelSize(r.y),
- getZoomedPixelSize(r.width),
- getZoomedPixelSize(r.height));
- }
- }
- }
- }
- }
-
- private void drawGuideLine(GC gc, int baseX, int baseY) {
- gc.setAntialias(SWT.ON);
- gc.setInterpolation(SWT.HIGH);
-
- int x = Math.round((mCursorPoint.x * ((float) mZoom / 100) + baseX)
- + ((float) mZoom / 100 / 2));
- int y = Math.round((mCursorPoint.y * ((float) mZoom / 100) + baseY)
- + ((float) mZoom / 100 / 2));
- gc.setAlpha(GUIDE_ALPHA);
-
- Point size = getSize();
- gc.drawLine(x, 0, x, size.y);
- gc.drawLine(0, y, size.x, y);
-
- gc.setAlpha(NONE_ALPHA);
- }
-
- @Override
- public void keyPressed(KeyEvent event) {
- int keycode = event.keyCode;
- if (keycode == SWT.CTRL) {
- isCtrlPressed = true;
- }
- if (keycode == SWT.SHIFT) {
- isShiftPressed = true;
- if (mStatusChangedListener != null) {
- mStatusChangedListener.helpTextChanged(HELP_MESSAGE_KEY_TIPS2);
- }
- }
- }
-
- @Override
- public void keyReleased(KeyEvent event) {
- int keycode = event.keyCode;
- if (keycode == SWT.CTRL) {
- isCtrlPressed = false;
- }
- if (keycode == SWT.SHIFT) {
- isShiftPressed = false;
- if (mStatusChangedListener != null) {
- mStatusChangedListener.helpTextChanged(HELP_MESSAGE_KEY_TIPS);
- }
- }
- }
-
- @Override
- public void dispose() {
- mBackgroundLayer.dispose();
- super.dispose();
- }
-
- /**
- * Listen image updated event.
- */
- public interface UpdateListener {
- /**
- * 9-patched image has been updated.
- */
- public void update(NinePatchedImage image);
- }
-
- /**
- * Listen status changed event.
- */
- public interface StatusChangedListener {
- /**
- * Mouse cursor position has been changed.
- */
- public void cursorPositionChanged(int x, int y);
-
- /**
- * Help text has been changed.
- */
- public void helpTextChanged(String text);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/ui/MainFrame.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/ui/MainFrame.java
deleted file mode 100644
index 71845c11c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/ui/MainFrame.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.draw9patch.ui;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.FormAttachment;
-import org.eclipse.swt.layout.FormData;
-import org.eclipse.swt.layout.FormLayout;
-import org.eclipse.swt.widgets.Composite;
-
-/**
- * Main frame.
- */
-public class MainFrame extends Composite implements ImageViewer.StatusChangedListener {
-
- private final StatusPanel mStatusPanel;
- private final ImageEditorPanel mImageEditorPanel;
-
- public StatusPanel getStatusPanel() {
- return mStatusPanel;
- }
-
- public ImageEditorPanel getImageEditorPanel() {
- return mImageEditorPanel;
- }
-
- public MainFrame(Composite parent, int style) {
- super(parent, style);
- setLayout(new FormLayout());
-
- mStatusPanel = new StatusPanel(this, SWT.NULL);
-
- FormData bottom = new FormData();
- bottom.bottom = new FormAttachment(100, 0);
- bottom.left = new FormAttachment(0, 0);
- bottom.right = new FormAttachment(100, 0);
- mStatusPanel.setLayoutData(bottom);
-
- mImageEditorPanel = new ImageEditorPanel(this, SWT.NULL);
- mImageEditorPanel.getImageViewer().setStatusChangedListener(this);
-
- mStatusPanel.setStatusChangedListener(mImageEditorPanel);
-
- FormData top = new FormData();
- top.top = new FormAttachment(0);
- top.left = new FormAttachment(0);
- top.right = new FormAttachment(100);
- top.bottom = new FormAttachment(mStatusPanel);
- mImageEditorPanel.setLayoutData(top);
-
- addKeyListener(mStatusPanel);
- addKeyListener(mImageEditorPanel.getImageViewer());
- }
-
- @Override
- public void cursorPositionChanged(int x, int y) {
- mStatusPanel.setPosition(x, y);
- }
-
- @Override
- public void helpTextChanged(String text) {
- mStatusPanel.setHelpText(text);
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/ui/StatusPanel.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/ui/StatusPanel.java
deleted file mode 100644
index 6ad258ee2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/ui/StatusPanel.java
+++ /dev/null
@@ -1,357 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.draw9patch.ui;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ControlEvent;
-import org.eclipse.swt.events.ControlListener;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.KeyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.layout.FormAttachment;
-import org.eclipse.swt.layout.FormData;
-import org.eclipse.swt.layout.FormLayout;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Scale;
-
-/**
- * Status and control pane.
- */
-public class StatusPanel extends Composite implements KeyListener {
-
- public static final int SCALE_MIN = 2;
- public static final int SCALE_MAX = 6;
-
- public static final int ZOOM_MIN = 100;
- public static final int ZOOM_MAX = 800;
-
- public static final int PADDING_TOP = 12;
- public static final int PADDING_RIGHT = 0;
- public static final int PADDING_BOTTOM = 5;
- public static final int PADDING_LEFT = 10;
-
- public static final int MIN_WIDTH = 800;
-
- private Button mShowLock = null;
- private Button mShowPatches = null;
- private Button mShowBadPatches = null;
- private Button mShowContent = null;
-
- private Label mHelpLabel = null;
-
- private Label mXPosLabel = null;
- private Label mYPosLabel = null;
-
- private ZoomControl mZoomControl = null;
- private ZoomControl mScaleControl = null;
-
- private StatusChangedListener mListener = null;
-
- public void setStatusChangedListener(StatusChangedListener l) {
- mListener = l;
- }
-
- public void setHelpText(String text) {
- Point size = getSize();
- // check window width
- if (MIN_WIDTH < size.x) {
- mHelpLabel.setText(text);
- mHelpLabel.setVisible(true);
- } else {
- mHelpLabel.setText("N/A");
- mHelpLabel.setVisible(false);
- }
- }
-
- /**
- * Set mouse cursor position.
- */
- public void setPosition(int x, int y) {
- mXPosLabel.setText(String.format("X: %4d px", x));
- mYPosLabel.setText(String.format("Y: %4d px", y));
- }
-
- public StatusPanel(Composite parent, int style) {
- super(parent, style);
- setLayout(new FormLayout());
-
- final Composite container = new Composite(this, SWT.NULL);
- container.setLayout(new FormLayout());
-
- FormData innerForm = new FormData();
- innerForm.left = new FormAttachment(0, PADDING_LEFT);
- innerForm.top = new FormAttachment(0, PADDING_TOP);
- innerForm.right = new FormAttachment(100, PADDING_RIGHT);
- innerForm.bottom = new FormAttachment(100, -PADDING_BOTTOM);
- container.setLayoutData(innerForm);
-
- buildPosition(container);
-
- Composite zoomPanels = new Composite(container, SWT.NULL);
- zoomPanels.setLayout(new GridLayout(3, false));
-
- buildZoomControl(zoomPanels);
- buildScaleControl(zoomPanels);
-
- Composite checkPanel = new Composite(container, SWT.NULL);
- checkPanel.setLayout(new GridLayout(2, false));
- FormData checkPanelForm = new FormData();
- checkPanelForm.left = new FormAttachment(zoomPanels, 0);
- checkPanelForm.bottom = new FormAttachment(100, -PADDING_BOTTOM);
- checkPanel.setLayoutData(checkPanelForm);
-
- buildCheckboxes(checkPanel);
-
- mHelpLabel = new Label(container, SWT.BORDER_SOLID | SWT.BOLD | SWT.WRAP);
- mHelpLabel.setBackground(new Color(AdtPlugin.getDisplay(), 0xFF, 0xFF, 0xFF));
- FormData hintForm = new FormData();
- hintForm.left = new FormAttachment(checkPanel, 5);
- hintForm.right = new FormAttachment(mXPosLabel, -10);
- hintForm.top = new FormAttachment(PADDING_TOP);
- hintForm.bottom = new FormAttachment(100, -PADDING_BOTTOM);
- mHelpLabel.setLayoutData(hintForm);
-
- /*
- * If the window width is not much, the "help label" will break the window.
- * Because that is wrapped automatically.
- *
- * This listener catch resized events and reset help text.
- *
- * setHelpText method checks window width.
- * If window is too narrow, help text will be set invisible.
- */
- container.addControlListener(new ControlListener() {
- @Override
- public void controlResized(ControlEvent event) {
- // reset text
- setHelpText(ImageViewer.HELP_MESSAGE_KEY_TIPS);
- }
- @Override
- public void controlMoved(ControlEvent event) {
- }
- });
-
- }
-
- private void buildPosition(Composite parent) {
- mXPosLabel = new Label(parent, SWT.NULL);
- mYPosLabel = new Label(parent, SWT.NULL);
-
- mXPosLabel.setText(String.format("X: %4d px", 1000));
- mYPosLabel.setText(String.format("Y: %4d px", 1000));
-
- FormData bottomRight = new FormData();
- bottomRight.bottom = new FormAttachment(100, 0);
- bottomRight.right = new FormAttachment(100, 0);
- mYPosLabel.setLayoutData(bottomRight);
-
- FormData aboveYPosLabel = new FormData();
- aboveYPosLabel.bottom = new FormAttachment(mYPosLabel);
- aboveYPosLabel.right = new FormAttachment(100, 0);
- mXPosLabel.setLayoutData(aboveYPosLabel);
- }
-
- private void buildScaleControl(Composite parent) {
- mScaleControl = new ZoomControl(parent);
- mScaleControl.maxLabel.setText("6x");
- mScaleControl.minLabel.setText("2x");
- mScaleControl.scale.setMinimum(SCALE_MIN);
- mScaleControl.scale.setMaximum(SCALE_MAX);
- mScaleControl.scale.setSelection(2);
- mScaleControl.scale.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent event) {
- super.widgetSelected(event);
- if (mListener != null) {
- Scale scale = (Scale) event.widget;
- mListener.scaleChanged(scale.getSelection());
- }
- }
- });
- }
-
- private void buildZoomControl(Composite parent) {
- mZoomControl = new ZoomControl(parent);
- mZoomControl.maxLabel.setText("800%");
- mZoomControl.minLabel.setText("100%");
- mZoomControl.scale.setMinimum(ZOOM_MIN);
- mZoomControl.scale.setMaximum(ZOOM_MAX - ZOOM_MIN);
- mZoomControl.scale.setSelection(400);
- mZoomControl.scale.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent event) {
- super.widgetSelected(event);
- if (mListener != null) {
- Scale scale = (Scale) event.widget;
- mListener.zoomChanged(scale.getSelection() + ZOOM_MIN);
- }
- }
- });
-
- }
-
- private void buildCheckboxes(Composite parent) {
- // check lock
- mShowLock = new Button(parent, SWT.CHECK);
- mShowLock.setText("show Lock");
- mShowLock.setSelection(true);
- mShowLock.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent event) {
- super.widgetSelected(event);
- if (mListener != null) {
- mListener.lockVisibilityChanged(mShowLock.getSelection());
- }
- }
- });
-
- // check patches
- mShowPatches = new Button(parent, SWT.CHECK);
- mShowPatches.setText("show Patches");
- mShowPatches.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent event) {
- super.widgetSelected(event);
- if (mListener != null) {
- mListener.patchesVisibilityChanged(mShowPatches.getSelection());
- }
- }
- });
-
- // check patches
- mShowBadPatches = new Button(parent, SWT.CHECK);
- mShowBadPatches.setText("show Bad patches");
- mShowBadPatches.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent event) {
- super.widgetSelected(event);
- if (mListener != null) {
- mListener.badPatchesVisibilityChanged(mShowBadPatches.getSelection());
- }
- }
- });
-
- // check contents(padding)
- mShowContent = new Button(parent, SWT.CHECK);
- mShowContent.setText("show Contents");
- mShowContent.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent event) {
- super.widgetSelected(event);
- if (mListener != null) {
- mListener.contentAreaVisibilityChanged(mShowContent.getSelection());
- }
- }
- });
- }
-
- @Override
- public void keyPressed(KeyEvent event) {
- switch (event.character) {
- case 'c':
- mShowContent.setSelection(!mShowContent.getSelection());
- if (mListener != null) {
- mListener.contentAreaVisibilityChanged(mShowContent.getSelection());
- }
- break;
- case 'l':
- mShowLock.setSelection(!mShowLock.getSelection());
- if (mListener != null) {
- mListener.lockVisibilityChanged(mShowLock.getSelection());
- }
- break;
- case 'p':
- mShowPatches.setSelection(!mShowPatches.getSelection());
- if (mListener != null) {
- mListener.patchesVisibilityChanged(mShowPatches.getSelection());
- }
- break;
- case 'b':
- mShowBadPatches.setSelection(!mShowBadPatches.getSelection());
- if (mListener != null) {
- mListener.badPatchesVisibilityChanged(mShowBadPatches.getSelection());
- }
- break;
- }
- }
-
- @Override
- public void keyReleased(KeyEvent event) {
- }
-
- private static class ZoomControl {
-
- private Label minLabel;
- private Label maxLabel;
- Scale scale;
-
- public ZoomControl(Composite composite) {
- minLabel = new Label(composite, SWT.RIGHT);
- scale = new Scale(composite, SWT.HORIZONTAL);
- maxLabel = new Label(composite, SWT.LEFT);
- }
- }
-
- /**
- * Status changed events listener.
- */
- public interface StatusChangedListener {
- /**
- * Zoom level has been changed.
- * @param zoom
- */
- public void zoomChanged(int zoom);
-
- /**
- * Scale has been changed.
- * @param scale
- */
- public void scaleChanged(int scale);
-
- /**
- * Lock visibility has been changed.
- * @param visible
- */
- public void lockVisibilityChanged(boolean visible);
-
- /**
- * Patches visibility has been changed.
- * @param visible
- */
- public void patchesVisibilityChanged(boolean visible);
-
- /**
- * BadPatches visibility has been changed.
- * @param visible
- */
- public void badPatchesVisibilityChanged(boolean visible);
-
- /**
- * Content visibility has been changed.
- * @param visible
- */
- public void contentAreaVisibilityChanged(boolean visible);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/ui/StretchesViewer.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/ui/StretchesViewer.java
deleted file mode 100644
index 353312c85..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/draw9patch/ui/StretchesViewer.java
+++ /dev/null
@@ -1,267 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.draw9patch.ui;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.draw9patch.graphics.GraphicsUtilities;
-import com.android.ide.eclipse.adt.internal.editors.draw9patch.graphics.NinePatchedImage;
-import com.android.ide.eclipse.adt.internal.editors.draw9patch.graphics.NinePatchedImage.Projection;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.PaintEvent;
-import org.eclipse.swt.events.PaintListener;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.ImageData;
-import org.eclipse.swt.graphics.PaletteData;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.widgets.Canvas;
-import org.eclipse.swt.widgets.Composite;
-
-/**
- * Preview 9-patched image pane.
- */
-public class StretchesViewer extends Composite {
- private static final boolean DEBUG = false;
-
- private static final int PADDING_COLOR = 0x0000CC;
-
- private static final int PADDING_COLOR_ALPHA = 100;
-
- private static final PaletteData PADDING_PALLET
- = new PaletteData(new RGB[] {new RGB(0x00, 0x00, 0xCC)});
-
- private static final String CHECKER_PNG_PATH = "/icons/checker.png";
-
- private Image mBackgroundLayer = null;
-
- private final StretchView mHorizontal;
- private final StretchView mVertical;
-
- private final StretchView mBoth;
-
- private NinePatchedImage mNinePatchedImage = null;
-
- private ImageData mContentAreaImageData = null;
-
- private boolean mIsContentAreaShown = false;
-
- private Image mContentAreaImage = null;
-
- private int mScale = 2;
-
- public StretchesViewer(Composite parent, int style) {
- super(parent, style);
-
- mBackgroundLayer = AdtPlugin.getImageDescriptor(CHECKER_PNG_PATH).createImage();
-
- setLayout(new FillLayout(SWT.VERTICAL));
-
- mHorizontal = new StretchView(this, SWT.NULL);
- mVertical = new StretchView(this, SWT.NULL);
- mBoth = new StretchView(this, SWT.NULL);
- }
-
- /**
- * Set show/not show content area.
- * @param If show, true
- */
- public void setShowContentArea(boolean show) {
- mIsContentAreaShown = show;
- redraw();
- }
-
- private static final boolean equalSize(ImageData image1, ImageData image2) {
- return (image1.width == image2.width && image1.height == image2.height);
- }
-
- /**
- * Update preview image.
- */
- public void updatePreview(NinePatchedImage image) {
- mNinePatchedImage = image;
- ImageData base = mNinePatchedImage.getImageData();
-
- if (mContentAreaImageData == null
- || (mContentAreaImageData != null && !equalSize(base, mContentAreaImageData))) {
- mContentAreaImageData = new ImageData(
- base.width,
- base.height,
- 1,
- PADDING_PALLET);
- } else {
- GraphicsUtilities.clearImageData(mContentAreaImageData);
- }
-
- mHorizontal.setImage(mNinePatchedImage);
- mVertical.setImage(mNinePatchedImage);
- mBoth.setImage(mNinePatchedImage);
-
- mContentAreaImage = buildContentAreaPreview();
-
- setScale(mScale);
- }
-
- private Image buildContentAreaPreview() {
- if (mContentAreaImage != null) {
- mContentAreaImage.dispose();
- }
-
- Rectangle rect = mNinePatchedImage.getContentArea();
-
- int yLen = rect.y + rect.height;
- for (int y = rect.y; y < yLen; y++) {
- int xLen = rect.x + rect.width;
- for (int x = rect.x; x < xLen; x++) {
- mContentAreaImageData.setPixel(x, y, PADDING_COLOR);
- mContentAreaImageData.setAlpha(x, y, PADDING_COLOR_ALPHA);
- }
- }
- return new Image(AdtPlugin.getDisplay(), mContentAreaImageData);
- }
-
- public void setScale(int scale) {
- if (DEBUG) {
- System.out.println("scale = " + scale);
- }
-
- mScale = scale;
- int imageWidth = mNinePatchedImage.getWidth();
- int imageHeight = mNinePatchedImage.getHeight();
-
- mHorizontal.setSize(imageWidth * scale, imageHeight);
- mVertical.setSize(imageWidth, imageHeight * scale);
- mBoth.setSize(imageWidth * scale, imageHeight * scale);
-
- redraw();
- }
-
- @Override
- public void dispose() {
- mBackgroundLayer.dispose();
- super.dispose();
- }
-
- private class StretchView extends Canvas implements PaintListener {
-
- private final Point mSize = new Point(0, 0);
- private final Rectangle mPadding = new Rectangle(0, 0, 0, 0);
- private Projection[][] mProjection = null;
-
- public StretchView(Composite parent, int style) {
- super(parent, style);
- addPaintListener(this);
- }
-
- private void setImage(NinePatchedImage image) {
- setSize(image.getWidth(), image.getHeight());
- }
-
- @Override
- public void setSize(int width, int heigh) {
- mSize.x = width;
- mSize.y = heigh;
- mProjection = mNinePatchedImage.getProjections(mSize.x, mSize.y, mProjection);
- }
-
- private synchronized void calcPaddings(int width, int height) {
- Point canvasSize = getSize();
-
- mPadding.x = (canvasSize.x - width) / 2;
- mPadding.y = (canvasSize.y - height) / 2;
-
- mPadding.width = width;
- mPadding.height = height;
- }
-
- @Override
- public void paintControl(PaintEvent pe) {
- if (mNinePatchedImage == null || mProjection == null) {
- return;
- }
-
- Point size = getSize();
-
- // relative scaling
- float ratio = 1.0f;
- float wRatio = ((float) size.x / mSize.x);
- ratio = Math.min(wRatio, ratio);
- float hRatio = ((float) size.y / mSize.y);
- ratio = Math.min(hRatio, ratio);
-
- int width = Math.round(mSize.x * ratio);
- int height = Math.round(mSize.y * ratio);
-
- calcPaddings(width, height);
-
- Rectangle dest = new Rectangle(0, 0, 0, 0);
-
- GC gc = pe.gc;
-
- int backgroundLayerWidth = mBackgroundLayer.getImageData().width;
- int backgroundLayerHeight = mBackgroundLayer.getImageData().height;
-
- int yCount = size.y / backgroundLayerHeight
- + ((size.y % backgroundLayerHeight) > 0 ? 1 : 0);
- int xCount = size.x / backgroundLayerWidth
- + ((size.x % backgroundLayerWidth) > 0 ? 1 : 0);
-
- // draw background layer
- for (int y = 0; y < yCount; y++) {
- for (int x = 0; x < xCount; x++) {
- gc.drawImage(mBackgroundLayer,
- x * backgroundLayerWidth,
- y * backgroundLayerHeight);
- }
- }
-
- // draw the border line
- gc.setAlpha(0x88);
- gc.drawRectangle(0, 0, size.x, size.y);
- gc.setAlpha(0xFF);
-
- int yLen = mProjection.length;
- int xLen = mProjection[0].length;
- for (int yPos = 0; yPos < yLen; yPos++) {
- for (int xPos = 0; xPos < xLen; xPos++) {
- Projection p = mProjection[yPos][xPos];
-
- // consider the scale
- dest.x = (int) Math.ceil(p.dest.x * ratio);
- dest.y = (int) Math.ceil(p.dest.y * ratio);
- dest.width = (int) Math.ceil(p.dest.width * ratio);
- dest.height = (int) Math.ceil(p.dest.height * ratio);
-
- gc.drawImage(mNinePatchedImage.getImage(), p.src.x, p.src.y,
- p.src.width, p.src.height,
- (mPadding.x + dest.x), (mPadding.y + dest.y),
- dest.width, dest.height);
-
- if (mIsContentAreaShown) {
- gc.drawImage(mContentAreaImage, p.src.x, p.src.y,
- p.src.width, p.src.height,
- (mPadding.x + dest.x), (mPadding.y + dest.y),
- dest.width, dest.height);
- }
- }
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/drawable/DrawableContentAssist.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/drawable/DrawableContentAssist.java
deleted file mode 100644
index b0bea511d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/drawable/DrawableContentAssist.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.drawable;
-
-import com.android.annotations.VisibleForTesting;
-import com.android.ide.eclipse.adt.internal.editors.AndroidContentAssist;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-
-/**
- * Content Assist Processor for /res/drawable XML files
- */
-@VisibleForTesting
-public final class DrawableContentAssist extends AndroidContentAssist {
- public DrawableContentAssist() {
- super(AndroidTargetData.DESCRIPTOR_DRAWABLE);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/drawable/DrawableDescriptors.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/drawable/DrawableDescriptors.java
deleted file mode 100644
index 4858ac7c6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/drawable/DrawableDescriptors.java
+++ /dev/null
@@ -1,301 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.drawable;
-
-import static com.android.SdkConstants.ANDROID_NS_NAME;
-import static com.android.SdkConstants.ANDROID_URI;
-
-import com.android.ide.common.api.IAttributeInfo.Format;
-import com.android.ide.common.resources.platform.AttributeInfo;
-import com.android.ide.common.resources.platform.DeclareStyleableInfo;
-import com.android.ide.eclipse.adt.internal.editors.animator.AnimatorDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.IDescriptorProvider;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ReferenceAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.XmlnsAttributeDescriptor;
-import com.android.resources.ResourceType;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Descriptors for /res/drawable files
- */
-public class DrawableDescriptors implements IDescriptorProvider {
- private static final String SDK_URL_BASE =
- "http://d.android.com/guide/topics/resources/"; //$NON-NLS-1$
-
- /** The root element descriptor */
- private ElementDescriptor mDescriptor;
- /** The root element descriptors */
- private ElementDescriptor[] mRootDescriptors;
- private Map<String, ElementDescriptor> nameToDescriptor;
-
- /** @return the root descriptor. */
- @Override
- public ElementDescriptor getDescriptor() {
- if (mDescriptor == null) {
- mDescriptor = new ElementDescriptor("", getRootElementDescriptors()); //$NON-NLS-1$
- }
-
- return mDescriptor;
- }
-
- @Override
- public ElementDescriptor[] getRootElementDescriptors() {
- return mRootDescriptors;
- }
-
- /**
- * Returns a descriptor for the given root tag name
- *
- * @param tag the tag name to look up a descriptor for
- * @return a descriptor with the given tag name
- */
- public ElementDescriptor getElementDescriptor(String tag) {
- if (nameToDescriptor == null) {
- nameToDescriptor = new HashMap<String, ElementDescriptor>();
- for (ElementDescriptor descriptor : getRootElementDescriptors()) {
- nameToDescriptor.put(descriptor.getXmlName(), descriptor);
- }
- }
-
- ElementDescriptor descriptor = nameToDescriptor.get(tag);
- if (descriptor == null) {
- descriptor = getDescriptor();
- }
- return descriptor;
- }
-
- public synchronized void updateDescriptors(Map<String, DeclareStyleableInfo> styleMap) {
- XmlnsAttributeDescriptor xmlns = new XmlnsAttributeDescriptor(ANDROID_NS_NAME,
- ANDROID_URI);
- List<ElementDescriptor> descriptors = new ArrayList<ElementDescriptor>();
-
- AnimatorDescriptors.addElement(descriptors, styleMap,
- "animation-list", "Animation List", "AnimationDrawable", null, //$NON-NLS-1$ //$NON-NLS-3$
- "An animation defined in XML that shows a sequence of images in "
- + "order (like a film)",
- SDK_URL_BASE + "animation-resource.html#Frame",
- xmlns, null, true /*mandatory*/);
-
- /* For some reason, android.graphics.drawable.AnimatedRotateDrawable is marked with @hide
- * so we should not register it and its attributes here. See issue #19248 for details.
- AnimatorDescriptors.addElement(descriptors, styleMap,
- "animated-rotate", "Animated Rotate", "AnimatedRotateDrawable", null, //$NON-NLS-1$ //$NON-NLS-3$
- // Need docs
- null, // tooltip
- null, // sdk_url
- xmlns, null, true);
- */
-
- AnimatorDescriptors.addElement(descriptors, styleMap,
- "bitmap", "BitMap", "BitmapDrawable", null, //$NON-NLS-1$ //$NON-NLS-3$
- "An XML bitmap is a resource defined in XML that points to a bitmap file. "
- + "The effect is an alias for a raw bitmap file. The XML can "
- + "specify additional properties for the bitmap such as "
- + "dithering and tiling.",
- SDK_URL_BASE + "drawable-resource.html#Bitmap", //$NON-NLS-1$
- xmlns, null, true /* mandatory */);
-
- AnimatorDescriptors.addElement(descriptors, styleMap,
- "clip", "Clip", "ClipDrawable", null, //$NON-NLS-1$ //$NON-NLS-3$
- "An XML file that defines a drawable that clips another Drawable based on "
- + "this Drawable's current level value.",
- SDK_URL_BASE + "drawable-resource.html#Clip", //$NON-NLS-1$
- xmlns, null, true /*mandatory*/);
-
- AnimatorDescriptors.addElement(descriptors, styleMap,
- "color", "Color", "ColorDrawable", null, //$NON-NLS-1$ //$NON-NLS-3$
- "XML resource that carries a color value (a hexadecimal color)",
- SDK_URL_BASE + "more-resources.html#Color",
- xmlns, null, true /*mandatory*/);
-
- AnimatorDescriptors.addElement(descriptors, styleMap,
- "inset", "Inset", "InsetDrawable", null, //$NON-NLS-1$ //$NON-NLS-3$
- "An XML file that defines a drawable that insets another drawable by a "
- + "specified distance. This is useful when a View needs a background "
- + "drawble that is smaller than the View's actual bounds.",
- SDK_URL_BASE + "drawable-resource.html#Inset", //$NON-NLS-1$
- xmlns, null, true /*mandatory*/);
-
- // Layer list
-
- // An <item> in a <selector> or <
- ElementDescriptor layerItem = AnimatorDescriptors.addElement(null, styleMap,
- "item", "Item", "LayerDrawableItem", null, //$NON-NLS-1$ //$NON-NLS-3$
- "Defines a drawable to place in the layer drawable, in a position "
- + "defined by its attributes. Must be a child of a <selector> "
- + "element. Accepts child <bitmap> elements.",
- SDK_URL_BASE + "drawable-resource.html#LayerList", //$NON-NLS-1$
- null, /* extra attribute */
- null, /* This is wrong -- we can now embed any above drawable
- (but without xmlns as extra) */
- false /*mandatory*/);
- ElementDescriptor[] layerChildren = layerItem != null
- ? new ElementDescriptor[] { layerItem } : null;
-
- AnimatorDescriptors.addElement(descriptors, styleMap,
- "layer-list", "Layer List", "LayerDrawable", null, //$NON-NLS-1$ //$NON-NLS-3$
- "A Drawable that manages an array of other Drawables. These are drawn in "
- + "array order, so the element with the largest index is be drawn on top.",
- SDK_URL_BASE + "drawable-resource.html#LayerList", //$NON-NLS-1$
- xmlns,
- layerChildren,
- true /*mandatory*/);
-
- // Level list children
- ElementDescriptor levelListItem = AnimatorDescriptors.addElement(null, styleMap,
- "item", "Item", "LevelListDrawableItem", null, //$NON-NLS-1$ //$NON-NLS-3$
- "Defines a drawable to use at a certain level.",
- SDK_URL_BASE + "drawable-resource.html#LevelList", //$NON-NLS-1$
- null, /* extra attribute */
- null, /* no further children */
- // TODO: The inflation code seems to show that all drawables can be nested here!
- false /*mandatory*/);
- AnimatorDescriptors.addElement(descriptors, styleMap,
- "level-list", "Level List", "LevelListDrawable", null, //$NON-NLS-1$ //$NON-NLS-3$
- "An XML file that defines a drawable that manages a number of alternate "
- + "Drawables, each assigned a maximum numerical value",
- SDK_URL_BASE + "drawable-resource.html#LevelList", //$NON-NLS-1$
- xmlns,
- levelListItem != null ? new ElementDescriptor[] { levelListItem } : null,
- true /*mandatory*/);
-
- // Not yet supported
- //addElement(descriptors, styleMap, "mipmap", "Mipmap", "MipmapDrawable", null,
- // null /* tooltip */,
- // null /* sdk_url */,
- // xmlns, null, true /*mandatory*/);
-
- AnimatorDescriptors.addElement(descriptors, styleMap,
- "nine-patch", "Nine Patch", "NinePatchDrawable", null, //$NON-NLS-1$ //$NON-NLS-3$
- "A PNG file with stretchable regions to allow image resizing "
- + "based on content (.9.png).",
- SDK_URL_BASE + "drawable-resource.html#NinePatch", //$NON-NLS-1$
- xmlns, null, true /*mandatory*/);
-
- AnimatorDescriptors.addElement(descriptors, styleMap,
- "rotate", "Rotate", "RotateDrawable", null, //$NON-NLS-1$ //$NON-NLS-3$
- // Need docs
- null /* tooltip */,
- null /* sdk_url */,
- xmlns, null, true /*mandatory*/);
-
- AnimatorDescriptors.addElement(descriptors, styleMap,
- "scale", "Shape", "ScaleDrawable", null, //$NON-NLS-1$ //$NON-NLS-3$
- "An XML file that defines a drawable that changes the size of another Drawable "
- + "based on its current level value.",
- SDK_URL_BASE + "drawable-resource.html#Scale", //$NON-NLS-1$
- xmlns, null, true /*mandatory*/);
-
- // Selector children
- ElementDescriptor selectorItem = AnimatorDescriptors.addElement(null, styleMap,
- "item", "Item", "DrawableStates", null, //$NON-NLS-1$ //$NON-NLS-3$
- "Defines a drawable to use during certain states, as described by "
- + "its attributes. Must be a child of a <selector> element.",
- SDK_URL_BASE + "drawable-resource.html#StateList", //$NON-NLS-1$
- new ReferenceAttributeDescriptor(
- ResourceType.DRAWABLE, "drawable", ANDROID_URI, //$NON-NLS-1$
- new AttributeInfo("drawable", Format.REFERENCE_SET))
- .setTooltip("Reference to a drawable resource."),
- null, /* This is wrong -- we can now embed any above drawable
- (but without xmlns as extra) */
- false /*mandatory*/);
-
- AnimatorDescriptors.addElement(descriptors, styleMap,
- "selector", "Selector", "StateListDrawable", null, //$NON-NLS-1$ //$NON-NLS-3$
- "An XML file that references different bitmap graphics for different states "
- + "(for example, to use a different image when a button is pressed).",
- SDK_URL_BASE + "drawable-resource.html#StateList", //$NON-NLS-1$
- xmlns,
- selectorItem != null ? new ElementDescriptor[] { selectorItem } : null,
- true /*mandatory*/);
-
- // Shape
- // Shape children
- List<ElementDescriptor> shapeChildren = new ArrayList<ElementDescriptor>();
- // Selector children
- AnimatorDescriptors.addElement(shapeChildren, styleMap,
- "size", "Size", "GradientDrawableSize", null, //$NON-NLS-1$ //$NON-NLS-3$
- null /* tooltip */, null /* sdk_url */, null /* extra attribute */,
- null /* children */, false /* mandatory */);
- AnimatorDescriptors.addElement(shapeChildren, styleMap,
- "gradient", "Gradient", "GradientDrawableGradient", null, //$NON-NLS-1$ //$NON-NLS-3$
- null /* tooltip */, null /* sdk_url */, null /* extra attribute */,
- null /* children */, false /* mandatory */);
- AnimatorDescriptors.addElement(shapeChildren, styleMap,
- "solid", "Solid", "GradientDrawableSolid", null, //$NON-NLS-1$ //$NON-NLS-3$
- null /* tooltip */, null /* sdk_url */, null /* extra attribute */,
- null /* children */, false /* mandatory */);
- AnimatorDescriptors.addElement(shapeChildren, styleMap,
- "stroke", "Stroke", "GradientDrawableStroke", null, //$NON-NLS-1$ //$NON-NLS-3$
- null /* tooltip */, null /* sdk_url */, null /* extra attribute */,
- null /* children */, false /* mandatory */);
- AnimatorDescriptors.addElement(shapeChildren, styleMap,
- "corners", "Corners", "DrawableCorners", null, //$NON-NLS-1$ //$NON-NLS-3$
- null /* tooltip */, null /* sdk_url */, null /* extra attribute */,
- null /* children */, false /* mandatory */);
- AnimatorDescriptors.addElement(shapeChildren, styleMap,
- "padding", "Padding", "GradientDrawablePadding", null, //$NON-NLS-1$ //$NON-NLS-3$
- null /* tooltip */, null /* sdk_url */, null /* extra attribute */,
- null /* children */, false /* mandatory */);
-
- AnimatorDescriptors.addElement(descriptors, styleMap,
- "shape", "Shape", //$NON-NLS-1$
-
- // The documentation says that a <shape> element creates a ShapeDrawable,
- // but ShapeDrawable isn't finished and the code currently creates
- // a GradientDrawable.
- //"ShapeDrawable", //$NON-NLS-1$
- "GradientDrawable", //$NON-NLS-1$
-
- null,
- "An XML file that defines a geometric shape, including colors and gradients.",
- SDK_URL_BASE + "drawable-resource.html#Shape", //$NON-NLS-1$
- xmlns,
-
- // These are the GradientDrawable children, not the ShapeDrawable children
- shapeChildren.toArray(new ElementDescriptor[shapeChildren.size()]),
- true /*mandatory*/);
-
- AnimatorDescriptors.addElement(descriptors, styleMap,
- "transition", "Transition", "TransitionDrawable", null, //$NON-NLS-1$ //$NON-NLS-3$
- "An XML file that defines a drawable that can cross-fade between two "
- + "drawable resources. Each drawable is represented by an <item> "
- + "element inside a single <transition> element. No more than two "
- + "items are supported. To transition forward, call startTransition(). "
- + "To transition backward, call reverseTransition().",
- SDK_URL_BASE + "drawable-resource.html#Transition", //$NON-NLS-1$
- xmlns,
- layerChildren, // children: a TransitionDrawable is a LayerDrawable
- true /*mandatory*/);
-
- mRootDescriptors = descriptors.toArray(new ElementDescriptor[descriptors.size()]);
-
- // A <selector><item> can contain any of the top level drawables
- if (selectorItem != null) {
- selectorItem.setChildren(mRootDescriptors);
- }
- // Docs says it can accept <bitmap> but code comment suggests any is possible;
- // test and either use this or just { bitmap }
- if (layerItem != null) {
- layerItem.setChildren(mRootDescriptors);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/drawable/DrawableEditorDelegate.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/drawable/DrawableEditorDelegate.java
deleted file mode 100644
index a54fa8c41..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/drawable/DrawableEditorDelegate.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.drawable;
-
-import static com.android.ide.eclipse.adt.AdtConstants.EDITORS_NAMESPACE;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlDelegate;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DocumentDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.resources.ResourceFolderType;
-
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-/**
- * Editor for /res/drawable XML files.
- */
-@SuppressWarnings("restriction")
-public class DrawableEditorDelegate extends CommonXmlDelegate {
-
- public static class Creator implements IDelegateCreator {
- @Override
- @SuppressWarnings("unchecked")
- public DrawableEditorDelegate createForFile(
- @NonNull CommonXmlEditor delegator,
- @Nullable ResourceFolderType type) {
- if (ResourceFolderType.DRAWABLE == type) {
- return new DrawableEditorDelegate(delegator);
- }
-
- return null;
- }
- }
-
- /**
- * Old standalone-editor ID.
- * Use {@link CommonXmlEditor#ID} instead.
- */
- public static final String LEGACY_EDITOR_ID =
- EDITORS_NAMESPACE + ".drawable.DrawableEditor"; //$NON-NLS-1$
-
- /** The tag used at the root */
- private String mRootTag;
-
- /**
- * Creates the form editor for resources XML files.
- */
- private DrawableEditorDelegate(CommonXmlEditor editor) {
- super(editor, new DrawableContentAssist());
- editor.addDefaultTargetListener();
- }
-
- @Override
- public void delegateCreateFormPages() {
- /* Disabled for now; doesn't work quite right
- try {
- addPage(new DrawableTreePage(this));
- } catch (PartInitException e) {
- AdtPlugin.log(IStatus.ERROR, "Error creating nested page"); //$NON-NLS-1$
- AdtPlugin.getDefault().getLog().log(e.getStatus());
- }
- */
- }
-
- @Override
- public void delegateXmlModelChanged(Document xmlDoc) {
- Element rootElement = xmlDoc.getDocumentElement();
- if (rootElement != null) {
- mRootTag = rootElement.getTagName();
- }
-
- delegateInitUiRootNode(false /*force*/);
-
- if (mRootTag != null
- && !mRootTag.equals(getUiRootNode().getDescriptor().getXmlLocalName())) {
- AndroidTargetData data = getEditor().getTargetData();
- if (data != null) {
- ElementDescriptor descriptor =
- data.getDrawableDescriptors().getElementDescriptor(mRootTag);
- // Replace top level node now that we know the actual type
-
- // Disconnect from old
- getUiRootNode().setEditor(null);
- getUiRootNode().setXmlDocument(null);
-
- // Create new
- setUiRootNode(descriptor.createUiNode());
- getUiRootNode().setXmlDocument(xmlDoc);
- getUiRootNode().setEditor(getEditor());
- }
- }
-
- if (getUiRootNode().getDescriptor() instanceof DocumentDescriptor) {
- getUiRootNode().loadFromXmlNode(xmlDoc);
- } else {
- getUiRootNode().loadFromXmlNode(rootElement);
- }
- }
-
- @Override
- public void delegateInitUiRootNode(boolean force) {
- // The manifest UI node is always created, even if there's no corresponding XML node.
- if (getUiRootNode() == null || force) {
- ElementDescriptor descriptor;
- boolean reload = false;
- AndroidTargetData data = getEditor().getTargetData();
- if (data == null) {
- descriptor = new DocumentDescriptor("temp", null /*children*/);
- } else {
- descriptor = data.getDrawableDescriptors().getElementDescriptor(mRootTag);
- reload = true;
- }
- setUiRootNode(descriptor.createUiNode());
- getUiRootNode().setEditor(getEditor());
-
- if (reload) {
- onDescriptorsChanged();
- }
- }
- }
-
- private void onDescriptorsChanged() {
- IStructuredModel model = getEditor().getModelForRead();
- if (model != null) {
- try {
- Node node = getEditor().getXmlDocument(model).getDocumentElement();
- getUiRootNode().reloadFromXmlNode(node);
- } finally {
- model.releaseFromRead();
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/export/AbstractPropertiesFieldsPart.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/export/AbstractPropertiesFieldsPart.java
deleted file mode 100755
index bc3051e88..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/export/AbstractPropertiesFieldsPart.java
+++ /dev/null
@@ -1,356 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.export;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.ui.SectionHelper.ManifestSectionPart;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.Section;
-
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-
-/**
- * Section part for editing fields of a properties file in an Export editor.
- * <p/>
- * This base class is intended to be derived and customized.
- */
-abstract class AbstractPropertiesFieldsPart extends ManifestSectionPart {
-
- private final HashMap<String, Control> mNameToField = new HashMap<String, Control>();
-
- private ExportEditor mEditor;
-
- private boolean mInternalTextUpdate = false;
-
- public AbstractPropertiesFieldsPart(Composite body, FormToolkit toolkit, ExportEditor editor) {
- super(body, toolkit, Section.TWISTIE | Section.EXPANDED, true /* description */);
- mEditor = editor;
- }
-
- protected HashMap<String, Control> getNameToField() {
- return mNameToField;
- }
-
- protected ExportEditor getEditor() {
- return mEditor;
- }
-
- protected void setInternalTextUpdate(boolean internalTextUpdate) {
- mInternalTextUpdate = internalTextUpdate;
- }
-
- protected boolean isInternalTextUpdate() {
- return mInternalTextUpdate;
- }
-
- /**
- * Adds a modify listener to every text field that will mark the part as dirty.
- *
- * CONTRACT: Derived classes MUST call this at the end of their constructor.
- *
- * @see #setFieldModifyListener(Control, ModifyListener)
- */
- protected void addModifyListenerToFields() {
- ModifyListener markDirtyListener = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- // Mark the part as dirty if a field has been changed.
- // This will force a commit() operation to store the data in the model.
- if (!mInternalTextUpdate) {
- markDirty();
- }
- }
- };
-
- for (Control field : mNameToField.values()) {
- setFieldModifyListener(field, markDirtyListener);
- }
- }
-
- /**
- * Sets a listener that will mark the part as dirty when the control is modified.
- * The base method only handles {@link Text} fields.
- *
- * CONTRACT: Derived classes CAN use this to add a listener to their own controls.
- * The listener must call {@link #markDirty()} when the control is modified by the user.
- *
- * @param field A control previously registered with {@link #getNameToField()}.
- * @param markDirtyListener A {@link ModifyListener} that invokes {@link #markDirty()}.
- *
- * @see #isInternalTextUpdate()
- */
- protected void setFieldModifyListener(Control field, ModifyListener markDirtyListener) {
- if (field instanceof Text) {
- ((Text) field).addModifyListener(markDirtyListener);
- }
- }
-
- /**
- * Updates the model based on the content of fields. This is invoked when a field
- * has marked the document as dirty.
- *
- * CONTRACT: Derived classes do not need to override this.
- */
- @Override
- public void commit(boolean onSave) {
-
- // We didn't store any information indicating which field was dirty (we could).
- // Since there are not many fields, just update all the document lines that
- // match our field keywords.
-
- if (isDirty()) {
- mEditor.wrapRewriteSession(new Runnable() {
- @Override
- public void run() {
- saveFieldsToModel();
- }
- });
- }
-
- super.commit(onSave);
- }
-
- private void saveFieldsToModel() {
- // Get a list of all keywords to process. Go thru the document, replacing in-place
- // the ones we can find and remove them from this set. This will leave the list
- // of new keywords to add at the end of the document.
- HashSet<String> allKeywords = new HashSet<String>(mNameToField.keySet());
-
- IDocument doc = mEditor.getDocument();
- int numLines = doc.getNumberOfLines();
-
- String delim = null;
- try {
- delim = numLines > 0 ? doc.getLineDelimiter(0) : null;
- } catch (BadLocationException e1) {
- // ignore
- }
- if (delim == null || delim.length() == 0) {
- delim = SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_WINDOWS ?
- "\r\n" : "\n"; //$NON-NLS-1$ //$NON-NLS-2#
- }
-
- for (int i = 0; i < numLines; i++) {
- try {
- IRegion info = doc.getLineInformation(i);
- String line = doc.get(info.getOffset(), info.getLength());
- line = line.trim();
- if (line.startsWith("#")) { //$NON-NLS-1$
- continue;
- }
-
- int pos = line.indexOf('=');
- if (pos > 0 && pos < line.length() - 1) {
- String key = line.substring(0, pos).trim();
-
- Control field = mNameToField.get(key);
- if (field != null) {
-
- // This is the new line to inject
- line = key + "=" + getFieldText(field);
-
- try {
- // replace old line by new one. This doesn't change the
- // line delimiter.
- mInternalTextUpdate = true;
- doc.replace(info.getOffset(), info.getLength(), line);
- allKeywords.remove(key);
- } finally {
- mInternalTextUpdate = false;
- }
- }
- }
-
- } catch (BadLocationException e) {
- // TODO log it
- AdtPlugin.log(e, "Failed to replace in export.properties");
- }
- }
-
- for (String key : allKeywords) {
- Control field = mNameToField.get(key);
- if (field != null) {
- // This is the new line to inject
- String line = key + "=" + getFieldText(field);
-
- try {
- // replace old line by new one
- mInternalTextUpdate = true;
-
- numLines = doc.getNumberOfLines();
-
- IRegion info = numLines > 0 ? doc.getLineInformation(numLines - 1) : null;
- if (info != null && info.getLength() == 0) {
- // last line is empty. Insert right before there.
- doc.replace(info.getOffset(), info.getLength(), line);
- } else {
- if (numLines > 0) {
- String eofDelim = doc.getLineDelimiter(numLines - 1);
- if (eofDelim == null || eofDelim.length() == 0) {
- // The document doesn't end with a line delimiter, so add
- // one to the line to be written.
- line = delim + line;
- }
- }
-
- int len = doc.getLength();
- doc.replace(len, 0, line);
- }
-
- allKeywords.remove(key);
- } catch (BadLocationException e) {
- // TODO log it
- AdtPlugin.log(e, "Failed to append to export.properties: %s", line);
- } finally {
- mInternalTextUpdate = false;
- }
- }
- }
- }
-
- /**
- * Used when committing fields values to the model to retrieve the text
- * associated with a field.
- * <p/>
- * The base method only handles {@link Text} controls.
- *
- * CONTRACT: Derived classes CAN use this to support their own controls.
- *
- * @param field A control previously registered with {@link #getNameToField()}.
- * @return A non-null string to write to the properties files.
- */
- protected String getFieldText(Control field) {
- if (field instanceof Text) {
- return ((Text) field).getText();
- }
- return "";
- }
-
- /**
- * Called after all pages have been created, to let the parts initialize their
- * content based on the document's model.
- * <p/>
- * The model should be acceded via the {@link ExportEditor}.
- *
- * @param editor The {@link ExportEditor} instance.
- */
- public void onModelInit(ExportEditor editor) {
-
- // Start with a set of all the possible keywords and remove those we
- // found in the document as we read the lines.
- HashSet<String> allKeywords = new HashSet<String>(mNameToField.keySet());
-
- // Parse the lines in the document for patterns "keyword=value",
- // trimming all whitespace and discarding lines that start with # (comments)
- // then affect to the internal fields as appropriate.
- IDocument doc = editor.getDocument();
- int numLines = doc.getNumberOfLines();
- for (int i = 0; i < numLines; i++) {
- try {
- IRegion info = doc.getLineInformation(i);
- String line = doc.get(info.getOffset(), info.getLength());
- line = line.trim();
- if (line.startsWith("#")) { //$NON-NLS-1$
- continue;
- }
-
- int pos = line.indexOf('=');
- if (pos > 0 && pos < line.length() - 1) {
- String key = line.substring(0, pos).trim();
-
- Control field = mNameToField.get(key);
- if (field != null) {
- String value = line.substring(pos + 1).trim();
- try {
- mInternalTextUpdate = true;
- setFieldText(field, value);
- allKeywords.remove(key);
- } finally {
- mInternalTextUpdate = false;
- }
- }
- }
-
- } catch (BadLocationException e) {
- // TODO log it
- AdtPlugin.log(e, "Failed to set field to export.properties value");
- }
- }
-
- // Clear the text of any keyword we didn't find in the document
- Iterator<String> iterator = allKeywords.iterator();
- while (iterator.hasNext()) {
- String key = iterator.next();
- Control field = mNameToField.get(key);
- if (field != null) {
- try {
- mInternalTextUpdate = true;
- setFieldText(field, "");
- iterator.remove();
- } finally {
- mInternalTextUpdate = false;
- }
- }
- }
- }
-
- /**
- * Used when reading the model to set the field values.
- * <p/>
- * The base method only handles {@link Text} controls.
- *
- * CONTRACT: Derived classes CAN use this to support their own controls.
- *
- * @param field A control previously registered with {@link #getNameToField()}.
- * @param value A non-null string to that was read from the properties files.
- * The value is an empty string if the property line is missing.
- */
- protected void setFieldText(Control field, String value) {
- if (field instanceof Text) {
- ((Text) field).setText(value);
- }
- }
-
- /**
- * Called after the document model has been changed. The model should be acceded via
- * the {@link ExportEditor} (e.g. getDocument, wrapRewriteSession)
- *
- * @param editor The {@link ExportEditor} instance.
- * @param event Specification of changes applied to document.
- */
- public void onModelChanged(ExportEditor editor, DocumentEvent event) {
- // To simplify and since we don't have many fields, just reload all the values.
- // A better way would to be to look at DocumentEvent which gives us the offset/length
- // and text that has changed.
- if (!mInternalTextUpdate) {
- onModelInit(editor);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/export/ExportEditor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/export/ExportEditor.java
deleted file mode 100755
index 769f74e27..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/export/ExportEditor.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.export;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.internal.editors.AndroidTextEditor;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.part.FileEditorInput;
-
-/**
- * Multi-page form editor for export.properties in Export Projects.
- */
-public class ExportEditor extends AndroidTextEditor {
-
- public static final String ID = AdtConstants.EDITORS_NAMESPACE + ".text.ExportEditor"; //$NON-NLS-1$
-
- private ExportPropertiesPage mExportPropsPage;
-
- /**
- * Creates the form editor for resources XML files.
- */
- public ExportEditor() {
- super();
- }
-
- // ---- Base Class Overrides ----
-
- /**
- * Returns whether the "save as" operation is supported by this editor.
- * <p/>
- * Save-As is a valid operation for the ManifestEditor since it acts on a
- * single source file.
- *
- * @see IEditorPart
- */
- @Override
- public boolean isSaveAsAllowed() {
- return true;
- }
-
- /**
- * Create the various form pages.
- */
- @Override
- protected void createFormPages() {
- try {
- mExportPropsPage = new ExportPropertiesPage(this);
- addPage(mExportPropsPage);
- } catch (PartInitException e) {
- AdtPlugin.log(e, "Error creating nested page"); //$NON-NLS-1$
- }
-
- }
-
- /* (non-java doc)
- * Change the tab/title name to include the project name.
- */
- @Override
- protected void setInput(IEditorInput input) {
- super.setInput(input);
- if (input instanceof FileEditorInput) {
- FileEditorInput fileInput = (FileEditorInput) input;
- IFile file = fileInput.getFile();
- setPartName(String.format("%1$s", file.getName()));
- }
- }
-
- @Override
- protected void postCreatePages() {
- super.postCreatePages();
- mExportPropsPage.onModelInit();
- }
-
- /**
- * Indicates changes were made to the document.
- *
- * @param event Specification of changes applied to document.
- */
- @Override
- protected void onDocumentChanged(DocumentEvent event) {
- super.onDocumentChanged(event);
- mExportPropsPage.onModelChanged(event);
- }
-
- // ---- Local Methods ----
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/export/ExportFieldsPart.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/export/ExportFieldsPart.java
deleted file mode 100755
index eff3e4806..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/export/ExportFieldsPart.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.export;
-
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.Section;
-
-import java.util.HashMap;
-
-/**
- * Section part for editing the properties in an Export editor.
- */
-final class ExportFieldsPart extends AbstractPropertiesFieldsPart {
-
- public ExportFieldsPart(Composite body, FormToolkit toolkit, ExportEditor editor) {
- super(body, toolkit, editor);
- Section section = getSection();
-
- section.setText("Export Properties");
- section.setDescription("Properties of export.properties:");
-
- Composite table = createTableLayout(toolkit, 2 /* numColumns */);
-
- createLabel(table, toolkit,
- "Available Properties", //label
- "List of properties you can edit in export.properties"); //tooltip
-
- Text packageField = createLabelAndText(table, toolkit,
- "Package", //label,
- "", //$NON-NLS-1$ value,
- "TODO tooltip for Package"); //tooltip
-
- Text projectsField = createLabelAndText(table, toolkit,
- "Projects", //label,
- "", //$NON-NLS-1$ value,
- "TODO tooltip for Projects"); //tooltip
-
- Text versionCodeField = createLabelAndText(table, toolkit,
- "Version Code", //label,
- "", //$NON-NLS-1$ value,
- "TODO tooltip for Version Code"); //tooltip
-
- Text keyStoreField = createLabelAndText(table, toolkit,
- "Key Store", //label,
- "", //$NON-NLS-1$ value,
- "TODO tooltip for Key Store"); //tooltip
-
- Text keyAliasField = createLabelAndText(table, toolkit,
- "Key Alias", //label,
- "", //$NON-NLS-1$ value,
- "TODO tooltip for Key Alias"); //tooltip
-
- // Associate each field with the keyword in the properties files.
- // TODO there's probably some constant to reuse here.
- HashMap<String, Control> map = getNameToField();
- map.put("package", packageField); //$NON-NLS-1$
- map.put("projects", projectsField); //$NON-NLS-1$
- map.put("versionCode", versionCodeField); //$NON-NLS-1$
- map.put("_key.store", keyStoreField); //$NON-NLS-1$
- map.put("_key.alias", keyAliasField); //$NON-NLS-1$
-
- addModifyListenerToFields();
- }
-
- @Override
- protected void setFieldModifyListener(Control field, ModifyListener markDirtyListener) {
- super.setFieldModifyListener(field, markDirtyListener);
- // TODO override for custom controls
- }
-
- @Override
- protected String getFieldText(Control field) {
- // TODO override for custom controls
- return super.getFieldText(field);
- }
-
- @Override
- protected void setFieldText(Control field, String value) {
- // TODO override for custom controls
- super.setFieldText(field, value);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/export/ExportLinksPart.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/export/ExportLinksPart.java
deleted file mode 100644
index 85a2165cc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/export/ExportLinksPart.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.export;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.ui.SectionHelper.ManifestSectionPart;
-
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.MessageBox;
-import org.eclipse.ui.forms.events.HyperlinkEvent;
-import org.eclipse.ui.forms.events.IHyperlinkListener;
-import org.eclipse.ui.forms.widgets.FormText;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.Section;
-
-/**
- * Links section part for export properties page.
- * Displays some help and some links/actions for the user to use.
- */
-final class ExportLinksPart extends ManifestSectionPart {
-
- private FormText mFormText;
-
- public ExportLinksPart(Composite body, FormToolkit toolkit, ExportEditor editor) {
- super(body, toolkit, Section.TWISTIE | Section.EXPANDED, true /* description */);
- Section section = getSection();
- section.setText("Links");
- section.setDescription("TODO SOME TEXT HERE. You can also edit the XML directly.");
-
- final Composite table = createTableLayout(toolkit, 2 /* numColumns */);
-
- StringBuffer buf = new StringBuffer();
- buf.append("<form>"); //$NON-NLS-1$
-
- buf.append("<li style=\"image\" value=\"android_img\"><a href=\"action_dosomething\">");
- buf.append("TODO Custom Action");
- buf.append("</a>"); //$NON-NLS-1$
- buf.append(": blah blah do something (like build/export).");
- buf.append("</li>"); //$NON-NLS-1$
-
- buf.append(String.format("<li style=\"image\" value=\"android_img\"><a href=\"page:%1$s\">", //$NON-NLS-1$
- ExportEditor.TEXT_EDITOR_ID));
- buf.append("XML Source");
- buf.append("</a>"); //$NON-NLS-1$
- buf.append(": Directly edit the AndroidManifest.xml file.");
- buf.append("</li>"); //$NON-NLS-1$
-
- buf.append("<li style=\"image\" value=\"android_img\">"); //$NON-NLS-1$
- buf.append("<a href=\"http://code.google.com/android/devel/bblocks-manifest.html\">Documentation</a>: Documentation from the Android SDK for AndroidManifest.xml."); //$NON-NLS-1$
- buf.append("</li>"); //$NON-NLS-1$
- buf.append("</form>"); //$NON-NLS-1$
-
- mFormText = createFormText(table, toolkit, true, buf.toString(),
- false /* setupLayoutData */);
-
- Image androidLogo = AdtPlugin.getAndroidLogo();
- mFormText.setImage("android_img", androidLogo); //$NON-NLS-1$
-
- // Listener for default actions (page change, URL web browser)
- mFormText.addHyperlinkListener(editor.createHyperlinkListener());
-
- mFormText.addHyperlinkListener(new IHyperlinkListener() {
- @Override
- public void linkExited(HyperlinkEvent e) {
- // pass
- }
-
- @Override
- public void linkEntered(HyperlinkEvent e) {
- // pass
- }
-
- @Override
- public void linkActivated(HyperlinkEvent e) {
- String link = e.data.toString();
- if ("action_dosomething".equals(link)) {
- MessageBox mb = new MessageBox(table.getShell(), SWT.OK);
- mb.setText("Custom Action Invoked");
- mb.open();
- }
- }
- });
- }
-
- /**
- * Called after all pages have been created, to let the parts initialize their
- * content based on the document's model.
- * <p/>
- * The model should be acceded via the {@link ExportEditor}.
- *
- * @param editor The {@link ExportEditor} instance.
- */
- public void onModelInit(ExportEditor editor) {
- // pass
- }
-
- /**
- * Called after the document model has been changed. The model should be acceded via
- * the {@link ExportEditor} (e.g. getDocument, wrapRewriteSession)
- *
- * @param editor The {@link ExportEditor} instance.
- * @param event Specification of changes applied to document.
- */
- public void onModelChanged(ExportEditor editor, DocumentEvent event) {
- // pass
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/export/ExportPropertiesPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/export/ExportPropertiesPage.java
deleted file mode 100755
index f3db5eea6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/export/ExportPropertiesPage.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.export;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import org.eclipse.jface.text.DocumentEvent;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.ColumnLayout;
-import org.eclipse.ui.forms.widgets.ColumnLayoutData;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-
-
-/**
- * Page for export properties, used by {@link ExportEditor}.
- * It displays a part to edit the properties and another part
- * to provide some links and actions.
- */
-public final class ExportPropertiesPage extends FormPage {
-
- /** Page id used for switching tabs programmatically */
- final static String PAGE_ID = "export_prop_page"; //$NON-NLS-1$
-
- /** Container editor */
- ExportEditor mEditor;
- /** Export fields part */
- private ExportFieldsPart mFieldsPart;
- /** Export links part */
- private ExportLinksPart mLinksPart;
-
- public ExportPropertiesPage(ExportEditor editor) {
- super(editor, PAGE_ID, "Export Properties"); // tab's label, user visible, keep it short
- mEditor = editor;
- }
-
- /**
- * Creates the content in the form hosted in this page.
- *
- * @param managedForm the form hosted in this page.
- */
- @Override
- protected void createFormContent(IManagedForm managedForm) {
- super.createFormContent(managedForm);
- ScrolledForm form = managedForm.getForm();
- form.setText("Android Export Properties");
- form.setImage(AdtPlugin.getAndroidLogo());
-
- Composite body = form.getBody();
- FormToolkit toolkit = managedForm.getToolkit();
-
- body.setLayout(new ColumnLayout());
-
- mFieldsPart = new ExportFieldsPart(body, toolkit, mEditor);
- mFieldsPart.getSection().setLayoutData(new ColumnLayoutData());
- managedForm.addPart(mFieldsPart);
-
- mLinksPart = new ExportLinksPart(body, toolkit, mEditor);
- mLinksPart.getSection().setLayoutData(new ColumnLayoutData());
- managedForm.addPart(mLinksPart);
-
- mFieldsPart.onModelInit(mEditor);
- mLinksPart.onModelInit(mEditor);
- }
-
- /**
- * Called after all pages have been created, to let the parts initialize their
- * content based on the document's model.
- * <p/>
- * The model should be acceded via the {@link ExportEditor}.
- */
- public void onModelInit() {
- if (mFieldsPart != null) {
- mFieldsPart.onModelInit(mEditor);
- }
-
- if (mLinksPart != null) {
- mLinksPart.onModelInit(mEditor);
- }
- }
-
- /**
- * Called after the document model has been changed. The model should be acceded via
- * the {@link ExportEditor}.
- *
- * @param event Specification of changes applied to document.
- */
- public void onModelChanged(DocumentEvent event) {
- if (mFieldsPart != null) {
- mFieldsPart.onModelChanged(mEditor, event);
- }
-
- if (mLinksPart != null) {
- mLinksPart.onModelChanged(mEditor, event);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/formatting/AndroidXmlFormatter.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/formatting/AndroidXmlFormatter.java
deleted file mode 100644
index 403095450..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/formatting/AndroidXmlFormatter.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.formatting;
-
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.TypedPosition;
-import org.eclipse.jface.text.formatter.FormattingContext;
-import org.eclipse.jface.text.formatter.FormattingContextProperties;
-import org.eclipse.jface.text.formatter.IContentFormatter;
-import org.eclipse.jface.text.formatter.IContentFormatterExtension;
-import org.eclipse.jface.text.formatter.IFormattingContext;
-import org.eclipse.jface.text.formatter.IFormattingStrategy;
-import org.eclipse.wst.xml.core.text.IXMLPartitions;
-
-/**
- * Formatter which replaces the Eclipse formatter for the Android XML editors, and
- * delegates to it if the user has chosen to use the Eclipse formatter instead by turning
- * off {@link AdtPrefs#getUseCustomXmlFormatter()}
- */
-public class AndroidXmlFormatter implements IContentFormatter, IContentFormatterExtension {
- @Override
- public final void format(IDocument document, IRegion region) {
- /**
- * This method is probably not going to be called. It is part of the
- * {@link IContentFormatter} but since we also implement
- * {@link IContentFormatterExtension} Eclipse should /* be calling
- * {@link #format(IDocument,IFormattingContext)} instead. However, for
- * completeness (and because other implementations of {@link IContentFormatter}
- * also do this we might as well make the method behave correctly
- */
- FormattingContext context = new FormattingContext();
- context.setProperty(FormattingContextProperties.CONTEXT_DOCUMENT, Boolean.FALSE);
- context.setProperty(FormattingContextProperties.CONTEXT_REGION, region);
-
- format(document, context);
- }
-
- @Override
- public IFormattingStrategy getFormattingStrategy(String contentType) {
- return new AndroidXmlFormattingStrategy();
- }
-
- @Override
- public void format(IDocument document, IFormattingContext context) {
- context.setProperty(FormattingContextProperties.CONTEXT_MEDIUM, document);
- formatMaster(context, document, 0, document.getLength());
- }
-
- protected void formatMaster(IFormattingContext context, IDocument document, int offset,
- int length) {
- try {
- final int delta= offset - document.getLineInformationOfOffset(offset).getOffset();
- offset -= delta;
- length += delta;
- } catch (BadLocationException exception) {
- // Do nothing
- }
-
- AndroidXmlFormattingStrategy strategy = new AndroidXmlFormattingStrategy();
- context.setProperty(FormattingContextProperties.CONTEXT_PARTITION,
- new TypedPosition(offset, length, IXMLPartitions.XML_DEFAULT));
- strategy.formatterStarts(context);
- strategy.format();
- strategy.formatterStops();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/formatting/AndroidXmlFormattingStrategy.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/formatting/AndroidXmlFormattingStrategy.java
deleted file mode 100644
index 4cab41962..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/formatting/AndroidXmlFormattingStrategy.java
+++ /dev/null
@@ -1,754 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.formatting;
-
-import static com.android.SdkConstants.ANDROID_MANIFEST_XML;
-import static com.android.ide.eclipse.adt.internal.editors.AndroidXmlAutoEditStrategy.findLineStart;
-import static com.android.ide.eclipse.adt.internal.editors.AndroidXmlAutoEditStrategy.findTextStart;
-import static com.android.ide.eclipse.adt.internal.editors.color.ColorDescriptors.SELECTOR_TAG;
-import static org.eclipse.jface.text.formatter.FormattingContextProperties.CONTEXT_MEDIUM;
-import static org.eclipse.jface.text.formatter.FormattingContextProperties.CONTEXT_PARTITION;
-import static org.eclipse.jface.text.formatter.FormattingContextProperties.CONTEXT_REGION;
-import static org.eclipse.wst.xml.core.internal.regions.DOMRegionContext.XML_EMPTY_TAG_CLOSE;
-import static org.eclipse.wst.xml.core.internal.regions.DOMRegionContext.XML_END_TAG_OPEN;
-import static org.eclipse.wst.xml.core.internal.regions.DOMRegionContext.XML_TAG_CLOSE;
-import static org.eclipse.wst.xml.core.internal.regions.DOMRegionContext.XML_TAG_OPEN;
-
-import com.android.SdkConstants;
-import com.android.annotations.VisibleForTesting;
-import com.android.ide.common.xml.XmlFormatPreferences;
-import com.android.ide.common.xml.XmlFormatStyle;
-import com.android.ide.common.xml.XmlPrettyPrinter;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.resources.ResourceType;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.text.TypedPosition;
-import org.eclipse.jface.text.formatter.ContextBasedFormattingStrategy;
-import org.eclipse.jface.text.formatter.IFormattingContext;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.wst.sse.core.StructuredModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode;
-import org.eclipse.wst.xml.ui.internal.XMLFormattingStrategy;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.w3c.dom.Text;
-
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.Map;
-import java.util.Queue;
-
-/**
- * Formatter which formats XML content according to the established Android coding
- * conventions. It performs the format by computing the smallest set of DOM nodes
- * overlapping the formatted region, then it pretty-prints that XML region
- * using the {@link EclipseXmlPrettyPrinter}, and then it replaces the affected region
- * by the pretty-printed region.
- * <p>
- * This strategy is also used for delegation. If the user has chosen to use the
- * standard Eclipse XML formatter, this strategy simply delegates to the
- * default XML formatting strategy in WTP.
- */
-@SuppressWarnings("restriction")
-public class AndroidXmlFormattingStrategy extends ContextBasedFormattingStrategy {
- private IRegion mRegion;
- private final Queue<IDocument> mDocuments = new LinkedList<IDocument>();
- private final LinkedList<TypedPosition> mPartitions = new LinkedList<TypedPosition>();
- private ContextBasedFormattingStrategy mDelegate = null;
- /** False if document is known not to be in an Android project, null until initialized */
- private Boolean mIsAndroid;
-
- /**
- * Creates a new {@link AndroidXmlFormattingStrategy}
- */
- public AndroidXmlFormattingStrategy() {
- }
-
- private ContextBasedFormattingStrategy getDelegate() {
- if (!AdtPrefs.getPrefs().getUseCustomXmlFormatter()
- || mIsAndroid != null && !mIsAndroid.booleanValue()) {
- if (mDelegate == null) {
- mDelegate = new XMLFormattingStrategy();
- }
-
- return mDelegate;
- }
-
- return null;
- }
-
- @Override
- public void format() {
- // Use Eclipse XML formatter instead?
- ContextBasedFormattingStrategy delegate = getDelegate();
- if (delegate != null) {
- delegate.format();
- return;
- }
-
- super.format();
-
- IDocument document = mDocuments.poll();
- TypedPosition partition = mPartitions.poll();
-
- if (document != null && partition != null && mRegion != null) {
- try {
- if (document instanceof IStructuredDocument) {
- IStructuredDocument structuredDocument = (IStructuredDocument) document;
- IModelManager modelManager = StructuredModelManager.getModelManager();
- IStructuredModel model = modelManager.getModelForEdit(structuredDocument);
- if (model != null) {
- try {
- TextEdit edit = format(model, mRegion.getOffset(),
- mRegion.getLength());
- if (edit != null) {
- try {
- model.aboutToChangeModel();
- edit.apply(document);
- }
- finally {
- model.changedModel();
- }
- }
- }
- finally {
- model.releaseFromEdit();
- }
- }
- }
- }
- catch (BadLocationException e) {
- AdtPlugin.log(e, "Formatting error");
- }
- }
- }
-
- /**
- * Creates a {@link TextEdit} for formatting the given model's XML in the text range
- * starting at offset start with the given length. Note that the exact formatting
- * offsets may be adjusted to format a complete element.
- *
- * @param model the model to be formatted
- * @param start the starting offset
- * @param length the length of the text range to be formatted
- * @return a {@link TextEdit} which edits the model into a formatted document
- */
- private static TextEdit format(IStructuredModel model, int start, int length) {
- int end = start + length;
-
- TextEdit edit = new MultiTextEdit();
- IStructuredDocument document = model.getStructuredDocument();
-
- Node startNode = null;
- Node endNode = null;
- Document domDocument = null;
-
- if (model instanceof IDOMModel) {
- IDOMModel domModel = (IDOMModel) model;
- domDocument = domModel.getDocument();
- } else {
- // This should not happen
- return edit;
- }
-
- IStructuredDocumentRegion startRegion = document.getRegionAtCharacterOffset(start);
- if (startRegion != null) {
- int startOffset = startRegion.getStartOffset();
- IndexedRegion currentIndexedRegion = model.getIndexedRegion(startOffset);
- if (currentIndexedRegion instanceof IDOMNode) {
- IDOMNode currentDOMNode = (IDOMNode) currentIndexedRegion;
- startNode = currentDOMNode;
- }
- }
-
- boolean isOpenTagOnly = false;
- int openTagEnd = -1;
-
- IStructuredDocumentRegion endRegion = document.getRegionAtCharacterOffset(end);
- if (endRegion != null) {
- int endOffset = Math.max(endRegion.getStartOffset(),
- endRegion.getEndOffset() - 1);
- IndexedRegion currentIndexedRegion = model.getIndexedRegion(endOffset);
-
- // If you place the caret right on the right edge of an element, such as this:
- // <foo name="value">|
- // then the DOM model will consider the region containing the caret to be
- // whatever nodes FOLLOWS the element, usually a text node.
- // Detect this case, and look into the previous range.
- if (currentIndexedRegion instanceof Text
- && currentIndexedRegion.getStartOffset() == end && end > 0) {
- end--;
- currentIndexedRegion = model.getIndexedRegion(end);
- endRegion = document.getRegionAtCharacterOffset(
- currentIndexedRegion.getStartOffset());
- }
-
- if (currentIndexedRegion instanceof IDOMNode) {
- IDOMNode currentDOMNode = (IDOMNode) currentIndexedRegion;
- endNode = currentDOMNode;
-
- // See if this range is fully within the opening tag
- if (endNode == startNode && endRegion == startRegion) {
- ITextRegion subRegion = endRegion.getRegionAtCharacterOffset(end);
- ITextRegionList regions = endRegion.getRegions();
- int index = regions.indexOf(subRegion);
- if (index != -1) {
- // Skip past initial occurrence of close tag if we place the caret
- // right on a >
- subRegion = regions.get(index);
- String type = subRegion.getType();
- if (type == XML_TAG_CLOSE || type == XML_EMPTY_TAG_CLOSE) {
- index--;
- }
- }
- for (; index >= 0; index--) {
- subRegion = regions.get(index);
- String type = subRegion.getType();
- if (type == XML_TAG_OPEN) {
- isOpenTagOnly = true;
- } else if (type == XML_EMPTY_TAG_CLOSE || type == XML_TAG_CLOSE
- || type == XML_END_TAG_OPEN) {
- break;
- }
- }
-
- int max = regions.size();
- for (index = Math.max(0, index); index < max; index++) {
- subRegion = regions.get(index);
- String type = subRegion.getType();
- if (type == XML_EMPTY_TAG_CLOSE || type == XML_TAG_CLOSE) {
- openTagEnd = subRegion.getEnd() + endRegion.getStartOffset();
- }
- }
-
- if (openTagEnd == -1) {
- isOpenTagOnly = false;
- }
- }
- }
- }
-
- String[] indentationLevels = null;
- Node root = null;
- int initialDepth = 0;
- int replaceStart;
- int replaceEnd;
- boolean endWithNewline = false;
- if (startNode == null || endNode == null) {
- // Process the entire document
- root = domDocument;
- // both document and documentElement should be <= 0
- initialDepth = -1;
- startNode = root;
- endNode = root;
- replaceStart = 0;
- replaceEnd = document.getLength();
- try {
- endWithNewline = replaceEnd > 0 && document.getChar(replaceEnd - 1) == '\n';
- } catch (BadLocationException e) {
- // Can't happen
- }
- } else {
- root = DomUtilities.getCommonAncestor(startNode, endNode);
- initialDepth = root != null ? DomUtilities.getDepth(root) - 1 : 0;
-
- // Regions must be non-null since the DOM nodes are non null, but Eclipse null
- // analysis doesn't realize it:
- assert startRegion != null && endRegion != null;
-
- replaceStart = ((IndexedRegion) startNode).getStartOffset();
- if (isOpenTagOnly) {
- replaceEnd = openTagEnd;
- } else {
- replaceEnd = ((IndexedRegion) endNode).getEndOffset();
- }
-
- // Look up the indentation level of the start node, if it is an element
- // and it starts on its own line
- if (startNode.getNodeType() == Node.ELEMENT_NODE) {
- // Measure the indentation of the start node such that we can indent
- // the reformatted version of the node exactly in place and it should blend
- // in if the surrounding content does not use the same indentation size etc.
- // However, it's possible for the start node to have deeper depth than other
- // content we're formatting, as in the following scenario for example:
- // <foo>
- // <bar/>
- // </foo>
- // <baz/>
- // If you select this text range, we want <foo> to be formatted at whatever
- // level it is, and we also need to know the indentation level to use
- // for </baz>. We don't measure the depth of <bar/>, a child of the start node,
- // since from the initial indentation level and on down we want to normalize
- // the output.
- IndentationMeasurer m = new IndentationMeasurer(startNode, endNode, document);
- indentationLevels = m.measure(initialDepth, root);
-
- // Wipe out any levels deeper than the start node's level
- // (which may not be the smallest level, e.g. where you select a child
- // and the end of its parent etc).
- // (Since we're ONLY measuring the node and its parents, you might wonder
- // why this is doing a full subtree traversal instead of just walking up
- // the parent chain and looking up the indentation for each. The reason for
- // this is that some of theses nodes, which have not yet been formatted,
- // may be sharing lines with other nodes, and we disregard indentation for
- // any nodes that don't start a line since the indentation may only be correct
- // for the first element, so therefore we look for other nodes at the same
- // level that do have indentation info at the front of the line.
- int depth = DomUtilities.getDepth(startNode) - 1;
- for (int i = depth + 1; i < indentationLevels.length; i++) {
- indentationLevels[i] = null;
- }
- }
- }
-
- XmlFormatStyle style = guessStyle(model, domDocument);
- XmlFormatPreferences prefs = EclipseXmlFormatPreferences.create();
- String delimiter = TextUtilities.getDefaultLineDelimiter(document);
- XmlPrettyPrinter printer = new EclipseXmlPrettyPrinter(prefs, style, delimiter);
- printer.setEndWithNewline(endWithNewline);
-
- if (indentationLevels != null) {
- printer.setIndentationLevels(indentationLevels);
- }
-
- StringBuilder sb = new StringBuilder(length);
- printer.prettyPrint(initialDepth, root, startNode, endNode, sb, isOpenTagOnly);
-
- String formatted = sb.toString();
- ReplaceEdit replaceEdit = createReplaceEdit(document, replaceStart, replaceEnd, formatted,
- prefs);
- if (replaceEdit != null) {
- edit.addChild(replaceEdit);
- }
-
- // Attempt to fix the selection range since otherwise, with the document shifting
- // under it, you end up selecting a "random" portion of text now shifted into the
- // old positions of the formatted text:
- if (replaceEdit != null && replaceStart != 0 && replaceEnd != document.getLength()) {
- ITextEditor editor = AdtUtils.getActiveTextEditor();
- if (editor != null) {
- editor.setHighlightRange(replaceEdit.getOffset(), replaceEdit.getText().length(),
- false /*moveCursor*/);
- }
- }
-
- return edit;
- }
-
- /**
- * Create a {@link ReplaceEdit} which replaces the text in the given document with the
- * given new formatted content. The replaceStart and replaceEnd parameters point to
- * the equivalent unformatted text in the document, but the actual edit range may be
- * adjusted (for example to make the edit smaller if the beginning and/or end is
- * identical, and so on)
- */
- @VisibleForTesting
- static ReplaceEdit createReplaceEdit(IDocument document, int replaceStart,
- int replaceEnd, String formatted, XmlFormatPreferences prefs) {
- // If replacing a node somewhere in the middle, start the replacement at the
- // beginning of the current line
- int index = replaceStart;
- try {
- while (index > 0) {
- char c = document.getChar(index - 1);
- if (c == '\n') {
- if (index < replaceStart) {
- replaceStart = index;
- }
- break;
- } else if (!Character.isWhitespace(c)) {
- // The replaced node does not start on its own line; in that case,
- // remove the initial indentation in the reformatted element
- for (int i = 0; i < formatted.length(); i++) {
- if (!Character.isWhitespace(formatted.charAt(i))) {
- formatted = formatted.substring(i);
- break;
- }
- }
- break;
- }
- index--;
- }
- } catch (BadLocationException e) {
- AdtPlugin.log(e, null);
- }
-
- // If there are multiple blank lines before the insert position, collapse them down
- // to one
- int prevNewlineIndex = -1;
- boolean beginsWithNewline = false;
- for (int i = 0, n = formatted.length(); i < n; i++) {
- char c = formatted.charAt(i);
- if (c == '\n') {
- beginsWithNewline = true;
- break;
- } else if (!Character.isWhitespace(c)) { // \r is whitespace so is handled correctly
- break;
- }
- }
- try {
- for (index = replaceStart - 1; index > 0; index--) {
- char c = document.getChar(index);
- if (c == '\n') {
- if (prevNewlineIndex != -1) {
- replaceStart = prevNewlineIndex;
- }
- prevNewlineIndex = index;
- if (index > 0 && document.getChar(index - 1) == '\r') {
- prevNewlineIndex--;
- }
- } else if (!Character.isWhitespace(c)) {
- break;
- }
- }
- } catch (BadLocationException e) {
- AdtPlugin.log(e, null);
- }
- if (prefs.removeEmptyLines && prevNewlineIndex != -1 && beginsWithNewline) {
- replaceStart = prevNewlineIndex + 1;
- }
-
- // Search forwards too
- int nextNewlineIndex = -1;
- try {
- int max = document.getLength();
- for (index = replaceEnd; index < max; index++) {
- char c = document.getChar(index);
- if (c == '\n') {
- if (nextNewlineIndex != -1) {
- replaceEnd = nextNewlineIndex + 1;
- }
- nextNewlineIndex = index;
- } else if (!Character.isWhitespace(c)) {
- break;
- }
- }
- } catch (BadLocationException e) {
- AdtPlugin.log(e, null);
- }
- boolean endsWithNewline = false;
- for (int i = formatted.length() - 1; i >= 0; i--) {
- char c = formatted.charAt(i);
- if (c == '\n') {
- endsWithNewline = true;
- break;
- } else if (!Character.isWhitespace(c)) {
- break;
- }
- }
-
- if (prefs.removeEmptyLines && nextNewlineIndex != -1 && endsWithNewline) {
- replaceEnd = nextNewlineIndex + 1;
- }
-
- // Figure out how much of the before and after strings are identical and narrow
- // the replacement scope
- boolean foundDifference = false;
- int firstDifference = 0;
- int lastDifference = formatted.length();
- try {
- for (int i = 0, j = replaceStart; i < formatted.length() && j < replaceEnd; i++, j++) {
- if (formatted.charAt(i) != document.getChar(j)) {
- firstDifference = i;
- foundDifference = true;
- break;
- }
- }
-
- if (!foundDifference) {
- // No differences - the document is already formatted, nothing to do
- return null;
- }
-
- lastDifference = firstDifference + 1;
- for (int i = formatted.length() - 1, j = replaceEnd - 1;
- i > firstDifference && j > replaceStart;
- i--, j--) {
- if (formatted.charAt(i) != document.getChar(j)) {
- lastDifference = i + 1;
- break;
- }
- }
- } catch (BadLocationException e) {
- AdtPlugin.log(e, null);
- }
-
- replaceStart += firstDifference;
- replaceEnd -= (formatted.length() - lastDifference);
- replaceEnd = Math.max(replaceStart, replaceEnd);
- formatted = formatted.substring(firstDifference, lastDifference);
-
- ReplaceEdit replaceEdit = new ReplaceEdit(replaceStart, replaceEnd - replaceStart,
- formatted);
- return replaceEdit;
- }
-
- /**
- * Guess what style to use to edit the given document - layout, resource, manifest, ... ? */
- static XmlFormatStyle guessStyle(IStructuredModel model, Document domDocument) {
- // The "layout" style is used for most XML resource file types:
- // layouts, color-lists and state-lists, animations, drawables, menus, etc
- XmlFormatStyle style = XmlFormatStyle.get(domDocument);
- if (style == XmlFormatStyle.FILE) {
- style = XmlFormatStyle.LAYOUT;
- }
-
- // The "resource" style is used for most value-based XML files:
- // strings, dimensions, booleans, colors, integers, plurals,
- // integer-arrays, string-arrays, and typed-arrays
- Element rootElement = domDocument.getDocumentElement();
- if (rootElement != null
- && SdkConstants.TAG_RESOURCES.equals(rootElement.getTagName())) {
- style = XmlFormatStyle.RESOURCE;
- }
-
- // Selectors are also used similar to resources
- if (rootElement != null && SELECTOR_TAG.equals(rootElement.getTagName())) {
- return XmlFormatStyle.RESOURCE;
- }
-
- // The "manifest" style is used for manifest files
- String baseLocation = model.getBaseLocation();
- if (baseLocation != null) {
- if (baseLocation.endsWith(SdkConstants.FN_ANDROID_MANIFEST_XML)) {
- style = XmlFormatStyle.MANIFEST;
- } else {
- int lastSlash = baseLocation.lastIndexOf('/');
- if (lastSlash != -1) {
- int end = baseLocation.lastIndexOf('/', lastSlash - 1); // -1 is okay
- String resourceFolder = baseLocation.substring(end + 1, lastSlash);
- String[] segments = resourceFolder.split("-"); //$NON-NLS-1$
- ResourceType type = ResourceType.getEnum(segments[0]);
- if (type != null) {
- // <resources> files found in res/xml/ should be formatted as
- // resource files!
- if (type == ResourceType.XML && style == XmlFormatStyle.RESOURCE) {
- return style;
- }
- style = EclipseXmlPrettyPrinter.get(type);
- }
- }
- }
- }
-
- return style;
- }
-
- private Boolean isAndroid(IDocument document) {
- if (mIsAndroid == null) {
- // Look up the corresponding IResource for this document. This isn't
- // readily available, so take advantage of the structured model's base location
- // string and convert it to an IResource to look up its project.
- if (document instanceof IStructuredDocument) {
- IStructuredDocument structuredDocument = (IStructuredDocument) document;
- IModelManager modelManager = StructuredModelManager.getModelManager();
-
- IStructuredModel model = modelManager.getModelForRead(structuredDocument);
- if (model != null) {
- String location = model.getBaseLocation();
- model.releaseFromRead();
- if (location != null) {
- if (!location.endsWith(ANDROID_MANIFEST_XML)
- && !location.contains("/res/")) { //$NON-NLS-1$
- // See if it looks like a foreign document
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IWorkspaceRoot root = workspace.getRoot();
- IResource member = root.findMember(location);
- if (member.exists()) {
- IProject project = member.getProject();
- if (project.isAccessible() &&
- !BaseProjectHelper.isAndroidProject(project)) {
- mIsAndroid = false;
- return false;
- }
- }
- }
- // Ignore Maven POM files even in Android projects
- if (location.endsWith("/pom.xml")) { //$NON-NLS-1$
- mIsAndroid = false;
- return false;
- }
- }
- }
- }
-
- mIsAndroid = true;
- }
-
- return mIsAndroid.booleanValue();
- }
-
- @Override
- public void formatterStarts(final IFormattingContext context) {
- // Use Eclipse XML formatter instead?
- ContextBasedFormattingStrategy delegate = getDelegate();
- if (delegate != null) {
- delegate.formatterStarts(context);
-
- // We also need the super implementation because it stores items into the
- // map, and we can't override the getPreferences method, so we need for
- // this delegating strategy to supply the correct values when it is called
- // instead of the delegate
- super.formatterStarts(context);
-
- return;
- }
-
- super.formatterStarts(context);
- mRegion = (IRegion) context.getProperty(CONTEXT_REGION);
- TypedPosition partition = (TypedPosition) context.getProperty(CONTEXT_PARTITION);
- IDocument document = (IDocument) context.getProperty(CONTEXT_MEDIUM);
- mPartitions.offer(partition);
- mDocuments.offer(document);
-
- if (!isAndroid(document)) {
- // It's some foreign type of project: use default
- // formatter
- delegate = getDelegate();
- if (delegate != null) {
- delegate.formatterStarts(context);
- }
- }
- }
-
- @Override
- public void formatterStops() {
- // Use Eclipse XML formatter instead?
- ContextBasedFormattingStrategy delegate = getDelegate();
- if (delegate != null) {
- delegate.formatterStops();
- // See formatterStarts for an explanation
- super.formatterStops();
-
- return;
- }
-
- super.formatterStops();
- mRegion = null;
- mDocuments.clear();
- mPartitions.clear();
- }
-
- /**
- * Utility class which can measure the indentation strings for various node levels in
- * a given node range
- */
- static class IndentationMeasurer {
- private final Map<Integer, String> mDepth = new HashMap<Integer, String>();
- private final Node mStartNode;
- private final Node mEndNode;
- private final IStructuredDocument mDocument;
- private boolean mDone = false;
- private boolean mInRange = false;
- private int mMaxDepth;
-
- public IndentationMeasurer(Node mStartNode, Node mEndNode, IStructuredDocument document) {
- super();
- this.mStartNode = mStartNode;
- this.mEndNode = mEndNode;
- mDocument = document;
- }
-
- /**
- * Measure the various depths found in the range (defined in the constructor)
- * under the given node which should be a common ancestor of the start and end
- * nodes. The result is a string array where each index corresponds to a depth,
- * and the string is either empty, or the complete indentation string to be used
- * to indent to the given depth (note that these strings are not cumulative)
- *
- * @param initialDepth the initial depth to use when visiting
- * @param root the root node to look for depths under
- * @return a string array containing nulls or indentation strings
- */
- public String[] measure(int initialDepth, Node root) {
- visit(initialDepth, root);
- String[] indentationLevels = new String[mMaxDepth + 1];
- for (Map.Entry<Integer, String> entry : mDepth.entrySet()) {
- int depth = entry.getKey();
- String indentation = entry.getValue();
- indentationLevels[depth] = indentation;
- }
-
- return indentationLevels;
- }
-
- private void visit(int depth, Node node) {
- // Look up indentation for this level
- if (node.getNodeType() == Node.ELEMENT_NODE && mDepth.get(depth) == null) {
- // Look up the depth
- try {
- IndexedRegion region = (IndexedRegion) node;
- int lineStart = findLineStart(mDocument, region.getStartOffset());
- int textStart = findTextStart(mDocument, lineStart, region.getEndOffset());
-
- // Ensure that the text which begins the line is this element, otherwise
- // we could be measuring the indentation of a parent element which begins
- // the line
- if (textStart == region.getStartOffset()) {
- String indent = mDocument.get(lineStart,
- Math.max(0, textStart - lineStart));
- mDepth.put(depth, indent);
-
- if (depth > mMaxDepth) {
- mMaxDepth = depth;
- }
- }
- } catch (BadLocationException e) {
- AdtPlugin.log(e, null);
- }
- }
-
- NodeList children = node.getChildNodes();
- for (int i = 0, n = children.getLength(); i < n; i++) {
- Node child = children.item(i);
- visit(depth + 1, child);
- if (mDone) {
- return;
- }
- }
-
- if (node == mEndNode) {
- mDone = true;
- }
- }
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/formatting/EclipseXmlFormatPreferences.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/formatting/EclipseXmlFormatPreferences.java
deleted file mode 100644
index 6c00b8ee2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/formatting/EclipseXmlFormatPreferences.java
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.formatting;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.annotations.VisibleForTesting;
-import com.android.ide.common.xml.XmlFormatPreferences;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.common.xml.XmlAttributeSortOrder;
-
-import org.eclipse.core.runtime.Preferences;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.ui.internal.editors.text.EditorsPlugin;
-import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.xml.core.internal.XMLCorePlugin;
-import org.eclipse.wst.xml.core.internal.preferences.XMLCorePreferenceNames;
-import org.w3c.dom.Attr;
-
-import java.util.Comparator;
-
-/**
- * Formatting preferences used by the Android XML formatter.
- */
-public class EclipseXmlFormatPreferences extends XmlFormatPreferences {
- @VisibleForTesting
- protected EclipseXmlFormatPreferences() {
- }
-
- /**
- * Creates a new {@link EclipseXmlFormatPreferences} based on the current settings
- * in {@link AdtPrefs}
- *
- * @return an {@link EclipseXmlFormatPreferences} object
- */
- @NonNull
- public static EclipseXmlFormatPreferences create() {
- EclipseXmlFormatPreferences p = new EclipseXmlFormatPreferences();
- AdtPrefs prefs = AdtPrefs.getPrefs();
-
- p.useEclipseIndent = prefs.isUseEclipseIndent();
- p.removeEmptyLines = prefs.isRemoveEmptyLines();
- p.oneAttributeOnFirstLine = prefs.isOneAttributeOnFirstLine();
- p.sortAttributes = prefs.getAttributeSort();
- p.spaceBeforeClose = prefs.isSpaceBeforeClose();
-
- return p;
- }
-
- @Override
- @Nullable
- public Comparator<Attr> getAttributeComparator() {
- // Can't just skip sorting; the attribute table moves attributes out of order
- // due to hashing, so sort by node positions
- if (sortAttributes == XmlAttributeSortOrder.NO_SORTING) {
- return EXISTING_ORDER_COMPARATOR;
- }
- return sortAttributes.getAttributeComparator();
- }
-
- private static final Comparator<Attr> EXISTING_ORDER_COMPARATOR = new Comparator<Attr>() {
- @Override
- public int compare(Attr attr1, Attr attr2) {
- IndexedRegion region1 = (IndexedRegion) attr1;
- IndexedRegion region2 = (IndexedRegion) attr2;
-
- return region1.getStartOffset() - region2.getStartOffset();
- }
- };
-
- // The XML module settings do not have a public API. We should replace this with JDT
- // settings anyway since that's more likely what users have configured and want applied
- // to their XML files
-
- /**
- * Returns the string to use to indent one indentation level
- *
- * @return the string used to indent one indentation level
- */
- @Override
- @SuppressWarnings({
- "restriction", "deprecation"
- })
- public String getOneIndentUnit() {
- if (useEclipseIndent) {
- // Look up Eclipse indent preferences
- // TODO: Use the JDT preferences instead, which make more sense
- Preferences preferences = XMLCorePlugin.getDefault().getPluginPreferences();
- int indentationWidth = preferences.getInt(XMLCorePreferenceNames.INDENTATION_SIZE);
- String indentCharPref = preferences.getString(XMLCorePreferenceNames.INDENTATION_CHAR);
- boolean useSpaces = XMLCorePreferenceNames.SPACE.equals(indentCharPref);
-
- StringBuilder indentString = new StringBuilder();
- for (int j = 0; j < indentationWidth; j++) {
- if (useSpaces) {
- indentString.append(' ');
- } else {
- indentString.append('\t');
- }
- }
- mOneIndentUnit = indentString.toString();
- }
-
- return mOneIndentUnit;
- }
-
- /**
- * Returns the number of spaces used to display a single tab character
- *
- * @return the number of spaces used to display a single tab character
- */
- @Override
- @SuppressWarnings("restriction") // Editor settings
- public int getTabWidth() {
- if (mTabWidth == -1) {
- String key = AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH;
- try {
- IPreferenceStore prefs = EditorsPlugin.getDefault().getPreferenceStore();
- mTabWidth = prefs.getInt(key);
- } catch (Throwable t) {
- // Pass: We'll pick a suitable default instead below
- }
- if (mTabWidth <= 0) {
- mTabWidth = 4;
- }
- }
-
- return mTabWidth;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/formatting/EclipseXmlPrettyPrinter.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/formatting/EclipseXmlPrettyPrinter.java
deleted file mode 100644
index d3f7ec866..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/formatting/EclipseXmlPrettyPrinter.java
+++ /dev/null
@@ -1,249 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.formatting;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.xml.XmlFormatPreferences;
-import com.android.ide.common.xml.XmlFormatStyle;
-import com.android.ide.common.xml.XmlPrettyPrinter;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-import com.android.resources.ResourceFolderType;
-import com.android.resources.ResourceType;
-import com.android.utils.SdkUtils;
-import com.android.utils.XmlUtils;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMElement;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-/**
- * Eclipse customization of the {@link EclipseXmlPrettyPrinter} which takes advantage of the
- * Eclipse DOM Api to track additional information, such as whether an element with no children
- * was of the open form ({@code <foo></foo>}) or the closed form ({@code <foo/>}), the ability to
- * look up the original source (for proper entity handling), the ability to preserve attribute
- * source order, etc.
- */
-@SuppressWarnings("restriction") // WST XML API
-public class EclipseXmlPrettyPrinter extends XmlPrettyPrinter {
-
- /**
- * Creates a new {@link com.android.ide.common.xml.XmlPrettyPrinter}
- *
- * @param prefs the preferences to format with
- * @param style the style to format with
- * @param lineSeparator the line separator to use, such as "\n" (can be null, in which case the
- * system default is looked up via the line.separator property)
- */
- public EclipseXmlPrettyPrinter(
- XmlFormatPreferences prefs,
- XmlFormatStyle style,
- String lineSeparator) {
- super(prefs, style, lineSeparator == null ? getDefaultLineSeparator() : lineSeparator);
- }
-
- /**
- * Pretty-prints the given XML document, which must be well-formed. If it is not,
- * the original unformatted XML document is returned
- *
- * @param xml the XML content to format
- * @param prefs the preferences to format with
- * @param style the style to format with
- * @param lineSeparator the line separator to use, such as "\n" (can be null, in which
- * case the system default is looked up via the line.separator property)
- * @return the formatted document (or if a parsing error occurred, returns the
- * unformatted document)
- */
- @NonNull
- public static String prettyPrint(
- @NonNull String xml,
- @NonNull XmlFormatPreferences prefs,
- @NonNull XmlFormatStyle style,
- @Nullable String lineSeparator) {
- Document document = DomUtilities.parseStructuredDocument(xml);
- if (document != null) {
- EclipseXmlPrettyPrinter printer = new EclipseXmlPrettyPrinter(prefs, style,
- lineSeparator);
- if (xml.endsWith("\n")) { //$NON-NLS-1$
- printer.setEndWithNewline(true);
- }
-
- StringBuilder sb = new StringBuilder(3 * xml.length() / 2);
- printer.prettyPrint(-1, document, null, null, sb, false /*openTagOnly*/);
- return sb.toString();
- } else {
- // Parser error: just return the unformatted content
- return xml;
- }
- }
-
- @NonNull
- public static String prettyPrint(@NonNull Node node, boolean endWithNewline) {
- return prettyPrint(node, EclipseXmlFormatPreferences.create(), XmlFormatStyle.get(node),
- null, endWithNewline);
- }
-
- private static String getDefaultLineSeparator() {
- org.eclipse.jface.text.Document blank = new org.eclipse.jface.text.Document();
- String lineSeparator = TextUtilities.getDefaultLineDelimiter(blank);
- if (lineSeparator == null) {
- lineSeparator = SdkUtils.getLineSeparator();
- }
-
- return lineSeparator;
- }
-
- /**
- * Pretty prints the given node
- *
- * @param node the node, usually a document, to be printed
- * @param prefs the formatting preferences
- * @param style the formatting style to use
- * @param lineSeparator the line separator to use, or null to use the
- * default
- * @return a formatted string
- */
- @NonNull
- public static String prettyPrint(
- @NonNull Node node,
- @NonNull XmlFormatPreferences prefs,
- @NonNull XmlFormatStyle style,
- @Nullable String lineSeparator,
- boolean endWithNewline) {
- XmlPrettyPrinter printer = new EclipseXmlPrettyPrinter(prefs, style, lineSeparator);
- printer.setEndWithNewline(endWithNewline);
- StringBuilder sb = new StringBuilder(1000);
- printer.prettyPrint(-1, node, null, null, sb, false /*openTagOnly*/);
- String xml = sb.toString();
- if (node.getNodeType() == Node.DOCUMENT_NODE && !xml.startsWith("<?")) { //$NON-NLS-1$
- xml = XmlUtils.XML_PROLOG + xml;
- }
- return xml;
- }
-
- @Nullable
- @Override
- protected String getSource(@NonNull Node node) {
- // In Eclipse, org.w3c.dom.DocumentType.getTextContent() returns null
- if (node instanceof IDOMNode) {
- // Get the original source string. This will contain the actual entities
- // such as "&gt;" instead of ">" which it gets turned into for the DOM nodes.
- // By operating on source we can preserve the user's entities rather than
- // having &gt; for example always turned into >.
- IDOMNode textImpl = (IDOMNode) node;
- return textImpl.getSource();
- }
-
- return super.getSource(node);
- }
-
- @Override
- protected boolean isEmptyTag(Element element) {
- if (element instanceof IDOMElement) {
- IDOMElement elementImpl = (IDOMElement) element;
- if (elementImpl.isEmptyTag()) {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Returns the {@link XmlFormatStyle} to use for a resource of the given type
- *
- * @param resourceType the type of resource to be formatted
- * @return the suitable format style to use
- */
- public static XmlFormatStyle get(ResourceType resourceType) {
- switch (resourceType) {
- case ARRAY:
- case ATTR:
- case BOOL:
- case DECLARE_STYLEABLE:
- case DIMEN:
- case FRACTION:
- case ID:
- case INTEGER:
- case STRING:
- case PLURALS:
- case STYLE:
- case STYLEABLE:
- case COLOR:
- return XmlFormatStyle.RESOURCE;
-
- case LAYOUT:
- return XmlFormatStyle.LAYOUT;
-
- case DRAWABLE:
- case MENU:
- case ANIM:
- case ANIMATOR:
- case INTERPOLATOR:
- default:
- return XmlFormatStyle.FILE;
- }
- }
-
- /**
- * Returns the {@link XmlFormatStyle} to use for resource files in the given resource
- * folder
- *
- * @param folderType the type of folder containing the resource file
- * @return the suitable format style to use
- */
- public static XmlFormatStyle getForFolderType(ResourceFolderType folderType) {
- switch (folderType) {
- case LAYOUT:
- return XmlFormatStyle.LAYOUT;
- case COLOR:
- case VALUES:
- return XmlFormatStyle.RESOURCE;
- case ANIM:
- case ANIMATOR:
- case DRAWABLE:
- case INTERPOLATOR:
- case MENU:
- default:
- return XmlFormatStyle.FILE;
- }
- }
-
- /**
- * Returns the {@link XmlFormatStyle} to use for resource files of the given path.
- *
- * @param path the path to the resource file
- * @return the suitable format style to use
- */
- public static XmlFormatStyle getForFile(IPath path) {
- if (SdkConstants.FN_ANDROID_MANIFEST_XML.equals(path.lastSegment())) {
- return XmlFormatStyle.MANIFEST;
- }
-
- if (path.segmentCount() > 2) {
- String parentName = path.segment(path.segmentCount() - 2);
- ResourceFolderType folderType = ResourceFolderType.getFolderType(parentName);
- return getForFolderType(folderType);
- }
-
- return XmlFormatStyle.FILE;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/formatting/XmlFormatProcessor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/formatting/XmlFormatProcessor.java
deleted file mode 100644
index 3f833029d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/formatting/XmlFormatProcessor.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.formatting;
-
-import static org.eclipse.jface.text.formatter.FormattingContextProperties.CONTEXT_MEDIUM;
-import static org.eclipse.jface.text.formatter.FormattingContextProperties.CONTEXT_PARTITION;
-import static org.eclipse.jface.text.formatter.FormattingContextProperties.CONTEXT_REGION;
-
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-
-import org.eclipse.jface.text.TypedPosition;
-import org.eclipse.jface.text.formatter.FormattingContext;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.eclipse.wst.xml.core.internal.formatter.XMLFormatterFormatProcessor;
-import org.eclipse.wst.xml.core.text.IXMLPartitions;
-
-/**
- * Customized version of the builtin XML format processor which delegates to the
- * Android specific formatter such that applying format on IFiles work as
- * expected
- */
-@SuppressWarnings("restriction")
-public class XmlFormatProcessor extends XMLFormatterFormatProcessor {
- /** Constructs a new {@link XmlFormatProcessor} */
- public XmlFormatProcessor() {
- }
-
- @Override
- public void formatModel(IStructuredModel structuredModel, int start, int length) {
- if (!AdtPrefs.getPrefs().getUseCustomXmlFormatter()) {
- super.formatModel(structuredModel, start, length);
- return;
- }
-
- AndroidXmlFormatter formatter = new AndroidXmlFormatter();
- IStructuredDocument document = structuredModel.getStructuredDocument();
- FormattingContext context = new FormattingContext();
- context.setProperty(CONTEXT_MEDIUM, document);
- context.setProperty(CONTEXT_PARTITION, new TypedPosition(start, length,
- IXMLPartitions.XML_DEFAULT));
- context.setProperty(CONTEXT_REGION, new org.eclipse.jface.text.Region(start, length));
- formatter.formatMaster(context, document, start, length);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/formatting/XmlQuickAssistManager.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/formatting/XmlQuickAssistManager.java
deleted file mode 100644
index a979a8086..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/formatting/XmlQuickAssistManager.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.formatting;
-
-import com.android.ide.eclipse.adt.internal.build.AaptQuickFix;
-import com.android.ide.eclipse.adt.internal.editors.layout.refactoring.RefactoringAssistant;
-import com.android.ide.eclipse.adt.internal.lint.LintFixGenerator;
-
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext;
-import org.eclipse.jface.text.quickassist.IQuickAssistProcessor;
-import org.eclipse.jface.text.source.Annotation;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * This class implements Quick Assists for XML files. It does not perform any
- * quick assistance on its own, but it coordinates the various separate quick
- * assists available for XML such that the order is logical. This is necessary
- * because without it, the order of suggestions (when more than one assistant
- * provides suggestions) is not always optimal. There doesn't seem to be a way
- * from non-Java languages to set the sorting order (see
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=229983 ). So instead of
- * registering our multiple XML quick assistants via the plugin.xml file, we
- * register <b>just</b> this manager, which delegates to the various XML quick
- * assistants as appropriate.
- */
-public class XmlQuickAssistManager implements IQuickAssistProcessor {
- private final IQuickAssistProcessor[] mProcessors;
-
- /** Constructs a new {@link XmlQuickAssistManager} which orders the quick fixes */
- public XmlQuickAssistManager() {
- mProcessors = new IQuickAssistProcessor[] {
- new AaptQuickFix(),
- new LintFixGenerator(),
- new RefactoringAssistant()
- };
- }
-
- @Override
- public String getErrorMessage() {
- return null;
- }
-
- @Override
- public boolean canFix(Annotation annotation) {
- for (IQuickAssistProcessor processor : mProcessors) {
- if (processor.canFix(annotation)) {
- return true;
- }
- }
-
- return false;
- }
-
- @Override
- public boolean canAssist(IQuickAssistInvocationContext invocationContext) {
- for (IQuickAssistProcessor processor : mProcessors) {
- if (processor.canAssist(invocationContext)) {
- return true;
- }
- }
-
- return false;
- }
-
- @Override
- public ICompletionProposal[] computeQuickAssistProposals(
- IQuickAssistInvocationContext invocationContext) {
- List<ICompletionProposal> allProposals = null;
- for (IQuickAssistProcessor processor : mProcessors) {
- if (processor.canAssist(invocationContext)) {
- ICompletionProposal[] proposals =
- processor.computeQuickAssistProposals(invocationContext);
- if (proposals != null && proposals.length > 0) {
- if (allProposals == null) {
- allProposals = new ArrayList<ICompletionProposal>();
- }
- for (ICompletionProposal proposal : proposals) {
- allProposals.add(proposal);
- }
- }
- }
- }
-
- if (allProposals != null) {
- return allProposals.toArray(new ICompletionProposal[allProposals.size()]);
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/ActionBarHandler.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/ActionBarHandler.java
deleted file mode 100644
index 49585a3ef..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/ActionBarHandler.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.w3c.dom.Element;
-
-import com.android.ide.common.rendering.api.ActionBarCallback;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo.ActivityAttributes;
-import com.google.common.base.Splitter;
-import com.google.common.collect.Iterables;
-
-import static com.android.SdkConstants.TOOLS_URI;
-import static com.android.SdkConstants.VALUE_SPLIT_ACTION_BAR_WHEN_NARROW;
-
-public class ActionBarHandler extends ActionBarCallback {
-
- private final GraphicalEditorPart mEditor;
-
- ActionBarHandler(GraphicalEditorPart editor) {
- mEditor = editor;
- }
-
- @Override
- public List<String> getMenuIdNames() {
- String commaSeparatedMenus = getXmlAttribute(ATTR_MENU);
- List<String> menus = new ArrayList<String>();
- Iterables.addAll(menus, Splitter.on(',').trimResults().omitEmptyStrings()
- .split(commaSeparatedMenus));
- return menus;
- }
-
- @Override
- public boolean getSplitActionBarWhenNarrow() {
- ActivityAttributes attributes = getActivityAttributes();
- if (attributes != null) {
- return VALUE_SPLIT_ACTION_BAR_WHEN_NARROW.equals(attributes.getUiOptions());
- }
- return false;
- }
-
- @Override
- public int getNavigationMode() {
- String navMode = getXmlAttribute(ATTR_NAV_MODE);
- if (navMode.equalsIgnoreCase(VALUE_NAV_MODE_TABS)) {
- return NAVIGATION_MODE_TABS;
- }
- if (navMode.equalsIgnoreCase(VALUE_NAV_MODE_LIST)) {
- return NAVIGATION_MODE_LIST;
- }
- return NAVIGATION_MODE_STANDARD;
- }
-
- @Override
- public HomeButtonStyle getHomeButtonStyle() {
- ActivityAttributes attributes = getActivityAttributes();
- if (attributes != null && attributes.getParentActivity() != null) {
- return HomeButtonStyle.SHOW_HOME_AS_UP;
- }
- return HomeButtonStyle.NONE;
- }
-
- private ActivityAttributes getActivityAttributes() {
- ManifestInfo manifest = ManifestInfo.get(mEditor.getProject());
- String activity = mEditor.getConfigurationChooser().getConfiguration().getActivity();
- return manifest.getActivityAttributes(activity);
- }
-
- private String getXmlAttribute(String name) {
- Element element = mEditor.getModel().getUiRoot().getXmlDocument().getDocumentElement();
- String value = element.getAttributeNS(TOOLS_URI, name);
- if (value == null) {
- return "";
- }
- return value.trim();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/BasePullParser.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/BasePullParser.java
deleted file mode 100644
index 43fb1a5bd..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/BasePullParser.java
+++ /dev/null
@@ -1,244 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout;
-
-import com.android.ide.common.rendering.legacy.ILegacyPullParser;
-
-import org.xmlpull.v1.XmlPullParserException;
-
-import java.io.InputStream;
-import java.io.Reader;
-
-/**
- * Base implementation of an {@link ILegacyPullParser} for cases where the parser is not sitting
- * on top of an actual XML file.
- * <p/>It's designed to work on layout files, and will most likely not work on other resource
- * files.
- */
-public abstract class BasePullParser implements ILegacyPullParser {
-
- protected int mParsingState = START_DOCUMENT;
-
- public BasePullParser() {
- }
-
- // --- new methods to override ---
-
- public abstract void onNextFromStartDocument();
- public abstract void onNextFromStartTag();
- public abstract void onNextFromEndTag();
-
- // --- basic implementation of IXmlPullParser ---
-
- @Override
- public void setFeature(String name, boolean state) throws XmlPullParserException {
- if (FEATURE_PROCESS_NAMESPACES.equals(name) && state) {
- return;
- }
- if (FEATURE_REPORT_NAMESPACE_ATTRIBUTES.equals(name) && state) {
- return;
- }
- throw new XmlPullParserException("Unsupported feature: " + name);
- }
-
- @Override
- public boolean getFeature(String name) {
- if (FEATURE_PROCESS_NAMESPACES.equals(name)) {
- return true;
- }
- if (FEATURE_REPORT_NAMESPACE_ATTRIBUTES.equals(name)) {
- return true;
- }
- return false;
- }
-
- @Override
- public void setProperty(String name, Object value) throws XmlPullParserException {
- throw new XmlPullParserException("setProperty() not supported");
- }
-
- @Override
- public Object getProperty(String name) {
- return null;
- }
-
- @Override
- public void setInput(Reader in) throws XmlPullParserException {
- throw new XmlPullParserException("setInput() not supported");
- }
-
- @Override
- public void setInput(InputStream inputStream, String inputEncoding)
- throws XmlPullParserException {
- throw new XmlPullParserException("setInput() not supported");
- }
-
- @Override
- public void defineEntityReplacementText(String entityName, String replacementText)
- throws XmlPullParserException {
- throw new XmlPullParserException("defineEntityReplacementText() not supported");
- }
-
- @Override
- public String getNamespacePrefix(int pos) throws XmlPullParserException {
- throw new XmlPullParserException("getNamespacePrefix() not supported");
- }
-
- @Override
- public String getInputEncoding() {
- return null;
- }
-
- @Override
- public String getNamespace(String prefix) {
- throw new RuntimeException("getNamespace() not supported");
- }
-
- @Override
- public int getNamespaceCount(int depth) throws XmlPullParserException {
- throw new XmlPullParserException("getNamespaceCount() not supported");
- }
-
- @Override
- public String getNamespaceUri(int pos) throws XmlPullParserException {
- throw new XmlPullParserException("getNamespaceUri() not supported");
- }
-
- @Override
- public int getColumnNumber() {
- return -1;
- }
-
- @Override
- public int getLineNumber() {
- return -1;
- }
-
- @Override
- public String getAttributeType(int arg0) {
- return "CDATA";
- }
-
- @Override
- public int getEventType() {
- return mParsingState;
- }
-
- @Override
- public String getText() {
- return null;
- }
-
- @Override
- public char[] getTextCharacters(int[] arg0) {
- return null;
- }
-
- @Override
- public boolean isAttributeDefault(int arg0) {
- return false;
- }
-
- @Override
- public boolean isWhitespace() {
- return false;
- }
-
- @Override
- public int next() throws XmlPullParserException {
- switch (mParsingState) {
- case END_DOCUMENT:
- throw new XmlPullParserException("Nothing after the end");
- case START_DOCUMENT:
- onNextFromStartDocument();
- break;
- case START_TAG:
- onNextFromStartTag();
- break;
- case END_TAG:
- onNextFromEndTag();
- break;
- case TEXT:
- // not used
- break;
- case CDSECT:
- // not used
- break;
- case ENTITY_REF:
- // not used
- break;
- case IGNORABLE_WHITESPACE:
- // not used
- break;
- case PROCESSING_INSTRUCTION:
- // not used
- break;
- case COMMENT:
- // not used
- break;
- case DOCDECL:
- // not used
- break;
- }
-
- return mParsingState;
- }
-
- @Override
- public int nextTag() throws XmlPullParserException {
- int eventType = next();
- if (eventType != START_TAG && eventType != END_TAG) {
- throw new XmlPullParserException("expected start or end tag", this, null);
- }
- return eventType;
- }
-
- @Override
- public String nextText() throws XmlPullParserException {
- if (getEventType() != START_TAG) {
- throw new XmlPullParserException("parser must be on START_TAG to read next text", this,
- null);
- }
- int eventType = next();
- if (eventType == TEXT) {
- String result = getText();
- eventType = next();
- if (eventType != END_TAG) {
- throw new XmlPullParserException(
- "event TEXT it must be immediately followed by END_TAG", this, null);
- }
- return result;
- } else if (eventType == END_TAG) {
- return "";
- } else {
- throw new XmlPullParserException("parser must be on START_TAG or TEXT to read text",
- this, null);
- }
- }
-
- @Override
- public int nextToken() throws XmlPullParserException {
- return next();
- }
-
- @Override
- public void require(int type, String namespace, String name) throws XmlPullParserException {
- if (type != getEventType() || (namespace != null && !namespace.equals(getNamespace()))
- || (name != null && !name.equals(getName())))
- throw new XmlPullParserException("expected " + TYPES[type] + getPositionDescription());
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/ContextPullParser.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/ContextPullParser.java
deleted file mode 100644
index f30406520..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/ContextPullParser.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout;
-
-import static com.android.SdkConstants.ATTR_IGNORE;
-import static com.android.SdkConstants.ATTR_LAYOUT;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.EXPANDABLE_LIST_VIEW;
-import static com.android.SdkConstants.GRID_VIEW;
-import static com.android.SdkConstants.LIST_VIEW;
-import static com.android.SdkConstants.SPINNER;
-import static com.android.SdkConstants.TOOLS_URI;
-import static com.android.SdkConstants.VALUE_FILL_PARENT;
-import static com.android.SdkConstants.VALUE_MATCH_PARENT;
-import static com.android.SdkConstants.VIEW_FRAGMENT;
-import static com.android.SdkConstants.VIEW_INCLUDE;
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.LayoutMetadata.KEY_FRAGMENT_LAYOUT;
-
-import com.android.SdkConstants;
-import com.android.ide.common.rendering.api.ILayoutPullParser;
-import com.android.ide.common.rendering.api.IProjectCallback;
-import com.android.ide.common.res2.ValueXmlHelper;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.LayoutMetadata;
-import com.google.common.collect.Maps;
-
-import org.kxml2.io.KXmlParser;
-
-import java.io.File;
-import java.util.Map;
-
-/**
- * Modified {@link KXmlParser} that adds the methods of {@link ILayoutPullParser}, and
- * performs other layout-specific parser behavior like translating fragment tags into
- * include tags.
- * <p/>
- * It will return a given parser when queried for one through
- * {@link ILayoutPullParser#getParser(String)} for a given name.
- *
- */
-public class ContextPullParser extends KXmlParser implements ILayoutPullParser {
- private static final String COMMENT_PREFIX = "<!--"; //$NON-NLS-1$
- private static final String COMMENT_SUFFIX = "-->"; //$NON-NLS-1$
- /** The callback to request parsers from */
- private final IProjectCallback mProjectCallback;
- /** The {@link File} for the layout currently being parsed */
- private File mFile;
- /** The layout to be shown for the current {@code <fragment>} tag. Usually null. */
- private String mFragmentLayout = null;
-
- /**
- * Creates a new {@link ContextPullParser}
- *
- * @param projectCallback the associated callback
- * @param file the file to be parsed
- */
- public ContextPullParser(IProjectCallback projectCallback, File file) {
- super();
- mProjectCallback = projectCallback;
- mFile = file;
- }
-
- // --- Layout lib API methods
-
- @Override
- /**
- * this is deprecated but must still be implemented for older layout libraries.
- * @deprecated use {@link IProjectCallback#getParser(String)}.
- */
- @Deprecated
- public ILayoutPullParser getParser(String layoutName) {
- return mProjectCallback.getParser(layoutName);
- }
-
- @Override
- public Object getViewCookie() {
- String name = super.getName();
- if (name == null) {
- return null;
- }
-
- // Store tools attributes if this looks like a layout we'll need adapter view
- // bindings for in the ProjectCallback.
- if (LIST_VIEW.equals(name)
- || EXPANDABLE_LIST_VIEW.equals(name)
- || GRID_VIEW.equals(name)
- || SPINNER.equals(name)) {
- Map<String, String> map = null;
- int count = getAttributeCount();
- for (int i = 0; i < count; i++) {
- String namespace = getAttributeNamespace(i);
- if (namespace != null && namespace.equals(TOOLS_URI)) {
- String attribute = getAttributeName(i);
- if (attribute.equals(ATTR_IGNORE)) {
- continue;
- }
- if (map == null) {
- map = Maps.newHashMapWithExpectedSize(4);
- }
- map.put(attribute, getAttributeValue(i));
- }
- }
-
- return map;
- }
-
- return null;
- }
-
- // --- KXMLParser override
-
- @Override
- public String getName() {
- String name = super.getName();
-
- // At designtime, replace fragments with includes.
- if (name.equals(VIEW_FRAGMENT)) {
- mFragmentLayout = LayoutMetadata.getProperty(this, KEY_FRAGMENT_LAYOUT);
- if (mFragmentLayout != null) {
- return VIEW_INCLUDE;
- }
- } else {
- mFragmentLayout = null;
- }
-
-
- return name;
- }
-
- @Override
- public String getAttributeValue(String namespace, String localName) {
- if (ATTR_LAYOUT.equals(localName) && mFragmentLayout != null) {
- return mFragmentLayout;
- }
-
- String value = super.getAttributeValue(namespace, localName);
-
- // on the fly convert match_parent to fill_parent for compatibility with older
- // platforms.
- if (VALUE_MATCH_PARENT.equals(value) &&
- (ATTR_LAYOUT_WIDTH.equals(localName) ||
- ATTR_LAYOUT_HEIGHT.equals(localName)) &&
- SdkConstants.NS_RESOURCES.equals(namespace)) {
- return VALUE_FILL_PARENT;
- }
-
- // Handle unicode escapes etc
- value = ValueXmlHelper.unescapeResourceString(value, false, false);
-
- return value;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/ExplodedRenderingHelper.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/ExplodedRenderingHelper.java
deleted file mode 100644
index 25fa3e991..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/ExplodedRenderingHelper.java
+++ /dev/null
@@ -1,421 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.LayoutDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.sdklib.IAndroidTarget;
-
-import org.eclipse.core.resources.IProject;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
-/**
- * This class computes the new screen size in "exploded rendering" mode.
- * It goes through the whole layout tree and figures out how many embedded layouts will have
- * extra padding and compute how that will affect the screen size.
- *
- * TODO
- * - find a better class name :)
- * - move the logic for each layout to the layout rule classes?
- * - support custom classes (by querying JDT for its super class and reverting to its behavior)
- */
-public final class ExplodedRenderingHelper {
- /** value of the padding in pixel.
- * TODO: make a preference?
- */
- public final static int PADDING_VALUE = 10;
-
- private final int[] mPadding = new int[] { 0, 0 };
- private Set<String> mLayoutNames;
-
- /**
- * Computes the padding. access the result through {@link #getWidthPadding()} and
- * {@link #getHeightPadding()}.
- * @param root the root node (ie the top layout).
- * @param iProject the project to which the layout belong.
- */
- public ExplodedRenderingHelper(Node root, IProject iProject) {
- // get the layout descriptors to get the name of all the layout classes.
- IAndroidTarget target = Sdk.getCurrent().getTarget(iProject);
- AndroidTargetData data = Sdk.getCurrent().getTargetData(target);
- LayoutDescriptors descriptors = data.getLayoutDescriptors();
-
- mLayoutNames = new HashSet<String>();
- List<ViewElementDescriptor> layoutDescriptors = descriptors.getLayoutDescriptors();
- for (ViewElementDescriptor desc : layoutDescriptors) {
- mLayoutNames.add(desc.getXmlLocalName());
- }
-
- computePadding(root, mPadding);
- }
-
- /**
- * (Unit tests only)
- * Computes the padding. access the result through {@link #getWidthPadding()} and
- * {@link #getHeightPadding()}.
- * @param root the root node (ie the top layout).
- * @param layoutNames the list of layout classes
- */
- public ExplodedRenderingHelper(Node root, Set<String> layoutNames) {
- mLayoutNames = layoutNames;
-
- computePadding(root, mPadding);
- }
-
- /**
- * Returns the number of extra padding in the X axis. This doesn't return a number of pixel
- * or dip, but how many paddings are pushing the screen dimension out.
- */
- public int getWidthPadding() {
- return mPadding[0];
- }
-
- /**
- * Returns the number of extra padding in the Y axis. This doesn't return a number of pixel
- * or dip, but how many paddings are pushing the screen dimension out.
- */
- public int getHeightPadding() {
- return mPadding[1];
- }
-
- /**
- * Computes the number of padding for a given view, and fills the given array of int.
- * <p/>index 0 is X axis, index 1 is Y axis
- * @param view the view to compute
- * @param padding the result padding (index 0 is X axis, index 1 is Y axis)
- */
- private void computePadding(Node view, int[] padding) {
- String localName = view.getLocalName();
-
- // first compute for each children
- NodeList children = view.getChildNodes();
- int count = children.getLength();
- if (count > 0) {
- // compute the padding for all the children.
- Map<Node, int[]> childrenPadding = new HashMap<Node, int[]>(count);
- for (int i = 0 ; i < count ; i++) {
- Node child = children.item(i);
- short type = child.getNodeType();
- if (type == Node.ELEMENT_NODE) { // ignore TEXT/CDATA nodes.
- int[] p = new int[] { 0, 0 };
- childrenPadding.put(child, p);
- computePadding(child, p);
- }
- }
-
- // since the non ELEMENT_NODE children were filtered out, count must be updated.
- count = childrenPadding.size();
-
- // now combine/compare based on the parent.
- if (count == 1) {
- int[] p = childrenPadding.get(childrenPadding.keySet().iterator().next());
- padding[0] = p[0];
- padding[1] = p[1];
- } else {
- if ("LinearLayout".equals(localName)) { //$NON-NLS-1$
- String orientation = getAttribute(view, "orientation", null); //$NON-NLS-1$
-
- // default value is horizontal
- boolean horizontal = orientation == null ||
- "horizontal".equals("vertical"); //$NON-NLS-1$ //$NON-NLS-2$
- combineLinearLayout(childrenPadding.values(), padding, horizontal);
- } else if ("TableLayout".equals(localName)) { //$NON-NLS-1$
- combineLinearLayout(childrenPadding.values(), padding, false /*horizontal*/);
- } else if ("TableRow".equals(localName)) { //$NON-NLS-1$
- combineLinearLayout(childrenPadding.values(), padding, true /*true*/);
- // TODO: properly support Relative Layouts.
-// } else if ("RelativeLayout".equals(localName)) { //$NON-NLS-1$
-// combineRelativeLayout(childrenPadding, padding);
- } else {
- // unknown layout. For now, let's consider it's better to add the children
- // margins in both dimensions than not at all.
- for (int[] p : childrenPadding.values()) {
- padding[0] += p[0];
- padding[1] += p[1];
- }
- }
- }
- }
-
- // if the view itself is a layout, add its padding
- if (mLayoutNames.contains(localName)) {
- padding[0]++;
- padding[1]++;
- }
- }
-
- /**
- * Combines the padding of the children of a linear layout.
- * <p/>For this layout, the padding of the children are added in the direction of
- * the layout, while the max is taken for the other direction.
- * @param paddings the list of the padding for the children.
- * @param resultPadding the result padding array to fill.
- * @param horizontal whether this layout is horizontal (<code>true</code>) or vertical
- * (<code>false</code>)
- */
- private void combineLinearLayout(Collection<int[]> paddings, int[] resultPadding,
- boolean horizontal) {
- // The way the children are combined will depend on the direction.
- // For instance in a vertical layout, we add the y padding as they all add to the length
- // of the needed canvas, while we take the biggest x padding needed by the children
-
- // the axis in which we take the sum of the padding of the children
- int sumIndex = horizontal ? 0 : 1;
- // the axis in which we take the max of the padding of the children
- int maxIndex = horizontal ? 1 : 0;
-
- int max = -1;
- for (int[] p : paddings) {
- resultPadding[sumIndex] += p[sumIndex];
- if (max == -1 || max < p[maxIndex]) {
- max = p[maxIndex];
- }
- }
- resultPadding[maxIndex] = max;
- }
-
- /**
- * Combine the padding of children of a relative layout.
- * @param childrenPadding a map of the children. This is guaranteed that the node object
- * are of type ELEMENT_NODE
- * @param padding
- *
- * TODO: Not used yet. Still need (lots of) work.
- */
- private void combineRelativeLayout(Map<Node, int[]> childrenPadding, int[] padding) {
- /*
- * Combines the children of the layout.
- * The way this works: for each children, for each direction, look for all the chidrens
- * connected and compute the combined margin in that direction.
- *
- * There's a chance the returned value will be too much. this is due to the layout sometimes
- * dropping views which will not be dropped here. It's ok, as it's better to have too
- * much than not enough.
- * We could fix this by matching those UiElementNode with their bounds as returned
- * by the rendering (ie if bounds is 0/0 in h/w, then ignore the child)
- */
-
- // list of the UiElementNode
- Set<Node> nodeSet = childrenPadding.keySet();
- // map of Id -> node
- Map<String, Node> idNodeMap = computeIdNodeMap(nodeSet);
-
- for (Entry<Node, int[]> entry : childrenPadding.entrySet()) {
- Node node = entry.getKey();
-
- // first horizontal, to the left.
- int[] leftResult = getBiggestMarginInDirection(node, 0 /*horizontal*/,
- "layout_toRightOf", "layout_toLeftOf", //$NON-NLS-1$ //$NON-NLS-2$
- childrenPadding, nodeSet, idNodeMap,
- false /*includeThisPadding*/);
-
- // then to the right
- int[] rightResult = getBiggestMarginInDirection(node, 0 /*horizontal*/,
- "layout_toLeftOf", "layout_toRightOf", //$NON-NLS-1$ //$NON-NLS-2$
- childrenPadding, nodeSet, idNodeMap,
- false /*includeThisPadding*/);
-
- // compute total horizontal margins
- int[] thisPadding = childrenPadding.get(node);
- int combinedMargin =
- (thisPadding != null ? thisPadding[0] : 0) +
- (leftResult != null ? leftResult[0] : 0) +
- (rightResult != null ? rightResult[0] : 0);
- if (combinedMargin > padding[0]) {
- padding[0] = combinedMargin;
- }
-
- // first vertical, above.
- int[] topResult = getBiggestMarginInDirection(node, 1 /*horizontal*/,
- "layout_below", "layout_above", //$NON-NLS-1$ //$NON-NLS-2$
- childrenPadding, nodeSet, idNodeMap,
- false /*includeThisPadding*/);
-
- // then below
- int[] bottomResult = getBiggestMarginInDirection(node, 1 /*horizontal*/,
- "layout_above", "layout_below", //$NON-NLS-1$ //$NON-NLS-2$
- childrenPadding, nodeSet, idNodeMap,
- false /*includeThisPadding*/);
-
- // compute total horizontal margins
- combinedMargin =
- (thisPadding != null ? thisPadding[1] : 0) +
- (topResult != null ? topResult[1] : 0) +
- (bottomResult != null ? bottomResult[1] : 0);
- if (combinedMargin > padding[1]) {
- padding[1] = combinedMargin;
- }
- }
- }
-
- /**
- * Computes the biggest margin in a given direction.
- *
- * TODO: Not used yet. Still need (lots of) work.
- */
- private int[] getBiggestMarginInDirection(Node node, int resIndex, String relativeTo,
- String inverseRelation, Map<Node, int[]> childrenPadding,
- Set<Node> nodeSet, Map<String, Node> idNodeMap,
- boolean includeThisPadding) {
- NamedNodeMap attributes = node.getAttributes();
-
- String viewId = getAttribute(node, "id", attributes); //$NON-NLS-1$
-
- // first get the item this one is positioned relative to.
- String toLeftOfRef = getAttribute(node, relativeTo, attributes);
- Node toLeftOf = null;
- if (toLeftOfRef != null) {
- toLeftOf = idNodeMap.get(cleanUpIdReference(toLeftOfRef));
- }
-
- ArrayList<Node> list = null;
- if (viewId != null) {
- // now to the left for items being placed to the left of this one.
- list = getMatchingNode(nodeSet, cleanUpIdReference(viewId), inverseRelation);
- }
-
- // now process each children in the same direction.
- if (toLeftOf != null) {
- if (list == null) {
- list = new ArrayList<Node>();
- }
-
- if (list.indexOf(toLeftOf) == -1) {
- list.add(toLeftOf);
- }
- }
-
- int[] thisPadding = childrenPadding.get(node);
-
- if (list != null) {
- // since there's a combination to do, we'll return a new result object
- int[] result = null;
- for (Node nodeOnLeft : list) {
- int[] tempRes = getBiggestMarginInDirection(nodeOnLeft, resIndex, relativeTo,
- inverseRelation, childrenPadding, nodeSet, idNodeMap, true);
- if (tempRes != null && (result == null || result[resIndex] < tempRes[resIndex])) {
- result = tempRes;
- }
- }
-
- // return the combined padding
- if (includeThisPadding == false || thisPadding[resIndex] == 0) {
- // just return the one we got since this object adds no padding (or doesn't
- // need to be comibined)
- return result;
- } else if (result != null) { // if result is null, the main return below is used.
- // add the result we got with the padding from the current node
- int[] realRes = new int [2];
- realRes[resIndex] = thisPadding[resIndex] + result[resIndex];
- return realRes;
- }
- }
-
- // if we reach this, there were no other views to the left of this one, so just return
- // the view padding.
- return includeThisPadding ? thisPadding : null;
- }
-
- /**
- * Computes and returns a map of (id, node) for each node of a given {@link Set}.
- * <p/>
- * Nodes with no id are ignored and not put in the map.
- * @param nodes the nodes to fill the map with.
- * @return a newly allocated, non-null, map of (id, node)
- */
- private Map<String, Node> computeIdNodeMap(Set<Node> nodes) {
- Map<String, Node> map = new HashMap<String, Node>();
- for (Node node : nodes) {
- String viewId = getAttribute(node, "id", null); //$NON-NLS-1$
- if (viewId != null) {
- map.put(cleanUpIdReference(viewId), node);
- }
- }
- return map;
- }
-
- /**
- * Cleans up a reference to an ID to return the ID itself only.
- * @param reference the reference to "clean up".
- * @return the id string only.
- */
- private String cleanUpIdReference(String reference) {
- // format is @id/foo or @+id/foo or @android:id/foo, or something similar.
- int slash = reference.indexOf('/');
- return reference.substring(slash);
- }
-
- /**
- * Returns a list of nodes for which a given attribute contains a reference to a given ID.
- *
- * @param nodes the list of nodes to search through
- * @param resId the requested ID
- * @param attribute the name of the attribute to test.
- * @return a newly allocated, non-null, list of nodes. Could be empty.
- */
- private ArrayList<Node> getMatchingNode(Set<Node> nodes, String resId,
- String attribute) {
- ArrayList<Node> list = new ArrayList<Node>();
-
- for (Node node : nodes) {
- String value = getAttribute(node, attribute, null);
- if (value != null) {
- value = cleanUpIdReference(value);
- if (value.equals(resId)) {
- list.add(node);
- }
- }
- }
-
- return list;
- }
-
- /**
- * Returns an attribute for a given node.
- * @param node the node to query
- * @param name the name of an attribute
- * @param attributes the option {@link NamedNodeMap} object to use to read the attributes from.
- */
- private static String getAttribute(Node node, String name, NamedNodeMap attributes) {
- if (attributes == null) {
- attributes = node.getAttributes();
- }
-
- if (attributes != null) {
- Node attribute = attributes.getNamedItemNS(SdkConstants.NS_RESOURCES, name);
- if (attribute != null) {
- return attribute.getNodeValue();
- }
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/LayoutContentAssist.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/LayoutContentAssist.java
deleted file mode 100644
index 99549ab89..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/LayoutContentAssist.java
+++ /dev/null
@@ -1,234 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout;
-
-import static com.android.SdkConstants.ANDROID_PKG_PREFIX;
-import static com.android.SdkConstants.ATTR_CLASS;
-import static com.android.SdkConstants.ATTR_CONTEXT;
-import static com.android.SdkConstants.ATTR_NAME;
-import static com.android.SdkConstants.CLASS_ACTIVITY;
-import static com.android.SdkConstants.CLASS_FRAGMENT;
-import static com.android.SdkConstants.CLASS_V4_FRAGMENT;
-import static com.android.SdkConstants.CLASS_VIEW;
-import static com.android.SdkConstants.VIEW_FRAGMENT;
-import static com.android.SdkConstants.VIEW_TAG;
-
-import com.android.annotations.Nullable;
-import com.android.annotations.VisibleForTesting;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.AndroidContentAssist;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.CustomViewDescriptorService;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.CustomViewFinder;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.google.common.collect.Lists;
-import com.google.common.collect.ObjectArrays;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.core.ITypeHierarchy;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.w3c.dom.Node;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * Content Assist Processor for /res/layout XML files
- */
-@VisibleForTesting
-public final class LayoutContentAssist extends AndroidContentAssist {
-
- /**
- * Constructor for LayoutContentAssist
- */
- public LayoutContentAssist() {
- super(AndroidTargetData.DESCRIPTOR_LAYOUT);
- }
-
- @Override
- protected Object[] getChoicesForElement(String parent, Node currentNode) {
- Object[] choices = super.getChoicesForElement(parent, currentNode);
- if (choices == null) {
- if (currentNode.getParentNode().getNodeType() == Node.ELEMENT_NODE) {
- String parentName = currentNode.getParentNode().getNodeName();
- if (parentName.indexOf('.') != -1) {
- // Custom view with unknown children; just use the root descriptor
- // to get all eligible views instead
- ElementDescriptor[] children = getRootDescriptor().getChildren();
- for (ElementDescriptor e : children) {
- if (e.getXmlName().startsWith(parent)) {
- return sort(children);
- }
- }
- }
- }
- }
-
- if (choices == null && parent.length() >= 1 && Character.isLowerCase(parent.charAt(0))) {
- // Custom view prefix?
- List<ElementDescriptor> descriptors = getCustomViews();
- if (descriptors != null && !descriptors.isEmpty()) {
- List<ElementDescriptor> matches = Lists.newArrayList();
- for (ElementDescriptor descriptor : descriptors) {
- if (descriptor.getXmlLocalName().startsWith(parent)) {
- matches.add(descriptor);
- }
- }
- if (!matches.isEmpty()) {
- return matches.toArray(new ElementDescriptor[matches.size()]);
- }
- }
- }
-
- return choices;
- }
-
- @Override
- protected ElementDescriptor[] getElementChoicesForTextNode(Node parentNode) {
- ElementDescriptor[] choices = super.getElementChoicesForTextNode(parentNode);
-
- // Add in custom views, if any
- List<ElementDescriptor> descriptors = getCustomViews();
- if (descriptors != null && !descriptors.isEmpty()) {
- ElementDescriptor[] array = descriptors.toArray(
- new ElementDescriptor[descriptors.size()]);
- choices = ObjectArrays.concat(choices, array, ElementDescriptor.class);
- choices = sort(choices);
- }
-
- return choices;
- }
-
- @Nullable
- private List<ElementDescriptor> getCustomViews() {
- // Add in custom views, if any
- IProject project = mEditor.getProject();
- CustomViewFinder finder = CustomViewFinder.get(project);
- Collection<String> views = finder.getAllViews();
- if (views == null) {
- finder.refresh();
- views = finder.getAllViews();
- }
- if (views != null && !views.isEmpty()) {
- List<ElementDescriptor> descriptors = Lists.newArrayListWithExpectedSize(views.size());
- CustomViewDescriptorService customViews = CustomViewDescriptorService.getInstance();
- for (String fqcn : views) {
- ViewElementDescriptor descriptor = customViews.getDescriptor(project, fqcn);
- if (descriptor != null) {
- descriptors.add(descriptor);
- }
- }
-
- return descriptors;
- }
-
- return null;
- }
-
- @Override
- protected boolean computeAttributeValues(List<ICompletionProposal> proposals, int offset,
- String parentTagName, String attributeName, Node node, String wordPrefix,
- boolean skipEndTag, int replaceLength) {
- super.computeAttributeValues(proposals, offset, parentTagName, attributeName, node,
- wordPrefix, skipEndTag, replaceLength);
-
- boolean projectOnly = false;
- List<String> superClasses = null;
- if (VIEW_FRAGMENT.equals(parentTagName) && (attributeName.endsWith(ATTR_NAME)
- || attributeName.equals(ATTR_CLASS))) {
- // Insert fragment class matches
- superClasses = Arrays.asList(CLASS_V4_FRAGMENT, CLASS_FRAGMENT);
- } else if (VIEW_TAG.equals(parentTagName) && attributeName.endsWith(ATTR_CLASS)) {
- // Insert custom view matches
- superClasses = Collections.singletonList(CLASS_VIEW);
- projectOnly = true;
- } else if (attributeName.endsWith(ATTR_CONTEXT)) {
- // Insert activity matches
- superClasses = Collections.singletonList(CLASS_ACTIVITY);
- }
-
- if (superClasses != null) {
- IProject project = mEditor.getProject();
- if (project == null) {
- return false;
- }
- try {
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
- IType type = javaProject.findType(superClasses.get(0));
- Set<IType> elements = new HashSet<IType>();
- if (type != null) {
- ITypeHierarchy hierarchy = type.newTypeHierarchy(new NullProgressMonitor());
- IType[] allSubtypes = hierarchy.getAllSubtypes(type);
- for (IType subType : allSubtypes) {
- if (!projectOnly || subType.getResource() != null) {
- elements.add(subType);
- }
- }
- }
- assert superClasses.size() <= 2; // If more, need to do additional work below
- if (superClasses.size() == 2) {
- type = javaProject.findType(superClasses.get(1));
- if (type != null) {
- ITypeHierarchy hierarchy = type.newTypeHierarchy(
- new NullProgressMonitor());
- IType[] allSubtypes = hierarchy.getAllSubtypes(type);
- for (IType subType : allSubtypes) {
- if (!projectOnly || subType.getResource() != null) {
- elements.add(subType);
- }
- }
- }
- }
-
- List<IType> sorted = new ArrayList<IType>(elements);
- Collections.sort(sorted, new Comparator<IType>() {
- @Override
- public int compare(IType type1, IType type2) {
- String fqcn1 = type1.getFullyQualifiedName();
- String fqcn2 = type2.getFullyQualifiedName();
- int category1 = fqcn1.startsWith(ANDROID_PKG_PREFIX) ? 1 : -1;
- int category2 = fqcn2.startsWith(ANDROID_PKG_PREFIX) ? 1 : -1;
- if (category1 != category2) {
- return category1 - category2;
- }
- return fqcn1.compareTo(fqcn2);
- }
- });
- addMatchingProposals(proposals, sorted.toArray(), offset, node, wordPrefix,
- (char) 0, false /* isAttribute */, false /* isNew */,
- false /* skipEndTag */, replaceLength);
- return true;
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- }
-
- return false;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/LayoutEditorDelegate.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/LayoutEditorDelegate.java
deleted file mode 100644
index 1015d7d86..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/LayoutEditorDelegate.java
+++ /dev/null
@@ -1,1001 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.annotations.VisibleForTesting;
-import com.android.annotations.VisibleForTesting.Visibility;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.XmlEditorMultiOutline;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlDelegate;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DocumentDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.IUnknownDescriptorProvider;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.CustomViewDescriptorService;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.LayoutDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.LayoutActionBar;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.LayoutCanvas;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.OutlinePage;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.SelectionManager;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.RulesEngine;
-import com.android.ide.eclipse.adt.internal.editors.layout.properties.PropertySheetPage;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiDocumentNode;
-import com.android.ide.eclipse.adt.internal.lint.EclipseLintClient;
-import com.android.ide.eclipse.adt.internal.lint.EclipseLintRunner;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.resources.ResourceFolderType;
-import com.android.sdklib.IAndroidTarget;
-import com.android.tools.lint.client.api.IssueRegistry;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.jobs.IJobChangeEvent;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.core.runtime.jobs.JobChangeAdapter;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.ISelectionListener;
-import org.eclipse.ui.ISelectionService;
-import org.eclipse.ui.IShowEditorInput;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.forms.editor.IFormPage;
-import org.eclipse.ui.part.FileEditorInput;
-import org.eclipse.ui.views.contentoutline.IContentOutlinePage;
-import org.eclipse.ui.views.properties.IPropertySheetPage;
-import org.eclipse.wst.sse.ui.StructuredTextEditor;
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-
-import java.io.File;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * Multi-page form editor for /res/layout XML files.
- */
-public class LayoutEditorDelegate extends CommonXmlDelegate
- implements IShowEditorInput, CommonXmlDelegate.IActionContributorDelegate {
-
- /** The prefix for layout folders that are not the default layout folder */
- private static final String LAYOUT_FOLDER_PREFIX = "layout-"; //$NON-NLS-1$
-
- public static class Creator implements IDelegateCreator {
- @Override
- @SuppressWarnings("unchecked")
- public LayoutEditorDelegate createForFile(
- @NonNull CommonXmlEditor delegator,
- @Nullable ResourceFolderType type) {
- if (ResourceFolderType.LAYOUT == type) {
- return new LayoutEditorDelegate(delegator);
- }
-
- return null;
- }
- }
-
- /**
- * Old standalone-editor ID.
- * Use {@link CommonXmlEditor#ID} instead.
- */
- public static final String LEGACY_EDITOR_ID =
- AdtConstants.EDITORS_NAMESPACE + ".layout.LayoutEditor"; //$NON-NLS-1$
-
- /** Root node of the UI element hierarchy */
- private UiDocumentNode mUiDocRootNode;
-
- private GraphicalEditorPart mGraphicalEditor;
- private int mGraphicalEditorIndex;
-
- /** Implementation of the {@link IContentOutlinePage} for this editor */
- private OutlinePage mLayoutOutline;
-
- /** The XML editor outline */
- private IContentOutlinePage mEditorOutline;
-
- /** Multiplexing outline, used for multi-page editors that have their own outline */
- private XmlEditorMultiOutline mMultiOutline;
-
- /**
- * Temporary flag set by the editor caret listener which is used to cause
- * the next getAdapter(IContentOutlinePage.class) call to return the editor
- * outline rather than the multi-outline. See the {@link #delegateGetAdapter}
- * method for details.
- */
- private boolean mCheckOutlineAdapter;
-
- /** Custom implementation of {@link IPropertySheetPage} for this editor */
- private IPropertySheetPage mPropertyPage;
-
- private final HashMap<String, ElementDescriptor> mUnknownDescriptorMap =
- new HashMap<String, ElementDescriptor>();
-
- private EclipseLintClient mClient;
-
- /**
- * Flag indicating if the replacement file is due to a config change.
- * If false, it means the new file is due to an "open action" from the user.
- */
- private boolean mNewFileOnConfigChange = false;
-
- /**
- * Checks whether an editor part is an instance of {@link CommonXmlEditor}
- * with an associated {@link LayoutEditorDelegate} delegate.
- *
- * @param editorPart An editor part. Can be null.
- * @return The {@link LayoutEditorDelegate} delegate associated with the editor or null.
- */
- public static @Nullable LayoutEditorDelegate fromEditor(@Nullable IEditorPart editorPart) {
- if (editorPart instanceof CommonXmlEditor) {
- CommonXmlDelegate delegate = ((CommonXmlEditor) editorPart).getDelegate();
- if (delegate instanceof LayoutEditorDelegate) {
- return ((LayoutEditorDelegate) delegate);
- }
- } else if (editorPart instanceof GraphicalEditorPart) {
- GraphicalEditorPart part = (GraphicalEditorPart) editorPart;
- return part.getEditorDelegate();
- }
- return null;
- }
-
- /**
- * Creates the form editor for resources XML files.
- */
- @VisibleForTesting(visibility=Visibility.PRIVATE)
- protected LayoutEditorDelegate(CommonXmlEditor editor) {
- super(editor, new LayoutContentAssist());
- // Note that LayoutEditor has its own listeners and does not
- // need to call editor.addDefaultTargetListener().
- }
-
- /**
- * Returns the {@link RulesEngine} associated with this editor
- *
- * @return the {@link RulesEngine} associated with this editor.
- */
- public RulesEngine getRulesEngine() {
- return mGraphicalEditor.getRulesEngine();
- }
-
- /**
- * Returns the {@link GraphicalEditorPart} associated with this editor
- *
- * @return the {@link GraphicalEditorPart} associated with this editor
- */
- public GraphicalEditorPart getGraphicalEditor() {
- return mGraphicalEditor;
- }
-
- /**
- * @return The root node of the UI element hierarchy
- */
- @Override
- public UiDocumentNode getUiRootNode() {
- return mUiDocRootNode;
- }
-
- public void setNewFileOnConfigChange(boolean state) {
- mNewFileOnConfigChange = state;
- }
-
- // ---- Base Class Overrides ----
-
- @Override
- public void dispose() {
- super.dispose();
- if (mGraphicalEditor != null) {
- mGraphicalEditor.dispose();
- mGraphicalEditor = null;
- }
- }
-
- /**
- * Save the XML.
- * <p/>
- * Clients must NOT call this directly. Instead they should always
- * call {@link CommonXmlEditor#doSave(IProgressMonitor)} so that th
- * editor super class can commit the data properly.
- * <p/>
- * Here we just need to tell the graphical editor that the model has
- * been saved.
- */
- @Override
- public void delegateDoSave(IProgressMonitor monitor) {
- super.delegateDoSave(monitor);
- if (mGraphicalEditor != null) {
- mGraphicalEditor.doSave(monitor);
- }
- }
-
- /**
- * Create the various form pages.
- */
- @Override
- public void delegateCreateFormPages() {
- try {
- // get the file being edited so that it can be passed to the layout editor.
- IFile editedFile = null;
- IEditorInput input = getEditor().getEditorInput();
- if (input instanceof FileEditorInput) {
- FileEditorInput fileInput = (FileEditorInput)input;
- editedFile = fileInput.getFile();
- if (!editedFile.isAccessible()) {
- return;
- }
- } else {
- AdtPlugin.log(IStatus.ERROR,
- "Input is not of type FileEditorInput: %1$s", //$NON-NLS-1$
- input.toString());
- }
-
- // It is possible that the Layout Editor already exits if a different version
- // of the same layout is being opened (either through "open" action from
- // the user, or through a configuration change in the configuration selector.)
- if (mGraphicalEditor == null) {
-
- // Instantiate GLE v2
- mGraphicalEditor = new GraphicalEditorPart(this);
-
- mGraphicalEditorIndex = getEditor().addPage(mGraphicalEditor,
- getEditor().getEditorInput());
- getEditor().setPageText(mGraphicalEditorIndex, mGraphicalEditor.getTitle());
-
- mGraphicalEditor.openFile(editedFile);
- } else {
- if (mNewFileOnConfigChange) {
- mGraphicalEditor.changeFileOnNewConfig(editedFile);
- mNewFileOnConfigChange = false;
- } else {
- mGraphicalEditor.replaceFile(editedFile);
- }
- }
- } catch (PartInitException e) {
- AdtPlugin.log(e, "Error creating nested page"); //$NON-NLS-1$
- }
- }
-
- @Override
- public void delegatePostCreatePages() {
- // Optional: set the default page. Eventually a default page might be
- // restored by selectDefaultPage() later based on the last page used by the user.
- // For example, to make the last page the default one (rather than the first page),
- // uncomment this line:
- // setActivePage(getPageCount() - 1);
- }
-
- /* (non-java doc)
- * Change the tab/title name to include the name of the layout.
- */
- @Override
- public void delegateSetInput(IEditorInput input) {
- handleNewInput(input);
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.part.EditorPart#setInputWithNotify(org.eclipse.ui.IEditorInput)
- */
- public void delegateSetInputWithNotify(IEditorInput input) {
- handleNewInput(input);
- }
-
- /**
- * Called to replace the current {@link IEditorInput} with another one.
- * <p/>
- * This is used when {@link LayoutEditorMatchingStrategy} returned
- * <code>true</code> which means we're opening a different configuration of
- * the same layout.
- */
- @Override
- public void showEditorInput(IEditorInput editorInput) {
- if (getEditor().getEditorInput().equals(editorInput)) {
- return;
- }
-
- // Save the current editor input. This must be called on the editor itself
- // since it's the base editor that commits pending changes.
- getEditor().doSave(new NullProgressMonitor());
-
- // Get the current page
- int currentPage = getEditor().getActivePage();
-
- // Remove the pages, except for the graphical editor, which will be dynamically adapted
- // to the new model.
- // page after the graphical editor:
- int count = getEditor().getPageCount();
- for (int i = count - 1 ; i > mGraphicalEditorIndex ; i--) {
- getEditor().removePage(i);
- }
- // Pages before the graphical editor
- for (int i = mGraphicalEditorIndex - 1 ; i >= 0 ; i--) {
- getEditor().removePage(i);
- }
-
- // Set the current input. We're in the delegate, the input must
- // be set into the actual editor instance.
- getEditor().setInputWithNotify(editorInput);
-
- // Re-create or reload the pages with the default page shown as the previous active page.
- getEditor().createAndroidPages();
- getEditor().selectDefaultPage(Integer.toString(currentPage));
-
- // When changing an input file of an the editor, the titlebar is not refreshed to
- // show the new path/to/file being edited. So we force a refresh
- getEditor().firePropertyChange(IWorkbenchPart.PROP_TITLE);
- }
-
- /** Performs a complete refresh of the XML model */
- public void refreshXmlModel() {
- Document xmlDoc = mUiDocRootNode.getXmlDocument();
-
- delegateInitUiRootNode(true /*force*/);
- mUiDocRootNode.loadFromXmlNode(xmlDoc);
-
- // Update the model first, since it is used by the viewers.
- // No need to call AndroidXmlEditor.xmlModelChanged(xmlDoc) since it's
- // a no-op. Instead call onXmlModelChanged on the graphical editor.
-
- if (mGraphicalEditor != null) {
- mGraphicalEditor.onXmlModelChanged();
- }
- }
-
- /**
- * Processes the new XML Model, which XML root node is given.
- *
- * @param xml_doc The XML document, if available, or null if none exists.
- */
- @Override
- public void delegateXmlModelChanged(Document xml_doc) {
- // init the ui root on demand
- delegateInitUiRootNode(false /*force*/);
-
- mUiDocRootNode.loadFromXmlNode(xml_doc);
-
- // Update the model first, since it is used by the viewers.
- // No need to call AndroidXmlEditor.xmlModelChanged(xmlDoc) since it's
- // a no-op. Instead call onXmlModelChanged on the graphical editor.
-
- if (mGraphicalEditor != null) {
- mGraphicalEditor.onXmlModelChanged();
- }
- }
-
- /**
- * Tells the graphical editor to recompute its layout.
- */
- public void recomputeLayout() {
- mGraphicalEditor.recomputeLayout();
- }
-
- /**
- * Does this editor participate in the "format GUI editor changes" option?
- *
- * @return true since this editor supports automatically formatting XML
- * affected by GUI changes
- */
- @Override
- public boolean delegateSupportsFormatOnGuiEdit() {
- return true;
- }
-
- /**
- * Returns one of the issues for the given node (there could be more than one)
- *
- * @param node the node to look up lint issues for
- * @return the marker for one of the issues found for the given node
- */
- @Nullable
- public IMarker getIssueForNode(@Nullable UiViewElementNode node) {
- if (node == null) {
- return null;
- }
-
- if (mClient != null) {
- return mClient.getIssueForNode(node);
- }
-
- return null;
- }
-
- /**
- * Returns a collection of nodes that have one or more lint warnings
- * associated with them (retrievable via
- * {@link #getIssueForNode(UiViewElementNode)})
- *
- * @return a collection of nodes, which should <b>not</b> be modified by the
- * caller
- */
- @Nullable
- public Collection<Node> getLintNodes() {
- if (mClient != null) {
- return mClient.getIssueNodes();
- }
-
- return null;
- }
-
- @Override
- public Job delegateRunLint() {
- // We want to customize the {@link EclipseLintClient} created to run this
- // single file lint, in particular such that we can set the mode which collects
- // nodes on that lint job, such that we can quickly look up error nodes
- //Job job = super.delegateRunLint();
-
- Job job = null;
- IFile file = getEditor().getInputFile();
- if (file != null) {
- IssueRegistry registry = EclipseLintClient.getRegistry();
- List<IFile> resources = Collections.singletonList(file);
- mClient = new EclipseLintClient(registry,
- resources, getEditor().getStructuredDocument(), false /*fatal*/);
-
- mClient.setCollectNodes(true);
-
- job = EclipseLintRunner.startLint(mClient, resources, file,
- false /*show*/);
- }
-
- if (job != null) {
- GraphicalEditorPart graphicalEditor = getGraphicalEditor();
- if (graphicalEditor != null) {
- job.addJobChangeListener(new LintJobListener(graphicalEditor));
- }
- }
- return job;
- }
-
- private class LintJobListener extends JobChangeAdapter implements Runnable {
- private final GraphicalEditorPart mEditor;
- private final LayoutCanvas mCanvas;
-
- LintJobListener(GraphicalEditorPart editor) {
- mEditor = editor;
- mCanvas = editor.getCanvasControl();
- }
-
- @Override
- public void done(IJobChangeEvent event) {
- LayoutActionBar bar = mEditor.getLayoutActionBar();
- if (!bar.isDisposed()) {
- bar.updateErrorIndicator();
- }
-
- // Redraw
- if (!mCanvas.isDisposed()) {
- mCanvas.getDisplay().asyncExec(this);
- }
- }
-
- @Override
- public void run() {
- if (!mCanvas.isDisposed()) {
- mCanvas.redraw();
-
- OutlinePage outlinePage = mCanvas.getOutlinePage();
- if (outlinePage != null) {
- outlinePage.refreshIcons();
- }
- }
- }
- }
-
- /**
- * Returns the custom IContentOutlinePage or IPropertySheetPage when asked for it.
- */
- @Override
- public Object delegateGetAdapter(Class<?> adapter) {
- if (adapter == IContentOutlinePage.class) {
- // Somebody has requested the outline. Eclipse can only have a single outline page,
- // even for a multi-part editor:
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=1917
- // To work around this we use PDE's workaround of having a single multiplexing
- // outline which switches its contents between the outline pages we register
- // for it, and then on page switch we notify it to update itself.
-
- // There is one complication: The XML editor outline listens for the editor
- // selection and uses this to automatically expand its tree children and show
- // the current node containing the caret as selected. Unfortunately, this
- // listener code contains this:
- //
- // /* Bug 136310, unless this page is that part's
- // * IContentOutlinePage, ignore the selection change */
- // if (part.getAdapter(IContentOutlinePage.class) == this) {
- //
- // This means that when we return the multiplexing outline from this getAdapter
- // method, the outline no longer updates to track the selection.
- // To work around this, we use the following hack^H^H^H^H technique:
- // - Add a selection listener *before* requesting the editor outline, such
- // that the selection listener is told about the impending selection event
- // right before the editor outline hears about it. Set the flag
- // mCheckOutlineAdapter to true. (We also only set it if the editor view
- // itself is active.)
- // - In this getAdapter method, when somebody requests the IContentOutline.class,
- // see if mCheckOutlineAdapter to see if this request is *likely* coming
- // from the XML editor outline. If so, make sure it is by actually looking
- // at the signature of the caller. If it's the editor outline, then return
- // the editor outline instance itself rather than the multiplexing outline.
- if (mCheckOutlineAdapter && mEditorOutline != null) {
- mCheckOutlineAdapter = false;
- // Make *sure* this is really the editor outline calling in case
- // future versions of Eclipse changes the sequencing or dispatch of selection
- // events:
- StackTraceElement[] frames = new Throwable().fillInStackTrace().getStackTrace();
- if (frames.length > 2) {
- StackTraceElement frame = frames[2];
- if (frame.getClassName().equals(
- "org.eclipse.wst.sse.ui.internal.contentoutline." + //$NON-NLS-1$
- "ConfigurableContentOutlinePage$PostSelectionServiceListener")) { //$NON-NLS-1$
- return mEditorOutline;
- }
- }
- }
-
- // Use a multiplexing outline: workaround for
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=1917
- if (mMultiOutline == null || mMultiOutline.isDisposed()) {
- mMultiOutline = new XmlEditorMultiOutline();
- mMultiOutline.addSelectionChangedListener(new ISelectionChangedListener() {
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- ISelection selection = event.getSelection();
- getEditor().getSite().getSelectionProvider().setSelection(selection);
- if (getEditor().getIgnoreXmlUpdate()) {
- return;
- }
- SelectionManager manager =
- mGraphicalEditor.getCanvasControl().getSelectionManager();
- manager.setSelection(selection);
- }
- });
- updateOutline(getEditor().getActivePageInstance());
- }
-
- return mMultiOutline;
- }
-
- if (IPropertySheetPage.class == adapter && mGraphicalEditor != null) {
- if (mPropertyPage == null) {
- mPropertyPage = new PropertySheetPage(mGraphicalEditor);
- }
-
- return mPropertyPage;
- }
-
- // return default
- return super.delegateGetAdapter(adapter);
- }
-
- /**
- * Update the contents of the outline to show either the XML editor outline
- * or the layout editor graphical outline depending on which tab is visible
- */
- private void updateOutline(IFormPage page) {
- if (mMultiOutline == null) {
- return;
- }
-
- IContentOutlinePage outline;
- CommonXmlEditor editor = getEditor();
- if (!editor.isEditorPageActive()) {
- outline = getGraphicalOutline();
- } else {
- // Use plain XML editor outline instead
- if (mEditorOutline == null) {
- StructuredTextEditor structuredTextEditor = editor.getStructuredTextEditor();
- if (structuredTextEditor != null) {
- IWorkbenchWindow window = editor.getSite().getWorkbenchWindow();
- ISelectionService service = window.getSelectionService();
- service.addPostSelectionListener(new ISelectionListener() {
- @Override
- public void selectionChanged(IWorkbenchPart part, ISelection selection) {
- if (getEditor().isEditorPageActive()) {
- mCheckOutlineAdapter = true;
- }
- }
- });
-
- mEditorOutline = (IContentOutlinePage) structuredTextEditor.getAdapter(
- IContentOutlinePage.class);
- }
- }
-
- outline = mEditorOutline;
- }
-
- mMultiOutline.setPageActive(outline);
- }
-
- /**
- * Returns the graphical outline associated with the layout editor
- *
- * @return the outline page, never null
- */
- @NonNull
- public OutlinePage getGraphicalOutline() {
- if (mLayoutOutline == null) {
- mLayoutOutline = new OutlinePage(mGraphicalEditor);
- }
-
- return mLayoutOutline;
- }
-
- @Override
- public void delegatePageChange(int newPageIndex) {
- if (getEditor().getCurrentPage() == getEditor().getTextPageIndex() &&
- newPageIndex == mGraphicalEditorIndex) {
- // You're switching from the XML editor to the WYSIWYG editor;
- // look at the caret position and figure out which node it corresponds to
- // (if any) and if found, select the corresponding visual element.
- ISourceViewer textViewer = getEditor().getStructuredSourceViewer();
- int caretOffset = textViewer.getTextWidget().getCaretOffset();
- if (caretOffset >= 0) {
- Node node = DomUtilities.getNode(textViewer.getDocument(), caretOffset);
- if (node != null && mGraphicalEditor != null) {
- mGraphicalEditor.select(node);
- }
- }
- }
-
- super.delegatePageChange(newPageIndex);
-
- if (mGraphicalEditor != null) {
- if (newPageIndex == mGraphicalEditorIndex) {
- mGraphicalEditor.activated();
- } else {
- mGraphicalEditor.deactivated();
- }
- }
- }
-
- @Override
- public int delegateGetPersistenceCategory() {
- return AndroidXmlEditor.CATEGORY_LAYOUT;
- }
-
- @Override
- public void delegatePostPageChange(int newPageIndex) {
- super.delegatePostPageChange(newPageIndex);
-
- if (mGraphicalEditor != null) {
- LayoutCanvas canvas = mGraphicalEditor.getCanvasControl();
- if (canvas != null) {
- IActionBars bars = getEditor().getEditorSite().getActionBars();
- if (bars != null) {
- canvas.updateGlobalActions(bars);
- }
- }
- }
-
- IFormPage page = getEditor().getActivePageInstance();
- updateOutline(page);
- }
-
- @Override
- public IFormPage delegatePostSetActivePage(IFormPage superReturned, String pageIndex) {
- IFormPage page = superReturned;
- if (page != null) {
- updateOutline(page);
- }
-
- return page;
- }
-
- // ----- IActionContributorDelegate methods ----
-
- @Override
- public void setActiveEditor(IEditorPart part, IActionBars bars) {
- if (mGraphicalEditor != null) {
- LayoutCanvas canvas = mGraphicalEditor.getCanvasControl();
- if (canvas != null) {
- canvas.updateGlobalActions(bars);
- }
- }
- }
-
-
- @Override
- public void delegateActivated() {
- if (mGraphicalEditor != null) {
- if (getEditor().getActivePage() == mGraphicalEditorIndex) {
- mGraphicalEditor.activated();
- } else {
- mGraphicalEditor.deactivated();
- }
- }
- }
-
- @Override
- public void delegateDeactivated() {
- if (mGraphicalEditor != null && getEditor().getActivePage() == mGraphicalEditorIndex) {
- mGraphicalEditor.deactivated();
- }
- }
-
- @Override
- public String delegateGetPartName() {
- IEditorInput editorInput = getEditor().getEditorInput();
- if (!AdtPrefs.getPrefs().isSharedLayoutEditor()
- && editorInput instanceof IFileEditorInput) {
- IFileEditorInput fileInput = (IFileEditorInput) editorInput;
- IFile file = fileInput.getFile();
- IContainer parent = file.getParent();
- if (parent != null) {
- String parentName = parent.getName();
- if (parentName.startsWith(LAYOUT_FOLDER_PREFIX)) {
- parentName = parentName.substring(LAYOUT_FOLDER_PREFIX.length());
- return parentName + File.separatorChar + file.getName();
- }
- }
- }
-
- return super.delegateGetPartName();
- }
-
- // ---- Local Methods ----
-
- /**
- * Returns true if the Graphics editor page is visible. This <b>must</b> be
- * called from the UI thread.
- */
- public boolean isGraphicalEditorActive() {
- IWorkbenchPartSite workbenchSite = getEditor().getSite();
- IWorkbenchPage workbenchPage = workbenchSite.getPage();
-
- // check if the editor is visible in the workbench page
- if (workbenchPage.isPartVisible(getEditor())
- && workbenchPage.getActiveEditor() == getEditor()) {
- // and then if the page of the editor is visible (not to be confused with
- // the workbench page)
- return mGraphicalEditorIndex == getEditor().getActivePage();
- }
-
- return false;
- }
-
- @Override
- public void delegateInitUiRootNode(boolean force) {
- // The root UI node is always created, even if there's no corresponding XML node.
- if (mUiDocRootNode == null || force) {
- // get the target data from the opened file (and its project)
- AndroidTargetData data = getEditor().getTargetData();
-
- Document doc = null;
- if (mUiDocRootNode != null) {
- doc = mUiDocRootNode.getXmlDocument();
- }
-
- DocumentDescriptor desc;
- if (data == null) {
- desc = new DocumentDescriptor("temp", null /*children*/);
- } else {
- desc = data.getLayoutDescriptors().getDescriptor();
- }
-
- // get the descriptors from the data.
- mUiDocRootNode = (UiDocumentNode) desc.createUiNode();
- super.setUiRootNode(mUiDocRootNode);
- mUiDocRootNode.setEditor(getEditor());
-
- mUiDocRootNode.setUnknownDescriptorProvider(new IUnknownDescriptorProvider() {
- @Override
- public ElementDescriptor getDescriptor(String xmlLocalName) {
- ElementDescriptor unknown = mUnknownDescriptorMap.get(xmlLocalName);
- if (unknown == null) {
- unknown = createUnknownDescriptor(xmlLocalName);
- mUnknownDescriptorMap.put(xmlLocalName, unknown);
- }
-
- return unknown;
- }
- });
-
- onDescriptorsChanged(doc);
- }
- }
-
- /**
- * Creates a new {@link ViewElementDescriptor} for an unknown XML local name
- * (i.e. one that was not mapped by the current descriptors).
- * <p/>
- * Since we deal with layouts, we returns either a descriptor for a custom view
- * or one for the base View.
- *
- * @param xmlLocalName The XML local name to match.
- * @return A non-null {@link ViewElementDescriptor}.
- */
- private ViewElementDescriptor createUnknownDescriptor(String xmlLocalName) {
- ViewElementDescriptor desc = null;
- IEditorInput editorInput = getEditor().getEditorInput();
- if (editorInput instanceof IFileEditorInput) {
- IFileEditorInput fileInput = (IFileEditorInput)editorInput;
- IProject project = fileInput.getFile().getProject();
-
- // Check if we can find a custom view specific to this project.
- // This only works if there's an actual matching custom class in the project.
- if (xmlLocalName.indexOf('.') != -1) {
- desc = CustomViewDescriptorService.getInstance().getDescriptor(project,
- xmlLocalName);
- }
-
- if (desc == null) {
- // If we didn't find a custom view, create a synthetic one using the
- // the base View descriptor as a model.
- // This is a layout after all, so every XML node should represent
- // a view.
-
- Sdk currentSdk = Sdk.getCurrent();
- if (currentSdk != null) {
- IAndroidTarget target = currentSdk.getTarget(project);
- if (target != null) {
- AndroidTargetData data = currentSdk.getTargetData(target);
- if (data != null) {
- // data can be null when the target is still loading
- ViewElementDescriptor viewDesc =
- data.getLayoutDescriptors().getBaseViewDescriptor();
-
- desc = new ViewElementDescriptor(
- xmlLocalName, // xml local name
- xmlLocalName, // ui_name
- xmlLocalName, // canonical class name
- null, // tooltip
- null, // sdk_url
- viewDesc.getAttributes(),
- viewDesc.getLayoutAttributes(),
- null, // children
- false /* mandatory */);
- desc.setSuperClass(viewDesc);
- }
- }
- }
- }
- }
-
- if (desc == null) {
- // We can only arrive here if the SDK's android target has not finished
- // loading. Just create a dummy descriptor with no attributes to be able
- // to continue.
- desc = new ViewElementDescriptor(xmlLocalName, xmlLocalName);
- }
- return desc;
- }
-
- private void onDescriptorsChanged(Document document) {
-
- mUnknownDescriptorMap.clear();
-
- if (document != null) {
- mUiDocRootNode.loadFromXmlNode(document);
- } else {
- mUiDocRootNode.reloadFromXmlNode(mUiDocRootNode.getXmlDocument());
- }
-
- if (mGraphicalEditor != null) {
- mGraphicalEditor.onTargetChange();
- mGraphicalEditor.reloadPalette();
- mGraphicalEditor.getCanvasControl().syncPreviewMode();
- }
- }
-
- /**
- * Handles a new input, and update the part name.
- * @param input the new input.
- */
- private void handleNewInput(IEditorInput input) {
- if (input instanceof FileEditorInput) {
- FileEditorInput fileInput = (FileEditorInput) input;
- IFile file = fileInput.getFile();
- getEditor().setPartName(String.format("%1$s", file.getName()));
- }
- }
-
- /**
- * Helper method that returns a {@link ViewElementDescriptor} for the requested FQCN.
- * Will return null if we can't find that FQCN or we lack the editor/data/descriptors info.
- */
- public ViewElementDescriptor getFqcnViewDescriptor(String fqcn) {
- ViewElementDescriptor desc = null;
-
- AndroidTargetData data = getEditor().getTargetData();
- if (data != null) {
- LayoutDescriptors layoutDesc = data.getLayoutDescriptors();
- if (layoutDesc != null) {
- DocumentDescriptor docDesc = layoutDesc.getDescriptor();
- if (docDesc != null) {
- desc = internalFindFqcnViewDescriptor(fqcn, docDesc.getChildren(), null);
- }
- }
- }
-
- if (desc == null) {
- // We failed to find a descriptor for the given FQCN.
- // Let's consider custom classes and create one as needed.
- desc = createUnknownDescriptor(fqcn);
- }
-
- return desc;
- }
-
- /**
- * Internal helper to recursively search for a {@link ViewElementDescriptor} that matches
- * the requested FQCN.
- *
- * @param fqcn The target View FQCN to find.
- * @param descriptors A list of children descriptors to iterate through.
- * @param visited A set we use to remember which descriptors have already been visited,
- * necessary since the view descriptor hierarchy is cyclic.
- * @return Either a matching {@link ViewElementDescriptor} or null.
- */
- private ViewElementDescriptor internalFindFqcnViewDescriptor(String fqcn,
- ElementDescriptor[] descriptors,
- Set<ElementDescriptor> visited) {
- if (visited == null) {
- visited = new HashSet<ElementDescriptor>();
- }
-
- if (descriptors != null) {
- for (ElementDescriptor desc : descriptors) {
- if (visited.add(desc)) {
- // Set.add() returns true if this a new element that was added to the set.
- // That means we haven't visited this descriptor yet.
- // We want a ViewElementDescriptor with a matching FQCN.
- if (desc instanceof ViewElementDescriptor &&
- fqcn.equals(((ViewElementDescriptor) desc).getFullClassName())) {
- return (ViewElementDescriptor) desc;
- }
-
- // Visit its children
- ViewElementDescriptor vd =
- internalFindFqcnViewDescriptor(fqcn, desc.getChildren(), visited);
- if (vd != null) {
- return vd;
- }
- }
- }
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/LayoutEditorMatchingStrategy.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/LayoutEditorMatchingStrategy.java
deleted file mode 100644
index c1c606854..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/LayoutEditorMatchingStrategy.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout;
-
-import com.android.ide.common.resources.ResourceFolder;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.resources.ResourceFolderType;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorMatchingStrategy;
-import org.eclipse.ui.IEditorReference;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.part.FileEditorInput;
-
-/**
- * Matching strategy for the Layout Editor. This is used to open all configurations of a layout
- * in the same editor.
- */
-public class LayoutEditorMatchingStrategy implements IEditorMatchingStrategy {
-
- @Override
- public boolean matches(IEditorReference editorRef, IEditorInput input) {
- // first check that the file being opened is a layout file.
- if (input instanceof FileEditorInput) {
- FileEditorInput fileInput = (FileEditorInput)input;
-
- // get the IFile object and check it's in one of the layout folders.
- IFile file = fileInput.getFile();
- ResourceManager manager = ResourceManager.getInstance();
- ResourceFolder resFolder = manager.getResourceFolder(file);
-
- // Per the IEditorMatchingStrategy documentation, editorRef.getEditorInput()
- // is expensive so try exclude files that definitely don't match, such
- // as those with the wrong extension or wrong file name
- if (!file.getName().equals(editorRef.getName()) ||
- !editorRef.getId().equals(CommonXmlEditor.ID)) {
- return false;
- }
-
- // if it's a layout, we now check the name of the fileInput against the name of the
- // file being currently edited by the editor since those are independent of the config.
- if (resFolder != null && resFolder.getType() == ResourceFolderType.LAYOUT) {
- try {
- IEditorInput editorInput = editorRef.getEditorInput();
- if (editorInput instanceof FileEditorInput) {
- FileEditorInput editorFileInput = (FileEditorInput)editorInput;
- IFile editorFile = editorFileInput.getFile();
-
- ResourceFolder editorFolder = manager.getResourceFolder(editorFile);
- if (editorFolder == null
- || editorFolder.getType() != ResourceFolderType.LAYOUT) {
- return false;
- }
-
- return editorFile.getProject().equals(file.getProject())
- && editorFile.getName().equals(file.getName());
- }
- } catch (PartInitException e) {
- // we do nothing, we'll just return false.
- }
- }
- }
- return false;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/LayoutReloadMonitor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/LayoutReloadMonitor.java
deleted file mode 100644
index 4e4429dc8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/LayoutReloadMonitor.java
+++ /dev/null
@@ -1,375 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.resources.ResourceFile;
-import com.android.ide.common.resources.ResourceFolder;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.resources.manager.GlobalProjectMonitor;
-import com.android.ide.eclipse.adt.internal.resources.manager.GlobalProjectMonitor.IFileListener;
-import com.android.ide.eclipse.adt.internal.resources.manager.GlobalProjectMonitor.IResourceEventListener;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager.IResourceListener;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.resources.ResourceType;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarkerDelta;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.runtime.CoreException;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
-/**
- * Monitor for file changes that could trigger a layout redraw, or a UI update
- */
-public final class LayoutReloadMonitor {
-
- // singleton, enforced by private constructor.
- private final static LayoutReloadMonitor sThis = new LayoutReloadMonitor();
-
- /**
- * Map of listeners by IProject.
- */
- private final Map<IProject, List<ILayoutReloadListener>> mListenerMap =
- new HashMap<IProject, List<ILayoutReloadListener>>();
-
- public final static class ChangeFlags {
- public boolean code = false;
- /** any non-layout resource changes */
- public boolean resources = false;
- public boolean rClass = false;
- public boolean localeList = false;
- public boolean manifest = false;
-
- boolean isAllTrue() {
- return code && resources && rClass && localeList && manifest;
- }
- }
-
- /**
- * List of projects having received a resource change.
- */
- private final Map<IProject, ChangeFlags> mProjectFlags = new HashMap<IProject, ChangeFlags>();
-
- /**
- * Classes which implement this interface provide a method to respond to resource changes
- * triggering a layout redraw
- */
- public interface ILayoutReloadListener {
- /**
- * Sent when the layout needs to be redrawn
- *
- * @param flags a {@link ChangeFlags} object indicating what type of resource changed.
- * @param libraryModified <code>true</code> if the changeFlags are not for the project
- * associated with the listener, but instead correspond to a library.
- */
- void reloadLayout(ChangeFlags flags, boolean libraryModified);
- }
-
- /**
- * Returns the single instance of {@link LayoutReloadMonitor}.
- */
- public static LayoutReloadMonitor getMonitor() {
- return sThis;
- }
-
- private LayoutReloadMonitor() {
- // listen to resource changes. Used for non-layout resource (trigger a redraw), or
- // any resource folder (trigger a locale list refresh)
- ResourceManager.getInstance().addListener(mResourceListener);
-
- // also listen for .class file changed in case the layout has custom view classes.
- GlobalProjectMonitor monitor = GlobalProjectMonitor.getMonitor();
- monitor.addFileListener(mFileListener,
- IResourceDelta.ADDED | IResourceDelta.CHANGED | IResourceDelta.REMOVED);
-
- monitor.addResourceEventListener(mResourceEventListener);
- }
-
- /**
- * Adds a listener for a given {@link IProject}.
- * @param project
- * @param listener
- */
- public void addListener(IProject project, ILayoutReloadListener listener) {
- synchronized (mListenerMap) {
- List<ILayoutReloadListener> list = mListenerMap.get(project);
- if (list == null) {
- list = new ArrayList<ILayoutReloadListener>();
- mListenerMap.put(project, list);
- }
-
- list.add(listener);
- }
- }
-
- /**
- * Removes a listener for a given {@link IProject}.
- */
- public void removeListener(IProject project, ILayoutReloadListener listener) {
- synchronized (mListenerMap) {
- List<ILayoutReloadListener> list = mListenerMap.get(project);
- if (list != null) {
- list.remove(listener);
- }
- }
- }
-
- /**
- * Removes a listener, no matter which {@link IProject} it was associated with.
- */
- public void removeListener(ILayoutReloadListener listener) {
- synchronized (mListenerMap) {
-
- for (List<ILayoutReloadListener> list : mListenerMap.values()) {
- Iterator<ILayoutReloadListener> it = list.iterator();
- while (it.hasNext()) {
- ILayoutReloadListener i = it.next();
- if (i == listener) {
- it.remove();
- }
- }
- }
- }
- }
-
- /**
- * Implementation of the {@link IFileListener} as an internal class so that the methods
- * do not appear in the public API of {@link LayoutReloadMonitor}.
- *
- * This is only to detect code and manifest change. Resource changes (located in res/)
- * is done through {@link #mResourceListener}.
- */
- private IFileListener mFileListener = new IFileListener() {
- /*
- * Callback for IFileListener. Called when a file changed.
- * This records the changes for each project, but does not notify listeners.
- */
- @Override
- public void fileChanged(@NonNull IFile file, @NonNull IMarkerDelta[] markerDeltas,
- int kind, @Nullable String extension, int flags, boolean isAndroidProject) {
- // This listener only cares about .class files and AndroidManifest.xml files
- if (!(SdkConstants.EXT_CLASS.equals(extension)
- || SdkConstants.EXT_XML.equals(extension)
- && SdkConstants.FN_ANDROID_MANIFEST_XML.equals(file.getName()))) {
- return;
- }
-
- // get the file's project
- IProject project = file.getProject();
-
- if (isAndroidProject) {
- // project is an Android project, it's the one being affected
- // directly by its own file change.
- processFileChanged(file, project, extension);
- } else {
- // check the projects depending on it, if they are Android project, update them.
- IProject[] referencingProjects = project.getReferencingProjects();
-
- for (IProject p : referencingProjects) {
- try {
- boolean hasAndroidNature = p.hasNature(AdtConstants.NATURE_DEFAULT);
- if (hasAndroidNature) {
- // the changed project is a dependency on an Android project,
- // update the main project.
- processFileChanged(file, p, extension);
- }
- } catch (CoreException e) {
- // do nothing if the nature cannot be queried.
- }
- }
- }
- }
-
- /**
- * Processes a file change for a given project which may or may not be the file's project.
- * @param file the changed file
- * @param project the project impacted by the file change.
- */
- private void processFileChanged(IFile file, IProject project, String extension) {
- // if this project has already been marked as modified, we do nothing.
- ChangeFlags changeFlags = mProjectFlags.get(project);
- if (changeFlags != null && changeFlags.isAllTrue()) {
- return;
- }
-
- // here we only care about code change (so change for .class files).
- // Resource changes is handled by the IResourceListener.
- if (SdkConstants.EXT_CLASS.equals(extension)) {
- if (file.getName().matches("R[\\$\\.](.*)")) {
- // this is a R change!
- if (changeFlags == null) {
- changeFlags = new ChangeFlags();
- mProjectFlags.put(project, changeFlags);
- }
-
- changeFlags.rClass = true;
- } else {
- // this is a code change!
- if (changeFlags == null) {
- changeFlags = new ChangeFlags();
- mProjectFlags.put(project, changeFlags);
- }
-
- changeFlags.code = true;
- }
- } else if (SdkConstants.FN_ANDROID_MANIFEST_XML.equals(file.getName()) &&
- file.getParent().equals(project)) {
- // this is a manifest change!
- if (changeFlags == null) {
- changeFlags = new ChangeFlags();
- mProjectFlags.put(project, changeFlags);
- }
-
- changeFlags.manifest = true;
- }
- }
- };
-
- /**
- * Implementation of the {@link IResourceEventListener} as an internal class so that the methods
- * do not appear in the public API of {@link LayoutReloadMonitor}.
- */
- private IResourceEventListener mResourceEventListener = new IResourceEventListener() {
- /*
- * Callback for ResourceMonitor.IResourceEventListener. Called at the beginning of a
- * resource change event. This is called once, while fileChanged can be
- * called several times.
- *
- */
- @Override
- public void resourceChangeEventStart() {
- // nothing to be done here, it all happens in the resourceChangeEventEnd
- }
-
- /*
- * Callback for ResourceMonitor.IResourceEventListener. Called at the end of a resource
- * change event. This is where we notify the listeners.
- */
- @Override
- public void resourceChangeEventEnd() {
- // for each IProject that was changed, we notify all the listeners.
- for (Entry<IProject, ChangeFlags> entry : mProjectFlags.entrySet()) {
- IProject project = entry.getKey();
-
- // notify the project itself.
- notifyForProject(project, entry.getValue(), false);
-
- // check if the project is a library, and if it is search for what other
- // project depends on this one (directly or not)
- ProjectState state = Sdk.getProjectState(project);
- if (state != null && state.isLibrary()) {
- Set<ProjectState> mainProjects = Sdk.getMainProjectsFor(project);
- for (ProjectState mainProject : mainProjects) {
- // always give the changeflag of the modified project.
- notifyForProject(mainProject.getProject(), entry.getValue(), true);
- }
- }
- }
-
- // empty the list.
- mProjectFlags.clear();
- }
-
- /**
- * Notifies the listeners for a given project.
- * @param project the project for which the listeners must be notified
- * @param flags the change flags to pass to the listener
- * @param libraryChanged a flag indicating if the change flags are for the give project,
- * or if they are for a library dependency.
- */
- private void notifyForProject(IProject project, ChangeFlags flags,
- boolean libraryChanged) {
- synchronized (mListenerMap) {
- List<ILayoutReloadListener> listeners = mListenerMap.get(project);
-
- if (listeners != null) {
- for (ILayoutReloadListener listener : listeners) {
- try {
- listener.reloadLayout(flags, libraryChanged);
- } catch (Throwable t) {
- AdtPlugin.log(t, "Failed to call ILayoutReloadListener.reloadLayout");
- }
- }
- }
- }
- }
- };
-
- /**
- * Implementation of the {@link IResourceListener} as an internal class so that the methods
- * do not appear in the public API of {@link LayoutReloadMonitor}.
- */
- private IResourceListener mResourceListener = new IResourceListener() {
-
- @Override
- public void folderChanged(IProject project, ResourceFolder folder, int eventType) {
- // if this project has already been marked as modified, we do nothing.
- ChangeFlags changeFlags = mProjectFlags.get(project);
- if (changeFlags != null && changeFlags.isAllTrue()) {
- return;
- }
-
- // this means a new resource folder was added or removed, which can impact the
- // locale list.
- if (changeFlags == null) {
- changeFlags = new ChangeFlags();
- mProjectFlags.put(project, changeFlags);
- }
-
- changeFlags.localeList = true;
- }
-
- @Override
- public void fileChanged(IProject project, ResourceFile file, int eventType) {
- // if this project has already been marked as modified, we do nothing.
- ChangeFlags changeFlags = mProjectFlags.get(project);
- if (changeFlags != null && changeFlags.isAllTrue()) {
- return;
- }
-
- // now check that the file is *NOT* a layout file (those automatically trigger a layout
- // reload and we don't want to do it twice.)
- Collection<ResourceType> resTypes = file.getResourceTypes();
-
- // it's unclear why but there has been cases of resTypes being empty!
- if (resTypes.size() > 0) {
- // this is a resource change, that may require a layout redraw!
- if (changeFlags == null) {
- changeFlags = new ChangeFlags();
- mProjectFlags.put(project, changeFlags);
- }
-
- changeFlags.resources = true;
- }
- }
- };
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/ProjectCallback.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/ProjectCallback.java
deleted file mode 100644
index 020c666b9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/ProjectCallback.java
+++ /dev/null
@@ -1,693 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout;
-
-import static com.android.SdkConstants.ANDROID_PKG_PREFIX;
-import static com.android.SdkConstants.CALENDAR_VIEW;
-import static com.android.SdkConstants.CLASS_VIEW;
-import static com.android.SdkConstants.EXPANDABLE_LIST_VIEW;
-import static com.android.SdkConstants.FQCN_GRID_VIEW;
-import static com.android.SdkConstants.FQCN_SPINNER;
-import static com.android.SdkConstants.GRID_VIEW;
-import static com.android.SdkConstants.LIST_VIEW;
-import static com.android.SdkConstants.SPINNER;
-import static com.android.SdkConstants.VIEW_FRAGMENT;
-import static com.android.SdkConstants.VIEW_INCLUDE;
-
-import com.android.SdkConstants;
-import com.android.ide.common.rendering.LayoutLibrary;
-import com.android.ide.common.rendering.RenderSecurityManager;
-import com.android.ide.common.rendering.api.ActionBarCallback;
-import com.android.ide.common.rendering.api.AdapterBinding;
-import com.android.ide.common.rendering.api.DataBindingItem;
-import com.android.ide.common.rendering.api.Features;
-import com.android.ide.common.rendering.api.ILayoutPullParser;
-import com.android.ide.common.rendering.api.IProjectCallback;
-import com.android.ide.common.rendering.api.LayoutlibCallback;
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.ide.common.rendering.api.ResourceReference;
-import com.android.ide.common.rendering.api.ResourceValue;
-import com.android.ide.common.rendering.api.Result;
-import com.android.ide.common.resources.ResourceResolver;
-import com.android.ide.common.xml.ManifestData;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.LayoutMetadata;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderLogger;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.ide.eclipse.adt.internal.project.AndroidManifestHelper;
-import com.android.ide.eclipse.adt.internal.resources.manager.ProjectClassLoader;
-import com.android.ide.eclipse.adt.internal.resources.manager.ProjectResources;
-import com.android.resources.ResourceType;
-import com.android.util.Pair;
-import com.google.common.base.Charsets;
-import com.google.common.io.Files;
-
-import org.eclipse.core.resources.IProject;
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.StringReader;
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-
-/**
- * Loader for Android Project class in order to use them in the layout editor.
- * <p/>This implements {@link IProjectCallback} for the old and new API through
- * {@link LayoutlibCallback}
- */
-public final class ProjectCallback extends LayoutlibCallback {
- private final HashMap<String, Class<?>> mLoadedClasses = new HashMap<String, Class<?>>();
- private final Set<String> mMissingClasses = new TreeSet<String>();
- private final Set<String> mBrokenClasses = new TreeSet<String>();
- private final IProject mProject;
- private final ClassLoader mParentClassLoader;
- private final ProjectResources mProjectRes;
- private final Object mCredential;
- private boolean mUsed = false;
- private String mNamespace;
- private ProjectClassLoader mLoader = null;
- private LayoutLog mLogger;
- private LayoutLibrary mLayoutLib;
- private String mLayoutName;
- private ILayoutPullParser mLayoutEmbeddedParser;
- private ResourceResolver mResourceResolver;
- private GraphicalEditorPart mEditor;
-
- /**
- * Creates a new {@link ProjectCallback} to be used with the layout lib.
- *
- * @param layoutLib The layout library this callback is going to be invoked from
- * @param projectRes the {@link ProjectResources} for the project.
- * @param project the project.
- * @param credential the sandbox credential
- */
- public ProjectCallback(LayoutLibrary layoutLib,
- ProjectResources projectRes, IProject project, Object credential,
- GraphicalEditorPart editor) {
- mLayoutLib = layoutLib;
- mParentClassLoader = layoutLib.getClassLoader();
- mProjectRes = projectRes;
- mProject = project;
- mCredential = credential;
- mEditor = editor;
- }
-
- public Set<String> getMissingClasses() {
- return mMissingClasses;
- }
-
- public Set<String> getUninstantiatableClasses() {
- return mBrokenClasses;
- }
-
- /**
- * Sets the {@link LayoutLog} logger to use for error messages during problems
- *
- * @param logger the new logger to use, or null to clear it out
- */
- public void setLogger(LayoutLog logger) {
- mLogger = logger;
- }
-
- /**
- * Returns the {@link LayoutLog} logger used for error messages, or null
- *
- * @return the logger being used, or null if no logger is in use
- */
- public LayoutLog getLogger() {
- return mLogger;
- }
-
- /**
- * {@inheritDoc}
- *
- * This implementation goes through the output directory of the Eclipse project and loads the
- * <code>.class</code> file directly.
- */
- @Override
- @SuppressWarnings("unchecked")
- public Object loadView(String className, Class[] constructorSignature,
- Object[] constructorParameters)
- throws Exception {
- mUsed = true;
-
- if (className == null) {
- // Just make a plain <View> if you specify <view> without a class= attribute.
- className = CLASS_VIEW;
- }
-
- // look for a cached version
- Class<?> clazz = mLoadedClasses.get(className);
- if (clazz != null) {
- return instantiateClass(clazz, constructorSignature, constructorParameters);
- }
-
- // load the class.
-
- try {
- if (mLoader == null) {
- // Allow creating class loaders during rendering; may be prevented by the
- // RenderSecurityManager
- boolean token = RenderSecurityManager.enterSafeRegion(mCredential);
- try {
- mLoader = new ProjectClassLoader(mParentClassLoader, mProject);
- } finally {
- RenderSecurityManager.exitSafeRegion(token);
- }
- }
- clazz = mLoader.loadClass(className);
- } catch (Exception e) {
- // Add the missing class to the list so that the renderer can print them later.
- // no need to log this.
- if (!className.equals(VIEW_FRAGMENT) && !className.equals(VIEW_INCLUDE)) {
- mMissingClasses.add(className);
- }
- }
-
- try {
- if (clazz != null) {
- // first try to instantiate it because adding it the list of loaded class so that
- // we don't add broken classes.
- Object view = instantiateClass(clazz, constructorSignature, constructorParameters);
- mLoadedClasses.put(className, clazz);
-
- return view;
- }
- } catch (Throwable e) {
- // Find root cause to log it.
- while (e.getCause() != null) {
- e = e.getCause();
- }
-
- appendToIdeLog(e, "%1$s failed to instantiate.", className); //$NON-NLS-1$
-
- // Add the missing class to the list so that the renderer can print them later.
- if (mLogger instanceof RenderLogger) {
- RenderLogger renderLogger = (RenderLogger) mLogger;
- renderLogger.recordThrowable(e);
-
- }
- mBrokenClasses.add(className);
- }
-
- // Create a mock view instead. We don't cache it in the mLoadedClasses map.
- // If any exception is thrown, we'll return a CFN with the original class name instead.
- try {
- clazz = mLoader.loadClass(SdkConstants.CLASS_MOCK_VIEW);
- Object view = instantiateClass(clazz, constructorSignature, constructorParameters);
-
- // Set the text of the mock view to the simplified name of the custom class
- Method m = view.getClass().getMethod("setText",
- new Class<?>[] { CharSequence.class });
- String label = getShortClassName(className);
- if (label.equals(VIEW_FRAGMENT)) {
- label = "<fragment>\n"
- + "Pick preview layout from the \"Fragment Layout\" context menu";
- } else if (label.equals(VIEW_INCLUDE)) {
- label = "Text";
- }
-
- m.invoke(view, label);
-
- // Call MockView.setGravity(Gravity.CENTER) to get the text centered in
- // MockViews.
- // TODO: Do this in layoutlib's MockView class instead.
- try {
- // Look up android.view.Gravity#CENTER - or can we just hard-code
- // the value (17) here?
- Class<?> gravity =
- Class.forName("android.view.Gravity", //$NON-NLS-1$
- true, view.getClass().getClassLoader());
- Field centerField = gravity.getField("CENTER"); //$NON-NLS-1$
- int center = centerField.getInt(null);
- m = view.getClass().getMethod("setGravity",
- new Class<?>[] { Integer.TYPE });
- // Center
- //int center = (0x0001 << 4) | (0x0001 << 0);
- m.invoke(view, Integer.valueOf(center));
- } catch (Exception e) {
- // Not important to center views
- }
-
- return view;
- } catch (Exception e) {
- // We failed to create and return a mock view.
- // Just throw back a CNF with the original class name.
- throw new ClassNotFoundException(className, e);
- }
- }
-
- private String getShortClassName(String fqcn) {
- // The name is typically a fully-qualified class name. Let's make it a tad shorter.
-
- if (fqcn.startsWith("android.")) { //$NON-NLS-1$
- // For android classes, convert android.foo.Name to android...Name
- int first = fqcn.indexOf('.');
- int last = fqcn.lastIndexOf('.');
- if (last > first) {
- return fqcn.substring(0, first) + ".." + fqcn.substring(last); //$NON-NLS-1$
- }
- } else {
- // For custom non-android classes, it's best to keep the 2 first segments of
- // the namespace, e.g. we want to get something like com.example...MyClass
- int first = fqcn.indexOf('.');
- first = fqcn.indexOf('.', first + 1);
- int last = fqcn.lastIndexOf('.');
- if (last > first) {
- return fqcn.substring(0, first) + ".." + fqcn.substring(last); //$NON-NLS-1$
- }
- }
-
- return fqcn;
- }
-
- /**
- * Returns the namespace for the project. The namespace contains a standard part + the
- * application package.
- *
- * @return The package namespace of the project or null in case of error.
- */
- @Override
- public String getNamespace() {
- if (mNamespace == null) {
- boolean token = RenderSecurityManager.enterSafeRegion(mCredential);
- try {
- ManifestData manifestData = AndroidManifestHelper.parseForData(mProject);
- if (manifestData != null) {
- String javaPackage = manifestData.getPackage();
- mNamespace = String.format(AdtConstants.NS_CUSTOM_RESOURCES, javaPackage);
- }
- } finally {
- RenderSecurityManager.exitSafeRegion(token);
- }
- }
-
- return mNamespace;
- }
-
- @Override
- public Pair<ResourceType, String> resolveResourceId(int id) {
- if (mProjectRes != null) {
- return mProjectRes.resolveResourceId(id);
- }
-
- return null;
- }
-
- @Override
- public String resolveResourceId(int[] id) {
- if (mProjectRes != null) {
- return mProjectRes.resolveStyleable(id);
- }
-
- return null;
- }
-
- @Override
- public Integer getResourceId(ResourceType type, String name) {
- if (mProjectRes != null) {
- return mProjectRes.getResourceId(type, name);
- }
-
- return null;
- }
-
- /**
- * Returns whether the loader has received requests to load custom views. Note that
- * the custom view loading may not actually have succeeded; this flag only records
- * whether it was <b>requested</b>.
- * <p/>
- * This allows to efficiently only recreate when needed upon code change in the
- * project.
- *
- * @return true if the loader has been asked to load custom views
- */
- public boolean isUsed() {
- return mUsed;
- }
-
- /**
- * Instantiate a class object, using a specific constructor and parameters.
- * @param clazz the class to instantiate
- * @param constructorSignature the signature of the constructor to use
- * @param constructorParameters the parameters to use in the constructor.
- * @return A new class object, created using a specific constructor and parameters.
- * @throws Exception
- */
- @SuppressWarnings("unchecked")
- private Object instantiateClass(Class<?> clazz,
- Class[] constructorSignature,
- Object[] constructorParameters) throws Exception {
- Constructor<?> constructor = null;
-
- try {
- constructor = clazz.getConstructor(constructorSignature);
-
- } catch (NoSuchMethodException e) {
- // Custom views can either implement a 3-parameter, 2-parameter or a
- // 1-parameter. Let's synthetically build and try all the alternatives.
- // That's kind of like switching to the other box.
- //
- // The 3-parameter constructor takes the following arguments:
- // ...(Context context, AttributeSet attrs, int defStyle)
-
- int n = constructorSignature.length;
- if (n == 0) {
- // There is no parameter-less constructor. Nobody should ask for one.
- throw e;
- }
-
- for (int i = 3; i >= 1; i--) {
- if (i == n) {
- // Let's skip the one we know already fails
- continue;
- }
- Class[] sig = new Class[i];
- Object[] params = new Object[i];
-
- int k = i;
- if (n < k) {
- k = n;
- }
- System.arraycopy(constructorSignature, 0, sig, 0, k);
- System.arraycopy(constructorParameters, 0, params, 0, k);
-
- for (k++; k <= i; k++) {
- if (k == 2) {
- // Parameter 2 is the AttributeSet
- sig[k-1] = clazz.getClassLoader().loadClass("android.util.AttributeSet");
- params[k-1] = null;
-
- } else if (k == 3) {
- // Parameter 3 is the int defstyle
- sig[k-1] = int.class;
- params[k-1] = 0;
- }
- }
-
- constructorSignature = sig;
- constructorParameters = params;
-
- try {
- // Try again...
- constructor = clazz.getConstructor(constructorSignature);
- if (constructor != null) {
- // Found a suitable constructor, now let's use it.
- // (But let's warn the user if the simple View constructor was found
- // since Unexpected Things may happen if the attribute set constructors
- // are not found)
- if (constructorSignature.length < 2 && mLogger != null) {
- mLogger.warning("wrongconstructor", //$NON-NLS-1$
- String.format("Custom view %1$s is not using the 2- or 3-argument "
- + "View constructors; XML attributes will not work",
- clazz.getSimpleName()), null /*data*/);
- }
- break;
- }
- } catch (NoSuchMethodException e1) {
- // pass
- }
- }
-
- // If all the alternatives failed, throw the initial exception.
- if (constructor == null) {
- throw e;
- }
- }
-
- constructor.setAccessible(true);
- return constructor.newInstance(constructorParameters);
- }
-
- public void setLayoutParser(String layoutName, ILayoutPullParser layoutParser) {
- mLayoutName = layoutName;
- mLayoutEmbeddedParser = layoutParser;
- }
-
- @Override
- public ILayoutPullParser getParser(String layoutName) {
- boolean token = RenderSecurityManager.enterSafeRegion(mCredential);
- try {
- // Try to compute the ResourceValue for this layout since layoutlib
- // must be an older version which doesn't pass the value:
- if (mResourceResolver != null) {
- ResourceValue value = mResourceResolver.getProjectResource(ResourceType.LAYOUT,
- layoutName);
- if (value != null) {
- return getParser(value);
- }
- }
-
- return getParser(layoutName, null);
- } finally {
- RenderSecurityManager.exitSafeRegion(token);
- }
- }
-
- @Override
- public ILayoutPullParser getParser(ResourceValue layoutResource) {
- boolean token = RenderSecurityManager.enterSafeRegion(mCredential);
- try {
- return getParser(layoutResource.getName(),
- new File(layoutResource.getValue()));
- } finally {
- RenderSecurityManager.exitSafeRegion(token);
- }
- }
-
- private ILayoutPullParser getParser(String layoutName, File xml) {
- if (layoutName.equals(mLayoutName)) {
- ILayoutPullParser parser = mLayoutEmbeddedParser;
- // The parser should only be used once!! If it is included more than once,
- // subsequent includes should just use a plain pull parser that is not tied
- // to the XML model
- mLayoutEmbeddedParser = null;
- return parser;
- }
-
- // For included layouts, create a ContextPullParser such that we get the
- // layout editor behavior in included layouts as well - which for example
- // replaces <fragment> tags with <include>.
- if (xml != null && xml.isFile()) {
- ContextPullParser parser = new ContextPullParser(this, xml);
- try {
- parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
- String xmlText = Files.toString(xml, Charsets.UTF_8);
- parser.setInput(new StringReader(xmlText));
- return parser;
- } catch (XmlPullParserException e) {
- appendToIdeLog(e, null);
- } catch (FileNotFoundException e) {
- // Shouldn't happen since we check isFile() above
- } catch (IOException e) {
- appendToIdeLog(e, null);
- }
- }
-
- return null;
- }
-
- @Override
- public Object getAdapterItemValue(ResourceReference adapterView, Object adapterCookie,
- ResourceReference itemRef,
- int fullPosition, int typePosition, int fullChildPosition, int typeChildPosition,
- ResourceReference viewRef, ViewAttribute viewAttribute, Object defaultValue) {
-
- // Special case for the palette preview
- if (viewAttribute == ViewAttribute.TEXT
- && adapterView.getName().startsWith("android_widget_")) { //$NON-NLS-1$
- String name = adapterView.getName();
- if (viewRef.getName().equals("text2")) { //$NON-NLS-1$
- return "Sub Item";
- }
- if (fullPosition == 0) {
- String viewName = name.substring("android_widget_".length());
- if (viewName.equals(EXPANDABLE_LIST_VIEW)) {
- return "ExpandableList"; // ExpandableListView is too wide, character-wraps
- }
- return viewName;
- } else {
- return "Next Item";
- }
- }
-
- if (itemRef.isFramework()) {
- // Special case for list_view_item_2 and friends
- if (viewRef.getName().equals("text2")) { //$NON-NLS-1$
- return "Sub Item " + (fullPosition + 1);
- }
- }
-
- if (viewAttribute == ViewAttribute.TEXT && ((String) defaultValue).length() == 0) {
- return "Item " + (fullPosition + 1);
- }
-
- return null;
- }
-
- /**
- * For the given class, finds and returns the nearest super class which is a ListView
- * or an ExpandableListView or a GridView (which uses a list adapter), or returns null.
- *
- * @param clz the class of the view object
- * @return the fully qualified class name of the list ancestor, or null if there
- * is no list view ancestor
- */
- public static String getListAdapterViewFqcn(Class<?> clz) {
- String fqcn = clz.getName();
- if (fqcn.endsWith(LIST_VIEW)) { // including EXPANDABLE_LIST_VIEW
- return fqcn;
- } else if (fqcn.equals(FQCN_GRID_VIEW)) {
- return fqcn;
- } else if (fqcn.equals(FQCN_SPINNER)) {
- return fqcn;
- } else if (fqcn.startsWith(ANDROID_PKG_PREFIX)) {
- return null;
- }
- Class<?> superClass = clz.getSuperclass();
- if (superClass != null) {
- return getListAdapterViewFqcn(superClass);
- } else {
- // Should not happen; we would have encountered android.view.View first,
- // and it should have been covered by the ANDROID_PKG_PREFIX case above.
- return null;
- }
- }
-
- /**
- * Looks at the parent-chain of the view and if it finds a custom view, or a
- * CalendarView, within the given distance then it returns true. A ListView within a
- * CalendarView should not be assigned a custom list view type because it sets its own
- * and then attempts to cast the layout to its own type which would fail if the normal
- * default list item binding is used.
- */
- private boolean isWithinIllegalParent(Object viewObject, int depth) {
- String fqcn = viewObject.getClass().getName();
- if (fqcn.endsWith(CALENDAR_VIEW) || !fqcn.startsWith(ANDROID_PKG_PREFIX)) {
- return true;
- }
-
- if (depth > 0) {
- Result result = mLayoutLib.getViewParent(viewObject);
- if (result.isSuccess()) {
- Object parent = result.getData();
- if (parent != null) {
- return isWithinIllegalParent(parent, depth -1);
- }
- }
- }
-
- return false;
- }
-
- @Override
- public AdapterBinding getAdapterBinding(final ResourceReference adapterView,
- final Object adapterCookie, final Object viewObject) {
- // Look for user-recorded preference for layout to be used for previews
- if (adapterCookie instanceof UiViewElementNode) {
- UiViewElementNode uiNode = (UiViewElementNode) adapterCookie;
- AdapterBinding binding = LayoutMetadata.getNodeBinding(viewObject, uiNode);
- if (binding != null) {
- return binding;
- }
- } else if (adapterCookie instanceof Map<?,?>) {
- @SuppressWarnings("unchecked")
- Map<String, String> map = (Map<String, String>) adapterCookie;
- AdapterBinding binding = LayoutMetadata.getNodeBinding(viewObject, map);
- if (binding != null) {
- return binding;
- }
- }
-
- if (viewObject == null) {
- return null;
- }
-
- // Is this a ListView or ExpandableListView? If so, return its fully qualified
- // class name, otherwise return null. This is used to filter out other types
- // of AdapterViews (such as Spinners) where we don't want to use the list item
- // binding.
- String listFqcn = getListAdapterViewFqcn(viewObject.getClass());
- if (listFqcn == null) {
- return null;
- }
-
- // Is this ListView nested within an "illegal" container, such as a CalendarView?
- // If so, don't change the bindings below. Some views, such as CalendarView, and
- // potentially some custom views, might be doing specific things with the ListView
- // that could break if we add our own list binding, so for these leave the list
- // alone.
- if (isWithinIllegalParent(viewObject, 2)) {
- return null;
- }
-
- int count = listFqcn.endsWith(GRID_VIEW) ? 24 : 12;
- AdapterBinding binding = new AdapterBinding(count);
- if (listFqcn.endsWith(EXPANDABLE_LIST_VIEW)) {
- binding.addItem(new DataBindingItem(LayoutMetadata.DEFAULT_EXPANDABLE_LIST_ITEM,
- true /* isFramework */, 1));
- } else if (listFqcn.equals(SPINNER)) {
- binding.addItem(new DataBindingItem(LayoutMetadata.DEFAULT_SPINNER_ITEM,
- true /* isFramework */, 1));
- } else {
- binding.addItem(new DataBindingItem(LayoutMetadata.DEFAULT_LIST_ITEM,
- true /* isFramework */, 1));
- }
-
- return binding;
- }
-
- /**
- * Sets the {@link ResourceResolver} to be used when looking up resources
- *
- * @param resolver the resolver to use
- */
- public void setResourceResolver(ResourceResolver resolver) {
- mResourceResolver = resolver;
- }
-
- // Append the given message to the ADT log. Bypass the sandbox if necessary
- // such that we can write to the log file.
- private void appendToIdeLog(Throwable exception, String format, Object ... args) {
- boolean token = RenderSecurityManager.enterSafeRegion(mCredential);
- try {
- AdtPlugin.log(exception, format, args);
- } finally {
- RenderSecurityManager.exitSafeRegion(token);
- }
- }
-
- @Override
- public ActionBarCallback getActionBarCallback() {
- return new ActionBarHandler(mEditor);
- }
-
- @Override
- public boolean supports(int feature) {
- return feature <= Features.LAST_CAPABILITY;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/UiElementPullParser.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/UiElementPullParser.java
deleted file mode 100644
index 858156884..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/UiElementPullParser.java
+++ /dev/null
@@ -1,661 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_LAYOUT;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.ATTR_PADDING;
-import static com.android.SdkConstants.AUTO_URI;
-import static com.android.SdkConstants.UNIT_DIP;
-import static com.android.SdkConstants.UNIT_DP;
-import static com.android.SdkConstants.UNIT_IN;
-import static com.android.SdkConstants.UNIT_MM;
-import static com.android.SdkConstants.UNIT_PT;
-import static com.android.SdkConstants.UNIT_PX;
-import static com.android.SdkConstants.UNIT_SP;
-import static com.android.SdkConstants.VALUE_FILL_PARENT;
-import static com.android.SdkConstants.VALUE_MATCH_PARENT;
-import static com.android.SdkConstants.VIEW_FRAGMENT;
-import static com.android.SdkConstants.VIEW_INCLUDE;
-
-import com.android.ide.common.rendering.api.ILayoutPullParser;
-import com.android.ide.common.rendering.api.ViewInfo;
-import com.android.ide.common.res2.ValueXmlHelper;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.LayoutDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.FragmentMenu;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.resources.Density;
-import com.android.sdklib.IAndroidTarget;
-
-import org.eclipse.core.resources.IProject;
-import org.w3c.dom.Document;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.xmlpull.v1.XmlPullParserException;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Set;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * {@link ILayoutPullParser} implementation on top of {@link UiElementNode}.
- * <p/>
- * It's designed to work on layout files, and will most likely not work on other resource files.
- * <p/>
- * This pull parser generates {@link ViewInfo}s which key is a {@link UiElementNode}.
- */
-public class UiElementPullParser extends BasePullParser {
- private final static Pattern FLOAT_PATTERN = Pattern.compile("(-?[0-9]+(?:\\.[0-9]+)?)(.*)"); //$NON-NLS-1$
-
- private final int[] sIntOut = new int[1];
-
- private final ArrayList<UiElementNode> mNodeStack = new ArrayList<UiElementNode>();
- private UiElementNode mRoot;
- private final boolean mExplodedRendering;
- private boolean mZeroAttributeIsPadding = false;
- private boolean mIncreaseExistingPadding = false;
- private LayoutDescriptors mDescriptors;
- private final Density mDensity;
-
- /**
- * Number of pixels to pad views with in exploded-rendering mode.
- */
- private static final String DEFAULT_PADDING_VALUE =
- ExplodedRenderingHelper.PADDING_VALUE + UNIT_PX;
-
- /**
- * Number of pixels to pad exploded individual views with. (This is HALF the width of the
- * rectangle since padding is repeated on both sides of the empty content.)
- */
- private static final String FIXED_PADDING_VALUE = "20px"; //$NON-NLS-1$
-
- /**
- * Set of nodes that we want to auto-pad using {@link #FIXED_PADDING_VALUE} as the padding
- * attribute value. Can be null, which is the case when we don't want to perform any
- * <b>individual</b> node exploding.
- */
- private final Set<UiElementNode> mExplodeNodes;
-
- /**
- * Constructs a new {@link UiElementPullParser}, a parser dedicated to the special case of
- * parsing a layout resource files, and handling "exploded rendering" - adding padding on views
- * to make them easier to see and operate on.
- *
- * @param top The {@link UiElementNode} for the root node.
- * @param explodeRendering When true, add padding to <b>all</b> nodes in the hierarchy. This
- * will add rather than replace padding of a node.
- * @param explodeNodes A set of individual nodes that should be assigned a fixed amount of
- * padding ({@link #FIXED_PADDING_VALUE}). This is intended for use with nodes that
- * (without padding) would be invisible. This parameter can be null, in which case
- * nodes are not individually exploded (but they may all be exploded with the
- * explodeRendering parameter.
- * @param density the density factor for the screen.
- * @param project Project containing this layout.
- */
- public UiElementPullParser(UiElementNode top, boolean explodeRendering,
- Set<UiElementNode> explodeNodes,
- Density density, IProject project) {
- super();
- mRoot = top;
- mExplodedRendering = explodeRendering;
- mExplodeNodes = explodeNodes;
- mDensity = density;
- if (mExplodedRendering) {
- // get the layout descriptor
- IAndroidTarget target = Sdk.getCurrent().getTarget(project);
- AndroidTargetData data = Sdk.getCurrent().getTargetData(target);
- mDescriptors = data.getLayoutDescriptors();
- }
- push(mRoot);
- }
-
- protected UiElementNode getCurrentNode() {
- if (mNodeStack.size() > 0) {
- return mNodeStack.get(mNodeStack.size()-1);
- }
-
- return null;
- }
-
- private Node getAttribute(int i) {
- if (mParsingState != START_TAG) {
- throw new IndexOutOfBoundsException();
- }
-
- // get the current uiNode
- UiElementNode uiNode = getCurrentNode();
-
- // get its xml node
- Node xmlNode = uiNode.getXmlNode();
-
- if (xmlNode != null) {
- return xmlNode.getAttributes().item(i);
- }
-
- return null;
- }
-
- private void push(UiElementNode node) {
- mNodeStack.add(node);
-
- mZeroAttributeIsPadding = false;
- mIncreaseExistingPadding = false;
-
- if (mExplodedRendering) {
- // first get the node name
- String xml = node.getDescriptor().getXmlLocalName();
- ViewElementDescriptor descriptor = mDescriptors.findDescriptorByTag(xml);
- if (descriptor != null) {
- NamedNodeMap attributes = node.getXmlNode().getAttributes();
- Node padding = attributes.getNamedItemNS(ANDROID_URI, ATTR_PADDING);
- if (padding == null) {
- // we'll return an extra padding
- mZeroAttributeIsPadding = true;
- } else {
- mIncreaseExistingPadding = true;
- }
- }
- }
- }
-
- private UiElementNode pop() {
- return mNodeStack.remove(mNodeStack.size()-1);
- }
-
- // ------------- IXmlPullParser --------
-
- /**
- * {@inheritDoc}
- * <p/>
- * This implementation returns the underlying DOM node of type {@link UiElementNode}.
- * Note that the link between the GLE and the parsing code depends on this being the actual
- * type returned, so you can't just randomly change it here.
- * <p/>
- * Currently used by:
- * - private method GraphicalLayoutEditor#updateNodeWithBounds(ILayoutViewInfo).
- * - private constructor of LayoutCanvas.CanvasViewInfo.
- */
- @Override
- public Object getViewCookie() {
- return getCurrentNode();
- }
-
- /**
- * Legacy method required by {@link com.android.layoutlib.api.IXmlPullParser}
- */
- @Override
- public Object getViewKey() {
- return getViewCookie();
- }
-
- /**
- * This implementation does nothing for now as all the embedded XML will use a normal KXML
- * parser.
- */
- @Override
- public ILayoutPullParser getParser(String layoutName) {
- return null;
- }
-
- // ------------- XmlPullParser --------
-
- @Override
- public String getPositionDescription() {
- return "XML DOM element depth:" + mNodeStack.size();
- }
-
- /*
- * This does not seem to be called by the layoutlib, but we keep this (and maintain
- * it) just in case.
- */
- @Override
- public int getAttributeCount() {
- UiElementNode node = getCurrentNode();
-
- if (node != null) {
- Collection<UiAttributeNode> attributes = node.getAllUiAttributes();
- int count = attributes.size();
-
- return count + (mZeroAttributeIsPadding ? 1 : 0);
- }
-
- return 0;
- }
-
- /*
- * This does not seem to be called by the layoutlib, but we keep this (and maintain
- * it) just in case.
- */
- @Override
- public String getAttributeName(int i) {
- if (mZeroAttributeIsPadding) {
- if (i == 0) {
- return ATTR_PADDING;
- } else {
- i--;
- }
- }
-
- Node attribute = getAttribute(i);
- if (attribute != null) {
- return attribute.getLocalName();
- }
-
- return null;
- }
-
- /*
- * This does not seem to be called by the layoutlib, but we keep this (and maintain
- * it) just in case.
- */
- @Override
- public String getAttributeNamespace(int i) {
- if (mZeroAttributeIsPadding) {
- if (i == 0) {
- return ANDROID_URI;
- } else {
- i--;
- }
- }
-
- Node attribute = getAttribute(i);
- if (attribute != null) {
- return attribute.getNamespaceURI();
- }
- return ""; //$NON-NLS-1$
- }
-
- /*
- * This does not seem to be called by the layoutlib, but we keep this (and maintain
- * it) just in case.
- */
- @Override
- public String getAttributePrefix(int i) {
- if (mZeroAttributeIsPadding) {
- if (i == 0) {
- // figure out the prefix associated with the android namespace.
- Document doc = mRoot.getXmlDocument();
- return doc.lookupPrefix(ANDROID_URI);
- } else {
- i--;
- }
- }
-
- Node attribute = getAttribute(i);
- if (attribute != null) {
- return attribute.getPrefix();
- }
- return null;
- }
-
- /*
- * This does not seem to be called by the layoutlib, but we keep this (and maintain
- * it) just in case.
- */
- @Override
- public String getAttributeValue(int i) {
- if (mZeroAttributeIsPadding) {
- if (i == 0) {
- return DEFAULT_PADDING_VALUE;
- } else {
- i--;
- }
- }
-
- Node attribute = getAttribute(i);
- if (attribute != null) {
- String value = attribute.getNodeValue();
- if (mIncreaseExistingPadding && ATTR_PADDING.equals(attribute.getLocalName()) &&
- ANDROID_URI.equals(attribute.getNamespaceURI())) {
- // add the padding and return the value
- return addPaddingToValue(value);
- }
- return value;
- }
-
- return null;
- }
-
- /*
- * This is the main method used by the LayoutInflater to query for attributes.
- */
- @Override
- public String getAttributeValue(String namespace, String localName) {
- if (mExplodeNodes != null && ATTR_PADDING.equals(localName) &&
- ANDROID_URI.equals(namespace)) {
- UiElementNode node = getCurrentNode();
- if (node != null && mExplodeNodes.contains(node)) {
- return FIXED_PADDING_VALUE;
- }
- }
-
- if (mZeroAttributeIsPadding && ATTR_PADDING.equals(localName) &&
- ANDROID_URI.equals(namespace)) {
- return DEFAULT_PADDING_VALUE;
- }
-
- // get the current uiNode
- UiElementNode uiNode = getCurrentNode();
-
- // get its xml node
- Node xmlNode = uiNode.getXmlNode();
-
- if (xmlNode != null) {
- if (ATTR_LAYOUT.equals(localName) && VIEW_FRAGMENT.equals(xmlNode.getNodeName())) {
- String layout = FragmentMenu.getFragmentLayout(xmlNode);
- if (layout != null) {
- return layout;
- }
- }
-
- Node attribute = xmlNode.getAttributes().getNamedItemNS(namespace, localName);
-
- // Auto-convert http://schemas.android.com/apk/res-auto resources. The lookup
- // will be for the current application's resource package, e.g.
- // http://schemas.android.com/apk/res/foo.bar, but the XML document will
- // be using http://schemas.android.com/apk/res-auto in library projects:
- if (attribute == null && namespace != null && !namespace.equals(ANDROID_URI)) {
- attribute = xmlNode.getAttributes().getNamedItemNS(AUTO_URI, localName);
- }
-
- if (attribute != null) {
- String value = attribute.getNodeValue();
- if (mIncreaseExistingPadding && ATTR_PADDING.equals(localName) &&
- ANDROID_URI.equals(namespace)) {
- // add the padding and return the value
- return addPaddingToValue(value);
- }
-
- // on the fly convert match_parent to fill_parent for compatibility with older
- // platforms.
- if (VALUE_MATCH_PARENT.equals(value) &&
- (ATTR_LAYOUT_WIDTH.equals(localName) ||
- ATTR_LAYOUT_HEIGHT.equals(localName)) &&
- ANDROID_URI.equals(namespace)) {
- return VALUE_FILL_PARENT;
- }
-
- // Handle unicode escapes etc
- value = ValueXmlHelper.unescapeResourceString(value, false, false);
-
- return value;
- }
- }
-
- return null;
- }
-
- @Override
- public int getDepth() {
- return mNodeStack.size();
- }
-
- @Override
- public String getName() {
- if (mParsingState == START_TAG || mParsingState == END_TAG) {
- String name = getCurrentNode().getDescriptor().getXmlLocalName();
-
- if (name.equals(VIEW_FRAGMENT)) {
- // Temporarily translate <fragment> to <include> (and in getAttribute
- // we will also provide a layout-attribute for the corresponding
- // fragment name attribute)
- String layout = FragmentMenu.getFragmentLayout(getCurrentNode().getXmlNode());
- if (layout != null) {
- return VIEW_INCLUDE;
- }
- }
-
- return name;
- }
-
- return null;
- }
-
- @Override
- public String getNamespace() {
- if (mParsingState == START_TAG || mParsingState == END_TAG) {
- return getCurrentNode().getDescriptor().getNamespace();
- }
-
- return null;
- }
-
- @Override
- public String getPrefix() {
- if (mParsingState == START_TAG || mParsingState == END_TAG) {
- Document doc = mRoot.getXmlDocument();
- return doc.lookupPrefix(getCurrentNode().getDescriptor().getNamespace());
- }
-
- return null;
- }
-
- @Override
- public boolean isEmptyElementTag() throws XmlPullParserException {
- if (mParsingState == START_TAG) {
- return getCurrentNode().getUiChildren().size() == 0;
- }
-
- throw new XmlPullParserException("Call to isEmptyElementTag while not in START_TAG",
- this, null);
- }
-
- @Override
- public void onNextFromStartDocument() {
- onNextFromStartTag();
- }
-
- @Override
- public void onNextFromStartTag() {
- // get the current node, and look for text or children (children first)
- UiElementNode node = getCurrentNode();
- List<UiElementNode> children = node.getUiChildren();
- if (children.size() > 0) {
- // move to the new child, and don't change the state.
- push(children.get(0));
-
- // in case the current state is CURRENT_DOC, we set the proper state.
- mParsingState = START_TAG;
- } else {
- if (mParsingState == START_DOCUMENT) {
- // this handles the case where there's no node.
- mParsingState = END_DOCUMENT;
- } else {
- mParsingState = END_TAG;
- }
- }
- }
-
- @Override
- public void onNextFromEndTag() {
- // look for a sibling. if no sibling, go back to the parent
- UiElementNode node = getCurrentNode();
- node = node.getUiNextSibling();
- if (node != null) {
- // to go to the sibling, we need to remove the current node,
- pop();
- // and add its sibling.
- push(node);
- mParsingState = START_TAG;
- } else {
- // move back to the parent
- pop();
-
- // we have only one element left (mRoot), then we're done with the document.
- if (mNodeStack.size() == 1) {
- mParsingState = END_DOCUMENT;
- } else {
- mParsingState = END_TAG;
- }
- }
- }
-
- // ------- TypedValue stuff
- // This is adapted from com.android.layoutlib.bridge.ResourceHelper
- // (but modified to directly take the parsed value and convert it into pixel instead of
- // storing it into a TypedValue)
- // this was originally taken from platform/frameworks/base/libs/utils/ResourceTypes.cpp
-
- private static final class DimensionEntry {
- String name;
- int type;
-
- DimensionEntry(String name, int unit) {
- this.name = name;
- this.type = unit;
- }
- }
-
- /** {@link DimensionEntry} complex unit: Value is raw pixels. */
- private static final int COMPLEX_UNIT_PX = 0;
- /** {@link DimensionEntry} complex unit: Value is Device Independent
- * Pixels. */
- private static final int COMPLEX_UNIT_DIP = 1;
- /** {@link DimensionEntry} complex unit: Value is a scaled pixel. */
- private static final int COMPLEX_UNIT_SP = 2;
- /** {@link DimensionEntry} complex unit: Value is in points. */
- private static final int COMPLEX_UNIT_PT = 3;
- /** {@link DimensionEntry} complex unit: Value is in inches. */
- private static final int COMPLEX_UNIT_IN = 4;
- /** {@link DimensionEntry} complex unit: Value is in millimeters. */
- private static final int COMPLEX_UNIT_MM = 5;
-
- private final static DimensionEntry[] sDimensions = new DimensionEntry[] {
- new DimensionEntry(UNIT_PX, COMPLEX_UNIT_PX),
- new DimensionEntry(UNIT_DIP, COMPLEX_UNIT_DIP),
- new DimensionEntry(UNIT_DP, COMPLEX_UNIT_DIP),
- new DimensionEntry(UNIT_SP, COMPLEX_UNIT_SP),
- new DimensionEntry(UNIT_PT, COMPLEX_UNIT_PT),
- new DimensionEntry(UNIT_IN, COMPLEX_UNIT_IN),
- new DimensionEntry(UNIT_MM, COMPLEX_UNIT_MM),
- };
-
- /**
- * Adds padding to an existing dimension.
- * <p/>This will resolve the attribute value (which can be px, dip, dp, sp, pt, in, mm) to
- * a pixel value, add the padding value ({@link ExplodedRenderingHelper#PADDING_VALUE}),
- * and then return a string with the new value as a px string ("42px");
- * If the conversion fails, only the special padding is returned.
- */
- private String addPaddingToValue(String s) {
- int padding = ExplodedRenderingHelper.PADDING_VALUE;
- if (stringToPixel(s)) {
- padding += sIntOut[0];
- }
-
- return padding + UNIT_PX;
- }
-
- /**
- * Convert the string into a pixel value, and puts it in {@link #sIntOut}
- * @param s the dimension value from an XML attribute
- * @return true if success.
- */
- private boolean stringToPixel(String s) {
- // remove the space before and after
- s = s.trim();
- int len = s.length();
-
- if (len <= 0) {
- return false;
- }
-
- // check that there's no non ASCII characters.
- char[] buf = s.toCharArray();
- for (int i = 0 ; i < len ; i++) {
- if (buf[i] > 255) {
- return false;
- }
- }
-
- // check the first character
- if (buf[0] < '0' && buf[0] > '9' && buf[0] != '.') {
- return false;
- }
-
- // now look for the string that is after the float...
- Matcher m = FLOAT_PATTERN.matcher(s);
- if (m.matches()) {
- String f_str = m.group(1);
- String end = m.group(2);
-
- float f;
- try {
- f = Float.parseFloat(f_str);
- } catch (NumberFormatException e) {
- // this shouldn't happen with the regexp above.
- return false;
- }
-
- if (end.length() > 0 && end.charAt(0) != ' ') {
- // We only support dimension-type values, so try to parse the unit for dimension
- DimensionEntry dimension = parseDimension(end);
- if (dimension != null) {
- // convert the value into pixel based on the dimention type
- // This is similar to TypedValue.applyDimension()
- switch (dimension.type) {
- case COMPLEX_UNIT_PX:
- // do nothing, value is already in px
- break;
- case COMPLEX_UNIT_DIP:
- case COMPLEX_UNIT_SP: // intended fall-through since we don't
- // adjust for font size
- f *= (float)mDensity.getDpiValue() / Density.DEFAULT_DENSITY;
- break;
- case COMPLEX_UNIT_PT:
- f *= mDensity.getDpiValue() * (1.0f / 72);
- break;
- case COMPLEX_UNIT_IN:
- f *= mDensity.getDpiValue();
- break;
- case COMPLEX_UNIT_MM:
- f *= mDensity.getDpiValue() * (1.0f / 25.4f);
- break;
- }
-
- // store result (converted to int)
- sIntOut[0] = (int) (f + 0.5);
-
- return true;
- }
- }
- }
-
- return false;
- }
-
- private static DimensionEntry parseDimension(String str) {
- str = str.trim();
-
- for (DimensionEntry d : sDimensions) {
- if (d.name.equals(str)) {
- return d;
- }
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/WidgetPullParser.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/WidgetPullParser.java
deleted file mode 100644
index dce2ccbf1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/WidgetPullParser.java
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout;
-
-import com.android.SdkConstants;
-import com.android.ide.common.rendering.api.ILayoutPullParser;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.layoutlib.api.ILayoutResult.ILayoutViewInfo;
-
-import org.xmlpull.v1.XmlPullParserException;
-
-/**
- * {@link ILayoutPullParser} implementation to render android widget bitmap.
- * <p/>
- * The parser emulates a layout that contains just one widget, described by the
- * {@link ViewElementDescriptor} passed in the constructor.
- * <p/>
- * This pull parser generates {@link ILayoutViewInfo}s which key is a {@link ViewElementDescriptor}.
- */
-public class WidgetPullParser extends BasePullParser {
-
- private final ViewElementDescriptor mDescriptor;
- private String[][] mAttributes = new String[][] {
- { "text", null },
- { "layout_width", "wrap_content" },
- { "layout_height", "wrap_content" },
- };
-
- public WidgetPullParser(ViewElementDescriptor descriptor) {
- mDescriptor = descriptor;
-
- String[] segments = mDescriptor.getFullClassName().split(AdtConstants.RE_DOT);
- mAttributes[0][1] = segments[segments.length-1];
- }
-
- @Override
- public Object getViewCookie() {
- // we need a viewKey or the ILayoutResult will not contain any ILayoutViewInfo
- return mDescriptor;
- }
-
- /**
- * Legacy method required by {@link com.android.layoutlib.api.IXmlPullParser}
- */
- @Override
- public Object getViewKey() {
- return getViewCookie();
- }
-
- @Override
- public ILayoutPullParser getParser(String layoutName) {
- // there's no embedded layout for a single widget.
- return null;
- }
-
- @Override
- public int getAttributeCount() {
- return mAttributes.length; // text attribute
- }
-
- @Override
- public String getAttributeName(int index) {
- if (index < mAttributes.length) {
- return mAttributes[index][0];
- }
-
- return null;
- }
-
- @Override
- public String getAttributeNamespace(int index) {
- return SdkConstants.NS_RESOURCES;
- }
-
- @Override
- public String getAttributePrefix(int index) {
- // pass
- return null;
- }
-
- @Override
- public String getAttributeValue(int index) {
- if (index < mAttributes.length) {
- return mAttributes[index][1];
- }
-
- return null;
- }
-
- @Override
- public String getAttributeValue(String ns, String name) {
- if (SdkConstants.NS_RESOURCES.equals(ns)) {
- for (String[] attribute : mAttributes) {
- if (name.equals(attribute[0])) {
- return attribute[1];
- }
- }
- }
-
- return null;
- }
-
- @Override
- public int getDepth() {
- // pass
- return 0;
- }
-
- @Override
- public String getName() {
- return mDescriptor.getXmlLocalName();
- }
-
- @Override
- public String getNamespace() {
- // pass
- return null;
- }
-
- @Override
- public String getPositionDescription() {
- // pass
- return null;
- }
-
- @Override
- public String getPrefix() {
- // pass
- return null;
- }
-
- @Override
- public boolean isEmptyElementTag() throws XmlPullParserException {
- if (mParsingState == START_TAG) {
- return true;
- }
-
- throw new XmlPullParserException("Call to isEmptyElementTag while not in START_TAG",
- this, null);
- }
-
- @Override
- public void onNextFromStartDocument() {
- // just go to start_tag
- mParsingState = START_TAG;
- }
-
- @Override
- public void onNextFromStartTag() {
- // since we have no children, just go to end_tag
- mParsingState = END_TAG;
- }
-
- @Override
- public void onNextFromEndTag() {
- // just one tag. we are done.
- mParsingState = END_DOCUMENT;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ActivityMenuListener.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ActivityMenuListener.java
deleted file mode 100644
index 36cd0fbbb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ActivityMenuListener.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.configuration;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.ide.eclipse.adt.internal.resources.ResourceHelper;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jdt.ui.ISharedImages;
-import org.eclipse.jdt.ui.JavaUI;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MenuItem;
-import org.eclipse.swt.widgets.ToolItem;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * The {@linkplain ActivityMenuListener} class is responsible for
- * generating the activity menu in the {@link ConfigurationChooser}.
- */
-class ActivityMenuListener extends SelectionAdapter {
- private static final int ACTION_OPEN_ACTIVITY = 1;
- private static final int ACTION_SELECT_ACTIVITY = 2;
-
- private final ConfigurationChooser mConfigChooser;
- private final int mAction;
- private final String mFqcn;
-
- ActivityMenuListener(
- @NonNull ConfigurationChooser configChooser,
- int action,
- @Nullable String fqcn) {
- mConfigChooser = configChooser;
- mAction = action;
- mFqcn = fqcn;
- }
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- switch (mAction) {
- case ACTION_OPEN_ACTIVITY: {
- Configuration configuration = mConfigChooser.getConfiguration();
- String fqcn = configuration.getActivity();
- AdtPlugin.openJavaClass(mConfigChooser.getProject(), fqcn);
- break;
- }
- case ACTION_SELECT_ACTIVITY: {
- mConfigChooser.selectActivity(mFqcn);
- mConfigChooser.onSelectActivity();
- break;
- }
- default: assert false : mAction;
- }
- }
-
- static void show(ConfigurationChooser chooser, ToolItem combo) {
- // TODO: Allow using fragments here as well?
- Menu menu = new Menu(chooser.getShell(), SWT.POP_UP);
- ISharedImages sharedImages = JavaUI.getSharedImages();
- Configuration configuration = chooser.getConfiguration();
- String current = configuration.getActivity();
-
- if (current != null) {
- MenuItem item = new MenuItem(menu, SWT.PUSH);
- String label = ConfigurationChooser.getActivityLabel(current, true);
- item.setText( String.format("Open %1$s...", label));
- Image image = sharedImages.getImage(ISharedImages.IMG_OBJS_CUNIT);
- item.setImage(image);
- item.addSelectionListener(
- new ActivityMenuListener(chooser, ACTION_OPEN_ACTIVITY, null));
-
- @SuppressWarnings("unused")
- MenuItem separator = new MenuItem(menu, SWT.SEPARATOR);
- }
-
- IProject project = chooser.getProject();
- Image image = sharedImages.getImage(ISharedImages.IMG_OBJS_CLASS);
-
- // Add activities found to be relevant to this layout
- String layoutName = ResourceHelper.getLayoutName(chooser.getEditedFile());
- String pkg = ManifestInfo.get(project).getPackage();
- List<String> preferred = ManifestInfo.guessActivities(project, layoutName, pkg);
- current = addActivities(chooser, menu, current, image, preferred);
-
- // Add all activities
- List<String> activities = ManifestInfo.getProjectActivities(project);
- if (preferred.size() > 0) {
- // Filter out the activities we've already listed above
- List<String> filtered = new ArrayList<String>(activities.size());
- Set<String> remove = new HashSet<String>(preferred);
- for (String fqcn : activities) {
- if (!remove.contains(fqcn)) {
- filtered.add(fqcn);
- }
- }
- activities = filtered;
- }
-
- if (activities.size() > 0) {
- if (preferred.size() > 0) {
- @SuppressWarnings("unused")
- MenuItem separator = new MenuItem(menu, SWT.SEPARATOR);
- }
-
- addActivities(chooser, menu, current, image, activities);
- }
-
- Rectangle bounds = combo.getBounds();
- Point location = new Point(bounds.x, bounds.y + bounds.height);
- location = combo.getParent().toDisplay(location);
- menu.setLocation(location.x, location.y);
- menu.setVisible(true);
- }
-
- private static String addActivities(ConfigurationChooser chooser, Menu menu, String current,
- Image image, List<String> activities) {
- for (final String fqcn : activities) {
- String title = ConfigurationChooser.getActivityLabel(fqcn, false);
- MenuItem item = new MenuItem(menu, SWT.CHECK);
- item.setText(title);
- item.setImage(image);
-
- boolean selected = title.equals(current);
- if (selected) {
- item.setSelection(true);
- current = null; // Only show the first occurrence as selected
- // such that we don't show it selected again in the full activity list
- }
-
- item.addSelectionListener(new ActivityMenuListener(chooser,
- ACTION_SELECT_ACTIVITY, fqcn));
- }
-
- return current;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/Configuration.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/Configuration.java
deleted file mode 100644
index c4253cddf..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/Configuration.java
+++ /dev/null
@@ -1,1091 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.configuration;
-
-import static com.android.SdkConstants.ANDROID_STYLE_RESOURCE_PREFIX;
-import static com.android.SdkConstants.PREFIX_RESOURCE_REF;
-import static com.android.SdkConstants.STYLE_RESOURCE_PREFIX;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.rendering.LayoutLibrary;
-import com.android.ide.common.rendering.api.Capability;
-import com.android.ide.common.resources.ResourceFolder;
-import com.android.ide.common.resources.ResourceRepository;
-import com.android.ide.common.resources.configuration.DensityQualifier;
-import com.android.ide.common.resources.configuration.DeviceConfigHelper;
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.common.resources.configuration.LayoutDirectionQualifier;
-import com.android.ide.common.resources.configuration.LocaleQualifier;
-import com.android.ide.common.resources.configuration.NightModeQualifier;
-import com.android.ide.common.resources.configuration.ScreenSizeQualifier;
-import com.android.ide.common.resources.configuration.UiModeQualifier;
-import com.android.ide.common.resources.configuration.VersionQualifier;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderService;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo.ActivityAttributes;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.resources.ResourceHelper;
-import com.android.ide.eclipse.adt.internal.resources.manager.ProjectResources;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.resources.Density;
-import com.android.resources.LayoutDirection;
-import com.android.resources.NightMode;
-import com.android.resources.ScreenSize;
-import com.android.resources.UiMode;
-import com.android.sdklib.AndroidVersion;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.devices.Device;
-import com.android.sdklib.devices.State;
-import com.android.utils.Pair;
-import com.google.common.base.Objects;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.QualifiedName;
-
-import java.util.List;
-
-/**
- * A {@linkplain Configuration} is a selection of device, orientation, theme,
- * etc for use when rendering a layout.
- */
-public class Configuration {
- /** The {@link FolderConfiguration} in change flags or override flags */
- public static final int CFG_FOLDER = 1 << 0;
- /** The {@link Device} in change flags or override flags */
- public static final int CFG_DEVICE = 1 << 1;
- /** The {@link State} in change flags or override flags */
- public static final int CFG_DEVICE_STATE = 1 << 2;
- /** The theme in change flags or override flags */
- public static final int CFG_THEME = 1 << 3;
- /** The locale in change flags or override flags */
- public static final int CFG_LOCALE = 1 << 4;
- /** The rendering {@link IAndroidTarget} in change flags or override flags */
- public static final int CFG_TARGET = 1 << 5;
- /** The {@link NightMode} in change flags or override flags */
- public static final int CFG_NIGHT_MODE = 1 << 6;
- /** The {@link UiMode} in change flags or override flags */
- public static final int CFG_UI_MODE = 1 << 7;
- /** The {@link UiMode} in change flags or override flags */
- public static final int CFG_ACTIVITY = 1 << 8;
-
- /** References all attributes */
- public static final int MASK_ALL = 0xFFFF;
-
- /** Attributes which affect which best-layout-file selection */
- public static final int MASK_FILE_ATTRS =
- CFG_DEVICE|CFG_DEVICE_STATE|CFG_LOCALE|CFG_TARGET|CFG_NIGHT_MODE|CFG_UI_MODE;
-
- /** Attributes which affect rendering appearance */
- public static final int MASK_RENDERING = MASK_FILE_ATTRS|CFG_THEME;
-
- /**
- * Setting name for project-wide setting controlling rendering target and locale which
- * is shared for all files
- */
- public final static QualifiedName NAME_RENDER_STATE =
- new QualifiedName(AdtPlugin.PLUGIN_ID, "render"); //$NON-NLS-1$
-
- private final static String MARKER_FRAMEWORK = "-"; //$NON-NLS-1$
- private final static String MARKER_PROJECT = "+"; //$NON-NLS-1$
- private final static String SEP = ":"; //$NON-NLS-1$
- private final static String SEP_LOCALE = "-"; //$NON-NLS-1$
-
- @NonNull
- protected ConfigurationChooser mConfigChooser;
-
- /** The {@link FolderConfiguration} representing the state of the UI controls */
- @NonNull
- protected final FolderConfiguration mFullConfig = new FolderConfiguration();
-
- /** The {@link FolderConfiguration} being edited. */
- @Nullable
- protected FolderConfiguration mEditedConfig;
-
- /** The target of the project of the file being edited. */
- @Nullable
- private IAndroidTarget mTarget;
-
- /** The theme style to render with */
- @Nullable
- private String mTheme;
-
- /** The device to render with */
- @Nullable
- private Device mDevice;
-
- /** The device state */
- @Nullable
- private State mState;
-
- /**
- * The activity associated with the layout. This is just a cached value of
- * the true value stored on the layout.
- */
- @Nullable
- private String mActivity;
-
- /** The locale to use for this configuration */
- @NonNull
- private Locale mLocale = Locale.ANY;
-
- /** UI mode */
- @NonNull
- private UiMode mUiMode = UiMode.NORMAL;
-
- /** Night mode */
- @NonNull
- private NightMode mNightMode = NightMode.NOTNIGHT;
-
- /** The display name */
- private String mDisplayName;
-
- /**
- * Creates a new {@linkplain Configuration}
- *
- * @param chooser the associated chooser
- */
- protected Configuration(@NonNull ConfigurationChooser chooser) {
- mConfigChooser = chooser;
- }
-
- /**
- * Sets the associated configuration chooser
- *
- * @param chooser the chooser
- */
- void setChooser(@NonNull ConfigurationChooser chooser) {
- // TODO: We should get rid of the binding between configurations
- // and configuration choosers. This is currently needed because
- // the choosers contain vital data such as the set of available
- // rendering targets, the set of available locales etc, which
- // also doesn't belong inside the configuration but is needed by it.
- mConfigChooser = chooser;
- }
-
- /**
- * Gets the associated configuration chooser
- *
- * @return the chooser
- */
- @NonNull
- ConfigurationChooser getChooser() {
- return mConfigChooser;
- }
-
- /**
- * Creates a new {@linkplain Configuration}
- *
- * @param chooser the associated chooser
- * @return a new configuration
- */
- @NonNull
- public static Configuration create(@NonNull ConfigurationChooser chooser) {
- return new Configuration(chooser);
- }
-
- /**
- * Creates a configuration suitable for the given file
- *
- * @param base the base configuration to base the file configuration off of
- * @param file the file to look up a configuration for
- * @return a suitable configuration
- */
- @NonNull
- public static Configuration create(
- @NonNull Configuration base,
- @NonNull IFile file) {
- Configuration configuration = copy(base);
- ConfigurationChooser chooser = base.getChooser();
- ProjectResources resources = chooser.getResources();
- ConfigurationMatcher matcher = new ConfigurationMatcher(chooser, configuration, file,
- resources, false);
-
- ResourceFolder resFolder = ResourceManager.getInstance().getResourceFolder(file);
- configuration.mEditedConfig = new FolderConfiguration();
- configuration.mEditedConfig.set(resFolder.getConfiguration());
-
- matcher.adaptConfigSelection(true /*needBestMatch*/);
- configuration.syncFolderConfig();
-
- return configuration;
- }
-
- /**
- * Creates a new {@linkplain Configuration} that is a copy from a different configuration
- *
- * @param original the original to copy from
- * @return a new configuration copied from the original
- */
- @NonNull
- public static Configuration copy(@NonNull Configuration original) {
- Configuration copy = create(original.mConfigChooser);
- copy.mFullConfig.set(original.mFullConfig);
- if (original.mEditedConfig != null) {
- copy.mEditedConfig = new FolderConfiguration();
- copy.mEditedConfig.set(original.mEditedConfig);
- }
- copy.mTarget = original.getTarget();
- copy.mTheme = original.getTheme();
- copy.mDevice = original.getDevice();
- copy.mState = original.getDeviceState();
- copy.mActivity = original.getActivity();
- copy.mLocale = original.getLocale();
- copy.mUiMode = original.getUiMode();
- copy.mNightMode = original.getNightMode();
- copy.mDisplayName = original.getDisplayName();
-
- return copy;
- }
-
- /**
- * Returns the associated activity
- *
- * @return the activity
- */
- @Nullable
- public String getActivity() {
- return mActivity;
- }
-
- /**
- * Returns the chosen device.
- *
- * @return the chosen device
- */
- @Nullable
- public Device getDevice() {
- return mDevice;
- }
-
- /**
- * Returns the chosen device state
- *
- * @return the device state
- */
- @Nullable
- public State getDeviceState() {
- return mState;
- }
-
- /**
- * Returns the chosen locale
- *
- * @return the locale
- */
- @NonNull
- public Locale getLocale() {
- return mLocale;
- }
-
- /**
- * Returns the UI mode
- *
- * @return the UI mode
- */
- @NonNull
- public UiMode getUiMode() {
- return mUiMode;
- }
-
- /**
- * Returns the day/night mode
- *
- * @return the night mode
- */
- @NonNull
- public NightMode getNightMode() {
- return mNightMode;
- }
-
- /**
- * Returns the current theme style
- *
- * @return the theme style
- */
- @Nullable
- public String getTheme() {
- return mTheme;
- }
-
- /**
- * Returns the rendering target
- *
- * @return the target
- */
- @Nullable
- public IAndroidTarget getTarget() {
- return mTarget;
- }
-
- /**
- * Returns the display name to show for this configuration
- *
- * @return the display name, or null if none has been assigned
- */
- @Nullable
- public String getDisplayName() {
- return mDisplayName;
- }
-
- /**
- * Returns whether the configuration's theme is a project theme.
- * <p/>
- * The returned value is meaningless if {@link #getTheme()} returns
- * <code>null</code>.
- *
- * @return true for project a theme, false for a framework theme
- */
- public boolean isProjectTheme() {
- String theme = getTheme();
- if (theme != null) {
- assert theme.startsWith(STYLE_RESOURCE_PREFIX)
- || theme.startsWith(ANDROID_STYLE_RESOURCE_PREFIX);
-
- return ResourceHelper.isProjectStyle(theme);
- }
-
- return false;
- }
-
- /**
- * Returns true if the current layout is locale-specific
- *
- * @return if this configuration represents a locale-specific layout
- */
- public boolean isLocaleSpecificLayout() {
- return mEditedConfig == null || mEditedConfig.getLocaleQualifier() != null;
- }
-
- /**
- * Returns the full, complete {@link FolderConfiguration}
- *
- * @return the full configuration
- */
- @NonNull
- public FolderConfiguration getFullConfig() {
- return mFullConfig;
- }
-
- /**
- * Copies the full, complete {@link FolderConfiguration} into the given
- * folder config instance.
- *
- * @param dest the {@link FolderConfiguration} instance to copy into
- */
- public void copyFullConfig(FolderConfiguration dest) {
- dest.set(mFullConfig);
- }
-
- /**
- * Returns the edited {@link FolderConfiguration} (this is not a full
- * configuration, so you can think of it as the "constraints" used by the
- * {@link ConfigurationMatcher} to produce a full configuration.
- *
- * @return the constraints configuration
- */
- @NonNull
- public FolderConfiguration getEditedConfig() {
- return mEditedConfig;
- }
-
- /**
- * Sets the edited {@link FolderConfiguration} (this is not a full
- * configuration, so you can think of it as the "constraints" used by the
- * {@link ConfigurationMatcher} to produce a full configuration.
- *
- * @param editedConfig the constraints configuration
- */
- public void setEditedConfig(@NonNull FolderConfiguration editedConfig) {
- mEditedConfig = editedConfig;
- }
-
- /**
- * Sets the associated activity
- *
- * @param activity the activity
- */
- public void setActivity(String activity) {
- mActivity = activity;
- }
-
- /**
- * Sets the device
- *
- * @param device the device
- * @param skipSync if true, don't sync folder configuration (typically because
- * you are going to set other configuration parameters and you'll call
- * {@link #syncFolderConfig()} once at the end)
- */
- public void setDevice(Device device, boolean skipSync) {
- mDevice = device;
-
- if (!skipSync) {
- syncFolderConfig();
- }
- }
-
- /**
- * Sets the device state
- *
- * @param state the device state
- * @param skipSync if true, don't sync folder configuration (typically because
- * you are going to set other configuration parameters and you'll call
- * {@link #syncFolderConfig()} once at the end)
- */
- public void setDeviceState(State state, boolean skipSync) {
- mState = state;
-
- if (!skipSync) {
- syncFolderConfig();
- }
- }
-
- /**
- * Sets the locale
- *
- * @param locale the locale
- * @param skipSync if true, don't sync folder configuration (typically because
- * you are going to set other configuration parameters and you'll call
- * {@link #syncFolderConfig()} once at the end)
- */
- public void setLocale(@NonNull Locale locale, boolean skipSync) {
- mLocale = locale;
-
- if (!skipSync) {
- syncFolderConfig();
- }
- }
-
- /**
- * Sets the rendering target
- *
- * @param target rendering target
- * @param skipSync if true, don't sync folder configuration (typically because
- * you are going to set other configuration parameters and you'll call
- * {@link #syncFolderConfig()} once at the end)
- */
- public void setTarget(IAndroidTarget target, boolean skipSync) {
- mTarget = target;
-
- if (!skipSync) {
- syncFolderConfig();
- }
- }
-
- /**
- * Sets the display name to be shown for this configuration.
- *
- * @param displayName the new display name
- */
- public void setDisplayName(@Nullable String displayName) {
- mDisplayName = displayName;
- }
-
- /**
- * Sets the night mode
- *
- * @param night the night mode
- * @param skipSync if true, don't sync folder configuration (typically because
- * you are going to set other configuration parameters and you'll call
- * {@link #syncFolderConfig()} once at the end)
- */
- public void setNightMode(@NonNull NightMode night, boolean skipSync) {
- mNightMode = night;
-
- if (!skipSync) {
- syncFolderConfig();
- }
- }
-
- /**
- * Sets the UI mode
- *
- * @param uiMode the UI mode
- * @param skipSync if true, don't sync folder configuration (typically because
- * you are going to set other configuration parameters and you'll call
- * {@link #syncFolderConfig()} once at the end)
- */
- public void setUiMode(@NonNull UiMode uiMode, boolean skipSync) {
- mUiMode = uiMode;
-
- if (!skipSync) {
- syncFolderConfig();
- }
- }
-
- /**
- * Sets the theme style
- *
- * @param theme the theme
- */
- public void setTheme(String theme) {
- mTheme = theme;
- checkThemePrefix();
- }
-
- /**
- * Updates the folder configuration such that it reflects changes in
- * configuration state such as the device orientation, the UI mode, the
- * rendering target, etc.
- */
- public void syncFolderConfig() {
- Device device = getDevice();
- if (device == null) {
- return;
- }
-
- // get the device config from the device/state combos.
- FolderConfiguration config = DeviceConfigHelper.getFolderConfig(getDeviceState());
-
- // replace the config with the one from the device
- mFullConfig.set(config);
-
- // sync the selected locale
- Locale locale = getLocale();
- mFullConfig.setLocaleQualifier(locale.qualifier);
- if (!locale.hasLanguage()) {
- // Avoid getting the layout library if the locale doesn't have any language.
- mFullConfig.setLayoutDirectionQualifier(
- new LayoutDirectionQualifier(LayoutDirection.LTR));
- } else {
- Sdk currentSdk = Sdk.getCurrent();
- if (currentSdk != null) {
- AndroidTargetData targetData = currentSdk.getTargetData(getTarget());
- if (targetData != null) {
- LayoutLibrary layoutLib = targetData.getLayoutLibrary();
- if (layoutLib != null) {
- if (layoutLib.isRtl(locale.toLocaleId())) {
- mFullConfig.setLayoutDirectionQualifier(
- new LayoutDirectionQualifier(LayoutDirection.RTL));
- } else {
- mFullConfig.setLayoutDirectionQualifier(
- new LayoutDirectionQualifier(LayoutDirection.LTR));
- }
- }
- }
- }
- }
-
- // Replace the UiMode with the selected one, if one is selected
- UiMode uiMode = getUiMode();
- if (uiMode != null) {
- mFullConfig.setUiModeQualifier(new UiModeQualifier(uiMode));
- }
-
- // Replace the NightMode with the selected one, if one is selected
- NightMode nightMode = getNightMode();
- if (nightMode != null) {
- mFullConfig.setNightModeQualifier(new NightModeQualifier(nightMode));
- }
-
- // replace the API level by the selection of the combo
- IAndroidTarget target = getTarget();
- if (target == null && mConfigChooser != null) {
- target = mConfigChooser.getProjectTarget();
- }
- if (target != null) {
- int apiLevel = target.getVersion().getApiLevel();
- mFullConfig.setVersionQualifier(new VersionQualifier(apiLevel));
- }
- }
-
- /**
- * Creates a string suitable for persistence, which can be initialized back
- * to a configuration via {@link #initialize(String)}
- *
- * @return a persistent string
- */
- @NonNull
- public String toPersistentString() {
- StringBuilder sb = new StringBuilder(32);
- Device device = getDevice();
- if (device != null) {
- sb.append(device.getName());
- sb.append(SEP);
- State state = getDeviceState();
- if (state != null) {
- sb.append(state.getName());
- }
- sb.append(SEP);
- Locale locale = getLocale();
- if (isLocaleSpecificLayout() && locale != null && locale.qualifier.hasLanguage()) {
- // locale[0]/[1] can be null sometimes when starting Eclipse
- sb.append(locale.qualifier.getLanguage());
- sb.append(SEP_LOCALE);
- if (locale.qualifier.hasRegion()) {
- sb.append(locale.qualifier.getRegion());
- }
- }
- sb.append(SEP);
- // Need to escape the theme: if we write the full theme style, then
- // we can end up with ":"'s in the string (as in @android:style/Theme) which
- // can be mistaken for {@link #SEP}. Instead use {@link #MARKER_FRAMEWORK}.
- String theme = getTheme();
- if (theme != null) {
- String themeName = ResourceHelper.styleToTheme(theme);
- if (theme.startsWith(STYLE_RESOURCE_PREFIX)) {
- sb.append(MARKER_PROJECT);
- } else if (theme.startsWith(ANDROID_STYLE_RESOURCE_PREFIX)) {
- sb.append(MARKER_FRAMEWORK);
- }
- sb.append(themeName);
- }
- sb.append(SEP);
- UiMode uiMode = getUiMode();
- if (uiMode != null) {
- sb.append(uiMode.getResourceValue());
- }
- sb.append(SEP);
- NightMode nightMode = getNightMode();
- if (nightMode != null) {
- sb.append(nightMode.getResourceValue());
- }
- sb.append(SEP);
-
- // We used to store the render target here in R9. Leave a marker
- // to ensure that we don't reuse this slot; add new extra fields after it.
- sb.append(SEP);
- String activity = getActivity();
- if (activity != null) {
- sb.append(activity);
- }
- }
-
- return sb.toString();
- }
-
- /** Returns the preferred theme, or null */
- @Nullable
- String computePreferredTheme() {
- IProject project = mConfigChooser.getProject();
- ManifestInfo manifest = ManifestInfo.get(project);
-
- // Look up the screen size for the current state
- ScreenSize screenSize = null;
- Device device = getDevice();
- if (device != null) {
- List<State> states = device.getAllStates();
- for (State state : states) {
- FolderConfiguration folderConfig = DeviceConfigHelper.getFolderConfig(state);
- if (folderConfig != null) {
- ScreenSizeQualifier qualifier = folderConfig.getScreenSizeQualifier();
- screenSize = qualifier.getValue();
- break;
- }
- }
- }
-
- // Look up the default/fallback theme to use for this project (which
- // depends on the screen size when no particular theme is specified
- // in the manifest)
- String defaultTheme = manifest.getDefaultTheme(getTarget(), screenSize);
-
- String preferred = defaultTheme;
- if (getTheme() == null) {
- // If we are rendering a layout in included context, pick the theme
- // from the outer layout instead
-
- String activity = getActivity();
- if (activity != null) {
- ActivityAttributes attributes = manifest.getActivityAttributes(activity);
- if (attributes != null) {
- preferred = attributes.getTheme();
- }
- }
- if (preferred == null) {
- preferred = defaultTheme;
- }
- setTheme(preferred);
- }
-
- return preferred;
- }
-
- private void checkThemePrefix() {
- if (mTheme != null && !mTheme.startsWith(PREFIX_RESOURCE_REF)) {
- if (mTheme.isEmpty()) {
- computePreferredTheme();
- return;
- }
- ResourceRepository frameworkRes = mConfigChooser.getClient().getFrameworkResources();
- if (frameworkRes != null
- && frameworkRes.hasResourceItem(ANDROID_STYLE_RESOURCE_PREFIX + mTheme)) {
- mTheme = ANDROID_STYLE_RESOURCE_PREFIX + mTheme;
- } else {
- mTheme = STYLE_RESOURCE_PREFIX + mTheme;
- }
- }
- }
-
- /**
- * Initializes a string previously created with
- * {@link #toPersistentString()}
- *
- * @param data the string to initialize back from
- * @return true if the configuration was initialized
- */
- boolean initialize(String data) {
- String[] values = data.split(SEP);
- if (values.length >= 6 && values.length <= 8) {
- for (Device d : mConfigChooser.getDevices()) {
- if (d.getName().equals(values[0])) {
- mDevice = d;
- String stateName = null;
- FolderConfiguration config = null;
- if (!values[1].isEmpty() && !values[1].equals("null")) { //$NON-NLS-1$
- stateName = values[1];
- config = DeviceConfigHelper.getFolderConfig(mDevice, stateName);
- } else if (mDevice.getAllStates().size() > 0) {
- State first = mDevice.getAllStates().get(0);
- stateName = first.getName();
- config = DeviceConfigHelper.getFolderConfig(first);
- }
- mState = getState(mDevice, stateName);
- if (config != null) {
- // Load locale. Note that this can get overwritten by the
- // project-wide settings read below.
- LocaleQualifier locale = Locale.ANY_QUALIFIER;
- String locales[] = values[2].split(SEP_LOCALE);
- if (locales.length >= 2 && locales[0].length() > 0
- && !LocaleQualifier.FAKE_VALUE.equals(locales[0])) {
- String language = locales[0];
- String region = locales[1];
- if (region.length() > 0 && !LocaleQualifier.FAKE_VALUE.equals(region)) {
- locale = LocaleQualifier.getQualifier(language + "-r" + region);
- } else {
- locale = new LocaleQualifier(language);
- }
- mLocale = Locale.create(locale);
- }
-
- // Decode the theme name: See {@link #getData}
- mTheme = values[3];
- if (mTheme.startsWith(MARKER_FRAMEWORK)) {
- mTheme = ANDROID_STYLE_RESOURCE_PREFIX
- + mTheme.substring(MARKER_FRAMEWORK.length());
- } else if (mTheme.startsWith(MARKER_PROJECT)) {
- mTheme = STYLE_RESOURCE_PREFIX
- + mTheme.substring(MARKER_PROJECT.length());
- } else {
- checkThemePrefix();
- }
-
- mUiMode = UiMode.getEnum(values[4]);
- if (mUiMode == null) {
- mUiMode = UiMode.NORMAL;
- }
- mNightMode = NightMode.getEnum(values[5]);
- if (mNightMode == null) {
- mNightMode = NightMode.NOTNIGHT;
- }
-
- // element 7/values[6]: used to store render target in R9.
- // No longer stored here. If adding more data, make
- // sure you leave 7 alone.
-
- Pair<Locale, IAndroidTarget> pair = loadRenderState(mConfigChooser);
- if (pair != null) {
- // We only use the "global" setting
- if (!isLocaleSpecificLayout()) {
- mLocale = pair.getFirst();
- }
- mTarget = pair.getSecond();
- }
-
- if (values.length == 8) {
- mActivity = values[7];
- }
-
- return true;
- }
- }
- }
- }
-
- return false;
- }
-
- /**
- * Loads the render state (the locale and the render target, which are shared among
- * all the layouts meaning that changing it in one will change it in all) and returns
- * the current project-wide locale and render target to be used.
- *
- * @param chooser the {@link ConfigurationChooser} providing information about
- * loaded targets
- * @return a pair of a locale and a render target
- */
- @Nullable
- static Pair<Locale, IAndroidTarget> loadRenderState(ConfigurationChooser chooser) {
- IProject project = chooser.getProject();
- if (project == null || !project.isAccessible()) {
- return null;
- }
-
- try {
- String data = project.getPersistentProperty(NAME_RENDER_STATE);
- if (data != null) {
- Locale locale = Locale.ANY;
- IAndroidTarget target = null;
-
- String[] values = data.split(SEP);
- if (values.length == 2) {
-
- LocaleQualifier qualifier = Locale.ANY_QUALIFIER;
- String locales[] = values[0].split(SEP_LOCALE);
- if (locales.length >= 2 && locales[0].length() > 0
- && !LocaleQualifier.FAKE_VALUE.equals(locales[0])) {
- String language = locales[0];
- String region = locales[1];
- if (region.length() > 0 && !LocaleQualifier.FAKE_VALUE.equals(region)) {
- locale = Locale.create(LocaleQualifier.getQualifier(language + "-r" + region));
- } else {
- locale = Locale.create(new LocaleQualifier(language));
- }
- } else {
- locale = Locale.ANY;
- }
- if (AdtPrefs.getPrefs().isAutoPickRenderTarget()) {
- target = ConfigurationMatcher.findDefaultRenderTarget(chooser);
- } else {
- String targetString = values[1];
- target = stringToTarget(chooser, targetString);
- // See if we should "correct" the rendering target to a
- // better version. If you're using a pre-release version
- // of the render target, and a final release is
- // available and installed, we should switch to that
- // one instead.
- if (target != null) {
- AndroidVersion version = target.getVersion();
- List<IAndroidTarget> targetList = chooser.getTargetList();
- if (version.getCodename() != null && targetList != null) {
- int targetApiLevel = version.getApiLevel() + 1;
- for (IAndroidTarget t : targetList) {
- if (t.getVersion().getApiLevel() == targetApiLevel
- && t.isPlatform()) {
- target = t;
- break;
- }
- }
- }
- } else {
- target = ConfigurationMatcher.findDefaultRenderTarget(chooser);
- }
- }
- }
-
- return Pair.of(locale, target);
- }
-
- return Pair.of(Locale.ANY, ConfigurationMatcher.findDefaultRenderTarget(chooser));
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
-
- return null;
- }
-
- /**
- * Saves the render state (the current locale and render target settings) into the
- * project wide settings storage
- */
- void saveRenderState() {
- IProject project = mConfigChooser.getProject();
- if (project == null) {
- return;
- }
- try {
- // Generate a persistent string from locale+target
- StringBuilder sb = new StringBuilder(32);
- Locale locale = getLocale();
- if (locale != null) {
- // locale[0]/[1] can be null sometimes when starting Eclipse
- sb.append(locale.qualifier.getLanguage());
- sb.append(SEP_LOCALE);
- if (locale.qualifier.hasRegion()) {
- sb.append(locale.qualifier.getRegion());
- }
- }
- sb.append(SEP);
- IAndroidTarget target = getTarget();
- if (target != null) {
- sb.append(targetToString(target));
- sb.append(SEP);
- }
-
- project.setPersistentProperty(NAME_RENDER_STATE, sb.toString());
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- }
-
- /**
- * Returns a String id to represent an {@link IAndroidTarget} which can be translated
- * back to an {@link IAndroidTarget} by the matching {@link #stringToTarget}. The id
- * will never contain the {@link #SEP} character.
- *
- * @param target the target to return an id for
- * @return an id for the given target; never null
- */
- @NonNull
- public static String targetToString(@NonNull IAndroidTarget target) {
- return target.getFullName().replace(SEP, ""); //$NON-NLS-1$
- }
-
- /**
- * Returns an {@link IAndroidTarget} that corresponds to the given id that was
- * originally returned by {@link #targetToString}. May be null, if the platform is no
- * longer available, or if the platform list has not yet been initialized.
- *
- * @param chooser the {@link ConfigurationChooser} providing information about
- * loaded targets
- * @param id the id that corresponds to the desired platform
- * @return an {@link IAndroidTarget} that matches the given id, or null
- */
- @Nullable
- public static IAndroidTarget stringToTarget(
- @NonNull ConfigurationChooser chooser,
- @NonNull String id) {
- List<IAndroidTarget> targetList = chooser.getTargetList();
- if (targetList != null && targetList.size() > 0) {
- for (IAndroidTarget target : targetList) {
- if (id.equals(targetToString(target))) {
- return target;
- }
- }
- }
-
- return null;
- }
-
- /**
- * Returns an {@link IAndroidTarget} that corresponds to the given id that was
- * originally returned by {@link #targetToString}. May be null, if the platform is no
- * longer available, or if the platform list has not yet been initialized.
- *
- * @param id the id that corresponds to the desired platform
- * @return an {@link IAndroidTarget} that matches the given id, or null
- */
- @Nullable
- public static IAndroidTarget stringToTarget(
- @NonNull String id) {
- Sdk currentSdk = Sdk.getCurrent();
- if (currentSdk != null) {
- IAndroidTarget[] targets = currentSdk.getTargets();
- for (IAndroidTarget target : targets) {
- if (id.equals(targetToString(target))) {
- return target;
- }
- }
- }
-
- return null;
- }
-
- /**
- * Returns the {@link State} by the given name for the given {@link Device}
- *
- * @param device the device
- * @param name the name of the state
- */
- @Nullable
- static State getState(@Nullable Device device, @Nullable String name) {
- if (device == null) {
- return null;
- } else if (name != null) {
- State state = device.getState(name);
- if (state != null) {
- return state;
- }
- }
-
- return device.getDefaultState();
- }
-
- /**
- * Returns the currently selected {@link Density}. This is guaranteed to be non null.
- *
- * @return the density
- */
- @NonNull
- public Density getDensity() {
- if (mFullConfig != null) {
- DensityQualifier qual = mFullConfig.getDensityQualifier();
- if (qual != null) {
- // just a sanity check
- Density d = qual.getValue();
- if (d != Density.NODPI) {
- return d;
- }
- }
- }
-
- // no config? return medium as the default density.
- return Density.MEDIUM;
- }
-
- /**
- * Get the next cyclical state after the given state
- *
- * @param from the state to start with
- * @return the following state following
- */
- @Nullable
- public State getNextDeviceState(@Nullable State from) {
- Device device = getDevice();
- if (device == null) {
- return null;
- }
- List<State> states = device.getAllStates();
- for (int i = 0; i < states.size(); i++) {
- if (states.get(i) == from) {
- return states.get((i + 1) % states.size());
- }
- }
-
- return null;
- }
-
- /**
- * Returns true if this configuration supports the given rendering
- * capability
- *
- * @param capability the capability to check
- * @return true if the capability is supported
- */
- public boolean supports(Capability capability) {
- IAndroidTarget target = getTarget();
- if (target != null) {
- return RenderService.supports(target, capability);
- }
-
- return false;
- }
-
- @Override
- public String toString() {
- return Objects.toStringHelper(this.getClass())
- .add("display", getDisplayName()) //$NON-NLS-1$
- .add("persistent", toPersistentString()) //$NON-NLS-1$
- .toString();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ConfigurationChooser.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ConfigurationChooser.java
deleted file mode 100644
index 009b8646c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ConfigurationChooser.java
+++ /dev/null
@@ -1,2096 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.configuration;
-
-import static com.android.SdkConstants.ANDROID_NS_NAME_PREFIX;
-import static com.android.SdkConstants.ANDROID_STYLE_RESOURCE_PREFIX;
-import static com.android.SdkConstants.ATTR_CONTEXT;
-import static com.android.SdkConstants.PREFIX_RESOURCE_REF;
-import static com.android.SdkConstants.RES_QUALIFIER_SEP;
-import static com.android.SdkConstants.STYLE_RESOURCE_PREFIX;
-import static com.android.SdkConstants.TOOLS_URI;
-import static com.android.ide.eclipse.adt.AdtUtils.isUiThread;
-import static com.android.ide.eclipse.adt.internal.editors.layout.configuration.Configuration.CFG_DEVICE;
-import static com.android.ide.eclipse.adt.internal.editors.layout.configuration.Configuration.CFG_DEVICE_STATE;
-import static com.android.ide.eclipse.adt.internal.editors.layout.configuration.Configuration.CFG_FOLDER;
-import static com.android.ide.eclipse.adt.internal.editors.layout.configuration.Configuration.CFG_LOCALE;
-import static com.android.ide.eclipse.adt.internal.editors.layout.configuration.Configuration.CFG_TARGET;
-import static com.android.ide.eclipse.adt.internal.editors.layout.configuration.Configuration.CFG_THEME;
-import static com.android.ide.eclipse.adt.internal.editors.layout.configuration.Configuration.MASK_ALL;
-import static com.google.common.base.Objects.equal;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.rendering.api.ResourceValue;
-import com.android.ide.common.rendering.api.StyleResourceValue;
-import com.android.ide.common.resources.LocaleManager;
-import com.android.ide.common.resources.ResourceFile;
-import com.android.ide.common.resources.ResourceFolder;
-import com.android.ide.common.resources.ResourceRepository;
-import com.android.ide.common.resources.configuration.DeviceConfigHelper;
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.common.resources.configuration.LocaleQualifier;
-import com.android.ide.common.resources.configuration.ResourceQualifier;
-import com.android.ide.common.sdk.LoadStatus;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlDelegate;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.IncludeFinder.Reference;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.LayoutCanvas;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo.ActivityAttributes;
-import com.android.ide.eclipse.adt.internal.resources.ResourceHelper;
-import com.android.ide.eclipse.adt.internal.resources.manager.ProjectResources;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.resources.ResourceType;
-import com.android.resources.ScreenOrientation;
-import com.android.sdklib.AndroidVersion;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.devices.Device;
-import com.android.sdklib.devices.DeviceManager;
-import com.android.sdklib.devices.DeviceManager.DevicesChangedListener;
-import com.android.sdklib.devices.State;
-import com.android.utils.Pair;
-import com.google.common.base.Objects;
-import com.google.common.base.Strings;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.ToolBar;
-import org.eclipse.swt.widgets.ToolItem;
-import org.eclipse.ui.IEditorPart;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.IdentityHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.SortedSet;
-
-/**
- * The {@linkplain ConfigurationChooser} allows the user to pick a
- * {@link Configuration} by configuring various constraints.
- */
-public class ConfigurationChooser extends Composite
- implements DevicesChangedListener, DisposeListener {
- private static final String ICON_SQUARE = "square"; //$NON-NLS-1$
- private static final String ICON_LANDSCAPE = "landscape"; //$NON-NLS-1$
- private static final String ICON_PORTRAIT = "portrait"; //$NON-NLS-1$
- private static final String ICON_LANDSCAPE_FLIP = "flip_landscape";//$NON-NLS-1$
- private static final String ICON_PORTRAIT_FLIP = "flip_portrait";//$NON-NLS-1$
- private static final String ICON_DISPLAY = "display"; //$NON-NLS-1$
- private static final String ICON_THEMES = "themes"; //$NON-NLS-1$
- private static final String ICON_ACTIVITY = "activity"; //$NON-NLS-1$
-
- /** The configuration state associated with this editor */
- private @NonNull Configuration mConfiguration = Configuration.create(this);
-
- /** Serialized state to use when initializing the configuration after the SDK is loaded */
- private String mInitialState;
-
- /** The client of the configuration editor */
- private final ConfigurationClient mClient;
-
- /** Counter for programmatic UI changes: if greater than 0, we're within a call */
- private int mDisableUpdates = 0;
-
- /** List of available devices */
- private Collection<Device> mDevices = Collections.emptyList();
-
- /** List of available targets */
- private final List<IAndroidTarget> mTargetList = new ArrayList<IAndroidTarget>();
-
- /** List of available themes */
- private final List<String> mThemeList = new ArrayList<String>();
-
- /** List of available locales */
- private final List<Locale > mLocaleList = new ArrayList<Locale>();
-
- /** The file being edited */
- private IFile mEditedFile;
-
- /** The {@link ProjectResources} for the edited file's project */
- private ProjectResources mResources;
-
- /** The target of the project of the file being edited. */
- private IAndroidTarget mProjectTarget;
-
- /** Dropdown for configurations */
- private ToolItem mConfigCombo;
-
- /** Dropdown for devices */
- private ToolItem mDeviceCombo;
-
- /** Dropdown for device states */
- private ToolItem mOrientationCombo;
-
- /** Dropdown for themes */
- private ToolItem mThemeCombo;
-
- /** Dropdown for locales */
- private ToolItem mLocaleCombo;
-
- /** Dropdown for activities */
- private ToolItem mActivityCombo;
-
- /** Dropdown for rendering targets */
- private ToolItem mTargetCombo;
-
- /** Whether the SDK has changed since the last model reload; if so we must reload targets */
- private boolean mSdkChanged = true;
-
- /**
- * Creates a new {@linkplain ConfigurationChooser} and adds it to the
- * parent. The method also receives custom buttons to set into the
- * configuration composite. The list is organized as an array of arrays.
- * Each array represents a group of buttons thematically grouped together.
- *
- * @param client the client embedding this configuration chooser
- * @param parent The parent composite.
- * @param initialState The initial state (serialized form) to use for the
- * configuration
- */
- public ConfigurationChooser(
- @NonNull ConfigurationClient client,
- Composite parent,
- @Nullable String initialState) {
- super(parent, SWT.NONE);
- mClient = client;
-
- setVisible(false); // Delayed until the targets are loaded
-
- mInitialState = initialState;
- setLayout(new GridLayout(1, false));
-
- IconFactory icons = IconFactory.getInstance();
-
- // TODO: Consider switching to a CoolBar instead
- ToolBar toolBar = new ToolBar(this, SWT.WRAP | SWT.FLAT | SWT.RIGHT | SWT.HORIZONTAL);
- toolBar.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
-
- mConfigCombo = new ToolItem(toolBar, SWT.DROP_DOWN );
- mConfigCombo.setImage(icons.getIcon("android_file")); //$NON-NLS-1$
- mConfigCombo.setToolTipText("Configuration to render this layout with in Eclipse");
-
- @SuppressWarnings("unused")
- ToolItem separator2 = new ToolItem(toolBar, SWT.SEPARATOR);
-
- mDeviceCombo = new ToolItem(toolBar, SWT.DROP_DOWN);
- mDeviceCombo.setImage(icons.getIcon(ICON_DISPLAY));
-
- @SuppressWarnings("unused")
- ToolItem separator3 = new ToolItem(toolBar, SWT.SEPARATOR);
-
- mOrientationCombo = new ToolItem(toolBar, SWT.DROP_DOWN);
- mOrientationCombo.setImage(icons.getIcon(ICON_PORTRAIT));
- mOrientationCombo.setToolTipText("Go to next state");
-
- @SuppressWarnings("unused")
- ToolItem separator4 = new ToolItem(toolBar, SWT.SEPARATOR);
-
- mThemeCombo = new ToolItem(toolBar, SWT.DROP_DOWN);
- mThemeCombo.setImage(icons.getIcon(ICON_THEMES));
-
- @SuppressWarnings("unused")
- ToolItem separator5 = new ToolItem(toolBar, SWT.SEPARATOR);
-
- mActivityCombo = new ToolItem(toolBar, SWT.DROP_DOWN);
- mActivityCombo.setToolTipText("Associated activity or fragment providing context");
- // The JDT class icon is lopsided, presumably because they've left room in the
- // bottom right corner for badges (for static, final etc). Unfortunately, this
- // means that the icon looks out of place when sitting close to the language globe
- // icon, the theme icon, etc so that it looks vertically misaligned:
- //mActivityCombo.setImage(JavaUI.getSharedImages().getImage(ISharedImages.IMG_OBJS_CLASS));
- // ...so use one that is centered instead:
- mActivityCombo.setImage(icons.getIcon(ICON_ACTIVITY));
-
- @SuppressWarnings("unused")
- ToolItem separator6 = new ToolItem(toolBar, SWT.SEPARATOR);
-
- //ToolBar rightToolBar = new ToolBar(this, SWT.WRAP | SWT.FLAT | SWT.RIGHT | SWT.HORIZONTAL);
- //rightToolBar.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1));
- ToolBar rightToolBar = toolBar;
-
- mLocaleCombo = new ToolItem(rightToolBar, SWT.DROP_DOWN);
- mLocaleCombo.setImage(FlagManager.getGlobeIcon());
- mLocaleCombo.setToolTipText("Locale to use when rendering layouts in Eclipse");
-
- @SuppressWarnings("unused")
- ToolItem separator7 = new ToolItem(rightToolBar, SWT.SEPARATOR);
-
- mTargetCombo = new ToolItem(rightToolBar, SWT.DROP_DOWN);
- mTargetCombo.setImage(AdtPlugin.getAndroidLogo());
- mTargetCombo.setToolTipText("Android version to use when rendering layouts in Eclipse");
-
- SelectionListener listener = new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- Object source = e.getSource();
-
- if (source == mConfigCombo) {
- ConfigurationMenuListener.show(ConfigurationChooser.this, mConfigCombo);
- } else if (source == mActivityCombo) {
- ActivityMenuListener.show(ConfigurationChooser.this, mActivityCombo);
- } else if (source == mLocaleCombo) {
- LocaleMenuListener.show(ConfigurationChooser.this, mLocaleCombo);
- } else if (source == mDeviceCombo) {
- DeviceMenuListener.show(ConfigurationChooser.this, mDeviceCombo);
- } else if (source == mTargetCombo) {
- TargetMenuListener.show(ConfigurationChooser.this, mTargetCombo);
- } else if (source == mThemeCombo) {
- ThemeMenuAction.showThemeMenu(ConfigurationChooser.this, mThemeCombo,
- mThemeList);
- } else if (source == mOrientationCombo) {
- if (e.detail == SWT.ARROW) {
- OrientationMenuAction.showMenu(ConfigurationChooser.this,
- mOrientationCombo);
- } else {
- gotoNextState();
- }
- }
- }
- };
- mConfigCombo.addSelectionListener(listener);
- mActivityCombo.addSelectionListener(listener);
- mLocaleCombo.addSelectionListener(listener);
- mDeviceCombo.addSelectionListener(listener);
- mTargetCombo.addSelectionListener(listener);
- mThemeCombo.addSelectionListener(listener);
- mOrientationCombo.addSelectionListener(listener);
-
- addDisposeListener(this);
-
- initDevices();
- initTargets();
- }
-
- /**
- * Returns the edited file
- *
- * @return the file
- */
- @Nullable
- public IFile getEditedFile() {
- return mEditedFile;
- }
-
- /**
- * Returns the project of the edited file
- *
- * @return the project
- */
- @Nullable
- public IProject getProject() {
- if (mEditedFile != null) {
- return mEditedFile.getProject();
- } else {
- return null;
- }
- }
-
- ConfigurationClient getClient() {
- return mClient;
- }
-
- /**
- * Returns the project resources for the project being configured by this
- * chooser
- *
- * @return the project resources
- */
- @Nullable
- public ProjectResources getResources() {
- return mResources;
- }
-
- /**
- * Returns the full, complete {@link FolderConfiguration}
- *
- * @return the full configuration
- */
- public FolderConfiguration getFullConfiguration() {
- return mConfiguration.getFullConfig();
- }
-
- /**
- * Returns the project target
- *
- * @return the project target
- */
- public IAndroidTarget getProjectTarget() {
- return mProjectTarget;
- }
-
- /**
- * Returns the configuration being edited by this {@linkplain ConfigurationChooser}
- *
- * @return the configuration
- */
- public Configuration getConfiguration() {
- return mConfiguration;
- }
-
- /**
- * Returns the list of locales
- * @return a list of {@link ResourceQualifier} pairs
- */
- @NonNull
- public List<Locale> getLocaleList() {
- return mLocaleList;
- }
-
- /**
- * Returns the list of available devices
- *
- * @return a list of {@link Device} objects
- */
- @NonNull
- public Collection<Device> getDevices() {
- return mDevices;
- }
-
- /**
- * Returns the list of available render targets
- *
- * @return a list of {@link IAndroidTarget} objects
- */
- @NonNull
- public List<IAndroidTarget> getTargetList() {
- return mTargetList;
- }
-
- // ---- Configuration State Lookup ----
-
- /**
- * Returns the rendering target to be used
- *
- * @return the target
- */
- @NonNull
- public IAndroidTarget getTarget() {
- IAndroidTarget target = mConfiguration.getTarget();
- if (target == null) {
- target = mProjectTarget;
- }
-
- return target;
- }
-
- /**
- * Returns the current device string, or null if no device is selected
- *
- * @return the device name, or null
- */
- @Nullable
- public String getDeviceName() {
- Device device = mConfiguration.getDevice();
- if (device != null) {
- return device.getName();
- }
-
- return null;
- }
-
- /**
- * Returns the current theme, or null if none has been selected
- *
- * @return the theme name, or null
- */
- @Nullable
- public String getThemeName() {
- String theme = mConfiguration.getTheme();
- if (theme != null) {
- theme = ResourceHelper.styleToTheme(theme);
- }
-
- return theme;
- }
-
- /** Move to the next device state, changing the icon if it changes orientation */
- private void gotoNextState() {
- State state = mConfiguration.getDeviceState();
- State flipped = mConfiguration.getNextDeviceState(state);
- if (flipped != state) {
- selectDeviceState(flipped);
- onDeviceConfigChange();
- }
- }
-
- // ---- Implements DisposeListener ----
-
- @Override
- public void widgetDisposed(DisposeEvent e) {
- dispose();
- }
-
- @Override
- public void dispose() {
- if (!isDisposed()) {
- super.dispose();
-
- final Sdk sdk = Sdk.getCurrent();
- if (sdk != null) {
- DeviceManager manager = sdk.getDeviceManager();
- manager.unregisterListener(this);
- }
- }
- }
-
- // ---- Init and reset/reload methods ----
-
- /**
- * Sets the reference to the file being edited.
- * <p/>The UI is initialized in {@link #onXmlModelLoaded()} which is called as the XML model is
- * loaded (or reloaded as the SDK/target changes).
- *
- * @param file the file being opened
- *
- * @see #onXmlModelLoaded()
- * @see #replaceFile(IFile)
- * @see #changeFileOnNewConfig(IFile)
- */
- public void setFile(IFile file) {
- mEditedFile = file;
- ensureInitialized();
- }
-
- /**
- * Replaces the UI with a given file configuration. This is meant to answer the user
- * explicitly opening a different version of the same layout from the Package Explorer.
- * <p/>This attempts to keep the current config, but may change it if it's not compatible or
- * not the best match
- * @param file the file being opened.
- */
- public void replaceFile(IFile file) {
- // if there is no previous selection, revert to default mode.
- if (mConfiguration.getDevice() == null) {
- setFile(file); // onTargetChanged will be called later.
- return;
- }
-
- setFile(file);
- IProject project = mEditedFile.getProject();
- mResources = ResourceManager.getInstance().getProjectResources(project);
-
- ResourceFolder resFolder = ResourceManager.getInstance().getResourceFolder(file);
- mConfiguration.setEditedConfig(resFolder.getConfiguration());
-
- mDisableUpdates++; // we do not want to trigger onXXXChange when setting
- // new values in the widgets.
-
- try {
- // only attempt to do anything if the SDK and targets are loaded.
- LoadStatus sdkStatus = AdtPlugin.getDefault().getSdkLoadStatus();
-
- if (sdkStatus == LoadStatus.LOADED) {
- setVisible(true);
-
- LoadStatus targetStatus = Sdk.getCurrent().checkAndLoadTargetData(mProjectTarget,
- null /*project*/);
-
- if (targetStatus == LoadStatus.LOADED) {
-
- // update the current config selection to make sure it's
- // compatible with the new file
- ConfigurationMatcher matcher = new ConfigurationMatcher(this);
- matcher.adaptConfigSelection(true /*needBestMatch*/);
- mConfiguration.syncFolderConfig();
-
- // update the string showing the config value
- selectConfiguration(mConfiguration.getEditedConfig());
- updateActivity();
- }
- } else if (sdkStatus == LoadStatus.FAILED) {
- setVisible(true);
- }
- } finally {
- mDisableUpdates--;
- }
- }
-
- /**
- * Updates the UI with a new file that was opened in response to a config change.
- * @param file the file being opened.
- *
- * @see #replaceFile(IFile)
- */
- public void changeFileOnNewConfig(IFile file) {
- setFile(file);
- IProject project = mEditedFile.getProject();
- mResources = ResourceManager.getInstance().getProjectResources(project);
-
- ResourceFolder resFolder = ResourceManager.getInstance().getResourceFolder(file);
- FolderConfiguration config = resFolder.getConfiguration();
- mConfiguration.setEditedConfig(config);
-
- // All that's needed is to update the string showing the config value
- // (since the config combo settings chosen by the user).
- selectConfiguration(config);
- }
-
- /**
- * Resets the configuration chooser to reflect the given file configuration. This is
- * intended to be used by the "Show Included In" functionality where the user has
- * picked a non-default configuration (such as a particular landscape layout) and the
- * configuration chooser must be switched to a landscape layout. This method will
- * trigger a model change.
- * <p>
- * This will NOT trigger a redraw event!
- * <p>
- * FIXME: We are currently setting the configuration file to be the configuration for
- * the "outer" (the including) file, rather than the inner file, which is the file the
- * user is actually editing. We need to refine this, possibly with a way for the user
- * to choose which configuration they are editing. And in particular, we should be
- * filtering the configuration chooser to only show options in the outer configuration
- * that are compatible with the inner included file.
- *
- * @param file the file to be configured
- */
- public void resetConfigFor(IFile file) {
- setFile(file);
-
- IFolder parent = (IFolder) mEditedFile.getParent();
- ResourceFolder resFolder = mResources.getResourceFolder(parent);
- if (resFolder != null) {
- mConfiguration.setEditedConfig(resFolder.getConfiguration());
- } else {
- FolderConfiguration config = FolderConfiguration.getConfig(
- parent.getName().split(RES_QUALIFIER_SEP));
- if (config != null) {
- mConfiguration.setEditedConfig(config);
- } else {
- mConfiguration.setEditedConfig(new FolderConfiguration());
- }
- }
-
- onXmlModelLoaded();
- }
-
-
- /**
- * Sets the current configuration to match the given folder configuration,
- * the given theme name, the given device and device state.
- *
- * @param configuration new folder configuration to use
- */
- public void setConfiguration(@NonNull Configuration configuration) {
- if (mClient != null) {
- mClient.aboutToChange(MASK_ALL);
- }
-
- Configuration oldConfiguration = mConfiguration;
- mConfiguration = configuration;
- mConfiguration.setChooser(this);
-
- selectTheme(configuration.getTheme());
- selectLocale(configuration.getLocale());
- selectDevice(configuration.getDevice());
- selectDeviceState(configuration.getDeviceState());
- selectTarget(configuration.getTarget());
- selectActivity(configuration.getActivity());
-
- // This may be a second refresh after triggered by theme above
- if (mClient != null) {
- LayoutCanvas canvas = mClient.getCanvas();
- if (canvas != null) {
- assert mConfiguration != oldConfiguration;
- canvas.getPreviewManager().updateChooserConfig(oldConfiguration, mConfiguration);
- }
-
- boolean accepted = mClient.changed(MASK_ALL);
- if (!accepted) {
- configuration = oldConfiguration;
- selectTheme(configuration.getTheme());
- selectLocale(configuration.getLocale());
- selectDevice(configuration.getDevice());
- selectDeviceState(configuration.getDeviceState());
- selectTarget(configuration.getTarget());
- selectActivity(configuration.getActivity());
- if (canvas != null && mConfiguration != oldConfiguration) {
- canvas.getPreviewManager().updateChooserConfig(mConfiguration,
- oldConfiguration);
- }
- return;
- } else {
- int changed = 0;
- if (!equal(oldConfiguration.getTheme(), mConfiguration.getTheme())) {
- changed |= CFG_THEME;
- }
- if (!equal(oldConfiguration.getDevice(), mConfiguration.getDevice())) {
- changed |= CFG_DEVICE | CFG_DEVICE_STATE;
- }
- if (changed != 0) {
- syncToVariations(changed, mEditedFile, mConfiguration, false, true);
- }
- }
- }
-
- saveConstraints();
- }
-
- /**
- * Responds to the event that the basic SDK information finished loading.
- * @param target the possibly new target object associated with the file being edited (in case
- * the SDK path was changed).
- */
- public void onSdkLoaded(IAndroidTarget target) {
- // a change to the SDK means that we need to check for new/removed devices.
- mSdkChanged = true;
-
- // store the new target.
- mProjectTarget = target;
-
- mDisableUpdates++; // we do not want to trigger onXXXChange when setting
- // new values in the widgets.
- try {
- updateDevices();
- updateTargets();
- ensureInitialized();
- } finally {
- mDisableUpdates--;
- }
- }
-
- /**
- * Responds to the XML model being loaded, either the first time or when the
- * Target/SDK changes.
- * <p>
- * This initializes the UI, either with the first compatible configuration
- * found, or it will attempt to restore a configuration if one is found to
- * have been saved in the file persistent storage.
- * <p>
- * If the SDK or target are not loaded, nothing will happen (but the method
- * must be called back when they are.)
- * <p>
- * The method automatically handles being called the first time after editor
- * creation, or being called after during SDK/Target changes (as long as
- * {@link #onSdkLoaded(IAndroidTarget)} is properly called).
- *
- * @return the target data for the rendering target used to render the
- * layout
- *
- * @see #saveConstraints()
- * @see #onSdkLoaded(IAndroidTarget)
- */
- public AndroidTargetData onXmlModelLoaded() {
- AndroidTargetData targetData = null;
-
- // only attempt to do anything if the SDK and targets are loaded.
- LoadStatus sdkStatus = AdtPlugin.getDefault().getSdkLoadStatus();
- if (sdkStatus == LoadStatus.LOADED) {
- mDisableUpdates++; // we do not want to trigger onXXXChange when setting
-
- try {
- // init the devices if needed (new SDK or first time going through here)
- if (mSdkChanged) {
- updateDevices();
- updateTargets();
- ensureInitialized();
- mSdkChanged = false;
- }
-
- IProject project = mEditedFile.getProject();
-
- Sdk currentSdk = Sdk.getCurrent();
- if (currentSdk != null) {
- mProjectTarget = currentSdk.getTarget(project);
- }
-
- LoadStatus targetStatus = LoadStatus.FAILED;
- if (mProjectTarget != null) {
- targetStatus = Sdk.getCurrent().checkAndLoadTargetData(mProjectTarget, null);
- updateTargets();
- ensureInitialized();
- }
-
- if (targetStatus == LoadStatus.LOADED) {
- setVisible(true);
- if (mResources == null) {
- mResources = ResourceManager.getInstance().getProjectResources(project);
- }
- if (mConfiguration.getEditedConfig() == null) {
- IFolder parent = (IFolder) mEditedFile.getParent();
- ResourceFolder resFolder = mResources.getResourceFolder(parent);
- if (resFolder != null) {
- mConfiguration.setEditedConfig(resFolder.getConfiguration());
- } else {
- FolderConfiguration config = FolderConfiguration.getConfig(
- parent.getName().split(RES_QUALIFIER_SEP));
- if (config != null) {
- mConfiguration.setEditedConfig(config);
- } else {
- mConfiguration.setEditedConfig(new FolderConfiguration());
- }
- }
- }
-
- targetData = Sdk.getCurrent().getTargetData(mProjectTarget);
-
- // get the file stored state
- ensureInitialized();
- boolean loadedConfigData = mConfiguration.getDevice() != null &&
- mConfiguration.getDeviceState() != null;
-
- // Load locale list. This must be run after we initialize the
- // configuration above, since it attempts to sync the UI with
- // the value loaded into the configuration.
- updateLocales();
-
- // If the current state was loaded from the persistent storage, we update the
- // UI with it and then try to adapt it (which will handle incompatible
- // configuration).
- // Otherwise, just look for the first compatible configuration.
- ConfigurationMatcher matcher = new ConfigurationMatcher(this);
- if (loadedConfigData) {
- // first make sure we have the config to adapt
- selectDevice(mConfiguration.getDevice());
- selectDeviceState(mConfiguration.getDeviceState());
- mConfiguration.syncFolderConfig();
-
- matcher.adaptConfigSelection(false);
-
- IAndroidTarget target = mConfiguration.getTarget();
- selectTarget(target);
- targetData = Sdk.getCurrent().getTargetData(target);
- } else {
- matcher.findAndSetCompatibleConfig(false);
-
- // Default to modern layout lib
- IAndroidTarget target = ConfigurationMatcher.findDefaultRenderTarget(this);
- if (target != null) {
- targetData = Sdk.getCurrent().getTargetData(target);
- selectTarget(target);
- mConfiguration.setTarget(target, true);
- }
- }
-
- // Update activity: This is done before updateThemes() since
- // the themes selection can depend on the currently selected activity
- // (e.g. when there are manifest registrations for the theme to use
- // for a given activity)
- updateActivity();
-
- // Update themes. This is done after updating the devices above,
- // since we want to look at the chosen device size to decide
- // what the default theme (for example, with Honeycomb we choose
- // Holo as the default theme but only if the screen size is XLARGE
- // (and of course only if the manifest does not specify another
- // default theme).
- updateThemes();
-
- // update the string showing the config value
- selectConfiguration(mConfiguration.getEditedConfig());
-
- // compute the final current config
- mConfiguration.syncFolderConfig();
- } else if (targetStatus == LoadStatus.FAILED) {
- setVisible(true);
- }
- } finally {
- mDisableUpdates--;
- }
- }
-
- return targetData;
- }
-
- /**
- * This is a temporary workaround for a infrequently happening bug; apparently
- * there are cases where the configuration chooser isn't shown
- */
- public void ensureVisible() {
- if (!isVisible()) {
- LoadStatus sdkStatus = AdtPlugin.getDefault().getSdkLoadStatus();
- if (sdkStatus == LoadStatus.LOADED) {
- onXmlModelLoaded();
- }
- }
- }
-
- /**
- * An alternate layout for this layout has been created. This means that the
- * current layout may no longer be a best fit. However, since we support multiple
- * layouts being open at the same time, we need to adjust the current configuration
- * back to something where this layout <b>is</b> a best match.
- */
- public void onAlternateLayoutCreated() {
- IFile best = ConfigurationMatcher.getBestFileMatch(this);
- if (best != null && !best.equals(mEditedFile)) {
- ConfigurationMatcher matcher = new ConfigurationMatcher(this);
- matcher.adaptConfigSelection(true /*needBestMatch*/);
- mConfiguration.syncFolderConfig();
- if (mClient != null) {
- mClient.changed(MASK_ALL);
- }
- }
- }
-
- /**
- * Loads the list of {@link Device}s and inits the UI with it.
- */
- private void initDevices() {
- final Sdk sdk = Sdk.getCurrent();
- if (sdk != null) {
- DeviceManager manager = sdk.getDeviceManager();
- // This method can be called more than once, so avoid duplicate entries
- manager.unregisterListener(this);
- manager.registerListener(this);
- mDevices = manager.getDevices(DeviceManager.ALL_DEVICES);
- } else {
- mDevices = new ArrayList<Device>();
- }
- }
-
- /**
- * Loads the list of {@link IAndroidTarget} and inits the UI with it.
- */
- private boolean initTargets() {
- mTargetList.clear();
-
- Sdk currentSdk = Sdk.getCurrent();
- if (currentSdk != null) {
- IAndroidTarget[] targets = currentSdk.getTargets();
- for (int i = 0 ; i < targets.length; i++) {
- if (targets[i].hasRenderingLibrary()) {
- mTargetList.add(targets[i]);
- }
- }
-
- return true;
- }
-
- return false;
- }
-
- /** Ensures that the configuration has been initialized */
- public void ensureInitialized() {
- if (mConfiguration.getDevice() == null && mEditedFile != null) {
- String data = ConfigurationDescription.getDescription(mEditedFile);
- if (mInitialState != null) {
- data = mInitialState;
- mInitialState = null;
- }
- if (data != null) {
- mConfiguration.initialize(data);
- mConfiguration.syncFolderConfig();
- }
- }
- }
-
- private void updateDevices() {
- if (mDevices.size() == 0) {
- initDevices();
- }
- }
-
- private void updateTargets() {
- if (mTargetList.size() == 0) {
- if (!initTargets()) {
- return;
- }
- }
-
- IAndroidTarget renderingTarget = mConfiguration.getTarget();
-
- IAndroidTarget match = null;
- for (IAndroidTarget target : mTargetList) {
- if (renderingTarget != null) {
- // use equals because the rendering could be from a previous SDK, so
- // it may not be the same instance.
- if (renderingTarget.equals(target)) {
- match = target;
- }
- } else if (mProjectTarget == target) {
- match = target;
- }
-
- }
-
- if (match == null) {
- // the rendering target is the same as the project.
- renderingTarget = mProjectTarget;
- } else {
- // set the rendering target to the new object.
- renderingTarget = match;
- }
-
- mConfiguration.setTarget(renderingTarget, true);
- selectTarget(renderingTarget);
- }
-
- /** Update the toolbar whenever a label has changed, to not only
- * cause the layout in the current toolbar to update, but to possibly
- * wrap the toolbars and update the layout of the surrounding area.
- */
- private void resizeToolBar() {
- Point size = getSize();
- Point newSize = computeSize(size.x, SWT.DEFAULT, true);
- setSize(newSize);
- Composite parent = getParent();
- parent.layout();
- parent.redraw();
- }
-
-
- Image getOrientationIcon(ScreenOrientation orientation, boolean flip) {
- IconFactory icons = IconFactory.getInstance();
- switch (orientation) {
- case LANDSCAPE:
- return icons.getIcon(flip ? ICON_LANDSCAPE_FLIP : ICON_LANDSCAPE);
- case SQUARE:
- return icons.getIcon(ICON_SQUARE);
- case PORTRAIT:
- default:
- return icons.getIcon(flip ? ICON_PORTRAIT_FLIP : ICON_PORTRAIT);
- }
- }
-
- ImageDescriptor getOrientationImage(ScreenOrientation orientation, boolean flip) {
- IconFactory icons = IconFactory.getInstance();
- switch (orientation) {
- case LANDSCAPE:
- return icons.getImageDescriptor(flip ? ICON_LANDSCAPE_FLIP : ICON_LANDSCAPE);
- case SQUARE:
- return icons.getImageDescriptor(ICON_SQUARE);
- case PORTRAIT:
- default:
- return icons.getImageDescriptor(flip ? ICON_PORTRAIT_FLIP : ICON_PORTRAIT);
- }
- }
-
- @NonNull
- ScreenOrientation getOrientation(State state) {
- FolderConfiguration config = DeviceConfigHelper.getFolderConfig(state);
- ScreenOrientation orientation = null;
- if (config != null && config.getScreenOrientationQualifier() != null) {
- orientation = config.getScreenOrientationQualifier().getValue();
- }
-
- if (orientation == null) {
- orientation = ScreenOrientation.PORTRAIT;
- }
-
- return orientation;
- }
-
- /**
- * Stores the current config selection into the edited file such that we can
- * bring it back the next time this layout is opened.
- */
- public void saveConstraints() {
- String description = mConfiguration.toPersistentString();
- if (description != null && !description.isEmpty()) {
- ConfigurationDescription.setDescription(mEditedFile, description);
- }
- }
-
- // ---- Setting the current UI state ----
-
- void selectDeviceState(@Nullable State state) {
- assert isUiThread();
- try {
- mDisableUpdates++;
- mOrientationCombo.setData(state);
-
- State nextState = mConfiguration.getNextDeviceState(state);
- mOrientationCombo.setImage(getOrientationIcon(getOrientation(state),
- nextState != state));
- } finally {
- mDisableUpdates--;
- }
- }
-
- void selectTarget(IAndroidTarget target) {
- assert isUiThread();
- try {
- mDisableUpdates++;
- mTargetCombo.setData(target);
- String label = getRenderingTargetLabel(target, true);
- mTargetCombo.setText(label);
- resizeToolBar();
- } finally {
- mDisableUpdates--;
- }
- }
-
- /**
- * Selects a given {@link Device} in the device combo, if it is found.
- * @param device the device to select
- * @return true if the device was found.
- */
- boolean selectDevice(@Nullable Device device) {
- assert isUiThread();
- try {
- mDisableUpdates++;
- mDeviceCombo.setData(device);
- if (device != null) {
- mDeviceCombo.setText(getDeviceLabel(device, true));
- } else {
- mDeviceCombo.setText("Device");
- }
- resizeToolBar();
- } finally {
- mDisableUpdates--;
- }
-
- return false;
- }
-
- void selectActivity(@Nullable String fqcn) {
- assert isUiThread();
- try {
- mDisableUpdates++;
- if (fqcn != null) {
- mActivityCombo.setData(fqcn);
- String label = getActivityLabel(fqcn, true);
- mActivityCombo.setText(label);
- } else {
- mActivityCombo.setText("(Select)");
- }
- resizeToolBar();
- } finally {
- mDisableUpdates--;
- }
- }
-
- void selectTheme(@Nullable String theme) {
- assert isUiThread();
- try {
- mDisableUpdates++;
- assert theme == null || theme.startsWith(STYLE_RESOURCE_PREFIX)
- || theme.startsWith(ANDROID_STYLE_RESOURCE_PREFIX) : theme;
- mThemeCombo.setData(theme);
- if (theme != null) {
- mThemeCombo.setText(getThemeLabel(theme, true));
- } else {
- // FIXME eclipse claims this is dead code.
- mThemeCombo.setText("(Set Theme)");
- }
- resizeToolBar();
- } finally {
- mDisableUpdates--;
- }
- }
-
- void selectLocale(@Nullable Locale locale) {
- assert isUiThread();
- try {
- mDisableUpdates++;
- mLocaleCombo.setData(locale);
- String label = Strings.nullToEmpty(getLocaleLabel(this, locale, true));
- mLocaleCombo.setText(label);
-
- Image image = getFlagImage(locale);
- mLocaleCombo.setImage(image);
-
- resizeToolBar();
- } finally {
- mDisableUpdates--;
- }
- }
-
- @NonNull
- Image getFlagImage(@Nullable Locale locale) {
- if (locale != null) {
- return locale.getFlagImage();
- }
-
- return FlagManager.getGlobeIcon();
- }
-
- private void selectConfiguration(FolderConfiguration fileConfig) {
- /* For now, don't show any text in the configuration combo, use just an
- icon. This has the advantage that the configuration contents don't
- shift around, so you can for example click back and forth between
- portrait and landscape without the icon moving under the mouse.
- If this works well, remove this whole method post ADT 21.
- assert isUiThread();
- try {
- String current = mEditedFile.getParent().getName();
- if (current.equals(FD_RES_LAYOUT)) {
- current = "default";
- }
-
- // Pretty things up a bit
- //if (current == null || current.equals("default")) {
- // current = "Default Configuration";
- //}
- mConfigCombo.setText(current);
- resizeToolBar();
- } finally {
- mDisableUpdates--;
- }
- */
- }
-
- /**
- * Finds a locale matching the config from a file.
- *
- * @param language the language qualifier or null if none is set.
- * @param region the region qualifier or null if none is set.
- * @return true if there was a change in the combobox as a result of
- * applying the locale
- */
- private boolean setLocale(@Nullable Locale locale) {
- boolean changed = !Objects.equal(mConfiguration.getLocale(), locale);
- selectLocale(locale);
-
- return changed;
- }
-
- // ---- Creating UI labels ----
-
- /**
- * Returns a suitable label to use to display the given activity
- *
- * @param fqcn the activity class to look up a label for
- * @param brief if true, generate a brief label (suitable for a toolbar
- * button), otherwise a fuller name (suitable for a menu item)
- * @return the label
- */
- public static String getActivityLabel(String fqcn, boolean brief) {
- if (brief) {
- String label = fqcn;
- int packageIndex = label.lastIndexOf('.');
- if (packageIndex != -1) {
- label = label.substring(packageIndex + 1);
- }
- int innerClass = label.lastIndexOf('$');
- if (innerClass != -1) {
- label = label.substring(innerClass + 1);
- }
-
- // Also strip out the "Activity" or "Fragment" common suffix
- // if this is a long name
- if (label.endsWith("Activity") && label.length() > 8 + 12) { // 12 chars + 8 in suffix
- label = label.substring(0, label.length() - 8);
- } else if (label.endsWith("Fragment") && label.length() > 8 + 12) {
- label = label.substring(0, label.length() - 8);
- }
-
- return label;
- }
-
- return fqcn;
- }
-
- /**
- * Returns a suitable label to use to display the given theme
- *
- * @param theme the theme to produce a label for
- * @param brief if true, generate a brief label (suitable for a toolbar
- * button), otherwise a fuller name (suitable for a menu item)
- * @return the label
- */
- public static String getThemeLabel(String theme, boolean brief) {
- theme = ResourceHelper.styleToTheme(theme);
-
- if (brief) {
- int index = theme.lastIndexOf('.');
- if (index < theme.length() - 1) {
- return theme.substring(index + 1);
- }
- }
- return theme;
- }
-
- /**
- * Returns a suitable label to use to display the given rendering target
- *
- * @param target the target to produce a label for
- * @param brief if true, generate a brief label (suitable for a toolbar
- * button), otherwise a fuller name (suitable for a menu item)
- * @return the label
- */
- public static String getRenderingTargetLabel(IAndroidTarget target, boolean brief) {
- if (target == null) {
- return "<null>";
- }
-
- AndroidVersion version = target.getVersion();
-
- if (brief) {
- if (target.isPlatform()) {
- return Integer.toString(version.getApiLevel());
- } else {
- return target.getName() + ':' + Integer.toString(version.getApiLevel());
- }
- }
-
- String label = String.format("API %1$d: %2$s",
- version.getApiLevel(),
- target.getShortClasspathName());
-
- return label;
- }
-
- /**
- * Returns a suitable label to use to display the given device
- *
- * @param device the device to produce a label for
- * @param brief if true, generate a brief label (suitable for a toolbar
- * button), otherwise a fuller name (suitable for a menu item)
- * @return the label
- */
- public static String getDeviceLabel(@Nullable Device device, boolean brief) {
- if (device == null) {
- return "";
- }
- String name = device.getName();
-
- if (brief) {
- // Produce a really brief summary of the device name, suitable for
- // use in the narrow space available in the toolbar for example
- int nexus = name.indexOf("Nexus"); //$NON-NLS-1$
- if (nexus != -1) {
- int begin = name.indexOf('(');
- if (begin != -1) {
- begin++;
- int end = name.indexOf(')', begin);
- if (end != -1) {
- return name.substring(begin, end).trim();
- }
- }
- }
- }
-
- return name;
- }
-
- /**
- * Returns a suitable label to use to display the given locale
- *
- * @param chooser the chooser, if known
- * @param locale the locale to look up a label for
- * @param brief if true, generate a brief label (suitable for a toolbar
- * button), otherwise a fuller name (suitable for a menu item)
- * @return the label
- */
- @Nullable
- public static String getLocaleLabel(
- @Nullable ConfigurationChooser chooser,
- @Nullable Locale locale,
- boolean brief) {
- if (locale == null) {
- return null;
- }
-
- if (!locale.hasLanguage()) {
- if (brief) {
- // Just use the icon
- return "";
- }
-
- boolean hasLocale = false;
- ResourceRepository projectRes = chooser != null ? chooser.mClient.getProjectResources()
- : null;
- if (projectRes != null) {
- hasLocale = projectRes.getLanguages().size() > 0;
- }
-
- if (hasLocale) {
- return "Other";
- } else {
- return "Any";
- }
- }
-
- String languageCode = locale.qualifier.getLanguage();
- String languageName = LocaleManager.getLanguageName(languageCode);
-
- if (!locale.hasRegion()) {
- // TODO: Make the region string use "Other" instead of "Any" if
- // there is more than one region for a given language
- //if (regions.size() > 0) {
- // return String.format("%1$s / Other", language);
- //} else {
- // return String.format("%1$s / Any", language);
- //}
- if (!brief && languageName != null) {
- return String.format("%1$s (%2$s)", languageName, languageCode);
- } else {
- return languageCode;
- }
- } else {
- String regionCode = locale.qualifier.getRegion();
- if (!brief && languageName != null) {
- String regionName = LocaleManager.getRegionName(regionCode);
- if (regionName != null) {
- return String.format("%1$s (%2$s) in %3$s (%4$s)", languageName, languageCode,
- regionName, regionCode);
- }
- return String.format("%1$s (%2$s) in %3$s", languageName, languageCode,
- regionCode);
- }
- return String.format("%1$s / %2$s", languageCode, regionCode);
- }
- }
-
- // ---- Implements DevicesChangedListener ----
-
- @Override
- public void onDevicesChanged() {
- final Sdk sdk = Sdk.getCurrent();
- if (sdk != null) {
- mDevices = sdk.getDeviceManager().getDevices(DeviceManager.ALL_DEVICES);
- } else {
- mDevices = new ArrayList<Device>();
- }
- }
-
- // ---- Reacting to UI changes ----
-
- /**
- * Called when the selection of the device combo changes.
- */
- void onDeviceChange() {
- // because changing the content of a combo triggers a change event, respect the
- // mDisableUpdates flag
- if (mDisableUpdates > 0) {
- return;
- }
-
- // Attempt to preserve the device state
- String stateName = null;
- Device prevDevice = mConfiguration.getDevice();
- State prevState = mConfiguration.getDeviceState();
- Device device = (Device) mDeviceCombo.getData();
- if (prevDevice != null && prevState != null && device != null) {
- // get the previous config, so that we can look for a close match
- FolderConfiguration oldConfig = DeviceConfigHelper.getFolderConfig(prevState);
- if (oldConfig != null) {
- stateName = ConfigurationMatcher.getClosestMatch(oldConfig, device.getAllStates());
- }
- }
- mConfiguration.setDevice(device, true);
- State newState = Configuration.getState(device, stateName);
- mConfiguration.setDeviceState(newState, true);
- selectDeviceState(newState);
- mConfiguration.syncFolderConfig();
-
- // Notify
- IFile file = mEditedFile;
- boolean accepted = mClient.changed(CFG_DEVICE | CFG_DEVICE_STATE);
- if (!accepted) {
- mConfiguration.setDevice(prevDevice, true);
- mConfiguration.setDeviceState(prevState, true);
- mConfiguration.syncFolderConfig();
- selectDevice(prevDevice);
- selectDeviceState(prevState);
- return;
- } else {
- syncToVariations(CFG_DEVICE | CFG_DEVICE_STATE, file, mConfiguration, false, true);
- }
-
- saveConstraints();
- }
-
- /**
- * Synchronizes changes to the given attributes (indicated by the mask
- * referencing the {@code CFG_} configuration attribute bit flags in
- * {@link Configuration} to the layout variations of the given updated file.
- *
- * @param flags the attributes which were updated
- * @param updatedFile the file which was updated
- * @param base the base configuration to base the chooser off of
- * @param includeSelf whether the updated file itself should be updated
- * @param async whether the updates should be performed asynchronously
- */
- public void syncToVariations(
- final int flags,
- final @NonNull IFile updatedFile,
- final @NonNull Configuration base,
- final boolean includeSelf,
- boolean async) {
- if (async) {
- getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- doSyncToVariations(flags, updatedFile, includeSelf, base);
- }
- });
- } else {
- doSyncToVariations(flags, updatedFile, includeSelf, base);
- }
- }
-
- private void doSyncToVariations(int flags, IFile updatedFile, boolean includeSelf,
- Configuration base) {
- // Synchronize the given changes to other configurations as well
- List<IFile> files = AdtUtils.getResourceVariations(updatedFile, includeSelf);
- for (IFile file : files) {
- Configuration configuration = Configuration.create(base, file);
- configuration.setTheme(base.getTheme());
- configuration.setActivity(base.getActivity());
- Collection<IEditorPart> editors = AdtUtils.findEditorsFor(file, false);
- boolean found = false;
- for (IEditorPart editor : editors) {
- if (editor instanceof CommonXmlEditor) {
- CommonXmlDelegate delegate = ((CommonXmlEditor) editor).getDelegate();
- if (delegate instanceof LayoutEditorDelegate) {
- editor = ((LayoutEditorDelegate) delegate).getGraphicalEditor();
- }
- }
- if (editor instanceof GraphicalEditorPart) {
- ConfigurationChooser chooser =
- ((GraphicalEditorPart) editor).getConfigurationChooser();
- chooser.setConfiguration(configuration);
- found = true;
- }
- }
- if (!found) {
- // Just update the file persistence
- String description = configuration.toPersistentString();
- ConfigurationDescription.setDescription(file, description);
- }
- }
- }
-
- /**
- * Called when the device config selection changes.
- */
- void onDeviceConfigChange() {
- // because changing the content of a combo triggers a change event, respect the
- // mDisableUpdates flag
- if (mDisableUpdates > 0) {
- return;
- }
-
- State prev = mConfiguration.getDeviceState();
- State state = (State) mOrientationCombo.getData();
- mConfiguration.setDeviceState(state, false);
-
- if (mClient != null) {
- boolean accepted = mClient.changed(CFG_DEVICE | CFG_DEVICE_STATE);
- if (!accepted) {
- mConfiguration.setDeviceState(prev, false);
- selectDeviceState(prev);
- return;
- }
- }
-
- saveConstraints();
- }
-
- /**
- * Call back for language combo selection
- */
- void onLocaleChange() {
- // because mLocaleList triggers onLocaleChange at each modification, the filling
- // of the combo with data will trigger notifications, and we don't want that.
- if (mDisableUpdates > 0) {
- return;
- }
-
- Locale prev = mConfiguration.getLocale();
- Locale locale = (Locale) mLocaleCombo.getData();
- if (locale == null) {
- locale = Locale.ANY;
- }
- mConfiguration.setLocale(locale, false);
-
- if (mClient != null) {
- boolean accepted = mClient.changed(CFG_LOCALE);
- if (!accepted) {
- mConfiguration.setLocale(prev, false);
- selectLocale(prev);
- }
- }
-
- // Store locale project-wide setting
- mConfiguration.saveRenderState();
- }
-
-
- void onThemeChange() {
- if (mDisableUpdates > 0) {
- return;
- }
-
- String prev = mConfiguration.getTheme();
- mConfiguration.setTheme((String) mThemeCombo.getData());
-
- if (mClient != null) {
- boolean accepted = mClient.changed(CFG_THEME);
- if (!accepted) {
- mConfiguration.setTheme(prev);
- selectTheme(prev);
- return;
- } else {
- syncToVariations(CFG_DEVICE|CFG_DEVICE_STATE, mEditedFile, mConfiguration,
- false, true);
- }
- }
-
- saveConstraints();
- }
-
- void notifyFolderConfigChanged() {
- if (mDisableUpdates > 0 || mClient == null) {
- return;
- }
-
- if (mClient.changed(CFG_FOLDER)) {
- saveConstraints();
- }
- }
-
- void onSelectActivity() {
- if (mDisableUpdates > 0) {
- return;
- }
-
- String activity = (String) mActivityCombo.getData();
- mConfiguration.setActivity(activity);
-
- if (activity == null) {
- return;
- }
-
- // See if there is a default theme assigned to this activity, and if so, use it
- ManifestInfo manifest = ManifestInfo.get(mEditedFile.getProject());
- String preferred = null;
- ActivityAttributes attributes = manifest.getActivityAttributes(activity);
- if (attributes != null) {
- preferred = attributes.getTheme();
- }
- if (preferred != null && !Objects.equal(preferred, mConfiguration.getTheme())) {
- // Yes, switch to it
- selectTheme(preferred);
- onThemeChange();
- }
-
- // Persist in XML
- if (mClient != null) {
- mClient.setActivity(activity);
- }
-
- saveConstraints();
- }
-
- /**
- * Call back for api level combo selection
- */
- void onRenderingTargetChange() {
- // because mApiCombo triggers onApiLevelChange at each modification, the filling
- // of the combo with data will trigger notifications, and we don't want that.
- if (mDisableUpdates > 0) {
- return;
- }
-
- IAndroidTarget prevTarget = mConfiguration.getTarget();
- String prevTheme = mConfiguration.getTheme();
-
- int changeFlags = 0;
-
- // tell the listener a new rendering target is being set. Need to do this before updating
- // mRenderingTarget.
- if (prevTarget != null) {
- changeFlags |= CFG_TARGET;
- mClient.aboutToChange(changeFlags);
- }
-
- IAndroidTarget target = (IAndroidTarget) mTargetCombo.getData();
- mConfiguration.setTarget(target, true);
-
- // force a theme update to reflect the new rendering target.
- // This must be done after computeCurrentConfig since it'll depend on the currentConfig
- // to figure out the theme list.
- String oldTheme = mConfiguration.getTheme();
- updateThemes();
- // updateThemes may change the theme (based on theme availability in the new rendering
- // target) so mark theme change if necessary
- if (!Objects.equal(oldTheme, mConfiguration.getTheme())) {
- changeFlags |= CFG_THEME;
- }
-
- if (target != null) {
- changeFlags |= CFG_TARGET;
- changeFlags |= CFG_FOLDER; // In case we added a -vNN qualifier
- }
-
- // Store project-wide render-target setting
- mConfiguration.saveRenderState();
-
- mConfiguration.syncFolderConfig();
-
- if (mClient != null) {
- boolean accepted = mClient.changed(changeFlags);
- if (!accepted) {
- mConfiguration.setTarget(prevTarget, true);
- mConfiguration.setTheme(prevTheme);
- mConfiguration.syncFolderConfig();
- selectTheme(prevTheme);
- selectTarget(prevTarget);
- }
- }
- }
-
- /**
- * Syncs this configuration to the project wide locale and render target settings. The
- * locale may ignore the project-wide setting if it is a locale-specific
- * configuration.
- *
- * @return true if one or both of the toggles were changed, false if there were no
- * changes
- */
- public boolean syncRenderState() {
- if (mConfiguration.getEditedConfig() == null) {
- // Startup; ignore
- return false;
- }
-
- boolean renderTargetChanged = false;
-
- // When a page is re-activated, force the toggles to reflect the current project
- // state
-
- Pair<Locale, IAndroidTarget> pair = Configuration.loadRenderState(this);
-
- int changeFlags = 0;
- // Only sync the locale if this layout is not already a locale-specific layout!
- if (pair != null && !mConfiguration.isLocaleSpecificLayout()) {
- Locale locale = pair.getFirst();
- if (locale != null) {
- boolean localeChanged = setLocale(locale);
- if (localeChanged) {
- changeFlags |= CFG_LOCALE;
- }
- } else {
- locale = Locale.ANY;
- }
- mConfiguration.setLocale(locale, true);
- }
-
- // Sync render target
- IAndroidTarget configurationTarget = mConfiguration.getTarget();
- IAndroidTarget target = pair != null ? pair.getSecond() : configurationTarget;
- if (target != null && configurationTarget != target) {
- if (mClient != null && configurationTarget != null) {
- changeFlags |= CFG_TARGET;
- mClient.aboutToChange(changeFlags);
- }
-
- mConfiguration.setTarget(target, true);
- selectTarget(target);
- renderTargetChanged = true;
- }
-
- // Neither locale nor render target changed: nothing to do
- if (changeFlags == 0) {
- return false;
- }
-
- // Update the locale and/or the render target. This code contains a logical
- // merge of the onRenderingTargetChange() and onLocaleChange() methods, combined
- // such that we don't duplicate work.
-
- // Compute the new configuration; we want to do this both for locale changes
- // and for render targets.
- mConfiguration.syncFolderConfig();
- changeFlags |= CFG_FOLDER; // in case we added/remove a -v<NN> qualifier
-
- if (renderTargetChanged) {
- // force a theme update to reflect the new rendering target.
- // This must be done after computeCurrentConfig since it'll depend on the currentConfig
- // to figure out the theme list.
- updateThemes();
- }
-
- if (mClient != null) {
- mClient.changed(changeFlags);
- }
-
- return true;
- }
-
- // ---- Populate data structures with themes, locales, etc ----
-
- /**
- * Updates the internal list of themes.
- */
- private void updateThemes() {
- if (mClient == null) {
- return; // can't do anything without it.
- }
-
- ResourceRepository frameworkRes = mClient.getFrameworkResources(
- mConfiguration.getTarget());
-
- mDisableUpdates++;
-
- try {
- if (mEditedFile != null) {
- String theme = mConfiguration.getTheme();
- if (theme == null || theme.isEmpty() || mClient.getIncludedWithin() != null) {
- mConfiguration.setTheme(null);
- mConfiguration.computePreferredTheme();
- }
- assert mConfiguration.getTheme() != null;
- }
-
- mThemeList.clear();
-
- ArrayList<String> themes = new ArrayList<String>();
- ResourceRepository projectRes = mClient.getProjectResources();
- // in cases where the opened file is not linked to a project, this could be null.
- if (projectRes != null) {
- // get the configured resources for the project
- Map<ResourceType, Map<String, ResourceValue>> configuredProjectRes =
- mClient.getConfiguredProjectResources();
-
- if (configuredProjectRes != null) {
- // get the styles.
- Map<String, ResourceValue> styleMap = configuredProjectRes.get(
- ResourceType.STYLE);
-
- if (styleMap != null) {
- // collect the themes out of all the styles, ie styles that extend,
- // directly or indirectly a platform theme.
- for (ResourceValue value : styleMap.values()) {
- if (isTheme(value, styleMap, null)) {
- String theme = value.getName();
- themes.add(theme);
- }
- }
-
- Collections.sort(themes);
-
- for (String theme : themes) {
- if (!theme.startsWith(PREFIX_RESOURCE_REF)) {
- theme = STYLE_RESOURCE_PREFIX + theme;
- }
- mThemeList.add(theme);
- }
- }
- }
- themes.clear();
- }
-
- // get the themes, and languages from the Framework.
- if (frameworkRes != null) {
- // get the configured resources for the framework
- Map<ResourceType, Map<String, ResourceValue>> frameworResources =
- frameworkRes.getConfiguredResources(mConfiguration.getFullConfig());
-
- if (frameworResources != null) {
- // get the styles.
- Map<String, ResourceValue> styles = frameworResources.get(ResourceType.STYLE);
-
- // collect the themes out of all the styles.
- for (ResourceValue value : styles.values()) {
- String name = value.getName();
- if (name.startsWith("Theme.") || name.equals("Theme")) { //$NON-NLS-1$ //$NON-NLS-2$
- themes.add(value.getName());
- }
- }
-
- // sort them and add them to the combo
- Collections.sort(themes);
-
- for (String theme : themes) {
- if (!theme.startsWith(PREFIX_RESOURCE_REF)) {
- theme = ANDROID_STYLE_RESOURCE_PREFIX + theme;
- }
- mThemeList.add(theme);
- }
-
- themes.clear();
- }
- }
-
- // Migration: In the past we didn't store the style prefix in the settings;
- // this meant we might lose track of whether the theme is a project style
- // or a framework style. For now we need to migrate. Search through the
- // theme list until we have a match
- String theme = mConfiguration.getTheme();
- if (theme != null && !theme.startsWith(PREFIX_RESOURCE_REF)) {
- String projectStyle = STYLE_RESOURCE_PREFIX + theme;
- String frameworkStyle = ANDROID_STYLE_RESOURCE_PREFIX + theme;
- for (String t : mThemeList) {
- if (t.equals(projectStyle)) {
- mConfiguration.setTheme(projectStyle);
- break;
- } else if (t.equals(frameworkStyle)) {
- mConfiguration.setTheme(frameworkStyle);
- break;
- }
- }
- if (!theme.startsWith(PREFIX_RESOURCE_REF)) {
- // Arbitrary guess
- if (theme.startsWith("Theme.")) {
- theme = ANDROID_STYLE_RESOURCE_PREFIX + theme;
- } else {
- theme = STYLE_RESOURCE_PREFIX + theme;
- }
- }
- }
-
- // TODO: Handle the case where you have a theme persisted that isn't available??
- // We could look up mConfiguration.theme and make sure it appears in the list! And if
- // not, picking one.
- selectTheme(mConfiguration.getTheme());
- } finally {
- mDisableUpdates--;
- }
- }
-
- private void updateActivity() {
- if (mEditedFile != null) {
- String preferred = getPreferredActivity(mEditedFile);
- selectActivity(preferred);
- }
- }
-
- /**
- * Updates the locale combo.
- * This must be called from the UI thread.
- */
- public void updateLocales() {
- if (mClient == null) {
- return; // can't do anything w/o it.
- }
-
- mDisableUpdates++;
-
- try {
- mLocaleList.clear();
-
- SortedSet<String> languages = null;
-
- // get the languages from the project.
- ResourceRepository projectRes = mClient.getProjectResources();
-
- // in cases where the opened file is not linked to a project, this could be null.
- if (projectRes != null) {
- // now get the languages from the project.
- languages = projectRes.getLanguages();
-
- for (String language : languages) {
- // find the matching regions and add them
- SortedSet<String> regions = projectRes.getRegions(language);
- for (String region : regions) {
- LocaleQualifier locale = LocaleQualifier.getQualifier(language + "-r" + region);
- if (locale != null) {
- mLocaleList.add(Locale.create(locale));
- }
- }
-
- // now the entry for the other regions the language alone
- // create a region qualifier that will never be matched by qualified resources.
- LocaleQualifier locale = new LocaleQualifier(language);
- mLocaleList.add(Locale.create(locale));
- }
- }
-
- // create language/region qualifier that will never be matched by qualified resources.
- mLocaleList.add(Locale.ANY);
-
- Locale locale = mConfiguration.getLocale();
- setLocale(locale);
- } finally {
- mDisableUpdates--;
- }
- }
-
- @Nullable
- private String getPreferredActivity(@NonNull IFile file) {
- // Store/restore the activity context in the config state to help with
- // performance if for some reason we can't write it into the XML file and to
- // avoid having to open the model below
- if (mConfiguration.getActivity() != null) {
- return mConfiguration.getActivity();
- }
-
- IProject project = file.getProject();
-
- // Look up from XML file
- Document document = DomUtilities.getDocument(file);
- if (document != null) {
- Element element = document.getDocumentElement();
- if (element != null) {
- String activity = element.getAttributeNS(TOOLS_URI, ATTR_CONTEXT);
- if (activity != null && !activity.isEmpty()) {
- if (activity.startsWith(".") || activity.indexOf('.') == -1) { //$NON-NLS-1$
- ManifestInfo manifest = ManifestInfo.get(project);
- String pkg = manifest.getPackage();
- if (!pkg.isEmpty()) {
- if (activity.startsWith(".")) { //$NON-NLS-1$
- activity = pkg + activity;
- } else {
- activity = activity + '.' + pkg;
- }
- }
- }
-
- mConfiguration.setActivity(activity);
- saveConstraints();
- return activity;
- }
- }
- }
-
- // No, not available there: try to infer it from the code index
- String includedIn = null;
- Reference includedWithin = mClient.getIncludedWithin();
- if (mClient != null && includedWithin != null) {
- includedIn = includedWithin.getName();
- }
-
- ManifestInfo manifest = ManifestInfo.get(project);
- String pkg = manifest.getPackage();
- String layoutName = ResourceHelper.getLayoutName(mEditedFile);
-
- // If we are rendering a layout in included context, pick the theme
- // from the outer layout instead
- if (includedIn != null) {
- layoutName = includedIn;
- }
-
- String activity = ManifestInfo.guessActivity(project, layoutName, pkg);
-
- if (activity == null) {
- List<String> activities = ManifestInfo.getProjectActivities(project);
- if (activities.size() == 1) {
- activity = activities.get(0);
- }
- }
-
- if (activity != null) {
- mConfiguration.setActivity(activity);
- saveConstraints();
- return activity;
- }
-
- // TODO: Do anything else, such as pick the first activity found?
- // Or just leave some default label instead?
- // Also, figure out what to store in the mState so I don't keep trying
-
- return null;
- }
-
- /**
- * Returns whether the given <var>style</var> is a theme.
- * This is done by making sure the parent is a theme.
- * @param value the style to check
- * @param styleMap the map of styles for the current project. Key is the style name.
- * @param seen the map of styles we have already processed (or null if not yet
- * initialized). Only the keys are significant (since there is no IdentityHashSet).
- * @return True if the given <var>style</var> is a theme.
- */
- private static boolean isTheme(ResourceValue value, Map<String, ResourceValue> styleMap,
- IdentityHashMap<ResourceValue, Boolean> seen) {
- if (value instanceof StyleResourceValue) {
- StyleResourceValue style = (StyleResourceValue)value;
-
- boolean frameworkStyle = false;
- String parentStyle = style.getParentStyle();
- if (parentStyle == null) {
- // if there is no specified parent style we look an implied one.
- // For instance 'Theme.light' is implied child style of 'Theme',
- // and 'Theme.light.fullscreen' is implied child style of 'Theme.light'
- String name = style.getName();
- int index = name.lastIndexOf('.');
- if (index != -1) {
- parentStyle = name.substring(0, index);
- }
- } else {
- // remove the useless @ if it's there
- if (parentStyle.startsWith("@")) {
- parentStyle = parentStyle.substring(1);
- }
-
- // check for framework identifier.
- if (parentStyle.startsWith(ANDROID_NS_NAME_PREFIX)) {
- frameworkStyle = true;
- parentStyle = parentStyle.substring(ANDROID_NS_NAME_PREFIX.length());
- }
-
- // at this point we could have the format style/<name>. we want only the name
- if (parentStyle.startsWith("style/")) {
- parentStyle = parentStyle.substring("style/".length());
- }
- }
-
- if (parentStyle != null) {
- if (frameworkStyle) {
- // if the parent is a framework style, it has to be 'Theme' or 'Theme.*'
- return parentStyle.equals("Theme") || parentStyle.startsWith("Theme.");
- } else {
- // if it's a project style, we check this is a theme.
- ResourceValue parentValue = styleMap.get(parentStyle);
-
- // also prevent stack overflow in case the dev mistakenly declared
- // the parent of the style as the style itself.
- if (parentValue != null && !parentValue.equals(value)) {
- if (seen == null) {
- seen = new IdentityHashMap<ResourceValue, Boolean>();
- seen.put(value, Boolean.TRUE);
- } else if (seen.containsKey(parentValue)) {
- return false;
- }
- seen.put(parentValue, Boolean.TRUE);
- return isTheme(parentValue, styleMap, seen);
- }
- }
- }
- }
-
- return false;
- }
-
- /**
- * Returns true if this configuration chooser represents the best match for
- * the given file
- *
- * @param file the file to test
- * @param config the config to test
- * @return true if the given config is the best match for the given file
- */
- public boolean isBestMatchFor(IFile file, FolderConfiguration config) {
- ResourceFile match = mResources.getMatchingFile(mEditedFile.getName(),
- ResourceType.LAYOUT, config);
- if (match != null) {
- return match.getFile().equals(mEditedFile);
- }
-
- return false;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ConfigurationClient.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ConfigurationClient.java
deleted file mode 100644
index 3df2feda3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ConfigurationClient.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.configuration;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.rendering.api.ResourceValue;
-import com.android.ide.common.resources.ResourceRepository;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.IncludeFinder.Reference;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.LayoutCanvas;
-import com.android.resources.ResourceType;
-import com.android.sdklib.IAndroidTarget;
-
-import java.util.Map;
-
-/**
- * Interface implemented by clients who embed a {@link ConfigurationChooser}.
- */
-public interface ConfigurationClient {
- /**
- * The configuration is about to be changed.
- *
- * @param flags details about what changed; consult the {@code CFG_} flags
- * in {@link Configuration} such as
- * {@link Configuration#CFG_DEVICE},
- * {@link Configuration#CFG_LOCALE}, etc.
- */
- void aboutToChange(int flags);
-
- /**
- * The configuration has changed. If the client returns false, it means that
- * the change was rejected. This typically means that changing the
- * configuration in this particular way makes a configuration which has a
- * better file match than the current client's file, so it will open that
- * file to edit the new configuration -- and the current configuration
- * should go back to editing the state prior to this change.
- *
- * @param flags details about what changed; consult the {@code CFG_} flags
- * such as {@link Configuration#CFG_DEVICE},
- * {@link Configuration#CFG_LOCALE}, etc.
- * @return true if the change was accepted, false if it was rejected.
- */
- boolean changed(int flags);
-
- /**
- * Compute the project resources
- *
- * @return the project resources as a {@link ResourceRepository}
- */
- @Nullable
- ResourceRepository getProjectResources();
-
- /**
- * Compute the framework resources
- *
- * @return the project resources as a {@link ResourceRepository}
- */
- @Nullable
- ResourceRepository getFrameworkResources();
-
- /**
- * Compute the framework resources for the given Android API target
- *
- * @param target the target to look up framework resources for
- * @return the project resources as a {@link ResourceRepository}
- */
- @Nullable
- ResourceRepository getFrameworkResources(@Nullable IAndroidTarget target);
-
- /**
- * Returns the configured project resources for the current file and
- * configuration
- *
- * @return resource type maps to names to resource values
- */
- @NonNull
- Map<ResourceType, Map<String, ResourceValue>> getConfiguredProjectResources();
-
- /**
- * Returns the configured framework resources for the current file and
- * configuration
- *
- * @return resource type maps to names to resource values
- */
- @NonNull
- Map<ResourceType, Map<String, ResourceValue>> getConfiguredFrameworkResources();
-
- /**
- * If the current layout is an included layout rendered within an outer layout,
- * returns the outer layout.
- *
- * @return the outer including layout, or null
- */
- @Nullable
- Reference getIncludedWithin();
-
- /**
- * Called when the "Create" button is clicked.
- */
- void createConfigFile();
-
- /**
- * Called when an associated activity is picked
- *
- * @param fqcn the fully qualified class name for the associated activity context
- */
- void setActivity(@NonNull String fqcn);
-
- /**
- * Returns the associated layout canvas, if any
- *
- * @return the canvas, if any
- */
- @Nullable
- LayoutCanvas getCanvas();
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ConfigurationDescription.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ConfigurationDescription.java
deleted file mode 100644
index 956ac1839..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ConfigurationDescription.java
+++ /dev/null
@@ -1,395 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.configuration;
-
-import static com.android.SdkConstants.ANDROID_STYLE_RESOURCE_PREFIX;
-import static com.android.SdkConstants.ATTR_NAME;
-import static com.android.SdkConstants.ATTR_THEME;
-import static com.android.SdkConstants.PREFIX_RESOURCE_REF;
-import static com.android.SdkConstants.STYLE_RESOURCE_PREFIX;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.resources.ResourceRepository;
-import com.android.ide.common.resources.configuration.DeviceConfigHelper;
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.common.resources.configuration.LocaleQualifier;
-import com.android.ide.common.resources.configuration.ScreenSizeQualifier;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo.ActivityAttributes;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.resources.NightMode;
-import com.android.resources.ResourceFolderType;
-import com.android.resources.ScreenSize;
-import com.android.resources.UiMode;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.devices.Device;
-import com.android.sdklib.devices.State;
-import com.google.common.base.Splitter;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.QualifiedName;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-import java.util.Collection;
-import java.util.List;
-
-/** A description of a configuration, used for persistence */
-public class ConfigurationDescription {
- private static final String TAG_PREVIEWS = "previews"; //$NON-NLS-1$
- private static final String TAG_PREVIEW = "preview"; //$NON-NLS-1$
- private static final String ATTR_TARGET = "target"; //$NON-NLS-1$
- private static final String ATTR_CONFIG = "config"; //$NON-NLS-1$
- private static final String ATTR_LOCALE = "locale"; //$NON-NLS-1$
- private static final String ATTR_ACTIVITY = "activity"; //$NON-NLS-1$
- private static final String ATTR_DEVICE = "device"; //$NON-NLS-1$
- private static final String ATTR_STATE = "devicestate"; //$NON-NLS-1$
- private static final String ATTR_UIMODE = "ui"; //$NON-NLS-1$
- private static final String ATTR_NIGHTMODE = "night"; //$NON-NLS-1$
- private final static String SEP_LOCALE = "-"; //$NON-NLS-1$
-
- /**
- * Settings name for file-specific configuration preferences, such as which theme or
- * device to render the current layout with
- */
- public final static QualifiedName NAME_CONFIG_STATE =
- new QualifiedName(AdtPlugin.PLUGIN_ID, "state");//$NON-NLS-1$
-
- /** The project corresponding to this configuration's description */
- public final IProject project;
-
- /** The display name */
- public String displayName;
-
- /** The theme */
- public String theme;
-
- /** The target */
- public IAndroidTarget target;
-
- /** The display name */
- public FolderConfiguration folder;
-
- /** The locale */
- public Locale locale = Locale.ANY;
-
- /** The device */
- public Device device;
-
- /** The device state */
- public State state;
-
- /** The activity */
- public String activity;
-
- /** UI mode */
- @NonNull
- public UiMode uiMode = UiMode.NORMAL;
-
- /** Night mode */
- @NonNull
- public NightMode nightMode = NightMode.NOTNIGHT;
-
- private ConfigurationDescription(@Nullable IProject project) {
- this.project = project;
- }
-
- /**
- * Returns the persistent configuration description from the given file
- *
- * @param file the file to look up a description from
- * @return the description or null if never written
- */
- @Nullable
- public static String getDescription(@NonNull IFile file) {
- return AdtPlugin.getFileProperty(file, NAME_CONFIG_STATE);
- }
-
- /**
- * Sets the persistent configuration description data for the given file
- *
- * @param file the file to associate the description with
- * @param description the description
- */
- public static void setDescription(@NonNull IFile file, @NonNull String description) {
- AdtPlugin.setFileProperty(file, NAME_CONFIG_STATE, description);
- }
-
- /**
- * Creates a description from a given configuration
- *
- * @param project the project for this configuration's description
- * @param configuration the configuration to describe
- * @return a new configuration
- */
- public static ConfigurationDescription fromConfiguration(
- @Nullable IProject project,
- @NonNull Configuration configuration) {
- ConfigurationDescription description = new ConfigurationDescription(project);
- description.displayName = configuration.getDisplayName();
- description.theme = configuration.getTheme();
- description.target = configuration.getTarget();
- description.folder = new FolderConfiguration();
- description.folder.set(configuration.getFullConfig());
- description.locale = configuration.getLocale();
- description.device = configuration.getDevice();
- description.state = configuration.getDeviceState();
- description.activity = configuration.getActivity();
- return description;
- }
-
- /**
- * Initializes a string previously created with
- * {@link #toXml(Document)}
- *
- * @param project the project for this configuration's description
- * @param element the element to read back from
- * @param deviceList list of available devices
- * @return true if the configuration was initialized
- */
- @Nullable
- public static ConfigurationDescription fromXml(
- @Nullable IProject project,
- @NonNull Element element,
- @NonNull Collection<Device> deviceList) {
- ConfigurationDescription description = new ConfigurationDescription(project);
-
- if (!TAG_PREVIEW.equals(element.getTagName())) {
- return null;
- }
-
- String displayName = element.getAttribute(ATTR_NAME);
- if (!displayName.isEmpty()) {
- description.displayName = displayName;
- }
-
- String config = element.getAttribute(ATTR_CONFIG);
- Iterable<String> segments = Splitter.on('-').split(config);
- description.folder = FolderConfiguration.getConfig(segments);
-
- String theme = element.getAttribute(ATTR_THEME);
- if (!theme.isEmpty()) {
- description.theme = theme;
- }
-
- String targetId = element.getAttribute(ATTR_TARGET);
- if (!targetId.isEmpty()) {
- IAndroidTarget target = Configuration.stringToTarget(targetId);
- description.target = target;
- }
-
- String localeString = element.getAttribute(ATTR_LOCALE);
- if (!localeString.isEmpty()) {
- // Load locale. Note that this can get overwritten by the
- // project-wide settings read below.
- String locales[] = localeString.split(SEP_LOCALE);
- if (locales[0].length() > 0 && !LocaleQualifier.FAKE_VALUE.equals(locales[0])) {
- String language = locales[0];
- if (locales.length >= 2 && locales[1].length() > 0 && !LocaleQualifier.FAKE_VALUE.equals(locales[1])) {
- description.locale = Locale.create(LocaleQualifier.getQualifier(language + "-r" + locales[1]));
- } else {
- description.locale = Locale.create(new LocaleQualifier(language));
- }
- } else {
- description.locale = Locale.ANY;
- }
-
-
- }
-
- String activity = element.getAttribute(ATTR_ACTIVITY);
- if (activity.isEmpty()) {
- activity = null;
- }
-
- String deviceString = element.getAttribute(ATTR_DEVICE);
- if (!deviceString.isEmpty()) {
- for (Device d : deviceList) {
- if (d.getName().equals(deviceString)) {
- description.device = d;
- String stateName = element.getAttribute(ATTR_STATE);
- if (stateName.isEmpty() || stateName.equals("null")) {
- description.state = Configuration.getState(d, stateName);
- } else if (d.getAllStates().size() > 0) {
- description.state = d.getAllStates().get(0);
- }
- break;
- }
- }
- }
-
- String uiModeString = element.getAttribute(ATTR_UIMODE);
- if (!uiModeString.isEmpty()) {
- description.uiMode = UiMode.getEnum(uiModeString);
- if (description.uiMode == null) {
- description.uiMode = UiMode.NORMAL;
- }
- }
-
- String nightModeString = element.getAttribute(ATTR_NIGHTMODE);
- if (!nightModeString.isEmpty()) {
- description.nightMode = NightMode.getEnum(nightModeString);
- if (description.nightMode == null) {
- description.nightMode = NightMode.NOTNIGHT;
- }
- }
-
-
- // Should I really be storing the FULL configuration? Might be trouble if
- // you bring a different device
-
- return description;
- }
-
- /**
- * Write this description into the given document as a new element.
- *
- * @param document the document to add the description to
- * @return the newly inserted element
- */
- @NonNull
- public Element toXml(Document document) {
- Element element = document.createElement(TAG_PREVIEW);
-
- element.setAttribute(ATTR_NAME, displayName);
- FolderConfiguration fullConfig = folder;
- String folderName = fullConfig.getFolderName(ResourceFolderType.LAYOUT);
- element.setAttribute(ATTR_CONFIG, folderName);
- if (theme != null) {
- element.setAttribute(ATTR_THEME, theme);
- }
- if (target != null) {
- element.setAttribute(ATTR_TARGET, Configuration.targetToString(target));
- }
-
- if (locale != null && (locale.hasLanguage() || locale.hasRegion())) {
- String value;
- if (locale.hasRegion()) {
- value = locale.qualifier.getLanguage() + SEP_LOCALE + locale.qualifier.getRegion();
- } else {
- value = locale.qualifier.getLanguage();
- }
- element.setAttribute(ATTR_LOCALE, value);
- }
-
- if (device != null) {
- element.setAttribute(ATTR_DEVICE, device.getName());
- if (state != null) {
- element.setAttribute(ATTR_STATE, state.getName());
- }
- }
-
- if (activity != null) {
- element.setAttribute(ATTR_ACTIVITY, activity);
- }
-
- if (uiMode != null && uiMode != UiMode.NORMAL) {
- element.setAttribute(ATTR_UIMODE, uiMode.getResourceValue());
- }
-
- if (nightMode != null && nightMode != NightMode.NOTNIGHT) {
- element.setAttribute(ATTR_NIGHTMODE, nightMode.getResourceValue());
- }
-
- Element parent = document.getDocumentElement();
- if (parent == null) {
- parent = document.createElement(TAG_PREVIEWS);
- document.appendChild(parent);
- }
- parent.appendChild(element);
-
- return element;
- }
-
- /** Returns the preferred theme, or null */
- @Nullable
- String computePreferredTheme() {
- if (project == null) {
- return "Theme";
- }
- ManifestInfo manifest = ManifestInfo.get(project);
-
- // Look up the screen size for the current state
- ScreenSize screenSize = null;
- if (device != null) {
- List<State> states = device.getAllStates();
- for (State s : states) {
- FolderConfiguration folderConfig = DeviceConfigHelper.getFolderConfig(s);
- if (folderConfig != null) {
- ScreenSizeQualifier qualifier = folderConfig.getScreenSizeQualifier();
- screenSize = qualifier.getValue();
- break;
- }
- }
- }
-
- // Look up the default/fallback theme to use for this project (which
- // depends on the screen size when no particular theme is specified
- // in the manifest)
- String defaultTheme = manifest.getDefaultTheme(target, screenSize);
-
- String preferred = defaultTheme;
- if (theme == null) {
- // If we are rendering a layout in included context, pick the theme
- // from the outer layout instead
-
- if (activity != null) {
- ActivityAttributes attributes = manifest.getActivityAttributes(activity);
- if (attributes != null) {
- preferred = attributes.getTheme();
- }
- }
- if (preferred == null) {
- preferred = defaultTheme;
- }
- theme = preferred;
- }
-
- return preferred;
- }
-
- private void checkThemePrefix() {
- if (theme != null && !theme.startsWith(PREFIX_RESOURCE_REF)) {
- if (theme.isEmpty()) {
- computePreferredTheme();
- return;
- }
-
- if (target != null) {
- Sdk sdk = Sdk.getCurrent();
- if (sdk != null) {
- AndroidTargetData data = sdk.getTargetData(target);
-
- if (data != null) {
- ResourceRepository resources = data.getFrameworkResources();
- if (resources != null
- && resources.hasResourceItem(ANDROID_STYLE_RESOURCE_PREFIX + theme)) {
- theme = ANDROID_STYLE_RESOURCE_PREFIX + theme;
- return;
- }
- }
- }
- }
-
- theme = STYLE_RESOURCE_PREFIX + theme;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ConfigurationMatcher.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ConfigurationMatcher.java
deleted file mode 100644
index 9724d4015..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ConfigurationMatcher.java
+++ /dev/null
@@ -1,843 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.configuration;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.resources.ResourceFile;
-import com.android.ide.common.resources.configuration.DensityQualifier;
-import com.android.ide.common.resources.configuration.DeviceConfigHelper;
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.common.resources.configuration.LocaleQualifier;
-import com.android.ide.common.resources.configuration.NightModeQualifier;
-import com.android.ide.common.resources.configuration.ResourceQualifier;
-import com.android.ide.common.resources.configuration.ScreenOrientationQualifier;
-import com.android.ide.common.resources.configuration.ScreenSizeQualifier;
-import com.android.ide.common.resources.configuration.UiModeQualifier;
-import com.android.ide.common.resources.configuration.VersionQualifier;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.resources.manager.ProjectResources;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.io.IFileWrapper;
-import com.android.resources.Density;
-import com.android.resources.NightMode;
-import com.android.resources.ResourceType;
-import com.android.resources.ScreenOrientation;
-import com.android.resources.ScreenSize;
-import com.android.resources.UiMode;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.devices.Device;
-import com.android.sdklib.devices.State;
-import com.android.sdklib.repository.PkgProps;
-import com.android.utils.Pair;
-import com.android.utils.SparseIntArray;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.ui.IEditorPart;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
-
-/**
- * Produces matches for configurations
- * <p>
- * See algorithm described here:
- * http://developer.android.com/guide/topics/resources/providing-resources.html
- */
-public class ConfigurationMatcher {
- private static final boolean PREFER_RECENT_RENDER_TARGETS = true;
-
- private final ConfigurationChooser mConfigChooser;
- private final Configuration mConfiguration;
- private final IFile mEditedFile;
- private final ProjectResources mResources;
- private final boolean mUpdateUi;
-
- ConfigurationMatcher(ConfigurationChooser chooser) {
- this(chooser, chooser.getConfiguration(), chooser.getEditedFile(),
- chooser.getResources(), true);
- }
-
- ConfigurationMatcher(
- @NonNull ConfigurationChooser chooser,
- @NonNull Configuration configuration,
- @Nullable IFile editedFile,
- @Nullable ProjectResources resources,
- boolean updateUi) {
- mConfigChooser = chooser;
- mConfiguration = configuration;
- mEditedFile = editedFile;
- mResources = resources;
- mUpdateUi = updateUi;
- }
-
- // ---- Finding matching configurations ----
-
- private static class ConfigBundle {
- private final FolderConfiguration config;
- private int localeIndex;
- private int dockModeIndex;
- private int nightModeIndex;
-
- private ConfigBundle() {
- config = new FolderConfiguration();
- }
-
- private ConfigBundle(ConfigBundle bundle) {
- config = new FolderConfiguration();
- config.set(bundle.config);
- localeIndex = bundle.localeIndex;
- dockModeIndex = bundle.dockModeIndex;
- nightModeIndex = bundle.nightModeIndex;
- }
- }
-
- private static class ConfigMatch {
- final FolderConfiguration testConfig;
- final Device device;
- final State state;
- final ConfigBundle bundle;
-
- public ConfigMatch(@NonNull FolderConfiguration testConfig, @NonNull Device device,
- @NonNull State state, @NonNull ConfigBundle bundle) {
- this.testConfig = testConfig;
- this.device = device;
- this.state = state;
- this.bundle = bundle;
- }
-
- @Override
- public String toString() {
- return device.getName() + " - " + state.getName();
- }
- }
-
- /**
- * Checks whether the current edited file is the best match for a given config.
- * <p>
- * This tests against other versions of the same layout in the project.
- * <p>
- * The given config must be compatible with the current edited file.
- * @param config the config to test.
- * @return true if the current edited file is the best match in the project for the
- * given config.
- */
- public boolean isCurrentFileBestMatchFor(FolderConfiguration config) {
- ResourceFile match = mResources.getMatchingFile(mEditedFile.getName(),
- ResourceType.LAYOUT, config);
-
- if (match != null) {
- return match.getFile().equals(mEditedFile);
- } else {
- // if we stop here that means the current file is not even a match!
- AdtPlugin.log(IStatus.ERROR, "Current file is not a match for the given config.");
- }
-
- return false;
- }
-
- /**
- * Adapts the current device/config selection so that it's compatible with
- * the configuration.
- * <p>
- * If the current selection is compatible, nothing is changed.
- * <p>
- * If it's not compatible, configs from the current devices are tested.
- * <p>
- * If none are compatible, it reverts to
- * {@link #findAndSetCompatibleConfig(boolean)}
- */
- void adaptConfigSelection(boolean needBestMatch) {
- // check the device config (ie sans locale)
- boolean needConfigChange = true; // if still true, we need to find another config.
- boolean currentConfigIsCompatible = false;
- State selectedState = mConfiguration.getDeviceState();
- FolderConfiguration editedConfig = mConfiguration.getEditedConfig();
- if (selectedState != null) {
- FolderConfiguration currentConfig = DeviceConfigHelper.getFolderConfig(selectedState);
- if (currentConfig != null && editedConfig.isMatchFor(currentConfig)) {
- currentConfigIsCompatible = true; // current config is compatible
- if (!needBestMatch || isCurrentFileBestMatchFor(currentConfig)) {
- needConfigChange = false;
- }
- }
- }
-
- if (needConfigChange) {
- List<Locale> localeList = mConfigChooser.getLocaleList();
-
- // if the current state/locale isn't a correct match, then
- // look for another state/locale in the same device.
- FolderConfiguration testConfig = new FolderConfiguration();
-
- // first look in the current device.
- State matchState = null;
- int localeIndex = -1;
- Device device = mConfiguration.getDevice();
- if (device != null) {
- mainloop: for (State state : device.getAllStates()) {
- testConfig.set(DeviceConfigHelper.getFolderConfig(state));
-
- // loop on the locales.
- for (int i = 0 ; i < localeList.size() ; i++) {
- Locale locale = localeList.get(i);
-
- // update the test config with the locale qualifiers
- testConfig.setLocaleQualifier(locale.qualifier);
-
-
- if (editedConfig.isMatchFor(testConfig) &&
- isCurrentFileBestMatchFor(testConfig)) {
- matchState = state;
- localeIndex = i;
- break mainloop;
- }
- }
- }
- }
-
- if (matchState != null) {
- mConfiguration.setDeviceState(matchState, true);
- Locale locale = localeList.get(localeIndex);
- mConfiguration.setLocale(locale, true);
- if (mUpdateUi) {
- mConfigChooser.selectDeviceState(matchState);
- mConfigChooser.selectLocale(locale);
- }
- mConfiguration.syncFolderConfig();
- } else {
- // no match in current device with any state/locale
- // attempt to find another device that can display this
- // particular state.
- findAndSetCompatibleConfig(currentConfigIsCompatible);
- }
- }
- }
-
- /**
- * Finds a device/config that can display a configuration.
- * <p>
- * Once found the device and config combos are set to the config.
- * <p>
- * If there is no compatible configuration, a custom one is created.
- *
- * @param favorCurrentConfig if true, and no best match is found, don't
- * change the current config. This must only be true if the
- * current config is compatible.
- */
- void findAndSetCompatibleConfig(boolean favorCurrentConfig) {
- List<Locale> localeList = mConfigChooser.getLocaleList();
- Collection<Device> devices = mConfigChooser.getDevices();
- FolderConfiguration editedConfig = mConfiguration.getEditedConfig();
- FolderConfiguration currentConfig = mConfiguration.getFullConfig();
-
- // list of compatible device/state/locale
- List<ConfigMatch> anyMatches = new ArrayList<ConfigMatch>();
-
- // list of actual best match (ie the file is a best match for the
- // device/state)
- List<ConfigMatch> bestMatches = new ArrayList<ConfigMatch>();
-
- // get a locale that match the host locale roughly (may not be exact match on the region.)
- int localeHostMatch = getLocaleMatch();
-
- // build a list of combinations of non standard qualifiers to add to each device's
- // qualifier set when testing for a match.
- // These qualifiers are: locale, night-mode, car dock.
- List<ConfigBundle> configBundles = new ArrayList<ConfigBundle>(200);
-
- // If the edited file has locales, then we have to select a matching locale from
- // the list.
- // However, if it doesn't, we don't randomly take the first locale, we take one
- // matching the current host locale (making sure it actually exist in the project)
- int start, max;
- if (editedConfig.getLocaleQualifier() != null || localeHostMatch == -1) {
- // add all the locales
- start = 0;
- max = localeList.size();
- } else {
- // only add the locale host match
- start = localeHostMatch;
- max = localeHostMatch + 1; // test is <
- }
-
- for (int i = start ; i < max ; i++) {
- Locale l = localeList.get(i);
-
- ConfigBundle bundle = new ConfigBundle();
- bundle.config.setLocaleQualifier(l.qualifier);
-
- bundle.localeIndex = i;
- configBundles.add(bundle);
- }
-
- // add the dock mode to the bundle combinations.
- addDockModeToBundles(configBundles);
-
- // add the night mode to the bundle combinations.
- addNightModeToBundles(configBundles);
-
- addRenderTargetToBundles(configBundles);
-
- for (Device device : devices) {
- for (State state : device.getAllStates()) {
-
- // loop on the list of config bundles to create full
- // configurations.
- FolderConfiguration stateConfig = DeviceConfigHelper.getFolderConfig(state);
- for (ConfigBundle bundle : configBundles) {
- // create a new config with device config
- FolderConfiguration testConfig = new FolderConfiguration();
- testConfig.set(stateConfig);
-
- // add on top of it, the extra qualifiers from the bundle
- testConfig.add(bundle.config);
-
- if (editedConfig.isMatchFor(testConfig)) {
- // this is a basic match. record it in case we don't
- // find a match
- // where the edited file is a best config.
- anyMatches.add(new ConfigMatch(testConfig, device, state, bundle));
-
- if (isCurrentFileBestMatchFor(testConfig)) {
- // this is what we want.
- bestMatches.add(new ConfigMatch(testConfig, device, state, bundle));
- }
- }
- }
- }
- }
-
- if (bestMatches.size() == 0) {
- if (favorCurrentConfig) {
- // quick check
- if (!editedConfig.isMatchFor(currentConfig)) {
- AdtPlugin.log(IStatus.ERROR,
- "favorCurrentConfig can only be true if the current config is compatible");
- }
-
- // just display the warning
- AdtPlugin.printErrorToConsole(mEditedFile.getProject(),
- String.format(
- "'%1$s' is not a best match for any device/locale combination.",
- editedConfig.toDisplayString()),
- String.format(
- "Displaying it with '%1$s'",
- currentConfig.toDisplayString()));
- } else if (anyMatches.size() > 0) {
- // select the best device anyway.
- ConfigMatch match = selectConfigMatch(anyMatches);
- mConfiguration.setDevice(match.device, true);
- mConfiguration.setDeviceState(match.state, true);
- mConfiguration.setLocale(localeList.get(match.bundle.localeIndex), true);
- mConfiguration.setUiMode(UiMode.getByIndex(match.bundle.dockModeIndex), true);
- mConfiguration.setNightMode(NightMode.getByIndex(match.bundle.nightModeIndex),
- true);
-
- if (mUpdateUi) {
- mConfigChooser.selectDevice(mConfiguration.getDevice());
- mConfigChooser.selectDeviceState(mConfiguration.getDeviceState());
- mConfigChooser.selectLocale(mConfiguration.getLocale());
- }
-
- mConfiguration.syncFolderConfig();
-
- // TODO: display a better warning!
- AdtPlugin.printErrorToConsole(mEditedFile.getProject(),
- String.format(
- "'%1$s' is not a best match for any device/locale combination.",
- editedConfig.toDisplayString()),
- String.format(
- "Displaying it with '%1$s' which is compatible, but will " +
- "actually be displayed with another more specific version of " +
- "the layout.",
- currentConfig.toDisplayString()));
-
- } else {
- // TODO: there is no device/config able to display the layout, create one.
- // For the base config values, we'll take the first device and state,
- // and replace whatever qualifier required by the layout file.
- }
- } else {
- ConfigMatch match = selectConfigMatch(bestMatches);
- mConfiguration.setDevice(match.device, true);
- mConfiguration.setDeviceState(match.state, true);
- mConfiguration.setLocale(localeList.get(match.bundle.localeIndex), true);
- mConfiguration.setUiMode(UiMode.getByIndex(match.bundle.dockModeIndex), true);
- mConfiguration.setNightMode(NightMode.getByIndex(match.bundle.nightModeIndex), true);
-
- mConfiguration.syncFolderConfig();
-
- if (mUpdateUi) {
- mConfigChooser.selectDevice(mConfiguration.getDevice());
- mConfigChooser.selectDeviceState(mConfiguration.getDeviceState());
- mConfigChooser.selectLocale(mConfiguration.getLocale());
- }
- }
- }
-
- private void addRenderTargetToBundles(List<ConfigBundle> configBundles) {
- Pair<Locale, IAndroidTarget> state = Configuration.loadRenderState(mConfigChooser);
- if (state != null) {
- IAndroidTarget target = state.getSecond();
- if (target != null) {
- int apiLevel = target.getVersion().getApiLevel();
- for (ConfigBundle bundle : configBundles) {
- bundle.config.setVersionQualifier(
- new VersionQualifier(apiLevel));
- }
- }
- }
- }
-
- private void addDockModeToBundles(List<ConfigBundle> addConfig) {
- ArrayList<ConfigBundle> list = new ArrayList<ConfigBundle>();
-
- // loop on each item and for each, add all variations of the dock modes
- for (ConfigBundle bundle : addConfig) {
- int index = 0;
- for (UiMode mode : UiMode.values()) {
- ConfigBundle b = new ConfigBundle(bundle);
- b.config.setUiModeQualifier(new UiModeQualifier(mode));
- b.dockModeIndex = index++;
- list.add(b);
- }
- }
-
- addConfig.clear();
- addConfig.addAll(list);
- }
-
- private void addNightModeToBundles(List<ConfigBundle> addConfig) {
- ArrayList<ConfigBundle> list = new ArrayList<ConfigBundle>();
-
- // loop on each item and for each, add all variations of the night modes
- for (ConfigBundle bundle : addConfig) {
- int index = 0;
- for (NightMode mode : NightMode.values()) {
- ConfigBundle b = new ConfigBundle(bundle);
- b.config.setNightModeQualifier(new NightModeQualifier(mode));
- b.nightModeIndex = index++;
- list.add(b);
- }
- }
-
- addConfig.clear();
- addConfig.addAll(list);
- }
-
- private int getLocaleMatch() {
- java.util.Locale defaultLocale = java.util.Locale.getDefault();
- if (defaultLocale != null) {
- String currentLanguage = defaultLocale.getLanguage();
- String currentRegion = defaultLocale.getCountry();
-
- List<Locale> localeList = mConfigChooser.getLocaleList();
- final int count = localeList.size();
- for (int l = 0; l < count; l++) {
- Locale locale = localeList.get(l);
- LocaleQualifier qualifier = locale.qualifier;
-
- // there's always a ##/Other or ##/Any (which is the same, the region
- // contains FAKE_REGION_VALUE). If we don't find a perfect region match
- // we take the fake region. Since it's last in the list, this makes the
- // test easy.
- if (qualifier.getLanguage().equals(currentLanguage) &&
- (qualifier.getRegion() == null || qualifier.getRegion().equals(currentRegion))) {
- return l;
- }
- }
-
- // if no locale match the current local locale, it's likely that it is
- // the default one which is the last one.
- return count - 1;
- }
-
- return -1;
- }
-
- private ConfigMatch selectConfigMatch(List<ConfigMatch> matches) {
- // API 11-13: look for a x-large device
- Comparator<ConfigMatch> comparator = null;
- Sdk sdk = Sdk.getCurrent();
- if (sdk != null) {
- IAndroidTarget projectTarget = sdk.getTarget(mEditedFile.getProject());
- if (projectTarget != null) {
- int apiLevel = projectTarget.getVersion().getApiLevel();
- if (apiLevel >= 11 && apiLevel < 14) {
- // TODO: Maybe check the compatible-screen tag in the manifest to figure out
- // what kind of device should be used for display.
- comparator = new TabletConfigComparator();
- }
- }
- }
- if (comparator == null) {
- // lets look for a high density device
- comparator = new PhoneConfigComparator();
- }
- Collections.sort(matches, comparator);
-
- // Look at the currently active editor to see if it's a layout editor, and if so,
- // look up its configuration and if the configuration is in our match list,
- // use it. This means we "preserve" the current configuration when you open
- // new layouts.
- IEditorPart activeEditor = AdtUtils.getActiveEditor();
- LayoutEditorDelegate delegate = LayoutEditorDelegate.fromEditor(activeEditor);
- if (delegate != null
- // (Only do this when the two files are in the same project)
- && delegate.getEditor().getProject() == mEditedFile.getProject()) {
- FolderConfiguration configuration = delegate.getGraphicalEditor().getConfiguration();
- if (configuration != null) {
- for (ConfigMatch match : matches) {
- if (configuration.equals(match.testConfig)) {
- return match;
- }
- }
- }
- }
-
- // the list has been sorted so that the first item is the best config
- return matches.get(0);
- }
-
- /** Return the default render target to use, or null if no strong preference */
- @Nullable
- static IAndroidTarget findDefaultRenderTarget(ConfigurationChooser chooser) {
- if (PREFER_RECENT_RENDER_TARGETS) {
- // Use the most recent target
- List<IAndroidTarget> targetList = chooser.getTargetList();
- if (!targetList.isEmpty()) {
- return targetList.get(targetList.size() - 1);
- }
- }
-
- IProject project = chooser.getProject();
- // Default to layoutlib version 5
- Sdk current = Sdk.getCurrent();
- if (current != null) {
- IAndroidTarget projectTarget = current.getTarget(project);
- int minProjectApi = Integer.MAX_VALUE;
- if (projectTarget != null) {
- if (!projectTarget.isPlatform() && projectTarget.hasRenderingLibrary()) {
- // Renderable non-platform targets are all going to be adequate (they
- // will have at least version 5 of layoutlib) so use the project
- // target as the render target.
- return projectTarget;
- }
-
- if (projectTarget.getVersion().isPreview()
- && projectTarget.hasRenderingLibrary()) {
- // If the project target is a preview version, then just use it
- return projectTarget;
- }
-
- minProjectApi = projectTarget.getVersion().getApiLevel();
- }
-
- // We want to pick a render target that contains at least version 5 (and
- // preferably version 6) of the layout library. To do this, we go through the
- // targets and pick the -smallest- API level that is both simultaneously at
- // least as big as the project API level, and supports layoutlib level 5+.
- IAndroidTarget best = null;
- int bestApiLevel = Integer.MAX_VALUE;
-
- for (IAndroidTarget target : current.getTargets()) {
- // Non-platform targets are not chosen as the default render target
- if (!target.isPlatform()) {
- continue;
- }
-
- int apiLevel = target.getVersion().getApiLevel();
-
- // Ignore targets that have a lower API level than the minimum project
- // API level:
- if (apiLevel < minProjectApi) {
- continue;
- }
-
- // Look up the layout lib API level. This property is new so it will only
- // be defined for version 6 or higher, which means non-null is adequate
- // to see if this target is eligible:
- String property = target.getProperty(PkgProps.LAYOUTLIB_API);
- // In addition, Android 3.0 with API level 11 had version 5.0 which is adequate:
- if (property != null || apiLevel >= 11) {
- if (apiLevel < bestApiLevel) {
- bestApiLevel = apiLevel;
- best = target;
- }
- }
- }
-
- return best;
- }
-
- return null;
- }
-
- /**
- * Attempts to find a close state among a list
- *
- * @param oldConfig the reference config.
- * @param states the list of states to search through
- * @return the name of the closest state match, or possibly null if no states are compatible
- * (this can only happen if the states don't have a single qualifier that is the same).
- */
- @Nullable
- static String getClosestMatch(@NonNull FolderConfiguration oldConfig,
- @NonNull List<State> states) {
-
- // create 2 lists as we're going to go through one and put the
- // candidates in the other.
- List<State> list1 = new ArrayList<State>(states.size());
- List<State> list2 = new ArrayList<State>(states.size());
-
- list1.addAll(states);
-
- final int count = FolderConfiguration.getQualifierCount();
- for (int i = 0 ; i < count ; i++) {
- // compute the new candidate list by only taking states that have
- // the same i-th qualifier as the old state
- for (State s : list1) {
- ResourceQualifier oldQualifier = oldConfig.getQualifier(i);
-
- FolderConfiguration folderConfig = DeviceConfigHelper.getFolderConfig(s);
- ResourceQualifier newQualifier =
- folderConfig != null ? folderConfig.getQualifier(i) : null;
-
- if (oldQualifier == null) {
- if (newQualifier == null) {
- list2.add(s);
- }
- } else if (oldQualifier.equals(newQualifier)) {
- list2.add(s);
- }
- }
-
- // at any moment if the new candidate list contains only one match, its name
- // is returned.
- if (list2.size() == 1) {
- return list2.get(0).getName();
- }
-
- // if the list is empty, then all the new states failed. It is considered ok, and
- // we move to the next qualifier anyway. This way, if a qualifier is different for
- // all new states it is simply ignored.
- if (list2.size() != 0) {
- // move the candidates back into list1.
- list1.clear();
- list1.addAll(list2);
- list2.clear();
- }
- }
-
- // the only way to reach this point is if there's an exact match.
- // (if there are more than one, then there's a duplicate state and it doesn't matter,
- // we take the first one).
- if (list1.size() > 0) {
- return list1.get(0).getName();
- }
-
- return null;
- }
-
- /**
- * Returns the layout {@link IFile} which best matches the configuration
- * selected in the given configuration chooser.
- *
- * @param chooser the associated configuration chooser holding project state
- * @return the file which best matches the settings
- */
- @Nullable
- public static IFile getBestFileMatch(ConfigurationChooser chooser) {
- // get the resources of the file's project.
- ResourceManager manager = ResourceManager.getInstance();
- ProjectResources resources = manager.getProjectResources(chooser.getProject());
- if (resources == null) {
- return null;
- }
-
- // From the resources, look for a matching file
- IFile editedFile = chooser.getEditedFile();
- if (editedFile == null) {
- return null;
- }
- String name = editedFile.getName();
- FolderConfiguration config = chooser.getConfiguration().getFullConfig();
- ResourceFile match = resources.getMatchingFile(name, ResourceType.LAYOUT, config);
-
- if (match != null) {
- // In Eclipse, the match's file is always an instance of IFileWrapper
- return ((IFileWrapper) match.getFile()).getIFile();
- }
-
- return null;
- }
-
- /**
- * Note: this comparator imposes orderings that are inconsistent with equals.
- */
- private static class TabletConfigComparator implements Comparator<ConfigMatch> {
- @Override
- public int compare(ConfigMatch o1, ConfigMatch o2) {
- FolderConfiguration config1 = o1 != null ? o1.testConfig : null;
- FolderConfiguration config2 = o2 != null ? o2.testConfig : null;
- if (config1 == null) {
- if (config2 == null) {
- return 0;
- } else {
- return -1;
- }
- } else if (config2 == null) {
- return 1;
- }
-
- ScreenSizeQualifier size1 = config1.getScreenSizeQualifier();
- ScreenSizeQualifier size2 = config2.getScreenSizeQualifier();
- ScreenSize ss1 = size1 != null ? size1.getValue() : ScreenSize.NORMAL;
- ScreenSize ss2 = size2 != null ? size2.getValue() : ScreenSize.NORMAL;
-
- // X-LARGE is better than all others (which are considered identical)
- // if both X-LARGE, then LANDSCAPE is better than all others (which are identical)
-
- if (ss1 == ScreenSize.XLARGE) {
- if (ss2 == ScreenSize.XLARGE) {
- ScreenOrientationQualifier orientation1 =
- config1.getScreenOrientationQualifier();
- ScreenOrientation so1 = orientation1.getValue();
- if (so1 == null) {
- so1 = ScreenOrientation.PORTRAIT;
- }
- ScreenOrientationQualifier orientation2 =
- config2.getScreenOrientationQualifier();
- ScreenOrientation so2 = orientation2.getValue();
- if (so2 == null) {
- so2 = ScreenOrientation.PORTRAIT;
- }
-
- if (so1 == ScreenOrientation.LANDSCAPE) {
- if (so2 == ScreenOrientation.LANDSCAPE) {
- return 0;
- } else {
- return -1;
- }
- } else if (so2 == ScreenOrientation.LANDSCAPE) {
- return 1;
- } else {
- return 0;
- }
- } else {
- return -1;
- }
- } else if (ss2 == ScreenSize.XLARGE) {
- return 1;
- } else {
- return 0;
- }
- }
- }
-
- /**
- * Note: this comparator imposes orderings that are inconsistent with equals.
- */
- private static class PhoneConfigComparator implements Comparator<ConfigMatch> {
-
- private final SparseIntArray mDensitySort = new SparseIntArray(4);
-
- public PhoneConfigComparator() {
- // put the sort order for the density.
- mDensitySort.put(Density.HIGH.getDpiValue(), 1);
- mDensitySort.put(Density.MEDIUM.getDpiValue(), 2);
- mDensitySort.put(Density.XHIGH.getDpiValue(), 3);
- mDensitySort.put(Density.LOW.getDpiValue(), 4);
- }
-
- @Override
- public int compare(ConfigMatch o1, ConfigMatch o2) {
- FolderConfiguration config1 = o1 != null ? o1.testConfig : null;
- FolderConfiguration config2 = o2 != null ? o2.testConfig : null;
- if (config1 == null) {
- if (config2 == null) {
- return 0;
- } else {
- return -1;
- }
- } else if (config2 == null) {
- return 1;
- }
-
- int dpi1 = Density.DEFAULT_DENSITY;
- int dpi2 = Density.DEFAULT_DENSITY;
-
- DensityQualifier dpiQualifier1 = config1.getDensityQualifier();
- if (dpiQualifier1 != null) {
- Density value = dpiQualifier1.getValue();
- dpi1 = value != null ? value.getDpiValue() : Density.DEFAULT_DENSITY;
- }
- dpi1 = mDensitySort.get(dpi1, 100 /* valueIfKeyNotFound*/);
-
- DensityQualifier dpiQualifier2 = config2.getDensityQualifier();
- if (dpiQualifier2 != null) {
- Density value = dpiQualifier2.getValue();
- dpi2 = value != null ? value.getDpiValue() : Density.DEFAULT_DENSITY;
- }
- dpi2 = mDensitySort.get(dpi2, 100 /* valueIfKeyNotFound*/);
-
- if (dpi1 == dpi2) {
- // portrait is better
- ScreenOrientation so1 = ScreenOrientation.PORTRAIT;
- ScreenOrientationQualifier orientationQualifier1 =
- config1.getScreenOrientationQualifier();
- if (orientationQualifier1 != null) {
- so1 = orientationQualifier1.getValue();
- if (so1 == null) {
- so1 = ScreenOrientation.PORTRAIT;
- }
- }
- ScreenOrientation so2 = ScreenOrientation.PORTRAIT;
- ScreenOrientationQualifier orientationQualifier2 =
- config2.getScreenOrientationQualifier();
- if (orientationQualifier2 != null) {
- so2 = orientationQualifier2.getValue();
- if (so2 == null) {
- so2 = ScreenOrientation.PORTRAIT;
- }
- }
-
- if (so1 == ScreenOrientation.PORTRAIT) {
- if (so2 == ScreenOrientation.PORTRAIT) {
- return 0;
- } else {
- return -1;
- }
- } else if (so2 == ScreenOrientation.PORTRAIT) {
- return 1;
- } else {
- return 0;
- }
- }
-
- return dpi1 - dpi2;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ConfigurationMenuListener.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ConfigurationMenuListener.java
deleted file mode 100644
index a791c63f8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ConfigurationMenuListener.java
+++ /dev/null
@@ -1,290 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.configuration;
-
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderPreviewMode.CUSTOM;
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderPreviewMode.DEFAULT;
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderPreviewMode.INCLUDES;
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderPreviewMode.LOCALES;
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderPreviewMode.NONE;
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderPreviewMode.SCREENS;
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderPreviewMode.VARIATIONS;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.resources.ResourceFolder;
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.IncludeFinder;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.IncludeFinder.Reference;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.LayoutCanvas;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderPreviewManager;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderPreviewMode;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MenuItem;
-import org.eclipse.swt.widgets.ToolItem;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.PartInitException;
-
-import java.util.List;
-
-/**
- * The {@linkplain ConfigurationMenuListener} class is responsible for
- * generating the configuration menu in the {@link ConfigurationChooser}.
- */
-class ConfigurationMenuListener extends SelectionAdapter {
- private static final String ICON_NEW_CONFIG = "newConfig"; //$NON-NLS-1$
- private static final int ACTION_SELECT_CONFIG = 1;
- private static final int ACTION_CREATE_CONFIG_FILE = 2;
- private static final int ACTION_ADD = 3;
- private static final int ACTION_DELETE_ALL = 4;
- private static final int ACTION_PREVIEW_MODE = 5;
-
- private final ConfigurationChooser mConfigChooser;
- private final int mAction;
- private final IFile mResource;
- private final RenderPreviewMode mMode;
-
- ConfigurationMenuListener(
- @NonNull ConfigurationChooser configChooser,
- int action,
- @Nullable IFile resource,
- @Nullable RenderPreviewMode mode) {
- mConfigChooser = configChooser;
- mAction = action;
- mResource = resource;
- mMode = mode;
- }
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- switch (mAction) {
- case ACTION_SELECT_CONFIG: {
- try {
- AdtPlugin.openFile(mResource, null, false);
- } catch (PartInitException ex) {
- AdtPlugin.log(ex, null);
- }
- return;
- }
- case ACTION_CREATE_CONFIG_FILE: {
- ConfigurationClient client = mConfigChooser.getClient();
- if (client != null) {
- client.createConfigFile();
- }
- return;
- }
- }
-
- IEditorPart activeEditor = AdtUtils.getActiveEditor();
- LayoutEditorDelegate delegate = LayoutEditorDelegate.fromEditor(activeEditor);
- IFile editedFile = mConfigChooser.getEditedFile();
-
- if (delegate == null || editedFile == null) {
- return;
- }
- // (Only do this when the two files are in the same project)
- IProject project = delegate.getEditor().getProject();
- if (project == null ||
- !project.equals(editedFile.getProject())) {
- return;
- }
- LayoutCanvas canvas = delegate.getGraphicalEditor().getCanvasControl();
- RenderPreviewManager previewManager = canvas.getPreviewManager();
-
- switch (mAction) {
- case ACTION_ADD: {
- previewManager.addAsThumbnail();
- break;
- }
- case ACTION_PREVIEW_MODE: {
- previewManager.selectMode(mMode);
- break;
- }
- case ACTION_DELETE_ALL: {
- previewManager.deleteManualPreviews();
- break;
- }
- default: assert false : mAction;
- }
- canvas.setFitScale(true /*onlyZoomOut*/, false /*allowZoomIn*/);
- canvas.redraw();
- }
-
- static void show(ConfigurationChooser chooser, ToolItem combo) {
- Menu menu = new Menu(chooser.getShell(), SWT.POP_UP);
- RenderPreviewMode mode = AdtPrefs.getPrefs().getRenderPreviewMode();
-
- // Configuration Previews
- create(menu, "Add As Thumbnail...",
- new ConfigurationMenuListener(chooser, ACTION_ADD, null, null),
- SWT.PUSH, false);
- if (mode == RenderPreviewMode.CUSTOM) {
- MenuItem item = create(menu, "Delete All Thumbnails",
- new ConfigurationMenuListener(chooser, ACTION_DELETE_ALL, null, null),
- SWT.PUSH, false);
- IEditorPart activeEditor = AdtUtils.getActiveEditor();
- LayoutEditorDelegate delegate = LayoutEditorDelegate.fromEditor(activeEditor);
- if (delegate != null) {
- LayoutCanvas canvas = delegate.getGraphicalEditor().getCanvasControl();
- RenderPreviewManager previewManager = canvas.getPreviewManager();
- if (!previewManager.hasManualPreviews()) {
- item.setEnabled(false);
- }
- }
- }
-
- @SuppressWarnings("unused")
- MenuItem configSeparator = new MenuItem(menu, SWT.SEPARATOR);
-
- create(menu, "Preview Representative Sample",
- new ConfigurationMenuListener(chooser, ACTION_PREVIEW_MODE, null,
- DEFAULT), SWT.RADIO, mode == DEFAULT);
- create(menu, "Preview All Screen Sizes",
- new ConfigurationMenuListener(chooser, ACTION_PREVIEW_MODE, null,
- SCREENS), SWT.RADIO, mode == SCREENS);
-
- MenuItem localeItem = create(menu, "Preview All Locales",
- new ConfigurationMenuListener(chooser, ACTION_PREVIEW_MODE, null,
- LOCALES), SWT.RADIO, mode == LOCALES);
- if (chooser.getLocaleList().size() <= 1) {
- localeItem.setEnabled(false);
- }
-
- boolean canPreviewIncluded = false;
- IProject project = chooser.getProject();
- if (project != null) {
- IncludeFinder finder = IncludeFinder.get(project);
- final List<Reference> includedBy = finder.getIncludedBy(chooser.getEditedFile());
- canPreviewIncluded = includedBy != null && !includedBy.isEmpty();
- }
- //if (!graphicalEditor.renderingSupports(Capability.EMBEDDED_LAYOUT)) {
- // canPreviewIncluded = false;
- //}
- MenuItem includedItem = create(menu, "Preview Included",
- new ConfigurationMenuListener(chooser, ACTION_PREVIEW_MODE, null,
- INCLUDES), SWT.RADIO, mode == INCLUDES);
- if (!canPreviewIncluded) {
- includedItem.setEnabled(false);
- }
-
- IFile file = chooser.getEditedFile();
- List<IFile> variations = AdtUtils.getResourceVariations(file, true);
- MenuItem variationsItem = create(menu, "Preview Layout Versions",
- new ConfigurationMenuListener(chooser, ACTION_PREVIEW_MODE, null,
- VARIATIONS), SWT.RADIO, mode == VARIATIONS);
- if (variations.size() <= 1) {
- variationsItem.setEnabled(false);
- }
-
- create(menu, "Manual Previews",
- new ConfigurationMenuListener(chooser, ACTION_PREVIEW_MODE, null,
- CUSTOM), SWT.RADIO, mode == CUSTOM);
- create(menu, "None",
- new ConfigurationMenuListener(chooser, ACTION_PREVIEW_MODE, null,
- NONE), SWT.RADIO, mode == NONE);
-
- if (variations.size() > 1) {
- @SuppressWarnings("unused")
- MenuItem separator = new MenuItem(menu, SWT.SEPARATOR);
-
- ResourceManager manager = ResourceManager.getInstance();
- for (final IFile resource : variations) {
- IFolder parent = (IFolder) resource.getParent();
- ResourceFolder parentResource = manager.getResourceFolder(parent);
- FolderConfiguration configuration = parentResource.getConfiguration();
- String title = configuration.toDisplayString();
-
- MenuItem item = create(menu, title,
- new ConfigurationMenuListener(chooser, ACTION_SELECT_CONFIG,
- resource, null),
- SWT.CHECK, false);
-
- if (file != null) {
- boolean selected = file.equals(resource);
- if (selected) {
- item.setSelection(true);
- item.setEnabled(false);
- }
- }
- }
- }
-
- Configuration configuration = chooser.getConfiguration();
- if (configuration.getEditedConfig() != null &&
- !configuration.getEditedConfig().equals(configuration.getFullConfig())) {
- if (variations.size() > 0) {
- @SuppressWarnings("unused")
- MenuItem separator = new MenuItem(menu, SWT.SEPARATOR);
- }
-
- // Add action for creating a new configuration
- MenuItem item = create(menu, "Create New...",
- new ConfigurationMenuListener(chooser, ACTION_CREATE_CONFIG_FILE,
- null, null),
- SWT.PUSH, false);
- item.setImage(IconFactory.getInstance().getIcon(ICON_NEW_CONFIG));
- }
-
- Rectangle bounds = combo.getBounds();
- Point location = new Point(bounds.x, bounds.y + bounds.height);
- location = combo.getParent().toDisplay(location);
- menu.setLocation(location.x, location.y);
- menu.setVisible(true);
- }
-
- @NonNull
- public static MenuItem create(@NonNull Menu menu, String title,
- ConfigurationMenuListener listener, int style, boolean selected) {
- MenuItem item = new MenuItem(menu, style);
- item.setText(title);
- item.addSelectionListener(listener);
- if (selected) {
- item.setSelection(true);
- }
- return item;
- }
-
- @NonNull
- static MenuItem addTogglePreviewModeAction(
- @NonNull Menu menu,
- @NonNull String title,
- @NonNull ConfigurationChooser chooser,
- @NonNull RenderPreviewMode mode) {
- boolean selected = AdtPrefs.getPrefs().getRenderPreviewMode() == mode;
- if (selected) {
- mode = RenderPreviewMode.NONE;
- }
- return create(menu, title,
- new ConfigurationMenuListener(chooser, ACTION_PREVIEW_MODE, null, mode),
- SWT.CHECK, selected);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/DeviceMenuListener.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/DeviceMenuListener.java
deleted file mode 100644
index 72910f9cc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/DeviceMenuListener.java
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.configuration;
-
-import static com.android.ide.common.rendering.HardwareConfigHelper.MANUFACTURER_GENERIC;
-import static com.android.ide.common.rendering.HardwareConfigHelper.getGenericLabel;
-import static com.android.ide.common.rendering.HardwareConfigHelper.getNexusLabel;
-import static com.android.ide.common.rendering.HardwareConfigHelper.isGeneric;
-import static com.android.ide.common.rendering.HardwareConfigHelper.isNexus;
-import static com.android.ide.common.rendering.HardwareConfigHelper.sortNexusList;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderPreviewMode;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.sdklib.devices.Device;
-import com.android.sdklib.internal.avd.AvdInfo;
-import com.android.sdklib.internal.avd.AvdManager;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MenuItem;
-import org.eclipse.swt.widgets.ToolItem;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.TreeMap;
-
-/**
- * The {@linkplain DeviceMenuListener} class is responsible for generating the device
- * menu in the {@link ConfigurationChooser}.
- */
-class DeviceMenuListener extends SelectionAdapter {
- private final ConfigurationChooser mConfigChooser;
- private final Device mDevice;
-
- DeviceMenuListener(
- @NonNull ConfigurationChooser configChooser,
- @Nullable Device device) {
- mConfigChooser = configChooser;
- mDevice = device;
- }
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- mConfigChooser.selectDevice(mDevice);
- mConfigChooser.onDeviceChange();
- }
-
- static void show(final ConfigurationChooser chooser, ToolItem combo) {
- Configuration configuration = chooser.getConfiguration();
- Device current = configuration.getDevice();
- Menu menu = new Menu(chooser.getShell(), SWT.POP_UP);
-
- Collection<Device> deviceCollection = chooser.getDevices();
- Sdk sdk = Sdk.getCurrent();
- if (sdk != null) {
- AvdManager avdManager = sdk.getAvdManager();
- if (avdManager != null) {
- boolean separatorNeeded = false;
- AvdInfo[] avds = avdManager.getValidAvds();
- for (AvdInfo avd : avds) {
- for (Device device : deviceCollection) {
- if (device.getManufacturer().equals(avd.getDeviceManufacturer())
- && device.getName().equals(avd.getDeviceName())) {
- separatorNeeded = true;
- MenuItem item = new MenuItem(menu, SWT.CHECK);
- item.setText(avd.getName());
- item.setSelection(current == device);
-
- item.addSelectionListener(new DeviceMenuListener(chooser, device));
- }
- }
- }
-
- if (separatorNeeded) {
- @SuppressWarnings("unused")
- MenuItem separator = new MenuItem(menu, SWT.SEPARATOR);
- }
- }
- }
-
- // Group the devices by manufacturer, then put them in the menu.
- // If we don't have anything but Nexus devices, group them together rather than
- // make many manufacturer submenus.
- boolean haveNexus = false;
- boolean haveNonNexus = false;
- if (!deviceCollection.isEmpty()) {
- Map<String, List<Device>> manufacturers = new TreeMap<String, List<Device>>();
- for (Device device : deviceCollection) {
- List<Device> devices;
- if (isNexus(device)) {
- haveNexus = true;
- } else if (!isGeneric(device)) {
- haveNonNexus = true;
- }
- if (manufacturers.containsKey(device.getManufacturer())) {
- devices = manufacturers.get(device.getManufacturer());
- } else {
- devices = new ArrayList<Device>();
- manufacturers.put(device.getManufacturer(), devices);
- }
- devices.add(device);
- }
- if (haveNonNexus) {
- for (List<Device> devices : manufacturers.values()) {
- Menu manufacturerMenu = menu;
- if (manufacturers.size() > 1) {
- MenuItem item = new MenuItem(menu, SWT.CASCADE);
- item.setText(devices.get(0).getManufacturer());
- manufacturerMenu = new Menu(menu);
- item.setMenu(manufacturerMenu);
- }
- for (final Device device : devices) {
- MenuItem deviceItem = new MenuItem(manufacturerMenu, SWT.CHECK);
- deviceItem.setText(getGenericLabel(device));
- deviceItem.setSelection(current == device);
- deviceItem.addSelectionListener(new DeviceMenuListener(chooser, device));
- }
- }
- } else {
- List<Device> nexus = new ArrayList<Device>();
- List<Device> generic = new ArrayList<Device>();
- if (haveNexus) {
- // Nexus
- for (List<Device> devices : manufacturers.values()) {
- for (Device device : devices) {
- if (isNexus(device)) {
- if (device.getManufacturer().equals(MANUFACTURER_GENERIC)) {
- generic.add(device);
- } else {
- nexus.add(device);
- }
- } else {
- generic.add(device);
- }
- }
- }
- }
-
- if (!nexus.isEmpty()) {
- sortNexusList(nexus);
- for (final Device device : nexus) {
- MenuItem item = new MenuItem(menu, SWT.CHECK);
- item.setText(getNexusLabel(device));
- item.setSelection(current == device);
- item.addSelectionListener(new DeviceMenuListener(chooser, device));
- }
-
- @SuppressWarnings("unused")
- MenuItem separator = new MenuItem(menu, SWT.SEPARATOR);
- }
-
- // Generate the generic menu.
- Collections.reverse(generic);
- for (final Device device : generic) {
- MenuItem item = new MenuItem(menu, SWT.CHECK);
- item.setText(getGenericLabel(device));
- item.setSelection(current == device);
- item.addSelectionListener(new DeviceMenuListener(chooser, device));
- }
- }
- }
-
- @SuppressWarnings("unused")
- MenuItem separator = new MenuItem(menu, SWT.SEPARATOR);
-
- ConfigurationMenuListener.addTogglePreviewModeAction(menu,
- "Preview All Screens", chooser, RenderPreviewMode.SCREENS);
-
-
- Rectangle bounds = combo.getBounds();
- Point location = new Point(bounds.x, bounds.y + bounds.height);
- location = combo.getParent().toDisplay(location);
- menu.setLocation(location.x, location.y);
- menu.setVisible(true);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/FlagManager.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/FlagManager.java
deleted file mode 100644
index 15623cf30..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/FlagManager.java
+++ /dev/null
@@ -1,215 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.configuration;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.resources.LocaleManager;
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.common.resources.configuration.LocaleQualifier;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.google.common.collect.Maps;
-
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.wb.internal.core.DesignerPlugin;
-
-import java.util.Locale;
-import java.util.Map;
-
-/**
- * The {@linkplain FlagManager} provides access to flags for regions known
- * to {@link LocaleManager}. It also contains some locale related display
- * functions.
- * <p>
- * All the flag images came from the WindowBuilder subversion repository
- * http://dev.eclipse.org/svnroot/tools/org.eclipse.windowbuilder/trunk (and in
- * particular, a snapshot of revision 424). However, it appears that the icons
- * are from http://www.famfamfam.com/lab/icons/flags/ which states that "these
- * flag icons are available for free use for any purpose with no requirement for
- * attribution." Adding the URL here such that we can check back occasionally
- * and see if there are corrections or updates. Also note that the flag names
- * are in ISO 3166-1 alpha-2 country codes.
- */
-public class FlagManager {
- private static final FlagManager sInstance = new FlagManager();
-
- /**
- * Returns the {@linkplain FlagManager} singleton
- *
- * @return the {@linkplain FlagManager} singleton, never null
- */
- @NonNull
- public static FlagManager get() {
- return sInstance;
- }
-
- /** Use the {@link #get()} factory method */
- private FlagManager() {
- }
-
- /** Map from region to flag icon */
- private final Map<String, Image> mImageMap = Maps.newHashMap();
-
- /**
- * Returns the empty flag icon used to indicate an unknown country
- *
- * @return the globe icon used to indicate an unknown country
- */
- public static Image getEmptyIcon() {
- return DesignerPlugin.getImage("nls/flags/flag_empty.png"); //$NON-NLS-1$
- }
-
- /**
- * Returns the globe icon used to indicate "any" language
- *
- * @return the globe icon used to indicate "any" language
- */
- public static Image getGlobeIcon() {
- return IconFactory.getInstance().getIcon("globe"); //$NON-NLS-1$
- }
-
- /**
- * Returns the flag for the given language and region.
- *
- * @param language the language, or null (if null, region must not be null),
- * the 2 letter language code (ISO 639-1), in lower case
- * @param region the region, or null (if null, language must not be null),
- * the 2 letter region code (ISO 3166-1 alpha-2), in upper case
- * @return a suitable flag icon, or null
- */
- @Nullable
- public Image getFlag(@Nullable String language, @Nullable String region) {
- assert region != null || language != null;
- if (region == null || region.isEmpty()) {
- // Look up the region for a given language
- assert language != null;
-
- // Special cases where we have a dedicated flag available:
- if (language.equals("ca")) { //$NON-NLS-1$
- return getIcon("catalonia"); //$NON-NLS-1$
- }
- else if (language.equals("gd")) { //$NON-NLS-1$
- return getIcon("scotland"); //$NON-NLS-1$
- }
- else if (language.equals("cy")) { //$NON-NLS-1$
- return getIcon("wales"); //$NON-NLS-1$
- }
-
- // Prefer the local registration of the current locale; even if
- // for example the default locale for English is the US, if the current
- // default locale is English, then use its associated country, which could
- // for example be Australia.
- Locale locale = Locale.getDefault();
- if (language.equals(locale.getLanguage())) {
- Image flag = getFlag(locale.getCountry());
- if (flag != null) {
- return flag;
- }
- }
-
- region = LocaleManager.getLanguageRegion(language);
- }
-
- if (region == null || region.isEmpty()) {
- // No country specified, and the language is for a country we
- // don't have a flag for
- return null;
- }
-
- return getIcon(region);
- }
-
- /**
- * Returns the flag for the given language and region.
- *
- * @param language the language qualifier, or null (if null, region must not be null),
- * @param region the region, or null (if null, language must not be null),
- * @return a suitable flag icon, or null
- */
- public Image getFlag(@Nullable LocaleQualifier locale) {
- if (locale == null) {
- return null;
- }
- String languageCode = locale.getLanguage();
- String regionCode = locale.getRegion();
- if (LocaleQualifier.FAKE_VALUE.equals(languageCode)) {
- languageCode = null;
- }
- return getFlag(languageCode, regionCode);
- }
-
- /**
- * Returns a flag for a given resource folder name (such as
- * {@code values-en-rUS}), or null
- *
- * @param folder the folder name
- * @return a corresponding flag icon, or null if none was found
- */
- @Nullable
- public Image getFlagForFolderName(@NonNull String folder) {
- FolderConfiguration configuration = FolderConfiguration.getConfigForFolder(folder);
- if (configuration != null) {
- return get().getFlag(configuration);
- }
-
- return null;
- }
-
- /**
- * Returns the flag for the given folder
- *
- * @param configuration the folder configuration
- * @return a suitable flag icon, or null
- */
- @Nullable
- public Image getFlag(@NonNull FolderConfiguration configuration) {
- return getFlag(configuration.getLocaleQualifier());
- }
-
-
-
- /**
- * Returns the flag for the given region.
- *
- * @param region the 2 letter region code (ISO 3166-1 alpha-2), in upper case
- * @return a suitable flag icon, or null
- */
- @Nullable
- public Image getFlag(@NonNull String region) {
- assert region.length() == 2
- && Character.isUpperCase(region.charAt(0))
- && Character.isUpperCase(region.charAt(1)) : region;
-
- return getIcon(region);
- }
-
- private Image getIcon(@NonNull String base) {
- Image flagImage = mImageMap.get(base);
- if (flagImage == null) {
- // TODO: Special case locale currently running on system such
- // that the current country matches the current locale
- if (mImageMap.containsKey(base)) {
- // Already checked: there's just no image there
- return null;
- }
- String flagFileName = base.toLowerCase(Locale.US) + ".png"; //$NON-NLS-1$
- flagImage = DesignerPlugin.getImage("nls/flags/" + flagFileName); //$NON-NLS-1$
- mImageMap.put(base, flagImage);
- }
-
- return flagImage;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/LayoutCreatorDialog.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/LayoutCreatorDialog.java
deleted file mode 100644
index 97ff66845..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/LayoutCreatorDialog.java
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.configuration;
-
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.common.resources.configuration.ResourceQualifier;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.ui.ConfigurationSelector;
-import com.android.ide.eclipse.adt.internal.ui.ConfigurationSelector.ConfigurationState;
-import com.android.ide.eclipse.adt.internal.ui.ConfigurationSelector.SelectorMode;
-import com.android.resources.ResourceFolderType;
-import com.android.sdkuilib.ui.GridDialog;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-
-/**
- * Dialog to choose a non existing {@link FolderConfiguration}.
- */
-public final class LayoutCreatorDialog extends GridDialog {
-
- private ConfigurationSelector mSelector;
- private Composite mStatusComposite;
- private Label mStatusLabel;
- private Label mStatusImage;
-
- private final FolderConfiguration mConfig = new FolderConfiguration();
- private final String mFileName;
-
- /**
- * Creates a dialog, and init the UI from a {@link FolderConfiguration}.
- * @param parentShell the parent {@link Shell}.
- * @param fileName the filename associated with the configuration
- * @param config The starting configuration.
- */
- public LayoutCreatorDialog(Shell parentShell, String fileName, FolderConfiguration config) {
- super(parentShell, 1, false);
-
- mFileName = fileName;
-
- // FIXME: add some data to know what configurations already exist.
- mConfig.set(config);
- }
-
- @Override
- public void createDialogContent(Composite parent) {
- new Label(parent, SWT.NONE).setText(
- String.format("Configuration for the alternate version of %1$s", mFileName));
-
- mSelector = new ConfigurationSelector(parent, SelectorMode.CONFIG_ONLY);
- mSelector.setConfiguration(mConfig);
-
- // because the ConfigSelector is running in CONFIG_ONLY mode, the current config
- // displayed by it is not mConfig anymore, so get the current config.
- mSelector.getConfiguration(mConfig);
-
- // parent's layout is a GridLayout as specified in the javadoc.
- GridData gd = new GridData();
- gd.widthHint = ConfigurationSelector.WIDTH_HINT;
- gd.heightHint = ConfigurationSelector.HEIGHT_HINT;
- mSelector.setLayoutData(gd);
-
- // add a listener to check on the validity of the FolderConfiguration as
- // they are built.
- mSelector.setOnChangeListener(new Runnable() {
- @Override
- public void run() {
- ConfigurationState state = mSelector.getState();
-
- switch (state) {
- case OK:
- mSelector.getConfiguration(mConfig);
-
- resetStatus();
- mStatusImage.setImage(null);
- getButton(IDialogConstants.OK_ID).setEnabled(true);
- break;
- case INVALID_CONFIG:
- ResourceQualifier invalidQualifier = mSelector.getInvalidQualifier();
- mStatusLabel.setText(String.format(
- "Invalid Configuration: %1$s has no filter set.",
- invalidQualifier.getName()));
- mStatusImage.setImage(IconFactory.getInstance().getIcon("warning")); //$NON-NLS-1$
- getButton(IDialogConstants.OK_ID).setEnabled(false);
- break;
- case REGION_WITHOUT_LANGUAGE:
- mStatusLabel.setText(
- "The Region qualifier requires the Language qualifier.");
- mStatusImage.setImage(IconFactory.getInstance().getIcon("warning")); //$NON-NLS-1$
- getButton(IDialogConstants.OK_ID).setEnabled(false);
- break;
- }
-
- // need to relayout, because of the change in size in mErrorImage.
- mStatusComposite.layout();
- }
- });
-
- mStatusComposite = new Composite(parent, SWT.NONE);
- mStatusComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- GridLayout gl = new GridLayout(2, false);
- mStatusComposite.setLayout(gl);
- gl.marginHeight = gl.marginWidth = 0;
-
- mStatusImage = new Label(mStatusComposite, SWT.NONE);
- mStatusLabel = new Label(mStatusComposite, SWT.NONE);
- mStatusLabel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- resetStatus();
- }
-
- /**
- * Sets the edited configuration on the given configuration parameter
- *
- * @param config the configuration to apply the current edits to
- */
- public void getConfiguration(FolderConfiguration config) {
- config.set(mConfig);
- }
-
- /**
- * resets the status label to show the file that will be created.
- */
- private void resetStatus() {
- String displayString = Dialog.shortenText(String.format("New File: res/%1$s/%2$s",
- mConfig.getFolderName(ResourceFolderType.LAYOUT), mFileName),
- mStatusLabel);
- mStatusLabel.setText(displayString);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/Locale.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/Locale.java
deleted file mode 100644
index 6cb396394..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/Locale.java
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.configuration;
-
-import static com.android.ide.common.resources.configuration.LocaleQualifier.FAKE_VALUE;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.common.resources.configuration.LocaleQualifier;
-
-import org.eclipse.swt.graphics.Image;
-
-/**
- * A language,region pair
- */
-public class Locale {
- /**
- * A special marker region qualifier representing any region
- */
- public static final LocaleQualifier ANY_QUALIFIER = new LocaleQualifier(FAKE_VALUE);
-
- /**
- * A locale which matches any language and region
- */
- public static final Locale ANY = new Locale(ANY_QUALIFIER);
-
- /**
- * The locale qualifier, or {@link #ANY_QUALIFIER} if this locale matches
- * any locale
- */
- @NonNull
- public final LocaleQualifier qualifier;
-
- /**
- * Constructs a new {@linkplain Locale} matching a given language in a given
- * locale.
- *
- * @param locale the locale
- */
- private Locale(@NonNull
- LocaleQualifier locale) {
- qualifier = locale;
- }
-
- /**
- * Constructs a new {@linkplain Locale} matching a given language in a given
- * specific locale.
- *
- * @param locale the locale
- * @return a locale with the given locale
- */
- @NonNull
- public static Locale create(@NonNull
- LocaleQualifier locale) {
- return new Locale(locale);
- }
-
- /**
- * Constructs a new {@linkplain Locale} for the given folder configuration
- *
- * @param folder the folder configuration
- * @return a locale with the given language and region
- */
- public static Locale create(FolderConfiguration folder) {
- LocaleQualifier locale = folder.getLocaleQualifier();
- if (locale == null) {
- return ANY;
- } else {
- return new Locale(locale);
- }
- }
-
- /**
- * Constructs a new {@linkplain Locale} for the given locale string, e.g.
- * "zh", "en-rUS", or "b+eng+US".
- *
- * @param localeString the locale description
- * @return the corresponding locale
- */
- @NonNull
- public static Locale create(@NonNull
- String localeString) {
- // Load locale. Note that this can get overwritten by the
- // project-wide settings read below.
-
- LocaleQualifier qualifier = LocaleQualifier.getQualifier(localeString);
- if (qualifier != null) {
- return new Locale(qualifier);
- } else {
- return ANY;
- }
- }
-
- /**
- * Returns a flag image to use for this locale
- *
- * @return a flag image, or a default globe icon
- */
- @NonNull
- public Image getFlagImage() {
- String languageCode = qualifier.hasLanguage() ? qualifier.getLanguage() : null;
- if (languageCode == null) {
- return FlagManager.getGlobeIcon();
- }
- String regionCode = hasRegion() ? qualifier.getRegion() : null;
- FlagManager icons = FlagManager.get();
- Image image = icons.getFlag(languageCode, regionCode);
- if (image != null) {
- return image;
- } else {
- return FlagManager.getGlobeIcon();
- }
- }
-
- /**
- * Returns true if this locale specifies a specific language. This is true
- * for all locales except {@link #ANY}.
- *
- * @return true if this locale specifies a specific language
- */
- public boolean hasLanguage() {
- return !qualifier.hasFakeValue();
- }
-
- /**
- * Returns true if this locale specifies a specific region
- *
- * @return true if this locale specifies a region
- */
- public boolean hasRegion() {
- return qualifier.getRegion() != null && !FAKE_VALUE.equals(qualifier.getRegion());
- }
-
- /**
- * Returns the locale formatted as language-region. If region is not set,
- * language is returned. If language is not set, empty string is returned.
- */
- public String toLocaleId() {
- return qualifier == ANY_QUALIFIER ? "" : qualifier.getTag();
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + qualifier.hashCode();
- return result;
- }
-
- @Override
- public boolean equals(@Nullable
- Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- Locale other = (Locale) obj;
- if (!qualifier.equals(other.qualifier))
- return false;
- return true;
- }
-
- @Override
- public String toString() {
- return qualifier.getTag();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/LocaleMenuListener.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/LocaleMenuListener.java
deleted file mode 100644
index 2bc5417b0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/LocaleMenuListener.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.configuration;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderPreviewMode;
-import com.android.ide.eclipse.adt.internal.wizards.newxmlfile.AddTranslationDialog;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MenuItem;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.ToolItem;
-
-import java.util.List;
-
-/**
- * The {@linkplain LocaleMenuListener} class is responsible for generating the locale
- * menu in the {@link ConfigurationChooser}.
- */
-class LocaleMenuListener extends SelectionAdapter {
- private static final int ACTION_SET_LOCALE = 1;
- private static final int ACTION_ADD_TRANSLATION = 2;
-
- private final ConfigurationChooser mConfigChooser;
- private final int mAction;
- private final Locale mLocale;
-
- LocaleMenuListener(
- @NonNull ConfigurationChooser configChooser,
- int action,
- @Nullable Locale locale) {
- mConfigChooser = configChooser;
- mAction = action;
- mLocale = locale;
- }
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- switch (mAction) {
- case ACTION_SET_LOCALE: {
- mConfigChooser.selectLocale(mLocale);
- mConfigChooser.onLocaleChange();
- break;
- }
- case ACTION_ADD_TRANSLATION: {
- IProject project = mConfigChooser.getProject();
- Shell shell = mConfigChooser.getShell();
- AddTranslationDialog dialog = new AddTranslationDialog(shell, project);
- dialog.open();
- break;
- }
- default: assert false : mAction;
- }
- }
-
- static void show(final ConfigurationChooser chooser, ToolItem combo) {
- Menu menu = new Menu(chooser.getShell(), SWT.POP_UP);
- Configuration configuration = chooser.getConfiguration();
- List<Locale> locales = chooser.getLocaleList();
- Locale current = configuration.getLocale();
-
- for (Locale locale : locales) {
- String title = ConfigurationChooser.getLocaleLabel(chooser, locale, false);
- MenuItem item = new MenuItem(menu, SWT.CHECK);
- item.setText(title);
- Image image = locale.getFlagImage();
- item.setImage(image);
-
- boolean selected = current == locale;
- if (selected) {
- item.setSelection(true);
- }
-
- LocaleMenuListener listener = new LocaleMenuListener(chooser, ACTION_SET_LOCALE,
- locale);
- item.addSelectionListener(listener);
- }
-
- if (locales.size() > 1) {
- @SuppressWarnings("unused")
- MenuItem separator = new MenuItem(menu, SWT.SEPARATOR);
-
- ConfigurationMenuListener.addTogglePreviewModeAction(menu,
- "Preview All Locales", chooser, RenderPreviewMode.LOCALES);
- }
-
- @SuppressWarnings("unused")
- MenuItem separator = new MenuItem(menu, SWT.SEPARATOR);
-
- MenuItem item = new MenuItem(menu, SWT.PUSH);
- item.setText("Add New Translation...");
- LocaleMenuListener listener = new LocaleMenuListener(chooser,
- ACTION_ADD_TRANSLATION, null);
- item.addSelectionListener(listener);
-
- Rectangle bounds = combo.getBounds();
- Point location = new Point(bounds.x, bounds.y + bounds.height);
- location = combo.getParent().toDisplay(location);
- menu.setLocation(location.x, location.y);
- menu.setVisible(true);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/NestedConfiguration.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/NestedConfiguration.java
deleted file mode 100644
index 50778e2f1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/NestedConfiguration.java
+++ /dev/null
@@ -1,506 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.configuration;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.resources.NightMode;
-import com.android.resources.UiMode;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.devices.Device;
-import com.android.sdklib.devices.State;
-import com.google.common.base.Objects;
-
-/**
- * An {@linkplain NestedConfiguration} is a {@link Configuration} which inherits
- * all of its values from a different configuration, except for one or more
- * attributes where it overrides a custom value.
- * <p>
- * Unlike a {@link VaryingConfiguration}, a {@linkplain NestedConfiguration}
- * will always return the same overridden value, regardless of the inherited
- * value.
- * <p>
- * For example, an {@linkplain NestedConfiguration} may fix the locale to always
- * be "en", but otherwise inherit everything else.
- */
-public class NestedConfiguration extends Configuration {
- /** The configuration we are inheriting non-overridden values from */
- protected Configuration mParent;
-
- /** Bitmask of attributes to be overridden in this configuration */
- private int mOverride;
-
- /**
- * Constructs a new {@linkplain NestedConfiguration}.
- * Construct via
- *
- * @param chooser the associated chooser
- * @param configuration the configuration to inherit from
- */
- protected NestedConfiguration(
- @NonNull ConfigurationChooser chooser,
- @NonNull Configuration configuration) {
- super(chooser);
- mParent = configuration;
-
- mFullConfig.set(mParent.mFullConfig);
- if (mParent.getEditedConfig() != null) {
- mEditedConfig = new FolderConfiguration();
- mEditedConfig.set(mParent.mEditedConfig);
- }
- }
-
- /**
- * Returns the override flags for this configuration. Corresponds to
- * the {@code CFG_} flags in {@link ConfigurationClient}.
- *
- * @return the bitmask
- */
- public int getOverrideFlags() {
- return mOverride;
- }
-
- /**
- * Creates a new {@linkplain NestedConfiguration} that has the same overriding
- * attributes as the given other {@linkplain NestedConfiguration}, and gets
- * its values from the given {@linkplain Configuration}.
- *
- * @param other the configuration to copy overrides from
- * @param values the configuration to copy values from
- * @param parent the parent to tie the configuration to for inheriting values
- * @return a new configuration
- */
- @NonNull
- public static NestedConfiguration create(
- @NonNull NestedConfiguration other,
- @NonNull Configuration values,
- @NonNull Configuration parent) {
- NestedConfiguration configuration =
- new NestedConfiguration(other.mConfigChooser, parent);
- initFrom(configuration, other, values, true /*sync*/);
- return configuration;
- }
-
- /**
- * Initializes a new {@linkplain NestedConfiguration} with the overriding
- * attributes as the given other {@linkplain NestedConfiguration}, and gets
- * its values from the given {@linkplain Configuration}.
- *
- * @param configuration the configuration to initialize
- * @param other the configuration to copy overrides from
- * @param values the configuration to copy values from
- * @param sync if true, sync the folder configuration from
- */
- protected static void initFrom(NestedConfiguration configuration,
- NestedConfiguration other, Configuration values, boolean sync) {
- configuration.mOverride = other.mOverride;
- configuration.setDisplayName(values.getDisplayName());
- configuration.setActivity(values.getActivity());
-
- if (configuration.isOverridingLocale()) {
- configuration.setLocale(values.getLocale(), true);
- }
- if (configuration.isOverridingTarget()) {
- configuration.setTarget(values.getTarget(), true);
- }
- if (configuration.isOverridingDevice()) {
- configuration.setDevice(values.getDevice(), true);
- }
- if (configuration.isOverridingDeviceState()) {
- configuration.setDeviceState(values.getDeviceState(), true);
- }
- if (configuration.isOverridingNightMode()) {
- configuration.setNightMode(values.getNightMode(), true);
- }
- if (configuration.isOverridingUiMode()) {
- configuration.setUiMode(values.getUiMode(), true);
- }
- if (sync) {
- configuration.syncFolderConfig();
- }
- }
-
- /**
- * Sets the parent configuration that this configuration is inheriting from.
- *
- * @param parent the parent configuration
- */
- public void setParent(@NonNull Configuration parent) {
- mParent = parent;
- }
-
- /**
- * Creates a new {@linkplain Configuration} which inherits values from the
- * given parent {@linkplain Configuration}, possibly overriding some as
- * well.
- *
- * @param chooser the associated chooser
- * @param parent the configuration to inherit values from
- * @return a new configuration
- */
- @NonNull
- public static NestedConfiguration create(@NonNull ConfigurationChooser chooser,
- @NonNull Configuration parent) {
- return new NestedConfiguration(chooser, parent);
- }
-
- @Override
- @Nullable
- public String getTheme() {
- // Never overridden: this is a static attribute of a layout, not something which
- // varies by configuration or at runtime
- return mParent.getTheme();
- }
-
- @Override
- public void setTheme(String theme) {
- // Never overridden
- mParent.setTheme(theme);
- }
-
- /**
- * Sets whether the locale should be overridden by this configuration
- *
- * @param override if true, override the inherited value
- */
- public void setOverrideLocale(boolean override) {
- mOverride |= CFG_LOCALE;
- }
-
- /**
- * Returns true if the locale is overridden
- *
- * @return true if the locale is overridden
- */
- public final boolean isOverridingLocale() {
- return (mOverride & CFG_LOCALE) != 0;
- }
-
- @Override
- @NonNull
- public Locale getLocale() {
- if (isOverridingLocale()) {
- return super.getLocale();
- } else {
- return mParent.getLocale();
- }
- }
-
- @Override
- public void setLocale(@NonNull Locale locale, boolean skipSync) {
- if (isOverridingLocale()) {
- super.setLocale(locale, skipSync);
- } else {
- mParent.setLocale(locale, skipSync);
- }
- }
-
- /**
- * Sets whether the rendering target should be overridden by this configuration
- *
- * @param override if true, override the inherited value
- */
- public void setOverrideTarget(boolean override) {
- mOverride |= CFG_TARGET;
- }
-
- /**
- * Returns true if the target is overridden
- *
- * @return true if the target is overridden
- */
- public final boolean isOverridingTarget() {
- return (mOverride & CFG_TARGET) != 0;
- }
-
- @Override
- @Nullable
- public IAndroidTarget getTarget() {
- if (isOverridingTarget()) {
- return super.getTarget();
- } else {
- return mParent.getTarget();
- }
- }
-
- @Override
- public void setTarget(IAndroidTarget target, boolean skipSync) {
- if (isOverridingTarget()) {
- super.setTarget(target, skipSync);
- } else {
- mParent.setTarget(target, skipSync);
- }
- }
-
- /**
- * Sets whether the device should be overridden by this configuration
- *
- * @param override if true, override the inherited value
- */
- public void setOverrideDevice(boolean override) {
- mOverride |= CFG_DEVICE;
- }
-
- /**
- * Returns true if the device is overridden
- *
- * @return true if the device is overridden
- */
- public final boolean isOverridingDevice() {
- return (mOverride & CFG_DEVICE) != 0;
- }
-
- @Override
- @Nullable
- public Device getDevice() {
- if (isOverridingDevice()) {
- return super.getDevice();
- } else {
- return mParent.getDevice();
- }
- }
-
- @Override
- public void setDevice(Device device, boolean skipSync) {
- if (isOverridingDevice()) {
- super.setDevice(device, skipSync);
- } else {
- mParent.setDevice(device, skipSync);
- }
- }
-
- /**
- * Sets whether the device state should be overridden by this configuration
- *
- * @param override if true, override the inherited value
- */
- public void setOverrideDeviceState(boolean override) {
- mOverride |= CFG_DEVICE_STATE;
- }
-
- /**
- * Returns true if the device state is overridden
- *
- * @return true if the device state is overridden
- */
- public final boolean isOverridingDeviceState() {
- return (mOverride & CFG_DEVICE_STATE) != 0;
- }
-
- @Override
- @Nullable
- public State getDeviceState() {
- if (isOverridingDeviceState()) {
- return super.getDeviceState();
- } else {
- State state = mParent.getDeviceState();
- if (isOverridingDevice()) {
- // If the device differs, I need to look up a suitable equivalent state
- // on our device
- if (state != null) {
- Device device = super.getDevice();
- if (device != null) {
- return device.getState(state.getName());
- }
- }
- }
-
- return state;
- }
- }
-
- @Override
- public void setDeviceState(State state, boolean skipSync) {
- if (isOverridingDeviceState()) {
- super.setDeviceState(state, skipSync);
- } else {
- if (isOverridingDevice()) {
- Device device = super.getDevice();
- if (device != null) {
- State equivalentState = device.getState(state.getName());
- if (equivalentState != null) {
- state = equivalentState;
- }
- }
- }
- mParent.setDeviceState(state, skipSync);
- }
- }
-
- /**
- * Sets whether the night mode should be overridden by this configuration
- *
- * @param override if true, override the inherited value
- */
- public void setOverrideNightMode(boolean override) {
- mOverride |= CFG_NIGHT_MODE;
- }
-
- /**
- * Returns true if the night mode is overridden
- *
- * @return true if the night mode is overridden
- */
- public final boolean isOverridingNightMode() {
- return (mOverride & CFG_NIGHT_MODE) != 0;
- }
-
- @Override
- @NonNull
- public NightMode getNightMode() {
- if (isOverridingNightMode()) {
- return super.getNightMode();
- } else {
- return mParent.getNightMode();
- }
- }
-
- @Override
- public void setNightMode(@NonNull NightMode night, boolean skipSync) {
- if (isOverridingNightMode()) {
- super.setNightMode(night, skipSync);
- } else {
- mParent.setNightMode(night, skipSync);
- }
- }
-
- /**
- * Sets whether the UI mode should be overridden by this configuration
- *
- * @param override if true, override the inherited value
- */
- public void setOverrideUiMode(boolean override) {
- mOverride |= CFG_UI_MODE;
- }
-
- /**
- * Returns true if the UI mode is overridden
- *
- * @return true if the UI mode is overridden
- */
- public final boolean isOverridingUiMode() {
- return (mOverride & CFG_UI_MODE) != 0;
- }
-
- @Override
- @NonNull
- public UiMode getUiMode() {
- if (isOverridingUiMode()) {
- return super.getUiMode();
- } else {
- return mParent.getUiMode();
- }
- }
-
- @Override
- public void setUiMode(@NonNull UiMode uiMode, boolean skipSync) {
- if (isOverridingUiMode()) {
- super.setUiMode(uiMode, skipSync);
- } else {
- mParent.setUiMode(uiMode, skipSync);
- }
- }
-
- /**
- * Returns the configuration this {@linkplain NestedConfiguration} is
- * inheriting from
- *
- * @return the configuration this configuration is inheriting from
- */
- @NonNull
- public Configuration getParent() {
- return mParent;
- }
-
- @Override
- @Nullable
- public String getActivity() {
- return mParent.getActivity();
- }
-
- @Override
- public void setActivity(String activity) {
- super.setActivity(activity);
- }
-
- /**
- * Returns a computed display name (ignoring the value stored by
- * {@link #setDisplayName(String)}) by looking at the override flags
- * and picking a suitable name.
- *
- * @return a suitable display name
- */
- @Nullable
- public String computeDisplayName() {
- return computeDisplayName(mOverride, this);
- }
-
- /**
- * Computes a display name for the given configuration, using the given
- * override flags (which correspond to the {@code CFG_} constants in
- * {@link ConfigurationClient}
- *
- * @param flags the override bitmask
- * @param configuration the configuration to fetch values from
- * @return a suitable display name
- */
- @Nullable
- public static String computeDisplayName(int flags, @NonNull Configuration configuration) {
- if ((flags & CFG_LOCALE) != 0) {
- return ConfigurationChooser.getLocaleLabel(configuration.mConfigChooser,
- configuration.getLocale(), false);
- }
-
- if ((flags & CFG_TARGET) != 0) {
- return ConfigurationChooser.getRenderingTargetLabel(configuration.getTarget(), false);
- }
-
- if ((flags & CFG_DEVICE) != 0) {
- return ConfigurationChooser.getDeviceLabel(configuration.getDevice(), true);
- }
-
- if ((flags & CFG_DEVICE_STATE) != 0) {
- State deviceState = configuration.getDeviceState();
- if (deviceState != null) {
- return deviceState.getName();
- }
- }
-
- if ((flags & CFG_NIGHT_MODE) != 0) {
- return configuration.getNightMode().getLongDisplayValue();
- }
-
- if ((flags & CFG_UI_MODE) != 0) {
- configuration.getUiMode().getLongDisplayValue();
- }
-
- return null;
- }
-
- @Override
- public String toString() {
- return Objects.toStringHelper(this.getClass())
- .add("parent", mParent.getDisplayName()) //$NON-NLS-1$
- .add("display", getDisplayName()) //$NON-NLS-1$
- .add("overrideLocale", isOverridingLocale()) //$NON-NLS-1$
- .add("overrideTarget", isOverridingTarget()) //$NON-NLS-1$
- .add("overrideDevice", isOverridingDevice()) //$NON-NLS-1$
- .add("overrideDeviceState", isOverridingDeviceState()) //$NON-NLS-1$
- .add("persistent", toPersistentString()) //$NON-NLS-1$
- .toString();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/OrientationMenuAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/OrientationMenuAction.java
deleted file mode 100644
index 5cad29afc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/OrientationMenuAction.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.configuration;
-
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.SubmenuAction;
-import com.android.resources.NightMode;
-import com.android.resources.ScreenOrientation;
-import com.android.resources.UiMode;
-import com.android.sdklib.devices.Device;
-import com.android.sdklib.devices.State;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.ActionContributionItem;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.ToolItem;
-
-import java.util.List;
-
-/**
- * Action which creates a submenu that shows the available orientations as well
- * as some related options for night mode and dock mode
- */
-class OrientationMenuAction extends SubmenuAction {
- // Constants used to indicate what type of menu is being shown, such that
- // the submenus can lazily construct their contents
- private static final int MENU_NIGHTMODE = 1;
- private static final int MENU_UIMODE = 2;
-
- private final ConfigurationChooser mConfigChooser;
- /** Type of menu; one of the constants {@link #MENU_NIGHTMODE} etc */
- private final int mType;
-
- OrientationMenuAction(int type, String title, ConfigurationChooser configuration) {
- super(title);
- mType = type;
- mConfigChooser = configuration;
- }
-
- static void showMenu(ConfigurationChooser configChooser, ToolItem combo) {
- MenuManager manager = new MenuManager();
-
- // Show toggles for all the available states
-
- Configuration configuration = configChooser.getConfiguration();
- Device device = configuration.getDevice();
- State current = configuration.getDeviceState();
- if (device != null) {
- List<State> states = device.getAllStates();
-
- if (states.size() > 1 && current != null) {
- State flip = configuration.getNextDeviceState(current);
- String flipName = flip != null ? flip.getName() : current.getName();
- manager.add(new DeviceConfigAction(configChooser,
- String.format("Switch to %1$s", flipName), flip, false, true));
- manager.add(new Separator());
- }
-
- for (State config : states) {
- manager.add(new DeviceConfigAction(configChooser, config.getName(),
- config, config == current, false));
- }
- manager.add(new Separator());
- }
- manager.add(new OrientationMenuAction(MENU_UIMODE, "UI Mode", configChooser));
- manager.add(new Separator());
- manager.add(new OrientationMenuAction(MENU_NIGHTMODE, "Night Mode", configChooser));
-
- Menu menu = manager.createContextMenu(configChooser.getShell());
- Rectangle bounds = combo.getBounds();
- Point location = new Point(bounds.x, bounds.y + bounds.height);
- location = combo.getParent().toDisplay(location);
- menu.setLocation(location.x, location.y);
- menu.setVisible(true);
- }
-
- @Override
- protected void addMenuItems(Menu menu) {
- switch (mType) {
- case MENU_NIGHTMODE: {
- NightMode selected = mConfigChooser.getConfiguration().getNightMode();
- for (NightMode mode : NightMode.values()) {
- boolean checked = mode == selected;
- SelectNightModeAction action = new SelectNightModeAction(mode, checked);
- new ActionContributionItem(action).fill(menu, -1);
-
- }
- break;
- }
- case MENU_UIMODE: {
- UiMode selected = mConfigChooser.getConfiguration().getUiMode();
- for (UiMode mode : UiMode.values()) {
- boolean checked = mode == selected;
- SelectUiModeAction action = new SelectUiModeAction(mode, checked);
- new ActionContributionItem(action).fill(menu, -1);
- }
- break;
- }
- }
- }
-
-
- private class SelectNightModeAction extends Action {
- private final NightMode mMode;
-
- private SelectNightModeAction(NightMode mode, boolean checked) {
- super(mode.getLongDisplayValue(), IAction.AS_RADIO_BUTTON);
- mMode = mode;
- if (checked) {
- setChecked(true);
- }
- }
-
- @Override
- public void run() {
- Configuration configuration = mConfigChooser.getConfiguration();
- configuration.setNightMode(mMode, false);
- mConfigChooser.notifyFolderConfigChanged();
- }
- }
-
- private class SelectUiModeAction extends Action {
- private final UiMode mMode;
-
- private SelectUiModeAction(UiMode mode, boolean checked) {
- super(mode.getLongDisplayValue(), IAction.AS_RADIO_BUTTON);
- mMode = mode;
- if (checked) {
- setChecked(true);
- }
- }
-
- @Override
- public void run() {
- Configuration configuration = mConfigChooser.getConfiguration();
- configuration.setUiMode(mMode, false);
- }
- }
-
- private static class DeviceConfigAction extends Action {
- private final ConfigurationChooser mConfiguration;
- private final State mState;
-
- private DeviceConfigAction(ConfigurationChooser configuration, String title,
- State state, boolean checked, boolean flip) {
- super(title, IAction.AS_RADIO_BUTTON);
- mConfiguration = configuration;
- mState = state;
- if (checked) {
- setChecked(true);
- }
- ScreenOrientation orientation = configuration.getOrientation(state);
- setImageDescriptor(configuration.getOrientationImage(orientation, flip));
- }
-
- @Override
- public void run() {
- mConfiguration.selectDeviceState(mState);
- mConfiguration.onDeviceConfigChange();
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/SelectThemeAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/SelectThemeAction.java
deleted file mode 100644
index d062849d1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/SelectThemeAction.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.configuration;
-
-import static com.android.SdkConstants.ANDROID_STYLE_RESOURCE_PREFIX;
-import static com.android.SdkConstants.STYLE_RESOURCE_PREFIX;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-
-/**
- * Action which brings up the "Create new XML File" wizard, pre-selected with the
- * animation category
- */
-class SelectThemeAction extends Action {
- private final ConfigurationChooser mConfiguration;
- private final String mTheme;
-
- public SelectThemeAction(ConfigurationChooser configuration, String title, String theme,
- boolean selected) {
- super(title, IAction.AS_RADIO_BUTTON);
- assert theme.startsWith(STYLE_RESOURCE_PREFIX)
- || theme.startsWith(ANDROID_STYLE_RESOURCE_PREFIX) : theme;
- mConfiguration = configuration;
- mTheme = theme;
- if (selected) {
- setChecked(selected);
- }
- }
-
- @Override
- public void run() {
- mConfiguration.selectTheme(mTheme);
- mConfiguration.onThemeChange();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/TargetMenuListener.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/TargetMenuListener.java
deleted file mode 100644
index 71905f7c9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/TargetMenuListener.java
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.configuration;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.sdklib.AndroidVersion;
-import com.android.sdklib.IAndroidTarget;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MenuItem;
-import org.eclipse.swt.widgets.ToolItem;
-
-import java.util.List;
-import java.util.RandomAccess;
-
-/**
- * The {@linkplain TargetMenuListener} class is responsible for
- * generating the rendering target menu in the {@link ConfigurationChooser}.
- */
-class TargetMenuListener extends SelectionAdapter {
- private final ConfigurationChooser mConfigChooser;
- private final IAndroidTarget mTarget;
- private final boolean mPickBest;
-
- TargetMenuListener(
- @NonNull ConfigurationChooser configChooser,
- @Nullable IAndroidTarget target,
- boolean pickBest) {
- mConfigChooser = configChooser;
- mTarget = target;
- mPickBest = pickBest;
- }
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- IAndroidTarget target = mTarget;
- AdtPrefs prefs = AdtPrefs.getPrefs();
- if (mPickBest) {
- boolean autoPick = prefs.isAutoPickRenderTarget();
- autoPick = !autoPick;
- prefs.setAutoPickRenderTarget(autoPick);
- if (autoPick) {
- target = ConfigurationMatcher.findDefaultRenderTarget(mConfigChooser);
- } else {
- // Turn it off, but keep current target until another one is chosen
- return;
- }
- } else {
- // Manually picked some other target: turn off auto-pick
- prefs.setAutoPickRenderTarget(false);
- }
- mConfigChooser.selectTarget(target);
- mConfigChooser.onRenderingTargetChange();
- }
-
- static void show(ConfigurationChooser chooser, ToolItem combo) {
- Menu menu = new Menu(chooser.getShell(), SWT.POP_UP);
- Configuration configuration = chooser.getConfiguration();
- IAndroidTarget current = configuration.getTarget();
- List<IAndroidTarget> targets = chooser.getTargetList();
- boolean haveRecent = false;
-
- MenuItem menuItem = new MenuItem(menu, SWT.CHECK);
- menuItem.setText("Automatically Pick Best");
- menuItem.addSelectionListener(new TargetMenuListener(chooser, null, true));
- if (AdtPrefs.getPrefs().isAutoPickRenderTarget()) {
- menuItem.setSelection(true);
- }
-
- @SuppressWarnings("unused")
- MenuItem separator = new MenuItem(menu, SWT.SEPARATOR);
-
- // Process in reverse order: most important targets first
- assert targets instanceof RandomAccess;
- for (int i = targets.size() - 1; i >= 0; i--) {
- IAndroidTarget target = targets.get(i);
-
- AndroidVersion version = target.getVersion();
- if (version.getApiLevel() >= 7) {
- haveRecent = true;
- } else if (haveRecent) {
- // Don't show ancient rendering targets; they're pretty broken
- // (unless of course all you have are ancient targets)
- break;
- }
-
- String title = ConfigurationChooser.getRenderingTargetLabel(target, false);
- MenuItem item = new MenuItem(menu, SWT.CHECK);
- item.setText(title);
-
- boolean selected = current == target;
- if (selected) {
- item.setSelection(true);
- }
-
- item.addSelectionListener(new TargetMenuListener(chooser, target, false));
- }
-
- Rectangle bounds = combo.getBounds();
- Point location = new Point(bounds.x, bounds.y + bounds.height);
- location = combo.getParent().toDisplay(location);
- menu.setLocation(location.x, location.y);
- menu.setVisible(true);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ThemeMenuAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ThemeMenuAction.java
deleted file mode 100644
index b1ce21d36..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ThemeMenuAction.java
+++ /dev/null
@@ -1,318 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.configuration;
-
-import static com.android.SdkConstants.ANDROID_STYLE_RESOURCE_PREFIX;
-
-import com.android.ide.eclipse.adt.internal.editors.Hyperlinks;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.SubmenuAction;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo.ActivityAttributes;
-import com.android.ide.eclipse.adt.internal.resources.ResourceHelper;
-import com.android.sdklib.IAndroidTarget;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.ActionContributionItem;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.text.hyperlink.IHyperlink;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.ToolItem;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * Action which creates a submenu displaying available themes
- */
-class ThemeMenuAction extends SubmenuAction {
- private static final String DEVICE_LIGHT_PREFIX =
- ANDROID_STYLE_RESOURCE_PREFIX + "Theme.DeviceDefault.Light"; //$NON-NLS-1$
- private static final String HOLO_LIGHT_PREFIX =
- ANDROID_STYLE_RESOURCE_PREFIX + "Theme.Holo.Light"; //$NON-NLS-1$
- private static final String DEVICE_PREFIX =
- ANDROID_STYLE_RESOURCE_PREFIX + "Theme.DeviceDefault"; //$NON-NLS-1$
- private static final String HOLO_PREFIX =
- ANDROID_STYLE_RESOURCE_PREFIX + "Theme.Holo"; //$NON-NLS-1$
- private static final String LIGHT_PREFIX =
- ANDROID_STYLE_RESOURCE_PREFIX +"Theme.Light"; //$NON-NLS-1$
- private static final String THEME_PREFIX =
- ANDROID_STYLE_RESOURCE_PREFIX +"Theme"; //$NON-NLS-1$
-
- // Constants used to indicate what type of menu is being shown, such that
- // the submenus can lazily construct their contents
- private static final int MENU_MANIFEST = 1;
- private static final int MENU_PROJECT = 2;
- private static final int MENU_THEME = 3;
- private static final int MENU_THEME_LIGHT = 4;
- private static final int MENU_HOLO = 5;
- private static final int MENU_HOLO_LIGHT = 6;
- private static final int MENU_DEVICE = 7;
- private static final int MENU_DEVICE_LIGHT = 8;
- private static final int MENU_ALL = 9;
-
- private final ConfigurationChooser mConfigChooser;
- private final List<String> mThemeList;
- /** Type of menu; one of the constants {@link #MENU_ALL} etc */
- private final int mType;
-
- ThemeMenuAction(int type, String title, ConfigurationChooser configuration,
- List<String> themeList) {
- super(title);
- mType = type;
- mConfigChooser = configuration;
- mThemeList = themeList;
- }
-
- static void showThemeMenu(ConfigurationChooser configChooser, ToolItem combo,
- List<String> themeList) {
- MenuManager manager = new MenuManager();
-
- // First show the currently selected theme (grayed out since you can't
- // reselect it)
- Configuration configuration = configChooser.getConfiguration();
- String currentTheme = configuration.getTheme();
- String currentName = null;
- if (currentTheme != null) {
- currentName = ResourceHelper.styleToTheme(currentTheme);
- SelectThemeAction action = new SelectThemeAction(configChooser,
- currentName,
- currentTheme,
- true /* selected */);
- action.setEnabled(false);
- manager.add(action);
- manager.add(new Separator());
- }
-
- String preferred = configuration.computePreferredTheme();
- if (preferred != null && !preferred.equals(currentTheme)) {
- manager.add(new SelectThemeAction(configChooser,
- ResourceHelper.styleToTheme(preferred),
- preferred, false /* selected */));
- manager.add(new Separator());
- }
-
- IAndroidTarget target = configuration.getTarget();
- int apiLevel = target != null ? target.getVersion().getApiLevel() : 1;
- boolean hasHolo = apiLevel >= 11; // Honeycomb
- boolean hasDeviceDefault = apiLevel >= 14; // ICS
-
- // TODO: Add variations of the current theme here, e.g.
- // if you're using Theme.Holo, add Theme.Holo.Dialog, Theme.Holo.Panel,
- // Theme.Holo.Wallpaper etc
-
- manager.add(new ThemeMenuAction(MENU_PROJECT, "Project Themes",
- configChooser, themeList));
- manager.add(new ThemeMenuAction(MENU_MANIFEST, "Manifest Themes",
- configChooser, themeList));
-
- manager.add(new Separator());
-
- if (hasHolo) {
- manager.add(new ThemeMenuAction(MENU_HOLO, "Holo",
- configChooser, themeList));
- manager.add(new ThemeMenuAction(MENU_HOLO_LIGHT, "Holo.Light",
- configChooser, themeList));
- }
- if (hasDeviceDefault) {
- manager.add(new ThemeMenuAction(MENU_DEVICE, "DeviceDefault",
- configChooser, themeList));
- manager.add(new ThemeMenuAction(MENU_DEVICE_LIGHT, "DeviceDefault.Light",
- configChooser, themeList));
- }
- manager.add(new ThemeMenuAction(MENU_THEME, "Theme",
- configChooser, themeList));
- manager.add(new ThemeMenuAction(MENU_THEME_LIGHT, "Theme.Light",
- configChooser, themeList));
-
- // TODO: Add generic types like Wallpaper, Dialog, Alert, etc here, with
- // submenus for picking it within each theme category?
-
- manager.add(new Separator());
- manager.add(new ThemeMenuAction(MENU_ALL, "All",
- configChooser, themeList));
-
- if (currentTheme != null) {
- assert currentName != null;
- manager.add(new Separator());
- String title = String.format("Open %1$s Declaration...", currentName);
- manager.add(new OpenThemeAction(title, configChooser.getEditedFile(), currentTheme));
- }
-
- Menu menu = manager.createContextMenu(configChooser.getShell());
-
- Rectangle bounds = combo.getBounds();
- Point location = new Point(bounds.x, bounds.y + bounds.height);
- location = combo.getParent().toDisplay(location);
- menu.setLocation(location.x, location.y);
- menu.setVisible(true);
- }
-
- @Override
- protected void addMenuItems(Menu menu) {
- switch (mType) {
- case MENU_ALL:
- addMenuItems(menu, mThemeList);
- break;
-
- case MENU_MANIFEST: {
- IProject project = mConfigChooser.getEditedFile().getProject();
- ManifestInfo manifest = ManifestInfo.get(project);
- Configuration configuration = mConfigChooser.getConfiguration();
- String activity = configuration.getActivity();
- if (activity != null) {
- ActivityAttributes attributes = manifest.getActivityAttributes(activity);
- if (attributes != null) {
- String theme = attributes.getTheme();
- if (theme != null) {
- addMenuItem(menu, theme, isSelectedTheme(theme));
- }
- }
- }
-
- String manifestTheme = manifest.getManifestTheme();
- boolean found = false;
- Set<String> allThemes = new HashSet<String>();
- if (manifestTheme != null) {
- found = true;
- allThemes.add(manifestTheme);
- }
- for (ActivityAttributes info : manifest.getActivityAttributesMap().values()) {
- if (info.getTheme() != null) {
- found = true;
- allThemes.add(info.getTheme());
- }
- }
- List<String> sorted = new ArrayList<String>(allThemes);
- Collections.sort(sorted);
- String current = configuration.getTheme();
- for (String theme : sorted) {
- boolean selected = theme.equals(current);
- addMenuItem(menu, theme, selected);
- }
- if (!found) {
- addDisabledMessageItem("No themes are registered in the manifest");
- }
- break;
- }
- case MENU_PROJECT: {
- int size = mThemeList.size();
- List<String> themes = new ArrayList<String>(size);
- for (int i = 0; i < size; i++) {
- String theme = mThemeList.get(i);
- if (ResourceHelper.isProjectStyle(theme)) {
- themes.add(theme);
- }
- }
- if (themes.isEmpty()) {
- addDisabledMessageItem("There are no local theme styles in the project");
- } else {
- addMenuItems(menu, themes);
- }
- break;
- }
- case MENU_THEME: {
- // Can't just use the usual filterThemes() call here because we need
- // to exclude on multiple prefixes: Holo, DeviceDefault, Light, ...
- List<String> themes = new ArrayList<String>(mThemeList.size());
- for (String theme : mThemeList) {
- if (theme.startsWith(THEME_PREFIX)
- && !theme.startsWith(LIGHT_PREFIX)
- && !theme.startsWith(HOLO_PREFIX)
- && !theme.startsWith(DEVICE_PREFIX)) {
- themes.add(theme);
- }
- }
-
- addMenuItems(menu, themes);
- break;
- }
- case MENU_THEME_LIGHT:
- addMenuItems(menu, filterThemes(LIGHT_PREFIX, null));
- break;
- case MENU_HOLO:
- addMenuItems(menu, filterThemes(HOLO_PREFIX, HOLO_LIGHT_PREFIX));
- break;
- case MENU_HOLO_LIGHT:
- addMenuItems(menu, filterThemes(HOLO_LIGHT_PREFIX, null));
- break;
- case MENU_DEVICE:
- addMenuItems(menu, filterThemes(DEVICE_PREFIX, DEVICE_LIGHT_PREFIX));
- break;
- case MENU_DEVICE_LIGHT:
- addMenuItems(menu, filterThemes(DEVICE_LIGHT_PREFIX, null));
- break;
- }
- }
-
- private List<String> filterThemes(String include, String exclude) {
- List<String> themes = new ArrayList<String>(mThemeList.size());
- for (String theme : mThemeList) {
- if (theme.startsWith(include) && (exclude == null || !theme.startsWith(exclude))) {
- themes.add(theme);
- }
- }
-
- return themes;
- }
-
- private void addMenuItems(Menu menu, List<String> themes) {
- String current = mConfigChooser.getConfiguration().getTheme();
- for (String theme : themes) {
- addMenuItem(menu, theme, theme.equals(current));
- }
- }
-
- private boolean isSelectedTheme(String theme) {
- return theme.equals(mConfigChooser.getConfiguration().getTheme());
- }
-
- private void addMenuItem(Menu menu, String theme, boolean selected) {
- String title = ResourceHelper.styleToTheme(theme);
- SelectThemeAction action = new SelectThemeAction(mConfigChooser, title, theme, selected);
- new ActionContributionItem(action).fill(menu, -1);
- }
-
- private static class OpenThemeAction extends Action {
- private final String mTheme;
- private final IFile mFile;
-
- private OpenThemeAction(String title, IFile file, String theme) {
- super(title, IAction.AS_PUSH_BUTTON);
- mFile = file;
- mTheme = theme;
- }
-
- @Override
- public void run() {
- IProject project = mFile.getProject();
- IHyperlink[] links = Hyperlinks.getResourceLinks(null, mTheme, project, null);
- if (links != null && links.length > 0) {
- IHyperlink link = links[0];
- link.open();
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/VaryingConfiguration.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/VaryingConfiguration.java
deleted file mode 100644
index f472cd6b3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/configuration/VaryingConfiguration.java
+++ /dev/null
@@ -1,509 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.configuration;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.rendering.api.Capability;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.resources.Density;
-import com.android.resources.NightMode;
-import com.android.resources.UiMode;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.devices.Device;
-import com.android.sdklib.devices.Hardware;
-import com.android.sdklib.devices.Screen;
-import com.android.sdklib.devices.State;
-
-import java.util.Collection;
-import java.util.List;
-
-/**
- * An {@linkplain VaryingConfiguration} is a {@link Configuration} which
- * inherits all of its values from a different configuration, except for one or
- * more attributes where it overrides a custom value, and the overridden value
- * will always <b>differ</b> from the inherited value!
- * <p>
- * For example, a {@linkplain VaryingConfiguration} may state that it
- * overrides the locale, and if the inherited locale is "en", then the returned
- * locale from the {@linkplain VaryingConfiguration} may be for example "nb",
- * but never "en".
- * <p>
- * The configuration will attempt to make its changed inherited value to be as
- * different as possible from the inherited value. Thus, a configuration which
- * overrides the device will probably return a phone-sized screen if the
- * inherited device is a tablet, or vice versa.
- */
-public class VaryingConfiguration extends NestedConfiguration {
- /** Variation version; see {@link #setVariation(int)} */
- private int mVariation;
-
- /** Variation version count; see {@link #setVariationCount(int)} */
- private int mVariationCount;
-
- /** Bitmask of attributes to be varied/alternated from the parent */
- private int mAlternate;
-
- /**
- * Constructs a new {@linkplain VaryingConfiguration}.
- * Construct via
- *
- * @param chooser the associated chooser
- * @param configuration the configuration to inherit from
- */
- private VaryingConfiguration(
- @NonNull ConfigurationChooser chooser,
- @NonNull Configuration configuration) {
- super(chooser, configuration);
- }
-
- /**
- * Creates a new {@linkplain Configuration} which inherits values from the
- * given parent {@linkplain Configuration}, possibly overriding some as
- * well.
- *
- * @param chooser the associated chooser
- * @param parent the configuration to inherit values from
- * @return a new configuration
- */
- @NonNull
- public static VaryingConfiguration create(@NonNull ConfigurationChooser chooser,
- @NonNull Configuration parent) {
- return new VaryingConfiguration(chooser, parent);
- }
-
- /**
- * Creates a new {@linkplain VaryingConfiguration} that has the same overriding
- * attributes as the given other {@linkplain VaryingConfiguration}.
- *
- * @param other the configuration to copy overrides from
- * @param parent the parent to tie the configuration to for inheriting values
- * @return a new configuration
- */
- @NonNull
- public static VaryingConfiguration create(
- @NonNull VaryingConfiguration other,
- @NonNull Configuration parent) {
- VaryingConfiguration configuration =
- new VaryingConfiguration(other.mConfigChooser, parent);
- initFrom(configuration, other, other, false);
- configuration.mAlternate = other.mAlternate;
- configuration.mVariation = other.mVariation;
- configuration.mVariationCount = other.mVariationCount;
- configuration.syncFolderConfig();
-
- return configuration;
- }
-
- /**
- * Returns the alternate flags for this configuration. Corresponds to
- * the {@code CFG_} flags in {@link ConfigurationClient}.
- *
- * @return the bitmask
- */
- public int getAlternateFlags() {
- return mAlternate;
- }
-
- @Override
- public void syncFolderConfig() {
- super.syncFolderConfig();
- updateDisplayName();
- }
-
- /**
- * Sets the variation version for this
- * {@linkplain VaryingConfiguration}. There might be multiple
- * {@linkplain VaryingConfiguration} instances inheriting from a
- * {@link Configuration}. The variation version allows them to choose
- * different complementing values, so they don't all flip to the same other
- * (out of multiple choices) value. The {@link #setVariationCount(int)}
- * value can be used to determine how to partition the buckets of values.
- * Also updates the variation count if necessary.
- *
- * @param variation variation version
- */
- public void setVariation(int variation) {
- mVariation = variation;
- mVariationCount = Math.max(mVariationCount, variation + 1);
- }
-
- /**
- * Sets the number of {@link VaryingConfiguration} variations mapped
- * to the same parent configuration as this one. See
- * {@link #setVariation(int)} for details.
- *
- * @param count the total number of variation versions
- */
- public void setVariationCount(int count) {
- mVariationCount = count;
- }
-
- /**
- * Updates the display name in this configuration based on the values and override settings
- */
- public void updateDisplayName() {
- setDisplayName(computeDisplayName());
- }
-
- @Override
- @NonNull
- public Locale getLocale() {
- if (isOverridingLocale()) {
- return super.getLocale();
- }
- Locale locale = mParent.getLocale();
- if (isAlternatingLocale() && locale != null) {
- List<Locale> locales = mConfigChooser.getLocaleList();
- for (Locale l : locales) {
- // TODO: Try to be smarter about which one we pick; for example, try
- // to pick a language that is substantially different from the inherited
- // language, such as either with the strings of the largest or shortest
- // length, or perhaps based on some geography or population metrics
- if (!l.equals(locale)) {
- locale = l;
- break;
- }
- }
- }
-
- return locale;
- }
-
- @Override
- @Nullable
- public IAndroidTarget getTarget() {
- if (isOverridingTarget()) {
- return super.getTarget();
- }
- IAndroidTarget target = mParent.getTarget();
- if (isAlternatingTarget() && target != null) {
- List<IAndroidTarget> targets = mConfigChooser.getTargetList();
- if (!targets.isEmpty()) {
- // Pick a different target: if you're showing the most recent render target,
- // then pick the lowest supported target, and vice versa
- IAndroidTarget mostRecent = targets.get(targets.size() - 1);
- if (target.equals(mostRecent)) {
- // Find oldest supported
- ManifestInfo info = ManifestInfo.get(mConfigChooser.getProject());
- int minSdkVersion = info.getMinSdkVersion();
- for (IAndroidTarget t : targets) {
- if (t.getVersion().getApiLevel() >= minSdkVersion) {
- target = t;
- break;
- }
- }
- } else {
- target = mostRecent;
- }
- }
- }
-
- return target;
- }
-
- // Cached values, key=parent's device, cached value=device
- private Device mPrevParentDevice;
- private Device mPrevDevice;
-
- @Override
- @Nullable
- public Device getDevice() {
- if (isOverridingDevice()) {
- return super.getDevice();
- }
- Device device = mParent.getDevice();
- if (isAlternatingDevice() && device != null) {
- if (device == mPrevParentDevice) {
- return mPrevDevice;
- }
-
- mPrevParentDevice = device;
-
- // Pick a different device
- Collection<Device> devices = mConfigChooser.getDevices();
-
- // Divide up the available devices into {@link #mVariationCount} + 1 buckets
- // (the + 1 is for the bucket now taken up by the inherited value).
- // Then assign buckets to each {@link #mVariation} version, and pick one
- // from the bucket assigned to this current configuration's variation version.
-
- // I could just divide up the device list count, but that would treat a lot of
- // very similar phones as having the same kind of variety as the 7" and 10"
- // tablets which are sitting right next to each other in the device list.
- // Instead, do this by screen size.
-
-
- double smallest = 100;
- double biggest = 1;
- for (Device d : devices) {
- double size = getScreenSize(d);
- if (size < 0) {
- continue; // no data
- }
- if (size >= biggest) {
- biggest = size;
- }
- if (size <= smallest) {
- smallest = size;
- }
- }
-
- int bucketCount = mVariationCount + 1;
- double inchesPerBucket = (biggest - smallest) / bucketCount;
-
- double overriddenSize = getScreenSize(device);
- int overriddenBucket = (int) ((overriddenSize - smallest) / inchesPerBucket);
- int bucket = (mVariation < overriddenBucket) ? mVariation : mVariation + 1;
- double from = inchesPerBucket * bucket + smallest;
- double to = from + inchesPerBucket;
- if (biggest - to < 0.1) {
- to = biggest + 0.1;
- }
-
- boolean canScaleNinePatch = supports(Capability.FIXED_SCALABLE_NINE_PATCH);
- for (Device d : devices) {
- double size = getScreenSize(d);
- if (size >= from && size < to) {
- if (!canScaleNinePatch) {
- Density density = getDensity(d);
- if (density == Density.TV || density == Density.LOW) {
- continue;
- }
- }
-
- device = d;
- break;
- }
- }
-
- mPrevDevice = device;
- }
-
- return device;
- }
-
- /**
- * Returns the density of the given device
- *
- * @param device the device to check
- * @return the density or null
- */
- @Nullable
- private static Density getDensity(@NonNull Device device) {
- Hardware hardware = device.getDefaultHardware();
- if (hardware != null) {
- Screen screen = hardware.getScreen();
- if (screen != null) {
- return screen.getPixelDensity();
- }
- }
-
- return null;
- }
-
- /**
- * Returns the diagonal length of the given device
- *
- * @param device the device to check
- * @return the diagonal length or -1
- */
- private static double getScreenSize(@NonNull Device device) {
- Hardware hardware = device.getDefaultHardware();
- if (hardware != null) {
- Screen screen = hardware.getScreen();
- if (screen != null) {
- return screen.getDiagonalLength();
- }
- }
-
- return -1;
- }
-
- @Override
- @Nullable
- public State getDeviceState() {
- if (isOverridingDeviceState()) {
- return super.getDeviceState();
- }
- State state = mParent.getDeviceState();
- if (isAlternatingDeviceState() && state != null) {
- State alternate = getNextDeviceState(state);
-
- return alternate;
- } else {
- if ((isAlternatingDevice() || isOverridingDevice()) && state != null) {
- // If the device differs, I need to look up a suitable equivalent state
- // on our device
- Device device = getDevice();
- if (device != null) {
- return device.getState(state.getName());
- }
- }
-
- return state;
- }
- }
-
- @Override
- @NonNull
- public NightMode getNightMode() {
- if (isOverridingNightMode()) {
- return super.getNightMode();
- }
- NightMode nightMode = mParent.getNightMode();
- if (isAlternatingNightMode() && nightMode != null) {
- nightMode = nightMode == NightMode.NIGHT ? NightMode.NOTNIGHT : NightMode.NIGHT;
- return nightMode;
- } else {
- return nightMode;
- }
- }
-
- @Override
- @NonNull
- public UiMode getUiMode() {
- if (isOverridingUiMode()) {
- return super.getUiMode();
- }
- UiMode uiMode = mParent.getUiMode();
- if (isAlternatingUiMode() && uiMode != null) {
- // TODO: Use manifest's supports screen to decide which are most relevant
- // (as well as which available configuration qualifiers are present in the
- // layout)
- UiMode[] values = UiMode.values();
- uiMode = values[(uiMode.ordinal() + 1) % values.length];
- return uiMode;
- } else {
- return uiMode;
- }
- }
-
- @Override
- @Nullable
- public String computeDisplayName() {
- return computeDisplayName(getOverrideFlags() | mAlternate, this);
- }
-
- /**
- * Sets whether the locale should be alternated by this configuration
- *
- * @param alternate if true, alternate the inherited value
- */
- public void setAlternateLocale(boolean alternate) {
- mAlternate |= CFG_LOCALE;
- }
-
- /**
- * Returns true if the locale is alternated
- *
- * @return true if the locale is alternated
- */
- public final boolean isAlternatingLocale() {
- return (mAlternate & CFG_LOCALE) != 0;
- }
-
- /**
- * Sets whether the rendering target should be alternated by this configuration
- *
- * @param alternate if true, alternate the inherited value
- */
- public void setAlternateTarget(boolean alternate) {
- mAlternate |= CFG_TARGET;
- }
-
- /**
- * Returns true if the target is alternated
- *
- * @return true if the target is alternated
- */
- public final boolean isAlternatingTarget() {
- return (mAlternate & CFG_TARGET) != 0;
- }
-
- /**
- * Sets whether the device should be alternated by this configuration
- *
- * @param alternate if true, alternate the inherited value
- */
- public void setAlternateDevice(boolean alternate) {
- mAlternate |= CFG_DEVICE;
- }
-
- /**
- * Returns true if the device is alternated
- *
- * @return true if the device is alternated
- */
- public final boolean isAlternatingDevice() {
- return (mAlternate & CFG_DEVICE) != 0;
- }
-
- /**
- * Sets whether the device state should be alternated by this configuration
- *
- * @param alternate if true, alternate the inherited value
- */
- public void setAlternateDeviceState(boolean alternate) {
- mAlternate |= CFG_DEVICE_STATE;
- }
-
- /**
- * Returns true if the device state is alternated
- *
- * @return true if the device state is alternated
- */
- public final boolean isAlternatingDeviceState() {
- return (mAlternate & CFG_DEVICE_STATE) != 0;
- }
-
- /**
- * Sets whether the night mode should be alternated by this configuration
- *
- * @param alternate if true, alternate the inherited value
- */
- public void setAlternateNightMode(boolean alternate) {
- mAlternate |= CFG_NIGHT_MODE;
- }
-
- /**
- * Returns true if the night mode is alternated
- *
- * @return true if the night mode is alternated
- */
- public final boolean isAlternatingNightMode() {
- return (mAlternate & CFG_NIGHT_MODE) != 0;
- }
-
- /**
- * Sets whether the UI mode should be alternated by this configuration
- *
- * @param alternate if true, alternate the inherited value
- */
- public void setAlternateUiMode(boolean alternate) {
- mAlternate |= CFG_UI_MODE;
- }
-
- /**
- * Returns true if the UI mode is alternated
- *
- * @return true if the UI mode is alternated
- */
- public final boolean isAlternatingUiMode() {
- return (mAlternate & CFG_UI_MODE) != 0;
- }
-
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/descriptors/CustomViewDescriptorService.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/descriptors/CustomViewDescriptorService.java
deleted file mode 100644
index 6df6929a7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/descriptors/CustomViewDescriptorService.java
+++ /dev/null
@@ -1,621 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.descriptors;
-
-import static com.android.SdkConstants.ANDROID_NS_NAME_PREFIX;
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.AUTO_URI;
-import static com.android.SdkConstants.CLASS_VIEWGROUP;
-import static com.android.SdkConstants.URI_PREFIX;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.resources.ResourceFile;
-import com.android.ide.common.resources.ResourceItem;
-import com.android.ide.common.resources.platform.AttributeInfo;
-import com.android.ide.common.resources.platform.AttrsXmlParser;
-import com.android.ide.common.resources.platform.ViewClassInfo;
-import com.android.ide.common.resources.platform.ViewClassInfo.LayoutParamsInfo;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.ide.eclipse.adt.internal.resources.manager.ProjectResources;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.resources.ResourceType;
-import com.android.sdklib.IAndroidTarget;
-import com.google.common.collect.Maps;
-import com.google.common.collect.ObjectArrays;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jdt.core.IClassFile;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.core.ITypeHierarchy;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.swt.graphics.Image;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Service responsible for creating/managing {@link ViewElementDescriptor} objects for custom
- * View classes per project.
- * <p/>
- * The service provides an on-demand monitoring of custom classes to check for changes. Monitoring
- * starts once a request for an {@link ViewElementDescriptor} object has been done for a specific
- * class.
- * <p/>
- * The monitoring will notify a listener of any changes in the class triggering a change in its
- * associated {@link ViewElementDescriptor} object.
- * <p/>
- * If the custom class does not exist, no monitoring is put in place to avoid having to listen
- * to all class changes in the projects.
- */
-public final class CustomViewDescriptorService {
-
- private static CustomViewDescriptorService sThis = new CustomViewDescriptorService();
-
- /**
- * Map where keys are the project, and values are another map containing all the known
- * custom View class for this project. The custom View class are stored in a map
- * where the keys are the fully qualified class name, and the values are their associated
- * {@link ViewElementDescriptor}.
- */
- private HashMap<IProject, HashMap<String, ViewElementDescriptor>> mCustomDescriptorMap =
- new HashMap<IProject, HashMap<String, ViewElementDescriptor>>();
-
- /**
- * TODO will be used to update the ViewElementDescriptor of the custom view when it
- * is modified (either the class itself or its attributes.xml)
- */
- @SuppressWarnings("unused")
- private ICustomViewDescriptorListener mListener;
-
- /**
- * Classes which implements this interface provide a method that deal with modifications
- * in custom View class triggering a change in its associated {@link ViewClassInfo} object.
- */
- public interface ICustomViewDescriptorListener {
- /**
- * Sent when a custom View class has changed and
- * its {@link ViewElementDescriptor} was modified.
- *
- * @param project the project containing the class.
- * @param className the fully qualified class name.
- * @param descriptor the updated ElementDescriptor.
- */
- public void updatedClassInfo(IProject project,
- String className,
- ViewElementDescriptor descriptor);
- }
-
- /**
- * Returns the singleton instance of {@link CustomViewDescriptorService}.
- */
- public static CustomViewDescriptorService getInstance() {
- return sThis;
- }
-
- /**
- * Sets the listener receiving custom View class modification notifications.
- * @param listener the listener to receive the notifications.
- *
- * TODO will be used to update the ViewElementDescriptor of the custom view when it
- * is modified (either the class itself or its attributes.xml)
- */
- public void setListener(ICustomViewDescriptorListener listener) {
- mListener = listener;
- }
-
- /**
- * Returns the {@link ViewElementDescriptor} for a particular project/class when the
- * fully qualified class name actually matches a class from the given project.
- * <p/>
- * Custom descriptors are created as needed.
- * <p/>
- * If it is the first time the {@link ViewElementDescriptor} is requested, the method
- * will check that the specified class is in fact a custom View class. Once this is
- * established, a monitoring for that particular class is initiated. Any change will
- * trigger a notification to the {@link ICustomViewDescriptorListener}.
- *
- * @param project the project containing the class.
- * @param fqcn the fully qualified name of the class.
- * @return a {@link ViewElementDescriptor} or <code>null</code> if the class was not
- * a custom View class.
- */
- public ViewElementDescriptor getDescriptor(IProject project, String fqcn) {
- // look in the map first
- synchronized (mCustomDescriptorMap) {
- HashMap<String, ViewElementDescriptor> map = mCustomDescriptorMap.get(project);
-
- if (map != null) {
- ViewElementDescriptor descriptor = map.get(fqcn);
- if (descriptor != null) {
- return descriptor;
- }
- }
-
- // if we step here, it looks like we haven't created it yet.
- // First lets check this is in fact a valid type in the project
-
- try {
- // We expect the project to be both opened and of java type (since it's an android
- // project), so we can create a IJavaProject object from our IProject.
- IJavaProject javaProject = JavaCore.create(project);
-
- // replace $ by . in the class name
- String javaClassName = fqcn.replaceAll("\\$", "\\."); //$NON-NLS-1$ //$NON-NLS-2$
-
- // look for the IType object for this class
- IType type = javaProject.findType(javaClassName);
- if (type != null && type.exists()) {
- // the type exists. Let's get the parent class and its ViewClassInfo.
-
- // get the type hierarchy
- ITypeHierarchy hierarchy = type.newSupertypeHierarchy(
- new NullProgressMonitor());
-
- ViewElementDescriptor parentDescriptor = createViewDescriptor(
- hierarchy.getSuperclass(type), project, hierarchy);
-
- if (parentDescriptor != null) {
- // we have a valid parent, lets create a new ViewElementDescriptor.
- List<AttributeDescriptor> attrList = new ArrayList<AttributeDescriptor>();
- List<AttributeDescriptor> paramList = new ArrayList<AttributeDescriptor>();
- Map<ResourceFile, Long> files = findCustomDescriptors(project, type,
- attrList, paramList);
-
- AttributeDescriptor[] attributes =
- getAttributeDescriptor(type, parentDescriptor);
- if (!attrList.isEmpty()) {
- attributes = join(attrList, attributes);
- }
- AttributeDescriptor[] layoutAttributes =
- getLayoutAttributeDescriptors(type, parentDescriptor);
- if (!paramList.isEmpty()) {
- layoutAttributes = join(paramList, layoutAttributes);
- }
- String name = DescriptorsUtils.getBasename(fqcn);
- ViewElementDescriptor descriptor = new CustomViewDescriptor(name, fqcn,
- attributes,
- layoutAttributes,
- parentDescriptor.getChildren(),
- project, files);
- descriptor.setSuperClass(parentDescriptor);
-
- synchronized (mCustomDescriptorMap) {
- map = mCustomDescriptorMap.get(project);
- if (map == null) {
- map = new HashMap<String, ViewElementDescriptor>();
- mCustomDescriptorMap.put(project, map);
- }
-
- map.put(fqcn, descriptor);
- }
-
- //TODO setup listener on this resource change.
-
- return descriptor;
- }
- }
- } catch (JavaModelException e) {
- // there was an error accessing any of the IType, we'll just return null;
- }
- }
-
- return null;
- }
-
- private static AttributeDescriptor[] join(
- @NonNull List<AttributeDescriptor> attributeList,
- @NonNull AttributeDescriptor[] attributes) {
- if (!attributeList.isEmpty()) {
- return ObjectArrays.concat(
- attributeList.toArray(new AttributeDescriptor[attributeList.size()]),
- attributes,
- AttributeDescriptor.class);
- } else {
- return attributes;
- }
-
- }
-
- /** Cache used by {@link #getParser(ResourceFile)} */
- private Map<ResourceFile, AttrsXmlParser> mParserCache;
-
- private AttrsXmlParser getParser(ResourceFile file) {
- if (mParserCache == null) {
- mParserCache = new HashMap<ResourceFile, AttrsXmlParser>();
- }
-
- AttrsXmlParser parser = mParserCache.get(file);
- if (parser == null) {
- parser = new AttrsXmlParser(
- file.getFile().getOsLocation(),
- AdtPlugin.getDefault(), 20);
- parser.preload();
- mParserCache.put(file, parser);
- }
-
- return parser;
- }
-
- /** Compute/find the styleable resources for the given type, if possible */
- private Map<ResourceFile, Long> findCustomDescriptors(
- IProject project,
- IType type,
- List<AttributeDescriptor> customAttributes,
- List<AttributeDescriptor> customLayoutAttributes) {
- // Look up the project where the type is declared (could be a library project;
- // we cannot use type.getJavaProject().getProject())
- IProject library = getProjectDeclaringType(type);
- if (library == null) {
- library = project;
- }
-
- String className = type.getElementName();
- Set<ResourceFile> resourceFiles = findAttrsFiles(library, className);
- if (resourceFiles != null && resourceFiles.size() > 0) {
- String appUri = getAppResUri(project);
- Map<ResourceFile, Long> timestamps =
- Maps.newHashMapWithExpectedSize(resourceFiles.size());
- for (ResourceFile file : resourceFiles) {
- AttrsXmlParser attrsXmlParser = getParser(file);
- String fqcn = type.getFullyQualifiedName();
-
- // Attributes
- ViewClassInfo classInfo = new ViewClassInfo(true, fqcn, className);
- attrsXmlParser.loadViewAttributes(classInfo);
- appendAttributes(customAttributes, classInfo.getAttributes(), appUri);
-
- // Layout params
- LayoutParamsInfo layoutInfo = new ViewClassInfo.LayoutParamsInfo(
- classInfo, "Layout", null /*superClassInfo*/); //$NON-NLS-1$
- attrsXmlParser.loadLayoutParamsAttributes(layoutInfo);
- appendAttributes(customLayoutAttributes, layoutInfo.getAttributes(), appUri);
-
- timestamps.put(file, file.getFile().getModificationStamp());
- }
-
- return timestamps;
- }
-
- return null;
- }
-
- /**
- * Finds the set of XML files (if any) in the given library declaring
- * attributes for the given class name
- */
- @Nullable
- private static Set<ResourceFile> findAttrsFiles(IProject library, String className) {
- Set<ResourceFile> resourceFiles = null;
- ResourceManager manager = ResourceManager.getInstance();
- ProjectResources resources = manager.getProjectResources(library);
- if (resources != null) {
- Collection<ResourceItem> items =
- resources.getResourceItemsOfType(ResourceType.DECLARE_STYLEABLE);
- for (ResourceItem item : items) {
- String viewName = item.getName();
- if (viewName.equals(className)
- || (viewName.startsWith(className)
- && viewName.equals(className + "_Layout"))) { //$NON-NLS-1$
- if (resourceFiles == null) {
- resourceFiles = new HashSet<ResourceFile>();
- }
- resourceFiles.addAll(item.getSourceFileList());
- }
- }
- }
- return resourceFiles;
- }
-
- /**
- * Find the project containing this type declaration. We cannot use
- * {@link IType#getJavaProject()} since that will return the including
- * project and we're after the library project such that we can find the
- * attrs.xml file in the same project.
- */
- @Nullable
- private static IProject getProjectDeclaringType(IType type) {
- IClassFile classFile = type.getClassFile();
- if (classFile != null) {
- IPath path = classFile.getPath();
- IWorkspaceRoot workspace = ResourcesPlugin.getWorkspace().getRoot();
- IResource resource;
- if (path.isAbsolute()) {
- resource = AdtUtils.fileToResource(path.toFile());
- } else {
- resource = workspace.findMember(path);
- }
- if (resource != null && resource.getProject() != null) {
- return resource.getProject();
- }
- }
-
- return null;
- }
-
- /** Returns the name space to use for application attributes */
- private static String getAppResUri(IProject project) {
- String appResource;
- ProjectState projectState = Sdk.getProjectState(project);
- if (projectState != null && projectState.isLibrary()) {
- appResource = AUTO_URI;
- } else {
- ManifestInfo manifestInfo = ManifestInfo.get(project);
- appResource = URI_PREFIX + manifestInfo.getPackage();
- }
- return appResource;
- }
-
-
- /** Append the {@link AttributeInfo} objects converted {@link AttributeDescriptor}
- * objects into the given attribute list.
- * <p>
- * This is nearly identical to
- * {@link DescriptorsUtils#appendAttribute(List, String, String, AttributeInfo, boolean, Map)}
- * but it handles namespace declarations in the attrs.xml file where the android:
- * namespace is included in the names.
- */
- private static void appendAttributes(List<AttributeDescriptor> attributes,
- AttributeInfo[] attributeInfos, String appResource) {
- // Custom attributes
- for (AttributeInfo info : attributeInfos) {
- String nsUri;
- if (info.getName().startsWith(ANDROID_NS_NAME_PREFIX)) {
- info.setName(info.getName().substring(ANDROID_NS_NAME_PREFIX.length()));
- nsUri = ANDROID_URI;
- } else {
- nsUri = appResource;
- }
-
- DescriptorsUtils.appendAttribute(attributes,
- null /*elementXmlName*/, nsUri, info, false /*required*/,
- null /*overrides*/);
- }
- }
-
- /**
- * Computes (if needed) and returns the {@link ViewElementDescriptor} for the specified type.
- *
- * @return A {@link ViewElementDescriptor} or null if type or typeHierarchy is null.
- */
- private ViewElementDescriptor createViewDescriptor(IType type, IProject project,
- ITypeHierarchy typeHierarchy) {
- // check if the type is a built-in View class.
- List<ViewElementDescriptor> builtInList = null;
-
- // give up if there's no type
- if (type == null) {
- return null;
- }
-
- String fqcn = type.getFullyQualifiedName();
-
- Sdk currentSdk = Sdk.getCurrent();
- if (currentSdk != null) {
- IAndroidTarget target = currentSdk.getTarget(project);
- if (target != null) {
- AndroidTargetData data = currentSdk.getTargetData(target);
- if (data != null) {
- LayoutDescriptors descriptors = data.getLayoutDescriptors();
- ViewElementDescriptor d = descriptors.findDescriptorByClass(fqcn);
- if (d != null) {
- return d;
- }
- builtInList = descriptors.getViewDescriptors();
- }
- }
- }
-
- // it's not a built-in class? Lets look if the superclass is built-in
- // give up if there's no type
- if (typeHierarchy == null) {
- return null;
- }
-
- IType parentType = typeHierarchy.getSuperclass(type);
- if (parentType != null) {
- ViewElementDescriptor parentDescriptor = createViewDescriptor(parentType, project,
- typeHierarchy);
-
- if (parentDescriptor != null) {
- // parent class is a valid View class with a descriptor, so we create one
- // for this class.
- String name = DescriptorsUtils.getBasename(fqcn);
- // A custom view accepts children if its parent descriptor also does.
- // The only exception to this is ViewGroup, which accepts children even though
- // its parent does not.
- boolean isViewGroup = fqcn.equals(CLASS_VIEWGROUP);
- boolean hasChildren = isViewGroup || parentDescriptor.hasChildren();
- ViewElementDescriptor[] children = null;
- if (hasChildren && builtInList != null) {
- // We can't figure out what the allowable children are by just
- // looking at the class, so assume any View is valid
- children = builtInList.toArray(new ViewElementDescriptor[builtInList.size()]);
- }
- ViewElementDescriptor descriptor = new CustomViewDescriptor(name, fqcn,
- getAttributeDescriptor(type, parentDescriptor),
- getLayoutAttributeDescriptors(type, parentDescriptor),
- children, project, null);
- descriptor.setSuperClass(parentDescriptor);
-
- // add it to the map
- synchronized (mCustomDescriptorMap) {
- HashMap<String, ViewElementDescriptor> map = mCustomDescriptorMap.get(project);
-
- if (map == null) {
- map = new HashMap<String, ViewElementDescriptor>();
- mCustomDescriptorMap.put(project, map);
- }
-
- map.put(fqcn, descriptor);
-
- }
-
- //TODO setup listener on this resource change.
-
- return descriptor;
- }
- }
-
- // class is neither a built-in view class, nor extend one. return null.
- return null;
- }
-
- /**
- * Returns the array of {@link AttributeDescriptor} for the specified {@link IType}.
- * <p/>
- * The array should contain the descriptor for this type and all its supertypes.
- *
- * @param type the type for which the {@link AttributeDescriptor} are returned.
- * @param parentDescriptor the {@link ViewElementDescriptor} of the direct superclass.
- */
- private static AttributeDescriptor[] getAttributeDescriptor(IType type,
- ViewElementDescriptor parentDescriptor) {
- // TODO add the class attribute descriptors to the parent descriptors.
- return parentDescriptor.getAttributes();
- }
-
- private static AttributeDescriptor[] getLayoutAttributeDescriptors(IType type,
- ViewElementDescriptor parentDescriptor) {
- return parentDescriptor.getLayoutAttributes();
- }
-
- private class CustomViewDescriptor extends ViewElementDescriptor {
- private Map<ResourceFile, Long> mTimeStamps;
- private IProject mProject;
-
- public CustomViewDescriptor(String name, String fqcn, AttributeDescriptor[] attributes,
- AttributeDescriptor[] layoutAttributes,
- ElementDescriptor[] children, IProject project,
- Map<ResourceFile, Long> timestamps) {
- super(
- fqcn, // xml name
- name, // ui name
- fqcn, // full class name
- fqcn, // tooltip
- null, // sdk_url
- attributes,
- layoutAttributes,
- children,
- false // mandatory
- );
- mTimeStamps = timestamps;
- mProject = project;
- }
-
- @Override
- public Image getGenericIcon() {
- IconFactory iconFactory = IconFactory.getInstance();
-
- int index = mXmlName.lastIndexOf('.');
- if (index != -1) {
- return iconFactory.getIcon(mXmlName.substring(index + 1),
- "customView"); //$NON-NLS-1$
- }
-
- return iconFactory.getIcon("customView"); //$NON-NLS-1$
- }
-
- @Override
- public boolean syncAttributes() {
- // Check if any of the descriptors
- if (mTimeStamps != null) {
- // Prevent checking actual file timestamps too frequently on rapid burst calls
- long now = System.currentTimeMillis();
- if (now - sLastCheck < 1000) {
- return true;
- }
- sLastCheck = now;
-
- // Check whether the resource files (typically just one) which defined
- // custom attributes for this custom view have changed, and if so,
- // refresh the attribute descriptors.
- // This doesn't work the cases where you add descriptors for a custom
- // view after using it, or add attributes in a separate file, but those
- // scenarios aren't quite as common (and would require a bit more expensive
- // analysis.)
- for (Map.Entry<ResourceFile, Long> entry : mTimeStamps.entrySet()) {
- ResourceFile file = entry.getKey();
- Long timestamp = entry.getValue();
- boolean recompute = false;
- if (file.getFile().getModificationStamp() > timestamp.longValue()) {
- // One or more attributes changed: recompute
- recompute = true;
- mParserCache.remove(file);
- }
-
- if (recompute) {
- IJavaProject javaProject = JavaCore.create(mProject);
- String fqcn = getFullClassName();
- IType type = null;
- try {
- type = javaProject.findType(fqcn);
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- if (type == null || !type.exists()) {
- return true;
- }
-
- List<AttributeDescriptor> attrList = new ArrayList<AttributeDescriptor>();
- List<AttributeDescriptor> paramList = new ArrayList<AttributeDescriptor>();
-
- mTimeStamps = findCustomDescriptors(mProject, type, attrList, paramList);
-
- ViewElementDescriptor parentDescriptor = getSuperClassDesc();
- AttributeDescriptor[] attributes =
- getAttributeDescriptor(type, parentDescriptor);
- if (!attrList.isEmpty()) {
- attributes = join(attrList, attributes);
- }
- attributes = attrList.toArray(new AttributeDescriptor[attrList.size()]);
- setAttributes(attributes);
-
- return false;
- }
- }
- }
-
- return true;
- }
- }
-
- /** Timestamp of the most recent {@link CustomViewDescriptor#syncAttributes} check */
- private static long sLastCheck;
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/descriptors/LayoutDescriptors.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/descriptors/LayoutDescriptors.java
deleted file mode 100644
index 7b2fe84f0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/descriptors/LayoutDescriptors.java
+++ /dev/null
@@ -1,597 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.descriptors;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_CLASS;
-import static com.android.SdkConstants.ATTR_LAYOUT;
-import static com.android.SdkConstants.ATTR_NAME;
-import static com.android.SdkConstants.ATTR_TAG;
-import static com.android.SdkConstants.CLASS_VIEW;
-import static com.android.SdkConstants.FQCN_GESTURE_OVERLAY_VIEW;
-import static com.android.SdkConstants.REQUEST_FOCUS;
-import static com.android.SdkConstants.VIEW_FRAGMENT;
-import static com.android.SdkConstants.VIEW_INCLUDE;
-import static com.android.SdkConstants.VIEW_MERGE;
-import static com.android.SdkConstants.VIEW_TAG;
-
-import com.android.SdkConstants;
-import com.android.ide.common.api.IAttributeInfo.Format;
-import com.android.ide.common.resources.platform.AttributeInfo;
-import com.android.ide.common.resources.platform.DeclareStyleableInfo;
-import com.android.ide.common.resources.platform.ViewClassInfo;
-import com.android.ide.common.resources.platform.ViewClassInfo.LayoutParamsInfo;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DocumentDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.IDescriptorProvider;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.TextAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.manifest.descriptors.ClassAttributeDescriptor;
-import com.android.sdklib.IAndroidTarget;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-
-/**
- * Complete description of the layout structure.
- */
-public final class LayoutDescriptors implements IDescriptorProvider {
- /** The document descriptor. Contains all layouts and views linked together. */
- private DocumentDescriptor mRootDescriptor =
- new DocumentDescriptor("layout_doc", null); //$NON-NLS-1$
-
- /** The list of all known ViewLayout descriptors. */
- private List<ViewElementDescriptor> mLayoutDescriptors = Collections.emptyList();
-
- /** Read-Only list of View Descriptors. */
- private List<ViewElementDescriptor> mROLayoutDescriptors;
-
- /** The list of all known View (not ViewLayout) descriptors. */
- private List<ViewElementDescriptor> mViewDescriptors = Collections.emptyList();
-
- /** Read-Only list of View Descriptors. */
- private List<ViewElementDescriptor> mROViewDescriptors;
-
- /** The descriptor matching android.view.View. */
- private ViewElementDescriptor mBaseViewDescriptor;
-
- /** Map from view full class name to view descriptor */
- private Map<String, ViewElementDescriptor> mFqcnToDescriptor =
- // As of 3.1 there are 58 items in this map
- new HashMap<String, ViewElementDescriptor>(80);
-
- /** Returns the document descriptor. Contains all layouts and views linked together. */
- @Override
- public DocumentDescriptor getDescriptor() {
- return mRootDescriptor;
- }
-
- /** Returns the read-only list of all known ViewLayout descriptors. */
- public List<ViewElementDescriptor> getLayoutDescriptors() {
- return mROLayoutDescriptors;
- }
-
- /** Returns the read-only list of all known View (not ViewLayout) descriptors. */
- public List<ViewElementDescriptor> getViewDescriptors() {
- return mROViewDescriptors;
- }
-
- @Override
- public ElementDescriptor[] getRootElementDescriptors() {
- return mRootDescriptor.getChildren();
- }
-
- /**
- * Returns the descriptor matching android.view.View, which is guaranteed
- * to be a {@link ViewElementDescriptor}.
- */
- public ViewElementDescriptor getBaseViewDescriptor() {
- if (mBaseViewDescriptor == null) {
- mBaseViewDescriptor = findDescriptorByClass(SdkConstants.CLASS_VIEW);
- }
- return mBaseViewDescriptor;
- }
-
- /**
- * Updates the document descriptor.
- * <p/>
- * It first computes the new children of the descriptor and then update them
- * all at once.
- * <p/>
- * TODO: differentiate groups from views in the tree UI? => rely on icons
- * <p/>
- *
- * @param views The list of views in the framework.
- * @param layouts The list of layouts in the framework.
- * @param styleMap A map from style names to style information provided by the SDK
- * @param target The android target being initialized
- */
- public synchronized void updateDescriptors(ViewClassInfo[] views, ViewClassInfo[] layouts,
- Map<String, DeclareStyleableInfo> styleMap, IAndroidTarget target) {
-
- // This map links every ViewClassInfo to the ElementDescriptor we created.
- // It is filled by convertView() and used later to fix the super-class hierarchy.
- HashMap<ViewClassInfo, ViewElementDescriptor> infoDescMap =
- new HashMap<ViewClassInfo, ViewElementDescriptor>();
-
- ArrayList<ViewElementDescriptor> newViews = new ArrayList<ViewElementDescriptor>(40);
- if (views != null) {
- for (ViewClassInfo info : views) {
- ViewElementDescriptor desc = convertView(info, infoDescMap);
- newViews.add(desc);
- mFqcnToDescriptor.put(desc.getFullClassName(), desc);
- }
- }
-
- // Create <include> as a synthetic regular view.
- // Note: ViewStub is already described by attrs.xml
- insertInclude(newViews);
-
- List<ViewElementDescriptor> newLayouts = new ArrayList<ViewElementDescriptor>(30);
- if (layouts != null) {
- for (ViewClassInfo info : layouts) {
- ViewElementDescriptor desc = convertView(info, infoDescMap);
- newLayouts.add(desc);
- mFqcnToDescriptor.put(desc.getFullClassName(), desc);
- }
- }
-
- // Find View and inherit all its layout attributes
- AttributeDescriptor[] frameLayoutAttrs = findViewLayoutAttributes(
- SdkConstants.CLASS_FRAMELAYOUT);
-
- if (target.getVersion().getApiLevel() >= 4) {
- ViewElementDescriptor fragmentTag = createFragment(frameLayoutAttrs, styleMap);
- newViews.add(fragmentTag);
- }
-
- List<ElementDescriptor> newDescriptors = new ArrayList<ElementDescriptor>(80);
- newDescriptors.addAll(newLayouts);
- newDescriptors.addAll(newViews);
-
- ViewElementDescriptor viewTag = createViewTag(frameLayoutAttrs);
- newViews.add(viewTag);
- newDescriptors.add(viewTag);
-
- ViewElementDescriptor requestFocus = createRequestFocus();
- newViews.add(requestFocus);
- newDescriptors.add(requestFocus);
-
- // Link all layouts to everything else here.. recursively
- for (ViewElementDescriptor layoutDesc : newLayouts) {
- layoutDesc.setChildren(newDescriptors);
- }
-
- // The gesture overlay descriptor is really a layout but not included in the layouts list
- // so handle it specially
- ViewElementDescriptor gestureView = findDescriptorByClass(FQCN_GESTURE_OVERLAY_VIEW);
- if (gestureView != null) {
- gestureView.setChildren(newDescriptors);
- // Inherit layout attributes from FrameLayout
- gestureView.setLayoutAttributes(frameLayoutAttrs);
- }
-
- fixSuperClasses(infoDescMap);
-
- // The <merge> tag can only be a root tag, so it is added at the end.
- // It gets everything else as children but it is not made a child itself.
- ViewElementDescriptor mergeTag = createMerge(frameLayoutAttrs);
- mergeTag.setChildren(newDescriptors); // mergeTag makes a copy of the list
- newDescriptors.add(mergeTag);
- newLayouts.add(mergeTag);
-
- // Sort palette contents
- Collections.sort(newViews);
- Collections.sort(newLayouts);
-
- mViewDescriptors = newViews;
- mLayoutDescriptors = newLayouts;
- mRootDescriptor.setChildren(newDescriptors);
-
- mBaseViewDescriptor = null;
- mROLayoutDescriptors = Collections.unmodifiableList(mLayoutDescriptors);
- mROViewDescriptors = Collections.unmodifiableList(mViewDescriptors);
- }
-
- /**
- * Creates an element descriptor from a given {@link ViewClassInfo}.
- *
- * @param info The {@link ViewClassInfo} to convert into a new {@link ViewElementDescriptor}.
- * @param infoDescMap This map links every ViewClassInfo to the ElementDescriptor it created.
- * It is filled by here and used later to fix the super-class hierarchy.
- */
- private ViewElementDescriptor convertView(
- ViewClassInfo info,
- HashMap<ViewClassInfo, ViewElementDescriptor> infoDescMap) {
- String xmlName = info.getShortClassName();
- String uiName = xmlName;
- String fqcn = info.getFullClassName();
- if (ViewElementDescriptor.viewNeedsPackage(fqcn)) {
- xmlName = fqcn;
- }
- String tooltip = info.getJavaDoc();
-
- // Average is around 90, max (in 3.2) is 145
- ArrayList<AttributeDescriptor> attributes = new ArrayList<AttributeDescriptor>(120);
-
- // All views and groups have an implicit "style" attribute which is a reference.
- AttributeInfo styleInfo = new AttributeInfo(
- "style", //$NON-NLS-1$ xmlLocalName
- Format.REFERENCE_SET);
- styleInfo.setJavaDoc("A reference to a custom style"); //tooltip
- DescriptorsUtils.appendAttribute(attributes,
- "style", //$NON-NLS-1$
- null, //nsUri
- styleInfo,
- false, //required
- null); // overrides
- styleInfo.setDefinedBy(SdkConstants.CLASS_VIEW);
-
- // Process all View attributes
- DescriptorsUtils.appendAttributes(attributes,
- null, // elementName
- ANDROID_URI,
- info.getAttributes(),
- null, // requiredAttributes
- null /* overrides */);
-
- List<String> attributeSources = new ArrayList<String>();
- if (info.getAttributes() != null && info.getAttributes().length > 0) {
- attributeSources.add(fqcn);
- }
-
- for (ViewClassInfo link = info.getSuperClass();
- link != null;
- link = link.getSuperClass()) {
- AttributeInfo[] attrList = link.getAttributes();
- if (attrList.length > 0) {
- attributeSources.add(link.getFullClassName());
- DescriptorsUtils.appendAttributes(attributes,
- null, // elementName
- ANDROID_URI,
- attrList,
- null, // requiredAttributes
- null /* overrides */);
- }
- }
-
- // Process all LayoutParams attributes
- ArrayList<AttributeDescriptor> layoutAttributes = new ArrayList<AttributeDescriptor>();
- LayoutParamsInfo layoutParams = info.getLayoutData();
-
- for(; layoutParams != null; layoutParams = layoutParams.getSuperClass()) {
- for (AttributeInfo attrInfo : layoutParams.getAttributes()) {
- if (DescriptorsUtils.containsAttribute(layoutAttributes,
- ANDROID_URI, attrInfo)) {
- continue;
- }
- DescriptorsUtils.appendAttribute(layoutAttributes,
- null, // elementName
- ANDROID_URI,
- attrInfo,
- false, // required
- null /* overrides */);
- }
- }
-
- ViewElementDescriptor desc = new ViewElementDescriptor(
- xmlName,
- uiName,
- fqcn,
- tooltip,
- null, // sdk_url
- attributes.toArray(new AttributeDescriptor[attributes.size()]),
- layoutAttributes.toArray(new AttributeDescriptor[layoutAttributes.size()]),
- null, // children
- false /* mandatory */);
- desc.setAttributeSources(Collections.unmodifiableList(attributeSources));
- infoDescMap.put(info, desc);
- return desc;
- }
-
- /**
- * Creates a new {@code <include>} descriptor and adds it to the list of view descriptors.
- *
- * @param knownViews A list of view descriptors being populated. Also used to find the
- * View descriptor and extract its layout attributes.
- */
- private void insertInclude(List<ViewElementDescriptor> knownViews) {
- String xmlName = VIEW_INCLUDE;
-
- // Create the include custom attributes
- ArrayList<AttributeDescriptor> attributes = new ArrayList<AttributeDescriptor>();
-
- // Find View and inherit all its layout attributes
- AttributeDescriptor[] viewLayoutAttribs;
- AttributeDescriptor[] viewAttributes = null;
- ViewElementDescriptor viewDesc = findDescriptorByClass(SdkConstants.CLASS_VIEW);
- if (viewDesc != null) {
- viewAttributes = viewDesc.getAttributes();
- attributes = new ArrayList<AttributeDescriptor>(viewAttributes.length + 1);
- viewLayoutAttribs = viewDesc.getLayoutAttributes();
- } else {
- viewLayoutAttribs = new AttributeDescriptor[0];
- }
-
- // Note that the "layout" attribute does NOT have the Android namespace
- DescriptorsUtils.appendAttribute(attributes,
- null, //elementXmlName
- null, //nsUri
- new AttributeInfo(
- ATTR_LAYOUT,
- Format.REFERENCE_SET ),
- true, //required
- null); //overrides
-
- if (viewAttributes != null) {
- for (AttributeDescriptor descriptor : viewAttributes) {
- attributes.add(descriptor);
- }
- }
-
- // Create the include descriptor
- ViewElementDescriptor desc = new ViewElementDescriptor(xmlName,
- xmlName, // ui_name
- VIEW_INCLUDE, // "class name"; the GLE only treats this as an element tag
- "Lets you statically include XML layouts inside other XML layouts.", // tooltip
- null, // sdk_url
- attributes.toArray(new AttributeDescriptor[attributes.size()]),
- viewLayoutAttribs, // layout attributes
- null, // children
- false /* mandatory */);
-
- knownViews.add(desc);
- }
-
- /**
- * Creates and returns a new {@code <merge>} descriptor.
- * @param viewLayoutAttribs The layout attributes to use for the new descriptor
- */
- private ViewElementDescriptor createMerge(AttributeDescriptor[] viewLayoutAttribs) {
- String xmlName = VIEW_MERGE;
-
- // Create the include descriptor
- ViewElementDescriptor desc = new ViewElementDescriptor(xmlName,
- xmlName, // ui_name
- VIEW_MERGE, // "class name"; the GLE only treats this as an element tag
- "A root tag useful for XML layouts inflated using a ViewStub.", // tooltip
- null, // sdk_url
- null, // attributes
- viewLayoutAttribs, // layout attributes
- null, // children
- false /* mandatory */);
-
- return desc;
- }
-
- /**
- * Creates and returns a new {@code <fragment>} descriptor.
- * @param viewLayoutAttribs The layout attributes to use for the new descriptor
- * @param styleMap The style map provided by the SDK
- */
- private ViewElementDescriptor createFragment(AttributeDescriptor[] viewLayoutAttribs,
- Map<String, DeclareStyleableInfo> styleMap) {
- String xmlName = VIEW_FRAGMENT;
- final ViewElementDescriptor descriptor;
-
- // First try to create the descriptor from metadata in attrs.xml:
- DeclareStyleableInfo style = styleMap.get("Fragment"); //$NON-NLS-1$
- String fragmentTooltip =
- "A Fragment is a piece of an application's user interface or behavior that "
- + "can be placed in an Activity";
- String sdkUrl = "http://developer.android.com/guide/topics/fundamentals/fragments.html";
- TextAttributeDescriptor classAttribute = new ClassAttributeDescriptor(
- // Should accept both CLASS_V4_FRAGMENT and CLASS_FRAGMENT
- null /*superClassName*/,
- ATTR_CLASS, null /* namespace */,
- new AttributeInfo(ATTR_CLASS, Format.STRING_SET),
- true /*mandatory*/)
- .setTooltip("Supply the name of the fragment class to instantiate");
-
- if (style != null) {
- descriptor = new ViewElementDescriptor(
- VIEW_FRAGMENT, VIEW_FRAGMENT, VIEW_FRAGMENT,
- fragmentTooltip, // tooltip
- sdkUrl, //,
- null /* attributes */,
- viewLayoutAttribs, // layout attributes
- null /*childrenElements*/,
- false /*mandatory*/);
- ArrayList<AttributeDescriptor> descs = new ArrayList<AttributeDescriptor>();
- // The class attribute is not included in the attrs.xml
- descs.add(classAttribute);
- DescriptorsUtils.appendAttributes(descs,
- null, // elementName
- ANDROID_URI,
- style.getAttributes(),
- null, // requiredAttributes
- null); // overrides
- //descriptor.setTooltip(style.getJavaDoc());
- descriptor.setAttributes(descs.toArray(new AttributeDescriptor[descs.size()]));
- } else {
- // The above will only work on API 11 and up. However, fragments are *also* available
- // on older platforms, via the fragment support library, so add in a manual
- // entry if necessary.
- descriptor = new ViewElementDescriptor(xmlName,
- xmlName, // ui_name
- xmlName, // "class name"; the GLE only treats this as an element tag
- fragmentTooltip,
- sdkUrl,
- new AttributeDescriptor[] {
- new ClassAttributeDescriptor(
- null /*superClassName*/,
- ATTR_NAME, ANDROID_URI,
- new AttributeInfo(ATTR_NAME, Format.STRING_SET),
- true /*mandatory*/)
- .setTooltip("Supply the name of the fragment class to instantiate"),
- classAttribute,
- new ClassAttributeDescriptor(
- null /*superClassName*/,
- ATTR_TAG, ANDROID_URI,
- new AttributeInfo(ATTR_TAG, Format.STRING_SET),
- true /*mandatory*/)
- .setTooltip("Supply a tag for the top-level view containing a String"),
- }, // attributes
- viewLayoutAttribs, // layout attributes
- null, // children
- false /* mandatory */);
- }
-
- return descriptor;
- }
-
- /**
- * Creates and returns a new {@code <view>} descriptor.
- * @param viewLayoutAttribs The layout attributes to use for the new descriptor
- * @param styleMap The style map provided by the SDK
- */
- private ViewElementDescriptor createViewTag(AttributeDescriptor[] viewLayoutAttribs) {
- String xmlName = VIEW_TAG;
-
- TextAttributeDescriptor classAttribute = new ClassAttributeDescriptor(
- CLASS_VIEW,
- ATTR_CLASS, null /* namespace */,
- new AttributeInfo(ATTR_CLASS, Format.STRING_SET),
- true /*mandatory*/)
- .setTooltip("Supply the name of the view class to instantiate");
-
- // Create the include descriptor
- ViewElementDescriptor desc = new ViewElementDescriptor(xmlName,
- xmlName, // ui_name
- xmlName, // "class name"; the GLE only treats this as an element tag
- "A view tag whose class attribute names the class to be instantiated", // tooltip
- null, // sdk_url
- new AttributeDescriptor[] { // attributes
- classAttribute
- },
- viewLayoutAttribs, // layout attributes
- null, // children
- false /* mandatory */);
-
- return desc;
- }
-
- /**
- * Creates and returns a new {@code <requestFocus>} descriptor.
- */
- private ViewElementDescriptor createRequestFocus() {
- String xmlName = REQUEST_FOCUS;
-
- // Create the include descriptor
- return new ViewElementDescriptor(
- xmlName, // xml_name
- xmlName, // ui_name
- xmlName, // "class name"; the GLE only treats this as an element tag
- "Requests focus for the parent element or one of its descendants", // tooltip
- null, // sdk_url
- null, // attributes
- null, // layout attributes
- null, // children
- false /* mandatory */);
- }
-
- /**
- * Finds the descriptor and retrieves all its layout attributes.
- */
- private AttributeDescriptor[] findViewLayoutAttributes(
- String viewFqcn) {
- ViewElementDescriptor viewDesc = findDescriptorByClass(viewFqcn);
- if (viewDesc != null) {
- return viewDesc.getLayoutAttributes();
- }
-
- return null;
- }
-
- /**
- * Set the super-class of each {@link ViewElementDescriptor} by using the super-class
- * information available in the {@link ViewClassInfo}.
- */
- private void fixSuperClasses(Map<ViewClassInfo, ViewElementDescriptor> infoDescMap) {
-
- for (Entry<ViewClassInfo, ViewElementDescriptor> entry : infoDescMap.entrySet()) {
- ViewClassInfo info = entry.getKey();
- ViewElementDescriptor desc = entry.getValue();
-
- ViewClassInfo sup = info.getSuperClass();
- if (sup != null) {
- ViewElementDescriptor supDesc = infoDescMap.get(sup);
- while (supDesc == null && sup != null) {
- // We don't have a descriptor for the super-class. That means the class is
- // probably abstract, so we just need to walk up the super-class chain till
- // we find one we have. All views derive from android.view.View so we should
- // surely find that eventually.
- sup = sup.getSuperClass();
- if (sup != null) {
- supDesc = infoDescMap.get(sup);
- }
- }
- if (supDesc != null) {
- desc.setSuperClass(supDesc);
- }
- }
- }
- }
-
- /**
- * Returns the {@link ViewElementDescriptor} with the given fully qualified class
- * name, or null if not found. This is a quick map lookup.
- *
- * @param fqcn the fully qualified class name
- * @return the corresponding {@link ViewElementDescriptor} or null
- */
- public ViewElementDescriptor findDescriptorByClass(String fqcn) {
- return mFqcnToDescriptor.get(fqcn);
- }
-
- /**
- * Returns the {@link ViewElementDescriptor} with the given XML tag name,
- * which usually does not include the package (depending on the
- * value of {@link ViewElementDescriptor#viewNeedsPackage(String)}).
- *
- * @param tag the XML tag name
- * @return the corresponding {@link ViewElementDescriptor} or null
- */
- public ViewElementDescriptor findDescriptorByTag(String tag) {
- // TODO: Consider whether we need to add a direct map lookup for this as well.
- // Currently not done since this is not frequently needed (only needed for
- // exploded rendering which was already performing list iteration.)
- for (ViewElementDescriptor descriptor : mLayoutDescriptors) {
- if (tag.equals(descriptor.getXmlLocalName())) {
- return descriptor;
- }
- }
-
- return null;
- }
-
- /**
- * Returns a collection of all the view class names, including layouts
- *
- * @return a collection of all the view class names, never null
- */
- public Collection<String> getAllViewClassNames() {
- return mFqcnToDescriptor.keySet();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/descriptors/ViewElementDescriptor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/descriptors/ViewElementDescriptor.java
deleted file mode 100644
index 79995249c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/descriptors/ViewElementDescriptor.java
+++ /dev/null
@@ -1,249 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.descriptors;
-
-import static com.android.SdkConstants.ANDROID_VIEW_PKG;
-import static com.android.SdkConstants.ANDROID_WEBKIT_PKG;
-import static com.android.SdkConstants.ANDROID_WIDGET_PREFIX;
-import static com.android.SdkConstants.VIEW;
-import static com.android.SdkConstants.VIEW_TAG;
-
-import com.android.ide.common.resources.platform.AttributeInfo;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-import org.eclipse.swt.graphics.Image;
-
-import java.util.Collections;
-import java.util.List;
-
-/**
- * {@link ViewElementDescriptor} describes the properties expected for a given XML element node
- * representing a class in an XML Layout file.
- * <p/>
- * These descriptors describe Android views XML elements.
- * <p/>
- * The base class {@link ElementDescriptor} has a notion of "children", that is an XML element
- * can produce another set of XML elements. Because of the flat nature of Android's layout
- * XML files all possible views are children of the document and of themselves (that is any
- * view group can contain any other view). This is an implied contract of this class that is
- * enforces at construction by {@link LayoutDescriptors}. Note that by construction any code
- * that deals with the children hierarchy must also deal with potential infinite loops since views
- * <em>will</em> reference themselves (e.g. a ViewGroup can contain a ViewGroup).
- * <p/>
- * Since Views are also Java classes, they derive from each other. Here this is represented
- * as the "super class", which denotes the fact that a given View java class derives from
- * another class. These properties are also set at construction by {@link LayoutDescriptors}.
- * The super class hierarchy is very different from the descriptor's children hierarchy: the
- * later represents Java inheritance, the former represents an XML nesting capability.
- *
- * @see ElementDescriptor
- */
-public class ViewElementDescriptor extends ElementDescriptor {
-
- /** The full class name (FQCN) of this view. */
- private final String mFullClassName;
-
- /** The list of layout attributes. Can be empty but not null. */
- private AttributeDescriptor[] mLayoutAttributes;
-
- /** The super-class descriptor. Can be null. */
- private ViewElementDescriptor mSuperClassDesc;
-
- /** List of attribute sources, classes that contribute attributes to {@link #mAttributes} */
- private List<String> mAttributeSources;
-
- /**
- * Constructs a new {@link ViewElementDescriptor} based on its XML name, UI name,
- * the canonical name of the class it represents, its tooltip, its SDK url, its attributes list,
- * its children list and its mandatory flag.
- *
- * @param xml_name The XML element node name. Case sensitive.
- * @param ui_name The XML element name for the user interface, typically capitalized.
- * @param fullClassName The fully qualified class name the {@link ViewElementDescriptor} is
- * representing.
- * @param tooltip An optional tooltip. Can be null or empty.
- * @param sdk_url An optional SKD URL. Can be null or empty.
- * @param attributes The list of allowed attributes. Can be null or empty.
- * @param layoutAttributes The list of layout attributes. Can be null or empty.
- * @param children The list of allowed children. Can be null or empty.
- * @param mandatory Whether this node must always exist (even for empty models). A mandatory
- * UI node is never deleted and it may lack an actual XML node attached. A non-mandatory
- * UI node MUST have an XML node attached and it will cease to exist when the XML node
- * ceases to exist.
- */
- public ViewElementDescriptor(String xml_name, String ui_name,
- String fullClassName,
- String tooltip, String sdk_url,
- AttributeDescriptor[] attributes, AttributeDescriptor[] layoutAttributes,
- ElementDescriptor[] children, boolean mandatory) {
- super(xml_name, ui_name, tooltip, sdk_url, attributes, children, mandatory);
- mFullClassName = fullClassName;
- mLayoutAttributes = layoutAttributes != null ? layoutAttributes : new AttributeDescriptor[0];
- }
-
- /**
- * Constructs a new {@link ElementDescriptor} based on its XML name and on the canonical
- * name of the class it represents.
- * The UI name is build by capitalizing the XML name.
- * The UI nodes will be non-mandatory.
- *
- * @param xml_name The XML element node name. Case sensitive.
- * @param fullClassName The fully qualified class name the {@link ViewElementDescriptor} is
- * representing.
- */
- public ViewElementDescriptor(String xml_name, String fullClassName) {
- super(xml_name);
- mFullClassName = fullClassName;
- mLayoutAttributes = null;
- }
-
- /**
- * Returns the fully qualified name of the View class represented by this element descriptor
- * e.g. "android.view.View".
- *
- * @return the fully qualified class name, never null
- */
- public String getFullClassName() {
- return mFullClassName;
- }
-
- /** Returns the list of layout attributes. Can be empty but not null.
- *
- * @return the list of layout attributes, never null
- */
- public AttributeDescriptor[] getLayoutAttributes() {
- return mLayoutAttributes;
- }
-
- /**
- * Sets the list of layout attribute attributes.
- *
- * @param attributes the new layout attributes, not null
- */
- public void setLayoutAttributes(AttributeDescriptor[] attributes) {
- assert attributes != null;
- mLayoutAttributes = attributes;
- }
-
- /**
- * Returns a new {@link UiViewElementNode} linked to this descriptor.
- */
- @Override
- public UiElementNode createUiNode() {
- return new UiViewElementNode(this);
- }
-
- /**
- * Returns the {@link ViewElementDescriptor} of the super-class of this View descriptor
- * that matches the java View hierarchy. Can be null.
- *
- * @return the super class' descriptor or null
- */
- public ViewElementDescriptor getSuperClassDesc() {
- return mSuperClassDesc;
- }
-
- /**
- * Sets the {@link ViewElementDescriptor} of the super-class of this View descriptor
- * that matches the java View hierarchy. Can be null.
- *
- * @param superClassDesc the descriptor for the super class, or null
- */
- public void setSuperClass(ViewElementDescriptor superClassDesc) {
- mSuperClassDesc = superClassDesc;
- }
-
- /**
- * Returns an optional icon for the element.
- * <p/>
- * By default this tries to return an icon based on the XML name of the element.
- * If this fails, it tries to return the default element icon as defined in the
- * plugin. If all fails, it returns null.
- *
- * @return An icon for this element or null.
- */
- @Override
- public Image getGenericIcon() {
- IconFactory factory = IconFactory.getInstance();
- String name = mXmlName;
- if (name.indexOf('.') != -1) {
- // If the user uses a fully qualified name, such as
- // "android.gesture.GestureOverlayView" in their XML, we need to look up
- // only by basename
- name = name.substring(name.lastIndexOf('.') + 1);
- } else if (VIEW_TAG.equals(name)) {
- // Can't have both view.png and View.png; issues on case sensitive vs
- // case insensitive file systems
- name = VIEW;
- }
-
- Image icon = factory.getIcon(name);
- if (icon == null) {
- icon = AdtPlugin.getAndroidLogo();
- }
-
- return icon;
- }
-
- /**
- * Returns the list of attribute sources for the attributes provided by this
- * descriptor. An attribute source is the fully qualified class name of the
- * defining class for some of the properties. The specific attribute source
- * of a given {@link AttributeInfo} can be found by calling
- * {@link AttributeInfo#getDefinedBy()}.
- * <p>
- * The attribute sources are ordered from class to super class.
- * <p>
- * The list may <b>not</b> be modified by clients.
- *
- * @return a non null list of attribute sources for this view
- */
- public List<String> getAttributeSources() {
- return mAttributeSources != null ? mAttributeSources : Collections.<String>emptyList();
- }
-
- /**
- * Sets the attribute sources for this view. See {@link #getAttributes()}
- * for details.
- *
- * @param attributeSources a non null list of attribute sources for this
- * view descriptor
- * @see #getAttributeSources()
- */
- public void setAttributeSources(List<String> attributeSources) {
- mAttributeSources = attributeSources;
- }
-
- /**
- * Returns true if views with the given fully qualified class name need to include
- * their package in the layout XML tag
- *
- * @param fqcn the fully qualified class name, such as android.widget.Button
- * @return true if the full package path should be included in the layout XML element
- * tag
- */
- public static boolean viewNeedsPackage(String fqcn) {
- return !(fqcn.startsWith(ANDROID_WIDGET_PREFIX)
- || fqcn.startsWith(ANDROID_VIEW_PKG)
- || fqcn.startsWith(ANDROID_WEBKIT_PKG));
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/AccordionControl.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/AccordionControl.java
deleted file mode 100644
index b3dce0756..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/AccordionControl.java
+++ /dev/null
@@ -1,396 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.CLabel;
-import org.eclipse.swt.custom.ScrolledComposite;
-import org.eclipse.swt.events.ControlAdapter;
-import org.eclipse.swt.events.ControlEvent;
-import org.eclipse.swt.events.MouseAdapter;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseTrackListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.layout.RowLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.ScrollBar;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * The accordion control allows a series of labels with associated content that can be
- * shown. For more details on accordions, see http://en.wikipedia.org/wiki/Accordion_(GUI)
- * <p>
- * This control allows the children to be created lazily. You can also customize the
- * composite which is created to hold the children items, to for example allow multiple
- * columns of items rather than just the default vertical stack.
- * <p>
- * The visual appearance of the headers is built in; it uses a mild gradient, with a
- * heavier gradient during mouse-overs. It also uses a bold label along with the eclipse
- * folder icons.
- * <p>
- * The control can be configured to enforce a single category open at any time (the
- * default), or allowing multiple categories open (where they share the available space).
- * The control can also be configured to fill the available vertical space for the open
- * category/categories.
- */
-public abstract class AccordionControl extends Composite {
- /** Pixel spacing between header items */
- private static final int HEADER_SPACING = 0;
-
- /** Pixel spacing between items in the content area */
- private static final int ITEM_SPACING = 0;
-
- private static final String KEY_CONTENT = "content"; //$NON-NLS-1$
- private static final String KEY_HEADER = "header"; //$NON-NLS-1$
-
- private Image mClosed;
- private Image mOpen;
- private boolean mSingle = true;
- private boolean mWrap;
-
- /**
- * Creates the container which will hold the items in a category; this can be
- * overridden to lay out the children with a different layout than the default
- * vertical RowLayout
- */
- protected Composite createChildContainer(Composite parent, Object header, int style) {
- Composite composite = new Composite(parent, style);
- if (mWrap) {
- RowLayout layout = new RowLayout(SWT.HORIZONTAL);
- layout.center = true;
- composite.setLayout(layout);
- } else {
- RowLayout layout = new RowLayout(SWT.VERTICAL);
- layout.spacing = ITEM_SPACING;
- layout.marginHeight = 0;
- layout.marginWidth = 0;
- layout.marginLeft = 0;
- layout.marginTop = 0;
- layout.marginRight = 0;
- layout.marginBottom = 0;
- composite.setLayout(layout);
- }
-
- // TODO - maybe do multi-column arrangement for simple nodes
- return composite;
- }
-
- /**
- * Creates the children under a particular header
- *
- * @param parent the parent composite to add the SWT items to
- * @param header the header object that is being opened for the first time
- */
- protected abstract void createChildren(Composite parent, Object header);
-
- /**
- * Set whether a single category should be enforced or not (default=true)
- *
- * @param single if true, enforce a single category open at a time
- */
- public void setAutoClose(boolean single) {
- mSingle = single;
- }
-
- /**
- * Returns whether a single category should be enforced or not (default=true)
- *
- * @return true if only a single category can be open at a time
- */
- public boolean isAutoClose() {
- return mSingle;
- }
-
- /**
- * Returns the labels used as header categories
- *
- * @return list of header labels
- */
- public List<CLabel> getHeaderLabels() {
- List<CLabel> headers = new ArrayList<CLabel>();
- for (Control c : getChildren()) {
- if (c instanceof CLabel) {
- headers.add((CLabel) c);
- }
- }
-
- return headers;
- }
-
- /**
- * Show all categories
- *
- * @param performLayout if true, call {@link #layout} and {@link #pack} when done
- */
- public void expandAll(boolean performLayout) {
- for (Control c : getChildren()) {
- if (c instanceof CLabel) {
- if (!isOpen(c)) {
- toggle((CLabel) c, false, false);
- }
- }
- }
- if (performLayout) {
- pack();
- layout();
- }
- }
-
- /**
- * Hide all categories
- *
- * @param performLayout if true, call {@link #layout} and {@link #pack} when done
- */
- public void collapseAll(boolean performLayout) {
- for (Control c : getChildren()) {
- if (c instanceof CLabel) {
- if (isOpen(c)) {
- toggle((CLabel) c, false, false);
- }
- }
- }
- if (performLayout) {
- layout();
- }
- }
-
- /**
- * Create the composite.
- *
- * @param parent the parent widget to add the accordion to
- * @param style the SWT style mask to use
- * @param headers a list of headers, whose {@link Object#toString} method should
- * produce the heading label
- * @param greedy if true, grow vertically as much as possible
- * @param wrapChildren if true, configure the child area to be horizontally laid out
- * with wrapping
- * @param expand Set of headers to expand initially
- */
- public AccordionControl(Composite parent, int style, List<?> headers,
- boolean greedy, boolean wrapChildren, Set<String> expand) {
- super(parent, style);
- mWrap = wrapChildren;
-
- GridLayout gridLayout = new GridLayout(1, false);
- gridLayout.verticalSpacing = HEADER_SPACING;
- gridLayout.horizontalSpacing = 0;
- gridLayout.marginWidth = 0;
- gridLayout.marginHeight = 0;
- setLayout(gridLayout);
-
- Font labelFont = null;
-
- mOpen = IconFactory.getInstance().getIcon("open-folder"); //$NON-NLS-1$
- mClosed = IconFactory.getInstance().getIcon("closed-folder"); //$NON-NLS-1$
- List<CLabel> expandLabels = new ArrayList<CLabel>();
-
- for (Object header : headers) {
- final CLabel label = new CLabel(this, SWT.SHADOW_OUT);
- label.setText(header.toString().replace("&", "&&")); //$NON-NLS-1$ //$NON-NLS-2$
- updateBackground(label, false);
- if (labelFont == null) {
- labelFont = JFaceResources.getFontRegistry().getBold(JFaceResources.DEFAULT_FONT);
- }
- label.setFont(labelFont);
- label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- setHeader(header, label);
- label.addMouseListener(new MouseAdapter() {
- @Override
- public void mouseUp(MouseEvent e) {
- if (e.button == 1 && (e.stateMask & SWT.MODIFIER_MASK) == 0) {
- toggle(label, true, mSingle);
- }
- }
- });
- label.addMouseTrackListener(new MouseTrackListener() {
- @Override
- public void mouseEnter(MouseEvent e) {
- updateBackground(label, true);
- }
-
- @Override
- public void mouseExit(MouseEvent e) {
- updateBackground(label, false);
- }
-
- @Override
- public void mouseHover(MouseEvent e) {
- }
- });
-
- // Turn off border?
- final ScrolledComposite scrolledComposite = new ScrolledComposite(this, SWT.V_SCROLL);
- ScrollBar verticalBar = scrolledComposite.getVerticalBar();
- verticalBar.setIncrement(20);
- verticalBar.setPageIncrement(100);
-
- // Do we need the scrolled composite or can we just look at the next
- // wizard in the hierarchy?
-
- setContentArea(label, scrolledComposite);
- scrolledComposite.setExpandHorizontal(true);
- scrolledComposite.setExpandVertical(true);
- GridData scrollGridData = new GridData(SWT.FILL,
- greedy ? SWT.FILL : SWT.TOP, false, greedy, 1, 1);
- scrollGridData.exclude = true;
- scrollGridData.grabExcessHorizontalSpace = wrapChildren;
- scrolledComposite.setLayoutData(scrollGridData);
-
- if (wrapChildren) {
- scrolledComposite.addControlListener(new ControlAdapter() {
- @Override
- public void controlResized(ControlEvent e) {
- Rectangle r = scrolledComposite.getClientArea();
- Control content = scrolledComposite.getContent();
- if (content != null && r != null) {
- Point minSize = content.computeSize(r.width, SWT.DEFAULT);
- scrolledComposite.setMinSize(minSize);
- ScrollBar vBar = scrolledComposite.getVerticalBar();
- vBar.setPageIncrement(r.height);
- }
- }
- });
- }
-
- updateIcon(label);
- if (expand != null && expand.contains(label.getText())) {
- // Comparing "label.getText()" rather than "header" because we make some
- // tweaks to the label (replacing & with && etc) and in the getExpandedCategories
- // method we return the label texts
- expandLabels.add(label);
- }
- }
-
- // Expand the requested categories
- for (CLabel label : expandLabels) {
- toggle(label, false, false);
- }
- }
-
- /** Updates the background gradient of the given header label */
- private void updateBackground(CLabel label, boolean mouseOver) {
- Display display = label.getDisplay();
- label.setBackground(new Color[] {
- display.getSystemColor(SWT.COLOR_WIDGET_HIGHLIGHT_SHADOW),
- display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND),
- display.getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW)
- }, new int[] {
- mouseOver ? 60 : 40, 100
- }, true);
- }
-
- /**
- * Updates the icon for a header label to be open/close based on the {@link #isOpen}
- * state
- */
- private void updateIcon(CLabel label) {
- label.setImage(isOpen(label) ? mOpen : mClosed);
- }
-
- /** Returns true if the content area for the given label is open/showing */
- private boolean isOpen(Control label) {
- return !((GridData) getContentArea(label).getLayoutData()).exclude;
- }
-
- /** Toggles the visibility of the children of the given label */
- private void toggle(CLabel label, boolean performLayout, boolean autoClose) {
- if (autoClose) {
- collapseAll(true);
- }
- ScrolledComposite scrolledComposite = getContentArea(label);
-
- GridData scrollGridData = (GridData) scrolledComposite.getLayoutData();
- boolean close = !scrollGridData.exclude;
- scrollGridData.exclude = close;
- scrolledComposite.setVisible(!close);
- updateIcon(label);
-
- if (!scrollGridData.exclude && scrolledComposite.getContent() == null) {
- Object header = getHeader(label);
- Composite composite = createChildContainer(scrolledComposite, header, SWT.NONE);
- createChildren(composite, header);
- while (composite.getParent() != scrolledComposite) {
- composite = composite.getParent();
- }
- scrolledComposite.setContent(composite);
- scrolledComposite.setMinSize(composite.computeSize(SWT.DEFAULT, SWT.DEFAULT));
- }
-
- if (performLayout) {
- layout(true);
- }
- }
-
- /** Returns the header object for the given header label */
- private Object getHeader(Control label) {
- return label.getData(KEY_HEADER);
- }
-
- /** Sets the header object for the given header label */
- private void setHeader(Object header, final CLabel label) {
- label.setData(KEY_HEADER, header);
- }
-
- /** Returns the content area for the given header label */
- private ScrolledComposite getContentArea(Control label) {
- return (ScrolledComposite) label.getData(KEY_CONTENT);
- }
-
- /** Sets the content area for the given header label */
- private void setContentArea(final CLabel label, ScrolledComposite scrolledComposite) {
- label.setData(KEY_CONTENT, scrolledComposite);
- }
-
- @Override
- protected void checkSubclass() {
- // Disable the check that prevents subclassing of SWT components
- }
-
- /**
- * Returns the set of expanded categories in the palette. Note: Header labels will have
- * escaped ampersand characters with double ampersands.
- *
- * @return the set of expanded categories in the palette - never null
- */
- public Set<String> getExpandedCategories() {
- Set<String> expanded = new HashSet<String>();
- for (Control c : getChildren()) {
- if (c instanceof CLabel) {
- if (isOpen(c)) {
- expanded.add(((CLabel) c).getText());
- }
- }
- }
-
- return expanded;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/BinPacker.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/BinPacker.java
deleted file mode 100644
index 9fc2e0937..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/BinPacker.java
+++ /dev/null
@@ -1,352 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.Rect;
-
-import java.awt.Color;
-import java.awt.Graphics2D;
-import java.awt.image.BufferedImage;
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-import javax.imageio.ImageIO;
-
-/**
- * This class implements 2D bin packing: packing rectangles into a given area as
- * tightly as "possible" (bin packing in general is NP hard, so this class uses
- * heuristics).
- * <p>
- * The algorithm implemented is to keep a set of (possibly overlapping)
- * available areas for placement. For each newly inserted rectangle, we first
- * pick which available space to occupy, and we then subdivide the
- * current rectangle into all the possible remaining unoccupied sub-rectangles.
- * We also remove any other space rectangles which are no longer eligible if
- * they are intersecting the newly placed rectangle.
- * <p>
- * This algorithm is not very fast, so should not be used for a large number of
- * rectangles.
- */
-class BinPacker {
- /**
- * When enabled, the successive passes are dumped as PNG images showing the
- * various available and occupied rectangles)
- */
- private static final boolean DEBUG = false;
-
- private final List<Rect> mSpace = new ArrayList<Rect>();
- private final int mMinHeight;
- private final int mMinWidth;
-
- /**
- * Creates a new {@linkplain BinPacker}. To use it, first add one or more
- * initial available space rectangles with {@link #addSpace(Rect)}, and then
- * place the rectangles with {@link #occupy(int, int)}. The returned
- * {@link Rect} from {@link #occupy(int, int)} gives the coordinates of the
- * positioned rectangle.
- *
- * @param minWidth the smallest width of any rectangle placed into this bin
- * @param minHeight the smallest height of any rectangle placed into this bin
- */
- BinPacker(int minWidth, int minHeight) {
- mMinWidth = minWidth;
- mMinHeight = minHeight;
-
- if (DEBUG) {
- mAllocated = new ArrayList<Rect>();
- sLayoutId++;
- sRectId = 1;
- }
- }
-
- /** Adds more available space */
- void addSpace(Rect rect) {
- if (rect.w >= mMinWidth && rect.h >= mMinHeight) {
- mSpace.add(rect);
- }
- }
-
- /** Attempts to place a rectangle of the given dimensions, if possible */
- @Nullable
- Rect occupy(int width, int height) {
- int index = findBest(width, height);
- if (index == -1) {
- return null;
- }
-
- return split(index, width, height);
- }
-
- /**
- * Finds the best available space rectangle to position a new rectangle of
- * the given size in.
- */
- private int findBest(int width, int height) {
- if (mSpace.isEmpty()) {
- return -1;
- }
-
- // Try to pack as far up as possible first
- int bestIndex = -1;
- boolean multipleAtSameY = false;
- int minY = Integer.MAX_VALUE;
- for (int i = 0, n = mSpace.size(); i < n; i++) {
- Rect rect = mSpace.get(i);
- if (rect.y <= minY) {
- if (rect.w >= width && rect.h >= height) {
- if (rect.y < minY) {
- minY = rect.y;
- multipleAtSameY = false;
- bestIndex = i;
- } else if (minY == rect.y) {
- multipleAtSameY = true;
- }
- }
- }
- }
-
- if (!multipleAtSameY) {
- return bestIndex;
- }
-
- bestIndex = -1;
-
- // Pick a rectangle. This currently tries to find the rectangle whose shortest
- // side most closely matches the placed rectangle's size.
- // Attempt to find the best short side fit
- int bestShortDistance = Integer.MAX_VALUE;
- int bestLongDistance = Integer.MAX_VALUE;
-
- for (int i = 0, n = mSpace.size(); i < n; i++) {
- Rect rect = mSpace.get(i);
- if (rect.y != minY) { // Only comparing elements at same y
- continue;
- }
- if (rect.w >= width && rect.h >= height) {
- if (width < height) {
- int distance = rect.w - width;
- if (distance < bestShortDistance ||
- distance == bestShortDistance &&
- (rect.h - height) < bestLongDistance) {
- bestShortDistance = distance;
- bestLongDistance = rect.h - height;
- bestIndex = i;
- }
- } else {
- int distance = rect.w - width;
- if (distance < bestShortDistance ||
- distance == bestShortDistance &&
- (rect.h - height) < bestLongDistance) {
- bestShortDistance = distance;
- bestLongDistance = rect.h - height;
- bestIndex = i;
- }
- }
- }
- }
-
- return bestIndex;
- }
-
- /**
- * Removes the rectangle at the given index. Since the rectangles are in an
- * {@link ArrayList}, removing a rectangle in the normal way is slow (it
- * would involve shifting all elements), but since we don't care about
- * order, this always swaps the to-be-deleted element to the last position
- * in the array first, <b>then</b> it deletes it (which should be
- * immediate).
- *
- * @param index the index in the {@link #mSpace} list to remove a rectangle
- * from
- */
- private void removeRect(int index) {
- assert !mSpace.isEmpty();
- int lastIndex = mSpace.size() - 1;
- if (index != lastIndex) {
- // Swap before remove to make deletion faster since we don't
- // care about order
- Rect temp = mSpace.get(index);
- mSpace.set(index, mSpace.get(lastIndex));
- mSpace.set(lastIndex, temp);
- }
-
- mSpace.remove(lastIndex);
- }
-
- /**
- * Splits the rectangle at the given rectangle index such that it can contain
- * a rectangle of the given width and height. */
- private Rect split(int index, int width, int height) {
- Rect rect = mSpace.get(index);
- assert rect.w >= width && rect.h >= height : rect;
-
- Rect r = new Rect(rect);
- r.w = width;
- r.h = height;
-
- // Remove all rectangles that intersect my rectangle
- for (int i = 0; i < mSpace.size(); i++) {
- Rect other = mSpace.get(i);
- if (other.intersects(r)) {
- removeRect(i);
- i--;
- }
- }
-
-
- // Split along vertical line x = rect.x + width:
- // (rect.x,rect.y)
- // +-------------+-------------------------+
- // | | |
- // | | |
- // | | height |
- // | | |
- // | | |
- // +-------------+ B | rect.h
- // | width |
- // | | |
- // | A |
- // | | |
- // | |
- // +---------------------------------------+
- // rect.w
- int remainingHeight = rect.h - height;
- int remainingWidth = rect.w - width;
- if (remainingHeight >= mMinHeight) {
- mSpace.add(new Rect(rect.x, rect.y + height, width, remainingHeight));
- }
- if (remainingWidth >= mMinWidth) {
- mSpace.add(new Rect(rect.x + width, rect.y, remainingWidth, rect.h));
- }
-
- // Split along horizontal line y = rect.y + height:
- // +-------------+-------------------------+
- // | | |
- // | | height |
- // | | A |
- // | | |
- // | | | rect.h
- // +-------------+ - - - - - - - - - - - - |
- // | width |
- // | |
- // | B |
- // | |
- // | |
- // +---------------------------------------+
- // rect.w
- if (remainingHeight >= mMinHeight) {
- mSpace.add(new Rect(rect.x, rect.y + height, rect.w, remainingHeight));
- }
- if (remainingWidth >= mMinWidth) {
- mSpace.add(new Rect(rect.x + width, rect.y, remainingWidth, height));
- }
-
- // Remove redundant rectangles. This is not very efficient.
- for (int i = 0; i < mSpace.size() - 1; i++) {
- for (int j = i + 1; j < mSpace.size(); j++) {
- Rect iRect = mSpace.get(i);
- Rect jRect = mSpace.get(j);
- if (jRect.contains(iRect)) {
- removeRect(i);
- i--;
- break;
- }
- if (iRect.contains(jRect)) {
- removeRect(j);
- j--;
- }
- }
- }
-
- if (DEBUG) {
- mAllocated.add(r);
- dumpImage();
- }
-
- return r;
- }
-
- // DEBUGGING CODE: Enable with DEBUG
-
- private List<Rect> mAllocated;
- private static int sLayoutId;
- private static int sRectId;
- private void dumpImage() {
- if (DEBUG) {
- int width = 100;
- int height = 100;
- for (Rect rect : mSpace) {
- width = Math.max(width, rect.w);
- height = Math.max(height, rect.h);
- }
- width += 10;
- height += 10;
-
- BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
- Graphics2D g = image.createGraphics();
- g.setColor(Color.BLACK);
- g.fillRect(0, 0, image.getWidth(), image.getHeight());
-
- Color[] colors = new Color[] {
- Color.blue, Color.cyan,
- Color.green, Color.magenta, Color.orange,
- Color.pink, Color.red, Color.white, Color.yellow, Color.darkGray,
- Color.lightGray, Color.gray,
- };
-
- char allocated = 'A';
- for (Rect rect : mAllocated) {
- Color color = new Color(0x9FFFFFFF, true);
- g.setColor(color);
- g.setBackground(color);
- g.fillRect(rect.x, rect.y, rect.w, rect.h);
- g.setColor(Color.WHITE);
- g.drawRect(rect.x, rect.y, rect.w, rect.h);
- g.drawString("" + (allocated++),
- rect.x + rect.w / 2, rect.y + rect.h / 2);
- }
-
- int colorIndex = 0;
- for (Rect rect : mSpace) {
- Color color = colors[colorIndex];
- colorIndex = (colorIndex + 1) % colors.length;
-
- color = new Color(color.getRed(), color.getGreen(), color.getBlue(), 128);
- g.setColor(color);
-
- g.fillRect(rect.x, rect.y, rect.w, rect.h);
- g.setColor(Color.WHITE);
- g.drawString(Integer.toString(colorIndex),
- rect.x + rect.w / 2, rect.y + rect.h / 2);
- }
-
-
- g.dispose();
-
- File file = new File("/tmp/layout" + sLayoutId + "_pass" + sRectId + ".png");
- try {
- ImageIO.write(image, "PNG", file);
- System.out.println("Wrote diagnostics image " + file);
- } catch (IOException e) {
- e.printStackTrace();
- }
- sRectId++;
- }
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/CanvasAlternateSelection.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/CanvasAlternateSelection.java
deleted file mode 100644
index c04061cbd..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/CanvasAlternateSelection.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import java.util.List;
-
-/**
- * Information for the current alternate selection, i.e. the possible selected items
- * that are located at the same x/y as the original view, either sibling or parents.
- */
-/* package */ class CanvasAlternateSelection {
- private final CanvasViewInfo mOriginatingView;
- private final List<CanvasViewInfo> mAltViews;
- private int mIndex;
-
- /**
- * Creates a new alternate selection based on the given originating view and the
- * given list of alternate views. Both cannot be null.
- */
- public CanvasAlternateSelection(CanvasViewInfo originatingView, List<CanvasViewInfo> altViews) {
- assert originatingView != null;
- assert altViews != null;
- mOriginatingView = originatingView;
- mAltViews = altViews;
- mIndex = altViews.size() - 1;
- }
-
- /** Returns the list of alternate views. Cannot be null. */
- public List<CanvasViewInfo> getAltViews() {
- return mAltViews;
- }
-
- /** Returns the originating view. Cannot be null. */
- public CanvasViewInfo getOriginatingView() {
- return mOriginatingView;
- }
-
- /**
- * Returns the current alternate view to select.
- * Initially this is the top-most view.
- */
- public CanvasViewInfo getCurrent() {
- return mIndex >= 0 ? mAltViews.get(mIndex) : null;
- }
-
- /**
- * Changes the current view to be the next one and then returns it.
- * This loops through the alternate views.
- */
- public CanvasViewInfo getNext() {
- if (mIndex == 0) {
- mIndex = mAltViews.size() - 1;
- } else if (mIndex > 0) {
- mIndex--;
- }
-
- return getCurrent();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/CanvasTransform.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/CanvasTransform.java
deleted file mode 100644
index ad5bd52e5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/CanvasTransform.java
+++ /dev/null
@@ -1,215 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.ImageUtils.SHADOW_SIZE;
-
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.widgets.ScrollBar;
-
-/**
- * Helper class to convert between control pixel coordinates and canvas coordinates.
- * Takes care of the zooming and offset of the canvas.
- */
-public class CanvasTransform {
- /**
- * Default margin around the rendered image, reduced
- * when the contents do not fit.
- */
- public static final int DEFAULT_MARGIN = 25;
-
- /**
- * The canvas which controls the zooming.
- */
- private final LayoutCanvas mCanvas;
-
- /** Canvas image size (original, before zoom), in pixels. */
- private int mImgSize;
-
- /** Full size being scrolled (after zoom), in pixels */
- private int mFullSize;;
-
- /** Client size, in pixels. */
- private int mClientSize;
-
- /** Left-top offset in client pixel coordinates. */
- private int mTranslate;
-
- /** Current margin */
- private int mMargin = DEFAULT_MARGIN;
-
- /** Scaling factor, > 0. */
- private double mScale;
-
- /** Scrollbar widget. */
- private ScrollBar mScrollbar;
-
- public CanvasTransform(LayoutCanvas layoutCanvas, ScrollBar scrollbar) {
- mCanvas = layoutCanvas;
- mScrollbar = scrollbar;
- mScale = 1.0;
- mTranslate = 0;
-
- mScrollbar.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- // User requested scrolling. Changes translation and redraw canvas.
- mTranslate = mScrollbar.getSelection();
- CanvasTransform.this.mCanvas.redraw();
- }
- });
- mScrollbar.setIncrement(20);
- }
-
- /**
- * Sets the new scaling factor. Recomputes scrollbars.
- * @param scale Scaling factor, > 0.
- */
- public void setScale(double scale) {
- if (mScale != scale) {
- mScale = scale;
- resizeScrollbar();
- }
- }
-
- /** Recomputes the scrollbar and view port settings */
- public void refresh() {
- resizeScrollbar();
- }
-
- /**
- * Returns current scaling factor.
- *
- * @return The current scaling factor
- */
- public double getScale() {
- return mScale;
- }
-
- /**
- * Returns Canvas image size (original, before zoom), in pixels.
- *
- * @return Canvas image size (original, before zoom), in pixels
- */
- public int getImgSize() {
- return mImgSize;
- }
-
- /**
- * Returns the scaled image size in pixels.
- *
- * @return The scaled image size in pixels.
- */
- public int getScaledImgSize() {
- return (int) (mImgSize * mScale);
- }
-
- /**
- * Changes the size of the canvas image and the client size. Recomputes
- * scrollbars.
- *
- * @param imgSize the size of the image being scaled
- * @param fullSize the size of the full view area being scrolled
- * @param clientSize the size of the view port
- */
- public void setSize(int imgSize, int fullSize, int clientSize) {
- mImgSize = imgSize;
- mFullSize = fullSize;
- mClientSize = clientSize;
- mScrollbar.setPageIncrement(clientSize);
- resizeScrollbar();
- }
-
- private void resizeScrollbar() {
- // scaled image size
- int sx = (int) (mScale * mFullSize);
-
- // Adjust margin such that for zoomed out views
- // we don't waste space (unless the viewport is
- // large enough to accommodate it)
- int delta = mClientSize - sx;
- if (delta < 0) {
- mMargin = 0;
- } else if (delta < 2 * DEFAULT_MARGIN) {
- mMargin = delta / 2;
-
- ImageOverlay imageOverlay = mCanvas.getImageOverlay();
- if (imageOverlay != null && imageOverlay.getShowDropShadow()
- && delta >= SHADOW_SIZE / 2) {
- mMargin -= SHADOW_SIZE / 2;
- // Add a little padding on the top too, if there's room. The shadow assets
- // include enough padding on the bottom to not make this look clipped.
- if (mMargin < 4) {
- mMargin += 4;
- }
- }
- } else {
- mMargin = DEFAULT_MARGIN;
- }
-
- if (mCanvas.getPreviewManager().hasPreviews()) {
- // Make more room for the previews
- mMargin = 2;
- }
-
- // actual client area is always reduced by the margins
- int cx = mClientSize - 2 * mMargin;
-
- if (sx < cx) {
- mTranslate = 0;
- mScrollbar.setEnabled(false);
- } else {
- mScrollbar.setEnabled(true);
-
- int selection = mScrollbar.getSelection();
- int thumb = cx;
- int maximum = sx;
-
- if (selection + thumb > maximum) {
- selection = maximum - thumb;
- if (selection < 0) {
- selection = 0;
- }
- }
-
- mScrollbar.setValues(selection, mScrollbar.getMinimum(), maximum, thumb, mScrollbar
- .getIncrement(), mScrollbar.getPageIncrement());
-
- mTranslate = selection;
- }
- }
-
- public int getMargin() {
- return mMargin;
- }
-
- public int translate(int canvasX) {
- return mMargin - mTranslate + (int) (mScale * canvasX);
- }
-
- public int scale(int canwasW) {
- return (int) (mScale * canwasW);
- }
-
- public int inverseTranslate(int screenX) {
- return (int) ((screenX - mMargin + mTranslate) / mScale);
- }
-
- public int inverseScale(int canwasW) {
- return (int) (canwasW / mScale);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/CanvasViewInfo.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/CanvasViewInfo.java
deleted file mode 100644
index 03c6c3926..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/CanvasViewInfo.java
+++ /dev/null
@@ -1,1178 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.SdkConstants.FQCN_SPACE;
-import static com.android.SdkConstants.FQCN_SPACE_V7;
-import static com.android.SdkConstants.GESTURE_OVERLAY_VIEW;
-import static com.android.SdkConstants.VIEW_MERGE;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.Margins;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.layout.GridLayoutRule;
-import com.android.ide.common.rendering.api.Capability;
-import com.android.ide.common.rendering.api.MergeCookie;
-import com.android.ide.common.rendering.api.ViewInfo;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.UiElementPullParser;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.utils.Pair;
-
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.ui.views.properties.IPropertyDescriptor;
-import org.eclipse.ui.views.properties.IPropertySheetPage;
-import org.eclipse.ui.views.properties.IPropertySource;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Maps a {@link ViewInfo} in a structure more adapted to our needs.
- * The only large difference is that we keep both the original bounds of the view info
- * and we pre-compute the selection bounds which are absolute to the rendered image
- * (whereas the original bounds are relative to the parent view.)
- * <p/>
- * Each view also knows its parent and children.
- * <p/>
- * We can't alter {@link ViewInfo} as it is part of the LayoutBridge and needs to
- * have a fixed API.
- * <p/>
- * The view info also implements {@link IPropertySource}, which enables a linked
- * {@link IPropertySheetPage} to display the attributes of the selected element.
- * This class actually delegates handling of {@link IPropertySource} to the underlying
- * {@link UiViewElementNode}, if any.
- */
-public class CanvasViewInfo implements IPropertySource {
-
- /**
- * Minimal size of the selection, in case an empty view or layout is selected.
- */
- public static final int SELECTION_MIN_SIZE = 6;
-
- private final Rectangle mAbsRect;
- private final Rectangle mSelectionRect;
- private final String mName;
- private final Object mViewObject;
- private final UiViewElementNode mUiViewNode;
- private CanvasViewInfo mParent;
- private ViewInfo mViewInfo;
- private final List<CanvasViewInfo> mChildren = new ArrayList<CanvasViewInfo>();
-
- /**
- * Is this view info an individually exploded view? This is the case for views
- * that were specially inflated by the {@link UiElementPullParser} and assigned
- * fixed padding because they were invisible and somebody requested visibility.
- */
- private boolean mExploded;
-
- /**
- * Node sibling. This is usually null, but it's possible for a single node in the
- * model to have <b>multiple</b> separate views in the canvas, for example
- * when you {@code <include>} a view that has multiple widgets inside a
- * {@code <merge>} tag. In this case, all the views have the same node model,
- * the include tag, and selecting the include should highlight all the separate
- * views that are linked to this node. That's what this field is all about: it is
- * a <b>circular</b> list of all the siblings that share the same node.
- */
- private List<CanvasViewInfo> mNodeSiblings;
-
- /**
- * Constructs a {@link CanvasViewInfo} initialized with the given initial values.
- */
- private CanvasViewInfo(CanvasViewInfo parent, String name,
- Object viewObject, UiViewElementNode node, Rectangle absRect,
- Rectangle selectionRect, ViewInfo viewInfo) {
- mParent = parent;
- mName = name;
- mViewObject = viewObject;
- mViewInfo = viewInfo;
- mUiViewNode = node;
- mAbsRect = absRect;
- mSelectionRect = selectionRect;
- }
-
- /**
- * Returns the original {@link ViewInfo} bounds in absolute coordinates
- * over the whole graphic.
- *
- * @return the bounding box in absolute coordinates
- */
- @NonNull
- public Rectangle getAbsRect() {
- return mAbsRect;
- }
-
- /**
- * Returns the absolute selection bounds of the view info as a rectangle.
- * The selection bounds will always have a size greater or equal to
- * {@link #SELECTION_MIN_SIZE}.
- * The width/height is inclusive (i.e. width = right-left-1).
- * This is in absolute "screen" coordinates (relative to the rendered bitmap).
- *
- * @return the absolute selection bounds
- */
- @NonNull
- public Rectangle getSelectionRect() {
- return mSelectionRect;
- }
-
- /**
- * Returns the view node. Could be null, although unlikely.
- * @return An {@link UiViewElementNode} that uniquely identifies the object in the XML model.
- * @see ViewInfo#getCookie()
- */
- @Nullable
- public UiViewElementNode getUiViewNode() {
- return mUiViewNode;
- }
-
- /**
- * Returns the parent {@link CanvasViewInfo}.
- * It is null for the root and non-null for children.
- *
- * @return the parent {@link CanvasViewInfo}, which can be null
- */
- @Nullable
- public CanvasViewInfo getParent() {
- return mParent;
- }
-
- /**
- * Returns the list of children of this {@link CanvasViewInfo}.
- * The list is never null. It can be empty.
- * By contract, this.getChildren().get(0..n-1).getParent() == this.
- *
- * @return the children, never null
- */
- @NonNull
- public List<CanvasViewInfo> getChildren() {
- return mChildren;
- }
-
- /**
- * For nodes that have multiple views rendered from a single node, such as the
- * children of a {@code <merge>} tag included into a separate layout, return the
- * "primary" view, the first view that is rendered
- */
- @Nullable
- private CanvasViewInfo getPrimaryNodeSibling() {
- if (mNodeSiblings == null || mNodeSiblings.size() == 0) {
- return null;
- }
-
- return mNodeSiblings.get(0);
- }
-
- /**
- * Returns true if this view represents one view of many linked to a single node, and
- * where this is the primary view. The primary view is the one that will be shown
- * in the outline for example (since we only show nodes, not views, in the outline,
- * and therefore don't want repetitions when a view has more than one view info.)
- *
- * @return true if this is the primary view among more than one linked to a single
- * node
- */
- private boolean isPrimaryNodeSibling() {
- return getPrimaryNodeSibling() == this;
- }
-
- /**
- * Returns the list of node sibling of this view (which <b>will include this
- * view</b>). For most views this is going to be null, but for views that share a
- * single node (such as widgets inside a {@code <merge>} tag included into another
- * layout), this will provide all the views that correspond to the node.
- *
- * @return a non-empty list of siblings (including this), or null
- */
- @Nullable
- public List<CanvasViewInfo> getNodeSiblings() {
- return mNodeSiblings;
- }
-
- /**
- * Returns all the children of the canvas view info where each child corresponds to a
- * unique node that the user can see and select. This is intended for use by the
- * outline for example, where only the actual nodes are displayed, not the views
- * themselves.
- * <p>
- * Most views have their own nodes, so this is generally the same as
- * {@link #getChildren}, except in the case where you for example include a view that
- * has multiple widgets inside a {@code <merge>} tag, where all these widgets have the
- * same node (the {@code <merge>} tag).
- *
- * @return list of {@link CanvasViewInfo} objects that are children of this view,
- * never null
- */
- @NonNull
- public List<CanvasViewInfo> getUniqueChildren() {
- boolean haveHidden = false;
-
- for (CanvasViewInfo info : mChildren) {
- if (info.mNodeSiblings != null) {
- // We have secondary children; must create a new collection containing
- // only non-secondary children
- List<CanvasViewInfo> children = new ArrayList<CanvasViewInfo>();
- for (CanvasViewInfo vi : mChildren) {
- if (vi.mNodeSiblings == null) {
- children.add(vi);
- } else if (vi.isPrimaryNodeSibling()) {
- children.add(vi);
- }
- }
- return children;
- }
-
- haveHidden |= info.isHidden();
- }
-
- if (haveHidden) {
- List<CanvasViewInfo> children = new ArrayList<CanvasViewInfo>(mChildren.size());
- for (CanvasViewInfo vi : mChildren) {
- if (!vi.isHidden()) {
- children.add(vi);
- }
- }
-
- return children;
- }
-
- return mChildren;
- }
-
- /**
- * Returns true if the specific {@link CanvasViewInfo} is a parent
- * of this {@link CanvasViewInfo}. It can be a direct parent or any
- * grand-parent higher in the hierarchy.
- *
- * @param potentialParent the view info to check
- * @return true if the given info is a parent of this view
- */
- public boolean isParent(@NonNull CanvasViewInfo potentialParent) {
- CanvasViewInfo p = mParent;
- while (p != null) {
- if (p == potentialParent) {
- return true;
- }
- p = p.getParent();
- }
- return false;
- }
-
- /**
- * Returns the name of the {@link CanvasViewInfo}.
- * Could be null, although unlikely.
- * Experience shows this is the full qualified Java name of the View.
- * TODO: Rename this method to getFqcn.
- *
- * @return the name of the view info
- *
- * @see ViewInfo#getClassName()
- */
- @NonNull
- public String getName() {
- return mName;
- }
-
- /**
- * Returns the View object associated with the {@link CanvasViewInfo}.
- * @return the view object or null.
- */
- @Nullable
- public Object getViewObject() {
- return mViewObject;
- }
-
- /**
- * Returns the baseline of this object, or -1 if it does not support a baseline
- *
- * @return the baseline or -1
- */
- public int getBaseline() {
- if (mViewInfo != null) {
- int baseline = mViewInfo.getBaseLine();
- if (baseline != Integer.MIN_VALUE) {
- return baseline;
- }
- }
-
- return -1;
- }
-
- /**
- * Returns the {@link Margins} for this {@link CanvasViewInfo}
- *
- * @return the {@link Margins} for this {@link CanvasViewInfo}
- */
- @Nullable
- public Margins getMargins() {
- if (mViewInfo != null) {
- int leftMargin = mViewInfo.getLeftMargin();
- int topMargin = mViewInfo.getTopMargin();
- int rightMargin = mViewInfo.getRightMargin();
- int bottomMargin = mViewInfo.getBottomMargin();
- return new Margins(
- leftMargin != Integer.MIN_VALUE ? leftMargin : 0,
- rightMargin != Integer.MIN_VALUE ? rightMargin : 0,
- topMargin != Integer.MIN_VALUE ? topMargin : 0,
- bottomMargin != Integer.MIN_VALUE ? bottomMargin : 0
- );
- }
-
- return null;
- }
-
- // ---- Implementation of IPropertySource
- // TODO: Get rid of this once the old propertysheet implementation is fully gone
-
- @Override
- public Object getEditableValue() {
- UiViewElementNode uiView = getUiViewNode();
- if (uiView != null) {
- return ((IPropertySource) uiView).getEditableValue();
- }
- return null;
- }
-
- @Override
- public IPropertyDescriptor[] getPropertyDescriptors() {
- UiViewElementNode uiView = getUiViewNode();
- if (uiView != null) {
- return ((IPropertySource) uiView).getPropertyDescriptors();
- }
- return null;
- }
-
- @Override
- public Object getPropertyValue(Object id) {
- UiViewElementNode uiView = getUiViewNode();
- if (uiView != null) {
- return ((IPropertySource) uiView).getPropertyValue(id);
- }
- return null;
- }
-
- @Override
- public boolean isPropertySet(Object id) {
- UiViewElementNode uiView = getUiViewNode();
- if (uiView != null) {
- return ((IPropertySource) uiView).isPropertySet(id);
- }
- return false;
- }
-
- @Override
- public void resetPropertyValue(Object id) {
- UiViewElementNode uiView = getUiViewNode();
- if (uiView != null) {
- ((IPropertySource) uiView).resetPropertyValue(id);
- }
- }
-
- @Override
- public void setPropertyValue(Object id, Object value) {
- UiViewElementNode uiView = getUiViewNode();
- if (uiView != null) {
- ((IPropertySource) uiView).setPropertyValue(id, value);
- }
- }
-
- /**
- * Returns the XML node corresponding to this info, or null if there is no
- * such XML node.
- *
- * @return The XML node corresponding to this info object, or null
- */
- @Nullable
- public Node getXmlNode() {
- UiViewElementNode uiView = getUiViewNode();
- if (uiView != null) {
- return uiView.getXmlNode();
- }
-
- return null;
- }
-
- /**
- * Returns true iff this view info corresponds to a root element.
- *
- * @return True iff this is a root view info.
- */
- public boolean isRoot() {
- // Select the visual element -- unless it's the root.
- // The root element is the one whose GRAND parent
- // is null (because the parent will be a -document-
- // node).
-
- // Special case: a gesture overlay is sometimes added as the root, but for all intents
- // and purposes it is its layout child that is the real root so treat that one as the
- // root as well (such that the whole layout canvas does not highlight as part of hovers
- // etc)
- if (mParent != null
- && mParent.mName.endsWith(GESTURE_OVERLAY_VIEW)
- && mParent.isRoot()
- && mParent.mChildren.size() == 1) {
- return true;
- }
-
- return mUiViewNode == null || mUiViewNode.getUiParent() == null ||
- mUiViewNode.getUiParent().getUiParent() == null;
- }
-
- /**
- * Returns true if this {@link CanvasViewInfo} represents an invisible widget that
- * should be highlighted when selected. This is the case for any layout that is less than the minimum
- * threshold ({@link #SELECTION_MIN_SIZE}), or any other view that has -0- bounds.
- *
- * @return True if this is a tiny layout or invisible view
- */
- public boolean isInvisible() {
- if (isHidden()) {
- // Don't expand and highlight hidden widgets
- return false;
- }
-
- if (mAbsRect.width < SELECTION_MIN_SIZE || mAbsRect.height < SELECTION_MIN_SIZE) {
- return mUiViewNode != null && (mUiViewNode.getDescriptor().hasChildren() ||
- mAbsRect.width <= 0 || mAbsRect.height <= 0);
- }
-
- return false;
- }
-
- /**
- * Returns true if this {@link CanvasViewInfo} represents a widget that should be
- * hidden, such as a {@code <Space>} which are typically not manipulated by the user
- * through dragging etc.
- *
- * @return true if this is a hidden view
- */
- public boolean isHidden() {
- if (GridLayoutRule.sDebugGridLayout) {
- return false;
- }
-
- return FQCN_SPACE.equals(mName) || FQCN_SPACE_V7.equals(mName);
- }
-
- /**
- * Is this {@link CanvasViewInfo} a view that has had its padding inflated in order to
- * make it visible during selection or dragging? Note that this is NOT considered to
- * be the case in the explode-all-views mode where all nodes have their padding
- * increased; it's only used for views that individually exploded because they were
- * requested visible and they returned true for {@link #isInvisible()}.
- *
- * @return True if this is an exploded node.
- */
- public boolean isExploded() {
- return mExploded;
- }
-
- /**
- * Mark this {@link CanvasViewInfo} as having been exploded or not. See the
- * {@link #isExploded()} method for details on what this property means.
- *
- * @param exploded New value of the exploded property to mark this info with.
- */
- void setExploded(boolean exploded) {
- mExploded = exploded;
- }
-
- /**
- * Returns the info represented as a {@link SimpleElement}.
- *
- * @return A {@link SimpleElement} wrapping this info.
- */
- @NonNull
- SimpleElement toSimpleElement() {
-
- UiViewElementNode uiNode = getUiViewNode();
-
- String fqcn = SimpleXmlTransfer.getFqcn(uiNode.getDescriptor());
- String parentFqcn = null;
- Rect bounds = SwtUtils.toRect(getAbsRect());
- Rect parentBounds = null;
-
- UiElementNode uiParent = uiNode.getUiParent();
- if (uiParent != null) {
- parentFqcn = SimpleXmlTransfer.getFqcn(uiParent.getDescriptor());
- }
- if (getParent() != null) {
- parentBounds = SwtUtils.toRect(getParent().getAbsRect());
- }
-
- SimpleElement e = new SimpleElement(fqcn, parentFqcn, bounds, parentBounds);
-
- for (UiAttributeNode attr : uiNode.getAllUiAttributes()) {
- String value = attr.getCurrentValue();
- if (value != null && value.length() > 0) {
- AttributeDescriptor attrDesc = attr.getDescriptor();
- SimpleAttribute a = new SimpleAttribute(
- attrDesc.getNamespaceUri(),
- attrDesc.getXmlLocalName(),
- value);
- e.addAttribute(a);
- }
- }
-
- for (CanvasViewInfo childVi : getChildren()) {
- SimpleElement e2 = childVi.toSimpleElement();
- if (e2 != null) {
- e.addInnerElement(e2);
- }
- }
-
- return e;
- }
-
- /**
- * Returns the layout url attribute value for the closest surrounding include or
- * fragment element parent, or null if this {@link CanvasViewInfo} is not rendered as
- * part of an include or fragment tag.
- *
- * @return the layout url attribute value for the surrounding include tag, or null if
- * not applicable
- */
- @Nullable
- public String getIncludeUrl() {
- CanvasViewInfo curr = this;
- while (curr != null) {
- if (curr.mUiViewNode != null) {
- Node node = curr.mUiViewNode.getXmlNode();
- if (node != null && node.getNodeType() == Node.ELEMENT_NODE) {
- String nodeName = node.getNodeName();
- if (node.getNamespaceURI() == null
- && SdkConstants.VIEW_INCLUDE.equals(nodeName)) {
- // Note: the layout attribute is NOT in the Android namespace
- Element element = (Element) node;
- String url = element.getAttribute(SdkConstants.ATTR_LAYOUT);
- if (url.length() > 0) {
- return url;
- }
- } else if (SdkConstants.VIEW_FRAGMENT.equals(nodeName)) {
- String url = FragmentMenu.getFragmentLayout(node);
- if (url != null) {
- return url;
- }
- }
- }
- }
- curr = curr.mParent;
- }
-
- return null;
- }
-
- /** Adds the given {@link CanvasViewInfo} as a new last child of this view */
- private void addChild(@NonNull CanvasViewInfo child) {
- mChildren.add(child);
- }
-
- /** Adds the given {@link CanvasViewInfo} as a child at the given index */
- private void addChildAt(int index, @NonNull CanvasViewInfo child) {
- mChildren.add(index, child);
- }
-
- /**
- * Removes the given {@link CanvasViewInfo} from the child list of this view, and
- * returns true if it was successfully removed
- *
- * @param child the child to be removed
- * @return true if it was a child and was removed
- */
- public boolean removeChild(@NonNull CanvasViewInfo child) {
- return mChildren.remove(child);
- }
-
- @Override
- public String toString() {
- return "CanvasViewInfo [name=" + mName + ", node=" + mUiViewNode + "]";
- }
-
- // ---- Factory functionality ----
-
- /**
- * Creates a new {@link CanvasViewInfo} hierarchy based on the given {@link ViewInfo}
- * hierarchy. Note that this will not necessarily create one {@link CanvasViewInfo}
- * for each {@link ViewInfo}. It will generally only create {@link CanvasViewInfo}
- * objects for {@link ViewInfo} objects that contain a reference to an
- * {@link UiViewElementNode}, meaning that it corresponds to an element in the XML
- * file for this layout file. This is not always the case, such as in the following
- * scenarios:
- * <ul>
- * <li>we link to other layouts with {@code <include>}
- * <li>the current view is rendered within another view ("Show Included In") such that
- * the outer file does not correspond to elements in the current included XML layout
- * <li>on older platforms that don't support {@link Capability#EMBEDDED_LAYOUT} there
- * is no reference to the {@code <include>} tag
- * <li>with the {@code <merge>} tag we don't get a reference to the corresponding
- * element
- * <ul>
- * <p>
- * This method will build up a set of {@link CanvasViewInfo} that corresponds to the
- * actual <b>selectable</b> views (which are also shown in the Outline).
- *
- * @param layoutlib5 if true, the {@link ViewInfo} hierarchy was created by layoutlib
- * version 5 or higher, which means this algorithm can make certain assumptions
- * (for example that {@code <merge>} siblings will provide {@link MergeCookie}
- * references, so we don't have to search for them.)
- * @param root the root {@link ViewInfo} to build from
- * @return a {@link CanvasViewInfo} hierarchy
- */
- @NonNull
- public static Pair<CanvasViewInfo,List<Rectangle>> create(ViewInfo root, boolean layoutlib5) {
- return new Builder(layoutlib5).create(root);
- }
-
- /** Builder object which walks over a tree of {@link ViewInfo} objects and builds
- * up a corresponding {@link CanvasViewInfo} hierarchy. */
- private static class Builder {
- public Builder(boolean layoutlib5) {
- mLayoutLib5 = layoutlib5;
- }
-
- /**
- * The mapping from nodes that have a {@code <merge>} as a parent in the node
- * model to their corresponding views
- */
- private Map<UiViewElementNode, List<CanvasViewInfo>> mMergeNodeMap;
-
- /**
- * Whether the ViewInfos are provided by a layout library that is version 5 or
- * later, since that will allow us to take several shortcuts
- */
- private boolean mLayoutLib5;
-
- /**
- * Creates a hierarchy of {@link CanvasViewInfo} objects and merge bounding
- * rectangles from the given {@link ViewInfo} hierarchy
- */
- private Pair<CanvasViewInfo,List<Rectangle>> create(ViewInfo root) {
- Object cookie = root.getCookie();
- if (cookie == null) {
- // Special case: If the root-most view does not have a view cookie,
- // then we are rendering some outer layout surrounding this layout, and in
- // that case we must search down the hierarchy for the (possibly multiple)
- // sub-roots that correspond to elements in this layout, and place them inside
- // an outer view that has no node. In the outline this item will be used to
- // show the inclusion-context.
- CanvasViewInfo rootView = createView(null, root, 0, 0);
- addKeyedSubtrees(rootView, root, 0, 0);
-
- List<Rectangle> includedBounds = new ArrayList<Rectangle>();
- for (CanvasViewInfo vi : rootView.getChildren()) {
- if (vi.getNodeSiblings() == null || vi.isPrimaryNodeSibling()) {
- includedBounds.add(vi.getAbsRect());
- }
- }
-
- // There are <merge> nodes here; see if we can insert it into the hierarchy
- if (mMergeNodeMap != null) {
- // Locate all the nodes that have a <merge> as a parent in the node model,
- // and where the view sits at the top level inside the include-context node.
- UiViewElementNode merge = null;
- List<CanvasViewInfo> merged = new ArrayList<CanvasViewInfo>();
- for (Map.Entry<UiViewElementNode, List<CanvasViewInfo>> entry : mMergeNodeMap
- .entrySet()) {
- UiViewElementNode node = entry.getKey();
- if (!hasMergeParent(node)) {
- continue;
- }
- List<CanvasViewInfo> views = entry.getValue();
- assert views.size() > 0;
- CanvasViewInfo view = views.get(0); // primary
- if (view.getParent() != rootView) {
- continue;
- }
- UiElementNode parent = node.getUiParent();
- if (merge != null && parent != merge) {
- continue;
- }
- merge = (UiViewElementNode) parent;
- merged.add(view);
- }
- if (merged.size() > 0) {
- // Compute a bounding box for the merged views
- Rectangle absRect = null;
- for (CanvasViewInfo child : merged) {
- Rectangle rect = child.getAbsRect();
- if (absRect == null) {
- absRect = rect;
- } else {
- absRect = absRect.union(rect);
- }
- }
-
- CanvasViewInfo mergeView = new CanvasViewInfo(rootView, VIEW_MERGE, null,
- merge, absRect, absRect, null /* viewInfo */);
- for (CanvasViewInfo view : merged) {
- if (rootView.removeChild(view)) {
- mergeView.addChild(view);
- }
- }
- rootView.addChild(mergeView);
- }
- }
-
- return Pair.of(rootView, includedBounds);
- } else {
- // We have a view key at the top, so just go and create {@link CanvasViewInfo}
- // objects for each {@link ViewInfo} until we run into a null key.
- CanvasViewInfo rootView = addKeyedSubtrees(null, root, 0, 0);
-
- // Special case: look to see if the root element is really a <merge>, and if so,
- // manufacture a view for it such that we can target this root element
- // in drag & drop operations, such that we can show it in the outline, etc
- if (rootView != null && hasMergeParent(rootView.getUiViewNode())) {
- CanvasViewInfo merge = new CanvasViewInfo(null, VIEW_MERGE, null,
- (UiViewElementNode) rootView.getUiViewNode().getUiParent(),
- rootView.getAbsRect(), rootView.getSelectionRect(),
- null /* viewInfo */);
- // Insert the <merge> as the new real root
- rootView.mParent = merge;
- merge.addChild(rootView);
- rootView = merge;
- }
-
- return Pair.of(rootView, null);
- }
- }
-
- private boolean hasMergeParent(UiViewElementNode rootNode) {
- UiElementNode rootParent = rootNode.getUiParent();
- return (rootParent instanceof UiViewElementNode
- && VIEW_MERGE.equals(rootParent.getDescriptor().getXmlName()));
- }
-
- /** Creates a {@link CanvasViewInfo} for a given {@link ViewInfo} but does not recurse */
- private CanvasViewInfo createView(CanvasViewInfo parent, ViewInfo root, int parentX,
- int parentY) {
- Object cookie = root.getCookie();
- UiViewElementNode node = null;
- if (cookie instanceof UiViewElementNode) {
- node = (UiViewElementNode) cookie;
- } else if (cookie instanceof MergeCookie) {
- cookie = ((MergeCookie) cookie).getCookie();
- if (cookie instanceof UiViewElementNode) {
- node = (UiViewElementNode) cookie;
- CanvasViewInfo view = createView(parent, root, parentX, parentY, node);
- if (root.getCookie() instanceof MergeCookie && view.mNodeSiblings == null) {
- List<CanvasViewInfo> v = mMergeNodeMap == null ?
- null : mMergeNodeMap.get(node);
- if (v != null) {
- v.add(view);
- } else {
- v = new ArrayList<CanvasViewInfo>();
- v.add(view);
- if (mMergeNodeMap == null) {
- mMergeNodeMap =
- new HashMap<UiViewElementNode, List<CanvasViewInfo>>();
- }
- mMergeNodeMap.put(node, v);
- }
- view.mNodeSiblings = v;
- }
-
- return view;
- }
- }
-
- return createView(parent, root, parentX, parentY, node);
- }
-
- /**
- * Creates a {@link CanvasViewInfo} for a given {@link ViewInfo} but does not recurse.
- * This method specifies an explicit {@link UiViewElementNode} to use rather than
- * relying on the view cookie in the info object.
- */
- private CanvasViewInfo createView(CanvasViewInfo parent, ViewInfo root, int parentX,
- int parentY, UiViewElementNode node) {
-
- int x = root.getLeft();
- int y = root.getTop();
- int w = root.getRight() - x;
- int h = root.getBottom() - y;
-
- x += parentX;
- y += parentY;
-
- Rectangle absRect = new Rectangle(x, y, w - 1, h - 1);
-
- if (w < SELECTION_MIN_SIZE) {
- int d = (SELECTION_MIN_SIZE - w) / 2;
- x -= d;
- w += SELECTION_MIN_SIZE - w;
- }
-
- if (h < SELECTION_MIN_SIZE) {
- int d = (SELECTION_MIN_SIZE - h) / 2;
- y -= d;
- h += SELECTION_MIN_SIZE - h;
- }
-
- Rectangle selectionRect = new Rectangle(x, y, w - 1, h - 1);
-
- return new CanvasViewInfo(parent, root.getClassName(), root.getViewObject(), node,
- absRect, selectionRect, root);
- }
-
- /** Create a subtree recursively until you run out of keys */
- private CanvasViewInfo createSubtree(CanvasViewInfo parent, ViewInfo viewInfo,
- int parentX, int parentY) {
- assert viewInfo.getCookie() != null;
-
- CanvasViewInfo view = createView(parent, viewInfo, parentX, parentY);
- // Bug workaround: Ensure that we never have a child node identical
- // to its parent node: this can happen for example when rendering a
- // ZoomControls view where the merge cookies point to the parent.
- if (parent != null && view.mUiViewNode == parent.mUiViewNode) {
- return null;
- }
-
- // Process children:
- parentX += viewInfo.getLeft();
- parentY += viewInfo.getTop();
-
- List<ViewInfo> children = viewInfo.getChildren();
-
- if (mLayoutLib5) {
- for (ViewInfo child : children) {
- Object cookie = child.getCookie();
- if (cookie instanceof UiViewElementNode || cookie instanceof MergeCookie) {
- CanvasViewInfo childView = createSubtree(view, child,
- parentX, parentY);
- if (childView != null) {
- view.addChild(childView);
- }
- } // else: null cookies, adapter item references, etc: No child views.
- }
-
- return view;
- }
-
- // See if we have any missing keys at this level
- int missingNodes = 0;
- int mergeNodes = 0;
- for (ViewInfo child : children) {
- // Only use children which have a ViewKey of the correct type.
- // We can't interact with those when they have a null key or
- // an incompatible type.
- Object cookie = child.getCookie();
- if (!(cookie instanceof UiViewElementNode)) {
- if (cookie instanceof MergeCookie) {
- mergeNodes++;
- } else {
- missingNodes++;
- }
- }
- }
-
- if (missingNodes == 0 && mergeNodes == 0) {
- // No missing nodes; this is the normal case, and we can just continue to
- // recursively add our children
- for (ViewInfo child : children) {
- CanvasViewInfo childView = createSubtree(view, child,
- parentX, parentY);
- view.addChild(childView);
- }
-
- // TBD: Emit placeholder views for keys that have no views?
- } else {
- // We don't have keys for one or more of the ViewInfos. There are many
- // possible causes: we are on an SDK platform that does not support
- // embedded_layout rendering, or we are including a view with a <merge>
- // as the root element.
-
- UiViewElementNode uiViewNode = view.getUiViewNode();
- String containerName = uiViewNode != null
- ? uiViewNode.getDescriptor().getXmlLocalName() : ""; //$NON-NLS-1$
- if (containerName.equals(SdkConstants.VIEW_INCLUDE)) {
- // This is expected -- we don't WANT to get node keys for the content
- // of an include since it's in a different file and should be treated
- // as a single unit that cannot be edited (hence, no CanvasViewInfo
- // children)
- } else {
- // We are getting children with null keys where we don't expect it;
- // this usually means that we are dealing with an Android platform
- // that does not support {@link Capability#EMBEDDED_LAYOUT}, or
- // that there are <merge> tags which are doing surprising things
- // to the view hierarchy
- LinkedList<UiViewElementNode> unused = new LinkedList<UiViewElementNode>();
- if (uiViewNode != null) {
- for (UiElementNode child : uiViewNode.getUiChildren()) {
- if (child instanceof UiViewElementNode) {
- unused.addLast((UiViewElementNode) child);
- }
- }
- }
- for (ViewInfo child : children) {
- Object cookie = child.getCookie();
- if (mergeNodes > 0 && cookie instanceof MergeCookie) {
- cookie = ((MergeCookie) cookie).getCookie();
- }
- if (cookie != null) {
- unused.remove(cookie);
- }
- }
-
- if (unused.size() > 0 || mergeNodes > 0) {
- if (unused.size() == missingNodes) {
- // The number of unmatched elements and ViewInfos are identical;
- // it's very likely that they match one to one, so just use these
- for (ViewInfo child : children) {
- if (child.getCookie() == null) {
- // Only create a flat (non-recursive) view
- CanvasViewInfo childView = createView(view, child, parentX,
- parentY, unused.removeFirst());
- view.addChild(childView);
- } else {
- CanvasViewInfo childView = createSubtree(view, child, parentX,
- parentY);
- view.addChild(childView);
- }
- }
- } else {
- // We have an uneven match. In this case we might be dealing
- // with <merge> etc.
- // We have no way to associate elements back with the
- // corresponding <include> tags if there are more than one of
- // them. That's not a huge tragedy since visually you are not
- // allowed to edit these anyway; we just need to make a visual
- // block for these for selection and outline purposes.
- addMismatched(view, parentX, parentY, children, unused);
- }
- } else {
- // No unused keys, but there are views without keys.
- // We can't represent these since all views must have node keys
- // such that you can operate on them. Just ignore these.
- for (ViewInfo child : children) {
- if (child.getCookie() != null) {
- CanvasViewInfo childView = createSubtree(view, child,
- parentX, parentY);
- view.addChild(childView);
- }
- }
- }
- }
- }
-
- return view;
- }
-
- /**
- * We have various {@link ViewInfo} children with null keys, and/or nodes in
- * the corresponding UI model that are not referenced by any of the {@link ViewInfo}
- * objects. This method attempts to account for this, by matching the views in
- * the right order.
- */
- private void addMismatched(CanvasViewInfo parentView, int parentX, int parentY,
- List<ViewInfo> children, LinkedList<UiViewElementNode> unused) {
- UiViewElementNode afterNode = null;
- UiViewElementNode beforeNode = null;
- // We have one important clue we can use when matching unused nodes
- // with views: if we have a view V1 with node N1, and a view V2 with node N2,
- // then we can only match unknown node UN with unknown node UV if
- // V1 < UV < V2 and N1 < UN < N2.
- // We can use these constraints to do the matching, for example by
- // a simple DAG traversal. However, since the number of unmatched nodes
- // will typically be very small, we'll just do a simple algorithm here
- // which checks forwards/backwards whether a match is valid.
- for (int index = 0, size = children.size(); index < size; index++) {
- ViewInfo child = children.get(index);
- if (child.getCookie() != null) {
- CanvasViewInfo childView = createSubtree(parentView, child, parentX, parentY);
- if (childView != null) {
- parentView.addChild(childView);
- }
- if (child.getCookie() instanceof UiViewElementNode) {
- afterNode = (UiViewElementNode) child.getCookie();
- }
- } else {
- beforeNode = nextViewNode(children, index);
-
- // Find first eligible node from unused
- // TOD: What if there are more eligible? We need to process ALL views
- // and all nodes in one go here
-
- UiViewElementNode matching = null;
- for (UiViewElementNode candidate : unused) {
- if (afterNode == null || isAfter(afterNode, candidate)) {
- if (beforeNode == null || isBefore(beforeNode, candidate)) {
- matching = candidate;
- break;
- }
- }
- }
-
- if (matching != null) {
- unused.remove(matching);
- CanvasViewInfo childView = createView(parentView, child, parentX, parentY,
- matching);
- parentView.addChild(childView);
- afterNode = matching;
- } else {
- // We have no node for the view -- what do we do??
- // Nothing - we only represent stuff in the outline that is in the
- // source model, not in the render
- }
- }
- }
-
- // Add zero-bounded boxes for all remaining nodes since they need to show
- // up in the outline, need to be selectable so you can press Delete, etc.
- if (unused.size() > 0) {
- Map<UiViewElementNode, Integer> rankMap =
- new HashMap<UiViewElementNode, Integer>();
- Map<UiViewElementNode, CanvasViewInfo> infoMap =
- new HashMap<UiViewElementNode, CanvasViewInfo>();
- UiElementNode parent = unused.get(0).getUiParent();
- if (parent != null) {
- int index = 0;
- for (UiElementNode child : parent.getUiChildren()) {
- UiViewElementNode node = (UiViewElementNode) child;
- rankMap.put(node, index++);
- }
- for (CanvasViewInfo child : parentView.getChildren()) {
- infoMap.put(child.getUiViewNode(), child);
- }
- List<Integer> usedIndexes = new ArrayList<Integer>();
- for (UiViewElementNode node : unused) {
- Integer rank = rankMap.get(node);
- if (rank != null) {
- usedIndexes.add(rank);
- }
- }
- Collections.sort(usedIndexes);
- for (int i = usedIndexes.size() - 1; i >= 0; i--) {
- Integer rank = usedIndexes.get(i);
- UiViewElementNode found = null;
- for (UiViewElementNode node : unused) {
- if (rankMap.get(node) == rank) {
- found = node;
- break;
- }
- }
- if (found != null) {
- Rectangle absRect = new Rectangle(parentX, parentY, 0, 0);
- String name = found.getDescriptor().getXmlLocalName();
- CanvasViewInfo v = new CanvasViewInfo(parentView, name, null, found,
- absRect, absRect, null /* viewInfo */);
- // Find corresponding index in the parent view
- List<CanvasViewInfo> siblings = parentView.getChildren();
- int insertPosition = siblings.size();
- for (int j = siblings.size() - 1; j >= 0; j--) {
- CanvasViewInfo sibling = siblings.get(j);
- UiViewElementNode siblingNode = sibling.getUiViewNode();
- if (siblingNode != null) {
- Integer siblingRank = rankMap.get(siblingNode);
- if (siblingRank != null && siblingRank < rank) {
- insertPosition = j + 1;
- break;
- }
- }
- }
- parentView.addChildAt(insertPosition, v);
- unused.remove(found);
- }
- }
- }
- // Add in any remaining
- for (UiViewElementNode node : unused) {
- Rectangle absRect = new Rectangle(parentX, parentY, 0, 0);
- String name = node.getDescriptor().getXmlLocalName();
- CanvasViewInfo v = new CanvasViewInfo(parentView, name, null, node, absRect,
- absRect, null /* viewInfo */);
- parentView.addChild(v);
- }
- }
- }
-
- private boolean isBefore(UiViewElementNode beforeNode, UiViewElementNode candidate) {
- UiElementNode parent = candidate.getUiParent();
- if (parent != null) {
- for (UiElementNode sibling : parent.getUiChildren()) {
- if (sibling == beforeNode) {
- return false;
- } else if (sibling == candidate) {
- return true;
- }
- }
- }
- return false;
- }
-
- private boolean isAfter(UiViewElementNode afterNode, UiViewElementNode candidate) {
- UiElementNode parent = candidate.getUiParent();
- if (parent != null) {
- for (UiElementNode sibling : parent.getUiChildren()) {
- if (sibling == afterNode) {
- return true;
- } else if (sibling == candidate) {
- return false;
- }
- }
- }
- return false;
- }
-
- private UiViewElementNode nextViewNode(List<ViewInfo> children, int index) {
- int size = children.size();
- for (; index < size; index++) {
- ViewInfo child = children.get(index);
- if (child.getCookie() instanceof UiViewElementNode) {
- return (UiViewElementNode) child.getCookie();
- }
- }
-
- return null;
- }
-
- /** Search for a subtree with valid keys and add those subtrees */
- private CanvasViewInfo addKeyedSubtrees(CanvasViewInfo parent, ViewInfo viewInfo,
- int parentX, int parentY) {
- // We don't include MergeCookies when searching down for the first non-null key,
- // since this means we are in a "Show Included In" context, and the include tag itself
- // (which the merge cookie is pointing to) is still in the including-document rather
- // than the included document. Therefore, we only accept real UiViewElementNodes here,
- // not MergeCookies.
- if (viewInfo.getCookie() != null) {
- CanvasViewInfo subtree = createSubtree(parent, viewInfo, parentX, parentY);
- if (parent != null && subtree != null) {
- parent.mChildren.add(subtree);
- }
- return subtree;
- } else {
- for (ViewInfo child : viewInfo.getChildren()) {
- addKeyedSubtrees(parent, child, parentX + viewInfo.getLeft(), parentY
- + viewInfo.getTop());
- }
-
- return null;
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ClipboardSupport.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ClipboardSupport.java
deleted file mode 100644
index 263456984..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ClipboardSupport.java
+++ /dev/null
@@ -1,429 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.SdkConstants.ANDROID_NS_NAME;
-import static com.android.SdkConstants.NS_RESOURCES;
-import static com.android.SdkConstants.XMLNS_URI;
-
-import com.android.ide.common.api.IDragElement;
-import com.android.ide.common.api.IDragElement.IDragAttribute;
-import com.android.ide.common.api.INode;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.NodeProxy;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.RulesEngine;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiDocumentNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.dnd.TransferData;
-import org.eclipse.swt.widgets.Composite;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * The {@link ClipboardSupport} class manages the native clipboard, providing operations
- * to copy, cut and paste view items, and can answer whether the clipboard contains
- * a transferable we care about.
- */
-public class ClipboardSupport {
- private static final boolean DEBUG = false;
-
- /** SWT clipboard instance. */
- private Clipboard mClipboard;
- private LayoutCanvas mCanvas;
-
- /**
- * Constructs a new {@link ClipboardSupport} tied to the given
- * {@link LayoutCanvas}.
- *
- * @param canvas The {@link LayoutCanvas} to provide clipboard support for.
- * @param parent The parent widget in the SWT hierarchy of the canvas.
- */
- public ClipboardSupport(LayoutCanvas canvas, Composite parent) {
- mCanvas = canvas;
-
- mClipboard = new Clipboard(parent.getDisplay());
- }
-
- /**
- * Frees up any resources held by the {@link ClipboardSupport}.
- */
- public void dispose() {
- if (mClipboard != null) {
- mClipboard.dispose();
- mClipboard = null;
- }
- }
-
- /**
- * Perform the "Copy" action, either from the Edit menu or from the context
- * menu.
- * <p/>
- * This sanitizes the selection, so it must be a copy. It then inserts the
- * selection both as text and as {@link SimpleElement}s in the clipboard.
- * (If there is selected text in the error label, then the error is used
- * as the text portion of the transferable.)
- *
- * @param selection A list of selection items to add to the clipboard;
- * <b>this should be a copy already - this method will not make a
- * copy</b>
- */
- public void copySelectionToClipboard(List<SelectionItem> selection) {
- SelectionManager.sanitize(selection);
-
- // The error message area shares the copy action with the canvas. Invoking the
- // copy action when there are errors visible *AND* the user has selected text there,
- // should include the error message as the text transferable.
- String message = null;
- GraphicalEditorPart graphicalEditor = mCanvas.getEditorDelegate().getGraphicalEditor();
- StyledText errorLabel = graphicalEditor.getErrorLabel();
- if (errorLabel.getSelectionCount() > 0) {
- message = errorLabel.getSelectionText();
- }
-
- if (selection.isEmpty()) {
- if (message != null) {
- mClipboard.setContents(
- new Object[] { message },
- new Transfer[] { TextTransfer.getInstance() }
- );
- }
- return;
- }
-
- Object[] data = new Object[] {
- SelectionItem.getAsElements(selection),
- message != null ? message : SelectionItem.getAsText(mCanvas, selection)
- };
-
- Transfer[] types = new Transfer[] {
- SimpleXmlTransfer.getInstance(),
- TextTransfer.getInstance()
- };
-
- mClipboard.setContents(data, types);
- }
-
- /**
- * Perform the "Cut" action, either from the Edit menu or from the context
- * menu.
- * <p/>
- * This sanitizes the selection, so it must be a copy. It uses the
- * {@link #copySelectionToClipboard(List)} method to copy the selection to
- * the clipboard. Finally it uses {@link #deleteSelection(String, List)} to
- * delete the selection with a "Cut" verb for the title.
- *
- * @param selection A list of selection items to add to the clipboard;
- * <b>this should be a copy already - this method will not make a
- * copy</b>
- */
- public void cutSelectionToClipboard(List<SelectionItem> selection) {
- copySelectionToClipboard(selection);
- deleteSelection(mCanvas.getCutLabel(), selection);
- }
-
- /**
- * Deletes the given selection.
- *
- * @param verb A translated verb for the action. Will be used for the
- * undo/redo title. Typically this should be
- * {@link Action#getText()} for either the cut or the delete
- * actions in the canvas.
- * @param selection The selection. Must not be null. Can be empty, in which
- * case nothing happens. The selection list will be sanitized so
- * the caller should pass in a copy.
- */
- public void deleteSelection(String verb, final List<SelectionItem> selection) {
- SelectionManager.sanitize(selection);
-
- if (selection.isEmpty()) {
- return;
- }
-
- // If all selected items have the same *kind* of parent, display that in the undo title.
- String title = null;
- for (SelectionItem cs : selection) {
- CanvasViewInfo vi = cs.getViewInfo();
- if (vi != null && vi.getParent() != null) {
- CanvasViewInfo parent = vi.getParent();
- assert parent != null;
- if (title == null) {
- title = parent.getName();
- } else if (!title.equals(parent.getName())) {
- // More than one kind of parent selected.
- title = null;
- break;
- }
- }
- }
-
- if (title != null) {
- // Typically the name is an FQCN. Just get the last segment.
- int pos = title.lastIndexOf('.');
- if (pos > 0 && pos < title.length() - 1) {
- title = title.substring(pos + 1);
- }
- }
- boolean multiple = mCanvas.getSelectionManager().hasMultiSelection();
- if (title == null) {
- title = String.format(
- multiple ? "%1$s elements" : "%1$s element",
- verb);
- } else {
- title = String.format(
- multiple ? "%1$s elements from %2$s" : "%1$s element from %2$s",
- verb, title);
- }
-
- // Implementation note: we don't clear the internal selection after removing
- // the elements. An update XML model event should happen when the model gets released
- // which will trigger a recompute of the layout, thus reloading the model thus
- // resetting the selection.
- mCanvas.getEditorDelegate().getEditor().wrapUndoEditXmlModel(title, new Runnable() {
- @Override
- public void run() {
- // Segment the deleted nodes into clusters of siblings
- Map<NodeProxy, List<INode>> clusters =
- new HashMap<NodeProxy, List<INode>>();
- for (SelectionItem cs : selection) {
- NodeProxy node = cs.getNode();
- if (node == null) {
- continue;
- }
- INode parent = node.getParent();
- if (parent != null) {
- List<INode> children = clusters.get(parent);
- if (children == null) {
- children = new ArrayList<INode>();
- clusters.put((NodeProxy) parent, children);
- }
- children.add(node);
- }
- }
-
- // Notify parent views about children getting deleted
- RulesEngine rulesEngine = mCanvas.getRulesEngine();
- for (Map.Entry<NodeProxy, List<INode>> entry : clusters.entrySet()) {
- NodeProxy parent = entry.getKey();
- List<INode> children = entry.getValue();
- assert children != null && children.size() > 0;
- rulesEngine.callOnRemovingChildren(parent, children);
- parent.applyPendingChanges();
- }
-
- for (SelectionItem cs : selection) {
- CanvasViewInfo vi = cs.getViewInfo();
- // You can't delete the root element
- if (vi != null && !vi.isRoot()) {
- UiViewElementNode ui = vi.getUiViewNode();
- if (ui != null) {
- ui.deleteXmlNode();
- }
- }
- }
- }
- });
- }
-
- /**
- * Perform the "Paste" action, either from the Edit menu or from the context
- * menu.
- *
- * @param selection A list of selection items to add to the clipboard;
- * <b>this should be a copy already - this method will not make a
- * copy</b>
- */
- public void pasteSelection(List<SelectionItem> selection) {
-
- SimpleXmlTransfer sxt = SimpleXmlTransfer.getInstance();
- final SimpleElement[] pasted = (SimpleElement[]) mClipboard.getContents(sxt);
-
- if (pasted == null || pasted.length == 0) {
- return;
- }
-
- CanvasViewInfo lastRoot = mCanvas.getViewHierarchy().getRoot();
- if (lastRoot == null) {
- // Pasting in an empty document. Only paste the first element.
- pasteInEmptyDocument(pasted[0]);
- return;
- }
-
- // Otherwise use the current selection, if any, as a guide where to paste
- // using the first selected element only. If there's no selection use
- // the root as the insertion point.
- SelectionManager.sanitize(selection);
- final CanvasViewInfo target;
- if (selection.size() > 0) {
- SelectionItem cs = selection.get(0);
- target = cs.getViewInfo();
- } else {
- target = lastRoot;
- }
-
- final NodeProxy targetNode = mCanvas.getNodeFactory().create(target);
- mCanvas.getEditorDelegate().getEditor().wrapUndoEditXmlModel("Paste", new Runnable() {
- @Override
- public void run() {
- RulesEngine engine = mCanvas.getRulesEngine();
- NodeProxy node = engine.callOnPaste(targetNode, target.getViewObject(), pasted);
- node.applyPendingChanges();
- }
- });
- }
-
- /**
- * Paste a new root into an empty XML layout.
- * <p/>
- * In case of error (unknown FQCN, document not empty), silently do nothing.
- * In case of success, the new element will have some default attributes set (xmlns:android,
- * layout_width and height). The edit is wrapped in a proper undo.
- * <p/>
- * Implementation is similar to {@link #createDocumentRoot} except we also
- * copy all the attributes and inner elements recursively.
- */
- private void pasteInEmptyDocument(final IDragElement pastedElement) {
- String rootFqcn = pastedElement.getFqcn();
-
- // Need a valid empty document to create the new root
- final LayoutEditorDelegate delegate = mCanvas.getEditorDelegate();
- final UiDocumentNode uiDoc = delegate.getUiRootNode();
- if (uiDoc == null || uiDoc.getUiChildren().size() > 0) {
- debugPrintf("Failed to paste document root for %1$s: document is not empty", rootFqcn);
- return;
- }
-
- // Find the view descriptor matching our FQCN
- final ViewElementDescriptor viewDesc = delegate.getFqcnViewDescriptor(rootFqcn);
- if (viewDesc == null) {
- // TODO this could happen if pasting a custom view not known in this project
- debugPrintf("Failed to paste document root, unknown FQCN %1$s", rootFqcn);
- return;
- }
-
- // Get the last segment of the FQCN for the undo title
- String title = rootFqcn;
- int pos = title.lastIndexOf('.');
- if (pos > 0 && pos < title.length() - 1) {
- title = title.substring(pos + 1);
- }
- title = String.format("Paste root %1$s in document", title);
-
- delegate.getEditor().wrapUndoEditXmlModel(title, new Runnable() {
- @Override
- public void run() {
- UiElementNode uiNew = uiDoc.appendNewUiChild(viewDesc);
-
- // A root node requires the Android XMLNS
- uiNew.setAttributeValue(ANDROID_NS_NAME, XMLNS_URI, NS_RESOURCES,
- true /*override*/);
-
- // Copy all the attributes from the pasted element
- for (IDragAttribute attr : pastedElement.getAttributes()) {
- uiNew.setAttributeValue(
- attr.getName(),
- attr.getUri(),
- attr.getValue(),
- true /*override*/);
- }
-
- // Adjust the attributes, adding the default layout_width/height
- // only if they are not present (the original element should have
- // them though.)
- DescriptorsUtils.setDefaultLayoutAttributes(uiNew, false /*updateLayout*/);
-
- uiNew.createXmlNode();
-
- // Now process all children
- for (IDragElement childElement : pastedElement.getInnerElements()) {
- addChild(uiNew, childElement);
- }
- }
-
- private void addChild(UiElementNode uiParent, IDragElement childElement) {
- String childFqcn = childElement.getFqcn();
- final ViewElementDescriptor childDesc =
- delegate.getFqcnViewDescriptor(childFqcn);
- if (childDesc == null) {
- // TODO this could happen if pasting a custom view
- debugPrintf("Failed to paste element, unknown FQCN %1$s", childFqcn);
- return;
- }
-
- UiElementNode uiChild = uiParent.appendNewUiChild(childDesc);
-
- // Copy all the attributes from the pasted element
- for (IDragAttribute attr : childElement.getAttributes()) {
- uiChild.setAttributeValue(
- attr.getName(),
- attr.getUri(),
- attr.getValue(),
- true /*override*/);
- }
-
- // Adjust the attributes, adding the default layout_width/height
- // only if they are not present (the original element should have
- // them though.)
- DescriptorsUtils.setDefaultLayoutAttributes(
- uiChild, false /*updateLayout*/);
-
- uiChild.createXmlNode();
-
- // Now process all grand children
- for (IDragElement grandChildElement : childElement.getInnerElements()) {
- addChild(uiChild, grandChildElement);
- }
- }
- });
- }
-
- /**
- * Returns true if we have a a simple xml transfer data object on the
- * clipboard.
- *
- * @return True if and only if the clipboard contains one of XML element
- * objects.
- */
- public boolean hasSxtOnClipboard() {
- // The paste operation is only available if we can paste our custom type.
- // We do not currently support pasting random text (e.g. XML). Maybe later.
- SimpleXmlTransfer sxt = SimpleXmlTransfer.getInstance();
- for (TransferData td : mClipboard.getAvailableTypes()) {
- if (sxt.isSupportedType(td)) {
- return true;
- }
- }
-
- return false;
- }
-
- private void debugPrintf(String message, Object... params) {
- if (DEBUG) AdtPlugin.printToConsole("Clipboard", String.format(message, params));
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ControlPoint.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ControlPoint.java
deleted file mode 100644
index 55930f6cd..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ControlPoint.java
+++ /dev/null
@@ -1,195 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import org.eclipse.swt.dnd.DragSourceEvent;
-import org.eclipse.swt.dnd.DragSourceListener;
-import org.eclipse.swt.dnd.DropTargetEvent;
-import org.eclipse.swt.events.MenuDetectEvent;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseListener;
-import org.eclipse.swt.graphics.Point;
-
-/**
- * A {@link ControlPoint} is a coordinate in the canvas control which corresponds
- * exactly to (0,0) at the top left of the canvas. It is unaffected by canvas
- * zooming.
- */
-public final class ControlPoint {
- /** Containing canvas which the point is relative to. */
- private final LayoutCanvas mCanvas;
-
- /** The X coordinate of the mouse coordinate. */
- public final int x;
-
- /** The Y coordinate of the mouse coordinate. */
- public final int y;
-
- /**
- * Constructs a new {@link ControlPoint} from the given event. The event
- * must be from a {@link MouseListener} associated with the
- * {@link LayoutCanvas} such that the {@link MouseEvent#x} and
- * {@link MouseEvent#y} fields are relative to the canvas.
- *
- * @param canvas The {@link LayoutCanvas} this point is within.
- * @param event The mouse event to construct the {@link ControlPoint}
- * from.
- * @return A {@link ControlPoint} which corresponds to the given
- * {@link MouseEvent}.
- */
- public static ControlPoint create(LayoutCanvas canvas, MouseEvent event) {
- // The mouse event coordinates should already be relative to the canvas
- // widget.
- assert event.widget == canvas : event.widget;
- return new ControlPoint(canvas, event.x, event.y);
- }
-
- /**
- * Constructs a new {@link ControlPoint} from the given menu detect event.
- *
- * @param canvas The {@link LayoutCanvas} this point is within.
- * @param event The menu detect event to construct the {@link ControlPoint} from.
- * @return A {@link ControlPoint} which corresponds to the given
- * {@link MenuDetectEvent}.
- */
- public static ControlPoint create(LayoutCanvas canvas, MenuDetectEvent event) {
- // The menu detect events are always display-relative.
- org.eclipse.swt.graphics.Point p = canvas.toControl(event.x, event.y);
- return new ControlPoint(canvas, p.x, p.y);
- }
-
- /**
- * Constructs a new {@link ControlPoint} from the given event. The event
- * must be from a {@link DragSourceListener} associated with the
- * {@link LayoutCanvas} such that the {@link DragSourceEvent#x} and
- * {@link DragSourceEvent#y} fields are relative to the canvas.
- *
- * @param canvas The {@link LayoutCanvas} this point is within.
- * @param event The mouse event to construct the {@link ControlPoint}
- * from.
- * @return A {@link ControlPoint} which corresponds to the given
- * {@link DragSourceEvent}.
- */
- public static ControlPoint create(LayoutCanvas canvas, DragSourceEvent event) {
- // The drag source event coordinates should already be relative to the
- // canvas widget.
- return new ControlPoint(canvas, event.x, event.y);
- }
-
- /**
- * Constructs a new {@link ControlPoint} from the given event.
- *
- * @param canvas The {@link LayoutCanvas} this point is within.
- * @param event The mouse event to construct the {@link ControlPoint}
- * from.
- * @return A {@link ControlPoint} which corresponds to the given
- * {@link DropTargetEvent}.
- */
- public static ControlPoint create(LayoutCanvas canvas, DropTargetEvent event) {
- // The drop target events are always relative to the display, so we must
- // first convert them to be canvas relative.
- org.eclipse.swt.graphics.Point p = canvas.toControl(event.x, event.y);
- return new ControlPoint(canvas, p.x, p.y);
- }
-
- /**
- * Constructs a new {@link ControlPoint} from the given x,y coordinates,
- * which must be relative to the given {@link LayoutCanvas}.
- *
- * @param canvas The {@link LayoutCanvas} this point is within.
- * @param x The mouse event x coordinate relative to the canvas
- * @param y The mouse event x coordinate relative to the canvas
- * @return A {@link ControlPoint} which corresponds to the given
- * coordinates.
- */
- public static ControlPoint create(LayoutCanvas canvas, int x, int y) {
- return new ControlPoint(canvas, x, y);
- }
-
- /**
- * Constructs a new canvas control coordinate with the given X and Y
- * coordinates. This is private; use one of the factory methods
- * {@link #create(LayoutCanvas, MouseEvent)},
- * {@link #create(LayoutCanvas, DragSourceEvent)} or
- * {@link #create(LayoutCanvas, DropTargetEvent)} instead.
- *
- * @param canvas The canvas which contains this coordinate
- * @param x The mouse x coordinate
- * @param y The mouse y coordinate
- */
- private ControlPoint(LayoutCanvas canvas, int x, int y) {
- mCanvas = canvas;
- this.x = x;
- this.y = y;
- }
-
- /**
- * Returns the equivalent {@link LayoutPoint} to this
- * {@link ControlPoint}.
- *
- * @return The equivalent {@link LayoutPoint} to this
- * {@link ControlPoint}.
- */
- public LayoutPoint toLayout() {
- int lx = mCanvas.getHorizontalTransform().inverseTranslate(x);
- int ly = mCanvas.getVerticalTransform().inverseTranslate(y);
-
- return LayoutPoint.create(mCanvas, lx, ly);
- }
-
- @Override
- public String toString() {
- return "ControlPoint [x=" + x + ", y=" + y + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + x;
- result = prime * result + y;
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- ControlPoint other = (ControlPoint) obj;
- if (x != other.x)
- return false;
- if (y != other.y)
- return false;
- if (mCanvas != other.mCanvas) {
- return false;
- }
- return true;
- }
-
- /**
- * Returns this point as an SWT point in the display coordinate system
- *
- * @return this point as an SWT point in the display coordinate system
- */
- public Point toDisplayPoint() {
- return mCanvas.toDisplay(x, y);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/CreateNewConfigJob.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/CreateNewConfigJob.java
deleted file mode 100644
index 44cd0810f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/CreateNewConfigJob.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigurationChooser;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.resources.ResourceFolderType;
-import com.google.common.base.Charsets;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.PartInitException;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-
-/** Job which creates a new layout file for a given configuration */
-class CreateNewConfigJob extends Job {
- private final GraphicalEditorPart mEditor;
- private final IFile mFromFile;
- private final FolderConfiguration mConfig;
-
- CreateNewConfigJob(
- @NonNull GraphicalEditorPart editor,
- @NonNull IFile fromFile,
- @NonNull FolderConfiguration config) {
- super("Create Alternate Layout");
- mEditor = editor;
- mFromFile = fromFile;
- mConfig = config;
- }
-
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- // get the folder name
- String folderName = mConfig.getFolderName(ResourceFolderType.LAYOUT);
- try {
- // look to see if it exists.
- // get the res folder
- IFolder res = (IFolder) mFromFile.getParent().getParent();
-
- IFolder newParentFolder = res.getFolder(folderName);
- AdtUtils.ensureExists(newParentFolder);
- final IFile file = newParentFolder.getFile(mFromFile.getName());
- if (file.exists()) {
- String message = String.format("File 'res/%1$s/%2$s' already exists!",
- folderName, mFromFile.getName());
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, message);
- }
-
- // Read current document contents instead of from file: mFromFile.getContents()
- String text = mEditor.getEditorDelegate().getEditor().getStructuredDocument().get();
- ByteArrayInputStream input = new ByteArrayInputStream(text.getBytes(Charsets.UTF_8));
- file.create(input, false, monitor);
- input.close();
-
- // Ensure that the project resources updates itself to notice the new configuration.
- // In theory, this shouldn't be necessary, but we need to make sure the
- // resource manager knows about this immediately such that the call below
- // to find the best configuration takes the new folder into account.
- ResourceManager resourceManager = ResourceManager.getInstance();
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- IFolder folder = root.getFolder(newParentFolder.getFullPath());
- resourceManager.getResourceFolder(folder);
-
- // Switch to the new file
- Display display = mEditor.getConfigurationChooser().getDisplay();
- display.asyncExec(new Runnable() {
- @Override
- public void run() {
- // The given old layout has been forked into a new layout
- // for a given configuration. This means that the old layout
- // is no longer a match for the configuration, which is
- // probably what it is still showing. We have to modify
- // its configuration to no longer be an impossible
- // configuration.
- ConfigurationChooser chooser = mEditor.getConfigurationChooser();
- chooser.onAlternateLayoutCreated();
-
- // Finally open the new layout
- try {
- AdtPlugin.openFile(file, null, false);
- } catch (PartInitException e) {
- AdtPlugin.log(e, null);
- }
- }
- });
- } catch (IOException e2) {
- String message = String.format(
- "Failed to create File 'res/%1$s/%2$s' : %3$s",
- folderName, mFromFile.getName(), e2.getMessage());
- AdtPlugin.displayError("Layout Creation", message);
-
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- message, e2);
- } catch (CoreException e2) {
- String message = String.format(
- "Failed to create File 'res/%1$s/%2$s' : %3$s",
- folderName, mFromFile.getName(), e2.getMessage());
- AdtPlugin.displayError("Layout Creation", message);
-
- return e2.getStatus();
- }
-
- return Status.OK_STATUS;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/CustomViewFinder.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/CustomViewFinder.java
deleted file mode 100644
index 1f97c8c54..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/CustomViewFinder.java
+++ /dev/null
@@ -1,395 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.SdkConstants.CLASS_VIEW;
-import static com.android.SdkConstants.CLASS_VIEWGROUP;
-import static com.android.SdkConstants.FN_FRAMEWORK_LIBRARY;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.utils.Pair;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.QualifiedName;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jdt.core.Flags;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IMethod;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.core.search.IJavaSearchConstants;
-import org.eclipse.jdt.core.search.IJavaSearchScope;
-import org.eclipse.jdt.core.search.SearchEngine;
-import org.eclipse.jdt.core.search.SearchMatch;
-import org.eclipse.jdt.core.search.SearchParticipant;
-import org.eclipse.jdt.core.search.SearchPattern;
-import org.eclipse.jdt.core.search.SearchRequestor;
-import org.eclipse.jdt.internal.core.ResolvedBinaryType;
-import org.eclipse.jdt.internal.core.ResolvedSourceType;
-import org.eclipse.swt.widgets.Display;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * The {@link CustomViewFinder} can look up the custom views and third party views
- * available for a given project.
- */
-@SuppressWarnings("restriction") // JDT model access for custom-view class lookup
-public class CustomViewFinder {
- /**
- * Qualified name for the per-project non-persistent property storing the
- * {@link CustomViewFinder} for this project
- */
- private final static QualifiedName CUSTOM_VIEW_FINDER = new QualifiedName(AdtPlugin.PLUGIN_ID,
- "viewfinder"); //$NON-NLS-1$
-
- /** Project that this view finder locates views for */
- private final IProject mProject;
-
- private final List<Listener> mListeners = new ArrayList<Listener>();
-
- private List<String> mCustomViews;
- private List<String> mThirdPartyViews;
- private boolean mRefreshing;
-
- /**
- * Constructs an {@link CustomViewFinder} for the given project. Don't use this method;
- * use the {@link #get} factory method instead.
- *
- * @param project project to create an {@link CustomViewFinder} for
- */
- private CustomViewFinder(IProject project) {
- mProject = project;
- }
-
- /**
- * Returns the {@link CustomViewFinder} for the given project
- *
- * @param project the project the finder is associated with
- * @return a {@CustomViewFinder} for the given project, never null
- */
- public static CustomViewFinder get(IProject project) {
- CustomViewFinder finder = null;
- try {
- finder = (CustomViewFinder) project.getSessionProperty(CUSTOM_VIEW_FINDER);
- } catch (CoreException e) {
- // Not a problem; we will just create a new one
- }
-
- if (finder == null) {
- finder = new CustomViewFinder(project);
- try {
- project.setSessionProperty(CUSTOM_VIEW_FINDER, finder);
- } catch (CoreException e) {
- AdtPlugin.log(e, "Can't store CustomViewFinder");
- }
- }
-
- return finder;
- }
-
- public void refresh() {
- refresh(null /*listener*/, true /* sync */);
- }
-
- public void refresh(final Listener listener) {
- refresh(listener, false /* sync */);
- }
-
- private void refresh(final Listener listener, boolean sync) {
- // Add this listener to the list of listeners which should be notified when the
- // search is done. (There could be more than one since multiple requests could
- // arrive for a slow search since the search is run in a different thread).
- if (listener != null) {
- synchronized (this) {
- mListeners.add(listener);
- }
- }
- synchronized (this) {
- if (listener != null) {
- mListeners.add(listener);
- }
- if (mRefreshing) {
- return;
- }
- mRefreshing = true;
- }
-
- FindViewsJob job = new FindViewsJob();
- job.schedule();
- if (sync) {
- try {
- job.join();
- } catch (InterruptedException e) {
- AdtPlugin.log(e, null);
- }
- }
- }
-
- public Collection<String> getCustomViews() {
- return mCustomViews == null ? null : Collections.unmodifiableCollection(mCustomViews);
- }
-
- public Collection<String> getThirdPartyViews() {
- return mThirdPartyViews == null
- ? null : Collections.unmodifiableCollection(mThirdPartyViews);
- }
-
- public Collection<String> getAllViews() {
- // Not yet initialized: return null
- if (mCustomViews == null) {
- return null;
- }
- List<String> all = new ArrayList<String>(mCustomViews.size() + mThirdPartyViews.size());
- all.addAll(mCustomViews);
- all.addAll(mThirdPartyViews);
- return all;
- }
-
- /**
- * Returns a pair of view lists - the custom views and the 3rd-party views.
- * This method performs no caching; it is the same as asking the custom view finder
- * to refresh itself and then waiting for the answer and returning it.
- *
- * @param project the Android project
- * @param layoutsOnly if true, only search for layouts
- * @return a pair of lists, the first containing custom views and the second
- * containing 3rd party views
- */
- public static Pair<List<String>,List<String>> findViews(
- final IProject project, boolean layoutsOnly) {
- CustomViewFinder finder = get(project);
-
- return finder.findViews(layoutsOnly);
- }
-
- private Pair<List<String>,List<String>> findViews(final boolean layoutsOnly) {
- final Set<String> customViews = new HashSet<String>();
- final Set<String> thirdPartyViews = new HashSet<String>();
-
- ProjectState state = Sdk.getProjectState(mProject);
- final List<IProject> libraries = state != null
- ? state.getFullLibraryProjects() : Collections.<IProject>emptyList();
-
- SearchRequestor requestor = new SearchRequestor() {
- @Override
- public void acceptSearchMatch(SearchMatch match) throws CoreException {
- // Ignore matches in comments
- if (match.isInsideDocComment()) {
- return;
- }
-
- Object element = match.getElement();
- if (element instanceof ResolvedBinaryType) {
- // Third party view
- ResolvedBinaryType type = (ResolvedBinaryType) element;
- IPackageFragment fragment = type.getPackageFragment();
- IPath path = fragment.getPath();
- String last = path.lastSegment();
- // Filter out android.jar stuff
- if (last.equals(FN_FRAMEWORK_LIBRARY)) {
- return;
- }
- if (!isValidView(type, layoutsOnly)) {
- return;
- }
-
- IProject matchProject = match.getResource().getProject();
- if (mProject == matchProject || libraries.contains(matchProject)) {
- String fqn = type.getFullyQualifiedName();
- thirdPartyViews.add(fqn);
- }
- } else if (element instanceof ResolvedSourceType) {
- // User custom view
- IProject matchProject = match.getResource().getProject();
- if (mProject == matchProject || libraries.contains(matchProject)) {
- ResolvedSourceType type = (ResolvedSourceType) element;
- if (!isValidView(type, layoutsOnly)) {
- return;
- }
- String fqn = type.getFullyQualifiedName();
- fqn = fqn.replace('$', '.');
- customViews.add(fqn);
- }
- }
- }
- };
- try {
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(mProject);
- if (javaProject != null) {
- String className = layoutsOnly ? CLASS_VIEWGROUP : CLASS_VIEW;
- IType viewType = javaProject.findType(className);
- if (viewType != null) {
- IJavaSearchScope scope = SearchEngine.createHierarchyScope(viewType);
- SearchParticipant[] participants = new SearchParticipant[] {
- SearchEngine.getDefaultSearchParticipant()
- };
- int matchRule = SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE;
-
- SearchPattern pattern = SearchPattern.createPattern("*",
- IJavaSearchConstants.CLASS, IJavaSearchConstants.IMPLEMENTORS,
- matchRule);
- SearchEngine engine = new SearchEngine();
- engine.search(pattern, participants, scope, requestor,
- new NullProgressMonitor());
- }
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
-
-
- List<String> custom = new ArrayList<String>(customViews);
- List<String> thirdParty = new ArrayList<String>(thirdPartyViews);
-
- if (!layoutsOnly) {
- // Update our cached answers (unless we were filtered on only layouts)
- mCustomViews = custom;
- mThirdPartyViews = thirdParty;
- }
-
- return Pair.of(custom, thirdParty);
- }
-
- /**
- * Determines whether the given member is a valid android.view.View to be added to the
- * list of custom views or third party views. It checks that the view is public and
- * not abstract for example.
- */
- private static boolean isValidView(IType type, boolean layoutsOnly)
- throws JavaModelException {
- // Skip anonymous classes
- if (type.isAnonymous()) {
- return false;
- }
- int flags = type.getFlags();
- if (Flags.isAbstract(flags) || !Flags.isPublic(flags)) {
- return false;
- }
-
- // TODO: if (layoutsOnly) perhaps try to filter out AdapterViews and other ViewGroups
- // not willing to accept children via XML
-
- // See if the class has one of the acceptable constructors
- // needed for XML instantiation:
- // View(Context context)
- // View(Context context, AttributeSet attrs)
- // View(Context context, AttributeSet attrs, int defStyle)
- // We don't simply do three direct checks via type.getMethod() because the types
- // are not resolved, so we don't know for each parameter if we will get the
- // fully qualified or the unqualified class names.
- // Instead, iterate over the methods and look for a match.
- String typeName = type.getElementName();
- for (IMethod method : type.getMethods()) {
- // Only care about constructors
- if (!method.getElementName().equals(typeName)) {
- continue;
- }
-
- String[] parameterTypes = method.getParameterTypes();
- if (parameterTypes == null || parameterTypes.length < 1 || parameterTypes.length > 3) {
- continue;
- }
-
- String first = parameterTypes[0];
- // Look for the parameter type signatures -- produced by
- // JDT's Signature.createTypeSignature("Context", false /*isResolved*/);.
- // This is not a typo; they were copy/pasted from the actual parameter names
- // observed in the debugger examining these data structures.
- if (first.equals("QContext;") //$NON-NLS-1$
- || first.equals("Qandroid.content.Context;")) { //$NON-NLS-1$
- if (parameterTypes.length == 1) {
- return true;
- }
- String second = parameterTypes[1];
- if (second.equals("QAttributeSet;") //$NON-NLS-1$
- || second.equals("Qandroid.util.AttributeSet;")) { //$NON-NLS-1$
- if (parameterTypes.length == 2) {
- return true;
- }
- String third = parameterTypes[2];
- if (third.equals("I")) { //$NON-NLS-1$
- if (parameterTypes.length == 3) {
- return true;
- }
- }
- }
- }
- }
-
- return false;
- }
-
- /**
- * Interface implemented by clients of the {@link CustomViewFinder} to be notified
- * when a custom view search has completed. Will always be called on the SWT event
- * dispatch thread.
- */
- public interface Listener {
- void viewsUpdated(Collection<String> customViews, Collection<String> thirdPartyViews);
- }
-
- /**
- * Job for performing class search off the UI thread. This is marked as a system job
- * so that it won't show up in the progress monitor etc.
- */
- private class FindViewsJob extends Job {
- FindViewsJob() {
- super("Find Custom Views");
- setSystem(true);
- }
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- Pair<List<String>, List<String>> views = findViews(false);
- mCustomViews = views.getFirst();
- mThirdPartyViews = views.getSecond();
-
- // Notify listeners on SWT's UI thread
- Display.getDefault().asyncExec(new Runnable() {
- @Override
- public void run() {
- Collection<String> customViews =
- Collections.unmodifiableCollection(mCustomViews);
- Collection<String> thirdPartyViews =
- Collections.unmodifiableCollection(mThirdPartyViews);
- synchronized (this) {
- for (Listener l : mListeners) {
- l.viewsUpdated(customViews, thirdPartyViews);
- }
- mListeners.clear();
- mRefreshing = false;
- }
- }
- });
- return Status.OK_STATUS;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/DelegatingAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/DelegatingAction.java
deleted file mode 100644
index 7a41b5b15..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/DelegatingAction.java
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.annotations.NonNull;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuCreator;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.swt.events.HelpListener;
-import org.eclipse.swt.widgets.Event;
-
-/**
- * Implementation of {@link IAction} which delegates to a different
- * {@link IAction} which allows a subclass to wrap and customize some of the
- * behavior of a different action
- */
-public class DelegatingAction implements IAction {
- private final IAction mAction;
-
- /**
- * Construct a new delegate of the given action
- *
- * @param action the action to be delegated
- */
- public DelegatingAction(@NonNull IAction action) {
- mAction = action;
- }
-
- @Override
- public void addPropertyChangeListener(IPropertyChangeListener listener) {
- mAction.addPropertyChangeListener(listener);
- }
-
- @Override
- public int getAccelerator() {
- return mAction.getAccelerator();
- }
-
- @Override
- public String getActionDefinitionId() {
- return mAction.getActionDefinitionId();
- }
-
- @Override
- public String getDescription() {
- return mAction.getDescription();
- }
-
- @Override
- public ImageDescriptor getDisabledImageDescriptor() {
- return mAction.getDisabledImageDescriptor();
- }
-
- @Override
- public HelpListener getHelpListener() {
- return mAction.getHelpListener();
- }
-
- @Override
- public ImageDescriptor getHoverImageDescriptor() {
- return mAction.getHoverImageDescriptor();
- }
-
- @Override
- public String getId() {
- return mAction.getId();
- }
-
- @Override
- public ImageDescriptor getImageDescriptor() {
- return mAction.getImageDescriptor();
- }
-
- @Override
- public IMenuCreator getMenuCreator() {
- return mAction.getMenuCreator();
- }
-
- @Override
- public int getStyle() {
- return mAction.getStyle();
- }
-
- @Override
- public String getText() {
- return mAction.getText();
- }
-
- @Override
- public String getToolTipText() {
- return mAction.getToolTipText();
- }
-
- @Override
- public boolean isChecked() {
- return mAction.isChecked();
- }
-
- @Override
- public boolean isEnabled() {
- return mAction.isEnabled();
- }
-
- @Override
- public boolean isHandled() {
- return mAction.isHandled();
- }
-
- @Override
- public void removePropertyChangeListener(IPropertyChangeListener listener) {
- mAction.removePropertyChangeListener(listener);
- }
-
- @Override
- public void run() {
- mAction.run();
- }
-
- @Override
- public void runWithEvent(Event event) {
- mAction.runWithEvent(event);
- }
-
- @Override
- public void setActionDefinitionId(String id) {
- mAction.setActionDefinitionId(id);
- }
-
- @Override
- public void setChecked(boolean checked) {
- mAction.setChecked(checked);
- }
-
- @Override
- public void setDescription(String text) {
- mAction.setDescription(text);
- }
-
- @Override
- public void setDisabledImageDescriptor(ImageDescriptor newImage) {
- mAction.setDisabledImageDescriptor(newImage);
- }
-
- @Override
- public void setEnabled(boolean enabled) {
- mAction.setEnabled(enabled);
- }
-
- @Override
- public void setHelpListener(HelpListener listener) {
- mAction.setHelpListener(listener);
- }
-
- @Override
- public void setHoverImageDescriptor(ImageDescriptor newImage) {
- mAction.setHoverImageDescriptor(newImage);
- }
-
- @Override
- public void setId(String id) {
- mAction.setId(id);
- }
-
- @Override
- public void setImageDescriptor(ImageDescriptor newImage) {
- mAction.setImageDescriptor(newImage);
- }
-
- @Override
- public void setMenuCreator(IMenuCreator creator) {
- mAction.setMenuCreator(creator);
- }
-
- @Override
- public void setText(String text) {
- mAction.setText(text);
- }
-
- @Override
- public void setToolTipText(String text) {
- mAction.setToolTipText(text);
- }
-
- @Override
- public void setAccelerator(int keycode) {
- mAction.setAccelerator(keycode);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/DomUtilities.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/DomUtilities.java
deleted file mode 100644
index 145036bf3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/DomUtilities.java
+++ /dev/null
@@ -1,915 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ID_PREFIX;
-import static com.android.SdkConstants.NEW_ID_PREFIX;
-import static com.android.SdkConstants.TOOLS_URI;
-import static org.eclipse.wst.xml.core.internal.provisional.contenttype.ContentTypeIdForXML.ContentTypeID_XML;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.utils.Pair;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.wst.sse.core.StructuredModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
-import org.eclipse.wst.xml.core.internal.regions.DOMRegionContext;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.InputSource;
-
-import java.io.StringReader;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Locale;
-import java.util.Set;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-
-/**
- * Various utility methods for manipulating DOM nodes.
- */
-@SuppressWarnings("restriction") // No replacement for restricted XML model yet
-public class DomUtilities {
- /**
- * Finds the nearest common parent of the two given nodes (which could be one of the
- * two nodes as well)
- *
- * @param node1 the first node to test
- * @param node2 the second node to test
- * @return the nearest common parent of the two given nodes
- */
- @Nullable
- public static Node getCommonAncestor(@NonNull Node node1, @NonNull Node node2) {
- while (node2 != null) {
- Node current = node1;
- while (current != null && current != node2) {
- current = current.getParentNode();
- }
- if (current == node2) {
- return current;
- }
- node2 = node2.getParentNode();
- }
-
- return null;
- }
-
- /**
- * Returns all elements below the given node (which can be a document,
- * element, etc). This will include the node itself, if it is an element.
- *
- * @param node the node to search from
- * @return all elements in the subtree formed by the node parameter
- */
- @NonNull
- public static List<Element> getAllElements(@NonNull Node node) {
- List<Element> elements = new ArrayList<Element>(64);
- addElements(node, elements);
- return elements;
- }
-
- private static void addElements(@NonNull Node node, @NonNull List<Element> elements) {
- if (node instanceof Element) {
- elements.add((Element) node);
- }
-
- NodeList childNodes = node.getChildNodes();
- for (int i = 0, n = childNodes.getLength(); i < n; i++) {
- addElements(childNodes.item(i), elements);
- }
- }
-
- /**
- * Returns the depth of the given node (with the document node having depth 0,
- * and the document element having depth 1)
- *
- * @param node the node to test
- * @return the depth in the document
- */
- public static int getDepth(@NonNull Node node) {
- int depth = -1;
- while (node != null) {
- depth++;
- node = node.getParentNode();
- }
-
- return depth;
- }
-
- /**
- * Returns true if the given node has one or more element children
- *
- * @param node the node to test for element children
- * @return true if the node has one or more element children
- */
- public static boolean hasElementChildren(@NonNull Node node) {
- NodeList children = node.getChildNodes();
- for (int i = 0, n = children.getLength(); i < n; i++) {
- if (children.item(i).getNodeType() == Node.ELEMENT_NODE) {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Returns the DOM document for the given file
- *
- * @param file the XML file
- * @return the document, or null if not found or not parsed properly (no
- * errors are generated/thrown)
- */
- @Nullable
- public static Document getDocument(@NonNull IFile file) {
- IModelManager modelManager = StructuredModelManager.getModelManager();
- if (modelManager == null) {
- return null;
- }
- try {
- IStructuredModel model = modelManager.getExistingModelForRead(file);
- if (model == null) {
- model = modelManager.getModelForRead(file);
- }
- if (model != null) {
- if (model instanceof IDOMModel) {
- IDOMModel domModel = (IDOMModel) model;
- return domModel.getDocument();
- }
- try {
- } finally {
- model.releaseFromRead();
- }
- }
- } catch (Exception e) {
- // Ignore exceptions.
- }
-
- return null;
- }
-
- /**
- * Returns the DOM document for the given editor
- *
- * @param editor the XML editor
- * @return the document, or null if not found or not parsed properly (no
- * errors are generated/thrown)
- */
- @Nullable
- public static Document getDocument(@NonNull AndroidXmlEditor editor) {
- IStructuredModel model = editor.getModelForRead();
- try {
- if (model instanceof IDOMModel) {
- IDOMModel domModel = (IDOMModel) model;
- return domModel.getDocument();
- }
- } finally {
- if (model != null) {
- model.releaseFromRead();
- }
- }
-
- return null;
- }
-
-
- /**
- * Returns the XML DOM node corresponding to the given offset of the given
- * document.
- *
- * @param document The document to look in
- * @param offset The offset to look up the node for
- * @return The node containing the offset, or null
- */
- @Nullable
- public static Node getNode(@NonNull IDocument document, int offset) {
- Node node = null;
- IModelManager modelManager = StructuredModelManager.getModelManager();
- if (modelManager == null) {
- return null;
- }
- try {
- IStructuredModel model = modelManager.getExistingModelForRead(document);
- if (model != null) {
- try {
- for (; offset >= 0 && node == null; --offset) {
- node = (Node) model.getIndexedRegion(offset);
- }
- } finally {
- model.releaseFromRead();
- }
- }
- } catch (Exception e) {
- // Ignore exceptions.
- }
-
- return node;
- }
-
- /**
- * Returns the editing context at the given offset, as a pair of parent node and child
- * node. This is not the same as just calling {@link DomUtilities#getNode} and taking
- * its parent node, because special care has to be taken to return content element
- * positions.
- * <p>
- * For example, for the XML {@code <foo>^</foo>}, if the caret ^ is inside the foo
- * element, between the opening and closing tags, then the foo element is the parent,
- * and the child is null which represents a potential text node.
- * <p>
- * If the node is inside an element tag definition (between the opening and closing
- * bracket) then the child node will be the element and whatever parent (element or
- * document) will be its parent.
- * <p>
- * If the node is in a text node, then the text node will be the child and its parent
- * element or document node its parent.
- * <p>
- * Finally, if the caret is on a boundary of a text node, then the text node will be
- * considered the child, regardless of whether it is on the left or right of the
- * caret. For example, in the XML {@code <foo>^ </foo>} and in the XML
- * {@code <foo> ^</foo>}, in both cases the text node is preferred over the element.
- *
- * @param document the document to search in
- * @param offset the offset to look up
- * @return a pair of parent and child elements, where either the parent or the child
- * but not both can be null, and if non null the child.getParentNode() should
- * return the parent. Note that the method can also return null if no
- * document or model could be obtained or if the offset is invalid.
- */
- @Nullable
- public static Pair<Node, Node> getNodeContext(@NonNull IDocument document, int offset) {
- Node node = null;
- IModelManager modelManager = StructuredModelManager.getModelManager();
- if (modelManager == null) {
- return null;
- }
- try {
- IStructuredModel model = modelManager.getExistingModelForRead(document);
- if (model != null) {
- try {
- for (; offset >= 0 && node == null; --offset) {
- IndexedRegion indexedRegion = model.getIndexedRegion(offset);
- if (indexedRegion != null) {
- node = (Node) indexedRegion;
-
- if (node.getNodeType() == Node.TEXT_NODE) {
- return Pair.of(node.getParentNode(), node);
- }
-
- // Look at the structured document to see if
- // we have the special case where the caret is pointing at
- // a -potential- text node, e.g. <foo>^</foo>
- IStructuredDocument doc = model.getStructuredDocument();
- IStructuredDocumentRegion region =
- doc.getRegionAtCharacterOffset(offset);
-
- ITextRegion subRegion = region.getRegionAtCharacterOffset(offset);
- String type = subRegion.getType();
- if (DOMRegionContext.XML_END_TAG_OPEN.equals(type)) {
- // Try to return the text node if it's on the left
- // of this element node, such that replace strings etc
- // can be computed.
- Node lastChild = node.getLastChild();
- if (lastChild != null) {
- IndexedRegion previousRegion = (IndexedRegion) lastChild;
- if (previousRegion.getEndOffset() == offset) {
- return Pair.of(node, lastChild);
- }
- }
- return Pair.of(node, null);
- }
-
- return Pair.of(node.getParentNode(), node);
- }
- }
- } finally {
- model.releaseFromRead();
- }
- }
- } catch (Exception e) {
- // Ignore exceptions.
- }
-
- return null;
- }
-
- /**
- * Like {@link #getNode(IDocument, int)}, but has a bias parameter which lets you
- * indicate whether you want the search to look forwards or backwards.
- * This is vital when trying to compute a node range. Consider the following
- * XML fragment:
- * {@code
- * <a/><b/>[<c/><d/><e/>]<f/><g/>
- * }
- * Suppose we want to locate the nodes in the range indicated by the brackets above.
- * If we want to search for the node corresponding to the start position, should
- * we pick the node on its left or the node on its right? Similarly for the end
- * position. Clearly, we'll need to bias the search towards the right when looking
- * for the start position, and towards the left when looking for the end position.
- * The following method lets us do just that. When passed an offset which sits
- * on the edge of the computed node, it will pick the neighbor based on whether
- * "forward" is true or false, where forward means searching towards the right
- * and not forward is obviously towards the left.
- * @param document the document to search in
- * @param offset the offset to search for
- * @param forward if true, search forwards, otherwise search backwards when on node boundaries
- * @return the node which surrounds the given offset, or the node adjacent to the offset
- * where the side depends on the forward parameter
- */
- @Nullable
- public static Node getNode(@NonNull IDocument document, int offset, boolean forward) {
- Node node = getNode(document, offset);
-
- if (node instanceof IndexedRegion) {
- IndexedRegion region = (IndexedRegion) node;
-
- if (!forward && offset <= region.getStartOffset()) {
- Node left = node.getPreviousSibling();
- if (left == null) {
- left = node.getParentNode();
- }
-
- node = left;
- } else if (forward && offset >= region.getEndOffset()) {
- Node right = node.getNextSibling();
- if (right == null) {
- right = node.getParentNode();
- }
- node = right;
- }
- }
-
- return node;
- }
-
- /**
- * Returns a range of elements for the given caret range. Note that the two elements
- * may not be at the same level so callers may want to perform additional input
- * filtering.
- *
- * @param document the document to search in
- * @param beginOffset the beginning offset of the range
- * @param endOffset the ending offset of the range
- * @return a pair of begin+end elements, or null
- */
- @Nullable
- public static Pair<Element, Element> getElementRange(@NonNull IDocument document,
- int beginOffset, int endOffset) {
- Element beginElement = null;
- Element endElement = null;
- Node beginNode = getNode(document, beginOffset, true);
- Node endNode = beginNode;
- if (endOffset > beginOffset) {
- endNode = getNode(document, endOffset, false);
- }
-
- if (beginNode == null || endNode == null) {
- return null;
- }
-
- // Adjust offsets if you're pointing at text
- if (beginNode.getNodeType() != Node.ELEMENT_NODE) {
- // <foo> <bar1/> | <bar2/> </foo> => should pick <bar2/>
- beginElement = getNextElement(beginNode);
- if (beginElement == null) {
- // Might be inside the end of a parent, e.g.
- // <foo> <bar/> | </foo> => should pick <bar/>
- beginElement = getPreviousElement(beginNode);
- if (beginElement == null) {
- // We must be inside an empty element,
- // <foo> | </foo>
- // In that case just pick the parent.
- beginElement = getParentElement(beginNode);
- }
- }
- } else {
- beginElement = (Element) beginNode;
- }
-
- if (endNode.getNodeType() != Node.ELEMENT_NODE) {
- // In the following, | marks the caret position:
- // <foo> <bar1/> | <bar2/> </foo> => should pick <bar1/>
- endElement = getPreviousElement(endNode);
- if (endElement == null) {
- // Might be inside the beginning of a parent, e.g.
- // <foo> | <bar/></foo> => should pick <bar/>
- endElement = getNextElement(endNode);
- if (endElement == null) {
- // We must be inside an empty element,
- // <foo> | </foo>
- // In that case just pick the parent.
- endElement = getParentElement(endNode);
- }
- }
- } else {
- endElement = (Element) endNode;
- }
-
- if (beginElement != null && endElement != null) {
- return Pair.of(beginElement, endElement);
- }
-
- return null;
- }
-
- /**
- * Returns the next sibling element of the node, or null if there is no such element
- *
- * @param node the starting node
- * @return the next sibling element, or null
- */
- @Nullable
- public static Element getNextElement(@NonNull Node node) {
- while (node != null && node.getNodeType() != Node.ELEMENT_NODE) {
- node = node.getNextSibling();
- }
-
- return (Element) node; // may be null as well
- }
-
- /**
- * Returns the previous sibling element of the node, or null if there is no such element
- *
- * @param node the starting node
- * @return the previous sibling element, or null
- */
- @Nullable
- public static Element getPreviousElement(@NonNull Node node) {
- while (node != null && node.getNodeType() != Node.ELEMENT_NODE) {
- node = node.getPreviousSibling();
- }
-
- return (Element) node; // may be null as well
- }
-
- /**
- * Returns the closest ancestor element, or null if none
- *
- * @param node the starting node
- * @return the closest parent element, or null
- */
- @Nullable
- public static Element getParentElement(@NonNull Node node) {
- while (node != null && node.getNodeType() != Node.ELEMENT_NODE) {
- node = node.getParentNode();
- }
-
- return (Element) node; // may be null as well
- }
-
- /** Utility used by {@link #getFreeWidgetId(Element)} */
- private static void addLowercaseIds(@NonNull Element root, @NonNull Set<String> seen) {
- if (root.hasAttributeNS(ANDROID_URI, ATTR_ID)) {
- String id = root.getAttributeNS(ANDROID_URI, ATTR_ID);
- if (id.startsWith(NEW_ID_PREFIX)) {
- // See getFreeWidgetId for details on locale
- seen.add(id.substring(NEW_ID_PREFIX.length()).toLowerCase(Locale.US));
- } else if (id.startsWith(ID_PREFIX)) {
- seen.add(id.substring(ID_PREFIX.length()).toLowerCase(Locale.US));
- } else {
- seen.add(id.toLowerCase(Locale.US));
- }
- }
- }
-
- /**
- * Returns a suitable new widget id (not including the {@code @id/} prefix) for the
- * given element, which is guaranteed to be unique in this document
- *
- * @param element the element to compute a new widget id for
- * @param reserved an optional set of extra, "reserved" set of ids that should be
- * considered taken
- * @param prefix an optional prefix to use for the generated name, or null to get a
- * default (which is currently the tag name)
- * @return a unique id, never null, which does not include the {@code @id/} prefix
- * @see DescriptorsUtils#getFreeWidgetId
- */
- public static String getFreeWidgetId(
- @NonNull Element element,
- @Nullable Set<String> reserved,
- @Nullable String prefix) {
- Set<String> ids = new HashSet<String>();
- if (reserved != null) {
- for (String id : reserved) {
- // Note that we perform locale-independent lowercase checks; in "Image" we
- // want the lowercase version to be "image", not "?mage" where ? is
- // the char LATIN SMALL LETTER DOTLESS I.
-
- ids.add(id.toLowerCase(Locale.US));
- }
- }
- addLowercaseIds(element.getOwnerDocument().getDocumentElement(), ids);
-
- if (prefix == null) {
- prefix = DescriptorsUtils.getBasename(element.getTagName());
- }
- String generated;
- int num = 1;
- do {
- generated = String.format("%1$s%2$d", prefix, num++); //$NON-NLS-1$
- } while (ids.contains(generated.toLowerCase(Locale.US)));
-
- return generated;
- }
-
- /**
- * Returns the element children of the given element
- *
- * @param element the parent element
- * @return a list of child elements, possibly empty but never null
- */
- @NonNull
- public static List<Element> getChildren(@NonNull Element element) {
- // Convenience to avoid lots of ugly DOM access casting
- NodeList children = element.getChildNodes();
- // An iterator would have been more natural (to directly drive the child list
- // iteration) but iterators can't be used in enhanced for loops...
- List<Element> result = new ArrayList<Element>(children.getLength());
- for (int i = 0, n = children.getLength(); i < n; i++) {
- Node node = children.item(i);
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- Element child = (Element) node;
- result.add(child);
- }
- }
-
- return result;
- }
-
- /**
- * Returns true iff the given elements are contiguous siblings
- *
- * @param elements the elements to be tested
- * @return true if the elements are contiguous siblings with no gaps
- */
- public static boolean isContiguous(@NonNull List<Element> elements) {
- if (elements.size() > 1) {
- // All elements must be siblings (e.g. same parent)
- Node parent = elements.get(0).getParentNode();
- if (!(parent instanceof Element)) {
- return false;
- }
- for (Element node : elements) {
- if (parent != node.getParentNode()) {
- return false;
- }
- }
-
- // Ensure that the siblings are contiguous; no gaps.
- // If we've selected all the children of the parent then we don't need
- // to look.
- List<Element> siblings = DomUtilities.getChildren((Element) parent);
- if (siblings.size() != elements.size()) {
- Set<Element> nodeSet = new HashSet<Element>(elements);
- boolean inRange = false;
- int remaining = elements.size();
- for (Element node : siblings) {
- boolean in = nodeSet.contains(node);
- if (in) {
- remaining--;
- if (remaining == 0) {
- break;
- }
- inRange = true;
- } else if (inRange) {
- return false;
- }
- }
- }
- }
-
- return true;
- }
-
- /**
- * Determines whether two element trees are equivalent. Two element trees are
- * equivalent if they represent the same DOM structure (elements, attributes, and
- * children in order). This is almost the same as simply checking whether the String
- * representations of the two nodes are identical, but this allows for minor
- * variations that are not semantically significant, such as variations in formatting
- * or ordering of the element attribute declarations, and the text children are
- * ignored (this is such that in for example layout where content is only used for
- * indentation the indentation differences are ignored). Null trees are never equal.
- *
- * @param element1 the first element to compare
- * @param element2 the second element to compare
- * @return true if the two element hierarchies are logically equal
- */
- public static boolean isEquivalent(@Nullable Element element1, @Nullable Element element2) {
- if (element1 == null || element2 == null) {
- return false;
- }
-
- if (!element1.getTagName().equals(element2.getTagName())) {
- return false;
- }
-
- // Check attribute map
- NamedNodeMap attributes1 = element1.getAttributes();
- NamedNodeMap attributes2 = element2.getAttributes();
-
- List<Attr> attributeNodes1 = new ArrayList<Attr>();
- for (int i = 0, n = attributes1.getLength(); i < n; i++) {
- Attr attribute = (Attr) attributes1.item(i);
- // Ignore tools uri namespace attributes for equivalency test
- if (TOOLS_URI.equals(attribute.getNamespaceURI())) {
- continue;
- }
- attributeNodes1.add(attribute);
- }
- List<Attr> attributeNodes2 = new ArrayList<Attr>();
- for (int i = 0, n = attributes2.getLength(); i < n; i++) {
- Attr attribute = (Attr) attributes2.item(i);
- // Ignore tools uri namespace attributes for equivalency test
- if (TOOLS_URI.equals(attribute.getNamespaceURI())) {
- continue;
- }
- attributeNodes2.add(attribute);
- }
-
- if (attributeNodes1.size() != attributeNodes2.size()) {
- return false;
- }
-
- if (attributes1.getLength() > 0) {
- Collections.sort(attributeNodes1, ATTRIBUTE_COMPARATOR);
- Collections.sort(attributeNodes2, ATTRIBUTE_COMPARATOR);
- for (int i = 0; i < attributeNodes1.size(); i++) {
- Attr attr1 = attributeNodes1.get(i);
- Attr attr2 = attributeNodes2.get(i);
- if (attr1.getLocalName() == null || attr2.getLocalName() == null) {
- if (!attr1.getName().equals(attr2.getName())) {
- return false;
- }
- } else if (!attr1.getLocalName().equals(attr2.getLocalName())) {
- return false;
- }
- if (!attr1.getValue().equals(attr2.getValue())) {
- return false;
- }
- if (attr1.getNamespaceURI() == null) {
- if (attr2.getNamespaceURI() != null) {
- return false;
- }
- } else if (attr2.getNamespaceURI() == null) {
- return false;
- } else if (!attr1.getNamespaceURI().equals(attr2.getNamespaceURI())) {
- return false;
- }
- }
- }
-
- NodeList children1 = element1.getChildNodes();
- NodeList children2 = element2.getChildNodes();
- int nextIndex1 = 0;
- int nextIndex2 = 0;
- while (true) {
- while (nextIndex1 < children1.getLength() &&
- children1.item(nextIndex1).getNodeType() != Node.ELEMENT_NODE) {
- nextIndex1++;
- }
-
- while (nextIndex2 < children2.getLength() &&
- children2.item(nextIndex2).getNodeType() != Node.ELEMENT_NODE) {
- nextIndex2++;
- }
-
- Element nextElement1 = (Element) (nextIndex1 < children1.getLength()
- ? children1.item(nextIndex1) : null);
- Element nextElement2 = (Element) (nextIndex2 < children2.getLength()
- ? children2.item(nextIndex2) : null);
- if (nextElement1 == null) {
- return nextElement2 == null;
- } else if (nextElement2 == null) {
- return false;
- } else if (!isEquivalent(nextElement1, nextElement2)) {
- return false;
- }
- nextIndex1++;
- nextIndex2++;
- }
- }
-
- /**
- * Finds the corresponding element in a document to a given element in another
- * document. Note that this does <b>not</b> do any kind of equivalence check
- * (see {@link #isEquivalent(Element, Element)}), and currently the search
- * is only by id; there is no structural search.
- *
- * @param element the element to find an equivalent for
- * @param document the document to search for an equivalent element in
- * @return an equivalent element, or null
- */
- @Nullable
- public static Element findCorresponding(@NonNull Element element, @NonNull Document document) {
- // Make sure the method is called correctly -- the element is for a different
- // document than the one we are searching
- assert element.getOwnerDocument() != document;
-
- // First search by id. This allows us to find the corresponding
- String id = element.getAttributeNS(ANDROID_URI, ATTR_ID);
- if (id != null && id.length() > 0) {
- if (id.startsWith(ID_PREFIX)) {
- id = NEW_ID_PREFIX + id.substring(ID_PREFIX.length());
- }
-
- return findCorresponding(document.getDocumentElement(), id);
- }
-
- // TODO: Search by structure - look in the document and
- // find a corresponding element in the same location in the structure,
- // e.g. 4th child of root, 3rd child, 6th child, then pick node with tag "foo".
-
- return null;
- }
-
- /** Helper method for {@link #findCorresponding(Element, Document)} */
- @Nullable
- private static Element findCorresponding(@NonNull Element element, @NonNull String targetId) {
- String id = element.getAttributeNS(ANDROID_URI, ATTR_ID);
- if (id != null) { // Work around DOM bug
- if (id.equals(targetId)) {
- return element;
- } else if (id.startsWith(ID_PREFIX)) {
- id = NEW_ID_PREFIX + id.substring(ID_PREFIX.length());
- if (id.equals(targetId)) {
- return element;
- }
- }
- }
-
- NodeList children = element.getChildNodes();
- for (int i = 0, n = children.getLength(); i < n; i++) {
- Node node = children.item(i);
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- Element child = (Element) node;
- Element match = findCorresponding(child, targetId);
- if (match != null) {
- return match;
- }
- }
- }
-
- return null;
- }
-
- /**
- * Parses the given XML string as a DOM document, using Eclipse's structured
- * XML model (which for example allows us to distinguish empty elements
- * (<foo/>) from elements with no children (<foo></foo>).
- *
- * @param xml the XML content to be parsed (must be well formed)
- * @return the DOM document, or null
- */
- @Nullable
- public static Document parseStructuredDocument(@NonNull String xml) {
- IStructuredModel model = createStructuredModel(xml);
- if (model instanceof IDOMModel) {
- IDOMModel domModel = (IDOMModel) model;
- return domModel.getDocument();
- }
-
- return null;
- }
-
- /**
- * Parses the given XML string and builds an Eclipse structured model for it.
- *
- * @param xml the XML content to be parsed (must be well formed)
- * @return the structured model
- */
- @Nullable
- public static IStructuredModel createStructuredModel(@NonNull String xml) {
- IStructuredModel model = createEmptyModel();
- IStructuredDocument document = model.getStructuredDocument();
- model.aboutToChangeModel();
- document.set(xml);
- model.changedModel();
-
- return model;
- }
-
- /**
- * Creates an empty Eclipse XML model
- *
- * @return a new Eclipse XML model
- */
- @NonNull
- public static IStructuredModel createEmptyModel() {
- IModelManager modelManager = StructuredModelManager.getModelManager();
- return modelManager.createUnManagedStructuredModelFor(ContentTypeID_XML);
- }
-
- /**
- * Creates an empty Eclipse XML document
- *
- * @return an empty Eclipse XML document
- */
- @Nullable
- public static Document createEmptyDocument() {
- IStructuredModel model = createEmptyModel();
- if (model instanceof IDOMModel) {
- IDOMModel domModel = (IDOMModel) model;
- return domModel.getDocument();
- }
-
- return null;
- }
-
- /**
- * Creates an empty non-Eclipse XML document.
- * This is used when you need to use XML operations not supported by
- * the Eclipse XML model (such as serialization).
- * <p>
- * The new document will not validate, will ignore comments, and will
- * support namespace.
- *
- * @return the new document
- */
- @Nullable
- public static Document createEmptyPlainDocument() {
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- factory.setNamespaceAware(true);
- factory.setValidating(false);
- factory.setIgnoringComments(true);
- DocumentBuilder builder;
- try {
- builder = factory.newDocumentBuilder();
- return builder.newDocument();
- } catch (ParserConfigurationException e) {
- AdtPlugin.log(e, null);
- }
-
- return null;
- }
-
- /**
- * Parses the given XML string as a DOM document, using the JDK parser.
- * The parser does not validate, and is namespace aware.
- *
- * @param xml the XML content to be parsed (must be well formed)
- * @param logParserErrors if true, log parser errors to the log, otherwise
- * silently return null
- * @return the DOM document, or null
- */
- @Nullable
- public static Document parseDocument(@NonNull String xml, boolean logParserErrors) {
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- InputSource is = new InputSource(new StringReader(xml));
- factory.setNamespaceAware(true);
- factory.setValidating(false);
- try {
- DocumentBuilder builder = factory.newDocumentBuilder();
- return builder.parse(is);
- } catch (Exception e) {
- if (logParserErrors) {
- AdtPlugin.log(e, null);
- }
- }
-
- return null;
- }
-
- /** Can be used to sort attributes by name */
- private static final Comparator<Attr> ATTRIBUTE_COMPARATOR = new Comparator<Attr>() {
- @Override
- public int compare(Attr a1, Attr a2) {
- return a1.getName().compareTo(a2.getName());
- }
- };
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/DropGesture.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/DropGesture.java
deleted file mode 100644
index bb3be7f68..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/DropGesture.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import org.eclipse.swt.dnd.DropTargetEvent;
-import org.eclipse.swt.dnd.DropTargetListener;
-
-/**
- * A {@link DropGesture} is a {@link Gesture} which deals with drag and drop, so
- * it has additional hooks for indicating whether the current position is
- * "valid", and in general gets access to the system drag and drop data
- * structures. See the {@link Gesture} documentation for more details on whether
- * you should choose a plain {@link Gesture} or a {@link DropGesture}.
- */
-public abstract class DropGesture extends Gesture {
- /**
- * The cursor has entered the drop target boundaries.
- *
- * @param event The {@link DropTargetEvent} for this drag and drop event
- * @see DropTargetListener#dragEnter(DropTargetEvent)
- */
- public void dragEnter(DropTargetEvent event) {
- }
-
- /**
- * The cursor is moving over the drop target.
- *
- * @param event The {@link DropTargetEvent} for this drag and drop event
- * @see DropTargetListener#dragOver(DropTargetEvent)
- */
- public void dragOver(DropTargetEvent event) {
- }
-
- /**
- * The operation being performed has changed (usually due to the user
- * changing the selected modifier key(s) while dragging).
- *
- * @param event The {@link DropTargetEvent} for this drag and drop event
- * @see DropTargetListener#dragOperationChanged(DropTargetEvent)
- */
- public void dragOperationChanged(DropTargetEvent event) {
- }
-
- /**
- * The cursor has left the drop target boundaries OR the drop has been
- * canceled OR the data is about to be dropped.
- *
- * @param event The {@link DropTargetEvent} for this drag and drop event
- * @see DropTargetListener#dragLeave(DropTargetEvent)
- */
- public void dragLeave(DropTargetEvent event) {
- }
-
- /**
- * The drop is about to be performed. The drop target is given a last chance
- * to change the nature of the drop.
- *
- * @param event The {@link DropTargetEvent} for this drag and drop event
- * @see DropTargetListener#dropAccept(DropTargetEvent)
- */
- public void dropAccept(DropTargetEvent event) {
- }
-
- /**
- * The data is being dropped. The data field contains java format of the
- * data being dropped.
- *
- * @param event The {@link DropTargetEvent} for this drag and drop event
- * @see DropTargetListener#drop(DropTargetEvent)
- */
- public void drop(final DropTargetEvent event) {
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/DynamicContextMenu.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/DynamicContextMenu.java
deleted file mode 100644
index fc7127278..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/DynamicContextMenu.java
+++ /dev/null
@@ -1,654 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.EXPANDABLE_LIST_VIEW;
-import static com.android.SdkConstants.FQCN_GESTURE_OVERLAY_VIEW;
-import static com.android.SdkConstants.FQCN_IMAGE_VIEW;
-import static com.android.SdkConstants.FQCN_LINEAR_LAYOUT;
-import static com.android.SdkConstants.FQCN_TEXT_VIEW;
-import static com.android.SdkConstants.GRID_VIEW;
-import static com.android.SdkConstants.LIST_VIEW;
-import static com.android.SdkConstants.SPINNER;
-import static com.android.SdkConstants.VIEW_FRAGMENT;
-
-import com.android.SdkConstants;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.RuleAction;
-import com.android.ide.common.api.RuleAction.Choices;
-import com.android.ide.common.api.RuleAction.NestedAction;
-import com.android.ide.common.api.RuleAction.Toggle;
-import com.android.ide.common.layout.BaseViewRule;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.NodeFactory;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.NodeProxy;
-import com.android.ide.eclipse.adt.internal.editors.layout.refactoring.ChangeLayoutAction;
-import com.android.ide.eclipse.adt.internal.editors.layout.refactoring.ChangeViewAction;
-import com.android.ide.eclipse.adt.internal.editors.layout.refactoring.ExtractIncludeAction;
-import com.android.ide.eclipse.adt.internal.editors.layout.refactoring.ExtractStyleAction;
-import com.android.ide.eclipse.adt.internal.editors.layout.refactoring.UnwrapAction;
-import com.android.ide.eclipse.adt.internal.editors.layout.refactoring.UseCompoundDrawableAction;
-import com.android.ide.eclipse.adt.internal.editors.layout.refactoring.WrapInAction;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.ActionContributionItem;
-import org.eclipse.jface.action.ContributionItem;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IContributionItem;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Menu;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Helper class that is responsible for adding and managing the dynamic menu items
- * contributed by the {@link IViewRule} instances, based on the current selection
- * on the {@link LayoutCanvas}.
- * <p/>
- * This class is tied to a specific {@link LayoutCanvas} instance and a root {@link MenuManager}.
- * <p/>
- * Two instances of this are used: one created by {@link LayoutCanvas} and the other one
- * created by {@link OutlinePage}. Different root {@link MenuManager}s are populated, however
- * they are both linked to the current selection state of the {@link LayoutCanvas}.
- */
-class DynamicContextMenu {
- public static String DEFAULT_ACTION_SHORTCUT = "F2"; //$NON-NLS-1$
- public static int DEFAULT_ACTION_KEY = SWT.F2;
-
- /** The XML layout editor that contains the canvas that uses this menu. */
- private final LayoutEditorDelegate mEditorDelegate;
-
- /** The layout canvas that displays this context menu. */
- private final LayoutCanvas mCanvas;
-
- /** The root menu manager of the context menu. */
- private final MenuManager mMenuManager;
-
- /**
- * Creates a new helper responsible for adding and managing the dynamic menu items
- * contributed by the {@link IViewRule} instances, based on the current selection
- * on the {@link LayoutCanvas}.
- * @param editorDelegate the editor owning the menu
- * @param canvas The {@link LayoutCanvas} providing the selection, the node factory and
- * the rules engine.
- * @param rootMenu The root of the context menu displayed. In practice this may be the
- * context menu manager of the {@link LayoutCanvas} or the one from {@link OutlinePage}.
- */
- public DynamicContextMenu(
- LayoutEditorDelegate editorDelegate,
- LayoutCanvas canvas,
- MenuManager rootMenu) {
- mEditorDelegate = editorDelegate;
- mCanvas = canvas;
- mMenuManager = rootMenu;
-
- setupDynamicMenuActions();
- }
-
- /**
- * Setups the menu manager to receive dynamic menu contributions from the {@link IViewRule}s
- * when it's about to be shown.
- */
- private void setupDynamicMenuActions() {
- // Remember how many static actions we have. Then each time the menu is
- // shown, find dynamic contributions based on the current selection and insert
- // them at the beginning of the menu.
- final int numStaticActions = mMenuManager.getSize();
- mMenuManager.addMenuListener(new IMenuListener() {
- @Override
- public void menuAboutToShow(IMenuManager manager) {
-
- // Remove any previous dynamic contributions to keep only the
- // default static items.
- int n = mMenuManager.getSize() - numStaticActions;
- if (n > 0) {
- IContributionItem[] items = mMenuManager.getItems();
- for (int i = 0; i < n; i++) {
- mMenuManager.remove(items[i]);
- }
- }
-
- // Now add all the dynamic menu actions depending on the current selection.
- populateDynamicContextMenu();
- }
- });
-
- }
-
- /**
- * This method is invoked by <code>menuAboutToShow</code> on {@link #mMenuManager}.
- * All previous dynamic menu actions have been removed and this method can now insert
- * any new actions that depend on the current selection.
- */
- private void populateDynamicContextMenu() {
- // Create the actual menu contributions
- String endId = mMenuManager.getItems()[0].getId();
-
- Separator sep = new Separator();
- sep.setId("-dyn-gle-sep"); //$NON-NLS-1$
- mMenuManager.insertBefore(endId, sep);
- endId = sep.getId();
-
- List<SelectionItem> selections = mCanvas.getSelectionManager().getSelections();
- if (selections.size() == 0) {
- return;
- }
- List<INode> nodes = new ArrayList<INode>(selections.size());
- for (SelectionItem item : selections) {
- nodes.add(item.getNode());
- }
-
- List<IContributionItem> menuItems = getMenuItems(nodes);
- for (IContributionItem menuItem : menuItems) {
- mMenuManager.insertBefore(endId, menuItem);
- }
-
- insertTagSpecificMenus(endId);
- insertVisualRefactorings(endId);
- insertParentItems(endId);
- }
-
- /**
- * Returns the list of node-specific actions applicable to the given
- * collection of nodes
- *
- * @param nodes the collection of nodes to look up actions for
- * @return a list of contribution items applicable for all the nodes
- */
- private List<IContributionItem> getMenuItems(List<INode> nodes) {
- Map<INode, List<RuleAction>> allActions = new HashMap<INode, List<RuleAction>>();
- for (INode node : nodes) {
- List<RuleAction> actionList = getMenuActions((NodeProxy) node);
- allActions.put(node, actionList);
- }
-
- Set<String> availableIds = computeApplicableActionIds(allActions);
-
- // +10: Make room for separators too
- List<IContributionItem> items = new ArrayList<IContributionItem>(availableIds.size() + 10);
-
- // We'll use the actions returned by the first node. Even when there
- // are multiple items selected, we'll use the first action, but pass
- // the set of all selected nodes to that first action. Actions are required
- // to work this way to facilitate multi selection and actions which apply
- // to multiple nodes.
- NodeProxy first = (NodeProxy) nodes.get(0);
- List<RuleAction> firstSelectedActions = allActions.get(first);
- String defaultId = getDefaultActionId(first);
- for (RuleAction action : firstSelectedActions) {
- if (!availableIds.contains(action.getId())
- && !(action instanceof RuleAction.Separator)) {
- // This action isn't supported by all selected items.
- continue;
- }
-
- items.add(createContributionItem(action, nodes, defaultId));
- }
-
- return items;
- }
-
- private void insertParentItems(String endId) {
- List<SelectionItem> selection = mCanvas.getSelectionManager().getSelections();
- if (selection.size() == 1) {
- mMenuManager.insertBefore(endId, new Separator());
- INode parent = selection.get(0).getNode().getParent();
- while (parent != null) {
- String id = parent.getStringAttr(ANDROID_URI, ATTR_ID);
- String label;
- if (id != null && id.length() > 0) {
- label = BaseViewRule.stripIdPrefix(id);
- } else {
- // Use the view name, such as "Button", as the label
- label = parent.getFqcn();
- // Strip off package
- label = label.substring(label.lastIndexOf('.') + 1);
- }
- mMenuManager.insertBefore(endId, new NestedParentMenu(label, parent));
- parent = parent.getParent();
- }
- mMenuManager.insertBefore(endId, new Separator());
- }
- }
-
- private void insertVisualRefactorings(String endId) {
- // Extract As <include> refactoring, Wrap In Refactoring, etc.
- List<SelectionItem> selection = mCanvas.getSelectionManager().getSelections();
- if (selection.size() == 0) {
- return;
- }
- // Only include the menu item if you are not right clicking on a root,
- // or on an included view, or on a non-contiguous selection
- mMenuManager.insertBefore(endId, new Separator());
- if (selection.size() == 1 && selection.get(0).getViewInfo() != null
- && selection.get(0).getViewInfo().getName().equals(FQCN_LINEAR_LAYOUT)) {
- CanvasViewInfo info = selection.get(0).getViewInfo();
- List<CanvasViewInfo> children = info.getChildren();
- if (children.size() == 2) {
- String first = children.get(0).getName();
- String second = children.get(1).getName();
- if ((first.equals(FQCN_IMAGE_VIEW) && second.equals(FQCN_TEXT_VIEW))
- || (first.equals(FQCN_TEXT_VIEW) && second.equals(FQCN_IMAGE_VIEW))) {
- mMenuManager.insertBefore(endId, UseCompoundDrawableAction.create(
- mEditorDelegate));
- }
- }
- }
- mMenuManager.insertBefore(endId, ExtractIncludeAction.create(mEditorDelegate));
- mMenuManager.insertBefore(endId, ExtractStyleAction.create(mEditorDelegate));
- mMenuManager.insertBefore(endId, WrapInAction.create(mEditorDelegate));
- if (selection.size() == 1 && !(selection.get(0).isRoot())) {
- mMenuManager.insertBefore(endId, UnwrapAction.create(mEditorDelegate));
- }
- if (selection.size() == 1 && (selection.get(0).isLayout() ||
- selection.get(0).getViewInfo().getName().equals(FQCN_GESTURE_OVERLAY_VIEW))) {
- mMenuManager.insertBefore(endId, ChangeLayoutAction.create(mEditorDelegate));
- } else {
- mMenuManager.insertBefore(endId, ChangeViewAction.create(mEditorDelegate));
- }
- mMenuManager.insertBefore(endId, new Separator());
- }
-
- /** "Preview List Content" pull-right menu for lists, "Preview Fragment" for fragments, etc. */
- private void insertTagSpecificMenus(String endId) {
-
- List<SelectionItem> selection = mCanvas.getSelectionManager().getSelections();
- if (selection.size() == 0) {
- return;
- }
- for (SelectionItem item : selection) {
- UiViewElementNode node = item.getViewInfo().getUiViewNode();
- String name = node.getDescriptor().getXmlLocalName();
- boolean isGrid = name.equals(GRID_VIEW);
- boolean isSpinner = name.equals(SPINNER);
- if (name.equals(LIST_VIEW) || name.equals(EXPANDABLE_LIST_VIEW)
- || isGrid || isSpinner) {
- mMenuManager.insertBefore(endId, new Separator());
- mMenuManager.insertBefore(endId, new ListViewTypeMenu(mCanvas, isGrid, isSpinner));
- return;
- } else if (name.equals(VIEW_FRAGMENT) && selection.size() == 1) {
- mMenuManager.insertBefore(endId, new Separator());
- mMenuManager.insertBefore(endId, new FragmentMenu(mCanvas));
- return;
- }
- }
- }
-
- /**
- * Given a map from selection items to list of applicable actions (produced
- * by {@link #computeApplicableActions()}) this method computes the set of
- * common actions and returns the action ids of these actions.
- *
- * @param actions a map from selection item to list of actions applicable to
- * that selection item
- * @return set of action ids for the actions that are present in the action
- * lists for all selected items
- */
- private Set<String> computeApplicableActionIds(Map<INode, List<RuleAction>> actions) {
- if (actions.size() > 1) {
- // More than one view is selected, so we have to filter down the available
- // actions such that only those actions that are defined for all the views
- // are shown
- Map<String, Integer> idCounts = new HashMap<String, Integer>();
- for (Map.Entry<INode, List<RuleAction>> entry : actions.entrySet()) {
- List<RuleAction> actionList = entry.getValue();
- for (RuleAction action : actionList) {
- if (!action.supportsMultipleNodes()) {
- continue;
- }
- String id = action.getId();
- if (id != null) {
- assert id != null : action;
- Integer count = idCounts.get(id);
- if (count == null) {
- idCounts.put(id, Integer.valueOf(1));
- } else {
- idCounts.put(id, count + 1);
- }
- }
- }
- }
- Integer selectionCount = Integer.valueOf(actions.size());
- Set<String> validIds = new HashSet<String>(idCounts.size());
- for (Map.Entry<String, Integer> entry : idCounts.entrySet()) {
- Integer count = entry.getValue();
- if (selectionCount.equals(count)) {
- String id = entry.getKey();
- validIds.add(id);
- }
- }
- return validIds;
- } else {
- List<RuleAction> actionList = actions.values().iterator().next();
- Set<String> validIds = new HashSet<String>(actionList.size());
- for (RuleAction action : actionList) {
- String id = action.getId();
- validIds.add(id);
- }
- return validIds;
- }
- }
-
- /**
- * Returns the menu actions computed by the rule associated with this node.
- *
- * @param node the canvas node we need menu actions for
- * @return a list of {@link RuleAction} objects applicable to the node
- */
- private List<RuleAction> getMenuActions(NodeProxy node) {
- List<RuleAction> actions = mCanvas.getRulesEngine().callGetContextMenu(node);
- if (actions == null || actions.size() == 0) {
- return null;
- }
-
- return actions;
- }
-
- /**
- * Returns the default action id, or null
- *
- * @param node the node to look up the default action for
- * @return the action id, or null
- */
- private String getDefaultActionId(NodeProxy node) {
- return mCanvas.getRulesEngine().callGetDefaultActionId(node);
- }
-
- /**
- * Creates a {@link ContributionItem} for the given {@link RuleAction}.
- *
- * @param action the action to create a {@link ContributionItem} for
- * @param nodes the set of nodes the action should be applied to
- * @param defaultId if not non null, the id of an action which should be considered default
- * @return a new {@link ContributionItem} which implements the given action
- * on the given nodes
- */
- private ContributionItem createContributionItem(final RuleAction action,
- final List<INode> nodes, final String defaultId) {
- if (action instanceof RuleAction.Separator) {
- return new Separator();
- } else if (action instanceof NestedAction) {
- NestedAction parentAction = (NestedAction) action;
- return new ActionContributionItem(new NestedActionMenu(parentAction, nodes));
- } else if (action instanceof Choices) {
- Choices parentAction = (Choices) action;
- return new ActionContributionItem(new NestedChoiceMenu(parentAction, nodes));
- } else if (action instanceof Toggle) {
- return new ActionContributionItem(createToggleAction(action, nodes));
- } else {
- return new ActionContributionItem(createPlainAction(action, nodes, defaultId));
- }
- }
-
- private Action createToggleAction(final RuleAction action, final List<INode> nodes) {
- Toggle toggleAction = (Toggle) action;
- final boolean isChecked = toggleAction.isChecked();
- Action a = new Action(action.getTitle(), IAction.AS_CHECK_BOX) {
- @Override
- public void run() {
- String label = createActionLabel(action, nodes);
- mEditorDelegate.getEditor().wrapUndoEditXmlModel(label, new Runnable() {
- @Override
- public void run() {
- action.getCallback().action(action, nodes,
- null/* no valueId for a toggle */, !isChecked);
- applyPendingChanges();
- }
- });
- }
- };
- a.setId(action.getId());
- a.setChecked(isChecked);
- return a;
- }
-
- private IAction createPlainAction(final RuleAction action, final List<INode> nodes,
- final String defaultId) {
- IAction a = new Action(action.getTitle(), IAction.AS_PUSH_BUTTON) {
- @Override
- public void run() {
- String label = createActionLabel(action, nodes);
- mEditorDelegate.getEditor().wrapUndoEditXmlModel(label, new Runnable() {
- @Override
- public void run() {
- action.getCallback().action(action, nodes, null,
- Boolean.TRUE);
- applyPendingChanges();
- }
- });
- }
- };
-
- String id = action.getId();
- if (defaultId != null && id.equals(defaultId)) {
- a.setAccelerator(DEFAULT_ACTION_KEY);
- String text = a.getText();
- text = text + '\t' + DEFAULT_ACTION_SHORTCUT;
- a.setText(text);
-
- } else if (ATTR_ID.equals(id)) {
- // Keep in sync with {@link LayoutCanvas#handleKeyPressed}
- if (SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_DARWIN) {
- a.setAccelerator('R' | SWT.MOD1 | SWT.MOD3);
- // Option+Command
- a.setText(a.getText().trim() + "\t\u2325\u2318R"); //$NON-NLS-1$
- } else if (SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_LINUX) {
- a.setAccelerator('R' | SWT.MOD2 | SWT.MOD3);
- a.setText(a.getText() + "\tShift+Alt+R"); //$NON-NLS-1$
- } else {
- a.setAccelerator('R' | SWT.MOD2 | SWT.MOD3);
- a.setText(a.getText() + "\tAlt+Shift+R"); //$NON-NLS-1$
- }
- }
- a.setId(id);
- return a;
- }
-
- private static String createActionLabel(final RuleAction action, final List<INode> nodes) {
- String label = action.getTitle();
- if (nodes.size() > 1) {
- label += String.format(" (%d elements)", nodes.size());
- }
- return label;
- }
-
- /**
- * The {@link NestedParentMenu} provides submenu content which adds actions
- * available on one of the selected node's parent nodes. This will be
- * similar to the menu content for the selected node, except the parent
- * menus will not be embedded within the nested menu.
- */
- private class NestedParentMenu extends SubmenuAction {
- INode mParent;
-
- NestedParentMenu(String title, INode parent) {
- super(title);
- mParent = parent;
- }
-
- @Override
- protected void addMenuItems(Menu menu) {
- List<SelectionItem> selection = mCanvas.getSelectionManager().getSelections();
- if (selection.size() == 0) {
- return;
- }
-
- List<IContributionItem> menuItems = getMenuItems(Collections.singletonList(mParent));
- for (IContributionItem menuItem : menuItems) {
- menuItem.fill(menu, -1);
- }
- }
- }
-
- /**
- * The {@link NestedActionMenu} creates a lazily populated pull-right menu
- * where the children are {@link RuleAction}'s themselves.
- */
- private class NestedActionMenu extends SubmenuAction {
- private final NestedAction mParentAction;
- private final List<INode> mNodes;
-
- NestedActionMenu(NestedAction parentAction, List<INode> nodes) {
- super(parentAction.getTitle());
- mParentAction = parentAction;
- mNodes = nodes;
-
- assert mNodes.size() > 0;
- }
-
- @Override
- protected void addMenuItems(Menu menu) {
- Map<INode, List<RuleAction>> allActions = new HashMap<INode, List<RuleAction>>();
- for (INode node : mNodes) {
- List<RuleAction> actionList = mParentAction.getNestedActions(node);
- allActions.put(node, actionList);
- }
-
- Set<String> availableIds = computeApplicableActionIds(allActions);
-
- NodeProxy first = (NodeProxy) mNodes.get(0);
- String defaultId = getDefaultActionId(first);
- List<RuleAction> firstSelectedActions = allActions.get(first);
-
- int count = 0;
- for (RuleAction firstAction : firstSelectedActions) {
- if (!availableIds.contains(firstAction.getId())
- && !(firstAction instanceof RuleAction.Separator)) {
- // This action isn't supported by all selected items.
- continue;
- }
-
- createContributionItem(firstAction, mNodes, defaultId).fill(menu, -1);
- count++;
- }
-
- if (count == 0) {
- addDisabledMessageItem("<Empty>");
- }
- }
- }
-
- private void applyPendingChanges() {
- LayoutCanvas canvas = mEditorDelegate.getGraphicalEditor().getCanvasControl();
- CanvasViewInfo root = canvas.getViewHierarchy().getRoot();
- if (root != null) {
- UiViewElementNode uiViewNode = root.getUiViewNode();
- NodeFactory nodeFactory = canvas.getNodeFactory();
- NodeProxy rootNode = nodeFactory.create(uiViewNode);
- if (rootNode != null) {
- rootNode.applyPendingChanges();
- }
- }
- }
-
- /**
- * The {@link NestedChoiceMenu} creates a lazily populated pull-right menu
- * where the items in the menu are strings
- */
- private class NestedChoiceMenu extends SubmenuAction {
- private final Choices mParentAction;
- private final List<INode> mNodes;
-
- NestedChoiceMenu(Choices parentAction, List<INode> nodes) {
- super(parentAction.getTitle());
- mParentAction = parentAction;
- mNodes = nodes;
- }
-
- @Override
- protected void addMenuItems(Menu menu) {
- List<String> titles = mParentAction.getTitles();
- List<String> ids = mParentAction.getIds();
- String current = mParentAction.getCurrent();
- assert titles.size() == ids.size();
- String[] currentValues = current != null
- && current.indexOf(RuleAction.CHOICE_SEP) != -1 ?
- current.split(RuleAction.CHOICE_SEP_PATTERN) : null;
- for (int i = 0, n = Math.min(titles.size(), ids.size()); i < n; i++) {
- final String id = ids.get(i);
- if (id == null || id.equals(RuleAction.SEPARATOR)) {
- new Separator().fill(menu, -1);
- continue;
- }
-
- // Find out whether this item is selected
- boolean select = false;
- if (current != null) {
- // The current choice has a separator, so it's a flag with
- // multiple values selected. Compare keys with the split
- // values.
- if (currentValues != null) {
- if (current.indexOf(id) >= 0) {
- for (String value : currentValues) {
- if (id.equals(value)) {
- select = true;
- break;
- }
- }
- }
- } else {
- // current choice has no separator, simply compare to the key
- select = id.equals(current);
- }
- }
-
- String title = titles.get(i);
- IAction a = new Action(title,
- current != null ? IAction.AS_CHECK_BOX : IAction.AS_PUSH_BUTTON) {
- @Override
- public void runWithEvent(Event event) {
- run();
- }
- @Override
- public void run() {
- String label = createActionLabel(mParentAction, mNodes);
- mEditorDelegate.getEditor().wrapUndoEditXmlModel(label, new Runnable() {
- @Override
- public void run() {
- mParentAction.getCallback().action(mParentAction, mNodes, id,
- Boolean.TRUE);
- applyPendingChanges();
- }
- });
- }
- };
- a.setId(id);
- a.setEnabled(true);
- if (select) {
- a.setChecked(true);
- }
-
- new ActionContributionItem(a).fill(menu, -1);
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/EmptyViewsOverlay.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/EmptyViewsOverlay.java
deleted file mode 100644
index daa3e0eae..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/EmptyViewsOverlay.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Device;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Rectangle;
-
-/**
- * The {@link EmptyViewsOverlay} paints bounding rectangles for any of the empty and
- * invisible container views in the scene.
- */
-public class EmptyViewsOverlay extends Overlay {
- /** The {@link ViewHierarchy} containing visible view information. */
- private final ViewHierarchy mViewHierarchy;
-
- /** Border color to paint the bounding boxes with. */
- private Color mBorderColor;
-
- /** Vertical scaling & scrollbar information. */
- private CanvasTransform mVScale;
-
- /** Horizontal scaling & scrollbar information. */
- private CanvasTransform mHScale;
-
- /**
- * Constructs a new {@link EmptyViewsOverlay} linked to the given view hierarchy.
- *
- * @param viewHierarchy The {@link ViewHierarchy} to render.
- * @param hScale The {@link CanvasTransform} to use to transfer horizontal layout
- * coordinates to screen coordinates.
- * @param vScale The {@link CanvasTransform} to use to transfer vertical layout coordinates
- * to screen coordinates.
- */
- public EmptyViewsOverlay(
- ViewHierarchy viewHierarchy,
- CanvasTransform hScale,
- CanvasTransform vScale) {
- super();
- mViewHierarchy = viewHierarchy;
- mHScale = hScale;
- mVScale = vScale;
- }
-
- @Override
- public void create(Device device) {
- mBorderColor = new Color(device, SwtDrawingStyle.EMPTY.getStrokeColor());
- }
-
- @Override
- public void dispose() {
- if (mBorderColor != null) {
- mBorderColor.dispose();
- mBorderColor = null;
- }
- }
-
- @Override
- public void paint(GC gc) {
- gc.setForeground(mBorderColor);
- gc.setLineDash(null);
- gc.setLineStyle(SwtDrawingStyle.EMPTY.getLineStyle());
- int oldAlpha = gc.getAlpha();
- gc.setAlpha(SwtDrawingStyle.EMPTY.getStrokeAlpha());
- gc.setLineWidth(SwtDrawingStyle.EMPTY.getLineWidth());
-
- for (CanvasViewInfo info : mViewHierarchy.getInvisibleViews()) {
- Rectangle r = info.getAbsRect();
-
- int x = mHScale.translate(r.x);
- int y = mVScale.translate(r.y);
- int w = mHScale.scale(r.width);
- int h = mVScale.scale(r.height);
-
- // +1: See explanation in equivalent code in {@link OutlineOverlay#paint}
- gc.drawRectangle(x, y, w + 1, h + 1);
- }
-
- gc.setAlpha(oldAlpha);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ExportScreenshotAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ExportScreenshotAction.java
deleted file mode 100644
index ac3328db2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ExportScreenshotAction.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.SdkConstants.DOT_PNG;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Shell;
-
-import java.awt.image.BufferedImage;
-import java.io.File;
-import java.io.IOException;
-
-import javax.imageio.ImageIO;
-
-/** Saves the current layout editor's rendered image to disk */
-class ExportScreenshotAction extends Action {
- private final LayoutCanvas mCanvas;
-
- ExportScreenshotAction(LayoutCanvas canvas) {
- super("Export Screenshot...");
- mCanvas = canvas;
- }
-
- @Override
- public void run() {
- Shell shell = AdtPlugin.getShell();
-
- ImageOverlay imageOverlay = mCanvas.getImageOverlay();
- BufferedImage image = imageOverlay.getAwtImage();
- if (image != null) {
- FileDialog dialog = new FileDialog(shell, SWT.SAVE);
- dialog.setFilterExtensions(new String[] { "*.png" }); //$NON-NLS-1$
- String path = dialog.open();
- if (path != null) {
- if (!path.endsWith(DOT_PNG)) {
- path = path + DOT_PNG;
- }
- File file = new File(path);
- if (file.exists()) {
- MessageDialog d = new MessageDialog(null, "File Already Exists", null,
- String.format(
- "%1$s already exists.\nWould you like to replace it?",
- path),
- MessageDialog.QUESTION, new String[] {
- // Yes will be moved to the end because it's the default
- "Yes", "No"
- }, 0);
- int result = d.open();
- if (result != 0) {
- return;
- }
- }
- try {
- ImageIO.write(image, "PNG", file); //$NON-NLS-1$
- } catch (IOException e) {
- AdtPlugin.log(e, null);
- }
- }
- } else {
- MessageDialog.openError(shell, "Error", "Image not available");
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/FragmentMenu.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/FragmentMenu.java
deleted file mode 100644
index f7085fc12..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/FragmentMenu.java
+++ /dev/null
@@ -1,304 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.SdkConstants.ANDROID_LAYOUT_RESOURCE_PREFIX;
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_CLASS;
-import static com.android.SdkConstants.ATTR_NAME;
-import static com.android.SdkConstants.LAYOUT_RESOURCE_PREFIX;
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.LayoutMetadata.KEY_FRAGMENT_LAYOUT;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.resources.CyclicDependencyValidator;
-import com.android.ide.eclipse.adt.internal.ui.ResourceChooser;
-import com.android.resources.ResourceType;
-import com.android.utils.Pair;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.ActionContributionItem;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.widgets.Menu;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Fragment context menu allowing a layout to be chosen for previewing in the fragment frame.
- */
-public class FragmentMenu extends SubmenuAction {
- private static final String R_LAYOUT_RESOURCE_PREFIX = "R.layout."; //$NON-NLS-1$
- private static final String ANDROID_R_PREFIX = "android.R.layout"; //$NON-NLS-1$
-
- /** Associated canvas */
- private final LayoutCanvas mCanvas;
-
- /**
- * Creates a "Preview Fragment" menu
- *
- * @param canvas associated canvas
- */
- public FragmentMenu(LayoutCanvas canvas) {
- super("Fragment Layout");
- mCanvas = canvas;
- }
-
- @Override
- protected void addMenuItems(Menu menu) {
- IAction action = new PickLayoutAction("Choose Layout...");
- new ActionContributionItem(action).fill(menu, -1);
-
- SelectionManager selectionManager = mCanvas.getSelectionManager();
- List<SelectionItem> selections = selectionManager.getSelections();
- if (selections.size() == 0) {
- return;
- }
-
- SelectionItem first = selections.get(0);
- UiViewElementNode node = first.getViewInfo().getUiViewNode();
- if (node == null) {
- return;
- }
- Element element = (Element) node.getXmlNode();
-
- String selected = getSelectedLayout();
- if (selected != null) {
- if (selected.startsWith(ANDROID_LAYOUT_RESOURCE_PREFIX)) {
- selected = selected.substring(ANDROID_LAYOUT_RESOURCE_PREFIX.length());
- }
- }
-
- String fqcn = getFragmentClass(element);
- if (fqcn != null) {
- // Look up the corresponding activity class and try to figure out
- // which layouts it is referring to and list these here as reasonable
- // guesses
- IProject project = mCanvas.getEditorDelegate().getEditor().getProject();
- String source = null;
- try {
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
- IType type = javaProject.findType(fqcn);
- if (type != null) {
- source = type.getSource();
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- // Find layouts. This is based on just skimming the Fragment class and looking
- // for layout references of the form R.layout.*.
- if (source != null) {
- String self = mCanvas.getLayoutResourceName();
- // Pair of <title,layout> to be displayed to the user
- List<Pair<String, String>> layouts = new ArrayList<Pair<String, String>>();
-
- if (source.contains("extends ListFragment")) { //$NON-NLS-1$
- layouts.add(Pair.of("list_content", //$NON-NLS-1$
- "@android:layout/list_content")); //$NON-NLS-1$
- }
-
- int index = 0;
- while (true) {
- index = source.indexOf(R_LAYOUT_RESOURCE_PREFIX, index);
- if (index == -1) {
- break;
- } else {
- index += R_LAYOUT_RESOURCE_PREFIX.length();
- int end = index;
- while (end < source.length()) {
- char c = source.charAt(end);
- if (!Character.isJavaIdentifierPart(c)) {
- break;
- }
- end++;
- }
- if (end > index) {
- String title = source.substring(index, end);
- String layout;
- // Is this R.layout part of an android.R.layout?
- int len = ANDROID_R_PREFIX.length() + 1; // prefix length to check
- if (index > len && source.startsWith(ANDROID_R_PREFIX, index - len)) {
- layout = ANDROID_LAYOUT_RESOURCE_PREFIX + title;
- } else {
- layout = LAYOUT_RESOURCE_PREFIX + title;
- }
- if (!self.equals(title)) {
- layouts.add(Pair.of(title, layout));
- }
- }
- }
-
- index++;
- }
-
- if (layouts.size() > 0) {
- new Separator().fill(menu, -1);
- for (Pair<String, String> layout : layouts) {
- action = new SetFragmentLayoutAction(layout.getFirst(),
- layout.getSecond(), selected);
- new ActionContributionItem(action).fill(menu, -1);
- }
- }
- }
- }
-
- if (selected != null) {
- new Separator().fill(menu, -1);
- action = new SetFragmentLayoutAction("Clear", null, null);
- new ActionContributionItem(action).fill(menu, -1);
- }
- }
-
- /**
- * Returns the class name of the fragment associated with the given {@code <fragment>}
- * element.
- *
- * @param element the element for the fragment tag
- * @return the fully qualified fragment class name, or null
- */
- @Nullable
- public static String getFragmentClass(@NonNull Element element) {
- String fqcn = element.getAttribute(ATTR_CLASS);
- if (fqcn == null || fqcn.length() == 0) {
- fqcn = element.getAttributeNS(ANDROID_URI, ATTR_NAME);
- }
- if (fqcn != null && fqcn.length() > 0) {
- return fqcn;
- } else {
- return null;
- }
- }
-
- /**
- * Returns the layout to be shown for the given {@code <fragment>} node.
- *
- * @param node the node corresponding to the {@code <fragment>} element
- * @return the resource path to a layout to render for this fragment, or null
- */
- @Nullable
- public static String getFragmentLayout(@NonNull Node node) {
- String layout = LayoutMetadata.getProperty(
- node, LayoutMetadata.KEY_FRAGMENT_LAYOUT);
- if (layout != null) {
- return layout;
- }
-
- return null;
- }
-
- /** Returns the name of the currently displayed layout in the fragment, or null */
- @Nullable
- private String getSelectedLayout() {
- SelectionManager selectionManager = mCanvas.getSelectionManager();
- for (SelectionItem item : selectionManager.getSelections()) {
- UiViewElementNode node = item.getViewInfo().getUiViewNode();
- if (node != null) {
- String layout = getFragmentLayout(node.getXmlNode());
- if (layout != null) {
- return layout;
- }
- }
- }
- return null;
- }
-
- /**
- * Set the given layout as the new fragment layout
- *
- * @param layout the layout resource name to show in this fragment
- */
- public void setNewLayout(@Nullable String layout) {
- LayoutEditorDelegate delegate = mCanvas.getEditorDelegate();
- GraphicalEditorPart graphicalEditor = delegate.getGraphicalEditor();
- SelectionManager selectionManager = mCanvas.getSelectionManager();
-
- for (SelectionItem item : selectionManager.getSnapshot()) {
- UiViewElementNode node = item.getViewInfo().getUiViewNode();
- if (node != null) {
- Node xmlNode = node.getXmlNode();
- LayoutMetadata.setProperty(delegate.getEditor(), xmlNode, KEY_FRAGMENT_LAYOUT,
- layout);
- }
- }
-
- // Refresh
- graphicalEditor.recomputeLayout();
- mCanvas.redraw();
- }
-
- /** Action to set the given layout as the new layout in a fragment */
- private class SetFragmentLayoutAction extends Action {
- private final String mLayout;
-
- public SetFragmentLayoutAction(String title, String layout, String selected) {
- super(title, IAction.AS_RADIO_BUTTON);
- mLayout = layout;
-
- if (layout != null && layout.equals(selected)) {
- setChecked(true);
- }
- }
-
- @Override
- public void run() {
- if (isChecked()) {
- setNewLayout(mLayout);
- }
- }
- }
-
- /**
- * Action which brings up the "Create new XML File" wizard, pre-selected with the
- * animation category
- */
- private class PickLayoutAction extends Action {
-
- public PickLayoutAction(String title) {
- super(title, IAction.AS_PUSH_BUTTON);
- }
-
- @Override
- public void run() {
- LayoutEditorDelegate delegate = mCanvas.getEditorDelegate();
- IFile file = delegate.getEditor().getInputFile();
- GraphicalEditorPart editor = delegate.getGraphicalEditor();
- ResourceChooser dlg = ResourceChooser.create(editor, ResourceType.LAYOUT)
- .setInputValidator(CyclicDependencyValidator.create(file))
- .setInitialSize(85, 10)
- .setCurrentResource(getSelectedLayout());
- int result = dlg.open();
- if (result == ResourceChooser.CLEAR_RETURN_CODE) {
- setNewLayout(null);
- } else if (result == Window.OK) {
- String newType = dlg.getCurrentResource();
- setNewLayout(newType);
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/GCWrapper.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/GCWrapper.java
deleted file mode 100644
index 354517e76..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/GCWrapper.java
+++ /dev/null
@@ -1,645 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.DrawingStyle;
-import com.android.ide.common.api.IColor;
-import com.android.ide.common.api.IGraphics;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.Point;
-import com.android.ide.common.api.Rect;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.SWTException;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.FontMetrics;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.RGB;
-
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Wraps an SWT {@link GC} into an {@link IGraphics} interface so that {@link IViewRule} objects
- * can directly draw on the canvas.
- * <p/>
- * The actual wrapped GC object is only non-null during the context of a paint operation.
- */
-public class GCWrapper implements IGraphics {
-
- /**
- * The actual SWT {@link GC} being wrapped. This can change during the lifetime of the
- * object. It is generally set to something during an onPaint method and then changed
- * to null when not in the context of a paint.
- */
- private GC mGc;
-
- /**
- * Current style being used for drawing.
- */
- private SwtDrawingStyle mCurrentStyle = SwtDrawingStyle.INVALID;
-
- /**
- * Implementation of IColor wrapping an SWT color.
- */
- private static class ColorWrapper implements IColor {
- private final Color mColor;
-
- public ColorWrapper(Color color) {
- mColor = color;
- }
-
- public Color getColor() {
- return mColor;
- }
- }
-
- /** A map of registered colors. All these colors must be disposed at the end. */
- private final HashMap<Integer, ColorWrapper> mColorMap = new HashMap<Integer, ColorWrapper>();
-
- /**
- * A map of the {@link SwtDrawingStyle} stroke colors that we have actually
- * used (to be disposed)
- */
- private final Map<DrawingStyle, Color> mStyleStrokeMap = new EnumMap<DrawingStyle, Color>(
- DrawingStyle.class);
-
- /**
- * A map of the {@link SwtDrawingStyle} fill colors that we have actually
- * used (to be disposed)
- */
- private final Map<DrawingStyle, Color> mStyleFillMap = new EnumMap<DrawingStyle, Color>(
- DrawingStyle.class);
-
- /** The cached pixel height of the default current font. */
- private int mFontHeight = 0;
-
- /** The scaling of the canvas in X. */
- private final CanvasTransform mHScale;
- /** The scaling of the canvas in Y. */
- private final CanvasTransform mVScale;
-
- public GCWrapper(CanvasTransform hScale, CanvasTransform vScale) {
- mHScale = hScale;
- mVScale = vScale;
- mGc = null;
- }
-
- void setGC(GC gc) {
- mGc = gc;
- }
-
- private GC getGc() {
- return mGc;
- }
-
- void checkGC() {
- if (mGc == null) {
- throw new RuntimeException("IGraphics used without a valid context.");
- }
- }
-
- void dispose() {
- for (ColorWrapper c : mColorMap.values()) {
- c.getColor().dispose();
- }
- mColorMap.clear();
-
- for (Color c : mStyleStrokeMap.values()) {
- c.dispose();
- }
- mStyleStrokeMap.clear();
-
- for (Color c : mStyleFillMap.values()) {
- c.dispose();
- }
- mStyleFillMap.clear();
- }
-
- //-------------
-
- @Override
- public @NonNull IColor registerColor(int rgb) {
- checkGC();
-
- Integer key = Integer.valueOf(rgb);
- ColorWrapper c = mColorMap.get(key);
- if (c == null) {
- c = new ColorWrapper(new Color(getGc().getDevice(),
- (rgb >> 16) & 0xFF,
- (rgb >> 8) & 0xFF,
- (rgb >> 0) & 0xFF));
- mColorMap.put(key, c);
- }
-
- return c;
- }
-
- /** Returns the (cached) pixel height of the current font. */
- @Override
- public int getFontHeight() {
- if (mFontHeight < 1) {
- checkGC();
- FontMetrics fm = getGc().getFontMetrics();
- mFontHeight = fm.getHeight();
- }
- return mFontHeight;
- }
-
- @Override
- public @NonNull IColor getForeground() {
- Color c = getGc().getForeground();
- return new ColorWrapper(c);
- }
-
- @Override
- public @NonNull IColor getBackground() {
- Color c = getGc().getBackground();
- return new ColorWrapper(c);
- }
-
- @Override
- public int getAlpha() {
- return getGc().getAlpha();
- }
-
- @Override
- public void setForeground(@NonNull IColor color) {
- checkGC();
- getGc().setForeground(((ColorWrapper) color).getColor());
- }
-
- @Override
- public void setBackground(@NonNull IColor color) {
- checkGC();
- getGc().setBackground(((ColorWrapper) color).getColor());
- }
-
- @Override
- public void setAlpha(int alpha) {
- checkGC();
- try {
- getGc().setAlpha(alpha);
- } catch (SWTException e) {
- // This means that we cannot set the alpha on this platform; this is
- // an acceptable no-op.
- }
- }
-
- @Override
- public void setLineStyle(@NonNull LineStyle style) {
- int swtStyle = 0;
- switch (style) {
- case LINE_SOLID:
- swtStyle = SWT.LINE_SOLID;
- break;
- case LINE_DASH:
- swtStyle = SWT.LINE_DASH;
- break;
- case LINE_DOT:
- swtStyle = SWT.LINE_DOT;
- break;
- case LINE_DASHDOT:
- swtStyle = SWT.LINE_DASHDOT;
- break;
- case LINE_DASHDOTDOT:
- swtStyle = SWT.LINE_DASHDOTDOT;
- break;
- default:
- assert false : style;
- break;
- }
-
- if (swtStyle != 0) {
- checkGC();
- getGc().setLineStyle(swtStyle);
- }
- }
-
- @Override
- public void setLineWidth(int width) {
- checkGC();
- if (width > 0) {
- getGc().setLineWidth(width);
- }
- }
-
- // lines
-
- @Override
- public void drawLine(int x1, int y1, int x2, int y2) {
- checkGC();
- useStrokeAlpha();
- x1 = mHScale.translate(x1);
- y1 = mVScale.translate(y1);
- x2 = mHScale.translate(x2);
- y2 = mVScale.translate(y2);
- getGc().drawLine(x1, y1, x2, y2);
- }
-
- @Override
- public void drawLine(@NonNull Point p1, @NonNull Point p2) {
- drawLine(p1.x, p1.y, p2.x, p2.y);
- }
-
- // rectangles
-
- @Override
- public void drawRect(int x1, int y1, int x2, int y2) {
- checkGC();
- useStrokeAlpha();
- int x = mHScale.translate(x1);
- int y = mVScale.translate(y1);
- int w = mHScale.scale(x2 - x1);
- int h = mVScale.scale(y2 - y1);
- getGc().drawRectangle(x, y, w, h);
- }
-
- @Override
- public void drawRect(@NonNull Point p1, @NonNull Point p2) {
- drawRect(p1.x, p1.y, p2.x, p2.y);
- }
-
- @Override
- public void drawRect(@NonNull Rect r) {
- checkGC();
- useStrokeAlpha();
- int x = mHScale.translate(r.x);
- int y = mVScale.translate(r.y);
- int w = mHScale.scale(r.w);
- int h = mVScale.scale(r.h);
- getGc().drawRectangle(x, y, w, h);
- }
-
- @Override
- public void fillRect(int x1, int y1, int x2, int y2) {
- checkGC();
- useFillAlpha();
- int x = mHScale.translate(x1);
- int y = mVScale.translate(y1);
- int w = mHScale.scale(x2 - x1);
- int h = mVScale.scale(y2 - y1);
- getGc().fillRectangle(x, y, w, h);
- }
-
- @Override
- public void fillRect(@NonNull Point p1, @NonNull Point p2) {
- fillRect(p1.x, p1.y, p2.x, p2.y);
- }
-
- @Override
- public void fillRect(@NonNull Rect r) {
- checkGC();
- useFillAlpha();
- int x = mHScale.translate(r.x);
- int y = mVScale.translate(r.y);
- int w = mHScale.scale(r.w);
- int h = mVScale.scale(r.h);
- getGc().fillRectangle(x, y, w, h);
- }
-
- // circles (actually ovals)
-
- public void drawOval(int x1, int y1, int x2, int y2) {
- checkGC();
- useStrokeAlpha();
- int x = mHScale.translate(x1);
- int y = mVScale.translate(y1);
- int w = mHScale.scale(x2 - x1);
- int h = mVScale.scale(y2 - y1);
- getGc().drawOval(x, y, w, h);
- }
-
- public void drawOval(Point p1, Point p2) {
- drawOval(p1.x, p1.y, p2.x, p2.y);
- }
-
- public void drawOval(Rect r) {
- checkGC();
- useStrokeAlpha();
- int x = mHScale.translate(r.x);
- int y = mVScale.translate(r.y);
- int w = mHScale.scale(r.w);
- int h = mVScale.scale(r.h);
- getGc().drawOval(x, y, w, h);
- }
-
- public void fillOval(int x1, int y1, int x2, int y2) {
- checkGC();
- useFillAlpha();
- int x = mHScale.translate(x1);
- int y = mVScale.translate(y1);
- int w = mHScale.scale(x2 - x1);
- int h = mVScale.scale(y2 - y1);
- getGc().fillOval(x, y, w, h);
- }
-
- public void fillOval(Point p1, Point p2) {
- fillOval(p1.x, p1.y, p2.x, p2.y);
- }
-
- public void fillOval(Rect r) {
- checkGC();
- useFillAlpha();
- int x = mHScale.translate(r.x);
- int y = mVScale.translate(r.y);
- int w = mHScale.scale(r.w);
- int h = mVScale.scale(r.h);
- getGc().fillOval(x, y, w, h);
- }
-
-
- // strings
-
- @Override
- public void drawString(@NonNull String string, int x, int y) {
- checkGC();
- useStrokeAlpha();
- x = mHScale.translate(x);
- y = mVScale.translate(y);
- // Background fill of text is not useful because it does not
- // use the alpha; we instead supply a separate method (drawBoxedStrings) which
- // first paints a semi-transparent mask for the text to sit on
- // top of (this ensures that the text is readable regardless of
- // colors of the pixels below the text)
- getGc().drawString(string, x, y, true /*isTransparent*/);
- }
-
- @Override
- public void drawBoxedStrings(int x, int y, @NonNull List<?> strings) {
- checkGC();
-
- x = mHScale.translate(x);
- y = mVScale.translate(y);
-
- // Compute bounds of the box by adding up the sum of the text heights
- // and the max of the text widths
- int width = 0;
- int height = 0;
- int lineHeight = getGc().getFontMetrics().getHeight();
- for (Object s : strings) {
- org.eclipse.swt.graphics.Point extent = getGc().stringExtent(s.toString());
- height += extent.y;
- width = Math.max(width, extent.x);
- }
-
- // Paint a box below the text
- int padding = 2;
- useFillAlpha();
- getGc().fillRectangle(x - padding, y - padding, width + 2 * padding, height + 2 * padding);
-
- // Finally draw strings on top
- useStrokeAlpha();
- int lineY = y;
- for (Object s : strings) {
- getGc().drawString(s.toString(), x, lineY, true /* isTransparent */);
- lineY += lineHeight;
- }
- }
-
- @Override
- public void drawString(@NonNull String string, @NonNull Point topLeft) {
- drawString(string, topLeft.x, topLeft.y);
- }
-
- // Styles
-
- @Override
- public void useStyle(@NonNull DrawingStyle style) {
- checkGC();
-
- // Look up the specific SWT style which defines the actual
- // colors and attributes to be used for the logical drawing style.
- SwtDrawingStyle swtStyle = SwtDrawingStyle.of(style);
- RGB stroke = swtStyle.getStrokeColor();
- if (stroke != null) {
- Color color = getStrokeColor(style, stroke);
- mGc.setForeground(color);
- }
- RGB fill = swtStyle.getFillColor();
- if (fill != null) {
- Color color = getFillColor(style, fill);
- mGc.setBackground(color);
- }
- mGc.setLineWidth(swtStyle.getLineWidth());
- mGc.setLineStyle(swtStyle.getLineStyle());
- if (swtStyle.getLineStyle() == SWT.LINE_CUSTOM) {
- mGc.setLineDash(new int[] {
- 8, 4
- });
- }
- mCurrentStyle = swtStyle;
- }
-
- /** Uses the stroke alpha for subsequent drawing operations. */
- private void useStrokeAlpha() {
- mGc.setAlpha(mCurrentStyle.getStrokeAlpha());
- }
-
- /** Uses the fill alpha for subsequent drawing operations. */
- private void useFillAlpha() {
- mGc.setAlpha(mCurrentStyle.getFillAlpha());
- }
-
- /**
- * Get the SWT stroke color (foreground/border) to use for the given style,
- * using the provided color description if we haven't seen this color yet.
- * The color will also be placed in the {@link #mStyleStrokeMap} such that
- * it can be disposed of at cleanup time.
- *
- * @param style The drawing style for which we want a color
- * @param defaultColorDesc The RGB values to initialize the color to if we
- * haven't seen this color before
- * @return The color object
- */
- private Color getStrokeColor(DrawingStyle style, RGB defaultColorDesc) {
- return getStyleColor(style, defaultColorDesc, mStyleStrokeMap);
- }
-
- /**
- * Get the SWT fill (background/interior) color to use for the given style,
- * using the provided color description if we haven't seen this color yet.
- * The color will also be placed in the {@link #mStyleStrokeMap} such that
- * it can be disposed of at cleanup time.
- *
- * @param style The drawing style for which we want a color
- * @param defaultColorDesc The RGB values to initialize the color to if we
- * haven't seen this color before
- * @return The color object
- */
- private Color getFillColor(DrawingStyle style, RGB defaultColorDesc) {
- return getStyleColor(style, defaultColorDesc, mStyleFillMap);
- }
-
- /**
- * Get the SWT color to use for the given style, using the provided color
- * description if we haven't seen this color yet. The color will also be
- * placed in the map referenced by the map parameter such that it can be
- * disposed of at cleanup time.
- *
- * @param style The drawing style for which we want a color
- * @param defaultColorDesc The RGB values to initialize the color to if we
- * haven't seen this color before
- * @param map The color map to use
- * @return The color object
- */
- private Color getStyleColor(DrawingStyle style, RGB defaultColorDesc,
- Map<DrawingStyle, Color> map) {
- Color color = map.get(style);
- if (color == null) {
- color = new Color(getGc().getDevice(), defaultColorDesc);
- map.put(style, color);
- }
-
- return color;
- }
-
- // dots
-
- @Override
- public void drawPoint(int x, int y) {
- checkGC();
- useStrokeAlpha();
- x = mHScale.translate(x);
- y = mVScale.translate(y);
-
- getGc().drawPoint(x, y);
- }
-
- // arrows
-
- private static final int MIN_LENGTH = 10;
-
-
- @Override
- public void drawArrow(int x1, int y1, int x2, int y2, int size) {
- int arrowWidth = size;
- int arrowHeight = size;
-
- checkGC();
- useStrokeAlpha();
- x1 = mHScale.translate(x1);
- y1 = mVScale.translate(y1);
- x2 = mHScale.translate(x2);
- y2 = mVScale.translate(y2);
- GC graphics = getGc();
-
- // Make size adjustments to ensure that the arrow has enough width to be visible
- if (x1 == x2 && Math.abs(y1 - y2) < MIN_LENGTH) {
- int delta = (MIN_LENGTH - Math.abs(y1 - y2)) / 2;
- if (y1 < y2) {
- y1 -= delta;
- y2 += delta;
- } else {
- y1 += delta;
- y2-= delta;
- }
-
- } else if (y1 == y2 && Math.abs(x1 - x2) < MIN_LENGTH) {
- int delta = (MIN_LENGTH - Math.abs(x1 - x2)) / 2;
- if (x1 < x2) {
- x1 -= delta;
- x2 += delta;
- } else {
- x1 += delta;
- x2-= delta;
- }
- }
-
- graphics.drawLine(x1, y1, x2, y2);
-
- // Arrowhead:
-
- if (x1 == x2) {
- // Vertical
- if (y2 > y1) {
- graphics.drawLine(x2 - arrowWidth, y2 - arrowHeight, x2, y2);
- graphics.drawLine(x2 + arrowWidth, y2 - arrowHeight, x2, y2);
- } else {
- graphics.drawLine(x2 - arrowWidth, y2 + arrowHeight, x2, y2);
- graphics.drawLine(x2 + arrowWidth, y2 + arrowHeight, x2, y2);
- }
- } else if (y1 == y2) {
- // Horizontal
- if (x2 > x1) {
- graphics.drawLine(x2 - arrowHeight, y2 - arrowWidth, x2, y2);
- graphics.drawLine(x2 - arrowHeight, y2 + arrowWidth, x2, y2);
- } else {
- graphics.drawLine(x2 + arrowHeight, y2 - arrowWidth, x2, y2);
- graphics.drawLine(x2 + arrowHeight, y2 + arrowWidth, x2, y2);
- }
- } else {
- // Compute angle:
- int dy = y2 - y1;
- int dx = x2 - x1;
- double angle = Math.atan2(dy, dx);
- double lineLength = Math.sqrt(dy * dy + dx * dx);
-
- // Imagine a line of the same length as the arrow, but with angle 0.
- // Its two arrow lines are at (-arrowWidth, -arrowHeight) relative
- // to the endpoint (x1 + lineLength, y1) stretching up to (x2,y2).
- // We compute the positions of (ax,ay) for the point above and
- // below this line and paint the lines to it:
- double ax = x1 + lineLength - arrowHeight;
- double ay = y1 - arrowWidth;
- int rx = (int) (Math.cos(angle) * (ax-x1) - Math.sin(angle) * (ay-y1) + x1);
- int ry = (int) (Math.sin(angle) * (ax-x1) + Math.cos(angle) * (ay-y1) + y1);
- graphics.drawLine(x2, y2, rx, ry);
-
- ay = y1 + arrowWidth;
- rx = (int) (Math.cos(angle) * (ax-x1) - Math.sin(angle) * (ay-y1) + x1);
- ry = (int) (Math.sin(angle) * (ax-x1) + Math.cos(angle) * (ay-y1) + y1);
- graphics.drawLine(x2, y2, rx, ry);
- }
-
- /* TODO: Experiment with filled arrow heads?
- if (x1 == x2) {
- // Vertical
- if (y2 > y1) {
- for (int i = 0; i < arrowWidth; i++) {
- graphics.drawLine(x2 - arrowWidth + i, y2 - arrowWidth + i,
- x2 + arrowWidth - i, y2 - arrowWidth + i);
- }
- } else {
- for (int i = 0; i < arrowWidth; i++) {
- graphics.drawLine(x2 - arrowWidth + i, y2 + arrowWidth - i,
- x2 + arrowWidth - i, y2 + arrowWidth - i);
- }
- }
- } else if (y1 == y2) {
- // Horizontal
- if (x2 > x1) {
- for (int i = 0; i < arrowHeight; i++) {
- graphics.drawLine(x2 - arrowHeight + i, y2 - arrowHeight + i, x2
- - arrowHeight + i, y2 + arrowHeight - i);
- }
- } else {
- for (int i = 0; i < arrowHeight; i++) {
- graphics.drawLine(x2 + arrowHeight - i, y2 - arrowHeight + i, x2
- + arrowHeight - i, y2 + arrowHeight - i);
- }
- }
- } else {
- // Arbitrary angle -- need to use trig
- // TODO: Implement this
- }
- */
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/Gesture.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/Gesture.java
deleted file mode 100644
index a35d19078..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/Gesture.java
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.utils.Pair;
-
-import org.eclipse.swt.events.KeyEvent;
-
-import java.util.Collections;
-import java.util.List;
-
-/**
- * A gesture is a mouse or keyboard driven user operation, such as a
- * swipe-select or a resize. It can be thought of as a session, since it is
- * initiated, updated during user manipulation, and finally completed or
- * canceled. A gesture is associated with a single undo transaction (although
- * some gestures don't actually edit anything, such as a selection), and a
- * gesture can have a number of graphics {@link Overlay}s which are added and
- * cleaned up on behalf of the gesture by the system.
- * <p/>
- * Gestures are typically mouse oriented. If a mouse wishes to integrate
- * with the native drag &amp; drop support, it should also implement
- * the {@link DropGesture} interface, which is a sub interface of this
- * {@link Gesture} interface. There are pros and cons to using native drag
- * &amp; drop, so various gestures will differ in whether they use it.
- * In particular, you should use drag &amp; drop if your gesture should:
- * <ul>
- * <li> Show a native drag &amp; drop cursor
- * <li> Copy or move data, especially if this applies outside the canvas
- * control window or even the application itself
- * </ul>
- * You might want to avoid using native drag &amp; drop if your gesture should:
- * <ul>
- * <li> Continue updating itself even when the mouse cursor leaves the
- * canvas window (in a drag &amp; gesture, as soon as you leave the canvas
- * the drag source is no longer informed of mouse updates, whereas a regular
- * mouse listener is)
- * <li> Respond to modifier keys (for example, if toggling the Shift key
- * should constrain motion as is common during resizing, and so on)
- * <li> Use no special cursor (for example, during a marquee selection gesture we
- * don't want a native drag &amp; drop cursor)
- * </ul>
- * <p/>
- * Examples of gestures:
- * <ul>
- * <li>Move (dragging to reorder or change hierarchy of views or change visual
- * layout attributes)
- * <li>Marquee (swiping out a rectangle to make a selection)
- * <li>Resize (dragging some edge or corner of a widget to change its size, for
- * example to some new fixed size, or to "attach" it to some other edge.)
- * <li>Inline Editing (editing the text of some text-oriented widget like a
- * label or a button)
- * <li>Link (associate two or more widgets in some way, such as an
- * "is required" widget linked to a text field)
- * </ul>
- */
-public abstract class Gesture {
- /** Start mouse coordinate, in control coordinates. */
- protected ControlPoint mStart;
-
- /** Initial SWT mask when the gesture started. */
- protected int mStartMask;
-
- /**
- * Returns a list of overlays, from bottom to top (where the later overlays
- * are painted on top of earlier ones if they overlap).
- *
- * @return A list of overlays to paint for this gesture, if applicable.
- * Should not be null, but can be empty.
- */
- public List<Overlay> createOverlays() {
- return Collections.emptyList();
- }
-
- /**
- * Handles initialization of this gesture. Called when the gesture is
- * starting.
- *
- * @param pos The most recent mouse coordinate applicable to this
- * gesture, relative to the canvas control.
- * @param startMask The initial SWT mask for the gesture, if known, or
- * otherwise 0.
- */
- public void begin(ControlPoint pos, int startMask) {
- mStart = pos;
- mStartMask = startMask;
- }
-
- /**
- * Handles updating of the gesture state for a new mouse position.
- *
- * @param pos The most recent mouse coordinate applicable to this
- * gesture, relative to the canvas control.
- */
- public void update(ControlPoint pos) {
- }
-
- /**
- * Handles termination of the gesture. This method is called when the
- * gesture has terminated (either through successful completion, or because
- * it was canceled).
- *
- * @param pos The most recent mouse coordinate applicable to this
- * gesture, relative to the canvas control.
- * @param canceled True if the gesture was canceled, and false otherwise.
- */
- public void end(ControlPoint pos, boolean canceled) {
- }
-
- /**
- * Handles a key press during the gesture. May be called repeatedly when the
- * user is holding the key for several seconds.
- *
- * @param event The SWT event for the key press,
- * @return true if this gesture consumed the key press, otherwise return false
- */
- public boolean keyPressed(KeyEvent event) {
- return false;
- }
-
- /**
- * Handles a key release during the gesture.
- *
- * @param event The SWT event for the key release,
- * @return true if this gesture consumed the key press, otherwise return false
- */
- public boolean keyReleased(KeyEvent event) {
- return false;
- }
-
- /**
- * Returns whether tooltips should be display below and to the right of the mouse
- * cursor.
- *
- * @return a pair of booleans, the first indicating whether the tooltip should be
- * below and the second indicating whether the tooltip should be displayed to
- * the right of the mouse cursor.
- */
- public Pair<Boolean, Boolean> getTooltipPosition() {
- return Pair.of(true, true);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/GestureManager.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/GestureManager.java
deleted file mode 100644
index 98bc25e37..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/GestureManager.java
+++ /dev/null
@@ -1,930 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.SdkConstants;
-import com.android.ide.common.api.DropFeedback;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.api.SegmentType;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.NodeProxy;
-import com.android.utils.Pair;
-
-import org.eclipse.jface.action.IStatusLineManager;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DragSource;
-import org.eclipse.swt.dnd.DragSourceEvent;
-import org.eclipse.swt.dnd.DragSourceListener;
-import org.eclipse.swt.dnd.DropTarget;
-import org.eclipse.swt.dnd.DropTargetEvent;
-import org.eclipse.swt.dnd.DropTargetListener;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.KeyListener;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseListener;
-import org.eclipse.swt.events.MouseMoveListener;
-import org.eclipse.swt.events.MouseTrackListener;
-import org.eclipse.swt.events.TypedEvent;
-import org.eclipse.swt.graphics.Cursor;
-import org.eclipse.swt.graphics.Device;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.ImageData;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IEditorSite;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * The {@link GestureManager} is is the central manager of gestures; it is responsible
- * for recognizing when particular gestures should begin and terminate. It
- * listens to the drag, mouse and keyboard systems to find out when to start
- * gestures and in order to update the gestures along the way.
- */
-public class GestureManager {
- /** The canvas which owns this GestureManager. */
- private final LayoutCanvas mCanvas;
-
- /** The currently executing gesture, or null. */
- private Gesture mCurrentGesture;
-
- /** A listener for drop target events. */
- private final DropTargetListener mDropListener = new CanvasDropListener();
-
- /** A listener for drag source events. */
- private final DragSourceListener mDragSourceListener = new CanvasDragSourceListener();
-
- /** Tooltip shown during the gesture, or null */
- private GestureToolTip mTooltip;
-
- /**
- * The list of overlays associated with {@link #mCurrentGesture}. Will be
- * null before it has been initialized lazily by the paint routine (the
- * initialized value can never be null, but it can be an empty collection).
- */
- private List<Overlay> mOverlays;
-
- /**
- * Most recently seen mouse position (x coordinate). We keep a copy of this
- * value since we sometimes need to know it when we aren't told about the
- * mouse position (such as when a keystroke is received, such as an arrow
- * key in order to tweak the current drop position)
- */
- protected int mLastMouseX;
-
- /**
- * Most recently seen mouse position (y coordinate). We keep a copy of this
- * value since we sometimes need to know it when we aren't told about the
- * mouse position (such as when a keystroke is received, such as an arrow
- * key in order to tweak the current drop position)
- */
- protected int mLastMouseY;
-
- /**
- * Most recently seen mouse mask. We keep a copy of this since in some
- * scenarios (such as on a drag gesture) we don't get access to it.
- */
- protected int mLastStateMask;
-
- /**
- * Listener for mouse motion, click and keyboard events.
- */
- private Listener mListener;
-
- /**
- * When we the drag leaves, we don't know if that's the last we'll see of
- * this drag or if it's just temporarily outside the canvas and it will
- * return. We want to restore it if it comes back. This is also necessary
- * because even on a drop we'll receive a
- * {@link DropTargetListener#dragLeave} right before the drop, and we need
- * to restore it in the drop. Therefore, when we lose a {@link DropGesture}
- * to a {@link DropTargetListener#dragLeave}, we store a reference to the
- * current gesture as a {@link #mZombieGesture}, since the gesture is dead
- * but might be brought back to life if we see a subsequent
- * {@link DropTargetListener#dragEnter} before another gesture begins.
- */
- private DropGesture mZombieGesture;
-
- /**
- * Flag tracking whether we've set a message or error message on the global status
- * line (since we only want to clear that message if we have set it ourselves).
- * This is the actual message rather than a boolean such that (if we can get our
- * hands on the global message) we can check to see if the current message is the
- * one we set and only in that case clear it when it is no longer applicable.
- */
- private String mDisplayingMessage;
-
- /**
- * Constructs a new {@link GestureManager} for the given
- * {@link LayoutCanvas}.
- *
- * @param canvas The canvas which controls this {@link GestureManager}
- */
- public GestureManager(LayoutCanvas canvas) {
- mCanvas = canvas;
- }
-
- /**
- * Returns the canvas associated with this GestureManager.
- *
- * @return The {@link LayoutCanvas} associated with this GestureManager.
- * Never null.
- */
- public LayoutCanvas getCanvas() {
- return mCanvas;
- }
-
- /**
- * Returns the current gesture, if one is in progress, and otherwise returns
- * null.
- *
- * @return The current gesture or null.
- */
- public Gesture getCurrentGesture() {
- return mCurrentGesture;
- }
-
- /**
- * Paints the overlays associated with the current gesture, if any.
- *
- * @param gc The graphics object to paint into.
- */
- public void paint(GC gc) {
- if (mCurrentGesture == null) {
- return;
- }
-
- if (mOverlays == null) {
- mOverlays = mCurrentGesture.createOverlays();
- Device device = gc.getDevice();
- for (Overlay overlay : mOverlays) {
- overlay.create(device);
- }
- }
- for (Overlay overlay : mOverlays) {
- overlay.paint(gc);
- }
- }
-
- /**
- * Registers all the listeners needed by the {@link GestureManager}.
- *
- * @param dragSource The drag source in the {@link LayoutCanvas} to listen
- * to.
- * @param dropTarget The drop target in the {@link LayoutCanvas} to listen
- * to.
- */
- public void registerListeners(DragSource dragSource, DropTarget dropTarget) {
- assert mListener == null;
- mListener = new Listener();
- mCanvas.addMouseMoveListener(mListener);
- mCanvas.addMouseListener(mListener);
- mCanvas.addKeyListener(mListener);
-
- if (dragSource != null) {
- dragSource.addDragListener(mDragSourceListener);
- }
- if (dropTarget != null) {
- dropTarget.addDropListener(mDropListener);
- }
- }
-
- /**
- * Unregisters all the listeners previously registered by
- * {@link #registerListeners}.
- *
- * @param dragSource The drag source in the {@link LayoutCanvas} to stop
- * listening to.
- * @param dropTarget The drop target in the {@link LayoutCanvas} to stop
- * listening to.
- */
- public void unregisterListeners(DragSource dragSource, DropTarget dropTarget) {
- if (mCanvas.isDisposed()) {
- // If the LayoutCanvas is already disposed, we shouldn't try to unregister
- // the listeners; they are already not active and an attempt to remove the
- // listener will throw a widget-is-disposed exception.
- mListener = null;
- return;
- }
-
- if (mListener != null) {
- mCanvas.removeMouseMoveListener(mListener);
- mCanvas.removeMouseListener(mListener);
- mCanvas.removeKeyListener(mListener);
- mListener = null;
- }
-
- if (dragSource != null) {
- dragSource.removeDragListener(mDragSourceListener);
- }
- if (dropTarget != null) {
- dropTarget.removeDropListener(mDropListener);
- }
- }
-
- /**
- * Starts the given gesture.
- *
- * @param mousePos The most recent mouse coordinate applicable to the new
- * gesture, in control coordinates.
- * @param gesture The gesture to initiate
- */
- private void startGesture(ControlPoint mousePos, Gesture gesture, int mask) {
- if (mCurrentGesture != null) {
- finishGesture(mousePos, true);
- assert mCurrentGesture == null;
- }
-
- if (gesture != null) {
- mCurrentGesture = gesture;
- mCurrentGesture.begin(mousePos, mask);
- }
- }
-
- /**
- * Updates the current gesture, if any, for the given event.
- *
- * @param mousePos The most recent mouse coordinate applicable to the new
- * gesture, in control coordinates.
- * @param event The event corresponding to this update. May be null. Don't
- * make any assumptions about the type of this event - for
- * example, it may not always be a MouseEvent, it could be a
- * DragSourceEvent, etc.
- */
- private void updateMouse(ControlPoint mousePos, TypedEvent event) {
- if (mCurrentGesture != null) {
- mCurrentGesture.update(mousePos);
- }
- }
-
- /**
- * Finish the given gesture, either from successful completion or from
- * cancellation.
- *
- * @param mousePos The most recent mouse coordinate applicable to the new
- * gesture, in control coordinates.
- * @param canceled True if and only if the gesture was canceled.
- */
- private void finishGesture(ControlPoint mousePos, boolean canceled) {
- if (mCurrentGesture != null) {
- mCurrentGesture.end(mousePos, canceled);
- if (mOverlays != null) {
- for (Overlay overlay : mOverlays) {
- overlay.dispose();
- }
- mOverlays = null;
- }
- mCurrentGesture = null;
- mZombieGesture = null;
- mLastStateMask = 0;
- updateMessage(null);
- updateCursor(mousePos);
- mCanvas.redraw();
- }
- }
-
- /**
- * Update the cursor to show the type of operation we expect on a mouse press:
- * <ul>
- * <li>Over a selection handle, show a directional cursor depending on the position of
- * the selection handle
- * <li>Over a widget, show a move (hand) cursor
- * <li>Otherwise, show the default arrow cursor
- * </ul>
- */
- void updateCursor(ControlPoint controlPoint) {
- // We don't hover on the root since it's not a widget per see and it is always there.
- SelectionManager selectionManager = mCanvas.getSelectionManager();
-
- if (!selectionManager.isEmpty()) {
- Display display = mCanvas.getDisplay();
- Pair<SelectionItem, SelectionHandle> handlePair =
- selectionManager.findHandle(controlPoint);
- if (handlePair != null) {
- SelectionHandle handle = handlePair.getSecond();
- int cursorType = handle.getSwtCursorType();
- Cursor cursor = display.getSystemCursor(cursorType);
- if (cursor != mCanvas.getCursor()) {
- mCanvas.setCursor(cursor);
- }
- return;
- }
-
- // See if it's over a selected view
- LayoutPoint layoutPoint = controlPoint.toLayout();
- for (SelectionItem item : selectionManager.getSelections()) {
- if (item.getRect().contains(layoutPoint.x, layoutPoint.y)
- && !item.isRoot()) {
- Cursor cursor = display.getSystemCursor(SWT.CURSOR_HAND);
- if (cursor != mCanvas.getCursor()) {
- mCanvas.setCursor(cursor);
- }
- return;
- }
- }
- }
-
- if (mCanvas.getCursor() != null) {
- mCanvas.setCursor(null);
- }
- }
-
- /**
- * Update the Eclipse status message with any feedback messages from the given
- * {@link DropFeedback} object, or clean up if there is no more feedback to process
- * @param feedback the feedback whose message we want to display, or null to clear the
- * message if previously set
- */
- void updateMessage(DropFeedback feedback) {
- IEditorSite editorSite = mCanvas.getEditorDelegate().getEditor().getEditorSite();
- IStatusLineManager status = editorSite.getActionBars().getStatusLineManager();
- if (feedback == null) {
- if (mDisplayingMessage != null) {
- status.setMessage(null);
- status.setErrorMessage(null);
- mDisplayingMessage = null;
- }
- } else if (feedback.errorMessage != null) {
- if (!feedback.errorMessage.equals(mDisplayingMessage)) {
- mDisplayingMessage = feedback.errorMessage;
- status.setErrorMessage(mDisplayingMessage);
- }
- } else if (feedback.message != null) {
- if (!feedback.message.equals(mDisplayingMessage)) {
- mDisplayingMessage = feedback.message;
- status.setMessage(mDisplayingMessage);
- }
- } else if (mDisplayingMessage != null) {
- // TODO: Can we check the existing message and only clear it if it's the
- // same as the one we set?
- mDisplayingMessage = null;
- status.setMessage(null);
- status.setErrorMessage(null);
- }
-
- // Tooltip
- if (feedback != null && feedback.tooltip != null) {
- Pair<Boolean,Boolean> position = mCurrentGesture.getTooltipPosition();
- boolean below = position.getFirst();
- if (feedback.tooltipY != null) {
- below = feedback.tooltipY == SegmentType.BOTTOM;
- }
- boolean toRightOf = position.getSecond();
- if (feedback.tooltipX != null) {
- toRightOf = feedback.tooltipX == SegmentType.RIGHT;
- }
- if (mTooltip == null) {
- mTooltip = new GestureToolTip(mCanvas, below, toRightOf);
- }
- mTooltip.update(feedback.tooltip, below, toRightOf);
- } else if (mTooltip != null) {
- mTooltip.dispose();
- mTooltip = null;
- }
- }
-
- /**
- * Returns the current mouse position as a {@link ControlPoint}
- *
- * @return the current mouse position as a {@link ControlPoint}
- */
- public ControlPoint getCurrentControlPoint() {
- return ControlPoint.create(mCanvas, mLastMouseX, mLastMouseY);
- }
-
- /**
- * Returns the current SWT modifier key mask as an {@link IViewRule} modifier mask
- *
- * @return the current SWT modifier key mask as an {@link IViewRule} modifier mask
- */
- public int getRuleModifierMask() {
- int swtMask = mLastStateMask;
- int modifierMask = 0;
- if ((swtMask & SWT.MOD1) != 0) {
- modifierMask |= DropFeedback.MODIFIER1;
- }
- if ((swtMask & SWT.MOD2) != 0) {
- modifierMask |= DropFeedback.MODIFIER2;
- }
- if ((swtMask & SWT.MOD3) != 0) {
- modifierMask |= DropFeedback.MODIFIER3;
- }
- return modifierMask;
- }
-
- /**
- * Helper class which implements the {@link MouseMoveListener},
- * {@link MouseListener} and {@link KeyListener} interfaces.
- */
- private class Listener implements MouseMoveListener, MouseListener, MouseTrackListener,
- KeyListener {
-
- // --- MouseMoveListener ---
-
- @Override
- public void mouseMove(MouseEvent e) {
- mLastMouseX = e.x;
- mLastMouseY = e.y;
- mLastStateMask = e.stateMask;
-
- ControlPoint controlPoint = ControlPoint.create(mCanvas, e);
- if ((e.stateMask & SWT.BUTTON_MASK) != 0) {
- if (mCurrentGesture != null) {
- updateMouse(controlPoint, e);
- mCanvas.redraw();
- }
- } else {
- updateCursor(controlPoint);
- mCanvas.hover(e);
- mCanvas.getPreviewManager().moved(controlPoint);
- }
- }
-
- // --- MouseListener ---
-
- @Override
- public void mouseUp(MouseEvent e) {
- ControlPoint mousePos = ControlPoint.create(mCanvas, e);
-
- if (mCurrentGesture == null) {
- // If clicking on a configuration preview, just process it there
- if (mCanvas.getPreviewManager().click(mousePos)) {
- return;
- }
-
- // Just a click, select
- Pair<SelectionItem, SelectionHandle> handlePair =
- mCanvas.getSelectionManager().findHandle(mousePos);
- if (handlePair == null) {
- mCanvas.getSelectionManager().select(e);
- }
- }
- if (mCurrentGesture == null) {
- updateCursor(mousePos);
- } else if (mCurrentGesture instanceof DropGesture) {
- // Mouse Up shouldn't be delivered in the middle of a drag & drop -
- // but this can happen on some versions of Linux
- // (see http://code.google.com/p/android/issues/detail?id=19057 )
- // and if we process the mouseUp it will abort the remainder of
- // the drag & drop operation, so ignore this event!
- } else {
- finishGesture(mousePos, false);
- }
- mCanvas.redraw();
- }
-
- @Override
- public void mouseDown(MouseEvent e) {
- mLastMouseX = e.x;
- mLastMouseY = e.y;
- mLastStateMask = e.stateMask;
-
- // Not yet used. Should be, for Mac and Linux.
- }
-
- @Override
- public void mouseDoubleClick(MouseEvent e) {
- // SWT delivers a double click event even if you click two different buttons
- // in rapid succession. In any case, we only want to let you double click the
- // first button to warp to XML:
- if (e.button == 1) {
- // Warp to the text editor and show the corresponding XML for the
- // double-clicked widget
- LayoutPoint p = ControlPoint.create(mCanvas, e).toLayout();
- CanvasViewInfo vi = mCanvas.getViewHierarchy().findViewInfoAt(p);
- if (vi != null) {
- mCanvas.show(vi);
- }
- }
- }
-
- // --- MouseTrackListener ---
-
- @Override
- public void mouseEnter(MouseEvent e) {
- ControlPoint mousePos = ControlPoint.create(mCanvas, e);
- mCanvas.getPreviewManager().enter(mousePos);
- }
-
- @Override
- public void mouseExit(MouseEvent e) {
- ControlPoint mousePos = ControlPoint.create(mCanvas, e);
- mCanvas.getPreviewManager().exit(mousePos);
- }
-
- @Override
- public void mouseHover(MouseEvent e) {
- }
-
- // --- KeyListener ---
-
- @Override
- public void keyPressed(KeyEvent e) {
- mLastStateMask = e.stateMask;
- // Workaround for the fact that in keyPressed the current state
- // mask is not yet updated
- if (e.keyCode == SWT.SHIFT) {
- mLastStateMask |= SWT.MOD2;
- }
- if (SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_DARWIN) {
- if (e.keyCode == SWT.COMMAND) {
- mLastStateMask |= SWT.MOD1;
- }
- } else {
- if (e.keyCode == SWT.CTRL) {
- mLastStateMask |= SWT.MOD1;
- }
- }
-
- // Give gestures a first chance to see and consume the key press
- if (mCurrentGesture != null) {
- // unless it's "Escape", which cancels the gesture
- if (e.keyCode == SWT.ESC) {
- ControlPoint controlPoint = ControlPoint.create(mCanvas,
- mLastMouseX, mLastMouseY);
- finishGesture(controlPoint, true);
- return;
- }
-
- if (mCurrentGesture.keyPressed(e)) {
- return;
- }
- }
-
- // Fall back to canvas actions for the key press
- mCanvas.handleKeyPressed(e);
- }
-
- @Override
- public void keyReleased(KeyEvent e) {
- mLastStateMask = e.stateMask;
- // Workaround for the fact that in keyPressed the current state
- // mask is not yet updated
- if (e.keyCode == SWT.SHIFT) {
- mLastStateMask &= ~SWT.MOD2;
- }
- if (SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_DARWIN) {
- if (e.keyCode == SWT.COMMAND) {
- mLastStateMask &= ~SWT.MOD1;
- }
- } else {
- if (e.keyCode == SWT.CTRL) {
- mLastStateMask &= ~SWT.MOD1;
- }
- }
-
- if (mCurrentGesture != null) {
- mCurrentGesture.keyReleased(e);
- }
- }
- }
-
- /** Listener for Drag &amp; Drop events. */
- private class CanvasDropListener implements DropTargetListener {
- public CanvasDropListener() {
- }
-
- /**
- * The cursor has entered the drop target boundaries. {@inheritDoc}
- */
- @Override
- public void dragEnter(DropTargetEvent event) {
- mCanvas.showInvisibleViews(true);
- mCanvas.getEditorDelegate().getGraphicalEditor().dismissHoverPalette();
-
- if (mCurrentGesture == null) {
- Gesture newGesture = mZombieGesture;
- if (newGesture == null) {
- newGesture = new MoveGesture(mCanvas);
- } else {
- mZombieGesture = null;
- }
- startGesture(ControlPoint.create(mCanvas, event),
- newGesture, 0);
- }
-
- if (mCurrentGesture instanceof DropGesture) {
- ((DropGesture) mCurrentGesture).dragEnter(event);
- }
- }
-
- /**
- * The cursor is moving over the drop target. {@inheritDoc}
- */
- @Override
- public void dragOver(DropTargetEvent event) {
- if (mCurrentGesture instanceof DropGesture) {
- ((DropGesture) mCurrentGesture).dragOver(event);
- }
- }
-
- /**
- * The cursor has left the drop target boundaries OR data is about to be
- * dropped. {@inheritDoc}
- */
- @Override
- public void dragLeave(DropTargetEvent event) {
- if (mCurrentGesture instanceof DropGesture) {
- DropGesture dropGesture = (DropGesture) mCurrentGesture;
- dropGesture.dragLeave(event);
- finishGesture(ControlPoint.create(mCanvas, event), true);
- mZombieGesture = dropGesture;
- }
-
- mCanvas.showInvisibleViews(false);
- }
-
- /**
- * The drop is about to be performed. The drop target is given a last
- * chance to change the nature of the drop. {@inheritDoc}
- */
- @Override
- public void dropAccept(DropTargetEvent event) {
- Gesture gesture = mCurrentGesture != null ? mCurrentGesture : mZombieGesture;
- if (gesture instanceof DropGesture) {
- ((DropGesture) gesture).dropAccept(event);
- }
- }
-
- /**
- * The data is being dropped. {@inheritDoc}
- */
- @Override
- public void drop(final DropTargetEvent event) {
- // See if we had a gesture just prior to the drop (we receive a dragLeave
- // right before the drop which we don't know whether means the cursor has
- // left the canvas for good or just before a drop)
- Gesture gesture = mCurrentGesture != null ? mCurrentGesture : mZombieGesture;
- mZombieGesture = null;
-
- if (gesture instanceof DropGesture) {
- ((DropGesture) gesture).drop(event);
-
- finishGesture(ControlPoint.create(mCanvas, event), true);
- }
- }
-
- /**
- * The operation being performed has changed (e.g. modifier key).
- * {@inheritDoc}
- */
- @Override
- public void dragOperationChanged(DropTargetEvent event) {
- if (mCurrentGesture instanceof DropGesture) {
- ((DropGesture) mCurrentGesture).dragOperationChanged(event);
- }
- }
- }
-
- /**
- * Our canvas {@link DragSourceListener}. Handles drag being started and
- * finished and generating the drag data.
- */
- private class CanvasDragSourceListener implements DragSourceListener {
-
- /**
- * The current selection being dragged. This may be a subset of the
- * canvas selection due to the "sanitize" pass. Can be empty but never
- * null.
- */
- private final ArrayList<SelectionItem> mDragSelection = new ArrayList<SelectionItem>();
-
- private SimpleElement[] mDragElements;
-
- /**
- * The user has begun the actions required to drag the widget.
- * <p/>
- * Initiate a drag only if there is one or more item selected. If
- * there's none, try to auto-select the one under the cursor.
- * {@inheritDoc}
- */
- @Override
- public void dragStart(DragSourceEvent e) {
- LayoutPoint p = LayoutPoint.create(mCanvas, e);
- ControlPoint controlPoint = ControlPoint.create(mCanvas, e);
- SelectionManager selectionManager = mCanvas.getSelectionManager();
-
- // See if the mouse is over a selection handle; if so, start a resizing
- // gesture.
- Pair<SelectionItem, SelectionHandle> handle =
- selectionManager.findHandle(controlPoint);
- if (handle != null) {
- startGesture(controlPoint, new ResizeGesture(mCanvas, handle.getFirst(),
- handle.getSecond()), mLastStateMask);
- e.detail = DND.DROP_NONE;
- e.doit = false;
- mCanvas.redraw();
- return;
- }
-
- // We need a selection (simple or multiple) to do any transfer.
- // If there's a selection *and* the cursor is over this selection,
- // use all the currently selected elements.
- // If there is no selection or the cursor is not over a selected
- // element, *change* the selection to match the element under the
- // cursor and use that. If nothing can be selected, abort the drag
- // operation.
- List<SelectionItem> selections = selectionManager.getSelections();
- mDragSelection.clear();
- SelectionItem primary = null;
-
- if (!selections.isEmpty()) {
- // Is the cursor on top of a selected element?
- boolean insideSelection = false;
-
- for (SelectionItem cs : selections) {
- if (!cs.isRoot() && cs.getRect().contains(p.x, p.y)) {
- primary = cs;
- insideSelection = true;
- break;
- }
- }
-
- if (!insideSelection) {
- CanvasViewInfo vi = mCanvas.getViewHierarchy().findViewInfoAt(p);
- if (vi != null && !vi.isRoot() && !vi.isHidden()) {
- primary = selectionManager.selectSingle(vi);
- insideSelection = true;
- }
- }
-
- if (insideSelection) {
- // We should now have a proper selection that matches the
- // cursor. Let's use this one. We make a copy of it since
- // the "sanitize" pass below might remove some of the
- // selected objects.
- if (selections.size() == 1) {
- // You are dragging just one element - this might or
- // might not be the root, but if it's the root that is
- // fine since we will let you drag the root if it is the
- // only thing you are dragging.
- mDragSelection.addAll(selections);
- } else {
- // Only drag non-root items.
- for (SelectionItem cs : selections) {
- if (!cs.isRoot() && !cs.isHidden()) {
- mDragSelection.add(cs);
- } else if (cs == primary) {
- primary = null;
- }
- }
- }
- }
- }
-
- // If you are dragging a non-selected item, select it
- if (mDragSelection.isEmpty()) {
- CanvasViewInfo vi = mCanvas.getViewHierarchy().findViewInfoAt(p);
- if (vi != null && !vi.isRoot() && !vi.isHidden()) {
- primary = selectionManager.selectSingle(vi);
- mDragSelection.addAll(selections);
- }
- }
-
- SelectionManager.sanitize(mDragSelection);
-
- e.doit = !mDragSelection.isEmpty();
- int imageCount = mDragSelection.size();
- if (e.doit) {
- mDragElements = SelectionItem.getAsElements(mDragSelection, primary);
- GlobalCanvasDragInfo.getInstance().startDrag(mDragElements,
- mDragSelection.toArray(new SelectionItem[imageCount]),
- mCanvas, new Runnable() {
- @Override
- public void run() {
- mCanvas.getClipboardSupport().deleteSelection("Remove",
- mDragSelection);
- }
- });
- }
-
- // If you drag on the -background-, we make that into a marquee
- // selection
- if (!e.doit || (imageCount == 1
- && (mDragSelection.get(0).isRoot() || mDragSelection.get(0).isHidden()))) {
- boolean toggle = (mLastStateMask & (SWT.CTRL | SWT.SHIFT | SWT.COMMAND)) != 0;
- startGesture(controlPoint,
- new MarqueeGesture(mCanvas, toggle), mLastStateMask);
- e.detail = DND.DROP_NONE;
- e.doit = false;
- } else {
- // Otherwise, the drag means you are moving something
- mCanvas.showInvisibleViews(true);
- startGesture(controlPoint, new MoveGesture(mCanvas), 0);
-
- // Render drag-images: Copy portions of the full screen render.
- Image image = mCanvas.getImageOverlay().getImage();
- if (image != null) {
- /**
- * Transparency of the dragged image ([0-255]). We're using 30%
- * translucency to make the image faint and not obscure the drag
- * feedback below it.
- */
- final byte DRAG_TRANSPARENCY = (byte) (0.3 * 255);
-
- List<Rectangle> rectangles = new ArrayList<Rectangle>(imageCount);
- if (imageCount > 0) {
- ImageData data = image.getImageData();
- Rectangle imageRectangle = new Rectangle(0, 0, data.width, data.height);
- for (SelectionItem item : mDragSelection) {
- Rectangle bounds = item.getRect();
- // Some bounds can be outside the rendered rectangle (for
- // example, in an absolute layout, you can have negative
- // coordinates), so create the intersection of these bounds.
- Rectangle clippedBounds = imageRectangle.intersection(bounds);
- rectangles.add(clippedBounds);
- }
- Rectangle boundingBox = ImageUtils.getBoundingRectangle(rectangles);
- double scale = mCanvas.getHorizontalTransform().getScale();
- e.image = SwtUtils.drawRectangles(image, rectangles, boundingBox, scale,
- DRAG_TRANSPARENCY);
-
- // Set the image offset such that we preserve the relative
- // distance between the mouse pointer and the top left corner of
- // the dragged view
- int deltaX = (int) (scale * (boundingBox.x - p.x));
- int deltaY = (int) (scale * (boundingBox.y - p.y));
- e.offsetX = -deltaX;
- e.offsetY = -deltaY;
-
- // View rules may need to know it as well
- GlobalCanvasDragInfo dragInfo = GlobalCanvasDragInfo.getInstance();
- Rect dragBounds = null;
- int width = (int) (scale * boundingBox.width);
- int height = (int) (scale * boundingBox.height);
- dragBounds = new Rect(deltaX, deltaY, width, height);
- dragInfo.setDragBounds(dragBounds);
-
- // Record the baseline such that we can perform baseline alignment
- // on the node as it's dragged around
- NodeProxy firstNode =
- mCanvas.getNodeFactory().create(mDragSelection.get(0).getViewInfo());
- dragInfo.setDragBaseline(firstNode.getBaseline());
- }
- }
- }
-
- // No hover during drag (since no mouse over events are delivered
- // during a drag to keep the hovers up to date anyway)
- mCanvas.clearHover();
-
- mCanvas.redraw();
- }
-
- /**
- * Callback invoked when data is needed for the event, typically right
- * before drop. The drop side decides what type of transfer to use and
- * this side must now provide the adequate data. {@inheritDoc}
- */
- @Override
- public void dragSetData(DragSourceEvent e) {
- if (TextTransfer.getInstance().isSupportedType(e.dataType)) {
- e.data = SelectionItem.getAsText(mCanvas, mDragSelection);
- return;
- }
-
- if (SimpleXmlTransfer.getInstance().isSupportedType(e.dataType)) {
- e.data = mDragElements;
- return;
- }
-
- // otherwise we failed
- e.detail = DND.DROP_NONE;
- e.doit = false;
- }
-
- /**
- * Callback invoked when the drop has been finished either way. On a
- * successful move, remove the originating elements.
- */
- @Override
- public void dragFinished(DragSourceEvent e) {
- // Clear the selection
- mDragSelection.clear();
- mDragElements = null;
- GlobalCanvasDragInfo.getInstance().stopDrag();
-
- finishGesture(ControlPoint.create(mCanvas, e), e.detail == DND.DROP_NONE);
- mCanvas.showInvisibleViews(false);
- mCanvas.redraw();
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/GestureToolTip.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/GestureToolTip.java
deleted file mode 100644
index a49e79cbf..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/GestureToolTip.java
+++ /dev/null
@@ -1,217 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.CLabel;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.FontData;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-
-/**
- * A dedicated tooltip used during gestures, for example to show the resize dimensions.
- * <p>
- * This is necessary because {@link org.eclipse.jface.window.ToolTip} causes flicker when
- * used to dynamically update the position and text of the tip, and it does not seem to
- * have setter methods to update the text or position without recreating the tip.
- */
-public class GestureToolTip {
- /** Minimum number of milliseconds to wait between alignment changes */
- private static final int TIMEOUT_MS = 750;
-
- /**
- * The alpha to use for the tooltip window (which sadly will apply to the tooltip text
- * as well.)
- */
- private static final int SHELL_TRANSPARENCY = 220;
-
- /** The size of the font displayed in the tooltip */
- private static final int FONT_SIZE = 9;
-
- /** Horizontal delta from the mouse cursor to shift the tooltip by */
- private static final int OFFSET_X = 20;
-
- /** Vertical delta from the mouse cursor to shift the tooltip by */
- private static final int OFFSET_Y = 20;
-
- /** The label which displays the tooltip */
- private CLabel mLabel;
-
- /** The shell holding the tooltip */
- private Shell mShell;
-
- /** The font shown in the label; held here such that it can be disposed of after use */
- private Font mFont;
-
- /** Is the tooltip positioned below the given anchor? */
- private boolean mBelow;
-
- /** Is the tooltip positioned to the right of the given anchor? */
- private boolean mToRightOf;
-
- /** Is an alignment change pending? */
- private boolean mTimerPending;
-
- /** The new value for {@link #mBelow} when the timer expires */
- private boolean mPendingBelow;
-
- /** The new value for {@link #mToRightOf} when the timer expires */
- private boolean mPendingRight;
-
- /** The time stamp (from {@link System#currentTimeMillis()} of the last alignment change */
- private long mLastAlignmentTime;
-
- /**
- * Creates a new tooltip over the given parent with the given relative position.
- *
- * @param parent the parent control
- * @param below if true, display the tooltip below the mouse cursor otherwise above
- * @param toRightOf if true, display the tooltip to the right of the mouse cursor,
- * otherwise to the left
- */
- public GestureToolTip(Composite parent, boolean below, boolean toRightOf) {
- mBelow = below;
- mToRightOf = toRightOf;
- mLastAlignmentTime = System.currentTimeMillis();
-
- mShell = new Shell(parent.getShell(), SWT.ON_TOP | SWT.TOOL | SWT.NO_FOCUS);
- mShell.setLayout(new FillLayout());
- mShell.setAlpha(SHELL_TRANSPARENCY);
-
- Display display = parent.getDisplay();
- mLabel = new CLabel(mShell, SWT.SHADOW_NONE);
- mLabel.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
- mLabel.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
-
- Font systemFont = display.getSystemFont();
- FontData[] fd = systemFont.getFontData();
- for (int i = 0; i < fd.length; i++) {
- fd[i].setHeight(FONT_SIZE);
- }
- mFont = new Font(display, fd);
- mLabel.setFont(mFont);
-
- mShell.setVisible(false);
- }
-
- /**
- * Show the tooltip at the given position and with the given text. Note that the
- * position may not be applied immediately; to prevent flicker alignment changes
- * are queued up with a timer (unless it's been a while since the last change, in
- * which case the update is applied immediately.)
- *
- * @param text the new text to be displayed
- * @param below if true, display the tooltip below the mouse cursor otherwise above
- * @param toRightOf if true, display the tooltip to the right of the mouse cursor,
- * otherwise to the left
- */
- public void update(final String text, boolean below, boolean toRightOf) {
- // If the alignment has not changed recently, just apply the change immediately
- // instead of within a delay
- if (!mTimerPending && (below != mBelow || toRightOf != mToRightOf)
- && (System.currentTimeMillis() - mLastAlignmentTime >= TIMEOUT_MS)) {
- mBelow = below;
- mToRightOf = toRightOf;
- mLastAlignmentTime = System.currentTimeMillis();
- }
-
- Point location = mShell.getDisplay().getCursorLocation();
-
- mLabel.setText(text);
-
- // Pack the label to its minimum size -- unless we are positioning the tooltip
- // on the left. Because of the way SWT works (at least on the OSX) this sometimes
- // creates flicker, because when we switch to a longer string (such as when
- // switching from "52dp" to "wrap_content" during a resize) the window size will
- // change first, and then the location will update later - so there will be a
- // brief flash of the longer label before it is moved to the right position on the
- // left. To work around this, we simply pass false to pack such that it will reuse
- // its cached size, which in practice means that for labels on the right, the
- // label will grow but not shrink.
- // This workaround is disabled because it doesn't work well in Eclipse 3.5; the
- // labels don't grow when they should. Re-enable when we drop 3.5 support.
- //boolean changed = mToRightOf;
- boolean changed = true;
-
- mShell.pack(changed);
- Point size = mShell.getSize();
-
- // Position the tooltip to the left or right, and above or below, according
- // to the saved state of these flags, not the current parameters. We don't want
- // to flicker, instead we react on a timer to changes in alignment below.
- if (mBelow) {
- location.y += OFFSET_Y;
- } else {
- location.y -= OFFSET_Y;
- location.y -= size.y;
- }
-
- if (mToRightOf) {
- location.x += OFFSET_X;
- } else {
- location.x -= OFFSET_X;
- location.x -= size.x;
- }
-
- mShell.setLocation(location);
-
- if (!mShell.isVisible()) {
- mShell.setVisible(true);
- }
-
- // Has the orientation changed?
- mPendingBelow = below;
- mPendingRight = toRightOf;
- if (below != mBelow || toRightOf != mToRightOf) {
- // Yes, so schedule a timer (unless one is already scheduled)
- if (!mTimerPending) {
- mTimerPending = true;
- final Runnable timer = new Runnable() {
- @Override
- public void run() {
- mTimerPending = false;
- // Check whether the alignment is still different than the target
- // (since we may change back and forth repeatedly during the timeout)
- if (mBelow != mPendingBelow || mToRightOf != mPendingRight) {
- mBelow = mPendingBelow;
- mToRightOf = mPendingRight;
- mLastAlignmentTime = System.currentTimeMillis();
- if (mShell != null && mShell.isVisible()) {
- update(text, mBelow, mToRightOf);
- }
- }
- }
- };
- mShell.getDisplay().timerExec(TIMEOUT_MS, timer);
- }
- }
- }
-
- /** Hide the tooltip and dispose of any associated resources */
- public void dispose() {
- mShell.dispose();
- mFont.dispose();
-
- mShell = null;
- mFont = null;
- mLabel = null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/GlobalCanvasDragInfo.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/GlobalCanvasDragInfo.java
deleted file mode 100644
index b918b00bf..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/GlobalCanvasDragInfo.java
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.Rect;
-
-
-/**
- * This singleton is used to keep track of drag'n'drops initiated within this
- * session of Eclipse. A drag can be initiated from a palette or from a canvas
- * and its content is an Android View fully-qualified class name.
- * <p/>
- * Overall this is a workaround: the issue is that the drag'n'drop SWT API does not
- * allow us to know the transfered data during the initial drag -- only when the
- * data is dropped do we know what it is about (and to be more exact there is a workaround
- * to do just that which works on Windows but not on Linux/Mac SWT).
- * <p/>
- * In the GLE we'd like to adjust drag feedback to the data being actually dropped.
- * The singleton instance of this class will be used to track the data currently dragged
- * off a canvas or its palette and then set back to null when the drag'n'drop is finished.
- * <p/>
- * Note that when a drag starts in one instance of Eclipse and the dragOver/drop is done
- * in a <em>separate</em> instance of Eclipse, the dragged FQCN won't be registered here
- * and will be null.
- */
-final class GlobalCanvasDragInfo {
-
- private static final GlobalCanvasDragInfo sInstance = new GlobalCanvasDragInfo();
-
- private SimpleElement[] mCurrentElements = null;
- private SelectionItem[] mCurrentSelection;
- private Object mSourceCanvas = null;
- private Runnable mRemoveSourceHandler;
- private Rect mDragBounds;
- private int mDragBaseline = -1;
-
- /** Private constructor. Use {@link #getInstance()} to retrieve the singleton. */
- private GlobalCanvasDragInfo() {
- // pass
- }
-
- /** Returns the singleton instance. */
- public static GlobalCanvasDragInfo getInstance() {
- return sInstance;
- }
-
- /**
- * Registers the XML elements being dragged.
- *
- * @param elements The elements being dragged
- * @param primary the "primary" element among the elements; when there is a
- * single item dragged this will be the same, but in
- * multi-selection it will be the element under the mouse as the
- * selection was initiated
- * @param selection The selection (which can be null, for example when the
- * user drags from the palette)
- * @param sourceCanvas An object representing the source we are dragging
- * from (used for identity comparisons only)
- * @param removeSourceHandler A runnable (or null) which can clean up the
- * source. It should only be invoked if the drag operation is a
- * move, not a copy.
- */
- public void startDrag(
- @NonNull SimpleElement[] elements,
- @Nullable SelectionItem[] selection,
- @Nullable Object sourceCanvas,
- @Nullable Runnable removeSourceHandler) {
- mCurrentElements = elements;
- mCurrentSelection = selection;
- mSourceCanvas = sourceCanvas;
- mRemoveSourceHandler = removeSourceHandler;
- }
-
- /** Unregisters elements being dragged. */
- public void stopDrag() {
- mCurrentElements = null;
- mCurrentSelection = null;
- mSourceCanvas = null;
- mRemoveSourceHandler = null;
- mDragBounds = null;
- }
-
- public boolean isDragging() {
- return mCurrentElements != null;
- }
-
- /** Returns the elements being dragged. */
- @NonNull
- public SimpleElement[] getCurrentElements() {
- return mCurrentElements;
- }
-
- /** Returns the selection originally dragged.
- * Can be null if the drag did not start in a canvas.
- */
- public SelectionItem[] getCurrentSelection() {
- return mCurrentSelection;
- }
-
- /**
- * Returns the object that call {@link #startDrag(SimpleElement[], SelectionItem[], Object)}.
- * Can be null.
- * This is not meant to access the object indirectly, it is just meant to compare if the
- * source and the destination of the drag'n'drop are the same, so object identity
- * is all what matters.
- */
- public Object getSourceCanvas() {
- return mSourceCanvas;
- }
-
- /**
- * Removes source of the drag. This should only be called when the drag and
- * drop operation is a move (not a copy).
- */
- public void removeSource() {
- if (mRemoveSourceHandler != null) {
- mRemoveSourceHandler.run();
- mRemoveSourceHandler = null;
- }
- }
-
- /**
- * Get the bounds of the drag, relative to the starting mouse position. For example,
- * if you have a rectangular view of size 100x80, and you start dragging at position
- * (15,20) from the top left corner of this rectangle, then the drag bounds would be
- * (-15,-20, 100x80).
- * <p>
- * NOTE: The coordinate units will be in SWT/control pixels, not Android view pixels.
- * In other words, they are affected by the canvas zoom: If you zoom the view and the
- * bounds of a view grow, the drag bounds will be larger.
- *
- * @return the drag bounds, or null if there are no bounds for the current drag
- */
- public Rect getDragBounds() {
- return mDragBounds;
- }
-
- /**
- * Set the bounds of the drag, relative to the starting mouse position. See
- * {@link #getDragBounds()} for details on the semantics of the drag bounds.
- *
- * @param dragBounds the new drag bounds, or null if there are no drag bounds
- */
- public void setDragBounds(Rect dragBounds) {
- mDragBounds = dragBounds;
- }
-
- /**
- * Returns the baseline of the drag, or -1 if not applicable
- *
- * @return the current SWT modifier key mask as an {@link IViewRule} modifier mask
- */
- public int getDragBaseline() {
- return mDragBaseline;
- }
-
- /**
- * Sets the baseline of the drag
- *
- * @param baseline the new baseline
- */
- public void setDragBaseline(int baseline) {
- mDragBaseline = baseline;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/GraphicalEditorPart.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/GraphicalEditorPart.java
deleted file mode 100644
index 0f5762da6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/GraphicalEditorPart.java
+++ /dev/null
@@ -1,2937 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.SdkConstants.ANDROID_PKG;
-import static com.android.SdkConstants.ANDROID_STRING_PREFIX;
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_CONTEXT;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.FD_GEN_SOURCES;
-import static com.android.SdkConstants.GRID_LAYOUT;
-import static com.android.SdkConstants.SCROLL_VIEW;
-import static com.android.SdkConstants.STRING_PREFIX;
-import static com.android.SdkConstants.VALUE_FALSE;
-import static com.android.SdkConstants.VALUE_FILL_PARENT;
-import static com.android.SdkConstants.VALUE_MATCH_PARENT;
-import static com.android.SdkConstants.VALUE_WRAP_CONTENT;
-import static com.android.ide.common.rendering.RenderSecurityManager.ENABLED_PROPERTY;
-import static com.android.ide.eclipse.adt.internal.editors.layout.configuration.Configuration.CFG_DEVICE;
-import static com.android.ide.eclipse.adt.internal.editors.layout.configuration.Configuration.CFG_DEVICE_STATE;
-import static com.android.ide.eclipse.adt.internal.editors.layout.configuration.Configuration.CFG_FOLDER;
-import static com.android.ide.eclipse.adt.internal.editors.layout.configuration.Configuration.CFG_TARGET;
-import static com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor.viewNeedsPackage;
-import static org.eclipse.wb.core.controls.flyout.IFlyoutPreferences.DOCK_EAST;
-import static org.eclipse.wb.core.controls.flyout.IFlyoutPreferences.DOCK_WEST;
-import static org.eclipse.wb.core.controls.flyout.IFlyoutPreferences.STATE_COLLAPSED;
-import static org.eclipse.wb.core.controls.flyout.IFlyoutPreferences.STATE_OPEN;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.layout.BaseLayoutRule;
-import com.android.ide.common.rendering.LayoutLibrary;
-import com.android.ide.common.rendering.RenderSecurityException;
-import com.android.ide.common.rendering.RenderSecurityManager;
-import com.android.ide.common.rendering.StaticRenderSession;
-import com.android.ide.common.rendering.api.Capability;
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.ide.common.rendering.api.RenderSession;
-import com.android.ide.common.rendering.api.ResourceValue;
-import com.android.ide.common.rendering.api.Result;
-import com.android.ide.common.rendering.api.SessionParams.RenderingMode;
-import com.android.ide.common.resources.ResourceRepository;
-import com.android.ide.common.resources.ResourceResolver;
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.common.sdk.LoadStatus;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.IPageImageProvider;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlDelegate;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutReloadMonitor;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutReloadMonitor.ChangeFlags;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutReloadMonitor.ILayoutReloadListener;
-import com.android.ide.eclipse.adt.internal.editors.layout.ProjectCallback;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.Configuration;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigurationChooser;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigurationClient;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigurationDescription;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigurationMatcher;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.LayoutCreatorDialog;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.LayoutDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.IncludeFinder.Reference;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.PaletteControl.PalettePage;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.RulesEngine;
-import com.android.ide.eclipse.adt.internal.editors.layout.properties.PropertyFactory;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiDocumentNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.resources.ResourceHelper;
-import com.android.ide.eclipse.adt.internal.resources.manager.ProjectResources;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk.ITargetChangeListener;
-import com.android.resources.Density;
-import com.android.resources.ResourceFolderType;
-import com.android.resources.ResourceType;
-import com.android.sdklib.IAndroidTarget;
-import com.android.tools.lint.detector.api.LintUtils;
-import com.android.utils.Pair;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.QualifiedName;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jdt.core.IClasspathEntry;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IJavaModelMarker;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jdt.core.IPackageFragmentRoot;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.internal.ui.preferences.BuildPathsPropertyPage;
-import org.eclipse.jdt.ui.actions.OpenNewClassWizardAction;
-import org.eclipse.jdt.ui.wizards.NewClassWizardPage;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.SashForm;
-import org.eclipse.swt.custom.StyleRange;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.events.MouseAdapter;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.INullSelectionListener;
-import org.eclipse.ui.ISelectionListener;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.ui.part.EditorPart;
-import org.eclipse.ui.part.FileEditorInput;
-import org.eclipse.ui.part.IPageSite;
-import org.eclipse.ui.part.PageBookView;
-import org.eclipse.wb.core.controls.flyout.FlyoutControlComposite;
-import org.eclipse.wb.core.controls.flyout.IFlyoutListener;
-import org.eclipse.wb.core.controls.flyout.PluginFlyoutPreferences;
-import org.eclipse.wb.internal.core.editor.structure.PageSiteComposite;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Graphical layout editor part, version 2.
- * <p/>
- * The main component of the editor part is the {@link LayoutCanvasViewer}, which
- * actually delegates its work to the {@link LayoutCanvas} control.
- * <p/>
- * The {@link LayoutCanvasViewer} is set as the site's {@link ISelectionProvider}:
- * when the selection changes in the canvas, it is thus broadcasted to anyone listening
- * on the site's selection service.
- * <p/>
- * This part is also an {@link ISelectionListener}. It listens to the site's selection
- * service and thus receives selection changes from itself as well as the associated
- * outline and property sheet (these are registered by {@link LayoutEditorDelegate#delegateGetAdapter(Class)}).
- *
- * @since GLE2
- */
-public class GraphicalEditorPart extends EditorPart
- implements IPageImageProvider, INullSelectionListener, IFlyoutListener,
- ConfigurationClient {
-
- /*
- * Useful notes:
- * To understand Drag & drop:
- * http://www.eclipse.org/articles/Article-Workbench-DND/drag_drop.html
- *
- * To understand the site's selection listener, selection provider, and the
- * confusion of different-yet-similarly-named interfaces, consult this:
- * http://www.eclipse.org/articles/Article-WorkbenchSelections/article.html
- *
- * To summarize the selection mechanism:
- * - The workbench site selection service can be seen as "centralized"
- * service that registers selection providers and selection listeners.
- * - The editor part and the outline are selection providers.
- * - The editor part, the outline and the property sheet are listeners
- * which all listen to each others indirectly.
- */
-
- /** Property key for the window preferences for the structure flyout */
- private static final String PREF_STRUCTURE = "design.structure"; //$NON-NLS-1$
-
- /** Property key for the window preferences for the palette flyout */
- private static final String PREF_PALETTE = "design.palette"; //$NON-NLS-1$
-
- /**
- * Session-property on files which specifies the initial config state to be used on
- * this file
- */
- public final static QualifiedName NAME_INITIAL_STATE =
- new QualifiedName(AdtPlugin.PLUGIN_ID, "initialstate");//$NON-NLS-1$
-
- /**
- * Session-property on files which specifies the inclusion-context (reference to another layout
- * which should be "including" this layout) when the file is opened
- */
- public final static QualifiedName NAME_INCLUDE =
- new QualifiedName(AdtPlugin.PLUGIN_ID, "includer");//$NON-NLS-1$
-
- /** Reference to the layout editor */
- private final LayoutEditorDelegate mEditorDelegate;
-
- /** Reference to the file being edited. Can also be used to access the {@link IProject}. */
- private IFile mEditedFile;
-
- /** The configuration chooser at the top of the layout editor. */
- private ConfigurationChooser mConfigChooser;
-
- /** The sash that splits the palette from the error view.
- * The error view is shown only when needed. */
- private SashForm mSashError;
-
- /** The palette displayed on the left of the sash. */
- private PaletteControl mPalette;
-
- /** The layout canvas displayed to the right of the sash. */
- private LayoutCanvasViewer mCanvasViewer;
-
- /** The Rules Engine associated with this editor. It is project-specific. */
- private RulesEngine mRulesEngine;
-
- /** Styled text displaying the most recent error in the error view. */
- private StyledText mErrorLabel;
-
- /**
- * The resource reference to a file that should surround this file (e.g. include this file
- * visually), or null if not applicable
- */
- private Reference mIncludedWithin;
-
- private Map<ResourceType, Map<String, ResourceValue>> mConfiguredFrameworkRes;
- private Map<ResourceType, Map<String, ResourceValue>> mConfiguredProjectRes;
- private ProjectCallback mProjectCallback;
- private boolean mNeedsRecompute = false;
- private TargetListener mTargetListener;
- private ResourceResolver mResourceResolver;
- private ReloadListener mReloadListener;
- private int mMinSdkVersion;
- private int mTargetSdkVersion;
- private LayoutActionBar mActionBar;
- private OutlinePage mOutlinePage;
- private FlyoutControlComposite mStructureFlyout;
- private FlyoutControlComposite mPaletteComposite;
- private PropertyFactory mPropertyFactory;
- private boolean mRenderedOnce;
- private final Object mCredential = new Object();
-
- /**
- * Flags which tracks whether this editor is currently active which is set whenever
- * {@link #activated()} is called and clear whenever {@link #deactivated()} is called.
- * This is used to suppress repeated calls to {@link #activate()} to avoid doing
- * unnecessary work.
- */
- private boolean mActive;
-
- /**
- * Constructs a new {@link GraphicalEditorPart}
- *
- * @param editorDelegate the associated XML editor delegate
- */
- public GraphicalEditorPart(@NonNull LayoutEditorDelegate editorDelegate) {
- mEditorDelegate = editorDelegate;
- setPartName("Graphical Layout");
- }
-
- // ------------------------------------
- // Methods overridden from base classes
- //------------------------------------
-
- /**
- * Initializes the editor part with a site and input.
- * {@inheritDoc}
- */
- @Override
- public void init(IEditorSite site, IEditorInput input) throws PartInitException {
- setSite(site);
- useNewEditorInput(input);
-
- if (mTargetListener == null) {
- mTargetListener = new TargetListener();
- AdtPlugin.getDefault().addTargetListener(mTargetListener);
-
- // Trigger a check to see if the SDK needs to be reloaded (which will
- // invoke onSdkLoaded asynchronously as needed).
- AdtPlugin.getDefault().refreshSdk();
- }
- }
-
- private void useNewEditorInput(IEditorInput input) throws PartInitException {
- // The contract of init() mentions we need to fail if we can't understand the input.
- if (!(input instanceof FileEditorInput)) {
- throw new PartInitException("Input is not of type FileEditorInput: " + //$NON-NLS-1$
- input == null ? "null" : input.toString()); //$NON-NLS-1$
- }
- }
-
- @Override
- public Image getPageImage() {
- return IconFactory.getInstance().getIcon("editor_page_design"); //$NON-NLS-1$
- }
-
- @Override
- public void createPartControl(Composite parent) {
-
- Display d = parent.getDisplay();
-
- GridLayout gl = new GridLayout(1, false);
- parent.setLayout(gl);
- gl.marginHeight = gl.marginWidth = 0;
-
- // Check whether somebody has requested an initial state for the newly opened file.
- // The initial state is a serialized version of the state compatible with
- // {@link ConfigurationComposite#CONFIG_STATE}.
- String initialState = null;
- IFile file = mEditedFile;
- if (file == null) {
- IEditorInput input = mEditorDelegate.getEditor().getEditorInput();
- if (input instanceof FileEditorInput) {
- file = ((FileEditorInput) input).getFile();
- }
- }
-
- if (file != null) {
- try {
- initialState = (String) file.getSessionProperty(NAME_INITIAL_STATE);
- if (initialState != null) {
- // Only use once
- file.setSessionProperty(NAME_INITIAL_STATE, null);
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, "Can't read session property %1$s", NAME_INITIAL_STATE);
- }
- }
-
- IPreferenceStore preferenceStore = AdtPlugin.getDefault().getPreferenceStore();
- PluginFlyoutPreferences preferences;
- preferences = new PluginFlyoutPreferences(preferenceStore, PREF_PALETTE);
- preferences.initializeDefaults(DOCK_WEST, STATE_OPEN, 200);
- mPaletteComposite = new FlyoutControlComposite(parent, SWT.NONE, preferences);
- mPaletteComposite.setTitleText("Palette");
- mPaletteComposite.setMinWidth(100);
- Composite paletteParent = mPaletteComposite.getFlyoutParent();
- Composite editorParent = mPaletteComposite.getClientParent();
- mPaletteComposite.setListener(this);
-
- mPaletteComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- PageSiteComposite paletteComposite = new PageSiteComposite(paletteParent, SWT.BORDER);
- paletteComposite.setTitleText("Palette");
- paletteComposite.setTitleImage(IconFactory.getInstance().getIcon("palette"));
- PalettePage decor = new PalettePage(this);
- paletteComposite.setPage(decor);
- mPalette = (PaletteControl) decor.getControl();
- decor.createToolbarItems(paletteComposite.getToolBar());
-
- // Create the shared structure+editor area
- preferences = new PluginFlyoutPreferences(preferenceStore, PREF_STRUCTURE);
- preferences.initializeDefaults(DOCK_EAST, STATE_OPEN, 300);
- mStructureFlyout = new FlyoutControlComposite(editorParent, SWT.NONE, preferences);
- mStructureFlyout.setTitleText("Structure");
- mStructureFlyout.setMinWidth(150);
- mStructureFlyout.setListener(this);
-
- Composite layoutBarAndCanvas = new Composite(mStructureFlyout.getClientParent(), SWT.NONE);
- GridLayout gridLayout = new GridLayout(1, false);
- gridLayout.horizontalSpacing = 0;
- gridLayout.verticalSpacing = 0;
- gridLayout.marginWidth = 0;
- gridLayout.marginHeight = 0;
- layoutBarAndCanvas.setLayout(gridLayout);
-
- mConfigChooser = new ConfigurationChooser(this, layoutBarAndCanvas, initialState);
- mConfigChooser.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- mActionBar = new LayoutActionBar(layoutBarAndCanvas, SWT.NONE, this);
- GridData detailsData = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 1);
- mActionBar.setLayoutData(detailsData);
- if (file != null) {
- mActionBar.updateErrorIndicator(file);
- }
-
- mSashError = new SashForm(layoutBarAndCanvas, SWT.VERTICAL | SWT.BORDER);
- mSashError.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- mCanvasViewer = new LayoutCanvasViewer(mEditorDelegate, mRulesEngine, mSashError, SWT.NONE);
- mSashError.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
-
- mErrorLabel = new StyledText(mSashError, SWT.READ_ONLY | SWT.WRAP | SWT.V_SCROLL);
- mErrorLabel.setEditable(false);
- mErrorLabel.setBackground(d.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
- mErrorLabel.setForeground(d.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
- mErrorLabel.addMouseListener(new ErrorLabelListener());
-
- mSashError.setWeights(new int[] { 80, 20 });
- mSashError.setMaximizedControl(mCanvasViewer.getControl());
-
- // Create the structure views. We really should do this *lazily*, but that
- // seems to cause a bug: property sheet won't update. Track this down later.
- createStructureViews(mStructureFlyout.getFlyoutParent(), false);
- showStructureViews(false, false, false);
-
- // Initialize the state
- reloadPalette();
-
- IWorkbenchPartSite site = getSite();
- site.setSelectionProvider(mCanvasViewer);
- site.getPage().addSelectionListener(this);
- }
-
- private void createStructureViews(Composite parent, boolean createPropertySheet) {
- mOutlinePage = new OutlinePage(this);
- mOutlinePage.setShowPropertySheet(createPropertySheet);
- mOutlinePage.setShowHeader(true);
-
- IPageSite pageSite = new IPageSite() {
-
- @Override
- public IWorkbenchPage getPage() {
- return getSite().getPage();
- }
-
- @Override
- public ISelectionProvider getSelectionProvider() {
- return getSite().getSelectionProvider();
- }
-
- @Override
- public Shell getShell() {
- return getSite().getShell();
- }
-
- @Override
- public IWorkbenchWindow getWorkbenchWindow() {
- return getSite().getWorkbenchWindow();
- }
-
- @Override
- public void setSelectionProvider(ISelectionProvider provider) {
- getSite().setSelectionProvider(provider);
- }
-
- @Override
- public Object getAdapter(Class adapter) {
- return getSite().getAdapter(adapter);
- }
-
- @Override
- public Object getService(Class api) {
- return getSite().getService(api);
- }
-
- @Override
- public boolean hasService(Class api) {
- return getSite().hasService(api);
- }
-
- @Override
- public void registerContextMenu(String menuId, MenuManager menuManager,
- ISelectionProvider selectionProvider) {
- }
-
- @Override
- public IActionBars getActionBars() {
- return null;
- }
- };
- mOutlinePage.init(pageSite);
- mOutlinePage.createControl(parent);
- mOutlinePage.addSelectionChangedListener(new ISelectionChangedListener() {
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- getCanvasControl().getSelectionManager().setSelection(event.getSelection());
- }
- });
- }
-
- /** Shows the embedded (within the layout editor) outline and or properties */
- void showStructureViews(final boolean showOutline, final boolean showProperties,
- final boolean updateLayout) {
- Display display = mConfigChooser.getDisplay();
- if (display.getThread() != Thread.currentThread()) {
- display.asyncExec(new Runnable() {
- @Override
- public void run() {
- if (!mConfigChooser.isDisposed()) {
- showStructureViews(showOutline, showProperties, updateLayout);
- }
- }
-
- });
- return;
- }
-
- boolean show = showOutline || showProperties;
-
- Control[] children = mStructureFlyout.getFlyoutParent().getChildren();
- if (children.length == 0) {
- if (show) {
- createStructureViews(mStructureFlyout.getFlyoutParent(), showProperties);
- }
- return;
- }
-
- mOutlinePage.setShowPropertySheet(showProperties);
-
- Control control = children[0];
- if (show != control.getVisible()) {
- control.setVisible(show);
- mOutlinePage.setActive(show); // disable/re-enable listeners etc
- if (show) {
- ISelection selection = getCanvasControl().getSelectionManager().getSelection();
- mOutlinePage.selectionChanged(getEditorDelegate().getEditor(), selection);
- }
- if (updateLayout) {
- mStructureFlyout.layout();
- }
- // TODO: *dispose* the non-showing widgets to save memory?
- }
- }
-
- /**
- * Returns the property factory associated with this editor
- *
- * @return the factory
- */
- @NonNull
- public PropertyFactory getPropertyFactory() {
- if (mPropertyFactory == null) {
- mPropertyFactory = new PropertyFactory(this);
- }
-
- return mPropertyFactory;
- }
-
- /**
- * Invoked by {@link LayoutCanvas} to set the model (a.k.a. the root view info).
- *
- * @param rootViewInfo The root of the view info hierarchy. Can be null.
- */
- public void setModel(CanvasViewInfo rootViewInfo) {
- if (mOutlinePage != null) {
- mOutlinePage.setModel(rootViewInfo);
- }
- }
-
- /**
- * Listens to workbench selections that does NOT come from {@link LayoutEditorDelegate}
- * (those are generated by ourselves).
- * <p/>
- * Selection can be null, as indicated by this class implementing
- * {@link INullSelectionListener}.
- */
- @Override
- public void selectionChanged(IWorkbenchPart part, ISelection selection) {
- Object delegate = part instanceof IEditorPart ?
- LayoutEditorDelegate.fromEditor((IEditorPart) part) : null;
- if (delegate == null) {
- if (part instanceof PageBookView) {
- PageBookView pbv = (PageBookView) part;
- org.eclipse.ui.part.IPage currentPage = pbv.getCurrentPage();
- if (currentPage instanceof OutlinePage) {
- LayoutCanvas canvas = getCanvasControl();
- if (canvas != null && canvas.getOutlinePage() != currentPage) {
- // The notification is not for this view; ignore
- // (can happen when there are multiple pages simultaneously
- // visible)
- return;
- }
- }
- }
- mCanvasViewer.setSelection(selection);
- }
- }
-
- @Override
- public void dispose() {
- getSite().getPage().removeSelectionListener(this);
- getSite().setSelectionProvider(null);
-
- if (mTargetListener != null) {
- AdtPlugin.getDefault().removeTargetListener(mTargetListener);
- mTargetListener = null;
- }
-
- if (mReloadListener != null) {
- LayoutReloadMonitor.getMonitor().removeListener(mReloadListener);
- mReloadListener = null;
- }
-
- if (mCanvasViewer != null) {
- mCanvasViewer.dispose();
- mCanvasViewer = null;
- }
- super.dispose();
- }
-
- /**
- * Select the visual element corresponding to the given XML node
- * @param xmlNode The Node whose element we want to select
- */
- public void select(Node xmlNode) {
- mCanvasViewer.getCanvas().getSelectionManager().select(xmlNode);
- }
-
- // ---- Implements ConfigurationClient ----
- @Override
- public void aboutToChange(int flags) {
- if ((flags & CFG_TARGET) != 0) {
- IAndroidTarget oldTarget = mConfigChooser.getConfiguration().getTarget();
- preRenderingTargetChangeCleanUp(oldTarget);
- }
- }
-
- @Override
- public boolean changed(int flags) {
- mConfiguredFrameworkRes = mConfiguredProjectRes = null;
- mResourceResolver = null;
-
- if (mEditedFile == null) {
- return true;
- }
-
- // Before doing the normal process, test for the following case.
- // - the editor is being opened (or reset for a new input)
- // - the file being opened is not the best match for any possible configuration
- // - another random compatible config was chosen in the config composite.
- // The result is that 'match' will not be the file being edited, but because this is not
- // due to a config change, we should not trigger opening the actual best match (also,
- // because the editor is still opening the MatchingStrategy woudln't answer true
- // and the best match file would open in a different editor).
- // So the solution is that if the editor is being created, we just call recomputeLayout
- // without looking for a better matching layout file.
- if (mEditorDelegate.getEditor().isCreatingPages()) {
- recomputeLayout();
- } else {
- boolean affectsFileSelection = (flags & Configuration.MASK_FILE_ATTRS) != 0;
- IFile best = null;
- // get the resources of the file's project.
- if (affectsFileSelection) {
- best = ConfigurationMatcher.getBestFileMatch(mConfigChooser);
- }
- if (best != null) {
- if (!best.equals(mEditedFile)) {
- try {
- // tell the editor that the next replacement file is due to a config
- // change.
- mEditorDelegate.setNewFileOnConfigChange(true);
-
- boolean reuseEditor = AdtPrefs.getPrefs().isSharedLayoutEditor();
- if (!reuseEditor) {
- String data = ConfigurationDescription.getDescription(best);
- if (data == null) {
- // Not previously opened: duplicate the current state as
- // much as possible
- data = mConfigChooser.getConfiguration().toPersistentString();
- ConfigurationDescription.setDescription(best, data);
- }
- }
-
- // ask the IDE to open the replacement file.
- IDE.openEditor(getSite().getWorkbenchWindow().getActivePage(), best,
- CommonXmlEditor.ID);
-
- // we're done!
- return reuseEditor;
- } catch (PartInitException e) {
- // FIXME: do something!
- }
- }
-
- // at this point, we have not opened a new file.
-
- // Store the state in the current file
- mConfigChooser.saveConstraints();
-
- // Even though the layout doesn't change, the config changed, and referenced
- // resources need to be updated.
- recomputeLayout();
- } else if (affectsFileSelection) {
- // display the error.
- Configuration configuration = mConfigChooser.getConfiguration();
- FolderConfiguration currentConfig = configuration.getFullConfig();
- displayError(
- "No resources match the configuration\n" +
- " \n" +
- "\t%1$s\n" +
- " \n" +
- "Change the configuration or create:\n" +
- " \n" +
- "\tres/%2$s/%3$s\n" +
- " \n" +
- "You can also click the 'Create New...' item in the configuration " +
- "dropdown menu above.",
- currentConfig.toDisplayString(),
- currentConfig.getFolderName(ResourceFolderType.LAYOUT),
- mEditedFile.getName());
- } else {
- // Something else changed, such as the theme - just recompute existing
- // layout
- mConfigChooser.saveConstraints();
- recomputeLayout();
- }
- }
-
- if ((flags & CFG_TARGET) != 0) {
- Configuration configuration = mConfigChooser.getConfiguration();
- IAndroidTarget target = configuration.getTarget();
- Sdk current = Sdk.getCurrent();
- if (current != null) {
- AndroidTargetData targetData = current.getTargetData(target);
- updateCapabilities(targetData);
- }
- }
-
- if ((flags & (CFG_DEVICE | CFG_DEVICE_STATE)) != 0) {
- // When the device changes, zoom the view to fit, but only up to 100% (e.g. zoom
- // out to fit the content, or zoom back in if we were zoomed out more from the
- // previous view, but only up to 100% such that we never blow up pixels
- if (mActionBar.isZoomingAllowed()) {
- getCanvasControl().setFitScale(true, true /*allowZoomIn*/);
- }
- }
-
- reloadPalette();
-
- getCanvasControl().getPreviewManager().configurationChanged(flags);
-
- return true;
- }
-
- @Override
- public void setActivity(@NonNull String activity) {
- ManifestInfo manifest = ManifestInfo.get(mEditedFile.getProject());
- String pkg = manifest.getPackage();
- if (activity.startsWith(pkg) && activity.length() > pkg.length()
- && activity.charAt(pkg.length()) == '.') {
- activity = activity.substring(pkg.length());
- }
- CommonXmlEditor editor = getEditorDelegate().getEditor();
- Element element = editor.getUiRootNode().getXmlDocument().getDocumentElement();
- AdtUtils.setToolsAttribute(editor,
- element, "Choose Activity", ATTR_CONTEXT,
- activity, false /*reveal*/, false /*append*/);
- }
-
- /**
- * Returns a {@link ProjectResources} for the framework resources based on the current
- * configuration selection.
- * @return the framework resources or null if not found.
- */
- @Override
- @Nullable
- public ResourceRepository getFrameworkResources() {
- return getFrameworkResources(getRenderingTarget());
- }
-
- /**
- * Returns a {@link ProjectResources} for the framework resources of a given
- * target.
- * @param target the target for which to return the framework resources.
- * @return the framework resources or null if not found.
- */
- @Override
- @Nullable
- public ResourceRepository getFrameworkResources(@Nullable IAndroidTarget target) {
- if (target != null) {
- AndroidTargetData data = Sdk.getCurrent().getTargetData(target);
-
- if (data != null) {
- return data.getFrameworkResources();
- }
- }
-
- return null;
- }
-
- @Override
- @Nullable
- public ProjectResources getProjectResources() {
- if (mEditedFile != null) {
- ResourceManager manager = ResourceManager.getInstance();
- return manager.getProjectResources(mEditedFile.getProject());
- }
-
- return null;
- }
-
-
- @Override
- @NonNull
- public Map<ResourceType, Map<String, ResourceValue>> getConfiguredFrameworkResources() {
- if (mConfiguredFrameworkRes == null && mConfigChooser != null) {
- ResourceRepository frameworkRes = getFrameworkResources();
-
- if (frameworkRes == null) {
- AdtPlugin.log(IStatus.ERROR, "Failed to get ProjectResource for the framework");
- } else {
- // get the framework resource values based on the current config
- mConfiguredFrameworkRes = frameworkRes.getConfiguredResources(
- mConfigChooser.getConfiguration().getFullConfig());
- }
- }
-
- return mConfiguredFrameworkRes;
- }
-
- @Override
- @NonNull
- public Map<ResourceType, Map<String, ResourceValue>> getConfiguredProjectResources() {
- if (mConfiguredProjectRes == null && mConfigChooser != null) {
- ProjectResources project = getProjectResources();
-
- // get the project resource values based on the current config
- mConfiguredProjectRes = project.getConfiguredResources(
- mConfigChooser.getConfiguration().getFullConfig());
- }
-
- return mConfiguredProjectRes;
- }
-
- @Override
- public void createConfigFile() {
- LayoutCreatorDialog dialog = new LayoutCreatorDialog(mConfigChooser.getShell(),
- mEditedFile.getName(), mConfigChooser.getConfiguration().getFullConfig());
- if (dialog.open() != Window.OK) {
- return;
- }
-
- FolderConfiguration config = new FolderConfiguration();
- dialog.getConfiguration(config);
-
- // Creates a new layout file from the specified {@link FolderConfiguration}.
- CreateNewConfigJob job = new CreateNewConfigJob(this, mEditedFile, config);
- job.schedule();
- }
-
- /**
- * Returns the resource name of the file that is including this current layout, if any
- * (may be null)
- *
- * @return the resource name of an including layout, or null
- */
- @Override
- public Reference getIncludedWithin() {
- return mIncludedWithin;
- }
-
- @Override
- @Nullable
- public LayoutCanvas getCanvas() {
- return getCanvasControl();
- }
-
- /**
- * Listens to target changed in the current project, to trigger a new layout rendering.
- */
- private class TargetListener implements ITargetChangeListener {
-
- @Override
- public void onProjectTargetChange(IProject changedProject) {
- if (changedProject != null && changedProject.equals(getProject())) {
- updateEditor();
- }
- }
-
- @Override
- public void onTargetLoaded(IAndroidTarget loadedTarget) {
- IAndroidTarget target = getRenderingTarget();
- if (target != null && target.equals(loadedTarget)) {
- updateEditor();
- }
- }
-
- @Override
- public void onSdkLoaded() {
- // get the current rendering target to unload it
- IAndroidTarget oldTarget = getRenderingTarget();
- preRenderingTargetChangeCleanUp(oldTarget);
-
- computeSdkVersion();
-
- // get the project target
- Sdk currentSdk = Sdk.getCurrent();
- if (currentSdk != null) {
- IAndroidTarget target = currentSdk.getTarget(mEditedFile.getProject());
- if (target != null) {
- mConfigChooser.onSdkLoaded(target);
- changed(CFG_FOLDER | CFG_TARGET);
- }
- }
- }
-
- private void updateEditor() {
- mEditorDelegate.getEditor().commitPages(false /* onSave */);
-
- // because the target changed we must reset the configured resources.
- mConfiguredFrameworkRes = mConfiguredProjectRes = null;
- mResourceResolver = null;
-
- // make sure we remove the custom view loader, since its parent class loader is the
- // bridge class loader.
- mProjectCallback = null;
-
- // recreate the ui root node always, this will also call onTargetChange
- // on the config composite
- mEditorDelegate.delegateInitUiRootNode(true /*force*/);
- }
-
- private IProject getProject() {
- return getEditorDelegate().getEditor().getProject();
- }
- }
-
- /** Refresh the configured project resources associated with this editor */
- public void refreshProjectResources() {
- mConfiguredProjectRes = null;
- mResourceResolver = null;
- }
-
- /**
- * Returns the currently edited file
- *
- * @return the currently edited file, or null
- */
- public IFile getEditedFile() {
- return mEditedFile;
- }
-
- /**
- * Returns the project for the currently edited file, or null
- *
- * @return the project containing the edited file, or null
- */
- public IProject getProject() {
- if (mEditedFile != null) {
- return mEditedFile.getProject();
- } else {
- return null;
- }
- }
-
- // ----------------
-
- /**
- * Save operation in the Graphical Editor Part.
- * <p/>
- * In our workflow, the model is owned by the Structured XML Editor.
- * The graphical layout editor just displays it -- thus we don't really
- * save anything here.
- * <p/>
- * This must NOT call the parent editor part. At the contrary, the parent editor
- * part will call this *after* having done the actual save operation.
- * <p/>
- * The only action this editor must do is mark the undo command stack as
- * being no longer dirty.
- */
- @Override
- public void doSave(IProgressMonitor monitor) {
- // TODO implement a command stack
-// getCommandStack().markSaveLocation();
-// firePropertyChange(PROP_DIRTY);
- }
-
- /**
- * Save operation in the Graphical Editor Part.
- * <p/>
- * In our workflow, the model is owned by the Structured XML Editor.
- * The graphical layout editor just displays it -- thus we don't really
- * save anything here.
- */
- @Override
- public void doSaveAs() {
- // pass
- }
-
- /**
- * In our workflow, the model is owned by the Structured XML Editor.
- * The graphical layout editor just displays it -- thus we don't really
- * save anything here.
- */
- @Override
- public boolean isDirty() {
- return false;
- }
-
- /**
- * In our workflow, the model is owned by the Structured XML Editor.
- * The graphical layout editor just displays it -- thus we don't really
- * save anything here.
- */
- @Override
- public boolean isSaveAsAllowed() {
- return false;
- }
-
- @Override
- public void setFocus() {
- // TODO Auto-generated method stub
-
- }
-
- /**
- * Responds to a page change that made the Graphical editor page the activated page.
- */
- public void activated() {
- if (!mActive) {
- mActive = true;
-
- syncDockingState();
- mActionBar.updateErrorIndicator();
-
- boolean changed = mConfigChooser.syncRenderState();
- if (changed) {
- // Will also force recomputeLayout()
- return;
- }
-
- if (mNeedsRecompute) {
- recomputeLayout();
- }
-
- mCanvasViewer.getCanvas().syncPreviewMode();
- }
- }
-
- /**
- * The global docking state version. This number is incremented each time
- * the user customizes the window layout in any layout.
- */
- private static int sDockingStateVersion;
-
- /**
- * The window docking state version that this window is currently showing;
- * when a different window is reconfigured, the global version number is
- * incremented, and when this window is shown, and the current version is
- * less than the global version, the window layout will be synced.
- */
- private int mDockingStateVersion;
-
- /**
- * Syncs the window docking state.
- * <p>
- * The layout editor lets you change the docking state -- e.g. you can minimize the
- * palette, and drag the structure view to the bottom, and so on. When you restart
- * the IDE, the window comes back up with your customized state.
- * <p>
- * <b>However</b>, when you have multiple editor files open, if you minimize the palette
- * in one editor and then switch to another, the other editor will have the old window
- * state. That's because each editor has its own set of windows.
- * <p>
- * This method fixes this. Whenever a window is shown, this method is called, and the
- * docking state is synced such that the editor will match the current persistent docking
- * state.
- */
- private void syncDockingState() {
- if (mDockingStateVersion == sDockingStateVersion) {
- // No changes to apply
- return;
- }
- mDockingStateVersion = sDockingStateVersion;
-
- IPreferenceStore preferenceStore = AdtPlugin.getDefault().getPreferenceStore();
- PluginFlyoutPreferences preferences;
- preferences = new PluginFlyoutPreferences(preferenceStore, PREF_PALETTE);
- mPaletteComposite.apply(preferences);
- preferences = new PluginFlyoutPreferences(preferenceStore, PREF_STRUCTURE);
- mStructureFlyout.apply(preferences);
- mPaletteComposite.layout();
- mStructureFlyout.layout();
- mPaletteComposite.redraw(); // the structure view is nested within the palette
- }
-
- /**
- * Responds to a page change that made the Graphical editor page the deactivated page
- */
- public void deactivated() {
- mActive = false;
-
- LayoutCanvas canvas = getCanvasControl();
- if (canvas != null) {
- canvas.deactivated();
- }
- }
-
- /**
- * Opens and initialize the editor with a new file.
- * @param file the file being edited.
- */
- public void openFile(IFile file) {
- mEditedFile = file;
- mConfigChooser.setFile(mEditedFile);
-
- if (mReloadListener == null) {
- mReloadListener = new ReloadListener();
- LayoutReloadMonitor.getMonitor().addListener(mEditedFile.getProject(), mReloadListener);
- }
-
- if (mRulesEngine == null) {
- mRulesEngine = new RulesEngine(this, mEditedFile.getProject());
- if (mCanvasViewer != null) {
- mCanvasViewer.getCanvas().setRulesEngine(mRulesEngine);
- }
- }
-
- // Pick up hand-off data: somebody requesting this file to be opened may have
- // requested that it should be opened as included within another file
- if (mEditedFile != null) {
- try {
- mIncludedWithin = (Reference) mEditedFile.getSessionProperty(NAME_INCLUDE);
- if (mIncludedWithin != null) {
- // Only use once
- mEditedFile.setSessionProperty(NAME_INCLUDE, null);
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, "Can't access session property %1$s", NAME_INCLUDE);
- }
- }
-
- computeSdkVersion();
- }
-
- /**
- * Resets the editor with a replacement file.
- * @param file the replacement file.
- */
- public void replaceFile(IFile file) {
- mEditedFile = file;
- mConfigChooser.replaceFile(mEditedFile);
- computeSdkVersion();
- }
-
- /**
- * Resets the editor with a replacement file coming from a config change in the config
- * selector.
- * @param file the replacement file.
- */
- public void changeFileOnNewConfig(IFile file) {
- mEditedFile = file;
- mConfigChooser.changeFileOnNewConfig(mEditedFile);
- }
-
- /**
- * Responds to a target change for the project of the edited file
- */
- public void onTargetChange() {
- AndroidTargetData targetData = mConfigChooser.onXmlModelLoaded();
- updateCapabilities(targetData);
-
- changed(CFG_FOLDER | CFG_TARGET);
- }
-
- /** Updates the capabilities for the given target data (which may be null) */
- private void updateCapabilities(AndroidTargetData targetData) {
- if (targetData != null) {
- LayoutLibrary layoutLib = targetData.getLayoutLibrary();
- if (mIncludedWithin != null && !layoutLib.supports(Capability.EMBEDDED_LAYOUT)) {
- showIn(null);
- }
- }
- }
-
- /**
- * Returns the {@link CommonXmlDelegate} for this editor
- *
- * @return the {@link CommonXmlDelegate} for this editor
- */
- @NonNull
- public LayoutEditorDelegate getEditorDelegate() {
- return mEditorDelegate;
- }
-
- /**
- * Returns the {@link RulesEngine} associated with this editor
- *
- * @return the {@link RulesEngine} associated with this editor, never null
- */
- public RulesEngine getRulesEngine() {
- return mRulesEngine;
- }
-
- /**
- * Return the {@link LayoutCanvas} associated with this editor
- *
- * @return the associated {@link LayoutCanvas}
- */
- public LayoutCanvas getCanvasControl() {
- if (mCanvasViewer != null) {
- return mCanvasViewer.getCanvas();
- }
- return null;
- }
-
- /**
- * Returns the {@link UiDocumentNode} for the XML model edited by this editor
- *
- * @return the associated model
- */
- public UiDocumentNode getModel() {
- return mEditorDelegate.getUiRootNode();
- }
-
- /**
- * Callback for XML model changed. Only update/recompute the layout if the editor is visible
- */
- public void onXmlModelChanged() {
- // To optimize the rendering when the user is editing in the XML pane, we don't
- // refresh the editor if it's not the active part.
- //
- // This behavior is acceptable when the editor is the single "full screen" part
- // (as in this case active means visible.)
- // Unfortunately this breaks in 2 cases:
- // - when performing a drag'n'drop from one editor to another, the target is not
- // properly refreshed before it becomes active.
- // - when duplicating the editor window and placing both editors side by side (xml in one
- // and canvas in the other one), the canvas may not be refreshed when the XML is edited.
- //
- // TODO find a way to really query whether the pane is visible, not just active.
-
- if (mEditorDelegate.isGraphicalEditorActive()) {
- recomputeLayout();
- } else {
- // Remember we want to recompute as soon as the editor becomes active.
- mNeedsRecompute = true;
- }
- }
-
- /**
- * Recomputes the layout
- */
- public void recomputeLayout() {
- try {
- if (!ensureFileValid()) {
- return;
- }
-
- UiDocumentNode model = getModel();
- LayoutCanvas canvas = mCanvasViewer.getCanvas();
- if (!ensureModelValid(model)) {
- // Although we display an error, we still treat an empty document as a
- // successful layout result so that we can drop new elements in it.
- //
- // For that purpose, create a special LayoutScene that has no image,
- // no root view yet indicates success and then update the canvas with it.
-
- canvas.setSession(
- new StaticRenderSession(
- Result.Status.SUCCESS.createResult(),
- null /*rootViewInfo*/, null /*image*/),
- null /*explodeNodes*/, true /* layoutlib5 */);
- return;
- }
-
- LayoutLibrary layoutLib = getReadyLayoutLib(true /*displayError*/);
-
- if (layoutLib != null) {
- // if drawing in real size, (re)set the scaling factor.
- if (mActionBar.isZoomingRealSize()) {
- mActionBar.computeAndSetRealScale(false /* redraw */);
- }
-
- IProject project = mEditedFile.getProject();
- renderWithBridge(project, model, layoutLib);
-
- canvas.getPreviewManager().renderPreviews();
- }
- } finally {
- // no matter the result, we are done doing the recompute based on the latest
- // resource/code change.
- mNeedsRecompute = false;
- }
- }
-
- /**
- * Reloads the palette
- */
- public void reloadPalette() {
- if (mPalette != null) {
- IAndroidTarget renderingTarget = getRenderingTarget();
- if (renderingTarget != null) {
- mPalette.reloadPalette(renderingTarget);
- }
- }
- }
-
- /**
- * Returns the {@link LayoutLibrary} associated with this editor, if it has
- * been initialized already. May return null if it has not been initialized (or has
- * not finished initializing).
- *
- * @return The {@link LayoutLibrary}, or null
- */
- public LayoutLibrary getLayoutLibrary() {
- return getReadyLayoutLib(false /*displayError*/);
- }
-
- /**
- * Returns the scale to multiply pixels in the layout coordinate space with to obtain
- * the corresponding dip (device independent pixel)
- *
- * @return the scale to multiple layout coordinates with to obtain the dip position
- */
- public float getDipScale() {
- float dpi = mConfigChooser.getConfiguration().getDensity().getDpiValue();
- return Density.DEFAULT_DENSITY / dpi;
- }
-
- // --- private methods ---
-
- /**
- * Ensure that the file associated with this editor is valid (exists and is
- * synchronized). Any reasons why it is not are displayed in the editor's error area.
- *
- * @return True if the editor is valid, false otherwise.
- */
- private boolean ensureFileValid() {
- // check that the resource exists. If the file is opened but the project is closed
- // or deleted for some reason (changed from outside of eclipse), then this will
- // return false;
- if (mEditedFile.exists() == false) {
- displayError("Resource '%1$s' does not exist.",
- mEditedFile.getFullPath().toString());
- return false;
- }
-
- if (mEditedFile.isSynchronized(IResource.DEPTH_ZERO) == false) {
- String message = String.format("%1$s is out of sync. Please refresh.",
- mEditedFile.getName());
-
- displayError(message);
-
- // also print it in the error console.
- IProject iProject = mEditedFile.getProject();
- AdtPlugin.printErrorToConsole(iProject.getName(), message);
- return false;
- }
-
- return true;
- }
-
- /**
- * Returns a {@link LayoutLibrary} that is ready for rendering, or null if the bridge
- * is not available or not ready yet (due to SDK loading still being in progress etc).
- * If enabled, any reasons preventing the bridge from being returned are displayed to the
- * editor's error area.
- *
- * @param displayError whether to display the loading error or not.
- *
- * @return LayoutBridge the layout bridge for rendering this editor's scene
- */
- LayoutLibrary getReadyLayoutLib(boolean displayError) {
- Sdk currentSdk = Sdk.getCurrent();
- if (currentSdk != null) {
- IAndroidTarget target = getRenderingTarget();
-
- if (target != null) {
- AndroidTargetData data = currentSdk.getTargetData(target);
- if (data != null) {
- LayoutLibrary layoutLib = data.getLayoutLibrary();
-
- if (layoutLib.getStatus() == LoadStatus.LOADED) {
- return layoutLib;
- } else if (displayError) { // getBridge() == null
- // SDK is loaded but not the layout library!
-
- // check whether the bridge managed to load, or not
- if (layoutLib.getStatus() == LoadStatus.LOADING) {
- displayError("Eclipse is loading framework information and the layout library from the SDK folder.\n%1$s will refresh automatically once the process is finished.",
- mEditedFile.getName());
- } else {
- String message = layoutLib.getLoadMessage();
- displayError("Eclipse failed to load the framework information and the layout library!" +
- message != null ? "\n" + message : "");
- }
- }
- } else { // data == null
- // It can happen that the workspace refreshes while the SDK is loading its
- // data, which could trigger a redraw of the opened layout if some resources
- // changed while Eclipse is closed.
- // In this case data could be null, but this is not an error.
- // We can just silently return, as all the opened editors are automatically
- // refreshed once the SDK finishes loading.
- LoadStatus targetLoadStatus = currentSdk.checkAndLoadTargetData(target, null);
-
- // display error is asked.
- if (displayError) {
- String targetName = target.getName();
- switch (targetLoadStatus) {
- case LOADING:
- String s;
- if (currentSdk.getTarget(getProject()) == target) {
- s = String.format(
- "The project target (%1$s) is still loading.",
- targetName);
- } else {
- s = String.format(
- "The rendering target (%1$s) is still loading.",
- targetName);
- }
- s += "\nThe layout will refresh automatically once the process is finished.";
- displayError(s);
-
- break;
- case FAILED: // known failure
- case LOADED: // success but data isn't loaded?!?!
- displayError("The project target (%s) was not properly loaded.",
- targetName);
- break;
- }
- }
- }
-
- } else if (displayError) { // target == null
- displayError("The project target is not set. Right click project, choose Properties | Android.");
- }
- } else if (displayError) { // currentSdk == null
- displayError("Eclipse is loading the SDK.\n%1$s will refresh automatically once the process is finished.",
- mEditedFile.getName());
- }
-
- return null;
- }
-
- /**
- * Returns the {@link IAndroidTarget} used for the rendering.
- * <p/>
- * This first looks for the rendering target setup in the config UI, and if nothing has
- * been setup yet, returns the target of the project.
- *
- * @return an IAndroidTarget object or null if no target is setup and the project has no
- * target set.
- *
- */
- public IAndroidTarget getRenderingTarget() {
- // if the SDK is null no targets are loaded.
- Sdk currentSdk = Sdk.getCurrent();
- if (currentSdk == null) {
- return null;
- }
-
- // attempt to get a target from the configuration selector.
- IAndroidTarget renderingTarget = mConfigChooser.getConfiguration().getTarget();
- if (renderingTarget != null) {
- return renderingTarget;
- }
-
- // fall back to the project target
- if (mEditedFile != null) {
- return currentSdk.getTarget(mEditedFile.getProject());
- }
-
- return null;
- }
-
- /**
- * Returns whether the current rendering target supports the given capability
- *
- * @param capability the capability to be looked up
- * @return true if the current rendering target supports the given capability
- */
- public boolean renderingSupports(Capability capability) {
- IAndroidTarget target = getRenderingTarget();
- if (target != null) {
- AndroidTargetData targetData = Sdk.getCurrent().getTargetData(target);
- LayoutLibrary layoutLib = targetData.getLayoutLibrary();
- return layoutLib.supports(capability);
- }
-
- return false;
- }
-
- private boolean ensureModelValid(UiDocumentNode model) {
- // check there is actually a model (maybe the file is empty).
- if (model.getUiChildren().size() == 0) {
- if (mEditorDelegate.getEditor().isCreatingPages()) {
- displayError("Loading editor");
- return false;
- }
- displayError(
- "No XML content. Please add a root view or layout to your document.");
- return false;
- }
-
- return true;
- }
-
- /**
- * Creates a {@link RenderService} associated with this editor
- * @return the render service
- */
- @NonNull
- public RenderService createRenderService() {
- return RenderService.create(this, mCredential);
- }
-
- /**
- * Creates a {@link RenderLogger} associated with this editor
- * @param name the name of the logger
- * @return the new logger
- */
- @NonNull
- public RenderLogger createRenderLogger(String name) {
- return new RenderLogger(name, mCredential);
- }
-
- /**
- * Creates a {@link RenderService} associated with this editor
- *
- * @param configuration the configuration to use (and fallback to editor for the rest)
- * @param resolver a resource resolver to use to look up resources
- * @return the render service
- */
- @NonNull
- public RenderService createRenderService(Configuration configuration,
- ResourceResolver resolver) {
- return RenderService.create(this, configuration, resolver, mCredential);
- }
-
- private void renderWithBridge(IProject iProject, UiDocumentNode model,
- LayoutLibrary layoutLib) {
- LayoutCanvas canvas = getCanvasControl();
- Set<UiElementNode> explodeNodes = canvas.getNodesToExplode();
- RenderLogger logger = createRenderLogger(mEditedFile.getName());
- RenderingMode renderingMode = RenderingMode.NORMAL;
- // FIXME set the rendering mode using ViewRule or something.
- List<UiElementNode> children = model.getUiChildren();
- if (children.size() > 0 &&
- children.get(0).getDescriptor().getXmlLocalName().equals(SCROLL_VIEW)) {
- renderingMode = RenderingMode.V_SCROLL;
- }
-
- RenderSession session = RenderService.create(this, mCredential)
- .setModel(model)
- .setLog(logger)
- .setRenderingMode(renderingMode)
- .setIncludedWithin(mIncludedWithin)
- .setNodesToExpand(explodeNodes)
- .createRenderSession();
-
- boolean layoutlib5 = layoutLib.supports(Capability.EMBEDDED_LAYOUT);
- canvas.setSession(session, explodeNodes, layoutlib5);
-
- // update the UiElementNode with the layout info.
- if (session != null && session.getResult().isSuccess() == false) {
- // An error was generated. Print it (and any other accumulated warnings)
- String errorMessage = session.getResult().getErrorMessage();
- Throwable exception = session.getResult().getException();
- if (exception != null && errorMessage == null) {
- errorMessage = exception.toString();
- }
- if (exception != null || (errorMessage != null && errorMessage.length() > 0)) {
- logger.error(null, errorMessage, exception, null /*data*/);
- } else if (!logger.hasProblems()) {
- logger.error(null, "Unexpected error in rendering, no details given",
- null /*data*/);
- }
- // These errors will be included in the log warnings which are
- // displayed regardless of render success status below
- }
-
- // We might have detected some missing classes and swapped them by a mock view,
- // or run into fidelity warnings or missing resources, so emit all these
- // warnings
- Set<String> missingClasses = mProjectCallback.getMissingClasses();
- Set<String> brokenClasses = mProjectCallback.getUninstantiatableClasses();
- if (logger.hasProblems()) {
- displayLoggerProblems(iProject, logger);
- displayFailingClasses(missingClasses, brokenClasses, true);
- displayUserStackTrace(logger, true);
- } else if (missingClasses.size() > 0 || brokenClasses.size() > 0) {
- displayFailingClasses(missingClasses, brokenClasses, false);
- displayUserStackTrace(logger, true);
- } else if (session != null) {
- // Nope, no missing or broken classes. Clear success, congrats!
- hideError();
-
- // First time this layout is opened, run lint on the file (after a delay)
- if (!mRenderedOnce) {
- mRenderedOnce = true;
- Job job = new Job("Run Lint") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- getEditorDelegate().delegateRunLint();
- return Status.OK_STATUS;
- }
-
- };
- job.setSystem(true);
- job.schedule(3000); // 3 seconds
- }
-
- mConfigChooser.ensureInitialized();
- }
-
- model.refreshUi();
- }
-
- /**
- * Returns the {@link ResourceResolver} for this editor
- *
- * @return the resolver used to resolve resources for the current configuration of
- * this editor, or null
- */
- public ResourceResolver getResourceResolver() {
- if (mResourceResolver == null) {
- String theme = mConfigChooser.getThemeName();
- if (theme == null) {
- displayError("Missing theme.");
- return null;
- }
- boolean isProjectTheme = mConfigChooser.getConfiguration().isProjectTheme();
-
- Map<ResourceType, Map<String, ResourceValue>> configuredProjectRes =
- getConfiguredProjectResources();
-
- // Get the framework resources
- Map<ResourceType, Map<String, ResourceValue>> frameworkResources =
- getConfiguredFrameworkResources();
-
- if (configuredProjectRes == null) {
- displayError("Missing project resources for current configuration.");
- return null;
- }
-
- if (frameworkResources == null) {
- displayError("Missing framework resources.");
- return null;
- }
-
- mResourceResolver = ResourceResolver.create(
- configuredProjectRes, frameworkResources,
- theme, isProjectTheme);
- }
-
- return mResourceResolver;
- }
-
- /** Returns a project callback, and optionally resets it */
- ProjectCallback getProjectCallback(boolean reset, LayoutLibrary layoutLibrary) {
- // Lazily create the project callback the first time we need it
- if (mProjectCallback == null) {
- ResourceManager resManager = ResourceManager.getInstance();
- IProject project = getProject();
- ProjectResources projectRes = resManager.getProjectResources(project);
- mProjectCallback = new ProjectCallback(layoutLibrary, projectRes, project,
- mCredential, this);
- } else if (reset) {
- // Also clears the set of missing/broken classes prior to rendering
- mProjectCallback.getMissingClasses().clear();
- mProjectCallback.getUninstantiatableClasses().clear();
- }
-
- return mProjectCallback;
- }
-
- /**
- * Returns the resource name of this layout, NOT including the @layout/ prefix
- *
- * @return the resource name of this layout, NOT including the @layout/ prefix
- */
- public String getLayoutResourceName() {
- return ResourceHelper.getLayoutName(mEditedFile);
- }
-
- /**
- * Cleans up when the rendering target is about to change
- * @param oldTarget the old rendering target.
- */
- private void preRenderingTargetChangeCleanUp(IAndroidTarget oldTarget) {
- // first clear the caches related to this file in the old target
- Sdk currentSdk = Sdk.getCurrent();
- if (currentSdk != null) {
- AndroidTargetData data = currentSdk.getTargetData(oldTarget);
- if (data != null) {
- LayoutLibrary layoutLib = data.getLayoutLibrary();
-
- // layoutLib can never be null.
- layoutLib.clearCaches(mEditedFile.getProject());
- }
- }
-
- // Also remove the ProjectCallback as it caches custom views which must be reloaded
- // with the classloader of the new LayoutLib. We also have to clear it out
- // because it stores a reference to the layout library which could have changed.
- mProjectCallback = null;
-
- // FIXME: get rid of the current LayoutScene if any.
- }
-
- private class ReloadListener implements ILayoutReloadListener {
- /**
- * Called when the file changes triggered a redraw of the layout
- */
- @Override
- public void reloadLayout(final ChangeFlags flags, final boolean libraryChanged) {
- if (mConfigChooser.isDisposed()) {
- return;
- }
- Display display = mConfigChooser.getDisplay();
- display.asyncExec(new Runnable() {
- @Override
- public void run() {
- reloadLayoutSwt(flags, libraryChanged);
- }
- });
- }
-
- /** Reload layout. <b>Must be called on the SWT thread</b> */
- private void reloadLayoutSwt(ChangeFlags flags, boolean libraryChanged) {
- if (mConfigChooser.isDisposed()) {
- return;
- }
- assert mConfigChooser.getDisplay().getThread() == Thread.currentThread();
-
- boolean recompute = false;
- // we only care about the r class of the main project.
- if (flags.rClass && libraryChanged == false) {
- recompute = true;
- if (mEditedFile != null) {
- ResourceManager manager = ResourceManager.getInstance();
- ProjectResources projectRes = manager.getProjectResources(
- mEditedFile.getProject());
-
- if (projectRes != null) {
- projectRes.resetDynamicIds();
- }
- }
- }
-
- if (flags.localeList) {
- // the locale list *potentially* changed so we update the locale in the
- // config composite.
- // However there's no recompute, as it could not be needed
- // (for instance a new layout)
- // If a resource that's not a layout changed this will trigger a recompute anyway.
- mConfigChooser.updateLocales();
- }
-
- // if a resources was modified.
- if (flags.resources) {
- recompute = true;
-
- // TODO: differentiate between single and multi resource file changed, and whether
- // the resource change affects the cache.
-
- // force a reparse in case a value XML file changed.
- mConfiguredProjectRes = null;
- mResourceResolver = null;
-
- // clear the cache in the bridge in case a bitmap/9-patch changed.
- LayoutLibrary layoutLib = getReadyLayoutLib(true /*displayError*/);
- if (layoutLib != null) {
- layoutLib.clearCaches(mEditedFile.getProject());
- }
- }
-
- if (flags.code) {
- // only recompute if the custom view loader was used to load some code.
- if (mProjectCallback != null && mProjectCallback.isUsed()) {
- mProjectCallback = null;
- recompute = true;
- }
- }
-
- if (flags.manifest) {
- recompute |= computeSdkVersion();
- }
-
- if (recompute) {
- if (mEditorDelegate.isGraphicalEditorActive()) {
- recomputeLayout();
- } else {
- mNeedsRecompute = true;
- }
- }
- }
- }
-
- // ---- Error handling ----
-
- /**
- * Switches the sash to display the error label.
- *
- * @param errorFormat The new error to display if not null.
- * @param parameters String.format parameters for the error format.
- */
- private void displayError(String errorFormat, Object...parameters) {
- if (errorFormat != null) {
- mErrorLabel.setText(String.format(errorFormat, parameters));
- } else {
- mErrorLabel.setText("");
- }
- mSashError.setMaximizedControl(null);
- }
-
- /** Displays the canvas and hides the error label. */
- private void hideError() {
- mErrorLabel.setText("");
- mSashError.setMaximizedControl(mCanvasViewer.getControl());
- }
-
- /** Display the problem list encountered during a render */
- private void displayUserStackTrace(RenderLogger logger, boolean append) {
- List<Throwable> throwables = logger.getFirstTrace();
- if (throwables == null || throwables.isEmpty()) {
- return;
- }
-
- Throwable throwable = throwables.get(0);
-
- if (throwable instanceof RenderSecurityException) {
- addActionLink(mErrorLabel, ActionLinkStyleRange.LINK_DISABLE_SANDBOX,
- "\nTurn off custom view rendering sandbox\n");
-
- StringBuilder builder = new StringBuilder(200);
- String lastFailedPath = RenderSecurityManager.getLastFailedPath();
- if (lastFailedPath != null) {
- builder.append("Diagnostic info for ADT bug report:\n");
- builder.append("Failed path: ").append(lastFailedPath).append('\n');
- String tempDir = System.getProperty("java.io.tmpdir");
- builder.append("Normal temp dir: ").append(tempDir).append('\n');
- File normalized = new File(tempDir);
- builder.append("Normalized temp dir: ").append(normalized.getPath()).append('\n');
- try {
- builder.append("Canonical temp dir: ").append(normalized.getCanonicalPath())
- .append('\n');
- } catch (IOException e) {
- // ignore
- }
- builder.append("os.name: ").append(System.getProperty("os.name")).append('\n');
- builder.append("os.version: ").append(System.getProperty("os.version"));
- builder.append('\n');
- builder.append("java.runtime.version: ");
- builder.append(System.getProperty("java.runtime.version"));
- }
- if (throwable.getMessage().equals("Unable to create temporary file")) {
- String javaVersion = System.getProperty("java.version");
- if (javaVersion.startsWith("1.7.0_")) {
- int version = Integer
- .parseInt(javaVersion.substring(javaVersion.indexOf('_') + 1));
- if (version > 0 && version < 45) {
- builder.append('\n');
- builder.append("Tip: This may be caused by using an older version " +
- "of JDK 1.7.0; try using at least 1.7.0_45 (you are using " +
- javaVersion + ")");
- }
- }
- }
- if (builder.length() > 0) {
- addText(mErrorLabel, builder.toString());
- }
- }
-
- StackTraceElement[] frames = throwable.getStackTrace();
- int end = -1;
- boolean haveInterestingFrame = false;
- for (int i = 0; i < frames.length; i++) {
- StackTraceElement frame = frames[i];
- if (isInterestingFrame(frame)) {
- haveInterestingFrame = true;
- }
- String className = frame.getClassName();
- if (className.equals(
- "com.android.layoutlib.bridge.impl.RenderSessionImpl")) { //$NON-NLS-1$
- end = i;
- break;
- }
- }
-
- if (end == -1 || !haveInterestingFrame) {
- // Not a recognized stack trace range: just skip it
- return;
- }
-
- if (!append) {
- mErrorLabel.setText("\n"); //$NON-NLS-1$
- } else {
- addText(mErrorLabel, "\n\n"); //$NON-NLS-1$
- }
-
- addText(mErrorLabel, throwable.toString() + '\n');
- for (int i = 0; i < end; i++) {
- StackTraceElement frame = frames[i];
- String className = frame.getClassName();
- String methodName = frame.getMethodName();
- addText(mErrorLabel, " at " + className + '.' + methodName + '(');
- String fileName = frame.getFileName();
- if (fileName != null && !fileName.isEmpty()) {
- int lineNumber = frame.getLineNumber();
- String location = fileName + ':' + lineNumber;
- if (isInterestingFrame(frame)) {
- addActionLink(mErrorLabel, ActionLinkStyleRange.LINK_OPEN_LINE,
- location, className, methodName, fileName, lineNumber);
- } else {
- addText(mErrorLabel, location);
- }
- addText(mErrorLabel, ")\n"); //$NON-NLS-1$
- }
- }
- }
-
- private static boolean isInterestingFrame(StackTraceElement frame) {
- String className = frame.getClassName();
- return !(className.startsWith("android.") //$NON-NLS-1$
- || className.startsWith("com.android.") //$NON-NLS-1$
- || className.startsWith("java.") //$NON-NLS-1$
- || className.startsWith("javax.") //$NON-NLS-1$
- || className.startsWith("sun.")); //$NON-NLS-1$
- }
-
- /**
- * Switches the sash to display the error label to show a list of
- * missing classes and give options to create them.
- */
- private void displayFailingClasses(Set<String> missingClasses, Set<String> brokenClasses,
- boolean append) {
- if (missingClasses.size() == 0 && brokenClasses.size() == 0) {
- return;
- }
-
- if (!append) {
- mErrorLabel.setText(""); //$NON-NLS-1$
- } else {
- addText(mErrorLabel, "\n"); //$NON-NLS-1$
- }
-
- if (missingClasses.size() > 0) {
- addText(mErrorLabel, "The following classes could not be found:\n");
- for (String clazz : missingClasses) {
- addText(mErrorLabel, "- ");
- addText(mErrorLabel, clazz);
- addText(mErrorLabel, " (");
-
- IProject project = getProject();
- Collection<String> customViews = getCustomViewClassNames(project);
- addTypoSuggestions(clazz, customViews, false);
- addTypoSuggestions(clazz, customViews, true);
- addTypoSuggestions(clazz, getAndroidViewClassNames(project), false);
-
- addActionLink(mErrorLabel,
- ActionLinkStyleRange.LINK_FIX_BUILD_PATH, "Fix Build Path", clazz);
- addText(mErrorLabel, ", ");
- addActionLink(mErrorLabel,
- ActionLinkStyleRange.LINK_EDIT_XML, "Edit XML", clazz);
- if (clazz.indexOf('.') != -1) {
- // Add "Create Class" link, but only for custom views
- addText(mErrorLabel, ", ");
- addActionLink(mErrorLabel,
- ActionLinkStyleRange.LINK_CREATE_CLASS, "Create Class", clazz);
- }
- addText(mErrorLabel, ")\n");
- }
- }
- if (brokenClasses.size() > 0) {
- addText(mErrorLabel, "The following classes could not be instantiated:\n");
-
- // Do we have a custom class (not an Android or add-ons class)
- boolean haveCustomClass = false;
-
- for (String clazz : brokenClasses) {
- addText(mErrorLabel, "- ");
- addText(mErrorLabel, clazz);
- addText(mErrorLabel, " (");
- addActionLink(mErrorLabel,
- ActionLinkStyleRange.LINK_OPEN_CLASS, "Open Class", clazz);
- addText(mErrorLabel, ", ");
- addActionLink(mErrorLabel,
- ActionLinkStyleRange.LINK_SHOW_LOG, "Show Error Log", clazz);
- addText(mErrorLabel, ")\n");
-
- if (!(clazz.startsWith("android.") || //$NON-NLS-1$
- clazz.startsWith("com.google."))) { //$NON-NLS-1$
- haveCustomClass = true;
- }
- }
-
- addText(mErrorLabel, "See the Error Log (Window > Show View) for more details.\n");
-
- if (haveCustomClass) {
- addBoldText(mErrorLabel, "Tip: Use View.isInEditMode() in your custom views "
- + "to skip code when shown in Eclipse");
- }
- }
-
- mSashError.setMaximizedControl(null);
- }
-
- private void addTypoSuggestions(String actual, Collection<String> views,
- boolean compareWithPackage) {
- if (views.size() == 0) {
- return;
- }
-
- // Look for typos and try to match with custom views and android views
- String actualBase = actual.substring(actual.lastIndexOf('.') + 1);
- int maxDistance = actualBase.length() >= 4 ? 2 : 1;
-
- if (views.size() > 0) {
- for (String suggested : views) {
- String suggestedBase = suggested.substring(suggested.lastIndexOf('.') + 1);
-
- String matchWith = compareWithPackage ? suggested : suggestedBase;
- if (Math.abs(actualBase.length() - matchWith.length()) > maxDistance) {
- // The string lengths differ more than the allowed edit distance;
- // no point in even attempting to compute the edit distance (requires
- // O(n*m) storage and O(n*m) speed, where n and m are the string lengths)
- continue;
- }
- if (LintUtils.editDistance(actualBase, matchWith) <= maxDistance) {
- // Suggest this class as a typo for the given class
- String labelClass = (suggestedBase.equals(actual) || actual.indexOf('.') != -1)
- ? suggested : suggestedBase;
- addActionLink(mErrorLabel,
- ActionLinkStyleRange.LINK_CHANGE_CLASS_TO,
- String.format("Change to %1$s",
- // Only show full package name if class name
- // is the same
- labelClass),
- actual,
- viewNeedsPackage(suggested) ? suggested : suggestedBase);
- addText(mErrorLabel, ", ");
- }
- }
- }
- }
-
- private static Collection<String> getCustomViewClassNames(IProject project) {
- CustomViewFinder finder = CustomViewFinder.get(project);
- Collection<String> views = finder.getAllViews();
- if (views == null) {
- finder.refresh();
- views = finder.getAllViews();
- }
-
- return views;
- }
-
- private static Collection<String> getAndroidViewClassNames(IProject project) {
- Sdk currentSdk = Sdk.getCurrent();
- IAndroidTarget target = currentSdk.getTarget(project);
- if (target != null) {
- AndroidTargetData targetData = currentSdk.getTargetData(target);
- if (targetData != null) {
- LayoutDescriptors layoutDescriptors = targetData.getLayoutDescriptors();
- return layoutDescriptors.getAllViewClassNames();
- }
- }
-
- return Collections.emptyList();
- }
-
- /** Add a normal line of text to the styled text widget. */
- private void addText(StyledText styledText, String...string) {
- for (String s : string) {
- styledText.append(s);
- }
- }
-
- /** Display the problem list encountered during a render */
- private void displayLoggerProblems(IProject project, RenderLogger logger) {
- if (logger.hasProblems()) {
- mErrorLabel.setText("");
- // A common source of problems is attempting to open a layout when there are
- // compilation errors. In this case, may not have run (or may not be up to date)
- // so resources cannot be looked up etc. Explain this situation to the user.
-
- boolean hasAaptErrors = false;
- boolean hasJavaErrors = false;
- try {
- IMarker[] markers;
- markers = project.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE);
- if (markers.length > 0) {
- for (IMarker marker : markers) {
- String markerType = marker.getType();
- if (markerType.equals(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER)) {
- int severity = marker.getAttribute(IMarker.SEVERITY, -1);
- if (severity == IMarker.SEVERITY_ERROR) {
- hasJavaErrors = true;
- }
- } else if (markerType.equals(AdtConstants.MARKER_AAPT_COMPILE)) {
- int severity = marker.getAttribute(IMarker.SEVERITY, -1);
- if (severity == IMarker.SEVERITY_ERROR) {
- hasAaptErrors = true;
- }
- }
- }
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
-
- if (logger.seenTagPrefix(LayoutLog.TAG_RESOURCES_RESOLVE_THEME_ATTR)) {
- addBoldText(mErrorLabel,
- "Missing styles. Is the correct theme chosen for this layout?\n");
- addText(mErrorLabel,
- "Use the Theme combo box above the layout to choose a different layout, " +
- "or fix the theme style references.\n\n");
- }
-
- List<Throwable> trace = logger.getFirstTrace();
- if (trace != null
- && trace.toString().contains(
- "java.lang.IndexOutOfBoundsException: Index: 2, Size: 2") //$NON-NLS-1$
- && mConfigChooser.getConfiguration().getDensity() == Density.TV) {
- addBoldText(mErrorLabel,
- "It looks like you are using a render target where the layout library " +
- "does not support the tvdpi density.\n\n");
- addText(mErrorLabel, "Please try either updating to " +
- "the latest available version (using the SDK manager), or if no updated " +
- "version is available for this specific version of Android, try using " +
- "a more recent render target version.\n\n");
-
- }
-
- if (hasAaptErrors && logger.seenTagPrefix(LayoutLog.TAG_RESOURCES_PREFIX)) {
- // Text will automatically be wrapped by the error widget so no reason
- // to insert linebreaks in this error message:
- String message =
- "NOTE: This project contains resource errors, so aapt did not succeed, "
- + "which can cause rendering failures. "
- + "Fix resource problems first.\n\n";
- addBoldText(mErrorLabel, message);
- } else if (hasJavaErrors && mProjectCallback != null && mProjectCallback.isUsed()) {
- // Text will automatically be wrapped by the error widget so no reason
- // to insert linebreaks in this error message:
- String message =
- "NOTE: This project contains Java compilation errors, "
- + "which can cause rendering failures for custom views. "
- + "Fix compilation problems first.\n\n";
- addBoldText(mErrorLabel, message);
- }
-
- if (logger.seenTag(RenderLogger.TAG_MISSING_DIMENSION)) {
- List<UiElementNode> elements = UiDocumentNode.getAllElements(getModel());
- for (UiElementNode element : elements) {
- String width = element.getAttributeValue(ATTR_LAYOUT_WIDTH);
- if (width == null || width.length() == 0) {
- addSetAttributeLink(element, ATTR_LAYOUT_WIDTH);
- }
-
- String height = element.getAttributeValue(ATTR_LAYOUT_HEIGHT);
- if (height == null || height.length() == 0) {
- addSetAttributeLink(element, ATTR_LAYOUT_HEIGHT);
- }
- }
- }
-
- String problems = logger.getProblems(false /*includeFidelityWarnings*/);
- addText(mErrorLabel, problems);
-
- List<String> fidelityWarnings = logger.getFidelityWarnings();
- if (fidelityWarnings != null && fidelityWarnings.size() > 0) {
- addText(mErrorLabel,
- "The graphics preview in the layout editor may not be accurate:\n");
- for (String warning : fidelityWarnings) {
- addText(mErrorLabel, warning + ' ');
- addActionLink(mErrorLabel,
- ActionLinkStyleRange.IGNORE_FIDELITY_WARNING,
- "(Ignore for this session)\n", warning);
- }
- }
-
- mSashError.setMaximizedControl(null);
- } else {
- mSashError.setMaximizedControl(mCanvasViewer.getControl());
- }
- }
-
- /** Appends an action link to set the given attribute on the given value */
- private void addSetAttributeLink(UiElementNode element, String attribute) {
- if (element.getXmlNode().getNodeName().equals(GRID_LAYOUT)) {
- // GridLayout does not require a layout_width or layout_height to be defined
- return;
- }
-
- String fill = VALUE_FILL_PARENT;
- // See whether we should offer match_parent instead of fill_parent
- Sdk currentSdk = Sdk.getCurrent();
- if (currentSdk != null) {
- IAndroidTarget target = currentSdk.getTarget(getProject());
- if (target.getVersion().getApiLevel() >= 8) {
- fill = VALUE_MATCH_PARENT;
- }
- }
-
- String id = element.getAttributeValue(ATTR_ID);
- if (id == null || id.length() == 0) {
- id = '<' + element.getXmlNode().getNodeName() + '>';
- } else {
- id = BaseLayoutRule.stripIdPrefix(id);
- }
-
- addText(mErrorLabel, String.format("\"%1$s\" does not set the required %2$s attribute:\n",
- id, attribute));
- addText(mErrorLabel, " (1) ");
- addActionLink(mErrorLabel,
- ActionLinkStyleRange.SET_ATTRIBUTE,
- String.format("Set to \"%1$s\"", VALUE_WRAP_CONTENT),
- element, attribute, VALUE_WRAP_CONTENT);
- addText(mErrorLabel, "\n (2) ");
- addActionLink(mErrorLabel,
- ActionLinkStyleRange.SET_ATTRIBUTE,
- String.format("Set to \"%1$s\"\n", fill),
- element, attribute, fill);
- }
-
- /** Appends the given text as a bold string in the given text widget */
- private void addBoldText(StyledText styledText, String text) {
- String s = styledText.getText();
- int start = (s == null ? 0 : s.length());
-
- styledText.append(text);
- StyleRange sr = new StyleRange();
- sr.start = start;
- sr.length = text.length();
- sr.fontStyle = SWT.BOLD;
- styledText.setStyleRange(sr);
- }
-
- /**
- * Add a URL-looking link to the styled text widget.
- * <p/>
- * A mouse-click listener is setup and it interprets the link based on the
- * action, corresponding to the value fields in {@link ActionLinkStyleRange}.
- */
- private void addActionLink(StyledText styledText, int action, String label,
- Object... data) {
- String s = styledText.getText();
- int start = (s == null ? 0 : s.length());
- styledText.append(label);
-
- StyleRange sr = new ActionLinkStyleRange(action, data);
- sr.start = start;
- sr.length = label.length();
- sr.fontStyle = SWT.NORMAL;
- sr.underlineStyle = SWT.UNDERLINE_LINK;
- sr.underline = true;
- styledText.setStyleRange(sr);
- }
-
- /**
- * Looks up the resource file corresponding to the given type
- *
- * @param type The type of resource to look up, such as {@link ResourceType#LAYOUT}
- * @param name The name of the resource (not including ".xml")
- * @param isFrameworkResource if true, the resource is a framework resource, otherwise
- * it's a project resource
- * @return the resource file defining the named resource, or null if not found
- */
- public IPath findResourceFile(ResourceType type, String name, boolean isFrameworkResource) {
- // FIXME: This code does not handle theme value resolution.
- // There is code to handle this, but it's in layoutlib; we should
- // expose that and use it here.
-
- Map<ResourceType, Map<String, ResourceValue>> map;
- map = isFrameworkResource ? mConfiguredFrameworkRes : mConfiguredProjectRes;
- if (map == null) {
- // Not yet configured
- return null;
- }
-
- Map<String, ResourceValue> layoutMap = map.get(type);
- if (layoutMap != null) {
- ResourceValue value = layoutMap.get(name);
- if (value != null) {
- String valueStr = value.getValue();
- if (valueStr.startsWith("?")) { //$NON-NLS-1$
- // FIXME: It's a reference. We should resolve this properly.
- return null;
- }
- return new Path(valueStr);
- }
- }
-
- return null;
- }
-
- /**
- * Looks up the path to the file corresponding to the given attribute value, such as
- * @layout/foo, which will return the foo.xml file in res/layout/. (The general format
- * of the resource url is {@literal @[<package_name>:]<resource_type>/<resource_name>}.
- *
- * @param url the attribute url
- * @return the path to the file defining this attribute, or null if not found
- */
- public IPath findResourceFile(String url) {
- if (!url.startsWith("@")) { //$NON-NLS-1$
- return null;
- }
- int typeEnd = url.indexOf('/', 1);
- if (typeEnd == -1) {
- return null;
- }
- int nameBegin = typeEnd + 1;
- int typeBegin = 1;
- int colon = url.lastIndexOf(':', typeEnd);
- boolean isFrameworkResource = false;
- if (colon != -1) {
- // The URL contains a package name.
- // While the url format technically allows other package names,
- // the platform apparently only supports @android for now (or if it does,
- // there are no usages in the current code base so this is not common).
- String packageName = url.substring(typeBegin, colon);
- if (ANDROID_PKG.equals(packageName)) {
- isFrameworkResource = true;
- }
-
- typeBegin = colon + 1;
- }
-
- String typeName = url.substring(typeBegin, typeEnd);
- ResourceType type = ResourceType.getEnum(typeName);
- if (type == null) {
- return null;
- }
-
- String name = url.substring(nameBegin);
- return findResourceFile(type, name, isFrameworkResource);
- }
-
- /**
- * Resolve the given @string reference into a literal String using the current project
- * configuration
- *
- * @param text the text resource reference to resolve
- * @return the resolved string, or null
- */
- public String findString(String text) {
- if (text.startsWith(STRING_PREFIX)) {
- return findString(text.substring(STRING_PREFIX.length()), false);
- } else if (text.startsWith(ANDROID_STRING_PREFIX)) {
- return findString(text.substring(ANDROID_STRING_PREFIX.length()), true);
- } else {
- return text;
- }
- }
-
- private String findString(String name, boolean isFrameworkResource) {
- Map<ResourceType, Map<String, ResourceValue>> map;
- map = isFrameworkResource ? mConfiguredFrameworkRes : mConfiguredProjectRes;
- if (map == null) {
- // Not yet configured
- return null;
- }
-
- Map<String, ResourceValue> layoutMap = map.get(ResourceType.STRING);
- if (layoutMap != null) {
- ResourceValue value = layoutMap.get(name);
- if (value != null) {
- // FIXME: This code does not handle theme value resolution.
- // There is code to handle this, but it's in layoutlib; we should
- // expose that and use it here.
- return value.getValue();
- }
- }
-
- return null;
- }
-
- /**
- * This StyleRange represents a clickable link in the render output, where various
- * actions can be taken such as creating a class, opening the project chooser to
- * adjust the build path, etc.
- */
- private class ActionLinkStyleRange extends StyleRange {
- /** Create a view class */
- private static final int LINK_CREATE_CLASS = 1;
- /** Edit the build path for the current project */
- private static final int LINK_FIX_BUILD_PATH = 2;
- /** Show the XML tab */
- private static final int LINK_EDIT_XML = 3;
- /** Open the given class */
- private static final int LINK_OPEN_CLASS = 4;
- /** Show the error log */
- private static final int LINK_SHOW_LOG = 5;
- /** Change the class reference to the given fully qualified name */
- private static final int LINK_CHANGE_CLASS_TO = 6;
- /** Ignore the given fidelity warning */
- private static final int IGNORE_FIDELITY_WARNING = 7;
- /** Set an attribute on the given XML element to a given value */
- private static final int SET_ATTRIBUTE = 8;
- /** Open the given file and line number */
- private static final int LINK_OPEN_LINE = 9;
- /** Disable sandbox */
- private static final int LINK_DISABLE_SANDBOX = 10;
-
- /** Client data: the contents depend on the specific action */
- private final Object[] mData;
- /** The action to be taken when the link is clicked */
- private final int mAction;
-
- private ActionLinkStyleRange(int action, Object... data) {
- super();
- mAction = action;
- mData = data;
- }
-
- /** Performs the click action */
- public void onClick() {
- switch (mAction) {
- case LINK_CREATE_CLASS:
- createNewClass((String) mData[0]);
- break;
- case LINK_EDIT_XML:
- mEditorDelegate.getEditor().setActivePage(AndroidXmlEditor.TEXT_EDITOR_ID);
- break;
- case LINK_FIX_BUILD_PATH:
- @SuppressWarnings("restriction")
- String id = BuildPathsPropertyPage.PROP_ID;
- PreferencesUtil.createPropertyDialogOn(
- AdtPlugin.getShell(),
- getProject(), id, null, null).open();
- break;
- case LINK_OPEN_CLASS:
- AdtPlugin.openJavaClass(getProject(), (String) mData[0]);
- break;
- case LINK_OPEN_LINE:
- boolean success = AdtPlugin.openStackTraceLine(
- (String) mData[0], // class
- (String) mData[1], // method
- (String) mData[2], // file
- (Integer) mData[3]); // line
- if (!success) {
- MessageDialog.openError(mErrorLabel.getShell(), "Not Found",
- String.format("Could not find %1$s.%2$s", mData[0], mData[1]));
- }
- break;
- case LINK_SHOW_LOG:
- IWorkbench workbench = PlatformUI.getWorkbench();
- IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
- try {
- IWorkbenchPage page = workbenchWindow.getActivePage();
- page.showView("org.eclipse.pde.runtime.LogView"); //$NON-NLS-1$
- } catch (PartInitException e) {
- AdtPlugin.log(e, null);
- }
- break;
- case LINK_CHANGE_CLASS_TO:
- // Change class reference of mData[0] to mData[1]
- // TODO: run under undo lock
- MultiTextEdit edits = new MultiTextEdit();
- ISourceViewer textViewer =
- mEditorDelegate.getEditor().getStructuredSourceViewer();
- IDocument document = textViewer.getDocument();
- String xml = document.get();
- int index = 0;
- // Replace <old with <new and </old with </new
- String prefix = "<"; //$NON-NLS-1$
- String find = prefix + mData[0];
- String replaceWith = prefix + mData[1];
- while (true) {
- index = xml.indexOf(find, index);
- if (index == -1) {
- break;
- }
- edits.addChild(new ReplaceEdit(index, find.length(), replaceWith));
- index += find.length();
- }
- index = 0;
- prefix = "</"; //$NON-NLS-1$
- find = prefix + mData[0];
- replaceWith = prefix + mData[1];
- while (true) {
- index = xml.indexOf(find, index);
- if (index == -1) {
- break;
- }
- edits.addChild(new ReplaceEdit(index, find.length(), replaceWith));
- index += find.length();
- }
- // Handle <view class="old">
- index = 0;
- prefix = "\""; //$NON-NLS-1$
- String suffix = "\""; //$NON-NLS-1$
- find = prefix + mData[0] + suffix;
- replaceWith = prefix + mData[1] + suffix;
- while (true) {
- index = xml.indexOf(find, index);
- if (index == -1) {
- break;
- }
- edits.addChild(new ReplaceEdit(index, find.length(), replaceWith));
- index += find.length();
- }
- try {
- edits.apply(document);
- } catch (MalformedTreeException e) {
- AdtPlugin.log(e, null);
- } catch (BadLocationException e) {
- AdtPlugin.log(e, null);
- }
- break;
- case IGNORE_FIDELITY_WARNING:
- RenderLogger.ignoreFidelityWarning((String) mData[0]);
- recomputeLayout();
- break;
- case SET_ATTRIBUTE: {
- final UiElementNode element = (UiElementNode) mData[0];
- final String attribute = (String) mData[1];
- final String value = (String) mData[2];
- mEditorDelegate.getEditor().wrapUndoEditXmlModel(
- String.format("Set \"%1$s\" to \"%2$s\"", attribute, value),
- new Runnable() {
- @Override
- public void run() {
- element.setAttributeValue(attribute, ANDROID_URI, value, true);
- element.commitDirtyAttributesToXml();
- }
- });
- break;
- }
- case LINK_DISABLE_SANDBOX: {
- RenderSecurityManager.sEnabled = false;
- recomputeLayout();
-
- MessageDialog.openInformation(AdtPlugin.getShell(),
- "Disabled Rendering Sandbox",
- "The custom view rendering sandbox was disabled for this session.\n\n" +
- "You can turn it off permanently by adding\n" +
- "-D" + ENABLED_PROPERTY + "=" + VALUE_FALSE + "\n" +
- "as a new line in eclipse.ini.");
-
- break;
- }
- default:
- assert false : mAction;
- break;
- }
- }
-
- @Override
- public boolean similarTo(StyleRange style) {
- // Prevent adjacent link ranges from getting merged
- return false;
- }
- }
-
- /**
- * Returns the error label for the graphical editor (which may not be visible
- * or showing errors)
- *
- * @return the error label, never null
- */
- StyledText getErrorLabel() {
- return mErrorLabel;
- }
-
- /**
- * Monitor clicks on the error label.
- * If the click happens on a style range created by
- * {@link GraphicalEditorPart#addClassLink(StyledText, String)}, we assume it's about
- * a missing class and we then proceed to display the standard Eclipse class creator wizard.
- */
- private class ErrorLabelListener extends MouseAdapter {
-
- @Override
- public void mouseUp(MouseEvent event) {
- super.mouseUp(event);
-
- if (event.widget != mErrorLabel) {
- return;
- }
-
- int offset = mErrorLabel.getCaretOffset();
-
- StyleRange r = null;
- StyleRange[] ranges = mErrorLabel.getStyleRanges();
- if (ranges != null && ranges.length > 0) {
- for (StyleRange sr : ranges) {
- if (sr.start <= offset && sr.start + sr.length > offset) {
- r = sr;
- break;
- }
- }
- }
-
- if (r instanceof ActionLinkStyleRange) {
- ActionLinkStyleRange range = (ActionLinkStyleRange) r;
- range.onClick();
- }
-
- LayoutCanvas canvas = getCanvasControl();
- canvas.updateMenuActionState();
- }
- }
-
- private void createNewClass(String fqcn) {
-
- int pos = fqcn.lastIndexOf('.');
- String packageName = pos < 0 ? "" : fqcn.substring(0, pos); //$NON-NLS-1$
- String className = pos <= 0 || pos >= fqcn.length() ? "" : fqcn.substring(pos + 1); //$NON-NLS-1$
-
- // create the wizard page for the class creation, and configure it
- NewClassWizardPage page = new NewClassWizardPage();
-
- // set the parent class
- page.setSuperClass(SdkConstants.CLASS_VIEW, true /* canBeModified */);
-
- // get the source folders as java elements.
- IPackageFragmentRoot[] roots = getPackageFragmentRoots(
- mEditorDelegate.getEditor().getProject(),
- false /*includeContainers*/, true /*skipGenFolder*/);
-
- IPackageFragmentRoot currentRoot = null;
- IPackageFragment currentFragment = null;
- int packageMatchCount = -1;
-
- for (IPackageFragmentRoot root : roots) {
- // Get the java element for the package.
- // This method is said to always return a IPackageFragment even if the
- // underlying folder doesn't exist...
- IPackageFragment fragment = root.getPackageFragment(packageName);
- if (fragment != null && fragment.exists()) {
- // we have a perfect match! we use it.
- currentRoot = root;
- currentFragment = fragment;
- packageMatchCount = -1;
- break;
- } else {
- // we don't have a match. we look for the fragment with the best match
- // (ie the closest parent package we can find)
- try {
- IJavaElement[] children;
- children = root.getChildren();
- for (IJavaElement child : children) {
- if (child instanceof IPackageFragment) {
- fragment = (IPackageFragment)child;
- if (packageName.startsWith(fragment.getElementName())) {
- // its a match. get the number of segments
- String[] segments = fragment.getElementName().split("\\."); //$NON-NLS-1$
- if (segments.length > packageMatchCount) {
- packageMatchCount = segments.length;
- currentFragment = fragment;
- currentRoot = root;
- }
- }
- }
- }
- } catch (JavaModelException e) {
- // Couldn't get the children: we just ignore this package root.
- }
- }
- }
-
- ArrayList<IPackageFragment> createdFragments = null;
-
- if (currentRoot != null) {
- // if we have a perfect match, we set it and we're done.
- if (packageMatchCount == -1) {
- page.setPackageFragmentRoot(currentRoot, true /* canBeModified*/);
- page.setPackageFragment(currentFragment, true /* canBeModified */);
- } else {
- // we have a partial match.
- // create the package. We have to start with the first segment so that we
- // know what to delete in case of a cancel.
- try {
- createdFragments = new ArrayList<IPackageFragment>();
-
- int totalCount = packageName.split("\\.").length; //$NON-NLS-1$
- int count = 0;
- int index = -1;
- // skip the matching packages
- while (count < packageMatchCount) {
- index = packageName.indexOf('.', index+1);
- count++;
- }
-
- // create the rest of the segments, except for the last one as indexOf will
- // return -1;
- while (count < totalCount - 1) {
- index = packageName.indexOf('.', index+1);
- count++;
- createdFragments.add(currentRoot.createPackageFragment(
- packageName.substring(0, index),
- true /* force*/, new NullProgressMonitor()));
- }
-
- // create the last package
- createdFragments.add(currentRoot.createPackageFragment(
- packageName, true /* force*/, new NullProgressMonitor()));
-
- // set the root and fragment in the Wizard page
- page.setPackageFragmentRoot(currentRoot, true /* canBeModified*/);
- page.setPackageFragment(createdFragments.get(createdFragments.size()-1),
- true /* canBeModified */);
- } catch (JavaModelException e) {
- // If we can't create the packages, there's a problem.
- // We revert to the default package
- for (IPackageFragmentRoot root : roots) {
- // Get the java element for the package.
- // This method is said to always return a IPackageFragment even if the
- // underlying folder doesn't exist...
- IPackageFragment fragment = root.getPackageFragment(packageName);
- if (fragment != null && fragment.exists()) {
- page.setPackageFragmentRoot(root, true /* canBeModified*/);
- page.setPackageFragment(fragment, true /* canBeModified */);
- break;
- }
- }
- }
- }
- } else if (roots.length > 0) {
- // if we haven't found a valid fragment, we set the root to the first source folder.
- page.setPackageFragmentRoot(roots[0], true /* canBeModified*/);
- }
-
- // if we have a starting class name we use it
- if (className != null) {
- page.setTypeName(className, true /* canBeModified*/);
- }
-
- // create the action that will open it the wizard.
- OpenNewClassWizardAction action = new OpenNewClassWizardAction();
- action.setConfiguredWizardPage(page);
- action.run();
- IJavaElement element = action.getCreatedElement();
-
- if (element == null) {
- // lets delete the packages we created just for this.
- // we need to start with the leaf and go up
- if (createdFragments != null) {
- try {
- for (int i = createdFragments.size() - 1 ; i >= 0 ; i--) {
- createdFragments.get(i).delete(true /* force*/,
- new NullProgressMonitor());
- }
- } catch (JavaModelException e) {
- e.printStackTrace();
- }
- }
- }
- }
-
- /**
- * Computes and return the {@link IPackageFragmentRoot}s corresponding to the source
- * folders of the specified project.
- *
- * @param project the project
- * @param includeContainers True to include containers
- * @param skipGenFolder True to skip the "gen" folder
- * @return an array of IPackageFragmentRoot.
- */
- private IPackageFragmentRoot[] getPackageFragmentRoots(IProject project,
- boolean includeContainers, boolean skipGenFolder) {
- ArrayList<IPackageFragmentRoot> result = new ArrayList<IPackageFragmentRoot>();
- try {
- IJavaProject javaProject = JavaCore.create(project);
- IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
- for (int i = 0; i < roots.length; i++) {
- if (skipGenFolder) {
- IResource resource = roots[i].getResource();
- if (resource != null && resource.getName().equals(FD_GEN_SOURCES)) {
- continue;
- }
- }
- IClasspathEntry entry = roots[i].getRawClasspathEntry();
- if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE ||
- (includeContainers &&
- entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER)) {
- result.add(roots[i]);
- }
- }
- } catch (JavaModelException e) {
- }
-
- return result.toArray(new IPackageFragmentRoot[result.size()]);
- }
-
- /**
- * Reopens this file as included within the given file (this assumes that the given
- * file has an include tag referencing this view, and the set of views that have this
- * property can be found using the {@link IncludeFinder}.
- *
- * @param includeWithin reference to a file to include as a surrounding context,
- * or null to show the file standalone
- */
- public void showIn(Reference includeWithin) {
- mIncludedWithin = includeWithin;
-
- if (includeWithin != null) {
- IFile file = includeWithin.getFile();
-
- // Update configuration
- if (file != null) {
- mConfigChooser.resetConfigFor(file);
- }
- }
- recomputeLayout();
- }
-
- /**
- * Return all resource names of a given type, either in the project or in the
- * framework.
- *
- * @param framework if true, return all the framework resource names, otherwise return
- * all the project resource names
- * @param type the type of resource to look up
- * @return a collection of resource names, never null but possibly empty
- */
- public Collection<String> getResourceNames(boolean framework, ResourceType type) {
- Map<ResourceType, Map<String, ResourceValue>> map =
- framework ? mConfiguredFrameworkRes : mConfiguredProjectRes;
- Map<String, ResourceValue> animations = map.get(type);
- if (animations != null) {
- return animations.keySet();
- } else {
- return Collections.emptyList();
- }
- }
-
- /**
- * Return this editor's current configuration
- *
- * @return the current configuration
- */
- public FolderConfiguration getConfiguration() {
- return mConfigChooser.getConfiguration().getFullConfig();
- }
-
- /**
- * Figures out the project's minSdkVersion and targetSdkVersion and return whether the values
- * have changed.
- */
- private boolean computeSdkVersion() {
- int oldMinSdkVersion = mMinSdkVersion;
- int oldTargetSdkVersion = mTargetSdkVersion;
-
- Pair<Integer, Integer> v = ManifestInfo.computeSdkVersions(mEditedFile.getProject());
- mMinSdkVersion = v.getFirst();
- mTargetSdkVersion = v.getSecond();
-
- return oldMinSdkVersion != mMinSdkVersion || oldTargetSdkVersion != mTargetSdkVersion;
- }
-
- /**
- * Returns the associated configuration chooser
- *
- * @return the configuration chooser
- */
- @NonNull
- public ConfigurationChooser getConfigurationChooser() {
- return mConfigChooser;
- }
-
- /**
- * Returns the associated layout actions bar
- *
- * @return the layout actions bar
- */
- @NonNull
- public LayoutActionBar getLayoutActionBar() {
- return mActionBar;
- }
-
- /**
- * Returns the target SDK version
- *
- * @return the target SDK version
- */
- public int getTargetSdkVersion() {
- return mTargetSdkVersion;
- }
-
- /**
- * Returns the minimum SDK version
- *
- * @return the minimum SDK version
- */
- public int getMinSdkVersion() {
- return mMinSdkVersion;
- }
-
- /** If the flyout hover is showing, dismiss it */
- public void dismissHoverPalette() {
- mPaletteComposite.dismissHover();
- }
-
- // ---- Implements IFlyoutListener ----
-
- @Override
- public void stateChanged(int oldState, int newState) {
- // Auto zoom the surface if you open or close flyout windows such as the palette
- // or the property/outline views
- if (newState == STATE_OPEN || newState == STATE_COLLAPSED && oldState == STATE_OPEN) {
- getCanvasControl().setFitScale(true /*onlyZoomOut*/, true /*allowZoomIn*/);
- }
-
- sDockingStateVersion++;
- mDockingStateVersion = sDockingStateVersion;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/HoverOverlay.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/HoverOverlay.java
deleted file mode 100644
index 2e7c559db..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/HoverOverlay.java
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.SwtDrawingStyle.HOVER;
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.SwtDrawingStyle.HOVER_SELECTION;
-
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Device;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Rectangle;
-
-import java.util.List;
-
-/**
- * The {@link HoverOverlay} paints an optional hover on top of the layout,
- * highlighting the currently hovered view.
- */
-public class HoverOverlay extends Overlay {
- private final LayoutCanvas mCanvas;
-
- /** Hover border color. Must be disposed, it's NOT a system color. */
- private Color mHoverStrokeColor;
-
- /** Hover fill color. Must be disposed, it's NOT a system color. */
- private Color mHoverFillColor;
-
- /** Hover border select color. Must be disposed, it's NOT a system color. */
- private Color mHoverSelectStrokeColor;
-
- /** Hover fill select color. Must be disposed, it's NOT a system color. */
- private Color mHoverSelectFillColor;
-
- /** Vertical scaling & scrollbar information. */
- private CanvasTransform mVScale;
-
- /** Horizontal scaling & scrollbar information. */
- private CanvasTransform mHScale;
-
- /**
- * Current mouse hover border rectangle. Null when there's no mouse hover.
- * The rectangle coordinates do not take account of the translation, which
- * must be applied to the rectangle when drawing.
- */
- private Rectangle mHoverRect;
-
- /**
- * Constructs a new {@link HoverOverlay} linked to the given view hierarchy.
- *
- * @param canvas the associated canvas
- * @param hScale The {@link CanvasTransform} to use to transfer horizontal layout
- * coordinates to screen coordinates.
- * @param vScale The {@link CanvasTransform} to use to transfer vertical layout
- * coordinates to screen coordinates.
- */
- public HoverOverlay(LayoutCanvas canvas, CanvasTransform hScale, CanvasTransform vScale) {
- mCanvas = canvas;
- mHScale = hScale;
- mVScale = vScale;
- }
-
- @Override
- public void create(Device device) {
- if (SwtDrawingStyle.HOVER.getStrokeColor() != null) {
- mHoverStrokeColor = new Color(device, SwtDrawingStyle.HOVER.getStrokeColor());
- }
- if (SwtDrawingStyle.HOVER.getFillColor() != null) {
- mHoverFillColor = new Color(device, SwtDrawingStyle.HOVER.getFillColor());
- }
-
- if (SwtDrawingStyle.HOVER_SELECTION.getStrokeColor() != null) {
- mHoverSelectStrokeColor = new Color(device,
- SwtDrawingStyle.HOVER_SELECTION.getStrokeColor());
- }
- if (SwtDrawingStyle.HOVER_SELECTION.getFillColor() != null) {
- mHoverSelectFillColor = new Color(device,
- SwtDrawingStyle.HOVER_SELECTION.getFillColor());
- }
- }
-
- @Override
- public void dispose() {
- if (mHoverStrokeColor != null) {
- mHoverStrokeColor.dispose();
- mHoverStrokeColor = null;
- }
-
- if (mHoverFillColor != null) {
- mHoverFillColor.dispose();
- mHoverFillColor = null;
- }
-
- if (mHoverSelectStrokeColor != null) {
- mHoverSelectStrokeColor.dispose();
- mHoverSelectStrokeColor = null;
- }
-
- if (mHoverSelectFillColor != null) {
- mHoverSelectFillColor.dispose();
- mHoverSelectFillColor = null;
- }
- }
-
- /**
- * Sets the hover rectangle. The coordinates of the rectangle are in layout
- * coordinates. The recipient is will own this rectangle.
- * <p/>
- * TODO: Consider switching input arguments to two {@link LayoutPoint}s so
- * we don't have ambiguity about the coordinate system of these input
- * parameters.
- * <p/>
- *
- * @param x The top left x coordinate, in layout coordinates, of the hover.
- * @param y The top left y coordinate, in layout coordinates, of the hover.
- * @param w The width of the hover (in layout coordinates).
- * @param h The height of the hover (in layout coordinates).
- */
- public void setHover(int x, int y, int w, int h) {
- mHoverRect = new Rectangle(x, y, w, h);
- }
-
- /**
- * Removes the hover for the next paint.
- */
- public void clearHover() {
- mHoverRect = null;
- }
-
- @Override
- public void paint(GC gc) {
- if (mHoverRect != null) {
- // Translate the hover rectangle (in canvas coordinates) to control
- // coordinates
- int x = mHScale.translate(mHoverRect.x);
- int y = mVScale.translate(mHoverRect.y);
- int w = mHScale.scale(mHoverRect.width);
- int h = mVScale.scale(mHoverRect.height);
-
-
- boolean hoverIsSelected = false;
- List<SelectionItem> selections = mCanvas.getSelectionManager().getSelections();
- for (SelectionItem item : selections) {
- if (mHoverRect.equals(item.getViewInfo().getSelectionRect())) {
- hoverIsSelected = true;
- break;
- }
- }
-
- Color stroke = hoverIsSelected ? mHoverSelectStrokeColor : mHoverStrokeColor;
- Color fill = hoverIsSelected ? mHoverSelectFillColor : mHoverFillColor;
-
- if (stroke != null) {
- int oldAlpha = gc.getAlpha();
- gc.setForeground(stroke);
- gc.setLineStyle(hoverIsSelected ?
- HOVER_SELECTION.getLineStyle() : HOVER.getLineStyle());
- gc.setAlpha(hoverIsSelected ?
- HOVER_SELECTION.getStrokeAlpha() : HOVER.getStrokeAlpha());
- gc.drawRectangle(x, y, w, h);
- gc.setAlpha(oldAlpha);
- }
-
- if (fill != null) {
- int oldAlpha = gc.getAlpha();
- gc.setAlpha(hoverIsSelected ?
- HOVER_SELECTION.getFillAlpha() : HOVER.getFillAlpha());
- gc.setBackground(fill);
- gc.fillRectangle(x, y, w, h);
- gc.setAlpha(oldAlpha);
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ImageControl.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ImageControl.java
deleted file mode 100644
index 4447eebd2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ImageControl.java
+++ /dev/null
@@ -1,241 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.CLabel;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseTrackListener;
-import org.eclipse.swt.events.PaintEvent;
-import org.eclipse.swt.events.PaintListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Canvas;
-import org.eclipse.swt.widgets.Composite;
-
-/**
- * An ImageControl which simply renders an image, with optional margins and tooltips. This
- * is useful since a {@link CLabel}, even without text, will hide the image when there is
- * not enough room to fully fit it.
- * <p>
- * The image is always rendered left and top aligned.
- */
-public class ImageControl extends Canvas implements MouseTrackListener {
- private Image mImage;
- private int mLeftMargin;
- private int mTopMargin;
- private int mRightMargin;
- private int mBottomMargin;
- private boolean mDisposeImage = true;
- private boolean mMouseIn;
- private Color mHoverColor;
- private float mScale = 1.0f;
-
- /**
- * Creates an ImageControl rendering the given image, which will be disposed when this
- * control is disposed (unless the {@link #setDisposeImage} method is called to turn
- * off auto dispose).
- *
- * @param parent the parent to add the image control to
- * @param style the SWT style to use
- * @param image the image to be rendered, which must not be null and should be unique
- * for this image control since it will be disposed by this control when
- * the control is disposed (unless the {@link #setDisposeImage} method is
- * called to turn off auto dispose)
- */
- public ImageControl(@NonNull Composite parent, int style, @Nullable Image image) {
- super(parent, style | SWT.NO_FOCUS | SWT.DOUBLE_BUFFERED);
- mImage = image;
-
- addPaintListener(new PaintListener() {
- @Override
- public void paintControl(PaintEvent event) {
- onPaint(event);
- }
- });
- }
-
- @Nullable
- public Image getImage() {
- return mImage;
- }
-
- public void setImage(@Nullable Image image) {
- if (mDisposeImage && mImage != null) {
- mImage.dispose();
- }
- mImage = image;
- redraw();
- }
-
- public void fitToWidth(int width) {
- if (mImage == null) {
- return;
- }
- Rectangle imageRect = mImage.getBounds();
- int imageWidth = imageRect.width;
- if (imageWidth <= width) {
- mScale = 1.0f;
- return;
- }
-
- mScale = width / (float) imageWidth;
- redraw();
- }
-
- public void setScale(float scale) {
- mScale = scale;
- }
-
- public float getScale() {
- return mScale;
- }
-
- public void setHoverColor(@Nullable Color hoverColor) {
- if (mHoverColor != null) {
- removeMouseTrackListener(this);
- }
- mHoverColor = hoverColor;
- if (hoverColor != null) {
- addMouseTrackListener(this);
- }
- }
-
- @Nullable
- public Color getHoverColor() {
- return mHoverColor;
- }
-
- @Override
- public void dispose() {
- super.dispose();
-
- if (mDisposeImage && mImage != null && !mImage.isDisposed()) {
- mImage.dispose();
- }
- mImage = null;
- }
-
- public void setDisposeImage(boolean disposeImage) {
- mDisposeImage = disposeImage;
- }
-
- public boolean getDisposeImage() {
- return mDisposeImage;
- }
-
- @Override
- public Point computeSize(int wHint, int hHint, boolean changed) {
- checkWidget();
- Point e = new Point(0, 0);
- if (mImage != null) {
- Rectangle r = mImage.getBounds();
- if (mScale != 1.0f) {
- e.x += mScale * r.width;
- e.y += mScale * r.height;
- } else {
- e.x += r.width;
- e.y += r.height;
- }
- }
- if (wHint == SWT.DEFAULT) {
- e.x += mLeftMargin + mRightMargin;
- } else {
- e.x = wHint;
- }
- if (hHint == SWT.DEFAULT) {
- e.y += mTopMargin + mBottomMargin;
- } else {
- e.y = hHint;
- }
-
- return e;
- }
-
- private void onPaint(PaintEvent event) {
- Rectangle rect = getClientArea();
- if (mImage == null || rect.width == 0 || rect.height == 0) {
- return;
- }
-
- GC gc = event.gc;
- Rectangle imageRect = mImage.getBounds();
- int imageHeight = imageRect.height;
- int imageWidth = imageRect.width;
- int destWidth = imageWidth;
- int destHeight = imageHeight;
-
- int oldGcAlias = gc.getAntialias();
- int oldGcInterpolation = gc.getInterpolation();
- if (mScale != 1.0f) {
- destWidth = (int) (mScale * destWidth);
- destHeight = (int) (mScale * destHeight);
- gc.setAntialias(SWT.ON);
- gc.setInterpolation(SWT.HIGH);
- }
-
- gc.drawImage(mImage, 0, 0, imageWidth, imageHeight, rect.x + mLeftMargin, rect.y
- + mTopMargin, destWidth, destHeight);
-
- gc.setAntialias(oldGcAlias);
- gc.setInterpolation(oldGcInterpolation);
-
- if (mHoverColor != null && mMouseIn) {
- gc.setAlpha(60);
- gc.setBackground(mHoverColor);
- gc.setLineWidth(1);
- gc.fillRectangle(0, 0, destWidth, destHeight);
- }
- }
-
- public void setMargins(int leftMargin, int topMargin, int rightMargin, int bottomMargin) {
- checkWidget();
- mLeftMargin = Math.max(0, leftMargin);
- mTopMargin = Math.max(0, topMargin);
- mRightMargin = Math.max(0, rightMargin);
- mBottomMargin = Math.max(0, bottomMargin);
- redraw();
- }
-
- // ---- Implements MouseTrackListener ----
-
- @Override
- public void mouseEnter(MouseEvent e) {
- mMouseIn = true;
- if (mHoverColor != null) {
- redraw();
- }
- }
-
- @Override
- public void mouseExit(MouseEvent e) {
- mMouseIn = false;
- if (mHoverColor != null) {
- redraw();
- }
- }
-
- @Override
- public void mouseHover(MouseEvent e) {
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ImageOverlay.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ImageOverlay.java
deleted file mode 100644
index a1363ecb1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ImageOverlay.java
+++ /dev/null
@@ -1,447 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.ImageUtils.SHADOW_SIZE;
-
-import com.android.SdkConstants;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.rendering.api.IImageFactory;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.SWTException;
-import org.eclipse.swt.graphics.Device;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.ImageData;
-import org.eclipse.swt.graphics.PaletteData;
-
-import java.awt.image.BufferedImage;
-import java.awt.image.DataBufferInt;
-import java.awt.image.WritableRaster;
-import java.lang.ref.SoftReference;
-
-/**
- * The {@link ImageOverlay} class renders an image as an overlay.
- */
-public class ImageOverlay extends Overlay implements IImageFactory {
- /**
- * Whether the image should be pre-scaled (scaled to the zoom level) once
- * instead of dynamically during each paint; this is necessary on some
- * platforms (see issue #19447)
- */
- private static final boolean PRESCALE =
- // Currently this is necessary on Linux because the "Cairo" library
- // seems to be a bottleneck
- SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_LINUX
- && !(Boolean.getBoolean("adt.noprescale")); //$NON-NLS-1$
-
- /** Current background image. Null when there's no image. */
- private Image mImage;
-
- /** A pre-scaled version of the image */
- private Image mPreScaledImage;
-
- /** Whether the rendered image should have a drop shadow */
- private boolean mShowDropShadow;
-
- /** Current background AWT image. This is created by {@link #getImage()}, which is called
- * by the LayoutLib. */
- private SoftReference<BufferedImage> mAwtImage = new SoftReference<BufferedImage>(null);
-
- /**
- * Strong reference to the image in the above soft reference, to prevent
- * garbage collection when {@link PRESCALE} is set, until the scaled image
- * is created (lazily as part of the next paint call, where this strong
- * reference is nulled out and the above soft reference becomes eligible to
- * be reclaimed when memory is low.)
- */
- @SuppressWarnings("unused") // Used by the garbage collector to keep mAwtImage non-soft
- private BufferedImage mAwtImageStrongRef;
-
- /** The associated {@link LayoutCanvas}. */
- private LayoutCanvas mCanvas;
-
- /** Vertical scaling & scrollbar information. */
- private CanvasTransform mVScale;
-
- /** Horizontal scaling & scrollbar information. */
- private CanvasTransform mHScale;
-
- /**
- * Constructs an {@link ImageOverlay} tied to the given canvas.
- *
- * @param canvas The {@link LayoutCanvas} to paint the overlay over.
- * @param hScale The horizontal scale information.
- * @param vScale The vertical scale information.
- */
- public ImageOverlay(LayoutCanvas canvas, CanvasTransform hScale, CanvasTransform vScale) {
- mCanvas = canvas;
- mHScale = hScale;
- mVScale = vScale;
- }
-
- @Override
- public void create(Device device) {
- super.create(device);
- }
-
- @Override
- public void dispose() {
- if (mImage != null) {
- mImage.dispose();
- mImage = null;
- }
- if (mPreScaledImage != null) {
- mPreScaledImage.dispose();
- mPreScaledImage = null;
- }
- }
-
- /**
- * Sets the image to be drawn as an overlay from the passed in AWT
- * {@link BufferedImage} (which will be converted to an SWT image).
- * <p/>
- * The image <b>can</b> be null, which is the case when we are dealing with
- * an empty document.
- *
- * @param awtImage The AWT image to be rendered as an SWT image.
- * @param isAlphaChannelImage whether the alpha channel of the image is relevant
- * @return The corresponding SWT image, or null.
- */
- public synchronized Image setImage(BufferedImage awtImage, boolean isAlphaChannelImage) {
- mShowDropShadow = !isAlphaChannelImage;
-
- BufferedImage oldAwtImage = mAwtImage.get();
- if (awtImage != oldAwtImage || awtImage == null) {
- mAwtImage.clear();
- mAwtImageStrongRef = null;
-
- if (mImage != null) {
- mImage.dispose();
- }
-
- if (awtImage == null) {
- mImage = null;
- } else {
- mImage = SwtUtils.convertToSwt(mCanvas.getDisplay(), awtImage,
- isAlphaChannelImage, -1);
- }
- } else {
- assert awtImage instanceof SwtReadyBufferedImage;
-
- if (isAlphaChannelImage) {
- if (mImage != null) {
- mImage.dispose();
- }
-
- mImage = SwtUtils.convertToSwt(mCanvas.getDisplay(), awtImage, true, -1);
- } else {
- Image prev = mImage;
- mImage = ((SwtReadyBufferedImage)awtImage).getSwtImage();
- if (prev != mImage && prev != null) {
- prev.dispose();
- }
- }
- }
-
- if (mPreScaledImage != null) {
- // Force refresh on next paint
- mPreScaledImage.dispose();
- mPreScaledImage = null;
- }
-
- return mImage;
- }
-
- /**
- * Returns the currently painted image, or null if none has been set
- *
- * @return the currently painted image or null
- */
- public Image getImage() {
- return mImage;
- }
-
- /**
- * Returns the currently rendered image, or null if none has been set
- *
- * @return the currently rendered image or null
- */
- @Nullable
- BufferedImage getAwtImage() {
- BufferedImage awtImage = mAwtImage.get();
- if (awtImage == null && mImage != null) {
- awtImage = SwtUtils.convertToAwt(mImage);
- }
-
- return awtImage;
- }
-
- /**
- * Returns whether this image overlay should be painted with a drop shadow.
- * This is usually the case, but not for transparent themes like the dialog
- * theme (Theme.*Dialog), which already provides its own shadow.
- *
- * @return true if the image overlay should be shown with a drop shadow.
- */
- public boolean getShowDropShadow() {
- return mShowDropShadow;
- }
-
- @Override
- public synchronized void paint(GC gc) {
- if (mImage != null) {
- boolean valid = mCanvas.getViewHierarchy().isValid();
- mCanvas.ensureZoomed();
- if (!valid) {
- gc_setAlpha(gc, 128); // half-transparent
- }
-
- CanvasTransform hi = mHScale;
- CanvasTransform vi = mVScale;
-
- // On some platforms, dynamic image scaling is very slow (see issue #19447) so
- // compute a pre-scaled version of the image once and render that instead.
- // This is done lazily in paint rather than when the image changes because
- // the image must be rescaled each time the zoom level changes, which varies
- // independently from when the image changes.
- BufferedImage awtImage = mAwtImage.get();
- if (PRESCALE && awtImage != null) {
- int imageWidth = (mPreScaledImage == null) ? 0
- : mPreScaledImage.getImageData().width
- - (mShowDropShadow ? SHADOW_SIZE : 0);
- if (mPreScaledImage == null || imageWidth != hi.getScaledImgSize()) {
- double xScale = hi.getScaledImgSize() / (double) awtImage.getWidth();
- double yScale = vi.getScaledImgSize() / (double) awtImage.getHeight();
- BufferedImage scaledAwtImage;
-
- // NOTE: == comparison on floating point numbers is okay
- // here because we normalize the scaling factor
- // to an exact 1.0 in the zooming code when the value gets
- // near 1.0 to make painting more efficient in the presence
- // of rounding errors.
- if (xScale == 1.0 && yScale == 1.0) {
- // Scaling to 100% is easy!
- scaledAwtImage = awtImage;
-
- if (mShowDropShadow) {
- // Just need to draw drop shadows
- scaledAwtImage = ImageUtils.createRectangularDropShadow(awtImage);
- }
- } else {
- if (mShowDropShadow) {
- scaledAwtImage = ImageUtils.scale(awtImage, xScale, yScale,
- SHADOW_SIZE, SHADOW_SIZE);
- ImageUtils.drawRectangleShadow(scaledAwtImage, 0, 0,
- scaledAwtImage.getWidth() - SHADOW_SIZE,
- scaledAwtImage.getHeight() - SHADOW_SIZE);
- } else {
- scaledAwtImage = ImageUtils.scale(awtImage, xScale, yScale);
- }
- }
-
- if (mPreScaledImage != null && !mPreScaledImage.isDisposed()) {
- mPreScaledImage.dispose();
- }
- mPreScaledImage = SwtUtils.convertToSwt(mCanvas.getDisplay(), scaledAwtImage,
- true /*transferAlpha*/, -1);
- // We can't just clear the mAwtImageStrongRef here, because if the
- // zooming factor changes, we may need to use it again
- }
-
- if (mPreScaledImage != null) {
- gc.drawImage(mPreScaledImage, hi.translate(0), vi.translate(0));
- }
- return;
- }
-
- // we only anti-alias when reducing the image size.
- int oldAlias = -2;
- if (hi.getScale() < 1.0) {
- oldAlias = gc_setAntialias(gc, SWT.ON);
- }
-
- int srcX = 0;
- int srcY = 0;
- int srcWidth = hi.getImgSize();
- int srcHeight = vi.getImgSize();
- int destX = hi.translate(0);
- int destY = vi.translate(0);
- int destWidth = hi.getScaledImgSize();
- int destHeight = vi.getScaledImgSize();
-
- gc.drawImage(mImage,
- srcX, srcY, srcWidth, srcHeight,
- destX, destY, destWidth, destHeight);
-
- if (mShowDropShadow) {
- SwtUtils.drawRectangleShadow(gc, destX, destY, destWidth, destHeight);
- }
-
- if (oldAlias != -2) {
- gc_setAntialias(gc, oldAlias);
- }
-
- if (!valid) {
- gc_setAlpha(gc, 255); // opaque
- }
- }
- }
-
- /**
- * Sets the alpha for the given GC.
- * <p/>
- * Alpha may not work on all platforms and may fail with an exception, which
- * is hidden here (false is returned in that case).
- *
- * @param gc the GC to change
- * @param alpha the new alpha, 0 for transparent, 255 for opaque.
- * @return True if the operation worked, false if it failed with an
- * exception.
- * @see GC#setAlpha(int)
- */
- private boolean gc_setAlpha(GC gc, int alpha) {
- try {
- gc.setAlpha(alpha);
- return true;
- } catch (SWTException e) {
- return false;
- }
- }
-
- /**
- * Sets the non-text antialias flag for the given GC.
- * <p/>
- * Antialias may not work on all platforms and may fail with an exception,
- * which is hidden here (-2 is returned in that case).
- *
- * @param gc the GC to change
- * @param alias One of {@link SWT#DEFAULT}, {@link SWT#ON}, {@link SWT#OFF}.
- * @return The previous aliasing mode if the operation worked, or -2 if it
- * failed with an exception.
- * @see GC#setAntialias(int)
- */
- private int gc_setAntialias(GC gc, int alias) {
- try {
- int old = gc.getAntialias();
- gc.setAntialias(alias);
- return old;
- } catch (SWTException e) {
- return -2;
- }
- }
-
- /**
- * Custom {@link BufferedImage} class able to convert itself into an SWT {@link Image}
- * efficiently.
- *
- * The BufferedImage also contains an instance of {@link ImageData} that's kept around
- * and used to create new SWT {@link Image} objects in {@link #getSwtImage()}.
- *
- */
- private static final class SwtReadyBufferedImage extends BufferedImage {
-
- private final ImageData mImageData;
- private final Device mDevice;
-
- /**
- * Creates the image with a given model, raster and SWT {@link ImageData}
- * @param model the color model
- * @param raster the image raster
- * @param imageData the SWT image data.
- * @param device the {@link Device} in which the SWT image will be painted.
- */
- private SwtReadyBufferedImage(int width, int height, ImageData imageData, Device device) {
- super(width, height, BufferedImage.TYPE_INT_ARGB);
- mImageData = imageData;
- mDevice = device;
- }
-
- /**
- * Returns a new {@link Image} object initialized with the content of the BufferedImage.
- * @return the image object.
- */
- private Image getSwtImage() {
- // transfer the content of the bufferedImage into the image data.
- WritableRaster raster = getRaster();
- int[] imageDataBuffer = ((DataBufferInt) raster.getDataBuffer()).getData();
-
- mImageData.setPixels(0, 0, imageDataBuffer.length, imageDataBuffer, 0);
-
- return new Image(mDevice, mImageData);
- }
-
- /**
- * Creates a new {@link SwtReadyBufferedImage}.
- * @param w the width of the image
- * @param h the height of the image
- * @param device the device in which the SWT image will be painted
- * @return a new {@link SwtReadyBufferedImage} object
- */
- private static SwtReadyBufferedImage createImage(int w, int h, Device device) {
- // NOTE: We can't make this image bigger to accommodate the drop shadow directly
- // (such that we could paint one into the image after a layoutlib render)
- // since this image is in the full resolution of the device, and gets scaled
- // to fit in the layout editor. This would have the net effect of causing
- // the drop shadow to get zoomed/scaled along with the scene, making a tiny
- // drop shadow for tablet layouts, a huge drop shadow for tiny QVGA screens, etc.
-
- ImageData imageData = new ImageData(w, h, 32,
- new PaletteData(0x00FF0000, 0x0000FF00, 0x000000FF));
-
- SwtReadyBufferedImage swtReadyImage = new SwtReadyBufferedImage(w, h,
- imageData, device);
-
- return swtReadyImage;
- }
- }
-
- /**
- * Implementation of {@link IImageFactory#getImage(int, int)}.
- */
- @Override
- public BufferedImage getImage(int w, int h) {
- BufferedImage awtImage = mAwtImage.get();
- if (awtImage == null ||
- awtImage.getWidth() != w ||
- awtImage.getHeight() != h) {
- mAwtImage.clear();
- awtImage = SwtReadyBufferedImage.createImage(w, h, getDevice());
- mAwtImage = new SoftReference<BufferedImage>(awtImage);
- if (PRESCALE) {
- mAwtImageStrongRef = awtImage;
- }
- }
-
- return awtImage;
- }
-
- /**
- * Returns the bounds of the current image, or null
- *
- * @return the bounds of the current image, or null
- */
- public Rect getImageBounds() {
- if (mImage == null) {
- return null;
- }
-
- return new Rect(0, 0, mImage.getImageData().width, mImage.getImageData().height);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ImageUtils.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ImageUtils.java
deleted file mode 100644
index b5bc9aa72..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ImageUtils.java
+++ /dev/null
@@ -1,979 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.SdkConstants.DOT_9PNG;
-import static com.android.SdkConstants.DOT_BMP;
-import static com.android.SdkConstants.DOT_GIF;
-import static com.android.SdkConstants.DOT_JPG;
-import static com.android.SdkConstants.DOT_PNG;
-import static com.android.utils.SdkUtils.endsWithIgnoreCase;
-import static java.awt.RenderingHints.KEY_ANTIALIASING;
-import static java.awt.RenderingHints.KEY_INTERPOLATION;
-import static java.awt.RenderingHints.KEY_RENDERING;
-import static java.awt.RenderingHints.VALUE_ANTIALIAS_ON;
-import static java.awt.RenderingHints.VALUE_INTERPOLATION_BILINEAR;
-import static java.awt.RenderingHints.VALUE_RENDER_QUALITY;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.Rect;
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.graphics.Rectangle;
-
-import java.awt.AlphaComposite;
-import java.awt.Color;
-import java.awt.Graphics;
-import java.awt.Graphics2D;
-import java.awt.image.BufferedImage;
-import java.awt.image.DataBufferInt;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Iterator;
-import java.util.List;
-
-import javax.imageio.ImageIO;
-
-/**
- * Utilities related to image processing.
- */
-public class ImageUtils {
- /**
- * Returns true if the given image has no dark pixels
- *
- * @param image the image to be checked for dark pixels
- * @return true if no dark pixels were found
- */
- public static boolean containsDarkPixels(BufferedImage image) {
- for (int y = 0, height = image.getHeight(); y < height; y++) {
- for (int x = 0, width = image.getWidth(); x < width; x++) {
- int pixel = image.getRGB(x, y);
- if ((pixel & 0xFF000000) != 0) {
- int r = (pixel & 0xFF0000) >> 16;
- int g = (pixel & 0x00FF00) >> 8;
- int b = (pixel & 0x0000FF);
-
- // One perceived luminance formula is (0.299*red + 0.587*green + 0.114*blue)
- // In order to keep this fast since we don't need a very accurate
- // measure, I'll just estimate this with integer math:
- long brightness = (299L*r + 587*g + 114*b) / 1000;
- if (brightness < 128) {
- return true;
- }
- }
- }
- }
- return false;
- }
-
- /**
- * Returns the perceived brightness of the given RGB integer on a scale from 0 to 255
- *
- * @param rgb the RGB triplet, 8 bits each
- * @return the perceived brightness, with 0 maximally dark and 255 maximally bright
- */
- public static int getBrightness(int rgb) {
- if ((rgb & 0xFFFFFF) != 0) {
- int r = (rgb & 0xFF0000) >> 16;
- int g = (rgb & 0x00FF00) >> 8;
- int b = (rgb & 0x0000FF);
- // See the containsDarkPixels implementation for details
- return (int) ((299L*r + 587*g + 114*b) / 1000);
- }
-
- return 0;
- }
-
- /**
- * Converts an alpha-red-green-blue integer color into an {@link RGB} color.
- * <p>
- * <b>NOTE</b> - this will drop the alpha value since {@link RGB} objects do not
- * contain transparency information.
- *
- * @param rgb the RGB integer to convert to a color description
- * @return the color description corresponding to the integer
- */
- public static RGB intToRgb(int rgb) {
- return new RGB((rgb & 0xFF0000) >>> 16, (rgb & 0xFF00) >>> 8, rgb & 0xFF);
- }
-
- /**
- * Converts an {@link RGB} color into a alpha-red-green-blue integer
- *
- * @param rgb the RGB color descriptor to convert
- * @param alpha the amount of alpha to add into the color integer (since the
- * {@link RGB} objects do not contain an alpha channel)
- * @return an integer corresponding to the {@link RGB} color
- */
- public static int rgbToInt(RGB rgb, int alpha) {
- return alpha << 24 | (rgb.red << 16) | (rgb.green << 8) | rgb.blue;
- }
-
- /**
- * Crops blank pixels from the edges of the image and returns the cropped result. We
- * crop off pixels that are blank (meaning they have an alpha value = 0). Note that
- * this is not the same as pixels that aren't opaque (an alpha value other than 255).
- *
- * @param image the image to be cropped
- * @param initialCrop If not null, specifies a rectangle which contains an initial
- * crop to continue. This can be used to crop an image where you already
- * know about margins in the image
- * @return a cropped version of the source image, or null if the whole image was blank
- * and cropping completely removed everything
- */
- @Nullable
- public static BufferedImage cropBlank(
- @NonNull BufferedImage image,
- @Nullable Rect initialCrop) {
- return cropBlank(image, initialCrop, image.getType());
- }
-
- /**
- * Crops blank pixels from the edges of the image and returns the cropped result. We
- * crop off pixels that are blank (meaning they have an alpha value = 0). Note that
- * this is not the same as pixels that aren't opaque (an alpha value other than 255).
- *
- * @param image the image to be cropped
- * @param initialCrop If not null, specifies a rectangle which contains an initial
- * crop to continue. This can be used to crop an image where you already
- * know about margins in the image
- * @param imageType the type of {@link BufferedImage} to create
- * @return a cropped version of the source image, or null if the whole image was blank
- * and cropping completely removed everything
- */
- public static BufferedImage cropBlank(BufferedImage image, Rect initialCrop, int imageType) {
- CropFilter filter = new CropFilter() {
- @Override
- public boolean crop(BufferedImage bufferedImage, int x, int y) {
- int rgb = bufferedImage.getRGB(x, y);
- return (rgb & 0xFF000000) == 0x00000000;
- // TODO: Do a threshold of 80 instead of just 0? Might give better
- // visual results -- e.g. check <= 0x80000000
- }
- };
- return crop(image, filter, initialCrop, imageType);
- }
-
- /**
- * Crops pixels of a given color from the edges of the image and returns the cropped
- * result.
- *
- * @param image the image to be cropped
- * @param blankArgb the color considered to be blank, as a 32 pixel integer with 8
- * bits of alpha, red, green and blue
- * @param initialCrop If not null, specifies a rectangle which contains an initial
- * crop to continue. This can be used to crop an image where you already
- * know about margins in the image
- * @return a cropped version of the source image, or null if the whole image was blank
- * and cropping completely removed everything
- */
- @Nullable
- public static BufferedImage cropColor(
- @NonNull BufferedImage image,
- final int blankArgb,
- @Nullable Rect initialCrop) {
- return cropColor(image, blankArgb, initialCrop, image.getType());
- }
-
- /**
- * Crops pixels of a given color from the edges of the image and returns the cropped
- * result.
- *
- * @param image the image to be cropped
- * @param blankArgb the color considered to be blank, as a 32 pixel integer with 8
- * bits of alpha, red, green and blue
- * @param initialCrop If not null, specifies a rectangle which contains an initial
- * crop to continue. This can be used to crop an image where you already
- * know about margins in the image
- * @param imageType the type of {@link BufferedImage} to create
- * @return a cropped version of the source image, or null if the whole image was blank
- * and cropping completely removed everything
- */
- public static BufferedImage cropColor(BufferedImage image,
- final int blankArgb, Rect initialCrop, int imageType) {
- CropFilter filter = new CropFilter() {
- @Override
- public boolean crop(BufferedImage bufferedImage, int x, int y) {
- return blankArgb == bufferedImage.getRGB(x, y);
- }
- };
- return crop(image, filter, initialCrop, imageType);
- }
-
- /**
- * Interface implemented by cropping functions that determine whether
- * a pixel should be cropped or not.
- */
- private static interface CropFilter {
- /**
- * Returns true if the pixel is should be cropped.
- *
- * @param image the image containing the pixel in question
- * @param x the x position of the pixel
- * @param y the y position of the pixel
- * @return true if the pixel should be cropped (for example, is blank)
- */
- boolean crop(BufferedImage image, int x, int y);
- }
-
- private static BufferedImage crop(BufferedImage image, CropFilter filter, Rect initialCrop,
- int imageType) {
- if (image == null) {
- return null;
- }
-
- // First, determine the dimensions of the real image within the image
- int x1, y1, x2, y2;
- if (initialCrop != null) {
- x1 = initialCrop.x;
- y1 = initialCrop.y;
- x2 = initialCrop.x + initialCrop.w;
- y2 = initialCrop.y + initialCrop.h;
- } else {
- x1 = 0;
- y1 = 0;
- x2 = image.getWidth();
- y2 = image.getHeight();
- }
-
- // Nothing left to crop
- if (x1 == x2 || y1 == y2) {
- return null;
- }
-
- // This algorithm is a bit dumb -- it just scans along the edges looking for
- // a pixel that shouldn't be cropped. I could maybe try to make it smarter by
- // for example doing a binary search to quickly eliminate large empty areas to
- // the right and bottom -- but this is slightly tricky with components like the
- // AnalogClock where I could accidentally end up finding a blank horizontal or
- // vertical line somewhere in the middle of the rendering of the clock, so for now
- // we do the dumb thing -- not a big deal since we tend to crop reasonably
- // small images.
-
- // First determine top edge
- topEdge: for (; y1 < y2; y1++) {
- for (int x = x1; x < x2; x++) {
- if (!filter.crop(image, x, y1)) {
- break topEdge;
- }
- }
- }
-
- if (y1 == image.getHeight()) {
- // The image is blank
- return null;
- }
-
- // Next determine left edge
- leftEdge: for (; x1 < x2; x1++) {
- for (int y = y1; y < y2; y++) {
- if (!filter.crop(image, x1, y)) {
- break leftEdge;
- }
- }
- }
-
- // Next determine right edge
- rightEdge: for (; x2 > x1; x2--) {
- for (int y = y1; y < y2; y++) {
- if (!filter.crop(image, x2 - 1, y)) {
- break rightEdge;
- }
- }
- }
-
- // Finally determine bottom edge
- bottomEdge: for (; y2 > y1; y2--) {
- for (int x = x1; x < x2; x++) {
- if (!filter.crop(image, x, y2 - 1)) {
- break bottomEdge;
- }
- }
- }
-
- // No need to crop?
- if (x1 == 0 && y1 == 0 && x2 == image.getWidth() && y2 == image.getHeight()) {
- return image;
- }
-
- if (x1 == x2 || y1 == y2) {
- // Nothing left after crop -- blank image
- return null;
- }
-
- int width = x2 - x1;
- int height = y2 - y1;
-
- // Now extract the sub-image
- if (imageType == -1) {
- imageType = image.getType();
- }
- if (imageType == BufferedImage.TYPE_CUSTOM) {
- imageType = BufferedImage.TYPE_INT_ARGB;
- }
- BufferedImage cropped = new BufferedImage(width, height, imageType);
- Graphics g = cropped.getGraphics();
- g.drawImage(image, 0, 0, width, height, x1, y1, x2, y2, null);
-
- g.dispose();
-
- return cropped;
- }
-
- /**
- * Creates a drop shadow of a given image and returns a new image which shows the
- * input image on top of its drop shadow.
- * <p>
- * <b>NOTE: If the shape is rectangular and opaque, consider using
- * {@link #drawRectangleShadow(Graphics, int, int, int, int)} instead.</b>
- *
- * @param source the source image to be shadowed
- * @param shadowSize the size of the shadow in pixels
- * @param shadowOpacity the opacity of the shadow, with 0=transparent and 1=opaque
- * @param shadowRgb the RGB int to use for the shadow color
- * @return a new image with the source image on top of its shadow
- */
- public static BufferedImage createDropShadow(BufferedImage source, int shadowSize,
- float shadowOpacity, int shadowRgb) {
-
- // This code is based on
- // http://www.jroller.com/gfx/entry/non_rectangular_shadow
-
- BufferedImage image = new BufferedImage(source.getWidth() + shadowSize * 2,
- source.getHeight() + shadowSize * 2,
- BufferedImage.TYPE_INT_ARGB);
-
- Graphics2D g2 = image.createGraphics();
- g2.drawImage(source, null, shadowSize, shadowSize);
-
- int dstWidth = image.getWidth();
- int dstHeight = image.getHeight();
-
- int left = (shadowSize - 1) >> 1;
- int right = shadowSize - left;
- int xStart = left;
- int xStop = dstWidth - right;
- int yStart = left;
- int yStop = dstHeight - right;
-
- shadowRgb = shadowRgb & 0x00FFFFFF;
-
- int[] aHistory = new int[shadowSize];
- int historyIdx = 0;
-
- int aSum;
-
- int[] dataBuffer = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
- int lastPixelOffset = right * dstWidth;
- float sumDivider = shadowOpacity / shadowSize;
-
- // horizontal pass
- for (int y = 0, bufferOffset = 0; y < dstHeight; y++, bufferOffset = y * dstWidth) {
- aSum = 0;
- historyIdx = 0;
- for (int x = 0; x < shadowSize; x++, bufferOffset++) {
- int a = dataBuffer[bufferOffset] >>> 24;
- aHistory[x] = a;
- aSum += a;
- }
-
- bufferOffset -= right;
-
- for (int x = xStart; x < xStop; x++, bufferOffset++) {
- int a = (int) (aSum * sumDivider);
- dataBuffer[bufferOffset] = a << 24 | shadowRgb;
-
- // subtract the oldest pixel from the sum
- aSum -= aHistory[historyIdx];
-
- // get the latest pixel
- a = dataBuffer[bufferOffset + right] >>> 24;
- aHistory[historyIdx] = a;
- aSum += a;
-
- if (++historyIdx >= shadowSize) {
- historyIdx -= shadowSize;
- }
- }
- }
- // vertical pass
- for (int x = 0, bufferOffset = 0; x < dstWidth; x++, bufferOffset = x) {
- aSum = 0;
- historyIdx = 0;
- for (int y = 0; y < shadowSize; y++, bufferOffset += dstWidth) {
- int a = dataBuffer[bufferOffset] >>> 24;
- aHistory[y] = a;
- aSum += a;
- }
-
- bufferOffset -= lastPixelOffset;
-
- for (int y = yStart; y < yStop; y++, bufferOffset += dstWidth) {
- int a = (int) (aSum * sumDivider);
- dataBuffer[bufferOffset] = a << 24 | shadowRgb;
-
- // subtract the oldest pixel from the sum
- aSum -= aHistory[historyIdx];
-
- // get the latest pixel
- a = dataBuffer[bufferOffset + lastPixelOffset] >>> 24;
- aHistory[historyIdx] = a;
- aSum += a;
-
- if (++historyIdx >= shadowSize) {
- historyIdx -= shadowSize;
- }
- }
- }
-
- g2.drawImage(source, null, 0, 0);
- g2.dispose();
-
- return image;
- }
-
- /**
- * Draws a rectangular drop shadow (of size {@link #SHADOW_SIZE} by
- * {@link #SHADOW_SIZE} around the given source and returns a new image with
- * both combined
- *
- * @param source the source image
- * @return the source image with a drop shadow on the bottom and right
- */
- public static BufferedImage createRectangularDropShadow(BufferedImage source) {
- int type = source.getType();
- if (type == BufferedImage.TYPE_CUSTOM) {
- type = BufferedImage.TYPE_INT_ARGB;
- }
-
- int width = source.getWidth();
- int height = source.getHeight();
- BufferedImage image = new BufferedImage(width + SHADOW_SIZE, height + SHADOW_SIZE, type);
- Graphics g = image.getGraphics();
- g.drawImage(source, 0, 0, width, height, null);
- ImageUtils.drawRectangleShadow(image, 0, 0, width, height);
- g.dispose();
-
- return image;
- }
-
- /**
- * Draws a drop shadow for the given rectangle into the given context. It
- * will not draw anything if the rectangle is smaller than a minimum
- * determined by the assets used to draw the shadow graphics.
- * The size of the shadow is {@link #SHADOW_SIZE}.
- *
- * @param image the image to draw the shadow into
- * @param x the left coordinate of the left hand side of the rectangle
- * @param y the top coordinate of the top of the rectangle
- * @param width the width of the rectangle
- * @param height the height of the rectangle
- */
- public static final void drawRectangleShadow(BufferedImage image,
- int x, int y, int width, int height) {
- Graphics gc = image.getGraphics();
- try {
- drawRectangleShadow(gc, x, y, width, height);
- } finally {
- gc.dispose();
- }
- }
-
- /**
- * Draws a small drop shadow for the given rectangle into the given context. It
- * will not draw anything if the rectangle is smaller than a minimum
- * determined by the assets used to draw the shadow graphics.
- * The size of the shadow is {@link #SMALL_SHADOW_SIZE}.
- *
- * @param image the image to draw the shadow into
- * @param x the left coordinate of the left hand side of the rectangle
- * @param y the top coordinate of the top of the rectangle
- * @param width the width of the rectangle
- * @param height the height of the rectangle
- */
- public static final void drawSmallRectangleShadow(BufferedImage image,
- int x, int y, int width, int height) {
- Graphics gc = image.getGraphics();
- try {
- drawSmallRectangleShadow(gc, x, y, width, height);
- } finally {
- gc.dispose();
- }
- }
-
- /**
- * The width and height of the drop shadow painted by
- * {@link #drawRectangleShadow(Graphics, int, int, int, int)}
- */
- public static final int SHADOW_SIZE = 20; // DO NOT EDIT. This corresponds to bitmap graphics
-
- /**
- * The width and height of the drop shadow painted by
- * {@link #drawSmallRectangleShadow(Graphics, int, int, int, int)}
- */
- public static final int SMALL_SHADOW_SIZE = 10; // DO NOT EDIT. Corresponds to bitmap graphics
-
- /**
- * Draws a drop shadow for the given rectangle into the given context. It
- * will not draw anything if the rectangle is smaller than a minimum
- * determined by the assets used to draw the shadow graphics.
- * <p>
- * This corresponds to
- * {@link SwtUtils#drawRectangleShadow(org.eclipse.swt.graphics.GC, int, int, int, int)},
- * but applied to an AWT graphics object instead, such that no image
- * conversion has to be performed.
- * <p>
- * Make sure to keep changes in the visual appearance here in sync with the
- * AWT version in
- * {@link SwtUtils#drawRectangleShadow(org.eclipse.swt.graphics.GC, int, int, int, int)}.
- *
- * @param gc the graphics context to draw into
- * @param x the left coordinate of the left hand side of the rectangle
- * @param y the top coordinate of the top of the rectangle
- * @param width the width of the rectangle
- * @param height the height of the rectangle
- */
- public static final void drawRectangleShadow(Graphics gc,
- int x, int y, int width, int height) {
- if (sShadowBottomLeft == null) {
- // Shadow graphics. This was generated by creating a drop shadow in
- // Gimp, using the parameters x offset=10, y offset=10, blur radius=10,
- // color=black, and opacity=51. These values attempt to make a shadow
- // that is legible both for dark and light themes, on top of the
- // canvas background (rgb(150,150,150). Darker shadows would tend to
- // blend into the foreground for a dark holo screen, and lighter shadows
- // would be hard to spot on the canvas background. If you make adjustments,
- // make sure to check the shadow with both dark and light themes.
- //
- // After making the graphics, I cut out the top right, bottom left
- // and bottom right corners as 20x20 images, and these are reproduced by
- // painting them in the corresponding places in the target graphics context.
- // I then grabbed a single horizontal gradient line from the middle of the
- // right edge,and a single vertical gradient line from the bottom. These
- // are then painted scaled/stretched in the target to fill the gaps between
- // the three corner images.
- //
- // Filenames: bl=bottom left, b=bottom, br=bottom right, r=right, tr=top right
- sShadowBottomLeft = readImage("shadow-bl.png"); //$NON-NLS-1$
- sShadowBottom = readImage("shadow-b.png"); //$NON-NLS-1$
- sShadowBottomRight = readImage("shadow-br.png"); //$NON-NLS-1$
- sShadowRight = readImage("shadow-r.png"); //$NON-NLS-1$
- sShadowTopRight = readImage("shadow-tr.png"); //$NON-NLS-1$
- assert sShadowBottomLeft != null;
- assert sShadowBottomRight.getWidth() == SHADOW_SIZE;
- assert sShadowBottomRight.getHeight() == SHADOW_SIZE;
- }
-
- int blWidth = sShadowBottomLeft.getWidth();
- int trHeight = sShadowTopRight.getHeight();
- if (width < blWidth) {
- return;
- }
- if (height < trHeight) {
- return;
- }
-
- gc.drawImage(sShadowBottomLeft, x, y + height, null);
- gc.drawImage(sShadowBottomRight, x + width, y + height, null);
- gc.drawImage(sShadowTopRight, x + width, y, null);
- gc.drawImage(sShadowBottom,
- x + sShadowBottomLeft.getWidth(), y + height,
- x + width, y + height + sShadowBottom.getHeight(),
- 0, 0, sShadowBottom.getWidth(), sShadowBottom.getHeight(),
- null);
- gc.drawImage(sShadowRight,
- x + width, y + sShadowTopRight.getHeight(),
- x + width + sShadowRight.getWidth(), y + height,
- 0, 0, sShadowRight.getWidth(), sShadowRight.getHeight(),
- null);
- }
-
- /**
- * Draws a small drop shadow for the given rectangle into the given context. It
- * will not draw anything if the rectangle is smaller than a minimum
- * determined by the assets used to draw the shadow graphics.
- * <p>
- *
- * @param gc the graphics context to draw into
- * @param x the left coordinate of the left hand side of the rectangle
- * @param y the top coordinate of the top of the rectangle
- * @param width the width of the rectangle
- * @param height the height of the rectangle
- */
- public static final void drawSmallRectangleShadow(Graphics gc,
- int x, int y, int width, int height) {
- if (sShadow2BottomLeft == null) {
- // Shadow graphics. This was generated by creating a drop shadow in
- // Gimp, using the parameters x offset=5, y offset=%, blur radius=5,
- // color=black, and opacity=51. These values attempt to make a shadow
- // that is legible both for dark and light themes, on top of the
- // canvas background (rgb(150,150,150). Darker shadows would tend to
- // blend into the foreground for a dark holo screen, and lighter shadows
- // would be hard to spot on the canvas background. If you make adjustments,
- // make sure to check the shadow with both dark and light themes.
- //
- // After making the graphics, I cut out the top right, bottom left
- // and bottom right corners as 20x20 images, and these are reproduced by
- // painting them in the corresponding places in the target graphics context.
- // I then grabbed a single horizontal gradient line from the middle of the
- // right edge,and a single vertical gradient line from the bottom. These
- // are then painted scaled/stretched in the target to fill the gaps between
- // the three corner images.
- //
- // Filenames: bl=bottom left, b=bottom, br=bottom right, r=right, tr=top right
- sShadow2BottomLeft = readImage("shadow2-bl.png"); //$NON-NLS-1$
- sShadow2Bottom = readImage("shadow2-b.png"); //$NON-NLS-1$
- sShadow2BottomRight = readImage("shadow2-br.png"); //$NON-NLS-1$
- sShadow2Right = readImage("shadow2-r.png"); //$NON-NLS-1$
- sShadow2TopRight = readImage("shadow2-tr.png"); //$NON-NLS-1$
- assert sShadow2BottomLeft != null;
- assert sShadow2TopRight != null;
- assert sShadow2BottomRight.getWidth() == SMALL_SHADOW_SIZE;
- assert sShadow2BottomRight.getHeight() == SMALL_SHADOW_SIZE;
- }
-
- int blWidth = sShadow2BottomLeft.getWidth();
- int trHeight = sShadow2TopRight.getHeight();
- if (width < blWidth) {
- return;
- }
- if (height < trHeight) {
- return;
- }
-
- gc.drawImage(sShadow2BottomLeft, x, y + height, null);
- gc.drawImage(sShadow2BottomRight, x + width, y + height, null);
- gc.drawImage(sShadow2TopRight, x + width, y, null);
- gc.drawImage(sShadow2Bottom,
- x + sShadow2BottomLeft.getWidth(), y + height,
- x + width, y + height + sShadow2Bottom.getHeight(),
- 0, 0, sShadow2Bottom.getWidth(), sShadow2Bottom.getHeight(),
- null);
- gc.drawImage(sShadow2Right,
- x + width, y + sShadow2TopRight.getHeight(),
- x + width + sShadow2Right.getWidth(), y + height,
- 0, 0, sShadow2Right.getWidth(), sShadow2Right.getHeight(),
- null);
- }
-
- /**
- * Reads the given image from the plugin folder
- *
- * @param name the name of the image (including file extension)
- * @return the corresponding image, or null if something goes wrong
- */
- @Nullable
- public static BufferedImage readImage(@NonNull String name) {
- InputStream stream = ImageUtils.class.getResourceAsStream("/icons/" + name); //$NON-NLS-1$
- if (stream != null) {
- try {
- return ImageIO.read(stream);
- } catch (IOException e) {
- AdtPlugin.log(e, "Could not read %1$s", name);
- } finally {
- try {
- stream.close();
- } catch (IOException e) {
- // Dumb API
- }
- }
- }
-
- return null;
- }
-
- // Normal drop shadow
- private static BufferedImage sShadowBottomLeft;
- private static BufferedImage sShadowBottom;
- private static BufferedImage sShadowBottomRight;
- private static BufferedImage sShadowRight;
- private static BufferedImage sShadowTopRight;
-
- // Small drop shadow
- private static BufferedImage sShadow2BottomLeft;
- private static BufferedImage sShadow2Bottom;
- private static BufferedImage sShadow2BottomRight;
- private static BufferedImage sShadow2Right;
- private static BufferedImage sShadow2TopRight;
-
- /**
- * Returns a bounding rectangle for the given list of rectangles. If the list is
- * empty, the bounding rectangle is null.
- *
- * @param items the list of rectangles to compute a bounding rectangle for (may not be
- * null)
- * @return a bounding rectangle of the passed in rectangles, or null if the list is
- * empty
- */
- public static Rectangle getBoundingRectangle(List<Rectangle> items) {
- Iterator<Rectangle> iterator = items.iterator();
- if (!iterator.hasNext()) {
- return null;
- }
-
- Rectangle bounds = iterator.next();
- Rectangle union = new Rectangle(bounds.x, bounds.y, bounds.width, bounds.height);
- while (iterator.hasNext()) {
- union.add(iterator.next());
- }
-
- return union;
- }
-
- /**
- * Returns a new image which contains of the sub image given by the rectangle (x1,y1)
- * to (x2,y2)
- *
- * @param source the source image
- * @param x1 top left X coordinate
- * @param y1 top left Y coordinate
- * @param x2 bottom right X coordinate
- * @param y2 bottom right Y coordinate
- * @return a new image containing the pixels in the given range
- */
- public static BufferedImage subImage(BufferedImage source, int x1, int y1, int x2, int y2) {
- int width = x2 - x1;
- int height = y2 - y1;
- int imageType = source.getType();
- if (imageType == BufferedImage.TYPE_CUSTOM) {
- imageType = BufferedImage.TYPE_INT_ARGB;
- }
- BufferedImage sub = new BufferedImage(width, height, imageType);
- Graphics g = sub.getGraphics();
- g.drawImage(source, 0, 0, width, height, x1, y1, x2, y2, null);
- g.dispose();
-
- return sub;
- }
-
- /**
- * Returns the color value represented by the given string value
- * @param value the color value
- * @return the color as an int
- * @throw NumberFormatException if the conversion failed.
- */
- public static int getColor(String value) {
- // Copied from ResourceHelper in layoutlib
- if (value != null) {
- if (value.startsWith("#") == false) { //$NON-NLS-1$
- throw new NumberFormatException(
- String.format("Color value '%s' must start with #", value));
- }
-
- value = value.substring(1);
-
- // make sure it's not longer than 32bit
- if (value.length() > 8) {
- throw new NumberFormatException(String.format(
- "Color value '%s' is too long. Format is either" +
- "#AARRGGBB, #RRGGBB, #RGB, or #ARGB",
- value));
- }
-
- if (value.length() == 3) { // RGB format
- char[] color = new char[8];
- color[0] = color[1] = 'F';
- color[2] = color[3] = value.charAt(0);
- color[4] = color[5] = value.charAt(1);
- color[6] = color[7] = value.charAt(2);
- value = new String(color);
- } else if (value.length() == 4) { // ARGB format
- char[] color = new char[8];
- color[0] = color[1] = value.charAt(0);
- color[2] = color[3] = value.charAt(1);
- color[4] = color[5] = value.charAt(2);
- color[6] = color[7] = value.charAt(3);
- value = new String(color);
- } else if (value.length() == 6) {
- value = "FF" + value; //$NON-NLS-1$
- }
-
- // this is a RRGGBB or AARRGGBB value
-
- // Integer.parseInt will fail to parse strings like "ff191919", so we use
- // a Long, but cast the result back into an int, since we know that we're only
- // dealing with 32 bit values.
- return (int)Long.parseLong(value, 16);
- }
-
- throw new NumberFormatException();
- }
-
- /**
- * Resize the given image
- *
- * @param source the image to be scaled
- * @param xScale x scale
- * @param yScale y scale
- * @return the scaled image
- */
- public static BufferedImage scale(BufferedImage source, double xScale, double yScale) {
- return scale(source, xScale, yScale, 0, 0);
- }
-
- /**
- * Resize the given image
- *
- * @param source the image to be scaled
- * @param xScale x scale
- * @param yScale y scale
- * @param rightMargin extra margin to add on the right
- * @param bottomMargin extra margin to add on the bottom
- * @return the scaled image
- */
- public static BufferedImage scale(BufferedImage source, double xScale, double yScale,
- int rightMargin, int bottomMargin) {
- int sourceWidth = source.getWidth();
- int sourceHeight = source.getHeight();
- int destWidth = Math.max(1, (int) (xScale * sourceWidth));
- int destHeight = Math.max(1, (int) (yScale * sourceHeight));
- int imageType = source.getType();
- if (imageType == BufferedImage.TYPE_CUSTOM) {
- imageType = BufferedImage.TYPE_INT_ARGB;
- }
- if (xScale > 0.5 && yScale > 0.5) {
- BufferedImage scaled =
- new BufferedImage(destWidth + rightMargin, destHeight + bottomMargin, imageType);
- Graphics2D g2 = scaled.createGraphics();
- g2.setComposite(AlphaComposite.Src);
- g2.setColor(new Color(0, true));
- g2.fillRect(0, 0, destWidth + rightMargin, destHeight + bottomMargin);
- g2.setRenderingHint(KEY_INTERPOLATION, VALUE_INTERPOLATION_BILINEAR);
- g2.setRenderingHint(KEY_RENDERING, VALUE_RENDER_QUALITY);
- g2.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON);
- g2.drawImage(source, 0, 0, destWidth, destHeight, 0, 0, sourceWidth, sourceHeight,
- null);
- g2.dispose();
- return scaled;
- } else {
- // When creating a thumbnail, using the above code doesn't work very well;
- // you get some visible artifacts, especially for text. Instead use the
- // technique of repeatedly scaling the image into half; this will cause
- // proper averaging of neighboring pixels, and will typically (for the kinds
- // of screen sizes used by this utility method in the layout editor) take
- // about 3-4 iterations to get the result since we are logarithmically reducing
- // the size. Besides, each successive pass in operating on much fewer pixels
- // (a reduction of 4 in each pass).
- //
- // However, we may not be resizing to a size that can be reached exactly by
- // successively diving in half. Therefore, once we're within a factor of 2 of
- // the final size, we can do a resize to the exact target size.
- // However, we can get even better results if we perform this final resize
- // up front. Let's say we're going from width 1000 to a destination width of 85.
- // The first approach would cause a resize from 1000 to 500 to 250 to 125, and
- // then a resize from 125 to 85. That last resize can distort/blur a lot.
- // Instead, we can start with the destination width, 85, and double it
- // successfully until we're close to the initial size: 85, then 170,
- // then 340, and finally 680. (The next one, 1360, is larger than 1000).
- // So, now we *start* the thumbnail operation by resizing from width 1000 to
- // width 680, which will preserve a lot of visual details such as text.
- // Then we can successively resize the image in half, 680 to 340 to 170 to 85.
- // We end up with the expected final size, but we've been doing an exact
- // divide-in-half resizing operation at the end so there is less distortion.
-
-
- int iterations = 0; // Number of halving operations to perform after the initial resize
- int nearestWidth = destWidth; // Width closest to source width that = 2^x, x is integer
- int nearestHeight = destHeight;
- while (nearestWidth < sourceWidth / 2) {
- nearestWidth *= 2;
- nearestHeight *= 2;
- iterations++;
- }
-
- // If we're supposed to add in margins, we need to do it in the initial resizing
- // operation if we don't have any subsequent resizing operations.
- if (iterations == 0) {
- nearestWidth += rightMargin;
- nearestHeight += bottomMargin;
- }
-
- BufferedImage scaled = new BufferedImage(nearestWidth, nearestHeight, imageType);
- Graphics2D g2 = scaled.createGraphics();
- g2.setRenderingHint(KEY_INTERPOLATION, VALUE_INTERPOLATION_BILINEAR);
- g2.setRenderingHint(KEY_RENDERING, VALUE_RENDER_QUALITY);
- g2.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON);
- g2.drawImage(source, 0, 0, nearestWidth, nearestHeight,
- 0, 0, sourceWidth, sourceHeight, null);
- g2.dispose();
-
- sourceWidth = nearestWidth;
- sourceHeight = nearestHeight;
- source = scaled;
-
- for (int iteration = iterations - 1; iteration >= 0; iteration--) {
- int halfWidth = sourceWidth / 2;
- int halfHeight = sourceHeight / 2;
- if (iteration == 0) { // Last iteration: Add margins in final image
- scaled = new BufferedImage(halfWidth + rightMargin, halfHeight + bottomMargin,
- imageType);
- } else {
- scaled = new BufferedImage(halfWidth, halfHeight, imageType);
- }
- g2 = scaled.createGraphics();
- g2.setRenderingHint(KEY_INTERPOLATION,VALUE_INTERPOLATION_BILINEAR);
- g2.setRenderingHint(KEY_RENDERING, VALUE_RENDER_QUALITY);
- g2.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON);
- g2.drawImage(source, 0, 0,
- halfWidth, halfHeight, 0, 0,
- sourceWidth, sourceHeight,
- null);
- g2.dispose();
-
- sourceWidth = halfWidth;
- sourceHeight = halfHeight;
- source = scaled;
- iterations--;
- }
- return scaled;
- }
- }
-
- /**
- * Returns true if the given file path points to an image file recognized by
- * Android. See http://developer.android.com/guide/appendix/media-formats.html
- * for details.
- *
- * @param path the filename to be tested
- * @return true if the file represents an image file
- */
- public static boolean hasImageExtension(String path) {
- return endsWithIgnoreCase(path, DOT_PNG)
- || endsWithIgnoreCase(path, DOT_9PNG)
- || endsWithIgnoreCase(path, DOT_GIF)
- || endsWithIgnoreCase(path, DOT_JPG)
- || endsWithIgnoreCase(path, DOT_BMP);
- }
-
- /**
- * Creates a new image of the given size filled with the given color
- *
- * @param width the width of the image
- * @param height the height of the image
- * @param color the color of the image
- * @return a new image of the given size filled with the given color
- */
- public static BufferedImage createColoredImage(int width, int height, RGB color) {
- BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
- Graphics g = image.getGraphics();
- g.setColor(new Color(color.red, color.green, color.blue));
- g.fillRect(0, 0, image.getWidth(), image.getHeight());
- g.dispose();
- return image;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/IncludeFinder.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/IncludeFinder.java
deleted file mode 100644
index 7bab914e5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/IncludeFinder.java
+++ /dev/null
@@ -1,1111 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.SdkConstants.ATTR_LAYOUT;
-import static com.android.SdkConstants.EXT_XML;
-import static com.android.SdkConstants.FD_RESOURCES;
-import static com.android.SdkConstants.FD_RES_LAYOUT;
-import static com.android.SdkConstants.TOOLS_URI;
-import static com.android.SdkConstants.VIEW_FRAGMENT;
-import static com.android.SdkConstants.VIEW_INCLUDE;
-import static com.android.ide.eclipse.adt.AdtConstants.WS_LAYOUTS;
-import static com.android.ide.eclipse.adt.AdtConstants.WS_SEP;
-import static com.android.resources.ResourceType.LAYOUT;
-import static org.eclipse.core.resources.IResourceDelta.ADDED;
-import static org.eclipse.core.resources.IResourceDelta.CHANGED;
-import static org.eclipse.core.resources.IResourceDelta.CONTENT;
-import static org.eclipse.core.resources.IResourceDelta.REMOVED;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.annotations.VisibleForTesting;
-import com.android.ide.common.resources.ResourceFile;
-import com.android.ide.common.resources.ResourceFolder;
-import com.android.ide.common.resources.ResourceItem;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.resources.manager.ProjectResources;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager.IResourceListener;
-import com.android.ide.eclipse.adt.io.IFileWrapper;
-import com.android.io.IAbstractFile;
-import com.android.resources.ResourceType;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.QualifiedName;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.wst.sse.core.StructuredModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * The include finder finds other XML files that are including a given XML file, and does
- * so efficiently (caching results across IDE sessions etc).
- */
-@SuppressWarnings("restriction") // XML model
-public class IncludeFinder {
- /** Qualified name for the per-project persistent property include-map */
- private final static QualifiedName CONFIG_INCLUDES = new QualifiedName(AdtPlugin.PLUGIN_ID,
- "includes");//$NON-NLS-1$
-
- /**
- * Qualified name for the per-project non-persistent property storing the
- * {@link IncludeFinder} for this project
- */
- private final static QualifiedName INCLUDE_FINDER = new QualifiedName(AdtPlugin.PLUGIN_ID,
- "includefinder"); //$NON-NLS-1$
-
- /** Project that the include finder locates includes for */
- private final IProject mProject;
-
- /** Map from a layout resource name to a set of layouts included by the given resource */
- private Map<String, List<String>> mIncludes = null;
-
- /**
- * Reverse map of {@link #mIncludes}; points to other layouts that are including a
- * given layouts
- */
- private Map<String, List<String>> mIncludedBy = null;
-
- /** Flag set during a refresh; ignore updates when this is true */
- private static boolean sRefreshing;
-
- /** Global (cross-project) resource listener */
- private static ResourceListener sListener;
-
- /**
- * Constructs an {@link IncludeFinder} for the given project. Don't use this method;
- * use the {@link #get} factory method instead.
- *
- * @param project project to create an {@link IncludeFinder} for
- */
- private IncludeFinder(IProject project) {
- mProject = project;
- }
-
- /**
- * Returns the {@link IncludeFinder} for the given project
- *
- * @param project the project the finder is associated with
- * @return an {@link IncludeFinder} for the given project, never null
- */
- @NonNull
- public static IncludeFinder get(IProject project) {
- IncludeFinder finder = null;
- try {
- finder = (IncludeFinder) project.getSessionProperty(INCLUDE_FINDER);
- } catch (CoreException e) {
- // Not a problem; we will just create a new one
- }
-
- if (finder == null) {
- finder = new IncludeFinder(project);
- try {
- project.setSessionProperty(INCLUDE_FINDER, finder);
- } catch (CoreException e) {
- AdtPlugin.log(e, "Can't store IncludeFinder");
- }
- }
-
- return finder;
- }
-
- /**
- * Returns a list of resource names that are included by the given resource
- *
- * @param includer the resource name to return included layouts for
- * @return the layouts included by the given resource
- */
- private List<String> getIncludesFrom(String includer) {
- ensureInitialized();
-
- return mIncludes.get(includer);
- }
-
- /**
- * Gets the list of all other layouts that are including the given layout.
- *
- * @param included the file that is included
- * @return the files that are including the given file, or null or empty
- */
- @Nullable
- public List<Reference> getIncludedBy(IResource included) {
- ensureInitialized();
- String mapKey = getMapKey(included);
- List<String> result = mIncludedBy.get(mapKey);
- if (result == null) {
- String name = getResourceName(included);
- if (!name.equals(mapKey)) {
- result = mIncludedBy.get(name);
- }
- }
-
- if (result != null && result.size() > 0) {
- List<Reference> references = new ArrayList<Reference>(result.size());
- for (String s : result) {
- references.add(new Reference(mProject, s));
- }
- return references;
- } else {
- return null;
- }
- }
-
- /**
- * Returns true if the given resource is included from some other layout in the
- * project
- *
- * @param included the resource to check
- * @return true if the file is included by some other layout
- */
- public boolean isIncluded(IResource included) {
- ensureInitialized();
- String mapKey = getMapKey(included);
- List<String> result = mIncludedBy.get(mapKey);
- if (result == null) {
- String name = getResourceName(included);
- if (!name.equals(mapKey)) {
- result = mIncludedBy.get(name);
- }
- }
-
- return result != null && result.size() > 0;
- }
-
- @VisibleForTesting
- /* package */ List<String> getIncludedBy(String included) {
- ensureInitialized();
- return mIncludedBy.get(included);
- }
-
- /** Initialize the inclusion data structures, if not already done */
- private void ensureInitialized() {
- if (mIncludes == null) {
- // Initialize
- if (!readSettings()) {
- // Couldn't read settings: probably the first time this code is running
- // so there is no known data about includes.
-
- // Yes, these should be multimaps! If we start using Guava replace
- // these with multimaps.
- mIncludes = new HashMap<String, List<String>>();
- mIncludedBy = new HashMap<String, List<String>>();
-
- scanProject();
- saveSettings();
- }
- }
- }
-
- // ----- Persistence -----
-
- /**
- * Create a String serialization of the includes map. The map attempts to be compact;
- * it strips out the @layout/ prefix, and eliminates the values for empty string
- * values. The map can be restored by calling {@link #decodeMap}. The encoded String
- * will have sorted keys.
- *
- * @param map the map to be serialized
- * @return a serialization (never null) of the given map
- */
- @VisibleForTesting
- public static String encodeMap(Map<String, List<String>> map) {
- StringBuilder sb = new StringBuilder();
-
- if (map != null) {
- // Process the keys in sorted order rather than just
- // iterating over the entry set to ensure stable output
- List<String> keys = new ArrayList<String>(map.keySet());
- Collections.sort(keys);
- for (String key : keys) {
- List<String> values = map.get(key);
-
- if (sb.length() > 0) {
- sb.append(',');
- }
- sb.append(key);
- if (values.size() > 0) {
- sb.append('=').append('>');
- sb.append('{');
- boolean first = true;
- for (String value : values) {
- if (first) {
- first = false;
- } else {
- sb.append(',');
- }
- sb.append(value);
- }
- sb.append('}');
- }
- }
- }
-
- return sb.toString();
- }
-
- /**
- * Decodes the encoding (produced by {@link #encodeMap}) back into the original map,
- * modulo any key sorting differences.
- *
- * @param encoded an encoding of a map created by {@link #encodeMap}
- * @return a map corresponding to the encoded values, never null
- */
- @VisibleForTesting
- public static Map<String, List<String>> decodeMap(String encoded) {
- HashMap<String, List<String>> map = new HashMap<String, List<String>>();
-
- if (encoded.length() > 0) {
- int i = 0;
- int end = encoded.length();
-
- while (i < end) {
-
- // Find key range
- int keyBegin = i;
- int keyEnd = i;
- while (i < end) {
- char c = encoded.charAt(i);
- if (c == ',') {
- break;
- } else if (c == '=') {
- i += 2; // Skip =>
- break;
- }
- i++;
- keyEnd = i;
- }
-
- List<String> values = new ArrayList<String>();
- // Find values
- if (i < end && encoded.charAt(i) == '{') {
- i++;
- while (i < end) {
- int valueBegin = i;
- int valueEnd = i;
- char c = 0;
- while (i < end) {
- c = encoded.charAt(i);
- if (c == ',' || c == '}') {
- valueEnd = i;
- break;
- }
- i++;
- }
- if (valueEnd > valueBegin) {
- values.add(encoded.substring(valueBegin, valueEnd));
- }
-
- if (c == '}') {
- if (i < end-1 && encoded.charAt(i+1) == ',') {
- i++;
- }
- break;
- }
- assert c == ',';
- i++;
- }
- }
-
- String key = encoded.substring(keyBegin, keyEnd);
- map.put(key, values);
- i++;
- }
- }
-
- return map;
- }
-
- /**
- * Stores the settings in the persistent project storage.
- */
- private void saveSettings() {
- // Serialize the mIncludes map into a compact String. The mIncludedBy map can be
- // inferred from it.
- String encoded = encodeMap(mIncludes);
-
- try {
- if (encoded.length() >= 2048) {
- // The maximum length of a setting key is 2KB, according to the javadoc
- // for the project class. It's unlikely that we'll
- // hit this -- even with an average layout root name of 20 characters
- // we can still store over a hundred names. But JUST IN CASE we run
- // into this, we'll clear out the key in this name which means that the
- // information will need to be recomputed in the next IDE session.
- mProject.setPersistentProperty(CONFIG_INCLUDES, null);
- } else {
- String existing = mProject.getPersistentProperty(CONFIG_INCLUDES);
- if (!encoded.equals(existing)) {
- mProject.setPersistentProperty(CONFIG_INCLUDES, encoded);
- }
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, "Can't store include settings");
- }
- }
-
- /**
- * Reads previously stored settings from the persistent project storage
- *
- * @return true iff settings were restored from the project
- */
- private boolean readSettings() {
- try {
- String encoded = mProject.getPersistentProperty(CONFIG_INCLUDES);
- if (encoded != null) {
- mIncludes = decodeMap(encoded);
-
- // Set up a reverse map, pointing from included files to the files that
- // included them
- mIncludedBy = new HashMap<String, List<String>>(2 * mIncludes.size());
- for (Map.Entry<String, List<String>> entry : mIncludes.entrySet()) {
- // File containing the <include>
- String includer = entry.getKey();
- // Files being <include>'ed by the above file
- List<String> included = entry.getValue();
- setIncludedBy(includer, included);
- }
-
- return true;
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, "Can't read include settings");
- }
-
- return false;
- }
-
- // ----- File scanning -----
-
- /**
- * Scan the whole project for XML layout resources that are performing includes.
- */
- private void scanProject() {
- ProjectResources resources = ResourceManager.getInstance().getProjectResources(mProject);
- if (resources != null) {
- Collection<ResourceItem> layouts = resources.getResourceItemsOfType(LAYOUT);
- for (ResourceItem layout : layouts) {
- List<ResourceFile> sources = layout.getSourceFileList();
- for (ResourceFile source : sources) {
- updateFileIncludes(source, false);
- }
- }
-
- return;
- }
- }
-
- /**
- * Scans the given {@link ResourceFile} and if it is a layout resource, updates the
- * includes in it.
- *
- * @param resourceFile the {@link ResourceFile} to be scanned for includes (doesn't
- * have to be only layout XML files; this method will filter the type)
- * @param singleUpdate true if this is a single file being updated, false otherwise
- * (e.g. during initial project scanning)
- * @return true if we updated the includes for the resource file
- */
- private boolean updateFileIncludes(ResourceFile resourceFile, boolean singleUpdate) {
- Collection<ResourceType> resourceTypes = resourceFile.getResourceTypes();
- for (ResourceType type : resourceTypes) {
- if (type == ResourceType.LAYOUT) {
- ensureInitialized();
-
- List<String> includes = Collections.emptyList();
- if (resourceFile.getFile() instanceof IFileWrapper) {
- IFile file = ((IFileWrapper) resourceFile.getFile()).getIFile();
-
- // See if we have an existing XML model for this file; if so, we can
- // just look directly at the parse tree
- boolean hadXmlModel = false;
- IStructuredModel model = null;
- try {
- IModelManager modelManager = StructuredModelManager.getModelManager();
- model = modelManager.getExistingModelForRead(file);
- if (model instanceof IDOMModel) {
- IDOMModel domModel = (IDOMModel) model;
- Document document = domModel.getDocument();
- includes = findIncludesInDocument(document);
- hadXmlModel = true;
- }
- } finally {
- if (model != null) {
- model.releaseFromRead();
- }
- }
-
- // If no XML model we have to read the XML contents and (possibly) parse it.
- // The actual file may not exist anymore (e.g. when deleting a layout file
- // or when the workspace is out of sync.)
- if (!hadXmlModel) {
- String xml = AdtPlugin.readFile(file);
- if (xml != null) {
- includes = findIncludes(xml);
- }
- }
- } else {
- String xml = AdtPlugin.readFile(resourceFile);
- if (xml != null) {
- includes = findIncludes(xml);
- }
- }
-
- String key = getMapKey(resourceFile);
- if (includes.equals(getIncludesFrom(key))) {
- // Common case -- so avoid doing settings flush etc
- return false;
- }
-
- boolean detectCycles = singleUpdate;
- setIncluded(key, includes, detectCycles);
-
- if (singleUpdate) {
- saveSettings();
- }
-
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Finds the list of includes in the given XML content. It attempts quickly return
- * empty if the file does not include any include tags; it does this by only parsing
- * if it detects the string &lt;include in the file.
- */
- @VisibleForTesting
- @NonNull
- static List<String> findIncludes(@NonNull String xml) {
- int index = xml.indexOf(ATTR_LAYOUT);
- if (index != -1) {
- return findIncludesInXml(xml);
- }
-
- return Collections.emptyList();
- }
-
- /**
- * Parses the given XML content and extracts all the included URLs and returns them
- *
- * @param xml layout XML content to be parsed for includes
- * @return a list of included urls, or null
- */
- @VisibleForTesting
- @NonNull
- static List<String> findIncludesInXml(@NonNull String xml) {
- Document document = DomUtilities.parseDocument(xml, false /*logParserErrors*/);
- if (document != null) {
- return findIncludesInDocument(document);
- }
-
- return Collections.emptyList();
- }
-
- /** Searches the given DOM document and returns the list of includes, if any */
- @NonNull
- private static List<String> findIncludesInDocument(@NonNull Document document) {
- List<String> includes = findIncludesInDocument(document, null);
- if (includes == null) {
- includes = Collections.emptyList();
- }
- return includes;
- }
-
- @Nullable
- private static List<String> findIncludesInDocument(@NonNull Node node,
- @Nullable List<String> urls) {
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- String tag = node.getNodeName();
- boolean isInclude = tag.equals(VIEW_INCLUDE);
- boolean isFragment = tag.equals(VIEW_FRAGMENT);
- if (isInclude || isFragment) {
- Element element = (Element) node;
- String url;
- if (isInclude) {
- url = element.getAttribute(ATTR_LAYOUT);
- } else {
- url = element.getAttributeNS(TOOLS_URI, ATTR_LAYOUT);
- }
- if (url.length() > 0) {
- String resourceName = urlToLocalResource(url);
- if (resourceName != null) {
- if (urls == null) {
- urls = new ArrayList<String>();
- }
- urls.add(resourceName);
- }
- }
-
- }
- }
-
- NodeList children = node.getChildNodes();
- for (int i = 0, n = children.getLength(); i < n; i++) {
- urls = findIncludesInDocument(children.item(i), urls);
- }
-
- return urls;
- }
-
-
- /**
- * Returns the layout URL to a local resource name (provided the URL is a local
- * resource, not something in @android etc.) Returns null otherwise.
- */
- private static String urlToLocalResource(String url) {
- if (!url.startsWith("@")) { //$NON-NLS-1$
- return null;
- }
- int typeEnd = url.indexOf('/', 1);
- if (typeEnd == -1) {
- return null;
- }
- int nameBegin = typeEnd + 1;
- int typeBegin = 1;
- int colon = url.lastIndexOf(':', typeEnd);
- if (colon != -1) {
- String packageName = url.substring(typeBegin, colon);
- if ("android".equals(packageName)) { //$NON-NLS-1$
- // Don't want to point to non-local resources
- return null;
- }
-
- typeBegin = colon + 1;
- assert "layout".equals(url.substring(typeBegin, typeEnd)); //$NON-NLS-1$
- }
-
- return url.substring(nameBegin);
- }
-
- /**
- * Record the list of included layouts from the given layout
- *
- * @param includer the layout including other layouts
- * @param included the layouts that were included by the including layout
- * @param detectCycles if true, check for cycles and report them as project errors
- */
- @VisibleForTesting
- /* package */ void setIncluded(String includer, List<String> included, boolean detectCycles) {
- // Remove previously linked inverse mappings
- List<String> oldIncludes = mIncludes.get(includer);
- if (oldIncludes != null && oldIncludes.size() > 0) {
- for (String includee : oldIncludes) {
- List<String> includers = mIncludedBy.get(includee);
- if (includers != null) {
- includers.remove(includer);
- }
- }
- }
-
- mIncludes.put(includer, included);
- // Reverse mapping: for included items, point back to including file
- setIncludedBy(includer, included);
-
- if (detectCycles) {
- detectCycles(includer);
- }
- }
-
- /** Record the list of included layouts from the given layout */
- private void setIncludedBy(String includer, List<String> included) {
- for (String target : included) {
- List<String> list = mIncludedBy.get(target);
- if (list == null) {
- list = new ArrayList<String>(2); // We don't expect many includes
- mIncludedBy.put(target, list);
- }
- if (!list.contains(includer)) {
- list.add(includer);
- }
- }
- }
-
- /** Start listening on project resources */
- public static void start() {
- assert sListener == null;
- sListener = new ResourceListener();
- ResourceManager.getInstance().addListener(sListener);
- }
-
- /** Stop listening on project resources */
- public static void stop() {
- assert sListener != null;
- ResourceManager.getInstance().addListener(sListener);
- }
-
- private static String getMapKey(ResourceFile resourceFile) {
- IAbstractFile file = resourceFile.getFile();
- String name = file.getName();
- String folderName = file.getParentFolder().getName();
- return getMapKey(folderName, name);
- }
-
- private static String getMapKey(IResource resourceFile) {
- String folderName = resourceFile.getParent().getName();
- String name = resourceFile.getName();
- return getMapKey(folderName, name);
- }
-
- private static String getResourceName(IResource resourceFile) {
- String name = resourceFile.getName();
- int baseEnd = name.length() - EXT_XML.length() - 1; // -1: the dot
- if (baseEnd > 0) {
- name = name.substring(0, baseEnd);
- }
-
- return name;
- }
-
- private static String getMapKey(String folderName, String name) {
- int baseEnd = name.length() - EXT_XML.length() - 1; // -1: the dot
- if (baseEnd > 0) {
- name = name.substring(0, baseEnd);
- }
-
- // Create a map key for the given resource file
- // This will map
- // /res/layout/foo.xml => "foo"
- // /res/layout-land/foo.xml => "-land/foo"
-
- if (FD_RES_LAYOUT.equals(folderName)) {
- // Normal case -- keep just the basename
- return name;
- } else {
- // Store the relative path from res/ on down, so
- // /res/layout-land/foo.xml becomes "layout-land/foo"
- //if (folderName.startsWith(FD_LAYOUT)) {
- // folderName = folderName.substring(FD_LAYOUT.length());
- //}
-
- return folderName + WS_SEP + name;
- }
- }
-
- /** Listener of resource file saves, used to update layout inclusion data structures */
- private static class ResourceListener implements IResourceListener {
- @Override
- public void fileChanged(IProject project, ResourceFile file, int eventType) {
- if (sRefreshing) {
- return;
- }
-
- if ((eventType & (CHANGED | ADDED | REMOVED | CONTENT)) == 0) {
- return;
- }
-
- IncludeFinder finder = get(project);
- if (finder != null) {
- if (finder.updateFileIncludes(file, true)) {
- finder.saveSettings();
- }
- }
- }
-
- @Override
- public void folderChanged(IProject project, ResourceFolder folder, int eventType) {
- // We only care about layout resource files
- }
- }
-
- // ----- Cycle detection -----
-
- private void detectCycles(String from) {
- // Perform DFS on the include graph and look for a cycle; if we find one, produce
- // a chain of includes on the way back to show to the user
- if (mIncludes.size() > 0) {
- Set<String> visiting = new HashSet<String>(mIncludes.size());
- String chain = dfs(from, visiting);
- if (chain != null) {
- addError(from, chain);
- } else {
- // Is there an existing error for us to clean up?
- removeErrors(from);
- }
- }
- }
-
- /** Format to chain include cycles in: a=>b=>c=>d etc */
- private final String CHAIN_FORMAT = "%1$s=>%2$s"; //$NON-NLS-1$
-
- private String dfs(String from, Set<String> visiting) {
- visiting.add(from);
-
- List<String> includes = mIncludes.get(from);
- if (includes != null && includes.size() > 0) {
- for (String include : includes) {
- if (visiting.contains(include)) {
- return String.format(CHAIN_FORMAT, from, include);
- }
- String chain = dfs(include, visiting);
- if (chain != null) {
- return String.format(CHAIN_FORMAT, from, chain);
- }
- }
- }
-
- visiting.remove(from);
-
- return null;
- }
-
- private void removeErrors(String from) {
- final IResource resource = findResource(from);
- if (resource != null) {
- try {
- final String markerId = IMarker.PROBLEM;
-
- IMarker[] markers = resource.findMarkers(markerId, true, IResource.DEPTH_ZERO);
-
- for (final IMarker marker : markers) {
- String tmpMsg = marker.getAttribute(IMarker.MESSAGE, null);
- if (tmpMsg == null || tmpMsg.startsWith(MESSAGE)) {
- // Remove
- runLater(new Runnable() {
- @Override
- public void run() {
- try {
- sRefreshing = true;
- marker.delete();
- } catch (CoreException e) {
- AdtPlugin.log(e, "Can't delete problem marker");
- } finally {
- sRefreshing = false;
- }
- }
- });
- }
- }
- } catch (CoreException e) {
- // if we couldn't get the markers, then we just mark the file again
- // (since markerAlreadyExists is initialized to false, we do nothing)
- }
- }
- }
-
- /** Error message for cycles */
- private static final String MESSAGE = "Found cyclical <include> chain";
-
- private void addError(String from, String chain) {
- final IResource resource = findResource(from);
- if (resource != null) {
- final String markerId = IMarker.PROBLEM;
- final String message = String.format("%1$s: %2$s", MESSAGE, chain);
- final int lineNumber = 1;
- final int severity = IMarker.SEVERITY_ERROR;
-
- // check if there's a similar marker already, since aapt is launched twice
- boolean markerAlreadyExists = false;
- try {
- IMarker[] markers = resource.findMarkers(markerId, true, IResource.DEPTH_ZERO);
-
- for (IMarker marker : markers) {
- int tmpLine = marker.getAttribute(IMarker.LINE_NUMBER, -1);
- if (tmpLine != lineNumber) {
- break;
- }
-
- int tmpSeverity = marker.getAttribute(IMarker.SEVERITY, -1);
- if (tmpSeverity != severity) {
- break;
- }
-
- String tmpMsg = marker.getAttribute(IMarker.MESSAGE, null);
- if (tmpMsg == null || tmpMsg.equals(message) == false) {
- break;
- }
-
- // if we're here, all the marker attributes are equals, we found it
- // and exit
- markerAlreadyExists = true;
- break;
- }
-
- } catch (CoreException e) {
- // if we couldn't get the markers, then we just mark the file again
- // (since markerAlreadyExists is initialized to false, we do nothing)
- }
-
- if (!markerAlreadyExists) {
- runLater(new Runnable() {
- @Override
- public void run() {
- try {
- sRefreshing = true;
-
- // Adding a resource will force a refresh on the file;
- // ignore these updates
- BaseProjectHelper.markResource(resource, markerId, message, lineNumber,
- severity);
- } finally {
- sRefreshing = false;
- }
- }
- });
- }
- }
- }
-
- // FIXME: Find more standard Eclipse way to do this.
- // We need to run marker registration/deletion "later", because when the include
- // scanning is running it's in the middle of resource notification, so the IDE
- // throws an exception
- private static void runLater(Runnable runnable) {
- Display display = Display.findDisplay(Thread.currentThread());
- if (display != null) {
- display.asyncExec(runnable);
- } else {
- AdtPlugin.log(IStatus.WARNING, "Could not find display");
- }
- }
-
- /**
- * Finds the project resource for the given layout path
- *
- * @param from the resource name
- * @return the {@link IResource}, or null if not found
- */
- private IResource findResource(String from) {
- final IResource resource = mProject.findMember(WS_LAYOUTS + WS_SEP + from + '.' + EXT_XML);
- return resource;
- }
-
- /**
- * Creates a blank, project-less {@link IncludeFinder} <b>for use by unit tests
- * only</b>
- */
- @VisibleForTesting
- /* package */ static IncludeFinder create() {
- IncludeFinder finder = new IncludeFinder(null);
- finder.mIncludes = new HashMap<String, List<String>>();
- finder.mIncludedBy = new HashMap<String, List<String>>();
- return finder;
- }
-
- /** A reference to a particular file in the project */
- public static class Reference {
- /** The unique id referencing the file, such as (for res/layout-land/main.xml)
- * "layout-land/main") */
- private final String mId;
-
- /** The project containing the file */
- private final IProject mProject;
-
- /** The resource name of the file, such as (for res/layout/main.xml) "main" */
- private String mName;
-
- /** Creates a new include reference */
- private Reference(IProject project, String id) {
- super();
- mProject = project;
- mId = id;
- }
-
- /**
- * Returns the id identifying the given file within the project
- *
- * @return the id identifying the given file within the project
- */
- public String getId() {
- return mId;
- }
-
- /**
- * Returns the {@link IFile} in the project for the given file. May return null if
- * there is an error in locating the file or if the file no longer exists.
- *
- * @return the project file, or null
- */
- public IFile getFile() {
- String reference = mId;
- if (!reference.contains(WS_SEP)) {
- reference = FD_RES_LAYOUT + WS_SEP + reference;
- }
-
- String projectPath = FD_RESOURCES + WS_SEP + reference + '.' + EXT_XML;
- IResource member = mProject.findMember(projectPath);
- if (member instanceof IFile) {
- return (IFile) member;
- }
-
- return null;
- }
-
- /**
- * Returns a description of this reference, suitable to be shown to the user
- *
- * @return a display name for the reference
- */
- public String getDisplayName() {
- // The ID is deliberately kept in a pretty user-readable format but we could
- // consider prepending layout/ on ids that don't have it (to make the display
- // more uniform) or ripping out all layout[-constraint] prefixes out and
- // instead prepending @ etc.
- return mId;
- }
-
- /**
- * Returns the name of the reference, suitable for resource lookup. For example,
- * for "res/layout/main.xml", as well as for "res/layout-land/main.xml", this
- * would be "main".
- *
- * @return the resource name of the reference
- */
- public String getName() {
- if (mName == null) {
- mName = mId;
- int index = mName.lastIndexOf(WS_SEP);
- if (index != -1) {
- mName = mName.substring(index + 1);
- }
- }
-
- return mName;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((mId == null) ? 0 : mId.hashCode());
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- Reference other = (Reference) obj;
- if (mId == null) {
- if (other.mId != null)
- return false;
- } else if (!mId.equals(other.mId))
- return false;
- return true;
- }
-
- @Override
- public String toString() {
- return "Reference [getId()=" + getId() //$NON-NLS-1$
- + ", getDisplayName()=" + getDisplayName() //$NON-NLS-1$
- + ", getName()=" + getName() //$NON-NLS-1$
- + ", getFile()=" + getFile() + "]"; //$NON-NLS-1$
- }
-
- /**
- * Creates a reference to the given file
- *
- * @param file the file to create a reference for
- * @return a reference to the given file
- */
- public static Reference create(IFile file) {
- return new Reference(file.getProject(), getMapKey(file));
- }
-
- /**
- * Returns the resource name of this layout, such as {@code @layout/foo}.
- *
- * @return the resource name
- */
- public String getResourceName() {
- return '@' + FD_RES_LAYOUT + '/' + getName();
- }
- }
-
- /**
- * Returns a collection of layouts (expressed as resource names, such as
- * {@code @layout/foo} which would be invalid includes in the given layout
- * (because it would introduce a cycle)
- *
- * @param layout the layout file to check for cyclic dependencies from
- * @return a collection of layout resources which cannot be included from
- * the given layout, never null
- */
- public Collection<String> getInvalidIncludes(IFile layout) {
- IProject project = layout.getProject();
- Reference self = Reference.create(layout);
-
- // Add anyone who transitively can reach this file via includes.
- LinkedList<Reference> queue = new LinkedList<Reference>();
- List<Reference> invalid = new ArrayList<Reference>();
- queue.add(self);
- invalid.add(self);
- Set<String> seen = new HashSet<String>();
- seen.add(self.getId());
- while (!queue.isEmpty()) {
- Reference reference = queue.removeFirst();
- String refId = reference.getId();
-
- // Look up both configuration specific includes as well as includes in the
- // base versions
- List<String> included = getIncludedBy(refId);
- if (refId.indexOf('/') != -1) {
- List<String> baseIncluded = getIncludedBy(reference.getName());
- if (included == null) {
- included = baseIncluded;
- } else if (baseIncluded != null) {
- included = new ArrayList<String>(included);
- included.addAll(baseIncluded);
- }
- }
-
- if (included != null && included.size() > 0) {
- for (String id : included) {
- if (!seen.contains(id)) {
- seen.add(id);
- Reference ref = new Reference(project, id);
- invalid.add(ref);
- queue.addLast(ref);
- }
- }
- }
- }
-
- List<String> result = new ArrayList<String>();
- for (Reference reference : invalid) {
- result.add(reference.getResourceName());
- }
-
- return result;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/IncludeOverlay.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/IncludeOverlay.java
deleted file mode 100644
index 81c03edd5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/IncludeOverlay.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.annotations.VisibleForTesting;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Rectangle;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-/**
- * The {@link IncludeOverlay} class renders masks to -partially- hide everything outside
- * an included file's own content. This overlay is in use when you are editing an included
- * file shown within a different file's context (e.g. "Show In > other").
- */
-public class IncludeOverlay extends Overlay {
- /** Mask transparency - 0 is transparent, 255 is opaque */
- private static final int MASK_TRANSPARENCY = 160;
-
- /** The associated {@link LayoutCanvas}. */
- private LayoutCanvas mCanvas;
-
- /**
- * Constructs an {@link IncludeOverlay} tied to the given canvas.
- *
- * @param canvas The {@link LayoutCanvas} to paint the overlay over.
- */
- public IncludeOverlay(LayoutCanvas canvas) {
- mCanvas = canvas;
- }
-
- @Override
- public void paint(GC gc) {
- ViewHierarchy viewHierarchy = mCanvas.getViewHierarchy();
- List<Rectangle> includedBounds = viewHierarchy.getIncludedBounds();
- if (includedBounds == null || includedBounds.size() == 0) {
- // We don't support multiple included children yet. When that works,
- // this code should use a BSP tree to figure out which regions to paint
- // to leave holes in the mask.
- return;
- }
-
- Image image = mCanvas.getImageOverlay().getImage();
- if (image == null) {
- return;
- }
-
- int oldAlpha = gc.getAlpha();
- gc.setAlpha(MASK_TRANSPARENCY);
- Color bg = gc.getDevice().getSystemColor(SWT.COLOR_WIDGET_BACKGROUND);
- gc.setBackground(bg);
-
- CanvasViewInfo root = viewHierarchy.getRoot();
- Rectangle whole = root.getAbsRect();
- whole = new Rectangle(whole.x, whole.y, whole.width + 1, whole.height + 1);
- Collection<Rectangle> masks = subtractRectangles(whole, includedBounds);
-
- for (Rectangle mask : masks) {
- ControlPoint topLeft = LayoutPoint.create(mCanvas, mask.x, mask.y).toControl();
- ControlPoint bottomRight = LayoutPoint.create(mCanvas, mask.x + mask.width,
- mask.y + mask.height).toControl();
- int x1 = topLeft.x;
- int y1 = topLeft.y;
- int x2 = bottomRight.x;
- int y2 = bottomRight.y;
-
- gc.fillRectangle(x1, y1, x2 - x1, y2 - y1);
- }
-
- gc.setAlpha(oldAlpha);
- }
-
- /**
- * Given a Rectangle, remove holes from it (specified as a collection of Rectangles) such
- * that the result is a list of rectangles that cover everything that is not a hole.
- *
- * @param rectangle the rectangle to subtract from
- * @param holes the holes to subtract from the rectangle
- * @return a list of sub rectangles that remain after subtracting out the given list of holes
- */
- @VisibleForTesting
- static Collection<Rectangle> subtractRectangles(
- Rectangle rectangle, Collection<Rectangle> holes) {
- List<Rectangle> result = new ArrayList<Rectangle>();
- result.add(rectangle);
-
- for (Rectangle hole : holes) {
- List<Rectangle> tempResult = new ArrayList<Rectangle>();
- for (Rectangle r : result) {
- if (hole.intersects(r)) {
- // Clip the hole to fit the rectangle bounds
- Rectangle h = hole.intersection(r);
-
- // Split the rectangle
-
- // Above (includes the NW and NE corners)
- if (h.y > r.y) {
- tempResult.add(new Rectangle(r.x, r.y, r.width, h.y - r.y));
- }
-
- // Left (not including corners)
- if (h.x > r.x) {
- tempResult.add(new Rectangle(r.x, h.y, h.x - r.x, h.height));
- }
-
- int hx2 = h.x + h.width;
- int hy2 = h.y + h.height;
- int rx2 = r.x + r.width;
- int ry2 = r.y + r.height;
-
- // Below (includes the SW and SE corners)
- if (hy2 < ry2) {
- tempResult.add(new Rectangle(r.x, hy2, r.width, ry2 - hy2));
- }
-
- // Right (not including corners)
- if (hx2 < rx2) {
- tempResult.add(new Rectangle(hx2, h.y, rx2 - hx2, h.height));
- }
- } else {
- tempResult.add(r);
- }
- }
-
- result = tempResult;
- }
-
- return result;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutActionBar.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutActionBar.java
deleted file mode 100644
index 1b1bd23c4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutActionBar.java
+++ /dev/null
@@ -1,732 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_ID;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.RuleAction;
-import com.android.ide.common.api.RuleAction.Choices;
-import com.android.ide.common.api.RuleAction.Separator;
-import com.android.ide.common.api.RuleAction.Toggle;
-import com.android.ide.common.layout.BaseViewRule;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.Configuration;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigurationChooser;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.NodeProxy;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.RulesEngine;
-import com.android.ide.eclipse.adt.internal.lint.EclipseLintClient;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.sdklib.devices.Device;
-import com.android.sdklib.devices.Screen;
-import com.android.sdkuilib.internal.widgets.ResolutionChooserDialog;
-import com.google.common.base.Strings;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MenuItem;
-import org.eclipse.swt.widgets.ToolBar;
-import org.eclipse.swt.widgets.ToolItem;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * Toolbar shown at the top of the layout editor, which adds a number of context-sensitive
- * layout actions (as well as zooming controls on the right).
- */
-public class LayoutActionBar extends Composite {
- private GraphicalEditorPart mEditor;
- private ToolBar mLayoutToolBar;
- private ToolBar mLintToolBar;
- private ToolBar mZoomToolBar;
- private ToolItem mZoomRealSizeButton;
- private ToolItem mZoomOutButton;
- private ToolItem mZoomResetButton;
- private ToolItem mZoomInButton;
- private ToolItem mZoomFitButton;
- private ToolItem mLintButton;
- private List<RuleAction> mPrevActions;
-
- /**
- * Creates a new {@link LayoutActionBar} and adds it to the given parent.
- *
- * @param parent the parent composite to add the actions bar to
- * @param style the SWT style to apply
- * @param editor the associated layout editor
- */
- public LayoutActionBar(Composite parent, int style, GraphicalEditorPart editor) {
- super(parent, style | SWT.NO_FOCUS);
- mEditor = editor;
-
- GridLayout layout = new GridLayout(3, false);
- setLayout(layout);
-
- mLayoutToolBar = new ToolBar(this, /*SWT.WRAP |*/ SWT.FLAT | SWT.RIGHT | SWT.HORIZONTAL);
- mLayoutToolBar.setLayoutData(new GridData(SWT.FILL, SWT.BEGINNING, true, false));
- mZoomToolBar = createZoomControls();
- mZoomToolBar.setLayoutData(new GridData(SWT.END, SWT.BEGINNING, false, false));
- mLintToolBar = createLintControls();
-
- GridData lintData = new GridData(SWT.END, SWT.BEGINNING, false, false);
- lintData.exclude = true;
- mLintToolBar.setLayoutData(lintData);
- }
-
- @Override
- public void dispose() {
- super.dispose();
- mPrevActions = null;
- }
-
- /** Updates the layout contents based on the current selection */
- void updateSelection() {
- NodeProxy parent = null;
- LayoutCanvas canvas = mEditor.getCanvasControl();
- SelectionManager selectionManager = canvas.getSelectionManager();
- List<SelectionItem> selections = selectionManager.getSelections();
- if (selections.size() > 0) {
- // TODO: better handle multi-selection -- maybe we should disable it or
- // something.
- // What if you select children with different parents? Of different types?
- // etc.
- NodeProxy node = selections.get(0).getNode();
- if (node != null && node.getParent() != null) {
- parent = (NodeProxy) node.getParent();
- }
- }
-
- if (parent == null) {
- // Show the background's properties
- CanvasViewInfo root = canvas.getViewHierarchy().getRoot();
- if (root == null) {
- return;
- }
- parent = canvas.getNodeFactory().create(root);
- selections = Collections.emptyList();
- }
-
- RulesEngine engine = mEditor.getRulesEngine();
- List<NodeProxy> selectedNodes = new ArrayList<NodeProxy>();
- for (SelectionItem item : selections) {
- selectedNodes.add(item.getNode());
- }
- List<RuleAction> actions = new ArrayList<RuleAction>();
- engine.callAddLayoutActions(actions, parent, selectedNodes);
-
- // Place actions in the correct order (the actions may come from different
- // rules and should be merged properly via sorting keys)
- Collections.sort(actions);
-
- // Add in actions for the child as well, if there is exactly one.
- // These are not merged into the parent list of actions; they are appended
- // at the end.
- int index = -1;
- String label = null;
- if (selectedNodes.size() == 1) {
- List<RuleAction> itemActions = new ArrayList<RuleAction>();
- NodeProxy selectedNode = selectedNodes.get(0);
- engine.callAddLayoutActions(itemActions, selectedNode, null);
- if (itemActions.size() > 0) {
- Collections.sort(itemActions);
-
- if (!(itemActions.get(0) instanceof RuleAction.Separator)) {
- actions.add(RuleAction.createSeparator(0));
- }
- label = selectedNode.getStringAttr(ANDROID_URI, ATTR_ID);
- if (label != null) {
- label = BaseViewRule.stripIdPrefix(label);
- index = actions.size();
- }
- actions.addAll(itemActions);
- }
- }
-
- if (!updateActions(actions)) {
- updateToolbar(actions, index, label);
- }
- mPrevActions = actions;
- }
-
- /** Update the toolbar widgets */
- private void updateToolbar(final List<RuleAction> actions, final int labelIndex,
- final String label) {
- if (mLayoutToolBar == null || mLayoutToolBar.isDisposed()) {
- return;
- }
- for (ToolItem c : mLayoutToolBar.getItems()) {
- c.dispose();
- }
- mLayoutToolBar.pack();
- addActions(actions, labelIndex, label);
- mLayoutToolBar.pack();
- mLayoutToolBar.layout();
- }
-
- /**
- * Attempts to update the existing toolbar actions, if the action list is
- * similar to the current list. Returns false if this cannot be done and the
- * contents must be replaced.
- */
- private boolean updateActions(@NonNull List<RuleAction> actions) {
- List<RuleAction> before = mPrevActions;
- List<RuleAction> after = actions;
-
- if (before == null) {
- return false;
- }
-
- if (!before.equals(after) || after.size() > mLayoutToolBar.getItemCount()) {
- return false;
- }
-
- int actionIndex = 0;
- for (int i = 0, max = mLayoutToolBar.getItemCount(); i < max; i++) {
- ToolItem item = mLayoutToolBar.getItem(i);
- int style = item.getStyle();
- Object data = item.getData();
- if (data != null) {
- // One action can result in multiple toolbar items (e.g. a choice action
- // can result in multiple radio buttons), so we've have to replace all of
- // them with the corresponding new action
- RuleAction prevAction = before.get(actionIndex);
- while (prevAction != data) {
- actionIndex++;
- if (actionIndex == before.size()) {
- return false;
- }
- prevAction = before.get(actionIndex);
- if (prevAction == data) {
- break;
- } else if (!(prevAction instanceof RuleAction.Separator)) {
- return false;
- }
- }
- RuleAction newAction = after.get(actionIndex);
- assert newAction.equals(prevAction); // Maybe I can do this lazily instead?
-
- // Update action binding to the new action
- item.setData(newAction);
-
- // Sync button states: the checked state is not considered part of
- // RuleAction equality
- if ((style & SWT.CHECK) != 0) {
- assert newAction instanceof Toggle;
- Toggle toggle = (Toggle) newAction;
- item.setSelection(toggle.isChecked());
- } else if ((style & SWT.RADIO) != 0) {
- assert newAction instanceof Choices;
- Choices choices = (Choices) newAction;
- String current = choices.getCurrent();
- String id = (String) item.getData(ATTR_ID);
- boolean selected = Strings.nullToEmpty(current).equals(id);
- item.setSelection(selected);
- }
- } else {
- // Must be a separator, or a label (which we insert for nested widgets)
- assert (style & SWT.SEPARATOR) != 0 || !item.getText().isEmpty() : item;
- }
- }
-
- return true;
- }
-
- private void addActions(List<RuleAction> actions, int labelIndex, String label) {
- if (actions.size() > 0) {
- // Flag used to indicate that if there are any actions -after- this, it
- // should be separated from this current action (we don't unconditionally
- // add a separator at the end of these groups in case there are no more
- // actions at the end so that we don't have a trailing separator)
- boolean needSeparator = false;
-
- int index = 0;
- for (RuleAction action : actions) {
- if (index == labelIndex) {
- final ToolItem button = new ToolItem(mLayoutToolBar, SWT.PUSH);
- button.setText(label);
- needSeparator = false;
- }
- index++;
-
- if (action instanceof Separator) {
- addSeparator(mLayoutToolBar);
- needSeparator = false;
- continue;
- } else if (needSeparator) {
- addSeparator(mLayoutToolBar);
- needSeparator = false;
- }
-
- if (action instanceof RuleAction.Choices) {
- RuleAction.Choices choices = (Choices) action;
- if (!choices.isRadio()) {
- addDropdown(choices);
- } else {
- addSeparator(mLayoutToolBar);
- addRadio(choices);
- needSeparator = true;
- }
- } else if (action instanceof RuleAction.Toggle) {
- addToggle((Toggle) action);
- } else {
- addPlainAction(action);
- }
- }
- }
- }
-
- /** Add a separator to the toolbar, unless there already is one there at the end already */
- private static void addSeparator(ToolBar toolBar) {
- int n = toolBar.getItemCount();
- if (n > 0 && (toolBar.getItem(n - 1).getStyle() & SWT.SEPARATOR) == 0) {
- ToolItem separator = new ToolItem(toolBar, SWT.SEPARATOR);
- separator.setWidth(15);
- }
- }
-
- private void addToggle(Toggle toggle) {
- final ToolItem button = new ToolItem(mLayoutToolBar, SWT.CHECK);
-
- URL iconUrl = toggle.getIconUrl();
- String title = toggle.getTitle();
- if (iconUrl != null) {
- button.setImage(IconFactory.getInstance().getIcon(iconUrl));
- button.setToolTipText(title);
- } else {
- button.setText(title);
- }
- button.setData(toggle);
-
- button.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- Toggle toggle = (Toggle) button.getData();
- toggle.getCallback().action(toggle, getSelectedNodes(),
- toggle.getId(), button.getSelection());
- updateSelection();
- }
- });
- if (toggle.isChecked()) {
- button.setSelection(true);
- }
- }
-
- private List<INode> getSelectedNodes() {
- List<SelectionItem> selections =
- mEditor.getCanvasControl().getSelectionManager().getSelections();
- List<INode> nodes = new ArrayList<INode>(selections.size());
- for (SelectionItem item : selections) {
- nodes.add(item.getNode());
- }
-
- return nodes;
- }
-
-
- private void addPlainAction(RuleAction menuAction) {
- final ToolItem button = new ToolItem(mLayoutToolBar, SWT.PUSH);
-
- URL iconUrl = menuAction.getIconUrl();
- String title = menuAction.getTitle();
- if (iconUrl != null) {
- button.setImage(IconFactory.getInstance().getIcon(iconUrl));
- button.setToolTipText(title);
- } else {
- button.setText(title);
- }
- button.setData(menuAction);
-
- button.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- RuleAction menuAction = (RuleAction) button.getData();
- menuAction.getCallback().action(menuAction, getSelectedNodes(), menuAction.getId(),
- false);
- updateSelection();
- }
- });
- }
-
- private void addRadio(RuleAction.Choices choices) {
- List<URL> icons = choices.getIconUrls();
- List<String> titles = choices.getTitles();
- List<String> ids = choices.getIds();
- String current = choices.getCurrent() != null ? choices.getCurrent() : ""; //$NON-NLS-1$
-
- assert icons != null;
- assert icons.size() == titles.size();
-
- for (int i = 0; i < icons.size(); i++) {
- URL iconUrl = icons.get(i);
- String title = titles.get(i);
- final String id = ids.get(i);
- final ToolItem item = new ToolItem(mLayoutToolBar, SWT.RADIO);
- item.setToolTipText(title);
- item.setImage(IconFactory.getInstance().getIcon(iconUrl));
- item.setData(choices);
- item.setData(ATTR_ID, id);
- item.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (item.getSelection()) {
- RuleAction.Choices choices = (Choices) item.getData();
- choices.getCallback().action(choices, getSelectedNodes(), id, null);
- updateSelection();
- }
- }
- });
- boolean selected = current.equals(id);
- if (selected) {
- item.setSelection(true);
- }
- }
- }
-
- private void addDropdown(RuleAction.Choices choices) {
- final ToolItem combo = new ToolItem(mLayoutToolBar, SWT.DROP_DOWN);
- URL iconUrl = choices.getIconUrl();
- if (iconUrl != null) {
- combo.setImage(IconFactory.getInstance().getIcon(iconUrl));
- combo.setToolTipText(choices.getTitle());
- } else {
- combo.setText(choices.getTitle());
- }
- combo.setData(choices);
-
- Listener menuListener = new Listener() {
- @Override
- public void handleEvent(Event event) {
- Menu menu = new Menu(mLayoutToolBar.getShell(), SWT.POP_UP);
- RuleAction.Choices choices = (Choices) combo.getData();
- List<URL> icons = choices.getIconUrls();
- List<String> titles = choices.getTitles();
- List<String> ids = choices.getIds();
- String current = choices.getCurrent() != null ? choices.getCurrent() : ""; //$NON-NLS-1$
-
- for (int i = 0; i < titles.size(); i++) {
- String title = titles.get(i);
- final String id = ids.get(i);
- URL itemIconUrl = icons != null && icons.size() > 0 ? icons.get(i) : null;
- MenuItem item = new MenuItem(menu, SWT.CHECK);
- item.setText(title);
- if (itemIconUrl != null) {
- Image itemIcon = IconFactory.getInstance().getIcon(itemIconUrl);
- item.setImage(itemIcon);
- }
-
- boolean selected = id.equals(current);
- if (selected) {
- item.setSelection(true);
- }
-
- item.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- RuleAction.Choices choices = (Choices) combo.getData();
- choices.getCallback().action(choices, getSelectedNodes(), id, null);
- updateSelection();
- }
- });
- }
-
- Rectangle bounds = combo.getBounds();
- Point location = new Point(bounds.x, bounds.y + bounds.height);
- location = combo.getParent().toDisplay(location);
- menu.setLocation(location.x, location.y);
- menu.setVisible(true);
- }
- };
- combo.addListener(SWT.Selection, menuListener);
- }
-
- // ---- Zoom Controls ----
-
- @SuppressWarnings("unused") // SWT constructors have side effects, they are not unused
- private ToolBar createZoomControls() {
- ToolBar toolBar = new ToolBar(this, SWT.FLAT | SWT.RIGHT | SWT.HORIZONTAL);
-
- IconFactory iconFactory = IconFactory.getInstance();
- mZoomRealSizeButton = new ToolItem(toolBar, SWT.CHECK);
- mZoomRealSizeButton.setToolTipText("Emulate Real Size");
- mZoomRealSizeButton.setImage(iconFactory.getIcon("zoomreal")); //$NON-NLS-1$);
- mZoomRealSizeButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- boolean newState = mZoomRealSizeButton.getSelection();
- if (rescaleToReal(newState)) {
- mZoomOutButton.setEnabled(!newState);
- mZoomResetButton.setEnabled(!newState);
- mZoomInButton.setEnabled(!newState);
- mZoomFitButton.setEnabled(!newState);
- } else {
- mZoomRealSizeButton.setSelection(!newState);
- }
- }
- });
-
- mZoomFitButton = new ToolItem(toolBar, SWT.PUSH);
- mZoomFitButton.setToolTipText("Zoom to Fit (0)");
- mZoomFitButton.setImage(iconFactory.getIcon("zoomfit")); //$NON-NLS-1$);
- mZoomFitButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- rescaleToFit(true);
- }
- });
-
- mZoomResetButton = new ToolItem(toolBar, SWT.PUSH);
- mZoomResetButton.setToolTipText("Reset Zoom to 100% (1)");
- mZoomResetButton.setImage(iconFactory.getIcon("zoom100")); //$NON-NLS-1$);
- mZoomResetButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- resetScale();
- }
- });
-
- // Group zoom in/out separately
- new ToolItem(toolBar, SWT.SEPARATOR);
-
- mZoomOutButton = new ToolItem(toolBar, SWT.PUSH);
- mZoomOutButton.setToolTipText("Zoom Out (-)");
- mZoomOutButton.setImage(iconFactory.getIcon("zoomminus")); //$NON-NLS-1$);
- mZoomOutButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- rescale(-1);
- }
- });
-
- mZoomInButton = new ToolItem(toolBar, SWT.PUSH);
- mZoomInButton.setToolTipText("Zoom In (+)");
- mZoomInButton.setImage(iconFactory.getIcon("zoomplus")); //$NON-NLS-1$);
- mZoomInButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- rescale(+1);
- }
- });
-
- return toolBar;
- }
-
- @SuppressWarnings("unused") // SWT constructors have side effects, they are not unused
- private ToolBar createLintControls() {
- ToolBar toolBar = new ToolBar(this, SWT.FLAT | SWT.RIGHT | SWT.HORIZONTAL);
-
- // Separate from adjacent toolbar
- new ToolItem(toolBar, SWT.SEPARATOR);
-
- ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages();
- mLintButton = new ToolItem(toolBar, SWT.PUSH);
- mLintButton.setToolTipText("Show Lint Warnings for this Layout");
- mLintButton.setImage(sharedImages.getImage(ISharedImages.IMG_OBJS_WARN_TSK));
- mLintButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- CommonXmlEditor editor = mEditor.getEditorDelegate().getEditor();
- IFile file = editor.getInputFile();
- if (file != null) {
- EclipseLintClient.showErrors(getShell(), file, editor);
- }
- }
- });
-
- return toolBar;
- }
-
- /**
- * Updates the lint indicator state in the given layout editor
- */
- public void updateErrorIndicator() {
- updateErrorIndicator(mEditor.getEditedFile());
- }
-
- /**
- * Updates the lint indicator state for the given file
- *
- * @param file the file to show the indicator status for
- */
- public void updateErrorIndicator(IFile file) {
- IMarker[] markers = EclipseLintClient.getMarkers(file);
- updateErrorIndicator(markers.length);
- }
-
- /**
- * Sets whether the action bar should show the "lint warnings" button
- *
- * @param hasLintWarnings whether there are lint errors to be shown
- */
- private void updateErrorIndicator(final int markerCount) {
- Display display = getDisplay();
- if (display.getThread() != Thread.currentThread()) {
- display.asyncExec(new Runnable() {
- @Override
- public void run() {
- if (!isDisposed()) {
- updateErrorIndicator(markerCount);
- }
- }
- });
- return;
- }
-
- GridData layoutData = (GridData) mLintToolBar.getLayoutData();
- Integer existing = (Integer) mLintToolBar.getData();
- Integer current = Integer.valueOf(markerCount);
- if (!current.equals(existing)) {
- mLintToolBar.setData(current);
- boolean layout = false;
- boolean hasLintWarnings = markerCount > 0 && AdtPrefs.getPrefs().isLintOnSave();
- if (layoutData.exclude == hasLintWarnings) {
- layoutData.exclude = !hasLintWarnings;
- mLintToolBar.setVisible(hasLintWarnings);
- layout = true;
- }
- if (markerCount > 0) {
- String iconName = "";
- switch (markerCount) {
- case 1: iconName = "lint1"; break; //$NON-NLS-1$
- case 2: iconName = "lint2"; break; //$NON-NLS-1$
- case 3: iconName = "lint3"; break; //$NON-NLS-1$
- case 4: iconName = "lint4"; break; //$NON-NLS-1$
- case 5: iconName = "lint5"; break; //$NON-NLS-1$
- case 6: iconName = "lint6"; break; //$NON-NLS-1$
- case 7: iconName = "lint7"; break; //$NON-NLS-1$
- case 8: iconName = "lint8"; break; //$NON-NLS-1$
- case 9: iconName = "lint9"; break; //$NON-NLS-1$
- default: iconName = "lint9p"; break;//$NON-NLS-1$
- }
- mLintButton.setImage(IconFactory.getInstance().getIcon(iconName));
- }
- if (layout) {
- layout();
- }
- redraw();
- }
- }
-
- /**
- * Returns true if zooming in/out/to-fit/etc is allowed (which is not the case while
- * emulating real size)
- *
- * @return true if zooming is allowed
- */
- boolean isZoomingAllowed() {
- return mZoomInButton.isEnabled();
- }
-
- boolean isZoomingRealSize() {
- return mZoomRealSizeButton.getSelection();
- }
-
- /**
- * Rescales canvas.
- * @param direction +1 for zoom in, -1 for zoom out
- */
- void rescale(int direction) {
- LayoutCanvas canvas = mEditor.getCanvasControl();
- double s = canvas.getScale();
-
- if (direction > 0) {
- s = s * 1.2;
- } else {
- s = s / 1.2;
- }
-
- // Some operations are faster if the zoom is EXACTLY 1.0 rather than ALMOST 1.0.
- // (This is because there is a fast-path when image copying and the scale is 1.0;
- // in that case it does not have to do any scaling).
- //
- // If you zoom out 10 times and then back in 10 times, small rounding errors mean
- // that you end up with a scale=1.0000000000000004. In the cases, when you get close
- // to 1.0, just make the zoom an exact 1.0.
- if (Math.abs(s-1.0) < 0.0001) {
- s = 1.0;
- }
-
- canvas.setScale(s, true /*redraw*/);
- }
-
- /**
- * Reset the canvas scale to 100%
- */
- void resetScale() {
- mEditor.getCanvasControl().setScale(1, true /*redraw*/);
- }
-
- /**
- * Reset the canvas scale to best fit (so content is as large as possible without scrollbars)
- */
- void rescaleToFit(boolean onlyZoomOut) {
- mEditor.getCanvasControl().setFitScale(onlyZoomOut, true /*allowZoomIn*/);
- }
-
- boolean rescaleToReal(boolean real) {
- if (real) {
- return computeAndSetRealScale(true /*redraw*/);
- } else {
- // reset the scale to 100%
- mEditor.getCanvasControl().setScale(1, true /*redraw*/);
- return true;
- }
- }
-
- boolean computeAndSetRealScale(boolean redraw) {
- // compute average dpi of X and Y
- ConfigurationChooser chooser = mEditor.getConfigurationChooser();
- Configuration config = chooser.getConfiguration();
- Device device = config.getDevice();
- Screen screen = device.getDefaultHardware().getScreen();
- double dpi = (screen.getXdpi() + screen.getYdpi()) / 2.;
-
- // get the monitor dpi
- float monitor = AdtPrefs.getPrefs().getMonitorDensity();
- if (monitor == 0.f) {
- ResolutionChooserDialog dialog = new ResolutionChooserDialog(chooser.getShell());
- if (dialog.open() == Window.OK) {
- monitor = dialog.getDensity();
- AdtPrefs.getPrefs().setMonitorDensity(monitor);
- } else {
- return false;
- }
- }
-
- mEditor.getCanvasControl().setScale(monitor / dpi, redraw);
- return true;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutCanvas.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutCanvas.java
deleted file mode 100644
index 814b82cec..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutCanvas.java
+++ /dev/null
@@ -1,1720 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.IDragElement.IDragAttribute;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.Margins;
-import com.android.ide.common.api.Point;
-import com.android.ide.common.rendering.api.Capability;
-import com.android.ide.common.rendering.api.RenderSession;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigurationChooser;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigurationDescription;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.IncludeFinder.Reference;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.NodeFactory;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.RulesEngine;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.ViewMetadataRepository;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiDocumentNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.lint.LintEditAction;
-import com.android.resources.Density;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.QualifiedName;
-import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.ActionContributionItem;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IContributionItem;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IStatusLineManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StyledText;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DragSource;
-import org.eclipse.swt.dnd.DropTarget;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.events.ControlAdapter;
-import org.eclipse.swt.events.ControlEvent;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.MenuDetectEvent;
-import org.eclipse.swt.events.MenuDetectListener;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.PaintEvent;
-import org.eclipse.swt.events.PaintListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.ImageData;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Canvas;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
-import org.eclipse.ui.actions.ContributionItemFactory;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.ui.internal.ide.IDEWorkbenchMessages;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.w3c.dom.Node;
-
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * Displays the image rendered by the {@link GraphicalEditorPart} and handles
- * the interaction with the widgets.
- * <p/>
- * {@link LayoutCanvas} implements the "Canvas" control. The editor part
- * actually uses the {@link LayoutCanvasViewer}, which is a JFace viewer wrapper
- * around this control.
- * <p/>
- * The LayoutCanvas contains the painting logic for the canvas. Selection,
- * clipboard, view management etc. is handled in separate helper classes.
- *
- * @since GLE2
- */
-@SuppressWarnings("restriction") // For WorkBench "Show In" support
-public class LayoutCanvas extends Canvas {
- private final static QualifiedName NAME_ZOOM =
- new QualifiedName(AdtPlugin.PLUGIN_ID, "zoom");//$NON-NLS-1$
-
- private static final boolean DEBUG = false;
-
- static final String PREFIX_CANVAS_ACTION = "canvas_action_"; //$NON-NLS-1$
-
- /** The layout editor that uses this layout canvas. */
- private final LayoutEditorDelegate mEditorDelegate;
-
- /** The Rules Engine, associated with the current project. */
- private RulesEngine mRulesEngine;
-
- /** GC wrapper given to the IViewRule methods. The GC itself is only defined in the
- * context of {@link #onPaint(PaintEvent)}; otherwise it is null. */
- private GCWrapper mGCWrapper;
-
- /** Default font used on the canvas. Do not dispose, it's a system font. */
- private Font mFont;
-
- /** Current hover view info. Null when no mouse hover. */
- private CanvasViewInfo mHoverViewInfo;
-
- /** When true, always display the outline of all views. */
- private boolean mShowOutline;
-
- /** When true, display the outline of all empty parent views. */
- private boolean mShowInvisible;
-
- /** Drop target associated with this composite. */
- private DropTarget mDropTarget;
-
- /** Factory that can create {@link INode} proxies. */
- private final @NonNull NodeFactory mNodeFactory = new NodeFactory(this);
-
- /** Vertical scaling & scrollbar information. */
- private final CanvasTransform mVScale;
-
- /** Horizontal scaling & scrollbar information. */
- private final CanvasTransform mHScale;
-
- /** Drag source associated with this canvas. */
- private DragSource mDragSource;
-
- /**
- * The current Outline Page, to set its model.
- * It isn't possible to call OutlinePage2.dispose() in this.dispose().
- * this.dispose() is called from GraphicalEditorPart.dispose(),
- * when page's widget is already disposed.
- * Added the DisposeListener to OutlinePage2 in order to correctly dispose this page.
- **/
- private OutlinePage mOutlinePage;
-
- /** Delete action for the Edit or context menu. */
- private Action mDeleteAction;
-
- /** Select-All action for the Edit or context menu. */
- private Action mSelectAllAction;
-
- /** Paste action for the Edit or context menu. */
- private Action mPasteAction;
-
- /** Cut action for the Edit or context menu. */
- private Action mCutAction;
-
- /** Copy action for the Edit or context menu. */
- private Action mCopyAction;
-
- /** Undo action: delegates to the text editor */
- private IAction mUndoAction;
-
- /** Redo action: delegates to the text editor */
- private IAction mRedoAction;
-
- /** Root of the context menu. */
- private MenuManager mMenuManager;
-
- /** The view hierarchy associated with this canvas. */
- private final ViewHierarchy mViewHierarchy = new ViewHierarchy(this);
-
- /** The selection in the canvas. */
- private final SelectionManager mSelectionManager = new SelectionManager(this);
-
- /** The overlay which paints the optional outline. */
- private OutlineOverlay mOutlineOverlay;
-
- /** The overlay which paints outlines around empty children */
- private EmptyViewsOverlay mEmptyOverlay;
-
- /** The overlay which paints the mouse hover. */
- private HoverOverlay mHoverOverlay;
-
- /** The overlay which paints the lint warnings */
- private LintOverlay mLintOverlay;
-
- /** The overlay which paints the selection. */
- private SelectionOverlay mSelectionOverlay;
-
- /** The overlay which paints the rendered layout image. */
- private ImageOverlay mImageOverlay;
-
- /** The overlay which paints masks hiding everything but included content. */
- private IncludeOverlay mIncludeOverlay;
-
- /** Configuration previews shown next to the layout */
- private final RenderPreviewManager mPreviewManager;
-
- /**
- * Gesture Manager responsible for identifying mouse, keyboard and drag and
- * drop events.
- */
- private final GestureManager mGestureManager = new GestureManager(this);
-
- /**
- * When set, performs a zoom-to-fit when the next rendering image arrives.
- */
- private boolean mZoomFitNextImage;
-
- /**
- * Native clipboard support.
- */
- private ClipboardSupport mClipboardSupport;
-
- /** Tooltip manager for lint warnings */
- private LintTooltipManager mLintTooltipManager;
-
- private Color mBackgroundColor;
-
- /**
- * Creates a new {@link LayoutCanvas} widget
- *
- * @param editorDelegate the associated editor delegate
- * @param rulesEngine the rules engine
- * @param parent parent SWT widget
- * @param style the SWT style
- */
- public LayoutCanvas(LayoutEditorDelegate editorDelegate,
- RulesEngine rulesEngine,
- Composite parent,
- int style) {
- super(parent, style | SWT.DOUBLE_BUFFERED | SWT.V_SCROLL | SWT.H_SCROLL);
- mEditorDelegate = editorDelegate;
- mRulesEngine = rulesEngine;
-
- mBackgroundColor = new Color(parent.getDisplay(), 150, 150, 150);
- setBackground(mBackgroundColor);
-
- mClipboardSupport = new ClipboardSupport(this, parent);
- mHScale = new CanvasTransform(this, getHorizontalBar());
- mVScale = new CanvasTransform(this, getVerticalBar());
- mPreviewManager = new RenderPreviewManager(this);
-
- // Unit test suite passes a null here; TODO: Replace with mocking
- IFile file = editorDelegate != null ? editorDelegate.getEditor().getInputFile() : null;
- if (file != null) {
- String zoom = AdtPlugin.getFileProperty(file, NAME_ZOOM);
- if (zoom != null) {
- try {
- double initialScale = Double.parseDouble(zoom);
- if (initialScale > 0.1) {
- mHScale.setScale(initialScale);
- mVScale.setScale(initialScale);
- }
- } catch (NumberFormatException nfe) {
- // Ignore - use zoom=100%
- }
- } else {
- mZoomFitNextImage = true;
- }
- }
-
- mGCWrapper = new GCWrapper(mHScale, mVScale);
-
- Display display = getDisplay();
- mFont = display.getSystemFont();
-
- // --- Set up graphic overlays
- // mOutlineOverlay and mEmptyOverlay are initialized lazily
- mHoverOverlay = new HoverOverlay(this, mHScale, mVScale);
- mHoverOverlay.create(display);
- mSelectionOverlay = new SelectionOverlay(this);
- mSelectionOverlay.create(display);
- mImageOverlay = new ImageOverlay(this, mHScale, mVScale);
- mIncludeOverlay = new IncludeOverlay(this);
- mImageOverlay.create(display);
- mLintOverlay = new LintOverlay(this);
- mLintOverlay.create(display);
-
- // --- Set up listeners
- addPaintListener(new PaintListener() {
- @Override
- public void paintControl(PaintEvent e) {
- onPaint(e);
- }
- });
-
- addControlListener(new ControlAdapter() {
- @Override
- public void controlResized(ControlEvent e) {
- super.controlResized(e);
-
- // Check editor state:
- LayoutWindowCoordinator coordinator = null;
- IEditorSite editorSite = getEditorDelegate().getEditor().getEditorSite();
- IWorkbenchWindow window = editorSite.getWorkbenchWindow();
- if (window != null) {
- coordinator = LayoutWindowCoordinator.get(window, false);
- if (coordinator != null) {
- coordinator.syncMaximizedState(editorSite.getPage());
- }
- }
-
- updateScrollBars();
-
- // Update the zoom level in the canvas when you toggle the zoom
- if (coordinator != null) {
- mZoomCheck.run();
- } else {
- // During startup, delay updates which can trigger further layout
- getDisplay().asyncExec(mZoomCheck);
-
- }
- }
- });
-
- // --- setup drag'n'drop ---
- // DND Reference: http://www.eclipse.org/articles/Article-SWT-DND/DND-in-SWT.html
-
- mDropTarget = createDropTarget(this);
- mDragSource = createDragSource(this);
- mGestureManager.registerListeners(mDragSource, mDropTarget);
-
- if (mEditorDelegate == null) {
- // TODO: In another CL we should use EasyMock/objgen to provide an editor.
- return; // Unit test
- }
-
- // --- setup context menu ---
- setupGlobalActionHandlers();
- createContextMenu();
-
- // --- setup outline ---
- // Get the outline associated with this editor, if any and of the right type.
- if (editorDelegate != null) {
- mOutlinePage = editorDelegate.getGraphicalOutline();
- }
-
- mLintTooltipManager = new LintTooltipManager(this);
- mLintTooltipManager.register();
- }
-
- void updateScrollBars() {
- Rectangle clientArea = getClientArea();
- Image image = mImageOverlay.getImage();
- if (image != null) {
- ImageData imageData = image.getImageData();
- int clientWidth = clientArea.width;
- int clientHeight = clientArea.height;
-
- int imageWidth = imageData.width;
- int imageHeight = imageData.height;
-
- int fullWidth = imageWidth;
- int fullHeight = imageHeight;
-
- if (mPreviewManager.hasPreviews()) {
- fullHeight = Math.max(fullHeight,
- (int) (mPreviewManager.getHeight() / mHScale.getScale()));
- }
-
- if (clientWidth == 0) {
- clientWidth = imageWidth;
- Shell shell = getShell();
- if (shell != null) {
- org.eclipse.swt.graphics.Point size = shell.getSize();
- if (size.x > 0) {
- clientWidth = size.x * 70 / 100;
- }
- }
- }
- if (clientHeight == 0) {
- clientHeight = imageHeight;
- Shell shell = getShell();
- if (shell != null) {
- org.eclipse.swt.graphics.Point size = shell.getSize();
- if (size.y > 0) {
- clientWidth = size.y * 80 / 100;
- }
- }
- }
-
- mHScale.setSize(imageWidth, fullWidth, clientWidth);
- mVScale.setSize(imageHeight, fullHeight, clientHeight);
- }
- }
-
- private Runnable mZoomCheck = new Runnable() {
- private Boolean mWasZoomed;
-
- @Override
- public void run() {
- if (isDisposed()) {
- return;
- }
-
- IEditorSite editorSite = getEditorDelegate().getEditor().getEditorSite();
- IWorkbenchWindow window = editorSite.getWorkbenchWindow();
- if (window != null) {
- LayoutWindowCoordinator coordinator = LayoutWindowCoordinator.get(window, false);
- if (coordinator != null) {
- Boolean zoomed = coordinator.isEditorMaximized();
- if (mWasZoomed != zoomed) {
- if (mWasZoomed != null) {
- LayoutActionBar actionBar = getGraphicalEditor().getLayoutActionBar();
- if (actionBar.isZoomingAllowed()) {
- setFitScale(true /*onlyZoomOut*/, true /*allowZoomIn*/);
- }
- }
- mWasZoomed = zoomed;
- }
- }
- }
- }
- };
-
- void handleKeyPressed(KeyEvent e) {
- // Set up backspace as an alias for the delete action within the canvas.
- // On most Macs there is no delete key - though there IS a key labeled
- // "Delete" and it sends a backspace key code! In short, for Macs we should
- // treat backspace as delete, and it's harmless (and probably useful) to
- // handle backspace for other platforms as well.
- if (e.keyCode == SWT.BS) {
- mDeleteAction.run();
- } else if (e.keyCode == SWT.ESC) {
- mSelectionManager.selectParent();
- } else if (e.keyCode == DynamicContextMenu.DEFAULT_ACTION_KEY) {
- mSelectionManager.performDefaultAction();
- } else if (e.keyCode == 'r') {
- // Keep key bindings in sync with {@link DynamicContextMenu#createPlainAction}
- // TODO: Find a way to look up the Eclipse key bindings and attempt
- // to use the current keymap's rename action.
- if (SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_DARWIN) {
- // Command+Option+R
- if ((e.stateMask & (SWT.MOD1 | SWT.MOD3)) == (SWT.MOD1 | SWT.MOD3)) {
- mSelectionManager.performRename();
- }
- } else {
- // Alt+Shift+R
- if ((e.stateMask & (SWT.MOD2 | SWT.MOD3)) == (SWT.MOD2 | SWT.MOD3)) {
- mSelectionManager.performRename();
- }
- }
- } else {
- // Zooming actions
- char c = e.character;
- LayoutActionBar actionBar = getGraphicalEditor().getLayoutActionBar();
- if (c == '1' && actionBar.isZoomingAllowed()) {
- setScale(1, true);
- } else if (c == '0' && actionBar.isZoomingAllowed()) {
- setFitScale(true, true /*allowZoomIn*/);
- } else if (e.keyCode == '0' && (e.stateMask & SWT.MOD2) != 0
- && actionBar.isZoomingAllowed()) {
- setFitScale(false, true /*allowZoomIn*/);
- } else if ((c == '+' || c == '=') && actionBar.isZoomingAllowed()) {
- if ((e.stateMask & SWT.MOD1) != 0) {
- mPreviewManager.zoomIn();
- } else {
- actionBar.rescale(1);
- }
- } else if (c == '-' && actionBar.isZoomingAllowed()) {
- if ((e.stateMask & SWT.MOD1) != 0) {
- mPreviewManager.zoomOut();
- } else {
- actionBar.rescale(-1);
- }
- }
- }
- }
-
- @Override
- public void dispose() {
- super.dispose();
-
- mGestureManager.unregisterListeners(mDragSource, mDropTarget);
-
- if (mLintTooltipManager != null) {
- mLintTooltipManager.unregister();
- mLintTooltipManager = null;
- }
-
- if (mDropTarget != null) {
- mDropTarget.dispose();
- mDropTarget = null;
- }
-
- if (mRulesEngine != null) {
- mRulesEngine.dispose();
- mRulesEngine = null;
- }
-
- if (mDragSource != null) {
- mDragSource.dispose();
- mDragSource = null;
- }
-
- if (mClipboardSupport != null) {
- mClipboardSupport.dispose();
- mClipboardSupport = null;
- }
-
- if (mGCWrapper != null) {
- mGCWrapper.dispose();
- mGCWrapper = null;
- }
-
- if (mOutlineOverlay != null) {
- mOutlineOverlay.dispose();
- mOutlineOverlay = null;
- }
-
- if (mEmptyOverlay != null) {
- mEmptyOverlay.dispose();
- mEmptyOverlay = null;
- }
-
- if (mHoverOverlay != null) {
- mHoverOverlay.dispose();
- mHoverOverlay = null;
- }
-
- if (mSelectionOverlay != null) {
- mSelectionOverlay.dispose();
- mSelectionOverlay = null;
- }
-
- if (mImageOverlay != null) {
- mImageOverlay.dispose();
- mImageOverlay = null;
- }
-
- if (mIncludeOverlay != null) {
- mIncludeOverlay.dispose();
- mIncludeOverlay = null;
- }
-
- if (mLintOverlay != null) {
- mLintOverlay.dispose();
- mLintOverlay = null;
- }
-
- if (mBackgroundColor != null) {
- mBackgroundColor.dispose();
- mBackgroundColor = null;
- }
-
- mPreviewManager.disposePreviews();
- mViewHierarchy.dispose();
- }
-
- /**
- * Returns the configuration preview manager for this canvas
- *
- * @return the configuration preview manager for this canvas
- */
- @NonNull
- public RenderPreviewManager getPreviewManager() {
- return mPreviewManager;
- }
-
- /** Returns the Rules Engine, associated with the current project. */
- RulesEngine getRulesEngine() {
- return mRulesEngine;
- }
-
- /** Sets the Rules Engine, associated with the current project. */
- void setRulesEngine(RulesEngine rulesEngine) {
- mRulesEngine = rulesEngine;
- }
-
- /**
- * Returns the factory to use to convert from {@link CanvasViewInfo} or from
- * {@link UiViewElementNode} to {@link INode} proxies.
- *
- * @return the node factory
- */
- @NonNull
- public NodeFactory getNodeFactory() {
- return mNodeFactory;
- }
-
- /**
- * Returns the GCWrapper used to paint view rules.
- *
- * @return The GCWrapper used to paint view rules
- */
- GCWrapper getGcWrapper() {
- return mGCWrapper;
- }
-
- /**
- * Returns the {@link LayoutEditorDelegate} associated with this canvas.
- *
- * @return the delegate
- */
- public LayoutEditorDelegate getEditorDelegate() {
- return mEditorDelegate;
- }
-
- /**
- * Returns the current {@link ImageOverlay} painting the rendered result
- *
- * @return the image overlay responsible for painting the rendered result, never null
- */
- ImageOverlay getImageOverlay() {
- return mImageOverlay;
- }
-
- /**
- * Returns the current {@link SelectionOverlay} painting the selection highlights
- *
- * @return the selection overlay responsible for painting the selection highlights,
- * never null
- */
- SelectionOverlay getSelectionOverlay() {
- return mSelectionOverlay;
- }
-
- /**
- * Returns the {@link GestureManager} associated with this canvas.
- *
- * @return the {@link GestureManager} associated with this canvas, never null.
- */
- GestureManager getGestureManager() {
- return mGestureManager;
- }
-
- /**
- * Returns the current {@link HoverOverlay} painting the mouse hover.
- *
- * @return the hover overlay responsible for painting the mouse hover,
- * never null
- */
- HoverOverlay getHoverOverlay() {
- return mHoverOverlay;
- }
-
- /**
- * Returns the horizontal {@link CanvasTransform} transform object, which can map
- * a layout point into a control point.
- *
- * @return A {@link CanvasTransform} for mapping between layout and control
- * coordinates in the horizontal dimension.
- */
- CanvasTransform getHorizontalTransform() {
- return mHScale;
- }
-
- /**
- * Returns the vertical {@link CanvasTransform} transform object, which can map a
- * layout point into a control point.
- *
- * @return A {@link CanvasTransform} for mapping between layout and control
- * coordinates in the vertical dimension.
- */
- CanvasTransform getVerticalTransform() {
- return mVScale;
- }
-
- /**
- * Returns the {@link OutlinePage} associated with this canvas
- *
- * @return the {@link OutlinePage} associated with this canvas
- */
- public OutlinePage getOutlinePage() {
- return mOutlinePage;
- }
-
- /**
- * Returns the {@link SelectionManager} associated with this canvas.
- *
- * @return The {@link SelectionManager} holding the selection for this
- * canvas. Never null.
- */
- public SelectionManager getSelectionManager() {
- return mSelectionManager;
- }
-
- /**
- * Returns the {@link ViewHierarchy} object associated with this canvas,
- * holding the most recent rendered view of the scene, if valid.
- *
- * @return The {@link ViewHierarchy} object associated with this canvas.
- * Never null.
- */
- public ViewHierarchy getViewHierarchy() {
- return mViewHierarchy;
- }
-
- /**
- * Returns the {@link ClipboardSupport} object associated with this canvas.
- *
- * @return The {@link ClipboardSupport} object for this canvas. Null only after dispose.
- */
- public ClipboardSupport getClipboardSupport() {
- return mClipboardSupport;
- }
-
- /** Returns the Select All action bound to this canvas */
- Action getSelectAllAction() {
- return mSelectAllAction;
- }
-
- /** Returns the associated {@link GraphicalEditorPart} */
- GraphicalEditorPart getGraphicalEditor() {
- return mEditorDelegate.getGraphicalEditor();
- }
-
- /**
- * Sets the result of the layout rendering. The result object indicates if the layout
- * rendering succeeded. If it did, it contains a bitmap and the objects rectangles.
- *
- * Implementation detail: the bridge's computeLayout() method already returns a newly
- * allocated ILayourResult. That means we can keep this result and hold on to it
- * when it is valid.
- *
- * @param session The new scene, either valid or not.
- * @param explodedNodes The set of individual nodes the layout computer was asked to
- * explode. Note that these are independent of the explode-all mode where
- * all views are exploded; this is used only for the mode (
- * {@link #showInvisibleViews(boolean)}) where individual invisible nodes
- * are padded during certain interactions.
- */
- void setSession(RenderSession session, Set<UiElementNode> explodedNodes,
- boolean layoutlib5) {
- // disable any hover
- clearHover();
-
- mViewHierarchy.setSession(session, explodedNodes, layoutlib5);
- if (mViewHierarchy.isValid() && session != null) {
- Image image = mImageOverlay.setImage(session.getImage(),
- session.isAlphaChannelImage());
-
- mOutlinePage.setModel(mViewHierarchy.getRoot());
- getGraphicalEditor().setModel(mViewHierarchy.getRoot());
-
- if (image != null) {
- updateScrollBars();
- if (mZoomFitNextImage) {
- // Must be run asynchronously because getClientArea() returns 0 bounds
- // when the editor is being initialized
- getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- if (!isDisposed()) {
- ensureZoomed();
- }
- }
- });
- }
-
- // Ensure that if we have a a preview mode enabled, it's shown
- syncPreviewMode();
- }
- }
-
- redraw();
- }
-
- void ensureZoomed() {
- if (mZoomFitNextImage && getClientArea().height > 0) {
- mZoomFitNextImage = false;
- LayoutActionBar actionBar = getGraphicalEditor().getLayoutActionBar();
- if (actionBar.isZoomingAllowed()) {
- setFitScale(true, true /*allowZoomIn*/);
- }
- }
- }
-
- void setShowOutline(boolean newState) {
- mShowOutline = newState;
- redraw();
- }
-
- /**
- * Returns the zoom scale factor of the canvas (the amount the full
- * resolution render of the device is zoomed before being shown on the
- * canvas)
- *
- * @return the image scale
- */
- public double getScale() {
- return mHScale.getScale();
- }
-
- void setScale(double scale, boolean redraw) {
- if (scale <= 0.0) {
- scale = 1.0;
- }
-
- if (scale == getScale()) {
- return;
- }
-
- mHScale.setScale(scale);
- mVScale.setScale(scale);
- if (redraw) {
- redraw();
- }
-
- // Clear the zoom setting if it is almost identical to 1.0
- String zoomValue = (Math.abs(scale - 1.0) < 0.0001) ? null : Double.toString(scale);
- IFile file = mEditorDelegate.getEditor().getInputFile();
- if (file != null) {
- AdtPlugin.setFileProperty(file, NAME_ZOOM, zoomValue);
- }
- }
-
- /**
- * Scales the canvas to best fit
- *
- * @param onlyZoomOut if true, then the zooming factor will never be larger than 1,
- * which means that this function will zoom out if necessary to show the
- * rendered image, but it will never zoom in.
- * TODO: Rename this, it sounds like it conflicts with allowZoomIn,
- * even though one is referring to the zoom level and one is referring
- * to the overall act of scaling above/below 1.
- * @param allowZoomIn if false, then if the computed zoom factor is smaller than
- * the current zoom factor, it will be ignored.
- */
- public void setFitScale(boolean onlyZoomOut, boolean allowZoomIn) {
- ImageOverlay imageOverlay = getImageOverlay();
- if (imageOverlay == null) {
- return;
- }
- Image image = imageOverlay.getImage();
- if (image != null) {
- Rectangle canvasSize = getClientArea();
- int canvasWidth = canvasSize.width;
- int canvasHeight = canvasSize.height;
-
- boolean hasPreviews = mPreviewManager.hasPreviews();
- if (hasPreviews) {
- canvasWidth = 2 * canvasWidth / 3;
- } else {
- canvasWidth -= 4;
- canvasHeight -= 4;
- }
-
- ImageData imageData = image.getImageData();
- int sceneWidth = imageData.width;
- int sceneHeight = imageData.height;
- if (sceneWidth == 0.0 || sceneHeight == 0.0) {
- return;
- }
-
- if (imageOverlay.getShowDropShadow()) {
- sceneWidth += 2 * ImageUtils.SHADOW_SIZE;
- sceneHeight += 2 * ImageUtils.SHADOW_SIZE;
- }
-
- // Reduce the margins if necessary
- int hDelta = canvasWidth - sceneWidth;
- int hMargin = 0;
- if (hDelta > 2 * CanvasTransform.DEFAULT_MARGIN) {
- hMargin = CanvasTransform.DEFAULT_MARGIN;
- } else if (hDelta > 0) {
- hMargin = hDelta / 2;
- }
-
- int vDelta = canvasHeight - sceneHeight;
- int vMargin = 0;
- if (vDelta > 2 * CanvasTransform.DEFAULT_MARGIN) {
- vMargin = CanvasTransform.DEFAULT_MARGIN;
- } else if (vDelta > 0) {
- vMargin = vDelta / 2;
- }
-
- double hScale = (canvasWidth - 2 * hMargin) / (double) sceneWidth;
- double vScale = (canvasHeight - 2 * vMargin) / (double) sceneHeight;
-
- double scale = Math.min(hScale, vScale);
-
- if (onlyZoomOut) {
- scale = Math.min(1.0, scale);
- }
-
- if (!allowZoomIn && scale > getScale()) {
- return;
- }
-
- setScale(scale, true);
- }
- }
-
- /**
- * Transforms a point, expressed in layout coordinates, into "client" coordinates
- * relative to the control (and not relative to the display).
- *
- * @param canvasX X in the canvas coordinates
- * @param canvasY Y in the canvas coordinates
- * @return A new {@link Point} in control client coordinates (not display coordinates)
- */
- Point layoutToControlPoint(int canvasX, int canvasY) {
- int x = mHScale.translate(canvasX);
- int y = mVScale.translate(canvasY);
- return new Point(x, y);
- }
-
- /**
- * Returns the action for the context menu corresponding to the given action id.
- * <p/>
- * For global actions such as copy or paste, the action id must be composed of
- * the {@link #PREFIX_CANVAS_ACTION} followed by one of {@link ActionFactory}'s
- * action ids.
- * <p/>
- * Returns null if there's no action for the given id.
- */
- IAction getAction(String actionId) {
- String prefix = PREFIX_CANVAS_ACTION;
- if (mMenuManager == null ||
- actionId == null ||
- !actionId.startsWith(prefix)) {
- return null;
- }
-
- actionId = actionId.substring(prefix.length());
-
- for (IContributionItem contrib : mMenuManager.getItems()) {
- if (contrib instanceof ActionContributionItem &&
- actionId.equals(contrib.getId())) {
- return ((ActionContributionItem) contrib).getAction();
- }
- }
-
- return null;
- }
-
- //---------------
-
- /**
- * Paints the canvas in response to paint events.
- */
- private void onPaint(PaintEvent e) {
- GC gc = e.gc;
- gc.setFont(mFont);
- mGCWrapper.setGC(gc);
- try {
- if (!mImageOverlay.isHiding()) {
- mImageOverlay.paint(gc);
- }
-
- mPreviewManager.paint(gc);
-
- if (mShowOutline) {
- if (mOutlineOverlay == null) {
- mOutlineOverlay = new OutlineOverlay(mViewHierarchy, mHScale, mVScale);
- mOutlineOverlay.create(getDisplay());
- }
- if (!mOutlineOverlay.isHiding()) {
- mOutlineOverlay.paint(gc);
- }
- }
-
- if (mShowInvisible) {
- if (mEmptyOverlay == null) {
- mEmptyOverlay = new EmptyViewsOverlay(mViewHierarchy, mHScale, mVScale);
- mEmptyOverlay.create(getDisplay());
- }
- if (!mEmptyOverlay.isHiding()) {
- mEmptyOverlay.paint(gc);
- }
- }
-
- if (!mHoverOverlay.isHiding()) {
- mHoverOverlay.paint(gc);
- }
-
- if (!mLintOverlay.isHiding()) {
- mLintOverlay.paint(gc);
- }
-
- if (!mIncludeOverlay.isHiding()) {
- mIncludeOverlay.paint(gc);
- }
-
- if (!mSelectionOverlay.isHiding()) {
- mSelectionOverlay.paint(mSelectionManager, mGCWrapper, gc, mRulesEngine);
- }
- mGestureManager.paint(gc);
-
- } finally {
- mGCWrapper.setGC(null);
- }
- }
-
- /**
- * Shows or hides invisible parent views, which are views which have empty bounds and
- * no children. The nodes which will be shown are provided by
- * {@link #getNodesToExplode()}.
- *
- * @param show When true, any invisible parent nodes are padded and highlighted
- * ("exploded"), and when false any formerly exploded nodes are hidden.
- */
- void showInvisibleViews(boolean show) {
- if (mShowInvisible == show) {
- return;
- }
- mShowInvisible = show;
-
- // Optimization: Avoid doing work when we don't have invisible parents (on show)
- // or formerly exploded nodes (on hide).
- if (show && !mViewHierarchy.hasInvisibleParents()) {
- return;
- } else if (!show && !mViewHierarchy.hasExplodedParents()) {
- return;
- }
-
- mEditorDelegate.recomputeLayout();
- }
-
- /**
- * Returns a set of nodes that should be exploded (forced non-zero padding during render),
- * or null if no nodes should be exploded. (Note that this is independent of the
- * explode-all mode, where all nodes are padded -- that facility does not use this
- * mechanism, which is only intended to be used to expose invisible parent nodes.
- *
- * @return The set of invisible parents, or null if no views should be expanded.
- */
- public Set<UiElementNode> getNodesToExplode() {
- if (mShowInvisible) {
- return mViewHierarchy.getInvisibleNodes();
- }
-
- // IF we have selection, and IF we have invisible nodes in the view,
- // see if any of the selected items are among the invisible nodes, and if so
- // add them to a lazily constructed set which we pass back for rendering.
- Set<UiElementNode> result = null;
- List<SelectionItem> selections = mSelectionManager.getSelections();
- if (selections.size() > 0) {
- List<CanvasViewInfo> invisibleParents = mViewHierarchy.getInvisibleViews();
- if (invisibleParents.size() > 0) {
- for (SelectionItem item : selections) {
- CanvasViewInfo viewInfo = item.getViewInfo();
- // O(n^2) here, but both the selection size and especially the
- // invisibleParents size are expected to be small
- if (invisibleParents.contains(viewInfo)) {
- UiViewElementNode node = viewInfo.getUiViewNode();
- if (node != null) {
- if (result == null) {
- result = new HashSet<UiElementNode>();
- }
- result.add(node);
- }
- }
- }
- }
- }
-
- return result;
- }
-
- /**
- * Clears the hover.
- */
- void clearHover() {
- mHoverOverlay.clearHover();
- }
-
- /**
- * Hover on top of a known child.
- */
- void hover(MouseEvent e) {
- // Check if a button is pressed; no hovers during drags
- if ((e.stateMask & SWT.BUTTON_MASK) != 0) {
- clearHover();
- return;
- }
-
- LayoutPoint p = ControlPoint.create(this, e).toLayout();
- CanvasViewInfo vi = mViewHierarchy.findViewInfoAt(p);
-
- // We don't hover on the root since it's not a widget per see and it is always there.
- // We also skip spacers...
- if (vi != null && (vi.isRoot() || vi.isHidden())) {
- vi = null;
- }
-
- boolean needsUpdate = vi != mHoverViewInfo;
- mHoverViewInfo = vi;
-
- if (vi == null) {
- clearHover();
- } else {
- Rectangle r = vi.getSelectionRect();
- mHoverOverlay.setHover(r.x, r.y, r.width, r.height);
- }
-
- if (needsUpdate) {
- redraw();
- }
- }
-
- /**
- * Shows the given {@link CanvasViewInfo}, which can mean exposing its XML or if it's
- * an included element, its corresponding file.
- *
- * @param vi the {@link CanvasViewInfo} to be shown
- */
- public void show(CanvasViewInfo vi) {
- String url = vi.getIncludeUrl();
- if (url != null) {
- showInclude(url);
- } else {
- showXml(vi);
- }
- }
-
- /**
- * Shows the layout file referenced by the given url in the same project.
- *
- * @param url The layout attribute url of the form @layout/foo
- */
- private void showInclude(String url) {
- GraphicalEditorPart graphicalEditor = getGraphicalEditor();
- IPath filePath = graphicalEditor.findResourceFile(url);
- if (filePath == null) {
- // Should not be possible - if the URL had been bad, then we wouldn't
- // have been able to render the scene and you wouldn't have been able
- // to click on it
- return;
- }
-
- // Save the including file, if necessary: without it, the "Show Included In"
- // facility which is invoked automatically will not work properly if the <include>
- // tag is not in the saved version of the file, since the outer file is read from
- // disk rather than from memory.
- IEditorSite editorSite = graphicalEditor.getEditorSite();
- IWorkbenchPage page = editorSite.getPage();
- page.saveEditor(mEditorDelegate.getEditor(), false);
-
- IWorkspaceRoot workspace = ResourcesPlugin.getWorkspace().getRoot();
- IFile xmlFile = null;
- IPath workspacePath = workspace.getLocation();
- if (workspacePath.isPrefixOf(filePath)) {
- IPath relativePath = filePath.makeRelativeTo(workspacePath);
- xmlFile = (IFile) workspace.findMember(relativePath);
- } else if (filePath.isAbsolute()) {
- xmlFile = workspace.getFileForLocation(filePath);
- }
- if (xmlFile != null) {
- IFile leavingFile = graphicalEditor.getEditedFile();
- Reference next = Reference.create(graphicalEditor.getEditedFile());
-
- try {
- IEditorPart openAlready = EditorUtility.isOpenInEditor(xmlFile);
-
- // Show the included file as included within this click source?
- if (openAlready != null) {
- LayoutEditorDelegate delegate = LayoutEditorDelegate.fromEditor(openAlready);
- if (delegate != null) {
- GraphicalEditorPart gEditor = delegate.getGraphicalEditor();
- if (gEditor != null &&
- gEditor.renderingSupports(Capability.EMBEDDED_LAYOUT)) {
- gEditor.showIn(next);
- }
- }
- } else {
- try {
- // Set initial state of a new file
- // TODO: Only set rendering target portion of the state
- String state = ConfigurationDescription.getDescription(leavingFile);
- xmlFile.setSessionProperty(GraphicalEditorPart.NAME_INITIAL_STATE,
- state);
- } catch (CoreException e) {
- // pass
- }
-
- if (graphicalEditor.renderingSupports(Capability.EMBEDDED_LAYOUT)) {
- try {
- xmlFile.setSessionProperty(GraphicalEditorPart.NAME_INCLUDE, next);
- } catch (CoreException e) {
- // pass - worst that can happen is that we don't
- //start with inclusion
- }
- }
- }
-
- EditorUtility.openInEditor(xmlFile, true);
- return;
- } catch (PartInitException ex) {
- AdtPlugin.log(ex, "Can't open %$1s", url); //$NON-NLS-1$
- }
- } else {
- // It's not a path in the workspace; look externally
- // (this is probably an @android: path)
- if (filePath.isAbsolute()) {
- IFileStore fileStore = EFS.getLocalFileSystem().getStore(filePath);
- // fileStore = fileStore.getChild(names[i]);
- if (!fileStore.fetchInfo().isDirectory() && fileStore.fetchInfo().exists()) {
- try {
- IDE.openEditorOnFileStore(page, fileStore);
- return;
- } catch (PartInitException ex) {
- AdtPlugin.log(ex, "Can't open %$1s", url); //$NON-NLS-1$
- }
- }
- }
- }
-
- // Failed: display message to the user
- String message = String.format("Could not find resource %1$s", url);
- IStatusLineManager status = editorSite.getActionBars().getStatusLineManager();
- status.setErrorMessage(message);
- getDisplay().beep();
- }
-
- /**
- * Returns the layout resource name of this layout
- *
- * @return the layout resource name of this layout
- */
- public String getLayoutResourceName() {
- GraphicalEditorPart graphicalEditor = getGraphicalEditor();
- return graphicalEditor.getLayoutResourceName();
- }
-
- /**
- * Returns the layout resource url of the current layout
- *
- * @return
- */
- /*
- public String getMe() {
- GraphicalEditorPart graphicalEditor = getGraphicalEditor();
- IFile editedFile = graphicalEditor.getEditedFile();
- return editedFile.getProjectRelativePath().toOSString();
- }
- */
-
- /**
- * Show the XML element corresponding to the given {@link CanvasViewInfo} (unless it's
- * a root).
- *
- * @param vi The clicked {@link CanvasViewInfo} whose underlying XML element we want
- * to view
- */
- private void showXml(CanvasViewInfo vi) {
- // Warp to the text editor and show the corresponding XML for the
- // double-clicked widget
- if (vi.isRoot()) {
- return;
- }
-
- Node xmlNode = vi.getXmlNode();
- if (xmlNode != null) {
- boolean found = mEditorDelegate.getEditor().show(xmlNode);
- if (!found) {
- getDisplay().beep();
- }
- }
- }
-
- //---------------
-
- /**
- * Helper to create the drag source for the given control.
- * <p/>
- * This is static with package-access so that {@link OutlinePage} can also
- * create an exact copy of the source with the same attributes.
- */
- /* package */static DragSource createDragSource(Control control) {
- DragSource source = new DragSource(control, DND.DROP_COPY | DND.DROP_MOVE);
- source.setTransfer(new Transfer[] {
- TextTransfer.getInstance(),
- SimpleXmlTransfer.getInstance()
- });
- return source;
- }
-
- /**
- * Helper to create the drop target for the given control.
- */
- private static DropTarget createDropTarget(Control control) {
- DropTarget dropTarget = new DropTarget(
- control, DND.DROP_COPY | DND.DROP_MOVE | DND.DROP_DEFAULT);
- dropTarget.setTransfer(new Transfer[] {
- SimpleXmlTransfer.getInstance()
- });
- return dropTarget;
- }
-
- //---------------
-
- /**
- * Invoked by the constructor to add our cut/copy/paste/delete/select-all
- * handlers in the global action handlers of this editor's site.
- * <p/>
- * This will enable the menu items under the global Edit menu and make them
- * invoke our actions as needed. As a benefit, the corresponding shortcut
- * accelerators will do what one would expect.
- */
- private void setupGlobalActionHandlers() {
- mCutAction = new Action() {
- @Override
- public void run() {
- mClipboardSupport.cutSelectionToClipboard(mSelectionManager.getSnapshot());
- updateMenuActionState();
- }
- };
-
- copyActionAttributes(mCutAction, ActionFactory.CUT);
-
- mCopyAction = new Action() {
- @Override
- public void run() {
- mClipboardSupport.copySelectionToClipboard(mSelectionManager.getSnapshot());
- updateMenuActionState();
- }
- };
-
- copyActionAttributes(mCopyAction, ActionFactory.COPY);
-
- mPasteAction = new Action() {
- @Override
- public void run() {
- mClipboardSupport.pasteSelection(mSelectionManager.getSnapshot());
- updateMenuActionState();
- }
- };
-
- copyActionAttributes(mPasteAction, ActionFactory.PASTE);
-
- mDeleteAction = new Action() {
- @Override
- public void run() {
- mClipboardSupport.deleteSelection(
- getDeleteLabel(),
- mSelectionManager.getSnapshot());
- }
- };
-
- copyActionAttributes(mDeleteAction, ActionFactory.DELETE);
-
- mSelectAllAction = new Action() {
- @Override
- public void run() {
- GraphicalEditorPart graphicalEditor = getEditorDelegate().getGraphicalEditor();
- StyledText errorLabel = graphicalEditor.getErrorLabel();
- if (errorLabel.isFocusControl()) {
- errorLabel.selectAll();
- return;
- }
-
- mSelectionManager.selectAll();
- }
- };
-
- copyActionAttributes(mSelectAllAction, ActionFactory.SELECT_ALL);
- }
-
- String getCutLabel() {
- return mCutAction.getText();
- }
-
- String getDeleteLabel() {
- // verb "Delete" from the DELETE action's title
- return mDeleteAction.getText();
- }
-
- /**
- * Updates menu actions that depends on the selection.
- */
- void updateMenuActionState() {
- List<SelectionItem> selections = getSelectionManager().getSelections();
- boolean hasSelection = !selections.isEmpty();
- if (hasSelection && selections.size() == 1 && selections.get(0).isRoot()) {
- hasSelection = false;
- }
-
- StyledText errorLabel = getGraphicalEditor().getErrorLabel();
- mCutAction.setEnabled(hasSelection);
- mCopyAction.setEnabled(hasSelection || errorLabel.getSelectionCount() > 0);
- mDeleteAction.setEnabled(hasSelection);
- // Select All should *always* be selectable, regardless of whether anything
- // is currently selected.
- mSelectAllAction.setEnabled(true);
-
- // The paste operation is only available if we can paste our custom type.
- // We do not currently support pasting random text (e.g. XML). Maybe later.
- boolean hasSxt = mClipboardSupport.hasSxtOnClipboard();
- mPasteAction.setEnabled(hasSxt);
- }
-
- /**
- * Update the actions when this editor is activated
- *
- * @param bars the action bar for this canvas
- */
- public void updateGlobalActions(@NonNull IActionBars bars) {
- updateMenuActionState();
-
- ITextEditor editor = mEditorDelegate.getEditor().getStructuredTextEditor();
- boolean graphical = getEditorDelegate().getEditor().getActivePage() == 0;
- if (graphical) {
- bars.setGlobalActionHandler(ActionFactory.CUT.getId(), mCutAction);
- bars.setGlobalActionHandler(ActionFactory.COPY.getId(), mCopyAction);
- bars.setGlobalActionHandler(ActionFactory.PASTE.getId(), mPasteAction);
- bars.setGlobalActionHandler(ActionFactory.DELETE.getId(), mDeleteAction);
- bars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(), mSelectAllAction);
-
- // Delegate the Undo and Redo actions to the text editor ones, but wrap them
- // such that we run lint to update the results on the current page (this is
- // normally done on each editor operation that goes through
- // {@link AndroidXmlEditor#wrapUndoEditXmlModel}, but not undo/redo)
- if (mUndoAction == null) {
- IAction undoAction = editor.getAction(ActionFactory.UNDO.getId());
- mUndoAction = new LintEditAction(undoAction, getEditorDelegate().getEditor());
- }
- bars.setGlobalActionHandler(ActionFactory.UNDO.getId(), mUndoAction);
- if (mRedoAction == null) {
- IAction redoAction = editor.getAction(ActionFactory.REDO.getId());
- mRedoAction = new LintEditAction(redoAction, getEditorDelegate().getEditor());
- }
- bars.setGlobalActionHandler(ActionFactory.REDO.getId(), mRedoAction);
- } else {
- bars.setGlobalActionHandler(ActionFactory.CUT.getId(),
- editor.getAction(ActionFactory.CUT.getId()));
- bars.setGlobalActionHandler(ActionFactory.COPY.getId(),
- editor.getAction(ActionFactory.COPY.getId()));
- bars.setGlobalActionHandler(ActionFactory.PASTE.getId(),
- editor.getAction(ActionFactory.PASTE.getId()));
- bars.setGlobalActionHandler(ActionFactory.DELETE.getId(),
- editor.getAction(ActionFactory.DELETE.getId()));
- bars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(),
- editor.getAction(ActionFactory.SELECT_ALL.getId()));
- bars.setGlobalActionHandler(ActionFactory.UNDO.getId(),
- editor.getAction(ActionFactory.UNDO.getId()));
- bars.setGlobalActionHandler(ActionFactory.REDO.getId(),
- editor.getAction(ActionFactory.REDO.getId()));
- }
-
- bars.updateActionBars();
- }
-
- /**
- * Helper for {@link #setupGlobalActionHandlers()}.
- * Copies the action attributes form the given {@link ActionFactory}'s action to
- * our action.
- * <p/>
- * {@link ActionFactory} provides access to the standard global actions in Eclipse.
- * <p/>
- * This allows us to grab the standard labels and icons for the
- * global actions such as copy, cut, paste, delete and select-all.
- */
- private void copyActionAttributes(Action action, ActionFactory factory) {
- IWorkbenchAction wa = factory.create(
- mEditorDelegate.getEditor().getEditorSite().getWorkbenchWindow());
- action.setId(wa.getId());
- action.setText(wa.getText());
- action.setEnabled(wa.isEnabled());
- action.setDescription(wa.getDescription());
- action.setToolTipText(wa.getToolTipText());
- action.setAccelerator(wa.getAccelerator());
- action.setActionDefinitionId(wa.getActionDefinitionId());
- action.setImageDescriptor(wa.getImageDescriptor());
- action.setHoverImageDescriptor(wa.getHoverImageDescriptor());
- action.setDisabledImageDescriptor(wa.getDisabledImageDescriptor());
- action.setHelpListener(wa.getHelpListener());
- }
-
- /**
- * Creates the context menu for the canvas. This is called once from the canvas' constructor.
- * <p/>
- * The menu has a static part with actions that are always available such as
- * copy, cut, paste and show in > explorer. This is created by
- * {@link #setupStaticMenuActions(IMenuManager)}.
- * <p/>
- * There's also a dynamic part that is populated by the rules of the
- * selected elements, created by {@link DynamicContextMenu}.
- */
- @SuppressWarnings("unused")
- private void createContextMenu() {
-
- // This manager is the root of the context menu.
- mMenuManager = new MenuManager() {
- @Override
- public boolean isDynamic() {
- return true;
- }
- };
-
- // Fill the menu manager with the static & dynamic actions
- setupStaticMenuActions(mMenuManager);
- new DynamicContextMenu(mEditorDelegate, this, mMenuManager);
- Menu menu = mMenuManager.createContextMenu(this);
- setMenu(menu);
-
- // Add listener to detect when the menu is about to be posted, such that
- // we can sync the selection. Without this, you can right click on something
- // in the canvas which is NOT selected, and the context menu will show items related
- // to the selection, NOT the item you clicked on!!
- addMenuDetectListener(new MenuDetectListener() {
- @Override
- public void menuDetected(MenuDetectEvent e) {
- mSelectionManager.menuClick(e);
- }
- });
- }
-
- /**
- * Invoked by {@link #createContextMenu()} to create our *static* context menu once.
- * <p/>
- * The content of the menu itself does not change. However the state of the
- * various items is controlled by their associated actions.
- * <p/>
- * For cut/copy/paste/delete/select-all, we explicitly reuse the actions
- * created by {@link #setupGlobalActionHandlers()}, so this method must be
- * invoked after that one.
- */
- private void setupStaticMenuActions(IMenuManager manager) {
- manager.removeAll();
-
- manager.add(new SelectionManager.SelectionMenu(getGraphicalEditor()));
- manager.add(new Separator());
- manager.add(mCutAction);
- manager.add(mCopyAction);
- manager.add(mPasteAction);
- manager.add(new Separator());
- manager.add(mDeleteAction);
- manager.add(new Separator());
- manager.add(new PlayAnimationMenu(this));
- manager.add(new ExportScreenshotAction(this));
- manager.add(new Separator());
-
- // Group "Show Included In" and "Show In" together
- manager.add(new ShowWithinMenu(mEditorDelegate));
-
- // Create a "Show In" sub-menu and automatically populate it using standard
- // actions contributed by the workbench.
- String showInLabel = IDEWorkbenchMessages.Workbench_showIn;
- MenuManager showInSubMenu = new MenuManager(showInLabel);
- showInSubMenu.add(
- ContributionItemFactory.VIEWS_SHOW_IN.create(
- mEditorDelegate.getEditor().getSite().getWorkbenchWindow()));
- manager.add(showInSubMenu);
- }
-
- /**
- * Deletes the selection. Equivalent to pressing the Delete key.
- */
- void delete() {
- mDeleteAction.run();
- }
-
- /**
- * Add new root in an existing empty XML layout.
- * <p/>
- * In case of error (unknown FQCN, document not empty), silently do nothing.
- * In case of success, the new element will have some default attributes set
- * (xmlns:android, layout_width and height). The edit is wrapped in a proper
- * undo.
- * <p/>
- * This is invoked by
- * {@link MoveGesture#drop(org.eclipse.swt.dnd.DropTargetEvent)}.
- *
- * @param root A non-null descriptor of the root element to create.
- */
- void createDocumentRoot(final @NonNull SimpleElement root) {
- String rootFqcn = root.getFqcn();
-
- // Need a valid empty document to create the new root
- final UiDocumentNode uiDoc = mEditorDelegate.getUiRootNode();
- if (uiDoc == null || uiDoc.getUiChildren().size() > 0) {
- debugPrintf("Failed to create document root for %1$s: document is not empty",
- rootFqcn);
- return;
- }
-
- // Find the view descriptor matching our FQCN
- final ViewElementDescriptor viewDesc = mEditorDelegate.getFqcnViewDescriptor(rootFqcn);
- if (viewDesc == null) {
- // TODO this could happen if dropping a custom view not known in this project
- debugPrintf("Failed to add document root, unknown FQCN %1$s", rootFqcn);
- return;
- }
-
- // Get the last segment of the FQCN for the undo title
- String title = rootFqcn;
- int pos = title.lastIndexOf('.');
- if (pos > 0 && pos < title.length() - 1) {
- title = title.substring(pos + 1);
- }
- title = String.format("Create root %1$s in document", title);
-
- mEditorDelegate.getEditor().wrapUndoEditXmlModel(title, new Runnable() {
- @Override
- public void run() {
- UiElementNode uiNew = uiDoc.appendNewUiChild(viewDesc);
-
- // A root node requires the Android XMLNS
- uiNew.setAttributeValue(
- SdkConstants.ANDROID_NS_NAME,
- SdkConstants.XMLNS_URI,
- SdkConstants.NS_RESOURCES,
- true /*override*/);
-
- IDragAttribute[] attributes = root.getAttributes();
- if (attributes != null) {
- for (IDragAttribute attribute : attributes) {
- String uri = attribute.getUri();
- String name = attribute.getName();
- String value = attribute.getValue();
- uiNew.setAttributeValue(name, uri, value, false /*override*/);
- }
- }
-
- // Adjust the attributes
- DescriptorsUtils.setDefaultLayoutAttributes(uiNew, false /*updateLayout*/);
-
- uiNew.createXmlNode();
- }
- });
- }
-
- /**
- * Returns the insets associated with views of the given fully qualified name, for the
- * current theme and screen type.
- *
- * @param fqcn the fully qualified name to the widget type
- * @return the insets, or null if unknown
- */
- public Margins getInsets(String fqcn) {
- if (ViewMetadataRepository.INSETS_SUPPORTED) {
- ConfigurationChooser configComposite = getGraphicalEditor().getConfigurationChooser();
- String theme = configComposite.getThemeName();
- Density density = configComposite.getConfiguration().getDensity();
- return ViewMetadataRepository.getInsets(fqcn, density, theme);
- } else {
- return null;
- }
- }
-
- private void debugPrintf(String message, Object... params) {
- if (DEBUG) {
- AdtPlugin.printToConsole("Canvas", String.format(message, params));
- }
- }
-
- /** The associated editor has been deactivated */
- public void deactivated() {
- // Force the tooltip to be hidden. If you switch from the layout editor
- // to a Java editor with the keyboard, the tooltip can stay open.
- if (mLintTooltipManager != null) {
- mLintTooltipManager.hide();
- }
- }
-
- /** @see #setPreview(RenderPreview) */
- private RenderPreview mPreview;
-
- /**
- * Sets the {@link RenderPreview} associated with the currently rendering
- * configuration.
- * <p>
- * A {@link RenderPreview} has various additional state beyond its rendering,
- * such as its display name (which can be edited by the user). When you click on
- * previews, the layout editor switches to show the given configuration preview.
- * The preview is then no longer shown in the list of previews and is instead rendered
- * in the main editor. However, when you then switch away to some other preview, we
- * want to be able to restore the preview with all its state.
- *
- * @param preview the preview associated with the current canvas
- */
- public void setPreview(@Nullable RenderPreview preview) {
- mPreview = preview;
- }
-
- /**
- * Returns the {@link RenderPreview} associated with this layout canvas.
- *
- * @see #setPreview(RenderPreview)
- * @return the {@link RenderPreview}
- */
- @Nullable
- public RenderPreview getPreview() {
- return mPreview;
- }
-
- /** Ensures that the configuration previews are up to date for this canvas */
- public void syncPreviewMode() {
- if (mImageOverlay != null && mImageOverlay.getImage() != null &&
- getGraphicalEditor().getConfigurationChooser().getResources() != null) {
- if (mPreviewManager.recomputePreviews(false)) {
- // Zoom when syncing modes
- mZoomFitNextImage = true;
- ensureZoomed();
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutCanvasViewer.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutCanvasViewer.java
deleted file mode 100644
index e349a1cb0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutCanvasViewer.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.RulesEngine;
-
-import org.eclipse.core.runtime.ListenerList;
-import org.eclipse.jface.util.SafeRunnable;
-import org.eclipse.jface.viewers.IPostSelectionProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.TreePath;
-import org.eclipse.jface.viewers.TreeSelection;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-
-
-/**
- * JFace {@link Viewer} wrapper around {@link LayoutCanvas}.
- * <p/>
- * The viewer is owned by {@link GraphicalEditorPart}.
- * <p/>
- * The viewer is an {@link ISelectionProvider} instance and is set as the
- * site's main {@link ISelectionProvider} by the editor part. Consequently
- * canvas' selection changes are broadcasted to anyone listening, which includes
- * the part itself as well as the associated outline and property sheet pages.
- */
-class LayoutCanvasViewer extends Viewer implements IPostSelectionProvider {
-
- private LayoutCanvas mCanvas;
- private final LayoutEditorDelegate mEditorDelegate;
-
- public LayoutCanvasViewer(LayoutEditorDelegate editorDelegate,
- RulesEngine rulesEngine,
- Composite parent,
- int style) {
- mEditorDelegate = editorDelegate;
- mCanvas = new LayoutCanvas(editorDelegate, rulesEngine, parent, style);
-
- mCanvas.getSelectionManager().addSelectionChangedListener(mSelectionListener);
- }
-
- private ISelectionChangedListener mSelectionListener = new ISelectionChangedListener() {
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- fireSelectionChanged(event);
- firePostSelectionChanged(event);
- }
- };
-
- @Override
- public Control getControl() {
- return mCanvas;
- }
-
- /**
- * Returns the underlying {@link LayoutCanvas}.
- * This is the same control as returned by {@link #getControl()} but clients
- * have it already casted in the right type.
- * <p/>
- * This can never be null.
- * @return The underlying {@link LayoutCanvas}.
- */
- public LayoutCanvas getCanvas() {
- return mCanvas;
- }
-
- /**
- * Returns the current layout editor's input.
- */
- @Override
- public Object getInput() {
- return mEditorDelegate.getEditor().getEditorInput();
- }
-
- /**
- * Unused. We don't support switching the input.
- */
- @Override
- public void setInput(Object input) {
- }
-
- /**
- * Returns a new {@link TreeSelection} where each {@link TreePath} item
- * is a {@link CanvasViewInfo}.
- */
- @Override
- public ISelection getSelection() {
- return mCanvas.getSelectionManager().getSelection();
- }
-
- /**
- * Sets a new selection. <code>reveal</code> is ignored right now.
- * <p/>
- * The selection can be null, which is interpreted as an empty selection.
- */
- @Override
- public void setSelection(ISelection selection, boolean reveal) {
- if (mEditorDelegate.getEditor().getIgnoreXmlUpdate()) {
- return;
- }
- mCanvas.getSelectionManager().setSelection(selection);
- }
-
- /** Unused. Refreshing is done solely by the owning {@link LayoutEditorDelegate}. */
- @Override
- public void refresh() {
- // ignore
- }
-
- public void dispose() {
- if (mSelectionListener != null) {
- mCanvas.getSelectionManager().removeSelectionChangedListener(mSelectionListener);
- }
- if (mCanvas != null) {
- mCanvas.dispose();
- mCanvas = null;
- }
- }
-
- // ---- Implements IPostSelectionProvider ----
-
- private ListenerList mPostChangedListeners = new ListenerList();
-
- @Override
- public void addPostSelectionChangedListener(ISelectionChangedListener listener) {
- mPostChangedListeners.add(listener);
- }
-
- @Override
- public void removePostSelectionChangedListener(ISelectionChangedListener listener) {
- mPostChangedListeners.remove(listener);
- }
-
- protected void firePostSelectionChanged(final SelectionChangedEvent event) {
- Object[] listeners = mPostChangedListeners.getListeners();
- for (int i = 0; i < listeners.length; i++) {
- final ISelectionChangedListener l = (ISelectionChangedListener) listeners[i];
- SafeRunnable.run(new SafeRunnable() {
- @Override
- public void run() {
- l.selectionChanged(event);
- }
- });
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutMetadata.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutMetadata.java
deleted file mode 100644
index b79e3b0a1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutMetadata.java
+++ /dev/null
@@ -1,413 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.SdkConstants.ANDROID_LAYOUT_RESOURCE_PREFIX;
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_NUM_COLUMNS;
-import static com.android.SdkConstants.EXPANDABLE_LIST_VIEW;
-import static com.android.SdkConstants.GRID_VIEW;
-import static com.android.SdkConstants.LAYOUT_RESOURCE_PREFIX;
-import static com.android.SdkConstants.TOOLS_URI;
-import static com.android.SdkConstants.VALUE_AUTO_FIT;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.rendering.api.AdapterBinding;
-import com.android.ide.common.rendering.api.DataBindingItem;
-import com.android.ide.common.rendering.api.ResourceReference;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.layout.ProjectCallback;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.progress.WorkbenchJob;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xmlpull.v1.XmlPullParser;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Design-time metadata lookup for layouts, such as fragment and AdapterView bindings.
- */
-public class LayoutMetadata {
- /** The default layout to use for list items in expandable list views */
- public static final String DEFAULT_EXPANDABLE_LIST_ITEM = "simple_expandable_list_item_2"; //$NON-NLS-1$
- /** The default layout to use for list items in plain list views */
- public static final String DEFAULT_LIST_ITEM = "simple_list_item_2"; //$NON-NLS-1$
- /** The default layout to use for list items in spinners */
- public static final String DEFAULT_SPINNER_ITEM = "simple_spinner_item"; //$NON-NLS-1$
-
- /** The string to start metadata comments with */
- private static final String COMMENT_PROLOGUE = " Preview: ";
- /** The property key, included in comments, which references a list item layout */
- public static final String KEY_LV_ITEM = "listitem"; //$NON-NLS-1$
- /** The property key, included in comments, which references a list header layout */
- public static final String KEY_LV_HEADER = "listheader"; //$NON-NLS-1$
- /** The property key, included in comments, which references a list footer layout */
- public static final String KEY_LV_FOOTER = "listfooter"; //$NON-NLS-1$
- /** The property key, included in comments, which references a fragment layout to show */
- public static final String KEY_FRAGMENT_LAYOUT = "layout"; //$NON-NLS-1$
- // NOTE: If you add additional keys related to resources, make sure you update the
- // ResourceRenameParticipant
-
- /** Utility class, do not create instances */
- private LayoutMetadata() {
- }
-
- /**
- * Returns the given property specified in the <b>current</b> element being
- * processed by the given pull parser.
- *
- * @param parser the pull parser, which must be in the middle of processing
- * the target element
- * @param name the property name to look up
- * @return the property value, or null if not defined
- */
- @Nullable
- public static String getProperty(@NonNull XmlPullParser parser, @NonNull String name) {
- String value = parser.getAttributeValue(TOOLS_URI, name);
- if (value != null && value.isEmpty()) {
- value = null;
- }
-
- return value;
- }
-
- /**
- * Clears the old metadata from the given node
- *
- * @param node the XML node to associate metadata with
- * @deprecated this method clears metadata using the old comment-based style;
- * should only be used for migration at this point
- */
- @Deprecated
- public static void clearLegacyComment(Node node) {
- NodeList children = node.getChildNodes();
- for (int i = 0, n = children.getLength(); i < n; i++) {
- Node child = children.item(i);
- if (child.getNodeType() == Node.COMMENT_NODE) {
- String text = child.getNodeValue();
- if (text.startsWith(COMMENT_PROLOGUE)) {
- Node commentNode = child;
- // Remove the comment, along with surrounding whitespace if applicable
- Node previous = commentNode.getPreviousSibling();
- if (previous != null && previous.getNodeType() == Node.TEXT_NODE) {
- if (previous.getNodeValue().trim().length() == 0) {
- node.removeChild(previous);
- }
- }
- node.removeChild(commentNode);
- Node first = node.getFirstChild();
- if (first != null && first.getNextSibling() == null
- && first.getNodeType() == Node.TEXT_NODE) {
- if (first.getNodeValue().trim().length() == 0) {
- node.removeChild(first);
- }
- }
- }
- }
- }
- }
-
- /**
- * Returns the given property of the given DOM node, or null
- *
- * @param node the XML node to associate metadata with
- * @param name the name of the property to look up
- * @return the value stored with the given node and name, or null
- */
- @Nullable
- public static String getProperty(
- @NonNull Node node,
- @NonNull String name) {
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- Element element = (Element) node;
- String value = element.getAttributeNS(TOOLS_URI, name);
- if (value != null && value.isEmpty()) {
- value = null;
- }
-
- return value;
- }
-
- return null;
- }
-
- /**
- * Sets the given property of the given DOM node to a given value, or if null clears
- * the property.
- *
- * @param editor the editor associated with the property
- * @param node the XML node to associate metadata with
- * @param name the name of the property to set
- * @param value the value to store for the given node and name, or null to remove it
- */
- public static void setProperty(
- @NonNull final AndroidXmlEditor editor,
- @NonNull final Node node,
- @NonNull final String name,
- @Nullable final String value) {
- // Clear out the old metadata
- clearLegacyComment(node);
-
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- final Element element = (Element) node;
- final String undoLabel = "Bind View";
- AdtUtils.setToolsAttribute(editor, element, undoLabel, name, value,
- false /*reveal*/, false /*append*/);
-
- // Also apply the same layout to any corresponding elements in other configurations
- // of this layout.
- final IFile file = editor.getInputFile();
- if (file != null) {
- final List<IFile> variations = AdtUtils.getResourceVariations(file, false);
- if (variations.isEmpty()) {
- return;
- }
- Display display = AdtPlugin.getDisplay();
- WorkbenchJob job = new WorkbenchJob(display, "Update alternate views") {
- @Override
- public IStatus runInUIThread(IProgressMonitor monitor) {
- for (IFile variation : variations) {
- if (variation.equals(file)) {
- continue;
- }
- try {
- // If the corresponding file is open in the IDE, use the
- // editor version instead
- if (!AdtPrefs.getPrefs().isSharedLayoutEditor()) {
- if (setPropertyInEditor(undoLabel, variation, element, name,
- value)) {
- return Status.OK_STATUS;
- }
- }
-
- boolean old = editor.getIgnoreXmlUpdate();
- try {
- editor.setIgnoreXmlUpdate(true);
- setPropertyInFile(undoLabel, variation, element, name, value);
- } finally {
- editor.setIgnoreXmlUpdate(old);
- }
- } catch (Exception e) {
- AdtPlugin.log(e, variation.getFullPath().toOSString());
- }
- }
- return Status.OK_STATUS;
- }
-
- };
- job.setSystem(true);
- job.schedule();
- }
- }
- }
-
- private static boolean setPropertyInEditor(
- @NonNull String undoLabel,
- @NonNull IFile variation,
- @NonNull final Element equivalentElement,
- @NonNull final String name,
- @Nullable final String value) {
- Collection<IEditorPart> editors =
- AdtUtils.findEditorsFor(variation, false /*restore*/);
- for (IEditorPart part : editors) {
- AndroidXmlEditor editor = AdtUtils.getXmlEditor(part);
- if (editor != null) {
- Document doc = DomUtilities.getDocument(editor);
- if (doc != null) {
- Element element = DomUtilities.findCorresponding(equivalentElement, doc);
- if (element != null) {
- AdtUtils.setToolsAttribute(editor, element, undoLabel, name,
- value, false /*reveal*/, false /*append*/);
- if (part instanceof GraphicalEditorPart) {
- GraphicalEditorPart g = (GraphicalEditorPart) part;
- g.recomputeLayout();
- g.getCanvasControl().redraw();
- }
- return true;
- }
- }
- }
- }
-
- return false;
- }
-
- private static boolean setPropertyInFile(
- @NonNull String undoLabel,
- @NonNull IFile variation,
- @NonNull final Element element,
- @NonNull final String name,
- @Nullable final String value) {
- Document doc = DomUtilities.getDocument(variation);
- if (doc != null && element.getOwnerDocument() != doc) {
- Element other = DomUtilities.findCorresponding(element, doc);
- if (other != null) {
- AdtUtils.setToolsAttribute(variation, other, undoLabel,
- name, value, false);
-
- return true;
- }
- }
-
- return false;
- }
-
- /** Strips out @layout/ or @android:layout/ from the given layout reference */
- private static String stripLayoutPrefix(String layout) {
- if (layout.startsWith(ANDROID_LAYOUT_RESOURCE_PREFIX)) {
- layout = layout.substring(ANDROID_LAYOUT_RESOURCE_PREFIX.length());
- } else if (layout.startsWith(LAYOUT_RESOURCE_PREFIX)) {
- layout = layout.substring(LAYOUT_RESOURCE_PREFIX.length());
- }
-
- return layout;
- }
-
- /**
- * Creates an {@link AdapterBinding} for the given view object, or null if the user
- * has not yet chosen a target layout to use for the given AdapterView.
- *
- * @param viewObject the view object to create an adapter binding for
- * @param map a map containing tools attribute metadata
- * @return a binding, or null
- */
- @Nullable
- public static AdapterBinding getNodeBinding(
- @Nullable Object viewObject,
- @NonNull Map<String, String> map) {
- String header = map.get(KEY_LV_HEADER);
- String footer = map.get(KEY_LV_FOOTER);
- String layout = map.get(KEY_LV_ITEM);
- if (layout != null || header != null || footer != null) {
- int count = 12;
- return getNodeBinding(viewObject, header, footer, layout, count);
- }
-
- return null;
- }
-
- /**
- * Creates an {@link AdapterBinding} for the given view object, or null if the user
- * has not yet chosen a target layout to use for the given AdapterView.
- *
- * @param viewObject the view object to create an adapter binding for
- * @param uiNode the ui node corresponding to the view object
- * @return a binding, or null
- */
- @Nullable
- public static AdapterBinding getNodeBinding(
- @Nullable Object viewObject,
- @NonNull UiViewElementNode uiNode) {
- Node xmlNode = uiNode.getXmlNode();
-
- String header = getProperty(xmlNode, KEY_LV_HEADER);
- String footer = getProperty(xmlNode, KEY_LV_FOOTER);
- String layout = getProperty(xmlNode, KEY_LV_ITEM);
- if (layout != null || header != null || footer != null) {
- int count = 12;
- // If we're dealing with a grid view, multiply the list item count
- // by the number of columns to ensure we have enough items
- if (xmlNode instanceof Element && xmlNode.getNodeName().endsWith(GRID_VIEW)) {
- Element element = (Element) xmlNode;
- String columns = element.getAttributeNS(ANDROID_URI, ATTR_NUM_COLUMNS);
- int multiplier = 2;
- if (columns != null && columns.length() > 0 &&
- !columns.equals(VALUE_AUTO_FIT)) {
- try {
- int c = Integer.parseInt(columns);
- if (c >= 1 && c <= 10) {
- multiplier = c;
- }
- } catch (NumberFormatException nufe) {
- // some unexpected numColumns value: just stick with 2 columns for
- // preview purposes
- }
- }
- count *= multiplier;
- }
-
- return getNodeBinding(viewObject, header, footer, layout, count);
- }
-
- return null;
- }
-
- private static AdapterBinding getNodeBinding(Object viewObject,
- String header, String footer, String layout, int count) {
- if (layout != null || header != null || footer != null) {
- AdapterBinding binding = new AdapterBinding(count);
-
- if (header != null) {
- boolean isFramework = header.startsWith(ANDROID_LAYOUT_RESOURCE_PREFIX);
- binding.addHeader(new ResourceReference(stripLayoutPrefix(header),
- isFramework));
- }
-
- if (footer != null) {
- boolean isFramework = footer.startsWith(ANDROID_LAYOUT_RESOURCE_PREFIX);
- binding.addFooter(new ResourceReference(stripLayoutPrefix(footer),
- isFramework));
- }
-
- if (layout != null) {
- boolean isFramework = layout.startsWith(ANDROID_LAYOUT_RESOURCE_PREFIX);
- if (isFramework) {
- layout = layout.substring(ANDROID_LAYOUT_RESOURCE_PREFIX.length());
- } else if (layout.startsWith(LAYOUT_RESOURCE_PREFIX)) {
- layout = layout.substring(LAYOUT_RESOURCE_PREFIX.length());
- }
-
- binding.addItem(new DataBindingItem(layout, isFramework, 1));
- } else if (viewObject != null) {
- String listFqcn = ProjectCallback.getListAdapterViewFqcn(viewObject.getClass());
- if (listFqcn != null) {
- if (listFqcn.endsWith(EXPANDABLE_LIST_VIEW)) {
- binding.addItem(
- new DataBindingItem(DEFAULT_EXPANDABLE_LIST_ITEM,
- true /* isFramework */, 1));
- } else {
- binding.addItem(
- new DataBindingItem(DEFAULT_LIST_ITEM,
- true /* isFramework */, 1));
- }
- }
- } else {
- binding.addItem(
- new DataBindingItem(DEFAULT_LIST_ITEM,
- true /* isFramework */, 1));
- }
- return binding;
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutPoint.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutPoint.java
deleted file mode 100644
index 818b2c4ef..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutPoint.java
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.ide.common.api.Point;
-
-import org.eclipse.swt.dnd.DragSourceEvent;
-import org.eclipse.swt.dnd.DragSourceListener;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseListener;
-
-/**
- * A {@link LayoutPoint} is a coordinate in the Android canvas (in other words,
- * it may differ from the canvas control mouse coordinate because the canvas may
- * be zoomed and scrolled.)
- */
-public final class LayoutPoint {
- /** Containing canvas which the point is relative to. */
- private final LayoutCanvas mCanvas;
-
- /** The X coordinate of the canvas coordinate. */
- public final int x;
-
- /** The Y coordinate of the canvas coordinate. */
- public final int y;
-
- /**
- * Constructs a new {@link LayoutPoint} from the given event. The event
- * must be from a {@link MouseListener} associated with the
- * {@link LayoutCanvas} such that the {@link MouseEvent#x} and
- * {@link MouseEvent#y} fields are relative to the canvas.
- *
- * @param canvas The {@link LayoutCanvas} this point is within.
- * @param event The mouse event to construct the {@link LayoutPoint}
- * from.
- * @return A {@link LayoutPoint} which corresponds to the given
- * {@link MouseEvent}.
- */
- public static LayoutPoint create(LayoutCanvas canvas, MouseEvent event) {
- // The mouse event coordinates should already be relative to the canvas
- // widget.
- assert event.widget == canvas : event.widget;
- return ControlPoint.create(canvas, event).toLayout();
- }
-
- /**
- * Constructs a new {@link LayoutPoint} from the given event. The event
- * must be from a {@link DragSourceListener} associated with the
- * {@link LayoutCanvas} such that the {@link DragSourceEvent#x} and
- * {@link DragSourceEvent#y} fields are relative to the canvas.
- *
- * @param canvas The {@link LayoutCanvas} this point is within.
- * @param event The mouse event to construct the {@link LayoutPoint}
- * from.
- * @return A {@link LayoutPoint} which corresponds to the given
- * {@link DragSourceEvent}.
- */
- public static LayoutPoint create(LayoutCanvas canvas, DragSourceEvent event) {
- // The drag source event coordinates should already be relative to the
- // canvas widget.
- return ControlPoint.create(canvas, event).toLayout();
- }
-
- /**
- * Constructs a new {@link LayoutPoint} from the given x,y coordinates.
- *
- * @param canvas The {@link LayoutCanvas} this point is within.
- * @param x The mouse event x coordinate relative to the canvas
- * @param y The mouse event x coordinate relative to the canvas
- * @return A {@link LayoutPoint} which corresponds to the given
- * layout coordinates.
- */
- public static LayoutPoint create(LayoutCanvas canvas, int x, int y) {
- return new LayoutPoint(canvas, x, y);
- }
-
- /**
- * Constructs a new {@link LayoutPoint} with the given X and Y coordinates.
- *
- * @param canvas The canvas which contains this coordinate
- * @param x The canvas X coordinate
- * @param y The canvas Y coordinate
- */
- private LayoutPoint(LayoutCanvas canvas, int x, int y) {
- mCanvas = canvas;
- this.x = x;
- this.y = y;
- }
-
- /**
- * Returns the equivalent {@link ControlPoint} to this
- * {@link LayoutPoint}.
- *
- * @return The equivalent {@link ControlPoint} to this
- * {@link LayoutPoint}
- */
- public ControlPoint toControl() {
- int cx = mCanvas.getHorizontalTransform().translate(x);
- int cy = mCanvas.getVerticalTransform().translate(y);
-
- return ControlPoint.create(mCanvas, cx, cy);
- }
-
- /**
- * Returns this {@link LayoutPoint} as a {@link Point}, in the same coordinate space.
- *
- * @return a new {@link Point} in the same coordinate space
- */
- public Point toPoint() {
- return new Point(x, y);
- }
-
- @Override
- public String toString() {
- return "LayoutPoint [x=" + x + ", y=" + y + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + x;
- result = prime * result + y;
- return result;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- LayoutPoint other = (LayoutPoint) obj;
- if (x != other.x)
- return false;
- if (y != other.y)
- return false;
- return true;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutWindowCoordinator.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutWindowCoordinator.java
deleted file mode 100644
index 56b86aa85..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutWindowCoordinator.java
+++ /dev/null
@@ -1,394 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.google.common.collect.Maps;
-
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IEditorReference;
-import org.eclipse.ui.IPartListener2;
-import org.eclipse.ui.IPartService;
-import org.eclipse.ui.IViewReference;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchPartReference;
-import org.eclipse.ui.IWorkbenchWindow;
-
-import java.util.Map;
-
-/**
- * The {@link LayoutWindowCoordinator} keeps track of Eclipse window events (opening, closing,
- * fronting, etc) and uses this information to manage the propertysheet and outline
- * views such that they are always(*) showing:
- * <ul>
- * <li> If the Property Sheet and Outline Eclipse views are showing, it does nothing.
- * "Showing" means "is open", not necessary "is visible", e.g. in a tabbed view
- * there could be a different view on top.
- * <li> If just the outline is showing, then the property sheet is shown in a sashed
- * pane below or to the right of the outline (depending on the dominant dimension
- * of the window).
- * <li> TBD: If just the property sheet is showing, should the outline be showed
- * inside that window? Not yet done.
- * <li> If the outline is *not* showing, then the outline is instead shown
- * <b>inside</b> the editor area, in a right-docked view! This right docked view
- * also includes the property sheet!
- * <li> If the property sheet is not showing (which includes not showing in the outline
- * view as well), then it will be shown inside the editor area, along with the outline
- * which should also be there (since if the outline was showing outside the editor
- * area, the property sheet would have docked there).
- * <li> When the editor is maximized, then all views are temporarily hidden. In this
- * case, the property sheet and outline will show up inside the editor.
- * When the editor view is un-maximized, the view state will return to what it
- * was before.
- * </ul>
- * </p>
- * There is one coordinator per workbench window, shared between all editors in that window.
- * <p>
- * TODO: Rename this class to AdtWindowCoordinator. It is used for more than just layout
- * window coordination now. For example, it's also used to dispatch {@code activated()} and
- * {@code deactivated()} events to all the XML editors, to ensure that key bindings are
- * properly dispatched to the right editors in Eclipse 4.x.
- */
-public class LayoutWindowCoordinator implements IPartListener2 {
- static final String PROPERTY_SHEET_PART_ID = "org.eclipse.ui.views.PropertySheet"; //$NON-NLS-1$
- static final String OUTLINE_PART_ID = "org.eclipse.ui.views.ContentOutline"; //$NON-NLS-1$
- /** The workbench window */
- private final IWorkbenchWindow mWindow;
- /** Is the Eclipse property sheet ViewPart open? */
- private boolean mPropertiesOpen;
- /** Is the Eclipse outline ViewPart open? */
- private boolean mOutlineOpen;
- /** Is the editor maximized? */
- private boolean mEditorMaximized;
- /**
- * Has the coordinator been initialized? We may have to delay initialization
- * and perform it lazily if the workbench window does not have an active
- * page when the coordinator is first started
- */
- private boolean mInitialized;
-
- /** Map from workbench windows to each layout window coordinator instance for that window */
- private static Map<IWorkbenchWindow, LayoutWindowCoordinator> sCoordinators =
- Maps.newHashMapWithExpectedSize(2);
-
- /**
- * Returns the coordinator for the given window.
- *
- * @param window the associated window
- * @param create whether to create the window if it does not already exist
- * @return the new coordinator, never null if {@code create} is true
- */
- @Nullable
- public static LayoutWindowCoordinator get(@NonNull IWorkbenchWindow window, boolean create) {
- synchronized (LayoutWindowCoordinator.class){
- LayoutWindowCoordinator coordinator = sCoordinators.get(window);
- if (coordinator == null && create) {
- coordinator = new LayoutWindowCoordinator(window);
-
- IPartService service = window.getPartService();
- if (service != null) {
- // What if the editor part is *already* open? How do I deal with that?
- service.addPartListener(coordinator);
- }
-
- sCoordinators.put(window, coordinator);
- }
-
- return coordinator;
- }
- }
-
-
- /** Disposes this coordinator (when a window is closed) */
- public void dispose() {
- IPartService service = mWindow.getPartService();
- if (service != null) {
- service.removePartListener(this);
- }
-
- synchronized (LayoutWindowCoordinator.class){
- sCoordinators.remove(mWindow);
- }
- }
-
- /**
- * Returns true if the main editor window is maximized
- *
- * @return true if the main editor window is maximized
- */
- public boolean isEditorMaximized() {
- return mEditorMaximized;
- }
-
- private LayoutWindowCoordinator(@NonNull IWorkbenchWindow window) {
- mWindow = window;
-
- initialize();
- }
-
- private void initialize() {
- if (mInitialized) {
- return;
- }
-
- IWorkbenchPage activePage = mWindow.getActivePage();
- if (activePage == null) {
- return;
- }
-
- mInitialized = true;
-
- // Look up current state of the properties and outline windows (in case
- // they have already been opened before we added our part listener)
- IViewReference ref = findPropertySheetView(activePage);
- if (ref != null) {
- IWorkbenchPart part = ref.getPart(false /*restore*/);
- if (activePage.isPartVisible(part)) {
- mPropertiesOpen = true;
- }
- }
- ref = findOutlineView(activePage);
- if (ref != null) {
- IWorkbenchPart part = ref.getPart(false /*restore*/);
- if (activePage.isPartVisible(part)) {
- mOutlineOpen = true;
- }
- }
- if (!syncMaximizedState(activePage)) {
- syncActive();
- }
- }
-
- static IViewReference findPropertySheetView(IWorkbenchPage activePage) {
- return activePage.findViewReference(PROPERTY_SHEET_PART_ID);
- }
-
- static IViewReference findOutlineView(IWorkbenchPage activePage) {
- return activePage.findViewReference(OUTLINE_PART_ID);
- }
-
- /**
- * Checks the maximized state of the page and updates internal state if
- * necessary.
- * <p>
- * This is used in Eclipse 4.x, where the {@link IPartListener2} does not
- * fire {@link IPartListener2#partHidden(IWorkbenchPartReference)} when the
- * editor is maximized anymore (see issue
- * https://bugs.eclipse.org/bugs/show_bug.cgi?id=382120 for details).
- * Instead, the layout editor listens for resize events, and upon resize it
- * looks up the part state and calls this method to ensure that the right
- * maximized state is known to the layout coordinator.
- *
- * @param page the active workbench page
- * @return true if the state changed, false otherwise
- */
- public boolean syncMaximizedState(IWorkbenchPage page) {
- boolean maximized = isPageZoomed(page);
- if (mEditorMaximized != maximized) {
- mEditorMaximized = maximized;
- syncActive();
- return true;
- }
- return false;
- }
-
- private boolean isPageZoomed(IWorkbenchPage page) {
- IWorkbenchPartReference reference = page.getActivePartReference();
- if (reference != null && reference instanceof IEditorReference) {
- int state = page.getPartState(reference);
- boolean maximized = (state & IWorkbenchPage.STATE_MAXIMIZED) != 0;
- return maximized;
- }
-
- // If the active reference isn't the editor, then the editor can't be maximized
- return false;
- }
-
- /**
- * Syncs the given editor's view state such that the property sheet and or
- * outline are shown or hidden according to the visibility of the global
- * outline and property sheet views.
- * <p>
- * This is typically done when a layout editor is fronted. For view updates
- * when the view is already showing, the {@link LayoutWindowCoordinator}
- * will automatically handle the current fronted window.
- *
- * @param editor the editor to sync
- */
- private void sync(@Nullable GraphicalEditorPart editor) {
- if (editor == null) {
- return;
- }
- if (mEditorMaximized) {
- editor.showStructureViews(true /*outline*/, true /*properties*/, true /*layout*/);
- } else if (mOutlineOpen) {
- editor.showStructureViews(false /*outline*/, false /*properties*/, true /*layout*/);
- editor.getCanvasControl().getOutlinePage().setShowPropertySheet(!mPropertiesOpen);
- } else {
- editor.showStructureViews(true /*outline*/, !mPropertiesOpen /*properties*/,
- true /*layout*/);
- }
- }
-
- private void sync(IWorkbenchPart part) {
- if (part instanceof AndroidXmlEditor) {
- LayoutEditorDelegate editor = LayoutEditorDelegate.fromEditor((IEditorPart) part);
- if (editor != null) {
- sync(editor.getGraphicalEditor());
- }
- }
- }
-
- private void syncActive() {
- IWorkbenchPage activePage = mWindow.getActivePage();
- if (activePage != null) {
- IEditorPart editor = activePage.getActiveEditor();
- sync(editor);
- }
- }
-
- private void propertySheetClosed() {
- mPropertiesOpen = false;
- syncActive();
- }
-
- private void propertySheetOpened() {
- mPropertiesOpen = true;
- syncActive();
- }
-
- private void outlineClosed() {
- mOutlineOpen = false;
- syncActive();
- }
-
- private void outlineOpened() {
- mOutlineOpen = true;
- syncActive();
- }
-
- // ---- Implements IPartListener2 ----
-
- @Override
- public void partOpened(IWorkbenchPartReference partRef) {
- // We ignore partOpened() and partClosed() because these methods are only
- // called when a view is opened in the first perspective, and closed in the
- // last perspective. The outline is typically used in multiple perspectives,
- // so closing it in the Java perspective does *not* fire a partClosed event.
- // There is no notification for "part closed in perspective" (see issue
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=54559 for details).
- // However, the workaround we can use is to listen to partVisible() and
- // partHidden(). These will be called more often than we'd like (e.g.
- // when the tab order causes a view to be obscured), however, we can use
- // the workaround of looking up IWorkbenchPage.findViewReference(id) after
- // partHidden(), which will return null if the view is closed in the current
- // perspective. For partOpened, we simply look in partVisible() for whether
- // our flags tracking the view state have been initialized already.
- }
-
- @Override
- public void partClosed(IWorkbenchPartReference partRef) {
- // partClosed() doesn't get called when a window is closed unless it has
- // been closed in *all* perspectives. See partOpened() for more.
- }
-
- @Override
- public void partHidden(IWorkbenchPartReference partRef) {
- IWorkbenchPage activePage = mWindow.getActivePage();
- if (activePage == null) {
- return;
- }
- initialize();
-
- // See if this looks like the window was closed in this workspace
- // See partOpened() for an explanation.
- String id = partRef.getId();
- if (PROPERTY_SHEET_PART_ID.equals(id)) {
- if (activePage.findViewReference(id) == null) {
- propertySheetClosed();
- return;
- }
- } else if (OUTLINE_PART_ID.equals(id)) {
- if (activePage.findViewReference(id) == null) {
- outlineClosed();
- return;
- }
- }
-
- // Does this look like a window getting maximized?
- syncMaximizedState(activePage);
- }
-
- @Override
- public void partVisible(IWorkbenchPartReference partRef) {
- IWorkbenchPage activePage = mWindow.getActivePage();
- if (activePage == null) {
- return;
- }
- initialize();
-
- String id = partRef.getId();
- if (mEditorMaximized) {
- // Return to their non-maximized state
- mEditorMaximized = false;
- syncActive();
- }
-
- IWorkbenchPart part = partRef.getPart(false /*restore*/);
- sync(part);
-
- // See partOpened() for an explanation
- if (PROPERTY_SHEET_PART_ID.equals(id)) {
- if (!mPropertiesOpen) {
- propertySheetOpened();
- assert mPropertiesOpen;
- }
- } else if (OUTLINE_PART_ID.equals(id)) {
- if (!mOutlineOpen) {
- outlineOpened();
- assert mOutlineOpen;
- }
- }
- }
-
- @Override
- public void partInputChanged(IWorkbenchPartReference partRef) {
- }
-
- @Override
- public void partActivated(IWorkbenchPartReference partRef) {
- IWorkbenchPart part = partRef.getPart(false);
- if (part instanceof AndroidXmlEditor) {
- ((AndroidXmlEditor)part).activated();
- }
- }
-
- @Override
- public void partBroughtToTop(IWorkbenchPartReference partRef) {
- }
-
- @Override
- public void partDeactivated(IWorkbenchPartReference partRef) {
- IWorkbenchPart part = partRef.getPart(false);
- if (part instanceof AndroidXmlEditor) {
- ((AndroidXmlEditor)part).deactivated();
- }
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LintOverlay.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LintOverlay.java
deleted file mode 100644
index ca74493e8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LintOverlay.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.google.common.collect.Lists;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.ImageData;
-import org.eclipse.swt.graphics.Rectangle;
-import org.w3c.dom.Node;
-
-import java.util.Collection;
-
-/**
- * The {@link LintOverlay} paints an icon over each view that contains at least one
- * lint error (unless the view is smaller than the icon)
- */
-public class LintOverlay extends Overlay {
- /** Approximate size of lint overlay icons */
- static final int ICON_SIZE = 8;
- /** Alpha to draw lint overlay icons with */
- private static final int ALPHA = 192;
-
- private final LayoutCanvas mCanvas;
- private Image mWarningImage;
- private Image mErrorImage;
-
- /**
- * Constructs a new {@link LintOverlay}
- *
- * @param canvas the associated canvas
- */
- public LintOverlay(LayoutCanvas canvas) {
- mCanvas = canvas;
- }
-
- @Override
- public boolean isHiding() {
- return super.isHiding() || !AdtPrefs.getPrefs().isLintOnSave();
- }
-
- @Override
- public void paint(GC gc) {
- LayoutEditorDelegate editor = mCanvas.getEditorDelegate();
- Collection<Node> nodes = editor.getLintNodes();
- if (nodes != null && !nodes.isEmpty()) {
- // Copy list before iterating through it to avoid a concurrent list modification
- // in case lint runs in the background while painting and updates this list
- nodes = Lists.newArrayList(nodes);
- ViewHierarchy hierarchy = mCanvas.getViewHierarchy();
- Image icon = getWarningIcon();
- ImageData imageData = icon.getImageData();
- int iconWidth = imageData.width;
- int iconHeight = imageData.height;
- CanvasTransform mHScale = mCanvas.getHorizontalTransform();
- CanvasTransform mVScale = mCanvas.getVerticalTransform();
-
- // Right/bottom edges of the canvas image; don't paint overlays outside of
- // that. (With for example RelativeLayouts with margins rendered on smaller
- // screens than they are intended for this can happen.)
- int maxX = mHScale.translate(0) + mHScale.getScaledImgSize();
- int maxY = mVScale.translate(0) + mVScale.getScaledImgSize();
-
- int oldAlpha = gc.getAlpha();
- try {
- gc.setAlpha(ALPHA);
- for (Node node : nodes) {
- CanvasViewInfo vi = hierarchy.findViewInfoFor(node);
- if (vi != null) {
- Rectangle bounds = vi.getAbsRect();
- int x = mHScale.translate(bounds.x);
- int y = mVScale.translate(bounds.y);
- int w = mHScale.scale(bounds.width);
- int h = mVScale.scale(bounds.height);
- if (w < iconWidth || h < iconHeight) {
- // Don't draw badges on tiny widgets (including those
- // that aren't tiny but are zoomed out too far)
- continue;
- }
-
- x += w - iconWidth;
- y += h - iconHeight;
-
- if (x > maxX || y > maxY) {
- continue;
- }
-
- boolean isError = false;
- IMarker marker = editor.getIssueForNode(vi.getUiViewNode());
- if (marker != null) {
- int severity = marker.getAttribute(IMarker.SEVERITY, 0);
- isError = severity == IMarker.SEVERITY_ERROR;
- }
-
- icon = isError ? getErrorIcon() : getWarningIcon();
-
- gc.drawImage(icon, x, y);
- }
- }
- } finally {
- gc.setAlpha(oldAlpha);
- }
- }
- }
-
- private Image getWarningIcon() {
- if (mWarningImage == null) {
- mWarningImage = IconFactory.getInstance().getIcon("warning-badge"); //$NON-NLS-1$
- }
-
- return mWarningImage;
- }
-
- private Image getErrorIcon() {
- if (mErrorImage == null) {
- mErrorImage = IconFactory.getInstance().getIcon("error-badge"); //$NON-NLS-1$
- }
-
- return mErrorImage;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LintTooltip.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LintTooltip.java
deleted file mode 100644
index cedd43659..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LintTooltip.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.SdkConstants.ATTR_ID;
-
-import com.android.ide.common.layout.BaseLayoutRule;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-
-import java.util.List;
-
-/** Actual tooltip showing multiple lines for various widgets that have lint errors */
-class LintTooltip extends Shell {
- private final LayoutCanvas mCanvas;
- private final List<UiViewElementNode> mNodes;
-
- LintTooltip(LayoutCanvas canvas, List<UiViewElementNode> nodes) {
- super(canvas.getDisplay(), SWT.ON_TOP | SWT.NO_FOCUS | SWT.TOOL);
- mCanvas = canvas;
- mNodes = nodes;
-
- createContents();
- }
-
- protected void createContents() {
- Display display = getDisplay();
- Color fg = display.getSystemColor(SWT.COLOR_INFO_FOREGROUND);
- Color bg = display.getSystemColor(SWT.COLOR_INFO_BACKGROUND);
- setBackground(bg);
- GridLayout gridLayout = new GridLayout(2, false);
- setLayout(gridLayout);
-
- LayoutEditorDelegate delegate = mCanvas.getEditorDelegate();
-
- boolean first = true;
- for (UiViewElementNode node : mNodes) {
- IMarker marker = delegate.getIssueForNode(node);
- if (marker != null) {
- String message = marker.getAttribute(IMarker.MESSAGE, null);
- if (message != null) {
- Label icon = new Label(this, SWT.NONE);
- icon.setForeground(fg);
- icon.setBackground(bg);
- icon.setImage(node.getIcon());
-
- Label label = new Label(this, SWT.WRAP);
- if (first) {
- label.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1));
- first = false;
- }
-
- String id = BaseLayoutRule.stripIdPrefix(node.getAttributeValue(ATTR_ID));
- if (id.isEmpty()) {
- if (node.getXmlNode() != null) {
- id = node.getXmlNode().getNodeName();
- } else {
- id = node.getDescriptor().getUiName();
- }
- }
-
- label.setText(String.format("%1$s: %2$s", id, message));
- }
- }
- }
- }
-
- @Override
- protected void checkSubclass() {
- // Disable the check that prevents subclassing of SWT components
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LintTooltipManager.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LintTooltipManager.java
deleted file mode 100644
index f71935889..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LintTooltipManager.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.LintOverlay.ICON_SIZE;
-
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Shell;
-import org.w3c.dom.Node;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-/** Tooltip in the layout editor showing lint errors under the cursor */
-class LintTooltipManager implements Listener {
- private final LayoutCanvas mCanvas;
- private Shell mTip = null;
- private List<UiViewElementNode> mShowingNodes;
-
- /**
- * Sets up a custom tooltip when hovering over tree items. It currently displays the error
- * message for the lint warning associated with each node, if any (and only if the hover
- * is over the icon portion).
- */
- LintTooltipManager(LayoutCanvas canvas) {
- mCanvas = canvas;
- }
-
- void register() {
- mCanvas.addListener(SWT.Dispose, this);
- mCanvas.addListener(SWT.KeyDown, this);
- mCanvas.addListener(SWT.MouseMove, this);
- mCanvas.addListener(SWT.MouseHover, this);
- }
-
- void unregister() {
- if (!mCanvas.isDisposed()) {
- mCanvas.removeListener(SWT.Dispose, this);
- mCanvas.removeListener(SWT.KeyDown, this);
- mCanvas.removeListener(SWT.MouseMove, this);
- mCanvas.removeListener(SWT.MouseHover, this);
- }
- }
-
- @Override
- public void handleEvent(Event event) {
- switch(event.type) {
- case SWT.MouseMove:
- // See if we're still overlapping this or *other* errors; if so, keep the
- // tip up (or update it).
- if (mShowingNodes != null) {
- List<UiViewElementNode> nodes = computeNodes(event);
- if (nodes != null && !nodes.isEmpty()) {
- if (nodes.equals(mShowingNodes)) {
- return;
- } else {
- show(nodes);
- }
- break;
- }
- }
-
- // If not, fall through and hide the tooltip
-
- //$FALL-THROUGH$
- case SWT.Dispose:
- case SWT.FocusOut:
- case SWT.KeyDown:
- case SWT.MouseExit:
- case SWT.MouseDown:
- hide();
- break;
- case SWT.MouseHover:
- hide();
- show(event);
- break;
- }
- }
-
- void hide() {
- if (mTip != null) {
- mTip.dispose();
- mTip = null;
- }
- mShowingNodes = null;
- }
-
- private void show(Event event) {
- List<UiViewElementNode> nodes = computeNodes(event);
- if (nodes != null && !nodes.isEmpty()) {
- show(nodes);
- }
- }
-
- /** Show a tooltip listing the lint errors for the given nodes */
- private void show(List<UiViewElementNode> nodes) {
- hide();
-
- if (!AdtPrefs.getPrefs().isLintOnSave()) {
- return;
- }
-
- mTip = new LintTooltip(mCanvas, nodes);
- Rectangle rect = mCanvas.getBounds();
- Point size = mTip.computeSize(SWT.DEFAULT, SWT.DEFAULT);
- Point pos = mCanvas.toDisplay(rect.x, rect.y + rect.height);
- if (size.x > rect.width) {
- size = mTip.computeSize(rect.width, SWT.DEFAULT);
- }
- mTip.setBounds(pos.x, pos.y, size.x, size.y);
-
- mShowingNodes = nodes;
- mTip.setVisible(true);
- }
-
- /**
- * Compute the list of nodes which have lint warnings near the given mouse
- * coordinates
- *
- * @param event the mouse cursor event
- * @return a list of nodes, possibly empty
- */
- @Nullable
- private List<UiViewElementNode> computeNodes(Event event) {
- LayoutPoint p = ControlPoint.create(mCanvas, event.x, event.y).toLayout();
- LayoutEditorDelegate delegate = mCanvas.getEditorDelegate();
- ViewHierarchy viewHierarchy = mCanvas.getViewHierarchy();
- CanvasTransform mHScale = mCanvas.getHorizontalTransform();
- CanvasTransform mVScale = mCanvas.getVerticalTransform();
-
- int layoutIconSize = mHScale.inverseScale(ICON_SIZE);
- int slop = mVScale.inverseScale(10); // extra space around icon where tip triggers
-
- Collection<Node> xmlNodes = delegate.getLintNodes();
- if (xmlNodes == null) {
- return null;
- }
- List<UiViewElementNode> nodes = new ArrayList<UiViewElementNode>();
- for (Node xmlNode : xmlNodes) {
- CanvasViewInfo v = viewHierarchy.findViewInfoFor(xmlNode);
- if (v != null) {
- Rectangle b = v.getAbsRect();
- int x2 = b.x + b.width;
- int y2 = b.y + b.height;
- if (p.x < x2 - layoutIconSize - slop
- || p.x > x2 + slop
- || p.y < y2 - layoutIconSize - slop
- || p.y > y2 + slop) {
- continue;
- }
-
- nodes.add(v.getUiViewNode());
- }
- }
-
- return nodes;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ListViewTypeMenu.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ListViewTypeMenu.java
deleted file mode 100644
index 4577f8d12..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ListViewTypeMenu.java
+++ /dev/null
@@ -1,220 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.SdkConstants.ANDROID_LAYOUT_RESOURCE_PREFIX;
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.LayoutMetadata.KEY_LV_FOOTER;
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.LayoutMetadata.KEY_LV_HEADER;
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.LayoutMetadata.KEY_LV_ITEM;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.rendering.api.Capability;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.ide.eclipse.adt.internal.resources.CyclicDependencyValidator;
-import com.android.ide.eclipse.adt.internal.ui.ResourceChooser;
-import com.android.resources.ResourceType;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.ActionContributionItem;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.widgets.Menu;
-import org.w3c.dom.Node;
-
-/**
- * "Preview List Content" context menu which lists available data types and layouts
- * the user can choose to view the ListView as.
- */
-public class ListViewTypeMenu extends SubmenuAction {
- /** Associated canvas */
- private final LayoutCanvas mCanvas;
- /** When true, this menu is for a grid rather than a simple list */
- private boolean mGrid;
- /** When true, this menu is for a spinner rather than a simple list */
- private boolean mSpinner;
-
- /**
- * Creates a "Preview List Content" menu
- *
- * @param canvas associated canvas
- * @param isGrid whether the menu is for a grid rather than a list
- * @param isSpinner whether the menu is for a spinner rather than a list
- */
- public ListViewTypeMenu(LayoutCanvas canvas, boolean isGrid, boolean isSpinner) {
- super(isGrid ? "Preview Grid Content" : isSpinner ? "Preview Spinner Layout"
- : "Preview List Content");
- mCanvas = canvas;
- mGrid = isGrid;
- mSpinner = isSpinner;
- }
-
- @Override
- protected void addMenuItems(Menu menu) {
- GraphicalEditorPart graphicalEditor = mCanvas.getEditorDelegate().getGraphicalEditor();
- if (graphicalEditor.renderingSupports(Capability.ADAPTER_BINDING)) {
- IAction action = new PickLayoutAction("Choose Layout...", KEY_LV_ITEM);
- new ActionContributionItem(action).fill(menu, -1);
- new Separator().fill(menu, -1);
-
- String selected = getSelectedLayout();
- if (selected != null) {
- if (selected.startsWith(ANDROID_LAYOUT_RESOURCE_PREFIX)) {
- selected = selected.substring(ANDROID_LAYOUT_RESOURCE_PREFIX.length());
- }
- }
-
- if (mSpinner) {
- action = new SetListTypeAction("Spinner Item",
- "simple_spinner_item", selected); //$NON-NLS-1$
- new ActionContributionItem(action).fill(menu, -1);
- action = new SetListTypeAction("Spinner Dropdown Item",
- "simple_spinner_dropdown_item", selected); //$NON-NLS-1$
- new ActionContributionItem(action).fill(menu, -1);
- return;
- }
-
- action = new SetListTypeAction("Simple List Item",
- "simple_list_item_1", selected); //$NON-NLS-1$
- new ActionContributionItem(action).fill(menu, -1);
- action = new SetListTypeAction("Simple 2-Line List Item",
- "simple_list_item_2", //$NON-NLS-1$
- selected);
- new ActionContributionItem(action).fill(menu, -1);
- action = new SetListTypeAction("Checked List Item",
- "simple_list_item_checked", //$NON-NLS-1$
- selected);
- new ActionContributionItem(action).fill(menu, -1);
- action = new SetListTypeAction("Single Choice List Item",
- "simple_list_item_single_choice", //$NON-NLS-1$
- selected);
- new ActionContributionItem(action).fill(menu, -1);
- action = new SetListTypeAction("Multiple Choice List Item",
- "simple_list_item_multiple_choice", //$NON-NLS-1$
- selected);
- if (!mGrid) {
- new Separator().fill(menu, -1);
- action = new SetListTypeAction("Simple Expandable List Item",
- "simple_expandable_list_item_1", selected); //$NON-NLS-1$
- new ActionContributionItem(action).fill(menu, -1);
- action = new SetListTypeAction("Simple 2-Line Expandable List Item",
- "simple_expandable_list_item_2", //$NON-NLS-1$
- selected);
- new ActionContributionItem(action).fill(menu, -1);
-
- new Separator().fill(menu, -1);
- action = new PickLayoutAction("Choose Header...", KEY_LV_HEADER);
- new ActionContributionItem(action).fill(menu, -1);
- action = new PickLayoutAction("Choose Footer...", KEY_LV_FOOTER);
- new ActionContributionItem(action).fill(menu, -1);
- }
- } else {
- // Should we just hide the menu item instead?
- addDisabledMessageItem(
- "Not supported for this SDK version; try changing the Render Target");
- }
- }
-
- private class SetListTypeAction extends Action {
- private final String mLayout;
-
- public SetListTypeAction(String title, String layout, String selected) {
- super(title, IAction.AS_RADIO_BUTTON);
- mLayout = layout;
-
- if (layout.equals(selected)) {
- setChecked(true);
- }
- }
-
- @Override
- public void run() {
- if (isChecked()) {
- setNewType(KEY_LV_ITEM, ANDROID_LAYOUT_RESOURCE_PREFIX + mLayout);
- }
- }
- }
-
- /**
- * Action which brings up a resource chooser to choose an arbitrary layout as the
- * layout to be previewed in the list.
- */
- private class PickLayoutAction extends Action {
- private final String mType;
-
- public PickLayoutAction(String title, String type) {
- super(title, IAction.AS_PUSH_BUTTON);
- mType = type;
- }
-
- @Override
- public void run() {
- LayoutEditorDelegate delegate = mCanvas.getEditorDelegate();
- IFile file = delegate.getEditor().getInputFile();
- GraphicalEditorPart editor = delegate.getGraphicalEditor();
- ResourceChooser dlg = ResourceChooser.create(editor, ResourceType.LAYOUT)
- .setInputValidator(CyclicDependencyValidator.create(file))
- .setInitialSize(85, 10)
- .setCurrentResource(getSelectedLayout());
- int result = dlg.open();
- if (result == ResourceChooser.CLEAR_RETURN_CODE) {
- setNewType(mType, null);
- } else if (result == Window.OK) {
- String newType = dlg.getCurrentResource();
- setNewType(mType, newType);
- }
- }
- }
-
- @Nullable
- private String getSelectedLayout() {
- String layout = null;
- SelectionManager selectionManager = mCanvas.getSelectionManager();
- for (SelectionItem item : selectionManager.getSelections()) {
- UiViewElementNode node = item.getViewInfo().getUiViewNode();
- if (node != null) {
- Node xmlNode = node.getXmlNode();
- layout = LayoutMetadata.getProperty(xmlNode, KEY_LV_ITEM);
- if (layout != null) {
- return layout;
- }
- }
- }
-
- return null;
- }
-
- private void setNewType(@NonNull String type, @Nullable String layout) {
- LayoutEditorDelegate delegate = mCanvas.getEditorDelegate();
- GraphicalEditorPart graphicalEditor = delegate.getGraphicalEditor();
- SelectionManager selectionManager = mCanvas.getSelectionManager();
-
- for (SelectionItem item : selectionManager.getSnapshot()) {
- UiViewElementNode node = item.getViewInfo().getUiViewNode();
- if (node != null) {
- Node xmlNode = node.getXmlNode();
- LayoutMetadata.setProperty(delegate.getEditor(), xmlNode, type, layout);
- }
- }
-
- // Refresh
- graphicalEditor.recomputeLayout();
- mCanvas.redraw();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/MarqueeGesture.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/MarqueeGesture.java
deleted file mode 100644
index 4cfd4fe3d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/MarqueeGesture.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Device;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Rectangle;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * A {@link MarqueeGesture} is a gesture for swiping out a selection rectangle.
- * With a modifier key, items that intersect the rectangle can be toggled
- * instead of added to the new selection set.
- */
-public class MarqueeGesture extends Gesture {
- /** The {@link Overlay} drawn for the marquee. */
- private MarqueeOverlay mOverlay;
-
- /** The canvas associated with this gesture. */
- private LayoutCanvas mCanvas;
-
- /** A copy of the initial selection, when we're toggling the marquee. */
- private Collection<CanvasViewInfo> mInitialSelection;
-
- /**
- * Creates a new marquee selection (selection swiping).
- *
- * @param canvas The canvas where selection is performed.
- * @param toggle If true, toggle the membership of contained elements
- * instead of adding it.
- */
- public MarqueeGesture(LayoutCanvas canvas, boolean toggle) {
- mCanvas = canvas;
-
- if (toggle) {
- List<SelectionItem> selection = canvas.getSelectionManager().getSelections();
- mInitialSelection = new ArrayList<CanvasViewInfo>(selection.size());
- for (SelectionItem item : selection) {
- mInitialSelection.add(item.getViewInfo());
- }
- } else {
- mInitialSelection = Collections.emptySet();
- }
- }
-
- @Override
- public void update(ControlPoint pos) {
- if (mOverlay == null) {
- return;
- }
-
- int x = Math.min(pos.x, mStart.x);
- int y = Math.min(pos.y, mStart.y);
- int w = Math.abs(pos.x - mStart.x);
- int h = Math.abs(pos.y - mStart.y);
-
- mOverlay.updateSize(x, y, w, h);
-
- // Compute selection overlaps
- LayoutPoint topLeft = ControlPoint.create(mCanvas, x, y).toLayout();
- LayoutPoint bottomRight = ControlPoint.create(mCanvas, x + w, y + h).toLayout();
- mCanvas.getSelectionManager().selectWithin(topLeft, bottomRight, mInitialSelection);
- }
-
- @Override
- public List<Overlay> createOverlays() {
- mOverlay = new MarqueeOverlay();
- return Collections.<Overlay> singletonList(mOverlay);
- }
-
- /**
- * An {@link Overlay} for the {@link MarqueeGesture}; paints a selection
- * overlay rectangle matching the mouse coordinate delta between gesture
- * start and the current position.
- */
- private static class MarqueeOverlay extends Overlay {
- /** Rectangle border color. */
- private Color mStroke;
-
- /** Rectangle fill color. */
- private Color mFill;
-
- /** Current rectangle coordinates (in terms of control coordinates). */
- private Rectangle mRectangle = new Rectangle(0, 0, 0, 0);
-
- /** Alpha value of the fill. */
- private int mFillAlpha;
-
- /** Alpha value of the border. */
- private int mStrokeAlpha;
-
- /** Constructs a new {@link MarqueeOverlay}. */
- public MarqueeOverlay() {
- }
-
- /**
- * Updates the size of the marquee rectangle.
- *
- * @param x The top left corner of the rectangle, x coordinate.
- * @param y The top left corner of the rectangle, y coordinate.
- * @param w Rectangle width.
- * @param h Rectangle height.
- */
- public void updateSize(int x, int y, int w, int h) {
- mRectangle.x = x;
- mRectangle.y = y;
- mRectangle.width = w;
- mRectangle.height = h;
- }
-
- @Override
- public void create(Device device) {
- // TODO: Integrate DrawingStyles with this?
- mStroke = new Color(device, 255, 255, 255);
- mFill = new Color(device, 128, 128, 128);
- mFillAlpha = 64;
- mStrokeAlpha = 255;
- }
-
- @Override
- public void dispose() {
- mStroke.dispose();
- mFill.dispose();
- }
-
- @Override
- public void paint(GC gc) {
- if (mRectangle.width > 0 && mRectangle.height > 0) {
- gc.setLineStyle(SWT.LINE_SOLID);
- gc.setLineWidth(1);
- gc.setForeground(mStroke);
- gc.setBackground(mFill);
- gc.setAlpha(mStrokeAlpha);
- gc.drawRectangle(mRectangle);
- gc.setAlpha(mFillAlpha);
- gc.fillRectangle(mRectangle);
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/MoveGesture.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/MoveGesture.java
deleted file mode 100644
index 7cf3a647a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/MoveGesture.java
+++ /dev/null
@@ -1,852 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.ide.common.api.DropFeedback;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.InsertType;
-import com.android.ide.common.api.Point;
-import com.android.ide.common.api.Rect;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.NodeFactory;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.NodeProxy;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.RulesEngine;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode.NodeCreationListener;
-
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.TreePath;
-import org.eclipse.jface.viewers.TreeSelection;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DropTargetEvent;
-import org.eclipse.swt.dnd.TransferData;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.widgets.Display;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * The Move gesture provides the operation for moving widgets around in the canvas.
- */
-public class MoveGesture extends DropGesture {
- /** The associated {@link LayoutCanvas}. */
- private LayoutCanvas mCanvas;
-
- /** Overlay which paints the drag &amp; drop feedback. */
- private MoveOverlay mOverlay;
-
- private static final boolean DEBUG = false;
-
- /**
- * The top view right under the drag'n'drop cursor.
- * This can only be null during a drag'n'drop when there is no view under the cursor
- * or after the state was all cleared.
- */
- private CanvasViewInfo mCurrentView;
-
- /**
- * The elements currently being dragged. This will always be non-null for a valid
- * drag'n'drop that happens within the same instance of Eclipse.
- * <p/>
- * In the event that the drag and drop happens between different instances of Eclipse
- * this will remain null.
- */
- private SimpleElement[] mCurrentDragElements;
-
- /**
- * The first view under the cursor that responded to onDropEnter is called the "target view".
- * It can differ from mCurrentView, typically because a terminal View doesn't
- * accept drag'n'drop so its parent layout became the target drag'n'drop receiver.
- * <p/>
- * The target node is the proxy node associated with the target view.
- * This can be null if no view under the cursor accepted the drag'n'drop or if the node
- * factory couldn't create a proxy for it.
- */
- private NodeProxy mTargetNode;
-
- /**
- * The latest drop feedback returned by IViewRule.onDropEnter/Move.
- */
- private DropFeedback mFeedback;
-
- /**
- * {@link #dragLeave(DropTargetEvent)} is unfortunately called right before data is
- * about to be dropped (between the last {@link #dragOver(DropTargetEvent)} and the
- * next {@link #dropAccept(DropTargetEvent)}). That means we can't just
- * trash the current DropFeedback from the current view rule in dragLeave().
- * Instead we preserve it in mLeaveTargetNode and mLeaveFeedback in case a dropAccept
- * happens next.
- */
- private NodeProxy mLeaveTargetNode;
-
- /**
- * @see #mLeaveTargetNode
- */
- private DropFeedback mLeaveFeedback;
-
- /**
- * @see #mLeaveTargetNode
- */
- private CanvasViewInfo mLeaveView;
-
- /** Singleton used to keep track of drag selection in the same Eclipse instance. */
- private final GlobalCanvasDragInfo mGlobalDragInfo;
-
- /**
- * Constructs a new {@link MoveGesture}, tied to the given canvas.
- *
- * @param canvas The canvas to associate the {@link MoveGesture} with.
- */
- public MoveGesture(LayoutCanvas canvas) {
- mCanvas = canvas;
- mGlobalDragInfo = GlobalCanvasDragInfo.getInstance();
- }
-
- @Override
- public List<Overlay> createOverlays() {
- mOverlay = new MoveOverlay();
- return Collections.<Overlay> singletonList(mOverlay);
- }
-
- @Override
- public void begin(ControlPoint pos, int startMask) {
- super.begin(pos, startMask);
-
- // Hide selection overlays during a move drag
- mCanvas.getSelectionOverlay().setHidden(true);
- }
-
- @Override
- public void end(ControlPoint pos, boolean canceled) {
- super.end(pos, canceled);
-
- mCanvas.getSelectionOverlay().setHidden(false);
-
- // Ensure that the outline is back to showing the current selection, since during
- // a drag gesture we temporarily set it to show the current target node instead.
- mCanvas.getSelectionManager().syncOutlineSelection();
- }
-
- /* TODO: Pass modifier mask to drag rules as well! This doesn't work yet since
- the drag &amp; drop code seems to steal keyboard events.
- @Override
- public boolean keyPressed(KeyEvent event) {
- update(mCanvas.getGestureManager().getCurrentControlPoint());
- mCanvas.redraw();
- return true;
- }
-
- @Override
- public boolean keyReleased(KeyEvent event) {
- update(mCanvas.getGestureManager().getCurrentControlPoint());
- mCanvas.redraw();
- return true;
- }
- */
-
- /*
- * The cursor has entered the drop target boundaries.
- * {@inheritDoc}
- */
- @Override
- public void dragEnter(DropTargetEvent event) {
- if (DEBUG) AdtPlugin.printErrorToConsole("DEBUG", "drag enter", event);
-
- // Make sure we don't have any residual data from an earlier operation.
- clearDropInfo();
- mLeaveTargetNode = null;
- mLeaveFeedback = null;
- mLeaveView = null;
-
- // Get the dragged elements.
- //
- // The current transfered type can be extracted from the event.
- // As described in dragOver(), this works basically works on Windows but
- // not on Linux or Mac, in which case we can't get the type until we
- // receive dropAccept/drop().
- // For consistency we try to use the GlobalCanvasDragInfo instance first,
- // and if it fails we use the event transfer type as a backup (but as said
- // before it will most likely work only on Windows.)
- // In any case this can be null even for a valid transfer.
-
- mCurrentDragElements = mGlobalDragInfo.getCurrentElements();
-
- if (mCurrentDragElements == null) {
- SimpleXmlTransfer sxt = SimpleXmlTransfer.getInstance();
- if (sxt.isSupportedType(event.currentDataType)) {
- mCurrentDragElements = (SimpleElement[]) sxt.nativeToJava(event.currentDataType);
- }
- }
-
- // if there is no data to transfer, invalidate the drag'n'drop.
- // The assumption is that the transfer should have at least one element with a
- // a non-null non-empty FQCN. Everything else is optional.
- if (mCurrentDragElements == null ||
- mCurrentDragElements.length == 0 ||
- mCurrentDragElements[0] == null ||
- mCurrentDragElements[0].getFqcn() == null ||
- mCurrentDragElements[0].getFqcn().length() == 0) {
- event.detail = DND.DROP_NONE;
- }
-
- dragOperationChanged(event);
- }
-
- /*
- * The operation being performed has changed (e.g. modifier key).
- * {@inheritDoc}
- */
- @Override
- public void dragOperationChanged(DropTargetEvent event) {
- if (DEBUG) AdtPlugin.printErrorToConsole("DEBUG", "drag changed", event);
-
- checkDataType(event);
- recomputeDragType(event);
- }
-
- private void recomputeDragType(DropTargetEvent event) {
- if (event.detail == DND.DROP_DEFAULT) {
- // Default means we can now choose the default operation, either copy or move.
- // If the drag comes from the same canvas we default to move, otherwise we
- // default to copy.
-
- if (mGlobalDragInfo.getSourceCanvas() == mCanvas &&
- (event.operations & DND.DROP_MOVE) != 0) {
- event.detail = DND.DROP_MOVE;
- } else if ((event.operations & DND.DROP_COPY) != 0) {
- event.detail = DND.DROP_COPY;
- }
- }
-
- // We don't support other types than copy and move
- if (event.detail != DND.DROP_COPY && event.detail != DND.DROP_MOVE) {
- event.detail = DND.DROP_NONE;
- }
- }
-
- /*
- * The cursor has left the drop target boundaries OR data is about to be dropped.
- * {@inheritDoc}
- */
- @Override
- public void dragLeave(DropTargetEvent event) {
- if (DEBUG) AdtPlugin.printErrorToConsole("DEBUG", "drag leave");
-
- // dragLeave is unfortunately called right before data is about to be dropped
- // (between the last dropMove and the next dropAccept). That means we can't just
- // trash the current DropFeedback from the current view rule, we need to preserve
- // it in case a dropAccept happens next.
- // See the corresponding kludge in dropAccept().
- mLeaveTargetNode = mTargetNode;
- mLeaveFeedback = mFeedback;
- mLeaveView = mCurrentView;
-
- clearDropInfo();
- }
-
- /*
- * The cursor is moving over the drop target.
- * {@inheritDoc}
- */
- @Override
- public void dragOver(DropTargetEvent event) {
- processDropEvent(event);
- }
-
- /*
- * The drop is about to be performed.
- * The drop target is given a last chance to change the nature of the drop.
- * {@inheritDoc}
- */
- @Override
- public void dropAccept(DropTargetEvent event) {
- if (DEBUG) AdtPlugin.printErrorToConsole("DEBUG", "drop accept");
-
- checkDataType(event);
-
- // If we have a valid target node and it matches the one we saved in
- // dragLeave then we restore the DropFeedback that we saved in dragLeave.
- if (mLeaveTargetNode != null) {
- mTargetNode = mLeaveTargetNode;
- mFeedback = mLeaveFeedback;
- mCurrentView = mLeaveView;
- }
-
- if (mFeedback != null && mFeedback.invalidTarget) {
- // The script said we can't drop here.
- event.detail = DND.DROP_NONE;
- }
-
- if (mLeaveTargetNode == null || event.detail == DND.DROP_NONE) {
- clearDropInfo();
- }
-
- mLeaveTargetNode = null;
- mLeaveFeedback = null;
- mLeaveView = null;
- }
-
- /*
- * The data is being dropped.
- * {@inheritDoc}
- */
- @Override
- public void drop(final DropTargetEvent event) {
- if (DEBUG) AdtPlugin.printErrorToConsole("DEBUG", "dropped");
-
- SimpleElement[] elements = null;
-
- SimpleXmlTransfer sxt = SimpleXmlTransfer.getInstance();
-
- if (sxt.isSupportedType(event.currentDataType)) {
- if (event.data instanceof SimpleElement[]) {
- elements = (SimpleElement[]) event.data;
- }
- }
-
- if (elements == null || elements.length < 1) {
- if (DEBUG) AdtPlugin.printErrorToConsole("DEBUG", "drop missing drop data");
- return;
- }
-
- if (mCurrentDragElements != null && Arrays.equals(elements, mCurrentDragElements)) {
- elements = mCurrentDragElements;
- }
-
- if (mTargetNode == null) {
- ViewHierarchy viewHierarchy = mCanvas.getViewHierarchy();
- if (viewHierarchy.isValid() && viewHierarchy.isEmpty()) {
- // There is no target node because the drop happens on an empty document.
- // Attempt to create a root node accordingly.
- createDocumentRoot(elements);
- } else {
- if (DEBUG) AdtPlugin.printErrorToConsole("DEBUG", "dropped on null targetNode");
- }
- return;
- }
-
- updateDropFeedback(mFeedback, event);
-
- final SimpleElement[] elementsFinal = elements;
- final LayoutPoint canvasPoint = getDropLocation(event).toLayout();
- String label = computeUndoLabel(mTargetNode, elements, event.detail);
-
- // Create node listener which (during the drop) listens for node additions
- // and stores the list of added node such that they can be selected afterwards.
- final List<UiElementNode> added = new ArrayList<UiElementNode>();
- // List of "index within parent" for each node
- final List<Integer> indices = new ArrayList<Integer>();
- NodeCreationListener listener = new NodeCreationListener() {
- @Override
- public void nodeCreated(UiElementNode parent, UiElementNode child, int index) {
- if (parent == mTargetNode.getNode()) {
- added.add(child);
-
- // Adjust existing indices
- for (int i = 0, n = indices.size(); i < n; i++) {
- int idx = indices.get(i);
- if (idx >= index) {
- indices.set(i, idx + 1);
- }
- }
-
- indices.add(index);
- }
- }
-
- @Override
- public void nodeDeleted(UiElementNode parent, UiElementNode child, int previousIndex) {
- if (parent == mTargetNode.getNode()) {
- // Adjust existing indices
- for (int i = 0, n = indices.size(); i < n; i++) {
- int idx = indices.get(i);
- if (idx >= previousIndex) {
- indices.set(i, idx - 1);
- }
- }
-
- // Make sure we aren't removing the same nodes that are being added
- // No, that can happen when canceling out of a drop handler such as
- // when dropping an included layout, then canceling out of the
- // resource chooser.
- //assert !added.contains(child);
- }
- }
- };
-
- try {
- UiElementNode.addNodeCreationListener(listener);
- mCanvas.getEditorDelegate().getEditor().wrapUndoEditXmlModel(label, new Runnable() {
- @Override
- public void run() {
- InsertType insertType = getInsertType(event, mTargetNode);
- mCanvas.getRulesEngine().callOnDropped(mTargetNode,
- elementsFinal,
- mFeedback,
- new Point(canvasPoint.x, canvasPoint.y),
- insertType);
- mTargetNode.applyPendingChanges();
- // Clean up drag if applicable
- if (event.detail == DND.DROP_MOVE) {
- GlobalCanvasDragInfo.getInstance().removeSource();
- }
- mTargetNode.applyPendingChanges();
- }
- });
- } finally {
- UiElementNode.removeNodeCreationListener(listener);
- }
-
- final List<INode> nodes = new ArrayList<INode>();
- NodeFactory nodeFactory = mCanvas.getNodeFactory();
- for (UiElementNode uiNode : added) {
- if (uiNode instanceof UiViewElementNode) {
- NodeProxy node = nodeFactory.create((UiViewElementNode) uiNode);
- if (node != null) {
- nodes.add(node);
- }
- }
- }
-
- // Select the newly dropped nodes:
- // Find out which nodes were added, and look up their corresponding
- // CanvasViewInfos.
- final SelectionManager selectionManager = mCanvas.getSelectionManager();
- // Don't use the indices to search for corresponding nodes yet, since a
- // render may not have happened yet and we'd rather use an up to date
- // view hierarchy than indices to look up the right view infos.
- if (!selectionManager.selectDropped(nodes, null /* indices */)) {
- // In some scenarios we can't find the actual view infos yet; this
- // seems to happen when you drag from one canvas to another (see the
- // related comment next to the setFocus() call below). In that case
- // defer selection briefly until the view hierarchy etc is up to
- // date.
- Display.getDefault().asyncExec(new Runnable() {
- @Override
- public void run() {
- selectionManager.selectDropped(nodes, indices);
- }
- });
- }
-
- clearDropInfo();
- mCanvas.redraw();
- // Request focus: This is *necessary* when you are dragging from one canvas editor
- // to another, because without it, the redraw does not seem to be processed (the change
- // is invisible until you click on the target canvas to give it focus).
- mCanvas.setFocus();
- }
-
- /**
- * Returns the right {@link InsertType} to use for the given drop target event and the
- * given target node
- *
- * @param event the drop target event
- * @param mTargetNode the node targeted by the drop
- * @return the {link InsertType} to use for the drop
- */
- public static InsertType getInsertType(DropTargetEvent event, NodeProxy mTargetNode) {
- GlobalCanvasDragInfo dragInfo = GlobalCanvasDragInfo.getInstance();
- if (event.detail == DND.DROP_MOVE) {
- SelectionItem[] selection = dragInfo.getCurrentSelection();
- if (selection != null) {
- for (SelectionItem item : selection) {
- if (item.getNode() != null
- && item.getNode().getParent() == mTargetNode) {
- return InsertType.MOVE_WITHIN;
- }
- }
- }
-
- return InsertType.MOVE_INTO;
- } else if (dragInfo.getSourceCanvas() != null) {
- return InsertType.PASTE;
- } else {
- return InsertType.CREATE;
- }
- }
-
- /**
- * Computes a suitable Undo label to use for a drop operation, such as
- * "Drop Button in LinearLayout" and "Move Widgets in RelativeLayout".
- *
- * @param targetNode The target of the drop
- * @param elements The dragged widgets
- * @param detail The DnD mode, as used in {@link DropTargetEvent#detail}.
- * @return A string suitable as an undo-label for the drop event
- */
- public static String computeUndoLabel(NodeProxy targetNode,
- SimpleElement[] elements, int detail) {
- // Decide whether it's a move or a copy; we'll label moves specifically
- // as a move and consider everything else a "Drop"
- String verb = (detail == DND.DROP_MOVE) ? "Move" : "Drop";
-
- // Get the type of widget being dropped/moved, IF there is only one. If
- // there is more than one, just reference it as "Widgets".
- String object;
- if (elements != null && elements.length == 1) {
- object = getSimpleName(elements[0].getFqcn());
- } else {
- object = "Widgets";
- }
-
- String where = getSimpleName(targetNode.getFqcn());
-
- // When we localize this: $1 is the verb (Move or Drop), $2 is the
- // object (such as "Button"), and $3 is the place we are doing it (such
- // as "LinearLayout").
- return String.format("%1$s %2$s in %3$s", verb, object, where);
- }
-
- /**
- * Returns simple name (basename, following last dot) of a fully qualified
- * class name.
- *
- * @param fqcn The fqcn to reduce
- * @return The base name of the fqcn
- */
- public static String getSimpleName(String fqcn) {
- // Note that the following works even when there is no dot, since
- // lastIndexOf will return -1 so we get fcqn.substring(-1+1) =
- // fcqn.substring(0) = fqcn
- return fqcn.substring(fqcn.lastIndexOf('.') + 1);
- }
-
- /**
- * Updates the {@link DropFeedback#isCopy} and {@link DropFeedback#sameCanvas} fields
- * of the given {@link DropFeedback}. This is generally called right before invoking
- * one of the callOnXyz methods of GRE to refresh the fields.
- *
- * @param df The current {@link DropFeedback}.
- * @param event An optional event to determine if the current operation is copy or move.
- */
- private void updateDropFeedback(DropFeedback df, DropTargetEvent event) {
- if (event != null) {
- df.isCopy = event.detail == DND.DROP_COPY;
- }
- df.sameCanvas = mCanvas == mGlobalDragInfo.getSourceCanvas();
- df.invalidTarget = false;
- df.dipScale = mCanvas.getEditorDelegate().getGraphicalEditor().getDipScale();
- df.modifierMask = mCanvas.getGestureManager().getRuleModifierMask();
-
- // Set the drag bounds, after converting it from control coordinates to
- // layout coordinates
- GlobalCanvasDragInfo dragInfo = GlobalCanvasDragInfo.getInstance();
- Rect dragBounds = null;
- Rect controlDragBounds = dragInfo.getDragBounds();
- if (controlDragBounds != null) {
- CanvasTransform ht = mCanvas.getHorizontalTransform();
- CanvasTransform vt = mCanvas.getVerticalTransform();
- double horizScale = ht.getScale();
- double verticalScale = vt.getScale();
- int x = (int) (controlDragBounds.x / horizScale);
- int y = (int) (controlDragBounds.y / verticalScale);
- int w = (int) (controlDragBounds.w / horizScale);
- int h = (int) (controlDragBounds.h / verticalScale);
- dragBounds = new Rect(x, y, w, h);
- }
- int baseline = dragInfo.getDragBaseline();
- if (baseline != -1) {
- df.dragBaseline = baseline;
- }
- df.dragBounds = dragBounds;
- }
-
- /**
- * Verifies that event.currentDataType is of type {@link SimpleXmlTransfer}.
- * If not, try to find a valid data type.
- * Otherwise set the drop to {@link DND#DROP_NONE} to cancel it.
- *
- * @return True if the data type is accepted.
- */
- private static boolean checkDataType(DropTargetEvent event) {
-
- SimpleXmlTransfer sxt = SimpleXmlTransfer.getInstance();
-
- TransferData current = event.currentDataType;
-
- if (sxt.isSupportedType(current)) {
- return true;
- }
-
- // We only support SimpleXmlTransfer and the current data type is not right.
- // Let's see if we can find another one.
-
- for (TransferData td : event.dataTypes) {
- if (td != current && sxt.isSupportedType(td)) {
- // We like this type better.
- event.currentDataType = td;
- return true;
- }
- }
-
- // We failed to find any good transfer type.
- event.detail = DND.DROP_NONE;
- return false;
- }
-
- /**
- * Returns the mouse location of the drop target event.
- *
- * @param event the drop target event
- * @return a {@link ControlPoint} location corresponding to the top left corner
- */
- private ControlPoint getDropLocation(DropTargetEvent event) {
- return ControlPoint.create(mCanvas, event);
- }
-
- /**
- * Called on both dragEnter and dragMove.
- * Generates the onDropEnter/Move/Leave events depending on the currently
- * selected target node.
- */
- private void processDropEvent(DropTargetEvent event) {
- if (!mCanvas.getViewHierarchy().isValid()) {
- // We don't allow drop on an invalid layout, even if we have some obsolete
- // layout info for it.
- event.detail = DND.DROP_NONE;
- clearDropInfo();
- return;
- }
-
- LayoutPoint p = getDropLocation(event).toLayout();
-
- // Is the mouse currently captured by a DropFeedback.captureArea?
- boolean isCaptured = false;
- if (mFeedback != null) {
- Rect r = mFeedback.captureArea;
- isCaptured = r != null && r.contains(p.x, p.y);
- }
-
- // We can't switch views/nodes when the mouse is captured
- CanvasViewInfo vi;
- if (isCaptured) {
- vi = mCurrentView;
- } else {
- vi = mCanvas.getViewHierarchy().findViewInfoAt(p);
-
- // When dragging into the canvas, if you are not over any other view, target
- // the root element (since it may not "fill" the screen, e.g. if you have a linear
- // layout but have layout_height wrap_content, then the layout will only extend
- // to cover the children in the layout, not the whole visible screen area, which
- // may be surprising
- if (vi == null) {
- vi = mCanvas.getViewHierarchy().getRoot();
- }
- }
-
- boolean isMove = true;
- boolean needRedraw = false;
-
- if (vi != mCurrentView) {
- // Current view has changed. Does that also change the target node?
- // Note that either mCurrentView or vi can be null.
-
- if (vi == null) {
- // vi is null but mCurrentView is not, no view is a target anymore
- // We don't need onDropMove in this case
- isMove = false;
- needRedraw = true;
- event.detail = DND.DROP_NONE;
- clearDropInfo(); // this will call callDropLeave.
-
- } else {
- // vi is a new current view.
- // Query GRE for onDropEnter on the ViewInfo hierarchy, starting from the child
- // towards its parent, till we find one that returns a non-null drop feedback.
-
- DropFeedback df = null;
- NodeProxy targetNode = null;
-
- for (CanvasViewInfo targetVi = vi;
- targetVi != null && df == null;
- targetVi = targetVi.getParent()) {
- targetNode = mCanvas.getNodeFactory().create(targetVi);
- df = mCanvas.getRulesEngine().callOnDropEnter(targetNode,
- targetVi.getViewObject(), mCurrentDragElements);
-
- if (df != null) {
- // We should also dispatch an onDropMove() call to the initial enter
- // position, such that the view is notified of the position where
- // we are within the node immediately (before we for example attempt
- // to draw feedback). This is necessary since most views perform the
- // guideline computations in onDropMove (since only onDropMove is handed
- // the -position- of the mouse), and we want this computation to happen
- // before we ask the view to draw its feedback.
- updateDropFeedback(df, event);
- df = mCanvas.getRulesEngine().callOnDropMove(targetNode,
- mCurrentDragElements, df, new Point(p.x, p.y));
- }
-
- if (df != null &&
- event.detail == DND.DROP_MOVE &&
- mCanvas == mGlobalDragInfo.getSourceCanvas()) {
- // You can't move an object into itself in the same canvas.
- // E.g. case of moving a layout and the node under the mouse is the
- // layout itself: a copy would be ok but not a move operation of the
- // layout into himself.
-
- SelectionItem[] selection = mGlobalDragInfo.getCurrentSelection();
- if (selection != null) {
- for (SelectionItem cs : selection) {
- if (cs.getViewInfo() == targetVi) {
- // The node that responded is one of the selection roots.
- // Simply invalidate the drop feedback and move on the
- // parent in the ViewInfo chain.
-
- updateDropFeedback(df, event);
- mCanvas.getRulesEngine().callOnDropLeave(
- targetNode, mCurrentDragElements, df);
- df = null;
- targetNode = null;
- }
- }
- }
- }
- }
-
- if (df == null) {
- // Provide visual feedback that we are refusing the drop
- event.detail = DND.DROP_NONE;
- clearDropInfo();
-
- } else if (targetNode != mTargetNode) {
- // We found a new target node for the drag'n'drop.
- // Release the previous one, if any.
- callDropLeave();
-
- // And assign the new one
- mTargetNode = targetNode;
- mFeedback = df;
-
- // We don't need onDropMove in this case
- isMove = false;
- }
- }
-
- mCurrentView = vi;
- }
-
- if (isMove && mTargetNode != null && mFeedback != null) {
- // this is a move inside the same view
- com.android.ide.common.api.Point p2 =
- new com.android.ide.common.api.Point(p.x, p.y);
- updateDropFeedback(mFeedback, event);
- DropFeedback df = mCanvas.getRulesEngine().callOnDropMove(
- mTargetNode, mCurrentDragElements, mFeedback, p2);
- mCanvas.getGestureManager().updateMessage(mFeedback);
-
- if (df == null) {
- // The target is no longer interested in the drop move.
- event.detail = DND.DROP_NONE;
- callDropLeave();
-
- } else if (df != mFeedback) {
- mFeedback = df;
- }
- }
-
- if (mFeedback != null) {
- if (event.detail == DND.DROP_NONE && !mFeedback.invalidTarget) {
- // If we previously provided visual feedback that we were refusing
- // the drop, we now need to change it to mean we're accepting it.
- event.detail = DND.DROP_DEFAULT;
- recomputeDragType(event);
-
- } else if (mFeedback.invalidTarget) {
- // Provide visual feedback that we are refusing the drop
- event.detail = DND.DROP_NONE;
- }
- }
-
- if (needRedraw || (mFeedback != null && mFeedback.requestPaint)) {
- mCanvas.redraw();
- }
-
- // Update outline to show the target node there
- OutlinePage outline = mCanvas.getOutlinePage();
- TreeSelection newSelection = TreeSelection.EMPTY;
- if (mCurrentView != null && mTargetNode != null) {
- // Find the view corresponding to the target node. The current view can be a leaf
- // view whereas the target node is always a parent layout.
- if (mCurrentView.getUiViewNode() != mTargetNode.getNode()) {
- mCurrentView = mCurrentView.getParent();
- }
- if (mCurrentView != null && mCurrentView.getUiViewNode() == mTargetNode.getNode()) {
- TreePath treePath = SelectionManager.getTreePath(mCurrentView);
- newSelection = new TreeSelection(treePath);
- }
- }
-
- ISelection currentSelection = outline.getSelection();
- if (currentSelection == null || !currentSelection.equals(newSelection)) {
- outline.setSelection(newSelection);
- }
- }
-
- /**
- * Calls onDropLeave on mTargetNode with the current mFeedback. <br/>
- * Then clears mTargetNode and mFeedback.
- */
- private void callDropLeave() {
- if (mTargetNode != null && mFeedback != null) {
- updateDropFeedback(mFeedback, null);
- mCanvas.getRulesEngine().callOnDropLeave(mTargetNode, mCurrentDragElements, mFeedback);
- }
-
- mTargetNode = null;
- mFeedback = null;
- }
-
- private void clearDropInfo() {
- callDropLeave();
- mCurrentView = null;
- mCanvas.redraw();
- }
-
- /**
- * Creates a root element in an empty document.
- * Only the first element's FQCN of the dragged elements is used.
- * <p/>
- * Actual XML handling is done by {@link LayoutCanvas#createDocumentRoot(String)}.
- */
- private void createDocumentRoot(SimpleElement[] elements) {
- if (elements == null || elements.length < 1 || elements[0] == null) {
- return;
- }
-
- mCanvas.createDocumentRoot(elements[0]);
- }
-
- /**
- * An {@link Overlay} to paint the move feedback. This just delegates to the
- * layout rules.
- */
- private class MoveOverlay extends Overlay {
- @Override
- public void paint(GC gc) {
- if (mTargetNode != null && mFeedback != null) {
- RulesEngine rulesEngine = mCanvas.getRulesEngine();
- rulesEngine.callDropFeedbackPaint(mCanvas.getGcWrapper(), mTargetNode, mFeedback);
- mFeedback.requestPaint = false;
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/OutlineDragListener.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/OutlineDragListener.java
deleted file mode 100644
index 1af3053e3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/OutlineDragListener.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DragSourceEvent;
-import org.eclipse.swt.dnd.DragSourceListener;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeItem;
-
-import java.util.ArrayList;
-
-/** Drag listener for the outline page */
-/* package */ class OutlineDragListener implements DragSourceListener {
- private TreeViewer mTreeViewer;
- private OutlinePage mOutlinePage;
- private final ArrayList<SelectionItem> mDragSelection = new ArrayList<SelectionItem>();
- private SimpleElement[] mDragElements;
-
- public OutlineDragListener(OutlinePage outlinePage, TreeViewer treeViewer) {
- super();
- mOutlinePage = outlinePage;
- mTreeViewer = treeViewer;
- }
-
- @Override
- public void dragStart(DragSourceEvent e) {
- Tree tree = mTreeViewer.getTree();
-
- TreeItem overTreeItem = tree.getItem(new Point(e.x, e.y));
- if (overTreeItem == null) {
- // Not dragging over a tree item
- e.doit = false;
- return;
- }
- CanvasViewInfo over = getViewInfo(overTreeItem);
- if (over == null) {
- e.doit = false;
- return;
- }
-
- // The selection logic for the outline is much simpler than in the canvas,
- // because for one thing, the tree selection is updated synchronously on mouse
- // down, so it's not possible to start dragging a non-selected item.
- // We also don't deliberately disallow root-element dragging since you can
- // drag it into another form.
- final LayoutCanvas canvas = mOutlinePage.getEditor().getCanvasControl();
- SelectionManager selectionManager = canvas.getSelectionManager();
- TreeItem[] treeSelection = tree.getSelection();
- mDragSelection.clear();
- for (TreeItem item : treeSelection) {
- CanvasViewInfo viewInfo = getViewInfo(item);
- if (viewInfo != null) {
- mDragSelection.add(selectionManager.createSelection(viewInfo));
- }
- }
- SelectionManager.sanitize(mDragSelection);
-
- e.doit = !mDragSelection.isEmpty();
- int imageCount = mDragSelection.size();
- if (e.doit) {
- mDragElements = SelectionItem.getAsElements(mDragSelection);
- GlobalCanvasDragInfo.getInstance().startDrag(mDragElements,
- mDragSelection.toArray(new SelectionItem[imageCount]),
- canvas, new Runnable() {
- @Override
- public void run() {
- canvas.getClipboardSupport().deleteSelection("Remove",
- mDragSelection);
- }
- });
- return;
- }
-
- e.detail = DND.DROP_NONE;
- }
-
- @Override
- public void dragSetData(DragSourceEvent e) {
- if (TextTransfer.getInstance().isSupportedType(e.dataType)) {
- LayoutCanvas canvas = mOutlinePage.getEditor().getCanvasControl();
- e.data = SelectionItem.getAsText(canvas, mDragSelection);
- return;
- }
-
- if (SimpleXmlTransfer.getInstance().isSupportedType(e.dataType)) {
- e.data = mDragElements;
- return;
- }
-
- // otherwise we failed
- e.detail = DND.DROP_NONE;
- e.doit = false;
- }
-
- @Override
- public void dragFinished(DragSourceEvent e) {
- // Unregister the dragged data.
- // Clear the selection
- mDragSelection.clear();
- mDragElements = null;
- GlobalCanvasDragInfo.getInstance().stopDrag();
- }
-
- private CanvasViewInfo getViewInfo(TreeItem item) {
- Object data = item.getData();
- if (data != null) {
- return OutlinePage.getViewInfo(data);
- }
-
- return null;
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/OutlineDropListener.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/OutlineDropListener.java
deleted file mode 100644
index f4a826fa2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/OutlineDropListener.java
+++ /dev/null
@@ -1,217 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.InsertType;
-import com.android.ide.common.layout.BaseLayoutRule;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.NodeProxy;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.ViewerDropAdapter;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DropTargetEvent;
-import org.eclipse.swt.dnd.TransferData;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/** Drop listener for the outline page */
-/*package*/ class OutlineDropListener extends ViewerDropAdapter {
- private final OutlinePage mOutlinePage;
-
- public OutlineDropListener(OutlinePage outlinePage, TreeViewer treeViewer) {
- super(treeViewer);
- mOutlinePage = outlinePage;
- }
-
- @Override
- public void dragEnter(DropTargetEvent event) {
- if (event.detail == DND.DROP_NONE && GlobalCanvasDragInfo.getInstance().isDragging()) {
- // For some inexplicable reason, we get DND.DROP_NONE from the palette
- // even though in its drag start we set DND.DROP_COPY, so correct that here...
- int operation = DND.DROP_COPY;
- event.detail = operation;
- }
- super.dragEnter(event);
- }
-
- @Override
- public boolean performDrop(Object data) {
- final DropTargetEvent event = getCurrentEvent();
- if (event == null) {
- return false;
- }
- int location = determineLocation(event);
- if (location == LOCATION_NONE) {
- return false;
- }
-
- final SimpleElement[] elements;
- SimpleXmlTransfer sxt = SimpleXmlTransfer.getInstance();
- if (sxt.isSupportedType(event.currentDataType)) {
- if (data instanceof SimpleElement[]) {
- elements = (SimpleElement[]) data;
- } else {
- return false;
- }
- } else {
- return false;
- }
- if (elements.length == 0) {
- return false;
- }
-
- // Determine target:
- CanvasViewInfo parent = OutlinePage.getViewInfo(event.item.getData());
- if (parent == null) {
- return false;
- }
-
- int index = -1;
- UiViewElementNode parentNode = parent.getUiViewNode();
- if (location == LOCATION_BEFORE || location == LOCATION_AFTER) {
- UiViewElementNode node = parentNode;
- parent = parent.getParent();
- if (parent == null) {
- return false;
- }
- parentNode = parent.getUiViewNode();
-
- // Determine index
- index = 0;
- for (UiElementNode child : parentNode.getUiChildren()) {
- if (child == node) {
- break;
- }
- index++;
- }
- if (location == LOCATION_AFTER) {
- index++;
- }
- }
-
- // Copy into new position.
- final LayoutCanvas canvas = mOutlinePage.getEditor().getCanvasControl();
- final NodeProxy targetNode = canvas.getNodeFactory().create(parentNode);
-
- // Record children of the target right before the drop (such that we can
- // find out after the drop which exact children were inserted)
- Set<INode> children = new HashSet<INode>();
- for (INode node : targetNode.getChildren()) {
- children.add(node);
- }
-
- String label = MoveGesture.computeUndoLabel(targetNode, elements, event.detail);
- final int indexFinal = index;
- canvas.getEditorDelegate().getEditor().wrapUndoEditXmlModel(label, new Runnable() {
- @Override
- public void run() {
- InsertType insertType = MoveGesture.getInsertType(event, targetNode);
- canvas.getRulesEngine().setInsertType(insertType);
-
- Object sourceCanvas = GlobalCanvasDragInfo.getInstance().getSourceCanvas();
- boolean createNew = event.detail == DND.DROP_COPY || sourceCanvas != canvas;
- BaseLayoutRule.insertAt(targetNode, elements, createNew, indexFinal);
- targetNode.applyPendingChanges();
-
- // Clean up drag if applicable
- if (event.detail == DND.DROP_MOVE) {
- GlobalCanvasDragInfo.getInstance().removeSource();
- }
- }
- });
-
- // Now find out which nodes were added, and look up their corresponding
- // CanvasViewInfos
- final List<INode> added = new ArrayList<INode>();
- for (INode node : targetNode.getChildren()) {
- if (!children.contains(node)) {
- added.add(node);
- }
- }
- // Select the newly dropped nodes
- final SelectionManager selectionManager = canvas.getSelectionManager();
- selectionManager.setOutlineSelection(added);
-
- canvas.redraw();
-
- return true;
- }
-
- @Override
- public boolean validateDrop(Object target, int operation,
- TransferData transferType) {
- DropTargetEvent event = getCurrentEvent();
- if (event == null) {
- return false;
- }
- int location = determineLocation(event);
- if (location == LOCATION_NONE) {
- return false;
- }
-
- SimpleXmlTransfer sxt = SimpleXmlTransfer.getInstance();
- if (!sxt.isSupportedType(transferType)) {
- return false;
- }
-
- CanvasViewInfo parent = OutlinePage.getViewInfo(event.item.getData());
- if (parent == null) {
- return false;
- }
-
- UiViewElementNode parentNode = parent.getUiViewNode();
-
- if (location == LOCATION_ON) {
- // Targeting the middle of an item means to add it as a new child
- // of the given element. This is only allowed on some types of nodes.
- if (!DescriptorsUtils.canInsertChildren(parentNode.getDescriptor(),
- parent.getViewObject())) {
- return false;
- }
- }
-
- // Check that the drop target position is not a child or identical to
- // one of the dragged items
- SelectionItem[] sel = GlobalCanvasDragInfo.getInstance().getCurrentSelection();
- if (sel != null) {
- for (SelectionItem item : sel) {
- if (isAncestor(item.getViewInfo().getUiViewNode(), parentNode)) {
- return false;
- }
- }
- }
-
- return true;
- }
-
- /** Returns true if the given parent node is an ancestor of the given child node */
- private boolean isAncestor(UiElementNode parent, UiElementNode child) {
- while (child != null) {
- if (child == parent) {
- return true;
- }
- child = child.getUiParent();
- }
- return false;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/OutlineOverlay.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/OutlineOverlay.java
deleted file mode 100644
index e63fff7ab..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/OutlineOverlay.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Device;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Rectangle;
-
-/**
- * The {@link OutlineOverlay} paints an optional outline on top of the layout,
- * showing the structure of the individual Android View elements.
- */
-public class OutlineOverlay extends Overlay {
- /** The {@link ViewHierarchy} this outline visualizes */
- private final ViewHierarchy mViewHierarchy;
-
- /** Outline color. Must be disposed, it's NOT a system color. */
- private Color mOutlineColor;
-
- /** Vertical scaling & scrollbar information. */
- private CanvasTransform mVScale;
-
- /** Horizontal scaling & scrollbar information. */
- private CanvasTransform mHScale;
-
- /**
- * Constructs a new {@link OutlineOverlay} linked to the given view
- * hierarchy.
- *
- * @param viewHierarchy The {@link ViewHierarchy} to render
- * @param hScale The {@link CanvasTransform} to use to transfer horizontal layout
- * coordinates to screen coordinates
- * @param vScale The {@link CanvasTransform} to use to transfer vertical layout
- * coordinates to screen coordinates
- */
- public OutlineOverlay(
- ViewHierarchy viewHierarchy,
- CanvasTransform hScale,
- CanvasTransform vScale) {
- super();
- mViewHierarchy = viewHierarchy;
- mHScale = hScale;
- mVScale = vScale;
- }
-
- @Override
- public void create(Device device) {
- mOutlineColor = new Color(device, SwtDrawingStyle.OUTLINE.getStrokeColor());
- }
-
- @Override
- public void dispose() {
- if (mOutlineColor != null) {
- mOutlineColor.dispose();
- mOutlineColor = null;
- }
- }
-
- @Override
- public void paint(GC gc) {
- CanvasViewInfo lastRoot = mViewHierarchy.getRoot();
- if (lastRoot != null) {
- gc.setForeground(mOutlineColor);
- gc.setLineStyle(SwtDrawingStyle.OUTLINE.getLineStyle());
- int oldAlpha = gc.getAlpha();
- gc.setAlpha(SwtDrawingStyle.OUTLINE.getStrokeAlpha());
- drawOutline(gc, lastRoot);
- gc.setAlpha(oldAlpha);
- }
- }
-
- private void drawOutline(GC gc, CanvasViewInfo info) {
- Rectangle r = info.getAbsRect();
-
- int x = mHScale.translate(r.x);
- int y = mVScale.translate(r.y);
- int w = mHScale.scale(r.width);
- int h = mVScale.scale(r.height);
-
- // Add +1 to the width and +1 to the height such that when you have a
- // series of boxes (in say a LinearLayout), instead of the bottom of one
- // box and the top of the next box being -adjacent-, they -overlap-.
- // This makes the outline nicer visually since you don't get
- // "double thickness" lines for all adjacent boxes.
- gc.drawRectangle(x, y, w + 1, h + 1);
-
- for (CanvasViewInfo vi : info.getChildren()) {
- drawOutline(gc, vi);
- }
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/OutlinePage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/OutlinePage.java
deleted file mode 100644
index 8178c6871..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/OutlinePage.java
+++ /dev/null
@@ -1,1439 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_COLUMN_COUNT;
-import static com.android.SdkConstants.ATTR_LAYOUT_COLUMN;
-import static com.android.SdkConstants.ATTR_LAYOUT_COLUMN_SPAN;
-import static com.android.SdkConstants.ATTR_LAYOUT_GRAVITY;
-import static com.android.SdkConstants.ATTR_LAYOUT_ROW;
-import static com.android.SdkConstants.ATTR_LAYOUT_ROW_SPAN;
-import static com.android.SdkConstants.ATTR_ROW_COUNT;
-import static com.android.SdkConstants.ATTR_SRC;
-import static com.android.SdkConstants.ATTR_TEXT;
-import static com.android.SdkConstants.AUTO_URI;
-import static com.android.SdkConstants.DRAWABLE_PREFIX;
-import static com.android.SdkConstants.GRID_LAYOUT;
-import static com.android.SdkConstants.LAYOUT_RESOURCE_PREFIX;
-import static com.android.SdkConstants.URI_PREFIX;
-import static org.eclipse.jface.viewers.StyledString.COUNTER_STYLER;
-import static org.eclipse.jface.viewers.StyledString.QUALIFIER_STYLER;
-
-import com.android.SdkConstants;
-import com.android.annotations.VisibleForTesting;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.InsertType;
-import com.android.ide.common.layout.BaseLayoutRule;
-import com.android.ide.common.layout.GridLayoutRule;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.IncludeFinder.Reference;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.NodeProxy;
-import com.android.ide.eclipse.adt.internal.editors.layout.properties.PropertySheetPage;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.utils.Pair;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.ActionContributionItem;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IContributionItem;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.preference.JFacePreferences;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.IElementComparer;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.ITreeSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StyledCellLabelProvider;
-import org.eclipse.jface.viewers.StyledString;
-import org.eclipse.jface.viewers.StyledString.Styler;
-import org.eclipse.jface.viewers.TreePath;
-import org.eclipse.jface.viewers.TreeSelection;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerCell;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.KeyListener;
-import org.eclipse.swt.events.MenuDetectEvent;
-import org.eclipse.swt.events.MenuDetectListener;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeItem;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.INullSelectionListener;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.views.contentoutline.ContentOutlinePage;
-import org.eclipse.wb.core.controls.SelfOrientingSashForm;
-import org.eclipse.wb.internal.core.editor.structure.IPage;
-import org.eclipse.wb.internal.core.editor.structure.PageSiteComposite;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * An outline page for the layout canvas view.
- * <p/>
- * The page is created by {@link LayoutEditorDelegate#delegateGetAdapter(Class)}. This means
- * we have *one* instance of the outline page per open canvas editor.
- * <p/>
- * It sets itself as a listener on the site's selection service in order to be
- * notified of the canvas' selection changes.
- * The underlying page is also a selection provider (via IContentOutlinePage)
- * and as such it will broadcast selection changes to the site's selection service
- * (on which both the layout editor part and the property sheet page listen.)
- */
-public class OutlinePage extends ContentOutlinePage
- implements INullSelectionListener, IPage {
-
- /** Label which separates outline text from additional attributes like text prefix or url */
- private static final String LABEL_SEPARATOR = " - ";
-
- /** Max character count in labels, used for truncation */
- private static final int LABEL_MAX_WIDTH = 50;
-
- /**
- * The graphical editor that created this outline.
- */
- private final GraphicalEditorPart mGraphicalEditorPart;
-
- /**
- * RootWrapper is a workaround: we can't set the input of the TreeView to its root
- * element, so we introduce a fake parent.
- */
- private final RootWrapper mRootWrapper = new RootWrapper();
-
- /**
- * Menu manager for the context menu actions.
- * The actions delegate to the current GraphicalEditorPart.
- */
- private MenuManager mMenuManager;
-
- private Composite mControl;
- private PropertySheetPage mPropertySheet;
- private PageSiteComposite mPropertySheetComposite;
- private boolean mShowPropertySheet;
- private boolean mShowHeader;
- private boolean mIgnoreSelection;
- private boolean mActive = true;
-
- /** Action to Select All in the tree */
- private final Action mTreeSelectAllAction = new Action() {
- @Override
- public void run() {
- getTreeViewer().getTree().selectAll();
- OutlinePage.this.fireSelectionChanged(getSelection());
- }
-
- @Override
- public String getId() {
- return ActionFactory.SELECT_ALL.getId();
- }
- };
-
- /** Action for moving items up in the tree */
- private Action mMoveUpAction = new Action("Move Up\t-",
- IconFactory.getInstance().getImageDescriptor("up")) { //$NON-NLS-1$
-
- @Override
- public String getId() {
- return "adt.outline.moveup"; //$NON-NLS-1$
- }
-
- @Override
- public boolean isEnabled() {
- return canMove(false);
- }
-
- @Override
- public void run() {
- move(false);
- }
- };
-
- /** Action for moving items down in the tree */
- private Action mMoveDownAction = new Action("Move Down\t+",
- IconFactory.getInstance().getImageDescriptor("down")) { //$NON-NLS-1$
-
- @Override
- public String getId() {
- return "adt.outline.movedown"; //$NON-NLS-1$
- }
-
- @Override
- public boolean isEnabled() {
- return canMove(true);
- }
-
- @Override
- public void run() {
- move(true);
- }
- };
-
- /**
- * Creates a new {@link OutlinePage} associated with the given editor
- *
- * @param graphicalEditorPart the editor associated with this outline
- */
- public OutlinePage(GraphicalEditorPart graphicalEditorPart) {
- super();
- mGraphicalEditorPart = graphicalEditorPart;
- }
-
- @Override
- public Control getControl() {
- // We've injected some controls between the root of the outline page
- // and the tree control, so return the actual root (a sash form) rather
- // than the superclass' implementation which returns the tree. If we don't
- // do this, various checks in the outline page which checks that getControl().getParent()
- // is the outline window itself will ignore this page.
- return mControl;
- }
-
- void setActive(boolean active) {
- if (active != mActive) {
- mActive = active;
-
- // Outlines are by default active when they are created; this is intended
- // for deactivating a hidden outline and later reactivating it
- assert mControl != null;
- if (active) {
- getSite().getPage().addSelectionListener(this);
- setModel(mGraphicalEditorPart.getCanvasControl().getViewHierarchy().getRoot());
- } else {
- getSite().getPage().removeSelectionListener(this);
- mRootWrapper.setRoot(null);
- if (mPropertySheet != null) {
- mPropertySheet.selectionChanged(null, TreeSelection.EMPTY);
- }
- }
- }
- }
-
- /** Refresh all the icon state */
- public void refreshIcons() {
- TreeViewer treeViewer = getTreeViewer();
- if (treeViewer != null) {
- Tree tree = treeViewer.getTree();
- if (tree != null && !tree.isDisposed()) {
- treeViewer.refresh();
- }
- }
- }
-
- /**
- * Set whether the outline should be shown in the header
- *
- * @param show whether a header should be shown
- */
- public void setShowHeader(boolean show) {
- mShowHeader = show;
- }
-
- /**
- * Set whether the property sheet should be shown within this outline
- *
- * @param show whether the property sheet should show
- */
- public void setShowPropertySheet(boolean show) {
- if (show != mShowPropertySheet) {
- mShowPropertySheet = show;
- if (mControl == null) {
- return;
- }
-
- if (show && mPropertySheet == null) {
- createPropertySheet();
- } else if (!show) {
- mPropertySheetComposite.dispose();
- mPropertySheetComposite = null;
- mPropertySheet.dispose();
- mPropertySheet = null;
- }
-
- mControl.layout();
- }
- }
-
- @Override
- public void createControl(Composite parent) {
- mControl = new SelfOrientingSashForm(parent, SWT.VERTICAL);
-
- if (mShowHeader) {
- PageSiteComposite mOutlineComposite = new PageSiteComposite(mControl, SWT.BORDER);
- mOutlineComposite.setTitleText("Outline");
- mOutlineComposite.setTitleImage(IconFactory.getInstance().getIcon("components_view"));
- mOutlineComposite.setPage(new IPage() {
- @Override
- public void createControl(Composite outlineParent) {
- createOutline(outlineParent);
- }
-
- @Override
- public void dispose() {
- }
-
- @Override
- public Control getControl() {
- return getTreeViewer().getTree();
- }
-
- @Override
- public void setToolBar(IToolBarManager toolBarManager) {
- makeContributions(null, toolBarManager, null);
- toolBarManager.update(false);
- }
-
- @Override
- public void setFocus() {
- getControl().setFocus();
- }
- });
- } else {
- createOutline(mControl);
- }
-
- if (mShowPropertySheet) {
- createPropertySheet();
- }
- }
-
- private void createOutline(Composite parent) {
- if (AdtUtils.isEclipse4()) {
- // This is a workaround for the focus behavior in Eclipse 4 where
- // the framework ends up calling setFocus() on the first widget in the outline
- // AFTER a mouse click has been received. Specifically, if the user clicks in
- // the embedded property sheet to for example give a Text property editor focus,
- // then after the mouse click, the Outline window activation event is processed,
- // and this event causes setFocus() to be called first on the PageBookView (which
- // ends up calling setFocus on the first control, normally the TreeViewer), and
- // then on the Page itself. We're dealing with the page setFocus() in the override
- // of that method in the class, such that it does nothing.
- // However, we have to also disable the setFocus on the first control in the
- // outline page. To deal with that, we create our *own* first control in the
- // outline, and make its setFocus() a no-op. We also make it invisible, since we
- // don't actually want anything but the tree viewer showing in the outline.
- Text text = new Text(parent, SWT.NONE) {
- @Override
- public boolean setFocus() {
- // Focus no-op
- return true;
- }
-
- @Override
- protected void checkSubclass() {
- // Disable the check that prevents subclassing of SWT components
- }
- };
- text.setVisible(false);
- }
-
- super.createControl(parent);
-
- TreeViewer tv = getTreeViewer();
- tv.setAutoExpandLevel(2);
- tv.setContentProvider(new ContentProvider());
- tv.setLabelProvider(new LabelProvider());
- tv.setInput(mRootWrapper);
- tv.expandToLevel(mRootWrapper.getRoot(), 2);
-
- int supportedOperations = DND.DROP_COPY | DND.DROP_MOVE;
- Transfer[] transfers = new Transfer[] {
- SimpleXmlTransfer.getInstance()
- };
-
- tv.addDropSupport(supportedOperations, transfers, new OutlineDropListener(this, tv));
- tv.addDragSupport(supportedOperations, transfers, new OutlineDragListener(this, tv));
-
- // The tree viewer will hold CanvasViewInfo instances, however these
- // change each time the canvas is reloaded. OTOH layoutlib gives us
- // constant UiView keys which we can use to perform tree item comparisons.
- tv.setComparer(new IElementComparer() {
- @Override
- public int hashCode(Object element) {
- if (element instanceof CanvasViewInfo) {
- UiViewElementNode key = ((CanvasViewInfo) element).getUiViewNode();
- if (key != null) {
- return key.hashCode();
- }
- }
- if (element != null) {
- return element.hashCode();
- }
- return 0;
- }
-
- @Override
- public boolean equals(Object a, Object b) {
- if (a instanceof CanvasViewInfo && b instanceof CanvasViewInfo) {
- UiViewElementNode keyA = ((CanvasViewInfo) a).getUiViewNode();
- UiViewElementNode keyB = ((CanvasViewInfo) b).getUiViewNode();
- if (keyA != null) {
- return keyA.equals(keyB);
- }
- }
- if (a != null) {
- return a.equals(b);
- }
- return false;
- }
- });
- tv.addDoubleClickListener(new IDoubleClickListener() {
- @Override
- public void doubleClick(DoubleClickEvent event) {
- // This used to open the property view, but now that properties are docked
- // let's use it for something else -- such as showing the editor source
- /*
- // Front properties panel; its selection is already linked
- IWorkbenchPage page = getSite().getPage();
- try {
- page.showView(IPageLayout.ID_PROP_SHEET, null, IWorkbenchPage.VIEW_ACTIVATE);
- } catch (PartInitException e) {
- AdtPlugin.log(e, "Could not activate property sheet");
- }
- */
-
- TreeItem[] selection = getTreeViewer().getTree().getSelection();
- if (selection.length > 0) {
- CanvasViewInfo vi = getViewInfo(selection[0].getData());
- if (vi != null) {
- LayoutCanvas canvas = mGraphicalEditorPart.getCanvasControl();
- canvas.show(vi);
- }
- }
- }
- });
-
- setupContextMenu();
-
- // Listen to selection changes from the layout editor
- getSite().getPage().addSelectionListener(this);
- getControl().addDisposeListener(new DisposeListener() {
-
- @Override
- public void widgetDisposed(DisposeEvent e) {
- dispose();
- }
- });
-
- Tree tree = tv.getTree();
- tree.addKeyListener(new KeyListener() {
-
- @Override
- public void keyPressed(KeyEvent e) {
- if (e.character == '-') {
- if (mMoveUpAction.isEnabled()) {
- mMoveUpAction.run();
- }
- } else if (e.character == '+') {
- if (mMoveDownAction.isEnabled()) {
- mMoveDownAction.run();
- }
- }
- }
-
- @Override
- public void keyReleased(KeyEvent e) {
- }
- });
-
- setupTooltip();
- }
-
- /**
- * This flag is true when the mouse button is being pressed somewhere inside
- * the property sheet
- */
- private boolean mPressInPropSheet;
-
- private void createPropertySheet() {
- mPropertySheetComposite = new PageSiteComposite(mControl, SWT.BORDER);
- mPropertySheetComposite.setTitleText("Properties");
- mPropertySheetComposite.setTitleImage(IconFactory.getInstance().getIcon("properties_view"));
- mPropertySheet = new PropertySheetPage(mGraphicalEditorPart);
- mPropertySheetComposite.setPage(mPropertySheet);
- if (AdtUtils.isEclipse4()) {
- mPropertySheet.getControl().addMouseListener(new MouseListener() {
- @Override
- public void mouseDown(MouseEvent e) {
- mPressInPropSheet = true;
- }
-
- @Override
- public void mouseUp(MouseEvent e) {
- mPressInPropSheet = false;
- }
-
- @Override
- public void mouseDoubleClick(MouseEvent e) {
- }
- });
- }
- }
-
- @Override
- public void setFocus() {
- // Only call setFocus on the tree viewer if the mouse click isn't in the property
- // sheet area
- if (!mPressInPropSheet) {
- super.setFocus();
- }
- }
-
- @Override
- public void dispose() {
- mRootWrapper.setRoot(null);
-
- getSite().getPage().removeSelectionListener(this);
- super.dispose();
- if (mPropertySheet != null) {
- mPropertySheet.dispose();
- mPropertySheet = null;
- }
- }
-
- /**
- * Invoked by {@link LayoutCanvas} to set the model (a.k.a. the root view info).
- *
- * @param rootViewInfo The root of the view info hierarchy. Can be null.
- */
- public void setModel(CanvasViewInfo rootViewInfo) {
- if (!mActive) {
- return;
- }
-
- mRootWrapper.setRoot(rootViewInfo);
-
- TreeViewer tv = getTreeViewer();
- if (tv != null && !tv.getTree().isDisposed()) {
- Object[] expanded = tv.getExpandedElements();
- tv.refresh();
- tv.setExpandedElements(expanded);
- // Ensure that the root is expanded
- tv.expandToLevel(rootViewInfo, 2);
- }
- }
-
- /**
- * Returns the current tree viewer selection. Shouldn't be null,
- * although it can be {@link TreeSelection#EMPTY}.
- */
- @Override
- public ISelection getSelection() {
- return super.getSelection();
- }
-
- /**
- * Sets the outline selection.
- *
- * @param selection Only {@link ITreeSelection} will be used, otherwise the
- * selection will be cleared (including a null selection).
- */
- @Override
- public void setSelection(ISelection selection) {
- // TreeViewer should be able to deal with a null selection, but let's make it safe
- if (selection == null) {
- selection = TreeSelection.EMPTY;
- }
- if (selection.equals(TreeSelection.EMPTY)) {
- return;
- }
-
- super.setSelection(selection);
-
- TreeViewer tv = getTreeViewer();
- if (tv == null || !(selection instanceof ITreeSelection) || selection.isEmpty()) {
- return;
- }
-
- // auto-reveal the selection
- ITreeSelection treeSel = (ITreeSelection) selection;
- for (TreePath p : treeSel.getPaths()) {
- tv.expandToLevel(p, 1);
- }
- }
-
- @Override
- protected void fireSelectionChanged(ISelection selection) {
- super.fireSelectionChanged(selection);
- if (mPropertySheet != null && !mIgnoreSelection) {
- mPropertySheet.selectionChanged(null, selection);
- }
- }
-
- /**
- * Listens to a workbench selection.
- * Only listen on selection coming from {@link LayoutEditorDelegate}, which avoid
- * picking up our own selections.
- */
- @Override
- public void selectionChanged(IWorkbenchPart part, ISelection selection) {
- if (mIgnoreSelection) {
- return;
- }
-
- if (part instanceof IEditorPart) {
- LayoutEditorDelegate delegate = LayoutEditorDelegate.fromEditor((IEditorPart) part);
- if (delegate != null) {
- try {
- mIgnoreSelection = true;
- setSelection(selection);
-
- if (mPropertySheet != null) {
- mPropertySheet.selectionChanged(part, selection);
- }
- } finally {
- mIgnoreSelection = false;
- }
- }
- }
- }
-
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- if (!mIgnoreSelection) {
- super.selectionChanged(event);
- }
- }
-
- // ----
-
- /**
- * In theory, the root of the model should be the input of the {@link TreeViewer},
- * which would be the root {@link CanvasViewInfo}.
- * That means in theory {@link ContentProvider#getElements(Object)} should return
- * its own input as the single root node.
- * <p/>
- * However as described in JFace Bug 9262, this case is not properly handled by
- * a {@link TreeViewer} and leads to an infinite recursion in the tree viewer.
- * See https://bugs.eclipse.org/bugs/show_bug.cgi?id=9262
- * <p/>
- * The solution is to wrap the tree viewer input in a dummy root node that acts
- * as a parent. This class does just that.
- */
- private static class RootWrapper {
- private CanvasViewInfo mRoot;
-
- public void setRoot(CanvasViewInfo root) {
- mRoot = root;
- }
-
- public CanvasViewInfo getRoot() {
- return mRoot;
- }
- }
-
- /** Return the {@link CanvasViewInfo} associated with the given TreeItem's data field */
- /* package */ static CanvasViewInfo getViewInfo(Object viewData) {
- if (viewData instanceof RootWrapper) {
- return ((RootWrapper) viewData).getRoot();
- }
- if (viewData instanceof CanvasViewInfo) {
- return (CanvasViewInfo) viewData;
- }
- return null;
- }
-
- // --- Content and Label Providers ---
-
- /**
- * Content provider for the Outline model.
- * Objects are going to be {@link CanvasViewInfo}.
- */
- private static class ContentProvider implements ITreeContentProvider {
-
- @Override
- public Object[] getChildren(Object element) {
- if (element instanceof RootWrapper) {
- CanvasViewInfo root = ((RootWrapper)element).getRoot();
- if (root != null) {
- return new Object[] { root };
- }
- }
- if (element instanceof CanvasViewInfo) {
- List<CanvasViewInfo> children = ((CanvasViewInfo) element).getUniqueChildren();
- if (children != null) {
- return children.toArray();
- }
- }
- return new Object[0];
- }
-
- @Override
- public Object getParent(Object element) {
- if (element instanceof CanvasViewInfo) {
- return ((CanvasViewInfo) element).getParent();
- }
- return null;
- }
-
- @Override
- public boolean hasChildren(Object element) {
- if (element instanceof CanvasViewInfo) {
- List<CanvasViewInfo> children = ((CanvasViewInfo) element).getChildren();
- if (children != null) {
- return children.size() > 0;
- }
- }
- return false;
- }
-
- /**
- * Returns the root element.
- * Semantically, the root element is the single top-level XML element of the XML layout.
- */
- @Override
- public Object[] getElements(Object inputElement) {
- return getChildren(inputElement);
- }
-
- @Override
- public void dispose() {
- // pass
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- // pass
- }
- }
-
- /**
- * Label provider for the Outline model.
- * Objects are going to be {@link CanvasViewInfo}.
- */
- private class LabelProvider extends StyledCellLabelProvider {
- /**
- * Returns the element's logo with a fallback on the android logo.
- *
- * @param element the tree element
- * @return the image to be used as a logo
- */
- public Image getImage(Object element) {
- if (element instanceof CanvasViewInfo) {
- element = ((CanvasViewInfo) element).getUiViewNode();
- }
-
- if (element instanceof UiViewElementNode) {
- UiViewElementNode v = (UiViewElementNode) element;
- return v.getIcon();
- }
-
- return AdtPlugin.getAndroidLogo();
- }
-
- /**
- * Uses {@link UiElementNode#getStyledDescription} for the label for this tree item.
- */
- @Override
- public void update(ViewerCell cell) {
- Object element = cell.getElement();
- StyledString styledString = null;
-
- CanvasViewInfo vi = null;
- if (element instanceof CanvasViewInfo) {
- vi = (CanvasViewInfo) element;
- element = vi.getUiViewNode();
- }
-
- Image image = getImage(element);
-
- if (element instanceof UiElementNode) {
- UiElementNode node = (UiElementNode) element;
- styledString = node.getStyledDescription();
- Node xmlNode = node.getXmlNode();
- if (xmlNode instanceof Element) {
- Element e = (Element) xmlNode;
-
- // Temporary diagnostics code when developing GridLayout
- if (GridLayoutRule.sDebugGridLayout) {
-
- String namespace;
- if (e.getNodeName().equals(GRID_LAYOUT) ||
- e.getParentNode() != null
- && e.getParentNode().getNodeName().equals(GRID_LAYOUT)) {
- namespace = ANDROID_URI;
- } else {
- // Else: probably a v7 gridlayout
- IProject project = mGraphicalEditorPart.getProject();
- ProjectState projectState = Sdk.getProjectState(project);
- if (projectState != null && projectState.isLibrary()) {
- namespace = AUTO_URI;
- } else {
- ManifestInfo info = ManifestInfo.get(project);
- namespace = URI_PREFIX + info.getPackage();
- }
- }
-
- if (e.getNodeName() != null && e.getNodeName().endsWith(GRID_LAYOUT)) {
- // Attach rowCount/columnCount info
- String rowCount = e.getAttributeNS(namespace, ATTR_ROW_COUNT);
- if (rowCount.length() == 0) {
- rowCount = "?";
- }
- String columnCount = e.getAttributeNS(namespace, ATTR_COLUMN_COUNT);
- if (columnCount.length() == 0) {
- columnCount = "?";
- }
-
- styledString.append(" - columnCount=", QUALIFIER_STYLER);
- styledString.append(columnCount, QUALIFIER_STYLER);
- styledString.append(", rowCount=", QUALIFIER_STYLER);
- styledString.append(rowCount, QUALIFIER_STYLER);
- } else if (e.getParentNode() != null
- && e.getParentNode().getNodeName() != null
- && e.getParentNode().getNodeName().endsWith(GRID_LAYOUT)) {
- // Attach row/column info
- String row = e.getAttributeNS(namespace, ATTR_LAYOUT_ROW);
- if (row.length() == 0) {
- row = "?";
- }
- Styler colStyle = QUALIFIER_STYLER;
- String column = e.getAttributeNS(namespace, ATTR_LAYOUT_COLUMN);
- if (column.length() == 0) {
- column = "?";
- } else {
- String colCount = ((Element) e.getParentNode()).getAttributeNS(
- namespace, ATTR_COLUMN_COUNT);
- if (colCount.length() > 0 && Integer.parseInt(colCount) <=
- Integer.parseInt(column)) {
- colStyle = StyledString.createColorRegistryStyler(
- JFacePreferences.ERROR_COLOR, null);
- }
- }
- String rowSpan = e.getAttributeNS(namespace, ATTR_LAYOUT_ROW_SPAN);
- String columnSpan = e.getAttributeNS(namespace,
- ATTR_LAYOUT_COLUMN_SPAN);
- if (rowSpan.length() == 0) {
- rowSpan = "1";
- }
- if (columnSpan.length() == 0) {
- columnSpan = "1";
- }
-
- styledString.append(" - cell (row=", QUALIFIER_STYLER);
- styledString.append(row, QUALIFIER_STYLER);
- styledString.append(',', QUALIFIER_STYLER);
- styledString.append("col=", colStyle);
- styledString.append(column, colStyle);
- styledString.append(')', colStyle);
- styledString.append(", span=(", QUALIFIER_STYLER);
- styledString.append(columnSpan, QUALIFIER_STYLER);
- styledString.append(',', QUALIFIER_STYLER);
- styledString.append(rowSpan, QUALIFIER_STYLER);
- styledString.append(')', QUALIFIER_STYLER);
-
- String gravity = e.getAttributeNS(namespace, ATTR_LAYOUT_GRAVITY);
- if (gravity != null && gravity.length() > 0) {
- styledString.append(" : ", COUNTER_STYLER);
- styledString.append(gravity, COUNTER_STYLER);
- }
-
- }
- }
-
- if (e.hasAttributeNS(ANDROID_URI, ATTR_TEXT)) {
- // Show the text attribute
- String text = e.getAttributeNS(ANDROID_URI, ATTR_TEXT);
- if (text != null && text.length() > 0
- && !text.contains(node.getDescriptor().getUiName())) {
- if (text.charAt(0) == '@') {
- String resolved = mGraphicalEditorPart.findString(text);
- if (resolved != null) {
- text = resolved;
- }
- }
- if (styledString.length() < LABEL_MAX_WIDTH - LABEL_SEPARATOR.length()
- - 2) {
- styledString.append(LABEL_SEPARATOR, QUALIFIER_STYLER);
-
- styledString.append('"', QUALIFIER_STYLER);
- styledString.append(truncate(text, styledString), QUALIFIER_STYLER);
- styledString.append('"', QUALIFIER_STYLER);
- }
- }
- } else if (e.hasAttributeNS(ANDROID_URI, ATTR_SRC)) {
- // Show ImageView source attributes etc
- String src = e.getAttributeNS(ANDROID_URI, ATTR_SRC);
- if (src != null && src.length() > 0) {
- if (src.startsWith(DRAWABLE_PREFIX)) {
- src = src.substring(DRAWABLE_PREFIX.length());
- }
- styledString.append(LABEL_SEPARATOR, QUALIFIER_STYLER);
- styledString.append(truncate(src, styledString), QUALIFIER_STYLER);
- }
- } else if (e.getTagName().equals(SdkConstants.VIEW_INCLUDE)) {
- // Show the include reference.
-
- // Note: the layout attribute is NOT in the Android namespace
- String src = e.getAttribute(SdkConstants.ATTR_LAYOUT);
- if (src != null && src.length() > 0) {
- if (src.startsWith(LAYOUT_RESOURCE_PREFIX)) {
- src = src.substring(LAYOUT_RESOURCE_PREFIX.length());
- }
- styledString.append(LABEL_SEPARATOR, QUALIFIER_STYLER);
- styledString.append(truncate(src, styledString), QUALIFIER_STYLER);
- }
- }
- }
- } else if (element == null && vi != null) {
- // It's an inclusion-context: display it
- Reference includedWithin = mGraphicalEditorPart.getIncludedWithin();
- if (includedWithin != null) {
- styledString = new StyledString();
- styledString.append(includedWithin.getDisplayName(), QUALIFIER_STYLER);
- image = IconFactory.getInstance().getIcon(SdkConstants.VIEW_INCLUDE);
- }
- }
-
- if (styledString == null) {
- styledString = new StyledString();
- styledString.append(element == null ? "(null)" : element.toString());
- }
-
- cell.setText(styledString.toString());
- cell.setStyleRanges(styledString.getStyleRanges());
- cell.setImage(image);
- super.update(cell);
- }
-
- @Override
- public boolean isLabelProperty(Object element, String property) {
- return super.isLabelProperty(element, property);
- }
- }
-
- // --- Context Menu ---
-
- /**
- * This viewer uses its own actions that delegate to the ones given
- * by the {@link LayoutCanvas}. All the processing is actually handled
- * directly by the canvas and this viewer only gets refreshed as a
- * consequence of the canvas changing the XML model.
- */
- private void setupContextMenu() {
-
- mMenuManager = new MenuManager();
- mMenuManager.removeAll();
-
- mMenuManager.add(mMoveUpAction);
- mMenuManager.add(mMoveDownAction);
- mMenuManager.add(new Separator());
-
- mMenuManager.add(new SelectionManager.SelectionMenu(mGraphicalEditorPart));
- mMenuManager.add(new Separator());
- final String prefix = LayoutCanvas.PREFIX_CANVAS_ACTION;
- mMenuManager.add(new DelegateAction(prefix + ActionFactory.CUT.getId()));
- mMenuManager.add(new DelegateAction(prefix + ActionFactory.COPY.getId()));
- mMenuManager.add(new DelegateAction(prefix + ActionFactory.PASTE.getId()));
-
- mMenuManager.add(new Separator());
-
- mMenuManager.add(new DelegateAction(prefix + ActionFactory.DELETE.getId()));
-
- mMenuManager.addMenuListener(new IMenuListener() {
- @Override
- public void menuAboutToShow(IMenuManager manager) {
- // Update all actions to match their LayoutCanvas counterparts
- for (IContributionItem contrib : manager.getItems()) {
- if (contrib instanceof ActionContributionItem) {
- IAction action = ((ActionContributionItem) contrib).getAction();
- if (action instanceof DelegateAction) {
- ((DelegateAction) action).updateFromEditorPart(mGraphicalEditorPart);
- }
- }
- }
- }
- });
-
- new DynamicContextMenu(
- mGraphicalEditorPart.getEditorDelegate(),
- mGraphicalEditorPart.getCanvasControl(),
- mMenuManager);
-
- getTreeViewer().getTree().setMenu(mMenuManager.createContextMenu(getControl()));
-
- // Update Move Up/Move Down state only when the menu is opened
- getTreeViewer().getTree().addMenuDetectListener(new MenuDetectListener() {
- @Override
- public void menuDetected(MenuDetectEvent e) {
- mMenuManager.update(IAction.ENABLED);
- }
- });
- }
-
- /**
- * An action that delegates its properties and behavior to a target action.
- * The target action can be null or it can change overtime, typically as the
- * layout canvas' editor part is activated or closed.
- */
- private static class DelegateAction extends Action {
- private IAction mTargetAction;
- private final String mCanvasActionId;
-
- public DelegateAction(String canvasActionId) {
- super(canvasActionId);
- setId(canvasActionId);
- mCanvasActionId = canvasActionId;
- }
-
- // --- Methods form IAction ---
-
- /** Returns the target action's {@link #isEnabled()} if defined, or false. */
- @Override
- public boolean isEnabled() {
- return mTargetAction == null ? false : mTargetAction.isEnabled();
- }
-
- /** Returns the target action's {@link #isChecked()} if defined, or false. */
- @Override
- public boolean isChecked() {
- return mTargetAction == null ? false : mTargetAction.isChecked();
- }
-
- /** Returns the target action's {@link #isHandled()} if defined, or false. */
- @Override
- public boolean isHandled() {
- return mTargetAction == null ? false : mTargetAction.isHandled();
- }
-
- /** Runs the target action if defined. */
- @Override
- public void run() {
- if (mTargetAction != null) {
- mTargetAction.run();
- }
- super.run();
- }
-
- /**
- * Updates this action to delegate to its counterpart in the given editor part
- *
- * @param editorPart The editor being updated
- */
- public void updateFromEditorPart(GraphicalEditorPart editorPart) {
- LayoutCanvas canvas = editorPart == null ? null : editorPart.getCanvasControl();
- if (canvas == null) {
- mTargetAction = null;
- } else {
- mTargetAction = canvas.getAction(mCanvasActionId);
- }
-
- if (mTargetAction != null) {
- setText(mTargetAction.getText());
- setId(mTargetAction.getId());
- setDescription(mTargetAction.getDescription());
- setImageDescriptor(mTargetAction.getImageDescriptor());
- setHoverImageDescriptor(mTargetAction.getHoverImageDescriptor());
- setDisabledImageDescriptor(mTargetAction.getDisabledImageDescriptor());
- setToolTipText(mTargetAction.getToolTipText());
- setActionDefinitionId(mTargetAction.getActionDefinitionId());
- setHelpListener(mTargetAction.getHelpListener());
- setAccelerator(mTargetAction.getAccelerator());
- setChecked(mTargetAction.isChecked());
- setEnabled(mTargetAction.isEnabled());
- } else {
- setEnabled(false);
- }
- }
- }
-
- /** Returns the associated editor with this outline */
- /* package */GraphicalEditorPart getEditor() {
- return mGraphicalEditorPart;
- }
-
- @Override
- public void setActionBars(IActionBars actionBars) {
- super.setActionBars(actionBars);
-
- // Map Outline actions to canvas actions such that they share Undo context etc
- LayoutCanvas canvas = mGraphicalEditorPart.getCanvasControl();
- canvas.updateGlobalActions(actionBars);
-
- // Special handling for Select All since it's different than the canvas (will
- // include selecting the root etc)
- actionBars.setGlobalActionHandler(mTreeSelectAllAction.getId(), mTreeSelectAllAction);
- actionBars.updateActionBars();
- }
-
- // ---- Move Up/Down Support ----
-
- /** Returns true if the current selected item can be moved */
- private boolean canMove(boolean forward) {
- CanvasViewInfo viewInfo = getSingleSelectedItem();
- if (viewInfo != null) {
- UiViewElementNode node = viewInfo.getUiViewNode();
- if (forward) {
- return findNext(node) != null;
- } else {
- return findPrevious(node) != null;
- }
- }
-
- return false;
- }
-
- /** Moves the current selected item down (forward) or up (not forward) */
- private void move(boolean forward) {
- CanvasViewInfo viewInfo = getSingleSelectedItem();
- if (viewInfo != null) {
- final Pair<UiViewElementNode, Integer> target;
- UiViewElementNode selected = viewInfo.getUiViewNode();
- if (forward) {
- target = findNext(selected);
- } else {
- target = findPrevious(selected);
- }
- if (target != null) {
- final LayoutCanvas canvas = mGraphicalEditorPart.getCanvasControl();
- final SelectionManager selectionManager = canvas.getSelectionManager();
- final ArrayList<SelectionItem> dragSelection = new ArrayList<SelectionItem>();
- dragSelection.add(selectionManager.createSelection(viewInfo));
- SelectionManager.sanitize(dragSelection);
-
- if (!dragSelection.isEmpty()) {
- final SimpleElement[] elements = SelectionItem.getAsElements(dragSelection);
- UiViewElementNode parentNode = target.getFirst();
- final NodeProxy targetNode = canvas.getNodeFactory().create(parentNode);
-
- // Record children of the target right before the drop (such that we
- // can find out after the drop which exact children were inserted)
- Set<INode> children = new HashSet<INode>();
- for (INode node : targetNode.getChildren()) {
- children.add(node);
- }
-
- String label = MoveGesture.computeUndoLabel(targetNode,
- elements, DND.DROP_MOVE);
- canvas.getEditorDelegate().getEditor().wrapUndoEditXmlModel(label, new Runnable() {
- @Override
- public void run() {
- InsertType insertType = InsertType.MOVE_INTO;
- if (dragSelection.get(0).getNode().getParent() == targetNode) {
- insertType = InsertType.MOVE_WITHIN;
- }
- canvas.getRulesEngine().setInsertType(insertType);
- int index = target.getSecond();
- BaseLayoutRule.insertAt(targetNode, elements, false, index);
- targetNode.applyPendingChanges();
- canvas.getClipboardSupport().deleteSelection("Remove", dragSelection);
- }
- });
-
- // Now find out which nodes were added, and look up their
- // corresponding CanvasViewInfos
- final List<INode> added = new ArrayList<INode>();
- for (INode node : targetNode.getChildren()) {
- if (!children.contains(node)) {
- added.add(node);
- }
- }
-
- selectionManager.setOutlineSelection(added);
- }
- }
- }
- }
-
- /**
- * Returns the {@link CanvasViewInfo} for the currently selected item, or null if
- * there are no or multiple selected items
- *
- * @return the current selected item if there is exactly one item selected
- */
- private CanvasViewInfo getSingleSelectedItem() {
- TreeItem[] selection = getTreeViewer().getTree().getSelection();
- if (selection.length == 1) {
- return getViewInfo(selection[0].getData());
- }
-
- return null;
- }
-
-
- /** Returns the pair [parent,index] of the next node (when iterating forward) */
- @VisibleForTesting
- /* package */ static Pair<UiViewElementNode, Integer> findNext(UiViewElementNode node) {
- UiElementNode parent = node.getUiParent();
- if (parent == null) {
- return null;
- }
-
- UiElementNode next = node.getUiNextSibling();
- if (next != null) {
- if (DescriptorsUtils.canInsertChildren(next.getDescriptor(), null)) {
- return getFirstPosition(next);
- } else {
- return getPositionAfter(next);
- }
- }
-
- next = parent.getUiNextSibling();
- if (next != null) {
- return getPositionBefore(next);
- } else {
- UiElementNode grandParent = parent.getUiParent();
- if (grandParent != null) {
- return getLastPosition(grandParent);
- }
- }
-
- return null;
- }
-
- /** Returns the pair [parent,index] of the previous node (when iterating backward) */
- @VisibleForTesting
- /* package */ static Pair<UiViewElementNode, Integer> findPrevious(UiViewElementNode node) {
- UiElementNode prev = node.getUiPreviousSibling();
- if (prev != null) {
- UiElementNode curr = prev;
- while (true) {
- List<UiElementNode> children = curr.getUiChildren();
- if (children.size() > 0) {
- curr = children.get(children.size() - 1);
- continue;
- }
- if (DescriptorsUtils.canInsertChildren(curr.getDescriptor(), null)) {
- return getFirstPosition(curr);
- } else {
- if (curr == prev) {
- return getPositionBefore(curr);
- } else {
- return getPositionAfter(curr);
- }
- }
- }
- }
-
- return getPositionBefore(node.getUiParent());
- }
-
- /** Returns the pair [parent,index] of the position immediately before the given node */
- private static Pair<UiViewElementNode, Integer> getPositionBefore(UiElementNode node) {
- if (node != null) {
- UiElementNode parent = node.getUiParent();
- if (parent != null && parent instanceof UiViewElementNode) {
- return Pair.of((UiViewElementNode) parent, node.getUiSiblingIndex());
- }
- }
-
- return null;
- }
-
- /** Returns the pair [parent,index] of the position immediately following the given node */
- private static Pair<UiViewElementNode, Integer> getPositionAfter(UiElementNode node) {
- if (node != null) {
- UiElementNode parent = node.getUiParent();
- if (parent != null && parent instanceof UiViewElementNode) {
- return Pair.of((UiViewElementNode) parent, node.getUiSiblingIndex() + 1);
- }
- }
-
- return null;
- }
-
- /** Returns the pair [parent,index] of the first position inside the given parent */
- private static Pair<UiViewElementNode, Integer> getFirstPosition(UiElementNode parent) {
- if (parent != null && parent instanceof UiViewElementNode) {
- return Pair.of((UiViewElementNode) parent, 0);
- }
-
- return null;
- }
-
- /**
- * Returns the pair [parent,index] of the last position after the given node's
- * children
- */
- private static Pair<UiViewElementNode, Integer> getLastPosition(UiElementNode parent) {
- if (parent != null && parent instanceof UiViewElementNode) {
- return Pair.of((UiViewElementNode) parent, parent.getUiChildren().size());
- }
-
- return null;
- }
-
- /**
- * Truncates the given text such that it will fit into the given {@link StyledString}
- * up to a maximum length of {@link #LABEL_MAX_WIDTH}.
- *
- * @param text the text to truncate
- * @param string the existing string to be appended to
- * @return the truncated string
- */
- private static String truncate(String text, StyledString string) {
- int existingLength = string.length();
-
- if (text.length() + existingLength > LABEL_MAX_WIDTH) {
- int truncatedLength = LABEL_MAX_WIDTH - existingLength - 3;
- if (truncatedLength > 0) {
- return String.format("%1$s...", text.substring(0, truncatedLength));
- } else {
- return ""; //$NON-NLS-1$
- }
- }
-
- return text;
- }
-
- @Override
- public void setToolBar(IToolBarManager toolBarManager) {
- makeContributions(null, toolBarManager, null);
- toolBarManager.update(false);
- }
-
- /**
- * Sets up a custom tooltip when hovering over tree items. It currently displays the error
- * message for the lint warning associated with each node, if any (and only if the hover
- * is over the icon portion).
- */
- private void setupTooltip() {
- final Tree tree = getTreeViewer().getTree();
-
- // This is based on SWT Snippet 125
- final Listener listener = new Listener() {
- Shell mTip = null;
- Label mLabel = null;
-
- @Override
- public void handleEvent(Event event) {
- switch(event.type) {
- case SWT.Dispose:
- case SWT.KeyDown:
- case SWT.MouseExit:
- case SWT.MouseDown:
- case SWT.MouseMove:
- if (mTip != null) {
- mTip.dispose();
- mTip = null;
- mLabel = null;
- }
- break;
- case SWT.MouseHover:
- if (mTip != null) {
- mTip.dispose();
- mTip = null;
- mLabel = null;
- }
-
- String tooltip = null;
-
- TreeItem item = tree.getItem(new Point(event.x, event.y));
- if (item != null) {
- Rectangle rect = item.getBounds(0);
- if (event.x - rect.x > 16) { // 16: Standard width of our outline icons
- return;
- }
-
- Object data = item.getData();
- if (data != null && data instanceof CanvasViewInfo) {
- LayoutEditorDelegate editor = mGraphicalEditorPart.getEditorDelegate();
- CanvasViewInfo vi = (CanvasViewInfo) data;
- IMarker marker = editor.getIssueForNode(vi.getUiViewNode());
- if (marker != null) {
- tooltip = marker.getAttribute(IMarker.MESSAGE, null);
- }
- }
-
- if (tooltip != null) {
- Shell shell = tree.getShell();
- Display display = tree.getDisplay();
-
- Color fg = display.getSystemColor(SWT.COLOR_INFO_FOREGROUND);
- Color bg = display.getSystemColor(SWT.COLOR_INFO_BACKGROUND);
- mTip = new Shell(shell, SWT.ON_TOP | SWT.NO_FOCUS | SWT.TOOL);
- mTip.setBackground(bg);
- FillLayout layout = new FillLayout();
- layout.marginWidth = 1;
- layout.marginHeight = 1;
- mTip.setLayout(layout);
- mLabel = new Label(mTip, SWT.WRAP);
- mLabel.setForeground(fg);
- mLabel.setBackground(bg);
- mLabel.setText(tooltip);
- mLabel.addListener(SWT.MouseExit, this);
- mLabel.addListener(SWT.MouseDown, this);
-
- Point pt = tree.toDisplay(rect.x, rect.y + rect.height);
- Rectangle displayBounds = display.getBounds();
- // -10: Don't extend -all- the way to the edge of the screen
- // which would make it look like it has been cropped
- int availableWidth = displayBounds.x + displayBounds.width - pt.x - 10;
- if (availableWidth < 80) {
- availableWidth = 80;
- }
- Point size = mTip.computeSize(SWT.DEFAULT, SWT.DEFAULT);
- if (size.x > availableWidth) {
- size = mTip.computeSize(availableWidth, SWT.DEFAULT);
- }
- mTip.setBounds(pt.x, pt.y, size.x, size.y);
-
- mTip.setVisible(true);
- }
- }
- }
- }
- };
-
- tree.addListener(SWT.Dispose, listener);
- tree.addListener(SWT.KeyDown, listener);
- tree.addListener(SWT.MouseMove, listener);
- tree.addListener(SWT.MouseHover, listener);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/Overlay.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/Overlay.java
deleted file mode 100644
index 9b7e0eb18..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/Overlay.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import org.eclipse.swt.graphics.Device;
-import org.eclipse.swt.graphics.GC;
-
-/**
- * An Overlay is a set of graphics which can be painted on top of the visual
- * editor. Different {@link Gesture}s produce context specific overlays, such as
- * swiping rectangles from the {@link MarqueeGesture} and guidelines from the
- * {@link MoveGesture}.
- */
-public abstract class Overlay {
- private Device mDevice;
-
- /** Whether the hover is hidden */
- private boolean mHiding;
-
- /**
- * Construct the overlay, using the given graphics context for painting.
- */
- public Overlay() {
- super();
- }
-
- /**
- * Initializes the overlay before the first use, if applicable. This is a
- * good place to initialize resources like colors.
- *
- * @param device The device to allocate resources for; the parameter passed
- * to {@link #paint} will correspond to this device.
- */
- public void create(Device device) {
- mDevice = device;
- }
-
- /**
- * Releases resources held by the overlay. Called by the editor when an
- * overlay has been removed.
- */
- public void dispose() {
- }
-
- /**
- * Paints the overlay.
- *
- * @param gc The SWT {@link GC} object to draw into.
- */
- public void paint(GC gc) {
- throw new IllegalArgumentException("paint() not implemented, probably done "
- + "with specialized paint signature");
- }
-
- /** Returns the device associated with this overlay */
- public Device getDevice() {
- return mDevice;
- }
-
- /**
- * Returns whether the overlay is hidden
- *
- * @return true if the selection overlay is hidden
- */
- public boolean isHiding() {
- return mHiding;
- }
-
- /**
- * Hides the overlay
- *
- * @param hiding true to hide the overlay, false to unhide it (default)
- */
- public void setHiding(boolean hiding) {
- mHiding = hiding;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/PaletteControl.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/PaletteControl.java
deleted file mode 100644
index 46168b70f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/PaletteControl.java
+++ /dev/null
@@ -1,1265 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.ATTR_TEXT;
-import static com.android.SdkConstants.VALUE_WRAP_CONTENT;
-import static com.android.SdkConstants.XMLNS_ANDROID;
-import static com.android.SdkConstants.XMLNS_URI;
-
-import com.android.ide.common.api.InsertType;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.api.RuleAction.Toggle;
-import com.android.ide.common.rendering.LayoutLibrary;
-import com.android.ide.common.rendering.api.Capability;
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.ide.common.rendering.api.RenderSession;
-import com.android.ide.common.rendering.api.ViewInfo;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DocumentDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigurationChooser;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.CustomViewDescriptorService;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.NodeFactory;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.NodeProxy;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.PaletteMetadataDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.ViewMetadataRepository;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.ViewMetadataRepository.RenderMode;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiDocumentNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.sdklib.IAndroidTarget;
-import com.android.utils.Pair;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.CLabel;
-import org.eclipse.swt.dnd.DND;
-import org.eclipse.swt.dnd.DragSource;
-import org.eclipse.swt.dnd.DragSourceEvent;
-import org.eclipse.swt.dnd.DragSourceListener;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.events.MenuDetectEvent;
-import org.eclipse.swt.events.MenuDetectListener;
-import org.eclipse.swt.events.MouseAdapter;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseTrackListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.ImageData;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.ToolBar;
-import org.eclipse.swt.widgets.ToolItem;
-import org.eclipse.wb.internal.core.editor.structure.IPage;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-import java.awt.image.BufferedImage;
-import java.io.IOException;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * A palette control for the {@link GraphicalEditorPart}.
- * <p/>
- * The palette contains several groups, each with a UI name (e.g. layouts and views) and each
- * with a list of element descriptors.
- * <p/>
- *
- * TODO list:
- * - The available items should depend on the actual GLE2 Canvas selection. Selected android
- * views should force filtering on what they accept can be dropped on them (e.g. TabHost,
- * TableLayout). Should enable/disable them, not hide them, to avoid shuffling around.
- * - Optional: a text filter
- * - Optional: have context-sensitive tools items, e.g. selection arrow tool,
- * group selection tool, alignment, etc.
- */
-public class PaletteControl extends Composite {
-
- /**
- * Wrapper to create a {@link PaletteControl}
- */
- static class PalettePage implements IPage {
- private final GraphicalEditorPart mEditorPart;
- private PaletteControl mControl;
-
- PalettePage(GraphicalEditorPart editor) {
- mEditorPart = editor;
- }
-
- @Override
- public void createControl(Composite parent) {
- mControl = new PaletteControl(parent, mEditorPart);
- }
-
- @Override
- public Control getControl() {
- return mControl;
- }
-
- @Override
- public void dispose() {
- mControl.dispose();
- }
-
- @Override
- public void setToolBar(IToolBarManager toolBarManager) {
- }
-
- /**
- * Add tool bar items to the given toolbar
- *
- * @param toolbar the toolbar to add items into
- */
- void createToolbarItems(final ToolBar toolbar) {
- final ToolItem popupMenuItem = new ToolItem(toolbar, SWT.PUSH);
- popupMenuItem.setToolTipText("View Menu");
- popupMenuItem.setImage(IconFactory.getInstance().getIcon("view_menu"));
- popupMenuItem.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- Rectangle bounds = popupMenuItem.getBounds();
- // Align menu horizontally with the toolbar button and
- // vertically with the bottom of the toolbar
- Point point = toolbar.toDisplay(bounds.x, bounds.y + bounds.height);
- mControl.showMenu(point.x, point.y);
- }
- });
- }
-
- @Override
- public void setFocus() {
- mControl.setFocus();
- }
- }
-
- /**
- * The parent grid layout that contains all the {@link Toggle} and
- * {@link IconTextItem} widgets.
- */
- private GraphicalEditorPart mEditor;
- private Color mBackground;
- private Color mForeground;
-
- /** The palette modes control various ways to visualize and lay out the views */
- private static enum PaletteMode {
- /** Show rendered previews of the views */
- PREVIEW("Show Previews", true),
- /** Show rendered previews of the views, scaled down to 75% */
- SMALL_PREVIEW("Show Small Previews", true),
- /** Show rendered previews of the views, scaled down to 50% */
- TINY_PREVIEW("Show Tiny Previews", true),
- /** Show an icon + text label */
- ICON_TEXT("Show Icon and Text", false),
- /** Show only icons, packed multiple per row */
- ICON_ONLY("Show Only Icons", true);
-
- PaletteMode(String actionLabel, boolean wrap) {
- mActionLabel = actionLabel;
- mWrap = wrap;
- }
-
- public String getActionLabel() {
- return mActionLabel;
- }
-
- public boolean getWrap() {
- return mWrap;
- }
-
- public boolean isPreview() {
- return this == PREVIEW || this == SMALL_PREVIEW || this == TINY_PREVIEW;
- }
-
- public boolean isScaledPreview() {
- return this == SMALL_PREVIEW || this == TINY_PREVIEW;
- }
-
- private final String mActionLabel;
- private final boolean mWrap;
- };
-
- /** Token used in preference string to record alphabetical sorting */
- private static final String VALUE_ALPHABETICAL = "alpha"; //$NON-NLS-1$
- /** Token used in preference string to record categories being turned off */
- private static final String VALUE_NO_CATEGORIES = "nocat"; //$NON-NLS-1$
- /** Token used in preference string to record auto close being turned off */
- private static final String VALUE_NO_AUTOCLOSE = "noauto"; //$NON-NLS-1$
-
- private final PreviewIconFactory mPreviewIconFactory = new PreviewIconFactory(this);
- private PaletteMode mPaletteMode = null;
- /** Use alphabetical sorting instead of natural order? */
- private boolean mAlphabetical;
- /** Use categories instead of a single large list of views? */
- private boolean mCategories = true;
- /** Auto-close the previous category when new categories are opened */
- private boolean mAutoClose = true;
- private AccordionControl mAccordion;
- private String mCurrentTheme;
- private String mCurrentDevice;
- private IAndroidTarget mCurrentTarget;
- private AndroidTargetData mCurrentTargetData;
-
- /**
- * Create the composite.
- * @param parent The parent composite.
- * @param editor An editor associated with this palette.
- */
- public PaletteControl(Composite parent, GraphicalEditorPart editor) {
- super(parent, SWT.NONE);
-
- mEditor = editor;
- }
-
- /** Reads UI mode from persistent store to preserve palette mode across IDE sessions */
- private void loadPaletteMode() {
- String paletteModes = AdtPrefs.getPrefs().getPaletteModes();
- if (paletteModes.length() > 0) {
- String[] tokens = paletteModes.split(","); //$NON-NLS-1$
- try {
- mPaletteMode = PaletteMode.valueOf(tokens[0]);
- } catch (Throwable t) {
- mPaletteMode = PaletteMode.values()[0];
- }
- mAlphabetical = paletteModes.contains(VALUE_ALPHABETICAL);
- mCategories = !paletteModes.contains(VALUE_NO_CATEGORIES);
- mAutoClose = !paletteModes.contains(VALUE_NO_AUTOCLOSE);
- } else {
- mPaletteMode = PaletteMode.SMALL_PREVIEW;
- }
- }
-
- /**
- * Returns the most recently stored version of auto-close-mode; this is the last
- * user-initiated setting of the auto-close mode (we programmatically switch modes when
- * you enter icons-only mode, and set it back to this when going to any other mode)
- */
- private boolean getSavedAutoCloseMode() {
- return !AdtPrefs.getPrefs().getPaletteModes().contains(VALUE_NO_AUTOCLOSE);
- }
-
- /** Saves UI mode to persistent store to preserve palette mode across IDE sessions */
- private void savePaletteMode() {
- StringBuilder sb = new StringBuilder();
- sb.append(mPaletteMode);
- if (mAlphabetical) {
- sb.append(',').append(VALUE_ALPHABETICAL);
- }
- if (!mCategories) {
- sb.append(',').append(VALUE_NO_CATEGORIES);
- }
- if (!mAutoClose) {
- sb.append(',').append(VALUE_NO_AUTOCLOSE);
- }
- AdtPrefs.getPrefs().setPaletteModes(sb.toString());
- }
-
- private void refreshPalette() {
- IAndroidTarget oldTarget = mCurrentTarget;
- mCurrentTarget = null;
- mCurrentTargetData = null;
- mCurrentTheme = null;
- mCurrentDevice = null;
- reloadPalette(oldTarget);
- }
-
- @Override
- protected void checkSubclass() {
- // Disable the check that prevents subclassing of SWT components
- }
-
- @Override
- public void dispose() {
- if (mBackground != null) {
- mBackground.dispose();
- mBackground = null;
- }
- if (mForeground != null) {
- mForeground.dispose();
- mForeground = null;
- }
-
- super.dispose();
- }
-
- /**
- * Returns the currently displayed target
- *
- * @return the current target, or null
- */
- public IAndroidTarget getCurrentTarget() {
- return mCurrentTarget;
- }
-
- /**
- * Returns the currently displayed theme (in palette modes that support previewing)
- *
- * @return the current theme, or null
- */
- public String getCurrentTheme() {
- return mCurrentTheme;
- }
-
- /**
- * Returns the currently displayed device (in palette modes that support previewing)
- *
- * @return the current device, or null
- */
- public String getCurrentDevice() {
- return mCurrentDevice;
- }
-
- /** Returns true if previews in the palette should be made available */
- private boolean previewsAvailable() {
- // Not layoutlib 5 -- we require custom background support to do
- // a decent job with previews
- LayoutLibrary layoutLibrary = mEditor.getLayoutLibrary();
- return layoutLibrary != null && layoutLibrary.supports(Capability.CUSTOM_BACKGROUND_COLOR);
- }
-
- /**
- * Loads or reloads the palette elements by using the layout and view descriptors from the
- * given target data.
- *
- * @param target The target that has just been loaded
- */
- public void reloadPalette(IAndroidTarget target) {
- ConfigurationChooser configChooser = mEditor.getConfigurationChooser();
- String theme = configChooser.getThemeName();
- String device = configChooser.getDeviceName();
- if (device == null) {
- return;
- }
- AndroidTargetData targetData =
- target != null ? Sdk.getCurrent().getTargetData(target) : null;
- if (target == mCurrentTarget && targetData == mCurrentTargetData
- && mCurrentTheme != null && mCurrentTheme.equals(theme)
- && mCurrentDevice != null && mCurrentDevice.equals(device)) {
- return;
- }
- mCurrentTheme = theme;
- mCurrentTarget = target;
- mCurrentTargetData = targetData;
- mCurrentDevice = device;
- mPreviewIconFactory.reset();
-
- if (targetData == null) {
- return;
- }
-
- Set<String> expandedCategories = null;
- if (mAccordion != null) {
- expandedCategories = mAccordion.getExpandedCategories();
- // We auto-expand all categories when showing icons-only. When returning to some
- // other mode we don't want to retain all categories open.
- if (expandedCategories.size() > 3) {
- expandedCategories = null;
- }
- }
-
- // Erase old content and recreate new
- for (Control c : getChildren()) {
- c.dispose();
- }
-
- if (mPaletteMode == null) {
- loadPaletteMode();
- assert mPaletteMode != null;
- }
-
- // Ensure that the palette mode is supported on this version of the layout library
- if (!previewsAvailable()) {
- if (mPaletteMode.isPreview()) {
- mPaletteMode = PaletteMode.ICON_TEXT;
- }
- }
-
- if (mPaletteMode.isPreview()) {
- if (mForeground != null) {
- mForeground.dispose();
- mForeground = null;
- }
- if (mBackground != null) {
- mBackground.dispose();
- mBackground = null;
- }
- RGB background = mPreviewIconFactory.getBackgroundColor();
- if (background != null) {
- mBackground = new Color(getDisplay(), background);
- }
- RGB foreground = mPreviewIconFactory.getForegroundColor();
- if (foreground != null) {
- mForeground = new Color(getDisplay(), foreground);
- }
- }
-
- List<String> headers = Collections.emptyList();
- final Map<String, List<ViewElementDescriptor>> categoryToItems;
- categoryToItems = new HashMap<String, List<ViewElementDescriptor>>();
- headers = new ArrayList<String>();
- List<Pair<String,List<ViewElementDescriptor>>> paletteEntries =
- ViewMetadataRepository.get().getPaletteEntries(targetData,
- mAlphabetical, mCategories);
- for (Pair<String,List<ViewElementDescriptor>> pair : paletteEntries) {
- String category = pair.getFirst();
- List<ViewElementDescriptor> categoryItems = pair.getSecond();
- headers.add(category);
- categoryToItems.put(category, categoryItems);
- }
-
- headers.add("Custom & Library Views");
-
- // Set the categories to expand the first item if
- // (1) we don't have a previously selected category, or
- // (2) there's just one category anyway, or
- // (3) the set of categories have changed so our previously selected category
- // doesn't exist anymore (can happen when you toggle "Show Categories")
- if ((expandedCategories == null && headers.size() > 0) || headers.size() == 1 ||
- (expandedCategories != null && expandedCategories.size() >= 1
- && !headers.contains(
- expandedCategories.iterator().next().replace("&&", "&")))) { //$NON-NLS-1$ //$NON-NLS-2$
- // Expand the first category if we don't have a previous selection (e.g. refresh)
- expandedCategories = Collections.singleton(headers.get(0));
- }
-
- boolean wrap = mPaletteMode.getWrap();
-
- // Pack icon-only view vertically; others stretch to fill palette region
- boolean fillVertical = mPaletteMode != PaletteMode.ICON_ONLY;
-
- mAccordion = new AccordionControl(this, SWT.NONE, headers, fillVertical, wrap,
- expandedCategories) {
- @Override
- protected Composite createChildContainer(Composite parent, Object header, int style) {
- assert categoryToItems != null;
- List<ViewElementDescriptor> list = categoryToItems.get(header);
- final Composite composite;
- if (list == null) {
- assert header.equals("Custom & Library Views");
-
- Composite wrapper = new Composite(parent, SWT.NONE);
- GridLayout gridLayout = new GridLayout(1, false);
- gridLayout.marginWidth = gridLayout.marginHeight = 0;
- gridLayout.horizontalSpacing = gridLayout.verticalSpacing = 0;
- gridLayout.marginBottom = 3;
- wrapper.setLayout(gridLayout);
- if (mPaletteMode.isPreview() && mBackground != null) {
- wrapper.setBackground(mBackground);
- }
- composite = super.createChildContainer(wrapper, header, style);
- if (mPaletteMode.isPreview() && mBackground != null) {
- composite.setBackground(mBackground);
- }
- composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
-
- Button refreshButton = new Button(wrapper, SWT.PUSH | SWT.FLAT);
- refreshButton.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER,
- false, false, 1, 1));
- refreshButton.setText("Refresh");
- refreshButton.setImage(IconFactory.getInstance().getIcon("refresh")); //$NON-NLS-1$
- refreshButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- CustomViewFinder finder = CustomViewFinder.get(mEditor.getProject());
- finder.refresh(new ViewFinderListener(composite));
- }
- });
-
- wrapper.layout(true);
- } else {
- composite = super.createChildContainer(parent, header, style);
- if (mPaletteMode.isPreview() && mBackground != null) {
- composite.setBackground(mBackground);
- }
- }
- addMenu(composite);
- return composite;
- }
- @Override
- protected void createChildren(Composite parent, Object header) {
- assert categoryToItems != null;
- List<ViewElementDescriptor> list = categoryToItems.get(header);
- if (list == null) {
- assert header.equals("Custom & Library Views");
- addCustomItems(parent);
- return;
- } else {
- for (ViewElementDescriptor desc : list) {
- createItem(parent, desc);
- }
- }
- }
- };
- addMenu(mAccordion);
- for (CLabel headerLabel : mAccordion.getHeaderLabels()) {
- addMenu(headerLabel);
- }
- setLayout(new FillLayout());
-
- // Expand All for icon-only mode, but don't store it as the persistent auto-close mode;
- // when we enter other modes it will read back whatever persistent mode.
- if (mPaletteMode == PaletteMode.ICON_ONLY) {
- mAccordion.expandAll(true);
- mAccordion.setAutoClose(false);
- } else {
- mAccordion.setAutoClose(getSavedAutoCloseMode());
- }
-
- layout(true);
- }
-
- protected void addCustomItems(final Composite parent) {
- final CustomViewFinder finder = CustomViewFinder.get(mEditor.getProject());
- Collection<String> allViews = finder.getAllViews();
- if (allViews == null) { // Not yet initialized: trigger an async refresh
- finder.refresh(new ViewFinderListener(parent));
- return;
- }
-
- // Remove previous content
- for (Control c : parent.getChildren()) {
- c.dispose();
- }
-
- // Add new views
- for (final String fqcn : allViews) {
- CustomViewDescriptorService service = CustomViewDescriptorService.getInstance();
- ViewElementDescriptor desc = service.getDescriptor(mEditor.getProject(), fqcn);
- if (desc == null) {
- // The descriptor lookup performs validation steps of the class, and may
- // in some cases determine that this is not a view and will return null;
- // guard against that.
- continue;
- }
-
- Control item = createItem(parent, desc);
-
- // Add control-click listener on custom view items to you can warp to
- // (and double click listener too -- the more discoverable, the better.)
- if (item instanceof IconTextItem) {
- IconTextItem it = (IconTextItem) item;
- it.addMouseListener(new MouseAdapter() {
- @Override
- public void mouseDoubleClick(MouseEvent e) {
- AdtPlugin.openJavaClass(mEditor.getProject(), fqcn);
- }
-
- @Override
- public void mouseDown(MouseEvent e) {
- if ((e.stateMask & SWT.MOD1) != 0) {
- AdtPlugin.openJavaClass(mEditor.getProject(), fqcn);
- }
- }
- });
- }
- }
- }
-
- /* package */ GraphicalEditorPart getEditor() {
- return mEditor;
- }
-
- private Control createItem(Composite parent, ViewElementDescriptor desc) {
- Control item = null;
- switch (mPaletteMode) {
- case SMALL_PREVIEW:
- case TINY_PREVIEW:
- case PREVIEW: {
- ImageDescriptor descriptor = mPreviewIconFactory.getImageDescriptor(desc);
- if (descriptor != null) {
- Image image = descriptor.createImage();
- ImageControl imageControl = new ImageControl(parent, SWT.None, image);
- if (mPaletteMode.isScaledPreview()) {
- // Try to preserve the overall size since rendering sizes typically
- // vary with the dpi - so while the scaling factor for a 160 dpi
- // rendering the scaling factor should be 0.5, for a 320 dpi one the
- // scaling factor should be half that, 0.25.
- float scale = 1.0f;
- if (mPaletteMode == PaletteMode.SMALL_PREVIEW) {
- scale = 0.75f;
- } else if (mPaletteMode == PaletteMode.TINY_PREVIEW) {
- scale = 0.5f;
- }
- ConfigurationChooser chooser = mEditor.getConfigurationChooser();
- int dpi = chooser.getConfiguration().getDensity().getDpiValue();
- while (dpi > 160) {
- scale = scale / 2;
- dpi = dpi / 2;
- }
- imageControl.setScale(scale);
- }
- imageControl.setHoverColor(getDisplay().getSystemColor(SWT.COLOR_WHITE));
- if (mBackground != null) {
- imageControl.setBackground(mBackground);
- }
- String toolTip = desc.getUiName();
- // It appears pretty much none of the descriptors have tooltips
- //String descToolTip = desc.getTooltip();
- //if (descToolTip != null && descToolTip.length() > 0) {
- // toolTip = toolTip + "\n" + descToolTip;
- //}
- imageControl.setToolTipText(toolTip);
-
- item = imageControl;
- } else {
- // Just use an Icon+Text item for these for now
- item = new IconTextItem(parent, desc);
- if (mForeground != null) {
- item.setForeground(mForeground);
- item.setBackground(mBackground);
- }
- }
- break;
- }
- case ICON_TEXT: {
- item = new IconTextItem(parent, desc);
- break;
- }
- case ICON_ONLY: {
- item = new ImageControl(parent, SWT.None, desc.getGenericIcon());
- item.setToolTipText(desc.getUiName());
- break;
- }
- default:
- throw new IllegalArgumentException("Not yet implemented");
- }
-
- final DragSource source = new DragSource(item, DND.DROP_COPY);
- source.setTransfer(new Transfer[] { SimpleXmlTransfer.getInstance() });
- source.addDragListener(new DescDragSourceListener(desc));
- item.addDisposeListener(new DisposeListener() {
- @Override
- public void widgetDisposed(DisposeEvent e) {
- source.dispose();
- }
- });
- addMenu(item);
-
- return item;
- }
-
- /**
- * An Item widget represents one {@link ElementDescriptor} that can be dropped on the
- * GLE2 canvas using drag'n'drop.
- */
- private static class IconTextItem extends CLabel implements MouseTrackListener {
-
- private boolean mMouseIn;
-
- public IconTextItem(Composite parent, ViewElementDescriptor desc) {
- super(parent, SWT.NONE);
- mMouseIn = false;
-
- setText(desc.getUiName());
- setImage(desc.getGenericIcon());
- setToolTipText(desc.getTooltip());
- addMouseTrackListener(this);
- }
-
- @Override
- public int getStyle() {
- int style = super.getStyle();
- if (mMouseIn) {
- style |= SWT.SHADOW_IN;
- }
- return style;
- }
-
- @Override
- public void mouseEnter(MouseEvent e) {
- if (!mMouseIn) {
- mMouseIn = true;
- redraw();
- }
- }
-
- @Override
- public void mouseExit(MouseEvent e) {
- if (mMouseIn) {
- mMouseIn = false;
- redraw();
- }
- }
-
- @Override
- public void mouseHover(MouseEvent e) {
- // pass
- }
- }
-
- /**
- * A {@link DragSourceListener} that deals with drag'n'drop of
- * {@link ElementDescriptor}s.
- */
- private class DescDragSourceListener implements DragSourceListener {
- private final ViewElementDescriptor mDesc;
- private SimpleElement[] mElements;
-
- public DescDragSourceListener(ViewElementDescriptor desc) {
- mDesc = desc;
- }
-
- @Override
- public void dragStart(DragSourceEvent e) {
- // See if we can find out the bounds of this element from a preview image.
- // Preview images are created before the drag source listener is notified
- // of the started drag.
- Rect bounds = null;
- Rect dragBounds = null;
-
- createDragImage(e);
- if (mImage != null && !mIsPlaceholder) {
- int width = mImageLayoutBounds.width;
- int height = mImageLayoutBounds.height;
- assert mImageLayoutBounds.x == 0;
- assert mImageLayoutBounds.y == 0;
- bounds = new Rect(0, 0, width, height);
- double scale = mEditor.getCanvasControl().getScale();
- int scaledWidth = (int) (scale * width);
- int scaledHeight = (int) (scale * height);
- int x = -scaledWidth / 2;
- int y = -scaledHeight / 2;
- dragBounds = new Rect(x, y, scaledWidth, scaledHeight);
- }
-
- SimpleElement se = new SimpleElement(
- SimpleXmlTransfer.getFqcn(mDesc),
- null /* parentFqcn */,
- bounds /* bounds */,
- null /* parentBounds */);
- if (mDesc instanceof PaletteMetadataDescriptor) {
- PaletteMetadataDescriptor pm = (PaletteMetadataDescriptor) mDesc;
- pm.initializeNew(se);
- }
- mElements = new SimpleElement[] { se };
-
- // Register this as the current dragged data
- GlobalCanvasDragInfo dragInfo = GlobalCanvasDragInfo.getInstance();
- dragInfo.startDrag(
- mElements,
- null /* selection */,
- null /* canvas */,
- null /* removeSource */);
- dragInfo.setDragBounds(dragBounds);
- dragInfo.setDragBaseline(mBaseline);
-
-
- e.doit = true;
- }
-
- @Override
- public void dragSetData(DragSourceEvent e) {
- // Provide the data for the drop when requested by the other side.
- if (SimpleXmlTransfer.getInstance().isSupportedType(e.dataType)) {
- e.data = mElements;
- }
- }
-
- @Override
- public void dragFinished(DragSourceEvent e) {
- // Unregister the dragged data.
- GlobalCanvasDragInfo.getInstance().stopDrag();
- mElements = null;
- if (mImage != null) {
- mImage.dispose();
- mImage = null;
- }
- }
-
- // TODO: Figure out the right dimensions to use for rendering.
- // We WILL crop this after rendering, but for performance reasons it would be good
- // not to make it much larger than necessary since to crop this we rely on
- // actually scanning pixels.
-
- /**
- * Width of the rendered preview image (before it is cropped), although the actual
- * width may be smaller (since we also take the device screen's size into account)
- */
- private static final int MAX_RENDER_HEIGHT = 400;
-
- /**
- * Height of the rendered preview image (before it is cropped), although the
- * actual width may be smaller (since we also take the device screen's size into
- * account)
- */
- private static final int MAX_RENDER_WIDTH = 500;
-
- /** Amount of alpha to multiply into the image (divided by 256) */
- private static final int IMG_ALPHA = 128;
-
- /** The image shown during the drag */
- private Image mImage;
- /** The non-effect bounds of the drag image */
- private Rectangle mImageLayoutBounds;
- private int mBaseline = -1;
-
- /**
- * If true, the image is a preview of the view, and if not it is a "fallback"
- * image of some sort, such as a rendering of the palette item itself
- */
- private boolean mIsPlaceholder;
-
- private void createDragImage(DragSourceEvent event) {
- mBaseline = -1;
- Pair<Image, Rectangle> preview = renderPreview();
- if (preview != null) {
- mImage = preview.getFirst();
- mImageLayoutBounds = preview.getSecond();
- } else {
- mImage = null;
- mImageLayoutBounds = null;
- }
-
- mIsPlaceholder = mImage == null;
- if (mIsPlaceholder) {
- // Couldn't render preview (or the preview is a blank image, such as for
- // example the preview of an empty layout), so instead create a placeholder
- // image
- // Render the palette item itself as an image
- Control control = ((DragSource) event.widget).getControl();
- GC gc = new GC(control);
- Point size = control.getSize();
- Display display = getDisplay();
- final Image image = new Image(display, size.x, size.y);
- gc.copyArea(image, 0, 0);
- gc.dispose();
-
- BufferedImage awtImage = SwtUtils.convertToAwt(image);
- if (awtImage != null) {
- awtImage = ImageUtils.createDropShadow(awtImage, 3 /* shadowSize */,
- 0.7f /* shadowAlpha */, 0x000000 /* shadowRgb */);
- mImage = SwtUtils.convertToSwt(display, awtImage, true, IMG_ALPHA);
- } else {
- ImageData data = image.getImageData();
- data.alpha = IMG_ALPHA;
-
- // Changing the ImageData -after- constructing an image on it
- // has no effect, so we have to construct a new image. Luckily these
- // are tiny images.
- mImage = new Image(display, data);
- }
- image.dispose();
- }
-
- event.image = mImage;
-
- if (!mIsPlaceholder) {
- // Shift the drag feedback image up such that it's centered under the
- // mouse pointer
- double scale = mEditor.getCanvasControl().getScale();
- event.offsetX = (int) (scale * mImageLayoutBounds.width / 2);
- event.offsetY = (int) (scale * mImageLayoutBounds.height / 2);
- }
- }
-
- /**
- * Performs the actual rendering of the descriptor into an image and returns the
- * image as well as the layout bounds of the image (not including drop shadow etc)
- */
- private Pair<Image, Rectangle> renderPreview() {
- ViewMetadataRepository repository = ViewMetadataRepository.get();
- RenderMode renderMode = repository.getRenderMode(mDesc.getFullClassName());
- if (renderMode == RenderMode.SKIP) {
- return null;
- }
-
- // Create blank XML document
- Document document = DomUtilities.createEmptyDocument();
-
- // Insert our target view's XML into it as a node
- GraphicalEditorPart editor = getEditor();
- LayoutEditorDelegate layoutEditorDelegate = editor.getEditorDelegate();
-
- String viewName = mDesc.getXmlLocalName();
- Element element = document.createElement(viewName);
-
- // Set up a proper name space
- Attr attr = document.createAttributeNS(XMLNS_URI, XMLNS_ANDROID);
- attr.setValue(ANDROID_URI);
- element.getAttributes().setNamedItemNS(attr);
-
- element.setAttributeNS(ANDROID_URI, ATTR_LAYOUT_WIDTH, VALUE_WRAP_CONTENT);
- element.setAttributeNS(ANDROID_URI, ATTR_LAYOUT_HEIGHT, VALUE_WRAP_CONTENT);
-
- // This doesn't apply to all, but doesn't seem to cause harm and makes for a
- // better experience with text-oriented views like buttons and texts
- element.setAttributeNS(ANDROID_URI, ATTR_TEXT,
- DescriptorsUtils.getBasename(mDesc.getUiName()));
-
- // Is this a palette variation?
- if (mDesc instanceof PaletteMetadataDescriptor) {
- PaletteMetadataDescriptor pm = (PaletteMetadataDescriptor) mDesc;
- pm.initializeNew(element);
- }
-
- document.appendChild(element);
-
- // Construct UI model from XML
- AndroidTargetData data = layoutEditorDelegate.getEditor().getTargetData();
- DocumentDescriptor documentDescriptor;
- if (data == null) {
- documentDescriptor = new DocumentDescriptor("temp", null/*children*/);//$NON-NLS-1$
- } else {
- documentDescriptor = data.getLayoutDescriptors().getDescriptor();
- }
- UiDocumentNode model = (UiDocumentNode) documentDescriptor.createUiNode();
- model.setEditor(layoutEditorDelegate.getEditor());
- model.setUnknownDescriptorProvider(editor.getModel().getUnknownDescriptorProvider());
- model.loadFromXmlNode(document);
-
- // Call the create-hooks such that we for example insert mandatory
- // children into views like the DialerFilter, apply image source attributes
- // to ImageButtons, etc.
- LayoutCanvas canvas = editor.getCanvasControl();
- NodeFactory nodeFactory = canvas.getNodeFactory();
- UiElementNode parent = model.getUiRoot();
- UiElementNode child = parent.getUiChildren().get(0);
- if (child instanceof UiViewElementNode) {
- UiViewElementNode childUiNode = (UiViewElementNode) child;
- NodeProxy childNode = nodeFactory.create(childUiNode);
-
- // Applying create hooks as part of palette render should
- // not trigger model updates
- layoutEditorDelegate.getEditor().setIgnoreXmlUpdate(true);
- try {
- canvas.getRulesEngine().callCreateHooks(layoutEditorDelegate.getEditor(),
- null, childNode, InsertType.CREATE_PREVIEW);
- childNode.applyPendingChanges();
- } catch (Throwable t) {
- AdtPlugin.log(t, "Failed calling creation hooks for widget %1$s", viewName);
- } finally {
- layoutEditorDelegate.getEditor().setIgnoreXmlUpdate(false);
- }
- }
-
- Integer overrideBgColor = null;
- boolean hasTransparency = false;
- LayoutLibrary layoutLibrary = editor.getLayoutLibrary();
- if (layoutLibrary != null &&
- layoutLibrary.supports(Capability.CUSTOM_BACKGROUND_COLOR)) {
- // It doesn't matter what the background color is as long as the alpha
- // is 0 (fully transparent). We're using red to make it more obvious if
- // for some reason the background is painted when it shouldn't be.
- overrideBgColor = new Integer(0x00FF0000);
- }
-
- RenderSession session = null;
- try {
- // Use at most the size of the screen for the preview render.
- // This is important since when we fill the size of certain views (like
- // a SeekBar), we want it to at most be the width of the screen, and for small
- // screens the RENDER_WIDTH was wider.
- LayoutLog silentLogger = new LayoutLog();
-
- session = RenderService.create(editor)
- .setModel(model)
- .setMaxRenderSize(MAX_RENDER_WIDTH, MAX_RENDER_HEIGHT)
- .setLog(silentLogger)
- .setOverrideBgColor(overrideBgColor)
- .setDecorations(false)
- .createRenderSession();
- } catch (Throwable t) {
- // Previews can fail for a variety of reasons -- let's not bug
- // the user with it
- return null;
- }
-
- if (session != null) {
- if (session.getResult().isSuccess()) {
- BufferedImage image = session.getImage();
- if (image != null) {
- BufferedImage cropped;
- Rect initialCrop = null;
- ViewInfo viewInfo = null;
-
- List<ViewInfo> viewInfoList = session.getRootViews();
-
- if (viewInfoList != null && viewInfoList.size() > 0) {
- viewInfo = viewInfoList.get(0);
- mBaseline = viewInfo.getBaseLine();
- }
-
- if (viewInfo != null) {
- int x1 = viewInfo.getLeft();
- int x2 = viewInfo.getRight();
- int y2 = viewInfo.getBottom();
- int y1 = viewInfo.getTop();
- initialCrop = new Rect(x1, y1, x2 - x1, y2 - y1);
- }
-
- if (hasTransparency) {
- cropped = ImageUtils.cropBlank(image, initialCrop);
- } else {
- // Find out what the "background" color is such that we can properly
- // crop it out of the image. To do this we pick out a pixel in the
- // bottom right unpainted area. Rather than pick the one in the far
- // bottom corner, we pick one as close to the bounds of the view as
- // possible (but still outside of the bounds), such that we can
- // deal with themes like the dialog theme.
- int edgeX = image.getWidth() -1;
- int edgeY = image.getHeight() -1;
- if (viewInfo != null) {
- if (viewInfo.getRight() < image.getWidth()-1) {
- edgeX = viewInfo.getRight()+1;
- }
- if (viewInfo.getBottom() < image.getHeight()-1) {
- edgeY = viewInfo.getBottom()+1;
- }
- }
- int edgeColor = image.getRGB(edgeX, edgeY);
- cropped = ImageUtils.cropColor(image, edgeColor, initialCrop);
- }
-
- if (cropped != null) {
- int width = initialCrop != null ? initialCrop.w : cropped.getWidth();
- int height = initialCrop != null ? initialCrop.h : cropped.getHeight();
- boolean needsContrast = hasTransparency
- && !ImageUtils.containsDarkPixels(cropped);
- cropped = ImageUtils.createDropShadow(cropped,
- hasTransparency ? 3 : 5 /* shadowSize */,
- !hasTransparency ? 0.6f : needsContrast ? 0.8f : 0.7f/*alpha*/,
- 0x000000 /* shadowRgb */);
-
- double scale = canvas.getScale();
- if (scale != 1L) {
- cropped = ImageUtils.scale(cropped, scale, scale);
- }
-
- Display display = getDisplay();
- int alpha = (!hasTransparency || !needsContrast) ? IMG_ALPHA : -1;
- Image swtImage = SwtUtils.convertToSwt(display, cropped, true, alpha);
- Rectangle imageBounds = new Rectangle(0, 0, width, height);
- return Pair.of(swtImage, imageBounds);
- }
- }
- }
-
- session.dispose();
- }
-
- return null;
- }
-
- /**
- * Utility method to print out the contents of the given XML document. This is
- * really useful when working on the preview code above. I'm including all the
- * code inside a constant false, which means the compiler will omit all the code,
- * but I'd like to leave it in the code base and by doing it this way rather than
- * as commented out code the code won't be accidentally broken.
- */
- @SuppressWarnings("all")
- private void dumpDocument(Document document) {
- // Diagnostics: print out the XML that we're about to render
- if (false) { // Will be omitted by the compiler
- org.apache.xml.serialize.OutputFormat outputFormat =
- new org.apache.xml.serialize.OutputFormat(
- "XML", "ISO-8859-1", true); //$NON-NLS-1$ //$NON-NLS-2$
- outputFormat.setIndent(2);
- outputFormat.setLineWidth(100);
- outputFormat.setIndenting(true);
- outputFormat.setOmitXMLDeclaration(true);
- outputFormat.setOmitDocumentType(true);
- StringWriter stringWriter = new StringWriter();
- // Using FQN here to avoid having an import above, which will result
- // in a deprecation warning, and there isn't a way to annotate a single
- // import element with a SuppressWarnings.
- org.apache.xml.serialize.XMLSerializer serializer =
- new org.apache.xml.serialize.XMLSerializer(stringWriter, outputFormat);
- serializer.setNamespaces(true);
- try {
- serializer.serialize(document.getDocumentElement());
- System.out.println(stringWriter.toString());
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
-
- /** Action for switching view modes via radio buttons */
- private class PaletteModeAction extends Action {
- private final PaletteMode mMode;
-
- PaletteModeAction(PaletteMode mode) {
- super(mode.getActionLabel(), IAction.AS_RADIO_BUTTON);
- mMode = mode;
- boolean selected = mMode == mPaletteMode;
- setChecked(selected);
- setEnabled(!selected);
- }
-
- @Override
- public void run() {
- if (isEnabled()) {
- mPaletteMode = mMode;
- refreshPalette();
- savePaletteMode();
- }
- }
- }
-
- /** Action for toggling various checkbox view modes - categories, sorting, etc */
- private class ToggleViewOptionAction extends Action {
- private final int mAction;
- final static int TOGGLE_CATEGORY = 1;
- final static int TOGGLE_ALPHABETICAL = 2;
- final static int TOGGLE_AUTO_CLOSE = 3;
- final static int REFRESH = 4;
- final static int RESET = 5;
-
- ToggleViewOptionAction(String title, int action, boolean checked) {
- super(title, (action == REFRESH || action == RESET) ? IAction.AS_PUSH_BUTTON
- : IAction.AS_CHECK_BOX);
- mAction = action;
- if (checked) {
- setChecked(checked);
- }
- }
-
- @Override
- public void run() {
- switch (mAction) {
- case TOGGLE_CATEGORY:
- mCategories = !mCategories;
- refreshPalette();
- break;
- case TOGGLE_ALPHABETICAL:
- mAlphabetical = !mAlphabetical;
- refreshPalette();
- break;
- case TOGGLE_AUTO_CLOSE:
- mAutoClose = !mAutoClose;
- mAccordion.setAutoClose(mAutoClose);
- break;
- case REFRESH:
- mPreviewIconFactory.refresh();
- refreshPalette();
- break;
- case RESET:
- mAlphabetical = false;
- mCategories = true;
- mAutoClose = true;
- mPaletteMode = PaletteMode.SMALL_PREVIEW;
- refreshPalette();
- break;
- }
- savePaletteMode();
- }
- }
-
- private void addMenu(Control control) {
- control.addMenuDetectListener(new MenuDetectListener() {
- @Override
- public void menuDetected(MenuDetectEvent e) {
- showMenu(e.x, e.y);
- }
- });
- }
-
- private void showMenu(int x, int y) {
- MenuManager manager = new MenuManager() {
- @Override
- public boolean isDynamic() {
- return true;
- }
- };
- boolean previews = previewsAvailable();
- for (PaletteMode mode : PaletteMode.values()) {
- if (mode.isPreview() && !previews) {
- continue;
- }
- manager.add(new PaletteModeAction(mode));
- }
- if (mPaletteMode.isPreview()) {
- manager.add(new Separator());
- manager.add(new ToggleViewOptionAction("Refresh Previews",
- ToggleViewOptionAction.REFRESH,
- false));
- }
- manager.add(new Separator());
- manager.add(new ToggleViewOptionAction("Show Categories",
- ToggleViewOptionAction.TOGGLE_CATEGORY,
- mCategories));
- manager.add(new ToggleViewOptionAction("Sort Alphabetically",
- ToggleViewOptionAction.TOGGLE_ALPHABETICAL,
- mAlphabetical));
- manager.add(new Separator());
- manager.add(new ToggleViewOptionAction("Auto Close Previous",
- ToggleViewOptionAction.TOGGLE_AUTO_CLOSE,
- mAutoClose));
- manager.add(new Separator());
- manager.add(new ToggleViewOptionAction("Reset",
- ToggleViewOptionAction.RESET,
- false));
-
- Menu menu = manager.createContextMenu(PaletteControl.this);
- menu.setLocation(x, y);
- menu.setVisible(true);
- }
-
- private final class ViewFinderListener implements CustomViewFinder.Listener {
- private final Composite mParent;
-
- private ViewFinderListener(Composite parent) {
- mParent = parent;
- }
-
- @Override
- public void viewsUpdated(Collection<String> customViews,
- Collection<String> thirdPartyViews) {
- addCustomItems(mParent);
- mParent.layout(true);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/PlayAnimationMenu.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/PlayAnimationMenu.java
deleted file mode 100644
index 629a42f18..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/PlayAnimationMenu.java
+++ /dev/null
@@ -1,247 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.SdkConstants.FD_RESOURCES;
-import static com.android.SdkConstants.FD_RES_ANIMATOR;
-import static com.android.ide.eclipse.adt.AdtConstants.WS_SEP;
-
-import com.android.ide.common.rendering.api.Capability;
-import com.android.ide.common.rendering.api.IAnimationListener;
-import com.android.ide.common.rendering.api.RenderSession;
-import com.android.ide.common.rendering.api.Result;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.wizards.newxmlfile.NewXmlFileWizard;
-import com.android.resources.ResourceType;
-import com.android.utils.Pair;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.ActionContributionItem;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchWindow;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * "Play Animation" context menu which lists available animations in the project and in
- * the framework, as well as a "Create Animation" shortcut, and allows the animation to be
- * run on the selection
- * <p/>
- * TODO: Add transport controls for play/rewind/pause/loop, and (if possible) scrubbing
- */
-public class PlayAnimationMenu extends SubmenuAction {
- /** Associated canvas */
- private final LayoutCanvas mCanvas;
- /** Whether this menu is showing local animations or framework animations */
- private boolean mFramework;
-
- /**
- * Creates a "Play Animation" menu
- *
- * @param canvas associated canvas
- */
- public PlayAnimationMenu(LayoutCanvas canvas) {
- this(canvas, "Play Animation", false);
- }
-
- /**
- * Creates an animation menu; this can be used either for the outer Play animation
- * menu, or the inner frameworks-animations list
- *
- * @param canvas the associated canvas
- * @param title menu item name
- * @param framework true to show the framework animations, false for the project (and
- * nested framework-animation-menu) animations
- */
- private PlayAnimationMenu(LayoutCanvas canvas, String title, boolean framework) {
- super(title);
- mCanvas = canvas;
- mFramework = framework;
- }
-
- @Override
- protected void addMenuItems(Menu menu) {
- SelectionManager selectionManager = mCanvas.getSelectionManager();
- List<SelectionItem> selection = selectionManager.getSelections();
- if (selection.size() != 1) {
- addDisabledMessageItem("Select exactly one widget");
- return;
- }
-
- GraphicalEditorPart graphicalEditor = mCanvas.getEditorDelegate().getGraphicalEditor();
- if (graphicalEditor.renderingSupports(Capability.PLAY_ANIMATION)) {
- // List of animations
- Collection<String> animationNames = graphicalEditor.getResourceNames(mFramework,
- ResourceType.ANIMATOR);
- if (animationNames.size() > 0) {
- // Sort alphabetically
- List<String> sortedNames = new ArrayList<String>(animationNames);
- Collections.sort(sortedNames);
-
- for (String animation : sortedNames) {
- String title = animation;
- IAction action = new PlayAnimationAction(title, animation, mFramework);
- new ActionContributionItem(action).fill(menu, -1);
- }
-
- new Separator().fill(menu, -1);
- }
-
- if (!mFramework) {
- // Not in the framework submenu: include recent list and create new actions
-
- // "Create New" action
- new ActionContributionItem(new CreateAnimationAction()).fill(menu, -1);
-
- // Framework resources submenu
- new Separator().fill(menu, -1);
- PlayAnimationMenu sub = new PlayAnimationMenu(mCanvas, "Android Builtin", true);
- new ActionContributionItem(sub).fill(menu, -1);
- }
- } else {
- addDisabledMessageItem(
- "Not supported for this SDK version; try changing the Render Target");
- }
- }
-
- private class PlayAnimationAction extends Action {
- private final String mAnimationName;
- private final boolean mIsFrameworkAnim;
-
- public PlayAnimationAction(String title, String animationName, boolean isFrameworkAnim) {
- super(title, IAction.AS_PUSH_BUTTON);
- mAnimationName = animationName;
- mIsFrameworkAnim = isFrameworkAnim;
- }
-
- @Override
- public void run() {
- SelectionManager selectionManager = mCanvas.getSelectionManager();
- List<SelectionItem> selection = selectionManager.getSelections();
- SelectionItem canvasSelection = selection.get(0);
- CanvasViewInfo info = canvasSelection.getViewInfo();
-
- Object viewObject = info.getViewObject();
- if (viewObject != null) {
- ViewHierarchy viewHierarchy = mCanvas.getViewHierarchy();
- RenderSession session = viewHierarchy.getSession();
- Result r = session.animate(viewObject, mAnimationName, mIsFrameworkAnim,
- new IAnimationListener() {
- private boolean mPendingDrawing = false;
-
- @Override
- public void onNewFrame(RenderSession s) {
- SelectionOverlay selectionOverlay = mCanvas.getSelectionOverlay();
- if (!selectionOverlay.isHiding()) {
- selectionOverlay.setHiding(true);
- }
- HoverOverlay hoverOverlay = mCanvas.getHoverOverlay();
- if (!hoverOverlay.isHiding()) {
- hoverOverlay.setHiding(true);
- }
-
- ImageOverlay imageOverlay = mCanvas.getImageOverlay();
- imageOverlay.setImage(s.getImage(), s.isAlphaChannelImage());
- synchronized (this) {
- if (mPendingDrawing == false) {
- mCanvas.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- synchronized (this) {
- mPendingDrawing = false;
- }
- mCanvas.redraw();
- }
- });
- mPendingDrawing = true;
- }
- }
- }
-
- @Override
- public boolean isCanceled() {
- return false;
- }
-
- @Override
- public void done(Result result) {
- SelectionOverlay selectionOverlay = mCanvas.getSelectionOverlay();
- selectionOverlay.setHiding(false);
- HoverOverlay hoverOverlay = mCanvas.getHoverOverlay();
- hoverOverlay.setHiding(false);
-
- // Must refresh view hierarchy to force objects back to
- // their original positions in case animations have left
- // them elsewhere
- mCanvas.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- GraphicalEditorPart graphicalEditor = mCanvas
- .getEditorDelegate().getGraphicalEditor();
- graphicalEditor.recomputeLayout();
- }
- });
- }
- });
-
- if (!r.isSuccess()) {
- if (r.getErrorMessage() != null) {
- AdtPlugin.log(r.getException(), r.getErrorMessage());
- }
- }
- }
- }
- }
-
- /**
- * Action which brings up the "Create new XML File" wizard, pre-selected with the
- * animation category
- */
- private class CreateAnimationAction extends Action {
- public CreateAnimationAction() {
- super("Create...", IAction.AS_PUSH_BUTTON);
- }
-
- @Override
- public void run() {
- Shell parent = mCanvas.getShell();
- NewXmlFileWizard wizard = new NewXmlFileWizard();
- LayoutEditorDelegate editor = mCanvas.getEditorDelegate();
- IWorkbenchWindow workbenchWindow =
- editor.getEditor().getEditorSite().getWorkbenchWindow();
- IWorkbench workbench = workbenchWindow.getWorkbench();
- String animationDir = FD_RESOURCES + WS_SEP + FD_RES_ANIMATOR;
- Pair<IProject, String> pair = Pair.of(editor.getEditor().getProject(), animationDir);
- IStructuredSelection selection = new StructuredSelection(pair);
- wizard.init(workbench, selection);
- WizardDialog dialog = new WizardDialog(parent, wizard);
- dialog.create();
- dialog.open();
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/PreviewIconFactory.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/PreviewIconFactory.java
deleted file mode 100644
index 5661b2919..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/PreviewIconFactory.java
+++ /dev/null
@@ -1,642 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.SdkConstants.DOT_PNG;
-import static com.android.SdkConstants.FQCN_DATE_PICKER;
-import static com.android.SdkConstants.FQCN_EXPANDABLE_LIST_VIEW;
-import static com.android.SdkConstants.FQCN_LIST_VIEW;
-import static com.android.SdkConstants.FQCN_TIME_PICKER;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.rendering.LayoutLibrary;
-import com.android.ide.common.rendering.api.Capability;
-import com.android.ide.common.rendering.api.RenderSession;
-import com.android.ide.common.rendering.api.ResourceValue;
-import com.android.ide.common.rendering.api.SessionParams.RenderingMode;
-import com.android.ide.common.rendering.api.StyleResourceValue;
-import com.android.ide.common.rendering.api.ViewInfo;
-import com.android.ide.common.resources.ResourceResolver;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DocumentDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.PaletteMetadataDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.ViewMetadataRepository;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.ViewMetadataRepository.RenderMode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiDocumentNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.resources.ResourceHelper;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.sdklib.IAndroidTarget;
-import com.android.utils.Pair;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.graphics.RGB;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import java.awt.image.BufferedImage;
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.MalformedURLException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Properties;
-
-import javax.imageio.ImageIO;
-
-/**
- * Factory which can provide preview icons for android views of a particular SDK and
- * editor's configuration chooser
- */
-public class PreviewIconFactory {
- private PaletteControl mPalette;
- private RGB mBackground;
- private RGB mForeground;
- private File mImageDir;
-
- private static final String PREVIEW_INFO_FILE = "preview.properties"; //$NON-NLS-1$
-
- public PreviewIconFactory(PaletteControl palette) {
- mPalette = palette;
- }
-
- /**
- * Resets the state in the preview icon factory such that it will re-fetch information
- * like the theme and SDK (the icons themselves are cached in a directory across IDE
- * session though)
- */
- public void reset() {
- mImageDir = null;
- mBackground = null;
- mForeground = null;
- }
-
- /**
- * Deletes all the persistent state for the current settings such that it will be regenerated
- */
- public void refresh() {
- File imageDir = getImageDir(false);
- if (imageDir != null && imageDir.exists()) {
- File[] files = imageDir.listFiles();
- for (File file : files) {
- file.delete();
- }
- imageDir.delete();
- reset();
- }
- }
-
- /**
- * Returns an image descriptor for the given element descriptor, or null if no image
- * could be computed. The rendering parameters (SDK, theme etc) correspond to those
- * stored in the associated palette.
- *
- * @param desc the element descriptor to get an image for
- * @return an image descriptor, or null if no image could be rendered
- */
- public ImageDescriptor getImageDescriptor(ElementDescriptor desc) {
- File imageDir = getImageDir(false);
- if (!imageDir.exists()) {
- render();
- }
- File file = new File(imageDir, getFileName(desc));
- if (file.exists()) {
- try {
- return ImageDescriptor.createFromURL(file.toURI().toURL());
- } catch (MalformedURLException e) {
- AdtPlugin.log(e, "Could not create image descriptor for %s", file);
- }
- }
-
- return null;
- }
-
- /**
- * Partition the elements in the document according to their rendering preferences;
- * elements that should be skipped are removed, elements that should be rendered alone
- * are placed in their own list, etc
- *
- * @param document the document containing render fragments for the various elements
- * @return
- */
- private List<List<Element>> partitionRenderElements(Document document) {
- List<List<Element>> elements = new ArrayList<List<Element>>();
-
- List<Element> shared = new ArrayList<Element>();
- Element root = document.getDocumentElement();
- elements.add(shared);
-
- ViewMetadataRepository repository = ViewMetadataRepository.get();
-
- NodeList children = root.getChildNodes();
- for (int i = 0, n = children.getLength(); i < n; i++) {
- Node node = children.item(i);
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- Element element = (Element) node;
- String fqn = repository.getFullClassName(element);
- assert fqn.length() > 0 : element.getNodeName();
- RenderMode renderMode = repository.getRenderMode(fqn);
-
- // Temporary special cases
- if (fqn.equals(FQCN_LIST_VIEW) || fqn.equals(FQCN_EXPANDABLE_LIST_VIEW)) {
- if (!mPalette.getEditor().renderingSupports(Capability.ADAPTER_BINDING)) {
- renderMode = RenderMode.SKIP;
- }
- } else if (fqn.equals(FQCN_DATE_PICKER) || fqn.equals(FQCN_TIME_PICKER)) {
- IAndroidTarget renderingTarget = mPalette.getEditor().getRenderingTarget();
- // In Honeycomb, these widgets only render properly in the Holo themes.
- int apiLevel = renderingTarget.getVersion().getApiLevel();
- if (apiLevel == 11) {
- String themeName = mPalette.getCurrentTheme();
- if (themeName == null || !themeName.startsWith("Theme.Holo")) { //$NON-NLS-1$
- // Note - it's possible that the the theme is some other theme
- // such as a user theme which inherits from Theme.Holo and that
- // the render -would- have worked, but it's harder to detect that
- // scenario, so we err on the side of caution and just show an
- // icon + name for the time widgets.
- renderMode = RenderMode.SKIP;
- }
- } else if (apiLevel >= 12) {
- // Currently broken, even for Holo.
- renderMode = RenderMode.SKIP;
- } // apiLevel <= 10 is fine
- }
-
- if (renderMode == RenderMode.ALONE) {
- elements.add(Collections.singletonList(element));
- } else if (renderMode == RenderMode.NORMAL) {
- shared.add(element);
- } else {
- assert renderMode == RenderMode.SKIP;
- }
- }
- }
-
- return elements;
- }
-
- /**
- * Renders ALL the widgets and then extracts image data for each view and saves it on
- * disk
- */
- private boolean render() {
- File imageDir = getImageDir(true);
-
- GraphicalEditorPart editor = mPalette.getEditor();
- LayoutEditorDelegate layoutEditorDelegate = editor.getEditorDelegate();
- LayoutLibrary layoutLibrary = editor.getLayoutLibrary();
- Integer overrideBgColor = null;
- if (layoutLibrary != null) {
- if (layoutLibrary.supports(Capability.CUSTOM_BACKGROUND_COLOR)) {
- Pair<RGB, RGB> themeColors = getColorsFromTheme();
- RGB bg = themeColors.getFirst();
- RGB fg = themeColors.getSecond();
- if (bg != null) {
- storeBackground(imageDir, bg, fg);
- overrideBgColor = Integer.valueOf(ImageUtils.rgbToInt(bg, 0xFF));
- }
- }
- }
-
- ViewMetadataRepository repository = ViewMetadataRepository.get();
- Document document = repository.getRenderingConfigDoc();
-
- if (document == null) {
- return false;
- }
-
- // Construct UI model from XML
- AndroidTargetData data = layoutEditorDelegate.getEditor().getTargetData();
- DocumentDescriptor documentDescriptor;
- if (data == null) {
- documentDescriptor = new DocumentDescriptor("temp", null/*children*/);//$NON-NLS-1$
- } else {
- documentDescriptor = data.getLayoutDescriptors().getDescriptor();
- }
- UiDocumentNode model = (UiDocumentNode) documentDescriptor.createUiNode();
- model.setEditor(layoutEditorDelegate.getEditor());
- model.setUnknownDescriptorProvider(editor.getModel().getUnknownDescriptorProvider());
-
- Element documentElement = document.getDocumentElement();
- List<List<Element>> elements = partitionRenderElements(document);
- for (List<Element> elementGroup : elements) {
- // Replace the document elements with the current element group
- while (documentElement.getFirstChild() != null) {
- documentElement.removeChild(documentElement.getFirstChild());
- }
- for (Element element : elementGroup) {
- documentElement.appendChild(element);
- }
-
- model.loadFromXmlNode(document);
-
- RenderSession session = null;
- NodeList childNodes = documentElement.getChildNodes();
- try {
- // Important to get these sizes large enough for clients that don't support
- // RenderMode.FULL_EXPAND such as 1.6
- int width = 200;
- int height = childNodes.getLength() == 1 ? 400 : 1600;
-
- session = RenderService.create(editor)
- .setModel(model)
- .setOverrideRenderSize(width, height)
- .setRenderingMode(RenderingMode.FULL_EXPAND)
- .setLog(editor.createRenderLogger("palette"))
- .setOverrideBgColor(overrideBgColor)
- .setDecorations(false)
- .createRenderSession();
- } catch (Throwable t) {
- // If there are internal errors previewing the components just revert to plain
- // icons and labels
- continue;
- }
-
- if (session != null) {
- if (session.getResult().isSuccess()) {
- BufferedImage image = session.getImage();
- if (image != null && image.getWidth() > 0 && image.getHeight() > 0) {
-
- // Fallback for older platforms where we couldn't do background rendering
- // at the beginning of this method
- if (mBackground == null) {
- Pair<RGB, RGB> themeColors = getColorsFromTheme();
- RGB bg = themeColors.getFirst();
- RGB fg = themeColors.getSecond();
-
- if (bg == null) {
- // Just use a pixel from the rendering instead.
- int p = image.getRGB(image.getWidth() - 1, image.getHeight() - 1);
- // However, in this case we don't trust the foreground color
- // even if one was found in the themes; pick one that is guaranteed
- // to contrast with the background
- bg = ImageUtils.intToRgb(p);
- if (ImageUtils.getBrightness(ImageUtils.rgbToInt(bg, 255)) < 128) {
- fg = new RGB(255, 255, 255);
- } else {
- fg = new RGB(0, 0, 0);
- }
- }
- storeBackground(imageDir, bg, fg);
- assert mBackground != null;
- }
-
- List<ViewInfo> viewInfoList = session.getRootViews();
- if (viewInfoList != null && viewInfoList.size() > 0) {
- // We don't render previews under a <merge> so there should
- // only be one root.
- ViewInfo firstRoot = viewInfoList.get(0);
- int parentX = firstRoot.getLeft();
- int parentY = firstRoot.getTop();
- List<ViewInfo> infos = firstRoot.getChildren();
- for (ViewInfo info : infos) {
- Object cookie = info.getCookie();
- if (!(cookie instanceof UiElementNode)) {
- continue;
- }
- UiElementNode node = (UiElementNode) cookie;
- String fileName = getFileName(node);
- File file = new File(imageDir, fileName);
- if (file.exists()) {
- // On Windows, perhaps we need to rename instead?
- file.delete();
- }
- int x1 = parentX + info.getLeft();
- int y1 = parentY + info.getTop();
- int x2 = parentX + info.getRight();
- int y2 = parentY + info.getBottom();
- if (x1 != x2 && y1 != y2) {
- savePreview(file, image, x1, y1, x2, y2);
- }
- }
- }
- }
- } else {
- StringBuilder sb = new StringBuilder();
- for (int i = 0, n = childNodes.getLength(); i < n; i++) {
- Node node = childNodes.item(i);
- if (node instanceof Element) {
- Element e = (Element) node;
- String fqn = repository.getFullClassName(e);
- fqn = fqn.substring(fqn.lastIndexOf('.') + 1);
- if (sb.length() > 0) {
- sb.append(", "); //$NON-NLS-1$
- }
- sb.append(fqn);
- }
- }
- AdtPlugin.log(IStatus.WARNING, "Failed to render set of icons for %1$s",
- sb.toString());
-
- if (session.getResult().getException() != null) {
- AdtPlugin.log(session.getResult().getException(),
- session.getResult().getErrorMessage());
- } else if (session.getResult().getErrorMessage() != null) {
- AdtPlugin.log(IStatus.WARNING, session.getResult().getErrorMessage());
- }
- }
-
- session.dispose();
- }
- }
-
- mPalette.getEditor().recomputeLayout();
-
- return true;
- }
-
- /**
- * Look up the background and foreground colors from the theme. May not find either
- * the background or foreground or both, but will always return a pair of possibly
- * null colors.
- *
- * @return a pair of possibly null color descriptions
- */
- @NonNull
- private Pair<RGB, RGB> getColorsFromTheme() {
- RGB background = null;
- RGB foreground = null;
-
- ResourceResolver resources = mPalette.getEditor().getResourceResolver();
- if (resources == null) {
- return Pair.of(background, foreground);
- }
- StyleResourceValue theme = resources.getCurrentTheme();
- if (theme != null) {
- background = resolveThemeColor(resources, "windowBackground"); //$NON-NLS-1$
- if (background == null) {
- background = renderDrawableResource("windowBackground"); //$NON-NLS-1$
- // This causes some harm with some themes: We'll find a color, say black,
- // that isn't actually rendered in the theme. Better to use null here,
- // which will cause the caller to pick a pixel from the observed background
- // instead.
- //if (background == null) {
- // background = resolveThemeColor(resources, "colorBackground"); //$NON-NLS-1$
- //}
- }
- foreground = resolveThemeColor(resources, "textColorPrimary"); //$NON-NLS-1$
- }
-
- // Ensure that the foreground color is suitably distinct from the background color
- if (background != null) {
- int bgRgb = ImageUtils.rgbToInt(background, 0xFF);
- int backgroundBrightness = ImageUtils.getBrightness(bgRgb);
- if (foreground == null) {
- if (backgroundBrightness < 128) {
- foreground = new RGB(255, 255, 255);
- } else {
- foreground = new RGB(0, 0, 0);
- }
- } else {
- int fgRgb = ImageUtils.rgbToInt(foreground, 0xFF);
- int foregroundBrightness = ImageUtils.getBrightness(fgRgb);
- if (Math.abs(backgroundBrightness - foregroundBrightness) < 64) {
- if (backgroundBrightness < 128) {
- foreground = new RGB(255, 255, 255);
- } else {
- foreground = new RGB(0, 0, 0);
- }
- }
- }
- }
-
- return Pair.of(background, foreground);
- }
-
- /**
- * Renders the given resource which should refer to a drawable and returns a
- * representative color value for the drawable (such as the color in the center)
- *
- * @param themeItemName the item in the theme to be looked up and rendered
- * @return a color representing a typical color in the drawable
- */
- private RGB renderDrawableResource(String themeItemName) {
- GraphicalEditorPart editor = mPalette.getEditor();
- ResourceResolver resources = editor.getResourceResolver();
- ResourceValue resourceValue = resources.findItemInTheme(themeItemName);
- BufferedImage image = RenderService.create(editor)
- .setOverrideRenderSize(100, 100)
- .renderDrawable(resourceValue);
- if (image != null) {
- // Use the middle pixel as the color since that works better for gradients;
- // solid colors work too.
- int rgb = image.getRGB(image.getWidth() / 2, image.getHeight() / 2);
- return ImageUtils.intToRgb(rgb);
- }
-
- return null;
- }
-
- private static RGB resolveThemeColor(ResourceResolver resources, String resourceName) {
- ResourceValue textColor = resources.findItemInTheme(resourceName);
- return ResourceHelper.resolveColor(resources, textColor);
- }
-
- private String getFileName(ElementDescriptor descriptor) {
- if (descriptor instanceof PaletteMetadataDescriptor) {
- PaletteMetadataDescriptor pmd = (PaletteMetadataDescriptor) descriptor;
- StringBuilder sb = new StringBuilder();
- String name = pmd.getUiName();
- // Strip out whitespace, parentheses, etc.
- for (int i = 0, n = name.length(); i < n; i++) {
- char c = name.charAt(i);
- if (Character.isLetter(c)) {
- sb.append(c);
- }
- }
- return sb.toString() + DOT_PNG;
- }
- return descriptor.getUiName() + DOT_PNG;
- }
-
- private String getFileName(UiElementNode node) {
- ViewMetadataRepository repository = ViewMetadataRepository.get();
- String fqn = repository.getFullClassName((Element) node.getXmlNode());
- return fqn.substring(fqn.lastIndexOf('.') + 1) + DOT_PNG;
- }
-
- /**
- * Cleans up a name by removing punctuation and whitespace etc to make
- * it a better filename
- * @param name the name to clean
- * @return a cleaned up name
- */
- @NonNull
- private static String cleanup(@Nullable String name) {
- if (name == null) {
- return "";
- }
-
- // Extract just the characters (no whitespace, parentheses, punctuation etc)
- // to ensure that the filename is pretty portable
- StringBuilder sb = new StringBuilder(name.length());
- for (int i = 0; i < name.length(); i++) {
- char c = name.charAt(i);
- if (Character.isJavaIdentifierPart(c)) {
- sb.append(Character.toLowerCase(c));
- }
- }
-
- return sb.toString();
- }
-
- /** Returns the location of a directory containing image previews (which may not exist) */
- private File getImageDir(boolean create) {
- if (mImageDir == null) {
- // Location for plugin-related state data
- IPath pluginState = AdtPlugin.getDefault().getStateLocation();
-
- // We have multiple directories - one for each combination of SDK, theme and device
- // (and later, possibly other qualifiers).
- // These are created -lazily-.
- String targetName = mPalette.getCurrentTarget().hashString();
- String androidTargetNamePrefix = "android-";
- String themeNamePrefix = "Theme.";
- if (targetName.startsWith(androidTargetNamePrefix)) {
- targetName = targetName.substring(androidTargetNamePrefix.length());
- }
- String themeName = mPalette.getCurrentTheme();
- if (themeName == null) {
- themeName = "Theme"; //$NON-NLS-1$
- }
- if (themeName.startsWith(themeNamePrefix)) {
- themeName = themeName.substring(themeNamePrefix.length());
- }
- targetName = cleanup(targetName);
- themeName = cleanup(themeName);
- String deviceName = cleanup(mPalette.getCurrentDevice());
- String dirName = String.format("palette-preview-r16b-%s-%s-%s", targetName,
- themeName, deviceName);
- IPath dirPath = pluginState.append(dirName);
-
- mImageDir = new File(dirPath.toOSString());
- }
-
- if (create && !mImageDir.exists()) {
- mImageDir.mkdirs();
- }
-
- return mImageDir;
- }
-
- private void savePreview(File output, BufferedImage image,
- int left, int top, int right, int bottom) {
- try {
- BufferedImage im = ImageUtils.subImage(image, left, top, right, bottom);
- ImageIO.write(im, "PNG", output); //$NON-NLS-1$
- } catch (IOException e) {
- AdtPlugin.log(e, "Failed writing palette file");
- }
- }
-
- private void storeBackground(File imageDir, RGB bg, RGB fg) {
- mBackground = bg;
- mForeground = fg;
- File file = new File(imageDir, PREVIEW_INFO_FILE);
- String colors = String.format(
- "background=#%02x%02x%02x\nforeground=#%02x%02x%02x\n", //$NON-NLS-1$
- bg.red, bg.green, bg.blue,
- fg.red, fg.green, fg.blue);
- AdtPlugin.writeFile(file, colors);
- }
-
- public RGB getBackgroundColor() {
- if (mBackground == null) {
- initColors();
- }
-
- return mBackground;
- }
-
- public RGB getForegroundColor() {
- if (mForeground == null) {
- initColors();
- }
-
- return mForeground;
- }
-
- public void initColors() {
- try {
- // Already initialized? Foreground can be null which would call
- // initColors again and again, but background is never null after
- // initialization so we use it as the have-initialized flag.
- if (mBackground != null) {
- return;
- }
-
- File imageDir = getImageDir(false);
- if (!imageDir.exists()) {
- render();
-
- // Initialized as part of the render
- if (mBackground != null) {
- return;
- }
- }
-
- File file = new File(imageDir, PREVIEW_INFO_FILE);
- if (file.exists()) {
- Properties properties = new Properties();
- InputStream is = null;
- try {
- is = new BufferedInputStream(new FileInputStream(file));
- properties.load(is);
- } catch (IOException e) {
- AdtPlugin.log(e, "Can't read preview properties");
- } finally {
- if (is != null) {
- try {
- is.close();
- } catch (IOException e) {
- // Nothing useful can be done.
- }
- }
- }
-
- String colorString = (String) properties.get("background"); //$NON-NLS-1$
- if (colorString != null) {
- int rgb = ImageUtils.getColor(colorString.trim());
- mBackground = ImageUtils.intToRgb(rgb);
- }
- colorString = (String) properties.get("foreground"); //$NON-NLS-1$
- if (colorString != null) {
- int rgb = ImageUtils.getColor(colorString.trim());
- mForeground = ImageUtils.intToRgb(rgb);
- }
- }
-
- if (mBackground == null) {
- mBackground = new RGB(0, 0, 0);
- }
- // mForeground is allowed to be null.
- } catch (Throwable t) {
- AdtPlugin.log(t, "Cannot initialize preview color settings");
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderLogger.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderLogger.java
deleted file mode 100644
index 8548830bd..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderLogger.java
+++ /dev/null
@@ -1,327 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.rendering.RenderSecurityManager;
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import org.eclipse.core.runtime.IStatus;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * A {@link LayoutLog} which records the problems it encounters and offers them as a
- * single summary at the end
- */
-public class RenderLogger extends LayoutLog {
- static final String TAG_MISSING_DIMENSION = "missing.dimension"; //$NON-NLS-1$
-
- private final String mName;
- private List<String> mFidelityWarnings;
- private List<String> mWarnings;
- private List<String> mErrors;
- private boolean mHaveExceptions;
- private List<String> mTags;
- private List<Throwable> mTraces;
- private static Set<String> sIgnoredFidelityWarnings;
- private final Object mCredential;
-
- /** Construct a logger for the given named layout */
- RenderLogger(String name, Object credential) {
- mName = name;
- mCredential = credential;
- }
-
- /**
- * Are there any logged errors or warnings during the render?
- *
- * @return true if there were problems during the render
- */
- public boolean hasProblems() {
- return mFidelityWarnings != null || mErrors != null || mWarnings != null ||
- mHaveExceptions;
- }
-
- /**
- * Returns a list of traces encountered during rendering, or null if none
- *
- * @return a list of traces encountered during rendering, or null if none
- */
- @Nullable
- public List<Throwable> getFirstTrace() {
- return mTraces;
- }
-
- /**
- * Returns a (possibly multi-line) description of all the problems
- *
- * @param includeFidelityWarnings if true, include fidelity warnings in the problem
- * summary
- * @return a string describing the rendering problems
- */
- @NonNull
- public String getProblems(boolean includeFidelityWarnings) {
- StringBuilder sb = new StringBuilder();
-
- if (mErrors != null) {
- for (String error : mErrors) {
- sb.append(error).append('\n');
- }
- }
-
- if (mWarnings != null) {
- for (String warning : mWarnings) {
- sb.append(warning).append('\n');
- }
- }
-
- if (includeFidelityWarnings && mFidelityWarnings != null) {
- sb.append("The graphics preview in the layout editor may not be accurate:\n");
- for (String warning : mFidelityWarnings) {
- sb.append("* ");
- sb.append(warning).append('\n');
- }
- }
-
- if (mHaveExceptions) {
- sb.append("Exception details are logged in Window > Show View > Error Log");
- }
-
- return sb.toString();
- }
-
- /**
- * Returns the fidelity warnings
- *
- * @return the fidelity warnings
- */
- @Nullable
- public List<String> getFidelityWarnings() {
- return mFidelityWarnings;
- }
-
- // ---- extends LayoutLog ----
-
- @Override
- public void error(String tag, String message, Object data) {
- String description = describe(message);
-
- appendToIdeLog(null, IStatus.ERROR, description);
-
- // Workaround: older layout libraries don't provide a tag for this error
- if (tag == null && message != null
- && message.startsWith("Failed to find style ")) { //$NON-NLS-1$
- tag = LayoutLog.TAG_RESOURCES_RESOLVE_THEME_ATTR;
- }
-
- addError(tag, description);
- }
-
- @Override
- public void error(String tag, String message, Throwable throwable, Object data) {
- String description = describe(message);
- appendToIdeLog(throwable, IStatus.ERROR, description);
-
- if (throwable != null) {
- if (throwable instanceof ClassNotFoundException) {
- // The project callback is given a chance to resolve classes,
- // and when it fails, it will record it in its own list which
- // is displayed in a special way (with action hyperlinks etc).
- // Therefore, include these messages in the visible render log,
- // especially since the user message from a ClassNotFoundException
- // is really not helpful (it just lists the class name without
- // even mentioning that it is a class-not-found exception.)
- return;
- }
-
- if (description.equals(throwable.getLocalizedMessage()) ||
- description.equals(throwable.getMessage())) {
- description = "Exception raised during rendering: " + description;
- }
- recordThrowable(throwable);
- mHaveExceptions = true;
- }
-
- addError(tag, description);
- }
-
- /**
- * Record that the given exception was encountered during rendering
- *
- * @param throwable the exception that was raised
- */
- public void recordThrowable(@NonNull Throwable throwable) {
- if (mTraces == null) {
- mTraces = new ArrayList<Throwable>();
- }
- mTraces.add(throwable);
- }
-
- @Override
- public void warning(String tag, String message, Object data) {
- String description = describe(message);
-
- boolean log = true;
- if (TAG_RESOURCES_FORMAT.equals(tag)) {
- if (description.equals("You must supply a layout_width attribute.") //$NON-NLS-1$
- || description.equals("You must supply a layout_height attribute.")) {//$NON-NLS-1$
- tag = TAG_MISSING_DIMENSION;
- log = false;
- }
- }
-
- if (log) {
- appendToIdeLog(null, IStatus.WARNING, description);
- }
-
- addWarning(tag, description);
- }
-
- @Override
- public void fidelityWarning(String tag, String message, Throwable throwable, Object data) {
- if (sIgnoredFidelityWarnings != null && sIgnoredFidelityWarnings.contains(message)) {
- return;
- }
-
- String description = describe(message);
- appendToIdeLog(throwable, IStatus.ERROR, description);
-
- if (throwable != null) {
- mHaveExceptions = true;
- }
-
- addFidelityWarning(tag, description);
- }
-
- /**
- * Ignore the given render fidelity warning for the current session
- *
- * @param message the message to be ignored for this session
- */
- public static void ignoreFidelityWarning(String message) {
- if (sIgnoredFidelityWarnings == null) {
- sIgnoredFidelityWarnings = new HashSet<String>();
- }
- sIgnoredFidelityWarnings.add(message);
- }
-
- @NonNull
- private String describe(@Nullable String message) {
- if (message == null) {
- return "";
- } else {
- return message;
- }
- }
-
- private void addWarning(String tag, String description) {
- if (mWarnings == null) {
- mWarnings = new ArrayList<String>();
- } else if (mWarnings.contains(description)) {
- // Avoid duplicates
- return;
- }
- mWarnings.add(description);
- addTag(tag);
- }
-
- private void addError(String tag, String description) {
- if (mErrors == null) {
- mErrors = new ArrayList<String>();
- } else if (mErrors.contains(description)) {
- // Avoid duplicates
- return;
- }
- mErrors.add(description);
- addTag(tag);
- }
-
- private void addFidelityWarning(String tag, String description) {
- if (mFidelityWarnings == null) {
- mFidelityWarnings = new ArrayList<String>();
- } else if (mFidelityWarnings.contains(description)) {
- // Avoid duplicates
- return;
- }
- mFidelityWarnings.add(description);
- addTag(tag);
- }
-
- // ---- Tags ----
-
- private void addTag(String tag) {
- if (tag != null) {
- if (mTags == null) {
- mTags = new ArrayList<String>();
- }
- mTags.add(tag);
- }
- }
-
- /**
- * Returns true if the given tag prefix has been seen
- *
- * @param prefix the tag prefix to look for
- * @return true iff any tags with the given prefix was seen during the render
- */
- public boolean seenTagPrefix(String prefix) {
- if (mTags != null) {
- for (String tag : mTags) {
- if (tag.startsWith(prefix)) {
- return true;
- }
- }
- }
-
- return false;
- }
-
- /**
- * Returns true if the given tag has been seen
- *
- * @param tag the tag to look for
- * @return true iff the tag was seen during the render
- */
- public boolean seenTag(String tag) {
- if (mTags != null) {
- return mTags.contains(tag);
- } else {
- return false;
- }
- }
-
- // Append the given message to the ADT log. Bypass the sandbox if necessary
- // such that we can write to the log file.
- private void appendToIdeLog(Throwable throwable, int severity, String description) {
- boolean token = RenderSecurityManager.enterSafeRegion(mCredential);
- try {
- if (throwable != null) {
- AdtPlugin.log(throwable, "%1$s: %2$s", mName, description);
- } else {
- AdtPlugin.log(severity, "%1$s: %2$s", mName, description);
- }
- } finally {
- RenderSecurityManager.exitSafeRegion(token);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderPreview.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderPreview.java
deleted file mode 100644
index 5621d5f17..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderPreview.java
+++ /dev/null
@@ -1,1333 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.SdkConstants.ANDROID_STYLE_RESOURCE_PREFIX;
-import static com.android.SdkConstants.PREFIX_RESOURCE_REF;
-import static com.android.SdkConstants.STYLE_RESOURCE_PREFIX;
-import static com.android.ide.eclipse.adt.internal.editors.layout.configuration.Configuration.MASK_RENDERING;
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.ImageUtils.SHADOW_SIZE;
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.ImageUtils.SMALL_SHADOW_SIZE;
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderPreviewMode.DEFAULT;
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderPreviewMode.INCLUDES;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.rendering.api.RenderSession;
-import com.android.ide.common.rendering.api.ResourceValue;
-import com.android.ide.common.rendering.api.Result;
-import com.android.ide.common.rendering.api.Result.Status;
-import com.android.ide.common.resources.ResourceFile;
-import com.android.ide.common.resources.ResourceRepository;
-import com.android.ide.common.resources.ResourceResolver;
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.common.resources.configuration.ScreenOrientationQualifier;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DocumentDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.Configuration;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigurationChooser;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigurationClient;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigurationDescription;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.Locale;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.NestedConfiguration;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.VaryingConfiguration;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.IncludeFinder.Reference;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiDocumentNode;
-import com.android.ide.eclipse.adt.internal.resources.ResourceHelper;
-import com.android.ide.eclipse.adt.internal.resources.manager.ProjectResources;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.io.IFileWrapper;
-import com.android.io.IAbstractFile;
-import com.android.resources.Density;
-import com.android.resources.ResourceType;
-import com.android.resources.ScreenOrientation;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.devices.Device;
-import com.android.sdklib.devices.Screen;
-import com.android.sdklib.devices.State;
-import com.android.utils.SdkUtils;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.jobs.IJobChangeEvent;
-import org.eclipse.core.runtime.jobs.IJobChangeListener;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.ImageData;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Region;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.progress.UIJob;
-import org.w3c.dom.Document;
-
-import java.awt.Graphics2D;
-import java.awt.image.BufferedImage;
-import java.io.File;
-import java.lang.ref.SoftReference;
-import java.util.Comparator;
-import java.util.Map;
-
-/**
- * Represents a preview rendering of a given configuration
- */
-public class RenderPreview implements IJobChangeListener {
- /** Whether previews should use large shadows */
- static final boolean LARGE_SHADOWS = false;
-
- /**
- * Still doesn't work; get exceptions from layoutlib:
- * java.lang.IllegalStateException: After scene creation, #init() must be called
- * at com.android.layoutlib.bridge.impl.RenderAction.acquire(RenderAction.java:151)
- * <p>
- * TODO: Investigate.
- */
- private static final boolean RENDER_ASYNC = false;
-
- /**
- * Height of the toolbar shown over a preview during hover. Needs to be
- * large enough to accommodate icons below.
- */
- private static final int HEADER_HEIGHT = 20;
-
- /** Whether to dump out rendering failures of the previews to the log */
- private static final boolean DUMP_RENDER_DIAGNOSTICS = false;
-
- /** Extra error checking in debug mode */
- private static final boolean DEBUG = false;
-
- private static final Image EDIT_ICON;
- private static final Image ZOOM_IN_ICON;
- private static final Image ZOOM_OUT_ICON;
- private static final Image CLOSE_ICON;
- private static final int EDIT_ICON_WIDTH;
- private static final int ZOOM_IN_ICON_WIDTH;
- private static final int ZOOM_OUT_ICON_WIDTH;
- private static final int CLOSE_ICON_WIDTH;
- static {
- ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages();
- IconFactory icons = IconFactory.getInstance();
- CLOSE_ICON = sharedImages.getImage(ISharedImages.IMG_ETOOL_DELETE);
- EDIT_ICON = icons.getIcon("editPreview"); //$NON-NLS-1$
- ZOOM_IN_ICON = icons.getIcon("zoomplus"); //$NON-NLS-1$
- ZOOM_OUT_ICON = icons.getIcon("zoomminus"); //$NON-NLS-1$
- CLOSE_ICON_WIDTH = CLOSE_ICON.getImageData().width;
- EDIT_ICON_WIDTH = EDIT_ICON.getImageData().width;
- ZOOM_IN_ICON_WIDTH = ZOOM_IN_ICON.getImageData().width;
- ZOOM_OUT_ICON_WIDTH = ZOOM_OUT_ICON.getImageData().width;
- }
-
- /** The configuration being previewed */
- private @NonNull Configuration mConfiguration;
-
- /** Configuration to use if we have an alternate input to be rendered */
- private @NonNull Configuration mAlternateConfiguration;
-
- /** The associated manager */
- private final @NonNull RenderPreviewManager mManager;
- private final @NonNull LayoutCanvas mCanvas;
-
- private @NonNull SoftReference<ResourceResolver> mResourceResolver =
- new SoftReference<ResourceResolver>(null);
- private @Nullable Job mJob;
- private @Nullable Image mThumbnail;
- private @Nullable String mDisplayName;
- private int mWidth;
- private int mHeight;
- private int mX;
- private int mY;
- private int mTitleHeight;
- private double mScale = 1.0;
- private double mAspectRatio;
-
- /** If non null, points to a separate file containing the source */
- private @Nullable IFile mAlternateInput;
-
- /** If included within another layout, the name of that outer layout */
- private @Nullable Reference mIncludedWithin;
-
- /** Whether the mouse is actively hovering over this preview */
- private boolean mActive;
-
- /**
- * Whether this preview cannot be rendered because of a model error - such
- * as an invalid configuration, a missing resource, an error in the XML
- * markup, etc. If non null, contains the error message (or a blank string
- * if not known), and null if the render was successful.
- */
- private String mError;
-
- /** Whether in the current layout, this preview is visible */
- private boolean mVisible;
-
- /** Whether the configuration has changed and needs to be refreshed the next time
- * this preview made visible. This corresponds to the change flags in
- * {@link ConfigurationClient}. */
- private int mDirty;
-
- /**
- * Creates a new {@linkplain RenderPreview}
- *
- * @param manager the manager
- * @param canvas canvas where preview is painted
- * @param configuration the associated configuration
- * @param width the initial width to use for the preview
- * @param height the initial height to use for the preview
- */
- private RenderPreview(
- @NonNull RenderPreviewManager manager,
- @NonNull LayoutCanvas canvas,
- @NonNull Configuration configuration) {
- mManager = manager;
- mCanvas = canvas;
- mConfiguration = configuration;
- updateSize();
-
- // Should only attempt to create configurations for fully configured devices
- assert mConfiguration.getDevice() != null
- && mConfiguration.getDeviceState() != null
- && mConfiguration.getLocale() != null
- && mConfiguration.getTarget() != null
- && mConfiguration.getTheme() != null
- && mConfiguration.getFullConfig() != null
- && mConfiguration.getFullConfig().getScreenSizeQualifier() != null :
- mConfiguration;
- }
-
- /**
- * Sets the configuration to use for this preview
- *
- * @param configuration the new configuration
- */
- public void setConfiguration(@NonNull Configuration configuration) {
- mConfiguration = configuration;
- }
-
- /**
- * Gets the scale being applied to the thumbnail
- *
- * @return the scale being applied to the thumbnail
- */
- public double getScale() {
- return mScale;
- }
-
- /**
- * Sets the scale to apply to the thumbnail
- *
- * @param scale the factor to scale the thumbnail picture by
- */
- public void setScale(double scale) {
- disposeThumbnail();
- mScale = scale;
- }
-
- /**
- * Returns the aspect ratio of this render preview
- *
- * @return the aspect ratio
- */
- public double getAspectRatio() {
- return mAspectRatio;
- }
-
- /**
- * Returns whether the preview is actively hovered
- *
- * @return whether the mouse is hovering over the preview
- */
- public boolean isActive() {
- return mActive;
- }
-
- /**
- * Sets whether the preview is actively hovered
- *
- * @param active if the mouse is hovering over the preview
- */
- public void setActive(boolean active) {
- mActive = active;
- }
-
- /**
- * Returns whether the preview is visible. Previews that are off
- * screen are typically marked invisible during layout, which means we don't
- * have to expend effort computing preview thumbnails etc
- *
- * @return true if the preview is visible
- */
- public boolean isVisible() {
- return mVisible;
- }
-
- /**
- * Returns whether this preview represents a forked layout
- *
- * @return true if this preview represents a separate file
- */
- public boolean isForked() {
- return mAlternateInput != null || mIncludedWithin != null;
- }
-
- /**
- * Returns the file to be used for this preview, or null if this is not a
- * forked layout meaning that the file is the one used in the chooser
- *
- * @return the file or null for non-forked layouts
- */
- @Nullable
- public IFile getAlternateInput() {
- if (mAlternateInput != null) {
- return mAlternateInput;
- } else if (mIncludedWithin != null) {
- return mIncludedWithin.getFile();
- }
-
- return null;
- }
-
- /**
- * Returns the area of this render preview, PRIOR to scaling
- *
- * @return the area (width times height without scaling)
- */
- int getArea() {
- return mWidth * mHeight;
- }
-
- /**
- * Sets whether the preview is visible. Previews that are off
- * screen are typically marked invisible during layout, which means we don't
- * have to expend effort computing preview thumbnails etc
- *
- * @param visible whether this preview is visible
- */
- public void setVisible(boolean visible) {
- if (visible != mVisible) {
- mVisible = visible;
- if (mVisible) {
- if (mDirty != 0) {
- // Just made the render preview visible:
- configurationChanged(mDirty); // schedules render
- } else {
- updateForkStatus();
- mManager.scheduleRender(this);
- }
- } else {
- dispose();
- }
- }
- }
-
- /**
- * Sets the layout position relative to the top left corner of the preview
- * area, in control coordinates
- */
- void setPosition(int x, int y) {
- mX = x;
- mY = y;
- }
-
- /**
- * Gets the layout X position relative to the top left corner of the preview
- * area, in control coordinates
- */
- int getX() {
- return mX;
- }
-
- /**
- * Gets the layout Y position relative to the top left corner of the preview
- * area, in control coordinates
- */
- int getY() {
- return mY;
- }
-
- /** Determine whether this configuration has a better match in a different layout file */
- private void updateForkStatus() {
- ConfigurationChooser chooser = mManager.getChooser();
- FolderConfiguration config = mConfiguration.getFullConfig();
- if (mAlternateInput != null && chooser.isBestMatchFor(mAlternateInput, config)) {
- return;
- }
-
- mAlternateInput = null;
- IFile editedFile = chooser.getEditedFile();
- if (editedFile != null) {
- if (!chooser.isBestMatchFor(editedFile, config)) {
- ProjectResources resources = chooser.getResources();
- if (resources != null) {
- ResourceFile best = resources.getMatchingFile(editedFile.getName(),
- ResourceType.LAYOUT, config);
- if (best != null) {
- IAbstractFile file = best.getFile();
- if (file instanceof IFileWrapper) {
- mAlternateInput = ((IFileWrapper) file).getIFile();
- } else if (file instanceof File) {
- mAlternateInput = AdtUtils.fileToIFile(((File) file));
- }
- }
- }
- if (mAlternateInput != null) {
- mAlternateConfiguration = Configuration.create(mConfiguration,
- mAlternateInput);
- }
- }
- }
- }
-
- /**
- * Creates a new {@linkplain RenderPreview}
- *
- * @param manager the manager
- * @param configuration the associated configuration
- * @return a new configuration
- */
- @NonNull
- public static RenderPreview create(
- @NonNull RenderPreviewManager manager,
- @NonNull Configuration configuration) {
- LayoutCanvas canvas = manager.getCanvas();
- return new RenderPreview(manager, canvas, configuration);
- }
-
- /**
- * Throws away this preview: cancels any pending rendering jobs and disposes
- * of image resources etc
- */
- public void dispose() {
- disposeThumbnail();
-
- if (mJob != null) {
- mJob.cancel();
- mJob = null;
- }
- }
-
- /** Disposes the thumbnail rendering. */
- void disposeThumbnail() {
- if (mThumbnail != null) {
- mThumbnail.dispose();
- mThumbnail = null;
- }
- }
-
- /**
- * Returns the display name of this preview
- *
- * @return the name of the preview
- */
- @NonNull
- public String getDisplayName() {
- if (mDisplayName == null) {
- String displayName = getConfiguration().getDisplayName();
- if (displayName == null) {
- // No display name: this must be the configuration used by default
- // for the view which is originally displayed (before adding thumbnails),
- // and you've switched away to something else; now we need to display a name
- // for this original configuration. For now, just call it "Original"
- return "Original";
- }
-
- return displayName;
- }
-
- return mDisplayName;
- }
-
- /**
- * Sets the display name of this preview. By default, the display name is
- * the display name of the configuration, but it can be overridden by calling
- * this setter (which only sets the preview name, without editing the configuration.)
- *
- * @param displayName the new display name
- */
- public void setDisplayName(@NonNull String displayName) {
- mDisplayName = displayName;
- }
-
- /**
- * Sets an inclusion context to use for this layout, if any. This will render
- * the configuration preview as the outer layout with the current layout
- * embedded within.
- *
- * @param includedWithin a reference to a layout which includes this one
- */
- public void setIncludedWithin(Reference includedWithin) {
- mIncludedWithin = includedWithin;
- }
-
- /**
- * Request a new render after the given delay
- *
- * @param delay the delay to wait before starting the render job
- */
- public void render(long delay) {
- Job job = mJob;
- if (job != null) {
- job.cancel();
- }
- if (RENDER_ASYNC) {
- job = new AsyncRenderJob();
- } else {
- job = new RenderJob();
- }
- job.schedule(delay);
- job.addJobChangeListener(this);
- mJob = job;
- }
-
- /** Render immediately */
- private void renderSync() {
- GraphicalEditorPart editor = mCanvas.getEditorDelegate().getGraphicalEditor();
- if (editor.getReadyLayoutLib(false /*displayError*/) == null) {
- // Don't attempt to render when there is no ready layout library: most likely
- // the targets are loading/reloading.
- return;
- }
-
- disposeThumbnail();
-
- Configuration configuration =
- mAlternateInput != null && mAlternateConfiguration != null
- ? mAlternateConfiguration : mConfiguration;
- ResourceResolver resolver = getResourceResolver(configuration);
- RenderService renderService = RenderService.create(editor, configuration, resolver);
-
- if (mIncludedWithin != null) {
- renderService.setIncludedWithin(mIncludedWithin);
- }
-
- if (mAlternateInput != null) {
- IAndroidTarget target = editor.getRenderingTarget();
- AndroidTargetData data = null;
- if (target != null) {
- Sdk sdk = Sdk.getCurrent();
- if (sdk != null) {
- data = sdk.getTargetData(target);
- }
- }
-
- // Construct UI model from XML
- DocumentDescriptor documentDescriptor;
- if (data == null) {
- documentDescriptor = new DocumentDescriptor("temp", null);//$NON-NLS-1$
- } else {
- documentDescriptor = data.getLayoutDescriptors().getDescriptor();
- }
- UiDocumentNode model = (UiDocumentNode) documentDescriptor.createUiNode();
- model.setEditor(mCanvas.getEditorDelegate().getEditor());
- model.setUnknownDescriptorProvider(editor.getModel().getUnknownDescriptorProvider());
-
- Document document = DomUtilities.getDocument(mAlternateInput);
- if (document == null) {
- mError = "No document";
- createErrorThumbnail();
- return;
- }
- model.loadFromXmlNode(document);
- renderService.setModel(model);
- } else {
- renderService.setModel(editor.getModel());
- }
- RenderLogger log = editor.createRenderLogger(getDisplayName());
- renderService.setLog(log);
- RenderSession session = renderService.createRenderSession();
- Result render = session.render(1000);
-
- if (DUMP_RENDER_DIAGNOSTICS) {
- if (log.hasProblems() || !render.isSuccess()) {
- AdtPlugin.log(IStatus.ERROR, "Found problems rendering preview "
- + getDisplayName() + ": "
- + render.getErrorMessage() + " : "
- + log.getProblems(false));
- Throwable exception = render.getException();
- if (exception != null) {
- AdtPlugin.log(exception, "Failure rendering preview " + getDisplayName());
- }
- }
- }
-
- if (render.isSuccess()) {
- mError = null;
- } else {
- mError = render.getErrorMessage();
- if (mError == null) {
- mError = "";
- }
- }
-
- if (render.getStatus() == Status.ERROR_TIMEOUT) {
- // TODO: Special handling? schedule update again later
- return;
- }
- if (render.isSuccess()) {
- BufferedImage image = session.getImage();
- if (image != null) {
- createThumbnail(image);
- }
- }
-
- if (mError != null) {
- createErrorThumbnail();
- }
- }
-
- private ResourceResolver getResourceResolver(Configuration configuration) {
- ResourceResolver resourceResolver = mResourceResolver.get();
- if (resourceResolver != null) {
- return resourceResolver;
- }
-
- GraphicalEditorPart graphicalEditor = mCanvas.getEditorDelegate().getGraphicalEditor();
- String theme = configuration.getTheme();
- if (theme == null) {
- return null;
- }
-
- Map<ResourceType, Map<String, ResourceValue>> configuredFrameworkRes = null;
- Map<ResourceType, Map<String, ResourceValue>> configuredProjectRes = null;
-
- FolderConfiguration config = configuration.getFullConfig();
- IAndroidTarget target = graphicalEditor.getRenderingTarget();
- ResourceRepository frameworkRes = null;
- if (target != null) {
- Sdk sdk = Sdk.getCurrent();
- if (sdk == null) {
- return null;
- }
- AndroidTargetData data = sdk.getTargetData(target);
-
- if (data != null) {
- // TODO: SHARE if possible
- frameworkRes = data.getFrameworkResources();
- configuredFrameworkRes = frameworkRes.getConfiguredResources(config);
- } else {
- return null;
- }
- } else {
- return null;
- }
- assert configuredFrameworkRes != null;
-
-
- // get the resources of the file's project.
- ProjectResources projectRes = ResourceManager.getInstance().getProjectResources(
- graphicalEditor.getProject());
- configuredProjectRes = projectRes.getConfiguredResources(config);
-
- if (!theme.startsWith(PREFIX_RESOURCE_REF)) {
- if (frameworkRes.hasResourceItem(ANDROID_STYLE_RESOURCE_PREFIX + theme)) {
- theme = ANDROID_STYLE_RESOURCE_PREFIX + theme;
- } else {
- theme = STYLE_RESOURCE_PREFIX + theme;
- }
- }
-
- resourceResolver = ResourceResolver.create(
- configuredProjectRes, configuredFrameworkRes,
- ResourceHelper.styleToTheme(theme),
- ResourceHelper.isProjectStyle(theme));
- mResourceResolver = new SoftReference<ResourceResolver>(resourceResolver);
- return resourceResolver;
- }
-
- /**
- * Sets the new image of the preview and generates a thumbnail
- *
- * @param image the full size image
- */
- void createThumbnail(BufferedImage image) {
- if (image == null) {
- mThumbnail = null;
- return;
- }
-
- ImageOverlay imageOverlay = mCanvas.getImageOverlay();
- boolean drawShadows = imageOverlay == null || imageOverlay.getShowDropShadow();
- double scale = getWidth() / (double) image.getWidth();
- int shadowSize;
- if (LARGE_SHADOWS) {
- shadowSize = drawShadows ? SHADOW_SIZE : 0;
- } else {
- shadowSize = drawShadows ? SMALL_SHADOW_SIZE : 0;
- }
- if (scale < 1.0) {
- if (LARGE_SHADOWS) {
- image = ImageUtils.scale(image, scale, scale,
- shadowSize, shadowSize);
- if (drawShadows) {
- ImageUtils.drawRectangleShadow(image, 0, 0,
- image.getWidth() - shadowSize,
- image.getHeight() - shadowSize);
- }
- } else {
- image = ImageUtils.scale(image, scale, scale,
- shadowSize, shadowSize);
- if (drawShadows) {
- ImageUtils.drawSmallRectangleShadow(image, 0, 0,
- image.getWidth() - shadowSize,
- image.getHeight() - shadowSize);
- }
- }
- }
-
- mThumbnail = SwtUtils.convertToSwt(mCanvas.getDisplay(), image,
- true /* transferAlpha */, -1);
- }
-
- void createErrorThumbnail() {
- int shadowSize = LARGE_SHADOWS ? SHADOW_SIZE : SMALL_SHADOW_SIZE;
- int width = getWidth();
- int height = getHeight();
- BufferedImage image = new BufferedImage(width + shadowSize, height + shadowSize,
- BufferedImage.TYPE_INT_ARGB);
-
- Graphics2D g = image.createGraphics();
- g.setColor(new java.awt.Color(0xfffbfcc6));
- g.fillRect(0, 0, width, height);
-
- g.dispose();
-
- ImageOverlay imageOverlay = mCanvas.getImageOverlay();
- boolean drawShadows = imageOverlay == null || imageOverlay.getShowDropShadow();
- if (drawShadows) {
- if (LARGE_SHADOWS) {
- ImageUtils.drawRectangleShadow(image, 0, 0,
- image.getWidth() - SHADOW_SIZE,
- image.getHeight() - SHADOW_SIZE);
- } else {
- ImageUtils.drawSmallRectangleShadow(image, 0, 0,
- image.getWidth() - SMALL_SHADOW_SIZE,
- image.getHeight() - SMALL_SHADOW_SIZE);
- }
- }
-
- mThumbnail = SwtUtils.convertToSwt(mCanvas.getDisplay(), image,
- true /* transferAlpha */, -1);
- }
-
- private static double getScale(int width, int height) {
- int maxWidth = RenderPreviewManager.getMaxWidth();
- int maxHeight = RenderPreviewManager.getMaxHeight();
- if (width > 0 && height > 0
- && (width > maxWidth || height > maxHeight)) {
- if (width >= height) { // landscape
- return maxWidth / (double) width;
- } else { // portrait
- return maxHeight / (double) height;
- }
- }
-
- return 1.0;
- }
-
- /**
- * Returns the width of the preview, in pixels
- *
- * @return the width in pixels
- */
- public int getWidth() {
- return (int) (mWidth * mScale * RenderPreviewManager.getScale());
- }
-
- /**
- * Returns the height of the preview, in pixels
- *
- * @return the height in pixels
- */
- public int getHeight() {
- return (int) (mHeight * mScale * RenderPreviewManager.getScale());
- }
-
- /**
- * Handles clicks within the preview (x and y are positions relative within the
- * preview
- *
- * @param x the x coordinate within the preview where the click occurred
- * @param y the y coordinate within the preview where the click occurred
- * @return true if this preview handled (and therefore consumed) the click
- */
- public boolean click(int x, int y) {
- if (y >= mTitleHeight && y < mTitleHeight + HEADER_HEIGHT) {
- int left = 0;
- left += CLOSE_ICON_WIDTH;
- if (x <= left) {
- // Delete
- mManager.deletePreview(this);
- return true;
- }
- left += ZOOM_IN_ICON_WIDTH;
- if (x <= left) {
- // Zoom in
- mScale = mScale * (1 / 0.5);
- if (Math.abs(mScale-1.0) < 0.0001) {
- mScale = 1.0;
- }
-
- render(0);
- mManager.layout(true);
- mCanvas.redraw();
- return true;
- }
- left += ZOOM_OUT_ICON_WIDTH;
- if (x <= left) {
- // Zoom out
- mScale = mScale * (0.5 / 1);
- if (Math.abs(mScale-1.0) < 0.0001) {
- mScale = 1.0;
- }
- render(0);
-
- mManager.layout(true);
- mCanvas.redraw();
- return true;
- }
- left += EDIT_ICON_WIDTH;
- if (x <= left) {
- // Edit. For now, just rename
- InputDialog d = new InputDialog(
- AdtPlugin.getShell(),
- "Rename Preview", // title
- "Name:",
- getDisplayName(),
- null);
- if (d.open() == Window.OK) {
- String newName = d.getValue();
- mConfiguration.setDisplayName(newName);
- if (mDescription != null) {
- mManager.rename(mDescription, newName);
- }
- mCanvas.redraw();
- }
-
- return true;
- }
-
- // Clicked anywhere else on header
- // Perhaps open Edit dialog here?
- }
-
- mManager.switchTo(this);
- return true;
- }
-
- /**
- * Paints the preview at the given x/y position
- *
- * @param gc the graphics context to paint it into
- * @param x the x coordinate to paint the preview at
- * @param y the y coordinate to paint the preview at
- */
- void paint(GC gc, int x, int y) {
- mTitleHeight = paintTitle(gc, x, y, true /*showFile*/);
- y += mTitleHeight;
- y += 2;
-
- int width = getWidth();
- int height = getHeight();
- if (mThumbnail != null && mError == null) {
- gc.drawImage(mThumbnail, x, y);
-
- if (mActive) {
- int oldWidth = gc.getLineWidth();
- gc.setLineWidth(3);
- gc.setForeground(gc.getDevice().getSystemColor(SWT.COLOR_LIST_SELECTION));
- gc.drawRectangle(x - 1, y - 1, width + 2, height + 2);
- gc.setLineWidth(oldWidth);
- }
- } else if (mError != null) {
- if (mThumbnail != null) {
- gc.drawImage(mThumbnail, x, y);
- } else {
- gc.setBackground(gc.getDevice().getSystemColor(SWT.COLOR_WIDGET_BORDER));
- gc.drawRectangle(x, y, width, height);
- }
-
- gc.setClipping(x, y, width, height);
- Image icon = IconFactory.getInstance().getIcon("renderError"); //$NON-NLS-1$
- ImageData data = icon.getImageData();
- int prevAlpha = gc.getAlpha();
- int alpha = 96;
- if (mThumbnail != null) {
- alpha -= 32;
- }
- gc.setAlpha(alpha);
- gc.drawImage(icon, x + (width - data.width) / 2, y + (height - data.height) / 2);
-
- String msg = mError;
- Density density = mConfiguration.getDensity();
- if (density == Density.TV || density == Density.LOW) {
- msg = "Broken rendering library; unsupported DPI. Try using the SDK manager " +
- "to get updated layout libraries.";
- }
- int charWidth = gc.getFontMetrics().getAverageCharWidth();
- int charsPerLine = (width - 10) / charWidth;
- msg = SdkUtils.wrap(msg, charsPerLine, null);
- gc.setAlpha(255);
- gc.setForeground(gc.getDevice().getSystemColor(SWT.COLOR_BLACK));
- gc.drawText(msg, x + 5, y + HEADER_HEIGHT, true);
- gc.setAlpha(prevAlpha);
- gc.setClipping((Region) null);
- } else {
- gc.setBackground(gc.getDevice().getSystemColor(SWT.COLOR_WIDGET_BORDER));
- gc.drawRectangle(x, y, width, height);
-
- Image icon = IconFactory.getInstance().getIcon("refreshPreview"); //$NON-NLS-1$
- ImageData data = icon.getImageData();
- int prevAlpha = gc.getAlpha();
- gc.setAlpha(96);
- gc.drawImage(icon, x + (width - data.width) / 2,
- y + (height - data.height) / 2);
- gc.setAlpha(prevAlpha);
- }
-
- if (mActive) {
- int left = x ;
- int prevAlpha = gc.getAlpha();
- gc.setAlpha(208);
- Color bg = mCanvas.getDisplay().getSystemColor(SWT.COLOR_WHITE);
- gc.setBackground(bg);
- gc.fillRectangle(left, y, x + width - left, HEADER_HEIGHT);
- gc.setAlpha(prevAlpha);
-
- y += 2;
-
- // Paint icons
- gc.drawImage(CLOSE_ICON, left, y);
- left += CLOSE_ICON_WIDTH;
-
- gc.drawImage(ZOOM_IN_ICON, left, y);
- left += ZOOM_IN_ICON_WIDTH;
-
- gc.drawImage(ZOOM_OUT_ICON, left, y);
- left += ZOOM_OUT_ICON_WIDTH;
-
- gc.drawImage(EDIT_ICON, left, y);
- left += EDIT_ICON_WIDTH;
- }
- }
-
- /**
- * Paints the preview title at the given position (and returns the required
- * height)
- *
- * @param gc the graphics context to paint into
- * @param x the left edge of the preview rectangle
- * @param y the top edge of the preview rectangle
- */
- private int paintTitle(GC gc, int x, int y, boolean showFile) {
- String displayName = getDisplayName();
- return paintTitle(gc, x, y, showFile, displayName);
- }
-
- /**
- * Paints the preview title at the given position (and returns the required
- * height)
- *
- * @param gc the graphics context to paint into
- * @param x the left edge of the preview rectangle
- * @param y the top edge of the preview rectangle
- * @param displayName the title string to be used
- */
- int paintTitle(GC gc, int x, int y, boolean showFile, String displayName) {
- int titleHeight = 0;
-
- if (showFile && mIncludedWithin != null) {
- if (mManager.getMode() != INCLUDES) {
- displayName = "<include>";
- } else {
- // Skip: just paint footer instead
- displayName = null;
- }
- }
-
- int width = getWidth();
- int labelTop = y + 1;
- gc.setClipping(x, labelTop, width, 100);
-
- // Use font height rather than extent height since we want two adjacent
- // previews (which may have different display names and therefore end
- // up with slightly different extent heights) to have identical title
- // heights such that they are aligned identically
- int fontHeight = gc.getFontMetrics().getHeight();
-
- if (displayName != null && displayName.length() > 0) {
- gc.setForeground(gc.getDevice().getSystemColor(SWT.COLOR_WHITE));
- Point extent = gc.textExtent(displayName);
- int labelLeft = Math.max(x, x + (width - extent.x) / 2);
- Image icon = null;
- Locale locale = mConfiguration.getLocale();
- if (locale != null && (locale.hasLanguage() || locale.hasRegion())
- && (!(mConfiguration instanceof NestedConfiguration)
- || ((NestedConfiguration) mConfiguration).isOverridingLocale())) {
- icon = locale.getFlagImage();
- }
-
- if (icon != null) {
- int flagWidth = icon.getImageData().width;
- int flagHeight = icon.getImageData().height;
- labelLeft = Math.max(x + flagWidth / 2, labelLeft);
- gc.drawImage(icon, labelLeft - flagWidth / 2 - 1, labelTop);
- labelLeft += flagWidth / 2 + 1;
- gc.drawText(displayName, labelLeft,
- labelTop - (extent.y - flagHeight) / 2, true);
- } else {
- gc.drawText(displayName, labelLeft, labelTop, true);
- }
-
- labelTop += extent.y;
- titleHeight += fontHeight;
- }
-
- if (showFile && (mAlternateInput != null || mIncludedWithin != null)) {
- // Draw file flag, and parent folder name
- IFile file = mAlternateInput != null
- ? mAlternateInput : mIncludedWithin.getFile();
- String fileName = file.getParent().getName() + File.separator
- + file.getName();
- Point extent = gc.textExtent(fileName);
- Image icon = IconFactory.getInstance().getIcon("android_file"); //$NON-NLS-1$
- int flagWidth = icon.getImageData().width;
- int flagHeight = icon.getImageData().height;
-
- int labelLeft = Math.max(x, x + (width - extent.x - flagWidth - 1) / 2);
-
- gc.drawImage(icon, labelLeft, labelTop);
-
- gc.setForeground(gc.getDevice().getSystemColor(SWT.COLOR_GRAY));
- labelLeft += flagWidth + 1;
- labelTop -= (extent.y - flagHeight) / 2;
- gc.drawText(fileName, labelLeft, labelTop, true);
-
- titleHeight += Math.max(titleHeight, icon.getImageData().height);
- }
-
- gc.setClipping((Region) null);
-
- return titleHeight;
- }
-
- /**
- * Notifies that the preview's configuration has changed.
- *
- * @param flags the change flags, a bitmask corresponding to the
- * {@code CHANGE_} constants in {@link ConfigurationClient}
- */
- public void configurationChanged(int flags) {
- if (!mVisible) {
- mDirty |= flags;
- return;
- }
-
- if ((flags & MASK_RENDERING) != 0) {
- mResourceResolver.clear();
- // Handle inheritance
- mConfiguration.syncFolderConfig();
- updateForkStatus();
- updateSize();
- }
-
- // Sanity check to make sure things are working correctly
- if (DEBUG) {
- RenderPreviewMode mode = mManager.getMode();
- if (mode == DEFAULT) {
- assert mConfiguration instanceof VaryingConfiguration;
- VaryingConfiguration config = (VaryingConfiguration) mConfiguration;
- int alternateFlags = config.getAlternateFlags();
- switch (alternateFlags) {
- case Configuration.CFG_DEVICE_STATE: {
- State configState = config.getDeviceState();
- State chooserState = mManager.getChooser().getConfiguration()
- .getDeviceState();
- assert configState != null && chooserState != null;
- assert !configState.getName().equals(chooserState.getName())
- : configState.toString() + ':' + chooserState;
-
- Device configDevice = config.getDevice();
- Device chooserDevice = mManager.getChooser().getConfiguration()
- .getDevice();
- assert configDevice != null && chooserDevice != null;
- assert configDevice == chooserDevice
- : configDevice.toString() + ':' + chooserDevice;
-
- break;
- }
- case Configuration.CFG_DEVICE: {
- Device configDevice = config.getDevice();
- Device chooserDevice = mManager.getChooser().getConfiguration()
- .getDevice();
- assert configDevice != null && chooserDevice != null;
- assert configDevice != chooserDevice
- : configDevice.toString() + ':' + chooserDevice;
-
- State configState = config.getDeviceState();
- State chooserState = mManager.getChooser().getConfiguration()
- .getDeviceState();
- assert configState != null && chooserState != null;
- assert configState.getName().equals(chooserState.getName())
- : configState.toString() + ':' + chooserState;
-
- break;
- }
- case Configuration.CFG_LOCALE: {
- Locale configLocale = config.getLocale();
- Locale chooserLocale = mManager.getChooser().getConfiguration()
- .getLocale();
- assert configLocale != null && chooserLocale != null;
- assert configLocale != chooserLocale
- : configLocale.toString() + ':' + chooserLocale;
- break;
- }
- default: {
- // Some other type of override I didn't anticipate
- assert false : alternateFlags;
- }
- }
- }
- }
-
- mDirty = 0;
- mManager.scheduleRender(this);
- }
-
- private void updateSize() {
- Device device = mConfiguration.getDevice();
- if (device == null) {
- return;
- }
- Screen screen = device.getDefaultHardware().getScreen();
- if (screen == null) {
- return;
- }
-
- FolderConfiguration folderConfig = mConfiguration.getFullConfig();
- ScreenOrientationQualifier qualifier = folderConfig.getScreenOrientationQualifier();
- ScreenOrientation orientation = qualifier == null
- ? ScreenOrientation.PORTRAIT : qualifier.getValue();
-
- // compute width and height to take orientation into account.
- int x = screen.getXDimension();
- int y = screen.getYDimension();
- int screenWidth, screenHeight;
-
- if (x > y) {
- if (orientation == ScreenOrientation.LANDSCAPE) {
- screenWidth = x;
- screenHeight = y;
- } else {
- screenWidth = y;
- screenHeight = x;
- }
- } else {
- if (orientation == ScreenOrientation.LANDSCAPE) {
- screenWidth = y;
- screenHeight = x;
- } else {
- screenWidth = x;
- screenHeight = y;
- }
- }
-
- int width = RenderPreviewManager.getMaxWidth();
- int height = RenderPreviewManager.getMaxHeight();
- if (screenWidth > 0) {
- double scale = getScale(screenWidth, screenHeight);
- width = (int) (screenWidth * scale);
- height = (int) (screenHeight * scale);
- }
-
- if (width != mWidth || height != mHeight) {
- mWidth = width;
- mHeight = height;
-
- Image thumbnail = mThumbnail;
- mThumbnail = null;
- if (thumbnail != null) {
- thumbnail.dispose();
- }
- if (mHeight != 0) {
- mAspectRatio = mWidth / (double) mHeight;
- }
- }
- }
-
- /**
- * Returns the configuration associated with this preview
- *
- * @return the configuration
- */
- @NonNull
- public Configuration getConfiguration() {
- return mConfiguration;
- }
-
- // ---- Implements IJobChangeListener ----
-
- @Override
- public void aboutToRun(IJobChangeEvent event) {
- }
-
- @Override
- public void awake(IJobChangeEvent event) {
- }
-
- @Override
- public void done(IJobChangeEvent event) {
- mJob = null;
- }
-
- @Override
- public void running(IJobChangeEvent event) {
- }
-
- @Override
- public void scheduled(IJobChangeEvent event) {
- }
-
- @Override
- public void sleeping(IJobChangeEvent event) {
- }
-
- // ---- Delayed Rendering ----
-
- private final class RenderJob extends UIJob {
- public RenderJob() {
- super("RenderPreview");
- setSystem(true);
- setUser(false);
- }
-
- @Override
- public IStatus runInUIThread(IProgressMonitor monitor) {
- mJob = null;
- if (!mCanvas.isDisposed()) {
- renderSync();
- mCanvas.redraw();
- return org.eclipse.core.runtime.Status.OK_STATUS;
- }
-
- return org.eclipse.core.runtime.Status.CANCEL_STATUS;
- }
-
- @Override
- public Display getDisplay() {
- if (mCanvas.isDisposed()) {
- return null;
- }
- return mCanvas.getDisplay();
- }
- }
-
- private final class AsyncRenderJob extends Job {
- public AsyncRenderJob() {
- super("RenderPreview");
- setSystem(true);
- setUser(false);
- }
-
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- mJob = null;
-
- if (mCanvas.isDisposed()) {
- return org.eclipse.core.runtime.Status.CANCEL_STATUS;
- }
-
- renderSync();
-
- // Update display
- mCanvas.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- mCanvas.redraw();
- }
- });
-
- return org.eclipse.core.runtime.Status.OK_STATUS;
- }
- }
-
- /**
- * Sets the input file to use for rendering. If not set, this will just be
- * the same file as the configuration chooser. This is used to render other
- * layouts, such as variations of the currently edited layout, which are
- * not kept in sync with the main layout.
- *
- * @param file the file to set as input
- */
- public void setAlternateInput(@Nullable IFile file) {
- mAlternateInput = file;
- }
-
- /** Corresponding description for this preview if it is a manually added preview */
- private @Nullable ConfigurationDescription mDescription;
-
- /**
- * Sets the description of this preview, if this preview is a manually added preview
- *
- * @param description the description of this preview
- */
- public void setDescription(@Nullable ConfigurationDescription description) {
- mDescription = description;
- }
-
- /**
- * Returns the description of this preview, if this preview is a manually added preview
- *
- * @return the description
- */
- @Nullable
- public ConfigurationDescription getDescription() {
- return mDescription;
- }
-
- @Override
- public String toString() {
- return getDisplayName() + ':' + mConfiguration;
- }
-
- /** Sorts render previews into increasing aspect ratio order */
- static Comparator<RenderPreview> INCREASING_ASPECT_RATIO = new Comparator<RenderPreview>() {
- @Override
- public int compare(RenderPreview preview1, RenderPreview preview2) {
- return (int) Math.signum(preview1.mAspectRatio - preview2.mAspectRatio);
- }
- };
- /** Sorts render previews into visual order: row by row, column by column */
- static Comparator<RenderPreview> VISUAL_ORDER = new Comparator<RenderPreview>() {
- @Override
- public int compare(RenderPreview preview1, RenderPreview preview2) {
- int delta = preview1.mY - preview2.mY;
- if (delta == 0) {
- delta = preview1.mX - preview2.mX;
- }
- return delta;
- }
- };
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderPreviewList.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderPreviewList.java
deleted file mode 100644
index 2bcdba382..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderPreviewList.java
+++ /dev/null
@@ -1,222 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.annotations.NonNull;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.formatting.EclipseXmlPrettyPrinter;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.Configuration;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigurationChooser;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigurationDescription;
-import com.android.sdklib.devices.Device;
-import com.google.common.base.Charsets;
-import com.google.common.collect.Lists;
-import com.google.common.io.Files;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.QualifiedName;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-/** A list of render previews */
-class RenderPreviewList {
- /** Name of file saved in project directory storing previews */
- private static final String PREVIEW_FILE_NAME = "previews.xml"; //$NON-NLS-1$
-
- /** Qualified name for the per-project persistent property include-map */
- private final static QualifiedName PREVIEW_LIST = new QualifiedName(AdtPlugin.PLUGIN_ID,
- "previewlist");//$NON-NLS-1$
-
- private final IProject mProject;
- private final List<ConfigurationDescription> mList = Lists.newArrayList();
-
- private RenderPreviewList(@NonNull IProject project) {
- mProject = project;
- }
-
- /**
- * Returns the {@link RenderPreviewList} for the given project
- *
- * @param project the project the list is associated with
- * @return a {@link RenderPreviewList} for the given project, never null
- */
- @NonNull
- public static RenderPreviewList get(@NonNull IProject project) {
- RenderPreviewList list = null;
- try {
- list = (RenderPreviewList) project.getSessionProperty(PREVIEW_LIST);
- } catch (CoreException e) {
- // Not a problem; we will just create a new one
- }
-
- if (list == null) {
- list = new RenderPreviewList(project);
- try {
- project.setSessionProperty(PREVIEW_LIST, list);
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- }
-
- return list;
- }
-
- private File getManualFile() {
- return new File(AdtUtils.getAbsolutePath(mProject).toFile(), PREVIEW_FILE_NAME);
- }
-
- void load(Collection<Device> deviceList) throws IOException {
- File file = getManualFile();
- if (file.exists()) {
- load(file, deviceList);
- }
- }
-
- void save() throws IOException {
- deleteFile();
- if (!mList.isEmpty()) {
- File file = getManualFile();
- save(file);
- }
- }
-
- private void save(File file) throws IOException {
- //Document document = DomUtilities.createEmptyPlainDocument();
- Document document = DomUtilities.createEmptyDocument();
- if (document != null) {
- for (ConfigurationDescription description : mList) {
- description.toXml(document);
- }
- String xml = EclipseXmlPrettyPrinter.prettyPrint(document, true);
- Files.write(xml, file, Charsets.UTF_8);
- }
- }
-
- void load(File file, Collection<Device> deviceList) throws IOException {
- mList.clear();
-
- String xml = Files.toString(file, Charsets.UTF_8);
- Document document = DomUtilities.parseDocument(xml, true);
- if (document == null || document.getDocumentElement() == null) {
- return;
- }
- List<Element> elements = DomUtilities.getChildren(document.getDocumentElement());
- for (Element element : elements) {
- ConfigurationDescription description = ConfigurationDescription.fromXml(
- mProject, element, deviceList);
- if (description != null) {
- mList.add(description);
- }
- }
- }
-
- /**
- * Create a list of previews for the given canvas that matches the internal
- * configuration preview list
- *
- * @param canvas the associated canvas
- * @return a new list of previews linked to the given canvas
- */
- @NonNull
- List<RenderPreview> createPreviews(LayoutCanvas canvas) {
- if (mList.isEmpty()) {
- return new ArrayList<RenderPreview>();
- }
- List<RenderPreview> previews = Lists.newArrayList();
- RenderPreviewManager manager = canvas.getPreviewManager();
- ConfigurationChooser chooser = canvas.getEditorDelegate().getGraphicalEditor()
- .getConfigurationChooser();
-
- Configuration chooserConfig = chooser.getConfiguration();
- for (ConfigurationDescription description : mList) {
- Configuration configuration = Configuration.create(chooser);
- configuration.setDisplayName(description.displayName);
- configuration.setActivity(description.activity);
- configuration.setLocale(
- description.locale != null ? description.locale : chooserConfig.getLocale(),
- true);
- // TODO: Make sure this layout isn't in some v-folder which is incompatible
- // with this target!
- configuration.setTarget(
- description.target != null ? description.target : chooserConfig.getTarget(),
- true);
- configuration.setTheme(
- description.theme != null ? description.theme : chooserConfig.getTheme());
- configuration.setDevice(
- description.device != null ? description.device : chooserConfig.getDevice(),
- true);
- configuration.setDeviceState(
- description.state != null ? description.state : chooserConfig.getDeviceState(),
- true);
- configuration.setNightMode(
- description.nightMode != null ? description.nightMode
- : chooserConfig.getNightMode(), true);
- configuration.setUiMode(
- description.uiMode != null ? description.uiMode : chooserConfig.getUiMode(), true);
-
- //configuration.syncFolderConfig();
- configuration.getFullConfig().set(description.folder);
-
- RenderPreview preview = RenderPreview.create(manager, configuration);
-
- preview.setDescription(description);
- previews.add(preview);
- }
-
- return previews;
- }
-
- void remove(@NonNull RenderPreview preview) {
- ConfigurationDescription description = preview.getDescription();
- if (description != null) {
- mList.remove(description);
- }
- }
-
- boolean isEmpty() {
- return mList.isEmpty();
- }
-
- void add(@NonNull RenderPreview preview) {
- Configuration configuration = preview.getConfiguration();
- ConfigurationDescription description =
- ConfigurationDescription.fromConfiguration(mProject, configuration);
- // RenderPreviews can have display names that aren't reflected in the configuration
- description.displayName = preview.getDisplayName();
- mList.add(description);
- preview.setDescription(description);
- }
-
- void delete() {
- mList.clear();
- deleteFile();
- }
-
- private void deleteFile() {
- File file = getManualFile();
- if (file.exists()) {
- file.delete();
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderPreviewManager.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderPreviewManager.java
deleted file mode 100644
index 98dde86e0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderPreviewManager.java
+++ /dev/null
@@ -1,1696 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.ide.eclipse.adt.internal.editors.layout.configuration.Configuration.CFG_DEVICE;
-import static com.android.ide.eclipse.adt.internal.editors.layout.configuration.Configuration.CFG_DEVICE_STATE;
-import static com.android.ide.eclipse.adt.internal.editors.layout.configuration.Configuration.MASK_ALL;
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.ImageUtils.SHADOW_SIZE;
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.ImageUtils.SMALL_SHADOW_SIZE;
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderPreview.LARGE_SHADOWS;
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderPreviewMode.CUSTOM;
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderPreviewMode.NONE;
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderPreviewMode.SCREENS;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.rendering.api.Capability;
-import com.android.ide.common.resources.configuration.DensityQualifier;
-import com.android.ide.common.resources.configuration.DeviceConfigHelper;
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.common.resources.configuration.LocaleQualifier;
-import com.android.ide.common.resources.configuration.ScreenSizeQualifier;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.Configuration;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigurationChooser;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigurationClient;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigurationDescription;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.Locale;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.NestedConfiguration;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.VaryingConfiguration;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.IncludeFinder.Reference;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.resources.Density;
-import com.android.resources.ScreenSize;
-import com.android.sdklib.devices.Device;
-import com.android.sdklib.devices.Screen;
-import com.android.sdklib.devices.State;
-import com.google.common.collect.Lists;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.ScrollBar;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.ide.IDE;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-
-/**
- * Manager for the configuration previews, which handles layout computations,
- * managing the image buffer cache, etc
- */
-public class RenderPreviewManager {
- private static double sScale = 1.0;
- private static final int RENDER_DELAY = 150;
- private static final int PREVIEW_VGAP = 18;
- private static final int PREVIEW_HGAP = 12;
- private static final int MAX_WIDTH = 200;
- private static final int MAX_HEIGHT = MAX_WIDTH;
- private static final int ZOOM_ICON_WIDTH = 16;
- private static final int ZOOM_ICON_HEIGHT = 16;
- private @Nullable List<RenderPreview> mPreviews;
- private @Nullable RenderPreviewList mManualList;
- private final @NonNull LayoutCanvas mCanvas;
- private final @NonNull CanvasTransform mVScale;
- private final @NonNull CanvasTransform mHScale;
- private int mPrevCanvasWidth;
- private int mPrevCanvasHeight;
- private int mPrevImageWidth;
- private int mPrevImageHeight;
- private @NonNull RenderPreviewMode mMode = NONE;
- private @Nullable RenderPreview mActivePreview;
- private @Nullable ScrollBarListener mListener;
- private int mLayoutHeight;
- /** Last seen state revision in this {@link RenderPreviewManager}. If less
- * than {@link #sRevision}, the previews need to be updated on next exposure */
- private static int mRevision;
- /** Current global revision count */
- private static int sRevision;
- private boolean mNeedLayout;
- private boolean mNeedRender;
- private boolean mNeedZoom;
- private SwapAnimation mAnimation;
-
- /**
- * Creates a {@link RenderPreviewManager} associated with the given canvas
- *
- * @param canvas the canvas to manage previews for
- */
- public RenderPreviewManager(@NonNull LayoutCanvas canvas) {
- mCanvas = canvas;
- mHScale = canvas.getHorizontalTransform();
- mVScale = canvas.getVerticalTransform();
- }
-
- /**
- * Revise the global state revision counter. This will cause all layout
- * preview managers to refresh themselves to the latest revision when they
- * are next exposed.
- */
- public static void bumpRevision() {
- sRevision++;
- }
-
- /**
- * Returns the associated chooser
- *
- * @return the associated chooser
- */
- @NonNull
- ConfigurationChooser getChooser() {
- GraphicalEditorPart editor = mCanvas.getEditorDelegate().getGraphicalEditor();
- return editor.getConfigurationChooser();
- }
-
- /**
- * Returns the associated canvas
- *
- * @return the canvas
- */
- @NonNull
- public LayoutCanvas getCanvas() {
- return mCanvas;
- }
-
- /** Zooms in (grows all previews) */
- public void zoomIn() {
- sScale = sScale * (1 / 0.9);
- if (Math.abs(sScale-1.0) < 0.0001) {
- sScale = 1.0;
- }
-
- updatedZoom();
- }
-
- /** Zooms out (shrinks all previews) */
- public void zoomOut() {
- sScale = sScale * (0.9 / 1);
- if (Math.abs(sScale-1.0) < 0.0001) {
- sScale = 1.0;
- }
- updatedZoom();
- }
-
- /** Zooms to 100 (resets zoom) */
- public void zoomReset() {
- sScale = 1.0;
- updatedZoom();
- mNeedZoom = mNeedLayout = true;
- mCanvas.redraw();
- }
-
- private void updatedZoom() {
- if (hasPreviews()) {
- for (RenderPreview preview : mPreviews) {
- preview.disposeThumbnail();
- }
- RenderPreview preview = mCanvas.getPreview();
- if (preview != null) {
- preview.disposeThumbnail();
- }
- }
-
- mNeedLayout = mNeedRender = true;
- mCanvas.redraw();
- }
-
- static int getMaxWidth() {
- return (int) (sScale * MAX_WIDTH);
- }
-
- static int getMaxHeight() {
- return (int) (sScale * MAX_HEIGHT);
- }
-
- static double getScale() {
- return sScale;
- }
-
- /**
- * Returns whether there are any manual preview items (provided the current
- * mode is manual previews
- *
- * @return true if there are items in the manual preview list
- */
- public boolean hasManualPreviews() {
- assert mMode == CUSTOM;
- return mManualList != null && !mManualList.isEmpty();
- }
-
- /** Delete all the previews */
- public void deleteManualPreviews() {
- disposePreviews();
- selectMode(NONE);
- mCanvas.setFitScale(true /* onlyZoomOut */, true /*allowZoomIn*/);
-
- if (mManualList != null) {
- mManualList.delete();
- }
- }
-
- /** Dispose all the previews */
- public void disposePreviews() {
- if (mPreviews != null) {
- List<RenderPreview> old = mPreviews;
- mPreviews = null;
- for (RenderPreview preview : old) {
- preview.dispose();
- }
- }
- }
-
- /**
- * Deletes the given preview
- *
- * @param preview the preview to be deleted
- */
- public void deletePreview(RenderPreview preview) {
- mPreviews.remove(preview);
- preview.dispose();
- layout(true);
- mCanvas.redraw();
-
- if (mManualList != null) {
- mManualList.remove(preview);
- saveList();
- }
- }
-
- /**
- * Compute the total width required for the previews, including internal padding
- *
- * @return total width in pixels
- */
- public int computePreviewWidth() {
- int maxPreviewWidth = 0;
- if (hasPreviews()) {
- for (RenderPreview preview : mPreviews) {
- maxPreviewWidth = Math.max(maxPreviewWidth, preview.getWidth());
- }
-
- if (maxPreviewWidth > 0) {
- maxPreviewWidth += 2 * PREVIEW_HGAP; // 2x for left and right side
- maxPreviewWidth += LARGE_SHADOWS ? SHADOW_SIZE : SMALL_SHADOW_SIZE;
- }
-
- return maxPreviewWidth;
- }
-
- return 0;
- }
-
- /**
- * Layout Algorithm. This sets the {@link RenderPreview#getX()} and
- * {@link RenderPreview#getY()} coordinates of all the previews. It also
- * marks previews as visible or invisible via
- * {@link RenderPreview#setVisible(boolean)} according to their position and
- * the current visible view port in the layout canvas. Finally, it also sets
- * the {@code mLayoutHeight} field, such that the scrollbars can compute the
- * right scrolled area, and that scrolling can cause render refreshes on
- * views that are made visible.
- * <p>
- * This is not a traditional bin packing problem, because the objects to be
- * packaged do not have a fixed size; we can scale them up and down in order
- * to provide an "optimal" size.
- * <p>
- * See http://en.wikipedia.org/wiki/Packing_problem See
- * http://en.wikipedia.org/wiki/Bin_packing_problem
- */
- void layout(boolean refresh) {
- mNeedLayout = false;
-
- if (mPreviews == null || mPreviews.isEmpty()) {
- return;
- }
-
- int scaledImageWidth = mHScale.getScaledImgSize();
- int scaledImageHeight = mVScale.getScaledImgSize();
- Rectangle clientArea = mCanvas.getClientArea();
-
- if (!refresh &&
- (scaledImageWidth == mPrevImageWidth
- && scaledImageHeight == mPrevImageHeight
- && clientArea.width == mPrevCanvasWidth
- && clientArea.height == mPrevCanvasHeight)) {
- // No change
- return;
- }
-
- mPrevImageWidth = scaledImageWidth;
- mPrevImageHeight = scaledImageHeight;
- mPrevCanvasWidth = clientArea.width;
- mPrevCanvasHeight = clientArea.height;
-
- if (mListener == null) {
- mListener = new ScrollBarListener();
- mCanvas.getVerticalBar().addSelectionListener(mListener);
- }
-
- beginRenderScheduling();
-
- mLayoutHeight = 0;
-
- if (previewsHaveIdenticalSize() || fixedOrder()) {
- // If all the preview boxes are of identical sizes, or if the order is predetermined,
- // just lay them out in rows.
- rowLayout();
- } else if (previewsFit()) {
- layoutFullFit();
- } else {
- rowLayout();
- }
-
- mCanvas.updateScrollBars();
- }
-
- /**
- * Performs a simple layout where the views are laid out in a row, wrapping
- * around the top left canvas image.
- */
- private void rowLayout() {
- // TODO: Separate layout heuristics for portrait and landscape orientations (though
- // it also depends on the dimensions of the canvas window, which determines the
- // shape of the leftover space)
-
- int scaledImageWidth = mHScale.getScaledImgSize();
- int scaledImageHeight = mVScale.getScaledImgSize();
- Rectangle clientArea = mCanvas.getClientArea();
-
- int availableWidth = clientArea.x + clientArea.width - getX();
- int availableHeight = clientArea.y + clientArea.height - getY();
- int maxVisibleY = clientArea.y + clientArea.height;
-
- int bottomBorder = scaledImageHeight;
- int rightHandSide = scaledImageWidth + PREVIEW_HGAP;
- int nextY = 0;
-
- // First lay out images across the top right hand side
- int x = rightHandSide;
- int y = 0;
- boolean wrapped = false;
-
- int vgap = PREVIEW_VGAP;
- for (RenderPreview preview : mPreviews) {
- // If we have forked previews, double the vgap to allow space for two labels
- if (preview.isForked()) {
- vgap *= 2;
- break;
- }
- }
-
- List<RenderPreview> aspectOrder;
- if (!fixedOrder()) {
- aspectOrder = new ArrayList<RenderPreview>(mPreviews);
- Collections.sort(aspectOrder, RenderPreview.INCREASING_ASPECT_RATIO);
- } else {
- aspectOrder = mPreviews;
- }
-
- for (RenderPreview preview : aspectOrder) {
- if (x > 0 && x + preview.getWidth() > availableWidth) {
- x = rightHandSide;
- int prevY = y;
- y = nextY;
- if ((prevY <= bottomBorder ||
- y <= bottomBorder)
- && Math.max(nextY, y + preview.getHeight()) > bottomBorder) {
- // If there's really no visible room below, don't bother
- // Similarly, don't wrap individually scaled views
- if (bottomBorder < availableHeight - 40 && preview.getScale() < 1.2) {
- // If it's closer to the top row than the bottom, just
- // mark the next row for left justify instead
- if (bottomBorder - y > y + preview.getHeight() - bottomBorder) {
- rightHandSide = 0;
- wrapped = true;
- } else if (!wrapped) {
- y = nextY = Math.max(nextY, bottomBorder + vgap);
- x = rightHandSide = 0;
- wrapped = true;
- }
- }
- }
- }
- if (x > 0 && y <= bottomBorder
- && Math.max(nextY, y + preview.getHeight()) > bottomBorder) {
- if (clientArea.height - bottomBorder < preview.getHeight()) {
- // No room below the device on the left; just continue on the
- // bottom row
- } else if (preview.getScale() < 1.2) {
- if (bottomBorder - y > y + preview.getHeight() - bottomBorder) {
- rightHandSide = 0;
- wrapped = true;
- } else {
- y = nextY = Math.max(nextY, bottomBorder + vgap);
- x = rightHandSide = 0;
- wrapped = true;
- }
- }
- }
-
- preview.setPosition(x, y);
-
- if (y > maxVisibleY && maxVisibleY > 0) {
- preview.setVisible(false);
- } else if (!preview.isVisible()) {
- preview.setVisible(true);
- }
-
- x += preview.getWidth();
- x += PREVIEW_HGAP;
- nextY = Math.max(nextY, y + preview.getHeight() + vgap);
- }
-
- mLayoutHeight = nextY;
- }
-
- private boolean fixedOrder() {
- return mMode == SCREENS;
- }
-
- /** Returns true if all the previews have the same identical size */
- private boolean previewsHaveIdenticalSize() {
- if (!hasPreviews()) {
- return true;
- }
-
- Iterator<RenderPreview> iterator = mPreviews.iterator();
- RenderPreview first = iterator.next();
- int width = first.getWidth();
- int height = first.getHeight();
-
- while (iterator.hasNext()) {
- RenderPreview preview = iterator.next();
- if (width != preview.getWidth() || height != preview.getHeight()) {
- return false;
- }
- }
-
- return true;
- }
-
- /** Returns true if all the previews can fully fit in the available space */
- private boolean previewsFit() {
- int scaledImageWidth = mHScale.getScaledImgSize();
- int scaledImageHeight = mVScale.getScaledImgSize();
- Rectangle clientArea = mCanvas.getClientArea();
- int availableWidth = clientArea.x + clientArea.width - getX();
- int availableHeight = clientArea.y + clientArea.height - getY();
- int bottomBorder = scaledImageHeight;
- int rightHandSide = scaledImageWidth + PREVIEW_HGAP;
-
- // First see if we can fit everything; if so, we can try to make the layouts
- // larger such that they fill up all the available space
- long availableArea = rightHandSide * bottomBorder +
- availableWidth * (Math.max(0, availableHeight - bottomBorder));
-
- long requiredArea = 0;
- for (RenderPreview preview : mPreviews) {
- // Note: This does not include individual preview scale; the layout
- // algorithm itself may be tweaking the scales to fit elements within
- // the layout
- requiredArea += preview.getArea();
- }
-
- return requiredArea * sScale < availableArea;
- }
-
- private void layoutFullFit() {
- int scaledImageWidth = mHScale.getScaledImgSize();
- int scaledImageHeight = mVScale.getScaledImgSize();
- Rectangle clientArea = mCanvas.getClientArea();
- int availableWidth = clientArea.x + clientArea.width - getX();
- int availableHeight = clientArea.y + clientArea.height - getY();
- int maxVisibleY = clientArea.y + clientArea.height;
- int bottomBorder = scaledImageHeight;
- int rightHandSide = scaledImageWidth + PREVIEW_HGAP;
-
- int minWidth = Integer.MAX_VALUE;
- int minHeight = Integer.MAX_VALUE;
- for (RenderPreview preview : mPreviews) {
- minWidth = Math.min(minWidth, preview.getWidth());
- minHeight = Math.min(minHeight, preview.getHeight());
- }
-
- BinPacker packer = new BinPacker(minWidth, minHeight);
-
- // TODO: Instead of this, just start with client area and occupy scaled image size!
-
- // Add in gap on right and bottom since we'll add that requirement on the width and
- // height rectangles too (for spacing)
- packer.addSpace(new Rect(rightHandSide, 0,
- availableWidth - rightHandSide + PREVIEW_HGAP,
- availableHeight + PREVIEW_VGAP));
- if (maxVisibleY > bottomBorder) {
- packer.addSpace(new Rect(0, bottomBorder + PREVIEW_VGAP,
- availableWidth + PREVIEW_HGAP, maxVisibleY - bottomBorder + PREVIEW_VGAP));
- }
-
- // TODO: Sort previews first before attempting to position them?
-
- ArrayList<RenderPreview> aspectOrder = new ArrayList<RenderPreview>(mPreviews);
- Collections.sort(aspectOrder, RenderPreview.INCREASING_ASPECT_RATIO);
-
- for (RenderPreview preview : aspectOrder) {
- int previewWidth = preview.getWidth();
- int previewHeight = preview.getHeight();
- previewHeight += PREVIEW_VGAP;
- if (preview.isForked()) {
- previewHeight += PREVIEW_VGAP;
- }
- previewWidth += PREVIEW_HGAP;
- // title height? how do I account for that?
- Rect position = packer.occupy(previewWidth, previewHeight);
- if (position != null) {
- preview.setPosition(position.x, position.y);
- preview.setVisible(true);
- } else {
- // Can't fit: give up and do plain row layout
- rowLayout();
- return;
- }
- }
-
- mLayoutHeight = availableHeight;
- }
- /**
- * Paints the configuration previews
- *
- * @param gc the graphics context to paint into
- */
- void paint(GC gc) {
- if (hasPreviews()) {
- // Ensure up to date at all times; consider moving if it's too expensive
- layout(mNeedLayout);
- if (mNeedRender) {
- renderPreviews();
- }
- if (mNeedZoom) {
- boolean allowZoomIn = true /*mMode == NONE*/;
- mCanvas.setFitScale(false /*onlyZoomOut*/, allowZoomIn);
- mNeedZoom = false;
- }
- int rootX = getX();
- int rootY = getY();
-
- for (RenderPreview preview : mPreviews) {
- if (preview.isVisible()) {
- int x = rootX + preview.getX();
- int y = rootY + preview.getY();
- preview.paint(gc, x, y);
- }
- }
-
- RenderPreview preview = mCanvas.getPreview();
- if (preview != null) {
- String displayName = null;
- Configuration configuration = preview.getConfiguration();
- if (configuration instanceof VaryingConfiguration) {
- // Use override flags from stashed preview, but configuration
- // data from live (not varying) configured configuration
- VaryingConfiguration cfg = (VaryingConfiguration) configuration;
- int flags = cfg.getAlternateFlags() | cfg.getOverrideFlags();
- displayName = NestedConfiguration.computeDisplayName(flags,
- getChooser().getConfiguration());
- } else if (configuration instanceof NestedConfiguration) {
- int flags = ((NestedConfiguration) configuration).getOverrideFlags();
- displayName = NestedConfiguration.computeDisplayName(flags,
- getChooser().getConfiguration());
- } else {
- displayName = configuration.getDisplayName();
- }
- if (displayName != null) {
- CanvasTransform hi = mHScale;
- CanvasTransform vi = mVScale;
-
- int destX = hi.translate(0);
- int destY = vi.translate(0);
- int destWidth = hi.getScaledImgSize();
- int destHeight = vi.getScaledImgSize();
-
- int x = destX + destWidth / 2 - preview.getWidth() / 2;
- int y = destY + destHeight;
-
- preview.paintTitle(gc, x, y, false /*showFile*/, displayName);
- }
- }
-
- // Zoom overlay
- int x = getZoomX();
- if (x > 0) {
- int y = getZoomY();
- int oldAlpha = gc.getAlpha();
-
- // Paint background oval rectangle behind the zoom and close icons
- gc.setBackground(gc.getDevice().getSystemColor(SWT.COLOR_GRAY));
- gc.setAlpha(128);
- int padding = 3;
- int arc = 5;
- gc.fillRoundRectangle(x - padding, y - padding,
- ZOOM_ICON_WIDTH + 2 * padding,
- 4 * ZOOM_ICON_HEIGHT + 2 * padding, arc, arc);
-
- gc.setAlpha(255);
- IconFactory iconFactory = IconFactory.getInstance();
- Image zoomOut = iconFactory.getIcon("zoomminus"); //$NON-NLS-1$);
- Image zoomIn = iconFactory.getIcon("zoomplus"); //$NON-NLS-1$);
- Image zoom100 = iconFactory.getIcon("zoom100"); //$NON-NLS-1$);
- Image close = iconFactory.getIcon("close"); //$NON-NLS-1$);
-
- gc.drawImage(zoomIn, x, y);
- y += ZOOM_ICON_HEIGHT;
- gc.drawImage(zoomOut, x, y);
- y += ZOOM_ICON_HEIGHT;
- gc.drawImage(zoom100, x, y);
- y += ZOOM_ICON_HEIGHT;
- gc.drawImage(close, x, y);
- y += ZOOM_ICON_HEIGHT;
- gc.setAlpha(oldAlpha);
- }
- } else if (mMode == CUSTOM) {
- int rootX = getX();
- rootX += mHScale.getScaledImgSize();
- rootX += 2 * PREVIEW_HGAP;
- int rootY = getY();
- rootY += 20;
- gc.setFont(mCanvas.getFont());
- gc.setForeground(mCanvas.getDisplay().getSystemColor(SWT.COLOR_BLACK));
- gc.drawText("Add previews with \"Add as Thumbnail\"\nin the configuration menu",
- rootX, rootY, true);
- }
-
- if (mAnimation != null) {
- mAnimation.tick(gc);
- }
- }
-
- private void addPreview(@NonNull RenderPreview preview) {
- if (mPreviews == null) {
- mPreviews = Lists.newArrayList();
- }
- mPreviews.add(preview);
- }
-
- /** Adds the current configuration as a new configuration preview */
- public void addAsThumbnail() {
- ConfigurationChooser chooser = getChooser();
- String name = chooser.getConfiguration().getDisplayName();
- if (name == null || name.isEmpty()) {
- name = getUniqueName();
- }
- InputDialog d = new InputDialog(
- AdtPlugin.getShell(),
- "Add as Thumbnail Preview", // title
- "Name of thumbnail:",
- name,
- null);
- if (d.open() == Window.OK) {
- selectMode(CUSTOM);
-
- String newName = d.getValue();
- // Create a new configuration from the current settings in the composite
- Configuration configuration = Configuration.copy(chooser.getConfiguration());
- configuration.setDisplayName(newName);
-
- RenderPreview preview = RenderPreview.create(this, configuration);
- addPreview(preview);
-
- layout(true);
- beginRenderScheduling();
- scheduleRender(preview);
- mCanvas.setFitScale(true /* onlyZoomOut */, false /*allowZoomIn*/);
-
- if (mManualList == null) {
- loadList();
- }
- if (mManualList != null) {
- mManualList.add(preview);
- saveList();
- }
- }
- }
-
- /**
- * Computes a unique new name for a configuration preview that represents
- * the current, default configuration
- *
- * @return a unique name
- */
- private String getUniqueName() {
- if (mPreviews == null || mPreviews.isEmpty()) {
- // NO, not for the first preview!
- return "Config1";
- }
-
- Set<String> names = new HashSet<String>(mPreviews.size());
- for (RenderPreview preview : mPreviews) {
- names.add(preview.getDisplayName());
- }
-
- int index = 2;
- while (true) {
- String name = String.format("Config%1$d", index);
- if (!names.contains(name)) {
- return name;
- }
- index++;
- }
- }
-
- /** Generates a bunch of default configuration preview thumbnails */
- public void addDefaultPreviews() {
- ConfigurationChooser chooser = getChooser();
- Configuration parent = chooser.getConfiguration();
- if (parent instanceof NestedConfiguration) {
- parent = ((NestedConfiguration) parent).getParent();
- }
- if (mCanvas.getImageOverlay().getImage() != null) {
- // Create Language variation
- createLocaleVariation(chooser, parent);
-
- // Vary screen size
- // TODO: Be smarter here: Pick a screen that is both as differently as possible
- // from the current screen as well as also supported. So consider
- // things like supported screens, targetSdk etc.
- createScreenVariations(parent);
-
- // Vary orientation
- createStateVariation(chooser, parent);
-
- // Vary render target
- createRenderTargetVariation(chooser, parent);
- }
-
- // Also add in include-context previews, if any
- addIncludedInPreviews();
-
- // Make a placeholder preview for the current screen, in case we switch from it
- RenderPreview preview = RenderPreview.create(this, parent);
- mCanvas.setPreview(preview);
-
- sortPreviewsByOrientation();
- }
-
- private void createRenderTargetVariation(ConfigurationChooser chooser, Configuration parent) {
- /* This is disabled for now: need to load multiple versions of layoutlib.
- When I did this, there seemed to be some drug interactions between
- them, and I would end up with NPEs in layoutlib code which normally works.
- VaryingConfiguration configuration =
- VaryingConfiguration.create(chooser, parent);
- configuration.setAlternatingTarget(true);
- configuration.syncFolderConfig();
- addPreview(RenderPreview.create(this, configuration));
- */
- }
-
- private void createStateVariation(ConfigurationChooser chooser, Configuration parent) {
- State currentState = parent.getDeviceState();
- State nextState = parent.getNextDeviceState(currentState);
- if (nextState != currentState) {
- VaryingConfiguration configuration =
- VaryingConfiguration.create(chooser, parent);
- configuration.setAlternateDeviceState(true);
- configuration.syncFolderConfig();
- addPreview(RenderPreview.create(this, configuration));
- }
- }
-
- private void createLocaleVariation(ConfigurationChooser chooser, Configuration parent) {
- LocaleQualifier currentLanguage = parent.getLocale().qualifier;
- for (Locale locale : chooser.getLocaleList()) {
- LocaleQualifier qualifier = locale.qualifier;
- if (!qualifier.getLanguage().equals(currentLanguage.getLanguage())) {
- VaryingConfiguration configuration =
- VaryingConfiguration.create(chooser, parent);
- configuration.setAlternateLocale(true);
- configuration.syncFolderConfig();
- addPreview(RenderPreview.create(this, configuration));
- break;
- }
- }
- }
-
- private void createScreenVariations(Configuration parent) {
- ConfigurationChooser chooser = getChooser();
- VaryingConfiguration configuration;
-
- configuration = VaryingConfiguration.create(chooser, parent);
- configuration.setVariation(0);
- configuration.setAlternateDevice(true);
- configuration.syncFolderConfig();
- addPreview(RenderPreview.create(this, configuration));
-
- configuration = VaryingConfiguration.create(chooser, parent);
- configuration.setVariation(1);
- configuration.setAlternateDevice(true);
- configuration.syncFolderConfig();
- addPreview(RenderPreview.create(this, configuration));
- }
-
- /**
- * Returns the current mode as seen by this {@link RenderPreviewManager}.
- * Note that it may not yet have been synced with the global mode kept in
- * {@link AdtPrefs#getRenderPreviewMode()}.
- *
- * @return the current preview mode
- */
- @NonNull
- public RenderPreviewMode getMode() {
- return mMode;
- }
-
- /**
- * Update the set of previews for the current mode
- *
- * @param force force a refresh even if the preview type has not changed
- * @return true if the views were recomputed, false if the previews were
- * already showing and the mode not changed
- */
- public boolean recomputePreviews(boolean force) {
- RenderPreviewMode newMode = AdtPrefs.getPrefs().getRenderPreviewMode();
- if (newMode == mMode && !force
- && (mRevision == sRevision
- || mMode == NONE
- || mMode == CUSTOM)) {
- return false;
- }
-
- RenderPreviewMode oldMode = mMode;
- mMode = newMode;
- mRevision = sRevision;
-
- sScale = 1.0;
- disposePreviews();
-
- switch (mMode) {
- case DEFAULT:
- addDefaultPreviews();
- break;
- case INCLUDES:
- addIncludedInPreviews();
- break;
- case LOCALES:
- addLocalePreviews();
- break;
- case SCREENS:
- addScreenSizePreviews();
- break;
- case VARIATIONS:
- addVariationPreviews();
- break;
- case CUSTOM:
- addManualPreviews();
- break;
- case NONE:
- // Can't just set mNeedZoom because with no previews, the paint
- // method does nothing
- mCanvas.setFitScale(false /*onlyZoomOut*/, true /*allowZoomIn*/);
- break;
- default:
- assert false : mMode;
- }
-
- // We schedule layout for the next redraw rather than process it here immediately;
- // not only does this let us avoid doing work for windows where the tab is in the
- // background, but when a file is opened we may not know the size of the canvas
- // yet, and the layout methods need it in order to do a good job. By the time
- // the canvas is painted, we have accurate bounds.
- mNeedLayout = mNeedRender = true;
- mCanvas.redraw();
-
- if (oldMode != mMode && (oldMode == NONE || mMode == NONE)) {
- // If entering or exiting preview mode: updating padding which is compressed
- // only in preview mode.
- mCanvas.getHorizontalTransform().refresh();
- mCanvas.getVerticalTransform().refresh();
- }
-
- return true;
- }
-
- /**
- * Sets the new render preview mode to use
- *
- * @param mode the new mode
- */
- public void selectMode(@NonNull RenderPreviewMode mode) {
- if (mode != mMode) {
- AdtPrefs.getPrefs().setPreviewMode(mode);
- recomputePreviews(false);
- }
- }
-
- /** Similar to {@link #addDefaultPreviews()} but for locales */
- public void addLocalePreviews() {
-
- ConfigurationChooser chooser = getChooser();
- List<Locale> locales = chooser.getLocaleList();
- Configuration parent = chooser.getConfiguration();
-
- for (Locale locale : locales) {
- if (!locale.hasLanguage() && !locale.hasRegion()) {
- continue;
- }
- NestedConfiguration configuration = NestedConfiguration.create(chooser, parent);
- configuration.setOverrideLocale(true);
- configuration.setLocale(locale, false);
-
- String displayName = ConfigurationChooser.getLocaleLabel(chooser, locale, false);
- assert displayName != null; // it's never non null when locale is non null
- configuration.setDisplayName(displayName);
-
- addPreview(RenderPreview.create(this, configuration));
- }
-
- // Make a placeholder preview for the current screen, in case we switch from it
- Configuration configuration = parent;
- Locale locale = configuration.getLocale();
- String label = ConfigurationChooser.getLocaleLabel(chooser, locale, false);
- if (label == null) {
- label = "default";
- }
- configuration.setDisplayName(label);
- RenderPreview preview = RenderPreview.create(this, parent);
- if (preview != null) {
- mCanvas.setPreview(preview);
- }
-
- // No need to sort: they should all be identical
- }
-
- /** Similar to {@link #addDefaultPreviews()} but for screen sizes */
- public void addScreenSizePreviews() {
- ConfigurationChooser chooser = getChooser();
- Collection<Device> devices = chooser.getDevices();
- Configuration configuration = chooser.getConfiguration();
- boolean canScaleNinePatch = configuration.supports(Capability.FIXED_SCALABLE_NINE_PATCH);
-
- // Rearrange the devices a bit such that the most interesting devices bubble
- // to the front
- // 10" tablet, 7" tablet, reference phones, tiny phone, and in general the first
- // version of each seen screen size
- List<Device> sorted = new ArrayList<Device>(devices);
- Set<ScreenSize> seenSizes = new HashSet<ScreenSize>();
- State currentState = configuration.getDeviceState();
- String currentStateName = currentState != null ? currentState.getName() : "";
-
- for (int i = 0, n = sorted.size(); i < n; i++) {
- Device device = sorted.get(i);
- boolean interesting = false;
-
- State state = device.getState(currentStateName);
- if (state == null) {
- state = device.getAllStates().get(0);
- }
-
- if (device.getName().startsWith("Nexus ") //$NON-NLS-1$
- || device.getName().endsWith(" Nexus")) { //$NON-NLS-1$
- // Not String#contains("Nexus") because that would also pick up all the generic
- // entries ("3.7in WVGA (Nexus One)") so we'd have them duplicated
- interesting = true;
- }
-
- FolderConfiguration c = DeviceConfigHelper.getFolderConfig(state);
- if (c != null) {
- ScreenSizeQualifier sizeQualifier = c.getScreenSizeQualifier();
- if (sizeQualifier != null) {
- ScreenSize size = sizeQualifier.getValue();
- if (!seenSizes.contains(size)) {
- seenSizes.add(size);
- interesting = true;
- }
- }
-
- // Omit LDPI, not really used anymore
- DensityQualifier density = c.getDensityQualifier();
- if (density != null) {
- Density d = density.getValue();
- if (d == Density.LOW) {
- interesting = false;
- }
-
- if (!canScaleNinePatch && d == Density.TV) {
- interesting = false;
- }
- }
- }
-
- if (interesting) {
- NestedConfiguration screenConfig = NestedConfiguration.create(chooser,
- configuration);
- screenConfig.setOverrideDevice(true);
- screenConfig.setDevice(device, true);
- screenConfig.syncFolderConfig();
- screenConfig.setDisplayName(ConfigurationChooser.getDeviceLabel(device, true));
- addPreview(RenderPreview.create(this, screenConfig));
- }
- }
-
- // Sorted by screen size, in decreasing order
- sortPreviewsByScreenSize();
- }
-
- /**
- * Previews this layout as included in other layouts
- */
- public void addIncludedInPreviews() {
- ConfigurationChooser chooser = getChooser();
- IProject project = chooser.getProject();
- if (project == null) {
- return;
- }
- IncludeFinder finder = IncludeFinder.get(project);
-
- final List<Reference> includedBy = finder.getIncludedBy(chooser.getEditedFile());
-
- if (includedBy == null || includedBy.isEmpty()) {
- // TODO: Generate some useful defaults, such as including it in a ListView
- // as the list item layout?
- return;
- }
-
- for (final Reference reference : includedBy) {
- String title = reference.getDisplayName();
- Configuration config = Configuration.create(chooser.getConfiguration(),
- reference.getFile());
- RenderPreview preview = RenderPreview.create(this, config);
- preview.setDisplayName(title);
- preview.setIncludedWithin(reference);
-
- addPreview(preview);
- }
-
- sortPreviewsByOrientation();
- }
-
- /**
- * Previews this layout as included in other layouts
- */
- public void addVariationPreviews() {
- ConfigurationChooser chooser = getChooser();
-
- IFile file = chooser.getEditedFile();
- List<IFile> variations = AdtUtils.getResourceVariations(file, false /*includeSelf*/);
-
- // Sort by parent folder
- Collections.sort(variations, new Comparator<IFile>() {
- @Override
- public int compare(IFile file1, IFile file2) {
- return file1.getParent().getName().compareTo(file2.getParent().getName());
- }
- });
-
- Configuration currentConfig = chooser.getConfiguration();
-
- for (IFile variation : variations) {
- String title = variation.getParent().getName();
- Configuration config = Configuration.create(chooser.getConfiguration(), variation);
- config.setTheme(currentConfig.getTheme());
- config.setActivity(currentConfig.getActivity());
- RenderPreview preview = RenderPreview.create(this, config);
- preview.setDisplayName(title);
- preview.setAlternateInput(variation);
-
- addPreview(preview);
- }
-
- sortPreviewsByOrientation();
- }
-
- /**
- * Previews this layout using a custom configured set of layouts
- */
- public void addManualPreviews() {
- if (mManualList == null) {
- loadList();
- } else {
- mPreviews = mManualList.createPreviews(mCanvas);
- }
- }
-
- private void loadList() {
- IProject project = getChooser().getProject();
- if (project == null) {
- return;
- }
-
- if (mManualList == null) {
- mManualList = RenderPreviewList.get(project);
- }
-
- try {
- mManualList.load(getChooser().getDevices());
- mPreviews = mManualList.createPreviews(mCanvas);
- } catch (IOException e) {
- AdtPlugin.log(e, null);
- }
- }
-
- private void saveList() {
- if (mManualList != null) {
- try {
- mManualList.save();
- } catch (IOException e) {
- AdtPlugin.log(e, null);
- }
- }
- }
-
- void rename(ConfigurationDescription description, String newName) {
- IProject project = getChooser().getProject();
- if (project == null) {
- return;
- }
-
- if (mManualList == null) {
- mManualList = RenderPreviewList.get(project);
- }
- description.displayName = newName;
- saveList();
- }
-
-
- /**
- * Notifies that the main configuration has changed.
- *
- * @param flags the change flags, a bitmask corresponding to the
- * {@code CHANGE_} constants in {@link ConfigurationClient}
- */
- public void configurationChanged(int flags) {
- // Similar to renderPreviews, but only acts on incomplete previews
- if (hasPreviews()) {
- // Do zoomed images first
- beginRenderScheduling();
- for (RenderPreview preview : mPreviews) {
- if (preview.getScale() > 1.2) {
- preview.configurationChanged(flags);
- }
- }
- for (RenderPreview preview : mPreviews) {
- if (preview.getScale() <= 1.2) {
- preview.configurationChanged(flags);
- }
- }
- RenderPreview preview = mCanvas.getPreview();
- if (preview != null) {
- preview.configurationChanged(flags);
- preview.dispose();
- }
- mNeedLayout = true;
- mCanvas.redraw();
- }
- }
-
- /** Updates the configuration preview thumbnails */
- public void renderPreviews() {
- if (hasPreviews()) {
- beginRenderScheduling();
-
- // Process in visual order
- ArrayList<RenderPreview> visualOrder = new ArrayList<RenderPreview>(mPreviews);
- Collections.sort(visualOrder, RenderPreview.VISUAL_ORDER);
-
- // Do zoomed images first
- for (RenderPreview preview : visualOrder) {
- if (preview.getScale() > 1.2 && preview.isVisible()) {
- scheduleRender(preview);
- }
- }
- // Non-zoomed images
- for (RenderPreview preview : visualOrder) {
- if (preview.getScale() <= 1.2 && preview.isVisible()) {
- scheduleRender(preview);
- }
- }
- }
-
- mNeedRender = false;
- }
-
- private int mPendingRenderCount;
-
- /**
- * Reset rendering scheduling. The next render request will be scheduled
- * after a single delay unit.
- */
- public void beginRenderScheduling() {
- mPendingRenderCount = 0;
- }
-
- /**
- * Schedule rendering the given preview. Each successive call will add an additional
- * delay unit to the schedule from the previous {@link #scheduleRender(RenderPreview)}
- * call, until {@link #beginRenderScheduling()} is called again.
- *
- * @param preview the preview to render
- */
- public void scheduleRender(@NonNull RenderPreview preview) {
- mPendingRenderCount++;
- preview.render(mPendingRenderCount * RENDER_DELAY);
- }
-
- /**
- * Switch to the given configuration preview
- *
- * @param preview the preview to switch to
- */
- public void switchTo(@NonNull RenderPreview preview) {
- IFile input = preview.getAlternateInput();
- if (input != null) {
- IWorkbenchPartSite site = mCanvas.getEditorDelegate().getEditor().getSite();
- try {
- // This switches to the given file, but the file might not have
- // an identical configuration to what was shown in the preview.
- // For example, while viewing a 10" layout-xlarge file, it might
- // show a preview for a 5" version tied to the default layout. If
- // you click on it, it will open the default layout file, but it might
- // be using a different screen size; any of those that match the
- // default layout, say a 3.8".
- //
- // Thus, we need to also perform a screen size sync first
- Configuration configuration = preview.getConfiguration();
- boolean setSize = false;
- if (configuration instanceof NestedConfiguration) {
- NestedConfiguration nestedConfig = (NestedConfiguration) configuration;
- setSize = nestedConfig.isOverridingDevice();
- if (configuration instanceof VaryingConfiguration) {
- VaryingConfiguration c = (VaryingConfiguration) configuration;
- setSize |= c.isAlternatingDevice();
- }
-
- if (setSize) {
- ConfigurationChooser chooser = getChooser();
- IFile editedFile = chooser.getEditedFile();
- if (editedFile != null) {
- chooser.syncToVariations(CFG_DEVICE|CFG_DEVICE_STATE,
- editedFile, configuration, false, false);
- }
- }
- }
-
- IDE.openEditor(site.getWorkbenchWindow().getActivePage(), input,
- CommonXmlEditor.ID);
- } catch (PartInitException e) {
- AdtPlugin.log(e, null);
- }
- return;
- }
-
- GraphicalEditorPart editor = mCanvas.getEditorDelegate().getGraphicalEditor();
- ConfigurationChooser chooser = editor.getConfigurationChooser();
-
- Configuration originalConfiguration = chooser.getConfiguration();
-
- // The new configuration is the configuration which will become the configuration
- // in the layout editor's chooser
- Configuration previewConfiguration = preview.getConfiguration();
- Configuration newConfiguration = previewConfiguration;
- if (newConfiguration instanceof NestedConfiguration) {
- // Should never use a complementing configuration for the main
- // rendering's configuration; instead, create a new configuration
- // with a snapshot of the configuration's current values
- newConfiguration = Configuration.copy(previewConfiguration);
-
- // Remap all the previews to be parented to this new copy instead
- // of the old one (which is no longer controlled by the chooser)
- for (RenderPreview p : mPreviews) {
- Configuration configuration = p.getConfiguration();
- if (configuration instanceof NestedConfiguration) {
- NestedConfiguration nested = (NestedConfiguration) configuration;
- nested.setParent(newConfiguration);
- }
- }
- }
-
- // Make a preview for the configuration which *was* showing in the
- // chooser up until this point:
- RenderPreview newPreview = mCanvas.getPreview();
- if (newPreview == null) {
- newPreview = RenderPreview.create(this, originalConfiguration);
- }
-
- // Update its configuration such that it is complementing or inheriting
- // from the new chosen configuration
- if (previewConfiguration instanceof VaryingConfiguration) {
- VaryingConfiguration varying = VaryingConfiguration.create(
- (VaryingConfiguration) previewConfiguration,
- newConfiguration);
- varying.updateDisplayName();
- originalConfiguration = varying;
- newPreview.setConfiguration(originalConfiguration);
- } else if (previewConfiguration instanceof NestedConfiguration) {
- NestedConfiguration nested = NestedConfiguration.create(
- (NestedConfiguration) previewConfiguration,
- originalConfiguration,
- newConfiguration);
- nested.setDisplayName(nested.computeDisplayName());
- originalConfiguration = nested;
- newPreview.setConfiguration(originalConfiguration);
- }
-
- // Replace clicked preview with preview of the formerly edited main configuration
- // This doesn't work yet because the image overlay has had its image
- // replaced by the configuration previews! I should make a list of them
- //newPreview.setFullImage(mImageOverlay.getAwtImage());
- for (int i = 0, n = mPreviews.size(); i < n; i++) {
- if (preview == mPreviews.get(i)) {
- mPreviews.set(i, newPreview);
- break;
- }
- }
-
- // Stash the corresponding preview (not active) on the canvas so we can
- // retrieve it if clicking to some other preview later
- mCanvas.setPreview(preview);
- preview.setVisible(false);
-
- // Switch to the configuration from the clicked preview (though it's
- // most likely a copy, see above)
- chooser.setConfiguration(newConfiguration);
- editor.changed(MASK_ALL);
-
- // Scroll to the top again, if necessary
- mCanvas.getVerticalBar().setSelection(mCanvas.getVerticalBar().getMinimum());
-
- mNeedLayout = mNeedZoom = true;
- mCanvas.redraw();
- mAnimation = new SwapAnimation(preview, newPreview);
- }
-
- /**
- * Gets the preview at the given location, or null if none. This is
- * currently deeply tied to where things are painted in onPaint().
- */
- RenderPreview getPreview(ControlPoint mousePos) {
- if (hasPreviews()) {
- int rootX = getX();
- if (mousePos.x < rootX) {
- return null;
- }
- int rootY = getY();
-
- for (RenderPreview preview : mPreviews) {
- int x = rootX + preview.getX();
- int y = rootY + preview.getY();
- if (mousePos.x >= x && mousePos.x <= x + preview.getWidth()) {
- if (mousePos.y >= y && mousePos.y <= y + preview.getHeight()) {
- return preview;
- }
- }
- }
- }
-
- return null;
- }
-
- private int getX() {
- return mHScale.translate(0);
- }
-
- private int getY() {
- return mVScale.translate(0);
- }
-
- private int getZoomX() {
- Rectangle clientArea = mCanvas.getClientArea();
- int x = clientArea.x + clientArea.width - ZOOM_ICON_WIDTH;
- if (x < mHScale.getScaledImgSize() + PREVIEW_HGAP) {
- // No visible previews because the main image is zoomed too far
- return -1;
- }
-
- return x - 6;
- }
-
- private int getZoomY() {
- Rectangle clientArea = mCanvas.getClientArea();
- return clientArea.y + 5;
- }
-
- /**
- * Returns the height of the layout
- *
- * @return the height
- */
- public int getHeight() {
- return mLayoutHeight;
- }
-
- /**
- * Notifies that preview manager that the mouse cursor has moved to the
- * given control position within the layout canvas
- *
- * @param mousePos the mouse position, relative to the layout canvas
- */
- public void moved(ControlPoint mousePos) {
- RenderPreview hovered = getPreview(mousePos);
- if (hovered != mActivePreview) {
- if (mActivePreview != null) {
- mActivePreview.setActive(false);
- }
- mActivePreview = hovered;
- if (mActivePreview != null) {
- mActivePreview.setActive(true);
- }
- mCanvas.redraw();
- }
- }
-
- /**
- * Notifies that preview manager that the mouse cursor has entered the layout canvas
- *
- * @param mousePos the mouse position, relative to the layout canvas
- */
- public void enter(ControlPoint mousePos) {
- moved(mousePos);
- }
-
- /**
- * Notifies that preview manager that the mouse cursor has exited the layout canvas
- *
- * @param mousePos the mouse position, relative to the layout canvas
- */
- public void exit(ControlPoint mousePos) {
- if (mActivePreview != null) {
- mActivePreview.setActive(false);
- }
- mActivePreview = null;
- mCanvas.redraw();
- }
-
- /**
- * Process a mouse click, and return true if it was handled by this manager
- * (e.g. the click was on a preview)
- *
- * @param mousePos the mouse position where the click occurred
- * @return true if the click occurred over a preview and was handled, false otherwise
- */
- public boolean click(ControlPoint mousePos) {
- // Clicked zoom?
- int x = getZoomX();
- if (x > 0) {
- if (mousePos.x >= x && mousePos.x <= x + ZOOM_ICON_WIDTH) {
- int y = getZoomY();
- if (mousePos.y >= y && mousePos.y <= y + 4 * ZOOM_ICON_HEIGHT) {
- if (mousePos.y < y + ZOOM_ICON_HEIGHT) {
- zoomIn();
- } else if (mousePos.y < y + 2 * ZOOM_ICON_HEIGHT) {
- zoomOut();
- } else if (mousePos.y < y + 3 * ZOOM_ICON_HEIGHT) {
- zoomReset();
- } else {
- selectMode(NONE);
- }
- return true;
- }
- }
- }
-
- RenderPreview preview = getPreview(mousePos);
- if (preview != null) {
- boolean handled = preview.click(mousePos.x - getX() - preview.getX(),
- mousePos.y - getY() - preview.getY());
- if (handled) {
- // In case layout was performed, there could be a new preview
- // under this coordinate now, so make sure it's hover etc
- // shows up
- moved(mousePos);
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Returns true if there are thumbnail previews
- *
- * @return true if thumbnails are being shown
- */
- public boolean hasPreviews() {
- return mPreviews != null && !mPreviews.isEmpty();
- }
-
-
- private void sortPreviewsByScreenSize() {
- if (mPreviews != null) {
- Collections.sort(mPreviews, new Comparator<RenderPreview>() {
- @Override
- public int compare(RenderPreview preview1, RenderPreview preview2) {
- Configuration config1 = preview1.getConfiguration();
- Configuration config2 = preview2.getConfiguration();
- Device device1 = config1.getDevice();
- Device device2 = config1.getDevice();
- if (device1 != null && device2 != null) {
- Screen screen1 = device1.getDefaultHardware().getScreen();
- Screen screen2 = device2.getDefaultHardware().getScreen();
- if (screen1 != null && screen2 != null) {
- double delta = screen1.getDiagonalLength()
- - screen2.getDiagonalLength();
- if (delta != 0.0) {
- return (int) Math.signum(delta);
- } else {
- if (screen1.getPixelDensity() != screen2.getPixelDensity()) {
- return screen1.getPixelDensity().compareTo(
- screen2.getPixelDensity());
- }
- }
- }
-
- }
- State state1 = config1.getDeviceState();
- State state2 = config2.getDeviceState();
- if (state1 != state2 && state1 != null && state2 != null) {
- return state1.getName().compareTo(state2.getName());
- }
-
- return preview1.getDisplayName().compareTo(preview2.getDisplayName());
- }
- });
- }
- }
-
- private void sortPreviewsByOrientation() {
- if (mPreviews != null) {
- Collections.sort(mPreviews, new Comparator<RenderPreview>() {
- @Override
- public int compare(RenderPreview preview1, RenderPreview preview2) {
- Configuration config1 = preview1.getConfiguration();
- Configuration config2 = preview2.getConfiguration();
- State state1 = config1.getDeviceState();
- State state2 = config2.getDeviceState();
- if (state1 != state2 && state1 != null && state2 != null) {
- return state1.getName().compareTo(state2.getName());
- }
-
- return preview1.getDisplayName().compareTo(preview2.getDisplayName());
- }
- });
- }
- }
-
- /**
- * Vertical scrollbar listener which updates render previews which are not
- * visible and triggers a redraw
- */
- private class ScrollBarListener implements SelectionListener {
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (mPreviews == null) {
- return;
- }
-
- ScrollBar bar = mCanvas.getVerticalBar();
- int selection = bar.getSelection();
- int thumb = bar.getThumb();
- int maxY = selection + thumb;
- beginRenderScheduling();
- for (RenderPreview preview : mPreviews) {
- if (!preview.isVisible() && preview.getY() <= maxY) {
- preview.setVisible(true);
- }
- }
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
- }
-
- /** Animation overlay shown briefly after swapping two previews */
- private class SwapAnimation implements Runnable {
- private long begin;
- private long end;
- private static final long DURATION = 400; // ms
- private Rect initialRect1;
- private Rect targetRect1;
- private Rect initialRect2;
- private Rect targetRect2;
- private RenderPreview preview;
-
- SwapAnimation(RenderPreview preview1, RenderPreview preview2) {
- begin = System.currentTimeMillis();
- end = begin + DURATION;
-
- initialRect1 = new Rect(preview1.getX(), preview1.getY(),
- preview1.getWidth(), preview1.getHeight());
-
- CanvasTransform hi = mCanvas.getHorizontalTransform();
- CanvasTransform vi = mCanvas.getVerticalTransform();
- initialRect2 = new Rect(hi.translate(0), vi.translate(0),
- hi.getScaledImgSize(), vi.getScaledImgSize());
- preview = preview2;
- }
-
- void tick(GC gc) {
- long now = System.currentTimeMillis();
- if (now > end || mCanvas.isDisposed()) {
- mAnimation = null;
- return;
- }
-
- CanvasTransform hi = mCanvas.getHorizontalTransform();
- CanvasTransform vi = mCanvas.getVerticalTransform();
- if (targetRect1 == null) {
- targetRect1 = new Rect(hi.translate(0), vi.translate(0),
- hi.getScaledImgSize(), vi.getScaledImgSize());
- }
- double portion = (now - begin) / (double) DURATION;
- Rect rect1 = new Rect(
- (int) (portion * (targetRect1.x - initialRect1.x) + initialRect1.x),
- (int) (portion * (targetRect1.y - initialRect1.y) + initialRect1.y),
- (int) (portion * (targetRect1.w - initialRect1.w) + initialRect1.w),
- (int) (portion * (targetRect1.h - initialRect1.h) + initialRect1.h));
-
- if (targetRect2 == null) {
- targetRect2 = new Rect(preview.getX(), preview.getY(),
- preview.getWidth(), preview.getHeight());
- }
- portion = (now - begin) / (double) DURATION;
- Rect rect2 = new Rect(
- (int) (portion * (targetRect2.x - initialRect2.x) + initialRect2.x),
- (int) (portion * (targetRect2.y - initialRect2.y) + initialRect2.y),
- (int) (portion * (targetRect2.w - initialRect2.w) + initialRect2.w),
- (int) (portion * (targetRect2.h - initialRect2.h) + initialRect2.h));
-
- gc.setForeground(gc.getDevice().getSystemColor(SWT.COLOR_GRAY));
- gc.drawRectangle(rect1.x, rect1.y, rect1.w, rect1.h);
- gc.drawRectangle(rect2.x, rect2.y, rect2.w, rect2.h);
-
- mCanvas.getDisplay().timerExec(5, this);
- }
-
- @Override
- public void run() {
- mCanvas.redraw();
- }
- }
-
- /**
- * Notifies the {@linkplain RenderPreviewManager} that the configuration used
- * in the main chooser has been changed. This may require updating parent references
- * in the preview configurations inheriting from it.
- *
- * @param oldConfiguration the previous configuration
- * @param newConfiguration the new configuration in the chooser
- */
- public void updateChooserConfig(
- @NonNull Configuration oldConfiguration,
- @NonNull Configuration newConfiguration) {
- if (hasPreviews()) {
- for (RenderPreview preview : mPreviews) {
- Configuration configuration = preview.getConfiguration();
- if (configuration instanceof NestedConfiguration) {
- NestedConfiguration nestedConfig = (NestedConfiguration) configuration;
- if (nestedConfig.getParent() == oldConfiguration) {
- nestedConfig.setParent(newConfiguration);
- }
- }
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderPreviewMode.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderPreviewMode.java
deleted file mode 100644
index 0f06d7f8a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderPreviewMode.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-/**
- * The {@linkplain RenderPreviewMode} records what type of configurations to
- * render in the layout editor
- */
-public enum RenderPreviewMode {
- /** Generate a set of default previews with maximum variation */
- DEFAULT,
-
- /** Preview all the locales */
- LOCALES,
-
- /** Preview all the screen sizes */
- SCREENS,
-
- /** Preview layout as included in other layouts */
- INCLUDES,
-
- /** Preview all the variations of this layout */
- VARIATIONS,
-
- /** Show a manually configured set of previews */
- CUSTOM,
-
- /** No previews */
- NONE;
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderService.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderService.java
deleted file mode 100644
index 3b9e2fc0f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderService.java
+++ /dev/null
@@ -1,668 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.SdkConstants.LAYOUT_RESOURCE_PREFIX;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.IClientRulesEngine;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.rendering.HardwareConfigHelper;
-import com.android.ide.common.rendering.LayoutLibrary;
-import com.android.ide.common.rendering.RenderSecurityManager;
-import com.android.ide.common.rendering.api.AssetRepository;
-import com.android.ide.common.rendering.api.Capability;
-import com.android.ide.common.rendering.api.DrawableParams;
-import com.android.ide.common.rendering.api.HardwareConfig;
-import com.android.ide.common.rendering.api.IImageFactory;
-import com.android.ide.common.rendering.api.ILayoutPullParser;
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.ide.common.rendering.api.RenderSession;
-import com.android.ide.common.rendering.api.ResourceValue;
-import com.android.ide.common.rendering.api.Result;
-import com.android.ide.common.rendering.api.SessionParams;
-import com.android.ide.common.rendering.api.SessionParams.RenderingMode;
-import com.android.ide.common.rendering.api.ViewInfo;
-import com.android.ide.common.resources.ResourceResolver;
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.ContextPullParser;
-import com.android.ide.eclipse.adt.internal.editors.layout.ProjectCallback;
-import com.android.ide.eclipse.adt.internal.editors.layout.UiElementPullParser;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.Configuration;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigurationChooser;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.Locale;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.IncludeFinder.Reference;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.NodeFactory;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.NodeProxy;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo.ActivityAttributes;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiDocumentNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.devices.Device;
-import com.google.common.base.Charsets;
-import com.google.common.io.Files;
-
-import org.eclipse.core.resources.IProject;
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-
-import java.awt.Toolkit;
-import java.awt.image.BufferedImage;
-import java.io.File;
-import java.io.IOException;
-import java.io.StringReader;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * The {@link RenderService} provides rendering and layout information for
- * Android layouts. This is a wrapper around the layout library.
- */
-public class RenderService {
- private static final Object RENDERING_LOCK = new Object();
-
- /** Reference to the file being edited. Can also be used to access the {@link IProject}. */
- private final GraphicalEditorPart mEditor;
-
- // The following fields are inferred from the editor and not customizable by the
- // client of the render service:
-
- private final IProject mProject;
- private final ProjectCallback mProjectCallback;
- private final ResourceResolver mResourceResolver;
- private final int mMinSdkVersion;
- private final int mTargetSdkVersion;
- private final LayoutLibrary mLayoutLib;
- private final IImageFactory mImageFactory;
- private final HardwareConfigHelper mHardwareConfigHelper;
- private final Locale mLocale;
-
- // The following fields are optional or configurable using the various chained
- // setters:
-
- private UiDocumentNode mModel;
- private Reference mIncludedWithin;
- private RenderingMode mRenderingMode = RenderingMode.NORMAL;
- private LayoutLog mLogger;
- private Integer mOverrideBgColor;
- private boolean mShowDecorations = true;
- private Set<UiElementNode> mExpandNodes = Collections.<UiElementNode>emptySet();
- private final Object mCredential;
-
- /** Use the {@link #create} factory instead */
- private RenderService(GraphicalEditorPart editor, Object credential) {
- mEditor = editor;
- mCredential = credential;
-
- mProject = editor.getProject();
- LayoutCanvas canvas = editor.getCanvasControl();
- mImageFactory = canvas.getImageOverlay();
- ConfigurationChooser chooser = editor.getConfigurationChooser();
- Configuration config = chooser.getConfiguration();
- FolderConfiguration folderConfig = config.getFullConfig();
-
- Device device = config.getDevice();
- assert device != null; // Should only attempt render with configuration that has device
- mHardwareConfigHelper = new HardwareConfigHelper(device);
- mHardwareConfigHelper.setOrientation(
- folderConfig.getScreenOrientationQualifier().getValue());
-
- mLayoutLib = editor.getReadyLayoutLib(true /*displayError*/);
- mResourceResolver = editor.getResourceResolver();
- mProjectCallback = editor.getProjectCallback(true /*reset*/, mLayoutLib);
- mMinSdkVersion = editor.getMinSdkVersion();
- mTargetSdkVersion = editor.getTargetSdkVersion();
- mLocale = config.getLocale();
- }
-
- private RenderService(GraphicalEditorPart editor,
- Configuration configuration, ResourceResolver resourceResolver,
- Object credential) {
- mEditor = editor;
- mCredential = credential;
-
- mProject = editor.getProject();
- LayoutCanvas canvas = editor.getCanvasControl();
- mImageFactory = canvas.getImageOverlay();
- FolderConfiguration folderConfig = configuration.getFullConfig();
-
- Device device = configuration.getDevice();
- assert device != null;
- mHardwareConfigHelper = new HardwareConfigHelper(device);
- mHardwareConfigHelper.setOrientation(
- folderConfig.getScreenOrientationQualifier().getValue());
-
- mLayoutLib = editor.getReadyLayoutLib(true /*displayError*/);
- mResourceResolver = resourceResolver != null ? resourceResolver : editor.getResourceResolver();
- mProjectCallback = editor.getProjectCallback(true /*reset*/, mLayoutLib);
- mMinSdkVersion = editor.getMinSdkVersion();
- mTargetSdkVersion = editor.getTargetSdkVersion();
- mLocale = configuration.getLocale();
- }
-
- private RenderSecurityManager createSecurityManager() {
- String projectPath = null;
- String sdkPath = null;
- if (RenderSecurityManager.RESTRICT_READS) {
- projectPath = AdtUtils.getAbsolutePath(mProject).toFile().getPath();
- Sdk sdk = Sdk.getCurrent();
- sdkPath = sdk != null ? sdk.getSdkOsLocation() : null;
- }
- RenderSecurityManager securityManager = new RenderSecurityManager(sdkPath, projectPath);
- securityManager.setLogger(AdtPlugin.getDefault());
-
- // Make sure this is initialized before we attempt to use it from layoutlib
- Toolkit.getDefaultToolkit();
-
- return securityManager;
- }
-
- /**
- * Returns true if this configuration supports the given rendering
- * capability
- *
- * @param target the target to look up the layout library for
- * @param capability the capability to check
- * @return true if the capability is supported
- */
- public static boolean supports(
- @NonNull IAndroidTarget target,
- @NonNull Capability capability) {
- Sdk sdk = Sdk.getCurrent();
- if (sdk != null) {
- AndroidTargetData targetData = sdk.getTargetData(target);
- if (targetData != null) {
- LayoutLibrary layoutLib = targetData.getLayoutLibrary();
- if (layoutLib != null) {
- return layoutLib.supports(capability);
- }
- }
- }
-
- return false;
- }
-
- /**
- * Creates a new {@link RenderService} associated with the given editor.
- *
- * @param editor the editor to provide configuration data such as the render target
- * @return a {@link RenderService} which can perform rendering services
- */
- public static RenderService create(GraphicalEditorPart editor) {
- // Delegate to editor such that it can pass its credential to the service
- return editor.createRenderService();
- }
-
- /**
- * Creates a new {@link RenderService} associated with the given editor.
- *
- * @param editor the editor to provide configuration data such as the render target
- * @param credential the sandbox credential
- * @return a {@link RenderService} which can perform rendering services
- */
- @NonNull
- public static RenderService create(GraphicalEditorPart editor, Object credential) {
- return new RenderService(editor, credential);
- }
-
- /**
- * Creates a new {@link RenderService} associated with the given editor.
- *
- * @param editor the editor to provide configuration data such as the render target
- * @param configuration the configuration to use (and fallback to editor for the rest)
- * @param resolver a resource resolver to use to look up resources
- * @return a {@link RenderService} which can perform rendering services
- */
- public static RenderService create(GraphicalEditorPart editor,
- Configuration configuration, ResourceResolver resolver) {
- // Delegate to editor such that it can pass its credential to the service
- return editor.createRenderService(configuration, resolver);
- }
-
- /**
- * Creates a new {@link RenderService} associated with the given editor.
- *
- * @param editor the editor to provide configuration data such as the render target
- * @param configuration the configuration to use (and fallback to editor for the rest)
- * @param resolver a resource resolver to use to look up resources
- * @param credential the sandbox credential
- * @return a {@link RenderService} which can perform rendering services
- */
- public static RenderService create(GraphicalEditorPart editor,
- Configuration configuration, ResourceResolver resolver, Object credential) {
- return new RenderService(editor, configuration, resolver, credential);
- }
-
- /**
- * Renders the given model, using this editor's theme and screen settings, and returns
- * the result as a {@link RenderSession}.
- *
- * @param model the model to be rendered, which can be different than the editor's own
- * {@link #getModel()}.
- * @param width the width to use for the layout, or -1 to use the width of the screen
- * associated with this editor
- * @param height the height to use for the layout, or -1 to use the height of the screen
- * associated with this editor
- * @param explodeNodes a set of nodes to explode, or null for none
- * @param overrideBgColor If non-null, use the given color as a background to render over
- * rather than the normal background requested by the theme
- * @param noDecor If true, don't draw window decorations like the system bar
- * @param logger a logger where rendering errors are reported
- * @param renderingMode the {@link RenderingMode} to use for rendering
- * @return the resulting rendered image wrapped in an {@link RenderSession}
- */
-
- /**
- * Sets the {@link LayoutLog} to be used during rendering. If none is specified, a
- * silent logger will be used.
- *
- * @param logger the log to be used
- * @return this (such that chains of setters can be stringed together)
- */
- public RenderService setLog(LayoutLog logger) {
- mLogger = logger;
- return this;
- }
-
- /**
- * Sets the model to be rendered, which can be different than the editor's own
- * {@link GraphicalEditorPart#getModel()}.
- *
- * @param model the model to be rendered
- * @return this (such that chains of setters can be stringed together)
- */
- public RenderService setModel(UiDocumentNode model) {
- mModel = model;
- return this;
- }
-
- /**
- * Overrides the width and height to be used during rendering (which might be adjusted if
- * the {@link #setRenderingMode(RenderingMode)} is {@link RenderingMode#FULL_EXPAND}.
- *
- * A value of -1 will make the rendering use the normal width and height coming from the
- * {@link Configuration#getDevice()} object.
- *
- * @param overrideRenderWidth the width in pixels of the layout to be rendered
- * @param overrideRenderHeight the height in pixels of the layout to be rendered
- * @return this (such that chains of setters can be stringed together)
- */
- public RenderService setOverrideRenderSize(int overrideRenderWidth, int overrideRenderHeight) {
- mHardwareConfigHelper.setOverrideRenderSize(overrideRenderWidth, overrideRenderHeight);
- return this;
- }
-
- /**
- * Sets the max width and height to be used during rendering (which might be adjusted if
- * the {@link #setRenderingMode(RenderingMode)} is {@link RenderingMode#FULL_EXPAND}.
- *
- * A value of -1 will make the rendering use the normal width and height coming from the
- * {@link Configuration#getDevice()} object.
- *
- * @param maxRenderWidth the max width in pixels of the layout to be rendered
- * @param maxRenderHeight the max height in pixels of the layout to be rendered
- * @return this (such that chains of setters can be stringed together)
- */
- public RenderService setMaxRenderSize(int maxRenderWidth, int maxRenderHeight) {
- mHardwareConfigHelper.setMaxRenderSize(maxRenderWidth, maxRenderHeight);
- return this;
- }
-
- /**
- * Sets the {@link RenderingMode} to be used during rendering. If none is specified,
- * the default is {@link RenderingMode#NORMAL}.
- *
- * @param renderingMode the rendering mode to be used
- * @return this (such that chains of setters can be stringed together)
- */
- public RenderService setRenderingMode(RenderingMode renderingMode) {
- mRenderingMode = renderingMode;
- return this;
- }
-
- /**
- * Sets the overriding background color to be used, if any. The color should be a
- * bitmask of AARRGGBB. The default is null.
- *
- * @param overrideBgColor the overriding background color to be used in the rendering,
- * in the form of a AARRGGBB bitmask, or null to use no custom background.
- * @return this (such that chains of setters can be stringed together)
- */
- public RenderService setOverrideBgColor(Integer overrideBgColor) {
- mOverrideBgColor = overrideBgColor;
- return this;
- }
-
- /**
- * Sets whether the rendering should include decorations such as a system bar, an
- * application bar etc depending on the SDK target and theme. The default is true.
- *
- * @param showDecorations true if the rendering should include system bars etc.
- * @return this (such that chains of setters can be stringed together)
- */
- public RenderService setDecorations(boolean showDecorations) {
- mShowDecorations = showDecorations;
- return this;
- }
-
- /**
- * Sets the nodes to expand during rendering. These will be padded with approximately
- * 20 pixels and also highlighted by the {@link EmptyViewsOverlay}. The default is an
- * empty collection.
- *
- * @param nodesToExpand the nodes to be expanded
- * @return this (such that chains of setters can be stringed together)
- */
- public RenderService setNodesToExpand(Set<UiElementNode> nodesToExpand) {
- mExpandNodes = nodesToExpand;
- return this;
- }
-
- /**
- * Sets the {@link Reference} to an outer layout that this layout should be rendered
- * within. The outer layout <b>must</b> contain an include tag which points to this
- * layout. The default is null.
- *
- * @param includedWithin a reference to an outer layout to render this layout within
- * @return this (such that chains of setters can be stringed together)
- */
- public RenderService setIncludedWithin(Reference includedWithin) {
- mIncludedWithin = includedWithin;
- return this;
- }
-
- /** Initializes any remaining optional fields after all setters have been called */
- private void finishConfiguration() {
- if (mLogger == null) {
- // Silent logging
- mLogger = new LayoutLog();
- }
- }
-
- /**
- * Renders the model and returns the result as a {@link RenderSession}.
- * @return the {@link RenderSession} resulting from rendering the current model
- */
- public RenderSession createRenderSession() {
- assert mModel != null : "Incomplete service config";
- finishConfiguration();
-
- if (mResourceResolver == null) {
- // Abort the rendering if the resources are not found.
- return null;
- }
-
- HardwareConfig hardwareConfig = mHardwareConfigHelper.getConfig();
-
- UiElementPullParser modelParser = new UiElementPullParser(mModel,
- false, mExpandNodes, hardwareConfig.getDensity(), mProject);
- ILayoutPullParser topParser = modelParser;
-
- // Code to support editing included layout
- // first reset the layout parser just in case.
- mProjectCallback.setLayoutParser(null, null);
-
- if (mIncludedWithin != null) {
- // Outer layout name:
- String contextLayoutName = mIncludedWithin.getName();
-
- // Find the layout file.
- ResourceValue contextLayout = mResourceResolver.findResValue(
- LAYOUT_RESOURCE_PREFIX + contextLayoutName, false /* forceFrameworkOnly*/);
- if (contextLayout != null) {
- File layoutFile = new File(contextLayout.getValue());
- if (layoutFile.isFile()) {
- try {
- // Get the name of the layout actually being edited, without the extension
- // as it's what IXmlPullParser.getParser(String) will receive.
- String queryLayoutName = mEditor.getLayoutResourceName();
- mProjectCallback.setLayoutParser(queryLayoutName, modelParser);
- topParser = new ContextPullParser(mProjectCallback, layoutFile);
- topParser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
- String xmlText = Files.toString(layoutFile, Charsets.UTF_8);
- topParser.setInput(new StringReader(xmlText));
- } catch (IOException e) {
- AdtPlugin.log(e, null);
- } catch (XmlPullParserException e) {
- AdtPlugin.log(e, null);
- }
- }
- }
- }
-
- SessionParams params = new SessionParams(
- topParser,
- mRenderingMode,
- mProject /* projectKey */,
- hardwareConfig,
- mResourceResolver,
- mProjectCallback,
- mMinSdkVersion,
- mTargetSdkVersion,
- mLogger);
-
- // Request margin and baseline information.
- // TODO: Be smarter about setting this; start without it, and on the first request
- // for an extended view info, re-render in the same session, and then set a flag
- // which will cause this to create extended view info each time from then on in the
- // same session
- params.setExtendedViewInfoMode(true);
-
- params.setLocale(mLocale.toLocaleId());
- params.setAssetRepository(new AssetRepository());
-
- ManifestInfo manifestInfo = ManifestInfo.get(mProject);
- try {
- params.setRtlSupport(manifestInfo.isRtlSupported());
- } catch (Exception e) {
- // ignore.
- }
- if (!mShowDecorations) {
- params.setForceNoDecor();
- } else {
- try {
- params.setAppLabel(manifestInfo.getApplicationLabel());
- params.setAppIcon(manifestInfo.getApplicationIcon());
- String activity = mEditor.getConfigurationChooser().getConfiguration().getActivity();
- if (activity != null) {
- ActivityAttributes info = manifestInfo.getActivityAttributes(activity);
- if (info != null) {
- if (info.getLabel() != null) {
- params.setAppLabel(info.getLabel());
- }
- if (info.getIcon() != null) {
- params.setAppIcon(info.getIcon());
- }
- }
- }
- } catch (Exception e) {
- // ignore.
- }
- }
-
- if (mOverrideBgColor != null) {
- params.setOverrideBgColor(mOverrideBgColor.intValue());
- }
-
- // set the Image Overlay as the image factory.
- params.setImageFactory(mImageFactory);
-
- mProjectCallback.setLogger(mLogger);
- mProjectCallback.setResourceResolver(mResourceResolver);
- RenderSecurityManager securityManager = createSecurityManager();
- try {
- securityManager.setActive(true, mCredential);
- synchronized (RENDERING_LOCK) {
- return mLayoutLib.createSession(params);
- }
- } catch (RuntimeException t) {
- // Exceptions from the bridge
- mLogger.error(null, t.getLocalizedMessage(), t, null);
- throw t;
- } finally {
- securityManager.dispose(mCredential);
- mProjectCallback.setLogger(null);
- mProjectCallback.setResourceResolver(null);
- }
- }
-
- /**
- * Renders the given resource value (which should refer to a drawable) and returns it
- * as an image
- *
- * @param drawableResourceValue the drawable resource value to be rendered, or null
- * @return the image, or null if something went wrong
- */
- public BufferedImage renderDrawable(ResourceValue drawableResourceValue) {
- if (drawableResourceValue == null) {
- return null;
- }
-
- finishConfiguration();
-
- HardwareConfig hardwareConfig = mHardwareConfigHelper.getConfig();
-
- DrawableParams params = new DrawableParams(drawableResourceValue, mProject, hardwareConfig,
- mResourceResolver, mProjectCallback, mMinSdkVersion,
- mTargetSdkVersion, mLogger);
- params.setAssetRepository(new AssetRepository());
- params.setForceNoDecor();
- Result result = mLayoutLib.renderDrawable(params);
- if (result != null && result.isSuccess()) {
- Object data = result.getData();
- if (data instanceof BufferedImage) {
- return (BufferedImage) data;
- }
- }
-
- return null;
- }
-
- /**
- * Measure the children of the given parent node, applying the given filter to the
- * pull parser's attribute values.
- *
- * @param parent the parent node to measure children for
- * @param filter the filter to apply to the attribute values
- * @return a map from node children of the parent to new bounds of the nodes
- */
- public Map<INode, Rect> measureChildren(INode parent,
- final IClientRulesEngine.AttributeFilter filter) {
- finishConfiguration();
- HardwareConfig hardwareConfig = mHardwareConfigHelper.getConfig();
-
- final NodeFactory mNodeFactory = mEditor.getCanvasControl().getNodeFactory();
- UiElementNode parentNode = ((NodeProxy) parent).getNode();
- UiElementPullParser topParser = new UiElementPullParser(parentNode,
- false, Collections.<UiElementNode>emptySet(), hardwareConfig.getDensity(),
- mProject) {
- @Override
- public String getAttributeValue(String namespace, String localName) {
- if (filter != null) {
- Object cookie = getViewCookie();
- if (cookie instanceof UiViewElementNode) {
- NodeProxy node = mNodeFactory.create((UiViewElementNode) cookie);
- if (node != null) {
- String value = filter.getAttribute(node, namespace, localName);
- if (value != null) {
- return value;
- }
- // null means no preference, not "unset".
- }
- }
- }
-
- return super.getAttributeValue(namespace, localName);
- }
-
- /**
- * The parser usually assumes that the top level node is a document node that
- * should be skipped, and that's not the case when we render in the middle of
- * the tree, so override {@link UiElementPullParser#onNextFromStartDocument}
- * to change this behavior
- */
- @Override
- public void onNextFromStartDocument() {
- mParsingState = START_TAG;
- }
- };
-
- SessionParams params = new SessionParams(
- topParser,
- RenderingMode.FULL_EXPAND,
- mProject /* projectKey */,
- hardwareConfig,
- mResourceResolver,
- mProjectCallback,
- mMinSdkVersion,
- mTargetSdkVersion,
- mLogger);
- params.setLayoutOnly();
- params.setForceNoDecor();
- params.setAssetRepository(new AssetRepository());
-
- RenderSession session = null;
- mProjectCallback.setLogger(mLogger);
- mProjectCallback.setResourceResolver(mResourceResolver);
- RenderSecurityManager securityManager = createSecurityManager();
- try {
- securityManager.setActive(true, mCredential);
- synchronized (RENDERING_LOCK) {
- session = mLayoutLib.createSession(params);
- }
- if (session.getResult().isSuccess()) {
- assert session.getRootViews().size() == 1;
- ViewInfo root = session.getRootViews().get(0);
- List<ViewInfo> children = root.getChildren();
- Map<INode, Rect> map = new HashMap<INode, Rect>(children.size());
- for (ViewInfo info : children) {
- if (info.getCookie() instanceof UiViewElementNode) {
- UiViewElementNode uiNode = (UiViewElementNode) info.getCookie();
- NodeProxy node = mNodeFactory.create(uiNode);
- map.put(node, new Rect(info.getLeft(), info.getTop(),
- info.getRight() - info.getLeft(),
- info.getBottom() - info.getTop()));
- }
- }
-
- return map;
- }
- } catch (RuntimeException t) {
- // Exceptions from the bridge
- mLogger.error(null, t.getLocalizedMessage(), t, null);
- throw t;
- } finally {
- securityManager.dispose(mCredential);
- mProjectCallback.setLogger(null);
- mProjectCallback.setResourceResolver(null);
- if (session != null) {
- session.dispose();
- }
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ResizeGesture.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ResizeGesture.java
deleted file mode 100644
index 4d51c07de..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ResizeGesture.java
+++ /dev/null
@@ -1,279 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.ide.common.api.DropFeedback;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.api.ResizePolicy;
-import com.android.ide.common.api.SegmentType;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.SelectionHandle.Position;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.NodeProxy;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.RulesEngine;
-import com.android.utils.Pair;
-
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.graphics.GC;
-
-import java.util.Collections;
-import java.util.List;
-
-/**
- * A {@link ResizeGesture} is a gesture for resizing a selected widget. It is initiated
- * by a drag of a {@link SelectionHandle}.
- */
-public class ResizeGesture extends Gesture {
- /** The {@link Overlay} drawn for the gesture feedback. */
- private ResizeOverlay mOverlay;
-
- /** The canvas associated with this gesture. */
- private LayoutCanvas mCanvas;
-
- /** The selection handle we're dragging to perform this resize */
- private SelectionHandle mHandle;
-
- private NodeProxy mParentNode;
- private NodeProxy mChildNode;
- private DropFeedback mFeedback;
- private ResizePolicy mResizePolicy;
- private SegmentType mHorizontalEdge;
- private SegmentType mVerticalEdge;
-
- /**
- * Creates a new marquee selection (selection swiping).
- *
- * @param canvas The canvas where selection is performed.
- * @param item The selected item the handle corresponds to
- * @param handle The handle being dragged to perform the resize
- */
- public ResizeGesture(LayoutCanvas canvas, SelectionItem item, SelectionHandle handle) {
- mCanvas = canvas;
- mHandle = handle;
-
- mChildNode = item.getNode();
- mParentNode = (NodeProxy) mChildNode.getParent();
- mResizePolicy = item.getResizePolicy();
- mHorizontalEdge = getHorizontalEdgeType(mHandle);
- mVerticalEdge = getVerticalEdgeType(mHandle);
- }
-
- @Override
- public void begin(ControlPoint pos, int startMask) {
- super.begin(pos, startMask);
-
- mCanvas.getSelectionOverlay().setHidden(true);
-
- RulesEngine rulesEngine = mCanvas.getRulesEngine();
- Rect newBounds = getNewBounds(pos);
- ViewHierarchy viewHierarchy = mCanvas.getViewHierarchy();
- CanvasViewInfo childInfo = viewHierarchy.findViewInfoFor(mChildNode);
- CanvasViewInfo parentInfo = viewHierarchy.findViewInfoFor(mParentNode);
- Object childView = childInfo != null ? childInfo.getViewObject() : null;
- Object parentView = parentInfo != null ? parentInfo.getViewObject() : null;
- mFeedback = rulesEngine.callOnResizeBegin(mChildNode, mParentNode, newBounds,
- mHorizontalEdge, mVerticalEdge, childView, parentView);
- update(pos);
- mCanvas.getGestureManager().updateMessage(mFeedback);
- }
-
- @Override
- public boolean keyPressed(KeyEvent event) {
- update(mCanvas.getGestureManager().getCurrentControlPoint());
- mCanvas.redraw();
- return true;
- }
-
- @Override
- public boolean keyReleased(KeyEvent event) {
- update(mCanvas.getGestureManager().getCurrentControlPoint());
- mCanvas.redraw();
- return true;
- }
-
- @Override
- public void update(ControlPoint pos) {
- super.update(pos);
- RulesEngine rulesEngine = mCanvas.getRulesEngine();
- Rect newBounds = getNewBounds(pos);
- int modifierMask = mCanvas.getGestureManager().getRuleModifierMask();
- rulesEngine.callOnResizeUpdate(mFeedback, mChildNode, mParentNode, newBounds,
- modifierMask);
- mCanvas.getGestureManager().updateMessage(mFeedback);
- }
-
- @Override
- public void end(ControlPoint pos, boolean canceled) {
- super.end(pos, canceled);
-
- if (!canceled) {
- RulesEngine rulesEngine = mCanvas.getRulesEngine();
- Rect newBounds = getNewBounds(pos);
- rulesEngine.callOnResizeEnd(mFeedback, mChildNode, mParentNode, newBounds);
- }
-
- mCanvas.getSelectionOverlay().setHidden(false);
- }
-
- @Override
- public Pair<Boolean, Boolean> getTooltipPosition() {
- return Pair.of(mHorizontalEdge != SegmentType.TOP, mVerticalEdge != SegmentType.LEFT);
- }
-
- /**
- * For the new mouse position, compute the resized bounds (the bounding rectangle that
- * the view should be resized to). This is not just a width or height, since in some
- * cases resizing will change the x/y position of the view as well (for example, in
- * RelativeLayout or in AbsoluteLayout).
- */
- private Rect getNewBounds(ControlPoint pos) {
- LayoutPoint p = pos.toLayout();
- LayoutPoint start = mStart.toLayout();
- Rect b = mChildNode.getBounds();
- Position direction = mHandle.getPosition();
-
- int x = b.x;
- int y = b.y;
- int w = b.w;
- int h = b.h;
- int deltaX = p.x - start.x;
- int deltaY = p.y - start.y;
-
- if (deltaX == 0 && deltaY == 0) {
- // No move - just use the existing bounds
- return b;
- }
-
- if (mResizePolicy.isAspectPreserving() && w != 0 && h != 0) {
- double aspectRatio = w / (double) h;
- int newW = Math.abs(b.w + (direction.isLeft() ? -deltaX : deltaX));
- int newH = Math.abs(b.h + (direction.isTop() ? -deltaY : deltaY));
- double newAspectRatio = newW / (double) newH;
- if (newH == 0 || newAspectRatio > aspectRatio) {
- deltaY = (int) (deltaX / aspectRatio);
- } else {
- deltaX = (int) (deltaY * aspectRatio);
- }
- }
- if (direction.isLeft()) {
- // The user is dragging the left edge, so the position is anchored on the
- // right.
- int x2 = b.x + b.w;
- int nx1 = b.x + deltaX;
- if (nx1 <= x2) {
- x = nx1;
- w = x2 - x;
- } else {
- w = 0;
- x = x2;
- }
- } else if (direction.isRight()) {
- // The user is dragging the right edge, so the position is anchored on the
- // left.
- int nx2 = b.x + b.w + deltaX;
- if (nx2 >= b.x) {
- w = nx2 - b.x;
- } else {
- w = 0;
- }
- } else {
- assert direction == Position.BOTTOM_MIDDLE || direction == Position.TOP_MIDDLE;
- }
-
- if (direction.isTop()) {
- // The user is dragging the top edge, so the position is anchored on the
- // bottom.
- int y2 = b.y + b.h;
- int ny1 = b.y + deltaY;
- if (ny1 < y2) {
- y = ny1;
- h = y2 - y;
- } else {
- h = 0;
- y = y2;
- }
- } else if (direction.isBottom()) {
- // The user is dragging the bottom edge, so the position is anchored on the
- // top.
- int ny2 = b.y + b.h + deltaY;
- if (ny2 >= b.y) {
- h = ny2 - b.y;
- } else {
- h = 0;
- }
- } else {
- assert direction == Position.LEFT_MIDDLE || direction == Position.RIGHT_MIDDLE;
- }
-
- return new Rect(x, y, w, h);
- }
-
- private static SegmentType getHorizontalEdgeType(SelectionHandle handle) {
- switch (handle.getPosition()) {
- case BOTTOM_LEFT:
- case BOTTOM_RIGHT:
- case BOTTOM_MIDDLE:
- return SegmentType.BOTTOM;
- case LEFT_MIDDLE:
- case RIGHT_MIDDLE:
- return null;
- case TOP_LEFT:
- case TOP_MIDDLE:
- case TOP_RIGHT:
- return SegmentType.TOP;
- default: assert false : handle.getPosition();
- }
- return null;
- }
-
- private static SegmentType getVerticalEdgeType(SelectionHandle handle) {
- switch (handle.getPosition()) {
- case TOP_LEFT:
- case LEFT_MIDDLE:
- case BOTTOM_LEFT:
- return SegmentType.LEFT;
- case BOTTOM_MIDDLE:
- case TOP_MIDDLE:
- return null;
- case TOP_RIGHT:
- case RIGHT_MIDDLE:
- case BOTTOM_RIGHT:
- return SegmentType.RIGHT;
- default: assert false : handle.getPosition();
- }
- return null;
- }
-
-
- @Override
- public List<Overlay> createOverlays() {
- mOverlay = new ResizeOverlay();
- return Collections.<Overlay> singletonList(mOverlay);
- }
-
- /**
- * An {@link Overlay} to paint the resize feedback. This just delegates to the
- * layout rule for the parent which is handling the resizing.
- */
- private class ResizeOverlay extends Overlay {
- @Override
- public void paint(GC gc) {
- if (mChildNode != null && mFeedback != null) {
- RulesEngine rulesEngine = mCanvas.getRulesEngine();
- rulesEngine.callDropFeedbackPaint(mCanvas.getGcWrapper(), mChildNode, mFeedback);
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SelectionHandle.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SelectionHandle.java
deleted file mode 100644
index c2db2431c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SelectionHandle.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import org.eclipse.swt.SWT;
-
-/**
- * A selection handle is a small rectangle on the border of a selected view which lets you
- * change the size of the view by dragging it.
- */
-public class SelectionHandle {
- /**
- * Size of the selection handle radius, in control coordinates. Note that this isn't
- * necessarily a <b>circular</b> radius; in the case of a rectangular handle, the
- * width and the height are both equal to this radius.
- * Note also that this radius is in <b>control</b> coordinates, whereas the rest
- * of the class operates in layout coordinates. This is because we do not want the
- * selection handles to grow or shrink along with the screen zoom; they are always
- * at the given pixel size in the control.
- */
- public final static int PIXEL_RADIUS = 3;
-
- /**
- * Extra number of pixels to look beyond the actual radius of the selection handle
- * when matching mouse positions to handles
- */
- public final static int PIXEL_MARGIN = 2;
-
- /** The position of the handle in the selection rectangle */
- enum Position {
- TOP_MIDDLE(SWT.CURSOR_SIZEN),
- TOP_RIGHT(SWT.CURSOR_SIZENE),
- RIGHT_MIDDLE(SWT.CURSOR_SIZEE),
- BOTTOM_RIGHT(SWT.CURSOR_SIZESE),
- BOTTOM_MIDDLE(SWT.CURSOR_SIZES),
- BOTTOM_LEFT(SWT.CURSOR_SIZESW),
- LEFT_MIDDLE(SWT.CURSOR_SIZEW),
- TOP_LEFT(SWT.CURSOR_SIZENW);
-
- /** Corresponding SWT cursor value */
- private int mSwtCursor;
-
- private Position(int swtCursor) {
- mSwtCursor = swtCursor;
- }
-
- private int getCursorType() {
- return mSwtCursor;
- }
-
- /** Is the {@link SelectionHandle} somewhere on the left edge? */
- boolean isLeft() {
- return this == TOP_LEFT || this == LEFT_MIDDLE || this == BOTTOM_LEFT;
- }
-
- /** Is the {@link SelectionHandle} somewhere on the right edge? */
- boolean isRight() {
- return this == TOP_RIGHT || this == RIGHT_MIDDLE || this == BOTTOM_RIGHT;
- }
-
- /** Is the {@link SelectionHandle} somewhere on the top edge? */
- boolean isTop() {
- return this == TOP_LEFT || this == TOP_MIDDLE || this == TOP_RIGHT;
- }
-
- /** Is the {@link SelectionHandle} somewhere on the bottom edge? */
- boolean isBottom() {
- return this == BOTTOM_LEFT || this == BOTTOM_MIDDLE || this == BOTTOM_RIGHT;
- }
- };
-
- /** The x coordinate of the center of the selection handle */
- public final int centerX;
- /** The y coordinate of the center of the selection handle */
- public final int centerY;
- /** The position of the handle in the selection rectangle */
- private final Position mPosition;
-
- /**
- * Constructs a new {@link SelectionHandle} at the given layout coordinate
- * corresponding to a handle at the given {@link Position}.
- *
- * @param centerX the x coordinate of the center of the selection handle
- * @param centerY y coordinate of the center of the selection handle
- * @param position the position of the handle in the selection rectangle
- */
- public SelectionHandle(int centerX, int centerY, Position position) {
- mPosition = position;
- this.centerX = centerX;
- this.centerY = centerY;
- }
-
- /**
- * Determines whether the given {@link LayoutPoint} is within the given distance in
- * layout coordinates. The distance should incorporate at least the equivalent
- * distance to the control coordinate space {@link #PIXEL_RADIUS}, but usually with a
- * few extra pixels added in to make the corners easier to target.
- *
- * @param point the mouse position in layout coordinates
- * @param distance the distance from the center of the handle to check whether the
- * point fits within
- * @return true if the given point is within the given distance of this handle
- */
- public boolean contains(LayoutPoint point, int distance) {
- return (point.x >= centerX - distance
- && point.x <= centerX + distance
- && point.y >= centerY - distance
- && point.y <= centerY + distance);
- }
-
- /**
- * Returns the position of the handle in the selection rectangle
- *
- * @return the position of the handle in the selection rectangle
- */
- public Position getPosition() {
- return mPosition;
- }
-
- /**
- * Returns the SWT cursor type to use for this selection handle
- *
- * @return the position of the handle in the selection rectangle
- */
- public int getSwtCursorType() {
- return mPosition.getCursorType();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SelectionHandles.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SelectionHandles.java
deleted file mode 100644
index 6d7f34a66..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SelectionHandles.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.ide.common.api.Margins;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.api.ResizePolicy;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.SelectionHandle.Position;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.NodeProxy;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-
-/**
- * The {@link SelectionHandles} of a {@link SelectionItem} are the set of
- * {@link SelectionHandle} objects (possibly empty, for non-resizable objects) the user
- * can manipulate to resize a widget.
- */
-public class SelectionHandles implements Iterable<SelectionHandle> {
- private final SelectionItem mItem;
- private List<SelectionHandle> mHandles;
-
- /**
- * Constructs a new {@link SelectionHandles} object for the given {link
- * {@link SelectionItem}
- * @param item the item to create {@link SelectionHandles} for
- */
- public SelectionHandles(SelectionItem item) {
- mItem = item;
-
- createHandles(item.getCanvas());
- }
-
- /**
- * Find a specific {@link SelectionHandle} from this set of {@link SelectionHandles},
- * which is within the given distance (in layout coordinates) from the center of the
- * {@link SelectionHandle}.
- *
- * @param point the mouse position (in layout coordinates) to test
- * @param distance the maximum distance from the handle center to accept
- * @return a {@link SelectionHandle} under the point, or null if not found
- */
- public SelectionHandle findHandle(LayoutPoint point, int distance) {
- for (SelectionHandle handle : mHandles) {
- if (handle.contains(point, distance)) {
- return handle;
- }
- }
-
- return null;
- }
-
- /**
- * Create the {@link SelectionHandle} objects for the selection item, according to its
- * {@link ResizePolicy}.
- */
- private void createHandles(LayoutCanvas canvas) {
- NodeProxy selectedNode = mItem.getNode();
- Rect r = selectedNode.getBounds();
- if (!r.isValid()) {
- mHandles = Collections.emptyList();
- return;
- }
-
- ResizePolicy resizability = mItem.getResizePolicy();
- if (resizability.isResizable()) {
- mHandles = new ArrayList<SelectionHandle>(8);
- boolean left = resizability.leftAllowed();
- boolean right = resizability.rightAllowed();
- boolean top = resizability.topAllowed();
- boolean bottom = resizability.bottomAllowed();
- int x1 = r.x;
- int y1 = r.y;
- int w = r.w;
- int h = r.h;
- int x2 = x1 + w;
- int y2 = y1 + h;
-
- Margins insets = canvas.getInsets(mItem.getNode().getFqcn());
- if (insets != null) {
- x1 += insets.left;
- x2 -= insets.right;
- y1 += insets.top;
- y2 -= insets.bottom;
- }
-
- int mx = (x1 + x2) / 2;
- int my = (y1 + y2) / 2;
-
- if (left) {
- mHandles.add(new SelectionHandle(x1, my, Position.LEFT_MIDDLE));
- if (top) {
- mHandles.add(new SelectionHandle(x1, y1, Position.TOP_LEFT));
- }
- if (bottom) {
- mHandles.add(new SelectionHandle(x1, y2, Position.BOTTOM_LEFT));
- }
- }
- if (right) {
- mHandles.add(new SelectionHandle(x2, my, Position.RIGHT_MIDDLE));
- if (top) {
- mHandles.add(new SelectionHandle(x2, y1, Position.TOP_RIGHT));
- }
- if (bottom) {
- mHandles.add(new SelectionHandle(x2, y2, Position.BOTTOM_RIGHT));
- }
- }
- if (top) {
- mHandles.add(new SelectionHandle(mx, y1, Position.TOP_MIDDLE));
- }
- if (bottom) {
- mHandles.add(new SelectionHandle(mx, y2, Position.BOTTOM_MIDDLE));
- }
- } else {
- mHandles = Collections.emptyList();
- }
- }
-
- // Implements Iterable<SelectionHandle>
- @Override
- public Iterator<SelectionHandle> iterator() {
- return mHandles.iterator();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SelectionItem.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SelectionItem.java
deleted file mode 100644
index d104e379e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SelectionItem.java
+++ /dev/null
@@ -1,252 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.ResizePolicy;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.NodeProxy;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.ViewMetadataRepository;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-
-import org.eclipse.swt.graphics.Rectangle;
-import org.w3c.dom.Node;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Represents one selection in {@link LayoutCanvas}.
- */
-class SelectionItem {
-
- /** The associated {@link LayoutCanvas} */
- private LayoutCanvas mCanvas;
-
- /** Current selected view info. Can be null. */
- private final CanvasViewInfo mCanvasViewInfo;
-
- /** Current selection border rectangle. Null when mCanvasViewInfo is null . */
- private final Rectangle mRect;
-
- /** The node proxy for drawing the selection. Null when mCanvasViewInfo is null. */
- private final NodeProxy mNodeProxy;
-
- /** The resize policy for this selection item */
- private ResizePolicy mResizePolicy;
-
- /** The selection handles for this item */
- private SelectionHandles mHandles;
-
- /**
- * Creates a new {@link SelectionItem} object.
- * @param canvas the associated canvas
- * @param canvasViewInfo The view info being selected. Must not be null.
- */
- public SelectionItem(LayoutCanvas canvas, CanvasViewInfo canvasViewInfo) {
- assert canvasViewInfo != null;
-
- mCanvas = canvas;
- mCanvasViewInfo = canvasViewInfo;
-
- if (canvasViewInfo == null) {
- mRect = null;
- mNodeProxy = null;
- } else {
- Rectangle r = canvasViewInfo.getSelectionRect();
- mRect = new Rectangle(r.x, r.y, r.width, r.height);
- mNodeProxy = mCanvas.getNodeFactory().create(canvasViewInfo);
- }
- }
-
- /**
- * Returns true when this selection item represents the root, the top level
- * layout element in the editor.
- *
- * @return True if and only if this element is at the root of the hierarchy
- */
- public boolean isRoot() {
- return mCanvasViewInfo.isRoot();
- }
-
- /**
- * Returns true if this item represents a widget that should not be manipulated by the
- * user.
- *
- * @return True if this widget should not be manipulated directly by the user
- */
- public boolean isHidden() {
- return mCanvasViewInfo.isHidden();
- }
-
- /**
- * Returns the selected view info. Cannot be null.
- *
- * @return the selected view info. Cannot be null.
- */
- @NonNull
- public CanvasViewInfo getViewInfo() {
- return mCanvasViewInfo;
- }
-
- /**
- * Returns the selected node.
- *
- * @return the selected node, or null
- */
- @Nullable
- public UiViewElementNode getUiNode() {
- return mCanvasViewInfo.getUiViewNode();
- }
-
- /**
- * Returns the selection border rectangle. Cannot be null.
- *
- * @return the selection border rectangle, never null
- */
- public Rectangle getRect() {
- return mRect;
- }
-
- /** Returns the node associated with this selection (may be null) */
- @Nullable
- NodeProxy getNode() {
- return mNodeProxy;
- }
-
- /** Returns the canvas associated with this selection (never null) */
- @NonNull
- LayoutCanvas getCanvas() {
- return mCanvas;
- }
-
- //----
-
- /**
- * Gets the XML text from the given selection for a text transfer.
- * The returned string can be empty but not null.
- */
- @NonNull
- static String getAsText(LayoutCanvas canvas, List<SelectionItem> selection) {
- StringBuilder sb = new StringBuilder();
-
- LayoutEditorDelegate layoutEditorDelegate = canvas.getEditorDelegate();
- for (SelectionItem cs : selection) {
- CanvasViewInfo vi = cs.getViewInfo();
- UiViewElementNode key = vi.getUiViewNode();
- Node node = key.getXmlNode();
- String t = layoutEditorDelegate.getEditor().getXmlText(node);
- if (t != null) {
- if (sb.length() > 0) {
- sb.append('\n');
- }
- sb.append(t);
- }
- }
-
- return sb.toString();
- }
-
- /**
- * Returns elements representing the given selection of canvas items.
- *
- * @param items Items to wrap in elements
- * @return An array of wrapper elements. Never null.
- */
- @NonNull
- static SimpleElement[] getAsElements(@NonNull List<SelectionItem> items) {
- return getAsElements(items, null);
- }
-
- /**
- * Returns elements representing the given selection of canvas items.
- *
- * @param items Items to wrap in elements
- * @param primary The primary selected item which should be listed first
- * @return An array of wrapper elements. Never null.
- */
- @NonNull
- static SimpleElement[] getAsElements(
- @NonNull List<SelectionItem> items,
- @Nullable SelectionItem primary) {
- List<SimpleElement> elements = new ArrayList<SimpleElement>();
-
- if (primary != null) {
- CanvasViewInfo vi = primary.getViewInfo();
- SimpleElement e = vi.toSimpleElement();
- e.setSelectionItem(primary);
- elements.add(e);
- }
-
- for (SelectionItem cs : items) {
- if (cs == primary) {
- // Already handled
- continue;
- }
-
- CanvasViewInfo vi = cs.getViewInfo();
- SimpleElement e = vi.toSimpleElement();
- e.setSelectionItem(cs);
- elements.add(e);
- }
-
- return elements.toArray(new SimpleElement[elements.size()]);
- }
-
- /**
- * Returns true if this selection item is a layout
- *
- * @return true if this selection item is a layout
- */
- public boolean isLayout() {
- UiViewElementNode node = mCanvasViewInfo.getUiViewNode();
- if (node != null) {
- return node.getDescriptor().hasChildren();
- } else {
- return false;
- }
- }
-
- /**
- * Returns the {@link SelectionHandles} for this {@link SelectionItem}. Never null.
- *
- * @return the {@link SelectionHandles} for this {@link SelectionItem}, never null
- */
- @NonNull
- public SelectionHandles getSelectionHandles() {
- if (mHandles == null) {
- mHandles = new SelectionHandles(this);
- }
-
- return mHandles;
- }
-
- /**
- * Returns the {@link ResizePolicy} for this item
- *
- * @return the {@link ResizePolicy} for this item, never null
- */
- @NonNull
- public ResizePolicy getResizePolicy() {
- if (mResizePolicy == null && mNodeProxy != null) {
- mResizePolicy = ViewMetadataRepository.get().getResizePolicy(mNodeProxy.getFqcn());
- }
-
- return mResizePolicy;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SelectionManager.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SelectionManager.java
deleted file mode 100644
index eb3d6f290..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SelectionManager.java
+++ /dev/null
@@ -1,1262 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.FQCN_SPACE;
-import static com.android.SdkConstants.FQCN_SPACE_V7;
-import static com.android.SdkConstants.NEW_ID_PREFIX;
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.SelectionHandle.PIXEL_MARGIN;
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.SelectionHandle.PIXEL_RADIUS;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.RuleAction;
-import com.android.ide.common.layout.BaseViewRule;
-import com.android.ide.common.layout.GridLayoutRule;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.NodeFactory;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.NodeProxy;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.RulesEngine;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.refactorings.core.RenameResourceWizard;
-import com.android.ide.eclipse.adt.internal.refactorings.core.RenameResult;
-import com.android.ide.eclipse.adt.internal.resources.ResourceNameValidator;
-import com.android.resources.ResourceType;
-import com.android.utils.Pair;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.ListenerList;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.ActionContributionItem;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.util.SafeRunnable;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.ITreeSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.TreePath;
-import org.eclipse.jface.viewers.TreeSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.MenuDetectEvent;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.w3c.dom.Node;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.ListIterator;
-import java.util.Set;
-
-/**
- * The {@link SelectionManager} manages the selection in the canvas editor.
- * It holds (and can be asked about) the set of selected items, and it also has
- * operations for manipulating the selection - such as toggling items, copying
- * the selection to the clipboard, etc.
- * <p/>
- * This class implements {@link ISelectionProvider} so that it can delegate
- * the selection provider from the {@link LayoutCanvasViewer}.
- * <p/>
- * Note that {@link LayoutCanvasViewer} sets a selection change listener on this
- * manager so that it can invoke its own fireSelectionChanged when the canvas'
- * selection changes.
- */
-public class SelectionManager implements ISelectionProvider {
-
- private LayoutCanvas mCanvas;
-
- /** The current selection list. The list is never null, however it can be empty. */
- private final LinkedList<SelectionItem> mSelections = new LinkedList<SelectionItem>();
-
- /** An unmodifiable view of {@link #mSelections}. */
- private final List<SelectionItem> mUnmodifiableSelection =
- Collections.unmodifiableList(mSelections);
-
- /** Barrier set when updating the selection to prevent from recursively
- * invoking ourselves. */
- private boolean mInsideUpdateSelection;
-
- /**
- * The <em>current</em> alternate selection, if any, which changes when the Alt key is
- * used during a selection. Can be null.
- */
- private CanvasAlternateSelection mAltSelection;
-
- /** List of clients listening to selection changes. */
- private final ListenerList mSelectionListeners = new ListenerList();
-
- /**
- * Constructs a new {@link SelectionManager} associated with the given layout canvas.
- *
- * @param layoutCanvas The layout canvas to create a {@link SelectionManager} for.
- */
- public SelectionManager(LayoutCanvas layoutCanvas) {
- mCanvas = layoutCanvas;
- }
-
- @Override
- public void addSelectionChangedListener(ISelectionChangedListener listener) {
- mSelectionListeners.add(listener);
- }
-
- @Override
- public void removeSelectionChangedListener(ISelectionChangedListener listener) {
- mSelectionListeners.remove(listener);
- }
-
- /**
- * Returns the native {@link SelectionItem} list.
- *
- * @return An immutable list of {@link SelectionItem}. Can be empty but not null.
- */
- @NonNull
- List<SelectionItem> getSelections() {
- return mUnmodifiableSelection;
- }
-
- /**
- * Return a snapshot/copy of the selection. Useful for clipboards etc where we
- * don't want the returned copy to be affected by future edits to the selection.
- *
- * @return A copy of the current selection. Never null.
- */
- @NonNull
- public List<SelectionItem> getSnapshot() {
- if (mSelectionListeners.isEmpty()) {
- return Collections.emptyList();
- }
-
- return new ArrayList<SelectionItem>(mSelections);
- }
-
- /**
- * Returns a {@link TreeSelection} where each {@link TreePath} item is
- * actually a {@link CanvasViewInfo}.
- */
- @Override
- public ISelection getSelection() {
- if (mSelections.isEmpty()) {
- return TreeSelection.EMPTY;
- }
-
- ArrayList<TreePath> paths = new ArrayList<TreePath>();
-
- for (SelectionItem cs : mSelections) {
- CanvasViewInfo vi = cs.getViewInfo();
- if (vi != null) {
- paths.add(getTreePath(vi));
- }
- }
-
- return new TreeSelection(paths.toArray(new TreePath[paths.size()]));
- }
-
- /**
- * Create a {@link TreePath} from the given view info
- *
- * @param viewInfo the view info to look up a tree path for
- * @return a {@link TreePath} for the given view info
- */
- public static TreePath getTreePath(CanvasViewInfo viewInfo) {
- ArrayList<Object> segments = new ArrayList<Object>();
- while (viewInfo != null) {
- segments.add(0, viewInfo);
- viewInfo = viewInfo.getParent();
- }
-
- return new TreePath(segments.toArray());
- }
-
- /**
- * Sets the selection. It must be an {@link ITreeSelection} where each segment
- * of the tree path is a {@link CanvasViewInfo}. A null selection is considered
- * as an empty selection.
- * <p/>
- * This method is invoked by {@link LayoutCanvasViewer#setSelection(ISelection)}
- * in response to an <em>outside</em> selection (compatible with ours) that has
- * changed. Typically it means the outline selection has changed and we're
- * synchronizing ours to match.
- */
- @Override
- public void setSelection(ISelection selection) {
- if (mInsideUpdateSelection) {
- return;
- }
-
- boolean changed = false;
- try {
- mInsideUpdateSelection = true;
-
- if (selection == null) {
- selection = TreeSelection.EMPTY;
- }
-
- if (selection instanceof ITreeSelection) {
- ITreeSelection treeSel = (ITreeSelection) selection;
-
- if (treeSel.isEmpty()) {
- // Clear existing selection, if any
- if (!mSelections.isEmpty()) {
- mSelections.clear();
- mAltSelection = null;
- updateActionsFromSelection();
- redraw();
- }
- return;
- }
-
- boolean redoLayout = false;
-
- // Create a list of all currently selected view infos
- Set<CanvasViewInfo> oldSelected = new HashSet<CanvasViewInfo>();
- for (SelectionItem cs : mSelections) {
- oldSelected.add(cs.getViewInfo());
- }
-
- // Go thru new selection and take care of selecting new items
- // or marking those which are the same as in the current selection
- for (TreePath path : treeSel.getPaths()) {
- Object seg = path.getLastSegment();
- if (seg instanceof CanvasViewInfo) {
- CanvasViewInfo newVi = (CanvasViewInfo) seg;
- if (oldSelected.contains(newVi)) {
- // This view info is already selected. Remove it from the
- // oldSelected list so that we don't deselect it later.
- oldSelected.remove(newVi);
- } else {
- // This view info is not already selected. Select it now.
-
- // reset alternate selection if any
- mAltSelection = null;
- // otherwise add it.
- mSelections.add(createSelection(newVi));
- changed = true;
- }
- if (newVi.isInvisible()) {
- redoLayout = true;
- }
- } else {
- // Unrelated selection (e.g. user clicked in the Project Explorer
- // or something) -- just ignore these
- return;
- }
- }
-
- // Deselect old selected items that are not in the new one
- for (CanvasViewInfo vi : oldSelected) {
- if (vi.isExploded()) {
- redoLayout = true;
- }
- deselect(vi);
- changed = true;
- }
-
- if (redoLayout) {
- mCanvas.getEditorDelegate().recomputeLayout();
- }
- }
- } finally {
- mInsideUpdateSelection = false;
- }
-
- if (changed) {
- redraw();
- fireSelectionChanged();
- updateActionsFromSelection();
- }
- }
-
- /**
- * The menu has been activated; ensure that the menu click is over the existing
- * selection, and if not, update the selection.
- *
- * @param e the {@link MenuDetectEvent} which triggered the menu
- */
- public void menuClick(MenuDetectEvent e) {
- LayoutPoint p = ControlPoint.create(mCanvas, e).toLayout();
-
- // Right click button is used to display a context menu.
- // If there's an existing selection and the click is anywhere in this selection
- // and there are no modifiers being used, we don't want to change the selection.
- // Otherwise we select the item under the cursor.
-
- for (SelectionItem cs : mSelections) {
- if (cs.isRoot()) {
- continue;
- }
- if (cs.getRect().contains(p.x, p.y)) {
- // The cursor is inside the selection. Don't change anything.
- return;
- }
- }
-
- CanvasViewInfo vi = mCanvas.getViewHierarchy().findViewInfoAt(p);
- selectSingle(vi);
- }
-
- /**
- * Performs selection for a mouse event.
- * <p/>
- * Shift key (or Command on the Mac) is used to toggle in multi-selection.
- * Alt key is used to cycle selection through objects at the same level than
- * the one pointed at (i.e. click on an object then alt-click to cycle).
- *
- * @param e The mouse event which triggered the selection. Cannot be null.
- * The modifier key mask will be used to determine whether this
- * is a plain select or a toggle, etc.
- */
- public void select(MouseEvent e) {
- boolean isMultiClick = (e.stateMask & SWT.SHIFT) != 0 ||
- // On Mac, the Command key is the normal toggle accelerator
- ((SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_DARWIN) &&
- (e.stateMask & SWT.COMMAND) != 0);
- boolean isCycleClick = (e.stateMask & SWT.ALT) != 0;
-
- LayoutPoint p = ControlPoint.create(mCanvas, e).toLayout();
-
- if (e.button == 3) {
- // Right click button is used to display a context menu.
- // If there's an existing selection and the click is anywhere in this selection
- // and there are no modifiers being used, we don't want to change the selection.
- // Otherwise we select the item under the cursor.
-
- if (!isCycleClick && !isMultiClick) {
- for (SelectionItem cs : mSelections) {
- if (cs.getRect().contains(p.x, p.y)) {
- // The cursor is inside the selection. Don't change anything.
- return;
- }
- }
- }
-
- } else if (e.button != 1) {
- // Click was done with something else than the left button for normal selection
- // or the right button for context menu.
- // We don't use mouse button 2 yet (middle mouse, or scroll wheel?) for
- // anything, so let's not change the selection.
- return;
- }
-
- CanvasViewInfo vi = mCanvas.getViewHierarchy().findViewInfoAt(p);
-
- if (vi != null && vi.isHidden()) {
- vi = vi.getParent();
- }
-
- if (isMultiClick && !isCycleClick) {
- // Case where shift is pressed: pointed object is toggled.
-
- // reset alternate selection if any
- mAltSelection = null;
-
- // If nothing has been found at the cursor, assume it might be a user error
- // and avoid clearing the existing selection.
-
- if (vi != null) {
- // toggle this selection on-off: remove it if already selected
- if (deselect(vi)) {
- if (vi.isExploded()) {
- mCanvas.getEditorDelegate().recomputeLayout();
- }
-
- redraw();
- return;
- }
-
- // otherwise add it.
- mSelections.add(createSelection(vi));
- fireSelectionChanged();
- redraw();
- }
-
- } else if (isCycleClick) {
- // Case where alt is pressed: select or cycle the object pointed at.
-
- // Note: if shift and alt are pressed, shift is ignored. The alternate selection
- // mechanism does not reset the current multiple selection unless they intersect.
-
- // We need to remember the "origin" of the alternate selection, to be
- // able to continue cycling through it later. If there's no alternate selection,
- // create one. If there's one but not for the same origin object, create a new
- // one too.
- if (mAltSelection == null || mAltSelection.getOriginatingView() != vi) {
- mAltSelection = new CanvasAlternateSelection(
- vi, mCanvas.getViewHierarchy().findAltViewInfoAt(p));
-
- // deselect them all, in case they were partially selected
- deselectAll(mAltSelection.getAltViews());
-
- // select the current one
- CanvasViewInfo vi2 = mAltSelection.getCurrent();
- if (vi2 != null) {
- mSelections.addFirst(createSelection(vi2));
- fireSelectionChanged();
- }
- } else {
- // We're trying to cycle through the current alternate selection.
- // First remove the current object.
- CanvasViewInfo vi2 = mAltSelection.getCurrent();
- deselect(vi2);
-
- // Now select the next one.
- vi2 = mAltSelection.getNext();
- if (vi2 != null) {
- mSelections.addFirst(createSelection(vi2));
- fireSelectionChanged();
- }
- }
- redraw();
-
- } else {
- // Case where no modifier is pressed: either select or reset the selection.
- selectSingle(vi);
- }
- }
-
- /**
- * Removes all the currently selected item and only select the given item.
- * Issues a redraw() if the selection changes.
- *
- * @param vi The new selected item if non-null. Selection becomes empty if null.
- * @return the item selected, or null if the selection was cleared (e.g. vi was null)
- */
- @Nullable
- SelectionItem selectSingle(CanvasViewInfo vi) {
- SelectionItem item = null;
-
- // reset alternate selection if any
- mAltSelection = null;
-
- if (vi == null) {
- // The user clicked outside the bounds of the root element; in that case, just
- // select the root element.
- vi = mCanvas.getViewHierarchy().getRoot();
- }
-
- boolean redoLayout = hasExplodedItems();
-
- // reset (multi)selection if any
- if (!mSelections.isEmpty()) {
- if (mSelections.size() == 1 && mSelections.getFirst().getViewInfo() == vi) {
- // CanvasSelection remains the same, don't touch it.
- return mSelections.getFirst();
- }
- mSelections.clear();
- }
-
- if (vi != null) {
- item = createSelection(vi);
- mSelections.add(item);
- if (vi.isInvisible()) {
- redoLayout = true;
- }
- }
- fireSelectionChanged();
-
- if (redoLayout) {
- mCanvas.getEditorDelegate().recomputeLayout();
- }
-
- redraw();
-
- return item;
- }
-
- /** Returns true if the view hierarchy is showing exploded items. */
- private boolean hasExplodedItems() {
- for (SelectionItem item : mSelections) {
- if (item.getViewInfo().isExploded()) {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Selects the given set of {@link CanvasViewInfo}s. This is similar to
- * {@link #selectSingle} but allows you to make a multi-selection. Issues a
- * {@link #redraw()}.
- *
- * @param viewInfos A collection of {@link CanvasViewInfo} objects to be
- * selected, or null or empty to clear the selection.
- */
- /* package */ void selectMultiple(Collection<CanvasViewInfo> viewInfos) {
- // reset alternate selection if any
- mAltSelection = null;
-
- boolean redoLayout = hasExplodedItems();
-
- mSelections.clear();
- if (viewInfos != null) {
- for (CanvasViewInfo viewInfo : viewInfos) {
- mSelections.add(createSelection(viewInfo));
- if (viewInfo.isInvisible()) {
- redoLayout = true;
- }
- }
- }
-
- fireSelectionChanged();
-
- if (redoLayout) {
- mCanvas.getEditorDelegate().recomputeLayout();
- }
-
- redraw();
- }
-
- public void select(Collection<INode> nodes) {
- List<CanvasViewInfo> infos = new ArrayList<CanvasViewInfo>(nodes.size());
- for (INode node : nodes) {
- CanvasViewInfo info = mCanvas.getViewHierarchy().findViewInfoFor(node);
- if (info != null) {
- infos.add(info);
- }
- }
- selectMultiple(infos);
- }
-
- /**
- * Selects the visual element corresponding to the given XML node
- * @param xmlNode The Node whose element we want to select.
- */
- /* package */ void select(Node xmlNode) {
- if (xmlNode == null) {
- return;
- } else if (xmlNode.getNodeType() == Node.TEXT_NODE) {
- xmlNode = xmlNode.getParentNode();
- }
-
- CanvasViewInfo vi = mCanvas.getViewHierarchy().findViewInfoFor(xmlNode);
- if (vi != null && !vi.isRoot()) {
- selectSingle(vi);
- }
- }
-
- /**
- * Selects any views that overlap the given selection rectangle.
- *
- * @param topLeft The top left corner defining the selection rectangle.
- * @param bottomRight The bottom right corner defining the selection
- * rectangle.
- * @param toggled A set of {@link CanvasViewInfo}s that should be toggled
- * rather than just added.
- */
- public void selectWithin(LayoutPoint topLeft, LayoutPoint bottomRight,
- Collection<CanvasViewInfo> toggled) {
- // reset alternate selection if any
- mAltSelection = null;
-
- ViewHierarchy viewHierarchy = mCanvas.getViewHierarchy();
- Collection<CanvasViewInfo> viewInfos = viewHierarchy.findWithin(topLeft, bottomRight);
-
- if (toggled.size() > 0) {
- // Copy; we're not allowed to touch the passed in collection
- Set<CanvasViewInfo> result = new HashSet<CanvasViewInfo>(toggled);
- for (CanvasViewInfo viewInfo : viewInfos) {
- if (toggled.contains(viewInfo)) {
- result.remove(viewInfo);
- } else {
- result.add(viewInfo);
- }
- }
- viewInfos = result;
- }
-
- mSelections.clear();
- for (CanvasViewInfo viewInfo : viewInfos) {
- if (viewInfo.isHidden()) {
- continue;
- }
- mSelections.add(createSelection(viewInfo));
- }
-
- fireSelectionChanged();
- redraw();
- }
-
- /**
- * Clears the selection and then selects everything (all views and all their
- * children).
- */
- public void selectAll() {
- // First clear the current selection, if any.
- mSelections.clear();
- mAltSelection = null;
-
- // Now select everything if there's a valid layout
- for (CanvasViewInfo vi : mCanvas.getViewHierarchy().findAllViewInfos(false)) {
- mSelections.add(createSelection(vi));
- }
-
- fireSelectionChanged();
- redraw();
- }
-
- /** Clears the selection */
- public void selectNone() {
- mSelections.clear();
- mAltSelection = null;
- fireSelectionChanged();
- redraw();
- }
-
- /** Selects the parent of the current selection */
- public void selectParent() {
- if (mSelections.size() == 1) {
- CanvasViewInfo parent = mSelections.get(0).getViewInfo().getParent();
- if (parent != null) {
- selectSingle(parent);
- }
- }
- }
-
- /** Finds all widgets in the layout that have the same type as the primary */
- public void selectSameType() {
- // Find all
- if (mSelections.size() == 1) {
- CanvasViewInfo viewInfo = mSelections.get(0).getViewInfo();
- ElementDescriptor descriptor = viewInfo.getUiViewNode().getDescriptor();
- mSelections.clear();
- mAltSelection = null;
- addSameType(mCanvas.getViewHierarchy().getRoot(), descriptor);
- fireSelectionChanged();
- redraw();
- }
- }
-
- /** Helper for {@link #selectSameType} */
- private void addSameType(CanvasViewInfo root, ElementDescriptor descriptor) {
- if (root.getUiViewNode().getDescriptor() == descriptor) {
- mSelections.add(createSelection(root));
- }
-
- for (CanvasViewInfo child : root.getChildren()) {
- addSameType(child, descriptor);
- }
- }
-
- /** Selects the siblings of the primary */
- public void selectSiblings() {
- // Find all
- if (mSelections.size() == 1) {
- CanvasViewInfo vi = mSelections.get(0).getViewInfo();
- mSelections.clear();
- mAltSelection = null;
- CanvasViewInfo parent = vi.getParent();
- if (parent == null) {
- selectNone();
- } else {
- for (CanvasViewInfo child : parent.getChildren()) {
- mSelections.add(createSelection(child));
- }
- fireSelectionChanged();
- redraw();
- }
- }
- }
-
- /**
- * Returns true if and only if there is currently more than one selected
- * item.
- *
- * @return True if more than one item is selected
- */
- public boolean hasMultiSelection() {
- return mSelections.size() > 1;
- }
-
- /**
- * Deselects a view info. Returns true if the object was actually selected.
- * Callers are responsible for calling redraw() and updateOulineSelection()
- * after.
- * @param canvasViewInfo The item to deselect.
- * @return True if the object was successfully removed from the selection.
- */
- public boolean deselect(CanvasViewInfo canvasViewInfo) {
- if (canvasViewInfo == null) {
- return false;
- }
-
- for (ListIterator<SelectionItem> it = mSelections.listIterator(); it.hasNext(); ) {
- SelectionItem s = it.next();
- if (canvasViewInfo == s.getViewInfo()) {
- it.remove();
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Deselects multiple view infos.
- * Callers are responsible for calling redraw() and updateOulineSelection() after.
- */
- private void deselectAll(List<CanvasViewInfo> canvasViewInfos) {
- for (ListIterator<SelectionItem> it = mSelections.listIterator(); it.hasNext(); ) {
- SelectionItem s = it.next();
- if (canvasViewInfos.contains(s.getViewInfo())) {
- it.remove();
- }
- }
- }
-
- /** Sync the selection with an updated view info tree */
- void sync() {
- // Check if the selection is still the same (based on the object keys)
- // and eventually recompute their bounds.
- for (ListIterator<SelectionItem> it = mSelections.listIterator(); it.hasNext(); ) {
- SelectionItem s = it.next();
-
- // Check if the selected object still exists
- ViewHierarchy viewHierarchy = mCanvas.getViewHierarchy();
- UiViewElementNode key = s.getViewInfo().getUiViewNode();
- CanvasViewInfo vi = viewHierarchy.findViewInfoFor(key);
-
- // Remove the previous selection -- if the selected object still exists
- // we need to recompute its bounds in case it moved so we'll insert a new one
- // at the same place.
- it.remove();
- if (vi == null) {
- vi = findCorresponding(s.getViewInfo(), viewHierarchy.getRoot());
- }
- if (vi != null) {
- it.add(createSelection(vi));
- }
- }
- fireSelectionChanged();
-
- // remove the current alternate selection views
- mAltSelection = null;
- }
-
- /** Finds the corresponding {@link CanvasViewInfo} in the new hierarchy */
- private CanvasViewInfo findCorresponding(CanvasViewInfo old, CanvasViewInfo newRoot) {
- CanvasViewInfo oldParent = old.getParent();
- if (oldParent != null) {
- CanvasViewInfo newParent = findCorresponding(oldParent, newRoot);
- if (newParent == null) {
- return null;
- }
-
- List<CanvasViewInfo> oldSiblings = oldParent.getChildren();
- List<CanvasViewInfo> newSiblings = newParent.getChildren();
- Iterator<CanvasViewInfo> oldIterator = oldSiblings.iterator();
- Iterator<CanvasViewInfo> newIterator = newSiblings.iterator();
- while (oldIterator.hasNext() && newIterator.hasNext()) {
- CanvasViewInfo oldSibling = oldIterator.next();
- CanvasViewInfo newSibling = newIterator.next();
-
- if (oldSibling.getName().equals(newSibling.getName())) {
- // Structure has changed: can't do a proper search
- return null;
- }
-
- if (oldSibling == old) {
- return newSibling;
- }
- }
- } else {
- return newRoot;
- }
-
- return null;
- }
-
- /**
- * Notifies listeners that the selection has changed.
- */
- private void fireSelectionChanged() {
- if (mInsideUpdateSelection) {
- return;
- }
- try {
- mInsideUpdateSelection = true;
-
- final SelectionChangedEvent event = new SelectionChangedEvent(this, getSelection());
-
- SafeRunnable.run(new SafeRunnable() {
- @Override
- public void run() {
- for (Object listener : mSelectionListeners.getListeners()) {
- ((ISelectionChangedListener) listener).selectionChanged(event);
- }
- }
- });
-
- updateActionsFromSelection();
- } finally {
- mInsideUpdateSelection = false;
- }
- }
-
- /**
- * Updates menu actions and the layout action bar after a selection change - these are
- * actions that depend on the selection
- */
- private void updateActionsFromSelection() {
- LayoutEditorDelegate editor = mCanvas.getEditorDelegate();
- if (editor != null) {
- // Update menu actions that depend on the selection
- mCanvas.updateMenuActionState();
-
- // Update the layout actions bar
- LayoutActionBar layoutActionBar = editor.getGraphicalEditor().getLayoutActionBar();
- layoutActionBar.updateSelection();
- }
- }
-
- /**
- * Sanitizes the selection for a copy/cut or drag operation.
- * <p/>
- * Sanitizes the list to make sure all elements have a valid XML attached to it,
- * that is remove element that have no XML to avoid having to make repeated such
- * checks in various places after.
- * <p/>
- * In case of multiple selection, we also need to remove all children when their
- * parent is already selected since parents will always be added with all their
- * children.
- * <p/>
- *
- * @param selection The selection list to be sanitized <b>in-place</b>.
- * The <code>selection</code> argument should not be {@link #mSelections} -- the
- * given list is going to be altered and we should never alter the user-made selection.
- * Instead the caller should provide its own copy.
- */
- /* package */ static void sanitize(List<SelectionItem> selection) {
- if (selection.isEmpty()) {
- return;
- }
-
- for (Iterator<SelectionItem> it = selection.iterator(); it.hasNext(); ) {
- SelectionItem cs = it.next();
- CanvasViewInfo vi = cs.getViewInfo();
- UiViewElementNode key = vi == null ? null : vi.getUiViewNode();
- Node node = key == null ? null : key.getXmlNode();
- if (node == null) {
- // Missing ViewInfo or view key or XML, discard this.
- it.remove();
- continue;
- }
-
- if (vi != null) {
- for (Iterator<SelectionItem> it2 = selection.iterator();
- it2.hasNext(); ) {
- SelectionItem cs2 = it2.next();
- if (cs != cs2) {
- CanvasViewInfo vi2 = cs2.getViewInfo();
- if (vi.isParent(vi2)) {
- // vi2 is a parent for vi. Remove vi.
- it.remove();
- break;
- }
- }
- }
- }
- }
- }
-
- /**
- * Selects the given list of nodes in the canvas, and returns true iff the
- * attempt to select was successful.
- *
- * @param nodes The collection of nodes to be selected
- * @param indices A list of indices within the parent for each node, or null
- * @return True if and only if all nodes were successfully selected
- */
- public boolean selectDropped(List<INode> nodes, List<Integer> indices) {
- assert indices == null || nodes.size() == indices.size();
-
- ViewHierarchy viewHierarchy = mCanvas.getViewHierarchy();
-
- // Look up a list of view infos which correspond to the nodes.
- final Collection<CanvasViewInfo> newChildren = new ArrayList<CanvasViewInfo>();
- for (int i = 0, n = nodes.size(); i < n; i++) {
- INode node = nodes.get(i);
-
- CanvasViewInfo viewInfo = viewHierarchy.findViewInfoFor(node);
-
- // There are two scenarios where looking up a view info fails.
- // The first one is that the node was just added and the render has not yet
- // happened, so the ViewHierarchy has no record of the node. In this case
- // there is nothing we can do, and the method will return false (which the
- // caller will use to schedule a second attempt later).
- // The second scenario is where the nodes *change identity*. This isn't
- // common, but when a drop handler makes a lot of changes to its children,
- // for example when dropping into a GridLayout where attributes are adjusted
- // on nearly all the other children to update row or column attributes
- // etc, then in some cases Eclipse's DOM model changes the identities of
- // the nodes when applying all the edits, so the new Node we created (as
- // well as possibly other nodes) are no longer the children we observe
- // after the edit, and there are new copies there instead. In this case
- // the UiViewModel also fails to map the nodes. To work around this,
- // we track the *indices* (within the parent) during a drop, such that we
- // know which children (according to their positions) the given nodes
- // are supposed to map to, and then we use these view infos instead.
- if (viewInfo == null && node instanceof NodeProxy && indices != null) {
- INode parent = node.getParent();
- CanvasViewInfo parentViewInfo = viewHierarchy.findViewInfoFor(parent);
- if (parentViewInfo != null) {
- UiViewElementNode parentUiNode = parentViewInfo.getUiViewNode();
- if (parentUiNode != null) {
- List<UiElementNode> children = parentUiNode.getUiChildren();
- int index = indices.get(i);
- if (index >= 0 && index < children.size()) {
- UiElementNode replacedNode = children.get(index);
- viewInfo = viewHierarchy.findViewInfoFor(replacedNode);
- }
- }
- }
- }
-
- if (viewInfo != null) {
- if (nodes.size() > 1 && viewInfo.isHidden()) {
- // Skip spacers - unless you're dropping just one
- continue;
- }
- if (GridLayoutRule.sDebugGridLayout && (viewInfo.getName().equals(FQCN_SPACE)
- || viewInfo.getName().equals(FQCN_SPACE_V7))) {
- // In debug mode they might not be marked as hidden but we never never
- // want to select these guys
- continue;
- }
- newChildren.add(viewInfo);
- }
- }
- boolean found = nodes.size() == newChildren.size();
-
- if (found || newChildren.size() > 0) {
- mCanvas.getSelectionManager().selectMultiple(newChildren);
- }
-
- return found;
- }
-
- /**
- * Update the outline selection to select the given nodes, asynchronously.
- * @param nodes The nodes to be selected
- */
- public void setOutlineSelection(final List<INode> nodes) {
- Display.getDefault().asyncExec(new Runnable() {
- @Override
- public void run() {
- selectDropped(nodes, null /* indices */);
- syncOutlineSelection();
- }
- });
- }
-
- /**
- * Syncs the current selection to the outline, synchronously.
- */
- public void syncOutlineSelection() {
- OutlinePage outlinePage = mCanvas.getOutlinePage();
- IWorkbenchPartSite site = outlinePage.getEditor().getSite();
- ISelectionProvider selectionProvider = site.getSelectionProvider();
- ISelection selection = selectionProvider.getSelection();
- if (selection != null) {
- outlinePage.setSelection(selection);
- }
- }
-
- private void redraw() {
- mCanvas.redraw();
- }
-
- SelectionItem createSelection(CanvasViewInfo vi) {
- return new SelectionItem(mCanvas, vi);
- }
-
- /**
- * Returns true if there is nothing selected
- *
- * @return true if there is nothing selected
- */
- public boolean isEmpty() {
- return mSelections.size() == 0;
- }
-
- /**
- * "Select" context menu which lists various menu options related to selection:
- * <ul>
- * <li> Select All
- * <li> Select Parent
- * <li> Select None
- * <li> Select Siblings
- * <li> Select Same Type
- * </ul>
- * etc.
- */
- public static class SelectionMenu extends SubmenuAction {
- private final GraphicalEditorPart mEditor;
-
- public SelectionMenu(GraphicalEditorPart editor) {
- super("Select");
- mEditor = editor;
- }
-
- @Override
- public String getId() {
- return "-selectionmenu"; //$NON-NLS-1$
- }
-
- @Override
- protected void addMenuItems(Menu menu) {
- LayoutCanvas canvas = mEditor.getCanvasControl();
- SelectionManager selectionManager = canvas.getSelectionManager();
- List<SelectionItem> selections = selectionManager.getSelections();
- boolean selectedOne = selections.size() == 1;
- boolean notRoot = selectedOne && !selections.get(0).isRoot();
- boolean haveSelection = selections.size() > 0;
-
- Action a;
- a = selectionManager.new SelectAction("Select Parent\tEsc", SELECT_PARENT);
- new ActionContributionItem(a).fill(menu, -1);
- a.setEnabled(notRoot);
- a.setAccelerator(SWT.ESC);
-
- a = selectionManager.new SelectAction("Select Siblings", SELECT_SIBLINGS);
- new ActionContributionItem(a).fill(menu, -1);
- a.setEnabled(notRoot);
-
- a = selectionManager.new SelectAction("Select Same Type", SELECT_SAME_TYPE);
- new ActionContributionItem(a).fill(menu, -1);
- a.setEnabled(selectedOne);
-
- new Separator().fill(menu, -1);
-
- // Special case for Select All: Use global action
- a = canvas.getSelectAllAction();
- new ActionContributionItem(a).fill(menu, -1);
- a.setEnabled(true);
-
- a = selectionManager.new SelectAction("Deselect All", SELECT_NONE);
- new ActionContributionItem(a).fill(menu, -1);
- a.setEnabled(haveSelection);
- }
- }
-
- private static final int SELECT_PARENT = 1;
- private static final int SELECT_SIBLINGS = 2;
- private static final int SELECT_SAME_TYPE = 3;
- private static final int SELECT_NONE = 4; // SELECT_ALL is handled separately
-
- private class SelectAction extends Action {
- private final int mType;
-
- public SelectAction(String title, int type) {
- super(title, IAction.AS_PUSH_BUTTON);
- mType = type;
- }
-
- @Override
- public void run() {
- switch (mType) {
- case SELECT_NONE:
- selectNone();
- break;
- case SELECT_PARENT:
- selectParent();
- break;
- case SELECT_SAME_TYPE:
- selectSameType();
- break;
- case SELECT_SIBLINGS:
- selectSiblings();
- break;
- }
-
- List<INode> nodes = new ArrayList<INode>();
- for (SelectionItem item : getSelections()) {
- nodes.add(item.getNode());
- }
- setOutlineSelection(nodes);
- }
- }
-
- public Pair<SelectionItem, SelectionHandle> findHandle(ControlPoint controlPoint) {
- if (!isEmpty()) {
- LayoutPoint layoutPoint = controlPoint.toLayout();
- int distance = (int) ((PIXEL_MARGIN + PIXEL_RADIUS) / mCanvas.getScale());
-
- for (SelectionItem item : getSelections()) {
- SelectionHandles handles = item.getSelectionHandles();
- // See if it's over the selection handles
- SelectionHandle handle = handles.findHandle(layoutPoint, distance);
- if (handle != null) {
- return Pair.of(item, handle);
- }
- }
-
- }
- return null;
- }
-
- /** Performs the default action provided by the currently selected view */
- public void performDefaultAction() {
- final List<SelectionItem> selections = getSelections();
- if (selections.size() > 0) {
- NodeProxy primary = selections.get(0).getNode();
- if (primary != null) {
- RulesEngine rulesEngine = mCanvas.getRulesEngine();
- final String id = rulesEngine.callGetDefaultActionId(primary);
- if (id == null) {
- return;
- }
- final List<RuleAction> actions = rulesEngine.callGetContextMenu(primary);
- if (actions == null) {
- return;
- }
- RuleAction matching = null;
- for (RuleAction a : actions) {
- if (id.equals(a.getId())) {
- matching = a;
- break;
- }
- }
- if (matching == null) {
- return;
- }
- final List<INode> selectedNodes = new ArrayList<INode>();
- for (SelectionItem item : selections) {
- NodeProxy n = item.getNode();
- if (n != null) {
- selectedNodes.add(n);
- }
- }
- final RuleAction action = matching;
- mCanvas.getEditorDelegate().getEditor().wrapUndoEditXmlModel(action.getTitle(),
- new Runnable() {
- @Override
- public void run() {
- action.getCallback().action(action, selectedNodes,
- action.getId(), null);
- LayoutCanvas canvas = mCanvas;
- CanvasViewInfo root = canvas.getViewHierarchy().getRoot();
- if (root != null) {
- UiViewElementNode uiViewNode = root.getUiViewNode();
- NodeFactory nodeFactory = canvas.getNodeFactory();
- NodeProxy rootNode = nodeFactory.create(uiViewNode);
- if (rootNode != null) {
- rootNode.applyPendingChanges();
- }
- }
- }
- });
- }
- }
- }
-
- /** Performs renaming the selected views */
- public void performRename() {
- final List<SelectionItem> selections = getSelections();
- if (selections.size() > 0) {
- NodeProxy primary = selections.get(0).getNode();
- if (primary != null) {
- performRename(primary, selections);
- }
- }
- }
-
- /**
- * Performs renaming the given node.
- *
- * @param primary the node to be renamed, or the primary node (to get the
- * current value from if more than one node should be renamed)
- * @param selections if not null, a list of nodes to apply the setting to
- * (which should include the primary)
- * @return the result of the renaming operation
- */
- @NonNull
- public RenameResult performRename(
- final @NonNull INode primary,
- final @Nullable List<SelectionItem> selections) {
- String id = primary.getStringAttr(ANDROID_URI, ATTR_ID);
- if (id != null && !id.isEmpty()) {
- RenameResult result = RenameResourceWizard.renameResource(
- mCanvas.getShell(),
- mCanvas.getEditorDelegate().getGraphicalEditor().getProject(),
- ResourceType.ID, BaseViewRule.stripIdPrefix(id), null, true /*canClear*/);
- if (result.isCanceled()) {
- return result;
- } else if (!result.isUnavailable()) {
- return result;
- }
- }
- String currentId = primary.getStringAttr(ANDROID_URI, ATTR_ID);
- currentId = BaseViewRule.stripIdPrefix(currentId);
- InputDialog d = new InputDialog(
- AdtPlugin.getDisplay().getActiveShell(),
- "Set ID",
- "New ID:",
- currentId,
- ResourceNameValidator.create(false, (IProject) null, ResourceType.ID));
- if (d.open() == Window.OK) {
- final String s = d.getValue();
- mCanvas.getEditorDelegate().getEditor().wrapUndoEditXmlModel("Set ID",
- new Runnable() {
- @Override
- public void run() {
- String newId = s;
- newId = NEW_ID_PREFIX + BaseViewRule.stripIdPrefix(s);
- if (selections != null) {
- for (SelectionItem item : selections) {
- NodeProxy node = item.getNode();
- if (node != null) {
- node.setAttribute(ANDROID_URI, ATTR_ID, newId);
- }
- }
- } else {
- primary.setAttribute(ANDROID_URI, ATTR_ID, newId);
- }
-
- LayoutCanvas canvas = mCanvas;
- CanvasViewInfo root = canvas.getViewHierarchy().getRoot();
- if (root != null) {
- UiViewElementNode uiViewNode = root.getUiViewNode();
- NodeFactory nodeFactory = canvas.getNodeFactory();
- NodeProxy rootNode = nodeFactory.create(uiViewNode);
- if (rootNode != null) {
- rootNode.applyPendingChanges();
- }
- }
- }
- });
- return RenameResult.name(BaseViewRule.stripIdPrefix(s));
- } else {
- return RenameResult.canceled();
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SelectionOverlay.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SelectionOverlay.java
deleted file mode 100644
index 97d048108..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SelectionOverlay.java
+++ /dev/null
@@ -1,247 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.ide.common.api.DrawingStyle;
-import com.android.ide.common.api.IGraphics;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.Margins;
-import com.android.ide.common.api.Rect;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.NodeProxy;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.RulesEngine;
-
-import org.eclipse.swt.graphics.GC;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * The {@link SelectionOverlay} paints the current selection as an overlay.
- */
-public class SelectionOverlay extends Overlay {
- private final LayoutCanvas mCanvas;
- private boolean mHidden;
-
- /**
- * Constructs a new {@link SelectionOverlay} tied to the given canvas.
- *
- * @param canvas the associated canvas
- */
- public SelectionOverlay(LayoutCanvas canvas) {
- mCanvas = canvas;
- }
-
- /**
- * Set whether the selection overlay should be hidden. This is done during some
- * gestures like resize where the new bounds could be confused with the current
- * selection bounds.
- *
- * @param hidden when true, hide the selection bounds, when false, unhide.
- */
- public void setHidden(boolean hidden) {
- mHidden = hidden;
- }
-
- /**
- * Paints the selection.
- *
- * @param selectionManager The {@link SelectionManager} holding the
- * selection.
- * @param gcWrapper The graphics context wrapper for the layout rules to use.
- * @param gc The SWT graphics object
- * @param rulesEngine The {@link RulesEngine} holding the rules.
- */
- public void paint(SelectionManager selectionManager, GCWrapper gcWrapper,
- GC gc, RulesEngine rulesEngine) {
- if (mHidden) {
- return;
- }
-
- List<SelectionItem> selections = selectionManager.getSelections();
- int n = selections.size();
- if (n > 0) {
- List<NodeProxy> selectedNodes = new ArrayList<NodeProxy>();
- boolean isMultipleSelection = n > 1;
- for (SelectionItem s : selections) {
- if (s.isRoot()) {
- // The root selection is never painted
- continue;
- }
-
- NodeProxy node = s.getNode();
- if (node != null) {
- paintSelection(gcWrapper, gc, s, isMultipleSelection);
- selectedNodes.add(node);
- }
- }
-
- if (selectedNodes.size() > 0) {
- paintSelectionFeedback(gcWrapper, selectedNodes, rulesEngine);
- } else {
- CanvasViewInfo root = mCanvas.getViewHierarchy().getRoot();
- if (root != null) {
- NodeProxy parent = mCanvas.getNodeFactory().create(root);
- rulesEngine.callPaintSelectionFeedback(gcWrapper,
- parent, Collections.<INode>emptyList(), root.getViewObject());
- }
- }
-
- if (n == 1) {
- NodeProxy node = selections.get(0).getNode();
- if (node != null) {
- paintHints(gcWrapper, node, rulesEngine);
- }
- }
- } else {
- CanvasViewInfo root = mCanvas.getViewHierarchy().getRoot();
- if (root != null) {
- NodeProxy parent = mCanvas.getNodeFactory().create(root);
- rulesEngine.callPaintSelectionFeedback(gcWrapper,
- parent, Collections.<INode>emptyList(), root.getViewObject());
- }
- }
- }
-
- /** Paint hint for current selection */
- private void paintHints(GCWrapper gcWrapper, NodeProxy node, RulesEngine rulesEngine) {
- INode parent = node.getParent();
- if (parent instanceof NodeProxy) {
- NodeProxy parentNode = (NodeProxy) parent;
- List<String> infos = rulesEngine.callGetSelectionHint(parentNode, node);
- if (infos != null && infos.size() > 0) {
- gcWrapper.useStyle(DrawingStyle.HELP);
-
- Rect b = mCanvas.getImageOverlay().getImageBounds();
- if (b == null) {
- return;
- }
-
- // Compute the location to display the help. This is done in
- // layout coordinates, so we need to apply the scale in reverse
- // when making pixel margins
- // TODO: We could take the Canvas dimensions into account to see
- // where there is more room.
- // TODO: The scrollbars should take the presence of hint text
- // into account.
- double scale = mCanvas.getScale();
- int x, y;
- if (b.w > b.h) {
- x = (int) (b.x + 3 / scale);
- y = (int) (b.y + b.h + 6 / scale);
- } else {
- x = (int) (b.x + b.w + 6 / scale);
- y = (int) (b.y + 3 / scale);
- }
- gcWrapper.drawBoxedStrings(x, y, infos);
- }
- }
- }
-
- private void paintSelectionFeedback(GCWrapper gcWrapper, List<NodeProxy> nodes,
- RulesEngine rulesEngine) {
- // Add fastpath for n=1
-
- // Group nodes into parent/child groups
- Set<INode> parents = new HashSet<INode>();
- for (INode node : nodes) {
- INode parent = node.getParent();
- if (/*parent == null || */parent instanceof NodeProxy) {
- NodeProxy parentNode = (NodeProxy) parent;
- parents.add(parentNode);
- }
- }
- ViewHierarchy viewHierarchy = mCanvas.getViewHierarchy();
- for (INode parent : parents) {
- List<INode> children = new ArrayList<INode>();
- for (INode node : nodes) {
- INode nodeParent = node.getParent();
- if (nodeParent == parent) {
- children.add(node);
- }
- }
- CanvasViewInfo viewInfo = viewHierarchy.findViewInfoFor((NodeProxy) parent);
- Object view = viewInfo != null ? viewInfo.getViewObject() : null;
-
- rulesEngine.callPaintSelectionFeedback(gcWrapper,
- (NodeProxy) parent, children, view);
- }
- }
-
- /** Called by the canvas when a view is being selected. */
- private void paintSelection(IGraphics gc, GC swtGc, SelectionItem item,
- boolean isMultipleSelection) {
- CanvasViewInfo view = item.getViewInfo();
- if (view.isHidden()) {
- return;
- }
-
- NodeProxy selectedNode = item.getNode();
- Rect r = selectedNode.getBounds();
- if (!r.isValid()) {
- return;
- }
-
- gc.useStyle(DrawingStyle.SELECTION);
-
- Margins insets = mCanvas.getInsets(selectedNode.getFqcn());
- int x1 = r.x;
- int y1 = r.y;
- int x2 = r.x2() + 1;
- int y2 = r.y2() + 1;
-
- if (insets != null) {
- x1 += insets.left;
- x2 -= insets.right;
- y1 += insets.top;
- y2 -= insets.bottom;
- }
-
- gc.drawRect(x1, y1, x2, y2);
-
- // Paint sibling rectangles, if applicable
- List<CanvasViewInfo> siblings = view.getNodeSiblings();
- if (siblings != null) {
- for (CanvasViewInfo sibling : siblings) {
- if (sibling != view) {
- r = SwtUtils.toRect(sibling.getSelectionRect());
- gc.fillRect(r);
- gc.drawRect(r);
- }
- }
- }
-
- // Paint selection handles. These are painted in control coordinates on the
- // real SWT GC object rather than in layout coordinates on the GCWrapper,
- // since we want them to have a fixed size that is independent of the
- // screen zoom.
- CanvasTransform horizontalTransform = mCanvas.getHorizontalTransform();
- CanvasTransform verticalTransform = mCanvas.getVerticalTransform();
- int radius = SelectionHandle.PIXEL_RADIUS;
- int doubleRadius = 2 * radius;
- for (SelectionHandle handle : item.getSelectionHandles()) {
- int cx = horizontalTransform.translate(handle.centerX);
- int cy = verticalTransform.translate(handle.centerY);
-
- SwtDrawingStyle style = SwtDrawingStyle.of(DrawingStyle.SELECTION);
- gc.setAlpha(style.getStrokeAlpha());
- swtGc.fillRectangle(cx - radius, cy - radius, doubleRadius, doubleRadius);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ShowWithinMenu.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ShowWithinMenu.java
deleted file mode 100644
index d1d529e5a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ShowWithinMenu.java
+++ /dev/null
@@ -1,82 +0,0 @@
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.ide.common.rendering.api.Capability;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.IncludeFinder.Reference;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.ActionContributionItem;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.swt.widgets.Menu;
-
-import java.util.List;
-
-/**
- * Action which creates a submenu for the "Show Included In" action
- */
-class ShowWithinMenu extends SubmenuAction {
- private LayoutEditorDelegate mEditorDelegate;
-
- ShowWithinMenu(LayoutEditorDelegate editorDelegate) {
- super("Show Included In");
- mEditorDelegate = editorDelegate;
- }
-
- @Override
- protected void addMenuItems(Menu menu) {
- GraphicalEditorPart graphicalEditor = mEditorDelegate.getGraphicalEditor();
- IFile file = graphicalEditor.getEditedFile();
- if (graphicalEditor.renderingSupports(Capability.EMBEDDED_LAYOUT)) {
- IProject project = file.getProject();
- IncludeFinder finder = IncludeFinder.get(project);
- final List<Reference> includedBy = finder.getIncludedBy(file);
-
- if (includedBy != null && includedBy.size() > 0) {
- for (final Reference reference : includedBy) {
- String title = reference.getDisplayName();
- IAction action = new ShowWithinAction(title, reference);
- new ActionContributionItem(action).fill(menu, -1);
- }
- new Separator().fill(menu, -1);
- }
- IAction action = new ShowWithinAction("Nothing", null);
- if (includedBy == null || includedBy.size() == 0) {
- action.setEnabled(false);
- }
- new ActionContributionItem(action).fill(menu, -1);
- } else {
- addDisabledMessageItem("Not supported on platform");
- }
- }
-
- /** Action to select one particular include-context */
- private class ShowWithinAction extends Action {
- private Reference mReference;
-
- public ShowWithinAction(String title, Reference reference) {
- super(title, IAction.AS_RADIO_BUTTON);
- mReference = reference;
- }
-
- @Override
- public boolean isChecked() {
- Reference within = mEditorDelegate.getGraphicalEditor().getIncludedWithin();
- if (within == null) {
- return mReference == null;
- } else {
- return within.equals(mReference);
- }
- }
-
- @Override
- public void run() {
- if (!isChecked()) {
- mEditorDelegate.getGraphicalEditor().showIn(mReference);
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SimpleAttribute.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SimpleAttribute.java
deleted file mode 100644
index 198c16484..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SimpleAttribute.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.INode.IAttribute;
-
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * Represents one XML attribute in a {@link SimpleElement}.
- * <p/>
- * The attribute is always represented by a namespace URI, a name and a value.
- * The name cannot be empty.
- * The namespace URI can be empty for an attribute without a namespace but is never null.
- * The value can be empty but cannot be null.
- * <p/>
- * For a more detailed explanation of the purpose of this class,
- * please see {@link SimpleXmlTransfer}.
- */
-public class SimpleAttribute implements IAttribute {
- private final String mName;
- private final String mValue;
- private final String mUri;
-
- /**
- * Creates a new {@link SimpleAttribute}.
- * <p/>
- * Any null value will be converted to an empty non-null string.
- * However it is a semantic error to use an empty name -- no assertion is done though.
- *
- * @param uri The URI of the attribute.
- * @param name The XML local name of the attribute.
- * @param value The value of the attribute.
- */
- public SimpleAttribute(String uri, String name, String value) {
- mUri = uri == null ? "" : uri;
- mName = name == null ? "" : name;
- mValue = value == null ? "" : value;
- }
-
- /**
- * Returns the namespace URI of the attribute.
- * Can be empty for an attribute without a namespace but is never null.
- */
- @Override
- public @NonNull String getUri() {
- return mUri;
- }
-
- /** Returns the XML local name of the attribute. Cannot be null nor empty. */
- @Override
- public @NonNull String getName() {
- return mName;
- }
-
- /** Returns the value of the attribute. Cannot be null. Can be empty. */
- @Override
- public @NonNull String getValue() {
- return mValue;
- }
-
- // reader and writer methods
-
- @Override
- public String toString() {
- return String.format("@%s:%s=%s\n", //$NON-NLS-1$
- mName,
- mUri,
- mValue);
- }
-
- private static final Pattern REGEXP =
- Pattern.compile("[^@]*@([^:]+):([^=]*)=([^\n]*)\n*"); //$NON-NLS-1$
-
- static SimpleAttribute parseString(String value) {
- Matcher m = REGEXP.matcher(value);
- if (m.matches()) {
- return new SimpleAttribute(m.group(2), m.group(1), m.group(3));
- }
-
- return null;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj instanceof SimpleAttribute) {
- SimpleAttribute sa = (SimpleAttribute) obj;
-
- return mName.equals(sa.mName) &&
- mUri.equals(sa.mUri) &&
- mValue.equals(sa.mValue);
- }
- return false;
- }
-
- @Override
- public int hashCode() {
- long c = mName.hashCode();
- // uses the formula defined in java.util.List.hashCode()
- c = 31*c + mUri.hashCode();
- c = 31*c + mValue.hashCode();
- if (c > 0x0FFFFFFFFL) {
- // wrap any overflow
- c = c ^ (c >> 32);
- }
- return (int)(c & 0x0FFFFFFFFL);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SimpleElement.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SimpleElement.java
deleted file mode 100644
index 9acc8c25e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SimpleElement.java
+++ /dev/null
@@ -1,370 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.IDragElement;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.Rect;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Represents an XML element with a name, attributes and inner elements.
- * <p/>
- * The semantic of the element name is to be a fully qualified class name of a View to inflate.
- * The element name is not expected to have a name space.
- * <p/>
- * For a more detailed explanation of the purpose of this class,
- * please see {@link SimpleXmlTransfer}.
- */
-public class SimpleElement implements IDragElement {
-
- /** Version number of the internal serialized string format. */
- private static final String FORMAT_VERSION = "3";
-
- private final String mFqcn;
- private final String mParentFqcn;
- private final Rect mBounds;
- private final Rect mParentBounds;
- private final List<IDragAttribute> mAttributes = new ArrayList<IDragAttribute>();
- private final List<IDragElement> mElements = new ArrayList<IDragElement>();
-
- private IDragAttribute[] mCachedAttributes = null;
- private IDragElement[] mCachedElements = null;
- private SelectionItem mSelectionItem;
-
- /**
- * Creates a new {@link SimpleElement} with the specified element name.
- *
- * @param fqcn A fully qualified class name of a View to inflate, e.g.
- * "android.view.Button". Must not be null nor empty.
- * @param parentFqcn The fully qualified class name of the parent of this element.
- * Can be null but not empty.
- * @param bounds The canvas bounds of the originating canvas node of the element.
- * If null, a non-null invalid rectangle will be assigned.
- * @param parentBounds The canvas bounds of the parent of this element. Can be null.
- */
- public SimpleElement(String fqcn, String parentFqcn, Rect bounds, Rect parentBounds) {
- mFqcn = fqcn;
- mParentFqcn = parentFqcn;
- mBounds = bounds == null ? new Rect() : bounds.copy();
- mParentBounds = parentBounds == null ? new Rect() : parentBounds.copy();
- }
-
- /**
- * Returns the element name, which must match a fully qualified class name of
- * a View to inflate.
- */
- @Override
- public @NonNull String getFqcn() {
- return mFqcn;
- }
-
- /**
- * Returns the bounds of the element's node, if it originated from an existing
- * canvas. The rectangle is invalid and non-null when the element originated
- * from the object palette (unless it successfully rendered a preview)
- */
- @Override
- public @NonNull Rect getBounds() {
- return mBounds;
- }
-
- /**
- * Returns the fully qualified class name of the parent, if the element originated
- * from an existing canvas. Returns null if the element has no parent, such as a top
- * level element or an element originating from the object palette.
- */
- @Override
- public String getParentFqcn() {
- return mParentFqcn;
- }
-
- /**
- * Returns the bounds of the element's parent, absolute for the canvas, or null if there
- * is no suitable parent. This is null when {@link #getParentFqcn()} is null.
- */
- @Override
- public @NonNull Rect getParentBounds() {
- return mParentBounds;
- }
-
- @Override
- public @NonNull IDragAttribute[] getAttributes() {
- if (mCachedAttributes == null) {
- mCachedAttributes = mAttributes.toArray(new IDragAttribute[mAttributes.size()]);
- }
- return mCachedAttributes;
- }
-
- @Override
- public IDragAttribute getAttribute(@Nullable String uri, @NonNull String localName) {
- for (IDragAttribute attr : mAttributes) {
- if (attr.getUri().equals(uri) && attr.getName().equals(localName)) {
- return attr;
- }
- }
-
- return null;
- }
-
- @Override
- public @NonNull IDragElement[] getInnerElements() {
- if (mCachedElements == null) {
- mCachedElements = mElements.toArray(new IDragElement[mElements.size()]);
- }
- return mCachedElements;
- }
-
- public void addAttribute(SimpleAttribute attr) {
- mCachedAttributes = null;
- mAttributes.add(attr);
- }
-
- public void addInnerElement(SimpleElement e) {
- mCachedElements = null;
- mElements.add(e);
- }
-
- @Override
- public boolean isSame(@NonNull INode node) {
- if (mSelectionItem != null) {
- return node == mSelectionItem.getNode();
- } else {
- return node.getBounds().equals(mBounds);
- }
- }
-
- void setSelectionItem(@Nullable SelectionItem selectionItem) {
- mSelectionItem = selectionItem;
- }
-
- @Nullable
- SelectionItem getSelectionItem() {
- return mSelectionItem;
- }
-
- @Nullable
- static SimpleElement findPrimary(SimpleElement[] elements, SelectionItem primary) {
- if (elements == null || elements.length == 0) {
- return null;
- }
-
- if (elements.length == 1 || primary == null) {
- return elements[0];
- }
-
- for (SimpleElement element : elements) {
- if (element.getSelectionItem() == primary) {
- return element;
- }
- }
-
- return elements[0];
- }
-
- // reader and writer methods
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append("{V=").append(FORMAT_VERSION);
- sb.append(",N=").append(mFqcn);
- if (mParentFqcn != null) {
- sb.append(",P=").append(mParentFqcn);
- }
- if (mBounds != null && mBounds.isValid()) {
- sb.append(String.format(",R=%d %d %d %d", mBounds.x, mBounds.y, mBounds.w, mBounds.h));
- }
- if (mParentBounds != null && mParentBounds.isValid()) {
- sb.append(String.format(",Q=%d %d %d %d",
- mParentBounds.x, mParentBounds.y, mParentBounds.w, mParentBounds.h));
- }
- sb.append('\n');
- for (IDragAttribute a : mAttributes) {
- sb.append(a.toString());
- }
- for (IDragElement e : mElements) {
- sb.append(e.toString());
- }
- sb.append("}\n"); //$NON-NLS-1$
- return sb.toString();
- }
-
- /** Parses a string containing one or more elements. */
- static SimpleElement[] parseString(String value) {
- ArrayList<SimpleElement> elements = new ArrayList<SimpleElement>();
- String[] lines = value.split("\n");
- int[] index = new int[] { 0 };
- SimpleElement element = null;
- while ((element = parseLines(lines, index)) != null) {
- elements.add(element);
- }
- return elements.toArray(new SimpleElement[elements.size()]);
- }
-
- /**
- * Parses one element from the input lines array, starting at the inOutIndex
- * and updating the inOutIndex to match the next unread line on output.
- */
- private static SimpleElement parseLines(String[] lines, int[] inOutIndex) {
- SimpleElement e = null;
- int index = inOutIndex[0];
- while (index < lines.length) {
- String line = lines[index++];
- String s = line.trim();
- if (s.startsWith("{")) { //$NON-NLS-1$
- if (e == null) {
- // This is the element's header, it should have
- // the format "key=value,key=value,..."
- String version = null;
- String fqcn = null;
- String parent = null;
- Rect bounds = null;
- Rect pbounds = null;
-
- for (String s2 : s.substring(1).split(",")) { //$NON-NLS-1$
- int pos = s2.indexOf('=');
- if (pos <= 0 || pos == s2.length() - 1) {
- continue;
- }
- String key = s2.substring(0, pos).trim();
- String value = s2.substring(pos + 1).trim();
-
- if (key.equals("V")) { //$NON-NLS-1$
- version = value;
- if (!value.equals(FORMAT_VERSION)) {
- // Wrong format version. Don't even try to process anything
- // else and just give up everything.
- inOutIndex[0] = index;
- return null;
- }
-
- } else if (key.equals("N")) { //$NON-NLS-1$
- fqcn = value;
-
- } else if (key.equals("P")) { //$NON-NLS-1$
- parent = value;
-
- } else if (key.equals("R") || key.equals("Q")) { //$NON-NLS-1$ //$NON-NLS-2$
- // Parse the canvas bounds
- String[] sb = value.split(" +"); //$NON-NLS-1$
- if (sb != null && sb.length == 4) {
- Rect r = null;
- try {
- r = new Rect();
- r.x = Integer.parseInt(sb[0]);
- r.y = Integer.parseInt(sb[1]);
- r.w = Integer.parseInt(sb[2]);
- r.h = Integer.parseInt(sb[3]);
-
- if (key.equals("R")) {
- bounds = r;
- } else {
- pbounds = r;
- }
- } catch (NumberFormatException ignore) {
- }
- }
- }
- }
-
- // We need at least a valid name to recreate an element
- if (version != null && fqcn != null && fqcn.length() > 0) {
- e = new SimpleElement(fqcn, parent, bounds, pbounds);
- }
- } else {
- // This is an inner element... need to parse the { line again.
- inOutIndex[0] = index - 1;
- SimpleElement e2 = SimpleElement.parseLines(lines, inOutIndex);
- if (e2 != null) {
- e.addInnerElement(e2);
- }
- index = inOutIndex[0];
- }
-
- } else if (e != null && s.startsWith("@")) { //$NON-NLS-1$
- SimpleAttribute a = SimpleAttribute.parseString(line);
- if (a != null) {
- e.addAttribute(a);
- }
-
- } else if (e != null && s.startsWith("}")) { //$NON-NLS-1$
- // We're done with this element
- inOutIndex[0] = index;
- return e;
- }
- }
- inOutIndex[0] = index;
- return null;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj instanceof SimpleElement) {
- SimpleElement se = (SimpleElement) obj;
-
- // Bounds and parentFqcn must be null on both sides or equal.
- if ((mBounds == null && se.mBounds != null) ||
- (mBounds != null && !mBounds.equals(se.mBounds))) {
- return false;
- }
- if ((mParentFqcn == null && se.mParentFqcn != null) ||
- (mParentFqcn != null && !mParentFqcn.equals(se.mParentFqcn))) {
- return false;
- }
- if ((mParentBounds == null && se.mParentBounds != null) ||
- (mParentBounds != null && !mParentBounds.equals(se.mParentBounds))) {
- return false;
- }
-
- return mFqcn.equals(se.mFqcn) &&
- mAttributes.size() == se.mAttributes.size() &&
- mElements.size() == se.mElements.size() &&
- mAttributes.equals(se.mAttributes) &&
- mElements.equals(se.mElements);
- }
- return false;
- }
-
- @Override
- public int hashCode() {
- long c = mFqcn.hashCode();
- // uses the formula defined in java.util.List.hashCode()
- c = 31*c + mAttributes.hashCode();
- c = 31*c + mElements.hashCode();
- if (mParentFqcn != null) {
- c = 31*c + mParentFqcn.hashCode();
- }
- if (mBounds != null && mBounds.isValid()) {
- c = 31*c + mBounds.hashCode();
- }
- if (mParentBounds != null && mParentBounds.isValid()) {
- c = 31*c + mParentBounds.hashCode();
- }
-
- if (c > 0x0FFFFFFFFL) {
- // wrap any overflow
- c = c ^ (c >> 32);
- }
- return (int)(c & 0x0FFFFFFFFL);
- }
-}
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SimpleXmlTransfer.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SimpleXmlTransfer.java
deleted file mode 100644
index 20ac2033e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SimpleXmlTransfer.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-
-import org.eclipse.swt.dnd.ByteArrayTransfer;
-import org.eclipse.swt.dnd.TransferData;
-
-import java.io.UnsupportedEncodingException;
-
-/**
- * A d'n'd {@link Transfer} class that can transfer a <em>simplified</em> XML fragment
- * to transfer elements and their attributes between {@link LayoutCanvas}.
- * <p/>
- * The implementation is based on the {@link ByteArrayTransfer} and what we transfer
- * is text with the following fixed format:
- * <p/>
- * <pre>
- * {element-name element-property ...
- * attrib_name="attrib_value"
- * attrib2="..."
- * {...inner elements...
- * }
- * }
- * {...next element...
- * }
- *
- * </pre>
- * The format has nothing to do with XML per se, except for the fact that the
- * transfered content represents XML elements and XML attributes.
- *
- * <p/>
- * The detailed syntax is:
- * <pre>
- * - ELEMENT := {NAME PROPERTY*\nATTRIB_LINE*ELEMENT*}\n
- * - PROPERTY := $[A-Z]=[^ ]*
- * - NAME := [^\n=]+
- * - ATTRIB_LINE := @URI:NAME=[^\n]*\n
- * </pre>
- *
- * Elements are represented by {@link SimpleElement}s and their attributes by
- * {@link SimpleAttribute}s, all of which have very specific properties that are
- * specifically limited to our needs for drag'n'drop.
- */
-final class SimpleXmlTransfer extends ByteArrayTransfer {
-
- // Reference: http://www.eclipse.org/articles/Article-SWT-DND/DND-in-SWT.html
-
- private static final String TYPE_NAME = "android.ADT.simple.xml.transfer.1"; //$NON-NLS-1$
- private static final int TYPE_ID = registerType(TYPE_NAME);
- private static final SimpleXmlTransfer sInstance = new SimpleXmlTransfer();
-
- /** Private constructor. Use {@link #getInstance()} to retrieve the singleton instance. */
- private SimpleXmlTransfer() {
- // pass
- }
-
- /** Returns the singleton instance. */
- public static SimpleXmlTransfer getInstance() {
- return sInstance;
- }
-
- /**
- * Helper method that returns the FQCN transfered for the given {@link ElementDescriptor}.
- * <p/>
- * If the descriptor is a {@link ViewElementDescriptor}, the transfered data is the FQCN
- * of the Android View class represented (e.g. "android.widget.Button").
- * For any other non-null descriptor, the XML name is used.
- * Otherwise it is null.
- *
- * @param desc The {@link ElementDescriptor} to transfer.
- * @return The FQCN, XML name or null.
- */
- public static String getFqcn(ElementDescriptor desc) {
- if (desc instanceof ViewElementDescriptor) {
- return ((ViewElementDescriptor) desc).getFullClassName();
- } else if (desc != null) {
- return desc.getXmlName();
- }
-
- return null;
- }
-
- @Override
- protected int[] getTypeIds() {
- return new int[] { TYPE_ID };
- }
-
- @Override
- protected String[] getTypeNames() {
- return new String[] { TYPE_NAME };
- }
-
- /** Transforms a array of {@link SimpleElement} into a native data transfer. */
- @Override
- protected void javaToNative(Object object, TransferData transferData) {
- if (object == null || !(object instanceof SimpleElement[])) {
- return;
- }
-
- if (isSupportedType(transferData)) {
- StringBuilder sb = new StringBuilder();
- for (SimpleElement e : (SimpleElement[]) object) {
- sb.append(e.toString());
- }
- String data = sb.toString();
-
- try {
- byte[] buf = data.getBytes("UTF-8"); //$NON-NLS-1$
- super.javaToNative(buf, transferData);
- } catch (UnsupportedEncodingException e) {
- // unlikely; ignore
- }
- }
- }
-
- /**
- * Recreates an array of {@link SimpleElement} from a native data transfer.
- *
- * @return An array of {@link SimpleElement} or null. The array may be empty.
- */
- @Override
- protected Object nativeToJava(TransferData transferData) {
- if (isSupportedType(transferData)) {
- byte[] buf = (byte[]) super.nativeToJava(transferData);
- if (buf != null && buf.length > 0) {
- try {
- String s = new String(buf, "UTF-8"); //$NON-NLS-1$
- return SimpleElement.parseString(s);
- } catch (UnsupportedEncodingException e) {
- // unlikely to happen, but still possible
- }
- }
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SubmenuAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SubmenuAction.java
deleted file mode 100644
index 0923dda79..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SubmenuAction.java
+++ /dev/null
@@ -1,75 +0,0 @@
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.ActionContributionItem;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuCreator;
-import org.eclipse.swt.events.MenuEvent;
-import org.eclipse.swt.events.MenuListener;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.MenuItem;
-
-/**
- * Action which creates a submenu that is dynamically populated by subclasses
- */
-public abstract class SubmenuAction extends Action implements MenuListener, IMenuCreator {
- private Menu mMenu;
-
- public SubmenuAction(String title) {
- super(title, IAction.AS_DROP_DOWN_MENU);
- }
-
- @Override
- public IMenuCreator getMenuCreator() {
- return this;
- }
-
- @Override
- public void dispose() {
- if (mMenu != null) {
- mMenu.dispose();
- mMenu = null;
- }
- }
-
- @Override
- public Menu getMenu(Control parent) {
- return null;
- }
-
- @Override
- public Menu getMenu(Menu parent) {
- mMenu = new Menu(parent);
- mMenu.addMenuListener(this);
- return mMenu;
- }
-
- @Override
- public void menuHidden(MenuEvent e) {
- }
-
- protected abstract void addMenuItems(Menu menu);
-
- @Override
- public void menuShown(MenuEvent e) {
- // TODO: Replace this stuff with manager.setRemoveAllWhenShown(true);
- MenuItem[] menuItems = mMenu.getItems();
- for (int i = 0; i < menuItems.length; i++) {
- menuItems[i].dispose();
- }
- addMenuItems(mMenu);
- }
-
- protected void addDisabledMessageItem(String message) {
- IAction action = new Action(message, IAction.AS_PUSH_BUTTON) {
- @Override
- public void run() {
- }
- };
- action.setEnabled(false);
- new ActionContributionItem(action).fill(mMenu, -1);
-
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SwtDrawingStyle.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SwtDrawingStyle.java
deleted file mode 100644
index 93a33283c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SwtDrawingStyle.java
+++ /dev/null
@@ -1,319 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.ide.common.api.DrawingStyle;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.RGB;
-
-/**
- * Description of the drawing styles with specific color, line style and alpha
- * definitions. This class corresponds to the more generic {@link DrawingStyle}
- * class which defines the drawing styles but does not introduce any specific
- * SWT values to the API clients.
- * <p>
- * TODO: This class should eventually be replaced by a scheme where the color
- * constants are instead coming from the theme.
- */
-public enum SwtDrawingStyle {
- /**
- * The style definition corresponding to {@link DrawingStyle#SELECTION}
- */
- SELECTION(new RGB(0x00, 0x99, 0xFF), 192, new RGB(0x00, 0x99, 0xFF), 192, 1, SWT.LINE_SOLID),
-
- /**
- * The style definition corresponding to {@link DrawingStyle#GUIDELINE}
- */
- GUIDELINE(new RGB(0x00, 0xAA, 0x00), 192, SWT.LINE_SOLID),
-
- /**
- * The style definition corresponding to {@link DrawingStyle#GUIDELINE}
- */
- GUIDELINE_SHADOW(new RGB(0x00, 0xAA, 0x00), 192, SWT.LINE_SOLID),
-
- /**
- * The style definition corresponding to {@link DrawingStyle#GUIDELINE_DASHED}
- */
- GUIDELINE_DASHED(new RGB(0x00, 0xAA, 0x00), 192, SWT.LINE_CUSTOM),
-
- /**
- * The style definition corresponding to {@link DrawingStyle#DISTANCE}
- */
- DISTANCE(new RGB(0xFF, 0x00, 0x00), 192 - 32, SWT.LINE_SOLID),
-
- /**
- * The style definition corresponding to {@link DrawingStyle#GRID}
- */
- GRID(new RGB(0xAA, 0xAA, 0xAA), 128, SWT.LINE_SOLID),
-
- /**
- * The style definition corresponding to {@link DrawingStyle#HOVER}
- */
- HOVER(null, 0, new RGB(0xFF, 0xFF, 0xFF), 40, 1, SWT.LINE_DOT),
-
- /**
- * The style definition corresponding to {@link DrawingStyle#HOVER}
- */
- HOVER_SELECTION(null, 0, new RGB(0xFF, 0xFF, 0xFF), 10, 1, SWT.LINE_DOT),
-
- /**
- * The style definition corresponding to {@link DrawingStyle#ANCHOR}
- */
- ANCHOR(new RGB(0x00, 0x99, 0xFF), 96, SWT.LINE_SOLID),
-
- /**
- * The style definition corresponding to {@link DrawingStyle#OUTLINE}
- */
- OUTLINE(new RGB(0x88, 0xFF, 0x88), 160, SWT.LINE_SOLID),
-
- /**
- * The style definition corresponding to {@link DrawingStyle#DROP_RECIPIENT}
- */
- DROP_RECIPIENT(new RGB(0xFF, 0x99, 0x00), 255, new RGB(0xFF, 0x99, 0x00), 160, 2,
- SWT.LINE_SOLID),
-
- /**
- * The style definition corresponding to {@link DrawingStyle#DROP_ZONE}
- */
- DROP_ZONE(new RGB(0x00, 0xAA, 0x00), 220, new RGB(0x55, 0xAA, 0x00), 200, 1, SWT.LINE_SOLID),
-
- /**
- * The style definition corresponding to
- * {@link DrawingStyle#DROP_ZONE_ACTIVE}
- */
- DROP_ZONE_ACTIVE(new RGB(0x00, 0xAA, 0x00), 220, new RGB(0x00, 0xAA, 0x00), 128, 2,
- SWT.LINE_SOLID),
-
- /**
- * The style definition corresponding to {@link DrawingStyle#DROP_PREVIEW}
- */
- DROP_PREVIEW(new RGB(0xFF, 0x99, 0x00), 255, null, 0, 2, SWT.LINE_CUSTOM),
-
- /**
- * The style definition corresponding to {@link DrawingStyle#RESIZE_PREVIEW}
- */
- RESIZE_PREVIEW(new RGB(0xFF, 0x99, 0x00), 255, null, 0, 2, SWT.LINE_SOLID),
-
- /**
- * The style used to show a proposed resize bound which is being rejected (for example,
- * because there is no near edge to attach to in a RelativeLayout).
- */
- RESIZE_FAIL(new RGB(0xFF, 0x99, 0x00), 255, null, 0, 2, SWT.LINE_CUSTOM),
-
- /**
- * The style definition corresponding to {@link DrawingStyle#HELP}
- */
- HELP(new RGB(0xFF, 0xFF, 0xFF), 255, new RGB(0x00, 0x00, 0x00), 128, 1, SWT.LINE_SOLID),
-
- /**
- * The style definition corresponding to {@link DrawingStyle#INVALID}
- */
- INVALID(new RGB(0xFF, 0xFF, 0xFF), 255, new RGB(0xFF, 0x00, 0x00), 64, 2, SWT.LINE_SOLID),
-
- /**
- * The style definition corresponding to {@link DrawingStyle#DEPENDENCY}
- */
- DEPENDENCY(new RGB(0xFF, 0xFF, 0xFF), 255, new RGB(0xFF, 0xFF, 0x00), 24, 2, SWT.LINE_SOLID),
-
- /**
- * The style definition corresponding to {@link DrawingStyle#CYCLE}
- */
- CYCLE(new RGB(0xFF, 0x00, 0x00), 192, null, 0, 1, SWT.LINE_SOLID),
-
- /**
- * The style definition corresponding to {@link DrawingStyle#DRAGGED}
- */
- DRAGGED(new RGB(0xFF, 0xFF, 0xFF), 255, new RGB(0x00, 0xFF, 0x00), 16, 2, SWT.LINE_SOLID),
-
- /**
- * The style definition corresponding to {@link DrawingStyle#EMPTY}
- */
- EMPTY(new RGB(0xFF, 0xFF, 0x55), 255, new RGB(0xFF, 0xFF, 0x55), 255, 1, SWT.LINE_DASH),
-
- /**
- * The style definition corresponding to {@link DrawingStyle#CUSTOM1}
- */
- CUSTOM1(new RGB(0xFF, 0x00, 0xFF), 255, null, 0, 1, SWT.LINE_SOLID),
-
- /**
- * The style definition corresponding to {@link DrawingStyle#CUSTOM2}
- */
- CUSTOM2(new RGB(0x00, 0xFF, 0xFF), 255, null, 0, 1, SWT.LINE_DOT);
-
- /**
- * Construct a new style value with the given foreground, background, width,
- * linestyle and transparency.
- *
- * @param stroke A color descriptor for the foreground color, or null if no
- * foreground color should be set
- * @param fill A color descriptor for the background color, or null if no
- * foreground color should be set
- * @param lineWidth The line width, in pixels, or 0 if no line width should
- * be set
- * @param lineStyle The SWT line style - such as {@link SWT#LINE_SOLID}.
- * @param strokeAlpha The alpha value of the stroke, an integer in the range 0 to 255
- * where 0 is fully transparent and 255 is fully opaque.
- * @param fillAlpha The alpha value of the fill, an integer in the range 0 to 255
- * where 0 is fully transparent and 255 is fully opaque.
- */
- private SwtDrawingStyle(RGB stroke, int strokeAlpha, RGB fill, int fillAlpha, int lineWidth,
- int lineStyle) {
- mStroke = stroke;
- mFill = fill;
- mLineWidth = lineWidth;
- mLineStyle = lineStyle;
- mStrokeAlpha = strokeAlpha;
- mFillAlpha = fillAlpha;
- }
-
- /**
- * Convenience constructor for typical drawing styles, which do not specify
- * a fill and use a standard thickness line
- *
- * @param stroke Stroke color to be used (e.g. for the border/foreground)
- * @param strokeAlpha Transparency to use for the stroke; 0 is transparent
- * and 255 is fully opaque.
- * @param lineStyle The SWT line style - such as {@link SWT#LINE_SOLID}.
- */
- private SwtDrawingStyle(RGB stroke, int strokeAlpha, int lineStyle) {
- this(stroke, strokeAlpha, null, 255, 1, lineStyle);
- }
-
- /**
- * Return the stroke/foreground/border RGB color description to be used for
- * this style, or null if none
- */
- public RGB getStrokeColor() {
- return mStroke;
- }
-
- /**
- * Return the fill/background/interior RGB color description to be used for
- * this style, or null if none
- */
- public RGB getFillColor() {
- return mFill;
- }
-
- /** Return the line width to be used for this style */
- public int getLineWidth() {
- return mLineWidth;
- }
-
- /** Return the SWT line style to be used for this style */
- public int getLineStyle() {
- return mLineStyle;
- }
-
- /**
- * Return the stroke alpha value (in the range 0,255) to be used for this
- * style
- */
- public int getStrokeAlpha() {
- return mStrokeAlpha;
- }
-
- /**
- * Return the fill alpha value (in the range 0,255) to be used for this
- * style
- */
- public int getFillAlpha() {
- return mFillAlpha;
- }
-
- /**
- * Return the corresponding SwtDrawingStyle for the given
- * {@link DrawingStyle}
- * @param style The style to convert from a {@link DrawingStyle} to a {@link SwtDrawingStyle}.
- * @return A corresponding {@link SwtDrawingStyle}.
- */
- public static SwtDrawingStyle of(DrawingStyle style) {
- switch (style) {
- case SELECTION:
- return SELECTION;
- case GUIDELINE:
- return GUIDELINE;
- case GUIDELINE_SHADOW:
- return GUIDELINE_SHADOW;
- case GUIDELINE_DASHED:
- return GUIDELINE_DASHED;
- case DISTANCE:
- return DISTANCE;
- case GRID:
- return GRID;
- case HOVER:
- return HOVER;
- case HOVER_SELECTION:
- return HOVER_SELECTION;
- case ANCHOR:
- return ANCHOR;
- case OUTLINE:
- return OUTLINE;
- case DROP_ZONE:
- return DROP_ZONE;
- case DROP_ZONE_ACTIVE:
- return DROP_ZONE_ACTIVE;
- case DROP_RECIPIENT:
- return DROP_RECIPIENT;
- case DROP_PREVIEW:
- return DROP_PREVIEW;
- case RESIZE_PREVIEW:
- return RESIZE_PREVIEW;
- case RESIZE_FAIL:
- return RESIZE_FAIL;
- case HELP:
- return HELP;
- case INVALID:
- return INVALID;
- case DEPENDENCY:
- return DEPENDENCY;
- case CYCLE:
- return CYCLE;
- case DRAGGED:
- return DRAGGED;
- case EMPTY:
- return EMPTY;
- case CUSTOM1:
- return CUSTOM1;
- case CUSTOM2:
- return CUSTOM2;
-
- // Internal error
- default:
- throw new IllegalArgumentException("Unknown style " + style);
- }
- }
-
- /** RGB description of the stroke/foreground/border color */
- private final RGB mStroke;
-
- /** RGB description of the fill/foreground/interior color */
- private final RGB mFill;
-
- /** Pixel thickness of the stroke/border */
- private final int mLineWidth;
-
- /** SWT line style of the border/stroke */
- private final int mLineStyle;
-
- /** Alpha (in the range 0-255) of the stroke/border */
- private final int mStrokeAlpha;
-
- /** Alpha (in the range 0-255) of the fill/interior */
- private final int mFillAlpha;
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SwtUtils.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SwtUtils.java
deleted file mode 100644
index 64e91bedf..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SwtUtils.java
+++ /dev/null
@@ -1,457 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.ide.eclipse.adt.internal.editors.layout.gle2.ImageUtils.SHADOW_SIZE;
-
-import com.android.ide.common.api.Rect;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-
-import org.eclipse.swt.SWTException;
-import org.eclipse.swt.graphics.Device;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.FontMetrics;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.ImageData;
-import org.eclipse.swt.graphics.PaletteData;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-
-import java.awt.Graphics;
-import java.awt.image.BufferedImage;
-import java.awt.image.DataBuffer;
-import java.awt.image.DataBufferByte;
-import java.awt.image.DataBufferInt;
-import java.awt.image.WritableRaster;
-import java.util.List;
-
-/**
- * Various generic SWT utilities such as image conversion.
- */
-public class SwtUtils {
-
- private SwtUtils() {
- }
-
- /**
- * Returns the {@link PaletteData} describing the ARGB ordering expected from integers
- * representing pixels for AWT {@link BufferedImage}.
- *
- * @param imageType the {@link BufferedImage#getType()} type
- * @return A new {@link PaletteData} suitable for AWT images.
- */
- public static PaletteData getAwtPaletteData(int imageType) {
- switch (imageType) {
- case BufferedImage.TYPE_INT_RGB:
- case BufferedImage.TYPE_INT_ARGB:
- case BufferedImage.TYPE_INT_ARGB_PRE:
- return new PaletteData(0x00FF0000, 0x0000FF00, 0x000000FF);
-
- case BufferedImage.TYPE_3BYTE_BGR:
- case BufferedImage.TYPE_4BYTE_ABGR:
- case BufferedImage.TYPE_4BYTE_ABGR_PRE:
- return new PaletteData(0x000000FF, 0x0000FF00, 0x00FF0000);
-
- default:
- throw new UnsupportedOperationException("RGB type not supported yet.");
- }
- }
-
- /**
- * Returns true if the given type of {@link BufferedImage} is supported for
- * conversion. For unsupported formats, use
- * {@link #convertToCompatibleFormat(BufferedImage)} first.
- *
- * @param imageType the {@link BufferedImage#getType()}
- * @return true if we can convert the given buffered image format
- */
- private static boolean isSupportedPaletteType(int imageType) {
- switch (imageType) {
- case BufferedImage.TYPE_INT_RGB:
- case BufferedImage.TYPE_INT_ARGB:
- case BufferedImage.TYPE_INT_ARGB_PRE:
- case BufferedImage.TYPE_3BYTE_BGR:
- case BufferedImage.TYPE_4BYTE_ABGR:
- case BufferedImage.TYPE_4BYTE_ABGR_PRE:
- return true;
- default:
- return false;
- }
- }
-
- /** Converts the given arbitrary {@link BufferedImage} to another {@link BufferedImage}
- * in a format that is supported (see {@link #isSupportedPaletteType(int)})
- *
- * @param image the image to be converted
- * @return a new image that is in a guaranteed compatible format
- */
- private static BufferedImage convertToCompatibleFormat(BufferedImage image) {
- BufferedImage converted = new BufferedImage(image.getWidth(), image.getHeight(),
- BufferedImage.TYPE_INT_ARGB);
- Graphics graphics = converted.getGraphics();
- graphics.drawImage(image, 0, 0, null);
- graphics.dispose();
-
- return converted;
- }
-
- /**
- * Converts an AWT {@link BufferedImage} into an equivalent SWT {@link Image}. Whether
- * the transparency data is transferred is optional, and this method can also apply an
- * alpha adjustment during the conversion.
- * <p/>
- * Implementation details: on Windows, the returned {@link Image} will have an ordering
- * matching the Windows DIB (e.g. RGBA, not ARGB). Callers must make sure to use
- * <code>Image.getImageData().paletteData</code> to get the right pixels out of the image.
- *
- * @param display The display where the SWT image will be shown
- * @param awtImage The AWT {@link BufferedImage}
- * @param transferAlpha If true, copy alpha data out of the source image
- * @param globalAlpha If -1, do nothing, otherwise adjust the alpha of the final image
- * by the given amount in the range [0,255]
- * @return A new SWT {@link Image} with the same contents as the source
- * {@link BufferedImage}
- */
- public static Image convertToSwt(Device display, BufferedImage awtImage,
- boolean transferAlpha, int globalAlpha) {
- if (!isSupportedPaletteType(awtImage.getType())) {
- awtImage = convertToCompatibleFormat(awtImage);
- }
-
- int width = awtImage.getWidth();
- int height = awtImage.getHeight();
-
- WritableRaster raster = awtImage.getRaster();
- DataBuffer dataBuffer = raster.getDataBuffer();
- ImageData imageData =
- new ImageData(width, height, 32, getAwtPaletteData(awtImage.getType()));
-
- if (dataBuffer instanceof DataBufferInt) {
- int[] imageDataBuffer = ((DataBufferInt) dataBuffer).getData();
- imageData.setPixels(0, 0, imageDataBuffer.length, imageDataBuffer, 0);
- } else if (dataBuffer instanceof DataBufferByte) {
- byte[] imageDataBuffer = ((DataBufferByte) dataBuffer).getData();
- try {
- imageData.setPixels(0, 0, imageDataBuffer.length, imageDataBuffer, 0);
- } catch (SWTException se) {
- // Unsupported depth
- return convertToSwt(display, convertToCompatibleFormat(awtImage),
- transferAlpha, globalAlpha);
- }
- }
-
- if (transferAlpha) {
- byte[] alphaData = new byte[height * width];
- for (int y = 0; y < height; y++) {
- byte[] alphaRow = new byte[width];
- for (int x = 0; x < width; x++) {
- int alpha = awtImage.getRGB(x, y) >>> 24;
-
- // We have to multiply in the alpha now since if we
- // set ImageData.alpha, it will ignore the alphaData.
- if (globalAlpha != -1) {
- alpha = alpha * globalAlpha >> 8;
- }
-
- alphaRow[x] = (byte) alpha;
- }
- System.arraycopy(alphaRow, 0, alphaData, y * width, width);
- }
-
- imageData.alphaData = alphaData;
- } else if (globalAlpha != -1) {
- imageData.alpha = globalAlpha;
- }
-
- return new Image(display, imageData);
- }
-
- /**
- * Converts a direct-color model SWT image to an equivalent AWT image. If the image
- * does not have a supported color model, returns null. This method does <b>NOT</b>
- * preserve alpha in the source image.
- *
- * @param swtImage the SWT image to be converted to AWT
- * @return an AWT image representing the source SWT image
- */
- public static BufferedImage convertToAwt(Image swtImage) {
- ImageData swtData = swtImage.getImageData();
- BufferedImage awtImage =
- new BufferedImage(swtData.width, swtData.height, BufferedImage.TYPE_INT_ARGB);
- PaletteData swtPalette = swtData.palette;
- if (swtPalette.isDirect) {
- PaletteData awtPalette = getAwtPaletteData(awtImage.getType());
-
- if (swtPalette.equals(awtPalette)) {
- // No color conversion needed.
- for (int y = 0; y < swtData.height; y++) {
- for (int x = 0; x < swtData.width; x++) {
- int pixel = swtData.getPixel(x, y);
- awtImage.setRGB(x, y, 0xFF000000 | pixel);
- }
- }
- } else {
- // We need to remap the colors
- int sr = -awtPalette.redShift + swtPalette.redShift;
- int sg = -awtPalette.greenShift + swtPalette.greenShift;
- int sb = -awtPalette.blueShift + swtPalette.blueShift;
-
- for (int y = 0; y < swtData.height; y++) {
- for (int x = 0; x < swtData.width; x++) {
- int pixel = swtData.getPixel(x, y);
-
- int r = pixel & swtPalette.redMask;
- int g = pixel & swtPalette.greenMask;
- int b = pixel & swtPalette.blueMask;
- r = (sr < 0) ? r >>> -sr : r << sr;
- g = (sg < 0) ? g >>> -sg : g << sg;
- b = (sb < 0) ? b >>> -sb : b << sb;
-
- pixel = 0xFF000000 | r | g | b;
- awtImage.setRGB(x, y, pixel);
- }
- }
- }
- } else {
- return null;
- }
-
- return awtImage;
- }
-
- /**
- * Creates a new image from a source image where the contents from a given set of
- * bounding boxes are copied into the new image and the rest is left transparent. A
- * scale can be applied to make the resulting image larger or smaller than the source
- * image. Note that the alpha channel in the original image is ignored, and the alpha
- * values for the painted rectangles will be set to a specific value passed into this
- * function.
- *
- * @param image the source image
- * @param rectangles the set of rectangles (bounding boxes) to copy from the source
- * image
- * @param boundingBox the bounding rectangle of the rectangle list, which can be
- * computed by {@link ImageUtils#getBoundingRectangle}
- * @param scale a scale factor to apply to the result, e.g. 0.5 to shrink the
- * destination down 50%, 1.0 to leave it alone and 2.0 to zoom in by
- * doubling the image size
- * @param alpha the alpha (in the range 0-255) that painted bits should be set to
- * @return a pair of the rendered cropped image, and the location within the source
- * image that the crop begins (multiplied by the scale). May return null if
- * there are no selected items.
- */
- public static Image drawRectangles(Image image,
- List<Rectangle> rectangles, Rectangle boundingBox, double scale, byte alpha) {
-
- if (rectangles.size() == 0 || boundingBox == null || boundingBox.isEmpty()) {
- return null;
- }
-
- ImageData srcData = image.getImageData();
- int destWidth = (int) (scale * boundingBox.width);
- int destHeight = (int) (scale * boundingBox.height);
-
- ImageData destData = new ImageData(destWidth, destHeight, srcData.depth, srcData.palette);
- byte[] alphaData = new byte[destHeight * destWidth];
- destData.alphaData = alphaData;
-
- for (Rectangle bounds : rectangles) {
- int dx1 = bounds.x - boundingBox.x;
- int dy1 = bounds.y - boundingBox.y;
- int dx2 = dx1 + bounds.width;
- int dy2 = dy1 + bounds.height;
-
- dx1 *= scale;
- dy1 *= scale;
- dx2 *= scale;
- dy2 *= scale;
-
- int sx1 = bounds.x;
- int sy1 = bounds.y;
- int sx2 = sx1 + bounds.width;
- int sy2 = sy1 + bounds.height;
-
- if (scale == 1.0d) {
- for (int dy = dy1, sy = sy1; dy < dy2; dy++, sy++) {
- for (int dx = dx1, sx = sx1; dx < dx2; dx++, sx++) {
- destData.setPixel(dx, dy, srcData.getPixel(sx, sy));
- alphaData[dy * destWidth + dx] = alpha;
- }
- }
- } else {
- // Scaled copy.
- int sxDelta = sx2 - sx1;
- int dxDelta = dx2 - dx1;
- int syDelta = sy2 - sy1;
- int dyDelta = dy2 - dy1;
- for (int dy = dy1, sy = sy1; dy < dy2; dy++, sy = (dy - dy1) * syDelta / dyDelta
- + sy1) {
- for (int dx = dx1, sx = sx1; dx < dx2; dx++, sx = (dx - dx1) * sxDelta
- / dxDelta + sx1) {
- assert sx < sx2 && sy < sy2;
- destData.setPixel(dx, dy, srcData.getPixel(sx, sy));
- alphaData[dy * destWidth + dx] = alpha;
- }
- }
- }
- }
-
- return new Image(image.getDevice(), destData);
- }
-
- /**
- * Creates a new empty/blank image of the given size
- *
- * @param display the display to associate the image with
- * @param width the width of the image
- * @param height the height of the image
- * @return a new blank image of the given size
- */
- public static Image createEmptyImage(Display display, int width, int height) {
- BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
- return SwtUtils.convertToSwt(display, image, false, 0);
- }
-
- /**
- * Converts the given SWT {@link Rectangle} into an ADT {@link Rect}
- *
- * @param swtRect the SWT {@link Rectangle}
- * @return an equivalent {@link Rect}
- */
- public static Rect toRect(Rectangle swtRect) {
- return new Rect(swtRect.x, swtRect.y, swtRect.width, swtRect.height);
- }
-
- /**
- * Sets the values of the given ADT {@link Rect} to the values of the given SWT
- * {@link Rectangle}
- *
- * @param target the ADT {@link Rect} to modify
- * @param source the SWT {@link Rectangle} to read values from
- */
- public static void set(Rect target, Rectangle source) {
- target.set(source.x, source.y, source.width, source.height);
- }
-
- /**
- * Compares an ADT {@link Rect} with an SWT {@link Rectangle} and returns true if they
- * are equivalent
- *
- * @param r1 the ADT {@link Rect}
- * @param r2 the SWT {@link Rectangle}
- * @return true if the two rectangles are equivalent
- */
- public static boolean equals(Rect r1, Rectangle r2) {
- return r1.x == r2.x && r1.y == r2.y && r1.w == r2.width && r1.h == r2.height;
-
- }
-
- /**
- * Get the average width of the font used by the given control
- *
- * @param display the display associated with the font usage
- * @param font the font to look up the average character width for
- * @return the average width, in pixels, of the given font
- */
- public static final int getAverageCharWidth(Display display, Font font) {
- GC gc = new GC(display);
- gc.setFont(font);
- FontMetrics fontMetrics = gc.getFontMetrics();
- int width = fontMetrics.getAverageCharWidth();
- gc.dispose();
- return width;
- }
-
- /**
- * Get the average width of the given font
- *
- * @param control the control to look up the default font for
- * @return the average width, in pixels, of the current font in the control
- */
- public static final int getAverageCharWidth(Control control) {
- GC gc = new GC(control.getDisplay());
- int width = gc.getFontMetrics().getAverageCharWidth();
- gc.dispose();
- return width;
- }
-
- /**
- * Draws a drop shadow for the given rectangle into the given context. It
- * will not draw anything if the rectangle is smaller than a minimum
- * determined by the assets used to draw the shadow graphics.
- * <p>
- * This corresponds to {@link ImageUtils#drawRectangleShadow(Graphics, int, int, int, int)},
- * but applied directly to an SWT graphics context instead, such that no image conversion
- * has to be performed.
- * <p>
- * Make sure to keep changes in the visual appearance here in sync with the
- * AWT version in {@link ImageUtils#drawRectangleShadow(Graphics, int, int, int, int)}.
- *
- * @param gc the graphics context to draw into
- * @param x the left coordinate of the left hand side of the rectangle
- * @param y the top coordinate of the top of the rectangle
- * @param width the width of the rectangle
- * @param height the height of the rectangle
- */
- public static final void drawRectangleShadow(GC gc, int x, int y, int width, int height) {
- if (sShadowBottomLeft == null) {
- IconFactory icons = IconFactory.getInstance();
- // See ImageUtils.drawRectangleShadow for an explanation of the assets.
- sShadowBottomLeft = icons.getIcon("shadow-bl"); //$NON-NLS-1$
- sShadowBottom = icons.getIcon("shadow-b"); //$NON-NLS-1$
- sShadowBottomRight = icons.getIcon("shadow-br"); //$NON-NLS-1$
- sShadowRight = icons.getIcon("shadow-r"); //$NON-NLS-1$
- sShadowTopRight = icons.getIcon("shadow-tr"); //$NON-NLS-1$
- assert sShadowBottomRight.getImageData().width == SHADOW_SIZE;
- assert sShadowBottomRight.getImageData().height == SHADOW_SIZE;
- }
-
- ImageData bottomLeftData = sShadowBottomLeft.getImageData();
- ImageData topRightData = sShadowTopRight.getImageData();
- ImageData bottomData = sShadowBottom.getImageData();
- ImageData rightData = sShadowRight.getImageData();
- int blWidth = bottomLeftData.width;
- int trHeight = topRightData.height;
- if (width < blWidth) {
- return;
- }
- if (height < trHeight) {
- return;
- }
-
- gc.drawImage(sShadowBottomLeft, x, y + height);
- gc.drawImage(sShadowBottomRight, x + width, y + height);
- gc.drawImage(sShadowTopRight, x + width, y);
- gc.drawImage(sShadowBottom,
- 0, 0,
- bottomData.width, bottomData.height,
- x + bottomLeftData.width, y + height,
- width - bottomLeftData.width, bottomData.height);
- gc.drawImage(sShadowRight,
- 0, 0,
- rightData.width, rightData.height,
- x + width, y + topRightData.height,
- rightData.width, height - topRightData.height);
- }
-
- private static Image sShadowBottomLeft;
- private static Image sShadowBottom;
- private static Image sShadowBottomRight;
- private static Image sShadowRight;
- private static Image sShadowTopRight;
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ViewHierarchy.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ViewHierarchy.java
deleted file mode 100644
index d247e28d7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ViewHierarchy.java
+++ /dev/null
@@ -1,771 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.VIEW_MERGE;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.rendering.api.RenderSession;
-import com.android.ide.common.rendering.api.ViewInfo;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.NodeProxy;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiDocumentNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.utils.Pair;
-
-import org.eclipse.swt.graphics.Rectangle;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-
-import java.awt.image.BufferedImage;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.RandomAccess;
-import java.util.Set;
-
-/**
- * The view hierarchy class manages a set of view info objects and performs find
- * operations on this set.
- */
-public class ViewHierarchy {
- private static final boolean DUMP_INFO = false;
-
- private LayoutCanvas mCanvas;
-
- /**
- * Constructs a new {@link ViewHierarchy} tied to the given
- * {@link LayoutCanvas}.
- *
- * @param canvas The {@link LayoutCanvas} to create a {@link ViewHierarchy}
- * for.
- */
- public ViewHierarchy(LayoutCanvas canvas) {
- mCanvas = canvas;
- }
-
- /**
- * The CanvasViewInfo root created by the last call to {@link #setSession}
- * with a valid layout.
- * <p/>
- * This <em>can</em> be null to indicate we're dealing with an empty document with
- * no root node. Null here does not mean the result was invalid, merely that the XML
- * had no content to display -- we need to treat an empty document as valid so that
- * we can drop new items in it.
- */
- private CanvasViewInfo mLastValidViewInfoRoot;
-
- /**
- * True when the last {@link #setSession} provided a valid {@link LayoutScene}.
- * <p/>
- * When false this means the canvas is displaying an out-dated result image & bounds and some
- * features should be disabled accordingly such a drag'n'drop.
- * <p/>
- * Note that an empty document (with a null {@link #mLastValidViewInfoRoot}) is considered
- * valid since it is an acceptable drop target.
- */
- private boolean mIsResultValid;
-
- /**
- * A list of invisible parents (see {@link CanvasViewInfo#isInvisible()} for
- * details) in the current view hierarchy.
- */
- private final List<CanvasViewInfo> mInvisibleParents = new ArrayList<CanvasViewInfo>();
-
- /**
- * A read-only view of {@link #mInvisibleParents}; note that this is NOT a copy so it
- * reflects updates to the underlying {@link #mInvisibleParents} list.
- */
- private final List<CanvasViewInfo> mInvisibleParentsReadOnly =
- Collections.unmodifiableList(mInvisibleParents);
-
- /**
- * Flag which records whether or not we have any exploded parent nodes in this
- * view hierarchy. This is used to track whether or not we need to recompute the
- * layout when we exit show-all-invisible-parents mode (see
- * {@link LayoutCanvas#showInvisibleViews}).
- */
- private boolean mExplodedParents;
-
- /**
- * Bounds of included views in the current view hierarchy when rendered in other context
- */
- private List<Rectangle> mIncludedBounds;
-
- /** The render session for the current view hierarchy */
- private RenderSession mSession;
-
- /** Map from nodes to canvas view infos */
- private Map<UiViewElementNode, CanvasViewInfo> mNodeToView = Collections.emptyMap();
-
- /** Map from DOM nodes to canvas view infos */
- private Map<Node, CanvasViewInfo> mDomNodeToView = Collections.emptyMap();
-
- /**
- * Disposes the view hierarchy content.
- */
- public void dispose() {
- if (mSession != null) {
- mSession.dispose();
- mSession = null;
- }
- }
-
-
- /**
- * Sets the result of the layout rendering. The result object indicates if the layout
- * rendering succeeded. If it did, it contains a bitmap and the objects rectangles.
- *
- * Implementation detail: the bridge's computeLayout() method already returns a newly
- * allocated ILayourResult. That means we can keep this result and hold on to it
- * when it is valid.
- *
- * @param session The new session, either valid or not.
- * @param explodedNodes The set of individual nodes the layout computer was asked to
- * explode. Note that these are independent of the explode-all mode where
- * all views are exploded; this is used only for the mode (
- * {@link LayoutCanvas#showInvisibleViews}) where individual invisible
- * nodes are padded during certain interactions.
- */
- /* package */ void setSession(RenderSession session, Set<UiElementNode> explodedNodes,
- boolean layoutlib5) {
- // replace the previous scene, so the previous scene must be disposed.
- if (mSession != null) {
- mSession.dispose();
- }
-
- mSession = session;
- mIsResultValid = (session != null && session.getResult().isSuccess());
- mExplodedParents = false;
- mNodeToView = new HashMap<UiViewElementNode, CanvasViewInfo>(50);
- if (mIsResultValid && session != null) {
- List<ViewInfo> rootList = session.getRootViews();
-
- Pair<CanvasViewInfo,List<Rectangle>> infos = null;
-
- if (rootList == null || rootList.size() == 0) {
- // Special case: Look to see if this is really an empty <merge> view,
- // which shows up without any ViewInfos in the merge. In that case we
- // want to manufacture an empty view, such that we can target the view
- // via drag & drop, etc.
- if (hasMergeRoot()) {
- ViewInfo mergeRoot = createMergeInfo(session);
- infos = CanvasViewInfo.create(mergeRoot, layoutlib5);
- } else {
- infos = null;
- }
- } else {
- if (rootList.size() > 1 && hasMergeRoot()) {
- ViewInfo mergeRoot = createMergeInfo(session);
- mergeRoot.setChildren(rootList);
- infos = CanvasViewInfo.create(mergeRoot, layoutlib5);
- } else {
- ViewInfo root = rootList.get(0);
-
- if (root != null) {
- infos = CanvasViewInfo.create(root, layoutlib5);
- if (DUMP_INFO) {
- dump(session, root, 0);
- }
- } else {
- infos = null;
- }
- }
- }
- if (infos != null) {
- mLastValidViewInfoRoot = infos.getFirst();
- mIncludedBounds = infos.getSecond();
-
- if (mLastValidViewInfoRoot.getUiViewNode() == null &&
- mLastValidViewInfoRoot.getChildren().isEmpty()) {
- GraphicalEditorPart editor = mCanvas.getEditorDelegate().getGraphicalEditor();
- if (editor.getIncludedWithin() != null) {
- // Somehow, this view was supposed to be rendered within another
- // view, yet this view was rendered as part of the other view.
- // In that case, abort attempting to show included in; clear the
- // include context and trigger a standalone re-render.
- editor.showIn(null);
- return;
- }
- }
-
- } else {
- mLastValidViewInfoRoot = null;
- mIncludedBounds = null;
- }
-
- updateNodeProxies(mLastValidViewInfoRoot);
-
- // Update the data structures related to tracking invisible and exploded nodes.
- // We need to find the {@link CanvasViewInfo} objects that correspond to
- // the passed in {@link UiElementNode} keys that were re-rendered, and mark
- // them as exploded and store them in a list for rendering.
- mExplodedParents = false;
- mInvisibleParents.clear();
- addInvisibleParents(mLastValidViewInfoRoot, explodedNodes);
-
- mDomNodeToView = new HashMap<Node, CanvasViewInfo>(mNodeToView.size());
- for (Map.Entry<UiViewElementNode, CanvasViewInfo> entry : mNodeToView.entrySet()) {
- mDomNodeToView.put(entry.getKey().getXmlNode(), entry.getValue());
- }
-
- // Update the selection
- mCanvas.getSelectionManager().sync();
- } else {
- mIncludedBounds = null;
- mInvisibleParents.clear();
- mDomNodeToView = Collections.emptyMap();
- }
- }
-
- private ViewInfo createMergeInfo(RenderSession session) {
- BufferedImage image = session.getImage();
- ControlPoint imageSize = ControlPoint.create(mCanvas,
- mCanvas.getHorizontalTransform().getMargin() + image.getWidth(),
- mCanvas.getVerticalTransform().getMargin() + image.getHeight());
- LayoutPoint layoutSize = imageSize.toLayout();
- UiDocumentNode model = mCanvas.getEditorDelegate().getUiRootNode();
- List<UiElementNode> children = model.getUiChildren();
- return new ViewInfo(VIEW_MERGE, children.get(0), 0, 0, layoutSize.x, layoutSize.y);
- }
-
- /**
- * Returns true if this view hierarchy corresponds to an editor that has a {@code
- * <merge>} tag at the root
- *
- * @return true if there is a {@code <merge>} at the root of this editor's document
- */
- private boolean hasMergeRoot() {
- UiDocumentNode model = mCanvas.getEditorDelegate().getUiRootNode();
- if (model != null) {
- List<UiElementNode> children = model.getUiChildren();
- if (children != null && children.size() > 0
- && VIEW_MERGE.equals(children.get(0).getDescriptor().getXmlName())) {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Creates or updates the node proxy for this canvas view info.
- * <p/>
- * Since proxies are reused, this will update the bounds of an existing proxy when the
- * canvas is refreshed and a view changes position or size.
- * <p/>
- * This is a recursive call that updates the whole hierarchy starting at the given
- * view info.
- */
- private void updateNodeProxies(CanvasViewInfo vi) {
- if (vi == null) {
- return;
- }
-
- UiViewElementNode key = vi.getUiViewNode();
-
- if (key != null) {
- mCanvas.getNodeFactory().create(vi);
- mNodeToView.put(key, vi);
- }
-
- for (CanvasViewInfo child : vi.getChildren()) {
- updateNodeProxies(child);
- }
- }
-
- /**
- * Make a pass over the view hierarchy and look for two things:
- * <ol>
- * <li>Invisible parents. These are nodes that can hold children and have empty
- * bounds. These are then added to the {@link #mInvisibleParents} list.
- * <li>Exploded nodes. These are nodes that were previously marked as invisible, and
- * subsequently rendered by a recomputed layout. They now no longer have empty bounds,
- * but should be specially marked via {@link CanvasViewInfo#setExploded} such that we
- * for example in selection operations can determine if we need to recompute the
- * layout.
- * </ol>
- *
- * @param vi
- * @param invisibleNodes
- */
- private void addInvisibleParents(CanvasViewInfo vi, Set<UiElementNode> invisibleNodes) {
- if (vi == null) {
- return;
- }
-
- if (vi.isInvisible()) {
- mInvisibleParents.add(vi);
- } else if (invisibleNodes != null) {
- UiViewElementNode key = vi.getUiViewNode();
-
- if (key != null && invisibleNodes.contains(key)) {
- vi.setExploded(true);
- mExplodedParents = true;
- mInvisibleParents.add(vi);
- }
- }
-
- for (CanvasViewInfo child : vi.getChildren()) {
- addInvisibleParents(child, invisibleNodes);
- }
- }
-
- /**
- * Returns the current {@link RenderSession}.
- * @return the session or null if none have been set.
- */
- public RenderSession getSession() {
- return mSession;
- }
-
- /**
- * Returns true when the last {@link #setSession} provided a valid
- * {@link RenderSession}.
- * <p/>
- * When false this means the canvas is displaying an out-dated result image & bounds and some
- * features should be disabled accordingly such a drag'n'drop.
- * <p/>
- * Note that an empty document (with a null {@link #getRoot()}) is considered
- * valid since it is an acceptable drop target.
- * @return True when this {@link ViewHierarchy} contains a valid hierarchy of views.
- */
- public boolean isValid() {
- return mIsResultValid;
- }
-
- /**
- * Returns true if the last valid content of the canvas represents an empty document.
- * @return True if the last valid content of the canvas represents an empty document.
- */
- public boolean isEmpty() {
- return mLastValidViewInfoRoot == null;
- }
-
- /**
- * Returns true if we have parents in this hierarchy that are invisible (e.g. because
- * they have no children and zero layout bounds).
- *
- * @return True if we have invisible parents.
- */
- public boolean hasInvisibleParents() {
- return mInvisibleParents.size() > 0;
- }
-
- /**
- * Returns true if we have views that were exploded during rendering
- * @return True if we have exploded parents
- */
- public boolean hasExplodedParents() {
- return mExplodedParents;
- }
-
- /** Locates and return any views that overlap the given selection rectangle.
- * @param topLeft The top left corner of the selection rectangle.
- * @param bottomRight The bottom right corner of the selection rectangle.
- * @return A collection of {@link CanvasViewInfo} objects that overlap the
- * rectangle.
- */
- public Collection<CanvasViewInfo> findWithin(
- LayoutPoint topLeft,
- LayoutPoint bottomRight) {
- Rectangle selectionRectangle = new Rectangle(topLeft.x, topLeft.y, bottomRight.x
- - topLeft.x, bottomRight.y - topLeft.y);
- List<CanvasViewInfo> infos = new ArrayList<CanvasViewInfo>();
- addWithin(mLastValidViewInfoRoot, selectionRectangle, infos);
- return infos;
- }
-
- /**
- * Recursive internal version of {@link #findViewInfoAt(int, int)}. Please don't use directly.
- * <p/>
- * Tries to find the inner most child matching the given x,y coordinates in the view
- * info sub-tree. This uses the potentially-expanded selection bounds.
- *
- * Returns null if not found.
- */
- private void addWithin(
- CanvasViewInfo canvasViewInfo,
- Rectangle canvasRectangle,
- List<CanvasViewInfo> infos) {
- if (canvasViewInfo == null) {
- return;
- }
- Rectangle r = canvasViewInfo.getSelectionRect();
- if (canvasRectangle.intersects(r)) {
-
- // try to find a matching child first
- for (CanvasViewInfo child : canvasViewInfo.getChildren()) {
- addWithin(child, canvasRectangle, infos);
- }
-
- if (canvasViewInfo != mLastValidViewInfoRoot) {
- infos.add(canvasViewInfo);
- }
- }
- }
-
- /**
- * Locates and returns the {@link CanvasViewInfo} corresponding to the given
- * node, or null if it cannot be found.
- *
- * @param node The node we want to find a corresponding
- * {@link CanvasViewInfo} for.
- * @return The {@link CanvasViewInfo} corresponding to the given node, or
- * null if no match was found.
- */
- @Nullable
- public CanvasViewInfo findViewInfoFor(@Nullable Node node) {
- CanvasViewInfo vi = mDomNodeToView.get(node);
-
- if (vi == null) {
- if (node == null) {
- return null;
- } else if (node.getNodeType() == Node.TEXT_NODE) {
- return mDomNodeToView.get(node.getParentNode());
- } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
- return mDomNodeToView.get(((Attr) node).getOwnerElement());
- } else if (node.getNodeType() == Node.DOCUMENT_NODE) {
- return mDomNodeToView.get(((Document) node).getDocumentElement());
- }
- }
-
- return vi;
- }
-
- /**
- * Tries to find the inner most child matching the given x,y coordinates in
- * the view info sub-tree, starting at the last know view info root. This
- * uses the potentially-expanded selection bounds.
- * <p/>
- * Returns null if not found or if there's no view info root.
- *
- * @param p The point at which to look for the deepest match in the view
- * hierarchy
- * @return A {@link CanvasViewInfo} that intersects the given point, or null
- * if nothing was found.
- */
- public CanvasViewInfo findViewInfoAt(LayoutPoint p) {
- if (mLastValidViewInfoRoot == null) {
- return null;
- }
-
- return findViewInfoAt_Recursive(p, mLastValidViewInfoRoot);
- }
-
- /**
- * Recursive internal version of {@link #findViewInfoAt(int, int)}. Please don't use directly.
- * <p/>
- * Tries to find the inner most child matching the given x,y coordinates in the view
- * info sub-tree. This uses the potentially-expanded selection bounds.
- *
- * Returns null if not found.
- */
- private CanvasViewInfo findViewInfoAt_Recursive(LayoutPoint p, CanvasViewInfo canvasViewInfo) {
- if (canvasViewInfo == null) {
- return null;
- }
- Rectangle r = canvasViewInfo.getSelectionRect();
- if (r.contains(p.x, p.y)) {
-
- // try to find a matching child first
- // Iterate in REVERSE z order such that siblings on top
- // are checked before earlier siblings (this matters in layouts like
- // FrameLayout and in <merge> contexts where the views are sitting on top
- // of each other and we want to select the same view as the one drawn
- // on top of the others
- List<CanvasViewInfo> children = canvasViewInfo.getChildren();
- assert children instanceof RandomAccess;
- for (int i = children.size() - 1; i >= 0; i--) {
- CanvasViewInfo child = children.get(i);
- CanvasViewInfo v = findViewInfoAt_Recursive(p, child);
- if (v != null) {
- return v;
- }
- }
-
- // if no children matched, this is the view that we're looking for
- return canvasViewInfo;
- }
-
- return null;
- }
-
- /**
- * Returns a list of all the possible alternatives for a given view at the given
- * position. This is used to build and manage the "alternate" selection that cycles
- * around the parents or children of the currently selected element.
- */
- /* package */ List<CanvasViewInfo> findAltViewInfoAt(LayoutPoint p) {
- if (mLastValidViewInfoRoot != null) {
- return findAltViewInfoAt_Recursive(p, mLastValidViewInfoRoot, null);
- }
-
- return null;
- }
-
- /**
- * Internal recursive version of {@link #findAltViewInfoAt(int, int, CanvasViewInfo)}.
- * Please don't use directly.
- */
- private List<CanvasViewInfo> findAltViewInfoAt_Recursive(
- LayoutPoint p, CanvasViewInfo parent, List<CanvasViewInfo> outList) {
- Rectangle r;
-
- if (outList == null) {
- outList = new ArrayList<CanvasViewInfo>();
-
- if (parent != null) {
- // add the parent root only once
- r = parent.getSelectionRect();
- if (r.contains(p.x, p.y)) {
- outList.add(parent);
- }
- }
- }
-
- if (parent != null && !parent.getChildren().isEmpty()) {
- // then add all children that match the position
- for (CanvasViewInfo child : parent.getChildren()) {
- r = child.getSelectionRect();
- if (r.contains(p.x, p.y)) {
- outList.add(child);
- }
- }
-
- // finally recurse in the children
- for (CanvasViewInfo child : parent.getChildren()) {
- r = child.getSelectionRect();
- if (r.contains(p.x, p.y)) {
- findAltViewInfoAt_Recursive(p, child, outList);
- }
- }
- }
-
- return outList;
- }
-
- /**
- * Locates and returns the {@link CanvasViewInfo} corresponding to the given
- * node, or null if it cannot be found.
- *
- * @param node The node we want to find a corresponding
- * {@link CanvasViewInfo} for.
- * @return The {@link CanvasViewInfo} corresponding to the given node, or
- * null if no match was found.
- */
- public CanvasViewInfo findViewInfoFor(INode node) {
- return findViewInfoFor((NodeProxy) node);
- }
-
- /**
- * Tries to find a child with the same view key in the view info sub-tree.
- * Returns null if not found.
- *
- * @param viewKey The view key that a matching {@link CanvasViewInfo} should
- * have as its key.
- * @return A {@link CanvasViewInfo} matching the given key, or null if not
- * found.
- */
- public CanvasViewInfo findViewInfoFor(UiElementNode viewKey) {
- return mNodeToView.get(viewKey);
- }
-
- /**
- * Tries to find a child with the given node proxy as the view key.
- * Returns null if not found.
- *
- * @param proxy The view key that a matching {@link CanvasViewInfo} should
- * have as its key.
- * @return A {@link CanvasViewInfo} matching the given key, or null if not
- * found.
- */
- @Nullable
- public CanvasViewInfo findViewInfoFor(@Nullable NodeProxy proxy) {
- if (proxy == null) {
- return null;
- }
- return mNodeToView.get(proxy.getNode());
- }
-
- /**
- * Returns a list of ALL ViewInfos (possibly excluding the root, depending
- * on the parameter for that).
- *
- * @param includeRoot If true, include the root in the list, otherwise
- * exclude it (but include all its children)
- * @return A list of canvas view infos.
- */
- public List<CanvasViewInfo> findAllViewInfos(boolean includeRoot) {
- List<CanvasViewInfo> infos = new ArrayList<CanvasViewInfo>();
- if (mIsResultValid && mLastValidViewInfoRoot != null) {
- findAllViewInfos(infos, mLastValidViewInfoRoot, includeRoot);
- }
-
- return infos;
- }
-
- private void findAllViewInfos(List<CanvasViewInfo> result, CanvasViewInfo canvasViewInfo,
- boolean includeRoot) {
- if (canvasViewInfo != null) {
- if (includeRoot || !canvasViewInfo.isRoot()) {
- result.add(canvasViewInfo);
- }
- for (CanvasViewInfo child : canvasViewInfo.getChildren()) {
- findAllViewInfos(result, child, true);
- }
- }
- }
-
- /**
- * Returns the root of the view hierarchy, if any (could be null, for example
- * on rendering failure).
- *
- * @return The current view hierarchy, or null
- */
- public CanvasViewInfo getRoot() {
- return mLastValidViewInfoRoot;
- }
-
- /**
- * Returns a collection of views that have zero bounds and that correspond to empty
- * parents. Note that the views may not actually have zero bounds; in particular, if
- * they are exploded ({@link CanvasViewInfo#isExploded()}, then they will have the
- * bounds of a shown invisible node. Therefore, this method returns the views that
- * would be invisible in a real rendering of the scene.
- *
- * @return A collection of empty parent views.
- */
- public List<CanvasViewInfo> getInvisibleViews() {
- return mInvisibleParentsReadOnly;
- }
-
- /**
- * Returns the invisible nodes (the {@link UiElementNode} objects corresponding
- * to the {@link CanvasViewInfo} objects returned from {@link #getInvisibleViews()}.
- * We are pulling out the nodes since they preserve their identity across layout
- * rendering, and in particular we return it as a set such that the layout renderer
- * can perform quick identity checks when looking up attribute values during the
- * rendering process.
- *
- * @return A set of the invisible nodes.
- */
- public Set<UiElementNode> getInvisibleNodes() {
- if (mInvisibleParents.size() == 0) {
- return Collections.emptySet();
- }
-
- Set<UiElementNode> nodes = new HashSet<UiElementNode>(mInvisibleParents.size());
- for (CanvasViewInfo info : mInvisibleParents) {
- UiViewElementNode node = info.getUiViewNode();
- if (node != null) {
- nodes.add(node);
- }
- }
-
- return nodes;
- }
-
- /**
- * Returns the list of bounds for included views in the current view hierarchy. Can be null
- * when there are no included views.
- *
- * @return a list of included view bounds, or null
- */
- public List<Rectangle> getIncludedBounds() {
- return mIncludedBounds;
- }
-
- /**
- * Returns a map of the default properties for the given view object in this session
- *
- * @param viewObject the object to look up the properties map for
- * @return the map of properties, or null if not found
- */
- @Nullable
- public Map<String, String> getDefaultProperties(@NonNull Object viewObject) {
- if (mSession != null) {
- return mSession.getDefaultProperties(viewObject);
- }
-
- return null;
- }
-
- /**
- * Dumps a {@link ViewInfo} hierarchy to stdout
- *
- * @param session the corresponding session, if any
- * @param info the {@link ViewInfo} object to dump
- * @param depth the depth to indent it to
- */
- public static void dump(RenderSession session, ViewInfo info, int depth) {
- if (DUMP_INFO) {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < depth; i++) {
- sb.append(" "); //$NON-NLS-1$
- }
- sb.append(info.getClassName());
- sb.append(" ["); //$NON-NLS-1$
- sb.append(info.getLeft());
- sb.append(","); //$NON-NLS-1$
- sb.append(info.getTop());
- sb.append(","); //$NON-NLS-1$
- sb.append(info.getRight());
- sb.append(","); //$NON-NLS-1$
- sb.append(info.getBottom());
- sb.append("]"); //$NON-NLS-1$
- Object cookie = info.getCookie();
- if (cookie instanceof UiViewElementNode) {
- sb.append(" "); //$NON-NLS-1$
- UiViewElementNode node = (UiViewElementNode) cookie;
- sb.append("<"); //$NON-NLS-1$
- sb.append(node.getDescriptor().getXmlName());
- sb.append(">"); //$NON-NLS-1$
-
- String id = node.getAttributeValue(ATTR_ID);
- if (id != null && !id.isEmpty()) {
- sb.append(" ");
- sb.append(id);
- }
- } else if (cookie != null) {
- sb.append(" " + cookie); //$NON-NLS-1$
- }
- /* Display defaults?
- if (info.getViewObject() != null) {
- Map<String, String> defaults = session.getDefaultProperties(info.getCookie());
- sb.append(" - defaults: "); //$NON-NLS-1$
- sb.append(defaults);
- sb.append('\n');
- }
- */
-
- System.out.println(sb.toString());
-
- for (ViewInfo child : info.getChildren()) {
- dump(session, child, depth + 1);
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/ClientRulesEngine.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/ClientRulesEngine.java
deleted file mode 100644
index 388907a46..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/ClientRulesEngine.java
+++ /dev/null
@@ -1,762 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gre;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.AUTO_URI;
-import static com.android.SdkConstants.CLASS_FRAGMENT;
-import static com.android.SdkConstants.CLASS_V4_FRAGMENT;
-import static com.android.SdkConstants.CLASS_VIEW;
-import static com.android.SdkConstants.NEW_ID_PREFIX;
-import static com.android.SdkConstants.URI_PREFIX;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.IClientRulesEngine;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IValidator;
-import com.android.ide.common.api.IViewMetadata;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.Margins;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.layout.BaseViewRule;
-import com.android.ide.common.resources.ResourceRepository;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.actions.AddSupportJarAction;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigurationChooser;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.CanvasViewInfo;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.LayoutCanvas;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderService;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.SelectionManager;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.ViewHierarchy;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiDocumentNode;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.refactorings.core.RenameResult;
-import com.android.ide.eclipse.adt.internal.resources.CyclicDependencyValidator;
-import com.android.ide.eclipse.adt.internal.resources.ResourceNameValidator;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.internal.ui.MarginChooser;
-import com.android.ide.eclipse.adt.internal.ui.ReferenceChooserDialog;
-import com.android.ide.eclipse.adt.internal.ui.ResourceChooser;
-import com.android.ide.eclipse.adt.internal.ui.ResourcePreviewHelper;
-import com.android.resources.ResourceType;
-import com.android.sdklib.IAndroidTarget;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jdt.core.Flags;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jdt.core.IPackageFragmentRoot;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.core.ITypeHierarchy;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.core.search.IJavaSearchScope;
-import org.eclipse.jdt.core.search.SearchEngine;
-import org.eclipse.jdt.ui.IJavaElementSearchConstants;
-import org.eclipse.jdt.ui.JavaUI;
-import org.eclipse.jdt.ui.actions.OpenNewClassWizardAction;
-import org.eclipse.jdt.ui.dialogs.ITypeInfoFilterExtension;
-import org.eclipse.jdt.ui.dialogs.ITypeInfoRequestor;
-import org.eclipse.jdt.ui.dialogs.TypeSelectionExtension;
-import org.eclipse.jdt.ui.wizards.NewClassWizardPage;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.IInputValidator;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.dialogs.ProgressMonitorDialog;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.dialogs.SelectionDialog;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicReference;
-
-/**
- * Implementation of {@link IClientRulesEngine}. This provides {@link IViewRule} clients
- * with a few methods they can use to access functionality from this {@link RulesEngine}.
- */
-class ClientRulesEngine implements IClientRulesEngine {
- /** The return code from the dialog for the user choosing "Clear" */
- public static final int CLEAR_RETURN_CODE = -5;
- /** The dialog button ID for the user choosing "Clear" */
- private static final int CLEAR_BUTTON_ID = CLEAR_RETURN_CODE;
-
- private final RulesEngine mRulesEngine;
- private final String mFqcn;
-
- public ClientRulesEngine(RulesEngine rulesEngine, String fqcn) {
- mRulesEngine = rulesEngine;
- mFqcn = fqcn;
- }
-
- @Override
- public @NonNull String getFqcn() {
- return mFqcn;
- }
-
- @Override
- public void debugPrintf(@NonNull String msg, Object... params) {
- AdtPlugin.printToConsole(
- mFqcn == null ? "<unknown>" : mFqcn,
- String.format(msg, params)
- );
- }
-
- @Override
- public IViewRule loadRule(@NonNull String fqcn) {
- return mRulesEngine.loadRule(fqcn, fqcn);
- }
-
- @Override
- public void displayAlert(@NonNull String message) {
- MessageDialog.openInformation(
- AdtPlugin.getShell(),
- mFqcn, // title
- message);
- }
-
- @Override
- public boolean rename(INode node) {
- GraphicalEditorPart editor = mRulesEngine.getEditor();
- SelectionManager manager = editor.getCanvasControl().getSelectionManager();
- RenameResult result = manager.performRename(node, null);
-
- return !result.isCanceled() && !result.isUnavailable();
- }
-
- @Override
- public String displayInput(@NonNull String message, @Nullable String value,
- final @Nullable IValidator filter) {
- IInputValidator validator = null;
- if (filter != null) {
- validator = new IInputValidator() {
- @Override
- public String isValid(String newText) {
- // IValidator has the same interface as SWT's IInputValidator
- try {
- return filter.validate(newText);
- } catch (Exception e) {
- AdtPlugin.log(e, "Custom validator failed: %s", e.toString());
- return ""; //$NON-NLS-1$
- }
- }
- };
- }
-
- InputDialog d = new InputDialog(
- AdtPlugin.getShell(),
- mFqcn, // title
- message,
- value == null ? "" : value, //$NON-NLS-1$
- validator) {
- @Override
- protected void createButtonsForButtonBar(Composite parent) {
- createButton(parent, CLEAR_BUTTON_ID, "Clear", false /*defaultButton*/);
- super.createButtonsForButtonBar(parent);
- }
-
- @Override
- protected void buttonPressed(int buttonId) {
- super.buttonPressed(buttonId);
-
- if (buttonId == CLEAR_BUTTON_ID) {
- assert CLEAR_RETURN_CODE != Window.OK && CLEAR_RETURN_CODE != Window.CANCEL;
- setReturnCode(CLEAR_RETURN_CODE);
- close();
- }
- }
- };
- int result = d.open();
- if (result == ResourceChooser.CLEAR_RETURN_CODE) {
- return "";
- } else if (result == Window.OK) {
- return d.getValue();
- }
- return null;
- }
-
- @Override
- @Nullable
- public Object getViewObject(@NonNull INode node) {
- ViewHierarchy views = mRulesEngine.getEditor().getCanvasControl().getViewHierarchy();
- CanvasViewInfo vi = views.findViewInfoFor(node);
- if (vi != null) {
- return vi.getViewObject();
- }
-
- return null;
- }
-
- @Override
- public @NonNull IViewMetadata getMetadata(final @NonNull String fqcn) {
- return new IViewMetadata() {
- @Override
- public @NonNull String getDisplayName() {
- // This also works when there is no "."
- return fqcn.substring(fqcn.lastIndexOf('.') + 1);
- }
-
- @Override
- public @NonNull FillPreference getFillPreference() {
- return ViewMetadataRepository.get().getFillPreference(fqcn);
- }
-
- @Override
- public @NonNull Margins getInsets() {
- return mRulesEngine.getEditor().getCanvasControl().getInsets(fqcn);
- }
-
- @Override
- public @NonNull List<String> getTopAttributes() {
- return ViewMetadataRepository.get().getTopAttributes(fqcn);
- }
- };
- }
-
- @Override
- public int getMinApiLevel() {
- Sdk currentSdk = Sdk.getCurrent();
- if (currentSdk != null) {
- IAndroidTarget target = currentSdk.getTarget(mRulesEngine.getEditor().getProject());
- if (target != null) {
- return target.getVersion().getApiLevel();
- }
- }
-
- return -1;
- }
-
- @Override
- public IValidator getResourceValidator(
- @NonNull final String resourceTypeName, final boolean uniqueInProject,
- final boolean uniqueInLayout, final boolean exists, final String... allowed) {
- return new IValidator() {
- private ResourceNameValidator mValidator;
-
- @Override
- public String validate(@NonNull String text) {
- if (mValidator == null) {
- ResourceType type = ResourceType.getEnum(resourceTypeName);
- if (uniqueInLayout) {
- assert !uniqueInProject;
- assert !exists;
- Set<String> existing = new HashSet<String>();
- Document doc = mRulesEngine.getEditor().getModel().getXmlDocument();
- if (doc != null) {
- addIds(doc, existing);
- }
- for (String s : allowed) {
- existing.remove(s);
- }
- mValidator = ResourceNameValidator.create(false, existing, type);
- } else {
- assert allowed.length == 0;
- IProject project = mRulesEngine.getEditor().getProject();
- mValidator = ResourceNameValidator.create(false, project, type);
- if (uniqueInProject) {
- mValidator.unique();
- }
- }
- if (exists) {
- mValidator.exist();
- }
- }
-
- return mValidator.isValid(text);
- }
- };
- }
-
- /** Find declared ids under the given DOM node */
- private static void addIds(Node node, Set<String> ids) {
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- Element element = (Element) node;
- String id = element.getAttributeNS(ANDROID_URI, ATTR_ID);
- if (id != null && id.startsWith(NEW_ID_PREFIX)) {
- ids.add(BaseViewRule.stripIdPrefix(id));
- }
- }
-
- NodeList children = node.getChildNodes();
- for (int i = 0, n = children.getLength(); i < n; i++) {
- Node child = children.item(i);
- addIds(child, ids);
- }
- }
-
- @Override
- public String displayReferenceInput(@Nullable String currentValue) {
- GraphicalEditorPart graphicalEditor = mRulesEngine.getEditor();
- LayoutEditorDelegate delegate = graphicalEditor.getEditorDelegate();
- IProject project = delegate.getEditor().getProject();
- if (project != null) {
- // get the resource repository for this project and the system resources.
- ResourceRepository projectRepository =
- ResourceManager.getInstance().getProjectResources(project);
- Shell shell = AdtPlugin.getShell();
- if (shell == null) {
- return null;
- }
- ReferenceChooserDialog dlg = new ReferenceChooserDialog(
- project,
- projectRepository,
- shell);
- dlg.setPreviewHelper(new ResourcePreviewHelper(dlg, graphicalEditor));
-
- dlg.setCurrentResource(currentValue);
-
- if (dlg.open() == Window.OK) {
- return dlg.getCurrentResource();
- }
- }
-
- return null;
- }
-
- @Override
- public String displayResourceInput(@NonNull String resourceTypeName,
- @Nullable String currentValue) {
- return displayResourceInput(resourceTypeName, currentValue, null);
- }
-
- private String displayResourceInput(String resourceTypeName, String currentValue,
- IInputValidator validator) {
- ResourceType type = ResourceType.getEnum(resourceTypeName);
- GraphicalEditorPart graphicalEditor = mRulesEngine.getEditor();
- return ResourceChooser.chooseResource(graphicalEditor, type, currentValue, validator);
- }
-
- @Override
- public String[] displayMarginInput(@Nullable String all, @Nullable String left,
- @Nullable String right, @Nullable String top, @Nullable String bottom) {
- GraphicalEditorPart editor = mRulesEngine.getEditor();
- IProject project = editor.getProject();
- if (project != null) {
- Shell shell = AdtPlugin.getShell();
- if (shell == null) {
- return null;
- }
- AndroidTargetData data = editor.getEditorDelegate().getEditor().getTargetData();
- MarginChooser dialog = new MarginChooser(shell, editor, data, all, left, right,
- top, bottom);
- if (dialog.open() == Window.OK) {
- return dialog.getMargins();
- }
- }
-
- return null;
- }
-
- @Override
- public String displayIncludeSourceInput() {
- AndroidXmlEditor editor = mRulesEngine.getEditor().getEditorDelegate().getEditor();
- IInputValidator validator = CyclicDependencyValidator.create(editor.getInputFile());
- return displayResourceInput(ResourceType.LAYOUT.getName(), null, validator);
- }
-
- @Override
- public void select(final @NonNull Collection<INode> nodes) {
- LayoutCanvas layoutCanvas = mRulesEngine.getEditor().getCanvasControl();
- final SelectionManager selectionManager = layoutCanvas.getSelectionManager();
- selectionManager.select(nodes);
- // ALSO run an async select since immediately after nodes are created they
- // may not be selectable. We can't ONLY run an async exec since
- // code may depend on operating on the selection.
- layoutCanvas.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- selectionManager.select(nodes);
- }
- });
- }
-
- @Override
- public String displayFragmentSourceInput() {
- try {
- // Compute a search scope: We need to merge all the subclasses
- // android.app.Fragment and android.support.v4.app.Fragment
- IJavaSearchScope scope = SearchEngine.createWorkspaceScope();
- IProject project = mRulesEngine.getProject();
- final IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
- if (javaProject != null) {
- IType oldFragmentType = javaProject.findType(CLASS_V4_FRAGMENT);
-
- // First check to make sure fragments are available, and if not,
- // warn the user.
- IAndroidTarget target = Sdk.getCurrent().getTarget(project);
- // No, this should be using the min SDK instead!
- if (target.getVersion().getApiLevel() < 11 && oldFragmentType == null) {
- // Compatibility library must be present
- MessageDialog dialog =
- new MessageDialog(
- Display.getCurrent().getActiveShell(),
- "Fragment Warning",
- null,
- "Fragments require API level 11 or higher, or a compatibility "
- + "library for older versions.\n\n"
- + " Do you want to install the compatibility library?",
- MessageDialog.QUESTION,
- new String[] { "Install", "Cancel" },
- 1 /* default button: Cancel */);
- int answer = dialog.open();
- if (answer == 0) {
- if (!AddSupportJarAction.install(project)) {
- return null;
- }
- } else {
- return null;
- }
- }
-
- // Look up sub-types of each (new fragment class and compatibility fragment
- // class, if any) and merge the two arrays - then create a scope from these
- // elements.
- IType[] fragmentTypes = new IType[0];
- IType[] oldFragmentTypes = new IType[0];
- if (oldFragmentType != null) {
- ITypeHierarchy hierarchy =
- oldFragmentType.newTypeHierarchy(new NullProgressMonitor());
- oldFragmentTypes = hierarchy.getAllSubtypes(oldFragmentType);
- }
- IType fragmentType = javaProject.findType(CLASS_FRAGMENT);
- if (fragmentType != null) {
- ITypeHierarchy hierarchy =
- fragmentType.newTypeHierarchy(new NullProgressMonitor());
- fragmentTypes = hierarchy.getAllSubtypes(fragmentType);
- }
- IType[] subTypes = new IType[fragmentTypes.length + oldFragmentTypes.length];
- System.arraycopy(fragmentTypes, 0, subTypes, 0, fragmentTypes.length);
- System.arraycopy(oldFragmentTypes, 0, subTypes, fragmentTypes.length,
- oldFragmentTypes.length);
- scope = SearchEngine.createJavaSearchScope(subTypes, IJavaSearchScope.SOURCES);
- }
-
- Shell parent = AdtPlugin.getShell();
- final AtomicReference<String> returnValue =
- new AtomicReference<String>();
- final AtomicReference<SelectionDialog> dialogHolder =
- new AtomicReference<SelectionDialog>();
- final SelectionDialog dialog = JavaUI.createTypeDialog(
- parent,
- new ProgressMonitorDialog(parent),
- scope,
- IJavaElementSearchConstants.CONSIDER_CLASSES, false,
- // Use ? as a default filter to fill dialog with matches
- "?", //$NON-NLS-1$
- new TypeSelectionExtension() {
- @Override
- public Control createContentArea(Composite parentComposite) {
- Composite composite = new Composite(parentComposite, SWT.NONE);
- composite.setLayout(new GridLayout(1, false));
- Button button = new Button(composite, SWT.PUSH);
- button.setText("Create New...");
- button.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- String fqcn = createNewFragmentClass(javaProject);
- if (fqcn != null) {
- returnValue.set(fqcn);
- dialogHolder.get().close();
- }
- }
- });
- return composite;
- }
-
- @Override
- public ITypeInfoFilterExtension getFilterExtension() {
- return new ITypeInfoFilterExtension() {
- @Override
- public boolean select(ITypeInfoRequestor typeInfoRequestor) {
- int modifiers = typeInfoRequestor.getModifiers();
- if (!Flags.isPublic(modifiers)
- || Flags.isInterface(modifiers)
- || Flags.isEnum(modifiers)
- || Flags.isAbstract(modifiers)) {
- return false;
- }
- return true;
- }
- };
- }
- });
- dialogHolder.set(dialog);
-
- dialog.setTitle("Choose Fragment Class");
- dialog.setMessage("Select a Fragment class (? = any character, * = any string):");
- if (dialog.open() == IDialogConstants.CANCEL_ID) {
- return null;
- }
- if (returnValue.get() != null) {
- return returnValue.get();
- }
-
- Object[] types = dialog.getResult();
- if (types != null && types.length > 0) {
- return ((IType) types[0]).getFullyQualifiedName();
- }
- } catch (JavaModelException e) {
- AdtPlugin.log(e, null);
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- return null;
- }
-
- @Override
- public String displayCustomViewClassInput() {
- try {
- IJavaSearchScope scope = SearchEngine.createWorkspaceScope();
- IProject project = mRulesEngine.getProject();
- final IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
- if (javaProject != null) {
- // Look up sub-types of each (new fragment class and compatibility fragment
- // class, if any) and merge the two arrays - then create a scope from these
- // elements.
- IType[] viewTypes = new IType[0];
- IType fragmentType = javaProject.findType(CLASS_VIEW);
- if (fragmentType != null) {
- ITypeHierarchy hierarchy =
- fragmentType.newTypeHierarchy(new NullProgressMonitor());
- viewTypes = hierarchy.getAllSubtypes(fragmentType);
- }
- scope = SearchEngine.createJavaSearchScope(viewTypes, IJavaSearchScope.SOURCES);
- }
-
- Shell parent = AdtPlugin.getShell();
- final AtomicReference<String> returnValue =
- new AtomicReference<String>();
- final AtomicReference<SelectionDialog> dialogHolder =
- new AtomicReference<SelectionDialog>();
- final SelectionDialog dialog = JavaUI.createTypeDialog(
- parent,
- new ProgressMonitorDialog(parent),
- scope,
- IJavaElementSearchConstants.CONSIDER_CLASSES, false,
- // Use ? as a default filter to fill dialog with matches
- "?", //$NON-NLS-1$
- new TypeSelectionExtension() {
- @Override
- public Control createContentArea(Composite parentComposite) {
- Composite composite = new Composite(parentComposite, SWT.NONE);
- composite.setLayout(new GridLayout(1, false));
- Button button = new Button(composite, SWT.PUSH);
- button.setText("Create New...");
- button.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- String fqcn = createNewCustomViewClass(javaProject);
- if (fqcn != null) {
- returnValue.set(fqcn);
- dialogHolder.get().close();
- }
- }
- });
- return composite;
- }
-
- @Override
- public ITypeInfoFilterExtension getFilterExtension() {
- return new ITypeInfoFilterExtension() {
- @Override
- public boolean select(ITypeInfoRequestor typeInfoRequestor) {
- int modifiers = typeInfoRequestor.getModifiers();
- if (!Flags.isPublic(modifiers)
- || Flags.isInterface(modifiers)
- || Flags.isEnum(modifiers)
- || Flags.isAbstract(modifiers)) {
- return false;
- }
- return true;
- }
- };
- }
- });
- dialogHolder.set(dialog);
-
- dialog.setTitle("Choose Custom View Class");
- dialog.setMessage("Select a Custom View class (? = any character, * = any string):");
- if (dialog.open() == IDialogConstants.CANCEL_ID) {
- return null;
- }
- if (returnValue.get() != null) {
- return returnValue.get();
- }
-
- Object[] types = dialog.getResult();
- if (types != null && types.length > 0) {
- return ((IType) types[0]).getFullyQualifiedName();
- }
- } catch (JavaModelException e) {
- AdtPlugin.log(e, null);
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- return null;
- }
-
- @Override
- public void redraw() {
- mRulesEngine.getEditor().getCanvasControl().redraw();
- }
-
- @Override
- public void layout() {
- mRulesEngine.getEditor().recomputeLayout();
- }
-
- @Override
- public Map<INode, Rect> measureChildren(@NonNull INode parent,
- @Nullable IClientRulesEngine.AttributeFilter filter) {
- RenderService renderService = RenderService.create(mRulesEngine.getEditor());
- Map<INode, Rect> map = renderService.measureChildren(parent, filter);
- if (map == null) {
- map = Collections.emptyMap();
- }
- return map;
- }
-
- @Override
- public int pxToDp(int px) {
- ConfigurationChooser chooser = mRulesEngine.getEditor().getConfigurationChooser();
- float dpi = chooser.getConfiguration().getDensity().getDpiValue();
- return (int) (px * 160 / dpi);
- }
-
- @Override
- public int dpToPx(int dp) {
- ConfigurationChooser chooser = mRulesEngine.getEditor().getConfigurationChooser();
- float dpi = chooser.getConfiguration().getDensity().getDpiValue();
- return (int) (dp * dpi / 160);
- }
-
- @Override
- public int screenToLayout(int pixels) {
- return (int) (pixels / mRulesEngine.getEditor().getCanvasControl().getScale());
- }
-
- private String createNewFragmentClass(IJavaProject javaProject) {
- NewClassWizardPage page = new NewClassWizardPage();
-
- IProject project = mRulesEngine.getProject();
- Sdk sdk = Sdk.getCurrent();
- if (sdk == null) {
- return null;
- }
- IAndroidTarget target = sdk.getTarget(project);
- String superClass;
- if (target == null || target.getVersion().getApiLevel() < 11) {
- superClass = CLASS_V4_FRAGMENT;
- } else {
- superClass = CLASS_FRAGMENT;
- }
- page.setSuperClass(superClass, true /* canBeModified */);
- IPackageFragmentRoot root = ManifestInfo.getSourcePackageRoot(javaProject);
- if (root != null) {
- page.setPackageFragmentRoot(root, true /* canBeModified */);
- }
- ManifestInfo manifestInfo = ManifestInfo.get(project);
- IPackageFragment pkg = manifestInfo.getPackageFragment();
- if (pkg != null) {
- page.setPackageFragment(pkg, true /* canBeModified */);
- }
- OpenNewClassWizardAction action = new OpenNewClassWizardAction();
- action.setConfiguredWizardPage(page);
- action.run();
- IType createdType = page.getCreatedType();
- if (createdType != null) {
- return createdType.getFullyQualifiedName();
- } else {
- return null;
- }
- }
-
- private String createNewCustomViewClass(IJavaProject javaProject) {
- NewClassWizardPage page = new NewClassWizardPage();
-
- IProject project = mRulesEngine.getProject();
- String superClass = CLASS_VIEW;
- page.setSuperClass(superClass, true /* canBeModified */);
- IPackageFragmentRoot root = ManifestInfo.getSourcePackageRoot(javaProject);
- if (root != null) {
- page.setPackageFragmentRoot(root, true /* canBeModified */);
- }
- ManifestInfo manifestInfo = ManifestInfo.get(project);
- IPackageFragment pkg = manifestInfo.getPackageFragment();
- if (pkg != null) {
- page.setPackageFragment(pkg, true /* canBeModified */);
- }
- OpenNewClassWizardAction action = new OpenNewClassWizardAction();
- action.setConfiguredWizardPage(page);
- action.run();
- IType createdType = page.getCreatedType();
- if (createdType != null) {
- return createdType.getFullyQualifiedName();
- } else {
- return null;
- }
- }
-
- @Override
- public @NonNull String getUniqueId(@NonNull String fqcn) {
- UiDocumentNode root = mRulesEngine.getEditor().getModel();
- String prefix = fqcn.substring(fqcn.lastIndexOf('.') + 1);
- prefix = Character.toLowerCase(prefix.charAt(0)) + prefix.substring(1);
- return DescriptorsUtils.getFreeWidgetId(root, prefix);
- }
-
- @Override
- public @NonNull String getAppNameSpace() {
- IProject project = mRulesEngine.getEditor().getProject();
-
- ProjectState projectState = Sdk.getProjectState(project);
- if (projectState != null && projectState.isLibrary()) {
- return AUTO_URI;
- }
-
- ManifestInfo info = ManifestInfo.get(project);
- return URI_PREFIX + info.getPackage();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/NodeFactory.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/NodeFactory.java
deleted file mode 100644
index b0b9971ba..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/NodeFactory.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gre;
-
-import com.android.ide.common.api.INode;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.CanvasViewInfo;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.LayoutCanvas;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.SwtUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-
-import org.eclipse.swt.graphics.Rectangle;
-
-import java.util.Map;
-import java.util.WeakHashMap;
-
-/**
- * An object that can create {@link INode} proxies.
- * This also keeps references to objects already created and tries to reuse them.
- */
-public class NodeFactory {
-
- private final Map<UiViewElementNode, NodeProxy> mNodeMap =
- new WeakHashMap<UiViewElementNode, NodeProxy>();
- private LayoutCanvas mCanvas;
-
- public NodeFactory(LayoutCanvas canvas) {
- mCanvas = canvas;
- }
-
- /**
- * Returns an {@link INode} proxy based on the view key of the given
- * {@link CanvasViewInfo}. The bounds of the node are set to the canvas view bounds.
- */
- public NodeProxy create(CanvasViewInfo canvasViewInfo) {
- return create(canvasViewInfo.getUiViewNode(), canvasViewInfo.getAbsRect());
- }
-
- /**
- * Returns an {@link INode} proxy based on a given {@link UiViewElementNode} that
- * is not yet part of the canvas, typically those created by layout rules
- * when generating new XML.
- */
- public NodeProxy create(UiViewElementNode uiNode) {
- return create(uiNode, null /*bounds*/);
- }
-
- public void clear() {
- mNodeMap.clear();
- }
-
- public LayoutCanvas getCanvas() {
- return mCanvas;
- }
-
- //----
-
- private NodeProxy create(UiViewElementNode uiNode, Rectangle bounds) {
- NodeProxy proxy = mNodeMap.get(uiNode);
-
- if (proxy == null) {
- // Create a new proxy if the key doesn't exist
- proxy = new NodeProxy(uiNode, bounds, this);
- mNodeMap.put(uiNode, proxy);
-
- } else if (bounds != null && !SwtUtils.equals(proxy.getBounds(), bounds)) {
- // Update the bounds if necessary
- proxy.setBounds(bounds);
- }
-
- return proxy;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/NodeProxy.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/NodeProxy.java
deleted file mode 100644
index 19d5e16b0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/NodeProxy.java
+++ /dev/null
@@ -1,517 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gre;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.IAttributeInfo;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.INodeHandler;
-import com.android.ide.common.api.Margins;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.resources.platform.AttributeInfo;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.CanvasViewInfo;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.SimpleAttribute;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.SwtUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.ViewHierarchy;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiDocumentNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.project.SupportLibraryHelper;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.swt.graphics.Rectangle;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- *
- */
-public class NodeProxy implements INode {
- private static final Margins NO_MARGINS = new Margins(0, 0, 0, 0);
- private final UiViewElementNode mNode;
- private final Rect mBounds;
- private final NodeFactory mFactory;
- /** Map from URI to Map(key=>value) (where no namespace uses "" as a key) */
- private Map<String, Map<String, String>> mPendingAttributes;
-
- /**
- * Creates a new {@link INode} that wraps an {@link UiViewElementNode} that is
- * actually valid in the current UI/XML model. The view may not be part of the canvas
- * yet (e.g. if it has just been dynamically added and the canvas hasn't reloaded yet.)
- * <p/>
- * This method is package protected. To create a node, please use {@link NodeFactory} instead.
- *
- * @param uiNode The node to wrap.
- * @param bounds The bounds of a the view in the canvas. Must be either: <br/>
- * - a valid rect for a view that is actually in the canvas <br/>
- * - <b>*or*</b> null (or an invalid rect) for a view that has just been added dynamically
- * to the model. We never store a null bounds rectangle in the node, a null rectangle
- * will be converted to an invalid rectangle.
- * @param factory A {@link NodeFactory} to create unique children nodes.
- */
- /*package*/ NodeProxy(UiViewElementNode uiNode, Rectangle bounds, NodeFactory factory) {
- mNode = uiNode;
- mFactory = factory;
- if (bounds == null) {
- mBounds = new Rect();
- } else {
- mBounds = SwtUtils.toRect(bounds);
- }
- }
-
- @Override
- public @NonNull Rect getBounds() {
- return mBounds;
- }
-
- @Override
- public @NonNull Margins getMargins() {
- ViewHierarchy viewHierarchy = mFactory.getCanvas().getViewHierarchy();
- CanvasViewInfo view = viewHierarchy.findViewInfoFor(this);
- if (view != null) {
- Margins margins = view.getMargins();
- if (margins != null) {
- return margins;
- }
- }
-
- return NO_MARGINS;
- }
-
-
- @Override
- public int getBaseline() {
- ViewHierarchy viewHierarchy = mFactory.getCanvas().getViewHierarchy();
- CanvasViewInfo view = viewHierarchy.findViewInfoFor(this);
- if (view != null) {
- return view.getBaseline();
- }
-
- return -1;
- }
-
- /**
- * Updates the bounds of this node proxy. Bounds cannot be null, but it can be invalid.
- * This is a package-protected method, only the {@link NodeFactory} uses this method.
- */
- /*package*/ void setBounds(Rectangle bounds) {
- SwtUtils.set(mBounds, bounds);
- }
-
- /**
- * Returns the {@link UiViewElementNode} corresponding to this
- * {@link NodeProxy}.
- *
- * @return The {@link UiViewElementNode} corresponding to this
- * {@link NodeProxy}
- */
- public UiViewElementNode getNode() {
- return mNode;
- }
-
- @Override
- public @NonNull String getFqcn() {
- if (mNode != null) {
- ElementDescriptor desc = mNode.getDescriptor();
- if (desc instanceof ViewElementDescriptor) {
- return ((ViewElementDescriptor) desc).getFullClassName();
- }
- }
-
- return "";
- }
-
-
- // ---- Hierarchy handling ----
-
-
- @Override
- public INode getRoot() {
- if (mNode != null) {
- UiElementNode p = mNode.getUiRoot();
- // The node root should be a document. Instead what we really mean to
- // return is the top level view element.
- if (p instanceof UiDocumentNode) {
- List<UiElementNode> children = p.getUiChildren();
- if (children.size() > 0) {
- p = children.get(0);
- }
- }
-
- // Cope with a badly structured XML layout
- while (p != null && !(p instanceof UiViewElementNode)) {
- p = p.getUiNextSibling();
- }
-
- if (p == mNode) {
- return this;
- }
- if (p instanceof UiViewElementNode) {
- return mFactory.create((UiViewElementNode) p);
- }
- }
-
- return null;
- }
-
- @Override
- public INode getParent() {
- if (mNode != null) {
- UiElementNode p = mNode.getUiParent();
- if (p instanceof UiViewElementNode) {
- return mFactory.create((UiViewElementNode) p);
- }
- }
-
- return null;
- }
-
- @Override
- public @NonNull INode[] getChildren() {
- if (mNode != null) {
- List<UiElementNode> uiChildren = mNode.getUiChildren();
- List<INode> nodes = new ArrayList<INode>(uiChildren.size());
- for (UiElementNode uiChild : uiChildren) {
- if (uiChild instanceof UiViewElementNode) {
- nodes.add(mFactory.create((UiViewElementNode) uiChild));
- }
- }
-
- return nodes.toArray(new INode[nodes.size()]);
- }
-
- return new INode[0];
- }
-
-
- // ---- XML Editing ---
-
- @Override
- public void editXml(@NonNull String undoName, final @NonNull INodeHandler c) {
- final AndroidXmlEditor editor = mNode.getEditor();
-
- if (editor != null) {
- // Create an undo edit XML wrapper, which takes a runnable
- editor.wrapUndoEditXmlModel(
- undoName,
- new Runnable() {
- @Override
- public void run() {
- // Here editor.isEditXmlModelPending returns true and it
- // is safe to edit the model using any method from INode.
-
- // Finally execute the closure that will act on the XML
- c.handle(NodeProxy.this);
- applyPendingChanges();
- }
- });
- }
- }
-
- private void checkEditOK() {
- final AndroidXmlEditor editor = mNode.getEditor();
- if (!editor.isEditXmlModelPending()) {
- throw new RuntimeException("Error: XML edit call without using INode.editXml!");
- }
- }
-
- @Override
- public @NonNull INode appendChild(@NonNull String viewFqcn) {
- return insertOrAppend(viewFqcn, -1);
- }
-
- @Override
- public @NonNull INode insertChildAt(@NonNull String viewFqcn, int index) {
- return insertOrAppend(viewFqcn, index);
- }
-
- @Override
- public void removeChild(@NonNull INode node) {
- checkEditOK();
-
- ((NodeProxy) node).mNode.deleteXmlNode();
- }
-
- private INode insertOrAppend(String viewFqcn, int index) {
- checkEditOK();
-
- AndroidXmlEditor editor = mNode.getEditor();
- if (editor != null) {
- // Possibly replace the tag with a compatibility version if the
- // minimum SDK requires it
- IProject project = editor.getProject();
- if (project != null) {
- viewFqcn = SupportLibraryHelper.getTagFor(project, viewFqcn);
- }
- }
-
- // Find the descriptor for this FQCN
- ViewElementDescriptor vd = getFqcnViewDescriptor(viewFqcn);
- if (vd == null) {
- warnPrintf("Can't create a new %s element", viewFqcn);
- return null;
- }
-
- final UiElementNode uiNew;
- if (index == -1) {
- // Append at the end.
- uiNew = mNode.appendNewUiChild(vd);
- } else {
- // Insert at the requested position or at the end.
- int n = mNode.getUiChildren().size();
- if (index < 0 || index >= n) {
- uiNew = mNode.appendNewUiChild(vd);
- } else {
- uiNew = mNode.insertNewUiChild(index, vd);
- }
- }
-
- // Set default attributes -- but only for new widgets (not when moving or copying)
- RulesEngine engine = null;
- LayoutEditorDelegate delegate = LayoutEditorDelegate.fromEditor(editor);
- if (delegate != null) {
- engine = delegate.getRulesEngine();
- }
- if (engine == null || engine.getInsertType().isCreate()) {
- // TODO: This should probably use IViewRule#getDefaultAttributes() at some point
- DescriptorsUtils.setDefaultLayoutAttributes(uiNew, false /*updateLayout*/);
- }
-
- Node xmlNode = uiNew.createXmlNode();
-
- if (!(uiNew instanceof UiViewElementNode) || xmlNode == null) {
- // Both things are not supposed to happen. When they do, we're in big trouble.
- // We don't really know how to revert the state at this point and the UI model is
- // now out of sync with the XML model.
- // Panic ensues.
- // The best bet is to abort now. The edit wrapper will release the edit and the
- // XML/UI should get reloaded properly (with a likely invalid XML.)
- warnPrintf("Failed to create a new %s element", viewFqcn);
- throw new RuntimeException("XML node creation failed."); //$NON-NLS-1$
- }
-
- UiViewElementNode uiNewView = (UiViewElementNode) uiNew;
- NodeProxy newNode = mFactory.create(uiNewView);
-
- if (engine != null) {
- engine.callCreateHooks(editor, this, newNode, null);
- }
-
- return newNode;
- }
-
- @Override
- public boolean setAttribute(
- @Nullable String uri,
- @NonNull String name,
- @Nullable String value) {
- checkEditOK();
- UiAttributeNode attr = mNode.setAttributeValue(name, uri, value, true /* override */);
-
- if (uri == null) {
- uri = ""; //$NON-NLS-1$
- }
-
- Map<String, String> map = null;
- if (mPendingAttributes == null) {
- // Small initial size: we don't expect many different namespaces
- mPendingAttributes = new HashMap<String, Map<String, String>>(3);
- } else {
- map = mPendingAttributes.get(uri);
- }
- if (map == null) {
- map = new HashMap<String, String>();
- mPendingAttributes.put(uri, map);
- }
- map.put(name, value);
-
- return attr != null;
- }
-
- @Override
- public String getStringAttr(@Nullable String uri, @NonNull String attrName) {
- UiElementNode uiNode = mNode;
-
- if (attrName == null) {
- return null;
- }
-
- if (mPendingAttributes != null) {
- Map<String, String> map = mPendingAttributes.get(uri == null ? "" : uri); //$NON-NLS-1$
- if (map != null) {
- String value = map.get(attrName);
- if (value != null) {
- return value;
- }
- }
- }
-
- if (uiNode.getXmlNode() != null) {
- Node xmlNode = uiNode.getXmlNode();
- if (xmlNode != null) {
- NamedNodeMap nodeAttributes = xmlNode.getAttributes();
- if (nodeAttributes != null) {
- Node attr = nodeAttributes.getNamedItemNS(uri, attrName);
- if (attr != null) {
- return attr.getNodeValue();
- }
- }
- }
- }
- return null;
- }
-
- @Override
- public IAttributeInfo getAttributeInfo(@Nullable String uri, @NonNull String attrName) {
- UiElementNode uiNode = mNode;
-
- if (attrName == null) {
- return null;
- }
-
- for (AttributeDescriptor desc : uiNode.getAttributeDescriptors()) {
- String dUri = desc.getNamespaceUri();
- String dName = desc.getXmlLocalName();
- if ((uri == null && dUri == null) || (uri != null && uri.equals(dUri))) {
- if (attrName.equals(dName)) {
- return desc.getAttributeInfo();
- }
- }
- }
-
- return null;
- }
-
- @Override
- public @NonNull IAttributeInfo[] getDeclaredAttributes() {
-
- AttributeDescriptor[] descs = mNode.getAttributeDescriptors();
- int n = descs.length;
- IAttributeInfo[] infos = new AttributeInfo[n];
-
- for (int i = 0; i < n; i++) {
- infos[i] = descs[i].getAttributeInfo();
- }
-
- return infos;
- }
-
- @Override
- public @NonNull List<String> getAttributeSources() {
- ElementDescriptor descriptor = mNode.getDescriptor();
- if (descriptor instanceof ViewElementDescriptor) {
- return ((ViewElementDescriptor) descriptor).getAttributeSources();
- } else {
- return Collections.emptyList();
- }
- }
-
- @Override
- public @NonNull IAttribute[] getLiveAttributes() {
- UiElementNode uiNode = mNode;
-
- if (uiNode.getXmlNode() != null) {
- Node xmlNode = uiNode.getXmlNode();
- if (xmlNode != null) {
- NamedNodeMap nodeAttributes = xmlNode.getAttributes();
- if (nodeAttributes != null) {
-
- int n = nodeAttributes.getLength();
- IAttribute[] result = new IAttribute[n];
- for (int i = 0; i < n; i++) {
- Node attr = nodeAttributes.item(i);
- String uri = attr.getNamespaceURI();
- String name = attr.getLocalName();
- String value = attr.getNodeValue();
-
- result[i] = new SimpleAttribute(uri, name, value);
- }
- return result;
- }
- }
- }
-
- return new IAttribute[0];
-
- }
-
- @Override
- public String toString() {
- return "NodeProxy [node=" + mNode + ", bounds=" + mBounds + "]";
- }
-
- // --- internal helpers ---
-
- /**
- * Helper methods that returns a {@link ViewElementDescriptor} for the requested FQCN.
- * Will return null if we can't find that FQCN or we lack the editor/data/descriptors info
- * (which shouldn't really happen since at this point the SDK should be fully loaded and
- * isn't reloading, or we wouldn't be here editing XML for a layout rule.)
- */
- private ViewElementDescriptor getFqcnViewDescriptor(String fqcn) {
- LayoutEditorDelegate delegate = LayoutEditorDelegate.fromEditor(mNode.getEditor());
- if (delegate != null) {
- return delegate.getFqcnViewDescriptor(fqcn);
- }
-
- return null;
- }
-
- private void warnPrintf(String msg, Object...params) {
- AdtPlugin.printToConsole(
- mNode == null ? "" : mNode.getDescriptor().getXmlLocalName(),
- String.format(msg, params)
- );
- }
-
- /**
- * If there are any pending changes in these nodes, apply them now
- *
- * @return true if any modifications were made
- */
- public boolean applyPendingChanges() {
- boolean modified = false;
-
- // Flush all pending attributes
- if (mPendingAttributes != null) {
- mNode.commitDirtyAttributesToXml();
- modified = true;
- mPendingAttributes = null;
-
- }
- for (INode child : getChildren()) {
- modified |= ((NodeProxy) child).applyPendingChanges();
- }
-
- return modified;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/PaletteMetadataDescriptor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/PaletteMetadataDescriptor.java
deleted file mode 100644
index 884cb077a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/PaletteMetadataDescriptor.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gre;
-
-import static com.android.SdkConstants.ANDROID_NS_NAME_PREFIX;
-import static com.android.SdkConstants.ANDROID_URI;
-
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.SimpleAttribute;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.SimpleElement;
-
-import org.eclipse.swt.graphics.Image;
-import org.w3c.dom.Element;
-
-/**
- * Special version of {@link ViewElementDescriptor} which is initialized by the palette
- * with specific metadata for how to instantiate particular variations of an existing
- * {@link ViewElementDescriptor} with initial values.
- */
-public class PaletteMetadataDescriptor extends ViewElementDescriptor {
- private String mInitString;
- private String mIconName;
-
- public PaletteMetadataDescriptor(ViewElementDescriptor descriptor, String displayName,
- String initString, String iconName) {
- super(descriptor.getXmlName(),
- displayName,
- descriptor.getFullClassName(),
- descriptor.getTooltip(),
- descriptor.getSdkUrl(),
- descriptor.getAttributes(),
- descriptor.getLayoutAttributes(),
- descriptor.getChildren(), descriptor.getMandatory() == Mandatory.MANDATORY);
- mInitString = initString;
- mIconName = iconName;
- setSuperClass(descriptor.getSuperClassDesc());
- }
-
- /**
- * Returns a String which contains a comma separated list of name=value tokens,
- * where the name can start with "android:" to indicate a property in the android namespace,
- * or no prefix for plain attributes.
- *
- * @return the initialization string, which can be empty but never null
- */
- public String getInitializedAttributes() {
- return mInitString != null ? mInitString : ""; //$NON-NLS-1$
- }
-
- @Override
- public Image getGenericIcon() {
- if (mIconName != null) {
- IconFactory factory = IconFactory.getInstance();
- Image icon = factory.getIcon(mIconName);
- if (icon != null) {
- return icon;
- }
- }
-
- return super.getGenericIcon();
- }
-
- /**
- * Initializes a new {@link SimpleElement} with the palette initialization
- * configuration
- *
- * @param element the new element to initialize
- */
- public void initializeNew(SimpleElement element) {
- initializeNew(element, null);
- }
-
- /**
- * Initializes a new {@link Element} with the palette initialization configuration
- *
- * @param element the new element to initialize
- */
- public void initializeNew(Element element) {
- initializeNew(null, element);
- }
-
- private void initializeNew(SimpleElement simpleElement, Element domElement) {
- String initializedAttributes = mInitString;
- if (initializedAttributes != null && initializedAttributes.length() > 0) {
- for (String s : initializedAttributes.split(",")) { //$NON-NLS-1$
- String[] nameValue = s.split("="); //$NON-NLS-1$
- String name = nameValue[0];
- String value = nameValue[1];
- String nameSpace = ""; //$NON-NLS-1$
- if (name.startsWith(ANDROID_NS_NAME_PREFIX)) {
- name = name.substring(ANDROID_NS_NAME_PREFIX.length());
- nameSpace = ANDROID_URI;
- }
-
- if (simpleElement != null) {
- SimpleAttribute attr = new SimpleAttribute(nameSpace, name, value);
- simpleElement.addAttribute(attr);
- }
-
- if (domElement != null) {
- domElement.setAttributeNS(nameSpace, name, value);
- }
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/RuleLoader.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/RuleLoader.java
deleted file mode 100644
index 4f49a7545..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/RuleLoader.java
+++ /dev/null
@@ -1,192 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gre;
-
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.sdklib.internal.project.ProjectProperties;
-import com.android.utils.Pair;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.QualifiedName;
-
-import java.io.File;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * The {@link RuleLoader} is responsible for loading (and unloading)
- * {@link IViewRule} classes. There is typically one {@link RuleLoader}
- * per project.
- */
-public class RuleLoader {
- /**
- * Qualified name for the per-project non-persistent property storing the
- * {@link RuleLoader} for this project
- */
- private final static QualifiedName RULE_LOADER = new QualifiedName(AdtPlugin.PLUGIN_ID,
- "ruleloader"); //$NON-NLS-1$
-
- private final IProject mProject;
- private ClassLoader mUserClassLoader;
- private List<Pair<File, Long>> mUserJarTimeStamps;
- private long mLastCheckTimeStamp;
-
- /**
- * Flag set when we've attempted to initialize the {@link #mUserClassLoader}
- * already
- */
- private boolean mUserClassLoaderInited;
-
- /**
- * Returns the {@link RuleLoader} for the given project
- *
- * @param project the project the loader is associated with
- * @return an {@RuleLoader} for the given project,
- * never null
- */
- public static RuleLoader get(IProject project) {
- RuleLoader loader = null;
- try {
- loader = (RuleLoader) project.getSessionProperty(RULE_LOADER);
- } catch (CoreException e) {
- // Not a problem; we will just create a new one
- }
- if (loader == null) {
- loader = new RuleLoader(project);
- try {
- project.setSessionProperty(RULE_LOADER, loader);
- } catch (CoreException e) {
- AdtPlugin.log(e, "Can't store RuleLoader");
- }
- }
- return loader;
- }
-
- /** Do not call; use the {@link #get} factory method instead. */
- private RuleLoader(IProject project) {
- mProject = project;
- }
-
- /**
- * Find out whether the given project has 3rd party ViewRules, and if so
- * return a ClassLoader which can locate them. If not, return null.
- * @param project The project to load user rules from
- * @return A class loader which can user view rules, or otherwise null
- */
- private ClassLoader computeUserClassLoader(IProject project) {
- // Default place to locate layout rules. The user may also add to this
- // path by defining a config property specifying
- // additional .jar files to search via a the layoutrules.jars property.
- ProjectState state = Sdk.getProjectState(project);
- ProjectProperties projectProperties = state.getProperties();
-
- // Ensure we have the latest & greatest version of the properties.
- // This allows users to reopen editors in a running Eclipse instance
- // to get updated view rule jars
- projectProperties.reload();
-
- String path = projectProperties.getProperty(
- ProjectProperties.PROPERTY_RULES_PATH);
-
- if (path != null && path.length() > 0) {
-
- mUserJarTimeStamps = new ArrayList<Pair<File, Long>>();
- mLastCheckTimeStamp = System.currentTimeMillis();
-
- List<URL> urls = new ArrayList<URL>();
- String[] pathElements = path.split(File.pathSeparator);
- for (String pathElement : pathElements) {
- pathElement = pathElement.trim(); // Avoid problems with trailing whitespace etc
- File pathFile = new File(pathElement);
- if (!pathFile.isAbsolute()) {
- pathFile = new File(project.getLocation().toFile(), pathElement);
- }
- // Directories and jar files are okay. Do we need to
- // validate the files here as .jar files?
- if (pathFile.isFile() || pathFile.isDirectory()) {
- URL url;
- try {
- url = pathFile.toURI().toURL();
- urls.add(url);
-
- mUserJarTimeStamps.add(Pair.of(pathFile, pathFile.lastModified()));
- } catch (MalformedURLException e) {
- AdtPlugin.log(IStatus.WARNING,
- "Invalid URL: %1$s", //$NON-NLS-1$
- e.toString());
- }
- }
- }
-
- if (urls.size() > 0) {
- return new URLClassLoader(urls.toArray(new URL[urls.size()]),
- RulesEngine.class.getClassLoader());
- }
- }
-
- return null;
- }
-
- /**
- * Return the class loader to use for custom views, or null if no custom
- * view rules are registered for the project. Note that this class loader
- * can change over time (if the jar files are updated), so callers should be
- * prepared to unload previous instances.
- *
- * @return a class loader to use for custom view rules, or null
- */
- public ClassLoader getClassLoader() {
- if (mUserClassLoader == null) {
- // Only attempt to load rule paths once.
- // TODO: Check the timestamp on the project.properties file so we can dynamically
- // pick up cases where the user edits the path
- if (!mUserClassLoaderInited) {
- mUserClassLoaderInited = true;
- mUserClassLoader = computeUserClassLoader(mProject);
- }
- } else {
- // Check the timestamp on the jar files in the custom view path to see if we
- // need to reload the classes (but only do this at most every 3 seconds)
- if (mUserJarTimeStamps != null) {
- long time = System.currentTimeMillis();
- if (time - mLastCheckTimeStamp > 3000) {
- mLastCheckTimeStamp = time;
- for (Pair<File, Long> pair : mUserJarTimeStamps) {
- File file = pair.getFirst();
- Long prevModified = pair.getSecond();
- long modified = file.lastModified();
- if (prevModified.longValue() != modified) {
- mUserClassLoaderInited = true;
- mUserJarTimeStamps = null;
- mUserClassLoader = computeUserClassLoader(mProject);
- }
- }
- }
- }
- }
-
- return mUserClassLoader;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/RulesEngine.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/RulesEngine.java
deleted file mode 100644
index 8f9923749..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/RulesEngine.java
+++ /dev/null
@@ -1,876 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gre;
-
-import static com.android.SdkConstants.ANDROID_WIDGET_PREFIX;
-import static com.android.SdkConstants.VIEW_MERGE;
-import static com.android.SdkConstants.VIEW_TAG;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.DropFeedback;
-import com.android.ide.common.api.IDragElement;
-import com.android.ide.common.api.IGraphics;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.InsertType;
-import com.android.ide.common.api.Point;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.api.RuleAction;
-import com.android.ide.common.api.SegmentType;
-import com.android.ide.common.layout.ViewRule;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.GCWrapper;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.SimpleElement;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.sdklib.IAndroidTarget;
-
-import org.eclipse.core.resources.IProject;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-
-/**
- * The rule engine manages the layout rules and interacts with them.
- * There's one {@link RulesEngine} instance per layout editor.
- * Each instance has 2 sets of rules: the static ADT rules (shared across all instances)
- * and the project specific rules (local to the current instance / layout editor).
- */
-public class RulesEngine {
- private final IProject mProject;
- private final Map<Object, IViewRule> mRulesCache = new HashMap<Object, IViewRule>();
-
- /**
- * The type of any upcoming node manipulations performed by the {@link IViewRule}s.
- * When actions are performed in the tool (like a paste action, or a drag from palette,
- * or a drag move within the canvas, etc), these are different types of inserts,
- * and we don't want to have the rules track them closely (and pass them back to us
- * in the {@link INode#insertChildAt} methods etc), so instead we track the state
- * here on behalf of the currently executing rule.
- */
- private InsertType mInsertType = InsertType.CREATE;
-
- /**
- * Per-project loader for custom view rules
- */
- private RuleLoader mRuleLoader;
- private ClassLoader mUserClassLoader;
-
- /**
- * The editor which owns this {@link RulesEngine}
- */
- private final GraphicalEditorPart mEditor;
-
- /**
- * Creates a new {@link RulesEngine} associated with the selected project.
- * <p/>
- * The rules engine will look in the project for a tools jar to load custom view rules.
- *
- * @param editor the editor which owns this {@link RulesEngine}
- * @param project A non-null open project.
- */
- public RulesEngine(GraphicalEditorPart editor, IProject project) {
- mProject = project;
- mEditor = editor;
-
- mRuleLoader = RuleLoader.get(project);
- }
-
- /**
- * Returns the {@link IProject} on which the {@link RulesEngine} was created.
- */
- public IProject getProject() {
- return mProject;
- }
-
- /**
- * Returns the {@link GraphicalEditorPart} for which the {@link RulesEngine} was
- * created.
- *
- * @return the associated editor
- */
- public GraphicalEditorPart getEditor() {
- return mEditor;
- }
-
- /**
- * Called by the owner of the {@link RulesEngine} when it is going to be disposed.
- * This frees some resources, such as the project's folder monitor.
- */
- public void dispose() {
- clearCache();
- }
-
- /**
- * Invokes {@link IViewRule#getDisplayName()} on the rule matching the specified element.
- *
- * @param element The view element to target. Can be null.
- * @return Null if the rule failed, there's no rule or the rule does not want to override
- * the display name. Otherwise, a string as returned by the rule.
- */
- public String callGetDisplayName(UiViewElementNode element) {
- // try to find a rule for this element's FQCN
- IViewRule rule = loadRule(element);
-
- if (rule != null) {
- try {
- return rule.getDisplayName();
-
- } catch (Exception e) {
- AdtPlugin.log(e, "%s.getDisplayName() failed: %s",
- rule.getClass().getSimpleName(),
- e.toString());
- }
- }
-
- return null;
- }
-
- /**
- * Invokes {@link IViewRule#addContextMenuActions(List, INode)} on the rule matching the specified element.
- *
- * @param selectedNode The node selected. Never null.
- * @return Null if the rule failed, there's no rule or the rule does not provide
- * any custom menu actions. Otherwise, a list of {@link RuleAction}.
- */
- @Nullable
- public List<RuleAction> callGetContextMenu(NodeProxy selectedNode) {
- // try to find a rule for this element's FQCN
- IViewRule rule = loadRule(selectedNode.getNode());
-
- if (rule != null) {
- try {
- mInsertType = InsertType.CREATE;
- List<RuleAction> actions = new ArrayList<RuleAction>();
- rule.addContextMenuActions(actions, selectedNode);
- Collections.sort(actions);
-
- return actions;
- } catch (Exception e) {
- AdtPlugin.log(e, "%s.getContextMenu() failed: %s",
- rule.getClass().getSimpleName(),
- e.toString());
- }
- }
-
- return null;
- }
-
- /**
- * Calls the selected node to return its default action
- *
- * @param selectedNode the node to apply the action to
- * @return the default action id
- */
- public String callGetDefaultActionId(@NonNull NodeProxy selectedNode) {
- // try to find a rule for this element's FQCN
- IViewRule rule = loadRule(selectedNode.getNode());
-
- if (rule != null) {
- try {
- mInsertType = InsertType.CREATE;
- return rule.getDefaultActionId(selectedNode);
- } catch (Exception e) {
- AdtPlugin.log(e, "%s.getDefaultAction() failed: %s",
- rule.getClass().getSimpleName(),
- e.toString());
- }
- }
-
- return null;
- }
-
- /**
- * Invokes {@link IViewRule#addLayoutActions(List, INode, List)} on the rule
- * matching the specified element.
- *
- * @param actions The list of actions to add layout actions into
- * @param parentNode The layout node
- * @param children The selected children of the node, if any (used to
- * initialize values of child layout controls, if applicable)
- * @return Null if the rule failed, there's no rule or the rule does not
- * provide any custom menu actions. Otherwise, a list of
- * {@link RuleAction}.
- */
- public List<RuleAction> callAddLayoutActions(List<RuleAction> actions,
- NodeProxy parentNode, List<NodeProxy> children ) {
- // try to find a rule for this element's FQCN
- IViewRule rule = loadRule(parentNode.getNode());
-
- if (rule != null) {
- try {
- mInsertType = InsertType.CREATE;
- rule.addLayoutActions(actions, parentNode, children);
- } catch (Exception e) {
- AdtPlugin.log(e, "%s.getContextMenu() failed: %s",
- rule.getClass().getSimpleName(),
- e.toString());
- }
- }
-
- return null;
- }
-
- /**
- * Invokes {@link IViewRule#getSelectionHint(INode, INode)}
- * on the rule matching the specified element.
- *
- * @param parentNode The parent of the node selected. Never null.
- * @param childNode The child node that was selected. Never null.
- * @return a list of strings to be displayed, or null or empty to display nothing
- */
- public List<String> callGetSelectionHint(NodeProxy parentNode, NodeProxy childNode) {
- // try to find a rule for this element's FQCN
- IViewRule rule = loadRule(parentNode.getNode());
-
- if (rule != null) {
- try {
- return rule.getSelectionHint(parentNode, childNode);
-
- } catch (Exception e) {
- AdtPlugin.log(e, "%s.getSelectionHint() failed: %s",
- rule.getClass().getSimpleName(),
- e.toString());
- }
- }
-
- return null;
- }
-
- public void callPaintSelectionFeedback(GCWrapper gcWrapper, NodeProxy parentNode,
- List<? extends INode> childNodes, Object view) {
- // try to find a rule for this element's FQCN
- IViewRule rule = loadRule(parentNode.getNode());
-
- if (rule != null) {
- try {
- rule.paintSelectionFeedback(gcWrapper, parentNode, childNodes, view);
-
- } catch (Exception e) {
- AdtPlugin.log(e, "%s.callPaintSelectionFeedback() failed: %s",
- rule.getClass().getSimpleName(),
- e.toString());
- }
- }
- }
-
- /**
- * Called when the d'n'd starts dragging over the target node.
- * If interested, returns a DropFeedback passed to onDrop/Move/Leave/Paint.
- * If not interested in drop, return false.
- * Followed by a paint.
- */
- public DropFeedback callOnDropEnter(NodeProxy targetNode,
- Object targetView, IDragElement[] elements) {
- // try to find a rule for this element's FQCN
- IViewRule rule = loadRule(targetNode.getNode());
-
- if (rule != null) {
- try {
- return rule.onDropEnter(targetNode, targetView, elements);
-
- } catch (Exception e) {
- AdtPlugin.log(e, "%s.onDropEnter() failed: %s",
- rule.getClass().getSimpleName(),
- e.toString());
- }
- }
-
- return null;
- }
-
- /**
- * Called after onDropEnter.
- * Returns a DropFeedback passed to onDrop/Move/Leave/Paint (typically same
- * as input one).
- */
- public DropFeedback callOnDropMove(NodeProxy targetNode,
- IDragElement[] elements,
- DropFeedback feedback,
- Point where) {
- // try to find a rule for this element's FQCN
- IViewRule rule = loadRule(targetNode.getNode());
-
- if (rule != null) {
- try {
- return rule.onDropMove(targetNode, elements, feedback, where);
-
- } catch (Exception e) {
- AdtPlugin.log(e, "%s.onDropMove() failed: %s",
- rule.getClass().getSimpleName(),
- e.toString());
- }
- }
-
- return null;
- }
-
- /**
- * Called when drop leaves the target without actually dropping
- */
- public void callOnDropLeave(NodeProxy targetNode,
- IDragElement[] elements,
- DropFeedback feedback) {
- // try to find a rule for this element's FQCN
- IViewRule rule = loadRule(targetNode.getNode());
-
- if (rule != null) {
- try {
- rule.onDropLeave(targetNode, elements, feedback);
-
- } catch (Exception e) {
- AdtPlugin.log(e, "%s.onDropLeave() failed: %s",
- rule.getClass().getSimpleName(),
- e.toString());
- }
- }
- }
-
- /**
- * Called when drop is released over the target to perform the actual drop.
- */
- public void callOnDropped(NodeProxy targetNode,
- IDragElement[] elements,
- DropFeedback feedback,
- Point where,
- InsertType insertType) {
- // try to find a rule for this element's FQCN
- IViewRule rule = loadRule(targetNode.getNode());
-
- if (rule != null) {
- try {
- mInsertType = insertType;
- rule.onDropped(targetNode, elements, feedback, where);
-
- } catch (Exception e) {
- AdtPlugin.log(e, "%s.onDropped() failed: %s",
- rule.getClass().getSimpleName(),
- e.toString());
- }
- }
- }
-
- /**
- * Called when a paint has been requested via DropFeedback.
- */
- public void callDropFeedbackPaint(IGraphics gc,
- NodeProxy targetNode,
- DropFeedback feedback) {
- if (gc != null && feedback != null && feedback.painter != null) {
- try {
- feedback.painter.paint(gc, targetNode, feedback);
- } catch (Exception e) {
- AdtPlugin.log(e, "DropFeedback.painter failed: %s",
- e.toString());
- }
- }
- }
-
- /**
- * Called when pasting elements in an existing document on the selected target.
- *
- * @param targetNode The first node selected.
- * @param targetView The view object for the target node, or null if not known
- * @param pastedElements The elements being pasted.
- * @return the parent node the paste was applied into
- */
- public NodeProxy callOnPaste(NodeProxy targetNode, Object targetView,
- SimpleElement[] pastedElements) {
-
- // Find a target which accepts children. If you for example select a button
- // and attempt to paste, this will reselect the parent of the button as the paste
- // target. (This is a loop rather than just checking the direct parent since
- // we will soon ask each child whether they are *willing* to accept the new child.
- // A ScrollView for example, which only accepts one child, might also say no
- // and delegate to its parent in turn.
- INode parent = targetNode;
- while (parent instanceof NodeProxy) {
- NodeProxy np = (NodeProxy) parent;
- if (np.getNode() != null && np.getNode().getDescriptor() != null) {
- ElementDescriptor descriptor = np.getNode().getDescriptor();
- if (descriptor.hasChildren()) {
- targetNode = np;
- break;
- }
- }
- parent = parent.getParent();
- }
-
- // try to find a rule for this element's FQCN
- IViewRule rule = loadRule(targetNode.getNode());
-
- if (rule != null) {
- try {
- mInsertType = InsertType.PASTE;
- rule.onPaste(targetNode, targetView, pastedElements);
-
- } catch (Exception e) {
- AdtPlugin.log(e, "%s.onPaste() failed: %s",
- rule.getClass().getSimpleName(),
- e.toString());
- }
- }
-
- return targetNode;
- }
-
- // ---- Resize operations ----
-
- public DropFeedback callOnResizeBegin(NodeProxy child, NodeProxy parent, Rect newBounds,
- SegmentType horizontalEdge, SegmentType verticalEdge, Object childView,
- Object parentView) {
- IViewRule rule = loadRule(parent.getNode());
-
- if (rule != null) {
- try {
- return rule.onResizeBegin(child, parent, horizontalEdge, verticalEdge,
- childView, parentView);
- } catch (Exception e) {
- AdtPlugin.log(e, "%s.onResizeBegin() failed: %s", rule.getClass().getSimpleName(),
- e.toString());
- }
- }
-
- return null;
- }
-
- public void callOnResizeUpdate(DropFeedback feedback, NodeProxy child, NodeProxy parent,
- Rect newBounds, int modifierMask) {
- IViewRule rule = loadRule(parent.getNode());
-
- if (rule != null) {
- try {
- rule.onResizeUpdate(feedback, child, parent, newBounds, modifierMask);
- } catch (Exception e) {
- AdtPlugin.log(e, "%s.onResizeUpdate() failed: %s", rule.getClass().getSimpleName(),
- e.toString());
- }
- }
- }
-
- public void callOnResizeEnd(DropFeedback feedback, NodeProxy child, NodeProxy parent,
- Rect newBounds) {
- IViewRule rule = loadRule(parent.getNode());
-
- if (rule != null) {
- try {
- rule.onResizeEnd(feedback, child, parent, newBounds);
- } catch (Exception e) {
- AdtPlugin.log(e, "%s.onResizeEnd() failed: %s", rule.getClass().getSimpleName(),
- e.toString());
- }
- }
- }
-
- // ---- Creation customizations ----
-
- /**
- * Invokes the create hooks ({@link IViewRule#onCreate},
- * {@link IViewRule#onChildInserted} when a new child has been created/pasted/moved, and
- * is inserted into a given parent. The parent may be null (for example when rendering
- * top level items for preview).
- *
- * @param editor the XML editor to apply edits to the model for (performed by view
- * rules)
- * @param parentNode the parent XML node, or null if unknown
- * @param childNode the XML node of the new node, never null
- * @param overrideInsertType If not null, specifies an explicit insert type to use for
- * edits made during the customization
- */
- public void callCreateHooks(
- AndroidXmlEditor editor,
- NodeProxy parentNode, NodeProxy childNode,
- InsertType overrideInsertType) {
- IViewRule parentRule = null;
-
- if (parentNode != null) {
- UiViewElementNode parentUiNode = parentNode.getNode();
- parentRule = loadRule(parentUiNode);
- }
-
- if (overrideInsertType != null) {
- mInsertType = overrideInsertType;
- }
-
- UiViewElementNode newUiNode = childNode.getNode();
- IViewRule childRule = loadRule(newUiNode);
- if (childRule != null || parentRule != null) {
- callCreateHooks(editor, mInsertType, parentRule, parentNode,
- childRule, childNode);
- }
- }
-
- private static void callCreateHooks(
- final AndroidXmlEditor editor, final InsertType insertType,
- final IViewRule parentRule, final INode parentNode,
- final IViewRule childRule, final INode newNode) {
- // Notify the parent about the new child in case it wants to customize it
- // (For example, a ScrollView parent can go and set all its children's layout params to
- // fill the parent.)
- if (!editor.isEditXmlModelPending()) {
- editor.wrapEditXmlModel(new Runnable() {
- @Override
- public void run() {
- callCreateHooks(editor, insertType,
- parentRule, parentNode, childRule, newNode);
- }
- });
- return;
- }
-
- if (parentRule != null) {
- parentRule.onChildInserted(newNode, parentNode, insertType);
- }
-
- // Look up corresponding IViewRule, and notify the rule about
- // this create action in case it wants to customize the new object.
- // (For example, a rule for TabHosts can go and create a default child tab
- // when you create it.)
- if (childRule != null) {
- childRule.onCreate(newNode, parentNode, insertType);
- }
-
- if (parentNode != null) {
- ((NodeProxy) parentNode).applyPendingChanges();
- }
- }
-
- /**
- * Set the type of insert currently in progress
- *
- * @param insertType the insert type to use for the next operation
- */
- public void setInsertType(InsertType insertType) {
- mInsertType = insertType;
- }
-
- /**
- * Return the type of insert currently in progress
- *
- * @return the type of insert currently in progress
- */
- public InsertType getInsertType() {
- return mInsertType;
- }
-
- // ---- Deletion ----
-
- public void callOnRemovingChildren(NodeProxy parentNode,
- List<INode> children) {
- if (parentNode != null) {
- UiViewElementNode parentUiNode = parentNode.getNode();
- IViewRule parentRule = loadRule(parentUiNode);
- if (parentRule != null) {
- try {
- parentRule.onRemovingChildren(children, parentNode,
- mInsertType == InsertType.MOVE_WITHIN);
- } catch (Exception e) {
- AdtPlugin.log(e, "%s.onDispose() failed: %s",
- parentRule.getClass().getSimpleName(),
- e.toString());
- }
- }
- }
- }
-
- // ---- private ---
-
- /**
- * Returns the descriptor for the base View class.
- * This could be null if the SDK or the given platform target hasn't loaded yet.
- */
- private ViewElementDescriptor getBaseViewDescriptor() {
- Sdk currentSdk = Sdk.getCurrent();
- if (currentSdk != null) {
- IAndroidTarget target = currentSdk.getTarget(mProject);
- if (target != null) {
- AndroidTargetData data = currentSdk.getTargetData(target);
- return data.getLayoutDescriptors().getBaseViewDescriptor();
- }
- }
- return null;
- }
-
- /**
- * Clear the Rules cache. Calls onDispose() on each rule.
- */
- private void clearCache() {
- // The cache can contain multiple times the same rule instance for different
- // keys (e.g. the UiViewElementNode key vs. the FQCN string key.) So transfer
- // all values to a unique set.
- HashSet<IViewRule> rules = new HashSet<IViewRule>(mRulesCache.values());
-
- mRulesCache.clear();
-
- for (IViewRule rule : rules) {
- if (rule != null) {
- try {
- rule.onDispose();
- } catch (Exception e) {
- AdtPlugin.log(e, "%s.onDispose() failed: %s",
- rule.getClass().getSimpleName(),
- e.toString());
- }
- }
- }
- }
-
- /**
- * Checks whether the project class loader has changed, and if so
- * unregisters any view rules that use classes from the old class loader. It
- * then returns the class loader to be used.
- */
- private ClassLoader updateClassLoader() {
- ClassLoader classLoader = mRuleLoader.getClassLoader();
- if (mUserClassLoader != null && classLoader != mUserClassLoader) {
- // We have to unload all the IViewRules from the old class
- List<Object> dispose = new ArrayList<Object>();
- for (Map.Entry<Object, IViewRule> entry : mRulesCache.entrySet()) {
- IViewRule rule = entry.getValue();
- if (rule.getClass().getClassLoader() == mUserClassLoader) {
- dispose.add(entry.getKey());
- }
- }
- for (Object object : dispose) {
- mRulesCache.remove(object);
- }
- }
-
- mUserClassLoader = classLoader;
- return mUserClassLoader;
- }
-
- /**
- * Load a rule using its descriptor. This will try to first load the rule using its
- * actual FQCN and if that fails will find the first parent that works in the view
- * hierarchy.
- */
- private IViewRule loadRule(UiViewElementNode element) {
- if (element == null) {
- return null;
- }
-
- String targetFqcn = null;
- ViewElementDescriptor targetDesc = null;
-
- ElementDescriptor d = element.getDescriptor();
- if (d instanceof ViewElementDescriptor) {
- targetDesc = (ViewElementDescriptor) d;
- }
- if (d == null || !(d instanceof ViewElementDescriptor)) {
- // This should not happen. All views should have some kind of *view* element
- // descriptor. Maybe the project is not complete and doesn't build or something.
- // In this case, we'll use the descriptor of the base android View class.
- targetDesc = getBaseViewDescriptor();
- }
-
- // Check whether any of the custom view .jar files have changed and if so
- // unregister previously cached view rules to force a new view rule to be loaded.
- updateClassLoader();
-
- // Return the rule if we find it in the cache, even if it was stored as null
- // (which means we didn't find it earlier, so don't look for it again)
- IViewRule rule = mRulesCache.get(targetDesc);
- if (rule != null || mRulesCache.containsKey(targetDesc)) {
- return rule;
- }
-
- // Get the descriptor and loop through the super class hierarchy
- for (ViewElementDescriptor desc = targetDesc;
- desc != null;
- desc = desc.getSuperClassDesc()) {
-
- // Get the FQCN of this View
- String fqcn = desc.getFullClassName();
- if (fqcn == null) {
- // Shouldn't be happening.
- return null;
- }
-
- // The first time we keep the FQCN around as it's the target class we were
- // initially trying to load. After, as we move through the hierarchy, the
- // target FQCN remains constant.
- if (targetFqcn == null) {
- targetFqcn = fqcn;
- }
-
- if (fqcn.indexOf('.') == -1) {
- // Deal with unknown descriptors; these lack the full qualified path and
- // elements in the layout without a package are taken to be in the
- // android.widget package.
- fqcn = ANDROID_WIDGET_PREFIX + fqcn;
- }
-
- // Try to find a rule matching the "real" FQCN. If we find it, we're done.
- // If not, the for loop will move to the parent descriptor.
- rule = loadRule(fqcn, targetFqcn);
- if (rule != null) {
- // We found one.
- // As a side effect, loadRule() also cached the rule using the target FQCN.
- return rule;
- }
- }
-
- // Memorize in the cache that we couldn't find a rule for this descriptor
- mRulesCache.put(targetDesc, null);
- return null;
- }
-
- /**
- * Try to load a rule given a specific FQCN. This looks for an exact match in either
- * the ADT scripts or the project scripts and does not look at parent hierarchy.
- * <p/>
- * Once a rule is found (or not), it is stored in a cache using its target FQCN
- * so we don't try to reload it.
- * <p/>
- * The real FQCN is the actual rule class we're loading, e.g. "android.view.View"
- * where target FQCN is the class we were initially looking for, which might be the same as
- * the real FQCN or might be a derived class, e.g. "android.widget.TextView".
- *
- * @param realFqcn The FQCN of the rule class actually being loaded.
- * @param targetFqcn The FQCN of the class actually processed, which might be different from
- * the FQCN of the rule being loaded.
- */
- IViewRule loadRule(String realFqcn, String targetFqcn) {
- if (realFqcn == null || targetFqcn == null) {
- return null;
- }
-
- // Return the rule if we find it in the cache, even if it was stored as null
- // (which means we didn't find it earlier, so don't look for it again)
- IViewRule rule = mRulesCache.get(realFqcn);
- if (rule != null || mRulesCache.containsKey(realFqcn)) {
- return rule;
- }
-
- // Look for class via reflection
- try {
- // For now, we package view rules for the builtin Android views and
- // widgets with the tool in a special package, so look there rather
- // than in the same package as the widgets.
- String ruleClassName;
- ClassLoader classLoader;
- if (realFqcn.startsWith("android.") || //$NON-NLS-1$
- realFqcn.equals(VIEW_MERGE) ||
- realFqcn.endsWith(".GridLayout") || //$NON-NLS-1$ // Temporary special case
- // FIXME: Remove this special case as soon as we pull
- // the MapViewRule out of this code base and bundle it
- // with the add ons
- realFqcn.startsWith("com.google.android.maps.")) { //$NON-NLS-1$
- // This doesn't handle a case where there are name conflicts
- // (e.g. where there are multiple different views with the same
- // class name and only differing in package names, but that's a
- // really bad practice in the first place, and if that situation
- // should come up in the API we can enhance this algorithm.
- String packageName = ViewRule.class.getName();
- packageName = packageName.substring(0, packageName.lastIndexOf('.'));
- classLoader = RulesEngine.class.getClassLoader();
- int dotIndex = realFqcn.lastIndexOf('.');
- String baseName = realFqcn.substring(dotIndex+1);
- // Capitalize rule class name to match naming conventions, if necessary (<merge>)
- if (Character.isLowerCase(baseName.charAt(0))) {
- if (baseName.equals(VIEW_TAG)) {
- // Hack: ViewRule is generic for the "View" class, so we can't use it
- // for the special XML "view" tag (lowercase); instead, the rule is
- // named "ViewTagRule" instead.
- baseName = "ViewTag"; //$NON-NLS-1$
- }
- baseName = Character.toUpperCase(baseName.charAt(0)) + baseName.substring(1);
- }
- ruleClassName = packageName + "." + //$NON-NLS-1$
- baseName + "Rule"; //$NON-NLS-1$
- } else {
- // Initialize the user-classpath for 3rd party IViewRules, if necessary
- classLoader = updateClassLoader();
- if (classLoader == null) {
- // The mUserClassLoader can be null; this is the typical scenario,
- // when the user is only using builtin layout rules.
- // This means however we can't resolve this fqcn since it's not
- // in the name space of the builtin rules.
- mRulesCache.put(realFqcn, null);
- return null;
- }
-
- // For other (3rd party) widgets, look in the same package (though most
- // likely not in the same jar!)
- ruleClassName = realFqcn + "Rule"; //$NON-NLS-1$
- }
-
- Class<?> clz = Class.forName(ruleClassName, true, classLoader);
- rule = (IViewRule) clz.newInstance();
- return initializeRule(rule, targetFqcn);
- } catch (ClassNotFoundException ex) {
- // Not an unexpected error - this means that there isn't a helper for this
- // class.
- } catch (InstantiationException e) {
- // This is NOT an expected error: fail.
- AdtPlugin.log(e, "load rule error (%s): %s", realFqcn, e.toString());
- } catch (IllegalAccessException e) {
- // This is NOT an expected error: fail.
- AdtPlugin.log(e, "load rule error (%s): %s", realFqcn, e.toString());
- }
-
- // Memorize in the cache that we couldn't find a rule for this real FQCN
- mRulesCache.put(realFqcn, null);
- return null;
- }
-
- /**
- * Initialize a rule we just loaded. The rule has a chance to examine the target FQCN
- * and bail out.
- * <p/>
- * Contract: the rule is not in the {@link #mRulesCache} yet and this method will
- * cache it using the target FQCN if the rule is accepted.
- * <p/>
- * The real FQCN is the actual rule class we're loading, e.g. "android.view.View"
- * where target FQCN is the class we were initially looking for, which might be the same as
- * the real FQCN or might be a derived class, e.g. "android.widget.TextView".
- *
- * @param rule A rule freshly loaded.
- * @param targetFqcn The FQCN of the class actually processed, which might be different from
- * the FQCN of the rule being loaded.
- * @return The rule if accepted, or null if the rule can't handle that FQCN.
- */
- private IViewRule initializeRule(IViewRule rule, String targetFqcn) {
-
- try {
- if (rule.onInitialize(targetFqcn, new ClientRulesEngine(this, targetFqcn))) {
- // Add it to the cache and return it
- mRulesCache.put(targetFqcn, rule);
- return rule;
- } else {
- rule.onDispose();
- }
- } catch (Exception e) {
- AdtPlugin.log(e, "%s.onInit() failed: %s",
- rule.getClass().getSimpleName(),
- e.toString());
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/ViewMetadataRepository.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/ViewMetadataRepository.java
deleted file mode 100644
index 5f2659ef2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/ViewMetadataRepository.java
+++ /dev/null
@@ -1,856 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gre;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.FQCN_BUTTON;
-import static com.android.SdkConstants.FQCN_SPINNER;
-import static com.android.SdkConstants.FQCN_TOGGLE_BUTTON;
-import static com.android.SdkConstants.ID_PREFIX;
-import static com.android.SdkConstants.NEW_ID_PREFIX;
-import static com.android.SdkConstants.VIEW_FRAGMENT;
-import static com.android.SdkConstants.VIEW_INCLUDE;
-
-import com.android.annotations.VisibleForTesting;
-import com.android.ide.common.api.IViewMetadata.FillPreference;
-import com.android.ide.common.api.Margins;
-import com.android.ide.common.api.ResizePolicy;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.LayoutDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.resources.Density;
-import com.android.utils.Pair;
-import com.google.common.base.Splitter;
-import com.google.common.io.Closeables;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.InputSource;
-
-import java.io.BufferedInputStream;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-
-/**
- * The {@link ViewMetadataRepository} contains additional metadata for Android view
- * classes
- */
-public class ViewMetadataRepository {
- private static final String PREVIEW_CONFIG_FILENAME = "rendering-configs.xml"; //$NON-NLS-1$
- private static final String METADATA_FILENAME = "extra-view-metadata.xml"; //$NON-NLS-1$
-
- /** Singleton instance */
- private static ViewMetadataRepository sInstance = new ViewMetadataRepository();
-
- /**
- * Returns the singleton instance
- *
- * @return the {@link ViewMetadataRepository}
- */
- public static ViewMetadataRepository get() {
- return sInstance;
- }
-
- /**
- * Ever increasing counter used to assign natural ordering numbers to views and
- * categories
- */
- private static int sNextOrdinal = 0;
-
- /**
- * List of categories (which contain views); constructed lazily so use
- * {@link #getCategories()}
- */
- private List<CategoryData> mCategories;
-
- /**
- * Map from class names to view data objects; constructed lazily so use
- * {@link #getClassToView}
- */
- private Map<String, ViewData> mClassToView;
-
- /** Hidden constructor: Create via factory {@link #get()} instead */
- private ViewMetadataRepository() {
- }
-
- /** Returns a map from class fully qualified names to {@link ViewData} objects */
- private Map<String, ViewData> getClassToView() {
- if (mClassToView == null) {
- int initialSize = 75;
- mClassToView = new HashMap<String, ViewData>(initialSize);
- List<CategoryData> categories = getCategories();
- for (CategoryData category : categories) {
- for (ViewData view : category) {
- mClassToView.put(view.getFcqn(), view);
- }
- }
- assert mClassToView.size() <= initialSize;
- }
-
- return mClassToView;
- }
-
- /**
- * Returns an XML document containing rendering configurations for the various Android
- * views. The FQN of each view can be obtained via the
- * {@link #getFullClassName(Element)} method
- *
- * @return an XML document containing rendering elements
- */
- public Document getRenderingConfigDoc() {
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- Class<ViewMetadataRepository> clz = ViewMetadataRepository.class;
- InputStream paletteStream = clz.getResourceAsStream(PREVIEW_CONFIG_FILENAME);
- InputSource is = new InputSource(paletteStream);
- try {
- factory.setNamespaceAware(true);
- factory.setValidating(false);
- factory.setIgnoringComments(true);
- DocumentBuilder builder = factory.newDocumentBuilder();
- return builder.parse(is);
- } catch (Exception e) {
- AdtPlugin.log(e, "Parsing palette file failed");
- return null;
- } finally {
- Closeables.closeQuietly(paletteStream);
- }
- }
-
- /**
- * Returns a fully qualified class name for an element in the rendering document
- * returned by {@link #getRenderingConfigDoc()}
- *
- * @param element the element to look up the fqcn for
- * @return the fqcn of the view the element represents a preview for
- */
- public String getFullClassName(Element element) {
- // We don't use the element tag name, because in some cases we have
- // an outer element to render some interesting inner element, such as a tab widget
- // (which must be rendered inside a tab host).
- //
- // Therefore, we instead use the convention that the id is the fully qualified
- // class name, with .'s replaced with _'s.
-
- // Special case: for tab host we aren't allowed to mess with the id
- String id = element.getAttributeNS(ANDROID_URI, ATTR_ID);
-
- if ("@android:id/tabhost".equals(id)) {
- // Special case to distinguish TabHost and TabWidget
- NodeList children = element.getChildNodes();
- if (children.getLength() > 1 && (children.item(1) instanceof Element)) {
- Element child = (Element) children.item(1);
- String childId = child.getAttributeNS(ANDROID_URI, ATTR_ID);
- if ("@+id/android_widget_TabWidget".equals(childId)) {
- return "android.widget.TabWidget"; // TODO: Tab widget!
- }
- }
- return "android.widget.TabHost"; // TODO: Tab widget!
- }
-
- StringBuilder sb = new StringBuilder();
- int i = 0;
- if (id.startsWith(NEW_ID_PREFIX)) {
- i = NEW_ID_PREFIX.length();
- } else if (id.startsWith(ID_PREFIX)) {
- i = ID_PREFIX.length();
- }
-
- for (; i < id.length(); i++) {
- char c = id.charAt(i);
- if (c == '_') {
- sb.append('.');
- } else {
- sb.append(c);
- }
- }
-
- return sb.toString();
- }
-
- /** Returns an ordered list of categories and views, parsed from a metadata file */
- @SuppressWarnings("resource") // streams passed to parser InputSource closed by parser
- private List<CategoryData> getCategories() {
- if (mCategories == null) {
- mCategories = new ArrayList<CategoryData>();
-
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- Class<ViewMetadataRepository> clz = ViewMetadataRepository.class;
- InputStream inputStream = clz.getResourceAsStream(METADATA_FILENAME);
- InputSource is = new InputSource(new BufferedInputStream(inputStream));
- try {
- factory.setNamespaceAware(true);
- factory.setValidating(false);
- factory.setIgnoringComments(true);
- DocumentBuilder builder = factory.newDocumentBuilder();
- Document document = builder.parse(is);
- Map<String, FillPreference> fillTypes = new HashMap<String, FillPreference>();
- for (FillPreference pref : FillPreference.values()) {
- fillTypes.put(pref.toString().toLowerCase(Locale.US), pref);
- }
-
- NodeList categoryNodes = document.getDocumentElement().getChildNodes();
- for (int i = 0, n = categoryNodes.getLength(); i < n; i++) {
- Node node = categoryNodes.item(i);
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- Element element = (Element) node;
- if (element.getNodeName().equals("category")) { //$NON-NLS-1$
- String name = element.getAttribute("name"); //$NON-NLS-1$
- CategoryData category = new CategoryData(name);
- NodeList children = element.getChildNodes();
- for (int j = 0, m = children.getLength(); j < m; j++) {
- Node childNode = children.item(j);
- if (childNode.getNodeType() == Node.ELEMENT_NODE) {
- Element child = (Element) childNode;
- ViewData view = createViewData(fillTypes, child,
- null, FillPreference.NONE, RenderMode.NORMAL, null);
- category.addView(view);
- }
- }
- mCategories.add(category);
- }
- }
- }
- } catch (Exception e) {
- AdtPlugin.log(e, "Invalid palette metadata"); //$NON-NLS-1$
- }
- }
-
- return mCategories;
- }
-
- private ViewData createViewData(Map<String, FillPreference> fillTypes,
- Element child, String defaultFqcn, FillPreference defaultFill,
- RenderMode defaultRender, String defaultSize) {
- String fqcn = child.getAttribute("class"); //$NON-NLS-1$
- if (fqcn.length() == 0) {
- fqcn = defaultFqcn;
- }
- String fill = child.getAttribute("fill"); //$NON-NLS-1$
- FillPreference fillPreference = null;
- if (fill.length() > 0) {
- fillPreference = fillTypes.get(fill);
- }
- if (fillPreference == null) {
- fillPreference = defaultFill;
- }
- String skip = child.getAttribute("skip"); //$NON-NLS-1$
- RenderMode renderMode = defaultRender;
- String render = child.getAttribute("render"); //$NON-NLS-1$
- if (render.length() > 0) {
- renderMode = RenderMode.get(render);
- }
- String displayName = child.getAttribute("name"); //$NON-NLS-1$
- if (displayName.length() == 0) {
- displayName = null;
- }
-
- String relatedTo = child.getAttribute("relatedTo"); //$NON-NLS-1$
- String topAttrs = child.getAttribute("topAttrs"); //$NON-NLS-1$
- String resize = child.getAttribute("resize"); //$NON-NLS-1$
- ViewData view = new ViewData(fqcn, displayName, fillPreference,
- skip.length() == 0 ? false : Boolean.valueOf(skip),
- renderMode, relatedTo, resize, topAttrs);
-
- String init = child.getAttribute("init"); //$NON-NLS-1$
- String icon = child.getAttribute("icon"); //$NON-NLS-1$
-
- view.setInitString(init);
- if (icon.length() > 0) {
- view.setIconName(icon);
- }
-
- // Nested variations?
- if (child.hasChildNodes()) {
- // Palette variations
- NodeList childNodes = child.getChildNodes();
- for (int k = 0, kl = childNodes.getLength(); k < kl; k++) {
- Node variationNode = childNodes.item(k);
- if (variationNode.getNodeType() == Node.ELEMENT_NODE) {
- Element variation = (Element) variationNode;
- ViewData variationView = createViewData(fillTypes, variation,
- fqcn, fillPreference, renderMode, resize);
- view.addVariation(variationView);
- }
- }
- }
-
- return view;
- }
-
- /**
- * Computes the palette entries for the given {@link AndroidTargetData}, looking up the
- * available node descriptors, categorizing and sorting them.
- *
- * @param targetData the target data for which to compute palette entries
- * @param alphabetical if true, sort all items in alphabetical order
- * @param createCategories if true, organize the items into categories
- * @return a list of pairs where each pair contains of the category label and an
- * ordered list of elements to be included in that category
- */
- public List<Pair<String, List<ViewElementDescriptor>>> getPaletteEntries(
- AndroidTargetData targetData, boolean alphabetical, boolean createCategories) {
- List<Pair<String, List<ViewElementDescriptor>>> result =
- new ArrayList<Pair<String, List<ViewElementDescriptor>>>();
-
- List<List<ViewElementDescriptor>> lists = new ArrayList<List<ViewElementDescriptor>>(2);
- LayoutDescriptors layoutDescriptors = targetData.getLayoutDescriptors();
- lists.add(layoutDescriptors.getViewDescriptors());
- lists.add(layoutDescriptors.getLayoutDescriptors());
-
- // First record map of FQCN to ViewElementDescriptor such that we can quickly
- // determine if a particular palette entry is available
- Map<String, ViewElementDescriptor> fqcnToDescriptor =
- new HashMap<String, ViewElementDescriptor>();
- for (List<ViewElementDescriptor> list : lists) {
- for (ViewElementDescriptor view : list) {
- String fqcn = view.getFullClassName();
- if (fqcn == null) {
- // <view> and <merge> tags etc
- fqcn = view.getUiName();
- }
- fqcnToDescriptor.put(fqcn, view);
- }
- }
-
- Set<ViewElementDescriptor> remaining = new HashSet<ViewElementDescriptor>(
- layoutDescriptors.getViewDescriptors().size()
- + layoutDescriptors.getLayoutDescriptors().size());
- remaining.addAll(layoutDescriptors.getViewDescriptors());
- remaining.addAll(layoutDescriptors.getLayoutDescriptors());
-
- // Now iterate in palette metadata order over the items in the palette and include
- // any that also appear as a descriptor
- List<ViewElementDescriptor> categoryItems = new ArrayList<ViewElementDescriptor>();
- for (CategoryData category : getCategories()) {
- if (createCategories) {
- categoryItems = new ArrayList<ViewElementDescriptor>();
- }
- for (ViewData view : category) {
- String fqcn = view.getFcqn();
- ViewElementDescriptor descriptor = fqcnToDescriptor.get(fqcn);
- if (descriptor != null) {
- remaining.remove(descriptor);
- if (view.getSkip()) {
- continue;
- }
-
- if (view.getDisplayName() != null || view.getInitString().length() > 0) {
- categoryItems.add(new PaletteMetadataDescriptor(descriptor,
- view.getDisplayName(), view.getInitString(), view.getIconName()));
- } else {
- categoryItems.add(descriptor);
- }
-
- if (view.hasVariations()) {
- for (ViewData variation : view.getVariations()) {
- String init = variation.getInitString();
- String icon = variation.getIconName();
- ViewElementDescriptor desc = new PaletteMetadataDescriptor(descriptor,
- variation.getDisplayName(), init, icon);
- categoryItems.add(desc);
- }
- }
- }
- }
-
- if (createCategories && categoryItems.size() > 0) {
- if (alphabetical) {
- Collections.sort(categoryItems);
- }
- result.add(Pair.of(category.getName(), categoryItems));
- }
- }
-
- if (remaining.size() > 0) {
- List<ViewElementDescriptor> otherItems =
- new ArrayList<ViewElementDescriptor>(remaining);
- // Always sorted, we don't have a natural order for these unknowns
- Collections.sort(otherItems);
- if (createCategories) {
- result.add(Pair.of("Other", otherItems));
- } else {
- categoryItems.addAll(otherItems);
- }
- }
-
- if (!createCategories) {
- if (alphabetical) {
- Collections.sort(categoryItems);
- }
- result.add(Pair.of("Views", categoryItems));
- }
-
- return result;
- }
-
- @VisibleForTesting
- Collection<String> getAllFqcns() {
- return getClassToView().keySet();
- }
-
- /**
- * Metadata holder for a particular category - contains the name of the category, its
- * ordinal (for natural/logical sorting order) and views contained in the category
- */
- private static class CategoryData implements Iterable<ViewData>, Comparable<CategoryData> {
- /** Category name */
- private final String mName;
- /** Views included in this category */
- private final List<ViewData> mViews = new ArrayList<ViewData>();
- /** Natural ordering rank */
- private final int mOrdinal = sNextOrdinal++;
-
- /** Constructs a new category with the given name */
- private CategoryData(String name) {
- super();
- mName = name;
- }
-
- /** Adds a new view into this category */
- private void addView(ViewData view) {
- mViews.add(view);
- }
-
- private String getName() {
- return mName;
- }
-
- // Implements Iterable<ViewData> such that we can use for-each on the category to
- // enumerate its views
- @Override
- public Iterator<ViewData> iterator() {
- return mViews.iterator();
- }
-
- // Implements Comparable<CategoryData> such that categories can be naturally sorted
- @Override
- public int compareTo(CategoryData other) {
- return mOrdinal - other.mOrdinal;
- }
- }
-
- /** Metadata holder for a view of a given fully qualified class name */
- private static class ViewData implements Comparable<ViewData> {
- /** The fully qualified class name of the view */
- private final String mFqcn;
- /** Fill preference of the view */
- private final FillPreference mFillPreference;
- /** Skip this item in the palette? */
- private final boolean mSkip;
- /** Must this item be rendered alone? skipped? etc */
- private final RenderMode mRenderMode;
- /** Related views */
- private final String mRelatedTo;
- /** The relative rank of the view for natural ordering */
- private final int mOrdinal = sNextOrdinal++;
- /** List of optional variations */
- private List<ViewData> mVariations;
- /** Display name. Can be null. */
- private String mDisplayName;
- /**
- * Optional initialization string - a comma separate set of name/value pairs to
- * initialize the element with
- */
- private String mInitString;
- /** The name of an icon (known to the {@link IconFactory} to show for this view */
- private String mIconName;
- /** The resize preference of this view */
- private String mResize;
- /** The most commonly set attributes of this view */
- private String mTopAttrs;
-
- /** Constructs a new view data for the given class */
- private ViewData(String fqcn, String displayName,
- FillPreference fillPreference, boolean skip, RenderMode renderMode,
- String relatedTo, String resize, String topAttrs) {
- super();
- mFqcn = fqcn;
- mDisplayName = displayName;
- mFillPreference = fillPreference;
- mSkip = skip;
- mRenderMode = renderMode;
- mRelatedTo = relatedTo;
- mResize = resize;
- mTopAttrs = topAttrs;
- }
-
- /** Returns the {@link FillPreference} for views of this type */
- private FillPreference getFillPreference() {
- return mFillPreference;
- }
-
- /** Fully qualified class name of views of this type */
- private String getFcqn() {
- return mFqcn;
- }
-
- private String getDisplayName() {
- return mDisplayName;
- }
-
- private String getResize() {
- return mResize;
- }
-
- // Implements Comparable<ViewData> such that views can be sorted naturally
- @Override
- public int compareTo(ViewData other) {
- return mOrdinal - other.mOrdinal;
- }
-
- public RenderMode getRenderMode() {
- return mRenderMode;
- }
-
- public boolean getSkip() {
- return mSkip;
- }
-
- public List<String> getRelatedTo() {
- if (mRelatedTo == null || mRelatedTo.length() == 0) {
- return Collections.emptyList();
- } else {
- List<String> result = new ArrayList<String>();
- ViewMetadataRepository repository = ViewMetadataRepository.get();
- Map<String, ViewData> classToView = repository.getClassToView();
-
- List<String> fqns = new ArrayList<String>(classToView.keySet());
- for (String basename : Splitter.on(',').split(mRelatedTo)) {
- boolean found = false;
- for (String fqcn : fqns) {
- String suffix = '.' + basename;
- if (fqcn.endsWith(suffix)) {
- result.add(fqcn);
- found = true;
- break;
- }
- }
- if (basename.equals(VIEW_FRAGMENT) || basename.equals(VIEW_INCLUDE)) {
- result.add(basename);
- } else {
- assert found : basename;
- }
- }
-
- return result;
- }
- }
-
- public List<String> getTopAttributes() {
- // "id" is a top attribute for all views, so it is not included in the XML, we just
- // add it in dynamically here
- if (mTopAttrs == null || mTopAttrs.length() == 0) {
- return Collections.singletonList(ATTR_ID);
- } else {
- String[] split = mTopAttrs.split(","); //$NON-NLS-1$
- List<String> topAttributes = new ArrayList<String>(split.length + 1);
- topAttributes.add(ATTR_ID);
- for (int i = 0, n = split.length; i < n; i++) {
- topAttributes.add(split[i]);
- }
- return Collections.<String>unmodifiableList(topAttributes);
- }
- }
-
- void addVariation(ViewData variation) {
- if (mVariations == null) {
- mVariations = new ArrayList<ViewData>(4);
- }
- mVariations.add(variation);
- }
-
- List<ViewData> getVariations() {
- return mVariations;
- }
-
- boolean hasVariations() {
- return mVariations != null && mVariations.size() > 0;
- }
-
- private void setInitString(String initString) {
- this.mInitString = initString;
- }
-
- private String getInitString() {
- return mInitString;
- }
-
- private void setIconName(String iconName) {
- this.mIconName = iconName;
- }
-
- private String getIconName() {
- return mIconName;
- }
- }
-
- /**
- * Returns the {@link FillPreference} for classes with the given fully qualified class
- * name
- *
- * @param fqcn the fully qualified class name of the view
- * @return a suitable {@link FillPreference} for the given view type
- */
- public FillPreference getFillPreference(String fqcn) {
- ViewData view = getClassToView().get(fqcn);
- if (view != null) {
- return view.getFillPreference();
- }
-
- return FillPreference.NONE;
- }
-
- /**
- * Returns the {@link RenderMode} for classes with the given fully qualified class
- * name
- *
- * @param fqcn the fully qualified class name
- * @return the {@link RenderMode} to use for previews of the given view type
- */
- public RenderMode getRenderMode(String fqcn) {
- ViewData view = getClassToView().get(fqcn);
- if (view != null) {
- return view.getRenderMode();
- }
-
- return RenderMode.NORMAL;
- }
-
- /**
- * Returns the {@link ResizePolicy} for the given class.
- *
- * @param fqcn the fully qualified class name of the target widget
- * @return the {@link ResizePolicy} for the widget, which will never be null (but may
- * be the default of {@link ResizePolicy#full()} if no metadata is found for
- * the given widget)
- */
- public ResizePolicy getResizePolicy(String fqcn) {
- ViewData view = getClassToView().get(fqcn);
- if (view != null) {
- String resize = view.getResize();
- if (resize != null && resize.length() > 0) {
- if ("full".equals(resize)) { //$NON-NLS-1$
- return ResizePolicy.full();
- } else if ("none".equals(resize)) { //$NON-NLS-1$
- return ResizePolicy.none();
- } else if ("horizontal".equals(resize)) { //$NON-NLS-1$
- return ResizePolicy.horizontal();
- } else if ("vertical".equals(resize)) { //$NON-NLS-1$
- return ResizePolicy.vertical();
- } else if ("scaled".equals(resize)) { //$NON-NLS-1$
- return ResizePolicy.scaled();
- } else {
- assert false : resize;
- }
- }
- }
-
- return ResizePolicy.full();
- }
-
- /**
- * Returns true if classes with the given fully qualified class name should be hidden
- * or skipped from the palette
- *
- * @param fqcn the fully qualified class name
- * @return true if views of the given type should be hidden from the palette
- */
- public boolean getSkip(String fqcn) {
- ViewData view = getClassToView().get(fqcn);
- if (view != null) {
- return view.getSkip();
- }
-
- return false;
- }
-
- /**
- * Returns a list of the top (most commonly set) attributes of the given
- * view.
- *
- * @param fqcn the fully qualified class name
- * @return a list, never null but possibly empty, of popular attribute names
- * (not including a namespace prefix)
- */
- public List<String> getTopAttributes(String fqcn) {
- ViewData view = getClassToView().get(fqcn);
- if (view != null) {
- return view.getTopAttributes();
- }
-
- return Collections.singletonList(ATTR_ID);
- }
-
- /**
- * Returns a set of fully qualified names for views that are closely related to the
- * given view
- *
- * @param fqcn the fully qualified class name
- * @return a list, never null but possibly empty, of views that are related to the
- * view of the given type
- */
- public List<String> getRelatedTo(String fqcn) {
- ViewData view = getClassToView().get(fqcn);
- if (view != null) {
- return view.getRelatedTo();
- }
-
- return Collections.emptyList();
- }
-
- /** Render mode for palette preview */
- public enum RenderMode {
- /**
- * Render previews, and it can be rendered as a sibling of many other views in a
- * big linear layout
- */
- NORMAL,
- /** This view needs to be rendered alone */
- ALONE,
- /**
- * Skip this element; it doesn't work or does not produce any visible artifacts
- * (such as the basic layouts)
- */
- SKIP;
-
- /**
- * Returns the {@link RenderMode} for the given render XML attribute
- * value
- *
- * @param render the attribute value in the metadata XML file
- * @return a corresponding {@link RenderMode}, never null
- */
- public static RenderMode get(String render) {
- if ("alone".equals(render)) { //$NON-NLS-1$
- return ALONE;
- } else if ("skip".equals(render)) { //$NON-NLS-1$
- return SKIP;
- } else {
- return NORMAL;
- }
- }
- }
-
- /**
- * Are insets supported yet? This flag indicates whether the {@link #getInsets} method
- * can return valid data, such that clients can avoid doing any work computing the
- * current theme or density if there's no chance that valid insets will be returned
- */
- public static final boolean INSETS_SUPPORTED = false;
-
- /**
- * Returns the insets of widgets with the given fully qualified name, in the given
- * theme and the given screen density.
- *
- * @param fqcn the fully qualified name of the view
- * @param density the screen density
- * @param theme the theme name
- * @return the insets of the visual bounds relative to the view info bounds, or null
- * if not known or if there are no insets
- */
- public static Margins getInsets(String fqcn, Density density, String theme) {
- if (INSETS_SUPPORTED) {
- // Some sample data measured manually for common themes and widgets.
- if (fqcn.equals(FQCN_BUTTON)) {
- if (density == Density.HIGH) {
- if (theme.startsWith(HOLO_PREFIX)) {
- // Theme.Holo, Theme.Holo.Light, WVGA
- return new Margins(5, 5, 5, 5);
- } else {
- // Theme.Light, WVGA
- return new Margins(4, 4, 0, 7);
- }
- } else if (density == Density.MEDIUM) {
- if (theme.startsWith(HOLO_PREFIX)) {
- // Theme.Holo, Theme.Holo.Light, WVGA
- return new Margins(3, 3, 3, 3);
- } else {
- // Theme.Light, HVGA
- return new Margins(2, 2, 0, 4);
- }
- } else if (density == Density.LOW) {
- if (theme.startsWith(HOLO_PREFIX)) {
- // Theme.Holo, Theme.Holo.Light, QVGA
- return new Margins(2, 2, 2, 2);
- } else {
- // Theme.Light, QVGA
- return new Margins(1, 3, 0, 4);
- }
- }
- } else if (fqcn.equals(FQCN_TOGGLE_BUTTON)) {
- if (density == Density.HIGH) {
- if (theme.startsWith(HOLO_PREFIX)) {
- // Theme.Holo, Theme.Holo.Light, WVGA
- return new Margins(5, 5, 5, 5);
- } else {
- // Theme.Light, WVGA
- return new Margins(2, 2, 0, 5);
- }
- } else if (density == Density.MEDIUM) {
- if (theme.startsWith(HOLO_PREFIX)) {
- // Theme.Holo, Theme.Holo.Light, WVGA
- return new Margins(3, 3, 3, 3);
- } else {
- // Theme.Light, HVGA
- return new Margins(0, 1, 0, 3);
- }
- } else if (density == Density.LOW) {
- if (theme.startsWith(HOLO_PREFIX)) {
- // Theme.Holo, Theme.Holo.Light, QVGA
- return new Margins(2, 2, 2, 2);
- } else {
- // Theme.Light, QVGA
- return new Margins(2, 2, 0, 4);
- }
- }
- } else if (fqcn.equals(FQCN_SPINNER)) {
- if (density == Density.HIGH) {
- if (!theme.startsWith(HOLO_PREFIX)) {
- // Theme.Light, WVGA
- return new Margins(3, 4, 2, 8);
- } // Doesn't render on Holo!
- } else if (density == Density.MEDIUM) {
- if (!theme.startsWith(HOLO_PREFIX)) {
- // Theme.Light, HVGA
- return new Margins(1, 1, 0, 4);
- }
- }
- }
- }
-
- return null;
- }
-
- private static final String HOLO_PREFIX = "Theme.Holo"; //$NON-NLS-1$
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/extra-view-metadata.xml b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/extra-view-metadata.xml
deleted file mode 100644
index 6a67b1db4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/extra-view-metadata.xml
+++ /dev/null
@@ -1,452 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
- <!--
- Palette Metadata
-
- This document provides additional designtime metadata for various Android views, such as
- logical palette categories (as well as a natural ordering of the views within their
- categories, fill-preferences (how a view will sets its width and height attributes when
- dropped into other views), and so on.
- -->
-<!DOCTYPE metadata [
-<!--- The metadata consists of a series of category definitions -->
-<!ELEMENT metadata (category)*>
-<!--- Each category has a name and contains a list of views in order -->
-<!ELEMENT category (view)*>
-<!ATTLIST category name CDATA #IMPLIED>
-<!--- Each view is identified by its full class name and has various
- other attributes such as a fill preference -->
-<!ELEMENT view (view)*>
-<!ATTLIST view
- class CDATA #IMPLIED
- name CDATA #IMPLIED
- init CDATA #IMPLIED
- icon CDATA #IMPLIED
- relatedTo CDATA #IMPLIED
- skip (true|false) "false"
- render (alone|skip|normal) "normal"
- fill (none|both|width|height|opposite|width_in_vertical|height_in_horizontal) "none"
- resize (full|none|horizontal|vertical|scaled) "full"
- topAttrs CDATA #IMPLIED
->
-]>
-<metadata>
- <category
- name="Form Widgets">
- <view
- class="android.widget.TextView"
- topAttrs="text,textAppearance,textColor,textSize"
- name="TextView"
- init=""
- relatedTo="EditText,AutoCompleteTextView,MultiAutoCompleteTextView">
- <view
- name="Large Text"
- init="android:textAppearance=?android:attr/textAppearanceLarge,android:text=Large Text" />
- <view
- name="Medium Text"
- init="android:textAppearance=?android:attr/textAppearanceMedium,android:text=Medium Text" />
- <view
- name="Small Text"
- init="android:textAppearance=?android:attr/textAppearanceSmall,android:text=Small Text" />
- </view>
- <view
- class="android.widget.Button"
- topAttrs="text,style"
- name="Button"
- init=""
- relatedTo="ImageButton">
- <view
- name="Small Button"
- init="style=?android:attr/buttonStyleSmall,android:text=Button" />
- </view>
- <view
- class="android.widget.ToggleButton"
- topAttrs="textOff,textOn,style,background"
- relatedTo="CheckBox" />
- <view
- class="android.widget.CheckBox"
- topAttrs="text"
- relatedTo="RadioButton,ToggleButton,CheckedTextView" />
- <view
- class="android.widget.RadioButton"
- topAttrs="text,style"
- relatedTo="CheckBox,ToggleButton" />
- <view
- class="android.widget.CheckedTextView"
- topAttrs="gravity,paddingLeft,paddingRight,checkMark,textAppearance"
- relatedTo="TextView,CheckBox" />
- <view
- class="android.widget.Spinner"
- topAttrs="prompt,entries,style"
- relatedTo="EditText"
- fill="width_in_vertical" />
- <view
- class="android.widget.ProgressBar"
- topAttrs="style,visibility,indeterminate,max"
- relatedTo="SeekBar"
- name="ProgressBar (Large)"
- init="style=?android:attr/progressBarStyleLarge"
- resize="scaled" >
- <view
- name="ProgressBar (Normal)"
- init=""
- resize="scaled" />
- <view
- name="ProgressBar (Small)"
- init="style=?android:attr/progressBarStyleSmall"
- resize="scaled" />
- <view
- name="ProgressBar (Horizontal)"
- init="style=?android:attr/progressBarStyleHorizontal"
- resize="horizontal" />
- </view>
- <view
- class="android.widget.SeekBar"
- topAttrs="paddingLeft,paddingRight,progressDrawable,thumb"
- relatedTo="ProgressBar"
- resize="horizontal"
- fill="width_in_vertical" />
- <view
- class="android.widget.QuickContactBadge"
- topAttrs="src,style,gravity"
- resize="scaled" />
- <view
- class="android.widget.RadioGroup"
- topAttrs="orientation,paddingBottom,paddingTop,style" />
- <view
- class="android.widget.RatingBar"
- topAttrs="numStars,stepSize,style,isIndicator"
- resize="horizontal" />
- <view
- class="android.widget.Switch"
- topAttrs="text,textOff,textOn,style,checked"
- relatedTo="CheckBox,ToggleButton"
- render="alone" />
- </category>
- <category
- name="Text Fields">
- <view
- class="android.widget.EditText"
- topAttrs="hint,inputType,singleLine"
- name="Plain Text"
- init=""
- resize="full"
- relatedTo="Spinner,TextView,AutoCompleteTextView,MultiAutoCompleteTextView"
- fill="width_in_vertical">
- <view
- name="Person Name"
- init="android:inputType=textPersonName" />
- <view
- name="Password"
- init="android:inputType=textPassword" />
- <view
- name="Password (Numeric)"
- init="android:inputType=numberPassword" />
- <view
- name="E-mail"
- init="android:inputType=textEmailAddress" />
- <view
- name="Phone"
- init="android:inputType=phone" />
- <view
- name="Postal Address"
- resize="full"
- init="android:inputType=textPostalAddress" />
- <view
- name="Multiline Text"
- resize="full"
- init="android:inputType=textMultiLine" />
- <view
- name="Time"
- init="android:inputType=time" />
- <view
- name="Date"
- init="android:inputType=date" />
- <view
- name="Number"
- init="android:inputType=number" />
- <view
- name="Number (Signed)"
- init="android:inputType=numberSigned" />
- <view
- name="Number (Decimal)"
- init="android:inputType=numberDecimal" />
- </view>
- <view
- class="android.widget.AutoCompleteTextView"
- topAttrs="singleLine,autoText"
- fill="width_in_vertical" />
- <view
- class="android.widget.MultiAutoCompleteTextView"
- topAttrs="background,hint,imeOptions,inputType,style,textColor"
- fill="width_in_vertical" />
- </category>
- <category
- name="Layouts">
- <view
- class="android.widget.GridLayout"
- fill="opposite"
- render="skip" />
- <view
- class="android.widget.LinearLayout"
- topAttrs="orientation,gravity"
- name="LinearLayout (Vertical)"
- init="android:orientation=vertical"
- icon="VerticalLinearLayout"
- fill="opposite"
- render="skip">
- <view
- name="LinearLayout (Horizontal)" />
- </view>
- <view
- class="android.widget.RelativeLayout"
- topAttrs="background,orientation,paddingLeft"
- fill="opposite"
- render="skip" />
- <view
- class="android.widget.FrameLayout"
- topAttrs="background"
- fill="opposite"
- render="skip" />
- <view
- class="include"
- topAttrs="layout"
- name="Include Other Layout"
- render="skip"
- relatedTo="fragment" />
- <view
- class="fragment"
- topAttrs="class,name"
- name="Fragment"
- fill="opposite"
- render="skip"
- relatedTo="include" />
- <view
- class="android.widget.TableLayout"
- topAttrs="stretchColumns,shrinkColumns,orientation"
- fill="opposite"
- render="skip" />
- <view
- class="android.widget.TableRow"
- topAttrs="paddingTop,focusable,gravity,visibility"
- fill="opposite"
- resize="vertical"
- render="skip" />
- <view
- class="android.widget.Space"
- fill="opposite"
- render="skip" />
- </category>
- <category
- name="Composite">
- <view
- class="android.widget.ListView"
- topAttrs="drawSelectorOnTop,cacheColorHint,divider,background"
- relatedTo="ExpandableListView"
- fill="width_in_vertical" />
- <view
- class="android.widget.ExpandableListView"
- topAttrs="drawSelectorOnTop,cacheColorHint,indicatorLeft,indicatorRight,scrollbars,textSize"
- relatedTo="ListView"
- fill="width_in_vertical" />
- <view
- class="android.widget.GridView"
- topAttrs="numColumns,verticalSpacing,horizontalSpacing"
- fill="opposite"
- render="skip" />
- <view
- class="android.widget.ScrollView"
- topAttrs="fillViewport,orientation,scrollbars"
- relatedTo="HorizontalScrollView"
- fill="opposite"
- render="skip" />
- <view
- class="android.widget.HorizontalScrollView"
- topAttrs="scrollbars,fadingEdgeLength,fadingEdge"
- relatedTo="ScrollView"
- render="skip" />
- <view
- class="android.widget.SearchView"
- topAttrs="iconifiedByDefault,queryHint,maxWidth,minWidth,visibility"
- render="skip" />
- <view
- class="android.widget.SlidingDrawer"
- render="skip"
- topAttrs="allowSingleTap,bottomOffset,content,handle,topOffset,visibility" />
- <view
- class="android.widget.TabHost"
- topAttrs="paddingTop,background,duplicateParentState,visibility"
- fill="width_in_vertical"
- render="alone" />
- <view
- class="android.widget.TabWidget"
- topAttrs="background,paddingLeft,tabStripEnabled,gravity"
- render="alone" />
- <view
- class="android.webkit.WebView"
- topAttrs="background,visibility,textAppearance"
- fill="opposite"
- render="skip" />
- </category>
- <category
- name="Images &amp; Media">
- <view
- class="android.widget.ImageView"
- topAttrs="src,scaleType"
- resize="scaled"
- render="skip"
- relatedTo="ImageButton,VideoView" />
- <view
- class="android.widget.ImageButton"
- topAttrs="src,background,style"
- resize="scaled"
- render="skip"
- relatedTo="Button,ImageView" />
- <view
- class="android.widget.Gallery"
- topAttrs="gravity,spacing,background"
- fill="width_in_vertical"
- render="skip" />
- <view
- class="android.widget.MediaController"
- render="skip" />
- <view
- class="android.widget.VideoView"
- relatedTo="ImageView"
- fill="opposite"
- render="skip" />
- </category>
- <category
- name="Time &amp; Date">
- <view
- class="android.widget.TimePicker"
- topAttrs="visibility"
- relatedTo="DatePicker,CalendarView"
- render="alone" />
- <view
- class="android.widget.DatePicker"
- relatedTo="TimePicker"
- render="alone" />
- <view
- class="android.widget.CalendarView"
- topAttrs="focusable,focusableInTouchMode,visibility"
- fill="both"
- relatedTo="TimePicker,DatePicker" />
- <view
- class="android.widget.Chronometer"
- topAttrs="textSize,gravity,visibility"
- render="skip" />
- <view
- class="android.widget.AnalogClock"
- topAttrs="dial,hand_hour,hand_minute"
- relatedTo="DigitalClock" />
- <view
- class="android.widget.DigitalClock"
- relatedTo="AnalogClock" />
- </category>
- <category
- name="Transitions">
- <view
- class="android.widget.ImageSwitcher"
- topAttrs="inAnimation,outAnimation,cropToPadding,padding,scaleType"
- relatedTo="ViewFlipper,ViewSwitcher,TextSwitcher"
- render="skip" />
- <view
- class="android.widget.AdapterViewFlipper"
- topAttrs="autoStart,flipInterval,inAnimation,outAnimation"
- fill="opposite"
- render="skip" />
- <view
- class="android.widget.StackView"
- topAttrs="loopViews,gravity"
- fill="opposite"
- render="skip" />
- <view
- class="android.widget.TextSwitcher"
- relatedTo="ViewFlipper,ImageSwitcher,ViewSwitcher"
- fill="opposite"
- render="skip" />
- <view
- class="android.widget.ViewAnimator"
- topAttrs="inAnimation,outAnimation"
- fill="opposite"
- render="skip" />
- <view
- class="android.widget.ViewFlipper"
- topAttrs="flipInterval,inAnimation,outAnimation,addStatesFromChildren,measureAllChildren"
- relatedTo="ViewSwitcher,ImageSwitcher,TextSwitcher"
- fill="opposite"
- render="skip" />
- <view
- class="android.widget.ViewSwitcher"
- topAttrs="inAnimation,outAnimation"
- relatedTo="ViewFlipper,ImageSwitcher,TextSwitcher"
- fill="opposite"
- render="skip" />
- </category>
- <category
- name="Advanced">
- <view
- class="requestFocus"
- render="skip" />
- <view
- class="android.view.View"
- topAttrs="background,visibility,style"
- render="skip" />
- <view
- class="android.view.ViewStub"
- topAttrs="layout,inflatedId,visibility"
- render="skip" />
- <view
- class="view"
- topAttrs="class"
- render="skip" />
- <view
- class="android.gesture.GestureOverlayView"
- topAttrs="gestureStrokeType,uncertainGestureColor,eventsInterceptionEnabled,gestureColor,orientation"
- render="skip" />
- <view
- class="android.view.TextureView"
- render="skip" />
- <view
- class="android.view.SurfaceView"
- render="skip" />
- <view
- class="android.widget.NumberPicker"
- topAttrs="focusable,focusableInTouchMode"
- relatedTo="TimePicker,DatePicker"
- render="alone" />
- <view
- class="android.widget.ZoomButton"
- topAttrs="background"
- relatedTo="Button,ZoomControls" />
- <view
- class="android.widget.ZoomControls"
- topAttrs="style,background,gravity"
- relatedTo="ZoomButton"
- resize="none" />
- <view
- class="merge"
- topAttrs="orientation,gravity,style"
- skip="true"
- render="skip" />
- <view
- class="android.widget.DialerFilter"
- fill="width_in_vertical"
- render="skip" />
- <view
- class="android.widget.TwoLineListItem"
- topAttrs="mode,paddingBottom,paddingTop,minHeight,paddingLeft"
- render="skip" />
- <view
- class="android.widget.AbsoluteLayout"
- topAttrs="background,orientation,paddingBottom,paddingLeft,paddingRight,paddingTop"
- name="AbsoluteLayout (Deprecated)"
- fill="opposite"
- render="skip" />
- </category>
- <category
- name="Other">
- <!-- This is the catch-all category which contains unknown views if we encounter any -->
- </category>
- <!-- TODO: Add-ons? -->
-</metadata>
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/rendering-configs.xml b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/rendering-configs.xml
deleted file mode 100644
index 96c7fe7d2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/gre/rendering-configs.xml
+++ /dev/null
@@ -1,382 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- Default configuration for various views to be rendered
- TODO: Remove views that don't have custom configuration
- TODO: Parameterize the custom width (200dip) in the below?
--->
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
- <AnalogClock
- android:layout_width="wrap_content"
- android:id="@+id/android_widget_AnalogClock"
- android:layout_height="75dip">
- </AnalogClock>
- <AutoCompleteTextView
- android:layout_height="wrap_content"
- android:layout_width="200dip"
- android:text="AutoComplete"
- android:id="@+id/android_widget_AutoCompleteTextView">
- </AutoCompleteTextView>
- <Button
- android:text="Button"
- android:id="@+id/android_widget_Button"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content">
- </Button>
- <Button
- android:text="Small"
- style="?android:attr/buttonStyleSmall"
- android:id="@+id/android_widget_SmallButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content">
- </Button>
- <CheckBox
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"
- android:text="CheckBox"
- android:id="@+id/android_widget_CheckBox"
- android:checked="true">
- </CheckBox>
- <CheckedTextView
- android:text="CheckedTextView"
- android:id="@+id/android_widget_CheckedTextView"
- android:layout_height="wrap_content"
- android:layout_width="wrap_content">
- </CheckedTextView>
- <!--
- <Chronometer
- android:text="Chronometer"
- android:id="@+id/android_widget_Chronometer"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content">
- </Chronometer>
- -->
- <DigitalClock
- android:text="DigitalClock"
- android:id="@+id/android_widget_DigitalClock"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content">
- </DigitalClock>
-
- <EditText
- android:id="@+id/PlainText"
- android:text="abc"
- android:layout_width="200dip"
- android:layout_height="wrap_content">
- </EditText>
-
- <EditText
- android:id="@+id/Password"
- android:inputType="textPassword"
- android:text="••••••••"
- android:layout_width="200dip"
- android:layout_height="wrap_content">
- </EditText>
-
- <!-- android:inputType="numberPassword" not used here to allow digits in preview only -->
- <EditText
- android:id="@+id/PasswordNumeric"
- android:text="1•••2•••3"
- android:layout_width="200dip"
- android:layout_height="wrap_content">
- </EditText>
-
- <EditText
- android:id="@+id/PersonName"
- android:inputType="textPersonName"
- android:text="Firstname Lastname"
- android:layout_width="200dip"
- android:layout_height="wrap_content">
- </EditText>
-
- <EditText
- android:id="@+id/Phone"
- android:inputType="phone"
- android:text="(555) 0100"
- android:layout_width="200dip"
- android:layout_height="wrap_content">
- </EditText>
-
- <EditText
- android:id="@+id/PostalAddress"
- android:inputType="textPostalAddress"
- android:text="Address"
- android:layout_width="200dip"
- android:layout_height="100dip">
- </EditText>
-
- <EditText
- android:id="@+id/MultilineText"
- android:inputType="textMultiLine"
- android:text="Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor"
- android:layout_width="200dip"
- android:layout_height="100dip">
- </EditText>
-
- <EditText
- android:id="@+id/Date"
- android:inputType="date"
- android:text="1/1/2011"
- android:layout_width="200dip"
- android:layout_height="wrap_content">
- </EditText>
-
- <EditText
- android:id="@+id/Time"
- android:inputType="time"
- android:text="12:00am"
- android:layout_width="200dip"
- android:layout_height="wrap_content">
- </EditText>
-
- <EditText
- android:id="@+id/Email"
- android:inputType="textEmailAddress"
- android:text="user@domain"
- android:layout_width="200dip"
- android:layout_height="wrap_content">
- </EditText>
-
- <EditText
- android:id="@+id/Number"
- android:inputType="number"
- android:text="42"
- android:layout_width="200dip"
- android:layout_height="wrap_content">
- </EditText>
-
- <EditText
- android:id="@+id/NumberSigned"
- android:inputType="numberSigned"
- android:text="-42"
- android:layout_width="200dip"
- android:layout_height="wrap_content">
- </EditText>
-
- <EditText
- android:id="@+id/NumberDecimal"
- android:inputType="numberDecimal"
- android:text="42.0"
- android:layout_width="200dip"
- android:layout_height="wrap_content">
- </EditText>
-
- <TextView
- android:text="Large"
- android:id="@+id/LargeText"
- android:textAppearance="?android:attr/textAppearanceLarge"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content">
- </TextView>
-
- <TextView
- android:text="Medium"
- android:id="@+id/MediumText"
- android:textAppearance="?android:attr/textAppearanceMedium"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content">
- </TextView>
-
- <TextView
- android:text="Small"
- android:id="@+id/SmallText"
- android:textAppearance="?android:attr/textAppearanceSmall"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content">
- </TextView>
-
- <MultiAutoCompleteTextView
- android:layout_height="wrap_content"
- android:layout_width="200dip"
- android:text="MultiAutoComplete"
- android:id="@+id/android_widget_MultiAutoCompleteTextView">
- </MultiAutoCompleteTextView>
- <ProgressBar
- android:id="@+id/android_widget_ProgressBarNormal"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content">
- </ProgressBar>
- <ProgressBar
- android:id="@+id/android_widget_ProgressBarHorizontal"
- android:layout_width="200dip"
- android:layout_height="wrap_content"
- android:progress="30"
- style="?android:attr/progressBarStyleHorizontal">
- </ProgressBar>
- <ProgressBar
- android:id="@+id/android_widget_ProgressBarLarge"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- style="?android:attr/progressBarStyleLarge">
- </ProgressBar>
- <ProgressBar
- android:id="@+id/android_widget_ProgressBarSmall"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- style="?android:attr/progressBarStyleSmall">
- </ProgressBar>
- <QuickContactBadge
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"
- android:id="@+id/android_widget_QuickContactBadge">
- </QuickContactBadge>
- <RadioButton
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"
- android:id="@+id/android_widget_RadioButton"
- android:text="RadioButton"
- android:checked="true">
- </RadioButton>
- <RatingBar
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"
- android:id="@+id/android_widget_RatingBar"
- android:rating="1">
- </RatingBar>
- <SeekBar
- android:layout_height="wrap_content"
- android:id="@+id/android_widget_SeekBar"
- android:layout_width="200dip"
- android:progress="30">
- </SeekBar>
- <ListView
- android:id="@+id/android_widget_ListView"
- android:layout_width="200dip"
- android:layout_height="60dip"
- android:divider="#333333"
- android:dividerHeight="1px"
- >
- </ListView>
- <ExpandableListView
- android:id="@+id/android_widget_ExpandableListView"
- android:layout_width="200dip"
- android:layout_height="60dip"
- android:divider="#333333"
- android:dividerHeight="1px"
- >
- </ExpandableListView>
- <Spinner
- android:layout_height="wrap_content"
- android:id="@+id/android_widget_Spinner"
- android:layout_width="200dip">
- </Spinner>
- <TextView
- android:text="TextView"
- android:id="@+id/android_widget_TextView"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content">
- </TextView>
- <ToggleButton
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"
- android:checked="false"
- android:id="@+id/android_widget_ToggleButton"
- android:text="ToggleButton">
- </ToggleButton>
- <ZoomButton
- android:id="@+id/android_widget_ZoomButton"
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"
- android:src="@android:drawable/btn_plus">
- </ZoomButton>
- <ZoomControls
- android:id="@+id/android_widget_ZoomControls"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content">
- </ZoomControls>
- <Switch
- android:id="@+id/android_widget_Switch"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- <TimePicker
- android:id="@+id/android_widget_TimePicker"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content">
- </TimePicker>
- <DatePicker
- android:id="@+id/android_widget_DatePicker"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content">
- </DatePicker>
- <CalendarView
- android:id="@+id/android_widget_CalendarView"
- android:layout_width="200dip"
- android:layout_height="200dip">
- </CalendarView>
- <RadioGroup
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"
- android:orientation="horizontal"
- android:id="@+id/android_widget_RadioGroup">
- <RadioButton
- android:checked="true">
- </RadioButton>
- <RadioButton></RadioButton>
- <RadioButton></RadioButton>
- </RadioGroup>
- <TabHost
- android:id="@android:id/tabhost"
- android:layout_width="200dip"
- android:layout_height="100dip">
- <LinearLayout
- android:id="@+id/linearLayout1"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
- <TabWidget
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@android:id/tabs">
- </TabWidget>
- <FrameLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:id="@android:id/tabcontent">
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:id="@+id/Tab1">
- </LinearLayout>
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:id="@+id/Tab2">
- </LinearLayout>
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:id="@+id/Tab3">
- </LinearLayout>
- </FrameLayout>
- </LinearLayout>
- </TabHost>
- <TabHost
- android:id="@android:id/tabhost"
- android:layout_width="70dip"
- android:layout_height="100dip">
- <LinearLayout
- android:id="@+id/android_widget_TabWidget"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
- <TabWidget
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@android:id/tabs">
- </TabWidget>
- <FrameLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:id="@android:id/tabcontent">
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:id="@+id/Tab1">
- </LinearLayout>
- </FrameLayout>
- </LinearLayout>
- </TabHost>
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/BooleanXmlPropertyEditor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/BooleanXmlPropertyEditor.java
deleted file mode 100644
index d6ff4d51d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/BooleanXmlPropertyEditor.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.properties;
-
-import static com.android.SdkConstants.VALUE_FALSE;
-import static com.android.SdkConstants.VALUE_TRUE;
-
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.wb.internal.core.DesignerPlugin;
-import org.eclipse.wb.internal.core.model.property.Property;
-import org.eclipse.wb.internal.core.model.property.table.PropertyTable;
-import org.eclipse.wb.internal.core.utils.ui.DrawUtils;
-
-/**
- * Handle an XML property which represents booleans.
- *
- * Similar to the WindowBuilder PropertyEditor, but operates on Strings rather
- * than Booleans (which means it is a tri-state boolean: true, false, not set)
- */
-public class BooleanXmlPropertyEditor extends XmlPropertyEditor {
- public static final BooleanXmlPropertyEditor INSTANCE = new BooleanXmlPropertyEditor();
-
- private static final Image mTrueImage = DesignerPlugin.getImage("properties/true.png");
- private static final Image mFalseImage = DesignerPlugin.getImage("properties/false.png");
- private static final Image mNullImage =
- DesignerPlugin.getImage("properties/BooleanNull.png");
- private static final Image mUnknownImage =
- DesignerPlugin.getImage("properties/BooleanUnknown.png");
-
- private BooleanXmlPropertyEditor() {
- }
-
- @Override
- public void paint(Property property, GC gc, int x, int y, int width, int height)
- throws Exception {
- Object value = property.getValue();
- assert value == null || value instanceof String;
- if (value == null || value instanceof String) {
- String text = (String) value;
- Image image;
- if (VALUE_TRUE.equals(text)) {
- image = mTrueImage;
- } else if (VALUE_FALSE.equals(text)) {
- image = mFalseImage;
- } else if (text == null) {
- image = mNullImage;
- } else {
- // Probably something like a reference, e.g. @boolean/foo
- image = mUnknownImage;
- }
-
- // draw image
- DrawUtils.drawImageCV(gc, image, x, y, height);
-
- // prepare new position/width
- int imageWidth = image.getBounds().width + 2;
- width -= imageWidth;
-
- // draw text
- if (text != null) {
- x += imageWidth;
- DrawUtils.drawStringCV(gc, text, x, y, width, height);
- }
- }
- }
-
- @Override
- public boolean activate(PropertyTable propertyTable, Property property, Point location)
- throws Exception {
- // check that user clicked on image
- if (location == null || location.x < mTrueImage.getBounds().width + 2) {
- cycleValue(property);
- }
- // don't activate
- return false;
- }
-
- @Override
- public void doubleClick(Property property, Point location) throws Exception {
- cycleValue(property);
- }
-
- /**
- * Cycles through the values
- */
- private void cycleValue(Property property) throws Exception {
- Object value = property.getValue();
- if (value == null || value instanceof String) {
- // Cycle null => true => false => null
- String text = (String) value;
- if (VALUE_TRUE.equals(text)) {
- property.setValue(VALUE_FALSE);
- } else if (VALUE_FALSE.equals(text)) {
- property.setValue(null);
- } else {
- property.setValue(VALUE_TRUE);
- }
- } else {
- assert false;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/EnumXmlPropertyEditor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/EnumXmlPropertyEditor.java
deleted file mode 100644
index f1a3f2aaa..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/EnumXmlPropertyEditor.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.properties;
-
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ListAttributeDescriptor;
-
-import org.eclipse.wb.core.controls.CCombo3;
-import org.eclipse.wb.internal.core.model.property.Property;
-import org.eclipse.wb.internal.core.model.property.editor.AbstractComboPropertyEditor;
-import org.eclipse.wb.internal.core.model.property.editor.ITextValuePropertyEditor;
-
-class EnumXmlPropertyEditor extends AbstractComboPropertyEditor implements
- ITextValuePropertyEditor {
- public static final EnumXmlPropertyEditor INSTANCE = new EnumXmlPropertyEditor();
-
- private EnumXmlPropertyEditor() {
- }
-
- @Override
- protected String getText(Property property) throws Exception {
- Object value = property.getValue();
- if (value == null) {
- return "";
- } else if (value instanceof String) {
- return (String) value;
- } else if (value == Property.UNKNOWN_VALUE) {
- return "<varies>";
- } else {
- return "";
- }
- }
-
- private String[] getItems(Property property) {
- XmlProperty xmlProperty = (XmlProperty) property;
- AttributeDescriptor descriptor = xmlProperty.getDescriptor();
- assert descriptor instanceof ListAttributeDescriptor;
- ListAttributeDescriptor list = (ListAttributeDescriptor) descriptor;
- return list.getValues();
- }
-
- @Override
- protected void addItems(Property property, CCombo3 combo) throws Exception {
- for (String item : getItems(property)) {
- combo.add(item);
- }
- }
-
- @Override
- protected void selectItem(Property property, CCombo3 combo) throws Exception {
- combo.setText(getText(property));
- }
-
- @Override
- protected void toPropertyEx(Property property, CCombo3 combo, int index) throws Exception {
- property.setValue(getItems(property)[index]);
- }
-
- @Override
- public void setText(Property property, String text) throws Exception {
- property.setValue(text);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/FlagXmlPropertyDialog.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/FlagXmlPropertyDialog.java
deleted file mode 100644
index 5e1e7029f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/FlagXmlPropertyDialog.java
+++ /dev/null
@@ -1,217 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.properties;
-
-import com.android.annotations.NonNull;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.google.common.base.Splitter;
-
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.viewers.CheckStateChangedEvent;
-import org.eclipse.jface.viewers.CheckboxTableViewer;
-import org.eclipse.jface.viewers.ICheckStateListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.KeyListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableItem;
-import org.eclipse.wb.internal.core.utils.execution.ExecutionUtils;
-import org.eclipse.wb.internal.core.utils.execution.RunnableEx;
-import org.eclipse.wb.internal.core.utils.ui.dialogs.ResizableDialog;
-
-import java.util.ArrayList;
-import java.util.List;
-
-class FlagXmlPropertyDialog extends ResizableDialog
-implements IStructuredContentProvider, ICheckStateListener, SelectionListener, KeyListener {
- private final String mTitle;
- private final XmlProperty mProperty;
- private final String[] mFlags;
- private final boolean mIsRadio;
-
- private Table mTable;
- private CheckboxTableViewer mViewer;
-
- FlagXmlPropertyDialog(
- @NonNull Shell parentShell,
- @NonNull String title,
- boolean isRadio,
- @NonNull String[] flags,
- @NonNull XmlProperty property) {
- super(parentShell, AdtPlugin.getDefault());
- mTitle = title;
- mIsRadio = isRadio;
- mFlags = flags;
- mProperty = property;
- }
-
- @Override
- protected void configureShell(Shell newShell) {
- super.configureShell(newShell);
- newShell.setText(mTitle);
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite container = (Composite) super.createDialogArea(parent);
-
- mViewer = CheckboxTableViewer.newCheckList(container,
- SWT.BORDER | SWT.FULL_SELECTION | SWT.HIDE_SELECTION);
- mTable = mViewer.getTable();
- mTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
-
- Composite workaround = PropertyFactory.addWorkaround(container);
- if (workaround != null) {
- workaround.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1));
- }
-
- mViewer.setContentProvider(this);
- mViewer.setInput(mFlags);
-
- String current = mProperty.getStringValue();
- if (current != null) {
- Object[] checked = null;
- if (mIsRadio) {
- checked = new String[] { current };
- } else {
- List<String> flags = new ArrayList<String>();
- for (String s : Splitter.on('|').omitEmptyStrings().trimResults().split(current)) {
- flags.add(s);
- }
- checked = flags.toArray(new String[flags.size()]);
- }
- mViewer.setCheckedElements(checked);
- }
- if (mFlags.length > 0) {
- mTable.setSelection(0);
- }
-
- if (mIsRadio) {
- // Enforce single-item selection
- mViewer.addCheckStateListener(this);
- }
- mTable.addSelectionListener(this);
- mTable.addKeyListener(this);
-
- return container;
- }
-
- @Override
- protected void createButtonsForButtonBar(Composite parent) {
- createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
- createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
- }
-
- @Override
- protected Point getDefaultSize() {
- return new Point(450, 400);
- }
-
- @Override
- protected void okPressed() {
- // Apply the value
- ExecutionUtils.runLog(new RunnableEx() {
- @Override
- public void run() throws Exception {
- StringBuilder sb = new StringBuilder(30);
- for (Object o : mViewer.getCheckedElements()) {
- if (sb.length() > 0) {
- sb.append('|');
- }
- sb.append((String) o);
- }
- String value = sb.length() > 0 ? sb.toString() : null;
- mProperty.setValue(value);
- }
- });
-
- // close dialog
- super.okPressed();
- }
-
- // ---- Implements IStructuredContentProvider ----
-
- @Override
- public Object[] getElements(Object inputElement) {
- return (Object []) inputElement;
- }
-
- @Override
- public void dispose() {
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- // ---- Implements ICheckStateListener ----
-
- @Override
- public void checkStateChanged(CheckStateChangedEvent event) {
- // Try to disable other elements that conflict with this
- boolean isChecked = event.getChecked();
- if (isChecked) {
- Object selected = event.getElement();
- for (Object other : mViewer.getCheckedElements()) {
- if (other != selected) {
- mViewer.setChecked(other, false);
- }
- }
- } else {
-
- }
- }
-
- // ---- Implements SelectionListener ----
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- if (e.item instanceof TableItem) {
- TableItem item = (TableItem) e.item;
- item.setChecked(!item.getChecked());
- }
- }
-
- // ---- Implements KeyListener ----
-
- @Override
- public void keyPressed(KeyEvent e) {
- // Let space toggle checked state
- if (e.keyCode == ' ' /* SWT.SPACE requires Eclipse 3.7 */) {
- if (mTable.getSelectionCount() == 1) {
- TableItem item = mTable.getSelection()[0];
- item.setChecked(!item.getChecked());
- }
- }
- }
-
- @Override
- public void keyReleased(KeyEvent e) {
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/PropertyFactory.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/PropertyFactory.java
deleted file mode 100644
index 2b8cfbf43..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/PropertyFactory.java
+++ /dev/null
@@ -1,750 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.properties;
-
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ATTR_LAYOUT_MARGIN;
-import static com.android.SdkConstants.ATTR_LAYOUT_RESOURCE_PREFIX;
-
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.IAttributeInfo;
-import com.android.ide.common.api.IAttributeInfo.Format;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.SeparatorAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.XmlnsAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.CanvasViewInfo;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.ViewMetadataRepository;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.tools.lint.detector.api.LintUtils;
-import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Multimap;
-
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.browser.IWebBrowser;
-import org.eclipse.wb.internal.core.editor.structure.property.PropertyListIntersector;
-import org.eclipse.wb.internal.core.model.property.ComplexProperty;
-import org.eclipse.wb.internal.core.model.property.Property;
-import org.eclipse.wb.internal.core.model.property.category.PropertyCategory;
-import org.eclipse.wb.internal.core.model.property.editor.PropertyEditor;
-import org.eclipse.wb.internal.core.model.property.editor.presentation.ButtonPropertyEditorPresentation;
-
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.EnumSet;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.WeakHashMap;
-
-/**
- * The {@link PropertyFactory} creates (and caches) the set of {@link Property}
- * instances applicable to a given node. It's also responsible for ordering
- * these, and sometimes combining them into {@link ComplexProperty} category
- * nodes.
- * <p>
- * TODO: For any properties that are *set* in XML, they should NOT be labeled as
- * advanced (which would make them disappear)
- */
-public class PropertyFactory {
- /** Disable cache during development only */
- @SuppressWarnings("unused")
- private static final boolean CACHE_ENABLED = true || !LintUtils.assertionsEnabled();
- static {
- if (!CACHE_ENABLED) {
- System.err.println("WARNING: The property cache is disabled");
- }
- }
-
- private static final Property[] NO_PROPERTIES = new Property[0];
-
- private static final int PRIO_FIRST = -100000;
- private static final int PRIO_SECOND = PRIO_FIRST + 10;
- private static final int PRIO_LAST = 100000;
-
- private final GraphicalEditorPart mGraphicalEditorPart;
- private Map<UiViewElementNode, Property[]> mCache =
- new WeakHashMap<UiViewElementNode, Property[]>();
- private UiViewElementNode mCurrentViewCookie;
-
- /** Sorting orders for the properties */
- public enum SortingMode {
- NATURAL,
- BY_ORIGIN,
- ALPHABETICAL;
- }
-
- /** The default sorting mode */
- public static final SortingMode DEFAULT_MODE = SortingMode.BY_ORIGIN;
-
- private SortingMode mSortMode = DEFAULT_MODE;
- private SortingMode mCacheSortMode;
-
- public PropertyFactory(GraphicalEditorPart graphicalEditorPart) {
- mGraphicalEditorPart = graphicalEditorPart;
- }
-
- /**
- * Get the properties for the given list of selection items.
- *
- * @param items the {@link CanvasViewInfo} instances to get an intersected
- * property list for
- * @return the properties for the given items
- */
- public Property[] getProperties(List<CanvasViewInfo> items) {
- mCurrentViewCookie = null;
-
- if (items == null || items.size() == 0) {
- return NO_PROPERTIES;
- } else if (items.size() == 1) {
- CanvasViewInfo item = items.get(0);
- mCurrentViewCookie = item.getUiViewNode();
-
- return getProperties(item);
- } else {
- // intersect properties
- PropertyListIntersector intersector = new PropertyListIntersector();
- for (CanvasViewInfo node : items) {
- intersector.intersect(getProperties(node));
- }
-
- return intersector.getProperties();
- }
- }
-
- private Property[] getProperties(CanvasViewInfo item) {
- UiViewElementNode node = item.getUiViewNode();
- if (node == null) {
- return NO_PROPERTIES;
- }
-
- if (mCacheSortMode != mSortMode) {
- mCacheSortMode = mSortMode;
- mCache.clear();
- }
-
- Property[] properties = mCache.get(node);
- if (!CACHE_ENABLED) {
- properties = null;
- }
- if (properties == null) {
- Collection<? extends Property> propertyList = getProperties(node);
- if (propertyList == null) {
- properties = new Property[0];
- } else {
- properties = propertyList.toArray(new Property[propertyList.size()]);
- }
- mCache.put(node, properties);
- }
- return properties;
- }
-
-
- protected Collection<? extends Property> getProperties(UiViewElementNode node) {
- ViewMetadataRepository repository = ViewMetadataRepository.get();
- ViewElementDescriptor viewDescriptor = (ViewElementDescriptor) node.getDescriptor();
- String fqcn = viewDescriptor.getFullClassName();
- Set<String> top = new HashSet<String>(repository.getTopAttributes(fqcn));
- AttributeDescriptor[] attributeDescriptors = node.getAttributeDescriptors();
-
- List<XmlProperty> properties = new ArrayList<XmlProperty>(attributeDescriptors.length);
- int priority = 0;
- for (final AttributeDescriptor descriptor : attributeDescriptors) {
- // TODO: Filter out non-public properties!!
- // (They shouldn't be in the descriptors at all)
-
- assert !(descriptor instanceof SeparatorAttributeDescriptor); // No longer inserted
- if (descriptor instanceof XmlnsAttributeDescriptor) {
- continue;
- }
-
- PropertyEditor editor = XmlPropertyEditor.INSTANCE;
- IAttributeInfo info = descriptor.getAttributeInfo();
- if (info != null) {
- EnumSet<Format> formats = info.getFormats();
- if (formats.contains(Format.BOOLEAN)) {
- editor = BooleanXmlPropertyEditor.INSTANCE;
- } else if (formats.contains(Format.ENUM)) {
- // We deliberately don't use EnumXmlPropertyEditor.INSTANCE here,
- // since some attributes (such as layout_width) can have not just one
- // of the enum values but custom values such as "42dp" as well. And
- // furthermore, we don't even bother limiting this to formats.size()==1,
- // since the editing experience with the enum property editor is
- // more limited than the text editor plus enum completer anyway
- // (for example, you can't type to filter the values, and clearing
- // the value is harder.)
- }
- }
-
- XmlProperty property = new XmlProperty(editor, this, node, descriptor);
- // Assign ids sequentially. This ensures that the properties will mostly keep their
- // relative order (such as placing width before height), even though we will regroup
- // some (such as properties in the same category, and the layout params etc)
- priority += 10;
-
- PropertyCategory category = PropertyCategory.NORMAL;
- String name = descriptor.getXmlLocalName();
- if (top.contains(name) || PropertyMetadata.isPreferred(name)) {
- category = PropertyCategory.PREFERRED;
- property.setPriority(PRIO_FIRST + priority);
- } else {
- property.setPriority(priority);
-
- // Prefer attributes defined on the specific type of this
- // widget
- // NOTE: This doesn't work very well for TextViews
- /* IAttributeInfo attributeInfo = descriptor.getAttributeInfo();
- if (attributeInfo != null && fqcn.equals(attributeInfo.getDefinedBy())) {
- category = PropertyCategory.PREFERRED;
- } else*/ if (PropertyMetadata.isAdvanced(name)) {
- category = PropertyCategory.ADVANCED;
- }
- }
- if (category != null) {
- property.setCategory(category);
- }
- properties.add(property);
- }
-
- switch (mSortMode) {
- case BY_ORIGIN:
- return sortByOrigin(node, properties);
-
- case ALPHABETICAL:
- return sortAlphabetically(node, properties);
-
- default:
- case NATURAL:
- return sortNatural(node, properties);
- }
- }
-
- protected Collection<? extends Property> sortAlphabetically(
- UiViewElementNode node,
- List<XmlProperty> properties) {
- Collections.sort(properties, Property.ALPHABETICAL);
- return properties;
- }
-
- protected Collection<? extends Property> sortByOrigin(
- UiViewElementNode node,
- List<XmlProperty> properties) {
- List<Property> collapsed = new ArrayList<Property>(properties.size());
- List<Property> layoutProperties = Lists.newArrayListWithExpectedSize(20);
- List<Property> marginProperties = null;
- List<Property> deprecatedProperties = null;
- Map<String, ComplexProperty> categoryToProperty = new HashMap<String, ComplexProperty>();
- Multimap<String, Property> categoryToProperties = ArrayListMultimap.create();
-
- if (properties.isEmpty()) {
- return properties;
- }
-
- ViewElementDescriptor parent = (ViewElementDescriptor) properties.get(0).getDescriptor()
- .getParent();
- Map<String, Integer> categoryPriorities = Maps.newHashMap();
- int nextCategoryPriority = 100;
- while (parent != null) {
- categoryPriorities.put(parent.getFullClassName(), nextCategoryPriority += 100);
- parent = parent.getSuperClassDesc();
- }
-
- for (int i = 0, max = properties.size(); i < max; i++) {
- XmlProperty property = properties.get(i);
-
- AttributeDescriptor descriptor = property.getDescriptor();
- if (descriptor.isDeprecated()) {
- if (deprecatedProperties == null) {
- deprecatedProperties = Lists.newArrayListWithExpectedSize(10);
- }
- deprecatedProperties.add(property);
- continue;
- }
-
- String firstName = descriptor.getXmlLocalName();
- if (firstName.startsWith(ATTR_LAYOUT_RESOURCE_PREFIX)) {
- if (firstName.startsWith(ATTR_LAYOUT_MARGIN)) {
- if (marginProperties == null) {
- marginProperties = Lists.newArrayListWithExpectedSize(5);
- }
- marginProperties.add(property);
- } else {
- layoutProperties.add(property);
- }
- continue;
- }
-
- if (firstName.equals(ATTR_ID)) {
- // Add id to the front (though the layout parameters will be added to
- // the front of this at the end)
- property.setPriority(PRIO_FIRST);
- collapsed.add(property);
- continue;
- }
-
- if (property.getCategory() == PropertyCategory.PREFERRED) {
- collapsed.add(property);
- // Fall through: these are *duplicated* inside their defining categories!
- // However, create a new instance of the property, such that the propertysheet
- // doesn't see the same property instance twice (when selected, it will highlight
- // both, etc.) Also, set the category to Normal such that we don't draw attention
- // to it again. We want it to appear in both places such that somebody looking
- // within a category will always find it there, even if for this specific
- // view type it's a common attribute and replicated up at the top.
- XmlProperty oldProperty = property;
- property = new XmlProperty(oldProperty.getEditor(), this, node,
- oldProperty.getDescriptor());
- property.setPriority(oldProperty.getPriority());
- }
-
- IAttributeInfo attributeInfo = descriptor.getAttributeInfo();
- if (attributeInfo != null && attributeInfo.getDefinedBy() != null) {
- String category = attributeInfo.getDefinedBy();
- ComplexProperty complex = categoryToProperty.get(category);
- if (complex == null) {
- complex = new ComplexProperty(
- category.substring(category.lastIndexOf('.') + 1),
- "[]",
- null /* properties */);
- categoryToProperty.put(category, complex);
- Integer categoryPriority = categoryPriorities.get(category);
- if (categoryPriority != null) {
- complex.setPriority(categoryPriority);
- } else {
- // Descriptor for an attribute whose definedBy does *not*
- // correspond to one of the known superclasses of this widget.
- // This sometimes happens; for example, a RatingBar will pull in
- // an ImageView's minWidth attribute. Probably an error in the
- // metadata, but deal with it gracefully here.
- categoryPriorities.put(category, nextCategoryPriority += 100);
- complex.setPriority(nextCategoryPriority);
- }
- }
- categoryToProperties.put(category, property);
- continue;
- } else {
- collapsed.add(property);
- }
- }
-
- // Update the complex properties
- for (String category : categoryToProperties.keySet()) {
- Collection<Property> subProperties = categoryToProperties.get(category);
- if (subProperties.size() > 1) {
- ComplexProperty complex = categoryToProperty.get(category);
- assert complex != null : category;
- Property[] subArray = new Property[subProperties.size()];
- complex.setProperties(subProperties.toArray(subArray));
- //complex.setPriority(subArray[0].getPriority());
-
- collapsed.add(complex);
-
- boolean allAdvanced = true;
- boolean isPreferred = false;
- for (Property p : subProperties) {
- PropertyCategory c = p.getCategory();
- if (c != PropertyCategory.ADVANCED) {
- allAdvanced = false;
- }
- if (c == PropertyCategory.PREFERRED) {
- isPreferred = true;
- }
- }
- if (isPreferred) {
- complex.setCategory(PropertyCategory.PREFERRED);
- } else if (allAdvanced) {
- complex.setCategory(PropertyCategory.ADVANCED);
- }
- } else if (subProperties.size() == 1) {
- collapsed.add(subProperties.iterator().next());
- }
- }
-
- if (layoutProperties.size() > 0 || marginProperties != null) {
- if (marginProperties != null) {
- XmlProperty[] m =
- marginProperties.toArray(new XmlProperty[marginProperties.size()]);
- Property marginProperty = new ComplexProperty(
- "Margins",
- "[]",
- m);
- layoutProperties.add(marginProperty);
- marginProperty.setPriority(PRIO_LAST);
-
- for (XmlProperty p : m) {
- p.setParent(marginProperty);
- }
- }
- Property[] l = layoutProperties.toArray(new Property[layoutProperties.size()]);
- Arrays.sort(l, Property.PRIORITY);
- Property property = new ComplexProperty(
- "Layout Parameters",
- "[]",
- l);
- for (Property p : l) {
- if (p instanceof XmlProperty) {
- ((XmlProperty) p).setParent(property);
- }
- }
- property.setCategory(PropertyCategory.PREFERRED);
- collapsed.add(property);
- property.setPriority(PRIO_SECOND);
- }
-
- if (deprecatedProperties != null && deprecatedProperties.size() > 0) {
- Property property = new ComplexProperty(
- "Deprecated",
- "(Deprecated Properties)",
- deprecatedProperties.toArray(new Property[deprecatedProperties.size()]));
- property.setPriority(PRIO_LAST);
- collapsed.add(property);
- }
-
- Collections.sort(collapsed, Property.PRIORITY);
-
- return collapsed;
- }
-
- protected Collection<? extends Property> sortNatural(
- UiViewElementNode node,
- List<XmlProperty> properties) {
- Collections.sort(properties, Property.ALPHABETICAL);
- List<Property> collapsed = new ArrayList<Property>(properties.size());
- List<Property> layoutProperties = Lists.newArrayListWithExpectedSize(20);
- List<Property> marginProperties = null;
- List<Property> deprecatedProperties = null;
- Map<String, ComplexProperty> categoryToProperty = new HashMap<String, ComplexProperty>();
- Multimap<String, Property> categoryToProperties = ArrayListMultimap.create();
-
- for (int i = 0, max = properties.size(); i < max; i++) {
- XmlProperty property = properties.get(i);
-
- AttributeDescriptor descriptor = property.getDescriptor();
- if (descriptor.isDeprecated()) {
- if (deprecatedProperties == null) {
- deprecatedProperties = Lists.newArrayListWithExpectedSize(10);
- }
- deprecatedProperties.add(property);
- continue;
- }
-
- String firstName = descriptor.getXmlLocalName();
- if (firstName.startsWith(ATTR_LAYOUT_RESOURCE_PREFIX)) {
- if (firstName.startsWith(ATTR_LAYOUT_MARGIN)) {
- if (marginProperties == null) {
- marginProperties = Lists.newArrayListWithExpectedSize(5);
- }
- marginProperties.add(property);
- } else {
- layoutProperties.add(property);
- }
- continue;
- }
-
- if (firstName.equals(ATTR_ID)) {
- // Add id to the front (though the layout parameters will be added to
- // the front of this at the end)
- property.setPriority(PRIO_FIRST);
- collapsed.add(property);
- continue;
- }
-
- String category = PropertyMetadata.getCategory(firstName);
- if (category != null) {
- ComplexProperty complex = categoryToProperty.get(category);
- if (complex == null) {
- complex = new ComplexProperty(
- category,
- "[]",
- null /* properties */);
- categoryToProperty.put(category, complex);
- complex.setPriority(property.getPriority());
- }
- categoryToProperties.put(category, property);
- continue;
- }
-
- // Index of second word in the first name, so in fooBar it's 3 (index of 'B')
- int firstNameIndex = firstName.length();
- for (int k = 0, kn = firstName.length(); k < kn; k++) {
- if (Character.isUpperCase(firstName.charAt(k))) {
- firstNameIndex = k;
- break;
- }
- }
-
- // Scout forwards and see how many properties we can combine
- int j = i + 1;
- if (property.getCategory() != PropertyCategory.PREFERRED
- && !property.getDescriptor().isDeprecated()) {
- for (; j < max; j++) {
- XmlProperty next = properties.get(j);
- String nextName = next.getName();
- if (nextName.regionMatches(0, firstName, 0, firstNameIndex)
- // Also make sure we begin the second word at the next
- // character; if not, we could have something like
- // scrollBar
- // scrollingBehavior
- && nextName.length() > firstNameIndex
- && Character.isUpperCase(nextName.charAt(firstNameIndex))) {
-
- // Deprecated attributes, and preferred attributes, should not
- // be pushed into normal clusters (preferred stay top-level
- // and sort to the top, deprecated are all put in the same cluster at
- // the end)
-
- if (next.getCategory() == PropertyCategory.PREFERRED) {
- break;
- }
- if (next.getDescriptor().isDeprecated()) {
- break;
- }
-
- // This property should be combined with the previous
- // property
- } else {
- break;
- }
- }
- }
- if (j - i > 1) {
- // Combining multiple properties: all the properties from i
- // through j inclusive
- XmlProperty[] subprops = new XmlProperty[j - i];
- for (int k = i, index = 0; k < j; k++, index++) {
- subprops[index] = properties.get(k);
- }
- Arrays.sort(subprops, Property.PRIORITY);
-
- // See if we can compute a LONGER base than just the first word.
- // For example, if we have "lineSpacingExtra" and "lineSpacingMultiplier"
- // we'd like the base to be "lineSpacing", not "line".
- int common = firstNameIndex;
- for (int k = firstNameIndex + 1, n = firstName.length(); k < n; k++) {
- if (Character.isUpperCase(firstName.charAt(k))) {
- common = k;
- break;
- }
- }
- if (common > firstNameIndex) {
- for (int k = 0, n = subprops.length; k < n; k++) {
- String nextName = subprops[k].getName();
- if (nextName.regionMatches(0, firstName, 0, common)
- // Also make sure we begin the second word at the next
- // character; if not, we could have something like
- // scrollBar
- // scrollingBehavior
- && nextName.length() > common
- && Character.isUpperCase(nextName.charAt(common))) {
- // New prefix is okay
- } else {
- common = firstNameIndex;
- break;
- }
- }
- firstNameIndex = common;
- }
-
- String base = firstName.substring(0, firstNameIndex);
- base = DescriptorsUtils.capitalize(base);
- Property complexProperty = new ComplexProperty(
- base,
- "[]",
- subprops);
- complexProperty.setPriority(subprops[0].getPriority());
- //complexProperty.setCategory(PropertyCategory.PREFERRED);
- collapsed.add(complexProperty);
- boolean allAdvanced = true;
- boolean isPreferred = false;
- for (XmlProperty p : subprops) {
- p.setParent(complexProperty);
- PropertyCategory c = p.getCategory();
- if (c != PropertyCategory.ADVANCED) {
- allAdvanced = false;
- }
- if (c == PropertyCategory.PREFERRED) {
- isPreferred = true;
- }
- }
- if (isPreferred) {
- complexProperty.setCategory(PropertyCategory.PREFERRED);
- } else if (allAdvanced) {
- complexProperty.setCategory(PropertyCategory.PREFERRED);
- }
- } else {
- // Add the individual properties (usually 1, sometimes 2
- for (int k = i; k < j; k++) {
- collapsed.add(properties.get(k));
- }
- }
-
- i = j - 1; // -1: compensate in advance for the for-loop adding 1
- }
-
- // Update the complex properties
- for (String category : categoryToProperties.keySet()) {
- Collection<Property> subProperties = categoryToProperties.get(category);
- if (subProperties.size() > 1) {
- ComplexProperty complex = categoryToProperty.get(category);
- assert complex != null : category;
- Property[] subArray = new Property[subProperties.size()];
- complex.setProperties(subProperties.toArray(subArray));
- complex.setPriority(subArray[0].getPriority());
- collapsed.add(complex);
-
- boolean allAdvanced = true;
- boolean isPreferred = false;
- for (Property p : subProperties) {
- PropertyCategory c = p.getCategory();
- if (c != PropertyCategory.ADVANCED) {
- allAdvanced = false;
- }
- if (c == PropertyCategory.PREFERRED) {
- isPreferred = true;
- }
- }
- if (isPreferred) {
- complex.setCategory(PropertyCategory.PREFERRED);
- } else if (allAdvanced) {
- complex.setCategory(PropertyCategory.ADVANCED);
- }
- } else if (subProperties.size() == 1) {
- collapsed.add(subProperties.iterator().next());
- }
- }
-
- if (layoutProperties.size() > 0 || marginProperties != null) {
- if (marginProperties != null) {
- XmlProperty[] m =
- marginProperties.toArray(new XmlProperty[marginProperties.size()]);
- Property marginProperty = new ComplexProperty(
- "Margins",
- "[]",
- m);
- layoutProperties.add(marginProperty);
- marginProperty.setPriority(PRIO_LAST);
-
- for (XmlProperty p : m) {
- p.setParent(marginProperty);
- }
- }
- Property[] l = layoutProperties.toArray(new Property[layoutProperties.size()]);
- Arrays.sort(l, Property.PRIORITY);
- Property property = new ComplexProperty(
- "Layout Parameters",
- "[]",
- l);
- for (Property p : l) {
- if (p instanceof XmlProperty) {
- ((XmlProperty) p).setParent(property);
- }
- }
- property.setCategory(PropertyCategory.PREFERRED);
- collapsed.add(property);
- property.setPriority(PRIO_SECOND);
- }
-
- if (deprecatedProperties != null && deprecatedProperties.size() > 0) {
- Property property = new ComplexProperty(
- "Deprecated",
- "(Deprecated Properties)",
- deprecatedProperties.toArray(new Property[deprecatedProperties.size()]));
- property.setPriority(PRIO_LAST);
- collapsed.add(property);
- }
-
- Collections.sort(collapsed, Property.PRIORITY);
-
- return collapsed;
- }
-
- @Nullable
- GraphicalEditorPart getGraphicalEditor() {
- return mGraphicalEditorPart;
- }
-
- // HACK: This should be passed into each property instead
- public Object getCurrentViewObject() {
- return mCurrentViewCookie;
- }
-
- public void setSortingMode(SortingMode sortingMode) {
- mSortMode = sortingMode;
- }
-
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=388574
- public static Composite addWorkaround(Composite parent) {
- if (ButtonPropertyEditorPresentation.isInWorkaround) {
- Composite top = new Composite(parent, SWT.NONE);
- top.setLayout(new GridLayout(1, false));
- Label label = new Label(top, SWT.WRAP);
- label.setText(
- "This dialog is shown instead of an inline text editor as a\n" +
- "workaround for an Eclipse bug specific to OSX Mountain Lion.\n" +
- "It should be fixed in Eclipse 4.3.");
- label.setForeground(top.getDisplay().getSystemColor(SWT.COLOR_RED));
- GridData data = new GridData();
- data.grabExcessVerticalSpace = false;
- data.grabExcessHorizontalSpace = false;
- data.horizontalAlignment = GridData.FILL;
- data.verticalAlignment = GridData.BEGINNING;
- label.setLayoutData(data);
-
- Link link = new Link(top, SWT.NO_FOCUS);
- link.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1));
- link.setText("<a>https://bugs.eclipse.org/bugs/show_bug.cgi?id=388574</a>");
- link.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent event) {
- try {
- IWorkbench workbench = PlatformUI.getWorkbench();
- IWebBrowser browser = workbench.getBrowserSupport().getExternalBrowser();
- browser.openURL(new URL(event.text));
- } catch (Exception e) {
- String message = String.format(
- "Could not open browser. Vist\n%1$s\ninstead.",
- event.text);
- MessageDialog.openError(((Link)event.getSource()).getShell(),
- "Browser Error", message);
- }
- }
- });
-
- return top;
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/PropertyMetadata.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/PropertyMetadata.java
deleted file mode 100644
index b230aa99d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/PropertyMetadata.java
+++ /dev/null
@@ -1,329 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.properties;
-
-import static com.android.SdkConstants.ATTR_CONTENT_DESCRIPTION;
-import static com.android.SdkConstants.ATTR_HINT;
-import static com.android.SdkConstants.ATTR_TEXT;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-
-import java.util.HashSet;
-import java.util.Set;
-
-/** Extra metadata about properties not available from the descriptors (yet) */
-class PropertyMetadata {
- static boolean isAdvanced(@NonNull String name) {
- return sAdvanced.contains(name);
- }
-
- static boolean isPreferred(@NonNull String name) {
- return sPreferred.contains(name);
- }
-
- @Nullable
- static String getCategory(@NonNull String name) {
- //return sCategories.get(name);
- assert false : "Disabled to save memory since this method is not currently used.";
- return null;
- }
-
- private static final int ADVANCED_MAP_SIZE = 134;
- private static final Set<String> sAdvanced = new HashSet<String>(ADVANCED_MAP_SIZE);
- static {
- // This metadata about which attributes are "advanced" was generated as follows:
- // First, I ran the sdk/attribute_stats project with the --list argument to dump out
- // *all* referenced XML attributes found in layouts, run against a bunch of
- // sample Android code (development/samples, packages/apps, vendor, etc.
- //
- // Then I iterated over the LayoutDescriptors' ViewElementDescriptors'
- // AttributeDescriptors, and basically diffed the two: any attribute descriptor name
- // which was *not* found in any of the representative layouts is added here
- // as an advanced property.
- //
- // Then I manually edited in some attributes that were referenced in the sample
- // layouts but which I still consider to be advanced:
- // -- nothing right now
-
- // I also manually *removed* some entries from the below list:
- // drawableBottom (the others, drawableTop, drawableLeft and drawableRight were all
- // NOT on the list so keep bottom off for symmetry)
- // rating (useful when you deal with a RatingsBar component)
-
-
- // Automatically generated, see above:
- sAdvanced.add("alwaysDrawnWithCache");
- sAdvanced.add("animationCache");
- sAdvanced.add("animationDuration");
- sAdvanced.add("animationResolution");
- sAdvanced.add("baseline");
- sAdvanced.add("bufferType");
- sAdvanced.add("calendarViewShown");
- sAdvanced.add("completionHint");
- sAdvanced.add("completionHintView");
- sAdvanced.add("completionThreshold");
- sAdvanced.add("cursorVisible");
- sAdvanced.add("dateTextAppearance");
- sAdvanced.add("dial");
- sAdvanced.add("digits");
- sAdvanced.add("disableChildrenWhenDisabled");
- sAdvanced.add("disabledAlpha");
- sAdvanced.add("drawableAlpha");
- sAdvanced.add("drawableEnd");
- sAdvanced.add("drawableStart");
- sAdvanced.add("drawingCacheQuality");
- sAdvanced.add("dropDownAnchor");
- sAdvanced.add("dropDownHeight");
- sAdvanced.add("dropDownHorizontalOffset");
- sAdvanced.add("dropDownSelector");
- sAdvanced.add("dropDownVerticalOffset");
- sAdvanced.add("dropDownWidth");
- sAdvanced.add("editorExtras");
- sAdvanced.add("ems");
- sAdvanced.add("endYear");
- sAdvanced.add("eventsInterceptionEnabled");
- sAdvanced.add("fadeDuration");
- sAdvanced.add("fadeEnabled");
- sAdvanced.add("fadeOffset");
- sAdvanced.add("fadeScrollbars");
- sAdvanced.add("filterTouchesWhenObscured");
- sAdvanced.add("firstDayOfWeek");
- sAdvanced.add("flingable");
- sAdvanced.add("focusedMonthDateColor");
- sAdvanced.add("foregroundInsidePadding");
- sAdvanced.add("format");
- sAdvanced.add("gestureColor");
- sAdvanced.add("gestureStrokeAngleThreshold");
- sAdvanced.add("gestureStrokeLengthThreshold");
- sAdvanced.add("gestureStrokeSquarenessThreshold");
- sAdvanced.add("gestureStrokeType");
- sAdvanced.add("gestureStrokeWidth");
- sAdvanced.add("hand_hour");
- sAdvanced.add("hand_minute");
- sAdvanced.add("hapticFeedbackEnabled");
- sAdvanced.add("id");
- sAdvanced.add("imeActionId");
- sAdvanced.add("imeActionLabel");
- sAdvanced.add("indeterminateDrawable");
- sAdvanced.add("indeterminateDuration");
- sAdvanced.add("inputMethod");
- sAdvanced.add("interpolator");
- sAdvanced.add("isScrollContainer");
- sAdvanced.add("keepScreenOn");
- sAdvanced.add("layerType");
- sAdvanced.add("layoutDirection");
- sAdvanced.add("maxDate");
- sAdvanced.add("minDate");
- sAdvanced.add("mode");
- sAdvanced.add("numeric");
- sAdvanced.add("paddingEnd");
- sAdvanced.add("paddingStart");
- sAdvanced.add("persistentDrawingCache");
- sAdvanced.add("phoneNumber");
- sAdvanced.add("popupBackground");
- sAdvanced.add("popupPromptView");
- sAdvanced.add("privateImeOptions");
- sAdvanced.add("quickContactWindowSize");
- //sAdvanced.add("rating");
- sAdvanced.add("requiresFadingEdge");
- sAdvanced.add("rotation");
- sAdvanced.add("rotationX");
- sAdvanced.add("rotationY");
- sAdvanced.add("saveEnabled");
- sAdvanced.add("scaleX");
- sAdvanced.add("scaleY");
- sAdvanced.add("scrollX");
- sAdvanced.add("scrollY");
- sAdvanced.add("scrollbarAlwaysDrawHorizontalTrack");
- sAdvanced.add("scrollbarDefaultDelayBeforeFade");
- sAdvanced.add("scrollbarFadeDuration");
- sAdvanced.add("scrollbarSize");
- sAdvanced.add("scrollbarThumbHorizontal");
- sAdvanced.add("scrollbarThumbVertical");
- sAdvanced.add("scrollbarTrackHorizontal");
- sAdvanced.add("scrollbarTrackVertical");
- sAdvanced.add("secondaryProgress");
- sAdvanced.add("selectedDateVerticalBar");
- sAdvanced.add("selectedWeekBackgroundColor");
- sAdvanced.add("selectionDivider");
- sAdvanced.add("selectionDividerHeight");
- sAdvanced.add("showWeekNumber");
- sAdvanced.add("shownWeekCount");
- sAdvanced.add("solidColor");
- sAdvanced.add("soundEffectsEnabled");
- sAdvanced.add("spinnerMode");
- sAdvanced.add("spinnersShown");
- sAdvanced.add("startYear");
- sAdvanced.add("switchMinWidth");
- sAdvanced.add("switchPadding");
- sAdvanced.add("switchTextAppearance");
- sAdvanced.add("textColorHighlight");
- sAdvanced.add("textCursorDrawable");
- sAdvanced.add("textDirection");
- sAdvanced.add("textEditNoPasteWindowLayout");
- sAdvanced.add("textEditPasteWindowLayout");
- sAdvanced.add("textEditSideNoPasteWindowLayout");
- sAdvanced.add("textEditSidePasteWindowLayout");
- sAdvanced.add("textEditSuggestionItemLayout");
- sAdvanced.add("textIsSelectable");
- sAdvanced.add("textOff");
- sAdvanced.add("textOn");
- sAdvanced.add("textScaleX");
- sAdvanced.add("textSelectHandle");
- sAdvanced.add("textSelectHandleLeft");
- sAdvanced.add("textSelectHandleRight");
- sAdvanced.add("thumbOffset");
- sAdvanced.add("thumbTextPadding");
- sAdvanced.add("tint");
- sAdvanced.add("track");
- sAdvanced.add("transformPivotX");
- sAdvanced.add("transformPivotY");
- sAdvanced.add("translationX");
- sAdvanced.add("translationY");
- sAdvanced.add("uncertainGestureColor");
- sAdvanced.add("unfocusedMonthDateColor");
- sAdvanced.add("unselectedAlpha");
- sAdvanced.add("verticalScrollbarPosition");
- sAdvanced.add("weekDayTextAppearance");
- sAdvanced.add("weekNumberColor");
- sAdvanced.add("weekSeparatorLineColor");
-
- assert sAdvanced.size() == ADVANCED_MAP_SIZE : sAdvanced.size();
-
- }
-
- private static final int PREFERRED_MAP_SIZE = 7;
- private static final Set<String> sPreferred = new HashSet<String>(PREFERRED_MAP_SIZE);
- static {
- // Manual registrations of attributes that should be treated as preferred if
- // they are available on a widget even if they don't show up in the top 10% of
- // usages (which the view metadata provides)
- sPreferred.add(ATTR_TEXT);
- sPreferred.add(ATTR_CONTENT_DESCRIPTION);
- sPreferred.add(ATTR_HINT);
- sPreferred.add("indeterminate");
- sPreferred.add("progress");
- sPreferred.add("rating");
- sPreferred.add("max");
- assert sPreferred.size() == PREFERRED_MAP_SIZE : sPreferred.size();
- }
-
- /*
- private static final int CATEGORY_MAP_SIZE = 62;
- private static final Map<String, String> sCategories =
- new HashMap<String, String>(CATEGORY_MAP_SIZE);
- static {
- sCategories.put("requiresFadingEdge", "Scrolling");
- sCategories.put("fadingEdgeLength", "Scrolling");
- sCategories.put("scrollbarSize", "Scrolling");
- sCategories.put("scrollbarThumbVertical", "Scrolling");
- sCategories.put("scrollbarThumbHorizontal", "Scrolling");
- sCategories.put("scrollbarTrackHorizontal", "Scrolling");
- sCategories.put("scrollbarTrackVertical", "Scrolling");
- sCategories.put("scrollbarAlwaysDrawHorizontalTrack", "Scrolling");
- sCategories.put("scrollbarAlwaysDrawVerticalTrack", "Scrolling");
- sCategories.put("scrollViewStyle", "Scrolling");
- sCategories.put("scrollbars", "Scrolling");
- sCategories.put("scrollingCache", "Scrolling");
- sCategories.put("scrollHorizontally", "Scrolling");
- sCategories.put("scrollbarFadeDuration", "Scrolling");
- sCategories.put("scrollbarDefaultDelayBeforeFade", "Scrolling");
- sCategories.put("fastScrollEnabled", "Scrolling");
- sCategories.put("smoothScrollbar", "Scrolling");
- sCategories.put("isScrollContainer", "Scrolling");
- sCategories.put("fadeScrollbars", "Scrolling");
- sCategories.put("overScrollMode", "Scrolling");
- sCategories.put("overScrollHeader", "Scrolling");
- sCategories.put("overScrollFooter", "Scrolling");
- sCategories.put("verticalScrollbarPosition", "Scrolling");
- sCategories.put("fastScrollAlwaysVisible", "Scrolling");
- sCategories.put("fastScrollThumbDrawable", "Scrolling");
- sCategories.put("fastScrollPreviewBackgroundLeft", "Scrolling");
- sCategories.put("fastScrollPreviewBackgroundRight", "Scrolling");
- sCategories.put("fastScrollTrackDrawable", "Scrolling");
- sCategories.put("fastScrollOverlayPosition", "Scrolling");
- sCategories.put("horizontalScrollViewStyle", "Scrolling");
- sCategories.put("fastScrollTextColor", "Scrolling");
- sCategories.put("scrollbarSize", "Scrolling");
- sCategories.put("scrollbarSize", "Scrolling");
- sCategories.put("scrollbarSize", "Scrolling");
- sCategories.put("scrollbarSize", "Scrolling");
- sCategories.put("scrollbarSize", "Scrolling");
-
- // TODO: All the styles: radioButtonStyle, ratingBarStyle, progressBarStyle, ...
-
- sCategories.put("focusable", "Focus");
- sCategories.put("focusableInTouchMode", "Focus");
- sCategories.put("nextFocusLeft", "Focus");
- sCategories.put("nextFocusRight", "Focus");
- sCategories.put("nextFocusUp", "Focus");
- sCategories.put("nextFocusDown", "Focus");
- sCategories.put("descendantFocusability", "Focus");
- sCategories.put("selectAllOnFocus", "Focus");
- sCategories.put("nextFocusForward", "Focus");
- sCategories.put("colorFocusedHighlight", "Focus");
-
- sCategories.put("rotation", "Transforms");
- sCategories.put("scrollX", "Transforms");
- sCategories.put("scrollY", "Transforms");
- sCategories.put("rotationX", "Transforms");
- sCategories.put("rotationY", "Transforms");
- sCategories.put("transformPivotX", "Transforms");
- sCategories.put("transformPivotY", "Transforms");
- sCategories.put("translationX", "Transforms");
- sCategories.put("translationY", "Transforms");
- sCategories.put("scaleX", "Transforms");
- sCategories.put("scaleY", "Transforms");
-
- sCategories.put("width", "Size");
- sCategories.put("height", "Size");
- sCategories.put("minWidth", "Size");
- sCategories.put("minHeight", "Size");
-
- sCategories.put("longClickable", "Clicks");
- sCategories.put("onClick", "Clicks");
- sCategories.put("clickable", "Clicks");
- sCategories.put("hapticFeedbackEnabled", "Clicks");
-
- sCategories.put("duplicateParentState", "State");
- sCategories.put("addStatesFromChildren", "State");
-
- assert sCategories.size() == CATEGORY_MAP_SIZE : sCategories.size();
- }
- */
-
-// private static final int PRIO_CLZ_LAYOUT = 1000;
-// private static final int PRIO_CLZ_TEXT = 2000;
-// private static final int PRIO_CLZ_DRAWABLE = 3000;
-// private static final int PRIO_CLZ_ANIMATION = 4000;
-// private static final int PRIO_CLZ_FOCUS = 5000;
-//
-// private static final int PRIORITY_MAP_SIZE = 100;
-// private static final Map<String, Integer> sPriorities =
-// new HashMap<String, Integer>(PRIORITY_MAP_SIZE);
-// static {
-// // TODO: I should put all the properties roughly based on their original order: this
-// // will correspond to the rough order they came in with
-// // TODO: How can I make similar complex properties show up adjacent; e.g. min and max
-// sPriorities.put("min", PRIO_CLZ_LAYOUT);
-// sPriorities.put("max", PRIO_CLZ_LAYOUT);
-//
-// assert sPriorities.size() == PRIORITY_MAP_SIZE : sPriorities.size();
-// }
-
- // TODO: Emit metadata into a file
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/PropertySheetPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/PropertySheetPage.java
deleted file mode 100644
index 58fddc0ee..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/PropertySheetPage.java
+++ /dev/null
@@ -1,403 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.properties;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.CanvasViewInfo;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart;
-import com.android.ide.eclipse.adt.internal.editors.layout.properties.PropertyFactory.SortingMode;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.IUiUpdateListener;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IStatusLineManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TreeSelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.MenuItem;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.part.Page;
-import org.eclipse.ui.views.properties.IPropertySheetPage;
-import org.eclipse.wb.internal.core.editor.structure.IPage;
-import org.eclipse.wb.internal.core.model.property.Property;
-import org.eclipse.wb.internal.core.model.property.table.IPropertyExceptionHandler;
-import org.eclipse.wb.internal.core.model.property.table.PropertyTable;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-
-/**
- * Property sheet page used when the graphical layout editor is chosen
- */
-public class PropertySheetPage extends Page
- implements IPropertySheetPage, IUiUpdateListener, IPage {
- private PropertyTable mPropertyTable;
- private final GraphicalEditorPart mEditor;
- private Property mActiveProperty;
- private Action mDefaultValueAction;
- private Action mShowAdvancedPropertiesAction;
- private Action mSortAlphaAction;
- private Action mCollapseAll;
- private Action mExpandAll;
- private List<CanvasViewInfo> mSelection;
-
- private static final String EXPAND_DISABLED_ICON = "expandall-disabled"; //$NON-NLS-1$
- private static final String EXPAND_ICON = "expandall"; //$NON-NLS-1$
- private static final String DEFAULT_ICON = "properties_default"; //$NON-NLS-1$
- private static final String ADVANCED_ICON = "filter_advanced_properties"; //$NON-NLS-1$
- private static final String ALPHA_ICON = "sort_alpha"; //$NON-NLS-1$
- // TODO: goto-definition.png
-
- /**
- * Constructs a new {@link PropertySheetPage} associated with the given
- * editor
- *
- * @param editor the editor associated with this property sheet page
- */
- public PropertySheetPage(GraphicalEditorPart editor) {
- mEditor = editor;
- }
-
- private PropertyFactory getPropertyFactory() {
- return mEditor.getPropertyFactory();
- }
-
- @Override
- public void createControl(Composite parent) {
- assert parent != null;
- mPropertyTable = new PropertyTable(parent, SWT.NONE);
- mPropertyTable.setExceptionHandler(new IPropertyExceptionHandler() {
- @Override
- public void handle(Throwable e) {
- AdtPlugin.log(e, null);
- }
- });
- mPropertyTable.setDefaultCollapsedNames(Arrays.asList(
- "Deprecated",
- "Layout Parameters",
- "Layout Parameters|Margins"));
-
- createActions();
- setPropertyTableContextMenu();
- }
-
- @Override
- public void selectionChanged(IWorkbenchPart part, ISelection selection) {
- if (selection instanceof TreeSelection
- && mPropertyTable != null && !mPropertyTable.isDisposed()) {
- TreeSelection treeSelection = (TreeSelection) selection;
-
- // We get a lot of repeated selection requests for the same selection
- // as before, so try to eliminate these
- if (mSelection != null) {
- if (mSelection.isEmpty()) {
- if (treeSelection.isEmpty()) {
- return;
- }
- } else {
- int selectionCount = treeSelection.size();
- if (selectionCount == mSelection.size()) {
- boolean same = true;
- Iterator<?> iterator = treeSelection.iterator();
- for (int i = 0, n = selectionCount; i < n && iterator.hasNext(); i++) {
- Object next = iterator.next();
- if (next instanceof CanvasViewInfo) {
- CanvasViewInfo info = (CanvasViewInfo) next;
- if (info != mSelection.get(i)) {
- same = false;
- break;
- }
- } else {
- same = false;
- break;
- }
- }
- if (same) {
- return;
- }
- }
- }
- }
-
- stopTrackingSelection();
-
- if (treeSelection.isEmpty()) {
- mSelection = Collections.emptyList();
- } else {
- int selectionCount = treeSelection.size();
- List<CanvasViewInfo> newSelection = new ArrayList<CanvasViewInfo>(selectionCount);
- Iterator<?> iterator = treeSelection.iterator();
- while (iterator.hasNext()) {
- Object next = iterator.next();
- if (next instanceof CanvasViewInfo) {
- CanvasViewInfo info = (CanvasViewInfo) next;
- newSelection.add(info);
- }
- }
- mSelection = newSelection;
- }
-
- startTrackingSelection();
-
- refreshProperties();
- }
- }
-
- @Override
- public void dispose() {
- stopTrackingSelection();
- super.dispose();
- }
-
- private void startTrackingSelection() {
- if (mSelection != null && !mSelection.isEmpty()) {
- for (CanvasViewInfo item : mSelection) {
- UiViewElementNode node = item.getUiViewNode();
- if (node != null) {
- node.addUpdateListener(this);
- }
- }
- }
- }
-
- private void stopTrackingSelection() {
- if (mSelection != null && !mSelection.isEmpty()) {
- for (CanvasViewInfo item : mSelection) {
- UiViewElementNode node = item.getUiViewNode();
- if (node != null) {
- node.removeUpdateListener(this);
- }
- }
- }
- mSelection = null;
- }
-
- // Implements IUiUpdateListener
- @Override
- public void uiElementNodeUpdated(UiElementNode node, UiUpdateState state) {
- refreshProperties();
- }
-
- @Override
- public Control getControl() {
- return mPropertyTable;
- }
-
- @Override
- public void setFocus() {
- mPropertyTable.setFocus();
- }
-
- @Override
- public void makeContributions(IMenuManager menuManager,
- IToolBarManager toolBarManager, IStatusLineManager statusLineManager) {
- toolBarManager.add(mShowAdvancedPropertiesAction);
- toolBarManager.add(new Separator());
- toolBarManager.add(mSortAlphaAction);
- toolBarManager.add(new Separator());
- toolBarManager.add(mDefaultValueAction);
- toolBarManager.add(new Separator());
- toolBarManager.add(mExpandAll);
- toolBarManager.add(mCollapseAll);
- toolBarManager.add(new Separator());
- }
-
- private void createActions() {
- ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages();
- IconFactory iconFactory = IconFactory.getInstance();
-
- mExpandAll = new PropertySheetAction(
- IAction.AS_PUSH_BUTTON,
- "Expand All",
- ACTION_EXPAND,
- iconFactory.getImageDescriptor(EXPAND_ICON),
- iconFactory.getImageDescriptor(EXPAND_DISABLED_ICON));
-
- mCollapseAll = new PropertySheetAction(
- IAction.AS_PUSH_BUTTON,
- "Collapse All",
- ACTION_COLLAPSE,
- sharedImages.getImageDescriptor(ISharedImages.IMG_ELCL_COLLAPSEALL),
- sharedImages.getImageDescriptor(ISharedImages.IMG_ELCL_COLLAPSEALL_DISABLED));
-
- mShowAdvancedPropertiesAction = new PropertySheetAction(
- IAction.AS_CHECK_BOX,
- "Show Advanced Properties",
- ACTION_SHOW_ADVANCED,
- iconFactory.getImageDescriptor(ADVANCED_ICON),
- null);
-
- mSortAlphaAction = new PropertySheetAction(
- IAction.AS_CHECK_BOX,
- "Sort Alphabetically",
- ACTION_SORT_ALPHA,
- iconFactory.getImageDescriptor(ALPHA_ICON),
- null);
-
- mDefaultValueAction = new PropertySheetAction(
- IAction.AS_PUSH_BUTTON,
- "Restore Default Value",
- ACTION_DEFAULT_VALUE,
- iconFactory.getImageDescriptor(DEFAULT_ICON),
- null);
-
- // Listen on the selection in the property sheet so we can update the
- // Restore Default Value action
- ISelectionChangedListener listener = new ISelectionChangedListener() {
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- StructuredSelection selection = (StructuredSelection) event.getSelection();
- mActiveProperty = (Property) selection.getFirstElement();
- updateDefaultValueAction();
- }
- };
- mPropertyTable.addSelectionChangedListener(listener);
- }
-
- /**
- * Updates the state of {@link #mDefaultValueAction}.
- */
- private void updateDefaultValueAction() {
- if (mActiveProperty != null) {
- try {
- mDefaultValueAction.setEnabled(mActiveProperty.isModified());
- } catch (Exception e) {
- AdtPlugin.log(e, null);
- }
- } else {
- mDefaultValueAction.setEnabled(false);
- }
- }
-
- /**
- * Sets the context menu for {@link #mPropertyTable}.
- */
- private void setPropertyTableContextMenu() {
- final MenuManager manager = new MenuManager();
- manager.setRemoveAllWhenShown(true);
- manager.addMenuListener(new IMenuListener() {
- @Override
- public void menuAboutToShow(IMenuManager m) {
- // dispose items to avoid caching
- for (MenuItem item : manager.getMenu().getItems()) {
- item.dispose();
- }
- // apply new items
- fillContextMenu();
- }
-
- private void fillContextMenu() {
- manager.add(mDefaultValueAction);
- manager.add(mSortAlphaAction);
- manager.add(mShowAdvancedPropertiesAction);
- }
- });
-
- mPropertyTable.setMenu(manager.createContextMenu(mPropertyTable));
- }
-
- /**
- * Shows {@link Property}'s of current objects.
- */
- private void refreshProperties() {
- PropertyFactory factory = getPropertyFactory();
- mPropertyTable.setInput(factory.getProperties(mSelection));
- updateDefaultValueAction();
- }
-
- // ---- Actions ----
-
- private static final int ACTION_DEFAULT_VALUE = 1;
- private static final int ACTION_SHOW_ADVANCED = 2;
- private static final int ACTION_COLLAPSE = 3;
- private static final int ACTION_EXPAND = 4;
- private static final int ACTION_SORT_ALPHA = 5;
-
- private class PropertySheetAction extends Action {
- private final int mAction;
-
- private PropertySheetAction(int style, String label, int action,
- ImageDescriptor imageDesc, ImageDescriptor disabledImageDesc) {
- super(label, style);
- mAction = action;
- setImageDescriptor(imageDesc);
- if (disabledImageDesc != null) {
- setDisabledImageDescriptor(disabledImageDesc);
- }
- setToolTipText(label);
- }
-
- @Override
- public void run() {
- switch (mAction) {
- case ACTION_COLLAPSE: {
- mPropertyTable.collapseAll();
- break;
- }
- case ACTION_EXPAND: {
- mPropertyTable.expandAll();
- break;
- }
- case ACTION_SHOW_ADVANCED: {
- boolean show = mShowAdvancedPropertiesAction.isChecked();
- mPropertyTable.setShowAdvancedProperties(show);
- break;
- }
- case ACTION_SORT_ALPHA: {
- boolean isAlphabetical = mSortAlphaAction.isChecked();
- getPropertyFactory().setSortingMode(
- isAlphabetical ? SortingMode.ALPHABETICAL : PropertyFactory.DEFAULT_MODE);
- refreshProperties();
- break;
- }
- case ACTION_DEFAULT_VALUE:
- try {
- mActiveProperty.setValue(Property.UNKNOWN_VALUE);
- } catch (Exception e) {
- // Ignore warnings from setters
- }
- break;
- default:
- assert false : mAction;
- }
- }
- }
-
- @Override
- public void setToolBar(IToolBarManager toolBarManager) {
- makeContributions(null, toolBarManager, null);
- toolBarManager.update(false);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/PropertyValueCompleter.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/PropertyValueCompleter.java
deleted file mode 100644
index f2bf07312..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/PropertyValueCompleter.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.properties;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-
-class PropertyValueCompleter extends ValueCompleter {
- private final XmlProperty mProperty;
-
- PropertyValueCompleter(XmlProperty property) {
- mProperty = property;
- }
-
- @Override
- @Nullable
- protected CommonXmlEditor getEditor() {
- return mProperty.getXmlEditor();
- }
-
- @Override
- @NonNull
- protected AttributeDescriptor getDescriptor() {
- return mProperty.getDescriptor();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/ResourceValueCompleter.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/ResourceValueCompleter.java
deleted file mode 100644
index 081ec8069..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/ResourceValueCompleter.java
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.properties;
-
-import static com.android.SdkConstants.ANDROID_PKG;
-import static com.android.SdkConstants.ANDROID_PREFIX;
-import static com.android.SdkConstants.ANDROID_THEME_PREFIX;
-import static com.android.SdkConstants.NEW_ID_PREFIX;
-import static com.android.SdkConstants.PREFIX_RESOURCE_REF;
-import static com.android.SdkConstants.PREFIX_THEME_REF;
-
-import com.android.ide.common.resources.ResourceItem;
-import com.android.ide.common.resources.ResourceRepository;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiResourceAttributeNode;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.resources.ResourceType;
-import com.android.utils.SdkUtils;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.fieldassist.ContentProposal;
-import org.eclipse.jface.fieldassist.IContentProposal;
-import org.eclipse.jface.fieldassist.IContentProposalProvider;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * Resource value completion for the given property
- * <p>
- * TODO:
- * <ul>
- * <li>also offer other values seen in the app
- * <li>also offer previously set values for this property
- * <li>also complete on properties
- * </ul>
- */
-class ResourceValueCompleter implements IContentProposalProvider {
- protected final XmlProperty xmlProperty;
-
- ResourceValueCompleter(XmlProperty xmlProperty) {
- this.xmlProperty = xmlProperty;
- }
-
- @Override
- public IContentProposal[] getProposals(String contents, int position) {
- if (contents.startsWith(PREFIX_RESOURCE_REF)) {
- CommonXmlEditor editor = this.xmlProperty.getXmlEditor();
- if (editor != null) {
- String[] matches = computeResourceStringMatches(
- editor,
- this.xmlProperty.mDescriptor, contents.substring(0, position));
- List<IContentProposal> proposals = null;
- if (matches != null && matches.length > 0) {
- proposals = new ArrayList<IContentProposal>(matches.length);
- for (String match : matches) {
- proposals.add(new ContentProposal(match));
- }
- return proposals.toArray(new IContentProposal[proposals.size()]);
- }
- }
- }
-
- return new IContentProposal[0];
- }
-
- /**
- * Similar to {@link UiResourceAttributeNode#computeResourceStringMatches}
- * but computes complete results up front rather than dividing it up into
- * smaller chunks like @{code @android:}, {@code string/}, and {@code ok}.
- */
- static String[] computeResourceStringMatches(AndroidXmlEditor editor,
- AttributeDescriptor attributeDescriptor, String prefix) {
- List<String> results = new ArrayList<String>(200);
-
- // System matches: only do this if the value already matches at least @a,
- // and doesn't start with something that can't possibly be @android
- if (prefix.startsWith("@a") && //$NON-NLS-1$
- prefix.regionMatches(true /* ignoreCase */, 0, ANDROID_PREFIX, 0,
- Math.min(prefix.length() - 1, ANDROID_PREFIX.length()))) {
- AndroidTargetData data = editor.getTargetData();
- if (data != null) {
- ResourceRepository repository = data.getFrameworkResources();
- addMatches(repository, prefix, true /* isSystem */, results);
- }
- } else if (prefix.startsWith("?") && //$NON-NLS-1$
- prefix.regionMatches(true /* ignoreCase */, 0, ANDROID_THEME_PREFIX, 0,
- Math.min(prefix.length() - 1, ANDROID_THEME_PREFIX.length()))) {
- AndroidTargetData data = editor.getTargetData();
- if (data != null) {
- ResourceRepository repository = data.getFrameworkResources();
- addMatches(repository, prefix, true /* isSystem */, results);
- }
- }
-
-
- // When completing project resources skip framework resources unless
- // the prefix possibly completes both, such as "@an" which can match
- // both the project resource @animator as well as @android:string
- if (!prefix.startsWith("@and") && !prefix.startsWith("?and")) { //$NON-NLS-1$ //$NON-NLS-2$
- IProject project = editor.getProject();
- if (project != null) {
- // get the resource repository for this project and the system resources.
- ResourceManager manager = ResourceManager.getInstance();
- ResourceRepository repository = manager.getProjectResources(project);
- if (repository != null) {
- // We have a style name and a repository. Find all resources that match this
- // type and recreate suggestions out of them.
- addMatches(repository, prefix, false /* isSystem */, results);
- }
-
- }
- }
-
- if (attributeDescriptor != null) {
- UiResourceAttributeNode.sortAttributeChoices(attributeDescriptor, results);
- } else {
- Collections.sort(results);
- }
-
- return results.toArray(new String[results.size()]);
- }
-
- private static void addMatches(ResourceRepository repository, String prefix, boolean isSystem,
- List<String> results) {
- int typeStart = isSystem
- ? ANDROID_PREFIX.length() : PREFIX_RESOURCE_REF.length();
-
- for (ResourceType type : repository.getAvailableResourceTypes()) {
- if (prefix.regionMatches(typeStart, type.getName(), 0,
- Math.min(type.getName().length(), prefix.length() - typeStart))) {
- StringBuilder sb = new StringBuilder();
- if (prefix.length() == 0 || prefix.startsWith(PREFIX_RESOURCE_REF)) {
- sb.append(PREFIX_RESOURCE_REF);
- } else {
- if (type != ResourceType.ATTR) {
- continue;
- }
- sb.append(PREFIX_THEME_REF);
- }
-
- if (type == ResourceType.ID && prefix.startsWith(NEW_ID_PREFIX)) {
- sb.append('+');
- }
-
- if (isSystem) {
- sb.append(ANDROID_PKG).append(':');
- }
-
- sb.append(type.getName()).append('/');
- String base = sb.toString();
-
- int nameStart = typeStart + type.getName().length() + 1; // +1: add "/" divider
- String namePrefix =
- prefix.length() <= nameStart ? "" : prefix.substring(nameStart);
- for (ResourceItem item : repository.getResourceItemsOfType(type)) {
- String name = item.getName();
- if (SdkUtils.startsWithIgnoreCase(name, namePrefix)) {
- results.add(base + name);
- }
- }
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/StringXmlPropertyDialog.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/StringXmlPropertyDialog.java
deleted file mode 100644
index fb7e45902..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/StringXmlPropertyDialog.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.properties;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wb.internal.core.model.property.Property;
-import org.eclipse.wb.internal.core.model.property.editor.string.StringPropertyDialog;
-
-class StringXmlPropertyDialog extends StringPropertyDialog {
- StringXmlPropertyDialog(Shell parentShell, Property property) throws Exception {
- super(parentShell, property);
- }
-
- @Override
- protected boolean isMultiLine() {
- return false;
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite area = (Composite) super.createDialogArea(parent);
-
- Composite workaround = PropertyFactory.addWorkaround(area);
- if (workaround != null) {
- workaround.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1));
- }
-
- return area;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/ValueCompleter.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/ValueCompleter.java
deleted file mode 100644
index 5559349fc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/ValueCompleter.java
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.properties;
-
-import static com.android.SdkConstants.ATTR_TEXT_SIZE;
-import static com.android.SdkConstants.PREFIX_RESOURCE_REF;
-import static com.android.SdkConstants.PREFIX_THEME_REF;
-import static com.android.SdkConstants.UNIT_DP;
-import static com.android.SdkConstants.UNIT_SP;
-import static com.android.SdkConstants.VALUE_FALSE;
-import static com.android.SdkConstants.VALUE_TRUE;
-import static com.android.ide.common.api.IAttributeInfo.Format.BOOLEAN;
-import static com.android.ide.common.api.IAttributeInfo.Format.DIMENSION;
-import static com.android.ide.common.api.IAttributeInfo.Format.ENUM;
-import static com.android.ide.common.api.IAttributeInfo.Format.FLAG;
-import static com.android.ide.common.api.IAttributeInfo.Format.FLOAT;
-import static com.android.ide.common.api.IAttributeInfo.Format.INTEGER;
-import static com.android.ide.common.api.IAttributeInfo.Format.REFERENCE;
-import static com.android.ide.common.api.IAttributeInfo.Format.STRING;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.IAttributeInfo;
-import com.android.ide.common.api.IAttributeInfo.Format;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.utils.SdkUtils;
-
-import org.eclipse.jface.fieldassist.ContentProposal;
-import org.eclipse.jface.fieldassist.IContentProposal;
-import org.eclipse.jface.fieldassist.IContentProposalProvider;
-
-import java.util.ArrayList;
-import java.util.EnumSet;
-import java.util.List;
-
-/**
- * An {@link IContentProposalProvider} which completes possible property values
- * for Android properties, completing resource strings, flag values, enum
- * values, as well as dimension units.
- */
-abstract class ValueCompleter implements IContentProposalProvider {
- @Nullable
- protected abstract CommonXmlEditor getEditor();
-
- @NonNull
- protected abstract AttributeDescriptor getDescriptor();
-
- @Override
- public IContentProposal[] getProposals(String contents, int position) {
- AttributeDescriptor descriptor = getDescriptor();
- IAttributeInfo info = descriptor.getAttributeInfo();
- EnumSet<Format> formats = info.getFormats();
-
- List<IContentProposal> proposals = new ArrayList<IContentProposal>();
-
- String prefix = contents; // TODO: Go back to position inside the array?
-
- // TODO: If the user is typing in a number, or a number plus a prefix of a dimension unit,
- // then propose that number plus the completed dimension unit (using sp for text, dp
- // for other properties and maybe both if I'm not sure)
- if (formats.contains(STRING)
- && !contents.isEmpty()
- && (formats.size() > 1 && formats.contains(REFERENCE) ||
- formats.size() > 2)
- && !contents.startsWith(PREFIX_RESOURCE_REF)
- && !contents.startsWith(PREFIX_THEME_REF)) {
- proposals.add(new ContentProposal(contents));
- }
-
- if (!contents.isEmpty() && Character.isDigit(contents.charAt(0))
- && (formats.contains(DIMENSION)
- || formats.contains(INTEGER)
- || formats.contains(FLOAT))) {
- StringBuilder sb = new StringBuilder();
- for (int i = 0, n = contents.length(); i < n; i++) {
- char c = contents.charAt(i);
- if (Character.isDigit(c)) {
- sb.append(c);
- } else {
- break;
- }
- }
-
- String number = sb.toString();
- if (formats.contains(Format.DIMENSION)) {
- if (descriptor.getXmlLocalName().equals(ATTR_TEXT_SIZE)) {
- proposals.add(new ContentProposal(number + UNIT_SP));
- }
- proposals.add(new ContentProposal(number + UNIT_DP));
- } else if (formats.contains(Format.INTEGER)) {
- proposals.add(new ContentProposal(number));
- }
- // Perhaps offer other units too -- see AndroidContentAssist.sDimensionUnits
- }
-
- if (formats.contains(REFERENCE) || contents.startsWith(PREFIX_RESOURCE_REF)
- || contents.startsWith(PREFIX_THEME_REF)) {
- CommonXmlEditor editor = getEditor();
- if (editor != null) {
- String[] matches = ResourceValueCompleter.computeResourceStringMatches(
- editor,
- descriptor, contents.substring(0, position));
- for (String match : matches) {
- proposals.add(new ContentProposal(match));
- }
- }
- }
-
- if (formats.contains(FLAG)) {
- String[] values = info.getFlagValues();
- if (values != null) {
- // Flag completion
- int flagStart = prefix.lastIndexOf('|');
- String prepend = null;
- if (flagStart != -1) {
- prepend = prefix.substring(0, flagStart + 1);
- prefix = prefix.substring(flagStart + 1).trim();
- }
-
- boolean exactMatch = false;
- for (String value : values) {
- if (prefix.equals(value)) {
- exactMatch = true;
- proposals.add(new ContentProposal(contents));
-
- break;
- }
- }
-
- if (exactMatch) {
- prepend = contents + '|';
- prefix = "";
- }
-
- for (String value : values) {
- if (SdkUtils.startsWithIgnoreCase(value, prefix)) {
- if (prepend != null && prepend.contains(value)) {
- continue;
- }
- String match;
- if (prepend != null) {
- match = prepend + value;
- } else {
- match = value;
- }
- proposals.add(new ContentProposal(match));
- }
- }
- }
- } else if (formats.contains(ENUM)) {
- String[] values = info.getEnumValues();
- if (values != null) {
- for (String value : values) {
- if (SdkUtils.startsWithIgnoreCase(value, prefix)) {
- proposals.add(new ContentProposal(value));
- }
- }
-
- for (String value : values) {
- if (!SdkUtils.startsWithIgnoreCase(value, prefix)) {
- proposals.add(new ContentProposal(value));
- }
- }
- }
- } else if (formats.contains(BOOLEAN)) {
- proposals.add(new ContentProposal(VALUE_TRUE));
- proposals.add(new ContentProposal(VALUE_FALSE));
- }
-
- return proposals.toArray(new IContentProposal[proposals.size()]);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/XmlProperty.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/XmlProperty.java
deleted file mode 100644
index a320b682d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/XmlProperty.java
+++ /dev/null
@@ -1,278 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.properties;
-
-import static com.android.SdkConstants.ATTR_LAYOUT_MARGIN;
-import static com.android.SdkConstants.ATTR_LAYOUT_RESOURCE_PREFIX;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.IAttributeInfo;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.ViewHierarchy;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-
-import org.eclipse.jface.fieldassist.IContentProposal;
-import org.eclipse.jface.fieldassist.IContentProposalProvider;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.views.properties.IPropertyDescriptor;
-import org.eclipse.wb.internal.core.model.property.Property;
-import org.eclipse.wb.internal.core.model.property.editor.PropertyEditor;
-import org.eclipse.wb.internal.core.model.property.table.PropertyTooltipProvider;
-import org.eclipse.wb.internal.core.model.property.table.PropertyTooltipTextProvider;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Element;
-
-import java.util.Map;
-
-/**
- * An Android XML property
- */
-class XmlProperty extends Property {
- private PropertyFactory mFactory;
- final AttributeDescriptor mDescriptor;
- private UiViewElementNode mNode;
- private Property mParent;
-
- XmlProperty(
- @NonNull PropertyEditor editor,
- @NonNull PropertyFactory factory,
- @NonNull UiViewElementNode node,
- @NonNull AttributeDescriptor descriptor) {
- super(editor);
- mFactory = factory;
- mNode = node;
- mDescriptor = descriptor;
- }
-
- @NonNull
- public PropertyFactory getFactory() {
- return mFactory;
- }
-
- @NonNull
- public UiViewElementNode getNode() {
- return mNode;
- }
-
- @NonNull
- public AttributeDescriptor getDescriptor() {
- return mDescriptor;
- }
-
- @Override
- @NonNull
- public String getName() {
- return mDescriptor.getXmlLocalName();
- }
-
- @Override
- @NonNull
- public String getTitle() {
- String name = mDescriptor.getXmlLocalName();
- int nameLength = name.length();
-
- if (name.startsWith(ATTR_LAYOUT_RESOURCE_PREFIX)) {
- if (name.startsWith(ATTR_LAYOUT_MARGIN)
- && nameLength > ATTR_LAYOUT_MARGIN.length()) {
- name = name.substring(ATTR_LAYOUT_MARGIN.length());
- } else {
- name = name.substring(ATTR_LAYOUT_RESOURCE_PREFIX.length());
- }
- }
-
- // Capitalize
- name = DescriptorsUtils.capitalize(name);
-
- // If we're nested within a complex property, say "Line Spacing", don't
- // include "Line Spacing " as a prefix for each property here
- if (mParent != null) {
- String parentTitle = mParent.getTitle();
- if (name.startsWith(parentTitle)) {
- int parentTitleLength = parentTitle.length();
- if (parentTitleLength < nameLength) {
- if (nameLength > parentTitleLength &&
- Character.isWhitespace(name.charAt(parentTitleLength))) {
- parentTitleLength++;
- }
- name = name.substring(parentTitleLength);
- }
- }
- }
-
- return name;
- }
-
- @Override
- public <T> T getAdapter(Class<T> adapter) {
- // tooltip
- if (adapter == PropertyTooltipProvider.class) {
- return adapter.cast(new PropertyTooltipTextProvider() {
- @Override
- protected String getText(Property p) throws Exception {
- if (mDescriptor instanceof IPropertyDescriptor) {
- IPropertyDescriptor d = (IPropertyDescriptor) mDescriptor;
- return d.getDescription();
- }
-
- return null;
- }
- });
- } else if (adapter == IContentProposalProvider.class) {
- IAttributeInfo info = mDescriptor.getAttributeInfo();
- if (info != null) {
- return adapter.cast(new PropertyValueCompleter(this));
- }
- // Fallback: complete values on resource values
- return adapter.cast(new ResourceValueCompleter(this));
- } else if (adapter == ILabelProvider.class) {
- return adapter.cast(new LabelProvider() {
- @Override
- public Image getImage(Object element) {
- return AdtPlugin.getAndroidLogo();
- }
-
- @Override
- public String getText(Object element) {
- return ((IContentProposal) element).getLabel();
- }
- });
- }
- return super.getAdapter(adapter);
- }
-
- @Override
- public boolean isModified() throws Exception {
- Object s = null;
- try {
- Element element = (Element) mNode.getXmlNode();
- if (element == null) {
- return false;
- }
- String name = mDescriptor.getXmlLocalName();
- String uri = mDescriptor.getNamespaceUri();
- if (uri != null) {
- return element.hasAttributeNS(uri, name);
- } else {
- return element.hasAttribute(name);
- }
- } catch (Exception e) {
- // pass
- }
- return s != null && s.toString().length() > 0;
- }
-
- @Nullable
- public String getStringValue() {
- Element element = (Element) mNode.getXmlNode();
- if (element == null) {
- return null;
- }
- String name = mDescriptor.getXmlLocalName();
- String uri = mDescriptor.getNamespaceUri();
- Attr attr;
- if (uri != null) {
- attr = element.getAttributeNodeNS(uri, name);
- } else {
- attr = element.getAttributeNode(name);
- }
- if (attr != null) {
- return attr.getValue();
- }
-
- Object viewObject = getFactory().getCurrentViewObject();
- if (viewObject != null) {
- GraphicalEditorPart graphicalEditor = getGraphicalEditor();
- if (graphicalEditor == null) {
- return null;
- }
- ViewHierarchy views = graphicalEditor.getCanvasControl().getViewHierarchy();
- Map<String, String> defaultProperties = views.getDefaultProperties(viewObject);
- if (defaultProperties != null) {
- return defaultProperties.get(name);
- }
- }
-
- return null;
- }
-
- @Override
- @Nullable
- public Object getValue() throws Exception {
- return getStringValue();
- }
-
- @Override
- public void setValue(Object value) throws Exception {
- CommonXmlEditor editor = getXmlEditor();
- if (editor == null) {
- return;
- }
- final String attribute = mDescriptor.getXmlLocalName();
- final String xmlValue = value != null && value != UNKNOWN_VALUE ? value.toString() : null;
- editor.wrapUndoEditXmlModel(
- String.format("Set \"%1$s\" to \"%2$s\"", attribute, xmlValue),
- new Runnable() {
- @Override
- public void run() {
- mNode.setAttributeValue(attribute,
- mDescriptor.getNamespaceUri(), xmlValue, true /*override*/);
- mNode.commitDirtyAttributesToXml();
- }
- });
- }
-
- @Override
- @NonNull
- public Property getComposite(Property[] properties) {
- return XmlPropertyComposite.create(properties);
- }
-
- @Nullable
- GraphicalEditorPart getGraphicalEditor() {
- return mFactory.getGraphicalEditor();
- }
-
- @Nullable
- CommonXmlEditor getXmlEditor() {
- GraphicalEditorPart graphicalEditor = getGraphicalEditor();
- if (graphicalEditor != null) {
- return graphicalEditor.getEditorDelegate().getEditor();
- }
-
- return null;
- }
-
- @Nullable
- public Property getParent() {
- return mParent;
- }
-
- public void setParent(@Nullable Property parent) {
- mParent = parent;
- }
-
- @Override
- public String toString() {
- return getName() + ":" + getPriority();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/XmlPropertyComposite.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/XmlPropertyComposite.java
deleted file mode 100644
index af9e13b3e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/XmlPropertyComposite.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.properties;
-
-import com.android.annotations.NonNull;
-import com.google.common.base.Objects;
-
-import org.eclipse.wb.internal.core.model.property.Property;
-
-import java.util.Arrays;
-
-/**
- * Property holding multiple instances of the same {@link XmlProperty} (but
- * bound to difference objects. This is used when multiple objects are selected
- * in the layout editor and the common properties are shown; editing a value
- * will (via {@link #setValue(Object)}) set it on all selected objects.
- * <p>
- * Similar to
- * org.eclipse.wb.internal.core.model.property.GenericPropertyComposite
- */
-class XmlPropertyComposite extends XmlProperty {
- private static final Object NO_VALUE = new Object();
-
- private final XmlProperty[] mProperties;
-
- public XmlPropertyComposite(XmlProperty primary, XmlProperty[] properties) {
- super(
- primary.getEditor(),
- primary.getFactory(),
- primary.getNode(),
- primary.getDescriptor());
- mProperties = properties;
- }
-
- @Override
- @NonNull
- public String getTitle() {
- return mProperties[0].getTitle();
- }
-
- @Override
- public int hashCode() {
- return mProperties.length;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj == this) {
- return true;
- }
-
- if (obj instanceof XmlPropertyComposite) {
- XmlPropertyComposite property = (XmlPropertyComposite) obj;
- return Arrays.equals(mProperties, property.mProperties);
- }
-
- return false;
- }
-
- @Override
- public boolean isModified() throws Exception {
- for (Property property : mProperties) {
- if (property.isModified()) {
- return true;
- }
- }
-
- return false;
- }
-
- @Override
- public Object getValue() throws Exception {
- Object value = NO_VALUE;
- for (Property property : mProperties) {
- Object propertyValue = property.getValue();
- if (value == NO_VALUE) {
- value = propertyValue;
- } else if (!Objects.equal(value, propertyValue)) {
- return UNKNOWN_VALUE;
- }
- }
-
- return value;
- }
-
- @Override
- public void setValue(final Object value) throws Exception {
- // TBD: Wrap in ExecutionUtils.run?
- for (Property property : mProperties) {
- property.setValue(value);
- }
- }
-
- @NonNull
- public static XmlPropertyComposite create(Property... properties) {
- // Cast from Property into XmlProperty
- XmlProperty[] xmlProperties = new XmlProperty[properties.length];
- for (int i = 0; i < properties.length; i++) {
- Property property = properties[i];
- xmlProperties[i] = (XmlProperty) property;
- }
-
- XmlPropertyComposite composite = new XmlPropertyComposite(xmlProperties[0], xmlProperties);
- composite.setCategory(xmlProperties[0].getCategory());
- return composite;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/XmlPropertyEditor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/XmlPropertyEditor.java
deleted file mode 100644
index 87fb0e6ed..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/properties/XmlPropertyEditor.java
+++ /dev/null
@@ -1,548 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.properties;
-
-import static com.android.SdkConstants.ANDROID_PREFIX;
-import static com.android.SdkConstants.ANDROID_THEME_PREFIX;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.DOT_PNG;
-import static com.android.SdkConstants.DOT_XML;
-import static com.android.SdkConstants.NEW_ID_PREFIX;
-import static com.android.SdkConstants.PREFIX_RESOURCE_REF;
-import static com.android.SdkConstants.PREFIX_THEME_REF;
-import static com.android.ide.common.layout.BaseViewRule.stripIdPrefix;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.IAttributeInfo;
-import com.android.ide.common.api.IAttributeInfo.Format;
-import com.android.ide.common.layout.BaseViewRule;
-import com.android.ide.common.rendering.api.ResourceValue;
-import com.android.ide.common.resources.ResourceRepository;
-import com.android.ide.common.resources.ResourceResolver;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.ImageUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.LayoutCanvas;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderService;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.SelectionManager;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.SwtUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.NodeProxy;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.refactorings.core.RenameResourceWizard;
-import com.android.ide.eclipse.adt.internal.refactorings.core.RenameResult;
-import com.android.ide.eclipse.adt.internal.resources.ResourceHelper;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.ide.eclipse.adt.internal.ui.ReferenceChooserDialog;
-import com.android.ide.eclipse.adt.internal.ui.ResourceChooser;
-import com.android.ide.eclipse.adt.internal.ui.ResourcePreviewHelper;
-import com.android.resources.ResourceType;
-import com.google.common.collect.Maps;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.QualifiedName;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialogWithToggle;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.ImageData;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wb.draw2d.IColorConstants;
-import org.eclipse.wb.internal.core.model.property.Property;
-import org.eclipse.wb.internal.core.model.property.editor.AbstractTextPropertyEditor;
-import org.eclipse.wb.internal.core.model.property.editor.presentation.ButtonPropertyEditorPresentation;
-import org.eclipse.wb.internal.core.model.property.editor.presentation.PropertyEditorPresentation;
-import org.eclipse.wb.internal.core.model.property.table.PropertyTable;
-import org.eclipse.wb.internal.core.utils.ui.DrawUtils;
-
-import java.awt.image.BufferedImage;
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.EnumSet;
-import java.util.List;
-import java.util.Map;
-
-import javax.imageio.ImageIO;
-
-/**
- * Special property editor used for the {@link XmlProperty} instances which handles
- * editing the XML properties, rendering defaults by looking up the actual colors and images,
- */
-class XmlPropertyEditor extends AbstractTextPropertyEditor {
- public static final XmlPropertyEditor INSTANCE = new XmlPropertyEditor();
- private static final int SAMPLE_SIZE = 10;
- private static final int SAMPLE_MARGIN = 3;
-
- protected XmlPropertyEditor() {
- }
-
- private final PropertyEditorPresentation mPresentation =
- new ButtonPropertyEditorPresentation() {
- @Override
- protected void onClick(PropertyTable propertyTable, Property property) throws Exception {
- openDialog(propertyTable, property);
- }
- };
-
- @Override
- public PropertyEditorPresentation getPresentation() {
- return mPresentation;
- }
-
- @Override
- public String getText(Property property) throws Exception {
- Object value = property.getValue();
- if (value instanceof String) {
- return (String) value;
- }
- return null;
- }
-
- @Override
- protected String getEditorText(Property property) throws Exception {
- return getText(property);
- }
-
- @Override
- public void paint(Property property, GC gc, int x, int y, int width, int height)
- throws Exception {
- String text = getText(property);
- if (text != null) {
- ResourceValue resValue = null;
- String resolvedText = null;
-
- // TODO: Use the constants for @, ?, @android: etc
- if (text.startsWith("@") || text.startsWith("?")) { //$NON-NLS-1$ //$NON-NLS-2$
- // Yes, try to resolve it in order to show better info
- XmlProperty xmlProperty = (XmlProperty) property;
- GraphicalEditorPart graphicalEditor = xmlProperty.getGraphicalEditor();
- if (graphicalEditor != null) {
- ResourceResolver resolver = graphicalEditor.getResourceResolver();
- boolean isFramework = text.startsWith(ANDROID_PREFIX)
- || text.startsWith(ANDROID_THEME_PREFIX);
- resValue = resolver.findResValue(text, isFramework);
- while (resValue != null && resValue.getValue() != null) {
- String value = resValue.getValue();
- if (value.startsWith(PREFIX_RESOURCE_REF)
- || value.startsWith(PREFIX_THEME_REF)) {
- // TODO: do I have to strip off the @ too?
- isFramework = isFramework
- || value.startsWith(ANDROID_PREFIX)
- || value.startsWith(ANDROID_THEME_PREFIX);
- ResourceValue v = resolver.findResValue(text, isFramework);
- if (v != null && !value.equals(v.getValue())) {
- resValue = v;
- } else {
- break;
- }
- } else {
- break;
- }
- }
- }
- } else if (text.startsWith("#") && text.matches("#\\p{XDigit}+")) { //$NON-NLS-1$
- resValue = new ResourceValue(ResourceType.COLOR, property.getName(), text, false);
- }
-
- if (resValue != null && resValue.getValue() != null) {
- String value = resValue.getValue();
- // Decide whether it's a color, an image, a nine patch etc
- // and decide how to render it
- if (value.startsWith("#") || value.endsWith(DOT_XML) //$NON-NLS-1$
- && value.contains("res/color")) { //$NON-NLS-1$ // TBD: File.separator?
- XmlProperty xmlProperty = (XmlProperty) property;
- GraphicalEditorPart graphicalEditor = xmlProperty.getGraphicalEditor();
- if (graphicalEditor != null) {
- ResourceResolver resolver = graphicalEditor.getResourceResolver();
- RGB rgb = ResourceHelper.resolveColor(resolver, resValue);
- if (rgb != null) {
- Color color = new Color(gc.getDevice(), rgb);
- // draw color sample
- Color oldBackground = gc.getBackground();
- Color oldForeground = gc.getForeground();
- try {
- int width_c = SAMPLE_SIZE;
- int height_c = SAMPLE_SIZE;
- int x_c = x;
- int y_c = y + (height - height_c) / 2;
- // update rest bounds
- int delta = SAMPLE_SIZE + SAMPLE_MARGIN;
- x += delta;
- width -= delta;
- // fill
- gc.setBackground(color);
- gc.fillRectangle(x_c, y_c, width_c, height_c);
- // draw line
- gc.setForeground(IColorConstants.gray);
- gc.drawRectangle(x_c, y_c, width_c, height_c);
- } finally {
- gc.setBackground(oldBackground);
- gc.setForeground(oldForeground);
- }
- color.dispose();
- }
- }
- } else {
- Image swtImage = null;
- if (value.endsWith(DOT_XML) && value.contains("res/drawable")) { // TBD: Filesep?
- Map<String, Image> cache = getImageCache(property);
- swtImage = cache.get(value);
- if (swtImage == null) {
- XmlProperty xmlProperty = (XmlProperty) property;
- GraphicalEditorPart graphicalEditor = xmlProperty.getGraphicalEditor();
- RenderService service = RenderService.create(graphicalEditor);
- service.setOverrideRenderSize(SAMPLE_SIZE, SAMPLE_SIZE);
- BufferedImage drawable = service.renderDrawable(resValue);
- if (drawable != null) {
- swtImage = SwtUtils.convertToSwt(gc.getDevice(), drawable,
- true /*transferAlpha*/, -1);
- cache.put(value, swtImage);
- }
- }
- } else if (value.endsWith(DOT_PNG)) {
- // TODO: 9-patch handling?
- //if (text.endsWith(DOT_9PNG)) {
- // // 9-patch image: How do we paint this?
- // URL url = new File(text).toURI().toURL();
- // NinePatch ninepatch = NinePatch.load(url, false /* ?? */);
- // BufferedImage image = ninepatch.getImage();
- //}
- Map<String, Image> cache = getImageCache(property);
- swtImage = cache.get(value);
- if (swtImage == null) {
- File file = new File(value);
- if (file.exists()) {
- try {
- BufferedImage awtImage = ImageIO.read(file);
- if (awtImage != null && awtImage.getWidth() > 0
- && awtImage.getHeight() > 0) {
- awtImage = ImageUtils.cropBlank(awtImage, null);
- if (awtImage != null) {
- // Scale image
- int imageWidth = awtImage.getWidth();
- int imageHeight = awtImage.getHeight();
- int maxWidth = 3 * height;
-
- if (imageWidth > maxWidth || imageHeight > height) {
- double scale = height / (double) imageHeight;
- int scaledWidth = (int) (imageWidth * scale);
- if (scaledWidth > maxWidth) {
- scale = maxWidth / (double) imageWidth;
- }
- awtImage = ImageUtils.scale(awtImage, scale,
- scale);
- }
- swtImage = SwtUtils.convertToSwt(gc.getDevice(),
- awtImage, true /*transferAlpha*/, -1);
- }
- }
- } catch (IOException e) {
- AdtPlugin.log(e, value);
- }
- }
- cache.put(value, swtImage);
- }
-
- } else if (value != null) {
- // It's a normal string: if different from the text, paint
- // it in parentheses, e.g.
- // @string/foo: Foo Bar (probably cropped)
- if (!value.equals(text) && !value.equals("@null")) { //$NON-NLS-1$
- resolvedText = value;
- }
- }
-
- if (swtImage != null) {
- // Make a square the size of the height
- ImageData imageData = swtImage.getImageData();
- int imageWidth = imageData.width;
- int imageHeight = imageData.height;
- if (imageWidth > 0 && imageHeight > 0) {
- gc.drawImage(swtImage, x, y + (height - imageHeight) / 2);
- int delta = imageWidth + SAMPLE_MARGIN;
- x += delta;
- width -= delta;
- }
- }
- }
- }
-
- DrawUtils.drawStringCV(gc, text, x, y, width, height);
-
- if (resolvedText != null && resolvedText.length() > 0) {
- Point size = gc.stringExtent(text);
- x += size.x;
- width -= size.x;
-
- x += SAMPLE_MARGIN;
- width -= SAMPLE_MARGIN;
-
- if (width > 0) {
- Color oldForeground = gc.getForeground();
- try {
- gc.setForeground(PropertyTable.COLOR_PROPERTY_FG_DEFAULT);
- DrawUtils.drawStringCV(gc, '(' + resolvedText + ')', x, y, width, height);
- } finally {
- gc.setForeground(oldForeground);
- }
- }
- }
- }
- }
-
- @Override
- protected boolean setEditorText(Property property, String text) throws Exception {
- Object oldValue = property.getValue();
- String old = oldValue != null ? oldValue.toString() : null;
-
- // If users enters a new id without specifying the @id/@+id prefix, insert it
- boolean isId = isIdProperty(property);
- if (isId && !text.startsWith(PREFIX_RESOURCE_REF)) {
- text = NEW_ID_PREFIX + text;
- }
-
- // Handle id refactoring: if you change an id, may want to update references too.
- // Ask user.
- if (isId && property instanceof XmlProperty
- && old != null && !old.isEmpty()
- && text != null && !text.isEmpty()
- && !text.equals(old)) {
- XmlProperty xmlProperty = (XmlProperty) property;
- IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore();
- String refactorPref = store.getString(AdtPrefs.PREFS_REFACTOR_IDS);
- boolean performRefactor = false;
- Shell shell = AdtPlugin.getShell();
- if (refactorPref == null
- || refactorPref.isEmpty()
- || refactorPref.equals(MessageDialogWithToggle.PROMPT)) {
- MessageDialogWithToggle dialog =
- MessageDialogWithToggle.openYesNoCancelQuestion(
- shell,
- "Update References?",
- "Update all references as well? " +
- "This will update all XML references and Java R field references.",
- "Do not show again",
- false,
- store,
- AdtPrefs.PREFS_REFACTOR_IDS);
- switch (dialog.getReturnCode()) {
- case IDialogConstants.CANCEL_ID:
- return false;
- case IDialogConstants.YES_ID:
- performRefactor = true;
- break;
- case IDialogConstants.NO_ID:
- performRefactor = false;
- break;
- }
- } else {
- performRefactor = refactorPref.equals(MessageDialogWithToggle.ALWAYS);
- }
- if (performRefactor) {
- CommonXmlEditor xmlEditor = xmlProperty.getXmlEditor();
- if (xmlEditor != null) {
- IProject project = xmlEditor.getProject();
- if (project != null && shell != null) {
- RenameResourceWizard.renameResource(shell, project,
- ResourceType.ID, stripIdPrefix(old), stripIdPrefix(text), false);
- }
- }
- }
- }
-
- property.setValue(text);
-
- return true;
- }
-
- private static boolean isIdProperty(Property property) {
- XmlProperty xmlProperty = (XmlProperty) property;
- return xmlProperty.getDescriptor().getXmlLocalName().equals(ATTR_ID);
- }
-
- private void openDialog(PropertyTable propertyTable, Property property) throws Exception {
- XmlProperty xmlProperty = (XmlProperty) property;
- IAttributeInfo attributeInfo = xmlProperty.getDescriptor().getAttributeInfo();
-
- if (isIdProperty(property)) {
- Object value = xmlProperty.getValue();
- if (value != null && !value.toString().isEmpty()) {
- GraphicalEditorPart editor = xmlProperty.getGraphicalEditor();
- if (editor != null) {
- LayoutCanvas canvas = editor.getCanvasControl();
- SelectionManager manager = canvas.getSelectionManager();
-
- NodeProxy primary = canvas.getNodeFactory().create(xmlProperty.getNode());
- if (primary != null) {
- RenameResult result = manager.performRename(primary, null);
- if (result.isCanceled()) {
- return;
- } else if (!result.isUnavailable()) {
- String name = result.getName();
- String id = NEW_ID_PREFIX + BaseViewRule.stripIdPrefix(name);
- xmlProperty.setValue(id);
- return;
- }
- }
- }
- }
-
- // When editing the id attribute, don't offer a resource chooser: usually
- // you want to enter a *new* id here
- attributeInfo = null;
- }
-
- boolean referenceAllowed = false;
- if (attributeInfo != null) {
- EnumSet<Format> formats = attributeInfo.getFormats();
- ResourceType type = null;
- List<ResourceType> types = null;
- if (formats.contains(Format.FLAG)) {
- String[] flagValues = attributeInfo.getFlagValues();
- if (flagValues != null) {
- FlagXmlPropertyDialog dialog =
- new FlagXmlPropertyDialog(propertyTable.getShell(),
- "Select Flag Values", false /* radio */,
- flagValues, xmlProperty);
-
- dialog.open();
- return;
- }
- } else if (formats.contains(Format.ENUM)) {
- String[] enumValues = attributeInfo.getEnumValues();
- if (enumValues != null) {
- FlagXmlPropertyDialog dialog =
- new FlagXmlPropertyDialog(propertyTable.getShell(),
- "Select Enum Value", true /* radio */,
- enumValues, xmlProperty);
- dialog.open();
- return;
- }
- } else {
- for (Format format : formats) {
- ResourceType t = format.getResourceType();
- if (t != null) {
- if (type != null) {
- if (types == null) {
- types = new ArrayList<ResourceType>();
- types.add(type);
- }
- types.add(t);
- }
- type = t;
- } else if (format == Format.REFERENCE) {
- referenceAllowed = true;
- }
- }
- }
- if (types != null || referenceAllowed) {
- // Multiple resource types (such as string *and* boolean):
- // just use a reference chooser
- GraphicalEditorPart graphicalEditor = xmlProperty.getGraphicalEditor();
- if (graphicalEditor != null) {
- LayoutEditorDelegate delegate = graphicalEditor.getEditorDelegate();
- IProject project = delegate.getEditor().getProject();
- if (project != null) {
- // get the resource repository for this project and the system resources.
- ResourceRepository projectRepository =
- ResourceManager.getInstance().getProjectResources(project);
- Shell shell = AdtPlugin.getShell();
- ReferenceChooserDialog dlg = new ReferenceChooserDialog(
- project,
- projectRepository,
- shell);
- dlg.setPreviewHelper(new ResourcePreviewHelper(dlg, graphicalEditor));
-
- String currentValue = (String) property.getValue();
- dlg.setCurrentResource(currentValue);
-
- if (dlg.open() == Window.OK) {
- String resource = dlg.getCurrentResource();
- if (resource != null) {
- // Returns null for cancel, "" for clear and otherwise a new value
- if (resource.length() > 0) {
- property.setValue(resource);
- } else {
- property.setValue(null);
- }
- }
- }
-
- return;
- }
- }
- } else if (type != null) {
- // Single resource type: use a resource chooser
- GraphicalEditorPart graphicalEditor = xmlProperty.getGraphicalEditor();
- if (graphicalEditor != null) {
- String currentValue = (String) property.getValue();
- // TODO: Add validator factory?
- String resource = ResourceChooser.chooseResource(graphicalEditor,
- type, currentValue, null /* validator */);
- // Returns null for cancel, "" for clear and otherwise a new value
- if (resource != null) {
- if (resource.length() > 0) {
- property.setValue(resource);
- } else {
- property.setValue(null);
- }
- }
- }
-
- return;
- }
- }
-
- // Fallback: Just use a plain string editor
- StringXmlPropertyDialog dialog =
- new StringXmlPropertyDialog(propertyTable.getShell(), property);
- if (dialog.open() == Window.OK) {
- // TODO: Do I need to activate?
- }
- }
-
- /** Qualified name for the per-project persistent property include-map */
- private final static QualifiedName CACHE_NAME = new QualifiedName(AdtPlugin.PLUGIN_ID,
- "property-images");//$NON-NLS-1$
-
- @NonNull
- private static Map<String, Image> getImageCache(@NonNull Property property) {
- XmlProperty xmlProperty = (XmlProperty) property;
- GraphicalEditorPart graphicalEditor = xmlProperty.getGraphicalEditor();
- IProject project = graphicalEditor.getProject();
- try {
- Map<String, Image> cache = (Map<String, Image>) project.getSessionProperty(CACHE_NAME);
- if (cache == null) {
- cache = Maps.newHashMap();
- project.setSessionProperty(CACHE_NAME, cache);
- }
-
- return cache;
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- return Maps.newHashMap();
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeLayoutAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeLayoutAction.java
deleted file mode 100644
index 306dd68c8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeLayoutAction.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
-
-/**
- * Action executed when the "Convert Layout" menu item is invoked.
- */
-public class ChangeLayoutAction extends VisualRefactoringAction {
- @Override
- public void run(IAction action) {
- if ((mTextSelection != null || mTreeSelection != null) && mFile != null) {
- ChangeLayoutRefactoring ref = new ChangeLayoutRefactoring(mFile, mDelegate,
- mTextSelection, mTreeSelection);
- RefactoringWizard wizard = new ChangeLayoutWizard(ref, mDelegate);
- RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation(wizard);
- try {
- op.run(mWindow.getShell(), wizard.getDefaultPageTitle());
- } catch (InterruptedException e) {
- // Interrupted. Pass.
- }
- }
- }
-
- public static IAction create(LayoutEditorDelegate editorDelegate) {
- return create("Change Layout...", editorDelegate, ChangeLayoutAction.class);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeLayoutContribution.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeLayoutContribution.java
deleted file mode 100644
index c508b7e92..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeLayoutContribution.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import org.eclipse.ltk.core.refactoring.RefactoringContribution;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-
-import java.util.Map;
-
-public class ChangeLayoutContribution extends RefactoringContribution {
-
- @SuppressWarnings("unchecked")
- @Override
- public RefactoringDescriptor createDescriptor(String id, String project, String description,
- String comment, Map arguments, int flags) throws IllegalArgumentException {
- return new ChangeLayoutRefactoring.Descriptor(project, description, comment, arguments);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public Map retrieveArgumentMap(RefactoringDescriptor descriptor) {
- if (descriptor instanceof ChangeLayoutRefactoring.Descriptor) {
- return ((ChangeLayoutRefactoring.Descriptor) descriptor).getArguments();
- }
- return super.retrieveArgumentMap(descriptor);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeLayoutRefactoring.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeLayoutRefactoring.java
deleted file mode 100644
index d8c85aab5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeLayoutRefactoring.java
+++ /dev/null
@@ -1,657 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ANDROID_WIDGET_PREFIX;
-import static com.android.SdkConstants.ATTR_BASELINE_ALIGNED;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_BASELINE;
-import static com.android.SdkConstants.ATTR_LAYOUT_BELOW;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_RESOURCE_PREFIX;
-import static com.android.SdkConstants.ATTR_LAYOUT_TO_RIGHT_OF;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.ATTR_ORIENTATION;
-import static com.android.SdkConstants.EXT_XML;
-import static com.android.SdkConstants.FQCN_GESTURE_OVERLAY_VIEW;
-import static com.android.SdkConstants.FQCN_GRID_LAYOUT;
-import static com.android.SdkConstants.FQCN_LINEAR_LAYOUT;
-import static com.android.SdkConstants.FQCN_RELATIVE_LAYOUT;
-import static com.android.SdkConstants.FQCN_TABLE_LAYOUT;
-import static com.android.SdkConstants.GESTURE_OVERLAY_VIEW;
-import static com.android.SdkConstants.LINEAR_LAYOUT;
-import static com.android.SdkConstants.TABLE_ROW;
-import static com.android.SdkConstants.VALUE_FALSE;
-import static com.android.SdkConstants.VALUE_VERTICAL;
-import static com.android.SdkConstants.VALUE_WRAP_CONTENT;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.VisibleForTesting;
-import com.android.ide.common.xml.XmlFormatStyle;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.CanvasViewInfo;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.LayoutCanvas;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.ViewHierarchy;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ITreeSelection;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Converts the selected layout into a layout of a different type.
- */
-@SuppressWarnings("restriction") // XML model
-public class ChangeLayoutRefactoring extends VisualRefactoring {
- private static final String KEY_TYPE = "type"; //$NON-NLS-1$
- private static final String KEY_FLATTEN = "flatten"; //$NON-NLS-1$
-
- private String mTypeFqcn;
- private String mInitializedAttributes;
- private boolean mFlatten;
-
- /**
- * This constructor is solely used by {@link Descriptor},
- * to replay a previous refactoring.
- * @param arguments argument map created by #createArgumentMap.
- */
- ChangeLayoutRefactoring(Map<String, String> arguments) {
- super(arguments);
- mTypeFqcn = arguments.get(KEY_TYPE);
- mFlatten = Boolean.parseBoolean(arguments.get(KEY_FLATTEN));
- }
-
- @VisibleForTesting
- ChangeLayoutRefactoring(List<Element> selectedElements, LayoutEditorDelegate delegate) {
- super(selectedElements, delegate);
- }
-
- public ChangeLayoutRefactoring(
- IFile file,
- LayoutEditorDelegate delegate,
- ITextSelection selection,
- ITreeSelection treeSelection) {
- super(file, delegate, selection, treeSelection);
- }
-
- @Override
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException,
- OperationCanceledException {
- RefactoringStatus status = new RefactoringStatus();
-
- try {
- pm.beginTask("Checking preconditions...", 2);
-
- if (mSelectionStart == -1 || mSelectionEnd == -1) {
- status.addFatalError("No selection to convert");
- return status;
- }
-
- if (mElements.size() != 1) {
- status.addFatalError("Select precisely one layout to convert");
- return status;
- }
-
- pm.worked(1);
- return status;
-
- } finally {
- pm.done();
- }
- }
-
- @Override
- protected VisualRefactoringDescriptor createDescriptor() {
- String comment = getName();
- return new Descriptor(
- mProject.getName(), //project
- comment, //description
- comment, //comment
- createArgumentMap());
- }
-
- @Override
- protected Map<String, String> createArgumentMap() {
- Map<String, String> args = super.createArgumentMap();
- args.put(KEY_TYPE, mTypeFqcn);
- args.put(KEY_FLATTEN, Boolean.toString(mFlatten));
-
- return args;
- }
-
- @Override
- public String getName() {
- return "Change Layout";
- }
-
- void setType(String typeFqcn) {
- mTypeFqcn = typeFqcn;
- }
-
- void setInitializedAttributes(String initializedAttributes) {
- mInitializedAttributes = initializedAttributes;
- }
-
- void setFlatten(boolean flatten) {
- mFlatten = flatten;
- }
-
- @Override
- protected List<Element> initElements() {
- List<Element> elements = super.initElements();
-
- // Don't convert a root GestureOverlayView; convert its child. This looks for
- // gesture overlays, and if found, it generates a new child list where the gesture
- // overlay children are replaced by their first element children
- for (Element element : elements) {
- String tagName = element.getTagName();
- if (tagName.equals(GESTURE_OVERLAY_VIEW)
- || tagName.equals(FQCN_GESTURE_OVERLAY_VIEW)) {
- List<Element> replacement = new ArrayList<Element>(elements.size());
- for (Element e : elements) {
- tagName = e.getTagName();
- if (tagName.equals(GESTURE_OVERLAY_VIEW)
- || tagName.equals(FQCN_GESTURE_OVERLAY_VIEW)) {
- NodeList children = e.getChildNodes();
- Element first = null;
- for (int i = 0, n = children.getLength(); i < n; i++) {
- Node node = children.item(i);
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- first = (Element) node;
- break;
- }
- }
- if (first != null) {
- e = first;
- }
- }
- replacement.add(e);
- }
- return replacement;
- }
- }
-
- return elements;
- }
-
- @Override
- protected @NonNull List<Change> computeChanges(IProgressMonitor monitor) {
- String name = getViewClass(mTypeFqcn);
-
- IFile file = mDelegate.getEditor().getInputFile();
- List<Change> changes = new ArrayList<Change>();
- if (file == null) {
- return changes;
- }
- TextFileChange change = new TextFileChange(file.getName(), file);
- MultiTextEdit rootEdit = new MultiTextEdit();
- change.setTextType(EXT_XML);
- changes.add(change);
-
- String text = getText(mSelectionStart, mSelectionEnd);
- Element layout = getPrimaryElement();
- String oldName = layout.getNodeName();
- int open = text.indexOf(oldName);
- int close = text.lastIndexOf(oldName);
-
- if (open != -1 && close != -1) {
- int oldLength = oldName.length();
- rootEdit.addChild(new ReplaceEdit(mSelectionStart + open, oldLength, name));
- if (close != open) { // Gracefully handle <FooLayout/>
- rootEdit.addChild(new ReplaceEdit(mSelectionStart + close, oldLength, name));
- }
- }
-
- String oldId = getId(layout);
- String newId = ensureIdMatchesType(layout, mTypeFqcn, rootEdit);
- // Update any layout references to the old id with the new id
- if (oldId != null && newId != null) {
- IStructuredModel model = mDelegate.getEditor().getModelForRead();
- try {
- IStructuredDocument doc = model.getStructuredDocument();
- if (doc != null) {
- List<TextEdit> replaceIds = replaceIds(getAndroidNamespacePrefix(), doc,
- mSelectionStart,
- mSelectionEnd, oldId, newId);
- for (TextEdit edit : replaceIds) {
- rootEdit.addChild(edit);
- }
- }
- } finally {
- model.releaseFromRead();
- }
- }
-
- String oldType = getOldType();
- String newType = mTypeFqcn;
-
- if (newType.equals(FQCN_RELATIVE_LAYOUT)) {
- if (oldType.equals(FQCN_LINEAR_LAYOUT) && !mFlatten) {
- // Hand-coded conversion specifically tailored for linear to relative, provided
- // there is no hierarchy flattening
- // TODO: use the RelativeLayoutConversionHelper for this; it does a better job
- // analyzing gravities etc.
- convertLinearToRelative(rootEdit);
- removeUndefinedAttrs(rootEdit, layout);
- addMissingWrapContentAttributes(rootEdit, layout, oldType, newType, null);
- } else {
- // Generic conversion to relative - can also flatten the hierarchy
- convertAnyToRelative(rootEdit, oldType, newType);
- // This already handles removing undefined layout attributes -- right?
- //removeUndefinedLayoutAttrs(rootEdit, layout);
- }
- } else if (newType.equals(FQCN_GRID_LAYOUT)) {
- convertAnyToGridLayout(rootEdit);
- // Layout attributes on children have already been removed as part of conversion
- // during the flattening
- removeUndefinedAttrs(rootEdit, layout, false /*removeLayoutAttrs*/);
- } else if (oldType.equals(FQCN_RELATIVE_LAYOUT) && newType.equals(FQCN_LINEAR_LAYOUT)) {
- convertRelativeToLinear(rootEdit);
- removeUndefinedAttrs(rootEdit, layout);
- addMissingWrapContentAttributes(rootEdit, layout, oldType, newType, null);
- } else if (oldType.equals(FQCN_LINEAR_LAYOUT) && newType.equals(FQCN_TABLE_LAYOUT)) {
- convertLinearToTable(rootEdit);
- removeUndefinedAttrs(rootEdit, layout);
- addMissingWrapContentAttributes(rootEdit, layout, oldType, newType, null);
- } else {
- convertGeneric(rootEdit, oldType, newType, layout);
- }
-
- if (mInitializedAttributes != null && mInitializedAttributes.length() > 0) {
- String namespace = getAndroidNamespacePrefix();
- for (String s : mInitializedAttributes.split(",")) { //$NON-NLS-1$
- String[] nameValue = s.split("="); //$NON-NLS-1$
- String attribute = nameValue[0];
- String value = nameValue[1];
- String prefix = null;
- String namespaceUri = null;
- if (attribute.startsWith(SdkConstants.ANDROID_NS_NAME_PREFIX)) {
- prefix = namespace;
- namespaceUri = ANDROID_URI;
- attribute = attribute.substring(SdkConstants.ANDROID_NS_NAME_PREFIX.length());
- }
- setAttribute(rootEdit, layout, namespaceUri,
- prefix, attribute, value);
- }
- }
-
- if (AdtPrefs.getPrefs().getFormatGuiXml()) {
- MultiTextEdit formatted = reformat(rootEdit, XmlFormatStyle.LAYOUT);
- if (formatted != null) {
- rootEdit = formatted;
- }
- }
- change.setEdit(rootEdit);
-
- return changes;
- }
-
- /** Checks whether we need to add any missing attributes on the elements */
- private void addMissingWrapContentAttributes(MultiTextEdit rootEdit, Element layout,
- String oldType, String newType, Set<Element> skip) {
- if (oldType.equals(FQCN_GRID_LAYOUT) && !newType.equals(FQCN_GRID_LAYOUT)) {
- String namespace = getAndroidNamespacePrefix();
-
- for (Element child : DomUtilities.getChildren(layout)) {
- if (skip != null && skip.contains(child)) {
- continue;
- }
-
- if (!child.hasAttributeNS(ANDROID_URI, ATTR_LAYOUT_WIDTH)) {
- setAttribute(rootEdit, child, ANDROID_URI,
- namespace, ATTR_LAYOUT_WIDTH, VALUE_WRAP_CONTENT);
- }
- if (!child.hasAttributeNS(ANDROID_URI, ATTR_LAYOUT_HEIGHT)) {
- setAttribute(rootEdit, child, ANDROID_URI,
- namespace, ATTR_LAYOUT_HEIGHT, VALUE_WRAP_CONTENT);
- }
- }
- }
- }
-
- /** Hand coded conversion from a LinearLayout to a TableLayout */
- private void convertLinearToTable(MultiTextEdit rootEdit) {
- // This is pretty easy; just switch the root tag (already done by the initial generic
- // conversion) and then convert all the children into <TableRow> elements.
- // Finally, get rid of the orientation attribute, if any.
- Element layout = getPrimaryElement();
- removeOrientationAttribute(rootEdit, layout);
-
- NodeList children = layout.getChildNodes();
- for (int i = 0, n = children.getLength(); i < n; i++) {
- Node node = children.item(i);
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- Element child = (Element) node;
- if (node instanceof IndexedRegion) {
- IndexedRegion region = (IndexedRegion) node;
- int start = region.getStartOffset();
- int end = region.getEndOffset();
- String text = getText(start, end);
- String oldName = child.getNodeName();
- if (oldName.equals(LINEAR_LAYOUT)) {
- removeOrientationAttribute(rootEdit, child);
- int open = text.indexOf(oldName);
- int close = text.lastIndexOf(oldName);
-
- if (open != -1 && close != -1) {
- int oldLength = oldName.length();
- rootEdit.addChild(new ReplaceEdit(mSelectionStart + open, oldLength,
- TABLE_ROW));
- if (close != open) { // Gracefully handle <FooLayout/>
- rootEdit.addChild(new ReplaceEdit(mSelectionStart + close,
- oldLength, TABLE_ROW));
- }
- }
- } // else: WRAP in TableLayout!
- }
- }
- }
- }
-
- /** Hand coded conversion from a LinearLayout to a RelativeLayout */
- private void convertLinearToRelative(MultiTextEdit rootEdit) {
- // This can be done accurately.
- Element layout = getPrimaryElement();
- // Horizontal is the default, so if no value is specified it is horizontal.
- boolean isVertical = VALUE_VERTICAL.equals(layout.getAttributeNS(ANDROID_URI,
- ATTR_ORIENTATION));
-
- String attributePrefix = getAndroidNamespacePrefix();
-
- // TODO: Consider gravity of each element
- // TODO: Consider weight of each element
- // Right now it simply makes a single attachment to keep the order.
-
- if (isVertical) {
- // Align each child to the bottom and left of its parent
- NodeList children = layout.getChildNodes();
- String prevId = null;
- for (int i = 0, n = children.getLength(); i < n; i++) {
- Node node = children.item(i);
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- Element child = (Element) node;
- String id = ensureHasId(rootEdit, child, null);
- if (prevId != null) {
- setAttribute(rootEdit, child, ANDROID_URI, attributePrefix,
- ATTR_LAYOUT_BELOW, prevId);
- }
- prevId = id;
- }
- }
- } else {
- // Align each child to the left
- NodeList children = layout.getChildNodes();
- boolean isBaselineAligned =
- !VALUE_FALSE.equals(layout.getAttributeNS(ANDROID_URI, ATTR_BASELINE_ALIGNED));
-
- String prevId = null;
- for (int i = 0, n = children.getLength(); i < n; i++) {
- Node node = children.item(i);
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- Element child = (Element) node;
- String id = ensureHasId(rootEdit, child, null);
- if (prevId != null) {
- setAttribute(rootEdit, child, ANDROID_URI, attributePrefix,
- ATTR_LAYOUT_TO_RIGHT_OF, prevId);
- if (isBaselineAligned) {
- setAttribute(rootEdit, child, ANDROID_URI, attributePrefix,
- ATTR_LAYOUT_ALIGN_BASELINE, prevId);
- }
- }
- prevId = id;
- }
- }
- }
- }
-
- /** Strips out the android:orientation attribute from the given linear layout element */
- private void removeOrientationAttribute(MultiTextEdit rootEdit, Element layout) {
- assert layout.getTagName().equals(LINEAR_LAYOUT);
- removeAttribute(rootEdit, layout, ANDROID_URI, ATTR_ORIENTATION);
- }
-
- /**
- * Hand coded conversion from a RelativeLayout to a LinearLayout
- *
- * @param rootEdit the root multi text edit to add edits to
- */
- private void convertRelativeToLinear(MultiTextEdit rootEdit) {
- // This is going to be lossy...
- // TODO: Attempt to "order" the items based on their visual positions
- // and insert them in that order in the LinearLayout.
- // TODO: Possibly use nesting if necessary, by spatial subdivision,
- // to accomplish roughly the same layout as the relative layout specifies.
- }
-
- /**
- * Hand coded -generic- conversion from one layout to another. This is not going to be
- * an accurate layout transformation; instead it simply migrates the layout attributes
- * that are supported, and adds defaults for any new required layout attributes. In
- * addition, it attempts to order the children visually based on where they fit in a
- * rendering. (Unsupported layout attributes will be removed by the caller at the
- * end.)
- * <ul>
- * <li>Try to handle nesting. Converting a *hierarchy* of layouts into a flatter
- * layout for powerful layouts that support it, like RelativeLayout.
- * <li>Try to do automatic "inference" about the layout. I can render it and look at
- * the ViewInfo positions and sizes. I can render it multiple times, at different
- * sizes, to infer "stretchiness" and "weight" properties of the children.
- * <li>Try to do indirect transformations. E.g. if I can go from A to B, and B to C,
- * then an attempt to go from A to C should perform conversions A to B and then B to
- * C.
- * </ul>
- *
- * @param rootEdit the root multi text edit to add edits to
- * @param oldType the fully qualified class name of the layout type we are converting
- * from
- * @param newType the fully qualified class name of the layout type we are converting
- * to
- * @param layout the layout to be converted
- */
- private void convertGeneric(MultiTextEdit rootEdit, String oldType, String newType,
- Element layout) {
- // TODO: Add hooks for 3rd party conversions getting registered through the
- // IViewRule interface.
-
- // For now we simply go with the default behavior, which is to just strip the
- // layout attributes that aren't supported.
- removeUndefinedAttrs(rootEdit, layout);
- addMissingWrapContentAttributes(rootEdit, layout, oldType, newType, null);
- }
-
- /**
- * Removes all the unavailable attributes after a conversion, both on the
- * layout element itself as well as the layout attributes of any of the
- * children
- */
- private void removeUndefinedAttrs(MultiTextEdit rootEdit, Element layout) {
- removeUndefinedAttrs(rootEdit, layout, true /*removeLayoutAttrs*/);
- }
-
- private void removeUndefinedAttrs(MultiTextEdit rootEdit, Element layout,
- boolean removeLayoutAttrs) {
- ViewElementDescriptor descriptor = getElementDescriptor(mTypeFqcn);
- if (descriptor == null) {
- return;
- }
-
- if (removeLayoutAttrs) {
- Set<String> defined = new HashSet<String>();
- AttributeDescriptor[] layoutAttributes = descriptor.getLayoutAttributes();
- for (AttributeDescriptor attribute : layoutAttributes) {
- defined.add(attribute.getXmlLocalName());
- }
-
- NodeList children = layout.getChildNodes();
- for (int i = 0, n = children.getLength(); i < n; i++) {
- Node node = children.item(i);
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- Element child = (Element) node;
-
- List<Attr> attributes = findLayoutAttributes(child);
- for (Attr attribute : attributes) {
- String name = attribute.getLocalName();
- if (!defined.contains(name)) {
- // Remove it
- try {
- removeAttribute(rootEdit, child, attribute.getNamespaceURI(), name);
- } catch (MalformedTreeException mte) {
- // Sometimes refactoring has modified attribute; not removing
- // it is non-fatal so just warn instead of letting refactoring
- // operation abort
- AdtPlugin.log(IStatus.WARNING,
- "Could not remove unsupported attribute %1$s; " + //$NON-NLS-1$
- "already modified during refactoring?", //$NON-NLS-1$
- attribute.getLocalName());
- }
- }
- }
- }
- }
- }
-
- // Also remove the unavailable attributes (not layout attributes) on the
- // converted element
- Set<String> defined = new HashSet<String>();
- AttributeDescriptor[] attributes = descriptor.getAttributes();
- for (AttributeDescriptor attribute : attributes) {
- defined.add(attribute.getXmlLocalName());
- }
-
- // Remove undefined attributes on the layout element itself
- NamedNodeMap attributeMap = layout.getAttributes();
- for (int i = 0, n = attributeMap.getLength(); i < n; i++) {
- Node attributeNode = attributeMap.item(i);
-
- String name = attributeNode.getLocalName();
- if (!name.startsWith(ATTR_LAYOUT_RESOURCE_PREFIX)
- && ANDROID_URI.equals(attributeNode.getNamespaceURI())) {
- if (!defined.contains(name)) {
- // Remove it
- removeAttribute(rootEdit, layout, ANDROID_URI, name);
- }
- }
- }
- }
-
- /** Hand coded conversion from any layout to a RelativeLayout */
- private void convertAnyToRelative(MultiTextEdit rootEdit, String oldType, String newType) {
- // To perform a conversion from any other layout type, including nested conversion,
- Element layout = getPrimaryElement();
- CanvasViewInfo rootView = mRootView;
- if (rootView == null) {
- LayoutCanvas canvas = mDelegate.getGraphicalEditor().getCanvasControl();
- ViewHierarchy viewHierarchy = canvas.getViewHierarchy();
- rootView = viewHierarchy.getRoot();
- }
-
- RelativeLayoutConversionHelper helper =
- new RelativeLayoutConversionHelper(this, layout, mFlatten, rootEdit, rootView);
- helper.convertToRelative();
- List<Element> deletedElements = helper.getDeletedElements();
- Set<Element> deleted = null;
- if (deletedElements != null && deletedElements.size() > 0) {
- deleted = new HashSet<Element>(deletedElements);
- }
- addMissingWrapContentAttributes(rootEdit, layout, oldType, newType, deleted);
- }
-
- /** Hand coded conversion from any layout to a GridLayout */
- private void convertAnyToGridLayout(MultiTextEdit rootEdit) {
- // To perform a conversion from any other layout type, including nested conversion,
- Element layout = getPrimaryElement();
- CanvasViewInfo rootView = mRootView;
- if (rootView == null) {
- LayoutCanvas canvas = mDelegate.getGraphicalEditor().getCanvasControl();
- ViewHierarchy viewHierarchy = canvas.getViewHierarchy();
- rootView = viewHierarchy.getRoot();
- }
-
- GridLayoutConverter converter = new GridLayoutConverter(this, layout, mFlatten,
- rootEdit, rootView);
- converter.convertToGridLayout();
- }
-
- public static class Descriptor extends VisualRefactoringDescriptor {
- public Descriptor(String project, String description, String comment,
- Map<String, String> arguments) {
- super("com.android.ide.eclipse.adt.refactoring.convert", //$NON-NLS-1$
- project, description, comment, arguments);
- }
-
- @Override
- protected Refactoring createRefactoring(Map<String, String> args) {
- return new ChangeLayoutRefactoring(args);
- }
- }
-
- String getOldType() {
- Element primary = getPrimaryElement();
- if (primary != null) {
- String oldType = primary.getTagName();
- if (oldType.indexOf('.') == -1) {
- oldType = ANDROID_WIDGET_PREFIX + oldType;
- }
- return oldType;
- }
-
- return null;
- }
-
- @VisibleForTesting
- protected CanvasViewInfo mRootView;
-
- @VisibleForTesting
- public void setRootView(CanvasViewInfo rootView) {
- mRootView = rootView;
- }
-
- @Override
- VisualRefactoringWizard createWizard() {
- return new ChangeLayoutWizard(this, mDelegate);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeLayoutWizard.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeLayoutWizard.java
deleted file mode 100644
index f5582712f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeLayoutWizard.java
+++ /dev/null
@@ -1,195 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import static com.android.SdkConstants.FQCN_GRID_LAYOUT;
-import static com.android.SdkConstants.FQCN_RELATIVE_LAYOUT;
-import static com.android.SdkConstants.GRID_LAYOUT;
-import static com.android.SdkConstants.RELATIVE_LAYOUT;
-import static com.android.SdkConstants.VIEW_FRAGMENT;
-import static com.android.SdkConstants.VIEW_INCLUDE;
-import static com.android.SdkConstants.VIEW_MERGE;
-
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.PaletteMetadataDescriptor;
-import com.android.utils.Pair;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-class ChangeLayoutWizard extends VisualRefactoringWizard {
-
- public ChangeLayoutWizard(ChangeLayoutRefactoring ref, LayoutEditorDelegate editor) {
- super(ref, editor);
- setDefaultPageTitle("Change Layout");
- }
-
- @Override
- protected void addUserInputPages() {
- ChangeLayoutRefactoring ref = (ChangeLayoutRefactoring) getRefactoring();
- String oldType = ref.getOldType();
- addPage(new InputPage(mDelegate.getEditor().getProject(), oldType));
- }
-
- /** Wizard page which inputs parameters for the {@link ChangeLayoutRefactoring} operation */
- private static class InputPage extends VisualRefactoringInputPage {
- private final IProject mProject;
- private final String mOldType;
- private Combo mTypeCombo;
- private Button mFlatten;
- private List<Pair<String, ViewElementDescriptor>> mClassNames;
-
- public InputPage(IProject project, String oldType) {
- super("ChangeLayoutInputPage"); //$NON-NLS-1$
- mProject = project;
- mOldType = oldType;
- }
-
- @Override
- public void createControl(Composite parent) {
- Composite composite = new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(2, false));
-
- Label fromLabel = new Label(composite, SWT.NONE);
- fromLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
- String oldTypeBase = mOldType.substring(mOldType.lastIndexOf('.') + 1);
- fromLabel.setText(String.format("Change from %1$s", oldTypeBase));
-
- Label typeLabel = new Label(composite, SWT.NONE);
- typeLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- typeLabel.setText("New Layout Type:");
-
- mTypeCombo = new Combo(composite, SWT.READ_ONLY);
- mTypeCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- SelectionAdapter selectionListener = new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- validatePage();
- // Hierarchy flattening only works for relative layout (and any future
- // layouts that can also support arbitrary layouts).
- String text = mTypeCombo.getText();
- mFlatten.setVisible(text.equals(RELATIVE_LAYOUT) || text.equals(GRID_LAYOUT));
- }
- };
- mTypeCombo.addSelectionListener(selectionListener);
- mTypeCombo.addSelectionListener(mSelectionValidateListener);
-
- mFlatten = new Button(composite, SWT.CHECK);
- mFlatten.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER,
- false, false, 2, 1));
- mFlatten.setText("Flatten hierarchy");
- mFlatten.addSelectionListener(selectionListener);
- // Should flattening be selected by default?
- mFlatten.setSelection(true);
- mFlatten.addSelectionListener(mSelectionValidateListener);
-
- // We don't exclude RelativeLayout even if the current layout is RelativeLayout,
- // in case you are trying to flatten the hierarchy for a hierarchy that has a
- // RelativeLayout at the root.
- Set<String> exclude = new HashSet<String>();
- exclude.add(VIEW_INCLUDE);
- exclude.add(VIEW_MERGE);
- exclude.add(VIEW_FRAGMENT);
- boolean oldIsRelativeLayout = mOldType.equals(FQCN_RELATIVE_LAYOUT);
- boolean oldIsGridLayout = mOldType.equals(FQCN_GRID_LAYOUT);
- if (oldIsRelativeLayout || oldIsGridLayout) {
- exclude.add(mOldType);
- }
- mClassNames = WrapInWizard.addLayouts(mProject, mOldType, mTypeCombo, exclude, false);
-
- boolean gridLayoutAvailable = false;
- for (int i = 0; i < mTypeCombo.getItemCount(); i++) {
- if (mTypeCombo.getItem(i).equals(GRID_LAYOUT)) {
- gridLayoutAvailable = true;
- break;
- }
- }
-
- mTypeCombo.select(0);
- // The default should be GridLayout (if available) and if not RelativeLayout,
- // if available (and not the old Type)
- if (gridLayoutAvailable && !oldIsGridLayout) {
- for (int i = 0; i < mTypeCombo.getItemCount(); i++) {
- if (mTypeCombo.getItem(i).equals(GRID_LAYOUT)) {
- mTypeCombo.select(i);
- break;
- }
- }
- } else if (!oldIsRelativeLayout) {
- for (int i = 0; i < mTypeCombo.getItemCount(); i++) {
- if (mTypeCombo.getItem(i).equals(RELATIVE_LAYOUT)) {
- mTypeCombo.select(i);
- break;
- }
- }
- }
- mFlatten.setVisible(mTypeCombo.getText().equals(RELATIVE_LAYOUT)
- || mTypeCombo.getText().equals(GRID_LAYOUT));
-
- setControl(composite);
- validatePage();
- }
-
- @Override
- protected boolean validatePage() {
- boolean ok = true;
-
- int selectionIndex = mTypeCombo.getSelectionIndex();
- String type = selectionIndex != -1 ? mClassNames.get(selectionIndex).getFirst() : null;
- if (type == null) {
- setErrorMessage("Select a layout type");
- ok = false; // The user has chosen a separator
- } else {
- setErrorMessage(null);
-
- // Record state
- ChangeLayoutRefactoring refactoring =
- (ChangeLayoutRefactoring) getRefactoring();
- refactoring.setType(type);
- refactoring.setFlatten(mFlatten.getSelection());
-
- ViewElementDescriptor descriptor = mClassNames.get(selectionIndex).getSecond();
- if (descriptor instanceof PaletteMetadataDescriptor) {
- PaletteMetadataDescriptor paletteDescriptor =
- (PaletteMetadataDescriptor) descriptor;
- String initializedAttributes = paletteDescriptor.getInitializedAttributes();
- if (initializedAttributes != null && initializedAttributes.length() > 0) {
- refactoring.setInitializedAttributes(initializedAttributes);
- }
- } else {
- refactoring.setInitializedAttributes(null);
- }
- }
-
- setPageComplete(ok);
- return ok;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeViewAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeViewAction.java
deleted file mode 100644
index fa14e5222..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeViewAction.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
-
-/**
- * Action executed when the "Change View Type" menu item is invoked.
- */
-public class ChangeViewAction extends VisualRefactoringAction {
- @Override
- public void run(IAction action) {
- if ((mTextSelection != null || mTreeSelection != null) && mFile != null) {
- ChangeViewRefactoring ref = new ChangeViewRefactoring(mFile, mDelegate,
- mTextSelection, mTreeSelection);
- RefactoringWizard wizard = new ChangeViewWizard(ref, mDelegate);
- RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation(wizard);
- try {
- op.run(mWindow.getShell(), wizard.getDefaultPageTitle());
- } catch (InterruptedException e) {
- // Interrupted. Pass.
- }
- }
- }
-
- public static IAction create(LayoutEditorDelegate editorDelegate) {
- return create("Change Widget Type...", editorDelegate, ChangeViewAction.class);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeViewContribution.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeViewContribution.java
deleted file mode 100644
index 7705ed808..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeViewContribution.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import org.eclipse.ltk.core.refactoring.RefactoringContribution;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-
-import java.util.Map;
-
-public class ChangeViewContribution extends RefactoringContribution {
-
- @SuppressWarnings("unchecked")
- @Override
- public RefactoringDescriptor createDescriptor(String id, String project, String description,
- String comment, Map arguments, int flags) throws IllegalArgumentException {
- return new ChangeViewRefactoring.Descriptor(project, description, comment, arguments);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public Map retrieveArgumentMap(RefactoringDescriptor descriptor) {
- if (descriptor instanceof ChangeViewRefactoring.Descriptor) {
- return ((ChangeViewRefactoring.Descriptor) descriptor).getArguments();
- }
- return super.retrieveArgumentMap(descriptor);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeViewRefactoring.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeViewRefactoring.java
deleted file mode 100644
index 73f5eb149..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeViewRefactoring.java
+++ /dev/null
@@ -1,298 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ANDROID_WIDGET_PREFIX;
-import static com.android.SdkConstants.ATTR_LAYOUT_RESOURCE_PREFIX;
-import static com.android.SdkConstants.ATTR_TEXT;
-import static com.android.SdkConstants.EXT_XML;
-import static com.android.SdkConstants.VIEW_FRAGMENT;
-import static com.android.SdkConstants.VIEW_INCLUDE;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.VisibleForTesting;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.CanvasViewInfo;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ITreeSelection;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.eclipse.wst.xml.core.internal.document.ElementImpl;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Changes the type of the given widgets to the given target type
- * and updates the attributes if necessary
- */
-@SuppressWarnings("restriction") // XML model
-public class ChangeViewRefactoring extends VisualRefactoring {
- private static final String KEY_TYPE = "type"; //$NON-NLS-1$
- private String mTypeFqcn;
-
- /**
- * This constructor is solely used by {@link Descriptor},
- * to replay a previous refactoring.
- * @param arguments argument map created by #createArgumentMap.
- */
- ChangeViewRefactoring(Map<String, String> arguments) {
- super(arguments);
- mTypeFqcn = arguments.get(KEY_TYPE);
- }
-
- public ChangeViewRefactoring(
- IFile file,
- LayoutEditorDelegate delegate,
- ITextSelection selection,
- ITreeSelection treeSelection) {
- super(file, delegate, selection, treeSelection);
- }
-
- @VisibleForTesting
- ChangeViewRefactoring(List<Element> selectedElements, LayoutEditorDelegate editor) {
- super(selectedElements, editor);
- }
-
- @Override
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException,
- OperationCanceledException {
- RefactoringStatus status = new RefactoringStatus();
-
- try {
- pm.beginTask("Checking preconditions...", 6);
-
- if (mSelectionStart == -1 || mSelectionEnd == -1) {
- status.addFatalError("No selection to convert");
- return status;
- }
-
- // Make sure the selection is contiguous
- if (mTreeSelection != null) {
- List<CanvasViewInfo> infos = getSelectedViewInfos();
- if (!validateNotEmpty(infos, status)) {
- return status;
- }
- }
-
- // Ensures that we have a valid DOM model:
- if (mElements.size() == 0) {
- status.addFatalError("Nothing to convert");
- return status;
- }
-
- pm.worked(1);
- return status;
-
- } finally {
- pm.done();
- }
- }
-
- @Override
- protected VisualRefactoringDescriptor createDescriptor() {
- String comment = getName();
- return new Descriptor(
- mProject.getName(), //project
- comment, //description
- comment, //comment
- createArgumentMap());
- }
-
- @Override
- protected Map<String, String> createArgumentMap() {
- Map<String, String> args = super.createArgumentMap();
- args.put(KEY_TYPE, mTypeFqcn);
-
- return args;
- }
-
- @Override
- public String getName() {
- return "Change Widget Type";
- }
-
- void setType(String typeFqcn) {
- mTypeFqcn = typeFqcn;
- }
-
- @Override
- protected @NonNull List<Change> computeChanges(IProgressMonitor monitor) {
- String name = getViewClass(mTypeFqcn);
-
- IFile file = mDelegate.getEditor().getInputFile();
- List<Change> changes = new ArrayList<Change>();
- if (file == null) {
- return changes;
- }
- TextFileChange change = new TextFileChange(file.getName(), file);
- MultiTextEdit rootEdit = new MultiTextEdit();
- change.setEdit(rootEdit);
- change.setTextType(EXT_XML);
- changes.add(change);
-
- for (Element element : getElements()) {
- IndexedRegion region = getRegion(element);
- String text = getText(region.getStartOffset(), region.getEndOffset());
- String oldName = element.getNodeName();
- int open = text.indexOf(oldName);
- int close = text.lastIndexOf(oldName);
- if (element instanceof ElementImpl && ((ElementImpl) element).isEmptyTag()) {
- close = -1;
- }
-
- if (open != -1) {
- int oldLength = oldName.length();
- rootEdit.addChild(new ReplaceEdit(region.getStartOffset() + open,
- oldLength, name));
- }
- if (close != -1 && close != open) {
- int oldLength = oldName.length();
- rootEdit.addChild(new ReplaceEdit(region.getStartOffset() + close, oldLength,
- name));
- }
-
- // Change tag type
- String oldId = getId(element);
- String newId = ensureIdMatchesType(element, mTypeFqcn, rootEdit);
- // Update any layout references to the old id with the new id
- if (oldId != null && newId != null) {
- IStructuredModel model = mDelegate.getEditor().getModelForRead();
- try {
- IStructuredDocument doc = model.getStructuredDocument();
- if (doc != null) {
- IndexedRegion range = getRegion(element);
- int skipStart = range.getStartOffset();
- int skipEnd = range.getEndOffset();
- List<TextEdit> replaceIds = replaceIds(getAndroidNamespacePrefix(), doc,
- skipStart, skipEnd,
- oldId, newId);
- for (TextEdit edit : replaceIds) {
- rootEdit.addChild(edit);
- }
- }
- } finally {
- model.releaseFromRead();
- }
- }
-
- // Strip out attributes that no longer make sense
- removeUndefinedAttrs(rootEdit, element);
- }
-
- return changes;
- }
-
- /** Removes all the unused attributes after a conversion */
- private void removeUndefinedAttrs(MultiTextEdit rootEdit, Element element) {
- ViewElementDescriptor descriptor = getElementDescriptor(mTypeFqcn);
- if (descriptor == null) {
- return;
- }
-
- Set<String> defined = new HashSet<String>();
- AttributeDescriptor[] layoutAttributes = descriptor.getAttributes();
- for (AttributeDescriptor attribute : layoutAttributes) {
- defined.add(attribute.getXmlLocalName());
- }
-
- List<Attr> attributes = findAttributes(element);
- for (Attr attribute : attributes) {
- String name = attribute.getLocalName();
- if (!defined.contains(name)) {
- // Remove it
- removeAttribute(rootEdit, element, attribute.getNamespaceURI(), name);
- }
- }
-
- // Set text attribute if it's defined
- if (defined.contains(ATTR_TEXT) && !element.hasAttributeNS(ANDROID_URI, ATTR_TEXT)) {
- setAttribute(rootEdit, element, ANDROID_URI, getAndroidNamespacePrefix(),
- ATTR_TEXT, descriptor.getUiName());
- }
- }
-
- protected List<Attr> findAttributes(Node root) {
- List<Attr> result = new ArrayList<Attr>();
- NamedNodeMap attributes = root.getAttributes();
- for (int i = 0, n = attributes.getLength(); i < n; i++) {
- Node attributeNode = attributes.item(i);
-
- String name = attributeNode.getLocalName();
- if (!name.startsWith(ATTR_LAYOUT_RESOURCE_PREFIX)
- && ANDROID_URI.equals(attributeNode.getNamespaceURI())) {
- result.add((Attr) attributeNode);
- }
- }
-
- return result;
- }
-
- List<String> getOldTypes() {
- List<String> types = new ArrayList<String>();
- for (Element primary : getElements()) {
- String oldType = primary.getTagName();
- if (oldType.indexOf('.') == -1
- && !oldType.equals(VIEW_INCLUDE) && !oldType.equals(VIEW_FRAGMENT)) {
- oldType = ANDROID_WIDGET_PREFIX + oldType;
- }
- types.add(oldType);
- }
-
- return types;
- }
-
- @Override
- VisualRefactoringWizard createWizard() {
- return new ChangeViewWizard(this, mDelegate);
- }
-
- public static class Descriptor extends VisualRefactoringDescriptor {
- public Descriptor(String project, String description, String comment,
- Map<String, String> arguments) {
- super("com.android.ide.eclipse.adt.refactoring.changeview", //$NON-NLS-1$
- project, description, comment, arguments);
- }
-
- @Override
- protected Refactoring createRefactoring(Map<String, String> args) {
- return new ChangeViewRefactoring(args);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeViewWizard.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeViewWizard.java
deleted file mode 100644
index 0ac7106b3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeViewWizard.java
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import static com.android.SdkConstants.REQUEST_FOCUS;
-import static com.android.SdkConstants.VIEW_FRAGMENT;
-import static com.android.SdkConstants.VIEW_INCLUDE;
-
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.CustomViewFinder;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.ViewMetadataRepository;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.sdklib.IAndroidTarget;
-import com.android.utils.Pair;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-
-import java.util.ArrayList;
-import java.util.List;
-
-class ChangeViewWizard extends VisualRefactoringWizard {
- private static final String SEPARATOR_LABEL =
- "----------------------------------------"; //$NON-NLS-1$
-
- public ChangeViewWizard(ChangeViewRefactoring ref, LayoutEditorDelegate editor) {
- super(ref, editor);
- setDefaultPageTitle("Change Widget Type");
- }
-
- @Override
- protected void addUserInputPages() {
- ChangeViewRefactoring ref = (ChangeViewRefactoring) getRefactoring();
- List<String> oldTypes = ref.getOldTypes();
- String oldType = null;
- for (String type : oldTypes) {
- if (oldType == null) {
- oldType = type;
- } else if (!oldType.equals(type)) {
- // If the types differ, don't offer related categories
- oldType = null;
- break;
- }
- }
- addPage(new InputPage(mDelegate.getEditor().getProject(), oldType));
- }
-
- /** Wizard page which inputs parameters for the {@link ChangeViewRefactoring} operation */
- private static class InputPage extends VisualRefactoringInputPage {
- private final IProject mProject;
- private Combo mTypeCombo;
- private final String mOldType;
- private List<String> mClassNames;
-
- public InputPage(IProject project, String oldType) {
- super("ChangeViewInputPage"); //$NON-NLS-1$
- mProject = project;
- mOldType = oldType;
- }
-
- @Override
- public void createControl(Composite parent) {
- Composite composite = new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(2, false));
-
- Label typeLabel = new Label(composite, SWT.NONE);
- typeLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- typeLabel.setText("New Widget Type:");
-
- mTypeCombo = new Combo(composite, SWT.READ_ONLY);
- mTypeCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- mTypeCombo.addSelectionListener(mSelectionValidateListener);
-
- mClassNames = getWidgetTypes(mOldType, mTypeCombo);
- mTypeCombo.select(0);
-
- setControl(composite);
- validatePage();
-
- mTypeCombo.setFocus();
- }
-
- private List<String> getWidgetTypes(String oldType, Combo combo) {
- List<String> classNames = new ArrayList<String>();
-
- // Populate type combo
- Sdk currentSdk = Sdk.getCurrent();
- if (currentSdk != null) {
- IAndroidTarget target = currentSdk.getTarget(mProject);
- if (target != null) {
- // Try to pick "related" widgets to the one you have selected.
- // For example, for an AnalogClock, display DigitalClock first.
- // For a Text, offer EditText, AutoComplete, etc.
- if (oldType != null) {
- ViewMetadataRepository repository = ViewMetadataRepository.get();
- List<String> relatedTo = repository.getRelatedTo(oldType);
- if (relatedTo.size() > 0) {
- for (String className : relatedTo) {
- String base = className.substring(className.lastIndexOf('.') + 1);
- combo.add(base);
- classNames.add(className);
- }
- combo.add(SEPARATOR_LABEL);
- classNames.add(null);
- }
- }
-
- Pair<List<String>,List<String>> result =
- CustomViewFinder.findViews(mProject, false);
- List<String> customViews = result.getFirst();
- List<String> thirdPartyViews = result.getSecond();
- if (customViews.size() > 0) {
- for (String view : customViews) {
- combo.add(view);
- classNames.add(view);
- }
- combo.add(SEPARATOR_LABEL);
- classNames.add(null);
- }
-
- if (thirdPartyViews.size() > 0) {
- for (String view : thirdPartyViews) {
- combo.add(view);
- classNames.add(view);
- }
- combo.add(SEPARATOR_LABEL);
- classNames.add(null);
- }
-
- AndroidTargetData targetData = currentSdk.getTargetData(target);
- if (targetData != null) {
- // Now add ALL known layout descriptors in case the user has
- // a special case
- List<ViewElementDescriptor> descriptors =
- targetData.getLayoutDescriptors().getViewDescriptors();
- for (ViewElementDescriptor d : descriptors) {
- String className = d.getFullClassName();
- if (className.equals(VIEW_INCLUDE)
- || className.equals(VIEW_FRAGMENT)
- || className.equals(REQUEST_FOCUS)) {
- continue;
- }
- combo.add(d.getUiName());
- classNames.add(className);
-
- }
- }
- }
- } else {
- combo.add("SDK not initialized");
- classNames.add(null);
- }
-
- return classNames;
- }
-
- @Override
- protected boolean validatePage() {
- boolean ok = true;
- int selectionIndex = mTypeCombo.getSelectionIndex();
- String type = selectionIndex != -1 ? mClassNames.get(selectionIndex) : null;
- if (type == null) {
- setErrorMessage("Select a widget type to convert to");
- ok = false; // The user has chosen a separator
- } else {
- setErrorMessage(null);
- }
-
- // Record state
- ChangeViewRefactoring refactoring =
- (ChangeViewRefactoring) getRefactoring();
- refactoring.setType(type);
-
- setPageComplete(ok);
- return ok;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractIncludeAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractIncludeAction.java
deleted file mode 100644
index 6f96fe489..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractIncludeAction.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
-
-/**
- * Action executed when the "Extract as Include" menu item is invoked.
- */
-public class ExtractIncludeAction extends VisualRefactoringAction {
- @Override
- public void run(IAction action) {
- if ((mTextSelection != null || mTreeSelection != null) && mFile != null) {
- ExtractIncludeRefactoring ref = new ExtractIncludeRefactoring(mFile, mDelegate,
- mTextSelection, mTreeSelection);
- RefactoringWizard wizard = new ExtractIncludeWizard(ref, mDelegate);
- RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation(wizard);
- try {
- op.run(mWindow.getShell(), wizard.getDefaultPageTitle());
- } catch (InterruptedException e) {
- // Interrupted. Pass.
- }
- }
- }
-
- public static IAction create(LayoutEditorDelegate editorDelegate) {
- return create("Extract Include...", editorDelegate, ExtractIncludeAction.class);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractIncludeContribution.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractIncludeContribution.java
deleted file mode 100644
index 5903812ea..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractIncludeContribution.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import org.eclipse.ltk.core.refactoring.RefactoringContribution;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-
-import java.util.Map;
-
-public class ExtractIncludeContribution extends RefactoringContribution {
-
- @SuppressWarnings("unchecked")
- @Override
- public RefactoringDescriptor createDescriptor(String id, String project, String description,
- String comment, Map arguments, int flags) throws IllegalArgumentException {
- return new ExtractIncludeRefactoring.Descriptor(project, description, comment, arguments);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public Map retrieveArgumentMap(RefactoringDescriptor descriptor) {
- if (descriptor instanceof ExtractIncludeRefactoring.Descriptor) {
- return ((ExtractIncludeRefactoring.Descriptor) descriptor).getArguments();
- }
- return super.retrieveArgumentMap(descriptor);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractIncludeRefactoring.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractIncludeRefactoring.java
deleted file mode 100644
index f58ac5501..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractIncludeRefactoring.java
+++ /dev/null
@@ -1,670 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import static com.android.SdkConstants.ANDROID_NS_NAME;
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_RESOURCE_PREFIX;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.DOT_XML;
-import static com.android.SdkConstants.EXT_XML;
-import static com.android.SdkConstants.FD_RES;
-import static com.android.SdkConstants.FD_RESOURCES;
-import static com.android.SdkConstants.FD_RES_LAYOUT;
-import static com.android.SdkConstants.ID_PREFIX;
-import static com.android.SdkConstants.NEW_ID_PREFIX;
-import static com.android.SdkConstants.VALUE_WRAP_CONTENT;
-import static com.android.SdkConstants.VIEW_INCLUDE;
-import static com.android.SdkConstants.XMLNS;
-import static com.android.SdkConstants.XMLNS_PREFIX;
-import static com.android.ide.eclipse.adt.AdtConstants.WS_SEP;
-import static com.android.resources.ResourceType.LAYOUT;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.VisibleForTesting;
-import com.android.ide.common.xml.XmlFormatStyle;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.formatting.EclipseXmlFormatPreferences;
-import com.android.ide.eclipse.adt.internal.editors.formatting.EclipseXmlPrettyPrinter;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.CanvasViewInfo;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.resources.ResourceNameValidator;
-import com.android.utils.XmlUtils;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.dialogs.IInputValidator;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ITreeSelection;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.NullChange;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.text.edits.InsertEdit;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.wst.sse.core.StructuredModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-
-/**
- * Extracts the selection and writes it out as a separate layout file, then adds an
- * include to that new layout file. Interactively asks the user for a new name for the
- * layout.
- */
-@SuppressWarnings("restriction") // XML model
-public class ExtractIncludeRefactoring extends VisualRefactoring {
- private static final String KEY_NAME = "name"; //$NON-NLS-1$
- private static final String KEY_OCCURRENCES = "all-occurrences"; //$NON-NLS-1$
- private String mLayoutName;
- private boolean mReplaceOccurrences;
-
- /**
- * This constructor is solely used by {@link Descriptor},
- * to replay a previous refactoring.
- * @param arguments argument map created by #createArgumentMap.
- */
- ExtractIncludeRefactoring(Map<String, String> arguments) {
- super(arguments);
- mLayoutName = arguments.get(KEY_NAME);
- mReplaceOccurrences = Boolean.parseBoolean(arguments.get(KEY_OCCURRENCES));
- }
-
- public ExtractIncludeRefactoring(
- IFile file,
- LayoutEditorDelegate delegate,
- ITextSelection selection,
- ITreeSelection treeSelection) {
- super(file, delegate, selection, treeSelection);
- }
-
- @VisibleForTesting
- ExtractIncludeRefactoring(List<Element> selectedElements, LayoutEditorDelegate editor) {
- super(selectedElements, editor);
- }
-
- @Override
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException,
- OperationCanceledException {
- RefactoringStatus status = new RefactoringStatus();
-
- try {
- pm.beginTask("Checking preconditions...", 6);
-
- if (mSelectionStart == -1 || mSelectionEnd == -1) {
- status.addFatalError("No selection to extract");
- return status;
- }
-
- // Make sure the selection is contiguous
- if (mTreeSelection != null) {
- // TODO - don't do this if we based the selection on text. In this case,
- // make sure we're -balanced-.
- List<CanvasViewInfo> infos = getSelectedViewInfos();
- if (!validateNotEmpty(infos, status)) {
- return status;
- }
-
- if (!validateNotRoot(infos, status)) {
- return status;
- }
-
- // Disable if you've selected a single include tag
- if (infos.size() == 1) {
- UiViewElementNode uiNode = infos.get(0).getUiViewNode();
- if (uiNode != null) {
- Node xmlNode = uiNode.getXmlNode();
- if (xmlNode.getLocalName().equals(VIEW_INCLUDE)) {
- status.addWarning("No point in refactoring a single include tag");
- }
- }
- }
-
- // Enforce that the selection is -contiguous-
- if (!validateContiguous(infos, status)) {
- return status;
- }
- }
-
- // This also ensures that we have a valid DOM model:
- if (mElements.size() == 0) {
- status.addFatalError("Nothing to extract");
- return status;
- }
-
- pm.worked(1);
- return status;
-
- } finally {
- pm.done();
- }
- }
-
- @Override
- protected VisualRefactoringDescriptor createDescriptor() {
- String comment = getName();
- return new Descriptor(
- mProject.getName(), //project
- comment, //description
- comment, //comment
- createArgumentMap());
- }
-
- @Override
- protected Map<String, String> createArgumentMap() {
- Map<String, String> args = super.createArgumentMap();
- args.put(KEY_NAME, mLayoutName);
- args.put(KEY_OCCURRENCES, Boolean.toString(mReplaceOccurrences));
-
- return args;
- }
-
- @Override
- public String getName() {
- return "Extract as Include";
- }
-
- void setLayoutName(String layoutName) {
- mLayoutName = layoutName;
- }
-
- void setReplaceOccurrences(boolean selection) {
- mReplaceOccurrences = selection;
- }
-
- // ---- Actual implementation of Extract as Include modification computation ----
-
- @Override
- protected @NonNull List<Change> computeChanges(IProgressMonitor monitor) {
- String extractedText = getExtractedText();
-
- String namespaceDeclarations = computeNamespaceDeclarations();
-
- // Insert namespace:
- extractedText = insertNamespace(extractedText, namespaceDeclarations);
-
- StringBuilder sb = new StringBuilder();
- sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); //$NON-NLS-1$
- sb.append(extractedText);
- sb.append('\n');
-
- List<Change> changes = new ArrayList<Change>();
-
- String newFileName = mLayoutName + DOT_XML;
- IProject project = mDelegate.getEditor().getProject();
- IFile sourceFile = mDelegate.getEditor().getInputFile();
- if (sourceFile == null) {
- return changes;
- }
-
- // Replace extracted elements by <include> tag
- handleIncludingFile(changes, sourceFile, mSelectionStart, mSelectionEnd,
- getDomDocument(), getPrimaryElement());
-
- // Also extract in other variations of the same file (landscape/portrait, etc)
- boolean haveVariations = false;
- if (mReplaceOccurrences) {
- List<IFile> layouts = getOtherLayouts(sourceFile);
- for (IFile file : layouts) {
- IModelManager modelManager = StructuredModelManager.getModelManager();
- IStructuredModel model = null;
- // We could enhance this with a SubMonitor to make the progress bar move as
- // well.
- monitor.subTask(String.format("Looking for duplicates in %1$s",
- file.getProjectRelativePath()));
- if (monitor.isCanceled()) {
- throw new OperationCanceledException();
- }
-
- try {
- model = modelManager.getModelForRead(file);
- if (model instanceof IDOMModel) {
- IDOMModel domModel = (IDOMModel) model;
- IDOMDocument otherDocument = domModel.getDocument();
- List<Element> otherElements = new ArrayList<Element>();
- Element otherPrimary = null;
-
- for (Element element : getElements()) {
- Element other = DomUtilities.findCorresponding(element,
- otherDocument);
- if (other != null) {
- // See if the structure is similar to what we have in this
- // document
- if (DomUtilities.isEquivalent(element, other)) {
- otherElements.add(other);
- if (element == getPrimaryElement()) {
- otherPrimary = other;
- }
- }
- }
- }
-
- // Only perform extract in the other file if we find a match for
- // ALL of elements being extracted, and if they too are contiguous
- if (otherElements.size() == getElements().size() &&
- DomUtilities.isContiguous(otherElements)) {
- // Find the range
- int begin = Integer.MAX_VALUE;
- int end = Integer.MIN_VALUE;
- for (Element element : otherElements) {
- // Yes!! Extract this one as well!
- IndexedRegion region = getRegion(element);
- end = Math.max(end, region.getEndOffset());
- begin = Math.min(begin, region.getStartOffset());
- }
- handleIncludingFile(changes, file, begin,
- end, otherDocument, otherPrimary);
- haveVariations = true;
- }
- }
- } catch (IOException e) {
- AdtPlugin.log(e, null);
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- } finally {
- if (model != null) {
- model.releaseFromRead();
- }
- }
- }
- }
-
- // Add change to create the new file
- IContainer parent = sourceFile.getParent();
- if (haveVariations) {
- // If we're extracting from multiple configuration folders, then we need to
- // place the extracted include in the base layout folder (if not it goes next to
- // the including file)
- parent = mProject.getFolder(FD_RES).getFolder(FD_RES_LAYOUT);
- }
- IPath parentPath = parent.getProjectRelativePath();
- final IFile file = project.getFile(new Path(parentPath + WS_SEP + newFileName));
- TextFileChange addFile = new TextFileChange("Create new separate layout", file);
- addFile.setTextType(EXT_XML);
- changes.add(addFile);
-
- String newFile = sb.toString();
- if (AdtPrefs.getPrefs().getFormatGuiXml()) {
- newFile = EclipseXmlPrettyPrinter.prettyPrint(newFile,
- EclipseXmlFormatPreferences.create(), XmlFormatStyle.LAYOUT,
- null /*lineSeparator*/);
- }
- addFile.setEdit(new InsertEdit(0, newFile));
-
- Change finishHook = createFinishHook(file);
- changes.add(finishHook);
-
- return changes;
- }
-
- private void handleIncludingFile(List<Change> changes,
- IFile sourceFile, int begin, int end, Document document, Element primary) {
- TextFileChange change = new TextFileChange(sourceFile.getName(), sourceFile);
- MultiTextEdit rootEdit = new MultiTextEdit();
- change.setTextType(EXT_XML);
- changes.add(change);
-
- String referenceId = getReferenceId();
- // Replace existing elements in the source file and insert <include>
- String androidNsPrefix = getAndroidNamespacePrefix(document);
- String include = computeIncludeString(primary, mLayoutName, androidNsPrefix, referenceId);
- int length = end - begin;
- ReplaceEdit replace = new ReplaceEdit(begin, length, include);
- rootEdit.addChild(replace);
-
- // Update any layout references to the old id with the new id
- if (referenceId != null && primary != null) {
- String rootId = getId(primary);
- IStructuredModel model = null;
- try {
- model = StructuredModelManager.getModelManager().getModelForRead(sourceFile);
- IStructuredDocument doc = model.getStructuredDocument();
- if (doc != null && rootId != null) {
- List<TextEdit> replaceIds = replaceIds(androidNsPrefix, doc, begin,
- end, rootId, referenceId);
- for (TextEdit edit : replaceIds) {
- rootEdit.addChild(edit);
- }
-
- if (AdtPrefs.getPrefs().getFormatGuiXml()) {
- MultiTextEdit formatted = reformat(doc.get(), rootEdit,
- XmlFormatStyle.LAYOUT);
- if (formatted != null) {
- rootEdit = formatted;
- }
- }
- }
- } catch (IOException e) {
- AdtPlugin.log(e, null);
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- } finally {
- if (model != null) {
- model.releaseFromRead();
- }
- }
- }
-
- change.setEdit(rootEdit);
- }
-
- /**
- * Returns a list of all the other layouts (in all configurations) in the project other
- * than the given source layout where the refactoring was initiated. Never null.
- */
- private List<IFile> getOtherLayouts(IFile sourceFile) {
- List<IFile> layouts = new ArrayList<IFile>(100);
- IPath sourcePath = sourceFile.getProjectRelativePath();
- IFolder resources = mProject.getFolder(FD_RESOURCES);
- try {
- for (IResource folder : resources.members()) {
- if (folder.getName().startsWith(FD_RES_LAYOUT) &&
- folder instanceof IFolder) {
- IFolder layoutFolder = (IFolder) folder;
- for (IResource file : layoutFolder.members()) {
- if (file.getName().endsWith(EXT_XML)
- && file instanceof IFile) {
- if (!file.getProjectRelativePath().equals(sourcePath)) {
- layouts.add((IFile) file);
- }
- }
- }
- }
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
-
- return layouts;
- }
-
- String getInitialName() {
- String defaultName = ""; //$NON-NLS-1$
- Element primary = getPrimaryElement();
- if (primary != null) {
- String id = primary.getAttributeNS(ANDROID_URI, ATTR_ID);
- // id null check for https://bugs.eclipse.org/bugs/show_bug.cgi?id=272378
- if (id != null && (id.startsWith(ID_PREFIX) || id.startsWith(NEW_ID_PREFIX))) {
- // Use everything following the id/, and make it lowercase since that is
- // the convention for layouts (and use Locale.US to ensure that "Image" becomes
- // "image" etc)
- defaultName = id.substring(id.indexOf('/') + 1).toLowerCase(Locale.US);
-
- IInputValidator validator = ResourceNameValidator.create(true, mProject, LAYOUT);
-
- if (validator.isValid(defaultName) != null) { // Already exists?
- defaultName = ""; //$NON-NLS-1$
- }
- }
- }
-
- return defaultName;
- }
-
- IFile getSourceFile() {
- return mFile;
- }
-
- private Change createFinishHook(final IFile file) {
- return new NullChange("Open extracted layout and refresh resources") {
- @Override
- public Change perform(IProgressMonitor pm) throws CoreException {
- Display display = AdtPlugin.getDisplay();
- display.asyncExec(new Runnable() {
- @Override
- public void run() {
- openFile(file);
- mDelegate.getGraphicalEditor().refreshProjectResources();
- // Save file to trigger include finder scanning (as well as making
- // the
- // actual show-include feature work since it relies on reading
- // files from
- // disk, not a live buffer)
- IWorkbenchPage page = mDelegate.getEditor().getEditorSite().getPage();
- page.saveEditor(mDelegate.getEditor(), false);
- }
- });
-
- // Not undoable: just return null instead of an undo-change.
- return null;
- }
- };
- }
-
- private String computeNamespaceDeclarations() {
- String androidNsPrefix = null;
- String namespaceDeclarations = null;
-
- StringBuilder sb = new StringBuilder();
- List<Attr> attributeNodes = findNamespaceAttributes();
- for (Node attributeNode : attributeNodes) {
- String prefix = attributeNode.getPrefix();
- if (XMLNS.equals(prefix)) {
- sb.append(' ');
- String name = attributeNode.getNodeName();
- sb.append(name);
- sb.append('=').append('"');
-
- String value = attributeNode.getNodeValue();
- if (value.equals(ANDROID_URI)) {
- androidNsPrefix = name;
- if (androidNsPrefix.startsWith(XMLNS_PREFIX)) {
- androidNsPrefix = androidNsPrefix.substring(XMLNS_PREFIX.length());
- }
- }
- sb.append(XmlUtils.toXmlAttributeValue(value));
- sb.append('"');
- }
- }
- namespaceDeclarations = sb.toString();
-
- if (androidNsPrefix == null) {
- androidNsPrefix = ANDROID_NS_NAME;
- }
-
- if (namespaceDeclarations.length() == 0) {
- sb.setLength(0);
- sb.append(' ');
- sb.append(XMLNS_PREFIX);
- sb.append(androidNsPrefix);
- sb.append('=').append('"');
- sb.append(ANDROID_URI);
- sb.append('"');
- namespaceDeclarations = sb.toString();
- }
-
- return namespaceDeclarations;
- }
-
- /** Returns the id to be used for the include tag itself (may be null) */
- private String getReferenceId() {
- String rootId = getRootId();
- if (rootId != null) {
- return rootId + "_ref";
- }
-
- return null;
- }
-
- /**
- * Compute the actual {@code <include>} string to be inserted in place of the old
- * selection
- */
- private static String computeIncludeString(Element primaryNode, String newName,
- String androidNsPrefix, String referenceId) {
- StringBuilder sb = new StringBuilder();
- sb.append("<include layout=\"@layout/"); //$NON-NLS-1$
- sb.append(newName);
- sb.append('"');
- sb.append(' ');
-
- // Create new id for the include itself
- if (referenceId != null) {
- sb.append(androidNsPrefix);
- sb.append(':');
- sb.append(ATTR_ID);
- sb.append('=').append('"');
- sb.append(referenceId);
- sb.append('"').append(' ');
- }
-
- // Add id string, unless it's a <merge>, since we may need to adjust any layout
- // references to apply to the <include> tag instead
-
- // I should move all the layout_ attributes as well
- // I also need to duplicate and modify the id and then replace
- // everything else in the file with this new id...
-
- // HACK: see issue 13494: We must duplicate the width/height attributes on the
- // <include> statement for designtime rendering only
- String width = null;
- String height = null;
- if (primaryNode == null) {
- // Multiple selection - in that case we will be creating an outer <merge>
- // so we need to set our own width/height on it
- width = height = VALUE_WRAP_CONTENT;
- } else {
- if (!primaryNode.hasAttributeNS(ANDROID_URI, ATTR_LAYOUT_WIDTH)) {
- width = VALUE_WRAP_CONTENT;
- } else {
- width = primaryNode.getAttributeNS(ANDROID_URI, ATTR_LAYOUT_WIDTH);
- }
- if (!primaryNode.hasAttributeNS(ANDROID_URI, ATTR_LAYOUT_HEIGHT)) {
- height = VALUE_WRAP_CONTENT;
- } else {
- height = primaryNode.getAttributeNS(ANDROID_URI, ATTR_LAYOUT_HEIGHT);
- }
- }
- if (width != null) {
- sb.append(' ');
- sb.append(androidNsPrefix);
- sb.append(':');
- sb.append(ATTR_LAYOUT_WIDTH);
- sb.append('=').append('"');
- sb.append(XmlUtils.toXmlAttributeValue(width));
- sb.append('"');
- }
- if (height != null) {
- sb.append(' ');
- sb.append(androidNsPrefix);
- sb.append(':');
- sb.append(ATTR_LAYOUT_HEIGHT);
- sb.append('=').append('"');
- sb.append(XmlUtils.toXmlAttributeValue(height));
- sb.append('"');
- }
-
- // Duplicate all the other layout attributes as well
- if (primaryNode != null) {
- NamedNodeMap attributes = primaryNode.getAttributes();
- for (int i = 0, n = attributes.getLength(); i < n; i++) {
- Node attr = attributes.item(i);
- String name = attr.getLocalName();
- if (name.startsWith(ATTR_LAYOUT_RESOURCE_PREFIX)
- && ANDROID_URI.equals(attr.getNamespaceURI())) {
- if (name.equals(ATTR_LAYOUT_WIDTH) || name.equals(ATTR_LAYOUT_HEIGHT)) {
- // Already handled
- continue;
- }
-
- sb.append(' ');
- sb.append(androidNsPrefix);
- sb.append(':');
- sb.append(name);
- sb.append('=').append('"');
- sb.append(XmlUtils.toXmlAttributeValue(attr.getNodeValue()));
- sb.append('"');
- }
- }
- }
-
- sb.append("/>");
- return sb.toString();
- }
-
- /** Return the text in the document in the range start to end */
- private String getExtractedText() {
- String xml = getText(mSelectionStart, mSelectionEnd);
- Element primaryNode = getPrimaryElement();
- xml = stripTopLayoutAttributes(primaryNode, mSelectionStart, xml);
- xml = dedent(xml);
-
- // Wrap siblings in <merge>?
- if (primaryNode == null) {
- StringBuilder sb = new StringBuilder();
- sb.append("<merge>\n"); //$NON-NLS-1$
- // indent an extra level
- for (String line : xml.split("\n")) { //$NON-NLS-1$
- sb.append(" "); //$NON-NLS-1$
- sb.append(line).append('\n');
- }
- sb.append("</merge>\n"); //$NON-NLS-1$
- xml = sb.toString();
- }
-
- return xml;
- }
-
- @Override
- VisualRefactoringWizard createWizard() {
- return new ExtractIncludeWizard(this, mDelegate);
- }
-
- public static class Descriptor extends VisualRefactoringDescriptor {
- public Descriptor(String project, String description, String comment,
- Map<String, String> arguments) {
- super("com.android.ide.eclipse.adt.refactoring.extract.include", //$NON-NLS-1$
- project, description, comment, arguments);
- }
-
- @Override
- protected Refactoring createRefactoring(Map<String, String> args) {
- return new ExtractIncludeRefactoring(args);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractIncludeWizard.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractIncludeWizard.java
deleted file mode 100644
index f3ac3f1b3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractIncludeWizard.java
+++ /dev/null
@@ -1,126 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.resources.ResourceNameValidator;
-import com.android.resources.ResourceType;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-
-class ExtractIncludeWizard extends VisualRefactoringWizard {
- public ExtractIncludeWizard(ExtractIncludeRefactoring ref, LayoutEditorDelegate editor) {
- super(ref, editor);
- setDefaultPageTitle(ref.getName());
- }
-
- @Override
- protected void addUserInputPages() {
- ExtractIncludeRefactoring ref = (ExtractIncludeRefactoring) getRefactoring();
- String initialName = ref.getInitialName();
- IFile sourceFile = ref.getSourceFile();
- addPage(new InputPage(mDelegate.getEditor().getProject(), sourceFile, initialName));
- }
-
- /** Wizard page which inputs parameters for the {@link ExtractIncludeRefactoring} operation */
- private static class InputPage extends VisualRefactoringInputPage {
- private final IProject mProject;
- private final IFile mSourceFile;
- private final String mSuggestedName;
- private Text mNameText;
- private Button mReplaceAllOccurrences;
-
- public InputPage(IProject project, IFile sourceFile, String suggestedName) {
- super("ExtractIncludeInputPage");
- mProject = project;
- mSourceFile = sourceFile;
- mSuggestedName = suggestedName;
- }
-
- @Override
- public void createControl(Composite parent) {
- Composite composite = new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(2, false));
-
- Label nameLabel = new Label(composite, SWT.NONE);
- nameLabel.setText("New Layout Name:");
- nameLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
-
- mNameText = new Text(composite, SWT.BORDER);
- mNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- mNameText.addModifyListener(mModifyValidateListener);
-
- mReplaceAllOccurrences = new Button(composite, SWT.CHECK);
- mReplaceAllOccurrences.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER,
- false, false, 2, 1));
- mReplaceAllOccurrences.setText(
- "Replace occurrences in all layouts with include to new layout");
- mReplaceAllOccurrences.setEnabled(true);
- mReplaceAllOccurrences.setSelection(true);
- mReplaceAllOccurrences.addSelectionListener(mSelectionValidateListener);
-
- // Initialize UI:
- if (mSuggestedName != null) {
- mNameText.setText(mSuggestedName);
- }
-
- setControl(composite);
- validatePage();
- }
-
- @Override
- protected boolean validatePage() {
- boolean ok = true;
-
- String text = mNameText.getText().trim();
-
- if (text.length() == 0) {
- setErrorMessage("Provide a name for the new layout");
- ok = false;
- } else {
- ResourceNameValidator validator = ResourceNameValidator.create(false, mProject,
- ResourceType.LAYOUT);
- String message = validator.isValid(text);
- if (message != null) {
- setErrorMessage(message);
- ok = false;
- }
- }
-
- if (ok) {
- setErrorMessage(null);
-
- // Record state
- ExtractIncludeRefactoring refactoring =
- (ExtractIncludeRefactoring) getRefactoring();
- refactoring.setLayoutName(text);
- refactoring.setReplaceOccurrences(mReplaceAllOccurrences.getSelection());
- }
-
- setPageComplete(ok);
- return ok;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractStyleAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractStyleAction.java
deleted file mode 100644
index 4a498637d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractStyleAction.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
-
-/**
- * Action executed when the "Extract Style" menu item is invoked.
- */
-public class ExtractStyleAction extends VisualRefactoringAction {
- @Override
- public void run(IAction action) {
- if ((mTextSelection != null || mTreeSelection != null) && mFile != null) {
- ExtractStyleRefactoring ref = new ExtractStyleRefactoring(mFile, mDelegate,
- mTextSelection, mTreeSelection);
- RefactoringWizard wizard = new ExtractStyleWizard(ref, mDelegate);
- RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation(wizard);
- try {
- op.run(mWindow.getShell(), wizard.getDefaultPageTitle());
- } catch (InterruptedException e) {
- // Interrupted. Pass.
- }
- }
- }
-
- public static IAction create(LayoutEditorDelegate editorDelegate) {
- return create("Extract Style...", editorDelegate, ExtractStyleAction.class);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractStyleContribution.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractStyleContribution.java
deleted file mode 100644
index 95fbdbc43..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractStyleContribution.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import org.eclipse.ltk.core.refactoring.RefactoringContribution;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-
-import java.util.Map;
-
-public class ExtractStyleContribution extends RefactoringContribution {
-
- @SuppressWarnings("unchecked")
- @Override
- public RefactoringDescriptor createDescriptor(String id, String project, String description,
- String comment, Map arguments, int flags) throws IllegalArgumentException {
- return new ExtractStyleRefactoring.Descriptor(project, description, comment, arguments);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public Map retrieveArgumentMap(RefactoringDescriptor descriptor) {
- if (descriptor instanceof ExtractStyleRefactoring.Descriptor) {
- return ((ExtractStyleRefactoring.Descriptor) descriptor).getArguments();
- }
- return super.retrieveArgumentMap(descriptor);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractStyleRefactoring.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractStyleRefactoring.java
deleted file mode 100644
index 9b1770d82..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractStyleRefactoring.java
+++ /dev/null
@@ -1,579 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import static com.android.SdkConstants.ANDROID_NS_NAME;
-import static com.android.SdkConstants.ANDROID_NS_NAME_PREFIX;
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_HINT;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ATTR_LAYOUT_MARGIN;
-import static com.android.SdkConstants.ATTR_LAYOUT_RESOURCE_PREFIX;
-import static com.android.SdkConstants.ATTR_NAME;
-import static com.android.SdkConstants.ATTR_ON_CLICK;
-import static com.android.SdkConstants.ATTR_PARENT;
-import static com.android.SdkConstants.ATTR_SRC;
-import static com.android.SdkConstants.ATTR_STYLE;
-import static com.android.SdkConstants.ATTR_TEXT;
-import static com.android.SdkConstants.EXT_XML;
-import static com.android.SdkConstants.FD_RESOURCES;
-import static com.android.SdkConstants.FD_RES_VALUES;
-import static com.android.SdkConstants.PREFIX_ANDROID;
-import static com.android.SdkConstants.PREFIX_RESOURCE_REF;
-import static com.android.SdkConstants.REFERENCE_STYLE;
-import static com.android.SdkConstants.TAG_ITEM;
-import static com.android.SdkConstants.TAG_RESOURCES;
-import static com.android.SdkConstants.XMLNS_PREFIX;
-import static com.android.ide.eclipse.adt.AdtConstants.WS_SEP;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.VisibleForTesting;
-import com.android.ide.common.rendering.api.ResourceValue;
-import com.android.ide.common.resources.ResourceResolver;
-import com.android.ide.common.xml.XmlFormatStyle;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.wizards.newxmlfile.NewXmlFileWizard;
-import com.android.utils.Pair;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ITreeSelection;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.text.edits.InsertEdit;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.wst.sse.core.StructuredModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-
-/**
- * Extracts the selection and writes it out as a separate layout file, then adds an
- * include to that new layout file. Interactively asks the user for a new name for the
- * layout.
- * <p>
- * Remaining work to do / Possible enhancements:
- * <ul>
- * <li>Optionally look in other files in the project and attempt to set style attributes
- * in other cases where the style attributes match?
- * <li>If the elements we are extracting from already contain a style attribute, set that
- * style as the parent style of the current style?
- * <li>Add a parent-style picker to the wizard (initialized with the above if applicable)
- * <li>Pick up indentation settings from the XML module
- * <li>Integrate with themes somehow -- make an option to have the extracted style go into
- * the theme instead
- * </ul>
- */
-@SuppressWarnings("restriction") // XML model
-public class ExtractStyleRefactoring extends VisualRefactoring {
- private static final String KEY_NAME = "name"; //$NON-NLS-1$
- private static final String KEY_REMOVE_EXTRACTED = "removeextracted"; //$NON-NLS-1$
- private static final String KEY_REMOVE_ALL = "removeall"; //$NON-NLS-1$
- private static final String KEY_APPLY_STYLE = "applystyle"; //$NON-NLS-1$
- private static final String KEY_PARENT = "parent"; //$NON-NLS-1$
- private String mStyleName;
- /** The name of the file in res/values/ that the style will be added to. Normally
- * res/values/styles.xml - but unit tests pick other names */
- private String mStyleFileName = "styles.xml";
- /** Set a style reference on the extracted elements? */
- private boolean mApplyStyle;
- /** Remove the attributes that were extracted? */
- private boolean mRemoveExtracted;
- /** List of attributes chosen by the user to be extracted */
- private List<Attr> mChosenAttributes = new ArrayList<Attr>();
- /** Remove all attributes that match the extracted attributes names, regardless of value */
- private boolean mRemoveAll;
- /** The parent style to extend */
- private String mParent;
- /** The full list of available attributes in the refactoring */
- private Map<String, List<Attr>> mAvailableAttributes;
-
- /**
- * This constructor is solely used by {@link Descriptor},
- * to replay a previous refactoring.
- * @param arguments argument map created by #createArgumentMap.
- */
- ExtractStyleRefactoring(Map<String, String> arguments) {
- super(arguments);
- mStyleName = arguments.get(KEY_NAME);
- mRemoveExtracted = Boolean.parseBoolean(arguments.get(KEY_REMOVE_EXTRACTED));
- mRemoveAll = Boolean.parseBoolean(arguments.get(KEY_REMOVE_ALL));
- mApplyStyle = Boolean.parseBoolean(arguments.get(KEY_APPLY_STYLE));
- mParent = arguments.get(KEY_PARENT);
- if (mParent != null && mParent.length() == 0) {
- mParent = null;
- }
- }
-
- public ExtractStyleRefactoring(
- IFile file,
- LayoutEditorDelegate delegate,
- ITextSelection selection,
- ITreeSelection treeSelection) {
- super(file, delegate, selection, treeSelection);
- }
-
- @VisibleForTesting
- ExtractStyleRefactoring(List<Element> selectedElements, LayoutEditorDelegate editor) {
- super(selectedElements, editor);
- }
-
- @Override
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException,
- OperationCanceledException {
- RefactoringStatus status = new RefactoringStatus();
-
- try {
- pm.beginTask("Checking preconditions...", 6);
-
- if (mSelectionStart == -1 || mSelectionEnd == -1) {
- status.addFatalError("No selection to extract");
- return status;
- }
-
- // This also ensures that we have a valid DOM model:
- if (mElements.size() == 0) {
- status.addFatalError("Nothing to extract");
- return status;
- }
-
- pm.worked(1);
- return status;
-
- } finally {
- pm.done();
- }
- }
-
- @Override
- protected VisualRefactoringDescriptor createDescriptor() {
- String comment = getName();
- return new Descriptor(
- mProject.getName(), //project
- comment, //description
- comment, //comment
- createArgumentMap());
- }
-
- @Override
- protected Map<String, String> createArgumentMap() {
- Map<String, String> args = super.createArgumentMap();
- args.put(KEY_NAME, mStyleName);
- args.put(KEY_REMOVE_EXTRACTED, Boolean.toString(mRemoveExtracted));
- args.put(KEY_REMOVE_ALL, Boolean.toString(mRemoveAll));
- args.put(KEY_APPLY_STYLE, Boolean.toString(mApplyStyle));
- args.put(KEY_PARENT, mParent != null ? mParent : "");
-
- return args;
- }
-
- @Override
- public String getName() {
- return "Extract Style";
- }
-
- void setStyleName(String styleName) {
- mStyleName = styleName;
- }
-
- void setStyleFileName(String styleFileName) {
- mStyleFileName = styleFileName;
- }
-
- void setChosenAttributes(List<Attr> attributes) {
- mChosenAttributes = attributes;
- }
-
- void setRemoveExtracted(boolean removeExtracted) {
- mRemoveExtracted = removeExtracted;
- }
-
- void setApplyStyle(boolean applyStyle) {
- mApplyStyle = applyStyle;
- }
-
- void setRemoveAll(boolean removeAll) {
- mRemoveAll = removeAll;
- }
-
- void setParent(String parent) {
- mParent = parent;
- }
-
- // ---- Actual implementation of Extract Style modification computation ----
-
- /**
- * Returns two items: a map from attribute name to a list of attribute nodes of that
- * name, and a subset of these attributes that fall within the text selection
- * (used to drive initial selection in the wizard)
- */
- Pair<Map<String, List<Attr>>, Set<Attr>> getAvailableAttributes() {
- mAvailableAttributes = new TreeMap<String, List<Attr>>();
- Set<Attr> withinSelection = new HashSet<Attr>();
- for (Element element : getElements()) {
- IndexedRegion elementRegion = getRegion(element);
- boolean allIncluded =
- (mOriginalSelectionStart <= elementRegion.getStartOffset() &&
- mOriginalSelectionEnd >= elementRegion.getEndOffset());
-
- NamedNodeMap attributeMap = element.getAttributes();
- for (int i = 0, n = attributeMap.getLength(); i < n; i++) {
- Attr attribute = (Attr) attributeMap.item(i);
-
- String name = attribute.getLocalName();
- if (!isStylableAttribute(name)) {
- // Don't offer to extract attributes that don't make sense in
- // styles (like "id" or "style"), or attributes that the user
- // probably does not want to define in styles (like layout
- // attributes such as layout_width, or the label of a button etc).
- // This makes the options offered listed in the wizard simpler.
- // In special cases where the user *does* want to set one of these
- // attributes, they can always do it manually so optimize for
- // the common case here.
- continue;
- }
-
- // Skip attributes that are in a namespace other than the Android one
- String namespace = attribute.getNamespaceURI();
- if (namespace != null && !ANDROID_URI.equals(namespace)) {
- continue;
- }
-
- if (!allIncluded) {
- IndexedRegion region = getRegion(attribute);
- boolean attributeIncluded = mOriginalSelectionStart < region.getEndOffset() &&
- mOriginalSelectionEnd >= region.getStartOffset();
- if (attributeIncluded) {
- withinSelection.add(attribute);
- }
- } else {
- withinSelection.add(attribute);
- }
-
- List<Attr> list = mAvailableAttributes.get(name);
- if (list == null) {
- list = new ArrayList<Attr>();
- mAvailableAttributes.put(name, list);
- }
- list.add(attribute);
- }
- }
-
- return Pair.of(mAvailableAttributes, withinSelection);
- }
-
- /**
- * Returns whether the given local attribute name is one the style wizard
- * should present as a selectable attribute to be extracted.
- *
- * @param name the attribute name, not including a namespace prefix
- * @return true if the name is one that the user can extract
- */
- public static boolean isStylableAttribute(String name) {
- return !(name == null
- || name.equals(ATTR_ID)
- || name.startsWith(ATTR_STYLE)
- || (name.startsWith(ATTR_LAYOUT_RESOURCE_PREFIX) &&
- !name.startsWith(ATTR_LAYOUT_MARGIN))
- || name.equals(ATTR_TEXT)
- || name.equals(ATTR_HINT)
- || name.equals(ATTR_SRC)
- || name.equals(ATTR_ON_CLICK));
- }
-
- IFile getStyleFile(IProject project) {
- return project.getFile(new Path(FD_RESOURCES + WS_SEP + FD_RES_VALUES + WS_SEP
- + mStyleFileName));
- }
-
- @Override
- protected @NonNull List<Change> computeChanges(IProgressMonitor monitor) {
- List<Change> changes = new ArrayList<Change>();
- if (mChosenAttributes.size() == 0) {
- return changes;
- }
-
- IFile file = getStyleFile(mDelegate.getEditor().getProject());
- boolean createFile = !file.exists();
- int insertAtIndex;
- String initialIndent = null;
- if (!createFile) {
- Pair<Integer, String> context = computeInsertContext(file);
- insertAtIndex = context.getFirst();
- initialIndent = context.getSecond();
- } else {
- insertAtIndex = 0;
- }
-
- TextFileChange addFile = new TextFileChange("Create new separate style declaration", file);
- addFile.setTextType(EXT_XML);
- changes.add(addFile);
- String styleString = computeStyleDeclaration(createFile, initialIndent);
- addFile.setEdit(new InsertEdit(insertAtIndex, styleString));
-
- // Remove extracted attributes?
- MultiTextEdit rootEdit = new MultiTextEdit();
- if (mRemoveExtracted || mRemoveAll) {
- for (Attr attribute : mChosenAttributes) {
- List<Attr> list = mAvailableAttributes.get(attribute.getLocalName());
- for (Attr attr : list) {
- if (mRemoveAll || attr.getValue().equals(attribute.getValue())) {
- removeAttribute(rootEdit, attr);
- }
- }
- }
- }
-
- // Set the style attribute?
- if (mApplyStyle) {
- for (Element element : getElements()) {
- String value = PREFIX_RESOURCE_REF + REFERENCE_STYLE + mStyleName;
- setAttribute(rootEdit, element, null, null, ATTR_STYLE, value);
- }
- }
-
- if (rootEdit.hasChildren()) {
- IFile sourceFile = mDelegate.getEditor().getInputFile();
- if (sourceFile == null) {
- return changes;
- }
- TextFileChange change = new TextFileChange(sourceFile.getName(), sourceFile);
- change.setTextType(EXT_XML);
- changes.add(change);
-
- if (AdtPrefs.getPrefs().getFormatGuiXml()) {
- MultiTextEdit formatted = reformat(rootEdit, XmlFormatStyle.LAYOUT);
- if (formatted != null) {
- rootEdit = formatted;
- }
- }
-
- change.setEdit(rootEdit);
- }
-
- return changes;
- }
-
- private String computeStyleDeclaration(boolean createFile, String initialIndent) {
- StringBuilder sb = new StringBuilder();
- if (createFile) {
- sb.append(NewXmlFileWizard.XML_HEADER_LINE);
- sb.append('<').append(TAG_RESOURCES).append(' ');
- sb.append(XMLNS_PREFIX).append(ANDROID_NS_NAME).append('=').append('"');
- sb.append(ANDROID_URI);
- sb.append('"').append('>').append('\n');
- }
-
- // Indent. Use the existing indent found for previous <style> elements in
- // the resource file - but if that indent was 0 (e.g. <style> elements are
- // at the left margin) only use it to indent the style elements and use a real
- // nonzero indent for its children.
- String indent = " "; //$NON-NLS-1$
- if (initialIndent == null) {
- initialIndent = indent;
- } else if (initialIndent.length() > 0) {
- indent = initialIndent;
- }
- sb.append(initialIndent);
- String styleTag = "style"; //$NON-NLS-1$ // TODO - use constant in parallel changeset
- sb.append('<').append(styleTag).append(' ').append(ATTR_NAME).append('=').append('"');
- sb.append(mStyleName);
- sb.append('"');
- if (mParent != null) {
- sb.append(' ').append(ATTR_PARENT).append('=').append('"');
- sb.append(mParent);
- sb.append('"');
- }
- sb.append('>').append('\n');
-
- for (Attr attribute : mChosenAttributes) {
- sb.append(initialIndent).append(indent);
- sb.append('<').append(TAG_ITEM).append(' ').append(ATTR_NAME).append('=').append('"');
- // We've already enforced that regardless of prefix, only attributes with
- // an Android namespace can be in the set of chosen attributes. Rewrite the
- // prefix to android here.
- if (attribute.getPrefix() != null) {
- sb.append(ANDROID_NS_NAME_PREFIX);
- }
- sb.append(attribute.getLocalName());
- sb.append('"').append('>');
- sb.append(attribute.getValue());
- sb.append('<').append('/').append(TAG_ITEM).append('>').append('\n');
- }
- sb.append(initialIndent).append('<').append('/').append(styleTag).append('>').append('\n');
-
- if (createFile) {
- sb.append('<').append('/').append(TAG_RESOURCES).append('>').append('\n');
- }
- String styleString = sb.toString();
- return styleString;
- }
-
- /** Computes the location in the file to insert the new style element at, as well as
- * the exact indent string to use to indent the {@code <style>} element.
- * @param file the styles.xml file to insert into
- * @return a pair of an insert offset and an indent string
- */
- private Pair<Integer, String> computeInsertContext(final IFile file) {
- int insertAtIndex = -1;
- // Find the insert of the final </resources> item where we will insert
- // the new style elements.
- String indent = null;
- IModelManager modelManager = StructuredModelManager.getModelManager();
- IStructuredModel model = null;
- try {
- model = modelManager.getModelForRead(file);
- if (model instanceof IDOMModel) {
- IDOMModel domModel = (IDOMModel) model;
- IDOMDocument otherDocument = domModel.getDocument();
- Element root = otherDocument.getDocumentElement();
- Node lastChild = root.getLastChild();
- if (lastChild != null) {
- if (lastChild instanceof IndexedRegion) {
- IndexedRegion region = (IndexedRegion) lastChild;
- insertAtIndex = region.getStartOffset() + region.getLength();
- }
-
- // Compute indent
- while (lastChild != null) {
- if (lastChild.getNodeType() == Node.ELEMENT_NODE) {
- IStructuredDocument document = model.getStructuredDocument();
- indent = AndroidXmlEditor.getIndent(document, lastChild);
- break;
- }
- lastChild = lastChild.getPreviousSibling();
- }
- }
- }
- } catch (IOException e) {
- AdtPlugin.log(e, null);
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- } finally {
- if (model != null) {
- model.releaseFromRead();
- }
- }
-
- if (insertAtIndex == -1) {
- String contents = AdtPlugin.readFile(file);
- insertAtIndex = contents.indexOf("</" + TAG_RESOURCES + ">"); //$NON-NLS-1$
- if (insertAtIndex == -1) {
- insertAtIndex = contents.length();
- }
- }
-
- return Pair.of(insertAtIndex, indent);
- }
-
- @Override
- VisualRefactoringWizard createWizard() {
- return new ExtractStyleWizard(this, mDelegate);
- }
-
- public static class Descriptor extends VisualRefactoringDescriptor {
- public Descriptor(String project, String description, String comment,
- Map<String, String> arguments) {
- super("com.android.ide.eclipse.adt.refactoring.extract.style", //$NON-NLS-1$
- project, description, comment, arguments);
- }
-
- @Override
- protected Refactoring createRefactoring(Map<String, String> args) {
- return new ExtractStyleRefactoring(args);
- }
- }
-
- /**
- * Determines the parent style to be used for this refactoring
- *
- * @return the parent style to be used for this refactoring
- */
- public String getParentStyle() {
- Set<String> styles = new HashSet<String>();
- for (Element element : getElements()) {
- // Includes "" for elements not setting the style
- styles.add(element.getAttribute(ATTR_STYLE));
- }
-
- if (styles.size() > 1) {
- // The elements differ in what style attributes they are set to
- return null;
- }
-
- String style = styles.iterator().next();
- if (style != null && style.length() > 0) {
- return style;
- }
-
- // None of the elements set the style -- see if they have the same widget types
- // and if so offer to extend the theme style for that widget type
-
- Set<String> types = new HashSet<String>();
- for (Element element : getElements()) {
- types.add(element.getTagName());
- }
-
- if (types.size() == 1) {
- String view = DescriptorsUtils.getBasename(types.iterator().next());
-
- ResourceResolver resolver = mDelegate.getGraphicalEditor().getResourceResolver();
- // Look up the theme item name, which for a Button would be "buttonStyle", and so on.
- String n = Character.toLowerCase(view.charAt(0)) + view.substring(1)
- + "Style"; //$NON-NLS-1$
- ResourceValue value = resolver.findItemInTheme(n);
- if (value != null) {
- ResourceValue resolvedValue = resolver.resolveResValue(value);
- String name = resolvedValue.getName();
- if (name != null) {
- if (resolvedValue.isFramework()) {
- return PREFIX_ANDROID + name;
- } else {
- return name;
- }
- }
- }
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractStyleWizard.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractStyleWizard.java
deleted file mode 100644
index 187452d21..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractStyleWizard.java
+++ /dev/null
@@ -1,440 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import static org.eclipse.jface.viewers.StyledString.DECORATIONS_STYLER;
-import static org.eclipse.jface.viewers.StyledString.QUALIFIER_STYLER;
-
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.resources.ResourceNameValidator;
-import com.android.resources.ResourceType;
-import com.android.utils.Pair;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.viewers.CheckStateChangedEvent;
-import org.eclipse.jface.viewers.CheckboxTableViewer;
-import org.eclipse.jface.viewers.ICheckStateListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.StyledCellLabelProvider;
-import org.eclipse.jface.viewers.StyledString;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerCell;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.layout.RowLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.Text;
-import org.w3c.dom.Attr;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-class ExtractStyleWizard extends VisualRefactoringWizard {
- public ExtractStyleWizard(ExtractStyleRefactoring ref, LayoutEditorDelegate editor) {
- super(ref, editor);
- setDefaultPageTitle(ref.getName());
- }
-
- @Override
- protected void addUserInputPages() {
- String initialName = "styleName";
- addPage(new InputPage(mDelegate.getEditor().getProject(), initialName));
- }
-
- /**
- * Wizard page which inputs parameters for the {@link ExtractStyleRefactoring}
- * operation
- */
- private static class InputPage extends VisualRefactoringInputPage {
- private final IProject mProject;
- private final String mSuggestedName;
- private Text mNameText;
- private Table mTable;
- private Button mRemoveExtracted;
- private Button mSetStyle;
- private Button mRemoveAll;
- private Button mExtend;
- private CheckboxTableViewer mCheckedView;
-
- private String mParentStyle;
- private Set<Attr> mInSelection;
- private List<Attr> mAllAttributes;
- private int mElementCount;
- private Map<Attr, Integer> mFrequencyCount;
- private Set<Attr> mShown;
- private List<Attr> mInitialChecked;
- private List<Attr> mAllChecked;
- private List<Map.Entry<String, List<Attr>>> mRoot;
- private Map<String, List<Attr>> mAvailableAttributes;
-
- public InputPage(IProject project, String suggestedName) {
- super("ExtractStyleInputPage");
- mProject = project;
- mSuggestedName = suggestedName;
- }
-
- @Override
- public void createControl(Composite parent) {
- initialize();
-
- Composite composite = new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(2, false));
-
- Label nameLabel = new Label(composite, SWT.NONE);
- nameLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- nameLabel.setText("Style Name:");
-
- mNameText = new Text(composite, SWT.BORDER);
- mNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- mNameText.addModifyListener(mModifyValidateListener);
-
- mRemoveExtracted = new Button(composite, SWT.CHECK);
- mRemoveExtracted.setSelection(true);
- mRemoveExtracted.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 2, 1));
- mRemoveExtracted.setText("Remove extracted attributes");
- mRemoveExtracted.addSelectionListener(mSelectionValidateListener);
-
- mRemoveAll = new Button(composite, SWT.CHECK);
- mRemoveAll.setSelection(false);
- mRemoveAll.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 2, 1));
- mRemoveAll.setText("Remove all extracted attributes regardless of value");
- mRemoveAll.addSelectionListener(mSelectionValidateListener);
-
- boolean defaultSetStyle = false;
- if (mParentStyle != null) {
- mExtend = new Button(composite, SWT.CHECK);
- mExtend.setSelection(true);
- mExtend.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 2, 1));
- mExtend.setText(String.format("Extend %1$s", mParentStyle));
- mExtend.addSelectionListener(mSelectionValidateListener);
- defaultSetStyle = true;
- }
-
- mSetStyle = new Button(composite, SWT.CHECK);
- mSetStyle.setSelection(defaultSetStyle);
- mSetStyle.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 2, 1));
- mSetStyle.setText("Set style attribute on extracted elements");
- mSetStyle.addSelectionListener(mSelectionValidateListener);
-
- new Label(composite, SWT.NONE);
- new Label(composite, SWT.NONE);
-
- Label tableLabel = new Label(composite, SWT.NONE);
- tableLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
- tableLabel.setText("Choose style attributes to extract:");
-
- mCheckedView = CheckboxTableViewer.newCheckList(composite, SWT.BORDER
- | SWT.FULL_SELECTION | SWT.HIDE_SELECTION);
- mTable = mCheckedView.getTable();
- mTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 2));
- ((GridData) mTable.getLayoutData()).heightHint = 200;
-
- mCheckedView.setContentProvider(new ArgumentContentProvider());
- mCheckedView.setLabelProvider(new ArgumentLabelProvider());
- mCheckedView.setInput(mRoot);
- final Object[] initialSelection = mInitialChecked.toArray();
- mCheckedView.setCheckedElements(initialSelection);
-
- mCheckedView.addCheckStateListener(new ICheckStateListener() {
- @Override
- public void checkStateChanged(CheckStateChangedEvent event) {
- // Try to disable other elements that conflict with this
- boolean isChecked = event.getChecked();
- if (isChecked) {
- Attr attribute = (Attr) event.getElement();
- List<Attr> list = mAvailableAttributes.get(attribute.getLocalName());
- for (Attr other : list) {
- if (other != attribute && mShown.contains(other)) {
- mCheckedView.setChecked(other, false);
- }
- }
- }
-
- validatePage();
- }
- });
-
- // Select All / Deselect All
- Composite buttonForm = new Composite(composite, SWT.NONE);
- buttonForm.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
- RowLayout rowLayout = new RowLayout(SWT.HORIZONTAL);
- rowLayout.marginTop = 0;
- rowLayout.marginLeft = 0;
- buttonForm.setLayout(rowLayout);
- Button checkAllButton = new Button(buttonForm, SWT.FLAT);
- checkAllButton.setText("Select All");
- checkAllButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- // Select "all" (but not conflicting settings)
- mCheckedView.setCheckedElements(mAllChecked.toArray());
- validatePage();
- }
- });
- Button uncheckAllButton = new Button(buttonForm, SWT.FLAT);
- uncheckAllButton.setText("Deselect All");
- uncheckAllButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- mCheckedView.setAllChecked(false);
- validatePage();
- }
- });
-
- // Initialize UI:
- if (mSuggestedName != null) {
- mNameText.setText(mSuggestedName);
- }
-
- setControl(composite);
- validatePage();
- }
-
- private void initialize() {
- ExtractStyleRefactoring ref = (ExtractStyleRefactoring) getRefactoring();
-
- mElementCount = ref.getElements().size();
-
- mParentStyle = ref.getParentStyle();
-
- // Set up data structures needed by the wizard -- to compute the actual
- // attributes to list in the wizard (there could be multiple attributes
- // of the same name (on different elements) and we only want to show one, etc.)
-
- Pair<Map<String, List<Attr>>, Set<Attr>> result = ref.getAvailableAttributes();
- // List of all available attributes on the selected elements
- mAvailableAttributes = result.getFirst();
- // Set of attributes that overlap the text selection, or all attributes if
- // wizard is invoked from GUI context
- mInSelection = result.getSecond();
-
- // The root data structure, which we set as the table root. The content provider
- // will produce children from it. This is the entry set of a map from
- // attribute name to list of attribute nodes for that attribute name.
- mRoot = new ArrayList<Map.Entry<String, List<Attr>>>(
- mAvailableAttributes.entrySet());
-
- // Sort the items by attribute name -- the attribute name is the key
- // in the entry set above.
- Collections.sort(mRoot, new Comparator<Map.Entry<String, List<Attr>>>() {
- @Override
- public int compare(Map.Entry<String, List<Attr>> e1,
- Map.Entry<String, List<Attr>> e2) {
- return e1.getKey().compareTo(e2.getKey());
- }
- });
-
- // Set of attributes actually included in the list shown to the user.
- // (There could be many additional "aliasing" nodes on other elements
- // with the same name.) Note however that we DO show multiple attribute
- // occurrences of the same attribute name: precisely one for each unique -value-
- // of that attribute.
- mShown = new HashSet<Attr>();
-
- // The list of initially checked attributes.
- mInitialChecked = new ArrayList<Attr>();
-
- // The list of attributes to be checked if "Select All" is chosen (this is not
- // the same as *all* attributes, since we need to exclude any conflicts)
- mAllChecked = new ArrayList<Attr>();
-
- // All attributes.
- mAllAttributes = new ArrayList<Attr>();
-
- // Frequency count, from attribute to integer. Attributes that do not
- // appear in the list have frequency 1, not 0.
- mFrequencyCount = new HashMap<Attr, Integer>();
-
- for (Map.Entry<String, List<Attr>> entry : mRoot) {
- // Iterate over all attributes of the same name, and sort them
- // by value. This will make it easy to list each -unique- value in the
- // wizard.
- List<Attr> attrList = entry.getValue();
- Collections.sort(attrList, new Comparator<Attr>() {
- @Override
- public int compare(Attr a1, Attr a2) {
- return a1.getValue().compareTo(a2.getValue());
- }
- });
-
- // We need to compute a couple of things: the frequency for all identical
- // values (and stash them in the frequency map), and record the first
- // attribute with a particular value into the list of attributes to
- // be shown.
- Attr prevAttr = null;
- String prev = null;
- List<Attr> uniqueValueAttrs = new ArrayList<Attr>();
- for (Attr attr : attrList) {
- String value = attr.getValue();
- if (value.equals(prev)) {
- Integer count = mFrequencyCount.get(prevAttr);
- if (count == null) {
- count = Integer.valueOf(2);
- } else {
- count = Integer.valueOf(count.intValue() + 1);
- }
- mFrequencyCount.put(prevAttr, count);
- } else {
- uniqueValueAttrs.add(attr);
- prev = value;
- prevAttr = attr;
- }
- }
-
- // Sort the values by frequency (and for equal frequencies, alphabetically
- // by value)
- Collections.sort(uniqueValueAttrs, new Comparator<Attr>() {
- @Override
- public int compare(Attr a1, Attr a2) {
- Integer f1 = mFrequencyCount.get(a1);
- Integer f2 = mFrequencyCount.get(a2);
- if (f1 == null) {
- f1 = Integer.valueOf(1);
- }
- if (f2 == null) {
- f2 = Integer.valueOf(1);
- }
- int delta = f2.intValue() - f1.intValue();
- if (delta != 0) {
- return delta;
- } else {
- return a1.getValue().compareTo(a2.getValue());
- }
- }
- });
-
- // Add the items in order, and select those attributes that overlap
- // the selection
- mAllAttributes.addAll(uniqueValueAttrs);
- mShown.addAll(uniqueValueAttrs);
- Attr first = uniqueValueAttrs.get(0);
- mAllChecked.add(first);
- if (mInSelection.contains(first)) {
- mInitialChecked.add(first);
- }
- }
- }
-
- @Override
- protected boolean validatePage() {
- boolean ok = true;
-
- String text = mNameText.getText().trim();
-
- if (text.length() == 0) {
- setErrorMessage("Provide a name for the new style");
- ok = false;
- } else {
- ResourceNameValidator validator = ResourceNameValidator.create(false, mProject,
- ResourceType.STYLE);
- String message = validator.isValid(text);
- if (message != null) {
- setErrorMessage(message);
- ok = false;
- }
- }
-
- Object[] checkedElements = mCheckedView.getCheckedElements();
- if (checkedElements.length == 0) {
- setErrorMessage("Choose at least one attribute to extract");
- ok = false;
- }
-
- if (ok) {
- setErrorMessage(null);
-
- // Record state
- ExtractStyleRefactoring refactoring = (ExtractStyleRefactoring) getRefactoring();
- refactoring.setStyleName(text);
- refactoring.setRemoveExtracted(mRemoveExtracted.getSelection());
- refactoring.setRemoveAll(mRemoveAll.getSelection());
- refactoring.setApplyStyle(mSetStyle.getSelection());
- if (mExtend != null && mExtend.getSelection()) {
- refactoring.setParent(mParentStyle);
- }
- List<Attr> attributes = new ArrayList<Attr>();
- for (Object o : checkedElements) {
- attributes.add((Attr) o);
- }
- refactoring.setChosenAttributes(attributes);
- }
-
- setPageComplete(ok);
- return ok;
- }
-
- private class ArgumentLabelProvider extends StyledCellLabelProvider {
- public ArgumentLabelProvider() {
- }
-
- @Override
- public void update(ViewerCell cell) {
- Object element = cell.getElement();
- Attr attribute = (Attr) element;
-
- StyledString styledString = new StyledString();
- styledString.append(attribute.getLocalName());
- styledString.append(" = ", QUALIFIER_STYLER);
- styledString.append(attribute.getValue());
-
- if (mElementCount > 1) {
- Integer f = mFrequencyCount.get(attribute);
- String s = String.format(" (in %d/%d elements)",
- f != null ? f.intValue(): 1, mElementCount);
- styledString.append(s, DECORATIONS_STYLER);
- }
- cell.setText(styledString.toString());
- cell.setStyleRanges(styledString.getStyleRanges());
- super.update(cell);
- }
- }
-
- private class ArgumentContentProvider implements IStructuredContentProvider {
- public ArgumentContentProvider() {
- }
-
- @Override
- public Object[] getElements(Object inputElement) {
- if (inputElement == mRoot) {
- return mAllAttributes.toArray();
- }
-
- return new Object[0];
- }
-
- @Override
- public void dispose() {
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/GridLayoutConverter.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/GridLayoutConverter.java
deleted file mode 100644
index fe673a5b7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/GridLayoutConverter.java
+++ /dev/null
@@ -1,988 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_BACKGROUND;
-import static com.android.SdkConstants.ATTR_COLUMN_COUNT;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_BASELINE;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_BOTTOM;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_LEFT;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_RIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_TOP;
-import static com.android.SdkConstants.ATTR_LAYOUT_COLUMN;
-import static com.android.SdkConstants.ATTR_LAYOUT_COLUMN_SPAN;
-import static com.android.SdkConstants.ATTR_LAYOUT_GRAVITY;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_RESOURCE_PREFIX;
-import static com.android.SdkConstants.ATTR_LAYOUT_ROW;
-import static com.android.SdkConstants.ATTR_LAYOUT_ROW_SPAN;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.ATTR_ORIENTATION;
-import static com.android.SdkConstants.FQCN_GRID_LAYOUT;
-import static com.android.SdkConstants.FQCN_SPACE;
-import static com.android.SdkConstants.GRAVITY_VALUE_FILL;
-import static com.android.SdkConstants.GRAVITY_VALUE_FILL_HORIZONTAL;
-import static com.android.SdkConstants.GRAVITY_VALUE_FILL_VERTICAL;
-import static com.android.SdkConstants.ID_PREFIX;
-import static com.android.SdkConstants.LINEAR_LAYOUT;
-import static com.android.SdkConstants.NEW_ID_PREFIX;
-import static com.android.SdkConstants.RADIO_GROUP;
-import static com.android.SdkConstants.RELATIVE_LAYOUT;
-import static com.android.SdkConstants.SPACE;
-import static com.android.SdkConstants.TABLE_LAYOUT;
-import static com.android.SdkConstants.TABLE_ROW;
-import static com.android.SdkConstants.VALUE_FILL_PARENT;
-import static com.android.SdkConstants.VALUE_HORIZONTAL;
-import static com.android.SdkConstants.VALUE_MATCH_PARENT;
-import static com.android.SdkConstants.VALUE_VERTICAL;
-import static com.android.SdkConstants.VALUE_WRAP_CONTENT;
-import static com.android.ide.common.layout.GravityHelper.GRAVITY_HORIZ_MASK;
-import static com.android.ide.common.layout.GravityHelper.GRAVITY_VERT_MASK;
-
-import com.android.ide.common.api.IViewMetadata.FillPreference;
-import com.android.ide.common.layout.BaseLayoutRule;
-import com.android.ide.common.layout.GravityHelper;
-import com.android.ide.common.layout.GridLayoutRule;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.CanvasViewInfo;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.ViewMetadataRepository;
-import com.android.ide.eclipse.adt.internal.project.SupportLibraryHelper;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.text.edits.InsertEdit;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Helper class which performs the bulk of the layout conversion to grid layout
- * <p>
- * Future enhancements:
- * <ul>
- * <li>Render the layout at multiple screen sizes and analyze how the widget bounds
- * change and use this to infer gravity
- * <li> Use the layout_width and layout_height attributes on views to infer column and
- * row flexibility (and as mentioned above, possibly layout_weight).
- * move and stretch and use that to add in additional constraints
- * <li> Take into account existing margins and add/subtract those from the
- * bounds computations and either clear or update them.
- * <li>Try to reorder elements into their natural order
- * <li> Try to preserve spacing? Right now everything gets converted into a compact
- * grid with no spacing between the views; consider inserting {@code <Space>} views
- * with dimensions based on existing distances.
- * </ul>
- */
-@SuppressWarnings("restriction") // DOM model access
-class GridLayoutConverter {
- private final MultiTextEdit mRootEdit;
- private final boolean mFlatten;
- private final Element mLayout;
- private final ChangeLayoutRefactoring mRefactoring;
- private final CanvasViewInfo mRootView;
-
- private List<View> mViews;
- private String mNamespace;
- private int mColumnCount;
-
- /** Creates a new {@link GridLayoutConverter} */
- GridLayoutConverter(ChangeLayoutRefactoring refactoring,
- Element layout, boolean flatten, MultiTextEdit rootEdit, CanvasViewInfo rootView) {
- mRefactoring = refactoring;
- mLayout = layout;
- mFlatten = flatten;
- mRootEdit = rootEdit;
- mRootView = rootView;
- }
-
- /** Performs conversion from any layout to a RelativeLayout */
- public void convertToGridLayout() {
- if (mRootView == null) {
- return;
- }
-
- // Locate the view for the layout
- CanvasViewInfo layoutView = findViewForElement(mRootView, mLayout);
- if (layoutView == null || layoutView.getChildren().size() == 0) {
- // No children. THAT was an easy conversion!
- return;
- }
-
- // Study the layout and get information about how to place individual elements
- GridModel gridModel = new GridModel(layoutView, mLayout, mFlatten);
- mViews = gridModel.getViews();
- mColumnCount = gridModel.computeColumnCount();
-
- deleteRemovedElements(gridModel.getDeletedElements());
- mNamespace = mRefactoring.getAndroidNamespacePrefix();
-
- processGravities();
-
- // Insert space views if necessary
- insertStretchableSpans();
-
- // Create/update relative layout constraints
- assignGridAttributes();
-
- removeUndefinedAttrs();
-
- if (mColumnCount > 0) {
- mRefactoring.setAttribute(mRootEdit, mLayout, ANDROID_URI,
- mNamespace, ATTR_COLUMN_COUNT, Integer.toString(mColumnCount));
- }
- }
-
- private void insertStretchableSpans() {
- // Look at the rows and columns and determine if we need to have a stretchable
- // row and/or a stretchable column in the layout.
- // In a GridLayout, a row or column is stretchable if it defines a gravity (regardless
- // of what the gravity is -- in other words, a column is not just stretchable if it
- // has gravity=fill but also if it has gravity=left). Furthermore, ALL the elements
- // in the row/column have to be stretchable for the overall row/column to be
- // considered stretchable.
-
- // Map from row index to boolean for "is the row fixed/inflexible?"
- Map<Integer, Boolean> rowFixed = new HashMap<Integer, Boolean>();
- Map<Integer, Boolean> columnFixed = new HashMap<Integer, Boolean>();
- for (View view : mViews) {
- if (view.mElement == mLayout) {
- continue;
- }
-
- int gravity = GravityHelper.getGravity(view.mGravity, 0);
- if ((gravity & GRAVITY_HORIZ_MASK) == 0) {
- columnFixed.put(view.mCol, true);
- } else if (!columnFixed.containsKey(view.mCol)) {
- columnFixed.put(view.mCol, false);
- }
- if ((gravity & GRAVITY_VERT_MASK) == 0) {
- rowFixed.put(view.mRow, true);
- } else if (!rowFixed.containsKey(view.mRow)) {
- rowFixed.put(view.mRow, false);
- }
- }
-
- boolean hasStretchableRow = false;
- boolean hasStretchableColumn = false;
- for (boolean fixed : rowFixed.values()) {
- if (!fixed) {
- hasStretchableRow = true;
- }
- }
- for (boolean fixed : columnFixed.values()) {
- if (!fixed) {
- hasStretchableColumn = true;
- }
- }
-
- if (!hasStretchableRow || !hasStretchableColumn) {
- // Insert <Space> to hold stretchable space
- // TODO: May also have to increment column count!
- int offset = 0; // WHERE?
-
- String gridLayout = mLayout.getTagName();
- if (mLayout instanceof IndexedRegion) {
- IndexedRegion region = (IndexedRegion) mLayout;
- int end = region.getEndOffset();
- // TODO: Look backwards for the "</"
- // (and can it ever be <foo/>) ?
- end -= (gridLayout.length() + 3); // 3: <, /, >
- offset = end;
- }
-
- int row = rowFixed.size();
- int column = columnFixed.size();
- StringBuilder sb = new StringBuilder(64);
- String spaceTag = SPACE;
- IFile file = mRefactoring.getFile();
- if (file != null) {
- spaceTag = SupportLibraryHelper.getTagFor(file.getProject(), FQCN_SPACE);
- if (spaceTag.equals(FQCN_SPACE)) {
- spaceTag = SPACE;
- }
- }
-
- sb.append('<').append(spaceTag).append(' ');
- String gravity;
- if (!hasStretchableRow && !hasStretchableColumn) {
- gravity = GRAVITY_VALUE_FILL;
- } else if (!hasStretchableRow) {
- gravity = GRAVITY_VALUE_FILL_VERTICAL;
- } else {
- assert !hasStretchableColumn;
- gravity = GRAVITY_VALUE_FILL_HORIZONTAL;
- }
-
- sb.append(mNamespace).append(':');
- sb.append(ATTR_LAYOUT_GRAVITY).append('=').append('"').append(gravity);
- sb.append('"').append(' ');
-
- sb.append(mNamespace).append(':');
- sb.append(ATTR_LAYOUT_ROW).append('=').append('"').append(Integer.toString(row));
- sb.append('"').append(' ');
-
- sb.append(mNamespace).append(':');
- sb.append(ATTR_LAYOUT_COLUMN).append('=').append('"').append(Integer.toString(column));
- sb.append('"').append('/').append('>');
-
- String space = sb.toString();
- InsertEdit replace = new InsertEdit(offset, space);
- mRootEdit.addChild(replace);
-
- mColumnCount++;
- }
- }
-
- private void removeUndefinedAttrs() {
- ViewElementDescriptor descriptor = mRefactoring.getElementDescriptor(FQCN_GRID_LAYOUT);
- if (descriptor == null) {
- return;
- }
-
- Set<String> defined = new HashSet<String>();
- AttributeDescriptor[] layoutAttributes = descriptor.getLayoutAttributes();
- for (AttributeDescriptor attribute : layoutAttributes) {
- defined.add(attribute.getXmlLocalName());
- }
-
- for (View view : mViews) {
- Element child = view.mElement;
-
- List<Attr> attributes = mRefactoring.findLayoutAttributes(child);
- for (Attr attribute : attributes) {
- String name = attribute.getLocalName();
- if (!defined.contains(name)) {
- // Remove it
- try {
- mRefactoring.removeAttribute(mRootEdit, child, attribute.getNamespaceURI(),
- name);
- } catch (MalformedTreeException mte) {
- // Sometimes refactoring has modified attribute; not
- // removing
- // it is non-fatal so just warn instead of letting
- // refactoring
- // operation abort
- AdtPlugin.log(IStatus.WARNING,
- "Could not remove unsupported attribute %1$s; " + //$NON-NLS-1$
- "already modified during refactoring?", //$NON-NLS-1$
- attribute.getLocalName());
- }
- }
- }
- }
- }
-
- /** Removes any elements targeted for deletion */
- private void deleteRemovedElements(List<Element> delete) {
- if (mFlatten && delete.size() > 0) {
- for (Element element : delete) {
- mRefactoring.removeElementTags(mRootEdit, element, delete,
- false /*changeIndentation*/);
- }
- }
- }
-
- /**
- * Creates refactoring edits which adds or updates the grid attributes
- */
- private void assignGridAttributes() {
- // We always convert to horizontal grid layouts for now
- mRefactoring.setAttribute(mRootEdit, mLayout, ANDROID_URI,
- mNamespace, ATTR_ORIENTATION, VALUE_HORIZONTAL);
-
- assignCellAttributes();
- }
-
- /**
- * Assign cell attributes to the table, skipping those that will be implied
- * by the grid model
- */
- private void assignCellAttributes() {
- int implicitRow = 0;
- int implicitColumn = 0;
- int nextRow = 0;
- for (View view : mViews) {
- Element element = view.getElement();
- if (element == mLayout) {
- continue;
- }
-
- int row = view.getRow();
- int column = view.getColumn();
-
- if (column != implicitColumn && (implicitColumn > 0 || implicitRow > 0)) {
- mRefactoring.setAttribute(mRootEdit, element, ANDROID_URI,
- mNamespace, ATTR_LAYOUT_COLUMN, Integer.toString(column));
- if (column < implicitColumn) {
- implicitRow++;
- }
- implicitColumn = column;
- }
- if (row != implicitRow) {
- mRefactoring.setAttribute(mRootEdit, element, ANDROID_URI,
- mNamespace, ATTR_LAYOUT_ROW, Integer.toString(row));
- implicitRow = row;
- }
-
- int rowSpan = view.getRowSpan();
- int columnSpan = view.getColumnSpan();
- assert columnSpan >= 1;
-
- if (rowSpan > 1) {
- mRefactoring.setAttribute(mRootEdit, element, ANDROID_URI,
- mNamespace, ATTR_LAYOUT_ROW_SPAN, Integer.toString(rowSpan));
- }
- if (columnSpan > 1) {
- mRefactoring.setAttribute(mRootEdit, element, ANDROID_URI,
- mNamespace, ATTR_LAYOUT_COLUMN_SPAN,
- Integer.toString(columnSpan));
- }
- nextRow = Math.max(nextRow, row + rowSpan);
-
- // wrap_content is redundant in GridLayouts
- Attr width = element.getAttributeNodeNS(ANDROID_URI, ATTR_LAYOUT_WIDTH);
- if (width != null && VALUE_WRAP_CONTENT.equals(width.getValue())) {
- mRefactoring.removeAttribute(mRootEdit, width);
- }
- Attr height = element.getAttributeNodeNS(ANDROID_URI, ATTR_LAYOUT_HEIGHT);
- if (height != null && VALUE_WRAP_CONTENT.equals(height.getValue())) {
- mRefactoring.removeAttribute(mRootEdit, height);
- }
-
- // Fix up children moved from LinearLayouts that have "invalid" sizes that
- // was intended for layout weight handling in their old parent
- if (LINEAR_LAYOUT.equals(element.getParentNode().getNodeName())) {
- convert0dipToWrapContent(element);
- }
-
- implicitColumn += columnSpan;
- if (implicitColumn >= mColumnCount) {
- implicitColumn = 0;
- assert nextRow > implicitRow;
- implicitRow = nextRow;
- }
- }
- }
-
- private void processGravities() {
- for (View view : mViews) {
- Element element = view.getElement();
- if (element == mLayout) {
- continue;
- }
-
- Attr width = element.getAttributeNodeNS(ANDROID_URI, ATTR_LAYOUT_WIDTH);
- Attr height = element.getAttributeNodeNS(ANDROID_URI, ATTR_LAYOUT_HEIGHT);
- String gravity = element.getAttributeNS(ANDROID_URI, ATTR_LAYOUT_GRAVITY);
- String newGravity = null;
- if (width != null && (VALUE_MATCH_PARENT.equals(width.getValue()) ||
- VALUE_FILL_PARENT.equals(width.getValue()))) {
- mRefactoring.removeAttribute(mRootEdit, width);
- newGravity = gravity = GRAVITY_VALUE_FILL_HORIZONTAL;
- }
- if (height != null && (VALUE_MATCH_PARENT.equals(height.getValue()) ||
- VALUE_FILL_PARENT.equals(height.getValue()))) {
- mRefactoring.removeAttribute(mRootEdit, height);
- if (newGravity == GRAVITY_VALUE_FILL_HORIZONTAL) {
- newGravity = GRAVITY_VALUE_FILL;
- } else {
- newGravity = GRAVITY_VALUE_FILL_VERTICAL;
- }
- gravity = newGravity;
- }
-
- if (gravity == null || gravity.length() == 0) {
- ElementDescriptor descriptor = view.mInfo.getUiViewNode().getDescriptor();
- if (descriptor instanceof ViewElementDescriptor) {
- ViewElementDescriptor viewDescriptor = (ViewElementDescriptor) descriptor;
- String fqcn = viewDescriptor.getFullClassName();
- FillPreference fill = ViewMetadataRepository.get().getFillPreference(fqcn);
- gravity = GridLayoutRule.computeDefaultGravity(fill);
- if (gravity != null) {
- newGravity = gravity;
- }
- }
- }
-
- if (newGravity != null) {
- mRefactoring.setAttribute(mRootEdit, element, ANDROID_URI,
- mNamespace, ATTR_LAYOUT_GRAVITY, newGravity);
- }
-
- view.mGravity = newGravity != null ? newGravity : gravity;
- }
- }
-
-
- /** Converts 0dip values in layout_width and layout_height to wrap_content instead */
- private void convert0dipToWrapContent(Element child) {
- // Must convert layout_height="0dip" to layout_height="wrap_content".
- // (And since wrap_content is the default, what we really do is remove
- // the attribute completely.)
- // 0dip is a special trick used in linear layouts in the presence of
- // weights where 0dip ensures that the height of the view is not taken
- // into account when distributing the weights. However, when converted
- // to RelativeLayout this will instead cause the view to actually be assigned
- // 0 height.
- Attr height = child.getAttributeNodeNS(ANDROID_URI, ATTR_LAYOUT_HEIGHT);
- // 0dip, 0dp, 0px, etc
- if (height != null && height.getValue().startsWith("0")) { //$NON-NLS-1$
- mRefactoring.removeAttribute(mRootEdit, height);
- }
- Attr width = child.getAttributeNodeNS(ANDROID_URI, ATTR_LAYOUT_WIDTH);
- if (width != null && width.getValue().startsWith("0")) { //$NON-NLS-1$
- mRefactoring.removeAttribute(mRootEdit, width);
- }
- }
-
- /**
- * Searches a view hierarchy and locates the {@link CanvasViewInfo} for the given
- * {@link Element}
- *
- * @param info the root {@link CanvasViewInfo} to search below
- * @param element the target element
- * @return the {@link CanvasViewInfo} which corresponds to the given element
- */
- private CanvasViewInfo findViewForElement(CanvasViewInfo info, Element element) {
- if (getElement(info) == element) {
- return info;
- }
-
- for (CanvasViewInfo child : info.getChildren()) {
- CanvasViewInfo result = findViewForElement(child, element);
- if (result != null) {
- return result;
- }
- }
-
- return null;
- }
-
- /** Returns the {@link Element} for the given {@link CanvasViewInfo} */
- private static Element getElement(CanvasViewInfo info) {
- Node node = info.getUiViewNode().getXmlNode();
- if (node instanceof Element) {
- return (Element) node;
- }
-
- return null;
- }
-
-
- /** Holds layout information about an individual view */
- private static class View {
- private final Element mElement;
- private int mRow = -1;
- private int mCol = -1;
- private int mRowSpan = -1;
- private int mColSpan = -1;
- private int mX1;
- private int mY1;
- private int mX2;
- private int mY2;
- private CanvasViewInfo mInfo;
- private String mGravity;
-
- public View(CanvasViewInfo view, Element element) {
- mInfo = view;
- mElement = element;
-
- Rectangle b = mInfo.getAbsRect();
- mX1 = b.x;
- mX2 = b.x + b.width;
- mY1 = b.y;
- mY2 = b.y + b.height;
- }
-
- /**
- * Returns the element for this view
- *
- * @return the element for the view
- */
- public Element getElement() {
- return mElement;
- }
-
- /**
- * The assigned row for this view
- *
- * @return the assigned row
- */
- public int getRow() {
- return mRow;
- }
-
- /**
- * The assigned column for this view
- *
- * @return the assigned column
- */
- public int getColumn() {
- return mCol;
- }
-
- /**
- * The assigned row span for this view
- *
- * @return the assigned row span
- */
- public int getRowSpan() {
- return mRowSpan;
- }
-
- /**
- * The assigned column span for this view
- *
- * @return the assigned column span
- */
- public int getColumnSpan() {
- return mColSpan;
- }
-
- /**
- * The left edge of the view to be used for placement
- *
- * @return the left edge x coordinate
- */
- public int getLeftEdge() {
- return mX1;
- }
-
- /**
- * The top edge of the view to be used for placement
- *
- * @return the top edge y coordinate
- */
- public int getTopEdge() {
- return mY1;
- }
-
- /**
- * The right edge of the view to be used for placement
- *
- * @return the right edge x coordinate
- */
- public int getRightEdge() {
- return mX2;
- }
-
- /**
- * The bottom edge of the view to be used for placement
- *
- * @return the bottom edge y coordinate
- */
- public int getBottomEdge() {
- return mY2;
- }
-
- @Override
- public String toString() {
- return "View(" + VisualRefactoring.getId(mElement) + ": " + mX1 + "," + mY1 + ")";
- }
- }
-
- /** Grid model for the views found in the view hierarchy, partitioned into rows and columns */
- private static class GridModel {
- private final List<View> mViews = new ArrayList<View>();
- private final List<Element> mDelete = new ArrayList<Element>();
- private final Map<Element, View> mElementToView = new HashMap<Element, View>();
- private Element mLayout;
- private boolean mFlatten;
-
- GridModel(CanvasViewInfo view, Element layout, boolean flatten) {
- mLayout = layout;
- mFlatten = flatten;
-
- scan(view, true);
- analyzeKnownLayouts();
- initializeColumns();
- initializeRows();
- mDelete.remove(getElement(view));
- }
-
- /**
- * Returns the {@link View} objects to be placed in the grid
- *
- * @return list of {@link View} objects, never null but possibly empty
- */
- public List<View> getViews() {
- return mViews;
- }
-
- /**
- * Returns the list of elements that are scheduled for deletion in the
- * flattening operation
- *
- * @return elements to be deleted, never null but possibly empty
- */
- public List<Element> getDeletedElements() {
- return mDelete;
- }
-
- /**
- * Compute and return column count
- *
- * @return the column count
- */
- public int computeColumnCount() {
- int columnCount = 0;
- for (View view : mViews) {
- if (view.getElement() == mLayout) {
- continue;
- }
-
- int column = view.getColumn();
- int columnSpan = view.getColumnSpan();
- if (column + columnSpan > columnCount) {
- columnCount = column + columnSpan;
- }
- }
- return columnCount;
- }
-
- /**
- * Initializes the column and columnSpan attributes of the views
- */
- private void initializeColumns() {
- // Now initialize table view row, column and spans
- Map<Integer, List<View>> mColumnViews = new HashMap<Integer, List<View>>();
- for (View view : mViews) {
- if (view.mElement == mLayout) {
- continue;
- }
- int x = view.getLeftEdge();
- List<View> list = mColumnViews.get(x);
- if (list == null) {
- list = new ArrayList<View>();
- mColumnViews.put(x, list);
- }
- list.add(view);
- }
-
- List<Integer> columnOffsets = new ArrayList<Integer>(mColumnViews.keySet());
- Collections.sort(columnOffsets);
-
- int columnIndex = 0;
- for (Integer column : columnOffsets) {
- List<View> views = mColumnViews.get(column);
- if (views != null) {
- for (View view : views) {
- view.mCol = columnIndex;
- }
- }
- columnIndex++;
- }
- // Initialize column spans
- for (View view : mViews) {
- if (view.mElement == mLayout) {
- continue;
- }
- int index = Collections.binarySearch(columnOffsets, view.getRightEdge());
- int column;
- if (index == -1) {
- // Smaller than the first element; just use the first column
- column = 0;
- } else if (index < 0) {
- column = -(index + 2);
- } else {
- column = index;
- }
-
- if (column < view.mCol) {
- column = view.mCol;
- }
-
- view.mColSpan = column - view.mCol + 1;
- }
- }
-
- /**
- * Initializes the row and rowSpan attributes of the views
- */
- private void initializeRows() {
- Map<Integer, List<View>> mRowViews = new HashMap<Integer, List<View>>();
- for (View view : mViews) {
- if (view.mElement == mLayout) {
- continue;
- }
- int y = view.getTopEdge();
- List<View> list = mRowViews.get(y);
- if (list == null) {
- list = new ArrayList<View>();
- mRowViews.put(y, list);
- }
- list.add(view);
- }
-
- List<Integer> rowOffsets = new ArrayList<Integer>(mRowViews.keySet());
- Collections.sort(rowOffsets);
-
- int rowIndex = 0;
- for (Integer row : rowOffsets) {
- List<View> views = mRowViews.get(row);
- if (views != null) {
- for (View view : views) {
- view.mRow = rowIndex;
- }
- }
- rowIndex++;
- }
-
- // Initialize row spans
- for (View view : mViews) {
- if (view.mElement == mLayout) {
- continue;
- }
- int index = Collections.binarySearch(rowOffsets, view.getBottomEdge());
- int row;
- if (index == -1) {
- // Smaller than the first element; just use the first row
- row = 0;
- } else if (index < 0) {
- row = -(index + 2);
- } else {
- row = index;
- }
-
- if (row < view.mRow) {
- row = view.mRow;
- }
-
- view.mRowSpan = row - view.mRow + 1;
- }
- }
-
- /**
- * Walks over a given view hierarchy and locates views to be placed in
- * the grid layout (or deleted if we are flattening the hierarchy)
- *
- * @param view the view to analyze
- * @param isRoot whether this view is the root (which cannot be removed)
- * @return the {@link View} object for the {@link CanvasViewInfo}
- * hierarchy we just analyzed, or null
- */
- private View scan(CanvasViewInfo view, boolean isRoot) {
- View added = null;
- if (!mFlatten || !isRemovableLayout(view)) {
- added = add(view);
- if (!isRoot) {
- return added;
- }
- } else {
- mDelete.add(getElement(view));
- }
-
- // Build up a table model of the view
- for (CanvasViewInfo child : view.getChildren()) {
- Element childElement = getElement(child);
-
- // See if this view shares the edge with the removed
- // parent layout, and if so, record that such that we can
- // later handle attachments to the removed parent edges
-
- if (mFlatten && isRemovableLayout(child)) {
- // When flattening, we want to disregard all layouts and instead
- // add their children!
- for (CanvasViewInfo childView : child.getChildren()) {
- scan(childView, false);
- }
- mDelete.add(childElement);
- } else {
- scan(child, false);
- }
- }
-
- return added;
- }
-
- /** Adds the given {@link CanvasViewInfo} into our internal view list */
- private View add(CanvasViewInfo info) {
- Element element = getElement(info);
- View view = new View(info, element);
- mViews.add(view);
- mElementToView.put(element, view);
- return view;
- }
-
- private void analyzeKnownLayouts() {
- Set<Element> parents = new HashSet<Element>();
- for (View view : mViews) {
- Node parent = view.getElement().getParentNode();
- if (parent instanceof Element) {
- parents.add((Element) parent);
- }
- }
-
- List<Collection<View>> rowGroups = new ArrayList<Collection<View>>();
- List<Collection<View>> columnGroups = new ArrayList<Collection<View>>();
- for (Element parent : parents) {
- String tagName = parent.getTagName();
- if (tagName.equals(LINEAR_LAYOUT) || tagName.equals(TABLE_LAYOUT) ||
- tagName.equals(TABLE_ROW) || tagName.equals(RADIO_GROUP)) {
- Set<View> group = new HashSet<View>();
- for (Element child : DomUtilities.getChildren(parent)) {
- View view = mElementToView.get(child);
- if (view != null) {
- group.add(view);
- }
- }
- if (group.size() > 1) {
- boolean isVertical = VALUE_VERTICAL.equals(parent.getAttributeNS(
- ANDROID_URI, ATTR_ORIENTATION));
- if (tagName.equals(TABLE_LAYOUT)) {
- isVertical = true;
- } else if (tagName.equals(TABLE_ROW)) {
- isVertical = false;
- }
- if (isVertical) {
- columnGroups.add(group);
- } else {
- rowGroups.add(group);
- }
- }
- } else if (tagName.equals(RELATIVE_LAYOUT)) {
- List<Element> children = DomUtilities.getChildren(parent);
- for (Element child : children) {
- View view = mElementToView.get(child);
- if (view == null) {
- continue;
- }
- NamedNodeMap attributes = child.getAttributes();
- for (int i = 0, n = attributes.getLength(); i < n; i++) {
- Attr attr = (Attr) attributes.item(i);
- String name = attr.getLocalName();
- if (name.startsWith(ATTR_LAYOUT_RESOURCE_PREFIX)) {
- boolean alignVertical =
- name.equals(ATTR_LAYOUT_ALIGN_TOP) ||
- name.equals(ATTR_LAYOUT_ALIGN_BOTTOM) ||
- name.equals(ATTR_LAYOUT_ALIGN_BASELINE);
- boolean alignHorizontal =
- name.equals(ATTR_LAYOUT_ALIGN_LEFT) ||
- name.equals(ATTR_LAYOUT_ALIGN_RIGHT);
- if (!alignVertical && !alignHorizontal) {
- continue;
- }
- String value = attr.getValue();
- if (value.startsWith(ID_PREFIX)
- || value.startsWith(NEW_ID_PREFIX)) {
- String targetName = BaseLayoutRule.stripIdPrefix(value);
- Element target = null;
- for (Element c : children) {
- String id = VisualRefactoring.getId(c);
- if (targetName.equals(BaseLayoutRule.stripIdPrefix(id))) {
- target = c;
- break;
- }
- }
- View targetView = mElementToView.get(target);
- if (targetView != null) {
- List<View> group = new ArrayList<View>(2);
- group.add(view);
- group.add(targetView);
- if (alignHorizontal) {
- columnGroups.add(group);
- } else {
- assert alignVertical;
- rowGroups.add(group);
- }
- }
- }
- }
- }
- }
- } else {
- // TODO: Consider looking for interesting metadata from other layouts
- }
- }
-
- // Assign the same top or left coordinates to the groups to ensure that they
- // all get positioned in the same row or column
- for (Collection<View> rowGroup : rowGroups) {
- // Find the smallest one
- Iterator<View> iterator = rowGroup.iterator();
- int smallest = iterator.next().mY1;
- while (iterator.hasNext()) {
- smallest = Math.min(smallest, iterator.next().mY1);
- }
- for (View view : rowGroup) {
- view.mY2 -= (view.mY1 - smallest);
- view.mY1 = smallest;
- }
- }
- for (Collection<View> columnGroup : columnGroups) {
- Iterator<View> iterator = columnGroup.iterator();
- int smallest = iterator.next().mX1;
- while (iterator.hasNext()) {
- smallest = Math.min(smallest, iterator.next().mX1);
- }
- for (View view : columnGroup) {
- view.mX2 -= (view.mX1 - smallest);
- view.mX1 = smallest;
- }
- }
- }
-
- /**
- * Returns true if the given {@link CanvasViewInfo} represents an element we
- * should remove in a flattening conversion. We don't want to remove non-layout
- * views, or layout views that for example contain drawables on their own.
- */
- private boolean isRemovableLayout(CanvasViewInfo child) {
- // The element being converted is NOT removable!
- Element element = getElement(child);
- if (element == mLayout) {
- return false;
- }
-
- ElementDescriptor descriptor = child.getUiViewNode().getDescriptor();
- String name = descriptor.getXmlLocalName();
- if (name.equals(LINEAR_LAYOUT) || name.equals(RELATIVE_LAYOUT)
- || name.equals(TABLE_LAYOUT) || name.equals(TABLE_ROW)) {
- // Don't delete layouts that provide a background image or gradient
- if (element.hasAttributeNS(ANDROID_URI, ATTR_BACKGROUND)) {
- AdtPlugin.log(IStatus.WARNING,
- "Did not flatten layout %1$s because it defines a '%2$s' attribute",
- VisualRefactoring.getId(element), ATTR_BACKGROUND);
- return false;
- }
-
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/JavaQuickAssistant.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/JavaQuickAssistant.java
deleted file mode 100644
index df5d9eaf3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/JavaQuickAssistant.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.refactorings.extractstring.ExtractStringProposal;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jdt.core.dom.ASTNode;
-import org.eclipse.jdt.ui.text.java.IInvocationContext;
-import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.jdt.ui.text.java.IProblemLocation;
-
-/**
- * Quick Assistant for Java files in Android projects
- */
-public class JavaQuickAssistant implements org.eclipse.jdt.ui.text.java.IQuickAssistProcessor {
- public JavaQuickAssistant() {
- }
-
- @Override
- public boolean hasAssists(IInvocationContext context) throws CoreException {
- return true;
- }
-
- @Override
- public IJavaCompletionProposal[] getAssists(IInvocationContext context,
- IProblemLocation[] locations) throws CoreException {
- // We should only offer Android quick assists within Android projects.
- // This can be done by adding this logic to the extension registration:
- //
- // <enablement>
- // <with variable="projectNatures">
- // <iterate operator="or">
- // <equals value="com.android.ide.eclipse.adt.AndroidNature"/>
- // </iterate>
- // </with>
- // </enablement>
- //
- // However, this causes some errors to be dumped to the log, so instead we filter
- // out non Android projects programmatically:
-
- IProject project = context.getCompilationUnit().getJavaProject().getProject();
- if (project == null || !BaseProjectHelper.isAndroidProject(project)) {
- return null;
- }
-
- ASTNode coveringNode = context.getCoveringNode();
- if (coveringNode != null && coveringNode.getNodeType() == ASTNode.STRING_LITERAL
- && coveringNode.getLength() > 2) { // don't extract empty strings (includes quotes)
- return new IJavaCompletionProposal[] {
- new ExtractStringProposal(context)
- };
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/RefactoringAssistant.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/RefactoringAssistant.java
deleted file mode 100644
index aa8c11999..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/RefactoringAssistant.java
+++ /dev/null
@@ -1,336 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import com.android.ide.common.resources.ResourceUrl;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-import com.android.ide.eclipse.adt.internal.refactorings.core.RenameResourceProcessor;
-import com.android.ide.eclipse.adt.internal.refactorings.core.RenameResourceWizard;
-import com.android.ide.eclipse.adt.internal.refactorings.core.RenameResourceXmlTextAction;
-import com.android.ide.eclipse.adt.internal.refactorings.extractstring.ExtractStringRefactoring;
-import com.android.ide.eclipse.adt.internal.refactorings.extractstring.ExtractStringWizard;
-import com.android.resources.ResourceType;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.TextSelection;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext;
-import org.eclipse.jface.text.quickassist.IQuickAssistProcessor;
-import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion;
-import org.eclipse.wst.sse.ui.StructuredTextEditor;
-import org.eclipse.wst.xml.core.internal.regions.DOMRegionContext;
-import org.w3c.dom.Node;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * QuickAssistProcessor which helps invoke refactoring operations on text elements.
- */
-@SuppressWarnings("restriction") // XML model
-public class RefactoringAssistant implements IQuickAssistProcessor {
-
- /**
- * Creates a new {@link RefactoringAssistant}
- */
- public RefactoringAssistant() {
- }
-
- @Override
- public boolean canAssist(IQuickAssistInvocationContext invocationContext) {
- return true;
- }
-
- @Override
- public boolean canFix(Annotation annotation) {
- return true;
- }
-
- @Override
- public ICompletionProposal[] computeQuickAssistProposals(
- IQuickAssistInvocationContext invocationContext) {
-
- ISourceViewer sourceViewer = invocationContext.getSourceViewer();
- AndroidXmlEditor xmlEditor = AndroidXmlEditor.fromTextViewer(sourceViewer);
- if (xmlEditor == null) {
- return null;
- }
-
- IFile file = xmlEditor.getInputFile();
- if (file == null) {
- return null;
- }
- int offset = invocationContext.getOffset();
-
- // Ensure that we are over a tag name (for element-based refactoring
- // operations) or a value (for the extract include refactoring)
-
- boolean isValue = false;
- boolean isReferenceValue = false;
- boolean isTagName = false;
- boolean isAttributeName = false;
- boolean isStylableAttribute = false;
- ResourceUrl resource = null;
- IStructuredModel model = null;
- try {
- model = xmlEditor.getModelForRead();
- IStructuredDocument doc = model.getStructuredDocument();
- IStructuredDocumentRegion region = doc.getRegionAtCharacterOffset(offset);
- ITextRegion subRegion = region.getRegionAtCharacterOffset(offset);
- if (subRegion != null) {
- String type = subRegion.getType();
- if (type.equals(DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE)) {
- String value = region.getText(subRegion);
- // Only extract values that aren't already resources
- // (and value includes leading ' or ")
- isValue = true;
- if (value.startsWith("'@") || value.startsWith("\"@")) { //$NON-NLS-1$ //$NON-NLS-2$
- isReferenceValue = true;
- resource = RenameResourceXmlTextAction.findResource(doc, offset);
- }
- } else if (type.equals(DOMRegionContext.XML_TAG_NAME)
- || type.equals(DOMRegionContext.XML_TAG_OPEN)
- || type.equals(DOMRegionContext.XML_TAG_CLOSE)) {
- isTagName = true;
- } else if (type.equals(DOMRegionContext.XML_TAG_ATTRIBUTE_NAME) ) {
- isAttributeName = true;
- String name = region.getText(subRegion);
- int index = name.indexOf(':');
- if (index != -1) {
- name = name.substring(index + 1);
- }
- isStylableAttribute = ExtractStyleRefactoring.isStylableAttribute(name);
- } else if (type.equals(DOMRegionContext.XML_TAG_ATTRIBUTE_EQUALS)) {
- // On the edge of an attribute name and an attribute value
- isAttributeName = true;
- isStylableAttribute = true;
- } else if (type.equals(DOMRegionContext.XML_CONTENT)) {
- resource = RenameResourceXmlTextAction.findResource(doc, offset);
- }
- }
- } finally {
- if (model != null) {
- model.releaseFromRead();
- }
- }
-
- List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
- if (isTagName || isAttributeName || isValue || resource != null) {
- StructuredTextEditor structuredEditor = xmlEditor.getStructuredTextEditor();
- ISelectionProvider provider = structuredEditor.getSelectionProvider();
- ISelection selection = provider.getSelection();
- if (selection instanceof ITextSelection) {
- ITextSelection textSelection = (ITextSelection) selection;
-
- ITextSelection originalSelection = textSelection;
-
- // Most of the visual refactorings do not work on text ranges
- // ...except for Extract Style where the actual attributes overlapping
- // the selection is going to be the set of eligible attributes
- boolean selectionOkay = false;
-
- if (textSelection.getLength() == 0 && !isValue) {
- selectionOkay = true;
- ISourceViewer textViewer = xmlEditor.getStructuredSourceViewer();
- int caretOffset = textViewer.getTextWidget().getCaretOffset();
- if (caretOffset >= 0) {
- Node node = DomUtilities.getNode(textViewer.getDocument(), caretOffset);
- if (node instanceof IndexedRegion) {
- IndexedRegion region = (IndexedRegion) node;
- int startOffset = region.getStartOffset();
- int length = region.getEndOffset() - region.getStartOffset();
- textSelection = new TextSelection(startOffset, length);
- }
- }
- }
-
- if (isValue && !isReferenceValue) {
- proposals.add(new RefactoringProposal(xmlEditor,
- new ExtractStringRefactoring(file, xmlEditor, textSelection)));
- } else if (resource != null) {
- RenameResourceProcessor processor = new RenameResourceProcessor(
- file.getProject(), resource.type, resource.name, null);
- RenameRefactoring refactoring = new RenameRefactoring(processor);
- proposals.add(new RefactoringProposal(xmlEditor, refactoring));
- }
-
- LayoutEditorDelegate delegate = LayoutEditorDelegate.fromEditor(xmlEditor);
- if (delegate != null) {
- boolean showStyleFirst = isValue || (isAttributeName && isStylableAttribute);
- if (showStyleFirst) {
- proposals.add(new RefactoringProposal(
- xmlEditor,
- new ExtractStyleRefactoring(
- file,
- delegate,
- originalSelection,
- null)));
- }
-
- if (selectionOkay) {
- proposals.add(new RefactoringProposal(
- xmlEditor,
- new WrapInRefactoring(
- file,
- delegate,
- textSelection,
- null)));
- proposals.add(new RefactoringProposal(
- xmlEditor,
- new UnwrapRefactoring(
- file,
- delegate,
- textSelection,
- null)));
- proposals.add(new RefactoringProposal(
- xmlEditor,
- new ChangeViewRefactoring(
- file,
- delegate,
- textSelection,
- null)));
- proposals.add(new RefactoringProposal(
- xmlEditor,
- new ChangeLayoutRefactoring(
- file,
- delegate,
- textSelection,
- null)));
- }
-
- // Extract Include must always have an actual block to be extracted
- if (textSelection.getLength() > 0) {
- proposals.add(new RefactoringProposal(
- xmlEditor,
- new ExtractIncludeRefactoring(
- file,
- delegate,
- textSelection,
- null)));
- }
-
- // If it's not a value or attribute name, don't place it on top
- if (!showStyleFirst) {
- proposals.add(new RefactoringProposal(
- xmlEditor,
- new ExtractStyleRefactoring(
- file,
- delegate,
- originalSelection,
- null)));
- }
- }
- }
- }
-
- if (proposals.size() == 0) {
- return null;
- } else {
- return proposals.toArray(new ICompletionProposal[proposals.size()]);
- }
- }
-
- @Override
- public String getErrorMessage() {
- return null;
- }
-
- private static class RefactoringProposal
- implements ICompletionProposal {
- private final AndroidXmlEditor mEditor;
- private final Refactoring mRefactoring;
-
- RefactoringProposal(AndroidXmlEditor editor, Refactoring refactoring) {
- super();
- mEditor = editor;
- mRefactoring = refactoring;
- }
-
- @Override
- public void apply(IDocument document) {
- RefactoringWizard wizard = null;
- if (mRefactoring instanceof VisualRefactoring) {
- wizard = ((VisualRefactoring) mRefactoring).createWizard();
- } else if (mRefactoring instanceof ExtractStringRefactoring) {
- wizard = new ExtractStringWizard((ExtractStringRefactoring) mRefactoring,
- mEditor.getProject());
- } else if (mRefactoring instanceof RenameRefactoring) {
- RenameRefactoring refactoring = (RenameRefactoring) mRefactoring;
- RenameResourceProcessor processor =
- (RenameResourceProcessor) refactoring.getProcessor();
- ResourceType type = processor.getType();
- wizard = new RenameResourceWizard((RenameRefactoring) mRefactoring, type, false);
- } else {
- throw new IllegalArgumentException();
- }
-
- RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation(wizard);
- try {
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- op.run(window.getShell(), wizard.getDefaultPageTitle());
- } catch (InterruptedException e) {
- }
- }
-
- @Override
- public String getAdditionalProposalInfo() {
- return String.format("Initiates the \"%1$s\" refactoring", mRefactoring.getName());
- }
-
- @Override
- public IContextInformation getContextInformation() {
- return null;
- }
-
- @Override
- public String getDisplayString() {
- return mRefactoring.getName();
- }
-
- @Override
- public Image getImage() {
- return AdtPlugin.getAndroidLogo();
- }
-
- @Override
- public Point getSelection(IDocument document) {
- return null;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/RelativeLayoutConversionHelper.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/RelativeLayoutConversionHelper.java
deleted file mode 100644
index e0d6313bf..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/RelativeLayoutConversionHelper.java
+++ /dev/null
@@ -1,1633 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_BACKGROUND;
-import static com.android.SdkConstants.ATTR_BASELINE_ALIGNED;
-import static com.android.SdkConstants.ATTR_LAYOUT_ABOVE;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_BASELINE;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_BOTTOM;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_LEFT;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_PARENT_BOTTOM;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_PARENT_LEFT;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_PARENT_RIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_PARENT_TOP;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_RIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_TOP;
-import static com.android.SdkConstants.ATTR_LAYOUT_ALIGN_WITH_PARENT_MISSING;
-import static com.android.SdkConstants.ATTR_LAYOUT_BELOW;
-import static com.android.SdkConstants.ATTR_LAYOUT_CENTER_HORIZONTAL;
-import static com.android.SdkConstants.ATTR_LAYOUT_CENTER_VERTICAL;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_MARGIN_LEFT;
-import static com.android.SdkConstants.ATTR_LAYOUT_MARGIN_TOP;
-import static com.android.SdkConstants.ATTR_LAYOUT_RESOURCE_PREFIX;
-import static com.android.SdkConstants.ATTR_LAYOUT_TO_LEFT_OF;
-import static com.android.SdkConstants.ATTR_LAYOUT_TO_RIGHT_OF;
-import static com.android.SdkConstants.ATTR_LAYOUT_WEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.ATTR_ORIENTATION;
-import static com.android.SdkConstants.ID_PREFIX;
-import static com.android.SdkConstants.LINEAR_LAYOUT;
-import static com.android.SdkConstants.NEW_ID_PREFIX;
-import static com.android.SdkConstants.RELATIVE_LAYOUT;
-import static com.android.SdkConstants.VALUE_FALSE;
-import static com.android.SdkConstants.VALUE_N_DP;
-import static com.android.SdkConstants.VALUE_TRUE;
-import static com.android.SdkConstants.VALUE_VERTICAL;
-import static com.android.SdkConstants.VALUE_WRAP_CONTENT;
-import static com.android.ide.common.layout.GravityHelper.GRAVITY_BOTTOM;
-import static com.android.ide.common.layout.GravityHelper.GRAVITY_CENTER_HORIZ;
-import static com.android.ide.common.layout.GravityHelper.GRAVITY_CENTER_VERT;
-import static com.android.ide.common.layout.GravityHelper.GRAVITY_FILL_HORIZ;
-import static com.android.ide.common.layout.GravityHelper.GRAVITY_FILL_VERT;
-import static com.android.ide.common.layout.GravityHelper.GRAVITY_LEFT;
-import static com.android.ide.common.layout.GravityHelper.GRAVITY_RIGHT;
-import static com.android.ide.common.layout.GravityHelper.GRAVITY_TOP;
-import static com.android.ide.common.layout.GravityHelper.GRAVITY_VERT_MASK;
-
-import com.android.ide.common.layout.GravityHelper;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.CanvasViewInfo;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.utils.Pair;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Helper class which performs the bulk of the layout conversion to relative layout
- * <p>
- * Future enhancements:
- * <ul>
- * <li>Render the layout at multiple screen sizes and analyze how the widgets move and
- * stretch and use that to add in additional constraints
- * <li> Adapt the LinearLayout analysis code to work with TableLayouts and TableRows as well
- * (just need to tweak the "isVertical" interpretation to account for the different defaults,
- * and perhaps do something about column size properties.
- * <li> We need to take into account existing margins and clear/update them
- * </ul>
- */
-class RelativeLayoutConversionHelper {
- private final MultiTextEdit mRootEdit;
- private final boolean mFlatten;
- private final Element mLayout;
- private final ChangeLayoutRefactoring mRefactoring;
- private final CanvasViewInfo mRootView;
- private List<Element> mDeletedElements;
-
- RelativeLayoutConversionHelper(ChangeLayoutRefactoring refactoring,
- Element layout, boolean flatten, MultiTextEdit rootEdit, CanvasViewInfo rootView) {
- mRefactoring = refactoring;
- mLayout = layout;
- mFlatten = flatten;
- mRootEdit = rootEdit;
- mRootView = rootView;
- }
-
- /** Performs conversion from any layout to a RelativeLayout */
- public void convertToRelative() {
- if (mRootView == null) {
- return;
- }
-
- // Locate the view for the layout
- CanvasViewInfo layoutView = findViewForElement(mRootView, mLayout);
- if (layoutView == null || layoutView.getChildren().size() == 0) {
- // No children. THAT was an easy conversion!
- return;
- }
-
- // Study the layout and get information about how to place individual elements
- List<View> views = analyzeLayout(layoutView);
-
- // Create/update relative layout constraints
- createAttachments(views);
- }
-
- /** Returns the elements that were deleted, or null */
- List<Element> getDeletedElements() {
- return mDeletedElements;
- }
-
- /**
- * Analyzes the given view hierarchy and produces a list of {@link View} objects which
- * contain placement information for each element
- */
- private List<View> analyzeLayout(CanvasViewInfo layoutView) {
- EdgeList edgeList = new EdgeList(layoutView);
- mDeletedElements = edgeList.getDeletedElements();
- deleteRemovedElements(mDeletedElements);
-
- List<Integer> columnOffsets = edgeList.getColumnOffsets();
- List<Integer> rowOffsets = edgeList.getRowOffsets();
-
- // Compute x/y offsets for each row/column index
- int[] left = new int[columnOffsets.size()];
- int[] top = new int[rowOffsets.size()];
-
- Map<Integer, Integer> xToCol = new HashMap<Integer, Integer>();
- int columnIndex = 0;
- for (Integer offset : columnOffsets) {
- left[columnIndex] = offset;
- xToCol.put(offset, columnIndex++);
- }
- Map<Integer, Integer> yToRow = new HashMap<Integer, Integer>();
- int rowIndex = 0;
- for (Integer offset : rowOffsets) {
- top[rowIndex] = offset;
- yToRow.put(offset, rowIndex++);
- }
-
- // Create a complete list of view objects
- List<View> views = createViews(edgeList, columnOffsets);
- initializeSpans(edgeList, columnOffsets, rowOffsets, xToCol, yToRow);
-
- // Sanity check
- for (View view : views) {
- assert view.getLeftEdge() == left[view.mCol];
- assert view.getTopEdge() == top[view.mRow];
- assert view.getRightEdge() == left[view.mCol+view.mColSpan];
- assert view.getBottomEdge() == top[view.mRow+view.mRowSpan];
- }
-
- // Ensure that every view has a proper id such that it can be referred to
- // with a constraint
- initializeIds(edgeList, views);
-
- // Attempt to lay the views out in a grid with constraints (though not that widgets
- // can overlap as well)
- Grid grid = new Grid(views, left, top);
- computeKnownConstraints(views, edgeList);
- computeHorizontalConstraints(grid);
- computeVerticalConstraints(grid);
-
- return views;
- }
-
- /** Produces a list of {@link View} objects from an {@link EdgeList} */
- private List<View> createViews(EdgeList edgeList, List<Integer> columnOffsets) {
- List<View> views = new ArrayList<View>();
- for (Integer offset : columnOffsets) {
- List<View> leftEdgeViews = edgeList.getLeftEdgeViews(offset);
- if (leftEdgeViews == null) {
- // must have been a right edge
- continue;
- }
- for (View view : leftEdgeViews) {
- views.add(view);
- }
- }
- return views;
- }
-
- /** Removes any elements targeted for deletion */
- private void deleteRemovedElements(List<Element> delete) {
- if (mFlatten && delete.size() > 0) {
- for (Element element : delete) {
- mRefactoring.removeElementTags(mRootEdit, element, delete,
- !AdtPrefs.getPrefs().getFormatGuiXml() /*changeIndentation*/);
- }
- }
- }
-
- /** Ensures that every element has an id such that it can be referenced from a constraint */
- private void initializeIds(EdgeList edgeList, List<View> views) {
- // Ensure that all views have a valid id
- for (View view : views) {
- String id = mRefactoring.ensureHasId(mRootEdit, view.mElement, null);
- edgeList.setIdAttributeValue(view, id);
- }
- }
-
- /**
- * Initializes the column and row indices, as well as any column span and row span
- * values
- */
- private void initializeSpans(EdgeList edgeList, List<Integer> columnOffsets,
- List<Integer> rowOffsets, Map<Integer, Integer> xToCol, Map<Integer, Integer> yToRow) {
- // Now initialize table view row, column and spans
- for (Integer offset : columnOffsets) {
- List<View> leftEdgeViews = edgeList.getLeftEdgeViews(offset);
- if (leftEdgeViews == null) {
- // must have been a right edge
- continue;
- }
- for (View view : leftEdgeViews) {
- Integer col = xToCol.get(view.getLeftEdge());
- assert col != null;
- Integer end = xToCol.get(view.getRightEdge());
- assert end != null;
-
- view.mCol = col;
- view.mColSpan = end - col;
- }
- }
-
- for (Integer offset : rowOffsets) {
- List<View> topEdgeViews = edgeList.getTopEdgeViews(offset);
- if (topEdgeViews == null) {
- // must have been a bottom edge
- continue;
- }
- for (View view : topEdgeViews) {
- Integer row = yToRow.get(view.getTopEdge());
- assert row != null;
- Integer end = yToRow.get(view.getBottomEdge());
- assert end != null;
-
- view.mRow = row;
- view.mRowSpan = end - row;
- }
- }
- }
-
- /**
- * Creates refactoring edits which adds or updates constraints for the given list of
- * views
- */
- private void createAttachments(List<View> views) {
- // Make the attachments
- String namespace = mRefactoring.getAndroidNamespacePrefix();
- for (View view : views) {
- for (Pair<String, String> constraint : view.getHorizConstraints()) {
- mRefactoring.setAttribute(mRootEdit, view.mElement, ANDROID_URI,
- namespace, constraint.getFirst(), constraint.getSecond());
- }
- for (Pair<String, String> constraint : view.getVerticalConstraints()) {
- mRefactoring.setAttribute(mRootEdit, view.mElement, ANDROID_URI,
- namespace, constraint.getFirst(), constraint.getSecond());
- }
- }
- }
-
- /**
- * Analyzes the existing layouts and layout parameter objects in the document to infer
- * constraints for layout types that we know about - such as LinearLayout baseline
- * alignment, weights, gravity, etc.
- */
- private void computeKnownConstraints(List<View> views, EdgeList edgeList) {
- // List of parent layout elements we've already processed. We iterate through all
- // the -children-, and we ask each for its element parent (which won't have a view)
- // and we look at the parent's layout attributes and its children layout constraints,
- // and then we stash away constraints that we can infer. This means that we will
- // encounter the same parent for every sibling, so that's why there's a map to
- // prevent duplicate work.
- Set<Node> seen = new HashSet<Node>();
-
- for (View view : views) {
- Element element = view.getElement();
- Node parent = element.getParentNode();
- if (seen.contains(parent)) {
- continue;
- }
- seen.add(parent);
-
- if (parent.getNodeType() != Node.ELEMENT_NODE) {
- continue;
- }
- Element layout = (Element) parent;
- String layoutName = layout.getTagName();
-
- if (LINEAR_LAYOUT.equals(layoutName)) {
- analyzeLinearLayout(edgeList, layout);
- } else if (RELATIVE_LAYOUT.equals(layoutName)) {
- analyzeRelativeLayout(edgeList, layout);
- } else {
- // Some other layout -- add more conditional handling here
- // for framelayout, tables, etc.
- }
- }
- }
-
- /**
- * Returns the layout weight of of the given child of a LinearLayout, or 0.0 if it
- * does not define a weight
- */
- private float getWeight(Element linearLayoutChild) {
- String weight = linearLayoutChild.getAttributeNS(ANDROID_URI, ATTR_LAYOUT_WEIGHT);
- if (weight != null && weight.length() > 0) {
- try {
- return Float.parseFloat(weight);
- } catch (NumberFormatException nfe) {
- AdtPlugin.log(nfe, "Invalid weight %1$s", weight);
- }
- }
-
- return 0.0f;
- }
-
- /**
- * Returns the sum of all the layout weights of the children in the given LinearLayout
- *
- * @param linearLayout the layout to compute the total sum for
- * @return the total sum of all the layout weights in the given layout
- */
- private float getWeightSum(Element linearLayout) {
- float sum = 0;
- for (Element child : DomUtilities.getChildren(linearLayout)) {
- sum += getWeight(child);
- }
-
- return sum;
- }
-
- /**
- * Analyzes the given LinearLayout and updates the constraints to reflect
- * relationships it can infer - based on baseline alignment, gravity, order and
- * weights. This method also removes "0dip" as a special width/height used in
- * LinearLayouts with weight distribution.
- */
- private void analyzeLinearLayout(EdgeList edgeList, Element layout) {
- boolean isVertical = VALUE_VERTICAL.equals(layout.getAttributeNS(ANDROID_URI,
- ATTR_ORIENTATION));
- View baselineRef = null;
- if (!isVertical &&
- !VALUE_FALSE.equals(layout.getAttributeNS(ANDROID_URI, ATTR_BASELINE_ALIGNED))) {
- // Baseline alignment. Find the tallest child and set it as the baseline reference.
- int tallestHeight = 0;
- View tallest = null;
- for (Element child : DomUtilities.getChildren(layout)) {
- View view = edgeList.getView(child);
- if (view != null && view.getHeight() > tallestHeight) {
- tallestHeight = view.getHeight();
- tallest = view;
- }
- }
- if (tallest != null) {
- baselineRef = tallest;
- }
- }
-
- float weightSum = getWeightSum(layout);
- float cumulativeWeight = 0;
-
- List<Element> children = DomUtilities.getChildren(layout);
- String prevId = null;
- boolean isFirstChild = true;
- boolean linkBackwards = true;
- boolean linkForwards = false;
-
- for (int index = 0, childCount = children.size(); index < childCount; index++) {
- Element child = children.get(index);
-
- View childView = edgeList.getView(child);
- if (childView == null) {
- // Could be a nested layout that is being removed etc
- prevId = null;
- isFirstChild = false;
- continue;
- }
-
- // Look at the layout_weight attributes and determine whether we should be
- // attached on the bottom/right or on the top/left
- if (weightSum > 0.0f) {
- float weight = getWeight(child);
-
- // We can't emulate a LinearLayout where multiple children have positive
- // weights. However, we CAN support the common scenario where a single
- // child has a non-zero weight, and all children after it are pushed
- // to the end and the weighted child fills the remaining space.
- if (cumulativeWeight == 0 && weight > 0) {
- // See if we have a bottom/right edge to attach the forwards link to
- // (at the end of the forwards chains). Only if so can we link forwards.
- View referenced;
- if (isVertical) {
- referenced = edgeList.getSharedBottomEdge(layout);
- } else {
- referenced = edgeList.getSharedRightEdge(layout);
- }
- if (referenced != null) {
- linkForwards = true;
- }
- } else if (cumulativeWeight > 0) {
- linkBackwards = false;
- }
-
- cumulativeWeight += weight;
- }
-
- analyzeGravity(edgeList, layout, isVertical, child, childView);
- convert0dipToWrapContent(child);
-
- // Chain elements together in the flow direction of the linear layout
- if (prevId != null) { // No constraint for first child
- if (linkBackwards) {
- if (isVertical) {
- childView.addVerticalConstraint(ATTR_LAYOUT_BELOW, prevId);
- } else {
- childView.addHorizConstraint(ATTR_LAYOUT_TO_RIGHT_OF, prevId);
- }
- }
- } else if (isFirstChild) {
- assert linkBackwards;
-
- // First element; attach it to the parent if we can
- if (isVertical) {
- View referenced = edgeList.getSharedTopEdge(layout);
- if (referenced != null) {
- if (isAncestor(referenced.getElement(), child)) {
- childView.addVerticalConstraint(ATTR_LAYOUT_ALIGN_PARENT_TOP,
- VALUE_TRUE);
- } else {
- childView.addVerticalConstraint(ATTR_LAYOUT_ALIGN_TOP,
- referenced.getId());
- }
- }
- } else {
- View referenced = edgeList.getSharedLeftEdge(layout);
- if (referenced != null) {
- if (isAncestor(referenced.getElement(), child)) {
- childView.addHorizConstraint(ATTR_LAYOUT_ALIGN_PARENT_LEFT,
- VALUE_TRUE);
- } else {
- childView.addHorizConstraint(
- ATTR_LAYOUT_ALIGN_LEFT, referenced.getId());
- }
- }
- }
- }
-
- if (linkForwards) {
- if (index < (childCount - 1)) {
- Element nextChild = children.get(index + 1);
- String nextId = mRefactoring.ensureHasId(mRootEdit, nextChild, null);
- if (nextId != null) {
- if (isVertical) {
- childView.addVerticalConstraint(ATTR_LAYOUT_ABOVE, nextId);
- } else {
- childView.addHorizConstraint(ATTR_LAYOUT_TO_LEFT_OF, nextId);
- }
- }
- } else {
- // Attach to right/bottom edge of the layout
- if (isVertical) {
- View referenced = edgeList.getSharedBottomEdge(layout);
- if (referenced != null) {
- if (isAncestor(referenced.getElement(), child)) {
- childView.addVerticalConstraint(ATTR_LAYOUT_ALIGN_PARENT_BOTTOM,
- VALUE_TRUE);
- } else {
- childView.addVerticalConstraint(ATTR_LAYOUT_ALIGN_BOTTOM,
- referenced.getId());
- }
- }
- } else {
- View referenced = edgeList.getSharedRightEdge(layout);
- if (referenced != null) {
- if (isAncestor(referenced.getElement(), child)) {
- childView.addHorizConstraint(ATTR_LAYOUT_ALIGN_PARENT_RIGHT,
- VALUE_TRUE);
- } else {
- childView.addHorizConstraint(
- ATTR_LAYOUT_ALIGN_RIGHT, referenced.getId());
- }
- }
- }
- }
- }
-
- if (baselineRef != null && baselineRef.getId() != null
- && !baselineRef.getId().equals(childView.getId())) {
- assert !isVertical;
- // Only align if they share the same gravity
- if ((childView.getGravity() & GRAVITY_VERT_MASK) ==
- (baselineRef.getGravity() & GRAVITY_VERT_MASK)) {
- childView.addHorizConstraint(ATTR_LAYOUT_ALIGN_BASELINE, baselineRef.getId());
- }
- }
-
- prevId = mRefactoring.ensureHasId(mRootEdit, child, null);
- isFirstChild = false;
- }
- }
-
- /**
- * Checks the layout "gravity" value for the given child and updates the constraints
- * to account for the gravity
- */
- private int analyzeGravity(EdgeList edgeList, Element layout, boolean isVertical,
- Element child, View childView) {
- // Use gravity to constrain elements in the axis orthogonal to the
- // direction of the layout
- int gravity = childView.getGravity();
- if (isVertical) {
- if ((gravity & GRAVITY_RIGHT) != 0) {
- View referenced = edgeList.getSharedRightEdge(layout);
- if (referenced != null) {
- if (isAncestor(referenced.getElement(), child)) {
- childView.addHorizConstraint(ATTR_LAYOUT_ALIGN_PARENT_RIGHT,
- VALUE_TRUE);
- } else {
- childView.addHorizConstraint(ATTR_LAYOUT_ALIGN_RIGHT,
- referenced.getId());
- }
- }
- } else if ((gravity & GRAVITY_CENTER_HORIZ) != 0) {
- View referenced1 = edgeList.getSharedLeftEdge(layout);
- View referenced2 = edgeList.getSharedRightEdge(layout);
- if (referenced1 != null && referenced2 == referenced1) {
- if (isAncestor(referenced1.getElement(), child)) {
- childView.addHorizConstraint(ATTR_LAYOUT_CENTER_HORIZONTAL,
- VALUE_TRUE);
- }
- }
- } else if ((gravity & GRAVITY_FILL_HORIZ) != 0) {
- View referenced1 = edgeList.getSharedLeftEdge(layout);
- View referenced2 = edgeList.getSharedRightEdge(layout);
- if (referenced1 != null && referenced2 == referenced1) {
- if (isAncestor(referenced1.getElement(), child)) {
- childView.addHorizConstraint(ATTR_LAYOUT_ALIGN_PARENT_LEFT,
- VALUE_TRUE);
- childView.addHorizConstraint(ATTR_LAYOUT_ALIGN_PARENT_RIGHT,
- VALUE_TRUE);
- } else {
- childView.addHorizConstraint(ATTR_LAYOUT_ALIGN_LEFT,
- referenced1.getId());
- childView.addHorizConstraint(ATTR_LAYOUT_ALIGN_RIGHT,
- referenced2.getId());
- }
- }
- } else if ((gravity & GRAVITY_LEFT) != 0) {
- View referenced = edgeList.getSharedLeftEdge(layout);
- if (referenced != null) {
- if (isAncestor(referenced.getElement(), child)) {
- childView.addHorizConstraint(ATTR_LAYOUT_ALIGN_PARENT_LEFT,
- VALUE_TRUE);
- } else {
- childView.addHorizConstraint(ATTR_LAYOUT_ALIGN_LEFT,
- referenced.getId());
- }
- }
- }
- } else {
- // Handle horizontal layout: perform vertical gravity attachments
- if ((gravity & GRAVITY_BOTTOM) != 0) {
- View referenced = edgeList.getSharedBottomEdge(layout);
- if (referenced != null) {
- if (isAncestor(referenced.getElement(), child)) {
- childView.addVerticalConstraint(ATTR_LAYOUT_ALIGN_PARENT_BOTTOM,
- VALUE_TRUE);
- } else {
- childView.addVerticalConstraint(ATTR_LAYOUT_ALIGN_BOTTOM,
- referenced.getId());
- }
- }
- } else if ((gravity & GRAVITY_CENTER_VERT) != 0) {
- View referenced1 = edgeList.getSharedTopEdge(layout);
- View referenced2 = edgeList.getSharedBottomEdge(layout);
- if (referenced1 != null && referenced2 == referenced1) {
- if (isAncestor(referenced1.getElement(), child)) {
- childView.addVerticalConstraint(ATTR_LAYOUT_CENTER_VERTICAL,
- VALUE_TRUE);
- }
- }
- } else if ((gravity & GRAVITY_FILL_VERT) != 0) {
- View referenced1 = edgeList.getSharedTopEdge(layout);
- View referenced2 = edgeList.getSharedBottomEdge(layout);
- if (referenced1 != null && referenced2 == referenced1) {
- if (isAncestor(referenced1.getElement(), child)) {
- childView.addVerticalConstraint(ATTR_LAYOUT_ALIGN_PARENT_TOP,
- VALUE_TRUE);
- childView.addVerticalConstraint(ATTR_LAYOUT_ALIGN_PARENT_BOTTOM,
- VALUE_TRUE);
- } else {
- childView.addVerticalConstraint(ATTR_LAYOUT_ALIGN_TOP,
- referenced1.getId());
- childView.addVerticalConstraint(ATTR_LAYOUT_ALIGN_BOTTOM,
- referenced2.getId());
- }
- }
- } else if ((gravity & GRAVITY_TOP) != 0) {
- View referenced = edgeList.getSharedTopEdge(layout);
- if (referenced != null) {
- if (isAncestor(referenced.getElement(), child)) {
- childView.addVerticalConstraint(ATTR_LAYOUT_ALIGN_PARENT_TOP,
- VALUE_TRUE);
- } else {
- childView.addVerticalConstraint(ATTR_LAYOUT_ALIGN_TOP,
- referenced.getId());
- }
- }
- }
- }
- return gravity;
- }
-
- /** Converts 0dip values in layout_width and layout_height to wrap_content instead */
- private void convert0dipToWrapContent(Element child) {
- // Must convert layout_height="0dip" to layout_height="wrap_content".
- // 0dip is a special trick used in linear layouts in the presence of
- // weights where 0dip ensures that the height of the view is not taken
- // into account when distributing the weights. However, when converted
- // to RelativeLayout this will instead cause the view to actually be assigned
- // 0 height.
- String height = child.getAttributeNS(ANDROID_URI, ATTR_LAYOUT_HEIGHT);
- // 0dip, 0dp, 0px, etc
- if (height != null && height.startsWith("0")) { //$NON-NLS-1$
- mRefactoring.setAttribute(mRootEdit, child, ANDROID_URI,
- mRefactoring.getAndroidNamespacePrefix(), ATTR_LAYOUT_HEIGHT,
- VALUE_WRAP_CONTENT);
- }
- String width = child.getAttributeNS(ANDROID_URI, ATTR_LAYOUT_WIDTH);
- if (width != null && width.startsWith("0")) { //$NON-NLS-1$
- mRefactoring.setAttribute(mRootEdit, child, ANDROID_URI,
- mRefactoring.getAndroidNamespacePrefix(), ATTR_LAYOUT_WIDTH,
- VALUE_WRAP_CONTENT);
- }
- }
-
- /**
- * Analyzes an embedded RelativeLayout within a layout hierarchy and updates the
- * constraints in the EdgeList with those relationships which can continue in the
- * outer single RelativeLayout.
- */
- private void analyzeRelativeLayout(EdgeList edgeList, Element layout) {
- NodeList children = layout.getChildNodes();
- for (int i = 0, n = children.getLength(); i < n; i++) {
- Node node = children.item(i);
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- Element child = (Element) node;
- View childView = edgeList.getView(child);
- if (childView == null) {
- // Could be a nested layout that is being removed etc
- continue;
- }
-
- NamedNodeMap attributes = child.getAttributes();
- for (int j = 0, m = attributes.getLength(); j < m; j++) {
- Attr attribute = (Attr) attributes.item(j);
- String name = attribute.getLocalName();
- String value = attribute.getValue();
- if (name.equals(ATTR_LAYOUT_WIDTH)
- || name.equals(ATTR_LAYOUT_HEIGHT)) {
- // Ignore these for now
- } else if (name.startsWith(ATTR_LAYOUT_RESOURCE_PREFIX)
- && ANDROID_URI.equals(attribute.getNamespaceURI())) {
- // Determine if the reference is to a known edge
- String id = getIdBasename(value);
- if (id != null) {
- View referenced = edgeList.getView(id);
- if (referenced != null) {
- // This is a valid reference, so preserve
- // the attribute
- if (name.equals(ATTR_LAYOUT_BELOW) ||
- name.equals(ATTR_LAYOUT_ABOVE) ||
- name.equals(ATTR_LAYOUT_ALIGN_TOP) ||
- name.equals(ATTR_LAYOUT_ALIGN_BOTTOM) ||
- name.equals(ATTR_LAYOUT_ALIGN_BASELINE)) {
- // Vertical constraint
- childView.addVerticalConstraint(name, value);
- } else if (name.equals(ATTR_LAYOUT_ALIGN_LEFT) ||
- name.equals(ATTR_LAYOUT_TO_LEFT_OF) ||
- name.equals(ATTR_LAYOUT_TO_RIGHT_OF) ||
- name.equals(ATTR_LAYOUT_ALIGN_RIGHT)) {
- // Horizontal constraint
- childView.addHorizConstraint(name, value);
- } else {
- // We don't expect this
- assert false : name;
- }
- } else {
- // Reference to some layout that is not included here.
- // TODO: See if the given layout has an edge
- // that corresponds to one of our known views
- // so we can adjust the constraints and keep it after all.
- }
- } else {
- // It's a parent-relative constraint (such
- // as aligning with a parent edge, or centering
- // in the parent view)
- boolean remove = true;
- if (name.equals(ATTR_LAYOUT_ALIGN_PARENT_LEFT)) {
- View referenced = edgeList.getSharedLeftEdge(layout);
- if (referenced != null) {
- if (isAncestor(referenced.getElement(), child)) {
- childView.addHorizConstraint(name, VALUE_TRUE);
- } else {
- childView.addHorizConstraint(
- ATTR_LAYOUT_ALIGN_LEFT, referenced.getId());
- }
- remove = false;
- }
- } else if (name.equals(ATTR_LAYOUT_ALIGN_PARENT_RIGHT)) {
- View referenced = edgeList.getSharedRightEdge(layout);
- if (referenced != null) {
- if (isAncestor(referenced.getElement(), child)) {
- childView.addHorizConstraint(name, VALUE_TRUE);
- } else {
- childView.addHorizConstraint(
- ATTR_LAYOUT_ALIGN_RIGHT, referenced.getId());
- }
- remove = false;
- }
- } else if (name.equals(ATTR_LAYOUT_ALIGN_PARENT_TOP)) {
- View referenced = edgeList.getSharedTopEdge(layout);
- if (referenced != null) {
- if (isAncestor(referenced.getElement(), child)) {
- childView.addVerticalConstraint(name, VALUE_TRUE);
- } else {
- childView.addVerticalConstraint(ATTR_LAYOUT_ALIGN_TOP,
- referenced.getId());
- }
- remove = false;
- }
- } else if (name.equals(ATTR_LAYOUT_ALIGN_PARENT_BOTTOM)) {
- View referenced = edgeList.getSharedBottomEdge(layout);
- if (referenced != null) {
- if (isAncestor(referenced.getElement(), child)) {
- childView.addVerticalConstraint(name, VALUE_TRUE);
- } else {
- childView.addVerticalConstraint(ATTR_LAYOUT_ALIGN_BOTTOM,
- referenced.getId());
- }
- remove = false;
- }
- }
-
- boolean alignWithParent =
- name.equals(ATTR_LAYOUT_ALIGN_WITH_PARENT_MISSING);
- if (remove && alignWithParent) {
- // TODO - look for this one AFTER we have processed
- // everything else, and then set constraints as necessary
- // IF there are no other conflicting constraints!
- }
-
- // Otherwise it's some kind of centering which we don't support
- // yet.
-
- // TODO: Find a way to determine whether we have
- // a corresponding edge for the parent (e.g. if
- // the ViewInfo bounds match our outer parent or
- // some other edge) and if so, substitute for that
- // id.
- // For example, if this element was centered
- // horizontally in a RelativeLayout that actually
- // occupies the entire width of our outer layout,
- // then it can be preserved after all!
-
- if (remove) {
- if (name.startsWith("layout_margin")) { //$NON-NLS-1$
- continue;
- }
-
- // Remove unknown attributes?
- // It's too early to do this, because we may later want
- // to *set* this value and it would result in an overlapping edits
- // exception. Therefore, we need to RECORD which attributes should
- // be removed, which lines should have its indentation adjusted
- // etc and finally process it all at the end!
- //mRefactoring.removeAttribute(mRootEdit, child,
- // attribute.getNamespaceURI(), name);
- }
- }
- }
- }
- }
- }
- }
-
- /**
- * Given {@code @id/foo} or {@code @+id/foo}, returns foo. Note that given foo it will
- * return null.
- */
- private static String getIdBasename(String id) {
- if (id.startsWith(NEW_ID_PREFIX)) {
- return id.substring(NEW_ID_PREFIX.length());
- } else if (id.startsWith(ID_PREFIX)) {
- return id.substring(ID_PREFIX.length());
- }
-
- return null;
- }
-
- /** Returns true if the given second argument is a descendant of the first argument */
- private static boolean isAncestor(Node ancestor, Node node) {
- while (node != null) {
- if (node == ancestor) {
- return true;
- }
- node = node.getParentNode();
- }
- return false;
- }
-
- /**
- * Computes horizontal constraints for the views in the grid for any remaining views
- * that do not have constraints (as the result of the analysis of known layouts). This
- * will look at the rendered layout coordinates and attempt to connect elements based
- * on a spatial layout in the grid.
- */
- private void computeHorizontalConstraints(Grid grid) {
- int columns = grid.getColumns();
-
- String attachLeftProperty = ATTR_LAYOUT_ALIGN_PARENT_LEFT;
- String attachLeftValue = VALUE_TRUE;
- int marginLeft = 0;
- for (int col = 0; col < columns; col++) {
- if (!grid.colContainsTopLeftCorner(col)) {
- // Just accumulate margins for the next column
- marginLeft += grid.getColumnWidth(col);
- } else {
- // Add horizontal attachments
- String firstId = null;
- for (View view : grid.viewsStartingInCol(col, true)) {
- assert view.getId() != null;
- if (firstId == null) {
- firstId = view.getId();
- if (view.isConstrainedHorizontally()) {
- // Nothing to do -- we already have an accurate position for
- // this view
- } else if (attachLeftProperty != null) {
- view.addHorizConstraint(attachLeftProperty, attachLeftValue);
- if (marginLeft > 0) {
- view.addHorizConstraint(ATTR_LAYOUT_MARGIN_LEFT,
- String.format(VALUE_N_DP, marginLeft));
- marginLeft = 0;
- }
- } else {
- assert false;
- }
- } else if (!view.isConstrainedHorizontally()) {
- view.addHorizConstraint(ATTR_LAYOUT_ALIGN_LEFT, firstId);
- }
- }
- }
-
- // Figure out edge for the next column
- View view = grid.findRightEdgeView(col);
- if (view != null) {
- assert view.getId() != null;
- attachLeftProperty = ATTR_LAYOUT_TO_RIGHT_OF;
- attachLeftValue = view.getId();
-
- marginLeft = 0;
- } else if (marginLeft == 0) {
- marginLeft = grid.getColumnWidth(col);
- }
- }
- }
-
- /**
- * Performs vertical layout just like the {@link #computeHorizontalConstraints} method
- * did horizontally
- */
- private void computeVerticalConstraints(Grid grid) {
- int rows = grid.getRows();
-
- String attachTopProperty = ATTR_LAYOUT_ALIGN_PARENT_TOP;
- String attachTopValue = VALUE_TRUE;
- int marginTop = 0;
- for (int row = 0; row < rows; row++) {
- if (!grid.rowContainsTopLeftCorner(row)) {
- // Just accumulate margins for the next column
- marginTop += grid.getRowHeight(row);
- } else {
- // Add horizontal attachments
- String firstId = null;
- for (View view : grid.viewsStartingInRow(row, true)) {
- assert view.getId() != null;
- if (firstId == null) {
- firstId = view.getId();
- if (view.isConstrainedVertically()) {
- // Nothing to do -- we already have an accurate position for
- // this view
- } else if (attachTopProperty != null) {
- view.addVerticalConstraint(attachTopProperty, attachTopValue);
- if (marginTop > 0) {
- view.addVerticalConstraint(ATTR_LAYOUT_MARGIN_TOP,
- String.format(VALUE_N_DP, marginTop));
- marginTop = 0;
- }
- } else {
- assert false;
- }
- } else if (!view.isConstrainedVertically()) {
- view.addVerticalConstraint(ATTR_LAYOUT_ALIGN_TOP, firstId);
- }
- }
- }
-
- // Figure out edge for the next row
- View view = grid.findBottomEdgeView(row);
- if (view != null) {
- assert view.getId() != null;
- attachTopProperty = ATTR_LAYOUT_BELOW;
- attachTopValue = view.getId();
- marginTop = 0;
- } else if (marginTop == 0) {
- marginTop = grid.getRowHeight(row);
- }
- }
- }
-
- /**
- * Searches a view hierarchy and locates the {@link CanvasViewInfo} for the given
- * {@link Element}
- *
- * @param info the root {@link CanvasViewInfo} to search below
- * @param element the target element
- * @return the {@link CanvasViewInfo} which corresponds to the given element
- */
- private CanvasViewInfo findViewForElement(CanvasViewInfo info, Element element) {
- if (getElement(info) == element) {
- return info;
- }
-
- for (CanvasViewInfo child : info.getChildren()) {
- CanvasViewInfo result = findViewForElement(child, element);
- if (result != null) {
- return result;
- }
- }
-
- return null;
- }
-
- /** Returns the {@link Element} for the given {@link CanvasViewInfo} */
- private static Element getElement(CanvasViewInfo info) {
- Node node = info.getUiViewNode().getXmlNode();
- if (node instanceof Element) {
- return (Element) node;
- }
-
- return null;
- }
-
- /**
- * A grid of cells which can contain views, used to infer spatial relationships when
- * computing constraints. Note that a view can appear in than one cell; they will
- * appear in all cells that their bounds overlap with!
- */
- private class Grid {
- private final int[] mLeft;
- private final int[] mTop;
- // A list from row to column to cell, where a cell is a list of views
- private final List<List<List<View>>> mRowList;
- private int mRowCount;
- private int mColCount;
-
- Grid(List<View> views, int[] left, int[] top) {
- mLeft = left;
- mTop = top;
-
- // The left/top arrays should include the ending point too
- mColCount = left.length - 1;
- mRowCount = top.length - 1;
-
- // Using nested lists rather than arrays to avoid lack of typed arrays
- // (can't create List<View>[row][column] arrays)
- mRowList = new ArrayList<List<List<View>>>(top.length);
- for (int row = 0; row < top.length; row++) {
- List<List<View>> columnList = new ArrayList<List<View>>(left.length);
- for (int col = 0; col < left.length; col++) {
- columnList.add(new ArrayList<View>(4));
- }
- mRowList.add(columnList);
- }
-
- for (View view : views) {
- // Get rid of the root view; we don't want that in the attachments logic;
- // it was there originally such that it would contribute the outermost
- // edges.
- if (view.mElement == mLayout) {
- continue;
- }
-
- for (int i = 0; i < view.mRowSpan; i++) {
- for (int j = 0; j < view.mColSpan; j++) {
- mRowList.get(view.mRow + i).get(view.mCol + j).add(view);
- }
- }
- }
- }
-
- /**
- * Returns the number of rows in the grid
- *
- * @return the row count
- */
- public int getRows() {
- return mRowCount;
- }
-
- /**
- * Returns the number of columns in the grid
- *
- * @return the column count
- */
- public int getColumns() {
- return mColCount;
- }
-
- /**
- * Returns the list of views overlapping the given cell
- *
- * @param row the row of the target cell
- * @param col the column of the target cell
- * @return a list of views overlapping the given column
- */
- public List<View> get(int row, int col) {
- return mRowList.get(row).get(col);
- }
-
- /**
- * Returns true if the given column contains a top left corner of a view
- *
- * @param column the column to check
- * @return true if one or more views have their top left corner in this column
- */
- public boolean colContainsTopLeftCorner(int column) {
- for (int row = 0; row < mRowCount; row++) {
- View view = getTopLeftCorner(row, column);
- if (view != null) {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Returns true if the given row contains a top left corner of a view
- *
- * @param row the row to check
- * @return true if one or more views have their top left corner in this row
- */
- public boolean rowContainsTopLeftCorner(int row) {
- for (int col = 0; col < mColCount; col++) {
- View view = getTopLeftCorner(row, col);
- if (view != null) {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Returns a list of views (optionally sorted by increasing row index) that have
- * their left edge starting in the given column
- *
- * @param col the column to look up views for
- * @param sort whether to sort the result in increasing row order
- * @return a list of views starting in the given column
- */
- public List<View> viewsStartingInCol(int col, boolean sort) {
- List<View> views = new ArrayList<View>();
- for (int row = 0; row < mRowCount; row++) {
- View view = getTopLeftCorner(row, col);
- if (view != null) {
- views.add(view);
- }
- }
-
- if (sort) {
- View.sortByRow(views);
- }
-
- return views;
- }
-
- /**
- * Returns a list of views (optionally sorted by increasing column index) that have
- * their top edge starting in the given row
- *
- * @param row the row to look up views for
- * @param sort whether to sort the result in increasing column order
- * @return a list of views starting in the given row
- */
- public List<View> viewsStartingInRow(int row, boolean sort) {
- List<View> views = new ArrayList<View>();
- for (int col = 0; col < mColCount; col++) {
- View view = getTopLeftCorner(row, col);
- if (view != null) {
- views.add(view);
- }
- }
-
- if (sort) {
- View.sortByColumn(views);
- }
-
- return views;
- }
-
- /**
- * Returns the pixel width of the given column
- *
- * @param col the column to look up the width of
- * @return the width of the column
- */
- public int getColumnWidth(int col) {
- return mLeft[col + 1] - mLeft[col];
- }
-
- /**
- * Returns the pixel height of the given row
- *
- * @param row the row to look up the height of
- * @return the height of the row
- */
- public int getRowHeight(int row) {
- return mTop[row + 1] - mTop[row];
- }
-
- /**
- * Returns the first view found that has its top left corner in the cell given by
- * the row and column indexes, or null if not found.
- *
- * @param row the row of the target cell
- * @param col the column of the target cell
- * @return a view with its top left corner in the given cell, or null if not found
- */
- View getTopLeftCorner(int row, int col) {
- List<View> views = get(row, col);
- if (views.size() > 0) {
- for (View view : views) {
- if (view.mRow == row && view.mCol == col) {
- return view;
- }
- }
- }
-
- return null;
- }
-
- public View findRightEdgeView(int col) {
- for (int row = 0; row < mRowCount; row++) {
- List<View> views = get(row, col);
- if (views.size() > 0) {
- List<View> result = new ArrayList<View>();
- for (View view : views) {
- // Ends on the right edge of this column?
- if (view.mCol + view.mColSpan == col + 1) {
- result.add(view);
- }
- }
- if (result.size() > 1) {
- View.sortByColumn(result);
- }
- if (result.size() > 0) {
- return result.get(0);
- }
- }
- }
-
- return null;
- }
-
- public View findBottomEdgeView(int row) {
- for (int col = 0; col < mColCount; col++) {
- List<View> views = get(row, col);
- if (views.size() > 0) {
- List<View> result = new ArrayList<View>();
- for (View view : views) {
- // Ends on the bottom edge of this column?
- if (view.mRow + view.mRowSpan == row + 1) {
- result.add(view);
- }
- }
- if (result.size() > 1) {
- View.sortByRow(result);
- }
- if (result.size() > 0) {
- return result.get(0);
- }
-
- }
- }
-
- return null;
- }
-
- /**
- * Produces a display of view contents along with the pixel positions of each row/column,
- * like the following (used for diagnostics only)
- * <pre>
- * |0 |49 |143 |192 |240
- * 36| | |button2 |
- * 72| |radioButton1 |button2 |
- * 74|button1 |radioButton1 |button2 |
- * 108|button1 | |button2 |
- * 110| | |button2 |
- * 149| | | |
- * 320
- * </pre>
- */
- @Override
- public String toString() {
- // Dump out the view table
- int cellWidth = 20;
-
- StringWriter stringWriter = new StringWriter();
- PrintWriter out = new PrintWriter(stringWriter);
- out.printf("%" + cellWidth + "s", ""); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- for (int col = 0; col < mColCount + 1; col++) {
- out.printf("|%-" + (cellWidth - 1) + "d", mLeft[col]); //$NON-NLS-1$ //$NON-NLS-2$
- }
- out.printf("\n"); //$NON-NLS-1$
- for (int row = 0; row < mRowCount + 1; row++) {
- out.printf("%" + cellWidth + "d", mTop[row]); //$NON-NLS-1$ //$NON-NLS-2$
- if (row == mRowCount) {
- break;
- }
- for (int col = 0; col < mColCount; col++) {
- List<View> views = get(row, col);
- StringBuilder sb = new StringBuilder();
- for (View view : views) {
- String id = view != null ? view.getId() : ""; //$NON-NLS-1$
- if (id.startsWith(NEW_ID_PREFIX)) {
- id = id.substring(NEW_ID_PREFIX.length());
- }
- if (id.length() > cellWidth - 2) {
- id = id.substring(0, cellWidth - 2);
- }
- if (sb.length() > 0) {
- sb.append(',');
- }
- sb.append(id);
- }
- String cellString = sb.toString();
- if (cellString.contains(",") && cellString.length() > cellWidth - 2) { //$NON-NLS-1$
- cellString = cellString.substring(0, cellWidth - 6) + "...,"; //$NON-NLS-1$
- }
- out.printf("|%-" + (cellWidth - 2) + "s ", cellString); //$NON-NLS-1$ //$NON-NLS-2$
- }
- out.printf("\n"); //$NON-NLS-1$
- }
-
- out.flush();
- return stringWriter.toString();
- }
- }
-
- /** Holds layout information about an individual view. */
- private static class View {
- private final Element mElement;
- private int mRow = -1;
- private int mCol = -1;
- private int mRowSpan = -1;
- private int mColSpan = -1;
- private CanvasViewInfo mInfo;
- private String mId;
- private List<Pair<String, String>> mHorizConstraints =
- new ArrayList<Pair<String, String>>(4);
- private List<Pair<String, String>> mVerticalConstraints =
- new ArrayList<Pair<String, String>>(4);
- private int mGravity;
-
- public View(CanvasViewInfo view, Element element) {
- mInfo = view;
- mElement = element;
- mGravity = GravityHelper.getGravity(element);
- }
-
- public int getHeight() {
- return mInfo.getAbsRect().height;
- }
-
- public int getGravity() {
- return mGravity;
- }
-
- public String getId() {
- return mId;
- }
-
- public Element getElement() {
- return mElement;
- }
-
- public List<Pair<String, String>> getHorizConstraints() {
- return mHorizConstraints;
- }
-
- public List<Pair<String, String>> getVerticalConstraints() {
- return mVerticalConstraints;
- }
-
- public boolean isConstrainedHorizontally() {
- return mHorizConstraints.size() > 0;
- }
-
- public boolean isConstrainedVertically() {
- return mVerticalConstraints.size() > 0;
- }
-
- public void addHorizConstraint(String property, String value) {
- assert property != null && value != null;
- // TODO - look for duplicates?
- mHorizConstraints.add(Pair.of(property, value));
- }
-
- public void addVerticalConstraint(String property, String value) {
- assert property != null && value != null;
- mVerticalConstraints.add(Pair.of(property, value));
- }
-
- public int getLeftEdge() {
- return mInfo.getAbsRect().x;
- }
-
- public int getTopEdge() {
- return mInfo.getAbsRect().y;
- }
-
- public int getRightEdge() {
- Rectangle bounds = mInfo.getAbsRect();
- // +1: make the bounds overlap, so the right edge is the same as the
- // left edge of the neighbor etc. Otherwise we end up with lots of 1-pixel wide
- // columns between adjacent items.
- return bounds.x + bounds.width + 1;
- }
-
- public int getBottomEdge() {
- Rectangle bounds = mInfo.getAbsRect();
- return bounds.y + bounds.height + 1;
- }
-
- @Override
- public String toString() {
- return "View [mId=" + mId + "]"; //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- public static void sortByRow(List<View> views) {
- Collections.sort(views, new ViewComparator(true/*rowSort*/));
- }
-
- public static void sortByColumn(List<View> views) {
- Collections.sort(views, new ViewComparator(false/*rowSort*/));
- }
-
- /** Comparator to help sort views by row or column index */
- private static class ViewComparator implements Comparator<View> {
- boolean mRowSort;
-
- public ViewComparator(boolean rowSort) {
- mRowSort = rowSort;
- }
-
- @Override
- public int compare(View view1, View view2) {
- if (mRowSort) {
- return view1.mRow - view2.mRow;
- } else {
- return view1.mCol - view2.mCol;
- }
- }
- }
- }
-
- /**
- * An edge list takes a hierarchy of elements and records the bounds of each element
- * into various lists such that it can answer queries about shared edges, about which
- * particular pixels occur as a boundary edge, etc.
- */
- private class EdgeList {
- private final Map<Element, View> mElementToViewMap = new HashMap<Element, View>(100);
- private final Map<String, View> mIdToViewMap = new HashMap<String, View>(100);
- private final Map<Integer, List<View>> mLeft = new HashMap<Integer, List<View>>();
- private final Map<Integer, List<View>> mTop = new HashMap<Integer, List<View>>();
- private final Map<Integer, List<View>> mRight = new HashMap<Integer, List<View>>();
- private final Map<Integer, List<View>> mBottom = new HashMap<Integer, List<View>>();
- private final Map<Element, Element> mSharedLeftEdge = new HashMap<Element, Element>();
- private final Map<Element, Element> mSharedTopEdge = new HashMap<Element, Element>();
- private final Map<Element, Element> mSharedRightEdge = new HashMap<Element, Element>();
- private final Map<Element, Element> mSharedBottomEdge = new HashMap<Element, Element>();
- private final List<Element> mDelete = new ArrayList<Element>();
-
- EdgeList(CanvasViewInfo view) {
- analyze(view, true);
- mDelete.remove(getElement(view));
- }
-
- public void setIdAttributeValue(View view, String id) {
- assert id.startsWith(NEW_ID_PREFIX) || id.startsWith(ID_PREFIX);
- view.mId = id;
- mIdToViewMap.put(getIdBasename(id), view);
- }
-
- public View getView(Element element) {
- return mElementToViewMap.get(element);
- }
-
- public View getView(String id) {
- return mIdToViewMap.get(id);
- }
-
- public List<View> getTopEdgeViews(Integer topOffset) {
- return mTop.get(topOffset);
- }
-
- public List<View> getLeftEdgeViews(Integer leftOffset) {
- return mLeft.get(leftOffset);
- }
-
- void record(Map<Integer, List<View>> map, Integer edge, View info) {
- List<View> list = map.get(edge);
- if (list == null) {
- list = new ArrayList<View>();
- map.put(edge, list);
- }
- list.add(info);
- }
-
- private List<Integer> getOffsets(Set<Integer> first, Set<Integer> second) {
- Set<Integer> joined = new HashSet<Integer>(first.size() + second.size());
- joined.addAll(first);
- joined.addAll(second);
- List<Integer> unique = new ArrayList<Integer>(joined);
- Collections.sort(unique);
-
- return unique;
- }
-
- public List<Element> getDeletedElements() {
- return mDelete;
- }
-
- public List<Integer> getColumnOffsets() {
- return getOffsets(mLeft.keySet(), mRight.keySet());
- }
- public List<Integer> getRowOffsets() {
- return getOffsets(mTop.keySet(), mBottom.keySet());
- }
-
- private View analyze(CanvasViewInfo view, boolean isRoot) {
- View added = null;
- if (!mFlatten || !isRemovableLayout(view)) {
- added = add(view);
- if (!isRoot) {
- return added;
- }
- } else {
- mDelete.add(getElement(view));
- }
-
- Element parentElement = getElement(view);
- Rectangle parentBounds = view.getAbsRect();
-
- // Build up a table model of the view
- for (CanvasViewInfo child : view.getChildren()) {
- Rectangle childBounds = child.getAbsRect();
- Element childElement = getElement(child);
-
- // See if this view shares the edge with the removed
- // parent layout, and if so, record that such that we can
- // later handle attachments to the removed parent edges
- if (parentBounds.x == childBounds.x) {
- mSharedLeftEdge.put(childElement, parentElement);
- }
- if (parentBounds.y == childBounds.y) {
- mSharedTopEdge.put(childElement, parentElement);
- }
- if (parentBounds.x + parentBounds.width == childBounds.x + childBounds.width) {
- mSharedRightEdge.put(childElement, parentElement);
- }
- if (parentBounds.y + parentBounds.height == childBounds.y + childBounds.height) {
- mSharedBottomEdge.put(childElement, parentElement);
- }
-
- if (mFlatten && isRemovableLayout(child)) {
- // When flattening, we want to disregard all layouts and instead
- // add their children!
- for (CanvasViewInfo childView : child.getChildren()) {
- analyze(childView, false);
-
- Element childViewElement = getElement(childView);
- Rectangle childViewBounds = childView.getAbsRect();
-
- // See if this view shares the edge with the removed
- // parent layout, and if so, record that such that we can
- // later handle attachments to the removed parent edges
- if (parentBounds.x == childViewBounds.x) {
- mSharedLeftEdge.put(childViewElement, parentElement);
- }
- if (parentBounds.y == childViewBounds.y) {
- mSharedTopEdge.put(childViewElement, parentElement);
- }
- if (parentBounds.x + parentBounds.width == childViewBounds.x
- + childViewBounds.width) {
- mSharedRightEdge.put(childViewElement, parentElement);
- }
- if (parentBounds.y + parentBounds.height == childViewBounds.y
- + childViewBounds.height) {
- mSharedBottomEdge.put(childViewElement, parentElement);
- }
- }
- mDelete.add(childElement);
- } else {
- analyze(child, false);
- }
- }
-
- return added;
- }
-
- public View getSharedLeftEdge(Element element) {
- return getSharedEdge(element, mSharedLeftEdge);
- }
-
- public View getSharedRightEdge(Element element) {
- return getSharedEdge(element, mSharedRightEdge);
- }
-
- public View getSharedTopEdge(Element element) {
- return getSharedEdge(element, mSharedTopEdge);
- }
-
- public View getSharedBottomEdge(Element element) {
- return getSharedEdge(element, mSharedBottomEdge);
- }
-
- private View getSharedEdge(Element element, Map<Element, Element> sharedEdgeMap) {
- Element original = element;
-
- while (element != null) {
- View view = getView(element);
- if (view != null) {
- assert isAncestor(element, original);
- return view;
- }
- element = sharedEdgeMap.get(element);
- }
-
- return null;
- }
-
- private View add(CanvasViewInfo info) {
- Rectangle bounds = info.getAbsRect();
- Element element = getElement(info);
- View view = new View(info, element);
- mElementToViewMap.put(element, view);
- record(mLeft, Integer.valueOf(bounds.x), view);
- record(mTop, Integer.valueOf(bounds.y), view);
- record(mRight, Integer.valueOf(view.getRightEdge()), view);
- record(mBottom, Integer.valueOf(view.getBottomEdge()), view);
- return view;
- }
-
- /**
- * Returns true if the given {@link CanvasViewInfo} represents an element we
- * should remove in a flattening conversion. We don't want to remove non-layout
- * views, or layout views that for example contain drawables on their own.
- */
- private boolean isRemovableLayout(CanvasViewInfo child) {
- // The element being converted is NOT removable!
- Element element = getElement(child);
- if (element == mLayout) {
- return false;
- }
-
- ElementDescriptor descriptor = child.getUiViewNode().getDescriptor();
- String name = descriptor.getXmlLocalName();
- if (name.equals(LINEAR_LAYOUT) || name.equals(RELATIVE_LAYOUT)) {
- // Don't delete layouts that provide a background image or gradient
- if (element.hasAttributeNS(ANDROID_URI, ATTR_BACKGROUND)) {
- AdtPlugin.log(IStatus.WARNING,
- "Did not flatten layout %1$s because it defines a '%2$s' attribute",
- VisualRefactoring.getId(element), ATTR_BACKGROUND);
- return false;
- }
-
- return true;
- }
-
- return false;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UnwrapAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UnwrapAction.java
deleted file mode 100644
index 02c2a276c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UnwrapAction.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
-
-/**
- * Action executed when the "Remove Container" menu item is invoked.
- */
-public class UnwrapAction extends VisualRefactoringAction {
- @Override
- public void run(IAction action) {
- if ((mTextSelection != null || mTreeSelection != null) && mFile != null) {
- UnwrapRefactoring ref = new UnwrapRefactoring(mFile, mDelegate,
- mTextSelection, mTreeSelection);
- RefactoringWizard wizard = new UnwrapWizard(ref, mDelegate);
- RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation(wizard);
- try {
- op.run(mWindow.getShell(), wizard.getDefaultPageTitle());
- } catch (InterruptedException e) {
- // Interrupted. Pass.
- }
- }
- }
-
- public static IAction create(LayoutEditorDelegate editorDelegate) {
- return create("Remove Container...", editorDelegate, UnwrapAction.class);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UnwrapContribution.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UnwrapContribution.java
deleted file mode 100644
index 0869fd637..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UnwrapContribution.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import org.eclipse.ltk.core.refactoring.RefactoringContribution;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-
-import java.util.Map;
-
-public class UnwrapContribution extends RefactoringContribution {
-
- @SuppressWarnings("unchecked")
- @Override
- public RefactoringDescriptor createDescriptor(String id, String project, String description,
- String comment, Map arguments, int flags) throws IllegalArgumentException {
- return new UnwrapRefactoring.Descriptor(project, description, comment, arguments);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public Map retrieveArgumentMap(RefactoringDescriptor descriptor) {
- if (descriptor instanceof UnwrapRefactoring.Descriptor) {
- return ((UnwrapRefactoring.Descriptor) descriptor).getArguments();
- }
- return super.retrieveArgumentMap(descriptor);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UnwrapRefactoring.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UnwrapRefactoring.java
deleted file mode 100644
index 4eff2cde5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UnwrapRefactoring.java
+++ /dev/null
@@ -1,246 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.EXT_XML;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.VisibleForTesting;
-import com.android.ide.common.xml.XmlFormatStyle;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ITreeSelection;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Removes the layout surrounding the current selection (or if the current selection has
- * children, removes the current layout), and migrates namespace and layout attributes.
- */
-@SuppressWarnings("restriction") // XML model
-public class UnwrapRefactoring extends VisualRefactoring {
- private Element mContainer;
-
- /**
- * This constructor is solely used by {@link Descriptor},
- * to replay a previous refactoring.
- * @param arguments argument map created by #createArgumentMap.
- */
- UnwrapRefactoring(Map<String, String> arguments) {
- super(arguments);
- }
-
- public UnwrapRefactoring(
- IFile file,
- LayoutEditorDelegate delegate,
- ITextSelection selection,
- ITreeSelection treeSelection) {
- super(file, delegate, selection, treeSelection);
- }
-
- @VisibleForTesting
- UnwrapRefactoring(List<Element> selectedElements, LayoutEditorDelegate editor) {
- super(selectedElements, editor);
- }
-
- @Override
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException,
- OperationCanceledException {
- RefactoringStatus status = new RefactoringStatus();
-
- try {
- pm.beginTask("Checking preconditions...", 6);
-
- if (mSelectionStart == -1 || mSelectionEnd == -1) {
- status.addFatalError("No selection to wrap");
- return status;
- }
-
- // Make sure that the selection all has the same parent?
- if (mElements.size() == 0) {
- status.addFatalError("Nothing to unwrap");
- return status;
- }
-
- Element first = mElements.get(0);
-
- // Determine the element of the container to be removed.
- // If you've selected a non-container, or you've selected multiple
- // elements, then it's the parent which should be removed. Otherwise,
- // it's the selection itself which represents the container.
- boolean useParent = mElements.size() > 1;
- if (!useParent) {
- if (DomUtilities.getChildren(first).size() == 0) {
- useParent = true;
- }
- }
- Node parent = first.getParentNode();
- if (parent instanceof Document) {
- mContainer = first;
- List<Element> elements = DomUtilities.getChildren(mContainer);
- if (elements.size() == 0) {
- status.addFatalError(
- "Cannot remove container when it has no children");
- return status;
- }
- } else if (useParent && (parent instanceof Element)) {
- mContainer = (Element) parent;
- } else {
- mContainer = first;
- }
-
- for (Element element : mElements) {
- if (element.getParentNode() != parent) {
- status.addFatalError(
- "All unwrapped elements must share the same parent element");
- return status;
- }
- }
-
- // Ensure that if we are removing the root, that it has only one child
- // such that there is a new single root
- if (mContainer.getParentNode() instanceof Document) {
- if (DomUtilities.getChildren(mContainer).size() > 1) {
- status.addFatalError(
- "Cannot remove root: it has more than one child "
- + "which would result in multiple new roots");
- return status;
- }
- }
-
- pm.worked(1);
- return status;
-
- } finally {
- pm.done();
- }
- }
-
- @Override
- protected VisualRefactoringDescriptor createDescriptor() {
- String comment = getName();
- return new Descriptor(
- mProject.getName(), //project
- comment, //description
- comment, //comment
- createArgumentMap());
- }
-
- @Override
- public String getName() {
- return "Remove Container";
- }
-
- @Override
- protected @NonNull List<Change> computeChanges(IProgressMonitor monitor) {
- // (1) If the removed parent is the root container, transfer its
- // namespace declarations
- // (2) Remove the root element completely
- // (3) Transfer layout attributes?
- // (4) Check for Java R.file usages?
-
- IFile file = mDelegate.getEditor().getInputFile();
- List<Change> changes = new ArrayList<Change>();
- if (file == null) {
- return changes;
- }
- MultiTextEdit rootEdit = new MultiTextEdit();
-
- // Transfer namespace elements?
- if (mContainer.getParentNode() instanceof Document) {
- List<Element> elements = DomUtilities.getChildren(mContainer);
- assert elements.size() == 1;
- Element newRoot = elements.get(0);
-
- List<Attr> declarations = findNamespaceAttributes(mContainer);
- for (Attr attribute : declarations) {
- if (attribute instanceof IndexedRegion) {
- setAttribute(rootEdit, newRoot, attribute.getNamespaceURI(),
- attribute.getPrefix(), attribute.getLocalName(), attribute.getValue());
- }
- }
- }
-
- // Transfer layout_ attributes (other than width and height)
- List<Element> children = DomUtilities.getChildren(mContainer);
- if (children.size() == 1) {
- List<Attr> layoutAttributes = findLayoutAttributes(mContainer);
- for (Attr attribute : layoutAttributes) {
- String name = attribute.getLocalName();
- if ((name.equals(ATTR_LAYOUT_WIDTH) || name.equals(ATTR_LAYOUT_HEIGHT))
- && ANDROID_URI.equals(attribute.getNamespaceURI())) {
- // Already handled specially
- continue;
- }
- }
- }
-
- // Remove the root
- removeElementTags(rootEdit, mContainer, Collections.<Element>emptyList() /* skip */,
- false /*changeIndentation*/);
-
- MultiTextEdit formatted = reformat(rootEdit, XmlFormatStyle.LAYOUT);
- if (formatted != null) {
- rootEdit = formatted;
- }
-
- TextFileChange change = new TextFileChange(file.getName(), file);
- change.setEdit(rootEdit);
- change.setTextType(EXT_XML);
- changes.add(change);
- return changes;
- }
-
- @Override
- public VisualRefactoringWizard createWizard() {
- return new UnwrapWizard(this, mDelegate);
- }
-
- public static class Descriptor extends VisualRefactoringDescriptor {
- public Descriptor(String project, String description, String comment,
- Map<String, String> arguments) {
- super("com.android.ide.eclipse.adt.refactoring.unwrap", //$NON-NLS-1$
- project, description, comment, arguments);
- }
-
- @Override
- protected Refactoring createRefactoring(Map<String, String> args) {
- return new UnwrapRefactoring(args);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UnwrapWizard.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UnwrapWizard.java
deleted file mode 100644
index 6e3bcf1e7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UnwrapWizard.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-
-public class UnwrapWizard extends VisualRefactoringWizard {
- public UnwrapWizard(UnwrapRefactoring ref, LayoutEditorDelegate editor) {
- super(ref, editor);
- setDefaultPageTitle("Remove Container");
- }
-
- @Override
- protected void addUserInputPages() {
- // This refactoring takes no parameters
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UseCompoundDrawableAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UseCompoundDrawableAction.java
deleted file mode 100644
index 84d3e7ee8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UseCompoundDrawableAction.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
-
-/**
- * Action executed when the "Convert Layout" menu item is invoked.
- */
-public class UseCompoundDrawableAction extends VisualRefactoringAction {
- @Override
- public void run(IAction action) {
- if ((mTextSelection != null || mTreeSelection != null) && mFile != null) {
- UseCompoundDrawableRefactoring ref = new UseCompoundDrawableRefactoring(
- mFile, mDelegate, mTextSelection, mTreeSelection);
- RefactoringWizard wizard = new UseCompoundDrawableWizard(ref, mDelegate);
- RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation(wizard);
- try {
- op.run(mWindow.getShell(), wizard.getDefaultPageTitle());
- } catch (InterruptedException e) {
- // Interrupted. Pass.
- }
- }
- }
-
- public static IAction create(LayoutEditorDelegate editorDelegate) {
- return create("Convert to a Compound Drawable...", editorDelegate,
- UseCompoundDrawableAction.class);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UseCompoundDrawableRefactoring.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UseCompoundDrawableRefactoring.java
deleted file mode 100644
index 0e56bdf4d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UseCompoundDrawableRefactoring.java
+++ /dev/null
@@ -1,452 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_DRAWABLE_BOTTOM;
-import static com.android.SdkConstants.ATTR_DRAWABLE_LEFT;
-import static com.android.SdkConstants.ATTR_DRAWABLE_PADDING;
-import static com.android.SdkConstants.ATTR_DRAWABLE_RIGHT;
-import static com.android.SdkConstants.ATTR_DRAWABLE_TOP;
-import static com.android.SdkConstants.ATTR_GRAVITY;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_MARGIN_BOTTOM;
-import static com.android.SdkConstants.ATTR_LAYOUT_MARGIN_LEFT;
-import static com.android.SdkConstants.ATTR_LAYOUT_MARGIN_RIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_MARGIN_TOP;
-import static com.android.SdkConstants.ATTR_LAYOUT_RESOURCE_PREFIX;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.ATTR_ORIENTATION;
-import static com.android.SdkConstants.ATTR_SRC;
-import static com.android.SdkConstants.EXT_XML;
-import static com.android.SdkConstants.IMAGE_VIEW;
-import static com.android.SdkConstants.LINEAR_LAYOUT;
-import static com.android.SdkConstants.PREFIX_RESOURCE_REF;
-import static com.android.SdkConstants.TEXT_VIEW;
-import static com.android.SdkConstants.VALUE_VERTICAL;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.annotations.VisibleForTesting;
-import com.android.ide.common.xml.XmlFormatStyle;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.formatting.EclipseXmlFormatPreferences;
-import com.android.ide.eclipse.adt.internal.editors.formatting.EclipseXmlPrettyPrinter;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.CanvasViewInfo;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ITreeSelection;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * Converts a LinearLayout with exactly a TextView child and an ImageView child into
- * a single TextView with a compound drawable.
- */
-@SuppressWarnings("restriction") // XML model
-public class UseCompoundDrawableRefactoring extends VisualRefactoring {
- /**
- * Constructs a new {@link UseCompoundDrawableRefactoring}
- *
- * @param file the file to refactor in
- * @param editor the corresponding editor
- * @param selection the editor selection, or null
- * @param treeSelection the canvas selection, or null
- */
- public UseCompoundDrawableRefactoring(IFile file, LayoutEditorDelegate editor,
- ITextSelection selection, ITreeSelection treeSelection) {
- super(file, editor, selection, treeSelection);
- }
-
- /**
- * This constructor is solely used by {@link Descriptor}, to replay a
- * previous refactoring.
- *
- * @param arguments argument map created by #createArgumentMap.
- */
- private UseCompoundDrawableRefactoring(Map<String, String> arguments) {
- super(arguments);
- }
-
- @VisibleForTesting
- UseCompoundDrawableRefactoring(List<Element> selectedElements, LayoutEditorDelegate editor) {
- super(selectedElements, editor);
- }
-
- @Override
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException,
- OperationCanceledException {
- RefactoringStatus status = new RefactoringStatus();
-
- try {
- pm.beginTask("Checking preconditions...", 6);
-
- if (mSelectionStart == -1 || mSelectionEnd == -1) {
- status.addFatalError("Nothing to convert");
- return status;
- }
-
- // Make sure the selection is contiguous
- if (mTreeSelection != null) {
- List<CanvasViewInfo> infos = getSelectedViewInfos();
- if (!validateNotEmpty(infos, status)) {
- return status;
- }
-
- // Enforce that the selection is -contiguous-
- if (!validateContiguous(infos, status)) {
- return status;
- }
- }
-
- // Ensures that we have a valid DOM model:
- if (mElements.size() == 0) {
- status.addFatalError("Nothing to convert");
- return status;
- }
-
- // Ensure that we have selected precisely one LinearLayout
- if (mElements.size() != 1 ||
- !(mElements.get(0).getTagName().equals(LINEAR_LAYOUT))) {
- status.addFatalError("Must select exactly one LinearLayout");
- return status;
- }
-
- Element layout = mElements.get(0);
- List<Element> children = DomUtilities.getChildren(layout);
- if (children.size() != 2) {
- status.addFatalError("The LinearLayout must have exactly two children");
- return status;
- }
- Element first = children.get(0);
- Element second = children.get(1);
- boolean haveTextView =
- first.getTagName().equals(TEXT_VIEW)
- || second.getTagName().equals(TEXT_VIEW);
- boolean haveImageView =
- first.getTagName().equals(IMAGE_VIEW)
- || second.getTagName().equals(IMAGE_VIEW);
- if (!(haveTextView && haveImageView)) {
- status.addFatalError("The LinearLayout must have exactly one TextView child " +
- "and one ImageView child");
- return status;
- }
-
- pm.worked(1);
- return status;
-
- } finally {
- pm.done();
- }
- }
-
- @Override
- protected VisualRefactoringDescriptor createDescriptor() {
- String comment = getName();
- return new Descriptor(
- mProject.getName(), //project
- comment, //description
- comment, //comment
- createArgumentMap());
- }
-
- @Override
- protected Map<String, String> createArgumentMap() {
- return super.createArgumentMap();
- }
-
- @Override
- public String getName() {
- return "Convert to Compound Drawable";
- }
-
- @Override
- protected @NonNull List<Change> computeChanges(IProgressMonitor monitor) {
- String androidNsPrefix = getAndroidNamespacePrefix();
- IFile file = mDelegate.getEditor().getInputFile();
- List<Change> changes = new ArrayList<Change>();
- if (file == null) {
- return changes;
- }
- TextFileChange change = new TextFileChange(file.getName(), file);
- MultiTextEdit rootEdit = new MultiTextEdit();
- change.setTextType(EXT_XML);
-
- // (1) Build up the contents of the new TextView. This is identical
- // to the old contents, but with the addition of a drawableTop/Left/Right/Bottom
- // attribute (depending on the orientation and order), as well as any layout
- // params from the LinearLayout.
- // (2) Delete the linear layout and replace with the text view.
- // (3) Reformat.
-
- // checkInitialConditions has already validated that we have exactly a LinearLayout
- // with an ImageView and a TextView child (in either order)
- Element layout = mElements.get(0);
- List<Element> children = DomUtilities.getChildren(layout);
- Element first = children.get(0);
- Element second = children.get(1);
- final Element text;
- final Element image;
- if (first.getTagName().equals(TEXT_VIEW)) {
- text = first;
- image = second;
- } else {
- text = second;
- image = first;
- }
-
- // Horizontal is the default, so if no value is specified it is horizontal.
- boolean isVertical = VALUE_VERTICAL.equals(layout.getAttributeNS(ANDROID_URI,
- ATTR_ORIENTATION));
-
- // The WST DOM implementation doesn't correctly implement cloneNode: this returns
- // an empty document instead:
- // text.getOwnerDocument().cloneNode(false/*deep*/);
- // Luckily we just need to clone a single element, not a nested structure, so it's
- // easy enough to do this manually:
- Document tempDocument = DomUtilities.createEmptyDocument();
- if (tempDocument == null) {
- return changes;
- }
- Element newTextElement = tempDocument.createElement(text.getTagName());
- tempDocument.appendChild(newTextElement);
-
- NamedNodeMap attributes = text.getAttributes();
- for (int i = 0, n = attributes.getLength(); i < n; i++) {
- Attr attribute = (Attr) attributes.item(i);
- String name = attribute.getLocalName();
- if (name.startsWith(ATTR_LAYOUT_RESOURCE_PREFIX)
- && ANDROID_URI.equals(attribute.getNamespaceURI())
- && !(name.equals(ATTR_LAYOUT_WIDTH) || name.equals(ATTR_LAYOUT_HEIGHT))) {
- // Ignore layout params: the parent layout is going away
- } else {
- newTextElement.setAttribute(attribute.getName(), attribute.getValue());
- }
- }
-
- // Apply all layout params from the parent (except width and height),
- // as well as android:gravity
- List<Attr> layoutAttributes = findLayoutAttributes(layout);
- for (Attr attribute : layoutAttributes) {
- String name = attribute.getLocalName();
- if ((name.equals(ATTR_LAYOUT_WIDTH) || name.equals(ATTR_LAYOUT_HEIGHT))
- && ANDROID_URI.equals(attribute.getNamespaceURI())) {
- // Already handled specially
- continue;
- }
- newTextElement.setAttribute(attribute.getName(), attribute.getValue());
- }
- String gravity = layout.getAttributeNS(ANDROID_URI, ATTR_GRAVITY);
- if (gravity.length() > 0) {
- setAndroidAttribute(newTextElement, androidNsPrefix, ATTR_GRAVITY, gravity);
- }
-
- String src = image.getAttributeNS(ANDROID_URI, ATTR_SRC);
-
- // Set the drawable
- String drawableAttribute;
- // The space between the image and the text can have margins/padding, both
- // from the text's perspective and from the image's perspective. We need to
- // combine these.
- String padding1 = null;
- String padding2 = null;
- if (isVertical) {
- if (first == image) {
- drawableAttribute = ATTR_DRAWABLE_TOP;
- padding1 = getPadding(image, ATTR_LAYOUT_MARGIN_BOTTOM);
- padding2 = getPadding(text, ATTR_LAYOUT_MARGIN_TOP);
- } else {
- drawableAttribute = ATTR_DRAWABLE_BOTTOM;
- padding1 = getPadding(text, ATTR_LAYOUT_MARGIN_BOTTOM);
- padding2 = getPadding(image, ATTR_LAYOUT_MARGIN_TOP);
- }
- } else {
- if (first == image) {
- drawableAttribute = ATTR_DRAWABLE_LEFT;
- padding1 = getPadding(image, ATTR_LAYOUT_MARGIN_RIGHT);
- padding2 = getPadding(text, ATTR_LAYOUT_MARGIN_LEFT);
- } else {
- drawableAttribute = ATTR_DRAWABLE_RIGHT;
- padding1 = getPadding(text, ATTR_LAYOUT_MARGIN_RIGHT);
- padding2 = getPadding(image, ATTR_LAYOUT_MARGIN_LEFT);
- }
- }
-
- setAndroidAttribute(newTextElement, androidNsPrefix, drawableAttribute, src);
-
- String padding = combine(padding1, padding2);
- if (padding != null) {
- setAndroidAttribute(newTextElement, androidNsPrefix, ATTR_DRAWABLE_PADDING, padding);
- }
-
- // If the removed LinearLayout is the root container, transfer its namespace
- // declaration to the TextView
- if (layout.getParentNode() instanceof Document) {
- List<Attr> declarations = findNamespaceAttributes(layout);
- for (Attr attribute : declarations) {
- if (attribute instanceof IndexedRegion) {
- newTextElement.setAttribute(attribute.getName(), attribute.getValue());
- }
- }
- }
-
- // Update any layout references to the layout to point to the text view
- String layoutId = getId(layout);
- if (layoutId.length() > 0) {
- String id = getId(text);
- if (id.length() == 0) {
- id = ensureHasId(rootEdit, text, null, false);
- setAndroidAttribute(newTextElement, androidNsPrefix, ATTR_ID, id);
- }
-
- IStructuredModel model = mDelegate.getEditor().getModelForRead();
- try {
- IStructuredDocument doc = model.getStructuredDocument();
- if (doc != null) {
- List<TextEdit> replaceIds = replaceIds(androidNsPrefix,
- doc, mSelectionStart, mSelectionEnd, layoutId, id);
- for (TextEdit edit : replaceIds) {
- rootEdit.addChild(edit);
- }
- }
- } finally {
- model.releaseFromRead();
- }
- }
-
- String xml = EclipseXmlPrettyPrinter.prettyPrint(
- tempDocument.getDocumentElement(),
- EclipseXmlFormatPreferences.create(),
- XmlFormatStyle.LAYOUT, null, false);
-
- TextEdit replace = new ReplaceEdit(mSelectionStart, mSelectionEnd - mSelectionStart, xml);
- rootEdit.addChild(replace);
-
- if (AdtPrefs.getPrefs().getFormatGuiXml()) {
- MultiTextEdit formatted = reformat(rootEdit, XmlFormatStyle.LAYOUT);
- if (formatted != null) {
- rootEdit = formatted;
- }
- }
-
- change.setEdit(rootEdit);
- changes.add(change);
- return changes;
- }
-
- @Nullable
- private static String getPadding(@NonNull Element element, @NonNull String attribute) {
- String padding = element.getAttributeNS(ANDROID_URI, attribute);
- if (padding != null && padding.isEmpty()) {
- padding = null;
- }
- return padding;
- }
-
- @VisibleForTesting
- @Nullable
- static String combine(@Nullable String dimension1, @Nullable String dimension2) {
- if (dimension1 == null || dimension1.isEmpty()) {
- if (dimension2 != null && dimension2.isEmpty()) {
- return null;
- }
- return dimension2;
- } else if (dimension2 == null || dimension2.isEmpty()) {
- if (dimension1 != null && dimension1.isEmpty()) {
- return null;
- }
- return dimension1;
- } else {
- // Two dimensions are specified (e.g. marginRight for the left one and marginLeft
- // for the right one); we have to add these together. We can only do that if
- // they use the same units, and do not use resources.
- if (dimension1.startsWith(PREFIX_RESOURCE_REF)
- || dimension2.startsWith(PREFIX_RESOURCE_REF)) {
- return null;
- }
-
- Pattern p = Pattern.compile("([\\d\\.]+)(.+)"); //$NON-NLS-1$
- Matcher matcher1 = p.matcher(dimension1);
- Matcher matcher2 = p.matcher(dimension2);
- if (matcher1.matches() && matcher2.matches()) {
- String unit = matcher1.group(2);
- if (unit.equals(matcher2.group(2))) {
- float value1 = Float.parseFloat(matcher1.group(1));
- float value2 = Float.parseFloat(matcher2.group(1));
- return AdtUtils.formatFloatAttribute(value1 + value2) + unit;
- }
- }
- }
-
- return null;
- }
-
- /**
- * Sets an Android attribute (in the Android namespace) on an element
- * without a given namespace prefix. This is done when building a new Element
- * in a temporary document such that the namespace prefix matches when the element is
- * formatted and replaced in the target document.
- */
- private static void setAndroidAttribute(Element element, String prefix, String name,
- String value) {
- element.setAttribute(prefix + ':' + name, value);
- }
-
- @Override
- public VisualRefactoringWizard createWizard() {
- return new UseCompoundDrawableWizard(this, mDelegate);
- }
-
- @SuppressWarnings("javadoc")
- public static class Descriptor extends VisualRefactoringDescriptor {
- public Descriptor(String project, String description, String comment,
- Map<String, String> arguments) {
- super("com.android.ide.eclipse.adt.refactoring.usecompound", //$NON-NLS-1$
- project, description, comment, arguments);
- }
-
- @Override
- protected Refactoring createRefactoring(Map<String, String> args) {
- return new UseCompoundDrawableRefactoring(args);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UseCompoundDrawableWizard.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UseCompoundDrawableWizard.java
deleted file mode 100644
index 3ffd6b5ea..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UseCompoundDrawableWizard.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-
-class UseCompoundDrawableWizard extends VisualRefactoringWizard {
- UseCompoundDrawableWizard(UseCompoundDrawableRefactoring ref, LayoutEditorDelegate editor) {
- super(ref, editor);
- setDefaultPageTitle("Use Compound Drawable");
- }
-
- @Override
- protected void addUserInputPages() {
- // This refactoring takes no parameters
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/VisualRefactoring.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/VisualRefactoring.java
deleted file mode 100644
index 904a3a084..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/VisualRefactoring.java
+++ /dev/null
@@ -1,1403 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import static com.android.SdkConstants.ANDROID_NS_NAME;
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ANDROID_WIDGET_PREFIX;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_RESOURCE_PREFIX;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.ID_PREFIX;
-import static com.android.SdkConstants.NEW_ID_PREFIX;
-import static com.android.SdkConstants.XMLNS;
-import static com.android.SdkConstants.XMLNS_PREFIX;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.VisibleForTesting;
-import com.android.ide.common.xml.XmlFormatStyle;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.formatting.EclipseXmlFormatPreferences;
-import com.android.ide.eclipse.adt.internal.editors.formatting.EclipseXmlPrettyPrinter;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.ConfigurationDescription;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.CanvasViewInfo;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.utils.Pair;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ITreeSelection;
-import org.eclipse.jface.viewers.TreePath;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.ChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.text.edits.DeleteEdit;
-import org.eclipse.text.edits.InsertEdit;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList;
-import org.eclipse.wst.xml.core.internal.regions.DOMRegionContext;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Parent class for the various visual refactoring operations; contains shared
- * implementations needed by most of them
- */
-@SuppressWarnings("restriction") // XML model
-public abstract class VisualRefactoring extends Refactoring {
- private static final String KEY_FILE = "file"; //$NON-NLS-1$
- private static final String KEY_PROJECT = "proj"; //$NON-NLS-1$
- private static final String KEY_SEL_START = "sel-start"; //$NON-NLS-1$
- private static final String KEY_SEL_END = "sel-end"; //$NON-NLS-1$
-
- protected final IFile mFile;
- protected final LayoutEditorDelegate mDelegate;
- protected final IProject mProject;
- protected int mSelectionStart = -1;
- protected int mSelectionEnd = -1;
- protected final List<Element> mElements;
- protected final ITreeSelection mTreeSelection;
- protected final ITextSelection mSelection;
- /** Same as {@link #mSelectionStart} but not adjusted to element edges */
- protected int mOriginalSelectionStart = -1;
- /** Same as {@link #mSelectionEnd} but not adjusted to element edges */
- protected int mOriginalSelectionEnd = -1;
-
- protected final Map<Element, String> mGeneratedIdMap = new HashMap<Element, String>();
- protected final Set<String> mGeneratedIds = new HashSet<String>();
-
- protected List<Change> mChanges;
- private String mAndroidNamespacePrefix;
-
- /**
- * This constructor is solely used by {@link VisualRefactoringDescriptor},
- * to replay a previous refactoring.
- * @param arguments argument map created by #createArgumentMap.
- */
- VisualRefactoring(Map<String, String> arguments) {
- IPath path = Path.fromPortableString(arguments.get(KEY_PROJECT));
- mProject = (IProject) ResourcesPlugin.getWorkspace().getRoot().findMember(path);
- path = Path.fromPortableString(arguments.get(KEY_FILE));
- mFile = (IFile) ResourcesPlugin.getWorkspace().getRoot().findMember(path);
- mSelectionStart = Integer.parseInt(arguments.get(KEY_SEL_START));
- mSelectionEnd = Integer.parseInt(arguments.get(KEY_SEL_END));
- mOriginalSelectionStart = mSelectionStart;
- mOriginalSelectionEnd = mSelectionEnd;
- mDelegate = null;
- mElements = null;
- mSelection = null;
- mTreeSelection = null;
- }
-
- @VisibleForTesting
- VisualRefactoring(List<Element> elements, LayoutEditorDelegate delegate) {
- mElements = elements;
- mDelegate = delegate;
-
- mFile = delegate != null ? delegate.getEditor().getInputFile() : null;
- mProject = delegate != null ? delegate.getEditor().getProject() : null;
- mSelectionStart = 0;
- mSelectionEnd = 0;
- mOriginalSelectionStart = 0;
- mOriginalSelectionEnd = 0;
- mSelection = null;
- mTreeSelection = null;
-
- int end = Integer.MIN_VALUE;
- int start = Integer.MAX_VALUE;
- for (Element element : elements) {
- if (element instanceof IndexedRegion) {
- IndexedRegion region = (IndexedRegion) element;
- start = Math.min(start, region.getStartOffset());
- end = Math.max(end, region.getEndOffset());
- }
- }
- if (start >= 0) {
- mSelectionStart = start;
- mSelectionEnd = end;
- mOriginalSelectionStart = start;
- mOriginalSelectionEnd = end;
- }
- }
-
- public VisualRefactoring(IFile file, LayoutEditorDelegate editor, ITextSelection selection,
- ITreeSelection treeSelection) {
- mFile = file;
- mDelegate = editor;
- mProject = file.getProject();
- mSelection = selection;
- mTreeSelection = treeSelection;
-
- // Initialize mSelectionStart and mSelectionEnd based on the selection context, which
- // is either a treeSelection (when invoked from the layout editor or the outline), or
- // a selection (when invoked from an XML editor)
- if (treeSelection != null) {
- int end = Integer.MIN_VALUE;
- int start = Integer.MAX_VALUE;
- for (TreePath path : treeSelection.getPaths()) {
- Object lastSegment = path.getLastSegment();
- if (lastSegment instanceof CanvasViewInfo) {
- CanvasViewInfo viewInfo = (CanvasViewInfo) lastSegment;
- UiViewElementNode uiNode = viewInfo.getUiViewNode();
- if (uiNode == null) {
- continue;
- }
- Node xmlNode = uiNode.getXmlNode();
- if (xmlNode instanceof IndexedRegion) {
- IndexedRegion region = (IndexedRegion) xmlNode;
-
- start = Math.min(start, region.getStartOffset());
- end = Math.max(end, region.getEndOffset());
- }
- }
- }
- if (start >= 0) {
- mSelectionStart = start;
- mSelectionEnd = end;
- mOriginalSelectionStart = mSelectionStart;
- mOriginalSelectionEnd = mSelectionEnd;
- }
- if (selection != null) {
- mOriginalSelectionStart = selection.getOffset();
- mOriginalSelectionEnd = mOriginalSelectionStart + selection.getLength();
- }
- } else if (selection != null) {
- // TODO: update selection to boundaries!
- mSelectionStart = selection.getOffset();
- mSelectionEnd = mSelectionStart + selection.getLength();
- mOriginalSelectionStart = mSelectionStart;
- mOriginalSelectionEnd = mSelectionEnd;
- }
-
- mElements = initElements();
- }
-
- @NonNull
- protected abstract List<Change> computeChanges(IProgressMonitor monitor);
-
- @Override
- public RefactoringStatus checkFinalConditions(IProgressMonitor monitor) throws CoreException,
- OperationCanceledException {
- RefactoringStatus status = new RefactoringStatus();
- mChanges = new ArrayList<Change>();
- try {
- monitor.beginTask("Checking post-conditions...", 5);
-
- // Reset state for each computeChanges call, in case the user goes back
- // and forth in the refactoring wizard
- mGeneratedIdMap.clear();
- mGeneratedIds.clear();
- List<Change> changes = computeChanges(monitor);
- mChanges.addAll(changes);
-
- monitor.worked(1);
- } finally {
- monitor.done();
- }
-
- return status;
- }
-
- @Override
- public Change createChange(IProgressMonitor monitor) throws CoreException,
- OperationCanceledException {
- try {
- monitor.beginTask("Applying changes...", 1);
-
- CompositeChange change = new CompositeChange(
- getName(),
- mChanges.toArray(new Change[mChanges.size()])) {
- @Override
- public ChangeDescriptor getDescriptor() {
- VisualRefactoringDescriptor desc = createDescriptor();
- return new RefactoringChangeDescriptor(desc);
- }
- };
-
- monitor.worked(1);
- return change;
-
- } finally {
- monitor.done();
- }
- }
-
- protected abstract VisualRefactoringDescriptor createDescriptor();
-
- protected Map<String, String> createArgumentMap() {
- HashMap<String, String> args = new HashMap<String, String>();
- args.put(KEY_PROJECT, mProject.getFullPath().toPortableString());
- args.put(KEY_FILE, mFile.getFullPath().toPortableString());
- args.put(KEY_SEL_START, Integer.toString(mSelectionStart));
- args.put(KEY_SEL_END, Integer.toString(mSelectionEnd));
-
- return args;
- }
-
- IFile getFile() {
- return mFile;
- }
-
- // ---- Shared functionality ----
-
-
- protected void openFile(IFile file) {
- GraphicalEditorPart graphicalEditor = mDelegate.getGraphicalEditor();
- IFile leavingFile = graphicalEditor.getEditedFile();
-
- try {
- // Duplicate the current state into the newly created file
- String state = ConfigurationDescription.getDescription(leavingFile);
-
- // TODO: Look for a ".NoTitleBar.Fullscreen" theme version of the current
- // theme to show.
-
- file.setSessionProperty(GraphicalEditorPart.NAME_INITIAL_STATE, state);
- } catch (CoreException e) {
- // pass
- }
-
- /* TBD: "Show Included In" if supported.
- * Not sure if this is a good idea.
- if (graphicalEditor.renderingSupports(Capability.EMBEDDED_LAYOUT)) {
- try {
- Reference include = Reference.create(graphicalEditor.getEditedFile());
- file.setSessionProperty(GraphicalEditorPart.NAME_INCLUDE, include);
- } catch (CoreException e) {
- // pass - worst that can happen is that we don't start with inclusion
- }
- }
- */
-
- try {
- IEditorPart part =
- IDE.openEditor(mDelegate.getEditor().getEditorSite().getPage(), file);
- if (part instanceof AndroidXmlEditor && AdtPrefs.getPrefs().getFormatGuiXml()) {
- AndroidXmlEditor newEditor = (AndroidXmlEditor) part;
- newEditor.reformatDocument();
- }
- } catch (PartInitException e) {
- AdtPlugin.log(e, "Can't open new included layout");
- }
- }
-
-
- /** Produce a list of edits to replace references to the given id with the given new id */
- protected static List<TextEdit> replaceIds(String androidNamePrefix,
- IStructuredDocument doc, int skipStart, int skipEnd,
- String rootId, String referenceId) {
- if (rootId == null) {
- return Collections.emptyList();
- }
-
- // We need to search for either @+id/ or @id/
- String match1 = rootId;
- String match2;
- if (match1.startsWith(ID_PREFIX)) {
- match2 = '"' + NEW_ID_PREFIX + match1.substring(ID_PREFIX.length()) + '"';
- match1 = '"' + match1 + '"';
- } else if (match1.startsWith(NEW_ID_PREFIX)) {
- match2 = '"' + ID_PREFIX + match1.substring(NEW_ID_PREFIX.length()) + '"';
- match1 = '"' + match1 + '"';
- } else {
- return Collections.emptyList();
- }
-
- String namePrefix = androidNamePrefix + ':' + ATTR_LAYOUT_RESOURCE_PREFIX;
- List<TextEdit> edits = new ArrayList<TextEdit>();
-
- IStructuredDocumentRegion region = doc.getFirstStructuredDocumentRegion();
- for (; region != null; region = region.getNext()) {
- ITextRegionList list = region.getRegions();
- int regionStart = region.getStart();
-
- // Look at all attribute values and look for an id reference match
- String attributeName = ""; //$NON-NLS-1$
- for (int j = 0; j < region.getNumberOfRegions(); j++) {
- ITextRegion subRegion = list.get(j);
- String type = subRegion.getType();
- if (DOMRegionContext.XML_TAG_ATTRIBUTE_NAME.equals(type)) {
- attributeName = region.getText(subRegion);
- } else if (DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE.equals(type)) {
- // Only replace references in layout attributes
- if (!attributeName.startsWith(namePrefix)) {
- continue;
- }
- // Skip occurrences in the given skip range
- int subRegionStart = regionStart + subRegion.getStart();
- if (subRegionStart >= skipStart && subRegionStart <= skipEnd) {
- continue;
- }
-
- String attributeValue = region.getText(subRegion);
- if (attributeValue.equals(match1) || attributeValue.equals(match2)) {
- int start = subRegionStart + 1; // skip quote
- int end = start + rootId.length();
-
- edits.add(new ReplaceEdit(start, end - start, referenceId));
- }
- }
- }
- }
-
- return edits;
- }
-
- /** Get the id of the root selected element, if any */
- protected String getRootId() {
- Element primary = getPrimaryElement();
- if (primary != null) {
- String oldId = primary.getAttributeNS(ANDROID_URI, ATTR_ID);
- // id null check for https://bugs.eclipse.org/bugs/show_bug.cgi?id=272378
- if (oldId != null && oldId.length() > 0) {
- return oldId;
- }
- }
-
- return null;
- }
-
- protected String getAndroidNamespacePrefix() {
- if (mAndroidNamespacePrefix == null) {
- List<Attr> attributeNodes = findNamespaceAttributes();
- for (Node attributeNode : attributeNodes) {
- String prefix = attributeNode.getPrefix();
- if (XMLNS.equals(prefix)) {
- String name = attributeNode.getNodeName();
- String value = attributeNode.getNodeValue();
- if (value.equals(ANDROID_URI)) {
- mAndroidNamespacePrefix = name;
- if (mAndroidNamespacePrefix.startsWith(XMLNS_PREFIX)) {
- mAndroidNamespacePrefix =
- mAndroidNamespacePrefix.substring(XMLNS_PREFIX.length());
- }
- }
- }
- }
-
- if (mAndroidNamespacePrefix == null) {
- mAndroidNamespacePrefix = ANDROID_NS_NAME;
- }
- }
-
- return mAndroidNamespacePrefix;
- }
-
- protected static String getAndroidNamespacePrefix(Document document) {
- String nsPrefix = null;
- List<Attr> attributeNodes = findNamespaceAttributes(document);
- for (Node attributeNode : attributeNodes) {
- String prefix = attributeNode.getPrefix();
- if (XMLNS.equals(prefix)) {
- String name = attributeNode.getNodeName();
- String value = attributeNode.getNodeValue();
- if (value.equals(ANDROID_URI)) {
- nsPrefix = name;
- if (nsPrefix.startsWith(XMLNS_PREFIX)) {
- nsPrefix =
- nsPrefix.substring(XMLNS_PREFIX.length());
- }
- }
- }
- }
-
- if (nsPrefix == null) {
- nsPrefix = ANDROID_NS_NAME;
- }
-
- return nsPrefix;
- }
-
- protected List<Attr> findNamespaceAttributes() {
- Document document = getDomDocument();
- return findNamespaceAttributes(document);
- }
-
- protected static List<Attr> findNamespaceAttributes(Document document) {
- if (document != null) {
- Element root = document.getDocumentElement();
- return findNamespaceAttributes(root);
- }
-
- return Collections.emptyList();
- }
-
- protected static List<Attr> findNamespaceAttributes(Node root) {
- List<Attr> result = new ArrayList<Attr>();
- NamedNodeMap attributes = root.getAttributes();
- for (int i = 0, n = attributes.getLength(); i < n; i++) {
- Node attributeNode = attributes.item(i);
-
- String prefix = attributeNode.getPrefix();
- if (XMLNS.equals(prefix)) {
- result.add((Attr) attributeNode);
- }
- }
-
- return result;
- }
-
- protected List<Attr> findLayoutAttributes(Node root) {
- List<Attr> result = new ArrayList<Attr>();
- NamedNodeMap attributes = root.getAttributes();
- for (int i = 0, n = attributes.getLength(); i < n; i++) {
- Node attributeNode = attributes.item(i);
-
- String name = attributeNode.getLocalName();
- if (name.startsWith(ATTR_LAYOUT_RESOURCE_PREFIX)
- && ANDROID_URI.equals(attributeNode.getNamespaceURI())) {
- result.add((Attr) attributeNode);
- }
- }
-
- return result;
- }
-
- protected String insertNamespace(String xmlText, String namespaceDeclarations) {
- // Insert namespace declarations into the extracted XML fragment
- int firstSpace = xmlText.indexOf(' ');
- int elementEnd = xmlText.indexOf('>');
- int insertAt;
- if (firstSpace != -1 && firstSpace < elementEnd) {
- insertAt = firstSpace;
- } else {
- insertAt = elementEnd;
- }
- xmlText = xmlText.substring(0, insertAt) + namespaceDeclarations
- + xmlText.substring(insertAt);
-
- return xmlText;
- }
-
- /** Remove sections of the document that correspond to top level layout attributes;
- * these are placed on the include element instead */
- protected String stripTopLayoutAttributes(Element primary, int start, String xml) {
- if (primary != null) {
- // List of attributes to remove
- List<IndexedRegion> skip = new ArrayList<IndexedRegion>();
- NamedNodeMap attributes = primary.getAttributes();
- for (int i = 0, n = attributes.getLength(); i < n; i++) {
- Node attr = attributes.item(i);
- String name = attr.getLocalName();
- if (name.startsWith(ATTR_LAYOUT_RESOURCE_PREFIX)
- && ANDROID_URI.equals(attr.getNamespaceURI())) {
- if (name.equals(ATTR_LAYOUT_WIDTH) || name.equals(ATTR_LAYOUT_HEIGHT)) {
- // These are special and are left in
- continue;
- }
-
- if (attr instanceof IndexedRegion) {
- skip.add((IndexedRegion) attr);
- }
- }
- }
- if (skip.size() > 0) {
- Collections.sort(skip, new Comparator<IndexedRegion>() {
- // Sort in start order
- @Override
- public int compare(IndexedRegion r1, IndexedRegion r2) {
- return r1.getStartOffset() - r2.getStartOffset();
- }
- });
-
- // Successively cut out the various layout attributes
- // TODO remove adjacent whitespace too (but not newlines, unless they
- // are newly adjacent)
- StringBuilder sb = new StringBuilder(xml.length());
- int nextStart = 0;
-
- // Copy out all the sections except the skip sections
- for (IndexedRegion r : skip) {
- int regionStart = r.getStartOffset();
- // Adjust to string offsets since we've copied the string out of
- // the document
- regionStart -= start;
-
- sb.append(xml.substring(nextStart, regionStart));
-
- nextStart = regionStart + r.getLength();
- }
- if (nextStart < xml.length()) {
- sb.append(xml.substring(nextStart));
- }
-
- return sb.toString();
- }
- }
-
- return xml;
- }
-
- protected static String getIndent(String line, int max) {
- int i = 0;
- int n = Math.min(max, line.length());
- for (; i < n; i++) {
- char c = line.charAt(i);
- if (!Character.isWhitespace(c)) {
- return line.substring(0, i);
- }
- }
-
- if (n < line.length()) {
- return line.substring(0, n);
- } else {
- return line;
- }
- }
-
- protected static String dedent(String xml) {
- String[] lines = xml.split("\n"); //$NON-NLS-1$
- if (lines.length < 2) {
- // The first line never has any indentation since we copy it out from the
- // element start index
- return xml;
- }
-
- String indentPrefix = getIndent(lines[1], lines[1].length());
- for (int i = 2, n = lines.length; i < n; i++) {
- String line = lines[i];
-
- // Ignore blank lines
- if (line.trim().length() == 0) {
- continue;
- }
-
- indentPrefix = getIndent(line, indentPrefix.length());
-
- if (indentPrefix.length() == 0) {
- return xml;
- }
- }
-
- StringBuilder sb = new StringBuilder();
- for (String line : lines) {
- if (line.startsWith(indentPrefix)) {
- sb.append(line.substring(indentPrefix.length()));
- } else {
- sb.append(line);
- }
- sb.append('\n');
- }
- return sb.toString();
- }
-
- protected String getText(int start, int end) {
- try {
- IStructuredDocument document = mDelegate.getEditor().getStructuredDocument();
- return document.get(start, end - start);
- } catch (BadLocationException e) {
- // the region offset was invalid. ignore.
- return null;
- }
- }
-
- protected List<Element> getElements() {
- return mElements;
- }
-
- protected List<Element> initElements() {
- List<Element> nodes = new ArrayList<Element>();
-
- assert mTreeSelection == null || mSelection == null :
- "treeSel= " + mTreeSelection + ", sel=" + mSelection;
-
- // Initialize mSelectionStart and mSelectionEnd based on the selection context, which
- // is either a treeSelection (when invoked from the layout editor or the outline), or
- // a selection (when invoked from an XML editor)
- if (mTreeSelection != null) {
- int end = Integer.MIN_VALUE;
- int start = Integer.MAX_VALUE;
- for (TreePath path : mTreeSelection.getPaths()) {
- Object lastSegment = path.getLastSegment();
- if (lastSegment instanceof CanvasViewInfo) {
- CanvasViewInfo viewInfo = (CanvasViewInfo) lastSegment;
- UiViewElementNode uiNode = viewInfo.getUiViewNode();
- if (uiNode == null) {
- continue;
- }
- Node xmlNode = uiNode.getXmlNode();
- if (xmlNode instanceof Element) {
- Element element = (Element) xmlNode;
- nodes.add(element);
- IndexedRegion region = getRegion(element);
- start = Math.min(start, region.getStartOffset());
- end = Math.max(end, region.getEndOffset());
- }
- }
- }
- if (start >= 0) {
- mSelectionStart = start;
- mSelectionEnd = end;
- }
- } else if (mSelection != null) {
- mSelectionStart = mSelection.getOffset();
- mSelectionEnd = mSelectionStart + mSelection.getLength();
- mOriginalSelectionStart = mSelectionStart;
- mOriginalSelectionEnd = mSelectionEnd;
-
- // Figure out the range of selected nodes from the document offsets
- IStructuredDocument doc = mDelegate.getEditor().getStructuredDocument();
- Pair<Element, Element> range = DomUtilities.getElementRange(doc,
- mSelectionStart, mSelectionEnd);
- if (range != null) {
- Element first = range.getFirst();
- Element last = range.getSecond();
-
- // Adjust offsets to get rid of surrounding text nodes (if you happened
- // to select a text range and included whitespace on either end etc)
- mSelectionStart = getRegion(first).getStartOffset();
- mSelectionEnd = getRegion(last).getEndOffset();
-
- if (mSelectionStart > mSelectionEnd) {
- int tmp = mSelectionStart;
- mSelectionStart = mSelectionEnd;
- mSelectionEnd = tmp;
- }
-
- if (first == last) {
- nodes.add(first);
- } else if (first.getParentNode() == last.getParentNode()) {
- // Add the range
- Node node = first;
- while (node != null) {
- if (node instanceof Element) {
- nodes.add((Element) node);
- }
- if (node == last) {
- break;
- }
- node = node.getNextSibling();
- }
- } else {
- // Different parents: this means we have an uneven selection, selecting
- // elements from different levels. We can't extract ranges like that.
- }
- }
- } else {
- assert false;
- }
-
- // Make sure that the list of elements is unique
- //Set<Element> seen = new HashSet<Element>();
- //for (Element element : nodes) {
- // assert !seen.contains(element) : element;
- // seen.add(element);
- //}
-
- return nodes;
- }
-
- protected Element getPrimaryElement() {
- List<Element> elements = getElements();
- if (elements != null && elements.size() == 1) {
- return elements.get(0);
- }
-
- return null;
- }
-
- protected Document getDomDocument() {
- if (mDelegate.getUiRootNode() != null) {
- return mDelegate.getUiRootNode().getXmlDocument();
- } else {
- return getElements().get(0).getOwnerDocument();
- }
- }
-
- protected List<CanvasViewInfo> getSelectedViewInfos() {
- List<CanvasViewInfo> infos = new ArrayList<CanvasViewInfo>();
- if (mTreeSelection != null) {
- for (TreePath path : mTreeSelection.getPaths()) {
- Object lastSegment = path.getLastSegment();
- if (lastSegment instanceof CanvasViewInfo) {
- infos.add((CanvasViewInfo) lastSegment);
- }
- }
- }
- return infos;
- }
-
- protected boolean validateNotEmpty(List<CanvasViewInfo> infos, RefactoringStatus status) {
- if (infos.size() == 0) {
- status.addFatalError("No selection to extract");
- return false;
- }
-
- return true;
- }
-
- protected boolean validateNotRoot(List<CanvasViewInfo> infos, RefactoringStatus status) {
- for (CanvasViewInfo info : infos) {
- if (info.isRoot()) {
- status.addFatalError("Cannot refactor the root");
- return false;
- }
- }
-
- return true;
- }
-
- protected boolean validateContiguous(List<CanvasViewInfo> infos, RefactoringStatus status) {
- if (infos.size() > 1) {
- // All elements must be siblings (e.g. same parent)
- List<UiViewElementNode> nodes = new ArrayList<UiViewElementNode>(infos
- .size());
- for (CanvasViewInfo info : infos) {
- UiViewElementNode node = info.getUiViewNode();
- if (node != null) {
- nodes.add(node);
- }
- }
- if (nodes.size() == 0) {
- status.addFatalError("No selected views");
- return false;
- }
-
- UiElementNode parent = nodes.get(0).getUiParent();
- for (UiViewElementNode node : nodes) {
- if (parent != node.getUiParent()) {
- status.addFatalError("The selected elements must be adjacent");
- return false;
- }
- }
- // Ensure that the siblings are contiguous; no gaps.
- // If we've selected all the children of the parent then we don't need
- // to look.
- List<UiElementNode> siblings = parent.getUiChildren();
- if (siblings.size() != nodes.size()) {
- Set<UiViewElementNode> nodeSet = new HashSet<UiViewElementNode>(nodes);
- boolean inRange = false;
- int remaining = nodes.size();
- for (UiElementNode node : siblings) {
- boolean in = nodeSet.contains(node);
- if (in) {
- remaining--;
- if (remaining == 0) {
- break;
- }
- inRange = true;
- } else if (inRange) {
- status.addFatalError("The selected elements must be adjacent");
- return false;
- }
- }
- }
- }
-
- return true;
- }
-
- /**
- * Updates the given element with a new name if the current id reflects the old
- * element type. If the name was changed, it will return the new name.
- */
- protected String ensureIdMatchesType(Element element, String newType, MultiTextEdit rootEdit) {
- String oldType = element.getTagName();
- if (oldType.indexOf('.') == -1) {
- oldType = ANDROID_WIDGET_PREFIX + oldType;
- }
- String oldTypeBase = oldType.substring(oldType.lastIndexOf('.') + 1);
- String id = getId(element);
- if (id == null || id.length() == 0
- || id.toLowerCase(Locale.US).contains(oldTypeBase.toLowerCase(Locale.US))) {
- String newTypeBase = newType.substring(newType.lastIndexOf('.') + 1);
- return ensureHasId(rootEdit, element, newTypeBase);
- }
-
- return null;
- }
-
- /**
- * Returns the {@link IndexedRegion} for the given node
- *
- * @param node the node to look up the region for
- * @return the corresponding region, or null
- */
- public static IndexedRegion getRegion(Node node) {
- if (node instanceof IndexedRegion) {
- return (IndexedRegion) node;
- }
-
- return null;
- }
-
- protected String ensureHasId(MultiTextEdit rootEdit, Element element, String prefix) {
- return ensureHasId(rootEdit, element, prefix, true);
- }
-
- protected String ensureHasId(MultiTextEdit rootEdit, Element element, String prefix,
- boolean apply) {
- String id = mGeneratedIdMap.get(element);
- if (id != null) {
- return NEW_ID_PREFIX + id;
- }
-
- if (!element.hasAttributeNS(ANDROID_URI, ATTR_ID)
- || (prefix != null && !getId(element).startsWith(prefix))) {
- id = DomUtilities.getFreeWidgetId(element, mGeneratedIds, prefix);
- // Make sure we don't use this one again
- mGeneratedIds.add(id);
- mGeneratedIdMap.put(element, id);
- id = NEW_ID_PREFIX + id;
- if (apply) {
- setAttribute(rootEdit, element,
- ANDROID_URI, getAndroidNamespacePrefix(), ATTR_ID, id);
- }
- return id;
- }
-
- return getId(element);
- }
-
- protected int getFirstAttributeOffset(Element element) {
- IndexedRegion region = getRegion(element);
- if (region != null) {
- int startOffset = region.getStartOffset();
- int endOffset = region.getEndOffset();
- String text = getText(startOffset, endOffset);
- String name = element.getLocalName();
- int nameOffset = text.indexOf(name);
- if (nameOffset != -1) {
- return startOffset + nameOffset + name.length();
- }
- }
-
- return -1;
- }
-
- /**
- * Returns the id of the given element
- *
- * @param element the element to look up the id for
- * @return the corresponding id, or an empty string (should not be null
- * according to the DOM API, but has been observed to be null on
- * some versions of Eclipse)
- */
- public static String getId(Element element) {
- return element.getAttributeNS(ANDROID_URI, ATTR_ID);
- }
-
- protected String ensureNewId(String id) {
- if (id != null && id.length() > 0) {
- if (id.startsWith(ID_PREFIX)) {
- id = NEW_ID_PREFIX + id.substring(ID_PREFIX.length());
- } else if (!id.startsWith(NEW_ID_PREFIX)) {
- id = NEW_ID_PREFIX + id;
- }
- } else {
- id = null;
- }
-
- return id;
- }
-
- protected String getViewClass(String fqcn) {
- // Don't include android.widget. as a package prefix in layout files
- if (fqcn.startsWith(ANDROID_WIDGET_PREFIX)) {
- fqcn = fqcn.substring(ANDROID_WIDGET_PREFIX.length());
- }
-
- return fqcn;
- }
-
- protected void setAttribute(MultiTextEdit rootEdit, Element element,
- String attributeUri,
- String attributePrefix, String attributeName, String attributeValue) {
- int offset = getFirstAttributeOffset(element);
- if (offset != -1) {
- if (element.hasAttributeNS(attributeUri, attributeName)) {
- replaceAttributeDeclaration(rootEdit, offset, element, attributePrefix,
- attributeUri, attributeName, attributeValue);
- } else {
- addAttributeDeclaration(rootEdit, offset, attributePrefix, attributeName,
- attributeValue);
- }
- }
- }
-
- private void addAttributeDeclaration(MultiTextEdit rootEdit, int offset,
- String attributePrefix, String attributeName, String attributeValue) {
- StringBuilder sb = new StringBuilder();
- sb.append(' ');
-
- if (attributePrefix != null) {
- sb.append(attributePrefix).append(':');
- }
- sb.append(attributeName).append('=').append('"');
- sb.append(attributeValue).append('"');
-
- InsertEdit setAttribute = new InsertEdit(offset, sb.toString());
- rootEdit.addChild(setAttribute);
- }
-
- /** Replaces the value declaration of the given attribute */
- private void replaceAttributeDeclaration(MultiTextEdit rootEdit, int offset,
- Element element, String attributePrefix, String attributeUri,
- String attributeName, String attributeValue) {
- // Find attribute value and replace it
- IStructuredModel model = mDelegate.getEditor().getModelForRead();
- try {
- IStructuredDocument doc = model.getStructuredDocument();
-
- IStructuredDocumentRegion region = doc.getRegionAtCharacterOffset(offset);
- ITextRegionList list = region.getRegions();
- int regionStart = region.getStart();
-
- int valueStart = -1;
- boolean useNextValue = false;
- String targetName = attributePrefix != null
- ? attributePrefix + ':' + attributeName : attributeName;
-
- // Look at all attribute values and look for an id reference match
- for (int j = 0; j < region.getNumberOfRegions(); j++) {
- ITextRegion subRegion = list.get(j);
- String type = subRegion.getType();
- if (DOMRegionContext.XML_TAG_ATTRIBUTE_NAME.equals(type)) {
- // What about prefix?
- if (targetName.equals(region.getText(subRegion))) {
- useNextValue = true;
- }
- } else if (DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE.equals(type)) {
- if (useNextValue) {
- valueStart = regionStart + subRegion.getStart();
- break;
- }
- }
- }
-
- if (valueStart != -1) {
- String oldValue = element.getAttributeNS(attributeUri, attributeName);
- int start = valueStart + 1; // Skip opening "
- ReplaceEdit setAttribute = new ReplaceEdit(start, oldValue.length(),
- attributeValue);
- try {
- rootEdit.addChild(setAttribute);
- } catch (MalformedTreeException mte) {
- AdtPlugin.log(mte, "Could not replace attribute %1$s with %2$s",
- attributeName, attributeValue);
- throw mte;
- }
- }
- } finally {
- model.releaseFromRead();
- }
- }
-
- /** Strips out the given attribute, if defined */
- protected void removeAttribute(MultiTextEdit rootEdit, Element element, String uri,
- String attributeName) {
- if (element.hasAttributeNS(uri, attributeName)) {
- Attr attribute = element.getAttributeNodeNS(uri, attributeName);
- removeAttribute(rootEdit, attribute);
- }
- }
-
- /** Strips out the given attribute, if defined */
- protected void removeAttribute(MultiTextEdit rootEdit, Attr attribute) {
- IndexedRegion region = getRegion(attribute);
- if (region != null) {
- int startOffset = region.getStartOffset();
- int endOffset = region.getEndOffset();
- DeleteEdit deletion = new DeleteEdit(startOffset, endOffset - startOffset);
- rootEdit.addChild(deletion);
- }
- }
-
-
- /**
- * Removes the given element's opening and closing tags (including all of its
- * attributes) but leaves any children alone
- *
- * @param rootEdit the multi edit to add the removal operation to
- * @param element the element to delete the open and closing tags for
- * @param skip a list of elements that should not be modified (for example because they
- * are targeted for deletion)
- *
- * TODO: Rename this to "unwrap" ? And allow for handling nested deletions.
- */
- protected void removeElementTags(MultiTextEdit rootEdit, Element element, List<Element> skip,
- boolean changeIndentation) {
- IndexedRegion elementRegion = getRegion(element);
- if (elementRegion == null) {
- return;
- }
-
- // Look for the opening tag
- IStructuredModel model = mDelegate.getEditor().getModelForRead();
- try {
- int startLineInclusive = -1;
- int endLineInclusive = -1;
- IStructuredDocument doc = model.getStructuredDocument();
- if (doc != null) {
- int start = elementRegion.getStartOffset();
- IStructuredDocumentRegion region = doc.getRegionAtCharacterOffset(start);
- ITextRegionList list = region.getRegions();
- int regionStart = region.getStart();
- int startOffset = regionStart;
- for (int j = 0; j < region.getNumberOfRegions(); j++) {
- ITextRegion subRegion = list.get(j);
- String type = subRegion.getType();
- if (DOMRegionContext.XML_TAG_OPEN.equals(type)) {
- startOffset = regionStart + subRegion.getStart();
- } else if (DOMRegionContext.XML_TAG_CLOSE.equals(type)) {
- int endOffset = regionStart + subRegion.getStart() + subRegion.getLength();
-
- DeleteEdit deletion = createDeletion(doc, startOffset, endOffset);
- rootEdit.addChild(deletion);
- startLineInclusive = doc.getLineOfOffset(endOffset) + 1;
- break;
- }
- }
-
- // Find the close tag
- // Look at all attribute values and look for an id reference match
- region = doc.getRegionAtCharacterOffset(elementRegion.getEndOffset()
- - element.getTagName().length() - 1);
- list = region.getRegions();
- regionStart = region.getStartOffset();
- startOffset = -1;
- for (int j = 0; j < region.getNumberOfRegions(); j++) {
- ITextRegion subRegion = list.get(j);
- String type = subRegion.getType();
- if (DOMRegionContext.XML_END_TAG_OPEN.equals(type)) {
- startOffset = regionStart + subRegion.getStart();
- } else if (DOMRegionContext.XML_TAG_CLOSE.equals(type)) {
- int endOffset = regionStart + subRegion.getStart() + subRegion.getLength();
- if (startOffset != -1) {
- DeleteEdit deletion = createDeletion(doc, startOffset, endOffset);
- rootEdit.addChild(deletion);
- endLineInclusive = doc.getLineOfOffset(startOffset) - 1;
- }
- break;
- }
- }
- }
-
- // Dedent the contents
- if (changeIndentation && startLineInclusive != -1 && endLineInclusive != -1) {
- String indent = AndroidXmlEditor.getIndentAtOffset(doc, getRegion(element)
- .getStartOffset());
- setIndentation(rootEdit, indent, doc, startLineInclusive, endLineInclusive,
- element, skip);
- }
- } finally {
- model.releaseFromRead();
- }
- }
-
- protected void removeIndentation(MultiTextEdit rootEdit, String removeIndent,
- IStructuredDocument doc, int startLineInclusive, int endLineInclusive,
- Element element, List<Element> skip) {
- if (startLineInclusive > endLineInclusive) {
- return;
- }
- int indentLength = removeIndent.length();
- if (indentLength == 0) {
- return;
- }
-
- try {
- for (int line = startLineInclusive; line <= endLineInclusive; line++) {
- IRegion info = doc.getLineInformation(line);
- int lineStart = info.getOffset();
- int lineLength = info.getLength();
- int lineEnd = lineStart + lineLength;
- if (overlaps(lineStart, lineEnd, element, skip)) {
- continue;
- }
- String lineText = getText(lineStart,
- lineStart + Math.min(lineLength, indentLength));
- if (lineText.startsWith(removeIndent)) {
- rootEdit.addChild(new DeleteEdit(lineStart, indentLength));
- }
- }
- } catch (BadLocationException e) {
- AdtPlugin.log(e, null);
- }
- }
-
- protected void setIndentation(MultiTextEdit rootEdit, String indent,
- IStructuredDocument doc, int startLineInclusive, int endLineInclusive,
- Element element, List<Element> skip) {
- if (startLineInclusive > endLineInclusive) {
- return;
- }
- int indentLength = indent.length();
- if (indentLength == 0) {
- return;
- }
-
- try {
- for (int line = startLineInclusive; line <= endLineInclusive; line++) {
- IRegion info = doc.getLineInformation(line);
- int lineStart = info.getOffset();
- int lineLength = info.getLength();
- int lineEnd = lineStart + lineLength;
- if (overlaps(lineStart, lineEnd, element, skip)) {
- continue;
- }
- String lineText = getText(lineStart, lineStart + lineLength);
- int indentEnd = getFirstNonSpace(lineText);
- rootEdit.addChild(new ReplaceEdit(lineStart, indentEnd, indent));
- }
- } catch (BadLocationException e) {
- AdtPlugin.log(e, null);
- }
- }
-
- private int getFirstNonSpace(String s) {
- for (int i = 0; i < s.length(); i++) {
- if (!Character.isWhitespace(s.charAt(i))) {
- return i;
- }
- }
-
- return s.length();
- }
-
- /** Returns true if the given line overlaps any of the given elements */
- private static boolean overlaps(int startOffset, int endOffset,
- Element element, List<Element> overlaps) {
- for (Element e : overlaps) {
- if (e == element) {
- continue;
- }
-
- IndexedRegion region = getRegion(e);
- if (region.getEndOffset() >= startOffset && region.getStartOffset() <= endOffset) {
- return true;
- }
- }
- return false;
- }
-
- protected DeleteEdit createDeletion(IStructuredDocument doc, int startOffset, int endOffset) {
- // Expand to delete the whole line?
- try {
- IRegion info = doc.getLineInformationOfOffset(startOffset);
- int lineBegin = info.getOffset();
- // Is the text on the line leading up to the deletion region,
- // and the text following it, all whitespace?
- boolean deleteLine = true;
- if (lineBegin < startOffset) {
- String prefix = getText(lineBegin, startOffset);
- if (prefix.trim().length() > 0) {
- deleteLine = false;
- }
- }
- info = doc.getLineInformationOfOffset(endOffset);
- int lineEnd = info.getOffset() + info.getLength();
- if (lineEnd > endOffset) {
- String suffix = getText(endOffset, lineEnd);
- if (suffix.trim().length() > 0) {
- deleteLine = false;
- }
- }
- if (deleteLine) {
- startOffset = lineBegin;
- endOffset = Math.min(doc.getLength(), lineEnd + 1);
- }
- } catch (BadLocationException e) {
- AdtPlugin.log(e, null);
- }
-
-
- return new DeleteEdit(startOffset, endOffset - startOffset);
- }
-
- /**
- * Rewrite the edits in the given {@link MultiTextEdit} such that same edits are
- * applied, but the resulting range is also formatted
- */
- protected MultiTextEdit reformat(MultiTextEdit edit, XmlFormatStyle style) {
- String xml = mDelegate.getEditor().getStructuredDocument().get();
- return reformat(xml, edit, style);
- }
-
- /**
- * Rewrite the edits in the given {@link MultiTextEdit} such that same edits are
- * applied, but the resulting range is also formatted
- *
- * @param oldContents the original contents that should be edited by a
- * {@link MultiTextEdit}
- * @param edit the {@link MultiTextEdit} to be applied to some string
- * @param style the formatting style to use
- * @return a new {@link MultiTextEdit} which performs the same edits as the input edit
- * but also reformats the text
- */
- public static MultiTextEdit reformat(String oldContents, MultiTextEdit edit,
- XmlFormatStyle style) {
- IDocument document = new org.eclipse.jface.text.Document();
- document.set(oldContents);
-
- try {
- edit.apply(document);
- } catch (MalformedTreeException e) {
- AdtPlugin.log(e, null);
- return null; // Abort formatting
- } catch (BadLocationException e) {
- AdtPlugin.log(e, null);
- return null; // Abort formatting
- }
-
- String actual = document.get();
-
- // TODO: Try to format only the affected portion of the document.
- // To do that we need to find out what the affected offsets are; we know
- // the MultiTextEdit's affected range, but that is referring to offsets
- // in the old document. Use that to compute offsets in the new document.
- //int distanceFromEnd = actual.length() - edit.getExclusiveEnd();
- //IStructuredModel model = DomUtilities.createStructuredModel(actual);
- //int start = edit.getOffset();
- //int end = actual.length() - distanceFromEnd;
- //int length = end - start;
- //TextEdit format = AndroidXmlFormattingStrategy.format(model, start, length);
- EclipseXmlFormatPreferences formatPrefs = EclipseXmlFormatPreferences.create();
- String formatted = EclipseXmlPrettyPrinter.prettyPrint(actual, formatPrefs, style,
- null /*lineSeparator*/);
-
-
- // Figure out how much of the before and after strings are identical and narrow
- // the replacement scope
- boolean foundDifference = false;
- int firstDifference = 0;
- int lastDifference = formatted.length();
- int start = 0;
- int end = oldContents.length();
-
- for (int i = 0, j = start; i < formatted.length() && j < end; i++, j++) {
- if (formatted.charAt(i) != oldContents.charAt(j)) {
- firstDifference = i;
- foundDifference = true;
- break;
- }
- }
-
- if (!foundDifference) {
- // No differences - the document is already formatted, nothing to do
- return null;
- }
-
- lastDifference = firstDifference + 1;
- for (int i = formatted.length() - 1, j = end - 1;
- i > firstDifference && j > start;
- i--, j--) {
- if (formatted.charAt(i) != oldContents.charAt(j)) {
- lastDifference = i + 1;
- break;
- }
- }
-
- start += firstDifference;
- end -= (formatted.length() - lastDifference);
- end = Math.max(start, end);
- formatted = formatted.substring(firstDifference, lastDifference);
-
- ReplaceEdit format = new ReplaceEdit(start, end - start,
- formatted);
-
- MultiTextEdit newEdit = new MultiTextEdit();
- newEdit.addChild(format);
-
- return newEdit;
- }
-
- protected ViewElementDescriptor getElementDescriptor(String fqcn) {
- AndroidTargetData data = mDelegate.getEditor().getTargetData();
- if (data != null) {
- return data.getLayoutDescriptors().findDescriptorByClass(fqcn);
- }
-
- return null;
- }
-
- /** Create a wizard for this refactoring */
- abstract VisualRefactoringWizard createWizard();
-
- public abstract static class VisualRefactoringDescriptor extends RefactoringDescriptor {
- private final Map<String, String> mArguments;
-
- public VisualRefactoringDescriptor(
- String id, String project, String description, String comment,
- Map<String, String> arguments) {
- super(id, project, description, comment, STRUCTURAL_CHANGE | MULTI_CHANGE);
- mArguments = arguments;
- }
-
- public Map<String, String> getArguments() {
- return mArguments;
- }
-
- protected abstract Refactoring createRefactoring(Map<String, String> args);
-
- @Override
- public Refactoring createRefactoring(RefactoringStatus status) throws CoreException {
- try {
- return createRefactoring(mArguments);
- } catch (NullPointerException e) {
- status.addFatalError("Failed to recreate refactoring from descriptor");
- return null;
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/VisualRefactoringAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/VisualRefactoringAction.java
deleted file mode 100644
index f1cc988d7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/VisualRefactoringAction.java
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.CanvasViewInfo;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ITreeSelection;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-import org.eclipse.ui.part.FileEditorInput;
-
-abstract class VisualRefactoringAction implements IWorkbenchWindowActionDelegate {
- protected IWorkbenchWindow mWindow;
- protected ITextSelection mTextSelection;
- protected ITreeSelection mTreeSelection;
- protected LayoutEditorDelegate mDelegate;
- protected IFile mFile;
-
- /**
- * Keep track of the current workbench window.
- */
- @Override
- public void init(IWorkbenchWindow window) {
- mWindow = window;
- }
-
- @Override
- public void dispose() {
- }
-
- /**
- * Examine the selection to determine if the action should be enabled or not.
- * <p/>
- * Keep a link to the relevant selection structure
- */
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
- // Look for selections in XML and in the layout UI editor
-
- // Note, two kinds of selections are returned here:
- // ITextSelection on a Java source window
- // IStructuredSelection in the outline or navigator
- // This simply deals with the refactoring based on a non-empty selection.
- // At that point, just enable the action and later decide if it's valid when it actually
- // runs since we don't have access to the AST yet.
-
- mTextSelection = null;
- mTreeSelection = null;
- mFile = null;
-
- IEditorPart editor = null;
-
- if (selection instanceof ITextSelection) {
- mTextSelection = (ITextSelection) selection;
- editor = AdtUtils.getActiveEditor();
- mFile = getSelectedFile(editor);
- } else if (selection instanceof ITreeSelection) {
- Object firstElement = ((ITreeSelection)selection).getFirstElement();
- if (firstElement instanceof CanvasViewInfo) {
- mTreeSelection = (ITreeSelection) selection;
- editor = AdtUtils.getActiveEditor();
- mFile = getSelectedFile(editor);
- }
- }
-
- mDelegate = LayoutEditorDelegate.fromEditor(editor);
-
- action.setEnabled((mTextSelection != null || mTreeSelection != null)
- && mFile != null && mDelegate != null);
- }
-
- /**
- * Create a new instance of our refactoring and a wizard to configure it.
- */
- @Override
- public abstract void run(IAction action);
-
- /**
- * Returns the active {@link IFile} (hopefully matching our selection) or null.
- * The file is only returned if it's a file from a project with an Android nature.
- * <p/>
- * At that point we do not try to analyze if the selection nor the file is suitable
- * for the refactoring. This check is performed when the refactoring is invoked since
- * it can then produce meaningful error messages as needed.
- */
- private IFile getSelectedFile(IEditorPart editor) {
- if (editor != null) {
- IEditorInput input = editor.getEditorInput();
-
- if (input instanceof FileEditorInput) {
- FileEditorInput fi = (FileEditorInput) input;
- IFile file = fi.getFile();
- if (file.exists()) {
- IProject proj = file.getProject();
- try {
- if (proj != null && proj.hasNature(AdtConstants.NATURE_DEFAULT)) {
- return file;
- }
- } catch (CoreException e) {
- // ignore
- }
- }
- }
- }
-
- return null;
- }
-
- public static IAction create(String title, LayoutEditorDelegate editorDelegate,
- Class<? extends VisualRefactoringAction> clz) {
- return new ActionWrapper(title, editorDelegate, clz);
- }
-
- private static class ActionWrapper extends Action {
- private Class<? extends VisualRefactoringAction> mClass;
- private LayoutEditorDelegate mEditorDelegate;
-
- ActionWrapper(String title, LayoutEditorDelegate editorDelegate,
- Class<? extends VisualRefactoringAction> clz) {
- super(title);
- mEditorDelegate = editorDelegate;
- mClass = clz;
- }
-
- @Override
- public void run() {
- VisualRefactoringAction action;
- try {
- action = mClass.newInstance();
- } catch (Exception e) {
- AdtPlugin.log(e, null);
- return;
- }
- IEditorSite site = mEditorDelegate.getEditor().getEditorSite();
- action.init(site.getWorkbenchWindow());
- ISelection selection = site.getSelectionProvider().getSelection();
- action.selectionChanged(ActionWrapper.this, selection);
- if (isEnabled()) {
- action.run(ActionWrapper.this);
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/VisualRefactoringWizard.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/VisualRefactoringWizard.java
deleted file mode 100644
index c103e47dc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/VisualRefactoringWizard.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-
-public abstract class VisualRefactoringWizard extends RefactoringWizard {
- protected final LayoutEditorDelegate mDelegate;
-
- public VisualRefactoringWizard(Refactoring refactoring, LayoutEditorDelegate editor) {
- super(refactoring, DIALOG_BASED_USER_INTERFACE | PREVIEW_EXPAND_FIRST_NODE);
- mDelegate = editor;
- }
-
- @Override
- public boolean performFinish() {
- mDelegate.getEditor().setIgnoreXmlUpdate(true);
- try {
- return super.performFinish();
- } finally {
- mDelegate.getEditor().setIgnoreXmlUpdate(false);
- mDelegate.refreshXmlModel();
- }
- }
-
- protected abstract static class VisualRefactoringInputPage extends UserInputWizardPage {
- public VisualRefactoringInputPage(String name) {
- super(name);
- }
-
- /**
- * Listener which can be attached on any widget in the wizard page to force
- * modifications of the associated widget to validate the page again
- */
- protected ModifyListener mModifyValidateListener = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- validatePage();
- }
- };
-
- /**
- * Listener which can be attached on any widget in the wizard page to force
- * selection changes of the associated widget to validate the page again
- */
- protected SelectionAdapter mSelectionValidateListener = new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- validatePage();
- }
- };
-
- protected abstract boolean validatePage();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/WrapInAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/WrapInAction.java
deleted file mode 100644
index 1cd66596b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/WrapInAction.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
-
-/**
- * Action executed when the "Wrap In" menu item is invoked.
- */
-public class WrapInAction extends VisualRefactoringAction {
- @Override
- public void run(IAction action) {
- if ((mTextSelection != null || mTreeSelection != null) && mFile != null) {
- WrapInRefactoring ref = new WrapInRefactoring(mFile, mDelegate,
- mTextSelection, mTreeSelection);
- RefactoringWizard wizard = new WrapInWizard(ref, mDelegate);
- RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation(wizard);
- try {
- op.run(mWindow.getShell(), wizard.getDefaultPageTitle());
- } catch (InterruptedException e) {
- // Interrupted. Pass.
- }
- }
- }
-
- public static IAction create(LayoutEditorDelegate editorDelegate) {
- return create("Wrap in Container...", editorDelegate, WrapInAction.class);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/WrapInContribution.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/WrapInContribution.java
deleted file mode 100644
index 61d7987d7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/WrapInContribution.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import org.eclipse.ltk.core.refactoring.RefactoringContribution;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-
-import java.util.Map;
-
-public class WrapInContribution extends RefactoringContribution {
-
- @SuppressWarnings("unchecked")
- @Override
- public RefactoringDescriptor createDescriptor(String id, String project, String description,
- String comment, Map arguments, int flags) throws IllegalArgumentException {
- return new WrapInRefactoring.Descriptor(project, description, comment, arguments);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public Map retrieveArgumentMap(RefactoringDescriptor descriptor) {
- if (descriptor instanceof WrapInRefactoring.Descriptor) {
- return ((WrapInRefactoring.Descriptor) descriptor).getArguments();
- }
- return super.retrieveArgumentMap(descriptor);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/WrapInRefactoring.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/WrapInRefactoring.java
deleted file mode 100644
index 07b00b8da..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/WrapInRefactoring.java
+++ /dev/null
@@ -1,439 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import static com.android.SdkConstants.ANDROID_NS_NAME_PREFIX;
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ANDROID_WIDGET_PREFIX;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.EXT_XML;
-import static com.android.SdkConstants.VALUE_FILL_PARENT;
-import static com.android.SdkConstants.VALUE_MATCH_PARENT;
-import static com.android.SdkConstants.VALUE_WRAP_CONTENT;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.VisibleForTesting;
-import com.android.ide.common.xml.XmlFormatStyle;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.CanvasViewInfo;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ITreeSelection;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.text.edits.DeleteEdit;
-import org.eclipse.text.edits.InsertEdit;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Element;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Inserts a new layout surrounding the current selection, migrates namespace
- * attributes (if wrapping the root node), and optionally migrates layout
- * attributes and updates references elsewhere.
- */
-@SuppressWarnings("restriction") // XML model
-public class WrapInRefactoring extends VisualRefactoring {
- private static final String KEY_ID = "name"; //$NON-NLS-1$
- private static final String KEY_TYPE = "type"; //$NON-NLS-1$
-
- private String mId;
- private String mTypeFqcn;
- private String mInitializedAttributes;
-
- /**
- * This constructor is solely used by {@link Descriptor},
- * to replay a previous refactoring.
- * @param arguments argument map created by #createArgumentMap.
- */
- WrapInRefactoring(Map<String, String> arguments) {
- super(arguments);
- mId = arguments.get(KEY_ID);
- mTypeFqcn = arguments.get(KEY_TYPE);
- }
-
- public WrapInRefactoring(
- IFile file,
- LayoutEditorDelegate delegate,
- ITextSelection selection,
- ITreeSelection treeSelection) {
- super(file, delegate, selection, treeSelection);
- }
-
- @VisibleForTesting
- WrapInRefactoring(List<Element> selectedElements, LayoutEditorDelegate editor) {
- super(selectedElements, editor);
- }
-
- @Override
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException,
- OperationCanceledException {
- RefactoringStatus status = new RefactoringStatus();
-
- try {
- pm.beginTask("Checking preconditions...", 6);
-
- if (mSelectionStart == -1 || mSelectionEnd == -1) {
- status.addFatalError("No selection to wrap");
- return status;
- }
-
- // Make sure the selection is contiguous
- if (mTreeSelection != null) {
- // TODO - don't do this if we based the selection on text. In this case,
- // make sure we're -balanced-.
-
- List<CanvasViewInfo> infos = getSelectedViewInfos();
- if (!validateNotEmpty(infos, status)) {
- return status;
- }
-
- // Enforce that the selection is -contiguous-
- if (!validateContiguous(infos, status)) {
- return status;
- }
- }
-
- // Ensures that we have a valid DOM model:
- if (mElements.size() == 0) {
- status.addFatalError("Nothing to wrap");
- return status;
- }
-
- pm.worked(1);
- return status;
-
- } finally {
- pm.done();
- }
- }
-
- @Override
- protected VisualRefactoringDescriptor createDescriptor() {
- String comment = getName();
- return new Descriptor(
- mProject.getName(), //project
- comment, //description
- comment, //comment
- createArgumentMap());
- }
-
- @Override
- protected Map<String, String> createArgumentMap() {
- Map<String, String> args = super.createArgumentMap();
- args.put(KEY_TYPE, mTypeFqcn);
- args.put(KEY_ID, mId);
-
- return args;
- }
-
- @Override
- public String getName() {
- return "Wrap in Container";
- }
-
- void setId(String id) {
- mId = id;
- }
-
- void setType(String typeFqcn) {
- mTypeFqcn = typeFqcn;
- }
-
- void setInitializedAttributes(String initializedAttributes) {
- mInitializedAttributes = initializedAttributes;
- }
-
- @Override
- protected @NonNull List<Change> computeChanges(IProgressMonitor monitor) {
- // (1) Insert the new container in front of the beginning of the
- // first wrapped view
- // (2) If the container is the new root, transfer namespace declarations
- // to it
- // (3) Insert the closing tag of the new container at the end of the
- // last wrapped view
- // (4) Reindent the wrapped views
- // (5) If the user requested it, update all layout references to the
- // wrapped views with the new container?
- // For that matter, does RelativeLayout even require it? Probably not,
- // it can point inside the current layout...
-
- // Add indent to all lines between mSelectionStart and mEnd
- // TODO: Figure out the indentation amount?
- // For now, use 4 spaces
- String indentUnit = " "; //$NON-NLS-1$
- boolean separateAttributes = true;
- IStructuredDocument document = mDelegate.getEditor().getStructuredDocument();
- String startIndent = AndroidXmlEditor.getIndentAtOffset(document, mSelectionStart);
-
- String viewClass = getViewClass(mTypeFqcn);
- String androidNsPrefix = getAndroidNamespacePrefix();
-
-
- IFile file = mDelegate.getEditor().getInputFile();
- List<Change> changes = new ArrayList<Change>();
- if (file == null) {
- return changes;
- }
- TextFileChange change = new TextFileChange(file.getName(), file);
- MultiTextEdit rootEdit = new MultiTextEdit();
- change.setTextType(EXT_XML);
-
- String id = ensureNewId(mId);
-
- // Update any layout references to the old id with the new id
- if (id != null) {
- String rootId = getRootId();
- IStructuredModel model = mDelegate.getEditor().getModelForRead();
- try {
- IStructuredDocument doc = model.getStructuredDocument();
- if (doc != null) {
- List<TextEdit> replaceIds = replaceIds(androidNsPrefix,
- doc, mSelectionStart, mSelectionEnd, rootId, id);
- for (TextEdit edit : replaceIds) {
- rootEdit.addChild(edit);
- }
- }
- } finally {
- model.releaseFromRead();
- }
- }
-
- // Insert namespace elements?
- StringBuilder namespace = null;
- List<DeleteEdit> deletions = new ArrayList<DeleteEdit>();
- Element primary = getPrimaryElement();
- if (primary != null && getDomDocument().getDocumentElement() == primary) {
- namespace = new StringBuilder();
-
- List<Attr> declarations = findNamespaceAttributes(primary);
- for (Attr attribute : declarations) {
- if (attribute instanceof IndexedRegion) {
- // Delete the namespace declaration in the node which is no longer the root
- IndexedRegion region = (IndexedRegion) attribute;
- int startOffset = region.getStartOffset();
- int endOffset = region.getEndOffset();
- String text = getText(startOffset, endOffset);
- DeleteEdit deletion = new DeleteEdit(startOffset, endOffset - startOffset);
- deletions.add(deletion);
- rootEdit.addChild(deletion);
- text = text.trim();
-
- // Insert the namespace declaration in the new root
- if (separateAttributes) {
- namespace.append('\n').append(startIndent).append(indentUnit);
- } else {
- namespace.append(' ');
- }
- namespace.append(text);
- }
- }
- }
-
- // Insert begin tag: <type ...>
- StringBuilder sb = new StringBuilder();
- sb.append('<');
- sb.append(viewClass);
-
- if (namespace != null) {
- sb.append(namespace);
- }
-
- // Set the ID if any
- if (id != null) {
- if (separateAttributes) {
- sb.append('\n').append(startIndent).append(indentUnit);
- } else {
- sb.append(' ');
- }
- sb.append(androidNsPrefix).append(':');
- sb.append(ATTR_ID).append('=').append('"').append(id).append('"');
- }
-
- // If any of the elements are fill/match parent, use that instead
- String width = VALUE_WRAP_CONTENT;
- String height = VALUE_WRAP_CONTENT;
-
- for (Element element : getElements()) {
- String oldWidth = element.getAttributeNS(ANDROID_URI, ATTR_LAYOUT_WIDTH);
- String oldHeight = element.getAttributeNS(ANDROID_URI, ATTR_LAYOUT_HEIGHT);
-
- if (VALUE_MATCH_PARENT.equals(oldWidth) || VALUE_FILL_PARENT.equals(oldWidth)) {
- width = oldWidth;
- }
- if (VALUE_MATCH_PARENT.equals(oldHeight) || VALUE_FILL_PARENT.equals(oldHeight)) {
- height = oldHeight;
- }
- }
-
- // Add in width/height.
- if (separateAttributes) {
- sb.append('\n').append(startIndent).append(indentUnit);
- } else {
- sb.append(' ');
- }
- sb.append(androidNsPrefix).append(':');
- sb.append(ATTR_LAYOUT_WIDTH).append('=').append('"').append(width).append('"');
-
- if (separateAttributes) {
- sb.append('\n').append(startIndent).append(indentUnit);
- } else {
- sb.append(' ');
- }
- sb.append(androidNsPrefix).append(':');
- sb.append(ATTR_LAYOUT_HEIGHT).append('=').append('"').append(height).append('"');
-
- if (mInitializedAttributes != null && mInitializedAttributes.length() > 0) {
- for (String s : mInitializedAttributes.split(",")) { //$NON-NLS-1$
- sb.append(' ');
- String[] nameValue = s.split("="); //$NON-NLS-1$
- String name = nameValue[0];
- String value = nameValue[1];
- if (name.startsWith(ANDROID_NS_NAME_PREFIX)) {
- name = name.substring(ANDROID_NS_NAME_PREFIX.length());
- sb.append(androidNsPrefix).append(':');
- }
- sb.append(name).append('=').append('"').append(value).append('"');
- }
- }
-
- // Transfer layout_ attributes (other than width and height)
- if (primary != null) {
- List<Attr> layoutAttributes = findLayoutAttributes(primary);
- for (Attr attribute : layoutAttributes) {
- String name = attribute.getLocalName();
- if ((name.equals(ATTR_LAYOUT_WIDTH) || name.equals(ATTR_LAYOUT_HEIGHT))
- && ANDROID_URI.equals(attribute.getNamespaceURI())) {
- // Already handled specially
- continue;
- }
-
- if (attribute instanceof IndexedRegion) {
- IndexedRegion region = (IndexedRegion) attribute;
- int startOffset = region.getStartOffset();
- int endOffset = region.getEndOffset();
- String text = getText(startOffset, endOffset);
- DeleteEdit deletion = new DeleteEdit(startOffset, endOffset - startOffset);
- rootEdit.addChild(deletion);
- deletions.add(deletion);
-
- if (separateAttributes) {
- sb.append('\n').append(startIndent).append(indentUnit);
- } else {
- sb.append(' ');
- }
- sb.append(text.trim());
- }
- }
- }
-
- // Finish open tag:
- sb.append('>');
- sb.append('\n').append(startIndent).append(indentUnit);
-
- InsertEdit beginEdit = new InsertEdit(mSelectionStart, sb.toString());
- rootEdit.addChild(beginEdit);
-
- String nested = getText(mSelectionStart, mSelectionEnd);
- int index = 0;
- while (index != -1) {
- index = nested.indexOf('\n', index);
- if (index != -1) {
- index++;
- InsertEdit newline = new InsertEdit(mSelectionStart + index, indentUnit);
- // Some of the deleted namespaces may have had newlines - be careful
- // not to overlap edits
- boolean covered = false;
- for (DeleteEdit deletion : deletions) {
- if (deletion.covers(newline)) {
- covered = true;
- break;
- }
- }
- if (!covered) {
- rootEdit.addChild(newline);
- }
- }
- }
-
- // Insert end tag: </type>
- sb.setLength(0);
- sb.append('\n').append(startIndent);
- sb.append('<').append('/').append(viewClass).append('>');
- InsertEdit endEdit = new InsertEdit(mSelectionEnd, sb.toString());
- rootEdit.addChild(endEdit);
-
- if (AdtPrefs.getPrefs().getFormatGuiXml()) {
- MultiTextEdit formatted = reformat(rootEdit, XmlFormatStyle.LAYOUT);
- if (formatted != null) {
- rootEdit = formatted;
- }
- }
-
- change.setEdit(rootEdit);
- changes.add(change);
- return changes;
- }
-
- String getOldType() {
- Element primary = getPrimaryElement();
- if (primary != null) {
- String oldType = primary.getTagName();
- if (oldType.indexOf('.') == -1) {
- oldType = ANDROID_WIDGET_PREFIX + oldType;
- }
- return oldType;
- }
-
- return null;
- }
-
- @Override
- VisualRefactoringWizard createWizard() {
- return new WrapInWizard(this, mDelegate);
- }
-
- public static class Descriptor extends VisualRefactoringDescriptor {
- public Descriptor(String project, String description, String comment,
- Map<String, String> arguments) {
- super("com.android.ide.eclipse.adt.refactoring.wrapin", //$NON-NLS-1$
- project, description, comment, arguments);
- }
-
- @Override
- protected Refactoring createRefactoring(Map<String, String> args) {
- return new WrapInRefactoring(args);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/WrapInWizard.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/WrapInWizard.java
deleted file mode 100644
index 2e06a3bbd..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/WrapInWizard.java
+++ /dev/null
@@ -1,268 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import static com.android.SdkConstants.FQCN_GESTURE_OVERLAY_VIEW;
-import static com.android.SdkConstants.FQCN_LINEAR_LAYOUT;
-import static com.android.SdkConstants.FQCN_RADIO_BUTTON;
-import static com.android.SdkConstants.GESTURE_OVERLAY_VIEW;
-import static com.android.SdkConstants.RADIO_GROUP;
-import static com.android.SdkConstants.VIEW_INCLUDE;
-
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.CustomViewFinder;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.PaletteMetadataDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.ViewMetadataRepository;
-import com.android.ide.eclipse.adt.internal.resources.ResourceNameValidator;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.resources.ResourceType;
-import com.android.sdklib.IAndroidTarget;
-import com.android.utils.Pair;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-
-public class WrapInWizard extends VisualRefactoringWizard {
- private static final String SEPARATOR_LABEL =
- "----------------------------------------"; //$NON-NLS-1$
-
- public WrapInWizard(WrapInRefactoring ref, LayoutEditorDelegate editor) {
- super(ref, editor);
- setDefaultPageTitle("Wrap in Container");
- }
-
- @Override
- protected void addUserInputPages() {
- WrapInRefactoring ref = (WrapInRefactoring) getRefactoring();
- String oldType = ref.getOldType();
- addPage(new InputPage(mDelegate.getEditor().getProject(), oldType));
- }
-
- /** Wizard page which inputs parameters for the {@link WrapInRefactoring} operation */
- private static class InputPage extends VisualRefactoringInputPage {
- private final IProject mProject;
- private final String mOldType;
- private Text mIdText;
- private Combo mTypeCombo;
- private List<Pair<String, ViewElementDescriptor>> mClassNames;
-
- public InputPage(IProject project, String oldType) {
- super("WrapInInputPage"); //$NON-NLS-1$
- mProject = project;
- mOldType = oldType;
- }
-
- @Override
- public void createControl(Composite parent) {
- Composite composite = new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(2, false));
-
- Label typeLabel = new Label(composite, SWT.NONE);
- typeLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- typeLabel.setText("Type of Container:");
-
- mTypeCombo = new Combo(composite, SWT.READ_ONLY);
- mTypeCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- mTypeCombo.addSelectionListener(mSelectionValidateListener);
-
- Label idLabel = new Label(composite, SWT.NONE);
- idLabel.setText("New Layout Id:");
- idLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
-
- mIdText = new Text(composite, SWT.BORDER);
- mIdText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- mIdText.addModifyListener(mModifyValidateListener);
-
- Set<String> exclude = Collections.singleton(VIEW_INCLUDE);
- mClassNames = addLayouts(mProject, mOldType, mTypeCombo, exclude, true);
- mTypeCombo.select(0);
-
- setControl(composite);
- validatePage();
-
- mTypeCombo.setFocus();
- }
-
- @Override
- protected boolean validatePage() {
- boolean ok = true;
-
- String id = mIdText.getText().trim();
-
- if (id.length() == 0) {
- setErrorMessage("ID required");
- ok = false;
- } else {
- // ...but if you do, it has to be valid!
- ResourceNameValidator validator = ResourceNameValidator.create(false, mProject,
- ResourceType.ID);
- String message = validator.isValid(id);
- if (message != null) {
- setErrorMessage(message);
- ok = false;
- }
- }
-
- int selectionIndex = mTypeCombo.getSelectionIndex();
- String type = selectionIndex != -1 ? mClassNames.get(selectionIndex).getFirst() : null;
- if (type == null) {
- setErrorMessage("Select a container type");
- ok = false; // The user has chosen a separator
- }
-
- if (ok) {
- setErrorMessage(null);
-
- // Record state
- WrapInRefactoring refactoring =
- (WrapInRefactoring) getRefactoring();
- refactoring.setId(id);
- refactoring.setType(type);
-
- ViewElementDescriptor descriptor = mClassNames.get(selectionIndex).getSecond();
- if (descriptor instanceof PaletteMetadataDescriptor) {
- PaletteMetadataDescriptor paletteDescriptor =
- (PaletteMetadataDescriptor) descriptor;
- String initializedAttributes = paletteDescriptor.getInitializedAttributes();
- refactoring.setInitializedAttributes(initializedAttributes);
- } else {
- refactoring.setInitializedAttributes(null);
- }
- }
-
- setPageComplete(ok);
- return ok;
- }
- }
-
- static List<Pair<String, ViewElementDescriptor>> addLayouts(IProject project,
- String oldType, Combo combo,
- Set<String> exclude, boolean addGestureOverlay) {
- List<Pair<String, ViewElementDescriptor>> classNames =
- new ArrayList<Pair<String, ViewElementDescriptor>>();
-
- if (oldType != null && oldType.equals(FQCN_RADIO_BUTTON)) {
- combo.add(RADIO_GROUP);
- // NOT a fully qualified name since android widgets do not include the package
- classNames.add(Pair.of(RADIO_GROUP, (ViewElementDescriptor) null));
-
- combo.add(SEPARATOR_LABEL);
- classNames.add(Pair.<String,ViewElementDescriptor>of(null, null));
- }
-
- Pair<List<String>,List<String>> result = CustomViewFinder.findViews(project, true);
- List<String> customViews = result.getFirst();
- List<String> thirdPartyViews = result.getSecond();
- if (customViews.size() > 0) {
- for (String view : customViews) {
- combo.add(view);
- classNames.add(Pair.of(view, (ViewElementDescriptor) null));
- }
- combo.add(SEPARATOR_LABEL);
- classNames.add(Pair.<String,ViewElementDescriptor>of(null, null));
- }
-
- // Populate type combo
- Sdk currentSdk = Sdk.getCurrent();
- if (currentSdk != null) {
- IAndroidTarget target = currentSdk.getTarget(project);
- if (target != null) {
- AndroidTargetData targetData = currentSdk.getTargetData(target);
- if (targetData != null) {
- ViewMetadataRepository repository = ViewMetadataRepository.get();
- List<Pair<String,List<ViewElementDescriptor>>> entries =
- repository.getPaletteEntries(targetData, false, true);
- // Find the layout category - it contains LinearLayout
- List<ViewElementDescriptor> layoutDescriptors = null;
-
- search: for (Pair<String,List<ViewElementDescriptor>> pair : entries) {
- List<ViewElementDescriptor> list = pair.getSecond();
- for (ViewElementDescriptor d : list) {
- if (d.getFullClassName().equals(FQCN_LINEAR_LAYOUT)) {
- // Found - use this list
- layoutDescriptors = list;
- break search;
- }
- }
- }
- if (layoutDescriptors != null) {
- for (ViewElementDescriptor d : layoutDescriptors) {
- String className = d.getFullClassName();
- if (exclude == null || !exclude.contains(className)) {
- combo.add(d.getUiName());
- classNames.add(Pair.of(className, d));
- }
- }
-
- // SWT does not support separators in combo boxes
- combo.add(SEPARATOR_LABEL);
- classNames.add(null);
-
- if (thirdPartyViews.size() > 0) {
- for (String view : thirdPartyViews) {
- combo.add(view);
- classNames.add(Pair.of(view, (ViewElementDescriptor) null));
- }
- combo.add(SEPARATOR_LABEL);
- classNames.add(null);
- }
-
- if (addGestureOverlay) {
- combo.add(GESTURE_OVERLAY_VIEW);
- classNames.add(Pair.<String, ViewElementDescriptor> of(
- FQCN_GESTURE_OVERLAY_VIEW, null));
-
- combo.add(SEPARATOR_LABEL);
- classNames.add(Pair.<String,ViewElementDescriptor>of(null, null));
- }
- }
-
- // Now add ALL known layout descriptors in case the user has
- // a special case
- layoutDescriptors =
- targetData.getLayoutDescriptors().getLayoutDescriptors();
-
- for (ViewElementDescriptor d : layoutDescriptors) {
- String className = d.getFullClassName();
- if (exclude == null || !exclude.contains(className)) {
- combo.add(d.getUiName());
- classNames.add(Pair.of(className, d));
- }
- }
- }
- }
- } else {
- combo.add("SDK not initialized");
- classNames.add(Pair.<String,ViewElementDescriptor>of(null, null));
- }
-
- return classNames;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/uimodel/UiViewElementNode.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/uimodel/UiViewElementNode.java
deleted file mode 100644
index d9d272224..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/layout/uimodel/UiViewElementNode.java
+++ /dev/null
@@ -1,208 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.uimodel;
-
-import static com.android.SdkConstants.ANDROID_NS_NAME;
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_CLASS;
-import static com.android.SdkConstants.ATTR_ORIENTATION;
-import static com.android.SdkConstants.FQCN_FRAME_LAYOUT;
-import static com.android.SdkConstants.LINEAR_LAYOUT;
-import static com.android.SdkConstants.VALUE_VERTICAL;
-import static com.android.SdkConstants.VIEW_TAG;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.XmlnsAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.LayoutDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiDocumentNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.sdklib.IAndroidTarget;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.swt.graphics.Image;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-/**
- * Specialized version of {@link UiElementNode} for the {@link ViewElementDescriptor}s.
- */
-public class UiViewElementNode extends UiElementNode {
-
- /** An AttributeDescriptor array that depends on the current UiParent. */
- private AttributeDescriptor[] mCachedAttributeDescriptors;
-
- public UiViewElementNode(ViewElementDescriptor elementDescriptor) {
- super(elementDescriptor);
- }
-
- /**
- * Returns an AttributeDescriptor array that depends on the current UiParent.
- * <p/>
- * The array merges both "direct" attributes with the descriptor layout attributes.
- * The array instance is cached and cleared if the UiParent is changed.
- */
- @Override
- public AttributeDescriptor[] getAttributeDescriptors() {
- if (!getDescriptor().syncAttributes()) {
- mCachedAttributeDescriptors = null;
- }
- if (mCachedAttributeDescriptors != null) {
- return mCachedAttributeDescriptors;
- }
-
- UiElementNode ui_parent = getUiParent();
- AttributeDescriptor[] direct_attrs = super.getAttributeDescriptors();
- mCachedAttributeDescriptors = direct_attrs;
-
- // Compute layout attributes: These depend on the *parent* this widget is within
- AttributeDescriptor[] layout_attrs = null;
- boolean need_xmlns = false;
-
- if (ui_parent instanceof UiDocumentNode) {
- // Limitation: right now the layout behaves as if everything was
- // owned by a FrameLayout.
- // TODO replace by something user-configurable.
-
- IProject project = getEditor().getProject();
- if (project != null) {
- Sdk currentSdk = Sdk.getCurrent();
- if (currentSdk != null) {
- IAndroidTarget target = currentSdk.getTarget(project);
- if (target != null) {
- AndroidTargetData data = currentSdk.getTargetData(target);
- if (data != null) {
- LayoutDescriptors descriptors = data.getLayoutDescriptors();
- ViewElementDescriptor desc =
- descriptors.findDescriptorByClass(FQCN_FRAME_LAYOUT);
- if (desc != null) {
- layout_attrs = desc.getLayoutAttributes();
- need_xmlns = true;
- }
- }
- }
- }
- }
- } else if (ui_parent instanceof UiViewElementNode) {
- layout_attrs =
- ((ViewElementDescriptor) ui_parent.getDescriptor()).getLayoutAttributes();
- }
-
- if (layout_attrs == null || layout_attrs.length == 0) {
- return mCachedAttributeDescriptors;
- }
-
- mCachedAttributeDescriptors =
- new AttributeDescriptor[direct_attrs.length +
- layout_attrs.length +
- (need_xmlns ? 1 : 0)];
- System.arraycopy(direct_attrs, 0,
- mCachedAttributeDescriptors, 0,
- direct_attrs.length);
- System.arraycopy(layout_attrs, 0,
- mCachedAttributeDescriptors, direct_attrs.length,
- layout_attrs.length);
- if (need_xmlns) {
- AttributeDescriptor desc = new XmlnsAttributeDescriptor(ANDROID_NS_NAME, ANDROID_URI);
- mCachedAttributeDescriptors[direct_attrs.length + layout_attrs.length] = desc;
- }
-
- return mCachedAttributeDescriptors;
- }
-
- public Image getIcon() {
- ElementDescriptor desc = getDescriptor();
- if (desc != null) {
- Image img = null;
- // Special case for the common case of vertical linear layouts:
- // show vertical linear icon (the default icon shows horizontal orientation)
- String uiName = desc.getUiName();
- IconFactory icons = IconFactory.getInstance();
- if (uiName.equals(LINEAR_LAYOUT)) {
- Element e = (Element) getXmlNode();
- if (VALUE_VERTICAL.equals(e.getAttributeNS(ANDROID_URI, ATTR_ORIENTATION))) {
- IconFactory factory = icons;
- img = factory.getIcon("VerticalLinearLayout"); //$NON-NLS-1$
- }
- } else if (uiName.equals(VIEW_TAG)) {
- Node xmlNode = getXmlNode();
- if (xmlNode instanceof Element) {
- String className = ((Element) xmlNode).getAttribute(ATTR_CLASS);
- if (className != null && className.length() > 0) {
- int index = className.lastIndexOf('.');
- if (index != -1) {
- className = "customView"; //$NON-NLS-1$
- }
- img = icons.getIcon(className);
- }
- }
-
- if (img == null) {
- // Can't have both view.png and View.png; issues on case sensitive vs
- // case insensitive file systems
- img = icons.getIcon("View"); //$NON-NLS-1$
- }
- }
- if (img == null) {
- img = desc.getGenericIcon();
- }
-
- if (img != null) {
- AndroidXmlEditor editor = getEditor();
- if (editor != null) {
- LayoutEditorDelegate delegate = LayoutEditorDelegate.fromEditor(editor);
- if (delegate != null) {
- IMarker marker = delegate.getIssueForNode(this);
- if (marker != null) {
- int severity = marker.getAttribute(IMarker.SEVERITY, 0);
- if (severity == IMarker.SEVERITY_ERROR) {
- return icons.addErrorIcon(img);
- } else {
- return icons.addWarningIcon(img);
- }
- }
- }
- }
-
- return img;
- }
-
- return img;
- }
-
- return AdtPlugin.getAndroidLogo();
- }
-
- /**
- * Sets the parent of this UI node.
- * <p/>
- * Also removes the cached AttributeDescriptor array that depends on the current UiParent.
- */
- @Override
- protected void setUiParent(UiElementNode parent) {
- super.setUiParent(parent);
- mCachedAttributeDescriptors = null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/ManifestContentAssist.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/ManifestContentAssist.java
deleted file mode 100644
index 1492adbb7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/ManifestContentAssist.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest;
-
-import static com.android.xml.AndroidManifest.ATTRIBUTE_MIN_SDK_VERSION;
-import static com.android.xml.AndroidManifest.ATTRIBUTE_TARGET_SDK_VERSION;
-
-import com.android.annotations.VisibleForTesting;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.AndroidContentAssist;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.sdklib.AndroidVersion;
-import com.android.sdklib.IAndroidTarget;
-import com.android.utils.Pair;
-
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.w3c.dom.Node;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Content Assist Processor for AndroidManifest.xml
- */
-@VisibleForTesting
-public final class ManifestContentAssist extends AndroidContentAssist {
-
- /**
- * Constructor for ManifestContentAssist
- */
- public ManifestContentAssist() {
- super(AndroidTargetData.DESCRIPTOR_MANIFEST);
- }
-
- @Override
- protected boolean computeAttributeValues(List<ICompletionProposal> proposals, int offset,
- String parentTagName, String attributeName, Node node, String wordPrefix,
- boolean skipEndTag, int replaceLength) {
- if (attributeName.endsWith(ATTRIBUTE_MIN_SDK_VERSION)
- || attributeName.endsWith(ATTRIBUTE_TARGET_SDK_VERSION)) {
- // The user is completing the minSdkVersion attribute: it should be
- // an integer for the API version, but we'll add full Android version
- // names to make it more obvious what they're selecting
-
- List<Pair<String, String>> choices = new ArrayList<Pair<String, String>>();
- int max = AdtUtils.getHighestKnownApiLevel();
- // Look for any more recent installed versions the user may have
- Sdk sdk = Sdk.getCurrent();
- if (sdk == null) {
- return false;
- }
- IAndroidTarget[] targets = sdk.getTargets();
- for (IAndroidTarget target : targets) {
- AndroidVersion version = target.getVersion();
- int apiLevel = version.getApiLevel();
- if (apiLevel > max) {
- if (version.isPreview()) {
- // Use codename, not API level, as version string for preview versions
- choices.add(Pair.of(version.getCodename(), version.getCodename()));
- } else {
- choices.add(Pair.of(Integer.toString(apiLevel), target.getFullName()));
- }
- }
- }
- for (int api = max; api >= 1; api--) {
- String name = AdtUtils.getAndroidName(api);
- choices.add(Pair.of(Integer.toString(api), name));
- }
- char needTag = 0;
- addMatchingProposals(proposals, choices.toArray(), offset, node, wordPrefix,
- needTag, true /* isAttribute */, false /* isNew */,
- skipEndTag /* skipEndTag */, replaceLength);
- return true;
- } else {
- return super.computeAttributeValues(proposals, offset, parentTagName, attributeName,
- node, wordPrefix, skipEndTag, replaceLength);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/ManifestEditor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/ManifestEditor.java
deleted file mode 100644
index 55ebf5970..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/ManifestEditor.java
+++ /dev/null
@@ -1,578 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_NAME;
-import static com.android.ide.eclipse.adt.internal.editors.manifest.descriptors.AndroidManifestDescriptors.USES_PERMISSION;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.manifest.descriptors.AndroidManifestDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.manifest.pages.ApplicationPage;
-import com.android.ide.eclipse.adt.internal.editors.manifest.pages.InstrumentationPage;
-import com.android.ide.eclipse.adt.internal.editors.manifest.pages.OverviewPage;
-import com.android.ide.eclipse.adt.internal.editors.manifest.pages.PermissionPage;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.lint.EclipseLintClient;
-import com.android.ide.eclipse.adt.internal.resources.manager.GlobalProjectMonitor;
-import com.android.ide.eclipse.adt.internal.resources.manager.GlobalProjectMonitor.IFileListener;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IMarkerDelta;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-import java.util.Collection;
-import java.util.List;
-
-/**
- * Multi-page form editor for AndroidManifest.xml.
- */
-@SuppressWarnings("restriction")
-public final class ManifestEditor extends AndroidXmlEditor {
-
- public static final String ID = AdtConstants.EDITORS_NAMESPACE + ".manifest.ManifestEditor"; //$NON-NLS-1$
-
- private final static String EMPTY = ""; //$NON-NLS-1$
-
- /** Root node of the UI element hierarchy */
- private UiElementNode mUiManifestNode;
- /** The Application Page tab */
- private ApplicationPage mAppPage;
- /** The Overview Manifest Page tab */
- private OverviewPage mOverviewPage;
- /** The Permission Page tab */
- private PermissionPage mPermissionPage;
- /** The Instrumentation Page tab */
- private InstrumentationPage mInstrumentationPage;
-
- private IFileListener mMarkerMonitor;
-
-
- /**
- * Creates the form editor for AndroidManifest.xml.
- */
- public ManifestEditor() {
- super();
- addDefaultTargetListener();
- }
-
- @Override
- public void dispose() {
- super.dispose();
-
- GlobalProjectMonitor.getMonitor().removeFileListener(mMarkerMonitor);
- }
-
- @Override
- public void activated() {
- super.activated();
- clearActionBindings(false);
- }
-
- @Override
- public void deactivated() {
- super.deactivated();
- updateActionBindings();
- }
-
- @Override
- protected void pageChange(int newPageIndex) {
- super.pageChange(newPageIndex);
- if (newPageIndex == mTextPageIndex) {
- updateActionBindings();
- } else {
- clearActionBindings(false);
- }
- }
-
- @Override
- protected int getPersistenceCategory() {
- return CATEGORY_MANIFEST;
- }
-
- /**
- * Return the root node of the UI element hierarchy, which here
- * is the "manifest" node.
- */
- @Override
- public UiElementNode getUiRootNode() {
- return mUiManifestNode;
- }
-
- /**
- * Returns the Manifest descriptors for the file being edited.
- */
- public AndroidManifestDescriptors getManifestDescriptors() {
- AndroidTargetData data = getTargetData();
- if (data != null) {
- return data.getManifestDescriptors();
- }
-
- return null;
- }
-
- // ---- Base Class Overrides ----
-
- /**
- * Returns whether the "save as" operation is supported by this editor.
- * <p/>
- * Save-As is a valid operation for the ManifestEditor since it acts on a
- * single source file.
- *
- * @see IEditorPart
- */
- @Override
- public boolean isSaveAsAllowed() {
- return true;
- }
-
- @Override
- public void doSave(IProgressMonitor monitor) {
- // Look up the current (pre-save) values of minSdkVersion and targetSdkVersion
- int prevMinSdkVersion = -1;
- int prevTargetSdkVersion = -1;
- IProject project = null;
- ManifestInfo info = null;
- try {
- project = getProject();
- if (project != null) {
- info = ManifestInfo.get(project);
- prevMinSdkVersion = info.getMinSdkVersion();
- prevTargetSdkVersion = info.getTargetSdkVersion();
- info.clear();
- }
- } catch (Throwable t) {
- // We don't expect exceptions from the above calls, but we *really*
- // need to make sure that nothing can prevent the save function from
- // getting called!
- AdtPlugin.log(t, null);
- }
-
- // Actually save
- super.doSave(monitor);
-
- // If the target/minSdkVersion has changed, clear all lint warnings (since many
- // of them are tied to the min/target sdk levels), in order to avoid showing stale
- // results
- try {
- if (info != null) {
- int newMinSdkVersion = info.getMinSdkVersion();
- int newTargetSdkVersion = info.getTargetSdkVersion();
- if (newMinSdkVersion != prevMinSdkVersion
- || newTargetSdkVersion != prevTargetSdkVersion) {
- assert project != null;
- EclipseLintClient.clearMarkers(project);
- }
- }
- } catch (Throwable t) {
- AdtPlugin.log(t, null);
- }
- }
-
- /**
- * Creates the various form pages.
- */
- @Override
- protected void createFormPages() {
- try {
- addPage(mOverviewPage = new OverviewPage(this));
- addPage(mAppPage = new ApplicationPage(this));
- addPage(mPermissionPage = new PermissionPage(this));
- addPage(mInstrumentationPage = new InstrumentationPage(this));
- } catch (PartInitException e) {
- AdtPlugin.log(e, "Error creating nested page"); //$NON-NLS-1$
- }
- }
-
- /* (non-java doc)
- * Change the tab/title name to include the project name.
- */
- @Override
- protected void setInput(IEditorInput input) {
- super.setInput(input);
- IFile inputFile = getInputFile();
- if (inputFile != null) {
- startMonitoringMarkers();
- setPartName(String.format("%1$s Manifest", inputFile.getProject().getName()));
- }
- }
-
- /**
- * Processes the new XML Model, which XML root node is given.
- *
- * @param xml_doc The XML document, if available, or null if none exists.
- */
- @Override
- protected void xmlModelChanged(Document xml_doc) {
- // create the ui root node on demand.
- initUiRootNode(false /*force*/);
-
- loadFromXml(xml_doc);
- }
-
- private void loadFromXml(Document xmlDoc) {
- mUiManifestNode.setXmlDocument(xmlDoc);
- Node node = getManifestXmlNode(xmlDoc);
-
- if (node != null) {
- // Refresh the manifest UI node and all its descendants
- mUiManifestNode.loadFromXmlNode(node);
- }
- }
-
- private Node getManifestXmlNode(Document xmlDoc) {
- if (xmlDoc != null) {
- ElementDescriptor manifestDesc = mUiManifestNode.getDescriptor();
- String manifestXmlName = manifestDesc == null ? null : manifestDesc.getXmlName();
- assert manifestXmlName != null;
-
- if (manifestXmlName != null) {
- Node node = xmlDoc.getDocumentElement();
- if (node != null && manifestXmlName.equals(node.getNodeName())) {
- return node;
- }
-
- for (node = xmlDoc.getFirstChild();
- node != null;
- node = node.getNextSibling()) {
- if (node.getNodeType() == Node.ELEMENT_NODE &&
- manifestXmlName.equals(node.getNodeName())) {
- return node;
- }
- }
- }
- }
-
- return null;
- }
-
- private void onDescriptorsChanged() {
- IStructuredModel model = getModelForRead();
- if (model != null) {
- try {
- Node node = getManifestXmlNode(getXmlDocument(model));
- mUiManifestNode.reloadFromXmlNode(node);
- } finally {
- model.releaseFromRead();
- }
- }
-
- if (mOverviewPage != null) {
- mOverviewPage.refreshUiApplicationNode();
- }
-
- if (mAppPage != null) {
- mAppPage.refreshUiApplicationNode();
- }
-
- if (mPermissionPage != null) {
- mPermissionPage.refreshUiNode();
- }
-
- if (mInstrumentationPage != null) {
- mInstrumentationPage.refreshUiNode();
- }
- }
-
- /**
- * Reads and processes the current markers and adds a listener for marker changes.
- */
- private void startMonitoringMarkers() {
- final IFile inputFile = getInputFile();
- if (inputFile != null) {
- updateFromExistingMarkers(inputFile);
-
- mMarkerMonitor = new IFileListener() {
- @Override
- public void fileChanged(@NonNull IFile file, @NonNull IMarkerDelta[] markerDeltas,
- int kind, @Nullable String extension, int flags, boolean isAndroidProject) {
- if (isAndroidProject && file.equals(inputFile)) {
- processMarkerChanges(markerDeltas);
- }
- }
- };
-
- GlobalProjectMonitor.getMonitor().addFileListener(
- mMarkerMonitor, IResourceDelta.CHANGED);
- }
- }
-
- /**
- * Processes the markers of the specified {@link IFile} and updates the error status of
- * {@link UiElementNode}s and {@link UiAttributeNode}s.
- * @param inputFile the file being edited.
- */
- private void updateFromExistingMarkers(IFile inputFile) {
- try {
- // get the markers for the file
- IMarker[] markers = inputFile.findMarkers(
- AdtConstants.MARKER_ANDROID, true, IResource.DEPTH_ZERO);
-
- AndroidManifestDescriptors desc = getManifestDescriptors();
- if (desc != null) {
- ElementDescriptor appElement = desc.getApplicationElement();
-
- if (appElement != null && mUiManifestNode != null) {
- UiElementNode appUiNode = mUiManifestNode.findUiChildNode(
- appElement.getXmlName());
- List<UiElementNode> children = appUiNode.getUiChildren();
-
- for (IMarker marker : markers) {
- processMarker(marker, children, IResourceDelta.ADDED);
- }
- }
- }
-
- } catch (CoreException e) {
- // findMarkers can throw an exception, in which case, we'll do nothing.
- }
- }
-
- /**
- * Processes a {@link IMarker} change.
- * @param markerDeltas the list of {@link IMarkerDelta}
- */
- private void processMarkerChanges(IMarkerDelta[] markerDeltas) {
- AndroidManifestDescriptors descriptors = getManifestDescriptors();
- if (descriptors != null && descriptors.getApplicationElement() != null) {
- UiElementNode app_ui_node = mUiManifestNode.findUiChildNode(
- descriptors.getApplicationElement().getXmlName());
- List<UiElementNode> children = app_ui_node.getUiChildren();
-
- for (IMarkerDelta markerDelta : markerDeltas) {
- processMarker(markerDelta.getMarker(), children, markerDelta.getKind());
- }
- }
- }
-
- /**
- * Processes a new/old/updated marker.
- * @param marker The marker being added/removed/changed
- * @param nodeList the list of activity/service/provider/receiver nodes.
- * @param kind the change kind. Can be {@link IResourceDelta#ADDED},
- * {@link IResourceDelta#REMOVED}, or {@link IResourceDelta#CHANGED}
- */
- private void processMarker(IMarker marker, List<UiElementNode> nodeList, int kind) {
- // get the data from the marker
- String nodeType = marker.getAttribute(AdtConstants.MARKER_ATTR_TYPE, EMPTY);
- if (nodeType == EMPTY) {
- return;
- }
-
- String className = marker.getAttribute(AdtConstants.MARKER_ATTR_CLASS, EMPTY);
- if (className == EMPTY) {
- return;
- }
-
- for (UiElementNode ui_node : nodeList) {
- if (ui_node.getDescriptor().getXmlName().equals(nodeType)) {
- for (UiAttributeNode attr : ui_node.getAllUiAttributes()) {
- if (attr.getDescriptor().getXmlLocalName().equals(
- AndroidManifestDescriptors.ANDROID_NAME_ATTR)) {
- if (attr.getCurrentValue().equals(className)) {
- if (kind == IResourceDelta.REMOVED) {
- attr.setHasError(false);
- } else {
- attr.setHasError(true);
- }
- return;
- }
- }
- }
- }
- }
- }
-
- /**
- * Creates the initial UI Root Node, including the known mandatory elements.
- * @param force if true, a new UiManifestNode is recreated even if it already exists.
- */
- @Override
- protected void initUiRootNode(boolean force) {
- // The manifest UI node is always created, even if there's no corresponding XML node.
- if (mUiManifestNode != null && force == false) {
- return;
- }
-
- AndroidManifestDescriptors manifestDescriptor = getManifestDescriptors();
-
- if (manifestDescriptor != null) {
- ElementDescriptor manifestElement = manifestDescriptor.getManifestElement();
- mUiManifestNode = manifestElement.createUiNode();
- mUiManifestNode.setEditor(this);
-
- // Similarly, always create the /manifest/uses-sdk followed by /manifest/application
- // (order of the elements now matters)
- ElementDescriptor element = manifestDescriptor.getUsesSdkElement();
- boolean present = false;
- for (UiElementNode ui_node : mUiManifestNode.getUiChildren()) {
- if (ui_node.getDescriptor() == element) {
- present = true;
- break;
- }
- }
- if (!present) {
- mUiManifestNode.appendNewUiChild(element);
- }
-
- element = manifestDescriptor.getApplicationElement();
- present = false;
- for (UiElementNode ui_node : mUiManifestNode.getUiChildren()) {
- if (ui_node.getDescriptor() == element) {
- present = true;
- break;
- }
- }
- if (!present) {
- mUiManifestNode.appendNewUiChild(element);
- }
-
- onDescriptorsChanged();
- } else {
- // create a dummy descriptor/uinode until we have real descriptors
- ElementDescriptor desc = new ElementDescriptor("manifest", //$NON-NLS-1$
- "temporary descriptors due to missing decriptors", //$NON-NLS-1$
- null /*tooltip*/, null /*sdk_url*/, null /*attributes*/,
- null /*children*/, false /*mandatory*/);
- mUiManifestNode = desc.createUiNode();
- mUiManifestNode.setEditor(this);
- }
- }
-
- /**
- * Adds the given set of permissions into the manifest file in the suitable
- * location
- *
- * @param permissions permission fqcn's to be added
- * @param show if true, show one or more of the newly added permissions
- */
- public void addPermissions(@NonNull final List<String> permissions, final boolean show) {
- wrapUndoEditXmlModel("Add permissions", new Runnable() {
- @Override
- public void run() {
- // Ensure that the model is current:
- initUiRootNode(true /*force*/);
- UiElementNode root = getUiRootNode();
-
- ElementDescriptor descriptor = getManifestDescriptors().getUsesPermissionElement();
- boolean shown = false;
- for (String permission : permissions) {
- // Find the first permission which sorts alphabetically laster than
- // this permission (or the last permission, if none are after in the alphabet)
- // and insert it there
- int lastPermissionIndex = -1;
- int nextPermissionIndex = -1;
- int index = 0;
- for (UiElementNode sibling : root.getUiChildren()) {
- Node node = sibling.getXmlNode();
- if (node.getNodeName().equals(USES_PERMISSION)) {
- lastPermissionIndex = index;
- String name = ((Element) node).getAttributeNS(ANDROID_URI, ATTR_NAME);
- if (permission.compareTo(name) < 0) {
- nextPermissionIndex = index;
- break;
- }
- } else if (node.getNodeName().equals("application")) { //$NON-NLS-1$
- // permissions should come before the application element
- nextPermissionIndex = index;
- break;
- }
- index++;
- }
-
- if (nextPermissionIndex != -1) {
- index = nextPermissionIndex;
- } else if (lastPermissionIndex != -1) {
- index = lastPermissionIndex + 1;
- } else {
- index = root.getUiChildren().size();
- }
- UiElementNode usesPermission = root.insertNewUiChild(index, descriptor);
- usesPermission.setAttributeValue(ATTR_NAME, ANDROID_URI, permission,
- true /*override*/);
- Node node = usesPermission.createXmlNode();
- if (show && !shown) {
- shown = true;
- if (node instanceof IndexedRegion && getInputFile() != null) {
- IndexedRegion indexedRegion = (IndexedRegion) node;
- IRegion region = new Region(indexedRegion.getStartOffset(),
- indexedRegion.getEndOffset() - indexedRegion.getStartOffset());
- try {
- AdtPlugin.openFile(getInputFile(), region, true /*show*/);
- } catch (PartInitException e) {
- AdtPlugin.log(e, null);
- }
- } else {
- show(node);
- }
- }
- }
- }
- });
- }
-
- /**
- * Removes the permissions from the manifest editor
- *
- * @param permissions the permission fqcn's to be removed
- */
- public void removePermissions(@NonNull final Collection<String> permissions) {
- wrapUndoEditXmlModel("Remove permissions", new Runnable() {
- @Override
- public void run() {
- // Ensure that the model is current:
- initUiRootNode(true /*force*/);
- UiElementNode root = getUiRootNode();
-
- for (String permission : permissions) {
- for (UiElementNode sibling : root.getUiChildren()) {
- Node node = sibling.getXmlNode();
- if (node.getNodeName().equals(USES_PERMISSION)) {
- String name = ((Element) node).getAttributeNS(ANDROID_URI, ATTR_NAME);
- if (name.equals(permission)) {
- sibling.deleteXmlNode();
- break;
- }
- }
- }
- }
- }
- });
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/ManifestEditorContributor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/ManifestEditorContributor.java
deleted file mode 100644
index 8beca30b8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/ManifestEditorContributor.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.ide.IDEActionFactory;
-import org.eclipse.ui.part.MultiPageEditorActionBarContributor;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.ITextEditorActionConstants;
-
-/**
- * Manages the installation/deinstallation of global actions for multi-page
- * editors. Responsible for the redirection of global actions to the active
- * editor. Multi-page contributor replaces the contributors for the individual
- * editors in the multi-page editor.
- *
- * TODO: Doesn't look like we need this. Remove it if not needed.
- * @deprecated
- */
-final class ManifestEditorContributor extends MultiPageEditorActionBarContributor {
- private IEditorPart mActiveEditorPart;
-
- /**
- * Creates a multi-page contributor.
- *
- * Marked as Private so it can't be instanciated. This is a cheap way to make sure
- * it's not being used. As noted in constructor, should be removed if not used.
- * @deprecated
- */
- private ManifestEditorContributor() {
- super();
- }
-
- /**
- * Returns the action registed with the given text editor.
- *
- * @return IAction or null if editor is null.
- */
- protected IAction getAction(ITextEditor editor, String actionID) {
- return (editor == null ? null : editor.getAction(actionID));
- }
-
- /*
- * (non-JavaDoc) Method declared in
- * AbstractMultiPageEditorActionBarContributor.
- */
-
- @Override
- public void setActivePage(IEditorPart part) {
- if (mActiveEditorPart == part)
- return;
-
- mActiveEditorPart = part;
-
- IActionBars actionBars = getActionBars();
- if (actionBars != null) {
-
- ITextEditor editor =
- (part instanceof ITextEditor) ? (ITextEditor)part : null;
-
- actionBars.setGlobalActionHandler(ActionFactory.DELETE.getId(),
- getAction(editor, ITextEditorActionConstants.DELETE));
- actionBars.setGlobalActionHandler(ActionFactory.UNDO.getId(),
- getAction(editor, ITextEditorActionConstants.UNDO));
- actionBars.setGlobalActionHandler(ActionFactory.REDO.getId(),
- getAction(editor, ITextEditorActionConstants.REDO));
- actionBars.setGlobalActionHandler(ActionFactory.CUT.getId(),
- getAction(editor, ITextEditorActionConstants.CUT));
- actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(),
- getAction(editor, ITextEditorActionConstants.COPY));
- actionBars.setGlobalActionHandler(ActionFactory.PASTE.getId(),
- getAction(editor, ITextEditorActionConstants.PASTE));
- actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(),
- getAction(editor, ITextEditorActionConstants.SELECT_ALL));
- actionBars.setGlobalActionHandler(ActionFactory.FIND.getId(),
- getAction(editor, ITextEditorActionConstants.FIND));
- actionBars.setGlobalActionHandler(
- IDEActionFactory.BOOKMARK.getId(), getAction(editor,
- IDEActionFactory.BOOKMARK.getId()));
- actionBars.updateActionBars();
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/ManifestInfo.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/ManifestInfo.java
deleted file mode 100644
index 6d2d1c1f2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/ManifestInfo.java
+++ /dev/null
@@ -1,957 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest;
-
-import static com.android.SdkConstants.ANDROID_STYLE_RESOURCE_PREFIX;
-import static com.android.SdkConstants.CLASS_ACTIVITY;
-import static com.android.SdkConstants.NS_RESOURCES;
-import static com.android.xml.AndroidManifest.ATTRIBUTE_ICON;
-import static com.android.xml.AndroidManifest.ATTRIBUTE_LABEL;
-import static com.android.xml.AndroidManifest.ATTRIBUTE_MIN_SDK_VERSION;
-import static com.android.xml.AndroidManifest.ATTRIBUTE_NAME;
-import static com.android.xml.AndroidManifest.ATTRIBUTE_PACKAGE;
-import static com.android.xml.AndroidManifest.ATTRIBUTE_PARENT_ACTIVITY_NAME;
-import static com.android.xml.AndroidManifest.ATTRIBUTE_SUPPORTS_RTL;
-import static com.android.xml.AndroidManifest.ATTRIBUTE_TARGET_SDK_VERSION;
-import static com.android.xml.AndroidManifest.ATTRIBUTE_THEME;
-import static com.android.xml.AndroidManifest.ATTRIBUTE_UI_OPTIONS;
-import static com.android.xml.AndroidManifest.ATTRIBUTE_VALUE;
-import static com.android.xml.AndroidManifest.NODE_ACTIVITY;
-import static com.android.xml.AndroidManifest.NODE_METADATA;
-import static com.android.xml.AndroidManifest.NODE_USES_SDK;
-import static com.android.xml.AndroidManifest.VALUE_PARENT_ACTIVITY;
-import static org.eclipse.jdt.core.search.IJavaSearchConstants.REFERENCES;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.io.IFolderWrapper;
-import com.android.io.IAbstractFile;
-import com.android.io.StreamException;
-import com.android.resources.ScreenSize;
-import com.android.sdklib.IAndroidTarget;
-import com.android.utils.Pair;
-import com.android.xml.AndroidManifest;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.QualifiedName;
-import org.eclipse.jdt.core.IField;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IMethod;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jdt.core.IPackageFragmentRoot;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.core.ITypeHierarchy;
-import org.eclipse.jdt.core.search.IJavaSearchScope;
-import org.eclipse.jdt.core.search.SearchEngine;
-import org.eclipse.jdt.core.search.SearchMatch;
-import org.eclipse.jdt.core.search.SearchParticipant;
-import org.eclipse.jdt.core.search.SearchPattern;
-import org.eclipse.jdt.core.search.SearchRequestor;
-import org.eclipse.jdt.internal.core.BinaryType;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.ui.editors.text.TextFileDocumentProvider;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
-import org.xml.sax.InputSource;
-import org.xml.sax.SAXException;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.xpath.XPathExpressionException;
-
-/**
- * Retrieves and caches manifest information such as the themes to be used for
- * a given activity.
- *
- * @see AndroidManifest
- */
-public class ManifestInfo {
-
- public static class ActivityAttributes {
- @Nullable
- private final String mIcon;
- @Nullable
- private final String mLabel;
- @NonNull
- private final String mName;
- @Nullable
- private final String mParentActivity;
- @Nullable
- private final String mTheme;
- @Nullable
- private final String mUiOptions;
-
- public ActivityAttributes(Element activity, String packageName) {
-
- // Get activity name.
- String name = activity.getAttributeNS(NS_RESOURCES, ATTRIBUTE_NAME);
- if (name == null || name.length() == 0) {
- throw new RuntimeException("Activity name cannot be empty");
- }
- int index = name.indexOf('.');
- if (index <= 0 && packageName != null && !packageName.isEmpty()) {
- name = packageName + (index == -1 ? "." : "") + name;
- }
- mName = name;
-
- // Get activity icon.
- String value = activity.getAttributeNS(NS_RESOURCES, ATTRIBUTE_ICON);
- if (value != null && value.length() > 0) {
- mIcon = value;
- } else {
- mIcon = null;
- }
-
- // Get activity label.
- value = activity.getAttributeNS(NS_RESOURCES, ATTRIBUTE_LABEL);
- if (value != null && value.length() > 0) {
- mLabel = value;
- } else {
- mLabel = null;
- }
-
- // Get activity parent. Also search the meta-data for parent info.
- value = activity.getAttributeNS(NS_RESOURCES, ATTRIBUTE_PARENT_ACTIVITY_NAME);
- if (value == null || value.length() == 0) {
- // TODO: Not sure if meta data can be used for API Level > 16
- NodeList metaData = activity.getElementsByTagName(NODE_METADATA);
- for (int j = 0, m = metaData.getLength(); j < m; j++) {
- Element data = (Element) metaData.item(j);
- String metadataName = data.getAttributeNS(NS_RESOURCES, ATTRIBUTE_NAME);
- if (VALUE_PARENT_ACTIVITY.equals(metadataName)) {
- value = data.getAttributeNS(NS_RESOURCES, ATTRIBUTE_VALUE);
- if (value != null) {
- index = value.indexOf('.');
- if (index <= 0 && packageName != null && !packageName.isEmpty()) {
- value = packageName + (index == -1 ? "." : "") + value;
- break;
- }
- }
- }
- }
- }
- if (value != null && value.length() > 0) {
- mParentActivity = value;
- } else {
- mParentActivity = null;
- }
-
- // Get activity theme.
- value = activity.getAttributeNS(NS_RESOURCES, ATTRIBUTE_THEME);
- if (value != null && value.length() > 0) {
- mTheme = value;
- } else {
- mTheme = null;
- }
-
- // Get UI options.
- value = activity.getAttributeNS(NS_RESOURCES, ATTRIBUTE_UI_OPTIONS);
- if (value != null && value.length() > 0) {
- mUiOptions = value;
- } else {
- mUiOptions = null;
- }
- }
-
- @Nullable
- public String getIcon() {
- return mIcon;
- }
-
- @Nullable
- public String getLabel() {
- return mLabel;
- }
-
- public String getName() {
- return mName;
- }
-
- @Nullable
- public String getParentActivity() {
- return mParentActivity;
- }
-
- @Nullable
- public String getTheme() {
- return mTheme;
- }
-
- @Nullable
- public String getUiOptions() {
- return mUiOptions;
- }
- }
-
- /**
- * The maximum number of milliseconds to search for an activity in the codebase when
- * attempting to associate layouts with activities in
- * {@link #guessActivity(IFile, String)}
- */
- private static final int SEARCH_TIMEOUT_MS = 3000;
-
- private final IProject mProject;
- private String mPackage;
- private String mManifestTheme;
- private Map<String, ActivityAttributes> mActivityAttributes;
- private IAbstractFile mManifestFile;
- private long mLastModified;
- private long mLastChecked;
- private String mMinSdkName;
- private int mMinSdk;
- private int mTargetSdk;
- private String mApplicationIcon;
- private String mApplicationLabel;
- private boolean mApplicationSupportsRtl;
-
- /**
- * Qualified name for the per-project non-persistent property storing the
- * {@link ManifestInfo} for this project
- */
- final static QualifiedName MANIFEST_FINDER = new QualifiedName(AdtPlugin.PLUGIN_ID,
- "manifest"); //$NON-NLS-1$
-
- /**
- * Constructs an {@link ManifestInfo} for the given project. Don't use this method;
- * use the {@link #get} factory method instead.
- *
- * @param project project to create an {@link ManifestInfo} for
- */
- private ManifestInfo(IProject project) {
- mProject = project;
- }
-
- /**
- * Clears the cached manifest information. The next get call on one of the
- * properties will cause the information to be refreshed.
- */
- public void clear() {
- mLastChecked = 0;
- }
-
- /**
- * Returns the {@link ManifestInfo} for the given project
- *
- * @param project the project the finder is associated with
- * @return a {@ManifestInfo} for the given project, never null
- */
- @NonNull
- public static ManifestInfo get(IProject project) {
- ManifestInfo finder = null;
- try {
- finder = (ManifestInfo) project.getSessionProperty(MANIFEST_FINDER);
- } catch (CoreException e) {
- // Not a problem; we will just create a new one
- }
-
- if (finder == null) {
- finder = new ManifestInfo(project);
- try {
- project.setSessionProperty(MANIFEST_FINDER, finder);
- } catch (CoreException e) {
- AdtPlugin.log(e, "Can't store ManifestInfo");
- }
- }
-
- return finder;
- }
-
- /**
- * Ensure that the package, theme and activity maps are initialized and up to date
- * with respect to the manifest file
- */
- private void sync() {
- // Since each of the accessors call sync(), allow a bunch of immediate
- // accessors to all bypass the file stat() below
- long now = System.currentTimeMillis();
- if (now - mLastChecked < 50 && mManifestFile != null) {
- return;
- }
- mLastChecked = now;
-
- if (mManifestFile == null) {
- IFolderWrapper projectFolder = new IFolderWrapper(mProject);
- mManifestFile = AndroidManifest.getManifest(projectFolder);
- if (mManifestFile == null) {
- return;
- }
- }
-
- // Check to see if our data is up to date
- long fileModified = mManifestFile.getModificationStamp();
- if (fileModified == mLastModified) {
- // Already have up to date data
- return;
- }
- mLastModified = fileModified;
-
- mActivityAttributes = new HashMap<String, ActivityAttributes>();
- mManifestTheme = null;
- mTargetSdk = 1; // Default when not specified
- mMinSdk = 1; // Default when not specified
- mMinSdkName = "1"; // Default when not specified
- mPackage = ""; //$NON-NLS-1$
- mApplicationIcon = null;
- mApplicationLabel = null;
- mApplicationSupportsRtl = false;
-
- Document document = null;
- try {
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- InputSource is = new InputSource(mManifestFile.getContents());
-
- factory.setNamespaceAware(true);
- factory.setValidating(false);
- DocumentBuilder builder = factory.newDocumentBuilder();
- document = builder.parse(is);
-
- Element root = document.getDocumentElement();
- mPackage = root.getAttribute(ATTRIBUTE_PACKAGE);
- NodeList activities = document.getElementsByTagName(NODE_ACTIVITY);
- for (int i = 0, n = activities.getLength(); i < n; i++) {
- Element activity = (Element) activities.item(i);
- ActivityAttributes info = new ActivityAttributes(activity, mPackage);
- mActivityAttributes.put(info.getName(), info);
- }
-
- NodeList applications = root.getElementsByTagName(AndroidManifest.NODE_APPLICATION);
- if (applications.getLength() > 0) {
- assert applications.getLength() == 1;
- Element application = (Element) applications.item(0);
- if (application.hasAttributeNS(NS_RESOURCES, ATTRIBUTE_ICON)) {
- mApplicationIcon = application.getAttributeNS(NS_RESOURCES, ATTRIBUTE_ICON);
- }
- if (application.hasAttributeNS(NS_RESOURCES, ATTRIBUTE_LABEL)) {
- mApplicationLabel = application.getAttributeNS(NS_RESOURCES, ATTRIBUTE_LABEL);
- }
- if (SdkConstants.VALUE_TRUE.equals(application.getAttributeNS(NS_RESOURCES,
- ATTRIBUTE_SUPPORTS_RTL))) {
- mApplicationSupportsRtl = true;
- }
-
- String defaultTheme = application.getAttributeNS(NS_RESOURCES, ATTRIBUTE_THEME);
- if (defaultTheme != null && !defaultTheme.isEmpty()) {
- // From manifest theme documentation:
- // "If that attribute is also not set, the default system theme is used."
- mManifestTheme = defaultTheme;
- }
- }
-
- // Look up target SDK
- NodeList usesSdks = root.getElementsByTagName(NODE_USES_SDK);
- if (usesSdks.getLength() > 0) {
- Element usesSdk = (Element) usesSdks.item(0);
- mMinSdk = getApiVersion(usesSdk, ATTRIBUTE_MIN_SDK_VERSION, 1);
- mTargetSdk = getApiVersion(usesSdk, ATTRIBUTE_TARGET_SDK_VERSION, mMinSdk);
- }
-
- } catch (SAXException e) {
- AdtPlugin.log(e, "Malformed manifest");
- } catch (Exception e) {
- AdtPlugin.log(e, "Could not read Manifest data");
- }
- }
-
- private int getApiVersion(Element usesSdk, String attribute, int defaultApiLevel) {
- String valueString = null;
- if (usesSdk.hasAttributeNS(NS_RESOURCES, attribute)) {
- valueString = usesSdk.getAttributeNS(NS_RESOURCES, attribute);
- if (attribute.equals(ATTRIBUTE_MIN_SDK_VERSION)) {
- mMinSdkName = valueString;
- }
- }
-
- if (valueString != null) {
- int apiLevel = -1;
- try {
- apiLevel = Integer.valueOf(valueString);
- } catch (NumberFormatException e) {
- // Handle codename
- if (Sdk.getCurrent() != null) {
- IAndroidTarget target = Sdk.getCurrent().getTargetFromHashString(
- "android-" + valueString); //$NON-NLS-1$
- if (target != null) {
- // codename future API level is current api + 1
- apiLevel = target.getVersion().getApiLevel() + 1;
- }
- }
- }
-
- return apiLevel;
- }
-
- return defaultApiLevel;
- }
-
- /**
- * Returns the default package registered in the Android manifest
- *
- * @return the default package registered in the manifest
- */
- @NonNull
- public String getPackage() {
- sync();
- return mPackage;
- }
-
- /**
- * Returns a map from activity full class names to the corresponding {@link ActivityAttributes}.
- *
- * @return a map from activity fqcn to ActivityAttributes
- */
- @NonNull
- public Map<String, ActivityAttributes> getActivityAttributesMap() {
- sync();
- return mActivityAttributes;
- }
-
- /**
- * Returns the attributes of an activity given its full class name.
- */
- @Nullable
- public ActivityAttributes getActivityAttributes(String activity) {
- return getActivityAttributesMap().get(activity);
- }
-
- /**
- * Returns the manifest theme registered on the application, if any
- *
- * @return a manifest theme, or null if none was registered
- */
- @Nullable
- public String getManifestTheme() {
- sync();
- return mManifestTheme;
- }
-
- /**
- * Returns the default theme for this project, by looking at the manifest default
- * theme registration, target SDK, rendering target, etc.
- *
- * @param renderingTarget the rendering target use to render the theme, or null
- * @param screenSize the screen size to obtain a default theme for, or null if unknown
- * @return the theme to use for this project, never null
- */
- @NonNull
- public String getDefaultTheme(IAndroidTarget renderingTarget, ScreenSize screenSize) {
- sync();
-
- if (mManifestTheme != null) {
- return mManifestTheme;
- }
-
- int renderingTargetSdk = mTargetSdk;
- if (renderingTarget != null) {
- renderingTargetSdk = renderingTarget.getVersion().getApiLevel();
- }
-
- int apiLevel = Math.min(mTargetSdk, renderingTargetSdk);
- // For now this theme works only on XLARGE screens. When it works for all sizes,
- // add that new apiLevel to this check.
- if (apiLevel >= 11 && screenSize == ScreenSize.XLARGE || apiLevel >= 14) {
- return ANDROID_STYLE_RESOURCE_PREFIX + "Theme.Holo"; //$NON-NLS-1$
- } else {
- return ANDROID_STYLE_RESOURCE_PREFIX + "Theme"; //$NON-NLS-1$
- }
- }
-
- /**
- * Returns the application icon, or null
- *
- * @return the application icon, or null
- */
- @Nullable
- public String getApplicationIcon() {
- sync();
- return mApplicationIcon;
- }
-
- /**
- * Returns the application label, or null
- *
- * @return the application label, or null
- */
- @Nullable
- public String getApplicationLabel() {
- sync();
- return mApplicationLabel;
- }
-
- /**
- * Returns true if the application has RTL support.
- *
- * @return true if the application has RTL support.
- */
- public boolean isRtlSupported() {
- sync();
- return mApplicationSupportsRtl;
- }
-
- /**
- * Returns the target SDK version
- *
- * @return the target SDK version
- */
- public int getTargetSdkVersion() {
- sync();
- return mTargetSdk;
- }
-
- /**
- * Returns the minimum SDK version
- *
- * @return the minimum SDK version
- */
- public int getMinSdkVersion() {
- sync();
- return mMinSdk;
- }
-
- /**
- * Returns the minimum SDK version name (which may not be a numeric string, e.g.
- * it could be a codename). It will never be null or empty; if no min sdk version
- * was specified in the manifest, the return value will be "1". Use
- * {@link #getMinSdkCodeName()} instead if you want to look up whether there is a code name.
- *
- * @return the minimum SDK version
- */
- @NonNull
- public String getMinSdkName() {
- sync();
- if (mMinSdkName == null || mMinSdkName.isEmpty()) {
- mMinSdkName = "1"; //$NON-NLS-1$
- }
-
- return mMinSdkName;
- }
-
- /**
- * Returns the code name used for the minimum SDK version, if any.
- *
- * @return the minSdkVersion codename or null
- */
- @Nullable
- public String getMinSdkCodeName() {
- String minSdkName = getMinSdkName();
- if (!Character.isDigit(minSdkName.charAt(0))) {
- return minSdkName;
- }
-
- return null;
- }
-
- /**
- * Returns the {@link IPackageFragment} for the package registered in the manifest
- *
- * @return the {@link IPackageFragment} for the package registered in the manifest
- */
- @Nullable
- public IPackageFragment getPackageFragment() {
- sync();
- try {
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(mProject);
- if (javaProject != null) {
- IPackageFragmentRoot root = ManifestInfo.getSourcePackageRoot(javaProject);
- if (root != null) {
- return root.getPackageFragment(mPackage);
- }
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
-
- return null;
- }
-
- /**
- * Returns the activity associated with the given layout file. Makes an educated guess
- * by peeking at the usages of the R.layout.name field corresponding to the layout and
- * if it finds a usage.
- *
- * @param project the project containing the layout
- * @param layoutName the layout whose activity we want to look up
- * @param pkg the package containing activities
- * @return the activity name
- */
- @Nullable
- public static String guessActivity(IProject project, String layoutName, String pkg) {
- List<String> activities = guessActivities(project, layoutName, pkg);
- if (activities.size() > 0) {
- return activities.get(0);
- } else {
- return null;
- }
- }
-
- /**
- * Returns the activities associated with the given layout file. Makes an educated guess
- * by peeking at the usages of the R.layout.name field corresponding to the layout and
- * if it finds a usage.
- *
- * @param project the project containing the layout
- * @param layoutName the layout whose activity we want to look up
- * @param pkg the package containing activities
- * @return the activity name
- */
- @NonNull
- public static List<String> guessActivities(IProject project, String layoutName, String pkg) {
- final LinkedList<String> activities = new LinkedList<String>();
- SearchRequestor requestor = new SearchRequestor() {
- @Override
- public void acceptSearchMatch(SearchMatch match) throws CoreException {
- Object element = match.getElement();
- if (element instanceof IMethod) {
- IMethod method = (IMethod) element;
- IType declaringType = method.getDeclaringType();
- String fqcn = declaringType.getFullyQualifiedName();
-
- if ((declaringType.getSuperclassName() != null &&
- declaringType.getSuperclassName().endsWith("Activity")) //$NON-NLS-1$
- || method.getElementName().equals("onCreate")) { //$NON-NLS-1$
- activities.addFirst(fqcn);
- } else {
- activities.addLast(fqcn);
- }
- }
- }
- };
- try {
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
- if (javaProject == null) {
- return Collections.emptyList();
- }
- // TODO - look around a bit more and see if we can figure out whether the
- // call if from within a setContentView call!
-
- // Search for which java classes call setContentView(R.layout.layoutname);
- String typeFqcn = "R.layout"; //$NON-NLS-1$
- if (pkg != null) {
- typeFqcn = pkg + '.' + typeFqcn;
- }
-
- IType type = javaProject.findType(typeFqcn);
- if (type != null) {
- IField field = type.getField(layoutName);
- if (field.exists()) {
- SearchPattern pattern = SearchPattern.createPattern(field, REFERENCES);
- try {
- search(requestor, javaProject, pattern);
- } catch (OperationCanceledException canceled) {
- // pass
- }
- }
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
-
- return activities;
- }
-
- /**
- * Returns all activities found in the given project (including those in libraries,
- * except for android.jar itself)
- *
- * @param project the project
- * @return a list of activity classes as fully qualified class names
- */
- @SuppressWarnings("restriction") // BinaryType
- @NonNull
- public static List<String> getProjectActivities(IProject project) {
- final List<String> activities = new ArrayList<String>();
- try {
- final IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
- if (javaProject != null) {
- IType[] activityTypes = new IType[0];
- IType activityType = javaProject.findType(CLASS_ACTIVITY);
- if (activityType != null) {
- ITypeHierarchy hierarchy =
- activityType.newTypeHierarchy(javaProject, new NullProgressMonitor());
- activityTypes = hierarchy.getAllSubtypes(activityType);
- for (IType type : activityTypes) {
- if (type instanceof BinaryType && (type.getClassFile() == null
- || type.getClassFile().getResource() == null)) {
- continue;
- }
- activities.add(type.getFullyQualifiedName());
- }
- }
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
-
- return activities;
- }
-
-
- /**
- * Returns the activity associated with the given layout file.
- * <p>
- * This is an alternative to {@link #guessActivity(IFile, String)}. Whereas
- * guessActivity simply looks for references to "R.layout.foo", this method searches
- * for all usages of Activity#setContentView(int), and for each match it looks up the
- * corresponding call text (such as "setContentView(R.layout.foo)"). From this it uses
- * a regexp to pull out "foo" from this, and stores the association that layout "foo"
- * is associated with the activity class that contained the setContentView call.
- * <p>
- * This has two potential advantages:
- * <ol>
- * <li>It can be faster. We do the reference search -once-, and we've built a map of
- * all the layout-to-activity mappings which we can then immediately look up other
- * layouts for, which is particularly useful at startup when we have to compute the
- * layout activity associations to populate the theme choosers.
- * <li>It can be more accurate. Just because an activity references an "R.layout.foo"
- * field doesn't mean it's setting it as a content view.
- * </ol>
- * However, this second advantage is also its chief problem. There are some common
- * code constructs which means that the associated layout is not explicitly referenced
- * in a direct setContentView call; on a couple of sample projects I tested I found
- * patterns like for example "setContentView(v)" where "v" had been computed earlier.
- * Therefore, for now we're going to stick with the more general approach of just
- * looking up each field when needed. We're keeping the code around, though statically
- * compiled out with the "if (false)" construct below in case we revisit this.
- *
- * @param layoutFile the layout whose activity we want to look up
- * @return the activity name
- */
- @SuppressWarnings("all")
- @Nullable
- public String guessActivityBySetContentView(String layoutName) {
- if (false) {
- // These should be fields
- final Pattern LAYOUT_FIELD_PATTERN =
- Pattern.compile("R\\.layout\\.([a-z0-9_]+)"); //$NON-NLS-1$
- Map<String, String> mUsages = null;
-
- sync();
- if (mUsages == null) {
- final Map<String, String> usages = new HashMap<String, String>();
- mUsages = usages;
- SearchRequestor requestor = new SearchRequestor() {
- @Override
- public void acceptSearchMatch(SearchMatch match) throws CoreException {
- Object element = match.getElement();
- if (element instanceof IMethod) {
- IMethod method = (IMethod) element;
- IType declaringType = method.getDeclaringType();
- String fqcn = declaringType.getFullyQualifiedName();
- IDocumentProvider provider = new TextFileDocumentProvider();
- IResource resource = match.getResource();
- try {
- provider.connect(resource);
- IDocument document = provider.getDocument(resource);
- if (document != null) {
- String matchText = document.get(match.getOffset(),
- match.getLength());
- Matcher matcher = LAYOUT_FIELD_PATTERN.matcher(matchText);
- if (matcher.find()) {
- usages.put(matcher.group(1), fqcn);
- }
- }
- } catch (Exception e) {
- AdtPlugin.log(e, "Can't find range information for %1$s",
- resource.getName());
- } finally {
- provider.disconnect(resource);
- }
- }
- }
- };
- try {
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(mProject);
- if (javaProject == null) {
- return null;
- }
-
- // Search for which java classes call setContentView(R.layout.layoutname);
- String typeFqcn = "R.layout"; //$NON-NLS-1$
- if (mPackage != null) {
- typeFqcn = mPackage + '.' + typeFqcn;
- }
-
- IType activityType = javaProject.findType(CLASS_ACTIVITY);
- if (activityType != null) {
- IMethod method = activityType.getMethod(
- "setContentView", new String[] {"I"}); //$NON-NLS-1$ //$NON-NLS-2$
- if (method.exists()) {
- SearchPattern pattern = SearchPattern.createPattern(method,
- REFERENCES);
- search(requestor, javaProject, pattern);
- }
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- }
-
- return mUsages.get(layoutName);
- }
-
- return null;
- }
-
- /**
- * Performs a search using the given pattern, scope and handler. The search will abort
- * if it takes longer than {@link #SEARCH_TIMEOUT_MS} milliseconds.
- */
- private static void search(SearchRequestor requestor, IJavaProject javaProject,
- SearchPattern pattern) throws CoreException {
- // Find the package fragment specified in the manifest; the activities should
- // live there.
- IJavaSearchScope scope = createPackageScope(javaProject);
-
- SearchParticipant[] participants = new SearchParticipant[] {
- SearchEngine.getDefaultSearchParticipant()
- };
- SearchEngine engine = new SearchEngine();
-
- final long searchStart = System.currentTimeMillis();
- NullProgressMonitor monitor = new NullProgressMonitor() {
- private boolean mCancelled;
- @Override
- public void internalWorked(double work) {
- long searchEnd = System.currentTimeMillis();
- if (searchEnd - searchStart > SEARCH_TIMEOUT_MS) {
- mCancelled = true;
- }
- }
-
- @Override
- public boolean isCanceled() {
- return mCancelled;
- }
- };
- engine.search(pattern, participants, scope, requestor, monitor);
- }
-
- /** Creates a package search scope for the first package root in the given java project */
- private static IJavaSearchScope createPackageScope(IJavaProject javaProject) {
- IPackageFragmentRoot packageRoot = getSourcePackageRoot(javaProject);
-
- IJavaSearchScope scope;
- if (packageRoot != null) {
- IJavaElement[] scopeElements = new IJavaElement[] { packageRoot };
- scope = SearchEngine.createJavaSearchScope(scopeElements);
- } else {
- scope = SearchEngine.createWorkspaceScope();
- }
- return scope;
- }
-
- /**
- * Returns the first package root for the given java project
- *
- * @param javaProject the project to search in
- * @return the first package root, or null
- */
- @Nullable
- public static IPackageFragmentRoot getSourcePackageRoot(IJavaProject javaProject) {
- IPackageFragmentRoot packageRoot = null;
- List<IPath> sources = BaseProjectHelper.getSourceClasspaths(javaProject);
-
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- for (IPath path : sources) {
- IResource firstSource = workspace.getRoot().findMember(path);
- if (firstSource != null) {
- packageRoot = javaProject.getPackageFragmentRoot(firstSource);
- if (packageRoot != null) {
- break;
- }
- }
- }
- return packageRoot;
- }
-
- /**
- * Computes the minimum SDK and target SDK versions for the project
- *
- * @param project the project to look up the versions for
- * @return a pair of (minimum SDK, target SDK) versions, never null
- */
- @NonNull
- public static Pair<Integer, Integer> computeSdkVersions(IProject project) {
- int mMinSdkVersion = 1;
- int mTargetSdkVersion = 1;
-
- IAbstractFile manifestFile = AndroidManifest.getManifest(new IFolderWrapper(project));
- if (manifestFile != null) {
- try {
- Object value = AndroidManifest.getMinSdkVersion(manifestFile);
- mMinSdkVersion = 1; // Default case if missing
- if (value instanceof Integer) {
- mMinSdkVersion = ((Integer) value).intValue();
- } else if (value instanceof String) {
- // handle codename, only if we can resolve it.
- if (Sdk.getCurrent() != null) {
- IAndroidTarget target = Sdk.getCurrent().getTargetFromHashString(
- "android-" + value); //$NON-NLS-1$
- if (target != null) {
- // codename future API level is current api + 1
- mMinSdkVersion = target.getVersion().getApiLevel() + 1;
- }
- }
- }
-
- value = AndroidManifest.getTargetSdkVersion(manifestFile);
- if (value == null) {
- mTargetSdkVersion = mMinSdkVersion;
- } else if (value instanceof String) {
- // handle codename, only if we can resolve it.
- if (Sdk.getCurrent() != null) {
- IAndroidTarget target = Sdk.getCurrent().getTargetFromHashString(
- "android-" + value); //$NON-NLS-1$
- if (target != null) {
- // codename future API level is current api + 1
- mTargetSdkVersion = target.getVersion().getApiLevel() + 1;
- }
- }
- }
- } catch (XPathExpressionException e) {
- // do nothing we'll use 1 below.
- } catch (StreamException e) {
- // do nothing we'll use 1 below.
- }
- }
-
- return Pair.of(mMinSdkVersion, mTargetSdkVersion);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/ManifestSourceViewerConfig.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/ManifestSourceViewerConfig.java
deleted file mode 100644
index a3d398657..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/ManifestSourceViewerConfig.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest;
-
-
-import com.android.ide.eclipse.adt.internal.editors.AndroidSourceViewerConfig;
-
-import org.eclipse.jface.text.contentassist.IContentAssistProcessor;
-import org.eclipse.jface.text.source.ISourceViewer;
-
-/**
- * Source Viewer Configuration that calls in ManifestContentAssist.
- */
-public final class ManifestSourceViewerConfig extends AndroidSourceViewerConfig {
-
- private ManifestContentAssist mAndroidContentAssist;
-
- public ManifestSourceViewerConfig() {
- super();
- mAndroidContentAssist = new ManifestContentAssist();
- }
-
- @Override
- public IContentAssistProcessor getAndroidContentAssistProcessor(
- ISourceViewer sourceViewer,
- String partitionType) {
- return mAndroidContentAssist;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/AndroidManifestDescriptors.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/AndroidManifestDescriptors.java
deleted file mode 100644
index 3429e43a0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/AndroidManifestDescriptors.java
+++ /dev/null
@@ -1,628 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest.descriptors;
-
-import com.android.SdkConstants;
-import com.android.ide.common.api.IAttributeInfo;
-import com.android.ide.common.api.IAttributeInfo.Format;
-import com.android.ide.common.resources.platform.AttributeInfo;
-import com.android.ide.common.resources.platform.AttrsXmlParser;
-import com.android.ide.common.resources.platform.DeclareStyleableInfo;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor.Mandatory;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.IDescriptorProvider;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ITextAttributeCreator;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ListAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ReferenceAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.TextAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.XmlnsAttributeDescriptor;
-
-import org.eclipse.core.runtime.IStatus;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.TreeSet;
-
-
-/**
- * Complete description of the AndroidManifest.xml structure.
- * <p/>
- * The root element are static instances which always exists.
- * However their sub-elements and attributes are created only when the SDK changes or is
- * loaded the first time.
- */
-public final class AndroidManifestDescriptors implements IDescriptorProvider {
- /** Name of the {@code <uses-permission>} */
- public static final String USES_PERMISSION = "uses-permission"; //$NON-NLS-1$
- private static final String MANIFEST_NODE_NAME = "manifest"; //$NON-NLS-1$
- private static final String ANDROID_MANIFEST_STYLEABLE =
- AttrsXmlParser.ANDROID_MANIFEST_STYLEABLE;
-
- // Public attributes names, attributes descriptors and elements descriptors
-
- public static final String ANDROID_LABEL_ATTR = "label"; //$NON-NLS-1$
- public static final String ANDROID_NAME_ATTR = "name"; //$NON-NLS-1$
- public static final String PACKAGE_ATTR = "package"; //$NON-NLS-1$
-
- /** The {@link ElementDescriptor} for the root Manifest element. */
- private final ElementDescriptor MANIFEST_ELEMENT;
- /** The {@link ElementDescriptor} for the root Application element. */
- private final ElementDescriptor APPLICATION_ELEMENT;
-
- /** The {@link ElementDescriptor} for the root Instrumentation element. */
- private final ElementDescriptor INTRUMENTATION_ELEMENT;
- /** The {@link ElementDescriptor} for the root Permission element. */
- private final ElementDescriptor PERMISSION_ELEMENT;
- /** The {@link ElementDescriptor} for the root UsesPermission element. */
- private final ElementDescriptor USES_PERMISSION_ELEMENT;
- /** The {@link ElementDescriptor} for the root UsesSdk element. */
- private final ElementDescriptor USES_SDK_ELEMENT;
-
- /** The {@link ElementDescriptor} for the root PermissionGroup element. */
- private final ElementDescriptor PERMISSION_GROUP_ELEMENT;
- /** The {@link ElementDescriptor} for the root PermissionTree element. */
- private final ElementDescriptor PERMISSION_TREE_ELEMENT;
-
- /** Private package attribute for the manifest element. Needs to be handled manually. */
- private final TextAttributeDescriptor PACKAGE_ATTR_DESC;
-
- public AndroidManifestDescriptors() {
- APPLICATION_ELEMENT = createElement("application", null, Mandatory.MANDATORY_LAST); //$NON-NLS-1$ + no child & mandatory
- INTRUMENTATION_ELEMENT = createElement("instrumentation"); //$NON-NLS-1$
-
- PERMISSION_ELEMENT = createElement("permission"); //$NON-NLS-1$
- USES_PERMISSION_ELEMENT = createElement(USES_PERMISSION);
- USES_SDK_ELEMENT = createElement("uses-sdk", null, Mandatory.MANDATORY); //$NON-NLS-1$ + no child & mandatory
-
- PERMISSION_GROUP_ELEMENT = createElement("permission-group"); //$NON-NLS-1$
- PERMISSION_TREE_ELEMENT = createElement("permission-tree"); //$NON-NLS-1$
-
- MANIFEST_ELEMENT = createElement(
- MANIFEST_NODE_NAME, // xml name
- new ElementDescriptor[] {
- APPLICATION_ELEMENT,
- INTRUMENTATION_ELEMENT,
- PERMISSION_ELEMENT,
- USES_PERMISSION_ELEMENT,
- PERMISSION_GROUP_ELEMENT,
- PERMISSION_TREE_ELEMENT,
- USES_SDK_ELEMENT,
- },
- Mandatory.MANDATORY);
-
- // The "package" attribute is treated differently as it doesn't have the standard
- // Android XML namespace.
- PACKAGE_ATTR_DESC = new PackageAttributeDescriptor(PACKAGE_ATTR,
- null /* nsUri */,
- new AttributeInfo(PACKAGE_ATTR, Format.REFERENCE_SET)).setTooltip(
- "This attribute gives a unique name for the package, using a Java-style " +
- "naming convention to avoid name collisions.\nFor example, applications " +
- "published by Google could have names of the form com.google.app.appname");
- }
-
- @Override
- public ElementDescriptor[] getRootElementDescriptors() {
- return new ElementDescriptor[] { MANIFEST_ELEMENT };
- }
-
- @Override
- public ElementDescriptor getDescriptor() {
- return getManifestElement();
- }
-
- public ElementDescriptor getApplicationElement() {
- return APPLICATION_ELEMENT;
- }
-
- public ElementDescriptor getManifestElement() {
- return MANIFEST_ELEMENT;
- }
-
- public ElementDescriptor getUsesSdkElement() {
- return USES_SDK_ELEMENT;
- }
-
- public ElementDescriptor getInstrumentationElement() {
- return INTRUMENTATION_ELEMENT;
- }
-
- public ElementDescriptor getPermissionElement() {
- return PERMISSION_ELEMENT;
- }
-
- public ElementDescriptor getUsesPermissionElement() {
- return USES_PERMISSION_ELEMENT;
- }
-
- public ElementDescriptor getPermissionGroupElement() {
- return PERMISSION_GROUP_ELEMENT;
- }
-
- public ElementDescriptor getPermissionTreeElement() {
- return PERMISSION_TREE_ELEMENT;
- }
-
- /**
- * Updates the document descriptor.
- * <p/>
- * It first computes the new children of the descriptor and then updates them
- * all at once.
- *
- * @param manifestMap The map style => attributes from the attrs_manifest.xml file
- */
- public synchronized void updateDescriptors(
- Map<String, DeclareStyleableInfo> manifestMap) {
-
- // -- setup the required attributes overrides --
-
- Set<String> required = new HashSet<String>();
- required.add("provider/authorities"); //$NON-NLS-1$
-
- // -- setup the various attribute format overrides --
-
- // The key for each override is "element1,element2,.../attr-xml-local-name" or
- // "*/attr-xml-local-name" to match the attribute in any element.
-
- Map<String, ITextAttributeCreator> overrides = new HashMap<String, ITextAttributeCreator>();
-
- overrides.put("*/icon", ReferenceAttributeDescriptor.CREATOR); //$NON-NLS-1$
-
- overrides.put("*/theme", ThemeAttributeDescriptor.CREATOR); //$NON-NLS-1$
- overrides.put("*/permission", ListAttributeDescriptor.CREATOR); //$NON-NLS-1$
- overrides.put("*/targetPackage", ManifestPkgAttrDescriptor.CREATOR); //$NON-NLS-1$
-
- overrides.put("uses-library/name", ListAttributeDescriptor.CREATOR); //$NON-NLS-1$
- overrides.put("action,category,uses-permission/" + ANDROID_NAME_ATTR, //$NON-NLS-1$
- ListAttributeDescriptor.CREATOR);
-
- overrideClassName(overrides, "application", //$NON-NLS-1$
- SdkConstants.CLASS_APPLICATION,
- false /*mandatory*/);
- overrideClassName(overrides, "application/backupAgent", //$NON-NLS-1$
- "android.app.backup.BackupAgent", //$NON-NLS-1$
- false /*mandatory*/);
- overrideClassName(overrides, "activity", SdkConstants.CLASS_ACTIVITY); //$NON-NLS-1$
- overrideClassName(overrides, "receiver", SdkConstants.CLASS_BROADCASTRECEIVER);//$NON-NLS-1$
- overrideClassName(overrides, "service", SdkConstants.CLASS_SERVICE); //$NON-NLS-1$
- overrideClassName(overrides, "provider", SdkConstants.CLASS_CONTENTPROVIDER); //$NON-NLS-1$
- overrideClassName(overrides, "instrumentation",
- SdkConstants.CLASS_INSTRUMENTATION); //$NON-NLS-1$
-
- // -- list element nodes already created --
- // These elements are referenced by already opened editors, so we want to update them
- // but not re-create them when reloading an SDK on the fly.
-
- HashMap<String, ElementDescriptor> elementDescs =
- new HashMap<String, ElementDescriptor>();
- elementDescs.put(MANIFEST_ELEMENT.getXmlLocalName(), MANIFEST_ELEMENT);
- elementDescs.put(APPLICATION_ELEMENT.getXmlLocalName(), APPLICATION_ELEMENT);
- elementDescs.put(INTRUMENTATION_ELEMENT.getXmlLocalName(), INTRUMENTATION_ELEMENT);
- elementDescs.put(PERMISSION_ELEMENT.getXmlLocalName(), PERMISSION_ELEMENT);
- elementDescs.put(USES_PERMISSION_ELEMENT.getXmlLocalName(), USES_PERMISSION_ELEMENT);
- elementDescs.put(USES_SDK_ELEMENT.getXmlLocalName(), USES_SDK_ELEMENT);
- elementDescs.put(PERMISSION_GROUP_ELEMENT.getXmlLocalName(), PERMISSION_GROUP_ELEMENT);
- elementDescs.put(PERMISSION_TREE_ELEMENT.getXmlLocalName(), PERMISSION_TREE_ELEMENT);
-
- // --
-
- inflateElement(manifestMap,
- overrides,
- required,
- elementDescs,
- MANIFEST_ELEMENT,
- "AndroidManifest"); //$NON-NLS-1$
- insertAttribute(MANIFEST_ELEMENT, PACKAGE_ATTR_DESC);
-
- XmlnsAttributeDescriptor xmlns = new XmlnsAttributeDescriptor(
- SdkConstants.ANDROID_NS_NAME, SdkConstants.ANDROID_URI);
- insertAttribute(MANIFEST_ELEMENT, xmlns);
-
- /*
- *
- *
- */
- assert sanityCheck(manifestMap, MANIFEST_ELEMENT);
- }
-
- /**
- * Sets up a mandatory attribute override using a ClassAttributeDescriptor
- * with the specified class name.
- *
- * @param overrides The current map of overrides.
- * @param elementName The element name to override, e.g. "application".
- * If this name does NOT have a slash (/), the ANDROID_NAME_ATTR attribute will be overriden.
- * Otherwise, if it contains a (/) the format is "element/attribute", for example
- * "application/name" vs "application/backupAgent".
- * @param className The fully qualified name of the base class of the attribute.
- */
- private static void overrideClassName(
- Map<String, ITextAttributeCreator> overrides,
- String elementName,
- final String className) {
- overrideClassName(overrides, elementName, className, true);
- }
-
- /**
- * Sets up an attribute override using a ClassAttributeDescriptor
- * with the specified class name.
- *
- * @param overrides The current map of overrides.
- * @param elementName The element name to override, e.g. "application".
- * If this name does NOT have a slash (/), the ANDROID_NAME_ATTR attribute will be overriden.
- * Otherwise, if it contains a (/) the format is "element/attribute", for example
- * "application/name" vs "application/backupAgent".
- * @param className The fully qualified name of the base class of the attribute.
- * @param mandatory True if this attribute is mandatory, false if optional.
- */
- private static void overrideClassName(
- Map<String, ITextAttributeCreator> overrides,
- String elementName,
- final String className,
- final boolean mandatory) {
- if (elementName.indexOf('/') == -1) {
- elementName = elementName + '/' + ANDROID_NAME_ATTR;
- }
- overrides.put(elementName,
- new ITextAttributeCreator() {
- @Override
- public TextAttributeDescriptor create(String xmlName, String nsUri,
- IAttributeInfo attrInfo) {
- if (attrInfo == null) {
- attrInfo = new AttributeInfo(xmlName, Format.STRING_SET );
- }
-
- if (SdkConstants.CLASS_ACTIVITY.equals(className)) {
- return new ClassAttributeDescriptor(
- className,
- PostActivityCreationAction.getAction(),
- xmlName,
- nsUri,
- attrInfo,
- mandatory,
- true /*defaultToProjectOnly*/);
- } else if (SdkConstants.CLASS_BROADCASTRECEIVER.equals(className)) {
- return new ClassAttributeDescriptor(
- className,
- PostReceiverCreationAction.getAction(),
- xmlName,
- nsUri,
- attrInfo,
- mandatory,
- true /*defaultToProjectOnly*/);
- } else if (SdkConstants.CLASS_INSTRUMENTATION.equals(className)) {
- return new ClassAttributeDescriptor(
- className,
- null, // no post action
- xmlName,
- nsUri,
- attrInfo,
- mandatory,
- false /*defaultToProjectOnly*/);
- } else {
- return new ClassAttributeDescriptor(
- className,
- xmlName,
- nsUri,
- attrInfo,
- mandatory);
- }
- }
- });
- }
-
- /**
- * Returns a new ElementDescriptor constructed from the information given here
- * and the javadoc & attributes extracted from the style map if any.
- * <p/>
- * Creates an element with no attribute overrides.
- */
- private ElementDescriptor createElement(
- String xmlName,
- ElementDescriptor[] childrenElements,
- Mandatory mandatory) {
- // Creates an element with no attribute overrides.
- String styleName = guessStyleName(xmlName);
- String sdkUrl = DescriptorsUtils.MANIFEST_SDK_URL + styleName;
- String uiName = getUiName(xmlName);
-
- ElementDescriptor element = new ManifestElementDescriptor(xmlName, uiName, null, sdkUrl,
- null, childrenElements, mandatory);
-
- return element;
- }
-
- /**
- * Returns a new ElementDescriptor constructed from its XML local name.
- * <p/>
- * This version creates an element not mandatory.
- */
- private ElementDescriptor createElement(String xmlName) {
- // Creates an element with no child and not mandatory
- return createElement(xmlName, null, Mandatory.NOT_MANDATORY);
- }
-
- /**
- * Inserts an attribute in this element attribute list if it is not present there yet
- * (based on the attribute XML name.)
- * The attribute is inserted at the beginning of the attribute list.
- */
- private void insertAttribute(ElementDescriptor element, AttributeDescriptor newAttr) {
- AttributeDescriptor[] attributes = element.getAttributes();
- for (AttributeDescriptor attr : attributes) {
- if (attr.getXmlLocalName().equals(newAttr.getXmlLocalName())) {
- return;
- }
- }
-
- AttributeDescriptor[] newArray = new AttributeDescriptor[attributes.length + 1];
- newArray[0] = newAttr;
- System.arraycopy(attributes, 0, newArray, 1, attributes.length);
- element.setAttributes(newArray);
- }
-
- /**
- * "Inflates" the properties of an {@link ElementDescriptor} from the styleable declaration.
- * <p/>
- * This first creates all the attributes for the given ElementDescriptor.
- * It then finds all children of the descriptor, inflates them recursively and sets them
- * as child to this ElementDescriptor.
- *
- * @param styleMap The input styleable map for manifest elements & attributes.
- * @param overrides A list of attribute overrides (to customize the type of the attribute
- * descriptors).
- * @param requiredAttributes Set of attributes to be marked as required.
- * @param existingElementDescs A map of already created element descriptors, keyed by
- * XML local name. This is used to use the static elements created initially by this
- * class, which are referenced directly by editors (so that reloading an SDK won't
- * break these references).
- * @param elemDesc The current {@link ElementDescriptor} to inflate.
- * @param styleName The name of the {@link ElementDescriptor} to inflate. Its XML local name
- * will be guessed automatically from the style name.
- */
- private void inflateElement(
- Map<String, DeclareStyleableInfo> styleMap,
- Map<String, ITextAttributeCreator> overrides,
- Set<String> requiredAttributes,
- HashMap<String, ElementDescriptor> existingElementDescs,
- ElementDescriptor elemDesc,
- String styleName) {
- assert elemDesc != null;
- assert styleName != null;
- assert styleMap != null;
-
- if (styleMap == null) {
- return;
- }
-
- // define attributes
- DeclareStyleableInfo style = styleMap.get(styleName);
- if (style != null) {
- ArrayList<AttributeDescriptor> attrDescs = new ArrayList<AttributeDescriptor>();
- DescriptorsUtils.appendAttributes(attrDescs,
- elemDesc.getXmlLocalName(),
- SdkConstants.NS_RESOURCES,
- style.getAttributes(),
- requiredAttributes,
- overrides);
- elemDesc.setTooltip(style.getJavaDoc());
- elemDesc.setAttributes(attrDescs.toArray(new AttributeDescriptor[attrDescs.size()]));
- }
-
- // find all elements that have this one as parent
- ArrayList<ElementDescriptor> children = new ArrayList<ElementDescriptor>();
- for (Entry<String, DeclareStyleableInfo> entry : styleMap.entrySet()) {
- DeclareStyleableInfo childStyle = entry.getValue();
- boolean isParent = false;
- String[] parents = childStyle.getParents();
- if (parents != null) {
- for (String parent: parents) {
- if (styleName.equals(parent)) {
- isParent = true;
- break;
- }
- }
- }
- if (isParent) {
- String childStyleName = entry.getKey();
- String childXmlName = guessXmlName(childStyleName);
-
- // create or re-use element
- ElementDescriptor child = existingElementDescs.get(childXmlName);
- if (child == null) {
- child = createElement(childXmlName);
- existingElementDescs.put(childXmlName, child);
- }
- children.add(child);
-
- inflateElement(styleMap,
- overrides,
- requiredAttributes,
- existingElementDescs,
- child,
- childStyleName);
- }
- }
- elemDesc.setChildren(children.toArray(new ElementDescriptor[children.size()]));
- }
-
- /**
- * Get an UI name from the element XML name.
- * <p/>
- * Capitalizes the first letter and replace non-alphabet by a space followed by a capital.
- */
- private static String getUiName(String xmlName) {
- StringBuilder sb = new StringBuilder();
-
- boolean capitalize = true;
- for (char c : xmlName.toCharArray()) {
- if (capitalize && c >= 'a' && c <= 'z') {
- sb.append((char)(c + 'A' - 'a'));
- capitalize = false;
- } else if ((c < 'A' || c > 'Z') && (c < 'a' || c > 'z')) {
- sb.append(' ');
- capitalize = true;
- } else {
- sb.append(c);
- }
- }
-
- return sb.toString();
- }
-
- /**
- * Guesses the style name for a given XML element name.
- * <p/>
- * The rules are:
- * - capitalize the first letter:
- * - if there's a dash, skip it and capitalize the next one
- * - prefix AndroidManifest
- * The exception is "manifest" which just becomes AndroidManifest.
- * <p/>
- * Examples:
- * - manifest => AndroidManifest
- * - application => AndroidManifestApplication
- * - uses-permission => AndroidManifestUsesPermission
- */
- private String guessStyleName(String xmlName) {
- StringBuilder sb = new StringBuilder();
-
- if (!xmlName.equals(MANIFEST_NODE_NAME)) {
- boolean capitalize = true;
- for (char c : xmlName.toCharArray()) {
- if (capitalize && c >= 'a' && c <= 'z') {
- sb.append((char)(c + 'A' - 'a'));
- capitalize = false;
- } else if ((c < 'A' || c > 'Z') && (c < 'a' || c > 'z')) {
- // not a letter -- skip the character and capitalize the next one
- capitalize = true;
- } else {
- sb.append(c);
- }
- }
- }
-
- sb.insert(0, ANDROID_MANIFEST_STYLEABLE);
- return sb.toString();
- }
-
- /**
- * This method performs a sanity check to make sure all the styles declared in the
- * manifestMap are actually defined in the actual element descriptors and reachable from
- * the manifestElement root node.
- */
- private boolean sanityCheck(Map<String, DeclareStyleableInfo> manifestMap,
- ElementDescriptor manifestElement) {
- TreeSet<String> elementsDeclared = new TreeSet<String>();
- findAllElementNames(manifestElement, elementsDeclared);
-
- TreeSet<String> stylesDeclared = new TreeSet<String>();
- for (String styleName : manifestMap.keySet()) {
- if (styleName.startsWith(ANDROID_MANIFEST_STYLEABLE)) {
- stylesDeclared.add(styleName);
- }
- }
-
- for (Iterator<String> it = elementsDeclared.iterator(); it.hasNext();) {
- String xmlName = it.next();
- String styleName = guessStyleName(xmlName);
- if (stylesDeclared.remove(styleName)) {
- it.remove();
- }
- }
-
- StringBuilder sb = new StringBuilder();
- if (!stylesDeclared.isEmpty()) {
- sb.append("Warning, ADT/SDK Mismatch! The following elements are declared by the SDK but unknown to ADT: ");
- for (String name : stylesDeclared) {
- sb.append(guessXmlName(name));
-
- if (!name.equals(stylesDeclared.last())) {
- sb.append(", "); //$NON-NLS-1$
- }
- }
-
- AdtPlugin.log(IStatus.WARNING, "%s", sb.toString());
- AdtPlugin.printToConsole((String)null, sb);
- sb.setLength(0);
- }
-
- if (!elementsDeclared.isEmpty()) {
- sb.append("Warning, ADT/SDK Mismatch! The following elements are declared by ADT but not by the SDK: ");
- for (String name : elementsDeclared) {
- sb.append(name);
- if (!name.equals(elementsDeclared.last())) {
- sb.append(", "); //$NON-NLS-1$
- }
- }
-
- AdtPlugin.log(IStatus.WARNING, "%s", sb.toString());
- AdtPlugin.printToConsole((String)null, sb);
- }
-
- return true;
- }
-
- /**
- * Performs an approximate translation of the style name into a potential
- * xml name. This is more or less the reverse from guessStyleName().
- *
- * @return The XML local name for a given style name.
- */
- private String guessXmlName(String name) {
- StringBuilder sb = new StringBuilder();
- if (ANDROID_MANIFEST_STYLEABLE.equals(name)) {
- sb.append(MANIFEST_NODE_NAME);
- } else {
- name = name.replace(ANDROID_MANIFEST_STYLEABLE, ""); //$NON-NLS-1$
- boolean first_char = true;
- for (char c : name.toCharArray()) {
- if (c >= 'A' && c <= 'Z') {
- if (!first_char) {
- sb.append('-');
- }
- c = (char) (c - 'A' + 'a');
- }
- sb.append(c);
- first_char = false;
- }
- }
- return sb.toString();
- }
-
- /**
- * Helper method used by {@link #sanityCheck(Map, ElementDescriptor)} to find all the
- * {@link ElementDescriptor} names defined by the tree of descriptors.
- * <p/>
- * Note: this assumes no circular reference in the tree of {@link ElementDescriptor}s.
- */
- private void findAllElementNames(ElementDescriptor element, TreeSet<String> declared) {
- declared.add(element.getXmlName());
- for (ElementDescriptor desc : element.getChildren()) {
- findAllElementNames(desc, declared);
- }
- }
-
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/ClassAttributeDescriptor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/ClassAttributeDescriptor.java
deleted file mode 100644
index 1a27f8d00..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/ClassAttributeDescriptor.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest.descriptors;
-
-import com.android.SdkConstants;
-import com.android.ide.common.api.IAttributeInfo;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.TextAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.manifest.model.UiClassAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.manifest.model.UiClassAttributeNode.IPostTypeCreationAction;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-/**
- * Describes an XML attribute representing a class name.
- * It is displayed by a {@link UiClassAttributeNode}.
- */
-public class ClassAttributeDescriptor extends TextAttributeDescriptor {
-
- /** Superclass of the class value. */
- private String mSuperClassName;
-
- private IPostTypeCreationAction mPostCreationAction;
-
- /** indicates if the class parameter is mandatory */
- boolean mMandatory;
-
- private final boolean mDefaultToProjectOnly;
-
- /**
- * Creates a new {@link ClassAttributeDescriptor}
- * @param superClassName the fully qualified name of the superclass of the class represented
- * by the attribute.
- * @param xmlLocalName The XML name of the attribute (case sensitive, with android: prefix).
- * @param nsUri The URI of the attribute. Can be null if attribute has no namespace.
- * See {@link SdkConstants#NS_RESOURCES} for a common value.
- * @param attrInfo The {@link IAttributeInfo} of this attribute. Can't be null.
- * @param mandatory indicates if the class attribute is mandatory.
- */
- public ClassAttributeDescriptor(String superClassName,
- String xmlLocalName,
- String nsUri,
- IAttributeInfo attrInfo,
- boolean mandatory) {
- super(xmlLocalName, nsUri, attrInfo);
- mSuperClassName = superClassName;
- mDefaultToProjectOnly = true;
- if (mandatory) {
- mMandatory = true;
- setRequired(true);
- }
- }
-
- /**
- * Creates a new {@link ClassAttributeDescriptor}
- * @param superClassName the fully qualified name of the superclass of the class represented
- * by the attribute.
- * @param postCreationAction the {@link IPostTypeCreationAction} to be executed on the
- * newly created class.
- * @param xmlLocalName The XML local name of the attribute (case sensitive).
- * @param nsUri The URI of the attribute. Can be null if attribute has no namespace.
- * See {@link SdkConstants#NS_RESOURCES} for a common value.
- * @param attrInfo The {@link IAttributeInfo} of this attribute. Can't be null.
- * @param mandatory indicates if the class attribute is mandatory.
- * @param defaultToProjectOnly True if only classes from the sources of this project should
- * be shown by default in the class browser.
- */
- public ClassAttributeDescriptor(String superClassName,
- IPostTypeCreationAction postCreationAction,
- String xmlLocalName,
- String nsUri,
- IAttributeInfo attrInfo,
- boolean mandatory,
- boolean defaultToProjectOnly) {
- super(xmlLocalName, nsUri, attrInfo);
- mSuperClassName = superClassName;
- mPostCreationAction = postCreationAction;
- mDefaultToProjectOnly = defaultToProjectOnly;
- if (mandatory) {
- mMandatory = true;
- setRequired(true);
- }
- }
-
- /**
- * @return A new {@link UiClassAttributeNode} linked to this descriptor.
- */
- @Override
- public UiAttributeNode createUiNode(UiElementNode uiParent) {
- return new UiClassAttributeNode(mSuperClassName, mPostCreationAction,
- mMandatory, this, uiParent, mDefaultToProjectOnly);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/ManifestElementDescriptor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/ManifestElementDescriptor.java
deleted file mode 100644
index deb815e57..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/ManifestElementDescriptor.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest.descriptors;
-
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.manifest.model.UiManifestElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-/**
- * {@link ManifestElementDescriptor} describes an XML element node, with its
- * element name, its possible attributes, its possible child elements but also
- * its display name and tooltip.
- *
- * This {@link ElementDescriptor} is specialized to create {@link UiManifestElementNode} UI nodes.
- */
-public class ManifestElementDescriptor extends ElementDescriptor {
-
- /**
- * Constructs a new {@link ManifestElementDescriptor}.
- *
- * @param xml_name The XML element node name. Case sensitive.
- * @param ui_name The XML element name for the user interface, typically capitalized.
- * @param tooltip An optional tooltip. Can be null or empty.
- * @param sdk_url An optional SKD URL. Can be null or empty.
- * @param attributes The list of allowed attributes. Can be null or empty.
- * @param children The list of allowed children. Can be null or empty.
- * @param mandatory Whether this node must always exist (even for empty models).
- */
- public ManifestElementDescriptor(String xml_name,
- String ui_name,
- String tooltip,
- String sdk_url,
- AttributeDescriptor[] attributes,
- ElementDescriptor[] children,
- Mandatory mandatory) {
- super(xml_name, ui_name, tooltip, sdk_url, attributes, children, mandatory);
- }
-
- /**
- * Constructs a new {@link ManifestElementDescriptor}.
- *
- * @param xml_name The XML element node name. Case sensitive.
- * @param ui_name The XML element name for the user interface, typically capitalized.
- * @param tooltip An optional tooltip. Can be null or empty.
- * @param sdk_url An optional SKD URL. Can be null or empty.
- * @param attributes The list of allowed attributes. Can be null or empty.
- * @param children The list of allowed children. Can be null or empty.
- * @param mandatory Whether this node must always exist (even for empty models).
- */
- public ManifestElementDescriptor(String xml_name,
- String ui_name,
- String tooltip,
- String sdk_url,
- AttributeDescriptor[] attributes,
- ElementDescriptor[] children,
- boolean mandatory) {
- super(xml_name, ui_name, tooltip, sdk_url, attributes, children, mandatory);
- }
-
- /**
- * Constructs a new {@link ManifestElementDescriptor}.
- *
- * @param xml_name The XML element node name. Case sensitive.
- * @param ui_name The XML element name for the user interface, typically capitalized.
- * @param tooltip An optional tooltip. Can be null or empty.
- * @param sdk_url An optional SKD URL. Can be null or empty.
- * @param attributes The list of allowed attributes. Can be null or empty.
- * @param children The list of allowed children. Can be null or empty.
- */
- public ManifestElementDescriptor(String xml_name,
- String ui_name,
- String tooltip,
- String sdk_url,
- AttributeDescriptor[] attributes,
- ElementDescriptor[] children) {
- super(xml_name, ui_name, tooltip, sdk_url, attributes, children, false);
- }
-
- /**
- * This is a shortcut for
- * ManifestElementDescriptor(xml_name, xml_name.capitalize(), null, null, null, children).
- * This constructor is mostly used for unit tests.
- *
- * @param xml_name The XML element node name. Case sensitive.
- */
- public ManifestElementDescriptor(String xml_name, ElementDescriptor[] children) {
- super(xml_name, children);
- }
-
- /**
- * This is a shortcut for
- * ManifestElementDescriptor(xml_name, xml_name.capitalize(), null, null, null, null).
- * This constructor is mostly used for unit tests.
- *
- * @param xml_name The XML element node name. Case sensitive.
- */
- public ManifestElementDescriptor(String xml_name) {
- super(xml_name, null);
- }
-
- /**
- * @return A new {@link UiElementNode} linked to this descriptor.
- */
- @Override
- public UiElementNode createUiNode() {
- return new UiManifestElementNode(this);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/ManifestPkgAttrDescriptor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/ManifestPkgAttrDescriptor.java
deleted file mode 100755
index 74b789487..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/ManifestPkgAttrDescriptor.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest.descriptors;
-
-import com.android.ide.common.api.IAttributeInfo;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ITextAttributeCreator;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.TextAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.manifest.model.UiManifestPkgAttrNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-/**
- * Describes a package XML attribute. It is displayed by a {@link UiManifestPkgAttrNode}.
- * <p/>
- * Used by the override for .../targetPackage in {@link AndroidManifestDescriptors}.
- */
-public class ManifestPkgAttrDescriptor extends TextAttributeDescriptor {
-
- /**
- * Used by {@link DescriptorsUtils} to create instances of this descriptor.
- */
- public static final ITextAttributeCreator CREATOR = new ITextAttributeCreator() {
- @Override
- public TextAttributeDescriptor create(String xmlLocalName,
- String nsUri, IAttributeInfo attrInfo) {
- return new ManifestPkgAttrDescriptor(xmlLocalName, nsUri, attrInfo);
- }
- };
-
- public ManifestPkgAttrDescriptor(String xmlLocalName, String nsUri, IAttributeInfo attrInfo) {
- super(xmlLocalName, nsUri, attrInfo);
- }
-
- /**
- * @return A new {@link UiManifestPkgAttrNode} linked to this descriptor.
- */
- @Override
- public UiAttributeNode createUiNode(UiElementNode uiParent) {
- return new UiManifestPkgAttrNode(this, uiParent);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/PackageAttributeDescriptor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/PackageAttributeDescriptor.java
deleted file mode 100644
index e8395ac40..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/PackageAttributeDescriptor.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest.descriptors;
-
-import com.android.ide.common.api.IAttributeInfo;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.TextAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.manifest.model.UiPackageAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-/**
- * Describes a package XML attribute. It is displayed by a {@link UiPackageAttributeNode}.
- */
-public class PackageAttributeDescriptor extends TextAttributeDescriptor {
-
- public PackageAttributeDescriptor(String xmlLocalName, String nsUri, IAttributeInfo attrInfo) {
- super(xmlLocalName, nsUri, attrInfo);
- }
-
- /**
- * @return A new {@link UiPackageAttributeNode} linked to this descriptor.
- */
- @Override
- public UiAttributeNode createUiNode(UiElementNode uiParent) {
- return new UiPackageAttributeNode(this, uiParent);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/PostActivityCreationAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/PostActivityCreationAction.java
deleted file mode 100644
index 60c663dfc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/PostActivityCreationAction.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest.descriptors;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.internal.editors.manifest.model.UiClassAttributeNode.IPostTypeCreationAction;
-
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jdt.core.ICompilationUnit;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.core.JavaModelException;
-
-/**
- * Action to be executed after an Activity class is created.
- */
-class PostActivityCreationAction implements IPostTypeCreationAction {
-
- private final static PostActivityCreationAction sAction = new PostActivityCreationAction();
-
- private PostActivityCreationAction() {
- // private constructor to enforce singleton.
- }
-
-
- /**
- * Returns the action.
- */
- public static IPostTypeCreationAction getAction() {
- return sAction;
- }
-
- /**
- * Processes a newly created Activity.
- *
- */
- @Override
- public void processNewType(IType newType) {
- try {
- String methodContent =
- " /** Called when the activity is first created. */\n" +
- " @Override\n" +
- " public void onCreate(Bundle savedInstanceState) {\n" +
- " super.onCreate(savedInstanceState);\n" +
- "\n" +
- " // TODO Auto-generated method stub\n" +
- " }";
- newType.createMethod(methodContent, null /* sibling*/, false /* force */,
- new NullProgressMonitor());
-
- // we need to add the import for Bundle, so we need the compilation unit.
- // Since the type could be enclosed in other types, we loop till we find it.
- ICompilationUnit compilationUnit = null;
- IJavaElement element = newType;
- do {
- IJavaElement parentElement = element.getParent();
- if (parentElement != null) {
- if (parentElement.getElementType() == IJavaElement.COMPILATION_UNIT) {
- compilationUnit = (ICompilationUnit)parentElement;
- }
-
- element = parentElement;
- } else {
- break;
- }
- } while (compilationUnit == null);
-
- if (compilationUnit != null) {
- compilationUnit.createImport(SdkConstants.CLASS_BUNDLE,
- null /* sibling */, new NullProgressMonitor());
- }
- } catch (JavaModelException e) {
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/PostReceiverCreationAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/PostReceiverCreationAction.java
deleted file mode 100644
index 8b2c36144..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/PostReceiverCreationAction.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest.descriptors;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.internal.editors.manifest.model.UiClassAttributeNode.IPostTypeCreationAction;
-
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jdt.core.ICompilationUnit;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.core.JavaModelException;
-
-/**
- * Action to be executed after an BroadcastReceiver class is created.
- */
-class PostReceiverCreationAction implements IPostTypeCreationAction {
-
- private final static PostReceiverCreationAction sAction = new PostReceiverCreationAction();
-
- private PostReceiverCreationAction() {
- // private constructor to enforce singleton.
- }
-
- /**
- * Returns the action.
- */
- public static IPostTypeCreationAction getAction() {
- return sAction;
- }
-
- /**
- * Processes a newly created Activity.
- *
- */
- @Override
- public void processNewType(IType newType) {
- try {
- String methodContent =
- " @Override\n" +
- " public void onReceive(Context context, Intent intent) {\n" +
- " // TODO Auto-generated method stub\n" +
- " }";
- newType.createMethod(methodContent, null /* sibling*/, false /* force */,
- new NullProgressMonitor());
-
- // we need to add the import for Bundle, so we need the compilation unit.
- // Since the type could be enclosed in other types, we loop till we find it.
- ICompilationUnit compilationUnit = null;
- IJavaElement element = newType;
- do {
- IJavaElement parentElement = element.getParent();
- if (parentElement != null) {
- if (parentElement.getElementType() == IJavaElement.COMPILATION_UNIT) {
- compilationUnit = (ICompilationUnit)parentElement;
- }
-
- element = parentElement;
- } else {
- break;
- }
- } while (compilationUnit == null);
-
- if (compilationUnit != null) {
- compilationUnit.createImport(SdkConstants.CLASS_CONTEXT,
- null /* sibling */, new NullProgressMonitor());
- compilationUnit.createImport(SdkConstants.CLASS_INTENT,
- null /* sibling */, new NullProgressMonitor());
- }
- } catch (JavaModelException e) {
- // looks like the class already existed (this happens when the user check to create
- // inherited abstract methods).
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/ThemeAttributeDescriptor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/ThemeAttributeDescriptor.java
deleted file mode 100644
index 881d75361..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/descriptors/ThemeAttributeDescriptor.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest.descriptors;
-
-import com.android.ide.common.api.IAttributeInfo;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ITextAttributeCreator;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.TextAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiResourceAttributeNode;
-import com.android.resources.ResourceType;
-
-/**
- * Describes a Theme/Style XML attribute displayed by a {@link UiResourceAttributeNode}
- * <p/>
- * Used by the override for .../theme in {@link AndroidManifestDescriptors}.
- */
-public final class ThemeAttributeDescriptor extends TextAttributeDescriptor {
-
- /**
- * Used by {@link DescriptorsUtils} to create instances of this descriptor.
- */
- public static final ITextAttributeCreator CREATOR = new ITextAttributeCreator() {
- @Override
- public TextAttributeDescriptor create(String xmlLocalName,
- String nsUri, IAttributeInfo attrInfo) {
- return new ThemeAttributeDescriptor(xmlLocalName, nsUri, attrInfo);
- }
- };
-
- public ThemeAttributeDescriptor(String xmlLocalName, String nsUri, IAttributeInfo attrInfo) {
- super(xmlLocalName, nsUri, attrInfo);
- }
-
- /**
- * @return A new {@link UiResourceAttributeNode} linked to this theme descriptor.
- */
- @Override
- public UiAttributeNode createUiNode(UiElementNode uiParent) {
- return new UiResourceAttributeNode(ResourceType.STYLE, this, uiParent);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/model/UiClassAttributeNode.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/model/UiClassAttributeNode.java
deleted file mode 100644
index 4c829d9ec..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/model/UiClassAttributeNode.java
+++ /dev/null
@@ -1,736 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest.model;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.TextAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.manifest.descriptors.AndroidManifestDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.ui.SectionHelper;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiTextAttributeNode;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.xml.AndroidManifest;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jdt.core.Flags;
-import org.eclipse.jdt.core.IClasspathEntry;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jdt.core.IPackageFragmentRoot;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.core.ITypeHierarchy;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.core.search.IJavaSearchScope;
-import org.eclipse.jdt.core.search.SearchEngine;
-import org.eclipse.jdt.ui.IJavaElementSearchConstants;
-import org.eclipse.jdt.ui.JavaUI;
-import org.eclipse.jdt.ui.actions.OpenNewClassWizardAction;
-import org.eclipse.jdt.ui.dialogs.ITypeInfoFilterExtension;
-import org.eclipse.jdt.ui.dialogs.ITypeInfoRequestor;
-import org.eclipse.jdt.ui.dialogs.ITypeSelectionComponent;
-import org.eclipse.jdt.ui.dialogs.TypeSelectionExtension;
-import org.eclipse.jdt.ui.wizards.NewClassWizardPage;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.SelectionDialog;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.events.HyperlinkAdapter;
-import org.eclipse.ui.forms.events.HyperlinkEvent;
-import org.eclipse.ui.forms.widgets.FormText;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.TableWrapData;
-import org.w3c.dom.Element;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * Represents an XML attribute for a class, that can be modified using a simple text field or
- * a dialog to choose an existing class. Also, there's a link to create a new class.
- * <p/>
- * See {@link UiTextAttributeNode} for more information.
- */
-public class UiClassAttributeNode extends UiTextAttributeNode {
-
- private String mReferenceClass;
- private IPostTypeCreationAction mPostCreationAction;
- private boolean mMandatory;
- private final boolean mDefaultToProjectOnly;
-
- private class HierarchyTypeSelection extends TypeSelectionExtension {
-
- private IJavaProject mJavaProject;
- private IType mReferenceType;
- private Button mProjectOnly;
- private boolean mUseProjectOnly;
-
- public HierarchyTypeSelection(IProject project, String referenceClass)
- throws JavaModelException {
- mJavaProject = JavaCore.create(project);
- mReferenceType = mJavaProject.findType(referenceClass);
- }
-
- @Override
- public ITypeInfoFilterExtension getFilterExtension() {
- return new ITypeInfoFilterExtension() {
- @Override
- public boolean select(ITypeInfoRequestor typeInfoRequestor) {
-
- boolean projectOnly = mUseProjectOnly;
-
- String packageName = typeInfoRequestor.getPackageName();
- String typeName = typeInfoRequestor.getTypeName();
- String enclosingType = typeInfoRequestor.getEnclosingName();
-
- // build the full class name.
- StringBuilder sb = new StringBuilder(packageName);
- sb.append('.');
- if (enclosingType.length() > 0) {
- sb.append(enclosingType);
- sb.append('.');
- }
- sb.append(typeName);
-
- String className = sb.toString();
-
- try {
- IType type = mJavaProject.findType(className);
-
- if (type == null) {
- return false;
- }
-
- // don't display abstract classes
- if ((type.getFlags() & Flags.AccAbstract) != 0) {
- return false;
- }
-
- // if project-only is selected, make sure the package fragment is
- // an actual source (thus "from this project").
- if (projectOnly) {
- IPackageFragment frag = type.getPackageFragment();
- if (frag == null || frag.getKind() != IPackageFragmentRoot.K_SOURCE) {
- return false;
- }
- }
-
- // get the type hierarchy and reference type is one of the super classes.
- ITypeHierarchy hierarchy = type.newSupertypeHierarchy(
- new NullProgressMonitor());
-
- IType[] supertypes = hierarchy.getAllSupertypes(type);
- int n = supertypes.length;
- for (int i = 0; i < n; i++) {
- IType st = supertypes[i];
- if (mReferenceType.equals(st)) {
- return true;
- }
- }
- } catch (JavaModelException e) {
- }
-
- return false;
- }
- };
- }
-
- @Override
- public Control createContentArea(Composite parent) {
-
- mProjectOnly = new Button(parent, SWT.CHECK);
- mProjectOnly.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mProjectOnly.setText(String.format("Display classes from sources of project '%s' only",
- mJavaProject.getProject().getName()));
-
- mUseProjectOnly = mDefaultToProjectOnly;
- mProjectOnly.setSelection(mUseProjectOnly);
-
- mProjectOnly.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- super.widgetSelected(e);
- mUseProjectOnly = mProjectOnly.getSelection();
- getTypeSelectionComponent().triggerSearch();
- }
- });
-
- return super.createContentArea(parent);
- }
- }
-
- /**
- * Classes which implement this interface provide a method processing newly created classes.
- */
- public static interface IPostTypeCreationAction {
- /**
- * Sent to process a newly created class.
- * @param newType the IType representing the newly created class.
- */
- public void processNewType(IType newType);
- }
-
- /**
- * Creates a {@link UiClassAttributeNode} object that will display ui to select or create
- * classes.
- * @param referenceClass The allowed supertype of the classes that are to be selected
- * or created. Can be null.
- * @param postCreationAction a {@link IPostTypeCreationAction} object handling post creation
- * modification of the class.
- * @param mandatory indicates if the class value is mandatory
- * @param attributeDescriptor the {@link AttributeDescriptor} object linked to the Ui Node.
- * @param defaultToProjectOnly When true display classes of this project only by default.
- * When false any class path will be considered. The user can always toggle this.
- */
- public UiClassAttributeNode(String referenceClass, IPostTypeCreationAction postCreationAction,
- boolean mandatory, AttributeDescriptor attributeDescriptor, UiElementNode uiParent,
- boolean defaultToProjectOnly) {
- super(attributeDescriptor, uiParent);
-
- mReferenceClass = referenceClass;
- mPostCreationAction = postCreationAction;
- mMandatory = mandatory;
- mDefaultToProjectOnly = defaultToProjectOnly;
- }
-
- /* (non-java doc)
- * Creates a label widget and an associated text field.
- * <p/>
- * As most other parts of the android manifest editor, this assumes the
- * parent uses a table layout with 2 columns.
- */
- @Override
- public void createUiControl(final Composite parent, IManagedForm managedForm) {
- setManagedForm(managedForm);
- FormToolkit toolkit = managedForm.getToolkit();
- TextAttributeDescriptor desc = (TextAttributeDescriptor) getDescriptor();
-
- StringBuilder label = new StringBuilder();
- label.append("<form><p><a href='unused'>");
- label.append(desc.getUiName());
- label.append("</a></p></form>");
- FormText formText = SectionHelper.createFormText(parent, toolkit, true /* isHtml */,
- label.toString(), true /* setupLayoutData */);
- formText.addHyperlinkListener(new HyperlinkAdapter() {
- @Override
- public void linkActivated(HyperlinkEvent e) {
- super.linkActivated(e);
- handleLabelClick();
- }
- });
- formText.setLayoutData(new TableWrapData(TableWrapData.LEFT, TableWrapData.MIDDLE));
- SectionHelper.addControlTooltip(formText, desc.getTooltip());
-
- Composite composite = toolkit.createComposite(parent);
- composite.setLayoutData(new TableWrapData(TableWrapData.FILL_GRAB, TableWrapData.MIDDLE));
- GridLayout gl = new GridLayout(2, false);
- gl.marginHeight = gl.marginWidth = 0;
- composite.setLayout(gl);
- // Fixes missing text borders under GTK... also requires adding a 1-pixel margin
- // for the text field below
- toolkit.paintBordersFor(composite);
-
- final Text text = toolkit.createText(composite, getCurrentValue());
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalIndent = 1; // Needed by the fixed composite borders under GTK
- text.setLayoutData(gd);
- Button browseButton = toolkit.createButton(composite, "Browse...", SWT.PUSH);
-
- setTextWidget(text);
-
- browseButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- super.widgetSelected(e);
- handleBrowseClick();
- }
- });
- }
-
- /* (non-java doc)
- *
- * Add a modify listener that will check the validity of the class
- */
- @Override
- protected void onAddValidators(final Text text) {
- ModifyListener listener = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- try {
- String textValue = text.getText().trim();
- if (textValue.length() == 0) {
- if (mMandatory) {
- setErrorMessage("Value is mandatory", text);
- } else {
- setErrorMessage(null, text);
- }
- return;
- }
- // first we need the current java package.
- String javaPackage = getManifestPackage();
-
- // build the fully qualified name of the class
- String className = AndroidManifest.combinePackageAndClassName(
- javaPackage, textValue);
-
- // only test the vilibility for activities.
- boolean testVisibility = SdkConstants.CLASS_ACTIVITY.equals(
- mReferenceClass);
-
- // test the class
- setErrorMessage(BaseProjectHelper.testClassForManifest(
- BaseProjectHelper.getJavaProject(getProject()), className,
- mReferenceClass, testVisibility), text);
- } catch (CoreException ce) {
- setErrorMessage(ce.getMessage(), text);
- }
- }
- };
-
- text.addModifyListener(listener);
-
- // Make sure the validator removes its message(s) when the widget is disposed
- text.addDisposeListener(new DisposeListener() {
- @Override
- public void widgetDisposed(DisposeEvent e) {
- // we don't want to use setErrorMessage, because we don't want to reset
- // the error flag in the UiAttributeNode
- getManagedForm().getMessageManager().removeMessage(text, text);
- }
- });
-
- // Finally call the validator once to make sure the initial value is processed
- listener.modifyText(null);
- }
-
- private void handleBrowseClick() {
- Text text = getTextWidget();
-
- // we need to get the project of the manifest.
- IProject project = getProject();
- if (project != null) {
-
- // Create a search scope including only the source folder of the current
- // project.
- IPackageFragmentRoot[] packageFragmentRoots = getPackageFragmentRoots(project,
- true /*include_containers*/);
- IJavaSearchScope scope = SearchEngine.createJavaSearchScope(
- packageFragmentRoots,
- false);
-
- try {
- SelectionDialog dlg = JavaUI.createTypeDialog(text.getShell(),
- PlatformUI.getWorkbench().getProgressService(),
- scope,
- IJavaElementSearchConstants.CONSIDER_CLASSES, // style
- false, // no multiple selection
- "**", //$NON-NLS-1$ //filter
- new HierarchyTypeSelection(project, mReferenceClass));
- dlg.setMessage(String.format("Select class name for element %1$s:",
- getUiParent().getBreadcrumbTrailDescription(false /* include_root */)));
- if (dlg instanceof ITypeSelectionComponent) {
- ((ITypeSelectionComponent)dlg).triggerSearch();
- }
-
- if (dlg.open() == Window.OK) {
- Object[] results = dlg.getResult();
- if (results.length == 1) {
- handleNewType((IType)results[0]);
- }
- }
- } catch (JavaModelException e1) {
- AdtPlugin.log(e1, "UiClassAttributeNode HandleBrowser failed");
- }
- }
- }
-
- private void handleLabelClick() {
- // get the current value
- String className = getTextWidget().getText().trim();
-
- // get the package name from the manifest.
- String packageName = getManifestPackage();
-
- if (className.length() == 0) {
- createNewClass(packageName, null /* className */);
- } else {
- // build back the fully qualified class name.
- String fullClassName = className;
- if (className.startsWith(".")) { //$NON-NLS-1$
- fullClassName = packageName + className;
- } else {
- String[] segments = className.split(AdtConstants.RE_DOT);
- if (segments.length == 1) {
- fullClassName = packageName + "." + className; //$NON-NLS-1$
- }
- }
-
- // in case the type is enclosed, we need to replace the $ with .
- fullClassName = fullClassName.replaceAll("\\$", "\\."); //$NON-NLS-1$ //$NON-NLS2$
-
- // now we try to find the file that contains this class and we open it in the editor.
- IProject project = getProject();
- IJavaProject javaProject = JavaCore.create(project);
-
- try {
- IType result = javaProject.findType(fullClassName);
- if (result != null) {
- JavaUI.openInEditor(result);
- } else {
- // split the last segment from the fullClassname
- int index = fullClassName.lastIndexOf('.');
- if (index != -1) {
- createNewClass(fullClassName.substring(0, index),
- fullClassName.substring(index+1));
- } else {
- createNewClass(packageName, className);
- }
- }
- } catch (JavaModelException e) {
- AdtPlugin.log(e, "UiClassAttributeNode HandleLabel failed");
- } catch (PartInitException e) {
- AdtPlugin.log(e, "UiClassAttributeNode HandleLabel failed");
- }
- }
- }
-
- private IProject getProject() {
- UiElementNode uiNode = getUiParent();
- AndroidXmlEditor editor = uiNode.getEditor();
- IEditorInput input = editor.getEditorInput();
- if (input instanceof IFileEditorInput) {
- // from the file editor we can get the IFile object, and from it, the IProject.
- IFile file = ((IFileEditorInput)input).getFile();
- return file.getProject();
- }
-
- return null;
- }
-
-
- /**
- * Returns the current value of the /manifest/package attribute.
- * @return the package or an empty string if not found
- */
- private String getManifestPackage() {
- // get the root uiNode to get the 'package' attribute value.
- UiElementNode rootNode = getUiParent().getUiRoot();
-
- Element xmlElement = (Element) rootNode.getXmlNode();
-
- if (xmlElement != null) {
- return xmlElement.getAttribute(AndroidManifestDescriptors.PACKAGE_ATTR);
- }
- return ""; //$NON-NLS-1$
- }
-
-
- /**
- * Computes and return the {@link IPackageFragmentRoot}s corresponding to the source folders of
- * the specified project.
- * @param project the project
- * @param include_containers True to include containers
- * @return an array of IPackageFragmentRoot.
- */
- private IPackageFragmentRoot[] getPackageFragmentRoots(IProject project,
- boolean include_containers) {
- ArrayList<IPackageFragmentRoot> result = new ArrayList<IPackageFragmentRoot>();
- try {
- IJavaProject javaProject = JavaCore.create(project);
- IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
- for (int i = 0; i < roots.length; i++) {
- IClasspathEntry entry = roots[i].getRawClasspathEntry();
- if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE ||
- (include_containers &&
- entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER)) {
- result.add(roots[i]);
- }
- }
- } catch (JavaModelException e) {
- }
-
- return result.toArray(new IPackageFragmentRoot[result.size()]);
- }
-
- private void handleNewType(IType type) {
- Text text = getTextWidget();
-
- // get the fully qualified name with $ to properly detect the enclosing types.
- String name = type.getFullyQualifiedName('$');
-
- String packageValue = getManifestPackage();
-
- // check if the class doesn't start with the package.
- if (packageValue.length() > 0 && name.startsWith(packageValue)) {
- // if it does, we remove the package and the first dot.
- name = name.substring(packageValue.length() + 1);
-
- // look for how many segments we have left.
- // if one, just write it that way.
- // if more than one, write it with a leading dot.
- String[] packages = name.split(AdtConstants.RE_DOT);
- if (packages.length == 1) {
- text.setText(name);
- } else {
- text.setText("." + name); //$NON-NLS-1$
- }
- } else {
- text.setText(name);
- }
- }
-
- private void createNewClass(String packageName, String className) {
- // create the wizard page for the class creation, and configure it
- NewClassWizardPage page = new NewClassWizardPage();
-
- // set the parent class
- page.setSuperClass(mReferenceClass, true /* canBeModified */);
-
- // get the source folders as java elements.
- IPackageFragmentRoot[] roots = getPackageFragmentRoots(getProject(),
- true /*include_containers*/);
-
- IPackageFragmentRoot currentRoot = null;
- IPackageFragment currentFragment = null;
- int packageMatchCount = -1;
-
- for (IPackageFragmentRoot root : roots) {
- // Get the java element for the package.
- // This method is said to always return a IPackageFragment even if the
- // underlying folder doesn't exist...
- IPackageFragment fragment = root.getPackageFragment(packageName);
- if (fragment != null && fragment.exists()) {
- // we have a perfect match! we use it.
- currentRoot = root;
- currentFragment = fragment;
- packageMatchCount = -1;
- break;
- } else {
- // we don't have a match. we look for the fragment with the best match
- // (ie the closest parent package we can find)
- try {
- IJavaElement[] children;
- children = root.getChildren();
- for (IJavaElement child : children) {
- if (child instanceof IPackageFragment) {
- fragment = (IPackageFragment)child;
- if (packageName.startsWith(fragment.getElementName())) {
- // its a match. get the number of segments
- String[] segments = fragment.getElementName().split("\\."); //$NON-NLS-1$
- if (segments.length > packageMatchCount) {
- packageMatchCount = segments.length;
- currentFragment = fragment;
- currentRoot = root;
- }
- }
- }
- }
- } catch (JavaModelException e) {
- // Couldn't get the children: we just ignore this package root.
- }
- }
- }
-
- ArrayList<IPackageFragment> createdFragments = null;
-
- if (currentRoot != null) {
- // if we have a perfect match, we set it and we're done.
- if (packageMatchCount == -1) {
- page.setPackageFragmentRoot(currentRoot, true /* canBeModified*/);
- page.setPackageFragment(currentFragment, true /* canBeModified */);
- } else {
- // we have a partial match.
- // create the package. We have to start with the first segment so that we
- // know what to delete in case of a cancel.
- try {
- createdFragments = new ArrayList<IPackageFragment>();
-
- int totalCount = packageName.split("\\.").length; //$NON-NLS-1$
- int count = 0;
- int index = -1;
- // skip the matching packages
- while (count < packageMatchCount) {
- index = packageName.indexOf('.', index+1);
- count++;
- }
-
- // create the rest of the segments, except for the last one as indexOf will
- // return -1;
- while (count < totalCount - 1) {
- index = packageName.indexOf('.', index+1);
- count++;
- createdFragments.add(currentRoot.createPackageFragment(
- packageName.substring(0, index),
- true /* force*/, new NullProgressMonitor()));
- }
-
- // create the last package
- createdFragments.add(currentRoot.createPackageFragment(
- packageName, true /* force*/, new NullProgressMonitor()));
-
- // set the root and fragment in the Wizard page
- page.setPackageFragmentRoot(currentRoot, true /* canBeModified*/);
- page.setPackageFragment(createdFragments.get(createdFragments.size()-1),
- true /* canBeModified */);
- } catch (JavaModelException e) {
- // if we can't create the packages, there's a problem. we revert to the default
- // package
- for (IPackageFragmentRoot root : roots) {
- // Get the java element for the package.
- // This method is said to always return a IPackageFragment even if the
- // underlying folder doesn't exist...
- IPackageFragment fragment = root.getPackageFragment(packageName);
- if (fragment != null && fragment.exists()) {
- page.setPackageFragmentRoot(root, true /* canBeModified*/);
- page.setPackageFragment(fragment, true /* canBeModified */);
- break;
- }
- }
- }
- }
- } else if (roots.length > 0) {
- // if we haven't found a valid fragment, we set the root to the first source folder.
- page.setPackageFragmentRoot(roots[0], true /* canBeModified*/);
- }
-
- // if we have a starting class name we use it
- if (className != null) {
- page.setTypeName(className, true /* canBeModified*/);
- }
-
- // create the action that will open it the wizard.
- OpenNewClassWizardAction action = new OpenNewClassWizardAction();
- action.setConfiguredWizardPage(page);
- action.run();
- IJavaElement element = action.getCreatedElement();
-
- if (element != null) {
- if (element.getElementType() == IJavaElement.TYPE) {
-
- IType type = (IType)element;
-
- if (mPostCreationAction != null) {
- mPostCreationAction.processNewType(type);
- }
-
- handleNewType(type);
- }
- } else {
- // lets delete the packages we created just for this.
- // we need to start with the leaf and go up
- if (createdFragments != null) {
- try {
- for (int i = createdFragments.size() - 1 ; i >= 0 ; i--) {
- createdFragments.get(i).delete(true /* force*/, new NullProgressMonitor());
- }
- } catch (JavaModelException e) {
- e.printStackTrace();
- }
- }
- }
- }
-
- /**
- * Sets the error messages. If message is <code>null</code>, the message is removed.
- * @param message the message to set, or <code>null</code> to remove the current message
- * @param textWidget the {@link Text} widget associated to the message.
- */
- private final void setErrorMessage(String message, Text textWidget) {
- if (message != null) {
- setHasError(true);
- getManagedForm().getMessageManager().addMessage(textWidget, message, null /* data */,
- IMessageProvider.ERROR, textWidget);
- } else {
- setHasError(false);
- getManagedForm().getMessageManager().removeMessage(textWidget, textWidget);
- }
- }
-
- @Override
- public String[] getPossibleValues(String prefix) {
- // Compute a list of existing classes for content assist completion
- IProject project = getProject();
- if (project == null || mReferenceClass == null) {
- return null;
- }
-
- try {
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
- IType type = javaProject.findType(mReferenceClass);
- // Use sets because query sometimes repeats the same class
- Set<String> libraryTypes = new HashSet<String>(80);
- Set<String> localTypes = new HashSet<String>(30);
- if (type != null) {
- ITypeHierarchy hierarchy = type.newTypeHierarchy(new NullProgressMonitor());
- IType[] allSubtypes = hierarchy.getAllSubtypes(type);
- for (IType subType : allSubtypes) {
- int flags = subType.getFlags();
- if (Flags.isPublic(flags) && !Flags.isAbstract(flags)) {
- String fqcn = subType.getFullyQualifiedName();
- if (subType.getResource() != null) {
- localTypes.add(fqcn);
- } else {
- libraryTypes.add(fqcn);
- }
- }
- }
- }
-
- List<String> local = new ArrayList<String>(localTypes);
- List<String> library = new ArrayList<String>(libraryTypes);
- Collections.sort(local);
- Collections.sort(library);
- List<String> combined = new ArrayList<String>(local.size() + library.size());
- combined.addAll(local);
- combined.addAll(library);
- return combined.toArray(new String[combined.size()]);
- } catch (Exception e) {
- AdtPlugin.log(e, null);
- }
-
- return null;
- }
-}
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/model/UiManifestElementNode.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/model/UiManifestElementNode.java
deleted file mode 100644
index 0151d4d46..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/model/UiManifestElementNode.java
+++ /dev/null
@@ -1,132 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest.model;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.manifest.descriptors.AndroidManifestDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.manifest.descriptors.ManifestElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-
-import org.w3c.dom.Element;
-
-/**
- * Represents an XML node that can be modified by the user interface in the XML editor.
- * <p/>
- * Each tree viewer used in the application page's parts needs to keep a model representing
- * each underlying node in the tree. This interface represents the base type for such a node.
- * <p/>
- * Each node acts as an intermediary model between the actual XML model (the real data support)
- * and the tree viewers or the corresponding page parts.
- * <p/>
- * Element nodes don't contain data per se. Their data is contained in their attributes
- * as well as their children's attributes, see {@link UiAttributeNode}.
- * <p/>
- * The structure of a given {@link UiElementNode} is declared by a corresponding
- * {@link ElementDescriptor}.
- */
-public final class UiManifestElementNode extends UiElementNode {
-
- /**
- * Creates a new {@link UiElementNode} described by a given {@link ElementDescriptor}.
- *
- * @param elementDescriptor The {@link ElementDescriptor} for the XML node. Cannot be null.
- */
- public UiManifestElementNode(ManifestElementDescriptor elementDescriptor) {
- super(elementDescriptor);
- }
-
- /**
- * Computes a short string describing the UI node suitable for tree views.
- * Uses the element's attribute "android:name" if present, or the "android:label" one
- * followed by the element's name if not repeated.
- *
- * @return A short string describing the UI node suitable for tree views.
- */
- @Override
- public String getShortDescription() {
- AndroidTargetData target = getAndroidTarget();
- AndroidManifestDescriptors manifestDescriptors = null;
- if (target != null) {
- manifestDescriptors = target.getManifestDescriptors();
- }
-
- String name = getDescriptor().getUiName();
-
- if (manifestDescriptors != null &&
- getXmlNode() != null &&
- getXmlNode() instanceof Element &&
- getXmlNode().hasAttributes()) {
-
- // Application and Manifest nodes have a special treatment: they are unique nodes
- // so we don't bother trying to differentiate their strings and we fall back to
- // just using the UI name below.
- ElementDescriptor desc = getDescriptor();
- if (desc != manifestDescriptors.getManifestElement() &&
- desc != manifestDescriptors.getApplicationElement()) {
- Element elem = (Element) getXmlNode();
- String attr = _Element_getAttributeNS(elem,
- SdkConstants.NS_RESOURCES,
- AndroidManifestDescriptors.ANDROID_NAME_ATTR);
- if (attr == null || attr.length() == 0) {
- attr = _Element_getAttributeNS(elem,
- SdkConstants.NS_RESOURCES,
- AndroidManifestDescriptors.ANDROID_LABEL_ATTR);
- }
- if (attr != null && attr.length() > 0) {
- // If the ui name is repeated in the attribute value, don't use it.
- // Typical case is to avoid ".pkg.MyActivity (Activity)".
- if (attr.contains(name)) {
- return attr;
- } else {
- return String.format("%1$s (%2$s)", attr, name);
- }
- }
- }
- }
-
- return String.format("%1$s", name);
- }
-
- /**
- * Retrieves an attribute value by local name and namespace URI.
- * <br>Per [<a href='http://www.w3.org/TR/1999/REC-xml-names-19990114/'>XML Namespaces</a>]
- * , applications must use the value <code>null</code> as the
- * <code>namespaceURI</code> parameter for methods if they wish to have
- * no namespace.
- * <p/>
- * Note: This is a wrapper around {@link Element#getAttributeNS(String, String)}.
- * In some versions of webtools, the getAttributeNS implementation crashes with an NPE.
- * This wrapper will return null instead.
- *
- * @see Element#getAttributeNS(String, String)
- * @see <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=318108">https://bugs.eclipse.org/bugs/show_bug.cgi?id=318108</a>
- * @return The result from {@link Element#getAttributeNS(String, String)} or or an empty string.
- */
- private String _Element_getAttributeNS(Element element,
- String namespaceURI,
- String localName) {
- try {
- return element.getAttributeNS(namespaceURI, localName);
- } catch (Exception ignore) {
- return "";
- }
- }
-}
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/model/UiManifestPkgAttrNode.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/model/UiManifestPkgAttrNode.java
deleted file mode 100755
index 60d9125f6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/model/UiManifestPkgAttrNode.java
+++ /dev/null
@@ -1,331 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest.model;
-
-import com.android.ide.common.xml.ManifestData;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.TextAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestEditor;
-import com.android.ide.eclipse.adt.internal.editors.ui.SectionHelper;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiTextAttributeNode;
-import com.android.ide.eclipse.adt.internal.project.AndroidManifestHelper;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.project.ProjectHelper;
-import com.android.ide.eclipse.adt.internal.wizards.actions.NewProjectAction;
-import com.android.ide.eclipse.adt.internal.wizards.newproject.NewProjectWizard;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.ElementListSelectionDialog;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.events.HyperlinkAdapter;
-import org.eclipse.ui.forms.events.HyperlinkEvent;
-import org.eclipse.ui.forms.widgets.FormText;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.TableWrapData;
-import org.eclipse.ui.part.FileEditorInput;
-
-import java.util.TreeSet;
-
-/**
- * Represents an XML attribute to select an existing manifest package, that can be modified using
- * a simple text field or a dialog to choose an existing package.
- * <p/>
- * See {@link UiTextAttributeNode} for more information.
- */
-public class UiManifestPkgAttrNode extends UiTextAttributeNode {
-
- /**
- * Creates a {@link UiManifestPkgAttrNode} object that will display ui to select or create
- * a manifest package.
- * @param attributeDescriptor the {@link AttributeDescriptor} object linked to the Ui Node.
- */
- public UiManifestPkgAttrNode(AttributeDescriptor attributeDescriptor, UiElementNode uiParent) {
- super(attributeDescriptor, uiParent);
- }
-
- /* (non-java doc)
- * Creates a label widget and an associated text field.
- * <p/>
- * As most other parts of the android manifest editor, this assumes the
- * parent uses a table layout with 2 columns.
- */
- @Override
- public void createUiControl(final Composite parent, final IManagedForm managedForm) {
- setManagedForm(managedForm);
- FormToolkit toolkit = managedForm.getToolkit();
- TextAttributeDescriptor desc = (TextAttributeDescriptor) getDescriptor();
-
- StringBuilder label = new StringBuilder();
- label.append("<form><p><a href='unused'>"); //$NON-NLS-1$
- label.append(desc.getUiName());
- label.append("</a></p></form>"); //$NON-NLS-1$
- FormText formText = SectionHelper.createFormText(parent, toolkit, true /* isHtml */,
- label.toString(), true /* setupLayoutData */);
- formText.addHyperlinkListener(new HyperlinkAdapter() {
- @Override
- public void linkActivated(HyperlinkEvent e) {
- super.linkActivated(e);
- doLabelClick();
- }
- });
- formText.setLayoutData(new TableWrapData(TableWrapData.LEFT, TableWrapData.MIDDLE));
- SectionHelper.addControlTooltip(formText, desc.getTooltip());
-
- Composite composite = toolkit.createComposite(parent);
- composite.setLayoutData(new TableWrapData(TableWrapData.FILL_GRAB, TableWrapData.MIDDLE));
- GridLayout gl = new GridLayout(2, false);
- gl.marginHeight = gl.marginWidth = 0;
- composite.setLayout(gl);
- // Fixes missing text borders under GTK... also requires adding a 1-pixel margin
- // for the text field below
- toolkit.paintBordersFor(composite);
-
- final Text text = toolkit.createText(composite, getCurrentValue());
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalIndent = 1; // Needed by the fixed composite borders under GTK
- text.setLayoutData(gd);
-
- setTextWidget(text);
-
- Button browseButton = toolkit.createButton(composite, "Browse...", SWT.PUSH);
-
- browseButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- super.widgetSelected(e);
- doBrowseClick();
- }
- });
-
- }
-
- /* (non-java doc)
- * Adds a validator to the text field that calls managedForm.getMessageManager().
- */
- @Override
- protected void onAddValidators(final Text text) {
- ModifyListener listener = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- String package_name = text.getText();
- if (package_name.indexOf('.') < 1) {
- getManagedForm().getMessageManager().addMessage(text,
- "Package name should contain at least two identifiers.",
- null /* data */, IMessageProvider.ERROR, text);
- } else {
- getManagedForm().getMessageManager().removeMessage(text, text);
- }
- }
- };
-
- text.addModifyListener(listener);
-
- // Make sure the validator removes its message(s) when the widget is disposed
- text.addDisposeListener(new DisposeListener() {
- @Override
- public void widgetDisposed(DisposeEvent e) {
- getManagedForm().getMessageManager().removeMessage(text, text);
- }
- });
-
- // Finally call the validator once to make sure the initial value is processed
- listener.modifyText(null);
- }
-
- /**
- * Handles response to the Browse button by creating a Package dialog.
- * */
- private void doBrowseClick() {
-
- // Display the list of AndroidManifest packages in a selection dialog
- ElementListSelectionDialog dialog = new ElementListSelectionDialog(
- getTextWidget().getShell(),
- new ILabelProvider() {
- @Override
- public Image getImage(Object element) {
- return null;
- }
-
- @Override
- public String getText(Object element) {
- return element.toString();
- }
-
- @Override
- public void addListener(ILabelProviderListener listener) {
- }
-
- @Override
- public void dispose() {
- }
-
- @Override
- public boolean isLabelProperty(Object element, String property) {
- return false;
- }
-
- @Override
- public void removeListener(ILabelProviderListener listener) {
- }
- });
-
- dialog.setTitle("Android Manifest Package Selection");
- dialog.setMessage("Select the Android Manifest package to target.");
-
- dialog.setElements(getPossibleValues(null));
-
- // open the dialog and use the object selected if OK was clicked, or null otherwise
- if (dialog.open() == Window.OK) {
- String result = (String) dialog.getFirstResult();
- if (result != null && result.length() > 0) {
- getTextWidget().setText(result);
- }
- }
- }
-
- /**
- * Handles response to the Label hyper link being activated.
- */
- private void doLabelClick() {
- // get the current package name
- String package_name = getTextWidget().getText().trim();
-
- if (package_name.length() == 0) {
- createNewProject();
- } else {
- displayExistingManifest(package_name);
- }
- }
-
- /**
- * When the label is clicked and there's already a package name, this method
- * attempts to find the project matching the android package name and it attempts
- * to open the manifest editor.
- *
- * @param package_name The android package name to find. Must not be null.
- */
- private void displayExistingManifest(String package_name) {
-
- // Look for the first project that uses this package name
- for (IJavaProject project : BaseProjectHelper.getAndroidProjects(null /*filter*/)) {
- // check that there is indeed a manifest file.
- IFile manifestFile = ProjectHelper.getManifest(project.getProject());
- if (manifestFile == null) {
- // no file? skip this project.
- continue;
- }
-
- ManifestData manifestData = AndroidManifestHelper.parseForData(manifestFile);
- if (manifestData == null) {
- // skip this project.
- continue;
- }
-
- if (package_name.equals(manifestData.getPackage())) {
- // Found the project.
-
- IWorkbenchWindow win = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- if (win != null) {
- IWorkbenchPage page = win.getActivePage();
- if (page != null) {
- try {
- page.openEditor(
- new FileEditorInput(manifestFile),
- ManifestEditor.ID,
- true, /* activate */
- IWorkbenchPage.MATCH_INPUT);
- } catch (PartInitException e) {
- AdtPlugin.log(e,
- "Opening editor failed for %s", //$NON-NLS-1$
- manifestFile.getFullPath());
- }
- }
- }
-
- // We found the project; even if we failed there's no need to keep looking.
- return;
- }
- }
- }
-
- /**
- * Displays the New Project Wizard to create a new project.
- * If one is successfully created, use the Android Package name.
- */
- private void createNewProject() {
-
- NewProjectAction npwAction = new NewProjectAction();
- npwAction.run(null /*action*/);
- if (npwAction.getDialogResult() == Dialog.OK) {
- NewProjectWizard npw = (NewProjectWizard) npwAction.getWizard();
- String name = npw.getPackageName();
- if (name != null && name.length() > 0) {
- getTextWidget().setText(name);
- }
- }
- }
-
- /**
- * Returns all the possible android package names that could be used.
- * The prefix is not used.
- *
- * {@inheritDoc}
- */
- @Override
- public String[] getPossibleValues(String prefix) {
- TreeSet<String> packages = new TreeSet<String>();
-
- for (IJavaProject project : BaseProjectHelper.getAndroidProjects(null /*filter*/)) {
- // check that there is indeed a manifest file.
- ManifestData manifestData = AndroidManifestHelper.parseForData(project.getProject());
- if (manifestData == null) {
- // skip this project.
- continue;
- }
-
- packages.add(manifestData.getPackage());
- }
-
- return packages.toArray(new String[packages.size()]);
- }
-}
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/model/UiPackageAttributeNode.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/model/UiPackageAttributeNode.java
deleted file mode 100644
index e6a2007b3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/model/UiPackageAttributeNode.java
+++ /dev/null
@@ -1,321 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest.model;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.TextAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.ui.SectionHelper;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiTextAttributeNode;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jdt.core.IClasspathEntry;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jdt.core.IPackageFragmentRoot;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.ui.JavaUI;
-import org.eclipse.jdt.ui.actions.OpenNewPackageWizardAction;
-import org.eclipse.jdt.ui.actions.ShowInPackageViewAction;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.ui.dialogs.SelectionDialog;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.events.HyperlinkAdapter;
-import org.eclipse.ui.forms.events.HyperlinkEvent;
-import org.eclipse.ui.forms.widgets.FormText;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.TableWrapData;
-
-import java.util.ArrayList;
-
-/**
- * Represents an XML attribute for a package, that can be modified using a simple text field or
- * a dialog to choose an existing package. Also, there's a link to create a new package.
- * <p/>
- * See {@link UiTextAttributeNode} for more information.
- */
-public class UiPackageAttributeNode extends UiTextAttributeNode {
-
- /**
- * Creates a {@link UiPackageAttributeNode} object that will display ui to select or create
- * a package.
- * @param attributeDescriptor the {@link AttributeDescriptor} object linked to the Ui Node.
- */
- public UiPackageAttributeNode(AttributeDescriptor attributeDescriptor, UiElementNode uiParent) {
- super(attributeDescriptor, uiParent);
- }
-
- /* (non-java doc)
- * Creates a label widget and an associated text field.
- * <p/>
- * As most other parts of the android manifest editor, this assumes the
- * parent uses a table layout with 2 columns.
- */
- @Override
- public void createUiControl(final Composite parent, final IManagedForm managedForm) {
- setManagedForm(managedForm);
- FormToolkit toolkit = managedForm.getToolkit();
- TextAttributeDescriptor desc = (TextAttributeDescriptor) getDescriptor();
-
- StringBuilder label = new StringBuilder();
- label.append("<form><p><a href='unused'>"); //$NON-NLS-1$
- label.append(desc.getUiName());
- label.append("</a></p></form>"); //$NON-NLS-1$
- FormText formText = SectionHelper.createFormText(parent, toolkit, true /* isHtml */,
- label.toString(), true /* setupLayoutData */);
- formText.addHyperlinkListener(new HyperlinkAdapter() {
- @Override
- public void linkActivated(HyperlinkEvent e) {
- super.linkActivated(e);
- doLabelClick();
- }
- });
- formText.setLayoutData(new TableWrapData(TableWrapData.LEFT, TableWrapData.MIDDLE));
- SectionHelper.addControlTooltip(formText, desc.getTooltip());
-
- Composite composite = toolkit.createComposite(parent);
- composite.setLayoutData(new TableWrapData(TableWrapData.FILL_GRAB, TableWrapData.MIDDLE));
- GridLayout gl = new GridLayout(2, false);
- gl.marginHeight = gl.marginWidth = 0;
- composite.setLayout(gl);
- // Fixes missing text borders under GTK... also requires adding a 1-pixel margin
- // for the text field below
- toolkit.paintBordersFor(composite);
-
- final Text text = toolkit.createText(composite, getCurrentValue());
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalIndent = 1; // Needed by the fixed composite borders under GTK
- text.setLayoutData(gd);
-
- setTextWidget(text);
-
- Button browseButton = toolkit.createButton(composite, "Browse...", SWT.PUSH);
-
- browseButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- super.widgetSelected(e);
- doBrowseClick();
- }
- });
-
- }
-
- /* (non-java doc)
- * Adds a validator to the text field that calls managedForm.getMessageManager().
- */
- @Override
- protected void onAddValidators(final Text text) {
- ModifyListener listener = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- String package_name = text.getText();
- if (package_name.indexOf('.') < 1) {
- getManagedForm().getMessageManager().addMessage(text,
- "Package name should contain at least two identifiers.",
- null /* data */, IMessageProvider.ERROR, text);
- } else {
- getManagedForm().getMessageManager().removeMessage(text, text);
- }
- }
- };
-
- text.addModifyListener(listener);
-
- // Make sure the validator removes its message(s) when the widget is disposed
- text.addDisposeListener(new DisposeListener() {
- @Override
- public void widgetDisposed(DisposeEvent e) {
- getManagedForm().getMessageManager().removeMessage(text, text);
- }
- });
-
- // Finally call the validator once to make sure the initial value is processed
- listener.modifyText(null);
- }
-
- /**
- * Handles response to the Browse button by creating a Package dialog.
- * */
- private void doBrowseClick() {
- Text text = getTextWidget();
-
- // we need to get the project of the manifest.
- IProject project = getProject();
- if (project != null) {
-
- try {
- SelectionDialog dlg = JavaUI.createPackageDialog(text.getShell(),
- JavaCore.create(project), 0);
- dlg.setTitle("Select Android Package");
- dlg.setMessage("Select the package for the Android project.");
- SelectionDialog.setDefaultImage(AdtPlugin.getAndroidLogo());
-
- if (dlg.open() == Window.OK) {
- Object[] results = dlg.getResult();
- if (results.length == 1) {
- setPackageTextField((IPackageFragment)results[0]);
- }
- }
- } catch (JavaModelException e1) {
- }
- }
- }
-
- /**
- * Handles response to the Label hyper link being activated.
- */
- private void doLabelClick() {
- // get the current package name
- String package_name = getTextWidget().getText().trim();
-
- if (package_name.length() == 0) {
- createNewPackage();
- } else {
- // Try to select the package in the Package Explorer for the current
- // project and the current editor's site.
-
- IProject project = getProject();
- if (project == null) {
- AdtPlugin.log(IStatus.ERROR, "Failed to get project for UiPackageAttribute"); //$NON-NLS-1$
- return;
- }
-
- IWorkbenchPartSite site = getUiParent().getEditor().getSite();
- if (site == null) {
- AdtPlugin.log(IStatus.ERROR, "Failed to get editor site for UiPackageAttribute"); //$NON-NLS-1$
- return;
- }
-
- for (IPackageFragmentRoot root : getPackageFragmentRoots(project)) {
- IPackageFragment fragment = root.getPackageFragment(package_name);
- if (fragment != null && fragment.exists()) {
- ShowInPackageViewAction action = new ShowInPackageViewAction(site);
- action.run(fragment);
- // This action's run() doesn't provide the status (although internally it could)
- // so we just assume it worked.
- return;
- }
- }
- }
- }
-
- /**
- * Utility method that returns the project for the current file being edited.
- *
- * @return The IProject for the current file being edited or null.
- */
- private IProject getProject() {
- UiElementNode uiNode = getUiParent();
- AndroidXmlEditor editor = uiNode.getEditor();
- IEditorInput input = editor.getEditorInput();
- if (input instanceof IFileEditorInput) {
- // from the file editor we can get the IFile object, and from it, the IProject.
- IFile file = ((IFileEditorInput)input).getFile();
- return file.getProject();
- }
-
- return null;
- }
-
- /**
- * Utility method that computes and returns the list of {@link IPackageFragmentRoot}
- * corresponding to the source folder of the specified project.
- *
- * @param project the project
- * @return an array of IPackageFragmentRoot. Can be empty but not null.
- */
- private IPackageFragmentRoot[] getPackageFragmentRoots(IProject project) {
- ArrayList<IPackageFragmentRoot> result = new ArrayList<IPackageFragmentRoot>();
- try {
- IJavaProject javaProject = JavaCore.create(project);
- IPackageFragmentRoot[] roots = javaProject.getPackageFragmentRoots();
- for (int i = 0; i < roots.length; i++) {
- IClasspathEntry entry = roots[i].getRawClasspathEntry();
- if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
- result.add(roots[i]);
- }
- }
- } catch (JavaModelException e) {
- }
-
- return result.toArray(new IPackageFragmentRoot[result.size()]);
- }
-
- /**
- * Utility method that sets the package's text field to the package fragment's name.
- * */
- private void setPackageTextField(IPackageFragment type) {
- Text text = getTextWidget();
-
- String name = type.getElementName();
-
- text.setText(name);
- }
-
-
- /**
- * Displays and handles a "Create Package Wizard".
- *
- * This is invoked by doLabelClick() when clicking on the hyperlink label with an
- * empty package text field.
- */
- private void createNewPackage() {
- OpenNewPackageWizardAction action = new OpenNewPackageWizardAction();
-
- IProject project = getProject();
- action.setSelection(new StructuredSelection(project));
- action.run();
-
- IJavaElement element = action.getCreatedElement();
- if (element != null &&
- element.exists() &&
- element.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
- setPackageTextField((IPackageFragment) element);
- }
- }
-
- @Override
- public String[] getPossibleValues(String prefix) {
- // TODO: compute a list of existing packages for content assist completion
- return null;
- }
-}
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/ApplicationAttributesPart.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/ApplicationAttributesPart.java
deleted file mode 100644
index 7d3f6a89f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/ApplicationAttributesPart.java
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest.pages;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.XmlnsAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestEditor;
-import com.android.ide.eclipse.adt.internal.editors.ui.UiElementPart;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.IUiUpdateListener;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.Section;
-
-/**
- * Application's attributes section part for Application page.
- * <p/>
- * This part is displayed at the top of the application page and displays all the possible
- * attributes of an application node in the AndroidManifest (icon, class name, label, etc.)
- */
-final class ApplicationAttributesPart extends UiElementPart {
-
- /** Listen to changes to the UI node for <application> and updates the UI */
- private AppNodeUpdateListener mAppNodeUpdateListener;
- /** ManagedForm needed to create the UI controls */
- private IManagedForm mManagedForm;
-
- public ApplicationAttributesPart(Composite body, FormToolkit toolkit, ManifestEditor editor,
- UiElementNode applicationUiNode) {
- super(body, toolkit, editor, applicationUiNode,
- "Application Attributes", // section title
- "Defines the attributes specific to the application.", // section description
- Section.TWISTIE | Section.EXPANDED);
- }
-
- /**
- * Changes and refreshes the Application UI node handle by the this part.
- */
- @Override
- public void setUiElementNode(UiElementNode uiElementNode) {
- super.setUiElementNode(uiElementNode);
-
- createUiAttributes(mManagedForm);
- }
-
- /* (non-java doc)
- * Create the controls to edit the attributes for the given ElementDescriptor.
- * <p/>
- * This MUST not be called by the constructor. Instead it must be called from
- * <code>initialize</code> (i.e. right after the form part is added to the managed form.)
- * <p/>
- * Derived classes can override this if necessary.
- *
- * @param managedForm The owner managed form
- */
- @Override
- protected void createFormControls(final IManagedForm managedForm) {
- mManagedForm = managedForm;
- setTable(createTableLayout(managedForm.getToolkit(), 4 /* numColumns */));
-
- mAppNodeUpdateListener = new AppNodeUpdateListener();
- getUiElementNode().addUpdateListener(mAppNodeUpdateListener);
-
- createUiAttributes(mManagedForm);
- }
-
- @Override
- public void dispose() {
- super.dispose();
- if (getUiElementNode() != null && mAppNodeUpdateListener != null) {
- getUiElementNode().removeUpdateListener(mAppNodeUpdateListener);
- mAppNodeUpdateListener = null;
- }
- }
-
- @Override
- protected void createUiAttributes(IManagedForm managedForm) {
- Composite table = getTable();
- if (table == null || managedForm == null) {
- return;
- }
-
- // Remove any old UI controls
- for (Control c : table.getChildren()) {
- c.dispose();
- }
-
- UiElementNode uiElementNode = getUiElementNode();
- AttributeDescriptor[] attr_desc_list = uiElementNode.getAttributeDescriptors();
-
- // Display the attributes in 2 columns:
- // attr 0 | attr 4
- // attr 1 | attr 5
- // attr 2 | attr 6
- // attr 3 | attr 7
- // that is we have to fill the grid in order 0, 4, 1, 5, 2, 6, 3, 7
- // thus index = i/2 + (i is odd * n/2)
- int n = attr_desc_list.length;
- int n2 = (int) Math.ceil(n / 2.0);
- for (int i = 0; i < n; i++) {
- AttributeDescriptor attr_desc = attr_desc_list[i / 2 + (i & 1) * n2];
- if (attr_desc instanceof XmlnsAttributeDescriptor) {
- // Do not show hidden attributes
- continue;
- }
-
- UiAttributeNode ui_attr = uiElementNode.findUiAttribute(attr_desc);
- if (ui_attr != null) {
- ui_attr.createUiControl(table, managedForm);
- } else {
- // The XML has an extra attribute which wasn't declared in
- // AndroidManifestDescriptors. This is not a problem, we just ignore it.
- AdtPlugin.log(IStatus.WARNING,
- "Attribute %1$s not declared in node %2$s, ignored.", //$NON-NLS-1$
- attr_desc.getXmlLocalName(),
- uiElementNode.getDescriptor().getXmlName());
- }
- }
-
- if (n == 0) {
- createLabel(table, managedForm.getToolkit(),
- "No attributes to display, waiting for SDK to finish loading...",
- null /* tooltip */ );
- }
-
- // Initialize the enabled/disabled state
- if (mAppNodeUpdateListener != null) {
- mAppNodeUpdateListener.uiElementNodeUpdated(uiElementNode, null /* state, not used */);
- }
-
- // Tell the section that the layout has changed.
- layoutChanged();
- }
-
- /**
- * This listener synchronizes the UI with the actual presence of the application XML node.
- */
- private class AppNodeUpdateListener implements IUiUpdateListener {
- @Override
- public void uiElementNodeUpdated(UiElementNode ui_node, UiUpdateState state) {
- // The UiElementNode for the application XML node always exists, even
- // if there is no corresponding XML node in the XML file.
- //
- // We enable the UI here if the XML node is not null.
- Composite table = getTable();
- boolean exists = (ui_node.getXmlNode() != null);
- if (table != null && table.getEnabled() != exists) {
- table.setEnabled(exists);
- for (Control c : table.getChildren()) {
- c.setEnabled(exists);
- }
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/ApplicationPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/ApplicationPage.java
deleted file mode 100644
index 06a3d3f3e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/ApplicationPage.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest.pages;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.IPageImageProvider;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestEditor;
-import com.android.ide.eclipse.adt.internal.editors.manifest.descriptors.AndroidManifestDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.ui.tree.UiTreeBlock;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-
-
-/**
- * Page for "Application" settings, part of the AndroidManifest form editor.
- * <p/>
- * Useful reference:
- * <a href="http://www.eclipse.org/articles/Article-Forms/article.html">
- * http://www.eclipse.org/articles/Article-Forms/article.html</a>
- */
-public final class ApplicationPage extends FormPage implements IPageImageProvider {
- /** Page id used for switching tabs programmatically */
- public final static String PAGE_ID = "application_page"; //$NON-NLS-1$
-
- /** Container editor */
- ManifestEditor mEditor;
- /** The Application Toogle part */
- private ApplicationToggle mTooglePart;
- /** The Application Attributes part */
- private ApplicationAttributesPart mAttrPart;
- /** The tree view block */
- private UiTreeBlock mTreeBlock;
-
- public ApplicationPage(ManifestEditor editor) {
- super(editor, PAGE_ID, "Application"); // tab's label, keep it short
- mEditor = editor;
- }
-
- @Override
- public Image getPageImage() {
- return IconFactory.getInstance().getIcon(getTitle(),
- IconFactory.COLOR_BLUE,
- IconFactory.SHAPE_RECT);
- }
-
- /**
- * Creates the content in the form hosted in this page.
- *
- * @param managedForm the form hosted in this page.
- */
- @Override
- protected void createFormContent(IManagedForm managedForm) {
- super.createFormContent(managedForm);
- ScrolledForm form = managedForm.getForm();
- form.setText("Android Manifest Application");
- form.setImage(AdtPlugin.getAndroidLogo());
-
- UiElementNode appUiNode = getUiApplicationNode();
-
- Composite body = form.getBody();
- FormToolkit toolkit = managedForm.getToolkit();
-
- // We usually prefer to have a ColumnLayout here. However
- // MasterDetailsBlock.createContent() below will reset the body's layout to a grid layout.
- mTooglePart = new ApplicationToggle(body, toolkit, mEditor, appUiNode);
- mTooglePart.getSection().setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- managedForm.addPart(mTooglePart);
- mAttrPart = new ApplicationAttributesPart(body, toolkit, mEditor, appUiNode);
- mAttrPart.getSection().setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- managedForm.addPart(mAttrPart);
-
- mTreeBlock = new UiTreeBlock(mEditor, appUiNode,
- false /* autoCreateRoot */,
- null /* element filters */,
- "Application Nodes",
- "List of all elements in the application");
- mTreeBlock.createContent(managedForm);
- }
-
- /**
- * Retrieves the application UI node. Since this is a mandatory node, it *always*
- * exists, even if there is no matching XML node.
- */
- private UiElementNode getUiApplicationNode() {
- AndroidManifestDescriptors manifestDescriptor = mEditor.getManifestDescriptors();
- if (manifestDescriptor != null) {
- ElementDescriptor desc = manifestDescriptor.getApplicationElement();
- return mEditor.getUiRootNode().findUiChildNode(desc.getXmlName());
- } else {
- // return the ui root node, as a dummy application root node.
- return mEditor.getUiRootNode();
- }
- }
-
- /**
- * Changes and refreshes the Application UI node handled by the sub parts.
- */
- public void refreshUiApplicationNode() {
- UiElementNode appUiNode = getUiApplicationNode();
- if (mTooglePart != null) {
- mTooglePart.setUiElementNode(appUiNode);
- }
- if (mAttrPart != null) {
- mAttrPart.setUiElementNode(appUiNode);
- }
- if (mTreeBlock != null) {
- mTreeBlock.changeRootAndDescriptors(appUiNode,
- null /* element filters */,
- true /* refresh */);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/ApplicationToggle.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/ApplicationToggle.java
deleted file mode 100644
index 159f08959..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/ApplicationToggle.java
+++ /dev/null
@@ -1,312 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest.pages;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestEditor;
-import com.android.ide.eclipse.adt.internal.editors.ui.UiElementPart;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.IUiUpdateListener;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.IUiUpdateListener.UiUpdateState;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.utils.SdkUtils;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.widgets.FormText;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.Section;
-import org.eclipse.ui.forms.widgets.TableWrapData;
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-import org.w3c.dom.Text;
-
-/**
- * Appllication Toogle section part for application page.
- */
-final class ApplicationToggle extends UiElementPart {
-
- /** Checkbox indicating whether an application node is present */
- private Button mCheckbox;
- /** Listen to changes to the UI node for <application> and updates the checkbox */
- private AppNodeUpdateListener mAppNodeUpdateListener;
- /** Internal flag to know where we're programmatically modifying the checkbox and we want to
- * avoid triggering the checkbox's callback. */
- public boolean mInternalModification;
- private FormText mTooltipFormText;
-
- public ApplicationToggle(Composite body, FormToolkit toolkit, ManifestEditor editor,
- UiElementNode applicationUiNode) {
- super(body, toolkit, editor, applicationUiNode,
- "Application Toggle",
- null, /* description */
- Section.TWISTIE | Section.EXPANDED);
- }
-
- @Override
- public void dispose() {
- super.dispose();
- if (getUiElementNode() != null && mAppNodeUpdateListener != null) {
- getUiElementNode().removeUpdateListener(mAppNodeUpdateListener);
- mAppNodeUpdateListener = null;
- }
- }
-
- /**
- * Changes and refreshes the Application UI node handle by the this part.
- */
- @Override
- public void setUiElementNode(UiElementNode uiElementNode) {
- super.setUiElementNode(uiElementNode);
-
- updateTooltip();
-
- // Set the state of the checkbox
- mAppNodeUpdateListener.uiElementNodeUpdated(getUiElementNode(),
- UiUpdateState.CHILDREN_CHANGED);
- }
-
- /**
- * Create the controls to edit the attributes for the given ElementDescriptor.
- * <p/>
- * This MUST not be called by the constructor. Instead it must be called from
- * <code>initialize</code> (i.e. right after the form part is added to the managed form.)
- *
- * @param managedForm The owner managed form
- */
- @Override
- protected void createFormControls(IManagedForm managedForm) {
- FormToolkit toolkit = managedForm.getToolkit();
- Composite table = createTableLayout(toolkit, 1 /* numColumns */);
-
- mTooltipFormText = createFormText(table, toolkit, true, "<form></form>",
- false /* setupLayoutData */);
- updateTooltip();
-
- mCheckbox = toolkit.createButton(table,
- "Define an <application> tag in the AndroidManifest.xml",
- SWT.CHECK);
- mCheckbox.setLayoutData(new TableWrapData(TableWrapData.FILL_GRAB, TableWrapData.TOP));
- mCheckbox.setSelection(false);
- mCheckbox.addSelectionListener(new CheckboxSelectionListener());
-
- mAppNodeUpdateListener = new AppNodeUpdateListener();
- getUiElementNode().addUpdateListener(mAppNodeUpdateListener);
-
- // Initialize the state of the checkbox
- mAppNodeUpdateListener.uiElementNodeUpdated(getUiElementNode(),
- UiUpdateState.CHILDREN_CHANGED);
-
- // Tell the section that the layout has changed.
- layoutChanged();
- }
-
- /**
- * Updates the application tooltip in the form text.
- * If there is no tooltip, the form text is hidden.
- */
- private void updateTooltip() {
- boolean isVisible = false;
-
- String tooltip = getUiElementNode().getDescriptor().getTooltip();
- if (tooltip != null) {
- tooltip = DescriptorsUtils.formatFormText(tooltip,
- getUiElementNode().getDescriptor(),
- Sdk.getCurrent().getDocumentationBaseUrl());
-
- mTooltipFormText.setText(tooltip, true /* parseTags */, true /* expandURLs */);
- mTooltipFormText.setImage(DescriptorsUtils.IMAGE_KEY, AdtPlugin.getAndroidLogo());
- mTooltipFormText.addHyperlinkListener(getEditor().createHyperlinkListener());
- isVisible = true;
- }
-
- mTooltipFormText.setVisible(isVisible);
- }
-
- /**
- * This listener synchronizes the XML application node when the checkbox
- * is changed by the user.
- */
- private class CheckboxSelectionListener extends SelectionAdapter {
- private Node mUndoXmlNode;
- private Node mUndoXmlParent;
- private Node mUndoXmlNextNode;
- private Node mUndoXmlNextElement;
- private Document mUndoXmlDocument;
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- super.widgetSelected(e);
- if (!mInternalModification && getUiElementNode() != null) {
- getUiElementNode().getEditor().wrapUndoEditXmlModel(
- mCheckbox.getSelection()
- ? "Create or restore Application node"
- : "Remove Application node",
- new Runnable() {
- @Override
- public void run() {
- if (mCheckbox.getSelection()) {
- // The user wants an <application> node.
- // Either restore a previous one
- // or create a full new one.
- boolean create = true;
- if (mUndoXmlNode != null) {
- create = !restoreApplicationNode();
- }
- if (create) {
- getUiElementNode().createXmlNode();
- }
- } else {
- // Users no longer wants the <application> node.
- removeApplicationNode();
- }
- }
- });
- }
- }
-
- /**
- * Restore a previously "saved" application node.
- *
- * @return True if the node could be restored, false otherwise.
- */
- private boolean restoreApplicationNode() {
- if (mUndoXmlDocument == null || mUndoXmlNode == null) {
- return false;
- }
-
- // Validate node references...
- mUndoXmlParent = validateNode(mUndoXmlDocument, mUndoXmlParent);
- mUndoXmlNextNode = validateNode(mUndoXmlDocument, mUndoXmlNextNode);
- mUndoXmlNextElement = validateNode(mUndoXmlDocument, mUndoXmlNextElement);
-
- if (mUndoXmlParent == null){
- // If the parent node doesn't exist, try to find a new manifest node.
- // If it doesn't exist, create it.
- mUndoXmlParent = getUiElementNode().getUiParent().prepareCommit();
- mUndoXmlNextNode = null;
- mUndoXmlNextElement = null;
- }
-
- boolean success = false;
- if (mUndoXmlParent != null) {
- // If the parent is still around, reuse the same node.
-
- // Ideally we want to insert the node before what used to be its next sibling.
- // If that's not possible, we try to insert it before its next sibling element.
- // If that's not possible either, it will be inserted at the end of the parent's.
- Node next = mUndoXmlNextNode;
- if (next == null) {
- next = mUndoXmlNextElement;
- }
- mUndoXmlParent.insertBefore(mUndoXmlNode, next);
- if (next == null) {
- Text sep = mUndoXmlDocument.createTextNode(SdkUtils.getLineSeparator());
- mUndoXmlParent.insertBefore(sep, null); // insert separator before end tag
- }
- success = true;
- }
-
- // Remove internal references to avoid using them twice
- mUndoXmlParent = null;
- mUndoXmlNextNode = null;
- mUndoXmlNextElement = null;
- mUndoXmlNode = null;
- mUndoXmlDocument = null;
- return success;
- }
-
- /**
- * Validates that the given xml_node is still either the root node or one of its
- * direct descendants.
- *
- * @param root_node The root of the node hierarchy to examine.
- * @param xml_node The XML node to find.
- * @return Returns xml_node if it is, otherwise returns null.
- */
- private Node validateNode(Node root_node, Node xml_node) {
- if (root_node == xml_node) {
- return xml_node;
- } else {
- for (Node node = root_node.getFirstChild(); node != null;
- node = node.getNextSibling()) {
- if (root_node == xml_node || validateNode(node, xml_node) != null) {
- return xml_node;
- }
- }
- }
- return null;
- }
-
- /**
- * Removes the <application> node from the hierarchy.
- * Before doing that, we try to remember where it was so that we can put it back
- * in the same place.
- */
- private void removeApplicationNode() {
- // Make sure the node actually exists...
- Node xml_node = getUiElementNode().getXmlNode();
- if (xml_node == null) {
- return;
- }
-
- // Save its parent, next sibling and next element
- mUndoXmlDocument = xml_node.getOwnerDocument();
- mUndoXmlParent = xml_node.getParentNode();
- mUndoXmlNextNode = xml_node.getNextSibling();
- mUndoXmlNextElement = mUndoXmlNextNode;
- while (mUndoXmlNextElement != null &&
- mUndoXmlNextElement.getNodeType() != Node.ELEMENT_NODE) {
- mUndoXmlNextElement = mUndoXmlNextElement.getNextSibling();
- }
-
- // Actually remove the node from the hierarchy and keep it here.
- // The returned node looses its parents/siblings pointers.
- mUndoXmlNode = getUiElementNode().deleteXmlNode();
- }
- }
-
- /**
- * This listener synchronizes the UI (i.e. the checkbox) with the
- * actual presence of the application XML node.
- */
- private class AppNodeUpdateListener implements IUiUpdateListener {
- @Override
- public void uiElementNodeUpdated(UiElementNode ui_node, UiUpdateState state) {
- // The UiElementNode for the application XML node always exists, even
- // if there is no corresponding XML node in the XML file.
- //
- // To update the checkbox to reflect the actual state, we just need
- // to check if the XML node is null.
- try {
- mInternalModification = true;
- boolean exists = ui_node.getXmlNode() != null;
- if (mCheckbox.getSelection() != exists) {
- mCheckbox.setSelection(exists);
- }
- } finally {
- mInternalModification = false;
- }
-
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/InstrumentationPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/InstrumentationPage.java
deleted file mode 100644
index a8bb34691..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/InstrumentationPage.java
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest.pages;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.IPageImageProvider;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestEditor;
-import com.android.ide.eclipse.adt.internal.editors.manifest.descriptors.AndroidManifestDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.ui.tree.UiTreeBlock;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-
-/**
- * Page for instrumentation settings, part of the AndroidManifest form editor.
- */
-public final class InstrumentationPage extends FormPage implements IPageImageProvider {
- /** Page id used for switching tabs programmatically */
- public final static String PAGE_ID = "instrumentation_page"; //$NON-NLS-1$
-
- /** Container editor */
- ManifestEditor mEditor;
-
- private UiTreeBlock mTreeBlock;
-
- public InstrumentationPage(ManifestEditor editor) {
- super(editor, PAGE_ID, "Instrumentation"); // tab's label, keep it short
- mEditor = editor;
- }
-
- @Override
- public Image getPageImage() {
- return IconFactory.getInstance().getIcon(getTitle(),
- IconFactory.COLOR_GREEN,
- IconFactory.SHAPE_RECT);
- }
-
- /**
- * Creates the content in the form hosted in this page.
- *
- * @param managedForm the form hosted in this page.
- */
- @Override
- protected void createFormContent(IManagedForm managedForm) {
- super.createFormContent(managedForm);
- ScrolledForm form = managedForm.getForm();
- form.setText("Android Manifest Instrumentation");
- form.setImage(AdtPlugin.getAndroidLogo());
-
- UiElementNode manifest = mEditor.getUiRootNode();
- AndroidManifestDescriptors manifestDescriptor = mEditor.getManifestDescriptors();
-
- ElementDescriptor[] descriptorFilters = null;
- if (manifestDescriptor != null) {
- descriptorFilters = new ElementDescriptor[] {
- manifestDescriptor.getInstrumentationElement(),
- };
- }
-
- mTreeBlock = new UiTreeBlock(mEditor, manifest,
- true /* autoCreateRoot */,
- descriptorFilters,
- "Instrumentation",
- "List of instrumentations defined in the manifest");
- mTreeBlock.createContent(managedForm);
- }
-
- /**
- * Changes and refreshes the Application UI node handled by the sub parts.
- */
- public void refreshUiNode() {
- if (mTreeBlock != null) {
- UiElementNode manifest = mEditor.getUiRootNode();
- AndroidManifestDescriptors manifestDescriptor = mEditor.getManifestDescriptors();
-
- mTreeBlock.changeRootAndDescriptors(manifest,
- new ElementDescriptor[] {
- manifestDescriptor.getInstrumentationElement()
- },
- true /* refresh */);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/OverviewExportPart.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/OverviewExportPart.java
deleted file mode 100644
index b0eb75a2d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/OverviewExportPart.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest.pages;
-
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestEditor;
-import com.android.ide.eclipse.adt.internal.editors.ui.SectionHelper.ManifestSectionPart;
-import com.android.ide.eclipse.adt.internal.project.ExportHelper;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.internal.wizards.export.ExportWizard;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.forms.events.HyperlinkAdapter;
-import org.eclipse.ui.forms.events.HyperlinkEvent;
-import org.eclipse.ui.forms.widgets.FormText;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.Section;
-import org.eclipse.ui.part.FileEditorInput;
-
-/**
- * Export section part for overview page.
- */
-final class OverviewExportPart extends ManifestSectionPart {
-
- private final OverviewPage mOverviewPage;
-
- public OverviewExportPart(OverviewPage overviewPage, final Composite body, FormToolkit toolkit,
- ManifestEditor editor) {
- super(body, toolkit, Section.TWISTIE | Section.EXPANDED, true /* description */);
- mOverviewPage = overviewPage;
- Section section = getSection();
- section.setText("Exporting");
-
- final IProject project = getProject();
- boolean isLibrary = false;
- if (project != null) {
- ProjectState state = Sdk.getProjectState(project);
- if (state != null) {
- isLibrary = state.isLibrary();
- }
- }
-
- if (isLibrary) {
- section.setDescription("Library project cannot be exported.");
- Composite table = createTableLayout(toolkit, 2 /* numColumns */);
- createFormText(table, toolkit, true, "<form></form>", false /* setupLayoutData */);
- } else {
- section.setDescription("To export the application for distribution, you have the following options:");
-
- Composite table = createTableLayout(toolkit, 2 /* numColumns */);
-
- StringBuffer buf = new StringBuffer();
- buf.append("<form><li><a href=\"wizard\">"); //$NON-NLS-1$
- buf.append("Use the Export Wizard");
- buf.append("</a>"); //$NON-NLS-1$
- buf.append(" to export and sign an APK");
- buf.append("</li>"); //$NON-NLS-1$
- buf.append("<li><a href=\"manual\">"); //$NON-NLS-1$
- buf.append("Export an unsigned APK");
- buf.append("</a>"); //$NON-NLS-1$
- buf.append(" and sign it manually");
- buf.append("</li></form>"); //$NON-NLS-1$
-
- FormText text = createFormText(table, toolkit, true, buf.toString(),
- false /* setupLayoutData */);
- text.addHyperlinkListener(new HyperlinkAdapter() {
- @Override
- public void linkActivated(HyperlinkEvent e) {
- if (project != null) {
- if ("manual".equals(e.data)) { //$NON-NLS-1$
- // now we can export an unsigned apk for the project.
- ExportHelper.exportUnsignedReleaseApk(project);
- } else {
- // call the export wizard
- StructuredSelection selection = new StructuredSelection(project);
-
- ExportWizard wizard = new ExportWizard();
- wizard.init(PlatformUI.getWorkbench(), selection);
- WizardDialog dialog = new WizardDialog(body.getShell(), wizard);
- dialog.open();
- }
- }
- }
- });
- }
-
- layoutChanged();
- }
-
- /**
- * Returns the project of the edited file.
- */
- private IProject getProject() {
- IEditorInput input = mOverviewPage.mEditor.getEditorInput();
- if (input instanceof FileEditorInput) {
- FileEditorInput fileInput = (FileEditorInput)input;
- IFile file = fileInput.getFile();
- return file.getProject();
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/OverviewInfoPart.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/OverviewInfoPart.java
deleted file mode 100644
index 98f2f9cc2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/OverviewInfoPart.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest.pages;
-
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestEditor;
-import com.android.ide.eclipse.adt.internal.editors.manifest.descriptors.AndroidManifestDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.ui.UiElementPart;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.Section;
-
-/**
- * Generic info section part for overview page: it displays all the attributes from
- * the manifest element.
- */
-final class OverviewInfoPart extends UiElementPart {
-
- private IManagedForm mManagedForm;
-
- public OverviewInfoPart(Composite body, FormToolkit toolkit, ManifestEditor editor) {
- super(body, toolkit, editor,
- getManifestUiNode(editor), // uiElementNode
- "Manifest General Attributes", // section title
- "Defines general information about the AndroidManifest.xml", // section description
- Section.TWISTIE | Section.EXPANDED);
- }
-
- /**
- * Retrieves the UiElementNode that this part will edit. The node must exist
- * and can't be null, by design, because it's a mandatory node.
- */
- private static UiElementNode getManifestUiNode(ManifestEditor editor) {
- AndroidManifestDescriptors manifestDescriptors = editor.getManifestDescriptors();
- if (manifestDescriptors != null) {
- ElementDescriptor desc = manifestDescriptors.getManifestElement();
- if (editor.getUiRootNode().getDescriptor() == desc) {
- return editor.getUiRootNode();
- } else {
- return editor.getUiRootNode().findUiChildNode(desc.getXmlName());
- }
- }
-
- // No manifest descriptor: we have a dummy UiRootNode, so we return that.
- // The editor will be reloaded once we have the proper descriptors anyway.
- return editor.getUiRootNode();
- }
-
- /**
- * Overridden in order to capture the current managed form.
- *
- * {@inheritDoc}
- */
- @Override
- protected void createFormControls(final IManagedForm managedForm) {
- mManagedForm = managedForm;
- super.createFormControls(managedForm);
- }
-
- /**
- * Removes any existing Attribute UI widgets and recreate them if the SDK has changed.
- * <p/>
- * This is called by {@link OverviewPage#refreshUiApplicationNode()} when the
- * SDK has changed.
- */
- public void onSdkChanged() {
- setUiElementNode(getManifestUiNode(getEditor()));
- createUiAttributes(mManagedForm);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/OverviewLinksPart.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/OverviewLinksPart.java
deleted file mode 100644
index f8213753a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/OverviewLinksPart.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest.pages;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestEditor;
-import com.android.ide.eclipse.adt.internal.editors.manifest.descriptors.AndroidManifestDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.ui.SectionHelper.ManifestSectionPart;
-
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.forms.widgets.FormText;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.Section;
-
-/**
- * Links section part for overview page.
- */
-final class OverviewLinksPart extends ManifestSectionPart {
-
- private final ManifestEditor mEditor;
- private FormText mFormText;
-
- public OverviewLinksPart(Composite body, FormToolkit toolkit, ManifestEditor editor) {
- super(body, toolkit, Section.TWISTIE | Section.EXPANDED, true /* description */);
- mEditor = editor;
- Section section = getSection();
- section.setText("Links");
- section.setDescription("The content of the Android Manifest is made up of three sections. You can also edit the XML directly.");
-
- Composite table = createTableLayout(toolkit, 2 /* numColumns */);
-
- StringBuffer buf = new StringBuffer();
- buf.append(String.format("<form><li style=\"image\" value=\"app_img\"><a href=\"page:%1$s\">", //$NON-NLS-1$
- ApplicationPage.PAGE_ID));
- buf.append("Application");
- buf.append("</a>"); //$NON-NLS-1$
- buf.append(": Activities, intent filters, providers, services and receivers.");
- buf.append("</li>"); //$NON-NLS-1$
-
- buf.append(String.format("<li style=\"image\" value=\"perm_img\"><a href=\"page:%1$s\">", //$NON-NLS-1$
- PermissionPage.PAGE_ID));
- buf.append("Permission");
- buf.append("</a>"); //$NON-NLS-1$
- buf.append(": Permissions defined and permissions used.");
- buf.append("</li>"); //$NON-NLS-1$
-
- buf.append(String.format("<li style=\"image\" value=\"inst_img\"><a href=\"page:%1$s\">", //$NON-NLS-1$
- InstrumentationPage.PAGE_ID));
- buf.append("Instrumentation");
- buf.append("</a>"); //$NON-NLS-1$
- buf.append(": Instrumentation defined.");
- buf.append("</li>"); //$NON-NLS-1$
-
- buf.append(String.format("<li style=\"image\" value=\"srce_img\"><a href=\"page:%1$s\">", //$NON-NLS-1$
- ManifestEditor.TEXT_EDITOR_ID));
- buf.append("XML Source");
- buf.append("</a>"); //$NON-NLS-1$
- buf.append(": Directly edit the AndroidManifest.xml file.");
- buf.append("</li>"); //$NON-NLS-1$
-
- buf.append("<li style=\"image\" value=\"android_img\">"); //$NON-NLS-1$
- buf.append("<a href=\"http://code.google.com/android/devel/bblocks-manifest.html\">Documentation</a>: Documentation from the Android SDK for AndroidManifest.xml."); //$NON-NLS-1$
- buf.append("</li>"); //$NON-NLS-1$
- buf.append("</form>"); //$NON-NLS-1$
-
- mFormText = createFormText(table, toolkit, true, buf.toString(),
- false /* setupLayoutData */);
-
- AndroidManifestDescriptors manifestDescriptor = editor.getManifestDescriptors();
-
- Image androidLogo = AdtPlugin.getAndroidLogo();
- mFormText.setImage("android_img", androidLogo); //$NON-NLS-1$
- mFormText.setImage("srce_img", IconFactory.getInstance().getIcon(AndroidXmlEditor.ICON_XML_PAGE));
-
- if (manifestDescriptor != null) {
- mFormText.setImage("app_img", getIcon(manifestDescriptor.getApplicationElement())); //$NON-NLS-1$
- mFormText.setImage("perm_img", getIcon(manifestDescriptor.getPermissionElement())); //$NON-NLS-1$
- mFormText.setImage("inst_img", getIcon(manifestDescriptor.getInstrumentationElement())); //$NON-NLS-1$
- } else {
- mFormText.setImage("app_img", androidLogo); //$NON-NLS-1$
- mFormText.setImage("perm_img", androidLogo); //$NON-NLS-1$
- mFormText.setImage("inst_img", androidLogo); //$NON-NLS-1$
- }
- mFormText.addHyperlinkListener(editor.createHyperlinkListener());
- }
-
- /**
- * Update the UI with information from the new descriptors.
- * <p/>At this point, this only refreshes the icons.
- * <p/>
- * This is called by {@link OverviewPage#refreshUiApplicationNode()} when the
- * SDK has changed.
- */
- public void onSdkChanged() {
- AndroidManifestDescriptors manifestDescriptor = mEditor.getManifestDescriptors();
- if (manifestDescriptor != null) {
- mFormText.setImage("app_img", getIcon(manifestDescriptor.getApplicationElement())); //$NON-NLS-1$
- mFormText.setImage("perm_img", getIcon(manifestDescriptor.getPermissionElement())); //$NON-NLS-1$
- mFormText.setImage("inst_img", getIcon(manifestDescriptor.getInstrumentationElement())); //$NON-NLS-1$
- }
- }
-
- private Image getIcon(ElementDescriptor desc) {
- return desc.getCustomizedIcon();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/OverviewPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/OverviewPage.java
deleted file mode 100644
index 7464f6a5f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/OverviewPage.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest.pages;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.IPageImageProvider;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestEditor;
-import com.android.ide.eclipse.adt.internal.editors.manifest.descriptors.AndroidManifestDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.ui.tree.UiTreeBlock;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-
-
-/**
- * Page for overview settings, part of the AndroidManifest form editor.
- * <p/>
- * Useful reference:
- * <a href="http://www.eclipse.org/articles/Article-Forms/article.html">
- * http://www.eclipse.org/articles/Article-Forms/article.html</a>
- */
-public final class OverviewPage extends FormPage implements IPageImageProvider {
-
- /** Page id used for switching tabs programmatically */
- final static String PAGE_ID = "overview_page"; //$NON-NLS-1$
-
- /** Container editor */
- ManifestEditor mEditor;
- /** Overview part (attributes for manifest) */
- private OverviewInfoPart mOverviewPart;
- /** Overview link part */
- private OverviewLinksPart mOverviewLinkPart;
-
- private UiTreeBlock mTreeBlock;
-
- public OverviewPage(ManifestEditor editor) {
- super(editor, PAGE_ID, "Manifest"); // tab's label, user visible, keep it short
- mEditor = editor;
- }
-
- @Override
- public Image getPageImage() {
- return IconFactory.getInstance().getIcon("editor_page_design"); //$NON-NLS-1$
- }
-
- /**
- * Creates the content in the form hosted in this page.
- *
- * @param managedForm the form hosted in this page.
- */
- @Override
- protected void createFormContent(IManagedForm managedForm) {
- super.createFormContent(managedForm);
- ScrolledForm form = managedForm.getForm();
- form.setText("Android Manifest");
- form.setImage(AdtPlugin.getAndroidLogo());
-
- Composite body = form.getBody();
- FormToolkit toolkit = managedForm.getToolkit();
-
- // Usually we would set a ColumnLayout on body here. However the presence of the
- // UiTreeBlock forces a GridLayout with one column so we comply with it.
-
- mOverviewPart = new OverviewInfoPart(body, toolkit, mEditor);
- mOverviewPart.getSection().setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- managedForm.addPart(mOverviewPart);
-
- newManifestExtrasPart(managedForm);
-
- OverviewExportPart exportPart = new OverviewExportPart(this, body, toolkit, mEditor);
- exportPart.getSection().setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- managedForm.addPart(exportPart);
-
- mOverviewLinkPart = new OverviewLinksPart(body, toolkit, mEditor);
- mOverviewLinkPart.getSection().setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false));
- managedForm.addPart(mOverviewLinkPart);
- }
-
- private void newManifestExtrasPart(IManagedForm managedForm) {
- UiElementNode manifest = mEditor.getUiRootNode();
- mTreeBlock = new UiTreeBlock(mEditor, manifest,
- true /* autoCreateRoot */,
- computeManifestExtraFilters(),
- "Manifest Extras",
- "Extra manifest elements");
- mTreeBlock.createContent(managedForm);
- }
-
- /**
- * Changes and refreshes the Application UI node handled by the sub parts.
- */
- public void refreshUiApplicationNode() {
- if (mOverviewPart != null) {
- mOverviewPart.onSdkChanged();
- }
-
- if (mOverviewLinkPart != null) {
- mOverviewLinkPart.onSdkChanged();
- }
-
- if (mTreeBlock != null) {
- UiElementNode manifest = mEditor.getUiRootNode();
- mTreeBlock.changeRootAndDescriptors(manifest,
- computeManifestExtraFilters(),
- true /* refresh */);
- }
- }
-
- private ElementDescriptor[] computeManifestExtraFilters() {
- UiElementNode manifest = mEditor.getUiRootNode();
- AndroidManifestDescriptors manifestDescriptor = mEditor.getManifestDescriptors();
-
- if (manifestDescriptor == null) {
- return null;
- }
-
- // get the elements we want to exclude
- HashSet<ElementDescriptor> excludes = new HashSet<ElementDescriptor>();
- excludes.add(manifestDescriptor.getApplicationElement());
- excludes.add(manifestDescriptor.getInstrumentationElement());
- excludes.add(manifestDescriptor.getPermissionElement());
- excludes.add(manifestDescriptor.getPermissionGroupElement());
- excludes.add(manifestDescriptor.getPermissionTreeElement());
- excludes.add(manifestDescriptor.getUsesPermissionElement());
-
- // walk through the known children of the manifest descriptor and keep what's not excluded
- ArrayList<ElementDescriptor> descriptorFilters = new ArrayList<ElementDescriptor>();
- for (ElementDescriptor child : manifest.getDescriptor().getChildren()) {
- if (!excludes.contains(child)) {
- descriptorFilters.add(child);
- }
- }
-
- if (descriptorFilters.size() == 0) {
- return null;
- }
- return descriptorFilters.toArray(new ElementDescriptor[descriptorFilters.size()]);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/PermissionPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/PermissionPage.java
deleted file mode 100644
index 2f655777a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/manifest/pages/PermissionPage.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest.pages;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.IPageImageProvider;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestEditor;
-import com.android.ide.eclipse.adt.internal.editors.manifest.descriptors.AndroidManifestDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.ui.tree.UiTreeBlock;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-
-/**
- * Page for permissions settings, part of the AndroidManifest form editor.
- * <p/>
- * Useful reference:
- * <a href="http://www.eclipse.org/articles/Article-Forms/article.html">
- * http://www.eclipse.org/articles/Article-Forms/article.html</a>
- */
-public final class PermissionPage extends FormPage implements IPageImageProvider {
- /** Page id used for switching tabs programmatically */
- public final static String PAGE_ID = "permission_page"; //$NON-NLS-1$
-
- /** Container editor */
- ManifestEditor mEditor;
-
- private UiTreeBlock mTreeBlock;
-
- public PermissionPage(ManifestEditor editor) {
- super(editor, PAGE_ID, "Permissions"); // tab label, keep it short
- mEditor = editor;
- }
-
- @Override
- public Image getPageImage() {
- return IconFactory.getInstance().getIcon(getTitle(),
- IconFactory.COLOR_RED,
- IconFactory.SHAPE_RECT);
- }
-
- /**
- * Creates the content in the form hosted in this page.
- *
- * @param managedForm the form hosted in this page.
- */
- @Override
- protected void createFormContent(IManagedForm managedForm) {
- super.createFormContent(managedForm);
- ScrolledForm form = managedForm.getForm();
- form.setText("Android Manifest Permissions");
- form.setImage(AdtPlugin.getAndroidLogo());
-
- UiElementNode manifest = mEditor.getUiRootNode();
- AndroidManifestDescriptors manifestDescriptor = mEditor.getManifestDescriptors();
-
- ElementDescriptor[] descriptorFilters = null;
- if (manifestDescriptor != null) {
- descriptorFilters = new ElementDescriptor[] {
- manifestDescriptor.getPermissionElement(),
- manifestDescriptor.getUsesPermissionElement(),
- manifestDescriptor.getPermissionGroupElement(),
- manifestDescriptor.getPermissionTreeElement()
- };
- }
- mTreeBlock = new UiTreeBlock(mEditor, manifest,
- true /* autoCreateRoot */,
- descriptorFilters,
- "Permissions",
- "List of permissions defined and used by the manifest");
- mTreeBlock.createContent(managedForm);
- }
-
- /**
- * Changes and refreshes the Application UI node handled by the sub parts.
- */
- public void refreshUiNode() {
- if (mTreeBlock != null) {
- UiElementNode manifest = mEditor.getUiRootNode();
- AndroidManifestDescriptors manifestDescriptor = mEditor.getManifestDescriptors();
-
- mTreeBlock.changeRootAndDescriptors(manifest,
- new ElementDescriptor[] {
- manifestDescriptor.getPermissionElement(),
- manifestDescriptor.getUsesPermissionElement(),
- manifestDescriptor.getPermissionGroupElement(),
- manifestDescriptor.getPermissionTreeElement()
- },
- true /* refresh */);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/menu/MenuContentAssist.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/menu/MenuContentAssist.java
deleted file mode 100644
index 59068e90e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/menu/MenuContentAssist.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.menu;
-
-import com.android.ide.eclipse.adt.internal.editors.AndroidContentAssist;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-
-/**
- * Content Assist Processor for /res/menu XML files
- */
-class MenuContentAssist extends AndroidContentAssist {
-
- /**
- * Constructor for LayoutContentAssist
- */
- public MenuContentAssist() {
- super(AndroidTargetData.DESCRIPTOR_MENU);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/menu/MenuEditorDelegate.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/menu/MenuEditorDelegate.java
deleted file mode 100644
index bfde86a65..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/menu/MenuEditorDelegate.java
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.menu;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlDelegate;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor.Mandatory;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.resources.ResourceFolderType;
-import com.android.xml.AndroidXPathFactory;
-
-import org.eclipse.ui.PartInitException;
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-
-import javax.xml.xpath.XPath;
-import javax.xml.xpath.XPathConstants;
-import javax.xml.xpath.XPathExpressionException;
-
-/**
- * Multi-page form editor for /res/menu XML files.
- */
-public class MenuEditorDelegate extends CommonXmlDelegate {
-
- public static class Creator implements IDelegateCreator {
- @Override
- @SuppressWarnings("unchecked")
- public MenuEditorDelegate createForFile(
- @NonNull CommonXmlEditor delegator,
- @Nullable ResourceFolderType type) {
- if (ResourceFolderType.MENU == type) {
- return new MenuEditorDelegate(delegator);
- }
-
- return null;
- }
- }
-
- /**
- * Old standalone-editor ID.
- * Use {@link CommonXmlEditor#ID} instead.
- */
- public static final String LEGACY_EDITOR_ID =
- AdtConstants.EDITORS_NAMESPACE + ".menu.MenuEditor"; //$NON-NLS-1$
-
- /**
- * Creates the form editor for resources XML files.
- */
- private MenuEditorDelegate(CommonXmlEditor editor) {
- super(editor, new MenuContentAssist());
- editor.addDefaultTargetListener();
- }
-
- /**
- * Create the various form pages.
- */
- @Override
- public void delegateCreateFormPages() {
- try {
- getEditor().addPage(new MenuTreePage(getEditor()));
- } catch (PartInitException e) {
- AdtPlugin.log(e, "Error creating nested page"); //$NON-NLS-1$
- }
-
- }
-
- private boolean mUpdatingModel;
-
- /**
- * Processes the new XML Model, which XML root node is given.
- *
- * @param xml_doc The XML document, if available, or null if none exists.
- */
- @Override
- public void delegateXmlModelChanged(Document xml_doc) {
- if (mUpdatingModel) {
- return;
- }
-
- try {
- mUpdatingModel = true;
-
- // init the ui root on demand
- delegateInitUiRootNode(false /*force*/);
-
- getUiRootNode().setXmlDocument(xml_doc);
- if (xml_doc != null) {
- ElementDescriptor root_desc = getUiRootNode().getDescriptor();
- try {
- XPath xpath = AndroidXPathFactory.newXPath();
- Node node = (Node) xpath.evaluate("/" + root_desc.getXmlName(), //$NON-NLS-1$
- xml_doc,
- XPathConstants.NODE);
- if (node == null && root_desc.getMandatory() != Mandatory.NOT_MANDATORY) {
- // Create the root element if it doesn't exist yet (for empty new documents)
- node = getUiRootNode().createXmlNode();
- }
-
- // Refresh the manifest UI node and all its descendants
- getUiRootNode().loadFromXmlNode(node);
-
- // TODO ? startMonitoringMarkers();
- } catch (XPathExpressionException e) {
- AdtPlugin.log(e, "XPath error when trying to find '%s' element in XML.", //$NON-NLS-1$
- root_desc.getXmlName());
- }
- }
-
- } finally {
- mUpdatingModel = false;
- }
- }
-
- /**
- * Creates the initial UI Root Node, including the known mandatory elements.
- * @param force if true, a new UiRootNode is recreated even if it already exists.
- */
- @Override
- public void delegateInitUiRootNode(boolean force) {
- // The root UI node is always created, even if there's no corresponding XML node.
- if (getUiRootNode() == null || force) {
- Document doc = null;
- if (getUiRootNode() != null) {
- doc = getUiRootNode().getXmlDocument();
- }
-
- // get the target data from the opened file (and its project)
- AndroidTargetData data = getEditor().getTargetData();
-
- ElementDescriptor desc;
- if (data == null) {
- desc = new ElementDescriptor("temp", null /*children*/);
- } else {
- desc = data.getMenuDescriptors().getDescriptor();
- }
-
- setUiRootNode(desc.createUiNode());
- getUiRootNode().setEditor(getEditor());
-
- onDescriptorsChanged(doc);
- }
- }
-
- // ---- Local Methods ----
-
- /**
- * Reloads the UI manifest node from the XML, and calls the pages to update.
- */
- private void onDescriptorsChanged(Document document) {
- if (document != null) {
- getUiRootNode().loadFromXmlNode(document);
- } else {
- getUiRootNode().reloadFromXmlNode(getUiRootNode().getXmlNode());
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/menu/MenuTreePage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/menu/MenuTreePage.java
deleted file mode 100644
index e24188541..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/menu/MenuTreePage.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.menu;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.IPageImageProvider;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.ui.tree.UiTreeBlock;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-
-/**
- * Page for the menu form editor.
- */
-public final class MenuTreePage extends FormPage implements IPageImageProvider {
- /** Page id used for switching tabs programmatically */
- public final static String PAGE_ID = "layout_tree_page"; //$NON-NLS-1$
-
- /** Container editor */
- CommonXmlEditor mEditor;
-
- public MenuTreePage(CommonXmlEditor editor) {
- super(editor, PAGE_ID, "Layout"); // tab's label, keep it short
- mEditor = editor;
- }
-
- @Override
- public Image getPageImage() {
- return IconFactory.getInstance().getIcon("editor_page_design"); //$NON-NLS-1$
- }
-
- /**
- * Creates the content in the form hosted in this page.
- *
- * @param managedForm the form hosted in this page.
- */
- @Override
- protected void createFormContent(IManagedForm managedForm) {
- super.createFormContent(managedForm);
- ScrolledForm form = managedForm.getForm();
- form.setText("Android Menu");
- form.setImage(AdtPlugin.getAndroidLogo());
-
- UiElementNode rootNode = mEditor.getUiRootNode();
- UiTreeBlock block = new UiTreeBlock(mEditor, rootNode,
- true /* autoCreateRoot */,
- null /* no element filters */,
- "Menu Elements",
- "List of all menu elements in this XML file.");
- block.createContent(managedForm);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/menu/descriptors/MenuDescriptors.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/menu/descriptors/MenuDescriptors.java
deleted file mode 100644
index b7bab1bd3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/menu/descriptors/MenuDescriptors.java
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.menu.descriptors;
-
-import static com.android.SdkConstants.ANDROID_NS_NAME;
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.TAG_MENU;
-
-import com.android.ide.common.resources.platform.DeclareStyleableInfo;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.IDescriptorProvider;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.XmlnsAttributeDescriptor;
-
-import java.util.ArrayList;
-import java.util.Map;
-
-/**
- * Complete description of the menu structure.
- */
-public final class MenuDescriptors implements IDescriptorProvider {
-
- /** The root element descriptor. */
- private ElementDescriptor mDescriptor = null;
-
- /** @return the root descriptor. */
- @Override
- public ElementDescriptor getDescriptor() {
- return mDescriptor;
- }
-
- @Override
- public ElementDescriptor[] getRootElementDescriptors() {
- return mDescriptor.getChildren();
- }
-
- /**
- * Updates the document descriptor.
- * <p/>
- * It first computes the new children of the descriptor and then updates them
- * all at once.
- *
- * @param styleMap The map style => attributes from the attrs.xml file
- */
- public synchronized void updateDescriptors(Map<String, DeclareStyleableInfo> styleMap) {
-
- // There are 3 elements: menu, item and group.
- // The root element MUST be a menu.
- // A top menu can contain items or group:
- // - top groups can contain top items
- // - top items can contain sub-menus
- // A sub menu can contains sub items or sub groups:
- // - sub groups can contain sub items
- // - sub items cannot contain anything
-
- if (mDescriptor == null) {
- mDescriptor = createElement(styleMap,
- TAG_MENU, // xmlName
- "Menu", // uiName,
- null, // TODO SDK URL
- null, // extraAttribute
- null, // childrenElements,
- true /* mandatory */);
- }
-
- // -- sub menu can have sub_items, sub_groups but not sub_menus
-
- ElementDescriptor sub_item = createElement(styleMap,
- "item", // xmlName //$NON-NLS-1$
- "Item", // uiName,
- null, // TODO SDK URL
- null, // extraAttribute
- null, // childrenElements,
- false /* mandatory */);
-
- ElementDescriptor sub_group = createElement(styleMap,
- "group", // xmlName //$NON-NLS-1$
- "Group", // uiName,
- null, // TODO SDK URL
- null, // extraAttribute
- new ElementDescriptor[] { sub_item }, // childrenElements,
- false /* mandatory */);
-
- ElementDescriptor sub_menu = createElement(styleMap,
- TAG_MENU, // xmlName
- "Sub-Menu", // uiName,
- null, // TODO SDK URL
- null, // extraAttribute
- new ElementDescriptor[] { sub_item, sub_group }, // childrenElements,
- true /* mandatory */);
-
- // -- top menu can have all top groups and top items (which can have sub menus)
-
- ElementDescriptor top_item = createElement(styleMap,
- "item", // xmlName //$NON-NLS-1$
- "Item", // uiName,
- null, // TODO SDK URL
- null, // extraAttribute
- new ElementDescriptor[] { sub_menu }, // childrenElements,
- false /* mandatory */);
-
- ElementDescriptor top_group = createElement(styleMap,
- "group", // xmlName //$NON-NLS-1$
- "Group", // uiName,
- null, // TODO SDK URL
- null, // extraAttribute
- new ElementDescriptor[] { top_item }, // childrenElements,
- false /* mandatory */);
-
- XmlnsAttributeDescriptor xmlns = new XmlnsAttributeDescriptor(ANDROID_NS_NAME,
- ANDROID_URI);
-
- updateElement(mDescriptor, styleMap, "Menu", xmlns); //$NON-NLS-1$
- mDescriptor.setChildren(new ElementDescriptor[] { top_item, top_group });
- }
-
- /**
- * Returns a new ElementDescriptor constructed from the information given here
- * and the javadoc & attributes extracted from the style map if any.
- */
- private ElementDescriptor createElement(
- Map<String, DeclareStyleableInfo> styleMap,
- String xmlName, String uiName, String sdkUrl,
- AttributeDescriptor extraAttribute,
- ElementDescriptor[] childrenElements, boolean mandatory) {
-
- ElementDescriptor element = new ElementDescriptor(xmlName, uiName, null, sdkUrl,
- null, childrenElements, mandatory);
-
- return updateElement(element, styleMap,
- getStyleName(xmlName),
- extraAttribute);
- }
-
- /**
- * Updates an ElementDescriptor with the javadoc & attributes extracted from the style
- * map if any.
- */
- private ElementDescriptor updateElement(ElementDescriptor element,
- Map<String, DeclareStyleableInfo> styleMap,
- String styleName,
- AttributeDescriptor extraAttribute) {
- ArrayList<AttributeDescriptor> descs = new ArrayList<AttributeDescriptor>();
-
- DeclareStyleableInfo style = styleMap != null ? styleMap.get(styleName) : null;
- if (style != null) {
- DescriptorsUtils.appendAttributes(descs,
- null, // elementName
- ANDROID_URI,
- style.getAttributes(),
- null, // requiredAttributes
- null); // overrides
- element.setTooltip(style.getJavaDoc());
- }
-
- if (extraAttribute != null) {
- descs.add(extraAttribute);
- }
-
- element.setAttributes(descs.toArray(new AttributeDescriptor[descs.size()]));
- return element;
- }
-
- /**
- * Returns the style name (i.e. the <declare-styleable> name found in attrs.xml)
- * for a given XML element name.
- * <p/>
- * The rule is that all elements have for style name:
- * - their xml name capitalized
- * - a "Menu" prefix, except for <menu> itself which is just "Menu".
- */
- private String getStyleName(String xmlName) {
- String styleName = AdtUtils.capitalize(xmlName);
-
- // This is NOT the UI Name but the expected internal style name
- final String MENU_STYLE_BASE_NAME = "Menu"; //$NON-NLS-1$
-
- if (!styleName.equals(MENU_STYLE_BASE_NAME)) {
- styleName = MENU_STYLE_BASE_NAME + styleName;
- }
- return styleName;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/otherxml/OtherXmlContentAssist.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/otherxml/OtherXmlContentAssist.java
deleted file mode 100644
index 19a8d85b2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/otherxml/OtherXmlContentAssist.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.otherxml;
-
-import com.android.ide.eclipse.adt.internal.editors.AndroidContentAssist;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-
-/**
- * Content Assist Processor for /res/xml XML files
- */
-class OtherXmlContentAssist extends AndroidContentAssist {
-
- /**
- * Constructor for LayoutContentAssist
- */
- public OtherXmlContentAssist() {
- super(AndroidTargetData.DESCRIPTOR_OTHER_XML);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/otherxml/OtherXmlEditorDelegate.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/otherxml/OtherXmlEditorDelegate.java
deleted file mode 100644
index 7d745165b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/otherxml/OtherXmlEditorDelegate.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.otherxml;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlDelegate;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DocumentDescriptor;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.resources.ResourceFolderType;
-
-import org.eclipse.ui.PartInitException;
-import org.w3c.dom.Document;
-
-/**
- * Multi-page form editor for /res/xml XML files.
- */
-public class OtherXmlEditorDelegate extends CommonXmlDelegate {
-
- public static class Creator implements IDelegateCreator {
- @Override
- @SuppressWarnings("unchecked")
- public OtherXmlEditorDelegate createForFile(
- @NonNull CommonXmlEditor delegator,
- @Nullable ResourceFolderType type) {
- if (ResourceFolderType.XML == type) {
- return new OtherXmlEditorDelegate(delegator);
- }
-
- return null;
- }
- }
-
- /**
- * Old standalone-editor ID.
- * Use {@link CommonXmlEditor#ID} instead.
- */
- public static final String LEGACY_EDITOR_ID =
- AdtConstants.EDITORS_NAMESPACE + ".xml.XmlEditor"; //$NON-NLS-1$
-
- /**
- * Creates the form editor for resources XML files.
- */
- public OtherXmlEditorDelegate(CommonXmlEditor editor) {
- super(editor, new OtherXmlContentAssist());
- editor.addDefaultTargetListener();
- }
-
- // ---- Base Class Overrides ----
-
- /**
- * Create the various form pages.
- */
- @Override
- public void delegateCreateFormPages() {
- try {
- getEditor().addPage(new OtherXmlTreePage(getEditor()));
- } catch (PartInitException e) {
- AdtPlugin.log(e, "Error creating nested page"); //$NON-NLS-1$
- }
-
- }
- /**
- * Processes the new XML Model, which XML root node is given.
- *
- * @param xml_doc The XML document, if available, or null if none exists.
- */
- @Override
- public void delegateXmlModelChanged(Document xml_doc) {
- // init the ui root on demand
- delegateInitUiRootNode(false /*force*/);
-
- getUiRootNode().loadFromXmlNode(xml_doc);
- }
-
- /**
- * Creates the initial UI Root Node, including the known mandatory elements.
- * @param force if true, a new UiRootNode is recreated even if it already exists.
- */
- @Override
- public void delegateInitUiRootNode(boolean force) {
- // The root UI node is always created, even if there's no corresponding XML node.
- if (getUiRootNode() == null || force) {
- Document doc = null;
- if (getUiRootNode() != null) {
- doc = getUiRootNode().getXmlDocument();
- }
-
- // get the target data from the opened file (and its project)
- AndroidTargetData data = getEditor().getTargetData();
-
- DocumentDescriptor desc;
- if (data == null) {
- desc = new DocumentDescriptor("temp", null /*children*/);
- } else {
- desc = data.getXmlDescriptors().getDescriptor();
- }
-
- setUiRootNode(desc.createUiNode());
- getUiRootNode().setEditor(getEditor());
-
- onDescriptorsChanged(doc);
- }
- }
-
- // ---- Local Methods ----
-
- /**
- * Reloads the UI manifest node from the XML, and calls the pages to update.
- */
- private void onDescriptorsChanged(Document document) {
- if (document != null) {
- getUiRootNode().loadFromXmlNode(document);
- } else {
- getUiRootNode().reloadFromXmlNode(getUiRootNode().getXmlNode());
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/otherxml/OtherXmlTreePage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/otherxml/OtherXmlTreePage.java
deleted file mode 100644
index ce81b0eb9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/otherxml/OtherXmlTreePage.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.otherxml;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.IPageImageProvider;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.ui.tree.UiTreeBlock;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-
-/**
- * Page for the xml form editor.
- */
-public final class OtherXmlTreePage extends FormPage implements IPageImageProvider {
- /** Page id used for switching tabs programmatically */
- public final static String PAGE_ID = "xml_tree_page"; //$NON-NLS-1$
-
- /** Container editor */
- CommonXmlEditor mEditor;
-
- public OtherXmlTreePage(CommonXmlEditor editor) {
- super(editor, PAGE_ID, "Structure"); // tab's label, keep it short
- mEditor = editor;
- }
-
- @Override
- public Image getPageImage() {
- return IconFactory.getInstance().getIcon("editor_page_design"); //$NON-NLS-1$
- }
-
- /**
- * Creates the content in the form hosted in this page.
- *
- * @param managedForm the form hosted in this page.
- */
- @Override
- protected void createFormContent(IManagedForm managedForm) {
- super.createFormContent(managedForm);
- ScrolledForm form = managedForm.getForm();
- form.setText("Android Xml");
- form.setImage(AdtPlugin.getAndroidLogo());
-
- UiElementNode rootNode = mEditor.getUiRootNode();
- UiTreeBlock block = new UiTreeBlock(mEditor, rootNode,
- true /* autoCreateRoot */,
- null /* no element filters */,
- "Xml Elements",
- "List of all xml elements in this XML file.");
- block.createContent(managedForm);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/otherxml/PlainXmlEditorDelegate.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/otherxml/PlainXmlEditorDelegate.java
deleted file mode 100644
index 5366988f5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/otherxml/PlainXmlEditorDelegate.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.otherxml;
-
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlDelegate;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-
-import org.w3c.dom.Document;
-
-/**
- * Plain XML editor with no form for files that have no associated descriptor data
- */
-public class PlainXmlEditorDelegate extends CommonXmlDelegate {
-
- /**
- * Creates the form editor for plain XML files.
- */
- public PlainXmlEditorDelegate(CommonXmlEditor editor) {
- super(editor, new OtherXmlContentAssist());
- editor.addDefaultTargetListener();
- }
-
- // ---- Base Class Overrides ----
-
- @Override
- public void delegateCreateFormPages() {
- }
-
- @Override
- public void delegateXmlModelChanged(Document xml_doc) {
- }
-
- @Override
- public void delegateInitUiRootNode(boolean force) {
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/otherxml/descriptors/OtherXmlDescriptors.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/otherxml/descriptors/OtherXmlDescriptors.java
deleted file mode 100644
index 7f3ed0939..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/otherxml/descriptors/OtherXmlDescriptors.java
+++ /dev/null
@@ -1,373 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.otherxml.descriptors;
-
-import static com.android.SdkConstants.ANDROID_NS_NAME;
-import static com.android.SdkConstants.ANDROID_URI;
-
-import com.android.SdkConstants;
-import com.android.ide.common.resources.platform.AttributeInfo;
-import com.android.ide.common.resources.platform.DeclareStyleableInfo;
-import com.android.ide.common.resources.platform.ViewClassInfo;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DocumentDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.IDescriptorProvider;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.SeparatorAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.XmlnsAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-
-import java.util.ArrayList;
-import java.util.Map;
-
-
-/**
- * Description of the /res/xml structure.
- * Currently supports the <searchable> and <preferences> root nodes.
- */
-public final class OtherXmlDescriptors implements IDescriptorProvider {
-
- // Public attributes names, attributes descriptors and elements descriptors referenced
- // elsewhere.
- public static final String PREF_KEY_ATTR = "key"; //$NON-NLS-1$
-
- /** The root document descriptor for both searchable and preferences. */
- private DocumentDescriptor mDescriptor = new DocumentDescriptor("xml_doc", null /* children */); //$NON-NLS-1$
-
- /** The root document descriptor for searchable. */
- private DocumentDescriptor mSearchDescriptor = new DocumentDescriptor("xml_doc", null /* children */); //$NON-NLS-1$
-
- /** The root document descriptor for preferences. */
- private DocumentDescriptor mPrefDescriptor = new DocumentDescriptor("xml_doc", null /* children */); //$NON-NLS-1$
-
- /** The root document descriptor for widget provider. */
- private DocumentDescriptor mAppWidgetDescriptor = new DocumentDescriptor("xml_doc", null /* children */); //$NON-NLS-1$
-
- /** @return the root descriptor for both searchable and preferences. */
- @Override
- public DocumentDescriptor getDescriptor() {
- return mDescriptor;
- }
-
- @Override
- public ElementDescriptor[] getRootElementDescriptors() {
- return mDescriptor.getChildren();
- }
-
- /** @return the root descriptor for searchable. */
- public DocumentDescriptor getSearchableDescriptor() {
- return mSearchDescriptor;
- }
-
- /** @return the root descriptor for preferences. */
- public DocumentDescriptor getPreferencesDescriptor() {
- return mPrefDescriptor;
- }
-
- /** @return the root descriptor for widget providers. */
- public DocumentDescriptor getAppWidgetDescriptor() {
- return mAppWidgetDescriptor;
- }
-
- public IDescriptorProvider getSearchableProvider() {
- return new IDescriptorProvider() {
- @Override
- public ElementDescriptor getDescriptor() {
- return mSearchDescriptor;
- }
-
- @Override
- public ElementDescriptor[] getRootElementDescriptors() {
- return mSearchDescriptor.getChildren();
- }
- };
- }
-
- public IDescriptorProvider getPreferencesProvider() {
- return new IDescriptorProvider() {
- @Override
- public ElementDescriptor getDescriptor() {
- return mPrefDescriptor;
- }
-
- @Override
- public ElementDescriptor[] getRootElementDescriptors() {
- return mPrefDescriptor.getChildren();
- }
- };
- }
-
- public IDescriptorProvider getAppWidgetProvider() {
- return new IDescriptorProvider() {
- @Override
- public ElementDescriptor getDescriptor() {
- return mAppWidgetDescriptor;
- }
-
- @Override
- public ElementDescriptor[] getRootElementDescriptors() {
- return mAppWidgetDescriptor.getChildren();
- }
- };
- }
-
- /**
- * Updates the document descriptor.
- * <p/>
- * It first computes the new children of the descriptor and then updates them
- * all at once.
- *
- * @param searchableStyleMap The map style=>attributes for <searchable> from the attrs.xml file
- * @param appWidgetStyleMap The map style=>attributes for <appwidget-provider> from the attrs.xml file
- * @param prefs The list of non-group preference descriptions
- * @param prefGroups The list of preference group descriptions
- */
- public synchronized void updateDescriptors(
- Map<String, DeclareStyleableInfo> searchableStyleMap,
- Map<String, DeclareStyleableInfo> appWidgetStyleMap,
- ViewClassInfo[] prefs, ViewClassInfo[] prefGroups) {
-
- XmlnsAttributeDescriptor xmlns = new XmlnsAttributeDescriptor(ANDROID_NS_NAME,
- ANDROID_URI);
-
- ElementDescriptor searchable = createSearchable(searchableStyleMap, xmlns);
- ElementDescriptor appWidget = createAppWidgetProviderInfo(appWidgetStyleMap, xmlns);
- ElementDescriptor preferences = createPreference(prefs, prefGroups, xmlns);
- ArrayList<ElementDescriptor> list = new ArrayList<ElementDescriptor>();
- if (searchable != null) {
- list.add(searchable);
- mSearchDescriptor.setChildren(new ElementDescriptor[]{ searchable });
- }
- if (appWidget != null) {
- list.add(appWidget);
- mAppWidgetDescriptor.setChildren(new ElementDescriptor[]{ appWidget });
- }
- if (preferences != null) {
- list.add(preferences);
- mPrefDescriptor.setChildren(new ElementDescriptor[]{ preferences });
- }
-
- if (list.size() > 0) {
- mDescriptor.setChildren(list.toArray(new ElementDescriptor[list.size()]));
- }
- }
-
- //-------------------------
- // Creation of <searchable>
- //-------------------------
-
- /**
- * Returns the new ElementDescriptor for <searchable>
- */
- private ElementDescriptor createSearchable(
- Map<String, DeclareStyleableInfo> searchableStyleMap,
- XmlnsAttributeDescriptor xmlns) {
-
- ElementDescriptor action_key = createElement(searchableStyleMap,
- "SearchableActionKey", //$NON-NLS-1$ styleName
- "actionkey", //$NON-NLS-1$ xmlName
- "Action Key", // uiName
- null, // sdk url
- null, // extraAttribute
- null, // childrenElements
- false /* mandatory */ );
-
- ElementDescriptor searchable = createElement(searchableStyleMap,
- "Searchable", //$NON-NLS-1$ styleName
- "searchable", //$NON-NLS-1$ xmlName
- "Searchable", // uiName
- null, // sdk url
- xmlns, // extraAttribute
- new ElementDescriptor[] { action_key }, // childrenElements
- false /* mandatory */ );
- return searchable;
- }
-
- /**
- * Returns the new ElementDescriptor for <appwidget-provider>
- */
- private ElementDescriptor createAppWidgetProviderInfo(
- Map<String, DeclareStyleableInfo> appWidgetStyleMap,
- XmlnsAttributeDescriptor xmlns) {
-
- if (appWidgetStyleMap == null) {
- return null;
- }
-
- ElementDescriptor appWidget = createElement(appWidgetStyleMap,
- "AppWidgetProviderInfo", //$NON-NLS-1$ styleName
- "appwidget-provider", //$NON-NLS-1$ xmlName
- "AppWidget Provider", // uiName
- null, // sdk url
- xmlns, // extraAttribute
- null, // childrenElements
- false /* mandatory */ );
- return appWidget;
- }
-
- /**
- * Returns a new ElementDescriptor constructed from the information given here
- * and the javadoc & attributes extracted from the style map if any.
- */
- private ElementDescriptor createElement(
- Map<String, DeclareStyleableInfo> styleMap, String styleName,
- String xmlName, String uiName, String sdkUrl,
- AttributeDescriptor extraAttribute,
- ElementDescriptor[] childrenElements, boolean mandatory) {
-
- ElementDescriptor element = new ElementDescriptor(xmlName, uiName, null, sdkUrl,
- null, childrenElements, mandatory);
-
- return updateElement(element, styleMap, styleName, extraAttribute);
- }
-
- /**
- * Updates an ElementDescriptor with the javadoc & attributes extracted from the style
- * map if any.
- */
- private ElementDescriptor updateElement(ElementDescriptor element,
- Map<String, DeclareStyleableInfo> styleMap,
- String styleName,
- AttributeDescriptor extraAttribute) {
- ArrayList<AttributeDescriptor> descs = new ArrayList<AttributeDescriptor>();
-
- DeclareStyleableInfo style = styleMap != null ? styleMap.get(styleName) : null;
- if (style != null) {
- DescriptorsUtils.appendAttributes(descs,
- null, // elementName
- SdkConstants.NS_RESOURCES,
- style.getAttributes(),
- null, // requiredAttributes
- null); // overrides
- element.setTooltip(style.getJavaDoc());
- }
-
- if (extraAttribute != null) {
- descs.add(extraAttribute);
- }
-
- element.setAttributes(descs.toArray(new AttributeDescriptor[descs.size()]));
- return element;
- }
-
- //--------------------------
- // Creation of <Preferences>
- //--------------------------
-
- /**
- * Returns the new ElementDescriptor for <Preferences>
- */
- private ElementDescriptor createPreference(ViewClassInfo[] prefs,
- ViewClassInfo[] prefGroups, XmlnsAttributeDescriptor xmlns) {
-
- ArrayList<ElementDescriptor> newPrefs = new ArrayList<ElementDescriptor>();
- if (prefs != null) {
- for (ViewClassInfo info : prefs) {
- ElementDescriptor desc = convertPref(info);
- newPrefs.add(desc);
- }
- }
-
- ElementDescriptor topPreferences = null;
-
- ArrayList<ElementDescriptor> newGroups = new ArrayList<ElementDescriptor>();
- if (prefGroups != null) {
- for (ViewClassInfo info : prefGroups) {
- ElementDescriptor desc = convertPref(info);
- newGroups.add(desc);
-
- if (info.getFullClassName() == SdkConstants.CLASS_PREFERENCES) {
- topPreferences = desc;
- }
- }
- }
-
- ArrayList<ElementDescriptor> everything = new ArrayList<ElementDescriptor>();
- everything.addAll(newGroups);
- everything.addAll(newPrefs);
- ElementDescriptor[] newArray = everything.toArray(new ElementDescriptor[everything.size()]);
-
- // Link all groups to everything else here.. recursively
- for (ElementDescriptor layoutDesc : newGroups) {
- layoutDesc.setChildren(newArray);
- }
-
- // The "top" element to be returned corresponds to the class "Preferences".
- // Its descriptor has already been created. However the root one also needs
- // the hidden xmlns:android definition..
- if (topPreferences != null) {
- AttributeDescriptor[] attrs = topPreferences.getAttributes();
- AttributeDescriptor[] newAttrs = new AttributeDescriptor[attrs.length + 1];
- System.arraycopy(attrs, 0, newAttrs, 0, attrs.length);
- newAttrs[attrs.length] = xmlns;
- return new ElementDescriptor(
- topPreferences.getXmlName(),
- topPreferences.getUiName(),
- topPreferences.getTooltip(),
- topPreferences.getSdkUrl(),
- newAttrs,
- topPreferences.getChildren(),
- false /* mandatory */);
- } else {
- return null;
- }
- }
-
- /**
- * Creates an element descriptor from a given {@link ViewClassInfo}.
- */
- private ElementDescriptor convertPref(ViewClassInfo info) {
- String xml_name = info.getShortClassName();
- String tooltip = info.getJavaDoc();
-
- // Process all Preference attributes
- ArrayList<AttributeDescriptor> attributes = new ArrayList<AttributeDescriptor>();
- DescriptorsUtils.appendAttributes(attributes,
- null, // elementName
- SdkConstants.NS_RESOURCES,
- info.getAttributes(),
- null, // requiredAttributes
- null); // overrides
-
- for (ViewClassInfo link = info.getSuperClass();
- link != null;
- link = link.getSuperClass()) {
- AttributeInfo[] attrList = link.getAttributes();
- if (attrList.length > 0) {
- attributes.add(new SeparatorAttributeDescriptor(
- String.format("Attributes from %1$s", link.getShortClassName())));
- DescriptorsUtils.appendAttributes(attributes,
- null, // elementName
- SdkConstants.NS_RESOURCES,
- attrList,
- null, // requiredAttributes
- null); // overrides
- }
- }
-
- return new ViewElementDescriptor(xml_name,
- xml_name, // ui_name
- info.getFullClassName(),
- tooltip,
- null, // sdk_url
- attributes.toArray(new AttributeDescriptor[attributes.size()]),
- null,
- null, // children
- false /* mandatory */);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/EditableDialogCellEditor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/EditableDialogCellEditor.java
deleted file mode 100644
index baf8a1039..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/EditableDialogCellEditor.java
+++ /dev/null
@@ -1,490 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.ui;
-
-import com.android.SdkConstants;
-
-import org.eclipse.core.runtime.Assert;
-import org.eclipse.jface.viewers.DialogCellEditor;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.FocusAdapter;
-import org.eclipse.swt.events.FocusEvent;
-import org.eclipse.swt.events.KeyAdapter;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.MouseAdapter;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.TraverseEvent;
-import org.eclipse.swt.events.TraverseListener;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Text;
-
-import java.text.MessageFormat;
-
-/**
- * Custom DialogCellEditor, replacing the Label with an editable {@link Text} widget.
- * <p/>Also set the button to {@link SWT#FLAT} to make sure it looks good on MacOS X.
- * <p/>Most of the code comes from TextCellEditor.
- */
-public abstract class EditableDialogCellEditor extends DialogCellEditor {
-
- private Text text;
-
- private ModifyListener modifyListener;
-
- /**
- * State information for updating action enablement
- */
- private boolean isSelection = false;
-
- private boolean isDeleteable = false;
-
- private boolean isSelectable = false;
-
- EditableDialogCellEditor(Composite parent) {
- super(parent);
- }
-
- /*
- * Re-implement this method only to properly set the style in the button, or it won't look
- * good in MacOS X
- */
- @Override
- protected Button createButton(Composite parent) {
- Button result = new Button(parent, SWT.DOWN | SWT.FLAT);
- result.setText("..."); //$NON-NLS-1$
- return result;
- }
-
-
- @Override
- protected Control createContents(Composite cell) {
- text = new Text(cell, SWT.SINGLE);
- text.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- handleDefaultSelection(e);
- }
- });
- text.addKeyListener(new KeyAdapter() {
- // hook key pressed - see PR 14201
- @Override
- public void keyPressed(KeyEvent e) {
- keyReleaseOccured(e);
-
- // as a result of processing the above call, clients may have
- // disposed this cell editor
- if ((getControl() == null) || getControl().isDisposed()) {
- return;
- }
- checkSelection(); // see explanation below
- checkDeleteable();
- checkSelectable();
- }
- });
- text.addTraverseListener(new TraverseListener() {
- @Override
- public void keyTraversed(TraverseEvent e) {
- if (e.detail == SWT.TRAVERSE_ESCAPE
- || e.detail == SWT.TRAVERSE_RETURN) {
- e.doit = false;
- }
- }
- });
- // We really want a selection listener but it is not supported so we
- // use a key listener and a mouse listener to know when selection changes
- // may have occurred
- text.addMouseListener(new MouseAdapter() {
- @Override
- public void mouseUp(MouseEvent e) {
- checkSelection();
- checkDeleteable();
- checkSelectable();
- }
- });
- text.addFocusListener(new FocusAdapter() {
- @Override
- public void focusLost(FocusEvent e) {
- EditableDialogCellEditor.this.focusLost();
- }
- });
- text.setFont(cell.getFont());
- text.setBackground(cell.getBackground());
- text.setText("");//$NON-NLS-1$
- text.addModifyListener(getModifyListener());
- return text;
- }
-
- /**
- * Checks to see if the "deletable" state (can delete/
- * nothing to delete) has changed and if so fire an
- * enablement changed notification.
- */
- private void checkDeleteable() {
- boolean oldIsDeleteable = isDeleteable;
- isDeleteable = isDeleteEnabled();
- if (oldIsDeleteable != isDeleteable) {
- fireEnablementChanged(DELETE);
- }
- }
-
- /**
- * Checks to see if the "selectable" state (can select)
- * has changed and if so fire an enablement changed notification.
- */
- private void checkSelectable() {
- boolean oldIsSelectable = isSelectable;
- isSelectable = isSelectAllEnabled();
- if (oldIsSelectable != isSelectable) {
- fireEnablementChanged(SELECT_ALL);
- }
- }
-
- /**
- * Checks to see if the selection state (selection /
- * no selection) has changed and if so fire an
- * enablement changed notification.
- */
- private void checkSelection() {
- boolean oldIsSelection = isSelection;
- isSelection = text.getSelectionCount() > 0;
- if (oldIsSelection != isSelection) {
- fireEnablementChanged(COPY);
- fireEnablementChanged(CUT);
- }
- }
-
- /* (non-Javadoc)
- * Method declared on CellEditor.
- */
- @Override
- protected void doSetFocus() {
- if (text != null) {
- text.selectAll();
- text.setFocus();
- checkSelection();
- checkDeleteable();
- checkSelectable();
- }
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.jface.viewers.DialogCellEditor#updateContents(java.lang.Object)
- */
- @Override
- protected void updateContents(Object value) {
- Assert.isTrue(text != null && (value == null || (value instanceof String)));
- if (value != null) {
- text.removeModifyListener(getModifyListener());
- text.setText((String) value);
- text.addModifyListener(getModifyListener());
- }
- }
-
- /**
- * The <code>TextCellEditor</code> implementation of
- * this <code>CellEditor</code> framework method returns
- * the text string.
- *
- * @return the text string
- */
- @Override
- protected Object doGetValue() {
- return text.getText();
- }
-
-
- /**
- * Processes a modify event that occurred in this text cell editor.
- * This framework method performs validation and sets the error message
- * accordingly, and then reports a change via <code>fireEditorValueChanged</code>.
- * Subclasses should call this method at appropriate times. Subclasses
- * may extend or reimplement.
- *
- * @param e the SWT modify event
- */
- protected void editOccured(ModifyEvent e) {
- String value = text.getText();
- if (value == null) {
- value = "";//$NON-NLS-1$
- }
- Object typedValue = value;
- boolean oldValidState = isValueValid();
- boolean newValidState = isCorrect(typedValue);
-
- if (!newValidState) {
- // try to insert the current value into the error message.
- setErrorMessage(MessageFormat.format(getErrorMessage(),
- new Object[] { value }));
- }
- valueChanged(oldValidState, newValidState);
- }
-
- /**
- * Return the modify listener.
- */
- private ModifyListener getModifyListener() {
- if (modifyListener == null) {
- modifyListener = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- editOccured(e);
- }
- };
- }
- return modifyListener;
- }
-
- /**
- * Handles a default selection event from the text control by applying the editor
- * value and deactivating this cell editor.
- *
- * @param event the selection event
- *
- * @since 3.0
- */
- protected void handleDefaultSelection(SelectionEvent event) {
- // same with enter-key handling code in keyReleaseOccured(e);
- fireApplyEditorValue();
- deactivate();
- }
-
- /**
- * The <code>TextCellEditor</code> implementation of this
- * <code>CellEditor</code> method returns <code>true</code> if
- * the current selection is not empty.
- */
- @Override
- public boolean isCopyEnabled() {
- if (text == null || text.isDisposed()) {
- return false;
- }
- return text.getSelectionCount() > 0;
- }
-
- /**
- * The <code>TextCellEditor</code> implementation of this
- * <code>CellEditor</code> method returns <code>true</code> if
- * the current selection is not empty.
- */
- @Override
- public boolean isCutEnabled() {
- if (text == null || text.isDisposed()) {
- return false;
- }
- return text.getSelectionCount() > 0;
- }
-
- /**
- * The <code>TextCellEditor</code> implementation of this
- * <code>CellEditor</code> method returns <code>true</code>
- * if there is a selection or if the caret is not positioned
- * at the end of the text.
- */
- @Override
- public boolean isDeleteEnabled() {
- if (text == null || text.isDisposed()) {
- return false;
- }
- return text.getSelectionCount() > 0
- || text.getCaretPosition() < text.getCharCount();
- }
-
- /**
- * The <code>TextCellEditor</code> implementation of this
- * <code>CellEditor</code> method always returns <code>true</code>.
- */
- @Override
- public boolean isPasteEnabled() {
- if (text == null || text.isDisposed()) {
- return false;
- }
- return true;
- }
-
- /**
- * Check if save all is enabled
- * @return true if it is
- */
- public boolean isSaveAllEnabled() {
- if (text == null || text.isDisposed()) {
- return false;
- }
- return true;
- }
-
- /**
- * Returns <code>true</code> if this cell editor is
- * able to perform the select all action.
- * <p>
- * This default implementation always returns
- * <code>false</code>.
- * </p>
- * <p>
- * Subclasses may override
- * </p>
- * @return <code>true</code> if select all is possible,
- * <code>false</code> otherwise
- */
- @Override
- public boolean isSelectAllEnabled() {
- if (text == null || text.isDisposed()) {
- return false;
- }
- return text.getCharCount() > 0;
- }
-
- /**
- * Processes a key release event that occurred in this cell editor.
- * <p>
- * The <code>TextCellEditor</code> implementation of this framework method
- * ignores when the RETURN key is pressed since this is handled in
- * <code>handleDefaultSelection</code>.
- * An exception is made for Ctrl+Enter for multi-line texts, since
- * a default selection event is not sent in this case.
- * </p>
- *
- * @param keyEvent the key event
- */
- @Override
- protected void keyReleaseOccured(KeyEvent keyEvent) {
- if (keyEvent.character == '\r') { // Return key
- // Enter is handled in handleDefaultSelection.
- // Do not apply the editor value in response to an Enter key event
- // since this can be received from the IME when the intent is -not-
- // to apply the value.
- // See bug 39074 [CellEditors] [DBCS] canna input mode fires bogus event from Text Control
- //
- // An exception is made for Ctrl+Enter for multi-line texts, since
- // a default selection event is not sent in this case.
- if (text != null && !text.isDisposed()
- && (text.getStyle() & SWT.MULTI) != 0) {
- if ((keyEvent.stateMask & SWT.CTRL) != 0) {
- super.keyReleaseOccured(keyEvent);
- }
- }
- return;
- }
- super.keyReleaseOccured(keyEvent);
- }
-
- /**
- * The <code>TextCellEditor</code> implementation of this
- * <code>CellEditor</code> method copies the
- * current selection to the clipboard.
- */
- @Override
- public void performCopy() {
- text.copy();
- }
-
- /**
- * The <code>TextCellEditor</code> implementation of this
- * <code>CellEditor</code> method cuts the
- * current selection to the clipboard.
- */
- @Override
- public void performCut() {
- text.cut();
- checkSelection();
- checkDeleteable();
- checkSelectable();
- }
-
- /**
- * The <code>TextCellEditor</code> implementation of this
- * <code>CellEditor</code> method deletes the
- * current selection or, if there is no selection,
- * the character next character from the current position.
- */
- @Override
- public void performDelete() {
- if (text.getSelectionCount() > 0) {
- // remove the contents of the current selection
- text.insert(""); //$NON-NLS-1$
- } else {
- // remove the next character
- int pos = text.getCaretPosition();
- if (pos < text.getCharCount()) {
- text.setSelection(pos, pos + 1);
- text.insert(""); //$NON-NLS-1$
- }
- }
- checkSelection();
- checkDeleteable();
- checkSelectable();
- }
-
- /**
- * The <code>TextCellEditor</code> implementation of this
- * <code>CellEditor</code> method pastes the
- * the clipboard contents over the current selection.
- */
- @Override
- public void performPaste() {
- text.paste();
- checkSelection();
- checkDeleteable();
- checkSelectable();
- }
-
- /**
- * The <code>TextCellEditor</code> implementation of this
- * <code>CellEditor</code> method selects all of the
- * current text.
- */
- @Override
- public void performSelectAll() {
- text.selectAll();
- checkSelection();
- checkDeleteable();
- }
-
- @Override
- protected void focusLost() {
- if (SdkConstants.currentPlatform() == SdkConstants.PLATFORM_LINUX) {
- // On Linux, something about the order of focus event delivery prevents the
- // callback on the "..." button to be invoked, which means the
- // customizer dialog never shows up (see issue #18348).
- // (Note that simply trying to Display.asyncRun() the super.focusLost()
- // method does not work.)
- //
- // We can work around this by not deactivating on a focus loss.
- // This means that in some cases the cell editor will still be
- // shown in the property sheet, but I've tested that the values
- // are all committed as before. This is better than having a non-operational
- // customizer, but since this issue only happens on Linux the workaround
- // is only done on Linux such that on other platforms we deactivate
- // immediately on focus loss.
- //
- if (isActivated()) {
- fireApplyEditorValue();
- // super.focusLost calls the following which we're deliberately
- // suppressing here:
- // deactivate();
- }
- } else {
- super.focusLost();
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/ErrorImageComposite.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/ErrorImageComposite.java
deleted file mode 100644
index 7085e5d50..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/ErrorImageComposite.java
+++ /dev/null
@@ -1,72 +0,0 @@
-package com.android.ide.eclipse.adt.internal.editors.ui;
-
-import static org.eclipse.ui.ISharedImages.IMG_DEC_FIELD_ERROR;
-import static org.eclipse.ui.ISharedImages.IMG_DEC_FIELD_WARNING;
-import static org.eclipse.ui.ISharedImages.IMG_OBJS_ERROR_TSK;
-import static org.eclipse.ui.ISharedImages.IMG_OBJS_WARN_TSK;
-
-import org.eclipse.jface.resource.CompositeImageDescriptor;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.DecorationOverlayIcon;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.ImageData;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-
-/**
- * ImageDescriptor that adds a error marker.
- * Based on {@link DecorationOverlayIcon} only available in Eclipse 3.3
- */
-public class ErrorImageComposite extends CompositeImageDescriptor {
-
- private Image mBaseImage;
- private ImageDescriptor mErrorImageDescriptor;
- private Point mSize;
-
- /**
- * Creates a new {@link ErrorImageComposite}
- *
- * @param baseImage the base image to overlay an icon on top of
- */
- public ErrorImageComposite(Image baseImage) {
- this(baseImage, false);
- }
-
- /**
- * Creates a new {@link ErrorImageComposite}
- *
- * @param baseImage the base image to overlay an icon on top of
- * @param warning if true, add a warning icon, otherwise an error icon
- */
- public ErrorImageComposite(Image baseImage, boolean warning) {
- mBaseImage = baseImage;
- ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages();
- mErrorImageDescriptor = sharedImages.getImageDescriptor(
- warning ? IMG_DEC_FIELD_WARNING : IMG_DEC_FIELD_ERROR);
- if (mErrorImageDescriptor == null) {
- mErrorImageDescriptor = sharedImages.getImageDescriptor(
- warning ? IMG_OBJS_WARN_TSK : IMG_OBJS_ERROR_TSK);
- }
- mSize = new Point(baseImage.getBounds().width, baseImage.getBounds().height);
- }
-
- @Override
- protected void drawCompositeImage(int width, int height) {
- ImageData baseData = mBaseImage.getImageData();
- drawImage(baseData, 0, 0);
-
- ImageData overlayData = mErrorImageDescriptor.getImageData();
- if (overlayData.width == baseData.width && overlayData.height == baseData.height) {
- overlayData = overlayData.scaledTo(14, 14);
- drawImage(overlayData, -3, mSize.y - overlayData.height + 3);
- } else {
- drawImage(overlayData, 0, mSize.y - overlayData.height);
- }
- }
-
- @Override
- protected Point getSize() {
- return mSize;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/FlagValueCellEditor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/FlagValueCellEditor.java
deleted file mode 100644
index 2a1bc36b5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/FlagValueCellEditor.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.ui;
-
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiFlagAttributeNode;
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-
-/**
- * DialogCellEditor able to receive a {@link UiFlagAttributeNode} in the {@link #setValue(Object)}
- * method.
- * <p/>The dialog box opened is the same as the one in the ui created by
- * {@link UiFlagAttributeNode#createUiControl(Composite, org.eclipse.ui.forms.IManagedForm)}
- */
-public class FlagValueCellEditor extends EditableDialogCellEditor {
-
- private UiFlagAttributeNode mUiFlagAttribute;
-
- public FlagValueCellEditor(Composite parent) {
- super(parent);
- }
-
- @Override
- protected Object openDialogBox(Control cellEditorWindow) {
- if (mUiFlagAttribute != null) {
- String currentValue = (String)getValue();
- return mUiFlagAttribute.showDialog(cellEditorWindow.getShell(), currentValue);
- }
-
- return null;
- }
-
- @Override
- protected void doSetValue(Object value) {
- if (value instanceof UiFlagAttributeNode) {
- mUiFlagAttribute = (UiFlagAttributeNode)value;
- super.doSetValue(mUiFlagAttribute.getCurrentValue());
- return;
- }
-
- super.doSetValue(value);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/ListValueCellEditor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/ListValueCellEditor.java
deleted file mode 100644
index 0c780a8c7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/ListValueCellEditor.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.ui;
-
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiListAttributeNode;
-
-import org.eclipse.jface.viewers.ComboBoxCellEditor;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.CCombo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-
-/**
- * ComboBoxCellEditor able to receive a {@link UiListAttributeNode} in the {@link #setValue(Object)}
- * method, and returning a {@link String} in {@link #getValue()} instead of an {@link Integer}.
- */
-public class ListValueCellEditor extends ComboBoxCellEditor {
- private String[] mItems;
- private CCombo mCombo;
-
- public ListValueCellEditor(Composite parent) {
- super(parent, new String[0], SWT.DROP_DOWN);
- }
-
- @Override
- protected Control createControl(Composite parent) {
- mCombo = (CCombo) super.createControl(parent);
- return mCombo;
- }
-
- @Override
- protected void doSetValue(Object value) {
- if (value instanceof UiListAttributeNode) {
- UiListAttributeNode uiListAttribute = (UiListAttributeNode)value;
-
- // set the possible values in the combo
- String[] items = uiListAttribute.getPossibleValues(null);
- mItems = new String[items.length];
- System.arraycopy(items, 0, mItems, 0, items.length);
- setItems(mItems);
-
- // now edit the current value of the attribute
- String attrValue = uiListAttribute.getCurrentValue();
- mCombo.setText(attrValue);
-
- return;
- }
-
- // default behavior
- super.doSetValue(value);
- }
-
- @Override
- protected Object doGetValue() {
- String comboText = mCombo.getText();
- if (comboText == null) {
- return ""; //$NON-NLS-1$
- }
- return comboText;
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/ResourceValueCellEditor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/ResourceValueCellEditor.java
deleted file mode 100644
index 8efe294b1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/ResourceValueCellEditor.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.ui;
-
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiFlagAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiResourceAttributeNode;
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-
-/**
- * DialogCellEditor able to receive a {@link UiFlagAttributeNode} in the {@link #setValue(Object)}
- * method.
- * <p/>The dialog box opened is the same as the one in the ui created by
- * {@link UiFlagAttributeNode#createUiControl(Composite, org.eclipse.ui.forms.IManagedForm)}
- */
-public class ResourceValueCellEditor extends EditableDialogCellEditor {
-
- private UiResourceAttributeNode mUiResourceAttribute;
-
- public ResourceValueCellEditor(Composite parent) {
- super(parent);
- }
-
- @Override
- protected Object openDialogBox(Control cellEditorWindow) {
- if (mUiResourceAttribute != null) {
- String currentValue = (String)getValue();
- return mUiResourceAttribute.showDialog(cellEditorWindow.getShell(), currentValue);
- }
-
- return null;
- }
-
- @Override
- protected void doSetValue(Object value) {
- if (value instanceof UiResourceAttributeNode) {
- mUiResourceAttribute = (UiResourceAttributeNode)value;
- super.doSetValue(mUiResourceAttribute.getCurrentValue());
- return;
- }
-
- super.doSetValue(value);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/SectionHelper.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/SectionHelper.java
deleted file mode 100644
index fdb5d8292..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/SectionHelper.java
+++ /dev/null
@@ -1,364 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.ui;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-
-import org.eclipse.jface.text.DefaultInformationControl;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseTrackListener;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.SectionPart;
-import org.eclipse.ui.forms.widgets.FormText;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.Section;
-import org.eclipse.ui.forms.widgets.TableWrapData;
-import org.eclipse.ui.forms.widgets.TableWrapLayout;
-
-import java.lang.reflect.Method;
-
-/**
- * Helper for the AndroidManifest form editor.
- *
- * Helps create a new SectionPart with sensible default parameters,
- * create default layout or add typical widgets.
- *
- * IMPORTANT: This is NOT a generic class. It makes a lot of assumptions on the
- * UI as used by the form editor for the AndroidManifest.
- *
- * TODO: Consider moving to a common package.
- */
-public final class SectionHelper {
-
- /**
- * Utility class that derives from SectionPart, constructs the Section with
- * sensible defaults (with a title and a description) and provide some shorthand
- * methods for creating typically UI (label and text, form text.)
- */
- static public class ManifestSectionPart extends SectionPart {
-
- /**
- * Construct a SectionPart that uses a title bar and a description.
- * It's up to the caller to call setText() and setDescription().
- * <p/>
- * The section style includes a description and a title bar by default.
- *
- * @param body The parent (e.g. FormPage body)
- * @param toolkit Form Toolkit
- */
- public ManifestSectionPart(Composite body, FormToolkit toolkit) {
- this(body, toolkit, 0, false);
- }
-
- /**
- * Construct a SectionPart that uses a title bar and a description.
- * It's up to the caller to call setText() and setDescription().
- * <p/>
- * The section style includes a description and a title bar by default.
- * You can add extra styles, like Section.TWISTIE.
- *
- * @param body The parent (e.g. FormPage body).
- * @param toolkit Form Toolkit.
- * @param extra_style Extra styles (on top of description and title bar).
- * @param use_description True if the Section.DESCRIPTION style should be added.
- */
- public ManifestSectionPart(Composite body, FormToolkit toolkit,
- int extra_style, boolean use_description) {
- super(body, toolkit, extra_style |
- Section.TITLE_BAR |
- (use_description ? Section.DESCRIPTION : 0));
- }
-
- // Create non-static methods of helpers just for convenience
-
- /**
- * Creates a new composite with a TableWrapLayout set with a given number of columns.
- *
- * If the parent composite is a Section, the new composite is set as a client.
- *
- * @param toolkit Form Toolkit
- * @param numColumns Desired number of columns.
- * @return The new composite.
- */
- public Composite createTableLayout(FormToolkit toolkit, int numColumns) {
- return SectionHelper.createTableLayout(getSection(), toolkit, numColumns);
- }
-
- /**
- * Creates a label widget.
- * If the parent layout if a TableWrapLayout, maximize it to span over all columns.
- *
- * @param parent The parent (e.g. composite from CreateTableLayout())
- * @param toolkit Form Toolkit
- * @param label The string for the label.
- * @param tooltip An optional tooltip for the label and text. Can be null.
- * @return The new created label
- */
- public Label createLabel(Composite parent, FormToolkit toolkit, String label,
- String tooltip) {
- return SectionHelper.createLabel(parent, toolkit, label, tooltip);
- }
-
- /**
- * Creates two widgets: a label and a text field.
- *
- * This expects the parent composite to have a TableWrapLayout with 2 columns.
- *
- * @param parent The parent (e.g. composite from CreateTableLayout())
- * @param toolkit Form Toolkit
- * @param label The string for the label.
- * @param value The initial value of the text field. Can be null.
- * @param tooltip An optional tooltip for the label and text. Can be null.
- * @return The new created Text field (the label is not returned)
- */
- public Text createLabelAndText(Composite parent, FormToolkit toolkit, String label,
- String value, String tooltip) {
- return SectionHelper.createLabelAndText(parent, toolkit, label, value, tooltip);
- }
-
- /**
- * Creates a FormText widget.
- *
- * This expects the parent composite to have a TableWrapLayout with 2 columns.
- *
- * @param parent The parent (e.g. composite from CreateTableLayout())
- * @param toolkit Form Toolkit
- * @param isHtml True if the form text will contain HTML that must be interpreted as
- * rich text (i.e. parse tags & expand URLs).
- * @param label The string for the label.
- * @param setupLayoutData indicates whether the created form text receives a TableWrapData
- * through the setLayoutData method. In some case, creating it will make the table parent
- * huge, which we don't want.
- * @return The new created FormText.
- */
- public FormText createFormText(Composite parent, FormToolkit toolkit, boolean isHtml,
- String label, boolean setupLayoutData) {
- return SectionHelper.createFormText(parent, toolkit, isHtml, label, setupLayoutData);
- }
-
- /**
- * Forces the section to recompute its layout and redraw.
- * This is needed after the content of the section has been changed at runtime.
- */
- public void layoutChanged() {
- Section section = getSection();
-
- // Calls getSection().reflow(), which is the same that Section calls
- // when the expandable state is changed and the height changes.
- // Since this is protected, some reflection is needed to invoke it.
- try {
- Method reflow;
- reflow = section.getClass().getDeclaredMethod("reflow", (Class<?>[])null);
- reflow.setAccessible(true);
- reflow.invoke(section);
- } catch (Exception e) {
- AdtPlugin.log(e, "Error when invoking Section.reflow");
- }
-
- section.layout(true /* changed */, true /* all */);
- }
- }
-
- /**
- * Creates a new composite with a TableWrapLayout set with a given number of columns.
- *
- * If the parent composite is a Section, the new composite is set as a client.
- *
- * @param composite The parent (e.g. a Section or SectionPart)
- * @param toolkit Form Toolkit
- * @param numColumns Desired number of columns.
- * @return The new composite.
- */
- static public Composite createTableLayout(Composite composite, FormToolkit toolkit,
- int numColumns) {
- Composite table = toolkit.createComposite(composite);
- TableWrapLayout layout = new TableWrapLayout();
- layout.numColumns = numColumns;
- table.setLayout(layout);
- toolkit.paintBordersFor(table);
- if (composite instanceof Section) {
- ((Section) composite).setClient(table);
- }
- return table;
- }
-
- /**
- * Creates a new composite with a GridLayout set with a given number of columns.
- *
- * If the parent composite is a Section, the new composite is set as a client.
- *
- * @param composite The parent (e.g. a Section or SectionPart)
- * @param toolkit Form Toolkit
- * @param numColumns Desired number of columns.
- * @return The new composite.
- */
- static public Composite createGridLayout(Composite composite, FormToolkit toolkit,
- int numColumns) {
- Composite grid = toolkit.createComposite(composite);
- GridLayout layout = new GridLayout();
- layout.numColumns = numColumns;
- grid.setLayout(layout);
- toolkit.paintBordersFor(grid);
- if (composite instanceof Section) {
- ((Section) composite).setClient(grid);
- }
- return grid;
- }
-
- /**
- * Creates two widgets: a label and a text field.
- *
- * This expects the parent composite to have a TableWrapLayout with 2 columns.
- *
- * @param parent The parent (e.g. composite from CreateTableLayout())
- * @param toolkit Form Toolkit
- * @param label_text The string for the label.
- * @param value The initial value of the text field. Can be null.
- * @param tooltip An optional tooltip for the label and text. Can be null.
- * @return The new created Text field (the label is not returned)
- */
- static public Text createLabelAndText(Composite parent, FormToolkit toolkit, String label_text,
- String value, String tooltip) {
- Label label = toolkit.createLabel(parent, label_text);
- label.setLayoutData(new TableWrapData(TableWrapData.LEFT, TableWrapData.MIDDLE));
- Text text = toolkit.createText(parent, value);
- text.setLayoutData(new TableWrapData(TableWrapData.FILL_GRAB, TableWrapData.MIDDLE));
-
- addControlTooltip(label, tooltip);
- return text;
- }
-
- /**
- * Creates a label widget.
- * If the parent layout if a TableWrapLayout, maximize it to span over all columns.
- *
- * @param parent The parent (e.g. composite from CreateTableLayout())
- * @param toolkit Form Toolkit
- * @param label_text The string for the label.
- * @param tooltip An optional tooltip for the label and text. Can be null.
- * @return The new created label
- */
- static public Label createLabel(Composite parent, FormToolkit toolkit, String label_text,
- String tooltip) {
- Label label = toolkit.createLabel(parent, label_text);
-
- TableWrapData twd = new TableWrapData(TableWrapData.FILL_GRAB);
- if (parent.getLayout() instanceof TableWrapLayout) {
- twd.colspan = ((TableWrapLayout) parent.getLayout()).numColumns;
- }
- label.setLayoutData(twd);
-
- addControlTooltip(label, tooltip);
- return label;
- }
-
- /**
- * Associates a tooltip with a control.
- *
- * This mirrors the behavior from org.eclipse.pde.internal.ui.editor.text.PDETextHover
- *
- * @param control The control to which associate the tooltip.
- * @param tooltip The tooltip string. Can use \n for multi-lines. Will not display if null.
- */
- static public void addControlTooltip(final Control control, String tooltip) {
- if (control == null || tooltip == null || tooltip.length() == 0) {
- return;
- }
-
- // Some kinds of controls already properly implement tooltip display.
- if (control instanceof Button) {
- control.setToolTipText(tooltip);
- return;
- }
-
- control.setToolTipText(null);
-
- final DefaultInformationControl ic = new DefaultInformationControl(control.getShell());
- ic.setInformation(tooltip);
- Point sz = ic.computeSizeHint();
- ic.setSize(sz.x, sz.y);
- ic.setVisible(false); // initially hidden
-
- control.addMouseTrackListener(new MouseTrackListener() {
- @Override
- public void mouseEnter(MouseEvent e) {
- }
-
- @Override
- public void mouseExit(MouseEvent e) {
- ic.setVisible(false);
- }
-
- @Override
- public void mouseHover(MouseEvent e) {
- ic.setLocation(control.toDisplay(10, 25)); // same offset as in PDETextHover
- ic.setVisible(true);
- }
- });
- control.addDisposeListener(new DisposeListener() {
- @Override
- public void widgetDisposed(DisposeEvent e) {
- ic.dispose();
- }
- });
- }
-
- /**
- * Creates a FormText widget.
- *
- * This expects the parent composite to have a TableWrapLayout with 2 columns.
- *
- * @param parent The parent (e.g. composite from CreateTableLayout())
- * @param toolkit Form Toolkit
- * @param isHtml True if the form text will contain HTML that must be interpreted as
- * rich text (i.e. parse tags & expand URLs).
- * @param label The string for the label.
- * @param setupLayoutData indicates whether the created form text receives a TableWrapData
- * through the setLayoutData method. In some case, creating it will make the table parent
- * huge, which we don't want.
- * @return The new created FormText.
- */
- static public FormText createFormText(Composite parent, FormToolkit toolkit,
- boolean isHtml, String label, boolean setupLayoutData) {
- FormText text = toolkit.createFormText(parent, true /* track focus */);
- if (setupLayoutData) {
- TableWrapData twd = new TableWrapData(TableWrapData.FILL_GRAB);
- twd.maxWidth = AndroidXmlEditor.TEXT_WIDTH_HINT;
- if (parent.getLayout() instanceof TableWrapLayout) {
- twd.colspan = ((TableWrapLayout) parent.getLayout()).numColumns;
- }
- text.setLayoutData(twd);
- }
- text.setWhitespaceNormalized(true);
- if (isHtml && !label.startsWith("<form>")) { //$NON-NLS-1$
- // This assertion is violated, for example by the Class attribute for an activity
- //assert label.startsWith("<form>") : "HTML for FormText must be wrapped in <form>...</form>"; //$NON-NLS-1$
- label = "<form>" + label + "</form>"; //$NON-NLS-1$ //$NON-NLS-2$
- }
- text.setText(label, isHtml /* parseTags */, isHtml /* expandURLs */);
- return text;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/TextValueCellEditor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/TextValueCellEditor.java
deleted file mode 100644
index 3750c3472..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/TextValueCellEditor.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.ui;
-
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-
-import org.eclipse.jface.viewers.TextCellEditor;
-import org.eclipse.swt.widgets.Composite;
-
-/**
- * TextCellEditor able to receive a {@link UiAttributeNode} in the {@link #setValue(Object)}
- * method.
- */
-public class TextValueCellEditor extends TextCellEditor {
-
- public TextValueCellEditor(Composite parent) {
- super(parent);
- }
-
- @Override
- protected void doSetValue(Object value) {
- if (value instanceof UiAttributeNode) {
- super.doSetValue(((UiAttributeNode)value).getCurrentValue());
- return;
- }
-
- super.doSetValue(value);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/UiElementPart.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/UiElementPart.java
deleted file mode 100644
index db9fa069f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/UiElementPart.java
+++ /dev/null
@@ -1,284 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.ui;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.XmlnsAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestEditor;
-import com.android.ide.eclipse.adt.internal.editors.ui.SectionHelper.ManifestSectionPart;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.Section;
-
-/**
- * Generic page's section part that displays all attributes of a given {@link UiElementNode}.
- * <p/>
- * This part is designed to be displayed in a page that has a table column layout.
- * It is linked to a specific {@link UiElementNode} and automatically displays all of its
- * attributes, manages its dirty state and commits the attributes when necessary.
- * <p/>
- * No derivation is needed unless the UI or workflow needs to be extended.
- */
-public class UiElementPart extends ManifestSectionPart {
-
- /** A reference to the container editor */
- private ManifestEditor mEditor;
- /** The {@link UiElementNode} manipulated by this SectionPart. It can be null. */
- private UiElementNode mUiElementNode;
- /** Table that contains all the attributes */
- private Composite mTable;
-
- public UiElementPart(Composite body, FormToolkit toolkit, ManifestEditor editor,
- UiElementNode uiElementNode, String sectionTitle, String sectionDescription,
- int extra_style) {
- super(body, toolkit, extra_style, sectionDescription != null);
- mEditor = editor;
- mUiElementNode = uiElementNode;
- setupSection(sectionTitle, sectionDescription);
-
- if (uiElementNode == null) {
- // This is serious and should never happen. Instead of crashing, simply abort.
- // There will be no UI, which will prevent further damage.
- AdtPlugin.log(IStatus.ERROR, "Missing node to edit!"); //$NON-NLS-1$
- return;
- }
- }
-
- /**
- * Returns the Editor associated with this part.
- */
- public ManifestEditor getEditor() {
- return mEditor;
- }
-
- /**
- * Returns the {@link UiElementNode} associated with this part.
- */
- public UiElementNode getUiElementNode() {
- return mUiElementNode;
- }
-
- /**
- * Changes the element node handled by this part.
- *
- * @param uiElementNode The new element node for the part.
- */
- public void setUiElementNode(UiElementNode uiElementNode) {
- mUiElementNode = uiElementNode;
- }
-
- /**
- * Initializes the form part.
- * <p/>
- * This is called by the owning managed form as soon as the part is added to the form,
- * which happens right after the part is actually created.
- */
- @Override
- public void initialize(IManagedForm form) {
- super.initialize(form);
- createFormControls(form);
- }
-
- /**
- * Setup the section that contains this part.
- * <p/>
- * This is called by the constructor to set the section's title and description
- * with parameters given in the constructor.
- * <br/>
- * Derived class override this if needed, however in most cases the default
- * implementation should be enough.
- *
- * @param sectionTitle The section part's title
- * @param sectionDescription The section part's description
- */
- protected void setupSection(String sectionTitle, String sectionDescription) {
- Section section = getSection();
- section.setText(sectionTitle);
- section.setDescription(sectionDescription);
- }
-
- /**
- * Create the controls to edit the attributes for the given ElementDescriptor.
- * <p/>
- * This MUST not be called by the constructor. Instead it must be called from
- * <code>initialize</code> (i.e. right after the form part is added to the managed form.)
- * <p/>
- * Derived classes can override this if necessary.
- *
- * @param managedForm The owner managed form
- */
- protected void createFormControls(IManagedForm managedForm) {
- setTable(createTableLayout(managedForm.getToolkit(), 2 /* numColumns */));
-
- createUiAttributes(managedForm);
- }
-
- /**
- * Sets the table where the attribute UI needs to be created.
- */
- protected void setTable(Composite table) {
- mTable = table;
- }
-
- /**
- * Returns the table where the attribute UI needs to be created.
- */
- protected Composite getTable() {
- return mTable;
- }
-
- /**
- * Add all the attribute UI widgets into the underlying table layout.
- *
- * @param managedForm The owner managed form
- */
- protected void createUiAttributes(IManagedForm managedForm) {
- Composite table = getTable();
- if (table == null || managedForm == null) {
- return;
- }
-
- // Remove any old UI controls
- for (Control c : table.getChildren()) {
- c.dispose();
- }
-
- fillTable(table, managedForm);
-
- // Tell the section that the layout has changed.
- layoutChanged();
- }
-
- /**
- * Actually fills the table.
- * This is called by {@link #createUiAttributes(IManagedForm)} to populate the new
- * table. The default implementation is to use
- * {@link #insertUiAttributes(UiElementNode, Composite, IManagedForm)} to actually
- * place the attributes of the default {@link UiElementNode} in the table.
- * <p/>
- * Derived classes can override this to add controls in the table before or after.
- *
- * @param table The table to fill. It must have 2 columns.
- * @param managedForm The managed form for new controls.
- */
- protected void fillTable(Composite table, IManagedForm managedForm) {
- int inserted = insertUiAttributes(mUiElementNode, table, managedForm);
-
- if (inserted == 0) {
- createLabel(table, managedForm.getToolkit(),
- "No attributes to display, waiting for SDK to finish loading...",
- null /* tooltip */ );
- }
- }
-
- /**
- * Insert the UI attributes of the given {@link UiElementNode} in the given table.
- *
- * @param uiNode The {@link UiElementNode} that contains the attributes to display.
- * Must not be null.
- * @param table The table to fill. It must have 2 columns.
- * @param managedForm The managed form for new controls.
- * @return The number of UI attributes inserted. It is >= 0.
- */
- protected int insertUiAttributes(UiElementNode uiNode, Composite table, IManagedForm managedForm) {
- if (uiNode == null || table == null || managedForm == null) {
- return 0;
- }
-
- // To iterate over all attributes, we use the {@link ElementDescriptor} instead
- // of the {@link UiElementNode} because the attributes' order is guaranteed in the
- // descriptor but not in the node itself.
- AttributeDescriptor[] attr_desc_list = uiNode.getAttributeDescriptors();
- for (AttributeDescriptor attr_desc : attr_desc_list) {
- if (attr_desc instanceof XmlnsAttributeDescriptor) {
- // Do not show hidden attributes
- continue;
- }
-
- UiAttributeNode ui_attr = uiNode.findUiAttribute(attr_desc);
- if (ui_attr != null) {
- ui_attr.createUiControl(table, managedForm);
- } else {
- // The XML has an extra attribute which wasn't declared in
- // AndroidManifestDescriptors. This is not a problem, we just ignore it.
- AdtPlugin.log(IStatus.WARNING,
- "Attribute %1$s not declared in node %2$s, ignored.", //$NON-NLS-1$
- attr_desc.getXmlLocalName(),
- uiNode.getDescriptor().getXmlName());
- }
- }
- return attr_desc_list.length;
- }
-
- /**
- * Tests whether the part is dirty i.e. its widgets have state that is
- * newer than the data in the model.
- * <p/>
- * This is done by iterating over all attributes and updating the super's
- * internal dirty flag. Stop once at least one attribute is dirty.
- *
- * @return <code>true</code> if the part is dirty, <code>false</code>
- * otherwise.
- */
- @Override
- public boolean isDirty() {
- if (mUiElementNode != null && !super.isDirty()) {
- for (UiAttributeNode ui_attr : mUiElementNode.getAllUiAttributes()) {
- if (ui_attr.isDirty()) {
- markDirty();
- break;
- }
- }
- }
- return super.isDirty();
- }
-
- /**
- * If part is displaying information loaded from a model, this method
- * instructs it to commit the new (modified) data back into the model.
- *
- * @param onSave
- * indicates if commit is called during 'save' operation or for
- * some other reason (for example, if form is contained in a
- * wizard or a multi-page editor and the user is about to leave
- * the page).
- */
- @Override
- public void commit(boolean onSave) {
- if (mUiElementNode != null) {
- mEditor.wrapEditXmlModel(new Runnable() {
- @Override
- public void run() {
- for (UiAttributeNode ui_attr : mUiElementNode.getAllUiAttributes()) {
- ui_attr.commit();
- }
- }
- });
- }
-
- // We need to call super's commit after we synchronized the nodes to make sure we
- // reset the dirty flag after all the side effects from committing have occurred.
- super.commit(onSave);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/CopyCutAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/CopyCutAction.java
deleted file mode 100644
index 3fe98bb23..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/CopyCutAction.java
+++ /dev/null
@@ -1,221 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.ui.tree;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-import org.apache.xml.serialize.Method;
-import org.apache.xml.serialize.OutputFormat;
-import org.apache.xml.serialize.XMLSerializer;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.eclipse.wst.xml.core.internal.document.NodeContainer;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-import java.io.IOException;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.List;
-
-
-/**
- * Provides Cut and Copy actions for the tree nodes.
- */
-@SuppressWarnings({"restriction", "deprecation"})
-public class CopyCutAction extends Action {
- private List<UiElementNode> mUiNodes;
- private boolean mPerformCut;
- private final AndroidXmlEditor mEditor;
- private final Clipboard mClipboard;
- private final ICommitXml mXmlCommit;
-
- /**
- * Creates a new Copy or Cut action.
- *
- * @param selected The UI node to cut or copy. It *must* have a non-null XML node.
- * @param performCut True if the operation is cut, false if it is copy.
- */
- public CopyCutAction(AndroidXmlEditor editor, Clipboard clipboard, ICommitXml xmlCommit,
- UiElementNode selected, boolean performCut) {
- this(editor, clipboard, xmlCommit, toList(selected), performCut);
- }
-
- /**
- * Creates a new Copy or Cut action.
- *
- * @param selected The UI nodes to cut or copy. They *must* have a non-null XML node.
- * The list becomes owned by the {@link CopyCutAction}.
- * @param performCut True if the operation is cut, false if it is copy.
- */
- public CopyCutAction(AndroidXmlEditor editor, Clipboard clipboard, ICommitXml xmlCommit,
- List<UiElementNode> selected, boolean performCut) {
- super(performCut ? "Cut" : "Copy");
- mEditor = editor;
- mClipboard = clipboard;
- mXmlCommit = xmlCommit;
-
- ISharedImages images = PlatformUI.getWorkbench().getSharedImages();
- if (performCut) {
- setImageDescriptor(images.getImageDescriptor(ISharedImages.IMG_TOOL_CUT));
- setHoverImageDescriptor(images.getImageDescriptor(ISharedImages.IMG_TOOL_CUT_HOVER));
- setDisabledImageDescriptor(
- images.getImageDescriptor(ISharedImages.IMG_TOOL_CUT_DISABLED));
- } else {
- setImageDescriptor(images.getImageDescriptor(ISharedImages.IMG_TOOL_COPY));
- setHoverImageDescriptor(images.getImageDescriptor(ISharedImages.IMG_TOOL_COPY_HOVER));
- setDisabledImageDescriptor(
- images.getImageDescriptor(ISharedImages.IMG_TOOL_COPY_DISABLED));
- }
-
- mUiNodes = selected;
- mPerformCut = performCut;
- }
-
- /**
- * Performs the cut or copy action.
- * First an XML serializer is used to turn the existing XML node into a valid
- * XML fragment, which is added as text to the clipboard.
- */
- @Override
- public void run() {
- super.run();
- if (mUiNodes == null || mUiNodes.size() < 1) {
- return;
- }
-
- // Commit the current pages first, to make sure the XML is in sync.
- // Committing may change the XML structure.
- if (mXmlCommit != null) {
- mXmlCommit.commitPendingXmlChanges();
- }
-
- StringBuilder allText = new StringBuilder();
- ArrayList<UiElementNode> nodesToCut = mPerformCut ? new ArrayList<UiElementNode>() : null;
-
- for (UiElementNode uiNode : mUiNodes) {
- try {
- Node xml_node = uiNode.getXmlNode();
- if (xml_node == null) {
- return;
- }
-
- String data = getXmlTextFromEditor(xml_node);
-
- // In the unlikely event that IStructuredDocument failed to extract the text
- // directly from the editor, try to fall back on a direct XML serialization
- // of the XML node. This uses the generic Node interface with no SSE tricks.
- if (data == null) {
- data = getXmlTextFromSerialization(xml_node);
- }
-
- if (data != null) {
- allText.append(data);
- if (mPerformCut) {
- // only remove notes to cut if we actually got some XML text from them
- nodesToCut.add(uiNode);
- }
- }
-
- } catch (Exception e) {
- AdtPlugin.log(e, "CopyCutAction failed for UI node %1$s", //$NON-NLS-1$
- uiNode.getBreadcrumbTrailDescription(true));
- }
- } // for uiNode
-
- if (allText != null && allText.length() > 0) {
- mClipboard.setContents(
- new Object[] { allText.toString() },
- new Transfer[] { TextTransfer.getInstance() });
- if (mPerformCut) {
- for (UiElementNode uiNode : nodesToCut) {
- uiNode.deleteXmlNode();
- }
- }
- }
- }
-
- /** Get the data directly from the editor. */
- private String getXmlTextFromEditor(Node xml_node) {
- String data = null;
- IStructuredModel model = mEditor.getModelForRead();
- try {
- IStructuredDocument sse_doc = mEditor.getStructuredDocument();
- if (xml_node instanceof NodeContainer) {
- // The easy way to get the source of an SSE XML node.
- data = ((NodeContainer) xml_node).getSource();
- } else if (xml_node instanceof IndexedRegion && sse_doc != null) {
- // Try harder.
- IndexedRegion region = (IndexedRegion) xml_node;
- int start = region.getStartOffset();
- int end = region.getEndOffset();
-
- if (end > start) {
- data = sse_doc.get(start, end - start);
- }
- }
- } catch (BadLocationException e) {
- // the region offset was invalid. ignore.
- } finally {
- model.releaseFromRead();
- }
- return data;
- }
-
- /**
- * Direct XML serialization of the XML node.
- * <p/>
- * This uses the generic Node interface with no SSE tricks. It's however slower
- * and doesn't respect formatting (since serialization is involved instead of reading
- * the actual text buffer.)
- */
- private String getXmlTextFromSerialization(Node xml_node) throws IOException {
- String data;
- StringWriter sw = new StringWriter();
- XMLSerializer serializer = new XMLSerializer(sw,
- new OutputFormat(Method.XML,
- OutputFormat.Defaults.Encoding /* utf-8 */,
- true /* indent */));
- // Serialize will throw an IOException if it fails.
- serializer.serialize((Element) xml_node);
- data = sw.toString();
- return data;
- }
-
- /**
- * Static helper class to wrap on node into a list for the constructors.
- */
- private static ArrayList<UiElementNode> toList(UiElementNode selected) {
- ArrayList<UiElementNode> list = null;
- if (selected != null) {
- list = new ArrayList<UiElementNode>(1);
- list.add(selected);
- }
- return list;
- }
-}
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/ICommitXml.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/ICommitXml.java
deleted file mode 100644
index 067d1459e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/ICommitXml.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-
-package com.android.ide.eclipse.adt.internal.editors.ui.tree;
-
-/**
- * Interface for an object that can commit its changes to the underlying XML model
- */
-public interface ICommitXml {
-
- /** Commits pending data to the underlying XML model. */
- public void commitPendingXmlChanges();
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/NewItemSelectionDialog.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/NewItemSelectionDialog.java
deleted file mode 100644
index 385a53a5f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/NewItemSelectionDialog.java
+++ /dev/null
@@ -1,415 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.ui.tree;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.dialogs.AbstractElementListSelectionDialog;
-import org.eclipse.ui.dialogs.ISelectionStatusValidator;
-import org.eclipse.ui.part.FileEditorInput;
-
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.TreeMap;
-
-/**
- * A selection dialog to select the type of the new element node to
- * create, either in the application node or the selected sub node.
- */
-public class NewItemSelectionDialog extends AbstractElementListSelectionDialog {
-
- /** The UI node selected in the tree view before creating the new item selection dialog.
- * Can be null -- which means new items must be created in the root_node. */
- private UiElementNode mSelectedUiNode;
- /** The root node chosen by the user, either root_node or the one passed
- * to the constructor if not null */
- private UiElementNode mChosenRootNode;
- private UiElementNode mLocalRootNode;
- /** The descriptor of the elements to be displayed as root in this tree view. All elements
- * of the same type in the root will be displayed. Can be null. */
- private ElementDescriptor[] mDescriptorFilters;
- /** The key for the {@link #setLastUsedXmlName(Object[])}. It corresponds to the full
- * workspace path of the currently edited file, if this can be computed. This is computed
- * by {@link #getLastUsedXmlName(UiElementNode)}, called from the constructor. */
- private String mLastUsedKey;
- /** A static map of known XML Names used for a given file. The map has full workspace
- * paths as key and XML names as values. */
- private static final Map<String, String> sLastUsedXmlName = new HashMap<String, String>();
- /** The potential XML Name to initially select in the selection dialog. This is computed
- * in the constructor and set by {@link #setInitialSelection(UiElementNode)}. */
- private String mInitialXmlName;
-
- /**
- * Creates the new item selection dialog.
- *
- * @param shell The parent shell for the list.
- * @param labelProvider ILabelProvider for the list.
- * @param descriptorFilters The element allows at the root of the tree. Can be null.
- * @param ui_node The selected node, or null if none is selected.
- * @param root_node The root of the Ui Tree, either the UiDocumentNode or a sub-node.
- */
- public NewItemSelectionDialog(Shell shell, ILabelProvider labelProvider,
- ElementDescriptor[] descriptorFilters,
- UiElementNode ui_node,
- UiElementNode root_node) {
- super(shell, labelProvider);
- mDescriptorFilters = descriptorFilters;
- mLocalRootNode = root_node;
-
- // Only accept the UI node if it is not the UI root node and it can have children.
- // If the node cannot have children, select its parent as a potential target.
- if (ui_node != null && ui_node != mLocalRootNode) {
- if (ui_node.getDescriptor().hasChildren()) {
- mSelectedUiNode = ui_node;
- } else {
- UiElementNode parent = ui_node.getUiParent();
- if (parent != null && parent != mLocalRootNode) {
- mSelectedUiNode = parent;
- }
- }
- }
-
- setHelpAvailable(false);
- setMultipleSelection(false);
-
- setValidator(new ISelectionStatusValidator() {
- @Override
- public IStatus validate(Object[] selection) {
- if (selection.length == 1 && selection[0] instanceof ViewElementDescriptor) {
- return new Status(IStatus.OK, // severity
- AdtPlugin.PLUGIN_ID, //plugin id
- IStatus.OK, // code
- ((ViewElementDescriptor) selection[0]).getFullClassName(), //msg
- null); // exception
- } else if (selection.length == 1 && selection[0] instanceof ElementDescriptor) {
- return new Status(IStatus.OK, // severity
- AdtPlugin.PLUGIN_ID, //plugin id
- IStatus.OK, // code
- "", //$NON-NLS-1$ // msg
- null); // exception
- } else {
- return new Status(IStatus.ERROR, // severity
- AdtPlugin.PLUGIN_ID, //plugin id
- IStatus.ERROR, // code
- "Invalid selection", // msg, translatable
- null); // exception
- }
- }
- });
-
- // Determine the initial selection using a couple heuristics.
-
- // First check if we can get the last used node type for this file.
- // The heuristic is that generally one keeps adding the same kind of items to the
- // same file, so reusing the last used item type makes most sense.
- String xmlName = getLastUsedXmlName(root_node);
- if (xmlName == null) {
- // Another heuristic is to find the most used item and default to that.
- xmlName = getMostUsedXmlName(root_node);
- }
- if (xmlName == null) {
- // Finally the last heuristic is to see if there's an item with a name
- // similar to the edited file name.
- xmlName = getLeafFileName(root_node);
- }
- // Set the potential name. Selecting the right item is done later by setInitialSelection().
- mInitialXmlName = xmlName;
- }
-
- /**
- * Returns a potential XML name based on the file name.
- * The item name is marked with an asterisk to identify it as a partial match.
- */
- private String getLeafFileName(UiElementNode ui_node) {
- if (ui_node != null) {
- AndroidXmlEditor editor = ui_node.getEditor();
- if (editor != null) {
- IEditorInput editorInput = editor.getEditorInput();
- if (editorInput instanceof FileEditorInput) {
- IFile f = ((FileEditorInput) editorInput).getFile();
- if (f != null) {
- String leafName = f.getFullPath().removeFileExtension().lastSegment();
- return "*" + leafName; //$NON-NLS-1$
- }
- }
- }
- }
-
- return null;
- }
-
- /**
- * Given a potential non-null root node, this method looks for the currently edited
- * file path and uses it as a key to retrieve the last used item for this file by this
- * selection dialog. Returns null if nothing can be found, otherwise returns the string
- * name of the item.
- */
- private String getLastUsedXmlName(UiElementNode ui_node) {
- if (ui_node != null) {
- AndroidXmlEditor editor = ui_node.getEditor();
- if (editor != null) {
- IEditorInput editorInput = editor.getEditorInput();
- if (editorInput instanceof FileEditorInput) {
- IFile f = ((FileEditorInput) editorInput).getFile();
- if (f != null) {
- mLastUsedKey = f.getFullPath().toPortableString();
-
- return sLastUsedXmlName.get(mLastUsedKey);
- }
- }
- }
- }
-
- return null;
- }
-
- /**
- * Sets the last used item for this selection dialog for this file.
- * @param objects The currently selected items. Only the first one is used if it is an
- * {@link ElementDescriptor}.
- */
- private void setLastUsedXmlName(Object[] objects) {
- if (mLastUsedKey != null &&
- objects != null &&
- objects.length > 0 &&
- objects[0] instanceof ElementDescriptor) {
- ElementDescriptor desc = (ElementDescriptor) objects[0];
- sLastUsedXmlName.put(mLastUsedKey, desc.getXmlName());
- }
- }
-
- /**
- * Returns the most used sub-element name, if any, or null.
- */
- private String getMostUsedXmlName(UiElementNode ui_node) {
- if (ui_node != null) {
- TreeMap<String, Integer> counts = new TreeMap<String, Integer>();
- int max = -1;
-
- for (UiElementNode child : ui_node.getUiChildren()) {
- String name = child.getDescriptor().getXmlName();
- Integer i = counts.get(name);
- int count = i == null ? 1 : i.intValue() + 1;
- counts.put(name, count);
- max = Math.max(max, count);
- }
-
- if (max > 0) {
- // Find first key with this max and return it
- for (Entry<String, Integer> entry : counts.entrySet()) {
- if (entry.getValue().intValue() == max) {
- return entry.getKey();
- }
- }
- }
- }
- return null;
- }
-
- /**
- * @return The root node selected by the user, either root node or the
- * one passed to the constructor if not null.
- */
- public UiElementNode getChosenRootNode() {
- return mChosenRootNode;
- }
-
- /**
- * Internal helper to compute the result. Returns the selection from
- * the list view, if any.
- */
- @Override
- protected void computeResult() {
- setResult(Arrays.asList(getSelectedElements()));
- setLastUsedXmlName(getSelectedElements());
- }
-
- /**
- * Creates the dialog area.
- *
- * First add a radio area, which may be either 2 radio controls or
- * just a message area if there's only one choice (the app root node).
- *
- * Then uses the default from the AbstractElementListSelectionDialog
- * which is to add both a filter text and a filtered list. Adding both
- * is necessary (since the base class accesses both internal directly
- * fields without checking for null pointers.)
- *
- * Finally sets the initial selection list.
- */
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite contents = (Composite) super.createDialogArea(parent);
-
- createRadioControl(contents);
- createFilterText(contents);
- createFilteredList(contents);
-
- // We don't want the builtin message area label (we use a radio control
- // instead), but if we don't create it, Bad Stuff happens on
- // Eclipse 3.8 and later (see issue 32527).
- Label label = createMessageArea(contents);
- if (label != null) {
- GridData data = (GridData) label.getLayoutData();
- data.exclude = true;
- }
-
- // Initialize the list state.
- // This must be done after the filtered list as been created.
- chooseNode(mChosenRootNode);
-
- // Set the initial selection
- setInitialSelection(mChosenRootNode);
- return contents;
- }
-
- /**
- * Tries to set the initial selection based on the {@link #mInitialXmlName} computed
- * in the constructor. The selection is only set if there's an element descriptor
- * that matches the same exact XML name. When {@link #mInitialXmlName} starts with an
- * asterisk, it means to do a partial case-insensitive match on the start of the
- * strings.
- */
- private void setInitialSelection(UiElementNode rootNode) {
- ElementDescriptor initialElement = null;
-
- if (mInitialXmlName != null && mInitialXmlName.length() > 0) {
- String name = mInitialXmlName;
- boolean partial = name.startsWith("*"); //$NON-NLS-1$
- if (partial) {
- name = name.substring(1).toLowerCase(Locale.US);
- }
-
- for (ElementDescriptor desc : getAllowedDescriptors(rootNode)) {
- if (!partial && desc.getXmlName().equals(name)) {
- initialElement = desc;
- break;
- } else if (partial) {
- String name2 = desc.getXmlLocalName().toLowerCase(Locale.US);
- if (name.startsWith(name2) || name2.startsWith(name)) {
- initialElement = desc;
- break;
- }
- }
- }
- }
-
- setSelection(initialElement == null ? null : new ElementDescriptor[] { initialElement });
- }
-
- /**
- * Creates the message text widget and sets layout data.
- * @param content the parent composite of the message area.
- */
- private Composite createRadioControl(Composite content) {
-
- if (mSelectedUiNode != null) {
- Button radio1 = new Button(content, SWT.RADIO);
- radio1.setText(String.format("Create a new element at the top level, in %1$s.",
- mLocalRootNode.getShortDescription()));
-
- Button radio2 = new Button(content, SWT.RADIO);
- radio2.setText(String.format("Create a new element in the selected element, %1$s.",
- mSelectedUiNode.getBreadcrumbTrailDescription(false /* include_root */)));
-
- // Set the initial selection before adding the listeners
- // (they can't be run till the filtered list has been created)
- radio1.setSelection(false);
- radio2.setSelection(true);
- mChosenRootNode = mSelectedUiNode;
-
- radio1.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- super.widgetSelected(e);
- chooseNode(mLocalRootNode);
- }
- });
-
- radio2.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- super.widgetSelected(e);
- chooseNode(mSelectedUiNode);
- }
- });
- } else {
- setMessage(String.format("Create a new element at the top level, in %1$s.",
- mLocalRootNode.getShortDescription()));
- createMessageArea(content);
-
- mChosenRootNode = mLocalRootNode;
- }
-
- return content;
- }
-
- /**
- * Internal helper to remember the root node choosen by the user.
- * It also sets the list view to the adequate list of children that can
- * be added to the chosen root node.
- *
- * If the chosen root node is mLocalRootNode and a descriptor filter was specified
- * when creating the master-detail part, we use this as the set of nodes that
- * can be created on the root node.
- *
- * @param ui_node The chosen root node, either mLocalRootNode or
- * mSelectedUiNode.
- */
- private void chooseNode(UiElementNode ui_node) {
- mChosenRootNode = ui_node;
- setListElements(getAllowedDescriptors(ui_node));
- }
-
- /**
- * Returns the list of {@link ElementDescriptor}s that can be added to the given
- * UI node.
- *
- * @param ui_node The UI node to which element should be added. Cannot be null.
- * @return A non-null array of {@link ElementDescriptor}. The array might be empty.
- */
- private ElementDescriptor[] getAllowedDescriptors(UiElementNode ui_node) {
- if (ui_node == mLocalRootNode &&
- mDescriptorFilters != null &&
- mDescriptorFilters.length != 0) {
- return mDescriptorFilters;
- } else {
- return ui_node.getDescriptor().getChildren();
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/PasteAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/PasteAction.java
deleted file mode 100644
index 6674ba9ca..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/PasteAction.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.ui.tree;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiDocumentNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion;
-import org.eclipse.wst.xml.core.internal.document.NodeContainer;
-import org.w3c.dom.Node;
-
-
-/**
- * Provides Paste operation for the tree nodes
- */
-@SuppressWarnings("restriction")
-public class PasteAction extends Action {
- private UiElementNode mUiNode;
- private final AndroidXmlEditor mEditor;
- private final Clipboard mClipboard;
-
- public PasteAction(AndroidXmlEditor editor, Clipboard clipboard, UiElementNode ui_node) {
- super("Paste");
- mEditor = editor;
- mClipboard = clipboard;
-
- ISharedImages images = PlatformUI.getWorkbench().getSharedImages();
- setImageDescriptor(images.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE));
- setHoverImageDescriptor(images.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE));
- setDisabledImageDescriptor(
- images.getImageDescriptor(ISharedImages.IMG_TOOL_PASTE_DISABLED));
-
- mUiNode = ui_node;
- }
-
- /**
- * Performs the paste operation.
- */
- @Override
- public void run() {
- super.run();
-
- final String data = (String) mClipboard.getContents(TextTransfer.getInstance());
- if (data != null) {
- mEditor.wrapEditXmlModel(new Runnable() {
- @Override
- public void run() {
- try {
- IStructuredDocument sse_doc = mEditor.getStructuredDocument();
- if (sse_doc != null) {
- if (mUiNode.getDescriptor().hasChildren()) {
- // This UI Node can have children. The new XML is
- // inserted as the first child.
-
- if (mUiNode.getUiChildren().size() > 0) {
- // There's already at least one child,
- // so insert right before it.
- Node xml_node = mUiNode.getUiChildren().get(0).getXmlNode();
-
- if (xml_node instanceof IndexedRegion) {
- IndexedRegion region = (IndexedRegion) xml_node;
- sse_doc.replace(region.getStartOffset(), 0, data);
- return; // we're done, no need to try the other cases
- }
- }
-
- // If there's no first XML node child. Create one by
- // inserting at the end of the *start* tag.
- Node xml_node = mUiNode.getXmlNode();
- if (xml_node instanceof NodeContainer) {
- NodeContainer container = (NodeContainer) xml_node;
- IStructuredDocumentRegion start_tag =
- container.getStartStructuredDocumentRegion();
- if (start_tag != null) {
- sse_doc.replace(start_tag.getEndOffset(), 0, data);
- return; // we're done, no need to try the other case
- }
- }
- }
-
- // This UI Node doesn't accept children. The new XML is inserted as the
- // next sibling. This also serves as a fallback if all the previous
- // attempts failed. However, this is not possible if the current node
- // has for parent a document -- an XML document can only have one root,
- // with no siblings.
- if (!(mUiNode.getUiParent() instanceof UiDocumentNode)) {
- Node xml_node = mUiNode.getXmlNode();
- if (xml_node instanceof IndexedRegion) {
- IndexedRegion region = (IndexedRegion) xml_node;
- sse_doc.replace(region.getEndOffset(), 0, data);
- }
- }
- }
-
- } catch (BadLocationException e) {
- AdtPlugin.log(e,
- "ParseAction failed for UI Node %2$s, content '%1$s'", //$NON-NLS-1$
- mUiNode.getBreadcrumbTrailDescription(true), data);
- }
- }
- });
- }
- }
-}
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/UiActions.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/UiActions.java
deleted file mode 100644
index 92ccf2e7d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/UiActions.java
+++ /dev/null
@@ -1,598 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-
-package com.android.ide.eclipse.adt.internal.editors.ui.tree;
-
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor.Mandatory;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiDocumentNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.swt.widgets.Shell;
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-
-import java.util.List;
-
-/**
- * Performs basic actions on an XML tree: add node, remove node, move up/down.
- */
-public abstract class UiActions implements ICommitXml {
-
- public UiActions() {
- }
-
- //---------------------
- // Actual implementations must override these to provide specific hooks
-
- /** Returns the UiDocumentNode for the current model. */
- abstract protected UiElementNode getRootNode();
-
- /** Commits pending data before the XML model is modified. */
- @Override
- abstract public void commitPendingXmlChanges();
-
- /**
- * Utility method to select an outline item based on its model node
- *
- * @param uiNode The node to select. Can be null (in which case nothing should happen)
- */
- abstract protected void selectUiNode(UiElementNode uiNode);
-
- //---------------------
-
- /**
- * Called when the "Add..." button next to the tree view is selected.
- * <p/>
- * This simplified version of doAdd does not support descriptor filters and creates
- * a new {@link UiModelTreeLabelProvider} for each call.
- */
- public void doAdd(UiElementNode uiNode, Shell shell) {
- doAdd(uiNode, null /* descriptorFilters */, shell, new UiModelTreeLabelProvider());
- }
-
- /**
- * Called when the "Add..." button next to the tree view is selected.
- *
- * Displays a selection dialog that lets the user select which kind of node
- * to create, depending on the current selection.
- */
- public void doAdd(UiElementNode uiNode,
- ElementDescriptor[] descriptorFilters,
- Shell shell, ILabelProvider labelProvider) {
- // If the root node is a document with already a root, use it as the root node
- UiElementNode rootNode = getRootNode();
- if (rootNode instanceof UiDocumentNode && rootNode.getUiChildren().size() > 0) {
- rootNode = rootNode.getUiChildren().get(0);
- }
-
- NewItemSelectionDialog dlg = new NewItemSelectionDialog(
- shell,
- labelProvider,
- descriptorFilters,
- uiNode, rootNode);
- dlg.open();
- Object[] results = dlg.getResult();
- if (results != null && results.length > 0) {
- addElement(dlg.getChosenRootNode(), null, (ElementDescriptor) results[0],
- true /*updateLayout*/);
- }
- }
-
- /**
- * Adds a new XML element based on the {@link ElementDescriptor} to the given parent
- * {@link UiElementNode}, and then select it.
- * <p/>
- * If the parent is a document root which already contains a root element, the inner
- * root element is used as the actual parent. This ensure you can't create a broken
- * XML file with more than one root element.
- * <p/>
- * If a sibling is given and that sibling has the same parent, the new node is added
- * right after that sibling. Otherwise the new node is added at the end of the parent
- * child list.
- *
- * @param uiParent An existing UI node or null to add to the tree root
- * @param uiSibling An existing UI node before which to insert the new node. Can be null.
- * @param descriptor The descriptor of the element to add
- * @param updateLayout True if layout attributes should be set
- * @return The new {@link UiElementNode} or null.
- */
- public UiElementNode addElement(UiElementNode uiParent,
- UiElementNode uiSibling,
- ElementDescriptor descriptor,
- boolean updateLayout) {
- if (uiParent instanceof UiDocumentNode && uiParent.getUiChildren().size() > 0) {
- uiParent = uiParent.getUiChildren().get(0);
- }
- if (uiSibling != null && uiSibling.getUiParent() != uiParent) {
- uiSibling = null;
- }
-
- UiElementNode uiNew = addNewTreeElement(uiParent, uiSibling, descriptor, updateLayout);
- selectUiNode(uiNew);
-
- return uiNew;
- }
-
- /**
- * Called when the "Remove" button is selected.
- *
- * If the tree has a selection, remove it.
- * This simply deletes the XML node attached to the UI node: when the XML model fires the
- * update event, the tree will get refreshed.
- */
- public void doRemove(final List<UiElementNode> nodes, Shell shell) {
-
- if (nodes == null || nodes.size() == 0) {
- return;
- }
-
- final int len = nodes.size();
-
- StringBuilder sb = new StringBuilder();
- for (UiElementNode node : nodes) {
- sb.append("\n- "); //$NON-NLS-1$
- sb.append(node.getBreadcrumbTrailDescription(false /* include_root */));
- }
-
- if (MessageDialog.openQuestion(shell,
- len > 1 ? "Remove elements from Android XML" // title
- : "Remove element from Android XML",
- String.format("Do you really want to remove %1$s?", sb.toString()))) {
- commitPendingXmlChanges();
- getRootNode().getEditor().wrapEditXmlModel(new Runnable() {
- @Override
- public void run() {
- UiElementNode previous = null;
- UiElementNode parent = null;
-
- for (int i = len - 1; i >= 0; i--) {
- UiElementNode node = nodes.get(i);
- previous = node.getUiPreviousSibling();
- parent = node.getUiParent();
-
- // delete node
- node.deleteXmlNode();
- }
-
- // try to select the last previous sibling or the last parent
- if (previous != null) {
- selectUiNode(previous);
- } else if (parent != null) {
- selectUiNode(parent);
- }
- }
- });
- }
- }
-
- /**
- * Called when the "Up" button is selected.
- * <p/>
- * If the tree has a selection, move it up, either in the child list or as the last child
- * of the previous parent.
- */
- public void doUp(
- final List<UiElementNode> uiNodes,
- final ElementDescriptor[] descriptorFilters) {
- if (uiNodes == null || uiNodes.size() < 1) {
- return;
- }
-
- final Node[] selectXmlNode = { null };
- final UiElementNode[] uiLastNode = { null };
- final UiElementNode[] uiSearchRoot = { null };
-
- commitPendingXmlChanges();
- getRootNode().getEditor().wrapEditXmlModel(new Runnable() {
- @Override
- public void run() {
- for (int i = 0; i < uiNodes.size(); i++) {
- UiElementNode uiNode = uiLastNode[0] = uiNodes.get(i);
- doUpInternal(
- uiNode,
- descriptorFilters,
- selectXmlNode,
- uiSearchRoot,
- false /*testOnly*/);
- }
- }
- });
-
- assert uiLastNode[0] != null; // tell Eclipse this can't be null below
-
- if (selectXmlNode[0] == null) {
- // The XML node has not been moved, we can just select the same UI node
- selectUiNode(uiLastNode[0]);
- } else {
- // The XML node has moved. At this point the UI model has been reloaded
- // and the XML node has been affected to a new UI node. Find that new UI
- // node and select it.
- if (uiSearchRoot[0] == null) {
- uiSearchRoot[0] = uiLastNode[0].getUiRoot();
- }
- if (uiSearchRoot[0] != null) {
- selectUiNode(uiSearchRoot[0].findXmlNode(selectXmlNode[0]));
- }
- }
- }
-
- /**
- * Checks whether the "up" action can be performed on all items.
- *
- * @return True if the up action can be carried on *all* items.
- */
- public boolean canDoUp(
- List<UiElementNode> uiNodes,
- ElementDescriptor[] descriptorFilters) {
- if (uiNodes == null || uiNodes.size() < 1) {
- return false;
- }
-
- final Node[] selectXmlNode = { null };
- final UiElementNode[] uiSearchRoot = { null };
-
- commitPendingXmlChanges();
-
- for (int i = 0; i < uiNodes.size(); i++) {
- if (!doUpInternal(
- uiNodes.get(i),
- descriptorFilters,
- selectXmlNode,
- uiSearchRoot,
- true /*testOnly*/)) {
- return false;
- }
- }
-
- return true;
- }
-
- private boolean doUpInternal(
- UiElementNode uiNode,
- ElementDescriptor[] descriptorFilters,
- Node[] outSelectXmlNode,
- UiElementNode[] outUiSearchRoot,
- boolean testOnly) {
- // the node will move either up to its parent or grand-parent
- outUiSearchRoot[0] = uiNode.getUiParent();
- if (outUiSearchRoot[0] != null && outUiSearchRoot[0].getUiParent() != null) {
- outUiSearchRoot[0] = outUiSearchRoot[0].getUiParent();
- }
- Node xmlNode = uiNode.getXmlNode();
- ElementDescriptor nodeDesc = uiNode.getDescriptor();
- if (xmlNode == null || nodeDesc == null) {
- return false;
- }
- UiElementNode uiParentNode = uiNode.getUiParent();
- Node xmlParent = uiParentNode == null ? null : uiParentNode.getXmlNode();
- if (xmlParent == null) {
- return false;
- }
-
- UiElementNode uiPrev = uiNode.getUiPreviousSibling();
-
- // Only accept a sibling that has an XML attached and
- // is part of the allowed descriptor filters.
- while (uiPrev != null &&
- (uiPrev.getXmlNode() == null || !matchDescFilter(descriptorFilters, uiPrev))) {
- uiPrev = uiPrev.getUiPreviousSibling();
- }
-
- if (uiPrev != null && uiPrev.getXmlNode() != null) {
- // This node is not the first one of the parent.
- Node xmlPrev = uiPrev.getXmlNode();
- if (uiPrev.getDescriptor().acceptChild(nodeDesc)) {
- // If the previous sibling can accept this child, then it
- // is inserted at the end of the children list.
- if (testOnly) {
- return true;
- }
- xmlPrev.appendChild(xmlParent.removeChild(xmlNode));
- outSelectXmlNode[0] = xmlNode;
- } else {
- // This node is not the first one of the parent, so it can be
- // removed and then inserted before its previous sibling.
- if (testOnly) {
- return true;
- }
- xmlParent.insertBefore(
- xmlParent.removeChild(xmlNode),
- xmlPrev);
- outSelectXmlNode[0] = xmlNode;
- }
- } else if (uiParentNode != null && !(xmlParent instanceof Document)) {
- UiElementNode uiGrandParent = uiParentNode.getUiParent();
- Node xmlGrandParent = uiGrandParent == null ? null : uiGrandParent.getXmlNode();
- ElementDescriptor grandDesc =
- uiGrandParent == null ? null : uiGrandParent.getDescriptor();
-
- if (xmlGrandParent != null &&
- !(xmlGrandParent instanceof Document) &&
- grandDesc != null &&
- grandDesc.acceptChild(nodeDesc)) {
- // If the node is the first one of the child list of its
- // parent, move it up in the hierarchy as previous sibling
- // to the parent. This is only possible if the parent of the
- // parent is not a document.
- // The parent node must actually accept this kind of child.
-
- if (testOnly) {
- return true;
- }
- xmlGrandParent.insertBefore(
- xmlParent.removeChild(xmlNode),
- xmlParent);
- outSelectXmlNode[0] = xmlNode;
- }
- }
-
- return false;
- }
-
- private boolean matchDescFilter(
- ElementDescriptor[] descriptorFilters,
- UiElementNode uiNode) {
- if (descriptorFilters == null || descriptorFilters.length < 1) {
- return true;
- }
-
- ElementDescriptor desc = uiNode.getDescriptor();
-
- for (ElementDescriptor filter : descriptorFilters) {
- if (filter.equals(desc)) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Called when the "Down" button is selected.
- *
- * If the tree has a selection, move it down, either in the same child list or as the
- * first child of the next parent.
- */
- public void doDown(
- final List<UiElementNode> nodes,
- final ElementDescriptor[] descriptorFilters) {
- if (nodes == null || nodes.size() < 1) {
- return;
- }
-
- final Node[] selectXmlNode = { null };
- final UiElementNode[] uiLastNode = { null };
- final UiElementNode[] uiSearchRoot = { null };
-
- commitPendingXmlChanges();
- getRootNode().getEditor().wrapEditXmlModel(new Runnable() {
- @Override
- public void run() {
- for (int i = nodes.size() - 1; i >= 0; i--) {
- final UiElementNode node = uiLastNode[0] = nodes.get(i);
- doDownInternal(
- node,
- descriptorFilters,
- selectXmlNode,
- uiSearchRoot,
- false /*testOnly*/);
- }
- }
- });
-
- assert uiLastNode[0] != null; // tell Eclipse this can't be null below
-
- if (selectXmlNode[0] == null) {
- // The XML node has not been moved, we can just select the same UI node
- selectUiNode(uiLastNode[0]);
- } else {
- // The XML node has moved. At this point the UI model has been reloaded
- // and the XML node has been affected to a new UI node. Find that new UI
- // node and select it.
- if (uiSearchRoot[0] == null) {
- uiSearchRoot[0] = uiLastNode[0].getUiRoot();
- }
- if (uiSearchRoot[0] != null) {
- selectUiNode(uiSearchRoot[0].findXmlNode(selectXmlNode[0]));
- }
- }
- }
-
- /**
- * Checks whether the "down" action can be performed on all items.
- *
- * @return True if the down action can be carried on *all* items.
- */
- public boolean canDoDown(
- List<UiElementNode> uiNodes,
- ElementDescriptor[] descriptorFilters) {
- if (uiNodes == null || uiNodes.size() < 1) {
- return false;
- }
-
- final Node[] selectXmlNode = { null };
- final UiElementNode[] uiSearchRoot = { null };
-
- commitPendingXmlChanges();
-
- for (int i = 0; i < uiNodes.size(); i++) {
- if (!doDownInternal(
- uiNodes.get(i),
- descriptorFilters,
- selectXmlNode,
- uiSearchRoot,
- true /*testOnly*/)) {
- return false;
- }
- }
-
- return true;
- }
-
- private boolean doDownInternal(
- UiElementNode uiNode,
- ElementDescriptor[] descriptorFilters,
- Node[] outSelectXmlNode,
- UiElementNode[] outUiSearchRoot,
- boolean testOnly) {
- // the node will move either down to its parent or grand-parent
- outUiSearchRoot[0] = uiNode.getUiParent();
- if (outUiSearchRoot[0] != null && outUiSearchRoot[0].getUiParent() != null) {
- outUiSearchRoot[0] = outUiSearchRoot[0].getUiParent();
- }
-
- Node xmlNode = uiNode.getXmlNode();
- ElementDescriptor nodeDesc = uiNode.getDescriptor();
- if (xmlNode == null || nodeDesc == null) {
- return false;
- }
- UiElementNode uiParentNode = uiNode.getUiParent();
- Node xmlParent = uiParentNode == null ? null : uiParentNode.getXmlNode();
- if (xmlParent == null) {
- return false;
- }
-
- UiElementNode uiNext = uiNode.getUiNextSibling();
-
- // Only accept a sibling that has an XML attached and
- // is part of the allowed descriptor filters.
- while (uiNext != null &&
- (uiNext.getXmlNode() == null || !matchDescFilter(descriptorFilters, uiNext))) {
- uiNext = uiNext.getUiNextSibling();
- }
-
- if (uiNext != null && uiNext.getXmlNode() != null) {
- // This node is not the last one of the parent.
- Node xmlNext = uiNext.getXmlNode();
- // If the next sibling is a node that can have children, though,
- // then the node is inserted as the first child.
- if (uiNext.getDescriptor().acceptChild(nodeDesc)) {
- if (testOnly) {
- return true;
- }
- // Note: insertBefore works as append if the ref node is
- // null, i.e. when the node doesn't have children yet.
- xmlNext.insertBefore(
- xmlParent.removeChild(xmlNode),
- xmlNext.getFirstChild());
- outSelectXmlNode[0] = xmlNode;
- } else {
- // This node is not the last one of the parent, so it can be
- // removed and then inserted after its next sibling.
-
- if (testOnly) {
- return true;
- }
- // Insert "before after next" ;-)
- xmlParent.insertBefore(
- xmlParent.removeChild(xmlNode),
- xmlNext.getNextSibling());
- outSelectXmlNode[0] = xmlNode;
- }
- } else if (uiParentNode != null && !(xmlParent instanceof Document)) {
- UiElementNode uiGrandParent = uiParentNode.getUiParent();
- Node xmlGrandParent = uiGrandParent == null ? null : uiGrandParent.getXmlNode();
- ElementDescriptor grandDesc =
- uiGrandParent == null ? null : uiGrandParent.getDescriptor();
-
- if (xmlGrandParent != null &&
- !(xmlGrandParent instanceof Document) &&
- grandDesc != null &&
- grandDesc.acceptChild(nodeDesc)) {
- // This node is the last node of its parent.
- // If neither the parent nor the grandparent is a document,
- // then the node can be inserted right after the parent.
- // The parent node must actually accept this kind of child.
- if (testOnly) {
- return true;
- }
- xmlGrandParent.insertBefore(
- xmlParent.removeChild(xmlNode),
- xmlParent.getNextSibling());
- outSelectXmlNode[0] = xmlNode;
- }
- }
-
- return false;
- }
-
- //---------------------
-
- /**
- * Adds a new element of the given descriptor's type to the given UI parent node.
- *
- * This actually creates the corresponding XML node in the XML model, which in turn
- * will refresh the current tree view.
- *
- * @param uiParent An existing UI node or null to add to the tree root
- * @param uiSibling An existing UI node to insert right before. Can be null.
- * @param descriptor The descriptor of the element to add
- * @param updateLayout True if layout attributes should be set
- * @return The {@link UiElementNode} that has been added to the UI tree.
- */
- private UiElementNode addNewTreeElement(UiElementNode uiParent,
- UiElementNode uiSibling,
- ElementDescriptor descriptor,
- final boolean updateLayout) {
- commitPendingXmlChanges();
-
- List<UiElementNode> uiChildren = uiParent.getUiChildren();
- int n = uiChildren.size();
-
- // The default is to append at the end of the list.
- int index = n;
-
- if (uiSibling != null) {
- // Try to find the requested sibling.
- index = uiChildren.indexOf(uiSibling);
- if (index < 0) {
- // This sibling didn't exist. Should not happen but compensate
- // by simply adding to the end of the list.
- uiSibling = null;
- index = n;
- }
- }
-
- if (uiSibling == null) {
- // If we don't require any specific position, make sure to insert before the
- // first mandatory_last descriptor's position, if any.
-
- for (int i = 0; i < n; i++) {
- UiElementNode uiChild = uiChildren.get(i);
- if (uiChild.getDescriptor().getMandatory() == Mandatory.MANDATORY_LAST) {
- index = i;
- break;
- }
- }
- }
-
- final UiElementNode uiNew = uiParent.insertNewUiChild(index, descriptor);
- UiElementNode rootNode = getRootNode();
-
- rootNode.getEditor().wrapEditXmlModel(new Runnable() {
- @Override
- public void run() {
- DescriptorsUtils.setDefaultLayoutAttributes(uiNew, updateLayout);
- uiNew.createXmlNode();
- }
- });
- return uiNew;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/UiElementDetail.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/UiElementDetail.java
deleted file mode 100644
index 2aa56a826..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/UiElementDetail.java
+++ /dev/null
@@ -1,494 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.ui.tree;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.SeparatorAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.XmlnsAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.ui.SectionHelper;
-import com.android.ide.eclipse.adt.internal.editors.ui.SectionHelper.ManifestSectionPart;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.IUiUpdateListener;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ITreeSelection;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.forms.IDetailsPage;
-import org.eclipse.ui.forms.IFormPart;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.events.ExpansionEvent;
-import org.eclipse.ui.forms.events.IExpansionListener;
-import org.eclipse.ui.forms.widgets.FormText;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.Section;
-import org.eclipse.ui.forms.widgets.SharedScrolledComposite;
-import org.eclipse.ui.forms.widgets.TableWrapData;
-import org.eclipse.ui.forms.widgets.TableWrapLayout;
-
-import java.util.Collection;
-import java.util.HashSet;
-
-/**
- * Details page for the {@link UiElementNode} nodes in the tree view.
- * <p/>
- * See IDetailsBase for more details.
- */
-class UiElementDetail implements IDetailsPage {
-
- /** The master-detail part, composed of a main tree and an auxiliary detail part */
- private ManifestSectionPart mMasterPart;
-
- private Section mMasterSection;
- private UiElementNode mCurrentUiElementNode;
- private Composite mCurrentTable;
- private boolean mIsDirty;
-
- private IManagedForm mManagedForm;
-
- private final UiTreeBlock mTree;
-
- public UiElementDetail(UiTreeBlock tree) {
- mTree = tree;
- mMasterPart = mTree.getMasterPart();
- mManagedForm = mMasterPart.getManagedForm();
- }
-
- /* (non-java doc)
- * Initializes the part.
- */
- @Override
- public void initialize(IManagedForm form) {
- mManagedForm = form;
- }
-
- /* (non-java doc)
- * Creates the contents of the page in the provided parent.
- */
- @Override
- public void createContents(Composite parent) {
- mMasterSection = createMasterSection(parent);
- }
-
- /* (non-java doc)
- * Called when the provided part has changed selection state.
- * <p/>
- * Only reply when our master part originates the selection.
- */
- @Override
- public void selectionChanged(IFormPart part, ISelection selection) {
- if (part == mMasterPart &&
- !selection.isEmpty() &&
- selection instanceof ITreeSelection) {
- ITreeSelection tree_selection = (ITreeSelection) selection;
-
- Object first = tree_selection.getFirstElement();
- if (first instanceof UiElementNode) {
- UiElementNode ui_node = (UiElementNode) first;
- createUiAttributeControls(mManagedForm, ui_node);
- }
- }
- }
-
- /* (non-java doc)
- * Instructs it to commit the new (modified) data back into the model.
- */
- @Override
- public void commit(boolean onSave) {
-
- mTree.getEditor().wrapEditXmlModel(new Runnable() {
- @Override
- public void run() {
- try {
- if (mCurrentUiElementNode != null) {
- mCurrentUiElementNode.commit();
- }
-
- // Finally reset the dirty flag if everything was saved properly
- mIsDirty = false;
- } catch (Exception e) {
- AdtPlugin.log(e, "Detail node failed to commit XML attribute!"); //$NON-NLS-1$
- }
- }
- });
- }
-
- @Override
- public void dispose() {
- // pass
- }
-
-
- /* (non-java doc)
- * Returns true if the part has been modified with respect to the data
- * loaded from the model.
- */
- @Override
- public boolean isDirty() {
- if (mCurrentUiElementNode != null && mCurrentUiElementNode.isDirty()) {
- markDirty();
- }
- return mIsDirty;
- }
-
- @Override
- public boolean isStale() {
- // pass
- return false;
- }
-
- /**
- * Called by the master part when the tree is refreshed after the framework resources
- * have been reloaded.
- */
- @Override
- public void refresh() {
- if (mCurrentTable != null) {
- mCurrentTable.dispose();
- mCurrentTable = null;
- }
- mCurrentUiElementNode = null;
- mMasterSection.getParent().pack(true /* changed */);
- }
-
- @Override
- public void setFocus() {
- // pass
- }
-
- @Override
- public boolean setFormInput(Object input) {
- // pass
- return false;
- }
-
- /**
- * Creates a TableWrapLayout in the DetailsPage, which in turns contains a Section.
- *
- * All the UI should be created in a layout which parent is the mSection itself.
- * The hierarchy is:
- * <pre>
- * DetailPage
- * + TableWrapLayout
- * + Section (with title/description && fill_grab horizontal)
- * + TableWrapLayout [*]
- * + Labels/Forms/etc... [*]
- * </pre>
- * Both items marked with [*] are created by the derived classes to fit their needs.
- *
- * @param parent Parent of the mSection (from createContents)
- * @return The new Section
- */
- private Section createMasterSection(Composite parent) {
- TableWrapLayout layout = new TableWrapLayout();
- layout.topMargin = 0;
- parent.setLayout(layout);
-
- FormToolkit toolkit = mManagedForm.getToolkit();
- Section section = toolkit.createSection(parent, Section.TITLE_BAR);
- section.setLayoutData(new TableWrapData(TableWrapData.FILL_GRAB, TableWrapData.TOP));
- return section;
- }
-
- /**
- * Create the ui attribute controls to edit the attributes for the given
- * ElementDescriptor.
- * <p/>
- * This is called by the constructor.
- * Derived classes can override this if necessary.
- *
- * @param managedForm The managed form
- */
- private void createUiAttributeControls(
- final IManagedForm managedForm,
- final UiElementNode ui_node) {
-
- final ElementDescriptor elem_desc = ui_node.getDescriptor();
- mMasterSection.setText(String.format("Attributes for %1$s", ui_node.getShortDescription()));
-
- if (mCurrentUiElementNode != ui_node) {
- // Before changing the table, commit all dirty state.
- if (mIsDirty) {
- commit(false);
- }
- if (mCurrentTable != null) {
- mCurrentTable.dispose();
- mCurrentTable = null;
- }
-
- // To iterate over all attributes, we use the {@link ElementDescriptor} instead
- // of the {@link UiElementNode} because the attributes order is guaranteed in the
- // descriptor but not in the node itself.
- AttributeDescriptor[] attr_desc_list = ui_node.getAttributeDescriptors();
-
- // If the attribute list contains at least one SeparatorAttributeDescriptor,
- // sub-sections will be used. This needs to be known early as it influences the
- // creation of the master table.
- boolean useSubsections = false;
- for (AttributeDescriptor attr_desc : attr_desc_list) {
- if (attr_desc instanceof SeparatorAttributeDescriptor) {
- // Sub-sections will be used. The default sections should no longer be
- useSubsections = true;
- break;
- }
- }
-
- FormToolkit toolkit = managedForm.getToolkit();
- Composite masterTable = SectionHelper.createTableLayout(mMasterSection,
- toolkit, useSubsections ? 1 : 2 /* numColumns */);
- mCurrentTable = masterTable;
-
- mCurrentUiElementNode = ui_node;
-
- if (elem_desc.getTooltip() != null) {
- String tooltip;
- if (Sdk.getCurrent() != null &&
- Sdk.getCurrent().getDocumentationBaseUrl() != null) {
- tooltip = DescriptorsUtils.formatFormText(elem_desc.getTooltip(),
- elem_desc,
- Sdk.getCurrent().getDocumentationBaseUrl());
- } else {
- tooltip = elem_desc.getTooltip();
- }
-
- try {
- FormText text = SectionHelper.createFormText(masterTable, toolkit,
- true /* isHtml */, tooltip, true /* setupLayoutData */);
- text.addHyperlinkListener(mTree.getEditor().createHyperlinkListener());
- Image icon = elem_desc.getCustomizedIcon();
- if (icon != null) {
- text.setImage(DescriptorsUtils.IMAGE_KEY, icon);
- }
- } catch(Exception e) {
- // The FormText parser is really really basic and will fail as soon as the
- // HTML javadoc is ever so slightly malformatted.
- AdtPlugin.log(e,
- "Malformed javadoc, rejected by FormText for node %1$s: '%2$s'", //$NON-NLS-1$
- ui_node.getDescriptor().getXmlName(),
- tooltip);
-
- // Fallback to a pure text tooltip, no fancy HTML
- tooltip = DescriptorsUtils.formatTooltip(elem_desc.getTooltip());
- SectionHelper.createLabel(masterTable, toolkit, tooltip, tooltip);
- }
- }
-
- Composite table = useSubsections ? null : masterTable;
-
- for (AttributeDescriptor attr_desc : attr_desc_list) {
- if (attr_desc instanceof XmlnsAttributeDescriptor) {
- // Do not show hidden attributes
- continue;
- } else if (table == null || attr_desc instanceof SeparatorAttributeDescriptor) {
- String title = null;
- if (attr_desc instanceof SeparatorAttributeDescriptor) {
- // xmlName is actually the label of the separator
- title = attr_desc.getXmlLocalName();
- } else {
- title = String.format("Attributes from %1$s", elem_desc.getUiName());
- }
-
- table = createSubSectionTable(toolkit, masterTable, title);
- if (attr_desc instanceof SeparatorAttributeDescriptor) {
- continue;
- }
- }
-
- UiAttributeNode ui_attr = ui_node.findUiAttribute(attr_desc);
-
- if (ui_attr != null) {
- ui_attr.createUiControl(table, managedForm);
-
- if (ui_attr.getCurrentValue() != null &&
- ui_attr.getCurrentValue().length() > 0) {
- ((Section) table.getParent()).setExpanded(true);
- }
- } else {
- // The XML has an extra unknown attribute.
- // This is not expected to happen so it is ignored.
- AdtPlugin.log(IStatus.INFO,
- "Attribute %1$s not declared in node %2$s, ignored.", //$NON-NLS-1$
- attr_desc.getXmlLocalName(),
- ui_node.getDescriptor().getXmlName());
- }
- }
-
- // Create a sub-section for the unknown attributes.
- // It is initially hidden till there are some attributes to show here.
- final Composite unknownTable = createSubSectionTable(toolkit, masterTable,
- "Unknown XML Attributes");
- unknownTable.getParent().setVisible(false); // set section to not visible
- final HashSet<UiAttributeNode> reference = new HashSet<UiAttributeNode>();
-
- final IUiUpdateListener updateListener = new IUiUpdateListener() {
- @Override
- public void uiElementNodeUpdated(UiElementNode uiNode, UiUpdateState state) {
- if (state == UiUpdateState.ATTR_UPDATED) {
- updateUnknownAttributesSection(uiNode, unknownTable, managedForm,
- reference);
- }
- }
- };
- ui_node.addUpdateListener(updateListener);
-
- // remove the listener when the UI is disposed
- unknownTable.addDisposeListener(new DisposeListener() {
- @Override
- public void widgetDisposed(DisposeEvent e) {
- ui_node.removeUpdateListener(updateListener);
- }
- });
-
- updateUnknownAttributesSection(ui_node, unknownTable, managedForm, reference);
-
- mMasterSection.getParent().pack(true /* changed */);
- }
- }
-
- /**
- * Create a sub Section and its embedding wrapper table with 2 columns.
- * @return The table, child of a new section.
- */
- private Composite createSubSectionTable(FormToolkit toolkit,
- Composite masterTable, String title) {
-
- // The Section composite seems to ignore colspan when assigned a TableWrapData so
- // if the parent is a table with more than one column an extra table with one column
- // is inserted to respect colspan.
- int parentNumCol = ((TableWrapLayout) masterTable.getLayout()).numColumns;
- if (parentNumCol > 1) {
- masterTable = SectionHelper.createTableLayout(masterTable, toolkit, 1);
- TableWrapData twd = new TableWrapData(TableWrapData.FILL_GRAB);
- twd.maxWidth = AndroidXmlEditor.TEXT_WIDTH_HINT;
- twd.colspan = parentNumCol;
- masterTable.setLayoutData(twd);
- }
-
- Composite table;
- Section section = toolkit.createSection(masterTable,
- Section.TITLE_BAR | Section.TWISTIE);
-
- // Add an expansion listener that will trigger a reflow on the parent
- // ScrolledPageBook (which is actually a SharedScrolledComposite). This will
- // recompute the correct size and adjust the scrollbar as needed.
- section.addExpansionListener(new IExpansionListener() {
- @Override
- public void expansionStateChanged(ExpansionEvent e) {
- reflowMasterSection();
- }
-
- @Override
- public void expansionStateChanging(ExpansionEvent e) {
- // pass
- }
- });
-
- section.setText(title);
- section.setLayoutData(new TableWrapData(TableWrapData.FILL_GRAB,
- TableWrapData.TOP));
- table = SectionHelper.createTableLayout(section, toolkit, 2 /* numColumns */);
- return table;
- }
-
- /**
- * Reflow the parent ScrolledPageBook (which is actually a SharedScrolledComposite).
- * This will recompute the correct size and adjust the scrollbar as needed.
- */
- private void reflowMasterSection() {
- for(Composite c = mMasterSection; c != null; c = c.getParent()) {
- if (c instanceof SharedScrolledComposite) {
- ((SharedScrolledComposite) c).reflow(true /* flushCache */);
- break;
- }
- }
- }
-
- /**
- * Updates the unknown attributes section for the UI Node.
- */
- private void updateUnknownAttributesSection(UiElementNode ui_node,
- final Composite unknownTable, final IManagedForm managedForm,
- HashSet<UiAttributeNode> reference) {
- Collection<UiAttributeNode> ui_attrs = ui_node.getUnknownUiAttributes();
- Section section = ((Section) unknownTable.getParent());
- boolean needs_reflow = false;
-
- // The table was created hidden, show it if there are unknown attributes now
- if (ui_attrs.size() > 0 && !section.isVisible()) {
- section.setVisible(true);
- needs_reflow = true;
- }
-
- // Compare the new attribute set with the old "reference" one
- boolean has_differences = ui_attrs.size() != reference.size();
- if (!has_differences) {
- for (UiAttributeNode ui_attr : ui_attrs) {
- if (!reference.contains(ui_attr)) {
- has_differences = true;
- break;
- }
- }
- }
-
- if (has_differences) {
- needs_reflow = true;
- reference.clear();
-
- // Remove all children of the table
- for (Control c : unknownTable.getChildren()) {
- c.dispose();
- }
-
- // Recreate all attributes UI
- for (UiAttributeNode ui_attr : ui_attrs) {
- reference.add(ui_attr);
- ui_attr.createUiControl(unknownTable, managedForm);
-
- if (ui_attr.getCurrentValue() != null && ui_attr.getCurrentValue().length() > 0) {
- section.setExpanded(true);
- }
- }
- }
-
- if (needs_reflow) {
- reflowMasterSection();
- }
- }
-
- /**
- * Marks the part dirty. Called as a result of user interaction with the widgets in the
- * section.
- */
- private void markDirty() {
- if (!mIsDirty) {
- mIsDirty = true;
- mManagedForm.dirtyStateChanged();
- }
- }
-}
-
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/UiModelTreeContentProvider.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/UiModelTreeContentProvider.java
deleted file mode 100644
index 14049cf86..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/UiModelTreeContentProvider.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.ui.tree;
-
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-
-import java.util.ArrayList;
-
-/**
- * UiModelTreeContentProvider is a trivial implementation of {@link ITreeContentProvider}
- * where elements are expected to be instances of {@link UiElementNode}.
- */
-class UiModelTreeContentProvider implements ITreeContentProvider {
-
- /** The descriptor of the elements to be displayed as root in this tree view. All elements
- * of the same type in the root will be displayed. */
- private ElementDescriptor[] mDescriptorFilters;
- /** The uiRootNode of the model. */
- private final UiElementNode mUiRootNode;
-
- public UiModelTreeContentProvider(UiElementNode uiRootNode,
- ElementDescriptor[] descriptorFilters) {
- mUiRootNode = uiRootNode;
- mDescriptorFilters = descriptorFilters;
- }
-
- /* (non-java doc)
- * Returns all the UI node children of the given element or null if not the right kind
- * of object. */
- @Override
- public Object[] getChildren(Object parentElement) {
- if (parentElement instanceof UiElementNode) {
- UiElementNode node = (UiElementNode) parentElement;
- return node.getUiChildren().toArray();
- }
- return null;
- }
-
- /* (non-java doc)
- * Returns the parent of a given UI node or null if it's a root node or it's not the
- * right kind of node. */
- @Override
- public Object getParent(Object element) {
- if (element instanceof UiElementNode) {
- UiElementNode node = (UiElementNode) element;
- return node.getUiParent();
- }
- return null;
- }
-
- /* (non-java doc)
- * Returns true if the UI node has any UI children nodes. */
- @Override
- public boolean hasChildren(Object element) {
- if (element instanceof UiElementNode) {
- UiElementNode node = (UiElementNode) element;
- return node.getUiChildren().size() > 0;
- }
- return false;
- }
-
- /* (non-java doc)
- * Get root elements for the tree. These are all the UI nodes that
- * match the filter descriptor in the current root node.
- * <p/>
- * Although not documented, it seems this method should not return null.
- * At worse, it should return new Object[0].
- * <p/>
- * inputElement is not currently used. The root node and the filter are given
- * by the enclosing class.
- */
- @Override
- public Object[] getElements(Object inputElement) {
- ArrayList<UiElementNode> roots = new ArrayList<UiElementNode>();
- if (mUiRootNode != null) {
- for (UiElementNode ui_node : mUiRootNode.getUiChildren()) {
- if (mDescriptorFilters == null || mDescriptorFilters.length == 0) {
- roots.add(ui_node);
- } else {
- for (ElementDescriptor filter : mDescriptorFilters) {
- if (ui_node.getDescriptor() == filter) {
- roots.add(ui_node);
- }
- }
- }
- }
- }
-
- return roots.toArray();
- }
-
- @Override
- public void dispose() {
- // pass
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- // pass
- }
-}
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/UiModelTreeLabelProvider.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/UiModelTreeLabelProvider.java
deleted file mode 100644
index 337319761..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/UiModelTreeLabelProvider.java
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.ui.tree;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.swt.graphics.Image;
-
-/**
- * UiModelTreeLabelProvider is a trivial implementation of {@link ILabelProvider}
- * where elements are expected to derive from {@link UiElementNode} or
- * from {@link ElementDescriptor}.
- *
- * It is used by both the master tree viewer and by the list in the Add... selection dialog.
- */
-public class UiModelTreeLabelProvider implements ILabelProvider {
-
- public UiModelTreeLabelProvider() {
- }
-
- /**
- * Returns the element's logo with a fallback on the android logo.
- */
- @Override
- public Image getImage(Object element) {
- ElementDescriptor desc = null;
- UiElementNode node = null;
-
- if (element instanceof ElementDescriptor) {
- desc = (ElementDescriptor) element;
- } else if (element instanceof UiElementNode) {
- node = (UiElementNode) element;
- desc = node.getDescriptor();
- }
-
- if (desc != null) {
- Image img = desc.getCustomizedIcon();
- if (img != null) {
- if (node != null && node.hasError()) {
- return IconFactory.getInstance().addErrorIcon(img);
- } else {
- return img;
- }
- }
- }
-
- return AdtPlugin.getAndroidLogo();
- }
-
- /**
- * Uses UiElementNode.shortDescription for the label for this tree item.
- */
- @Override
- public String getText(Object element) {
- if (element instanceof ElementDescriptor) {
- ElementDescriptor desc = (ElementDescriptor) element;
- return desc.getUiName();
- } else if (element instanceof UiElementNode) {
- UiElementNode node = (UiElementNode) element;
- return node.getShortDescription();
- }
- return element.toString();
- }
-
- @Override
- public void addListener(ILabelProviderListener listener) {
- // pass
- }
-
- @Override
- public void dispose() {
- // pass
- }
-
- @Override
- public boolean isLabelProperty(Object element, String property) {
- // pass
- return false;
- }
-
- @Override
- public void removeListener(ILabelProviderListener listener) {
- // pass
- }
-}
-
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/UiTreeBlock.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/UiTreeBlock.java
deleted file mode 100644
index d11b8a4c6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/ui/tree/UiTreeBlock.java
+++ /dev/null
@@ -1,946 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.ui.tree;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.ui.SectionHelper;
-import com.android.ide.eclipse.adt.internal.editors.ui.SectionHelper.ManifestSectionPart;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.IUiUpdateListener;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiDocumentNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk.ITargetChangeListener;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk.TargetChangeListener;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IMenuListener;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.action.ToolBarManager;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ITreeSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.TreePath;
-import org.eclipse.jface.viewers.TreeSelection;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.swt.widgets.ToolBar;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.ui.forms.DetailsPart;
-import org.eclipse.ui.forms.IDetailsPage;
-import org.eclipse.ui.forms.IDetailsPageProvider;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.MasterDetailsBlock;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.Section;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.LinkedList;
-
-/**
- * {@link UiTreeBlock} is a {@link MasterDetailsBlock} which displays a tree view for
- * a specific set of {@link UiElementNode}.
- * <p/>
- * For a given UI element node, the tree view displays all first-level children that
- * match a given type (given by an {@link ElementDescriptor}. All children from these
- * nodes are also displayed.
- * <p/>
- * In the middle next to the tree are some controls to add or delete tree nodes.
- * On the left is a details part that displays all the visible UI attributes for a given
- * selected UI element node.
- */
-public final class UiTreeBlock extends MasterDetailsBlock implements ICommitXml {
-
- /** Height hint for the tree view. Helps the grid layout resize properly on smaller screens. */
- private static final int TREE_HEIGHT_HINT = 50;
-
- /** Container editor */
- AndroidXmlEditor mEditor;
- /** The root {@link UiElementNode} which contains all the elements that are to be
- * manipulated by this tree view. In general this is the manifest UI node. */
- private UiElementNode mUiRootNode;
- /** The descriptor of the elements to be displayed as root in this tree view. All elements
- * of the same type in the root will be displayed. Can be null or empty to mean everything
- * can be displayed. */
- private ElementDescriptor[] mDescriptorFilters;
- /** The title for the master-detail part (displayed on the top "tab" on top of the tree) */
- private String mTitle;
- /** The description for the master-detail part (displayed on top of the tree view) */
- private String mDescription;
- /** The master-detail part, composed of a main tree and an auxiliary detail part */
- private ManifestSectionPart mMasterPart;
- /** The tree viewer in the master-detail part */
- private TreeViewer mTreeViewer;
- /** The "add" button for the tree view */
- private Button mAddButton;
- /** The "remove" button for the tree view */
- private Button mRemoveButton;
- /** The "up" button for the tree view */
- private Button mUpButton;
- /** The "down" button for the tree view */
- private Button mDownButton;
- /** The Managed Form used to create the master part */
- private IManagedForm mManagedForm;
- /** Reference to the details part of the tree master block. */
- private DetailsPart mDetailsPart;
- /** Reference to the clipboard for copy-paste */
- private Clipboard mClipboard;
- /** Listener to refresh the tree viewer when the parent's node has been updated */
- private IUiUpdateListener mUiRefreshListener;
- /** Listener to enable/disable the UI based on the application node's presence */
- private IUiUpdateListener mUiEnableListener;
- /** An adapter/wrapper to use the add/remove/up/down tree edit actions. */
- private UiTreeActions mUiTreeActions;
- /**
- * True if the root node can be created on-demand (i.e. as needed as
- * soon as children exist). False if an external entity controls the existence of the
- * root node. In practise, this is false for the manifest application page (the actual
- * "application" node is managed by the ApplicationToggle part) whereas it is true
- * for all other tree pages.
- */
- private final boolean mAutoCreateRoot;
-
-
- /**
- * Creates a new {@link MasterDetailsBlock} that will display all UI nodes matching the
- * given filter in the given root node.
- *
- * @param editor The parent manifest editor.
- * @param uiRootNode The root {@link UiElementNode} which contains all the elements that are
- * to be manipulated by this tree view. In general this is the manifest UI node or the
- * application UI node. This cannot be null.
- * @param autoCreateRoot True if the root node can be created on-demand (i.e. as needed as
- * soon as children exist). False if an external entity controls the existence of the
- * root node. In practise, this is false for the manifest application page (the actual
- * "application" node is managed by the ApplicationToggle part) whereas it is true
- * for all other tree pages.
- * @param descriptorFilters A list of descriptors of the elements to be displayed as root in
- * this tree view. Use null or an empty list to accept any kind of node.
- * @param title Title for the section
- * @param description Description for the section
- */
- public UiTreeBlock(AndroidXmlEditor editor,
- UiElementNode uiRootNode,
- boolean autoCreateRoot,
- ElementDescriptor[] descriptorFilters,
- String title,
- String description) {
- mEditor = editor;
- mUiRootNode = uiRootNode;
- mAutoCreateRoot = autoCreateRoot;
- mDescriptorFilters = descriptorFilters;
- mTitle = title;
- mDescription = description;
- }
-
- /** @returns The container editor */
- AndroidXmlEditor getEditor() {
- return mEditor;
- }
-
- /** @returns The reference to the clipboard for copy-paste */
- Clipboard getClipboard() {
- return mClipboard;
- }
-
- /** @returns The master-detail part, composed of a main tree and an auxiliary detail part */
- ManifestSectionPart getMasterPart() {
- return mMasterPart;
- }
-
- /**
- * Returns the {@link UiElementNode} for the current model.
- * <p/>
- * This is used by the content provider attached to {@link #mTreeViewer} since
- * the uiRootNode changes after each call to
- * {@link #changeRootAndDescriptors(UiElementNode, ElementDescriptor[], boolean)}.
- */
- public UiElementNode getRootNode() {
- return mUiRootNode;
- }
-
- @Override
- protected void createMasterPart(final IManagedForm managedForm, Composite parent) {
- FormToolkit toolkit = managedForm.getToolkit();
-
- mManagedForm = managedForm;
- mMasterPart = new ManifestSectionPart(parent, toolkit);
- Section section = mMasterPart.getSection();
- section.setText(mTitle);
- section.setDescription(mDescription);
- section.setLayout(new GridLayout());
- section.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- Composite grid = SectionHelper.createGridLayout(section, toolkit, 2);
-
- Tree tree = createTreeViewer(toolkit, grid, managedForm);
- createButtons(toolkit, grid);
- createTreeContextMenu(tree);
- createSectionActions(section, toolkit);
- }
-
- private void createSectionActions(Section section, FormToolkit toolkit) {
- ToolBarManager manager = new ToolBarManager(SWT.FLAT);
- manager.removeAll();
-
- ToolBar toolbar = manager.createControl(section);
- section.setTextClient(toolbar);
-
- ElementDescriptor[] descs = mDescriptorFilters;
- if (descs == null && mUiRootNode != null) {
- descs = mUiRootNode.getDescriptor().getChildren();
- }
-
- if (descs != null && descs.length > 1) {
- for (ElementDescriptor desc : descs) {
- manager.add(new DescriptorFilterAction(desc));
- }
- }
-
- manager.add(new TreeSortAction());
-
- manager.update(true /*force*/);
- }
-
- /**
- * Creates the tree and its viewer
- * @return The tree control
- */
- private Tree createTreeViewer(FormToolkit toolkit, Composite grid,
- final IManagedForm managedForm) {
- // Note: we *could* use a FilteredTree instead of the Tree+TreeViewer here.
- // However the class must be adapted to create an adapted toolkit tree.
- final Tree tree = toolkit.createTree(grid, SWT.MULTI);
- GridData gd = new GridData(GridData.FILL_BOTH);
- gd.widthHint = AndroidXmlEditor.TEXT_WIDTH_HINT;
- gd.heightHint = TREE_HEIGHT_HINT;
- tree.setLayoutData(gd);
-
- mTreeViewer = new TreeViewer(tree);
- mTreeViewer.setContentProvider(new UiModelTreeContentProvider(mUiRootNode, mDescriptorFilters));
- mTreeViewer.setLabelProvider(new UiModelTreeLabelProvider());
- mTreeViewer.setInput("unused"); //$NON-NLS-1$
-
- // Create a listener that reacts to selections on the tree viewer.
- // When a selection is made, ask the managed form to propagate an event to
- // all parts in the managed form.
- // This is picked up by UiElementDetail.selectionChanged().
- mTreeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- managedForm.fireSelectionChanged(mMasterPart, event.getSelection());
- adjustTreeButtons(event.getSelection());
- }
- });
-
- // Create three listeners:
- // - One to refresh the tree viewer when the parent's node has been updated
- // - One to refresh the tree viewer when the framework resources have changed
- // - One to enable/disable the UI based on the application node's presence.
- mUiRefreshListener = new IUiUpdateListener() {
- @Override
- public void uiElementNodeUpdated(UiElementNode ui_node, UiUpdateState state) {
- mTreeViewer.refresh();
- }
- };
-
- mUiEnableListener = new IUiUpdateListener() {
- @Override
- public void uiElementNodeUpdated(UiElementNode ui_node, UiUpdateState state) {
- // The UiElementNode for the application XML node always exists, even
- // if there is no corresponding XML node in the XML file.
- //
- // Normally, we enable the UI here if the XML node is not null.
- //
- // However if mAutoCreateRoot is true, the root node will be created on-demand
- // so the tree/block is always enabled.
- boolean exists = mAutoCreateRoot || (ui_node.getXmlNode() != null);
- if (mMasterPart != null) {
- Section section = mMasterPart.getSection();
- if (section.getEnabled() != exists) {
- section.setEnabled(exists);
- for (Control c : section.getChildren()) {
- c.setEnabled(exists);
- }
- }
- }
- }
- };
-
- /** Listener to update the root node if the target of the file is changed because of a
- * SDK location change or a project target change */
- final ITargetChangeListener targetListener = new TargetChangeListener() {
- @Override
- public IProject getProject() {
- if (mEditor != null) {
- return mEditor.getProject();
- }
-
- return null;
- }
-
- @Override
- public void reload() {
- // If a details part has been created, we need to "refresh" it too.
- if (mDetailsPart != null) {
- // The details part does not directly expose access to its internal
- // page book. Instead it is possible to resize the page book to 0 and then
- // back to its original value, which has the side effect of removing all
- // existing cached pages.
- int limit = mDetailsPart.getPageLimit();
- mDetailsPart.setPageLimit(0);
- mDetailsPart.setPageLimit(limit);
- }
- // Refresh the tree, preserving the selection if possible.
- mTreeViewer.refresh();
- }
- };
-
- // Setup the listeners
- changeRootAndDescriptors(mUiRootNode, mDescriptorFilters, false /* refresh */);
-
- // Listen on resource framework changes to refresh the tree
- AdtPlugin.getDefault().addTargetListener(targetListener);
-
- // Remove listeners when the tree widget gets disposed.
- tree.addDisposeListener(new DisposeListener() {
- @Override
- public void widgetDisposed(DisposeEvent e) {
- if (mUiRootNode != null) {
- UiElementNode node = mUiRootNode.getUiParent() != null ?
- mUiRootNode.getUiParent() :
- mUiRootNode;
-
- if (node != null) {
- node.removeUpdateListener(mUiRefreshListener);
- }
- mUiRootNode.removeUpdateListener(mUiEnableListener);
- }
-
- AdtPlugin.getDefault().removeTargetListener(targetListener);
- if (mClipboard != null) {
- mClipboard.dispose();
- mClipboard = null;
- }
- }
- });
-
- // Get a new clipboard reference. It is disposed when the tree is disposed.
- mClipboard = new Clipboard(tree.getDisplay());
-
- return tree;
- }
-
- /**
- * Changes the UI root node and the descriptor filters of the tree.
- * <p/>
- * This removes the listeners attached to the old root node and reattaches them to the
- * new one.
- *
- * @param uiRootNode The root {@link UiElementNode} which contains all the elements that are
- * to be manipulated by this tree view. In general this is the manifest UI node or the
- * application UI node. This cannot be null.
- * @param descriptorFilters A list of descriptors of the elements to be displayed as root in
- * this tree view. Use null or an empty list to accept any kind of node.
- * @param forceRefresh If tree, forces the tree to refresh
- */
- public void changeRootAndDescriptors(UiElementNode uiRootNode,
- ElementDescriptor[] descriptorFilters, boolean forceRefresh) {
- UiElementNode node;
-
- // Remove previous listeners if any
- if (mUiRootNode != null) {
- node = mUiRootNode.getUiParent() != null ? mUiRootNode.getUiParent() : mUiRootNode;
- node.removeUpdateListener(mUiRefreshListener);
- mUiRootNode.removeUpdateListener(mUiEnableListener);
- }
-
- mUiRootNode = uiRootNode;
- mDescriptorFilters = descriptorFilters;
-
- mTreeViewer.setContentProvider(
- new UiModelTreeContentProvider(mUiRootNode, mDescriptorFilters));
-
- // Listen on structural changes on the root node of the tree
- // If the node has a parent, listen on the parent instead.
- if (mUiRootNode != null) {
- node = mUiRootNode.getUiParent() != null ? mUiRootNode.getUiParent() : mUiRootNode;
-
- if (node != null) {
- node.addUpdateListener(mUiRefreshListener);
- }
-
- // Use the root node to listen to its presence.
- mUiRootNode.addUpdateListener(mUiEnableListener);
-
- // Initialize the enabled/disabled state
- mUiEnableListener.uiElementNodeUpdated(mUiRootNode, null /* state, not used */);
- }
-
- if (forceRefresh) {
- mTreeViewer.refresh();
- }
-
- createSectionActions(mMasterPart.getSection(), mManagedForm.getToolkit());
- }
-
- /**
- * Creates the buttons next to the tree.
- */
- private void createButtons(FormToolkit toolkit, Composite grid) {
-
- mUiTreeActions = new UiTreeActions();
-
- Composite button_grid = SectionHelper.createGridLayout(grid, toolkit, 1);
- button_grid.setLayoutData(new GridData(GridData.VERTICAL_ALIGN_BEGINNING));
- mAddButton = toolkit.createButton(button_grid, "Add...", SWT.PUSH);
- SectionHelper.addControlTooltip(mAddButton, "Adds a new element.");
- mAddButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL |
- GridData.VERTICAL_ALIGN_BEGINNING));
-
- mAddButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- super.widgetSelected(e);
- doTreeAdd();
- }
- });
-
- mRemoveButton = toolkit.createButton(button_grid, "Remove...", SWT.PUSH);
- SectionHelper.addControlTooltip(mRemoveButton, "Removes an existing selected element.");
- mRemoveButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- mRemoveButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- super.widgetSelected(e);
- doTreeRemove();
- }
- });
-
- mUpButton = toolkit.createButton(button_grid, "Up", SWT.PUSH);
- SectionHelper.addControlTooltip(mRemoveButton, "Moves the selected element up.");
- mUpButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- mUpButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- super.widgetSelected(e);
- doTreeUp();
- }
- });
-
- mDownButton = toolkit.createButton(button_grid, "Down", SWT.PUSH);
- SectionHelper.addControlTooltip(mRemoveButton, "Moves the selected element down.");
- mDownButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- mDownButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- super.widgetSelected(e);
- doTreeDown();
- }
- });
-
- adjustTreeButtons(TreeSelection.EMPTY);
- }
-
- private void createTreeContextMenu(Tree tree) {
- MenuManager menuManager = new MenuManager();
- menuManager.setRemoveAllWhenShown(true);
- menuManager.addMenuListener(new IMenuListener() {
- /**
- * The menu is about to be shown. The menu manager has already been
- * requested to remove any existing menu item. This method gets the
- * tree selection and if it is of the appropriate type it re-creates
- * the necessary actions.
- */
- @Override
- public void menuAboutToShow(IMenuManager manager) {
- ISelection selection = mTreeViewer.getSelection();
- if (!selection.isEmpty() && selection instanceof ITreeSelection) {
- ArrayList<UiElementNode> selected = filterSelection((ITreeSelection) selection);
- doCreateMenuAction(manager, selected);
- return;
- }
- doCreateMenuAction(manager, null /* ui_node */);
- }
- });
- Menu contextMenu = menuManager.createContextMenu(tree);
- tree.setMenu(contextMenu);
- }
-
- /**
- * Adds the menu actions to the context menu when the given UI node is selected in
- * the tree view.
- *
- * @param manager The context menu manager
- * @param selected The UI nodes selected in the tree. Can be null, in which case the root
- * is to be modified.
- */
- private void doCreateMenuAction(IMenuManager manager, ArrayList<UiElementNode> selected) {
- if (selected != null) {
- boolean hasXml = false;
- for (UiElementNode uiNode : selected) {
- if (uiNode.getXmlNode() != null) {
- hasXml = true;
- break;
- }
- }
-
- if (hasXml) {
- manager.add(new CopyCutAction(getEditor(), getClipboard(),
- null, selected, true /* cut */));
- manager.add(new CopyCutAction(getEditor(), getClipboard(),
- null, selected, false /* cut */));
-
- // Can't paste with more than one element selected (the selection is the target)
- if (selected.size() <= 1) {
- // Paste is not valid if it would add a second element on a terminal element
- // which parent is a document -- an XML document can only have one child. This
- // means paste is valid if the current UI node can have children or if the
- // parent is not a document.
- UiElementNode ui_root = selected.get(0).getUiRoot();
- if (ui_root.getDescriptor().hasChildren() ||
- !(ui_root.getUiParent() instanceof UiDocumentNode)) {
- manager.add(new PasteAction(getEditor(), getClipboard(), selected.get(0)));
- }
- }
- manager.add(new Separator());
- }
- }
-
- // Append "add" and "remove" actions. They do the same thing as the add/remove
- // buttons on the side.
- IconFactory factory = IconFactory.getInstance();
-
- // "Add" makes sense only if there's 0 or 1 item selected since the
- // one selected item becomes the target.
- if (selected == null || selected.size() <= 1) {
- manager.add(new Action("Add...", factory.getImageDescriptor("add")) { //$NON-NLS-1$
- @Override
- public void run() {
- super.run();
- doTreeAdd();
- }
- });
- }
-
- if (selected != null) {
- if (selected != null) {
- manager.add(new Action("Remove", factory.getImageDescriptor("delete")) { //$NON-NLS-1$
- @Override
- public void run() {
- super.run();
- doTreeRemove();
- }
- });
- }
- manager.add(new Separator());
-
- manager.add(new Action("Up", factory.getImageDescriptor("up")) { //$NON-NLS-1$
- @Override
- public void run() {
- super.run();
- doTreeUp();
- }
- });
- manager.add(new Action("Down", factory.getImageDescriptor("down")) { //$NON-NLS-1$
- @Override
- public void run() {
- super.run();
- doTreeDown();
- }
- });
- }
- }
-
-
- /**
- * This is called by the tree when a selection is made.
- * It enables/disables the buttons associated with the tree depending on the current
- * selection.
- *
- * @param selection The current tree selection (same as mTreeViewer.getSelection())
- */
- private void adjustTreeButtons(ISelection selection) {
- mRemoveButton.setEnabled(!selection.isEmpty() && selection instanceof ITreeSelection);
- mUpButton.setEnabled(canDoTreeUp(selection));
- mDownButton.setEnabled(canDoTreeDown(selection));
- }
-
- /**
- * An adapter/wrapper to use the add/remove/up/down tree edit actions.
- */
- private class UiTreeActions extends UiActions {
- @Override
- protected UiElementNode getRootNode() {
- return mUiRootNode;
- }
-
- @Override
- protected void selectUiNode(UiElementNode uiNodeToSelect) {
- // Select the new item
- if (uiNodeToSelect != null) {
- LinkedList<UiElementNode> segments = new LinkedList<UiElementNode>();
- for (UiElementNode ui_node = uiNodeToSelect; ui_node != mUiRootNode;
- ui_node = ui_node.getUiParent()) {
- segments.add(0, ui_node);
- }
- if (segments.size() > 0) {
- mTreeViewer.setSelection(new TreeSelection(new TreePath(segments.toArray())));
- } else {
- mTreeViewer.setSelection(null);
- }
- }
- }
-
- @Override
- public void commitPendingXmlChanges() {
- commitManagedForm();
- }
- }
-
- /**
- * Filters an ITreeSelection to only keep the {@link UiElementNode}s (in case there's
- * something else in there).
- *
- * @return A new list of {@link UiElementNode} with at least one item or null.
- */
- private ArrayList<UiElementNode> filterSelection(ITreeSelection selection) {
- ArrayList<UiElementNode> selected = new ArrayList<UiElementNode>();
-
- for (Iterator<Object> it = selection.iterator(); it.hasNext(); ) {
- Object selectedObj = it.next();
-
- if (selectedObj instanceof UiElementNode) {
- selected.add((UiElementNode) selectedObj);
- }
- }
-
- return selected.size() > 0 ? selected : null;
- }
-
- /**
- * Called when the "Add..." button next to the tree view is selected.
- *
- * Displays a selection dialog that lets the user select which kind of node
- * to create, depending on the current selection.
- */
- private void doTreeAdd() {
- UiElementNode ui_node = mUiRootNode;
- ISelection selection = mTreeViewer.getSelection();
- if (!selection.isEmpty() && selection instanceof ITreeSelection) {
- ITreeSelection tree_selection = (ITreeSelection) selection;
- Object first = tree_selection.getFirstElement();
- if (first != null && first instanceof UiElementNode) {
- ui_node = (UiElementNode) first;
- }
- }
-
- mUiTreeActions.doAdd(
- ui_node,
- mDescriptorFilters,
- mTreeViewer.getControl().getShell(),
- (ILabelProvider) mTreeViewer.getLabelProvider());
- }
-
- /**
- * Called when the "Remove" button is selected.
- *
- * If the tree has a selection, remove it.
- * This simply deletes the XML node attached to the UI node: when the XML model fires the
- * update event, the tree will get refreshed.
- */
- protected void doTreeRemove() {
- ISelection selection = mTreeViewer.getSelection();
- if (!selection.isEmpty() && selection instanceof ITreeSelection) {
- ArrayList<UiElementNode> selected = filterSelection((ITreeSelection) selection);
- mUiTreeActions.doRemove(selected, mTreeViewer.getControl().getShell());
- }
- }
-
- /**
- * Called when the "Up" button is selected.
- * <p/>
- * If the tree has a selection, move it up, either in the child list or as the last child
- * of the previous parent.
- */
- protected void doTreeUp() {
- ISelection selection = mTreeViewer.getSelection();
- if (!selection.isEmpty() && selection instanceof ITreeSelection) {
- ArrayList<UiElementNode> selected = filterSelection((ITreeSelection) selection);
- mUiTreeActions.doUp(selected, mDescriptorFilters);
- }
- }
-
- /**
- * Checks whether the "up" action can be done on the current selection.
- *
- * @param selection The current tree selection.
- * @return True if all the selected nodes can be moved up.
- */
- protected boolean canDoTreeUp(ISelection selection) {
- if (!selection.isEmpty() && selection instanceof ITreeSelection) {
- ArrayList<UiElementNode> selected = filterSelection((ITreeSelection) selection);
- return mUiTreeActions.canDoUp(selected, mDescriptorFilters);
- }
-
- return false;
- }
-
- /**
- * Called when the "Down" button is selected.
- *
- * If the tree has a selection, move it down, either in the same child list or as the
- * first child of the next parent.
- */
- protected void doTreeDown() {
- ISelection selection = mTreeViewer.getSelection();
- if (!selection.isEmpty() && selection instanceof ITreeSelection) {
- ArrayList<UiElementNode> selected = filterSelection((ITreeSelection) selection);
- mUiTreeActions.doDown(selected, mDescriptorFilters);
- }
- }
-
- /**
- * Checks whether the "down" action can be done on the current selection.
- *
- * @param selection The current tree selection.
- * @return True if all the selected nodes can be moved down.
- */
- protected boolean canDoTreeDown(ISelection selection) {
- if (!selection.isEmpty() && selection instanceof ITreeSelection) {
- ArrayList<UiElementNode> selected = filterSelection((ITreeSelection) selection);
- return mUiTreeActions.canDoDown(selected, mDescriptorFilters);
- }
-
- return false;
- }
-
- /**
- * Commits the current managed form (the one associated with our master part).
- * As a side effect, this will commit the current UiElementDetails page.
- */
- void commitManagedForm() {
- if (mManagedForm != null) {
- mManagedForm.commit(false /* onSave */);
- }
- }
-
- /* Implements ICommitXml for CopyCutAction */
- @Override
- public void commitPendingXmlChanges() {
- commitManagedForm();
- }
-
- @Override
- protected void createToolBarActions(IManagedForm managedForm) {
- // Pass. Not used, toolbar actions are defined by createSectionActions().
- }
-
- @Override
- protected void registerPages(DetailsPart inDetailsPart) {
- // Keep a reference on the details part (the super class doesn't provide a getter
- // for it.)
- mDetailsPart = inDetailsPart;
-
- // The page selection mechanism does not use pages registered by association with
- // a node class. Instead it uses a custom details page provider that provides a
- // new UiElementDetail instance for each node instance. A limit of 5 pages is
- // then set (the value is arbitrary but should be reasonable) for the internal
- // page book.
- inDetailsPart.setPageLimit(5);
-
- final UiTreeBlock tree = this;
-
- inDetailsPart.setPageProvider(new IDetailsPageProvider() {
- @Override
- public IDetailsPage getPage(Object key) {
- if (key instanceof UiElementNode) {
- return new UiElementDetail(tree);
- }
- return null;
- }
-
- @Override
- public Object getPageKey(Object object) {
- return object; // use node object as key
- }
- });
- }
-
- /**
- * An alphabetic sort action for the tree viewer.
- */
- private class TreeSortAction extends Action {
-
- private ViewerComparator mComparator;
-
- public TreeSortAction() {
- super("Sorts elements alphabetically.", AS_CHECK_BOX);
- setImageDescriptor(IconFactory.getInstance().getImageDescriptor("az_sort")); //$NON-NLS-1$
-
- if (mTreeViewer != null) {
- boolean is_sorted = mTreeViewer.getComparator() != null;
- setChecked(is_sorted);
- }
- }
-
- /**
- * Called when the button is selected. Toggles the tree viewer comparator.
- */
- @Override
- public void run() {
- if (mTreeViewer == null) {
- notifyResult(false /*success*/);
- return;
- }
-
- ViewerComparator comp = mTreeViewer.getComparator();
- if (comp != null) {
- // Tree is currently sorted.
- // Save currently comparator and remove it
- mComparator = comp;
- mTreeViewer.setComparator(null);
- } else {
- // Tree is not currently sorted.
- // Reuse or add a new comparator.
- if (mComparator == null) {
- mComparator = new ViewerComparator();
- }
- mTreeViewer.setComparator(mComparator);
- }
-
- notifyResult(true /*success*/);
- }
- }
-
- /**
- * A filter on descriptor for the tree viewer.
- * <p/>
- * The tree viewer will contain many of these actions and only one can be enabled at a
- * given time. When no action is selected, everything is displayed.
- * <p/>
- * Since "radio"-like actions do not allow for unselecting all of them, we manually
- * handle the exclusive radio button-like property: when an action is selected, it manually
- * removes all other actions as needed.
- */
- private class DescriptorFilterAction extends Action {
-
- private final ElementDescriptor mDescriptor;
- private ViewerFilter mFilter;
-
- public DescriptorFilterAction(ElementDescriptor descriptor) {
- super(String.format("Displays only %1$s elements.", descriptor.getUiName()),
- AS_CHECK_BOX);
-
- mDescriptor = descriptor;
- setImageDescriptor(descriptor.getImageDescriptor());
- }
-
- /**
- * Called when the button is selected.
- * <p/>
- * Find any existing {@link DescriptorFilter}s and remove them. Install ours.
- */
- @Override
- public void run() {
- super.run();
-
- if (isChecked()) {
- if (mFilter == null) {
- // create filter when required
- mFilter = new DescriptorFilter(this);
- }
-
- // we add our filter first, otherwise the UI might show the full list
- mTreeViewer.addFilter(mFilter);
-
- // Then remove the any other filters except ours. There should be at most
- // one other filter, since that's how the actions are made to look like
- // exclusive radio buttons.
- for (ViewerFilter filter : mTreeViewer.getFilters()) {
- if (filter instanceof DescriptorFilter && filter != mFilter) {
- DescriptorFilterAction action = ((DescriptorFilter) filter).getAction();
- action.setChecked(false);
- mTreeViewer.removeFilter(filter);
- }
- }
- } else if (mFilter != null){
- mTreeViewer.removeFilter(mFilter);
- }
- }
-
- /**
- * Filters the tree viewer for the given descriptor.
- * <p/>
- * The filter is linked to the action so that an action can iterate through the list
- * of filters and un-select the actions.
- */
- private class DescriptorFilter extends ViewerFilter {
-
- private final DescriptorFilterAction mAction;
-
- public DescriptorFilter(DescriptorFilterAction action) {
- mAction = action;
- }
-
- public DescriptorFilterAction getAction() {
- return mAction;
- }
-
- /**
- * Returns true if an element should be displayed, that if the element or
- * any of its parent matches the requested descriptor.
- */
- @Override
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- while (element instanceof UiElementNode) {
- UiElementNode uiNode = (UiElementNode)element;
- if (uiNode.getDescriptor() == mDescriptor) {
- return true;
- }
- element = uiNode.getUiParent();
- }
- return false;
- }
- }
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/IUiSettableAttributeNode.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/IUiSettableAttributeNode.java
deleted file mode 100644
index dd908ad7b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/IUiSettableAttributeNode.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-
-package com.android.ide.eclipse.adt.internal.editors.uimodel;
-
-/**
- * This interface decoration indicates that a given UiAttributeNode can both
- * set and get its current value.
- */
-public interface IUiSettableAttributeNode {
-
- /** Returns the current value of the node. */
- public String getCurrentValue();
-
- /** Sets the current value of the node. Cannot be null (use an empty string). */
- public void setCurrentValue(String value);
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/IUiUpdateListener.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/IUiUpdateListener.java
deleted file mode 100644
index a4f1f74ea..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/IUiUpdateListener.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.uimodel;
-
-
-/**
- * Listen to update notifications in UI nodes.
- */
-public interface IUiUpdateListener {
-
- /** Update state of the UI node */
- public enum UiUpdateState {
- /** The node's attributes have been updated. They may or may not actually have changed. */
- ATTR_UPDATED,
- /** The node sub-structure (i.e. child nodes) has changed */
- CHILDREN_CHANGED,
- /** The XML counterpart for the UI node has just been created. */
- CREATED,
- /** The XML counterpart for the UI node has just been deleted.
- * Note that mandatory UI nodes are never actually deleted. */
- DELETED
- }
-
- /**
- * Indicates that an UiElementNode has been updated.
- * <p/>
- * This happens when an {@link UiElementNode} is refreshed to match the
- * XML model. The actual UI element node may or may not have changed.
- *
- * @param ui_node The {@link UiElementNode} being updated.
- */
- public void uiElementNodeUpdated(UiElementNode ui_node, UiUpdateState state);
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiAbstractTextAttributeNode.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiAbstractTextAttributeNode.java
deleted file mode 100644
index 4f795904d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiAbstractTextAttributeNode.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.uimodel;
-
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-
-import org.w3c.dom.Node;
-
-/**
- * Represents an XML attribute in that can be modified using a simple text field
- * in the XML editor's user interface.
- * <p/>
- * The XML attribute has no default value. When unset, the text field is blank.
- * When updating the XML, if the field is empty, the attribute will be removed
- * from the XML element.
- * <p/>
- * See {@link UiAttributeNode} for more information.
- */
-public abstract class UiAbstractTextAttributeNode extends UiAttributeNode
- implements IUiSettableAttributeNode {
-
- protected static final String DEFAULT_VALUE = ""; //$NON-NLS-1$
-
- /** Prevent internal listener from firing when internally modifying the text */
- private boolean mInternalTextModification;
- /** Last value read from the XML model. Cannot be null. */
- private String mCurrentValue = DEFAULT_VALUE;
-
- public UiAbstractTextAttributeNode(AttributeDescriptor attributeDescriptor,
- UiElementNode uiParent) {
- super(attributeDescriptor, uiParent);
- }
-
- /** Returns the current value of the node. */
- @Override
- public final String getCurrentValue() {
- return mCurrentValue;
- }
-
- /** Sets the current value of the node. Cannot be null (use an empty string). */
- @Override
- public final void setCurrentValue(String value) {
- mCurrentValue = value;
- }
-
- /** Returns if the attribute node is valid, and its UI has been created. */
- public abstract boolean isValid();
-
- /** Returns the text value present in the UI. */
- public abstract String getTextWidgetValue();
-
- /** Sets the text value to be displayed in the UI. */
- public abstract void setTextWidgetValue(String value);
-
-
- /**
- * Updates the current text field's value when the XML has changed.
- * <p/>
- * The caller doesn't really know if attributes have changed,
- * so it will call this to refresh the attribute anyway. The value
- * is only set if it has changed.
- * <p/>
- * This also resets the "dirty" flag.
- */
- @Override
- public void updateValue(Node xml_attribute_node) {
- mCurrentValue = DEFAULT_VALUE;
- if (xml_attribute_node != null) {
- mCurrentValue = xml_attribute_node.getNodeValue();
- }
-
- if (isValid() && !getTextWidgetValue().equals(mCurrentValue)) {
- try {
- mInternalTextModification = true;
- setTextWidgetValue(mCurrentValue);
- setDirty(false);
- } finally {
- mInternalTextModification = false;
- }
- }
- }
-
- /* (non-java doc)
- * Called by the user interface when the editor is saved or its state changed
- * and the modified attributes must be committed (i.e. written) to the XML model.
- */
- @Override
- public void commit() {
- UiElementNode parent = getUiParent();
- if (parent != null && isValid() && isDirty()) {
- String value = getTextWidgetValue();
- if (parent.commitAttributeToXml(this, value)) {
- mCurrentValue = value;
- setDirty(false);
- }
- }
- }
-
- protected final boolean isInInternalTextModification() {
- return mInternalTextModification;
- }
-
- protected final void setInInternalTextModification(boolean internalTextModification) {
- mInternalTextModification = internalTextModification;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiAttributeNode.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiAttributeNode.java
deleted file mode 100644
index ffe637c5d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiAttributeNode.java
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.uimodel;
-
-import com.android.ide.common.xml.XmlAttributeSortOrder;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.forms.IManagedForm;
-import org.w3c.dom.Node;
-
-/**
- * Represents an XML attribute that can be modified by the XML editor's user interface.
- * <p/>
- * The characteristics of an {@link UiAttributeNode} are declared by a
- * corresponding {@link AttributeDescriptor}.
- * <p/>
- * This is an abstract class. Derived classes must implement the creation of the UI
- * and manage its synchronization with the XML.
- */
-public abstract class UiAttributeNode implements Comparable<UiAttributeNode> {
-
- private AttributeDescriptor mDescriptor;
- private UiElementNode mUiParent;
- private boolean mIsDirty;
- private boolean mHasError;
-
- /** Creates a new {@link UiAttributeNode} linked to a specific {@link AttributeDescriptor}
- * and the corresponding runtime {@link UiElementNode} parent. */
- public UiAttributeNode(AttributeDescriptor attributeDescriptor, UiElementNode uiParent) {
- mDescriptor = attributeDescriptor;
- mUiParent = uiParent;
- }
-
- /** Returns the {@link AttributeDescriptor} specific to this UI attribute node */
- public final AttributeDescriptor getDescriptor() {
- return mDescriptor;
- }
-
- /** Returns the {@link UiElementNode} that owns this {@link UiAttributeNode} */
- public final UiElementNode getUiParent() {
- return mUiParent;
- }
-
- /** Returns the current value of the node. */
- public abstract String getCurrentValue();
-
- /**
- * @return True if the attribute has been changed since it was last loaded
- * from the XML model.
- */
- public final boolean isDirty() {
- return mIsDirty;
- }
-
- /**
- * Sets whether the attribute is dirty and also notifies the editor some part's dirty
- * flag as changed.
- * <p/>
- * Subclasses should set the to true as a result of user interaction with the widgets in
- * the section and then should set to false when the commit() method completed.
- *
- * @param isDirty the new value to set the dirty-flag to
- */
- public void setDirty(boolean isDirty) {
- boolean wasDirty = mIsDirty;
- mIsDirty = isDirty;
- // TODO: for unknown attributes, getParent() != null && getParent().getEditor() != null
- if (wasDirty != isDirty) {
- AndroidXmlEditor editor = getUiParent().getEditor();
- if (editor != null) {
- editor.editorDirtyStateChanged();
- }
- }
- }
-
- /**
- * Sets the error flag value.
- * @param errorFlag the error flag
- */
- public final void setHasError(boolean errorFlag) {
- mHasError = errorFlag;
- }
-
- /**
- * Returns whether this node has errors.
- */
- public final boolean hasError() {
- return mHasError;
- }
-
- /**
- * Called once by the parent user interface to creates the necessary
- * user interface to edit this attribute.
- * <p/>
- * This method can be called more than once in the life cycle of an UI node,
- * typically when the UI is part of a master-detail tree, as pages are swapped.
- *
- * @param parent The composite where to create the user interface.
- * @param managedForm The managed form owning this part.
- */
- public abstract void createUiControl(Composite parent, IManagedForm managedForm);
-
- /**
- * Used to get a list of all possible values for this UI attribute.
- * <p/>
- * This is used, among other things, by the XML Content Assists to complete values
- * for an attribute.
- * <p/>
- * Implementations that do not have any known values should return null.
- *
- * @param prefix An optional prefix string, which is whatever the user has already started
- * typing. Can be null or an empty string. The implementation can use this to filter choices
- * and only return strings that match this prefix. A lazy or default implementation can
- * simply ignore this and return everything.
- * @return A list of possible completion values, and empty array or null.
- */
- public abstract String[] getPossibleValues(String prefix);
-
- /**
- * Called when the XML is being loaded or has changed to
- * update the value held by this user interface attribute node.
- * <p/>
- * The XML Node <em>may</em> be null, which denotes that the attribute is not
- * specified in the XML model. In general, this means the "default" value of the
- * attribute should be used.
- * <p/>
- * The caller doesn't really know if attributes have changed,
- * so it will call this to refresh the attribute anyway. It's up to the
- * UI implementation to minimize refreshes.
- *
- * @param node the node to read the value from
- */
- public abstract void updateValue(Node node);
-
- /**
- * Called by the user interface when the editor is saved or its state changed
- * and the modified attributes must be committed (i.e. written) to the XML model.
- * <p/>
- * Important behaviors:
- * <ul>
- * <li>The caller *must* have called IStructuredModel.aboutToChangeModel before.
- * The implemented methods must assume it is safe to modify the XML model.
- * <li>On success, the implementation *must* call setDirty(false).
- * <li>On failure, the implementation can fail with an exception, which
- * is trapped and logged by the caller, or do nothing, whichever is more
- * appropriate.
- * </ul>
- */
- public abstract void commit();
-
- // ---- Implements Comparable ----
-
- @Override
- public int compareTo(UiAttributeNode o) {
- return XmlAttributeSortOrder.compareAttributes(mDescriptor.getXmlLocalName(),
- o.mDescriptor.getXmlLocalName());
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiDocumentNode.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiDocumentNode.java
deleted file mode 100644
index 1a85ea682..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiDocumentNode.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.uimodel;
-
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DocumentDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.IUiUpdateListener.UiUpdateState;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Represents an XML document node that can be modified by the user interface in the XML editor.
- * <p/>
- * The structure of a given {@link UiDocumentNode} is declared by a corresponding
- * {@link DocumentDescriptor}.
- */
-public class UiDocumentNode extends UiElementNode {
-
- /**
- * Creates a new {@link UiDocumentNode} described by a given {@link DocumentDescriptor}.
- *
- * @param documentDescriptor The {@link DocumentDescriptor} for the XML node. Cannot be null.
- */
- public UiDocumentNode(DocumentDescriptor documentDescriptor) {
- super(documentDescriptor);
- }
-
- /**
- * Computes a short string describing the UI node suitable for tree views.
- * Uses the element's attribute "android:name" if present, or the "android:label" one
- * followed by the element's name.
- *
- * @return A short string describing the UI node suitable for tree views.
- */
- @Override
- public String getShortDescription() {
- return "Document"; //$NON-NLS-1$
- }
-
- /**
- * Computes a "breadcrumb trail" description for this node.
- *
- * @param include_root Whether to include the root (e.g. "Manifest") or not. Has no effect
- * when called on the root node itself.
- * @return The "breadcrumb trail" description for this node.
- */
- @Override
- public String getBreadcrumbTrailDescription(boolean include_root) {
- return "Document"; //$NON-NLS-1$
- }
-
- /**
- * This method throws an exception when attempted to assign a parent, since XML documents
- * cannot have a parent. It is OK to assign null.
- */
- @Override
- protected void setUiParent(UiElementNode parent) {
- if (parent != null) {
- // DEBUG. Change to log warning.
- throw new UnsupportedOperationException("Documents can't have UI parents"); //$NON-NLS-1$
- }
- super.setUiParent(null);
- }
-
- /**
- * Populate this element node with all values from the given XML node.
- *
- * This fails if the given XML node has a different element name -- it won't change the
- * type of this ui node.
- *
- * This method can be both used for populating values the first time and updating values
- * after the XML model changed.
- *
- * @param xml_node The XML node to mirror
- * @return Returns true if the XML structure has changed (nodes added, removed or replaced)
- */
- @Override
- public boolean loadFromXmlNode(Node xml_node) {
- boolean structure_changed = (getXmlDocument() != xml_node);
- setXmlDocument((Document) xml_node);
- structure_changed |= super.loadFromXmlNode(xml_node);
- if (structure_changed) {
- invokeUiUpdateListeners(UiUpdateState.CHILDREN_CHANGED);
- }
- return structure_changed;
- }
-
- /**
- * This method throws an exception if there is no underlying XML document.
- * <p/>
- * XML documents cannot be created per se -- they are a by-product of the StructuredEditor
- * XML parser.
- *
- * @return The current value of getXmlDocument().
- */
- @Override
- public Node createXmlNode() {
- if (getXmlDocument() == null) {
- // By design, a document node cannot be created, it is owned by the XML parser.
- // By "design" this should never happen since the XML parser always creates an XML
- // document container, even for an empty file.
- throw new UnsupportedOperationException("Documents cannot be created"); //$NON-NLS-1$
- }
- return getXmlDocument();
- }
-
- /**
- * This method throws an exception and does not even try to delete the XML document.
- * <p/>
- * XML documents cannot be deleted per se -- they are a by-product of the StructuredEditor
- * XML parser.
- *
- * @return The removed node or null if it didn't exist in the first place.
- */
- @Override
- public Node deleteXmlNode() {
- // DEBUG. Change to log warning.
- throw new UnsupportedOperationException("Documents cannot be deleted"); //$NON-NLS-1$
- }
-
- /**
- * Returns all elements in this document.
- *
- * @param document the document
- * @return all elements in the document
- */
- public static List<UiElementNode> getAllElements(UiDocumentNode document) {
- List<UiElementNode> elements = new ArrayList<UiElementNode>(64);
- for (UiElementNode child : document.getUiChildren()) {
- addElements(child, elements);
- }
- return elements;
- }
-
- private static void addElements(UiElementNode node, List<UiElementNode> elements) {
- elements.add(node);
-
- for (UiElementNode child : node.getUiChildren()) {
- addElements(child, elements);
- }
- }
-}
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiElementNode.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiElementNode.java
deleted file mode 100644
index ed447c634..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiElementNode.java
+++ /dev/null
@@ -1,2160 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.uimodel;
-
-import static com.android.SdkConstants.ANDROID_PKG_PREFIX;
-import static com.android.SdkConstants.ANDROID_SUPPORT_PKG_PREFIX;
-import static com.android.SdkConstants.ATTR_CLASS;
-import static com.android.SdkConstants.ID_PREFIX;
-import static com.android.SdkConstants.NEW_ID_PREFIX;
-
-import com.android.SdkConstants;
-import com.android.annotations.VisibleForTesting;
-import com.android.ide.common.api.IAttributeInfo.Format;
-import com.android.ide.common.resources.platform.AttributeInfo;
-import com.android.ide.common.xml.XmlAttributeSortOrder;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor.Mandatory;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.IUnknownDescriptorProvider;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.SeparatorAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.TextAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.XmlnsAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.CustomViewDescriptorService;
-import com.android.ide.eclipse.adt.internal.editors.manifest.descriptors.AndroidManifestDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.otherxml.descriptors.OtherXmlDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.IUiUpdateListener.UiUpdateState;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.utils.SdkUtils;
-import com.android.utils.XmlUtils;
-
-import org.eclipse.jface.text.TextUtilities;
-import org.eclipse.jface.viewers.StyledString;
-import org.eclipse.ui.views.properties.IPropertyDescriptor;
-import org.eclipse.ui.views.properties.IPropertySource;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.eclipse.wst.xml.core.internal.document.ElementImpl;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.Text;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
-/**
- * Represents an XML node that can be modified by the user interface in the XML editor.
- * <p/>
- * Each tree viewer used in the application page's parts needs to keep a model representing
- * each underlying node in the tree. This interface represents the base type for such a node.
- * <p/>
- * Each node acts as an intermediary model between the actual XML model (the real data support)
- * and the tree viewers or the corresponding page parts.
- * <p/>
- * Element nodes don't contain data per se. Their data is contained in their attributes
- * as well as their children's attributes, see {@link UiAttributeNode}.
- * <p/>
- * The structure of a given {@link UiElementNode} is declared by a corresponding
- * {@link ElementDescriptor}.
- * <p/>
- * The class implements {@link IPropertySource}, in order to fill the Eclipse property tab when
- * an element is selected. The {@link AttributeDescriptor} are used property descriptors.
- */
-@SuppressWarnings("restriction") // XML model
-public class UiElementNode implements IPropertySource {
-
- /** List of prefixes removed from android:id strings when creating short descriptions. */
- private static String[] ID_PREFIXES = {
- "@android:id/", //$NON-NLS-1$
- NEW_ID_PREFIX, ID_PREFIX, "@+", "@" }; //$NON-NLS-1$ //$NON-NLS-2$
-
- /** The element descriptor for the node. Always present, never null. */
- private ElementDescriptor mDescriptor;
- /** The parent element node in the UI model. It is null for a root element or until
- * the node is attached to its parent. */
- private UiElementNode mUiParent;
- /** The {@link AndroidXmlEditor} handling the UI hierarchy. This is defined only for the
- * root node. All children have the value set to null and query their parent. */
- private AndroidXmlEditor mEditor;
- /** The XML {@link Document} model that is being mirror by the UI model. This is defined
- * only for the root node. All children have the value set to null and query their parent. */
- private Document mXmlDocument;
- /** The XML {@link Node} mirror by this UI node. This can be null for mandatory UI node which
- * have no corresponding XML node or for new UI nodes before their XML node is set. */
- private Node mXmlNode;
- /** The list of all UI children nodes. Can be empty but never null. There's one UI children
- * node per existing XML children node. */
- private ArrayList<UiElementNode> mUiChildren;
- /** The list of <em>all</em> UI attributes, as declared in the {@link ElementDescriptor}.
- * The list is always defined and never null. Unlike the UiElementNode children list, this
- * is always defined, even for attributes that do not exist in the XML model - that's because
- * "missing" attributes in the XML model simply mean a default value is used. Also note that
- * the underlying collection is a map, so order is not respected. To get the desired attribute
- * order, iterate through the {@link ElementDescriptor}'s attribute list. */
- private HashMap<AttributeDescriptor, UiAttributeNode> mUiAttributes;
- private HashSet<UiAttributeNode> mUnknownUiAttributes;
- /** A read-only view of the UI children node collection. */
- private List<UiElementNode> mReadOnlyUiChildren;
- /** A read-only view of the UI attributes collection. */
- private Collection<UiAttributeNode> mCachedAllUiAttributes;
- /** A map of hidden attribute descriptors. Key is the XML name. */
- private Map<String, AttributeDescriptor> mCachedHiddenAttributes;
- /** An optional list of {@link IUiUpdateListener}. Most element nodes will not have any
- * listeners attached, so the list is only created on demand and can be null. */
- private List<IUiUpdateListener> mUiUpdateListeners;
- /** A provider that knows how to create {@link ElementDescriptor} from unmapped XML names.
- * The default is to have one that creates new {@link ElementDescriptor}. */
- private IUnknownDescriptorProvider mUnknownDescProvider;
- /** Error Flag */
- private boolean mHasError;
-
- /**
- * Creates a new {@link UiElementNode} described by a given {@link ElementDescriptor}.
- *
- * @param elementDescriptor The {@link ElementDescriptor} for the XML node. Cannot be null.
- */
- public UiElementNode(ElementDescriptor elementDescriptor) {
- mDescriptor = elementDescriptor;
- clearContent();
- }
-
- @Override
- public String toString() {
- return String.format("%s [desc: %s, parent: %s, children: %d]", //$NON-NLS-1$
- this.getClass().getSimpleName(),
- mDescriptor,
- mUiParent != null ? mUiParent.toString() : "none", //$NON-NLS-1$
- mUiChildren != null ? mUiChildren.size() : 0
- );
- }
-
- /**
- * Clears the {@link UiElementNode} by resetting the children list and
- * the {@link UiAttributeNode}s list.
- * Also resets the attached XML node, document, editor if any.
- * <p/>
- * The parent {@link UiElementNode} node is not reset so that it's position
- * in the hierarchy be left intact, if any.
- */
- /* package */ void clearContent() {
- mXmlNode = null;
- mXmlDocument = null;
- mEditor = null;
- clearAttributes();
- mReadOnlyUiChildren = null;
- if (mUiChildren == null) {
- mUiChildren = new ArrayList<UiElementNode>();
- } else {
- // We can't remove mandatory nodes, we just clear them.
- for (int i = mUiChildren.size() - 1; i >= 0; --i) {
- removeUiChildAtIndex(i);
- }
- }
- }
-
- /**
- * Clears the internal list of attributes, the read-only cached version of it
- * and the read-only cached hidden attribute list.
- */
- private void clearAttributes() {
- mUiAttributes = null;
- mCachedAllUiAttributes = null;
- mCachedHiddenAttributes = null;
- mUnknownUiAttributes = new HashSet<UiAttributeNode>();
- }
-
- /**
- * Gets or creates the internal UiAttributes list.
- * <p/>
- * When the descriptor derives from ViewElementDescriptor, this list depends on the
- * current UiParent node.
- *
- * @return A new set of {@link UiAttributeNode} that matches the expected
- * attributes for this node.
- */
- private HashMap<AttributeDescriptor, UiAttributeNode> getInternalUiAttributes() {
- if (mUiAttributes == null) {
- AttributeDescriptor[] attrList = getAttributeDescriptors();
- mUiAttributes = new HashMap<AttributeDescriptor, UiAttributeNode>(attrList.length);
- for (AttributeDescriptor desc : attrList) {
- UiAttributeNode uiNode = desc.createUiNode(this);
- if (uiNode != null) { // Some AttributeDescriptors do not have UI associated
- mUiAttributes.put(desc, uiNode);
- }
- }
- }
- return mUiAttributes;
- }
-
- /**
- * Computes a short string describing the UI node suitable for tree views.
- * Uses the element's attribute "android:name" if present, or the "android:label" one
- * followed by the element's name if not repeated.
- *
- * @return A short string describing the UI node suitable for tree views.
- */
- public String getShortDescription() {
- String name = mDescriptor.getUiName();
- String attr = getDescAttribute();
- if (attr != null) {
- // If the ui name is repeated in the attribute value, don't use it.
- // Typical case is to avoid ".pkg.MyActivity (Activity)".
- if (attr.contains(name)) {
- return attr;
- } else {
- return String.format("%1$s (%2$s)", attr, name);
- }
- }
-
- return name;
- }
-
- /** Returns the key attribute that can be used to describe this node, or null */
- private String getDescAttribute() {
- if (mXmlNode != null && mXmlNode instanceof Element && mXmlNode.hasAttributes()) {
- // Application and Manifest nodes have a special treatment: they are unique nodes
- // so we don't bother trying to differentiate their strings and we fall back to
- // just using the UI name below.
- Element elem = (Element) mXmlNode;
-
- String attr = _Element_getAttributeNS(elem,
- SdkConstants.NS_RESOURCES,
- AndroidManifestDescriptors.ANDROID_NAME_ATTR);
- if (attr == null || attr.length() == 0) {
- attr = _Element_getAttributeNS(elem,
- SdkConstants.NS_RESOURCES,
- AndroidManifestDescriptors.ANDROID_LABEL_ATTR);
- } else if (mXmlNode.getNodeName().equals(SdkConstants.VIEW_FRAGMENT)) {
- attr = attr.substring(attr.lastIndexOf('.') + 1);
- }
- if (attr == null || attr.length() == 0) {
- attr = _Element_getAttributeNS(elem,
- SdkConstants.NS_RESOURCES,
- OtherXmlDescriptors.PREF_KEY_ATTR);
- }
- if (attr == null || attr.length() == 0) {
- attr = _Element_getAttributeNS(elem,
- null, // no namespace
- SdkConstants.ATTR_NAME);
- }
- if (attr == null || attr.length() == 0) {
- attr = _Element_getAttributeNS(elem,
- SdkConstants.NS_RESOURCES,
- SdkConstants.ATTR_ID);
-
- if (attr != null && attr.length() > 0) {
- for (String prefix : ID_PREFIXES) {
- if (attr.startsWith(prefix)) {
- attr = attr.substring(prefix.length());
- break;
- }
- }
- }
- }
- if (attr != null && attr.length() > 0) {
- return attr;
- }
- }
-
- return null;
- }
-
- /**
- * Computes a styled string describing the UI node suitable for tree views.
- * Similar to {@link #getShortDescription()} but styles the Strings.
- *
- * @return A styled string describing the UI node suitable for tree views.
- */
- public StyledString getStyledDescription() {
- String uiName = mDescriptor.getUiName();
-
- // Special case: for <view>, show the class attribute value instead.
- // This is done here rather than in the descriptor since this depends on
- // node instance data.
- if (SdkConstants.VIEW_TAG.equals(uiName) && mXmlNode instanceof Element) {
- Element element = (Element) mXmlNode;
- String cls = element.getAttribute(ATTR_CLASS);
- if (cls != null) {
- uiName = cls.substring(cls.lastIndexOf('.') + 1);
- }
- }
-
- StyledString styledString = new StyledString();
- String attr = getDescAttribute();
- if (attr != null) {
- // Don't append the two when it's a repeat, e.g. Button01 (Button),
- // only when the ui name is not part of the attribute
- if (attr.toLowerCase(Locale.US).indexOf(uiName.toLowerCase(Locale.US)) == -1) {
- styledString.append(attr);
- styledString.append(String.format(" (%1$s)", uiName),
- StyledString.DECORATIONS_STYLER);
- } else {
- styledString.append(attr);
- }
- }
-
- if (styledString.length() == 0) {
- styledString.append(uiName);
- }
-
- return styledString;
- }
-
- /**
- * Retrieves an attribute value by local name and namespace URI.
- * <br>Per [<a href='http://www.w3.org/TR/1999/REC-xml-names-19990114/'>XML Namespaces</a>]
- * , applications must use the value <code>null</code> as the
- * <code>namespaceURI</code> parameter for methods if they wish to have
- * no namespace.
- * <p/>
- * Note: This is a wrapper around {@link Element#getAttributeNS(String, String)}.
- * In some versions of webtools, the getAttributeNS implementation crashes with an NPE.
- * This wrapper will return an empty string instead.
- *
- * @see Element#getAttributeNS(String, String)
- * @see <a href="https://bugs.eclipse.org/bugs/show_bug.cgi?id=318108">https://bugs.eclipse.org/bugs/show_bug.cgi?id=318108</a>
- * @return The result from {@link Element#getAttributeNS(String, String)} or an empty string.
- */
- private String _Element_getAttributeNS(Element element,
- String namespaceURI,
- String localName) {
- try {
- return element.getAttributeNS(namespaceURI, localName);
- } catch (Exception ignore) {
- return "";
- }
- }
-
- /**
- * Computes a "breadcrumb trail" description for this node.
- * It will look something like "Manifest > Application > .myactivity (Activity) > Intent-Filter"
- *
- * @param includeRoot Whether to include the root (e.g. "Manifest") or not. Has no effect
- * when called on the root node itself.
- * @return The "breadcrumb trail" description for this node.
- */
- public String getBreadcrumbTrailDescription(boolean includeRoot) {
- StringBuilder sb = new StringBuilder(getShortDescription());
-
- for (UiElementNode uiNode = getUiParent();
- uiNode != null;
- uiNode = uiNode.getUiParent()) {
- if (!includeRoot && uiNode.getUiParent() == null) {
- break;
- }
- sb.insert(0, String.format("%1$s > ", uiNode.getShortDescription())); //$NON-NLS-1$
- }
-
- return sb.toString();
- }
-
- /**
- * Sets the XML {@link Document}.
- * <p/>
- * The XML {@link Document} is initially null. The XML {@link Document} must be set only on the
- * UI root element node (this method takes care of that.)
- * @param xmlDoc The new XML document to associate this node with.
- */
- public void setXmlDocument(Document xmlDoc) {
- if (mUiParent == null) {
- mXmlDocument = xmlDoc;
- } else {
- mUiParent.setXmlDocument(xmlDoc);
- }
- }
-
- /**
- * Returns the XML {@link Document}.
- * <p/>
- * The value is initially null until the UI node is attached to its UI parent -- the value
- * of the document is then propagated.
- *
- * @return the XML {@link Document} or the parent's XML {@link Document} or null.
- */
- public Document getXmlDocument() {
- if (mXmlDocument != null) {
- return mXmlDocument;
- } else if (mUiParent != null) {
- return mUiParent.getXmlDocument();
- }
- return null;
- }
-
- /**
- * Returns the XML node associated with this UI node.
- * <p/>
- * Some {@link ElementDescriptor} are declared as being "mandatory". This means the
- * corresponding UI node will exist even if there is no corresponding XML node. Such structure
- * is created and enforced by the parent of the tree, not the element themselves. However
- * such nodes will likely not have an XML node associated, so getXmlNode() can return null.
- *
- * @return The associated XML node. Can be null for mandatory nodes.
- */
- public Node getXmlNode() {
- return mXmlNode;
- }
-
- /**
- * Returns the {@link ElementDescriptor} for this node. This is never null.
- * <p/>
- * Do not use this to call getDescriptor().getAttributes(), instead call
- * getAttributeDescriptors() which can be overridden by derived classes.
- * @return The {@link ElementDescriptor} for this node. This is never null.
- */
- public ElementDescriptor getDescriptor() {
- return mDescriptor;
- }
-
- /**
- * Returns the {@link AttributeDescriptor} array for the descriptor of this node.
- * <p/>
- * Use this instead of getDescriptor().getAttributes() -- derived classes can override
- * this to manipulate the attribute descriptor list depending on the current UI node.
- * @return The {@link AttributeDescriptor} array for the descriptor of this node.
- */
- public AttributeDescriptor[] getAttributeDescriptors() {
- return mDescriptor.getAttributes();
- }
-
- /**
- * Returns the hidden {@link AttributeDescriptor} array for the descriptor of this node.
- * This is a subset of the getAttributeDescriptors() list.
- * <p/>
- * Use this instead of getDescriptor().getHiddenAttributes() -- potentially derived classes
- * could override this to manipulate the attribute descriptor list depending on the current
- * UI node. There's no need for it right now so keep it private.
- */
- private Map<String, AttributeDescriptor> getHiddenAttributeDescriptors() {
- if (mCachedHiddenAttributes == null) {
- mCachedHiddenAttributes = new HashMap<String, AttributeDescriptor>();
- for (AttributeDescriptor attrDesc : getAttributeDescriptors()) {
- if (attrDesc instanceof XmlnsAttributeDescriptor) {
- mCachedHiddenAttributes.put(
- ((XmlnsAttributeDescriptor) attrDesc).getXmlNsName(),
- attrDesc);
- }
- }
- }
- return mCachedHiddenAttributes;
- }
-
- /**
- * Sets the parent of this UiElementNode.
- * <p/>
- * The root node has no parent.
- */
- protected void setUiParent(UiElementNode parent) {
- mUiParent = parent;
- // Invalidate the internal UiAttributes list, as it may depend on the actual UiParent.
- clearAttributes();
- }
-
- /**
- * @return The parent {@link UiElementNode} or null if this is the root node.
- */
- public UiElementNode getUiParent() {
- return mUiParent;
- }
-
- /**
- * Returns the root {@link UiElementNode}.
- *
- * @return The root {@link UiElementNode}.
- */
- public UiElementNode getUiRoot() {
- UiElementNode root = this;
- while (root.mUiParent != null) {
- root = root.mUiParent;
- }
-
- return root;
- }
-
- /**
- * Returns the index of this sibling (where the first child has index 0, the second child
- * has index 1, and so on.)
- *
- * @return The sibling index of this node
- */
- public int getUiSiblingIndex() {
- if (mUiParent != null) {
- int index = 0;
- for (UiElementNode node : mUiParent.getUiChildren()) {
- if (node == this) {
- break;
- }
- index++;
- }
- return index;
- }
-
- return 0;
- }
-
- /**
- * Returns the previous UI sibling of this UI node. If the node does not have a previous
- * sibling, returns null.
- *
- * @return The previous UI sibling of this UI node, or null if not applicable.
- */
- public UiElementNode getUiPreviousSibling() {
- if (mUiParent != null) {
- List<UiElementNode> childlist = mUiParent.getUiChildren();
- if (childlist != null && childlist.size() > 1 && childlist.get(0) != this) {
- int index = childlist.indexOf(this);
- return index > 0 ? childlist.get(index - 1) : null;
- }
- }
- return null;
- }
-
- /**
- * Returns the next UI sibling of this UI node.
- * If the node does not have a next sibling, returns null.
- *
- * @return The next UI sibling of this UI node, or null.
- */
- public UiElementNode getUiNextSibling() {
- if (mUiParent != null) {
- List<UiElementNode> childlist = mUiParent.getUiChildren();
- if (childlist != null) {
- int size = childlist.size();
- if (size > 1 && childlist.get(size - 1) != this) {
- int index = childlist.indexOf(this);
- return index >= 0 && index < size - 1 ? childlist.get(index + 1) : null;
- }
- }
- }
- return null;
- }
-
- /**
- * Sets the {@link AndroidXmlEditor} handling this {@link UiElementNode} hierarchy.
- * <p/>
- * The editor must always be set on the root node. This method takes care of that.
- *
- * @param editor The editor to associate this node with.
- */
- public void setEditor(AndroidXmlEditor editor) {
- if (mUiParent == null) {
- mEditor = editor;
- } else {
- mUiParent.setEditor(editor);
- }
- }
-
- /**
- * Returns the {@link AndroidXmlEditor} that embeds this {@link UiElementNode}.
- * <p/>
- * The value is initially null until the node is attached to its parent -- the value
- * of the root node is then propagated.
- *
- * @return The embedding {@link AndroidXmlEditor} or null.
- */
- public AndroidXmlEditor getEditor() {
- return mUiParent == null ? mEditor : mUiParent.getEditor();
- }
-
- /**
- * Returns the Android target data for the file being edited.
- *
- * @return The Android target data for the file being edited.
- */
- public AndroidTargetData getAndroidTarget() {
- return getEditor().getTargetData();
- }
-
- /**
- * @return A read-only version of the children collection.
- */
- public List<UiElementNode> getUiChildren() {
- if (mReadOnlyUiChildren == null) {
- mReadOnlyUiChildren = Collections.unmodifiableList(mUiChildren);
- }
- return mReadOnlyUiChildren;
- }
-
- /**
- * Returns a collection containing all the known attributes as well as
- * all the unknown ui attributes.
- *
- * @return A read-only version of the attributes collection.
- */
- public Collection<UiAttributeNode> getAllUiAttributes() {
- if (mCachedAllUiAttributes == null) {
-
- List<UiAttributeNode> allValues =
- new ArrayList<UiAttributeNode>(getInternalUiAttributes().values());
- allValues.addAll(mUnknownUiAttributes);
-
- mCachedAllUiAttributes = Collections.unmodifiableCollection(allValues);
- }
- return mCachedAllUiAttributes;
- }
-
- /**
- * Returns all the unknown ui attributes, that is those we found defined in the
- * actual XML but that we don't have descriptors for.
- *
- * @return A read-only version of the unknown attributes collection.
- */
- public Collection<UiAttributeNode> getUnknownUiAttributes() {
- return Collections.unmodifiableCollection(mUnknownUiAttributes);
- }
-
- /**
- * Sets the error flag value.
- *
- * @param errorFlag the error flag
- */
- public final void setHasError(boolean errorFlag) {
- mHasError = errorFlag;
- }
-
- /**
- * Returns whether this node, its attributes, or one of the children nodes (and attributes)
- * has errors.
- *
- * @return True if this node, its attributes, or one of the children nodes (and attributes)
- * has errors.
- */
- public final boolean hasError() {
- if (mHasError) {
- return true;
- }
-
- // get the error value from the attributes.
- for (UiAttributeNode attribute : getAllUiAttributes()) {
- if (attribute.hasError()) {
- return true;
- }
- }
-
- // and now from the children.
- for (UiElementNode child : mUiChildren) {
- if (child.hasError()) {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Returns the provider that knows how to create {@link ElementDescriptor} from unmapped
- * XML names.
- * <p/>
- * The default is to have one that creates new {@link ElementDescriptor}.
- * <p/>
- * There is only one such provider in any UI model tree, attached to the root node.
- *
- * @return An instance of {@link IUnknownDescriptorProvider}. Can never be null.
- */
- public IUnknownDescriptorProvider getUnknownDescriptorProvider() {
- if (mUiParent != null) {
- return mUiParent.getUnknownDescriptorProvider();
- }
- if (mUnknownDescProvider == null) {
- // Create the default one on demand.
- mUnknownDescProvider = new IUnknownDescriptorProvider() {
-
- private final HashMap<String, ElementDescriptor> mMap =
- new HashMap<String, ElementDescriptor>();
-
- /**
- * The default is to create a new ElementDescriptor wrapping
- * the unknown XML local name and reuse previously created descriptors.
- */
- @Override
- public ElementDescriptor getDescriptor(String xmlLocalName) {
-
- ElementDescriptor desc = mMap.get(xmlLocalName);
-
- if (desc == null) {
- desc = new ElementDescriptor(xmlLocalName);
- mMap.put(xmlLocalName, desc);
- }
-
- return desc;
- }
- };
- }
- return mUnknownDescProvider;
- }
-
- /**
- * Sets the provider that knows how to create {@link ElementDescriptor} from unmapped
- * XML names.
- * <p/>
- * The default is to have one that creates new {@link ElementDescriptor}.
- * <p/>
- * There is only one such provider in any UI model tree, attached to the root node.
- *
- * @param unknownDescProvider The new provider to use. Must not be null.
- */
- public void setUnknownDescriptorProvider(IUnknownDescriptorProvider unknownDescProvider) {
- if (mUiParent == null) {
- mUnknownDescProvider = unknownDescProvider;
- } else {
- mUiParent.setUnknownDescriptorProvider(unknownDescProvider);
- }
- }
-
- /**
- * Adds a new {@link IUiUpdateListener} to the internal update listener list.
- *
- * @param listener The listener to add.
- */
- public void addUpdateListener(IUiUpdateListener listener) {
- if (mUiUpdateListeners == null) {
- mUiUpdateListeners = new ArrayList<IUiUpdateListener>();
- }
- if (!mUiUpdateListeners.contains(listener)) {
- mUiUpdateListeners.add(listener);
- }
- }
-
- /**
- * Removes an existing {@link IUiUpdateListener} from the internal update listener list.
- * Does nothing if the list is empty or the listener is not registered.
- *
- * @param listener The listener to remove.
- */
- public void removeUpdateListener(IUiUpdateListener listener) {
- if (mUiUpdateListeners != null) {
- mUiUpdateListeners.remove(listener);
- }
- }
-
- /**
- * Finds a child node relative to this node using a path-like expression.
- * F.ex. "node1/node2" would find a child "node1" that contains a child "node2" and
- * returns the latter. If there are multiple nodes with the same name at the same
- * level, always uses the first one found.
- *
- * @param path The path like expression to select a child node.
- * @return The ui node found or null.
- */
- public UiElementNode findUiChildNode(String path) {
- String[] items = path.split("/"); //$NON-NLS-1$
- UiElementNode uiNode = this;
- for (String item : items) {
- boolean nextSegment = false;
- for (UiElementNode c : uiNode.mUiChildren) {
- if (c.getDescriptor().getXmlName().equals(item)) {
- uiNode = c;
- nextSegment = true;
- break;
- }
- }
- if (!nextSegment) {
- return null;
- }
- }
- return uiNode;
- }
-
- /**
- * Finds an {@link UiElementNode} which contains the give XML {@link Node}.
- * Looks recursively in all children UI nodes.
- *
- * @param xmlNode The XML node to look for.
- * @return The {@link UiElementNode} that contains xmlNode or null if not found,
- */
- public UiElementNode findXmlNode(Node xmlNode) {
- if (xmlNode == null) {
- return null;
- }
- if (getXmlNode() == xmlNode) {
- return this;
- }
-
- for (UiElementNode uiChild : mUiChildren) {
- UiElementNode found = uiChild.findXmlNode(xmlNode);
- if (found != null) {
- return found;
- }
- }
-
- return null;
- }
-
- /**
- * Returns the {@link UiAttributeNode} matching this attribute descriptor or
- * null if not found.
- *
- * @param attrDesc The {@link AttributeDescriptor} to match.
- * @return the {@link UiAttributeNode} matching this attribute descriptor or null
- * if not found.
- */
- public UiAttributeNode findUiAttribute(AttributeDescriptor attrDesc) {
- return getInternalUiAttributes().get(attrDesc);
- }
-
- /**
- * Populate this element node with all values from the given XML node.
- *
- * This fails if the given XML node has a different element name -- it won't change the
- * type of this ui node.
- *
- * This method can be both used for populating values the first time and updating values
- * after the XML model changed.
- *
- * @param xmlNode The XML node to mirror
- * @return Returns true if the XML structure has changed (nodes added, removed or replaced)
- */
- public boolean loadFromXmlNode(Node xmlNode) {
- boolean structureChanged = (mXmlNode != xmlNode);
- mXmlNode = xmlNode;
- if (xmlNode != null) {
- updateAttributeList(xmlNode);
- structureChanged |= updateElementList(xmlNode);
- invokeUiUpdateListeners(structureChanged ? UiUpdateState.CHILDREN_CHANGED
- : UiUpdateState.ATTR_UPDATED);
- }
- return structureChanged;
- }
-
- /**
- * Clears the UI node and reload it from the given XML node.
- * <p/>
- * This works by clearing all references to any previous XML or UI nodes and
- * then reloads the XML document from scratch. The editor reference is kept.
- * <p/>
- * This is used in the special case where the ElementDescriptor structure has changed.
- * Rather than try to diff inflated UI nodes (as loadFromXmlNode does), we don't bother
- * and reload everything. This is not subtle and should be used very rarely.
- *
- * @param xmlNode The XML node or document to reload. Can be null.
- */
- public void reloadFromXmlNode(Node xmlNode) {
- // The editor needs to be preserved, it is not affected by an XML change.
- AndroidXmlEditor editor = getEditor();
- clearContent();
- setEditor(editor);
- if (xmlNode != null) {
- setXmlDocument(xmlNode.getOwnerDocument());
- }
- // This will reload all the XML and recreate the UI structure from scratch.
- loadFromXmlNode(xmlNode);
- }
-
- /**
- * Called by attributes when they want to commit their value
- * to an XML node.
- * <p/>
- * For mandatory nodes, this makes sure the underlying XML element node
- * exists in the model. If not, it is created and assigned as the underlying
- * XML node.
- * </br>
- * For non-mandatory nodes, simply return the underlying XML node, which
- * must always exists.
- *
- * @return The XML node matching this {@link UiElementNode} or null.
- */
- public Node prepareCommit() {
- if (getDescriptor().getMandatory() != Mandatory.NOT_MANDATORY) {
- createXmlNode();
- // The new XML node has been created.
- // We don't need to refresh using loadFromXmlNode() since there are
- // no attributes or elements that need to be loading into this node.
- }
- return getXmlNode();
- }
-
- /**
- * Commits the attributes (all internal, inherited from UI parent & unknown attributes).
- * This is called by the UI when the embedding part needs to be committed.
- */
- public void commit() {
- for (UiAttributeNode uiAttr : getAllUiAttributes()) {
- uiAttr.commit();
- }
- }
-
- /**
- * Returns true if the part has been modified with respect to the data
- * loaded from the model.
- * @return True if the part has been modified with respect to the data
- * loaded from the model.
- */
- public boolean isDirty() {
- for (UiAttributeNode uiAttr : getAllUiAttributes()) {
- if (uiAttr.isDirty()) {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Creates the underlying XML element node for this UI node if it doesn't already
- * exists.
- *
- * @return The new value of getXmlNode() (can be null if creation failed)
- */
- public Node createXmlNode() {
- if (mXmlNode != null) {
- return null;
- }
- Node parentXmlNode = null;
- if (mUiParent != null) {
- parentXmlNode = mUiParent.prepareCommit();
- if (parentXmlNode == null) {
- // The parent failed to create its own backing XML node. Abort.
- // No need to throw an exception, the parent will most likely
- // have done so itself.
- return null;
- }
- }
-
- String elementName = getDescriptor().getXmlName();
- Document doc = getXmlDocument();
-
- // We *must* have a root node. If not, we need to abort.
- if (doc == null) {
- throw new RuntimeException(
- String.format("Missing XML document for %1$s XML node.", elementName));
- }
-
- // If we get here and parentXmlNode is null, the node is to be created
- // as the root node of the document (which can't be null, cf. check above).
- if (parentXmlNode == null) {
- parentXmlNode = doc;
- }
-
- mXmlNode = doc.createElement(elementName);
-
- // If this element does not have children, mark it as an empty tag
- // such that the XML looks like <tag/> instead of <tag></tag>
- if (!mDescriptor.hasChildren()) {
- if (mXmlNode instanceof ElementImpl) {
- ElementImpl element = (ElementImpl) mXmlNode;
- element.setEmptyTag(true);
- }
- }
-
- Node xmlNextSibling = null;
-
- UiElementNode uiNextSibling = getUiNextSibling();
- if (uiNextSibling != null) {
- xmlNextSibling = uiNextSibling.getXmlNode();
- }
-
- Node previousTextNode = null;
- if (xmlNextSibling != null) {
- Node previousNode = xmlNextSibling.getPreviousSibling();
- if (previousNode != null && previousNode.getNodeType() == Node.TEXT_NODE) {
- previousTextNode = previousNode;
- }
- } else {
- Node lastChild = parentXmlNode.getLastChild();
- if (lastChild != null && lastChild.getNodeType() == Node.TEXT_NODE) {
- previousTextNode = lastChild;
- }
- }
-
- String insertAfter = null;
-
- // Try to figure out the indentation node to insert. Even in auto-formatting
- // we need to do this, because it turns out the XML editor's formatter does
- // not do a very good job with completely botched up XML; it does a much better
- // job if the new XML is already mostly well formatted. Thus, the main purpose
- // of applying the real XML formatter after our own indentation attempts here is
- // to make it apply its own tab-versus-spaces indentation properties, have it
- // insert line breaks before attributes (if the user has configured that), etc.
-
- // First figure out the indentation level of the newly inserted element;
- // this is either the same as the previous sibling, or if there is no sibling,
- // it's the indentation of the parent plus one indentation level.
- boolean isFirstChild = getUiPreviousSibling() == null
- || parentXmlNode.getFirstChild() == null;
- AndroidXmlEditor editor = getEditor();
- String indent;
- String parentIndent = ""; //$NON-NLS-1$
- if (isFirstChild) {
- indent = parentIndent = editor.getIndent(parentXmlNode);
- // We need to add one level of indentation. Are we using tabs?
- // Can't get to formatting settings so let's just look at the
- // parent indentation and see if we can guess
- if (indent.length() > 0 && indent.charAt(indent.length()-1) == '\t') {
- indent = indent + '\t';
- } else {
- // Not using tabs, or we can't figure it out (because parent had no
- // indentation). In that case, indent with 4 spaces, as seems to
- // be the Android default.
- indent = indent + " "; //$NON-NLS-1$
- }
- } else {
- // Find out the indent of the previous sibling
- indent = editor.getIndent(getUiPreviousSibling().getXmlNode());
- }
-
- // We want to insert the new element BEFORE the text node which precedes
- // the next element, since that text node is the next element's indentation!
- if (previousTextNode != null) {
- xmlNextSibling = previousTextNode;
- } else {
- // If there's no previous text node, we are probably inside an
- // empty element (<LinearLayout>|</LinearLayout>) and in that case we need
- // to not only insert a newline and indentation before the new element, but
- // after it as well.
- insertAfter = parentIndent;
- }
-
- // Insert indent text node before the new element
- IStructuredDocument document = editor.getStructuredDocument();
- String newLine;
- if (document != null) {
- newLine = TextUtilities.getDefaultLineDelimiter(document);
- } else {
- newLine = SdkUtils.getLineSeparator();
- }
- Text indentNode = doc.createTextNode(newLine + indent);
- parentXmlNode.insertBefore(indentNode, xmlNextSibling);
-
- // Insert the element itself
- parentXmlNode.insertBefore(mXmlNode, xmlNextSibling);
-
- // Insert a separator after the tag. We only do this when we've inserted
- // a tag into an area where there was no whitespace before
- // (e.g. a new child of <LinearLayout></LinearLayout>).
- if (insertAfter != null) {
- Text sep = doc.createTextNode(newLine + insertAfter);
- parentXmlNode.insertBefore(sep, xmlNextSibling);
- }
-
- // Set all initial attributes in the XML node if they are not empty.
- // Iterate on the descriptor list to get the desired order and then use the
- // internal values, if any.
- List<UiAttributeNode> addAttributes = new ArrayList<UiAttributeNode>();
-
- for (AttributeDescriptor attrDesc : getAttributeDescriptors()) {
- if (attrDesc instanceof XmlnsAttributeDescriptor) {
- XmlnsAttributeDescriptor desc = (XmlnsAttributeDescriptor) attrDesc;
- Attr attr = doc.createAttributeNS(SdkConstants.XMLNS_URI,
- desc.getXmlNsName());
- attr.setValue(desc.getValue());
- attr.setPrefix(desc.getXmlNsPrefix());
- mXmlNode.getAttributes().setNamedItemNS(attr);
- } else {
- UiAttributeNode uiAttr = getInternalUiAttributes().get(attrDesc);
-
- // Don't apply the attribute immediately, instead record this attribute
- // such that we can gather all attributes and sort them first.
- // This is necessary because the XML model will *append* all attributes
- // so we want to add them in a particular order.
- // (Note that we only have to worry about UiAttributeNodes with non null
- // values, since this is a new node and we therefore don't need to attempt
- // to remove existing attributes)
- String value = uiAttr.getCurrentValue();
- if (value != null && value.length() > 0) {
- addAttributes.add(uiAttr);
- }
- }
- }
-
- // Sort and apply the attributes in order, because the Eclipse XML model will always
- // append the XML attributes, so by inserting them in our desired order they will
- // appear that way in the XML
- Collections.sort(addAttributes);
-
- for (UiAttributeNode node : addAttributes) {
- commitAttributeToXml(node, node.getCurrentValue());
- node.setDirty(false);
- }
-
- getEditor().scheduleNodeReformat(this, false);
-
- // Notify per-node listeners
- invokeUiUpdateListeners(UiUpdateState.CREATED);
- // Notify global listeners
- fireNodeCreated(this, getUiSiblingIndex());
-
- return mXmlNode;
- }
-
- /**
- * Removes the XML node corresponding to this UI node if it exists
- * and also removes all mirrored information in this UI node (i.e. children, attributes)
- *
- * @return The removed node or null if it didn't exist in the first place.
- */
- public Node deleteXmlNode() {
- if (mXmlNode == null) {
- return null;
- }
-
- int previousIndex = getUiSiblingIndex();
-
- // First clear the internals of the node and *then* actually deletes the XML
- // node (because doing so will generate an update even and this node may be
- // revisited via loadFromXmlNode).
- Node oldXmlNode = mXmlNode;
- clearContent();
-
- Node xmlParent = oldXmlNode.getParentNode();
- if (xmlParent == null) {
- xmlParent = getXmlDocument();
- }
- Node previousSibling = oldXmlNode.getPreviousSibling();
- oldXmlNode = xmlParent.removeChild(oldXmlNode);
-
- // We need to remove the text node BEFORE the removed element, since THAT's the
- // indentation node for the removed element.
- if (previousSibling != null && previousSibling.getNodeType() == Node.TEXT_NODE
- && previousSibling.getNodeValue().trim().length() == 0) {
- xmlParent.removeChild(previousSibling);
- }
-
- invokeUiUpdateListeners(UiUpdateState.DELETED);
- fireNodeDeleted(this, previousIndex);
-
- return oldXmlNode;
- }
-
- /**
- * Updates the element list for this UiElementNode.
- * At the end, the list of children UiElementNode here will match the one from the
- * provided XML {@link Node}:
- * <ul>
- * <li> Walk both the current ui children list and the xml children list at the same time.
- * <li> If we have a new xml child but already reached the end of the ui child list, add the
- * new xml node.
- * <li> Otherwise, check if the xml node is referenced later in the ui child list and if so,
- * move it here. It means the XML child list has been reordered.
- * <li> Otherwise, this is a new XML node that we add in the middle of the ui child list.
- * <li> At the end, we may have finished walking the xml child list but still have remaining
- * ui children, simply delete them as they matching trailing xml nodes that have been
- * removed unless they are mandatory ui nodes.
- * </ul>
- * Note that only the first case is used when populating the ui list the first time.
- *
- * @param xmlNode The XML node to mirror
- * @return True when the XML structure has changed.
- */
- protected boolean updateElementList(Node xmlNode) {
- boolean structureChanged = false;
- boolean hasMandatoryLast = false;
- int uiIndex = 0;
- Node xmlChild = xmlNode.getFirstChild();
- while (xmlChild != null) {
- if (xmlChild.getNodeType() == Node.ELEMENT_NODE) {
- String elementName = xmlChild.getNodeName();
- UiElementNode uiNode = null;
- CustomViewDescriptorService service = CustomViewDescriptorService.getInstance();
- if (mUiChildren.size() <= uiIndex) {
- // A new node is being added at the end of the list
- ElementDescriptor desc = mDescriptor.findChildrenDescriptor(elementName,
- false /* recursive */);
- if (desc == null && elementName.indexOf('.') != -1 &&
- (!elementName.startsWith(ANDROID_PKG_PREFIX)
- || elementName.startsWith(ANDROID_SUPPORT_PKG_PREFIX))) {
- AndroidXmlEditor editor = getEditor();
- if (editor != null && editor.getProject() != null) {
- desc = service.getDescriptor(editor.getProject(), elementName);
- }
- }
- if (desc == null) {
- // Unknown node. Create a temporary descriptor for it.
- // We'll add unknown attributes to it later.
- IUnknownDescriptorProvider p = getUnknownDescriptorProvider();
- desc = p.getDescriptor(elementName);
- }
- structureChanged = true;
- uiNode = appendNewUiChild(desc);
- uiIndex++;
- } else {
- // A new node is being inserted or moved.
- // Note: mandatory nodes can be created without an XML node in which case
- // getXmlNode() is null.
- UiElementNode uiChild;
- int n = mUiChildren.size();
- for (int j = uiIndex; j < n; j++) {
- uiChild = mUiChildren.get(j);
- if (uiChild.getXmlNode() != null && uiChild.getXmlNode() == xmlChild) {
- if (j > uiIndex) {
- // Found the same XML node at some later index, now move it here.
- mUiChildren.remove(j);
- mUiChildren.add(uiIndex, uiChild);
- structureChanged = true;
- }
- uiNode = uiChild;
- uiIndex++;
- break;
- }
- }
-
- if (uiNode == null) {
- // Look for an unused mandatory node with no XML node attached
- // referencing the same XML element name
- for (int j = uiIndex; j < n; j++) {
- uiChild = mUiChildren.get(j);
- if (uiChild.getXmlNode() == null &&
- uiChild.getDescriptor().getMandatory() !=
- Mandatory.NOT_MANDATORY &&
- uiChild.getDescriptor().getXmlName().equals(elementName)) {
-
- if (j > uiIndex) {
- // Found it, now move it here
- mUiChildren.remove(j);
- mUiChildren.add(uiIndex, uiChild);
- }
- // Assign the XML node to this empty mandatory element.
- uiChild.mXmlNode = xmlChild;
- structureChanged = true;
- uiNode = uiChild;
- uiIndex++;
- }
- }
- }
-
- if (uiNode == null) {
- // Inserting new node
- ElementDescriptor desc = mDescriptor.findChildrenDescriptor(elementName,
- false /* recursive */);
- if (desc == null && elementName.indexOf('.') != -1 &&
- (!elementName.startsWith(ANDROID_PKG_PREFIX)
- || elementName.startsWith(ANDROID_SUPPORT_PKG_PREFIX))) {
- AndroidXmlEditor editor = getEditor();
- if (editor != null && editor.getProject() != null) {
- desc = service.getDescriptor(editor.getProject(), elementName);
- }
- }
- if (desc == null) {
- // Unknown node. Create a temporary descriptor for it.
- // We'll add unknown attributes to it later.
- IUnknownDescriptorProvider p = getUnknownDescriptorProvider();
- desc = p.getDescriptor(elementName);
- } else {
- structureChanged = true;
- uiNode = insertNewUiChild(uiIndex, desc);
- uiIndex++;
- }
- }
- }
- if (uiNode != null) {
- // If we touched an UI Node, even an existing one, refresh its content.
- // For new nodes, this will populate them recursively.
- structureChanged |= uiNode.loadFromXmlNode(xmlChild);
-
- // Remember if there are any mandatory-last nodes to reorder.
- hasMandatoryLast |=
- uiNode.getDescriptor().getMandatory() == Mandatory.MANDATORY_LAST;
- }
- }
- xmlChild = xmlChild.getNextSibling();
- }
-
- // There might be extra UI nodes at the end if the XML node list got shorter.
- for (int index = mUiChildren.size() - 1; index >= uiIndex; --index) {
- structureChanged |= removeUiChildAtIndex(index);
- }
-
- if (hasMandatoryLast) {
- // At least one mandatory-last uiNode was moved. Let's see if we can
- // move them back to the last position. That's possible if the only
- // thing between these and the end are other mandatory empty uiNodes
- // (mandatory uiNodes with no XML attached are pure "virtual" reserved
- // slots and it's ok to reorganize them but other can't.)
- int n = mUiChildren.size() - 1;
- for (int index = n; index >= 0; index--) {
- UiElementNode uiChild = mUiChildren.get(index);
- Mandatory mand = uiChild.getDescriptor().getMandatory();
- if (mand == Mandatory.MANDATORY_LAST && index < n) {
- // Remove it from index and move it back at the end of the list.
- mUiChildren.remove(index);
- mUiChildren.add(uiChild);
- } else if (mand == Mandatory.NOT_MANDATORY || uiChild.getXmlNode() != null) {
- // We found at least one non-mandatory or a mandatory node with an actual
- // XML attached, so there's nothing we can reorganize past this point.
- break;
- }
- }
- }
-
- return structureChanged;
- }
-
- /**
- * Internal helper to remove an UI child node given by its index in the
- * internal child list.
- *
- * Also invokes the update listener on the node to be deleted *after* the node has
- * been removed.
- *
- * @param uiIndex The index of the UI child to remove, range 0 .. mUiChildren.size()-1
- * @return True if the structure has changed
- * @throws IndexOutOfBoundsException if index is out of mUiChildren's bounds. Of course you
- * know that could never happen unless the computer is on fire or something.
- */
- private boolean removeUiChildAtIndex(int uiIndex) {
- UiElementNode uiNode = mUiChildren.get(uiIndex);
- ElementDescriptor desc = uiNode.getDescriptor();
-
- try {
- if (uiNode.getDescriptor().getMandatory() != Mandatory.NOT_MANDATORY) {
- // This is a mandatory node. Such a node must exist in the UiNode hierarchy
- // even if there's no XML counterpart. However we only need to keep one.
-
- // Check if the parent (e.g. this node) has another similar ui child node.
- boolean keepNode = true;
- for (UiElementNode child : mUiChildren) {
- if (child != uiNode && child.getDescriptor() == desc) {
- // We found another child with the same descriptor that is not
- // the node we want to remove. This means we have one mandatory
- // node so we can safely remove uiNode.
- keepNode = false;
- break;
- }
- }
-
- if (keepNode) {
- // We can't remove a mandatory node as we need to keep at least one
- // mandatory node in the parent. Instead we just clear its content
- // (including its XML Node reference).
-
- // A mandatory node with no XML means it doesn't really exist, so it can't be
- // deleted. So the structure will change only if the ui node is actually
- // associated to an XML node.
- boolean xmlExists = (uiNode.getXmlNode() != null);
-
- uiNode.clearContent();
- return xmlExists;
- }
- }
-
- mUiChildren.remove(uiIndex);
-
- return true;
- } finally {
- // Tell listeners that a node has been removed.
- // The model has already been modified.
- invokeUiUpdateListeners(UiUpdateState.DELETED);
- }
- }
-
- /**
- * Creates a new {@link UiElementNode} from the given {@link ElementDescriptor}
- * and appends it to the end of the element children list.
- *
- * @param descriptor The {@link ElementDescriptor} that knows how to create the UI node.
- * @return The new UI node that has been appended
- */
- public UiElementNode appendNewUiChild(ElementDescriptor descriptor) {
- UiElementNode uiNode;
- uiNode = descriptor.createUiNode();
- mUiChildren.add(uiNode);
- uiNode.setUiParent(this);
- uiNode.invokeUiUpdateListeners(UiUpdateState.CREATED);
- return uiNode;
- }
-
- /**
- * Creates a new {@link UiElementNode} from the given {@link ElementDescriptor}
- * and inserts it in the element children list at the specified position.
- *
- * @param index The position where to insert in the element children list.
- * Shifts the element currently at that position (if any) and any
- * subsequent elements to the right (adds one to their indices).
- * Index must >= 0 and <= getUiChildren.size().
- * Using size() means to append to the end of the list.
- * @param descriptor The {@link ElementDescriptor} that knows how to create the UI node.
- * @return The new UI node.
- */
- public UiElementNode insertNewUiChild(int index, ElementDescriptor descriptor) {
- UiElementNode uiNode;
- uiNode = descriptor.createUiNode();
- mUiChildren.add(index, uiNode);
- uiNode.setUiParent(this);
- uiNode.invokeUiUpdateListeners(UiUpdateState.CREATED);
- return uiNode;
- }
-
- /**
- * Updates the {@link UiAttributeNode} list for this {@link UiElementNode}
- * using the values from the XML element.
- * <p/>
- * For a given {@link UiElementNode}, the attribute list always exists in
- * full and is totally independent of whether the XML model actually
- * has the corresponding attributes.
- * <p/>
- * For each attribute declared in this {@link UiElementNode}, get
- * the corresponding XML attribute. It may not exist, in which case the
- * value will be null. We don't really know if a value has changed, so
- * the updateValue() is called on the UI attribute in all cases.
- *
- * @param xmlNode The XML node to mirror
- */
- protected void updateAttributeList(Node xmlNode) {
- NamedNodeMap xmlAttrMap = xmlNode.getAttributes();
- HashSet<Node> visited = new HashSet<Node>();
-
- // For all known (i.e. expected) UI attributes, find an existing XML attribute of
- // same (uri, local name) and update the internal Ui attribute value.
- for (UiAttributeNode uiAttr : getInternalUiAttributes().values()) {
- AttributeDescriptor desc = uiAttr.getDescriptor();
- if (!(desc instanceof SeparatorAttributeDescriptor)) {
- Node xmlAttr = xmlAttrMap == null ? null :
- xmlAttrMap.getNamedItemNS(desc.getNamespaceUri(), desc.getXmlLocalName());
- uiAttr.updateValue(xmlAttr);
- visited.add(xmlAttr);
- }
- }
-
- // Clone the current list of unknown attributes. We'll then remove from this list when
- // we find attributes which are still unknown. What will be left are the old unknown
- // attributes that have been deleted in the current XML attribute list.
- @SuppressWarnings("unchecked")
- HashSet<UiAttributeNode> deleted = (HashSet<UiAttributeNode>) mUnknownUiAttributes.clone();
-
- // We need to ignore hidden attributes.
- Map<String, AttributeDescriptor> hiddenAttrDesc = getHiddenAttributeDescriptors();
-
- // Traverse the actual XML attribute list to find unknown attributes
- if (xmlAttrMap != null) {
- for (int i = 0; i < xmlAttrMap.getLength(); i++) {
- Node xmlAttr = xmlAttrMap.item(i);
- // Ignore attributes which have actual descriptors
- if (visited.contains(xmlAttr)) {
- continue;
- }
-
- String xmlFullName = xmlAttr.getNodeName();
-
- // Ignore attributes which are hidden (based on the prefix:localName key)
- if (hiddenAttrDesc.containsKey(xmlFullName)) {
- continue;
- }
-
- String xmlAttrLocalName = xmlAttr.getLocalName();
- String xmlNsUri = xmlAttr.getNamespaceURI();
-
- UiAttributeNode uiAttr = null;
- for (UiAttributeNode a : mUnknownUiAttributes) {
- String aLocalName = a.getDescriptor().getXmlLocalName();
- String aNsUri = a.getDescriptor().getNamespaceUri();
- if (aLocalName.equals(xmlAttrLocalName) &&
- (aNsUri == xmlNsUri || (aNsUri != null && aNsUri.equals(xmlNsUri)))) {
- // This attribute is still present in the unknown list
- uiAttr = a;
- // It has not been deleted
- deleted.remove(a);
- break;
- }
- }
- if (uiAttr == null) {
- uiAttr = addUnknownAttribute(xmlFullName, xmlAttrLocalName, xmlNsUri);
- }
-
- uiAttr.updateValue(xmlAttr);
- }
-
- // Remove from the internal list unknown attributes that have been deleted from the xml
- for (UiAttributeNode a : deleted) {
- mUnknownUiAttributes.remove(a);
- mCachedAllUiAttributes = null;
- }
- }
- }
-
- /**
- * Create a new temporary text attribute descriptor for the unknown attribute
- * and returns a new {@link UiAttributeNode} associated to this descriptor.
- * <p/>
- * The attribute is not marked as dirty, doing so is up to the caller.
- */
- private UiAttributeNode addUnknownAttribute(String xmlFullName,
- String xmlAttrLocalName, String xmlNsUri) {
- // Create a new unknown attribute of format string
- TextAttributeDescriptor desc = new TextAttributeDescriptor(
- xmlAttrLocalName, // xml name
- xmlNsUri, // ui name
- new AttributeInfo(xmlAttrLocalName, Format.STRING_SET)
- );
- UiAttributeNode uiAttr = desc.createUiNode(this);
- mUnknownUiAttributes.add(uiAttr);
- mCachedAllUiAttributes = null;
- return uiAttr;
- }
-
- /**
- * Invoke all registered {@link IUiUpdateListener} listening on this UI update for this node.
- */
- protected void invokeUiUpdateListeners(UiUpdateState state) {
- if (mUiUpdateListeners != null) {
- for (IUiUpdateListener listener : mUiUpdateListeners) {
- try {
- listener.uiElementNodeUpdated(this, state);
- } catch (Exception e) {
- // prevent a crashing listener from crashing the whole invocation chain
- AdtPlugin.log(e, "UIElement Listener failed: %s, state=%s", //$NON-NLS-1$
- getBreadcrumbTrailDescription(true),
- state.toString());
- }
- }
- }
- }
-
- // --- for derived implementations only ---
-
- @VisibleForTesting
- public void setXmlNode(Node xmlNode) {
- mXmlNode = xmlNode;
- }
-
- public void refreshUi() {
- invokeUiUpdateListeners(UiUpdateState.ATTR_UPDATED);
- }
-
-
- // ------------- Helpers
-
- /**
- * Helper method to commit a single attribute value to XML.
- * <p/>
- * This method updates the XML regardless of the current XML value.
- * Callers should check first if an update is needed.
- * If the new value is empty, the XML attribute will be actually removed.
- * <p/>
- * Note that the caller MUST ensure that modifying the underlying XML model is
- * safe and must take care of marking the model as dirty if necessary.
- *
- * @see AndroidXmlEditor#wrapEditXmlModel(Runnable)
- *
- * @param uiAttr The attribute node to commit. Must be a child of this UiElementNode.
- * @param newValue The new value to set.
- * @return True if the XML attribute was modified or removed, false if nothing changed.
- */
- public boolean commitAttributeToXml(UiAttributeNode uiAttr, String newValue) {
- // Get (or create) the underlying XML element node that contains the attributes.
- Node element = prepareCommit();
- if (element != null && uiAttr != null) {
- String attrLocalName = uiAttr.getDescriptor().getXmlLocalName();
- String attrNsUri = uiAttr.getDescriptor().getNamespaceUri();
-
- NamedNodeMap attrMap = element.getAttributes();
- if (newValue == null || newValue.length() == 0) {
- // Remove attribute if it's empty
- if (attrMap.getNamedItemNS(attrNsUri, attrLocalName) != null) {
- attrMap.removeNamedItemNS(attrNsUri, attrLocalName);
- return true;
- }
- } else {
- // Add or replace an attribute
- Document doc = element.getOwnerDocument();
- if (doc != null) {
- Attr attr;
- if (attrNsUri != null && attrNsUri.length() > 0) {
- attr = (Attr) attrMap.getNamedItemNS(attrNsUri, attrLocalName);
- if (attr == null) {
- attr = doc.createAttributeNS(attrNsUri, attrLocalName);
- attr.setPrefix(XmlUtils.lookupNamespacePrefix(element, attrNsUri));
- attrMap.setNamedItemNS(attr);
- }
- } else {
- attr = (Attr) attrMap.getNamedItem(attrLocalName);
- if (attr == null) {
- attr = doc.createAttribute(attrLocalName);
- attrMap.setNamedItem(attr);
- }
- }
- attr.setValue(newValue);
- return true;
- }
- }
- }
- return false;
- }
-
- /**
- * Helper method to commit all dirty attributes values to XML.
- * <p/>
- * This method is useful if {@link #setAttributeValue(String, String, String, boolean)} has
- * been called more than once and all the attributes marked as dirty must be committed to
- * the XML. It calls {@link #commitAttributeToXml(UiAttributeNode, String)} on each dirty
- * attribute.
- * <p/>
- * Note that the caller MUST ensure that modifying the underlying XML model is
- * safe and must take care of marking the model as dirty if necessary.
- *
- * @see AndroidXmlEditor#wrapEditXmlModel(Runnable)
- *
- * @return True if one or more values were actually modified or removed,
- * false if nothing changed.
- */
- @SuppressWarnings("null") // Eclipse is confused by the logic and gets it wrong
- public boolean commitDirtyAttributesToXml() {
- boolean result = false;
- List<UiAttributeNode> dirtyAttributes = new ArrayList<UiAttributeNode>();
- for (UiAttributeNode uiAttr : getAllUiAttributes()) {
- if (uiAttr.isDirty()) {
- String value = uiAttr.getCurrentValue();
- if (value != null && value.length() > 0) {
- // Defer the new attributes: set these last and in order
- dirtyAttributes.add(uiAttr);
- } else {
- result |= commitAttributeToXml(uiAttr, value);
- uiAttr.setDirty(false);
- }
- }
- }
- if (dirtyAttributes.size() > 0) {
- result = true;
-
- Collections.sort(dirtyAttributes);
-
- // The Eclipse XML model will *always* append new attributes.
- // Therefore, if any of the dirty attributes are new, they will appear
- // after any existing, clean attributes on the element. To fix this,
- // we need to first remove any of these attributes, then insert them
- // back in the right order.
- Node element = prepareCommit();
- if (element == null) {
- return result;
- }
-
- if (AdtPrefs.getPrefs().getFormatGuiXml() && getEditor().supportsFormatOnGuiEdit()) {
- // If auto formatting, don't bother with attribute sorting here since the
- // order will be corrected as soon as the edit is committed anyway
- for (UiAttributeNode uiAttribute : dirtyAttributes) {
- commitAttributeToXml(uiAttribute, uiAttribute.getCurrentValue());
- uiAttribute.setDirty(false);
- }
-
- return result;
- }
-
- AttributeDescriptor descriptor = dirtyAttributes.get(0).getDescriptor();
- String firstName = descriptor.getXmlLocalName();
- String firstNamePrefix = null;
- String namespaceUri = descriptor.getNamespaceUri();
- if (namespaceUri != null) {
- firstNamePrefix = XmlUtils.lookupNamespacePrefix(element, namespaceUri);
- }
- NamedNodeMap attributes = ((Element) element).getAttributes();
- List<Attr> move = new ArrayList<Attr>();
- for (int i = 0, n = attributes.getLength(); i < n; i++) {
- Attr attribute = (Attr) attributes.item(i);
- if (XmlAttributeSortOrder.compareAttributes(
- attribute.getPrefix(), attribute.getLocalName(),
- firstNamePrefix, firstName) > 0) {
- move.add(attribute);
- }
- }
-
- for (Attr attribute : move) {
- if (attribute.getNamespaceURI() != null) {
- attributes.removeNamedItemNS(attribute.getNamespaceURI(),
- attribute.getLocalName());
- } else {
- attributes.removeNamedItem(attribute.getName());
- }
- }
-
- // Merge back the removed DOM attribute nodes and the new UI attribute nodes.
- // In cases where the attribute DOM name and the UI attribute names equal,
- // skip the DOM nodes and just apply the UI attributes.
- int domAttributeIndex = 0;
- int domAttributeIndexMax = move.size();
- int uiAttributeIndex = 0;
- int uiAttributeIndexMax = dirtyAttributes.size();
-
- while (true) {
- Attr domAttribute;
- UiAttributeNode uiAttribute;
-
- int compare;
- if (uiAttributeIndex < uiAttributeIndexMax) {
- if (domAttributeIndex < domAttributeIndexMax) {
- domAttribute = move.get(domAttributeIndex);
- uiAttribute = dirtyAttributes.get(uiAttributeIndex);
-
- String domAttributeName = domAttribute.getLocalName();
- String uiAttributeName = uiAttribute.getDescriptor().getXmlLocalName();
- compare = XmlAttributeSortOrder.compareAttributes(domAttributeName,
- uiAttributeName);
- } else {
- compare = 1;
- uiAttribute = dirtyAttributes.get(uiAttributeIndex);
- domAttribute = null;
- }
- } else if (domAttributeIndex < domAttributeIndexMax) {
- compare = -1;
- domAttribute = move.get(domAttributeIndex);
- uiAttribute = null;
- } else {
- break;
- }
-
- if (compare < 0) {
- if (domAttribute.getNamespaceURI() != null) {
- attributes.setNamedItemNS(domAttribute);
- } else {
- attributes.setNamedItem(domAttribute);
- }
- domAttributeIndex++;
- } else {
- assert compare >= 0;
- if (compare == 0) {
- domAttributeIndex++;
- }
- commitAttributeToXml(uiAttribute, uiAttribute.getCurrentValue());
- uiAttribute.setDirty(false);
- uiAttributeIndex++;
- }
- }
- }
-
- return result;
- }
-
- /**
- * Utility method to internally set the value of a text attribute for the current
- * UiElementNode.
- * <p/>
- * This method is a helper. It silently ignores the errors such as the requested
- * attribute not being present in the element or attribute not being settable.
- * It accepts inherited attributes (such as layout).
- * <p/>
- * This does not commit to the XML model. It does mark the attribute node as dirty.
- * This is up to the caller.
- *
- * @see #commitAttributeToXml(UiAttributeNode, String)
- * @see #commitDirtyAttributesToXml()
- *
- * @param attrXmlName The XML <em>local</em> name of the attribute to modify
- * @param attrNsUri The namespace URI of the attribute.
- * Can be null if the attribute uses the global namespace.
- * @param value The new value for the attribute. If set to null, the attribute is removed.
- * @param override True if the value must be set even if one already exists.
- * @return The {@link UiAttributeNode} that has been modified or null.
- */
- public UiAttributeNode setAttributeValue(
- String attrXmlName,
- String attrNsUri,
- String value,
- boolean override) {
- if (value == null) {
- value = ""; //$NON-NLS-1$ -- this removes an attribute
- }
-
- getEditor().scheduleNodeReformat(this, true);
-
- // Try with all internal attributes
- UiAttributeNode uiAttr = setInternalAttrValue(
- getAllUiAttributes(), attrXmlName, attrNsUri, value, override);
- if (uiAttr != null) {
- return uiAttr;
- }
-
- if (uiAttr == null) {
- // Failed to find the attribute. For non-android attributes that is mostly expected,
- // in which case we just create a new custom one. As a side effect, we'll find the
- // attribute descriptor via getAllUiAttributes().
- addUnknownAttribute(attrXmlName, attrXmlName, attrNsUri);
-
- // We've created the attribute, but not actually set the value on it, so let's do it.
- // Try with the updated internal attributes.
- // Implementation detail: we could just do a setCurrentValue + setDirty on the
- // uiAttr returned by addUnknownAttribute(); however going through setInternalAttrValue
- // means we won't duplicate the logic, at the expense of doing one more lookup.
- uiAttr = setInternalAttrValue(
- getAllUiAttributes(), attrXmlName, attrNsUri, value, override);
- }
-
- return uiAttr;
- }
-
- private UiAttributeNode setInternalAttrValue(
- Collection<UiAttributeNode> attributes,
- String attrXmlName,
- String attrNsUri,
- String value,
- boolean override) {
-
- // For namespace less attributes (like the "layout" attribute of an <include> tag
- // we may be passed "" as the namespace (during an attribute copy), and it
- // should really be null instead.
- if (attrNsUri != null && attrNsUri.length() == 0) {
- attrNsUri = null;
- }
-
- for (UiAttributeNode uiAttr : attributes) {
- AttributeDescriptor uiDesc = uiAttr.getDescriptor();
-
- if (uiDesc.getXmlLocalName().equals(attrXmlName)) {
- // Both NS URI must be either null or equal.
- if ((attrNsUri == null && uiDesc.getNamespaceUri() == null) ||
- (attrNsUri != null && attrNsUri.equals(uiDesc.getNamespaceUri()))) {
-
- // Not all attributes are editable, ignore those which are not.
- if (uiAttr instanceof IUiSettableAttributeNode) {
- String current = uiAttr.getCurrentValue();
- // Only update (and mark as dirty) if the attribute did not have any
- // value or if the value was different.
- if (override || current == null || !current.equals(value)) {
- ((IUiSettableAttributeNode) uiAttr).setCurrentValue(value);
- // mark the attribute as dirty since their internal content
- // as been modified, but not the underlying XML model
- uiAttr.setDirty(true);
- return uiAttr;
- }
- }
-
- // We found the attribute but it's not settable. Since attributes are
- // not duplicated, just abandon here.
- break;
- }
- }
- }
-
- return null;
- }
-
- /**
- * Utility method to retrieve the internal value of an attribute.
- * <p/>
- * Note that this retrieves the *field* value if the attribute has some UI, and
- * not the actual XML value. They may differ if the attribute is dirty.
- *
- * @param attrXmlName The XML name of the attribute to modify
- * @return The current internal value for the attribute or null in case of error.
- */
- public String getAttributeValue(String attrXmlName) {
- HashMap<AttributeDescriptor, UiAttributeNode> attributeMap = getInternalUiAttributes();
-
- for (Entry<AttributeDescriptor, UiAttributeNode> entry : attributeMap.entrySet()) {
- AttributeDescriptor uiDesc = entry.getKey();
- if (uiDesc.getXmlLocalName().equals(attrXmlName)) {
- UiAttributeNode uiAttr = entry.getValue();
- return uiAttr.getCurrentValue();
- }
- }
- return null;
- }
-
- // ------ IPropertySource methods
-
- @Override
- public Object getEditableValue() {
- return null;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.views.properties.IPropertySource#getPropertyDescriptors()
- *
- * Returns the property descriptor for this node. Since the descriptors are not linked to the
- * data, the AttributeDescriptor are used directly.
- */
- @Override
- public IPropertyDescriptor[] getPropertyDescriptors() {
- List<IPropertyDescriptor> propDescs = new ArrayList<IPropertyDescriptor>();
-
- // get the standard descriptors
- HashMap<AttributeDescriptor, UiAttributeNode> attributeMap = getInternalUiAttributes();
- Set<AttributeDescriptor> keys = attributeMap.keySet();
-
-
- // we only want the descriptor that do implement the IPropertyDescriptor interface.
- for (AttributeDescriptor key : keys) {
- if (key instanceof IPropertyDescriptor) {
- propDescs.add((IPropertyDescriptor)key);
- }
- }
-
- // now get the descriptor from the unknown attributes
- for (UiAttributeNode unknownNode : mUnknownUiAttributes) {
- if (unknownNode.getDescriptor() instanceof IPropertyDescriptor) {
- propDescs.add((IPropertyDescriptor)unknownNode.getDescriptor());
- }
- }
-
- // TODO cache this maybe, as it's not going to change (except for unknown descriptors)
- return propDescs.toArray(new IPropertyDescriptor[propDescs.size()]);
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.views.properties.IPropertySource#getPropertyValue(java.lang.Object)
- *
- * Returns the value of a given property. The id is the result of IPropertyDescriptor.getId(),
- * which return the AttributeDescriptor itself.
- */
- @Override
- public Object getPropertyValue(Object id) {
- HashMap<AttributeDescriptor, UiAttributeNode> attributeMap = getInternalUiAttributes();
-
- UiAttributeNode attribute = attributeMap.get(id);
-
- if (attribute == null) {
- // look for the id in the unknown attributes.
- for (UiAttributeNode unknownAttr : mUnknownUiAttributes) {
- if (id == unknownAttr.getDescriptor()) {
- return unknownAttr;
- }
- }
- }
-
- return attribute;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.views.properties.IPropertySource#isPropertySet(java.lang.Object)
- *
- * Returns whether the property is set. In our case this is if the string is non empty.
- */
- @Override
- public boolean isPropertySet(Object id) {
- HashMap<AttributeDescriptor, UiAttributeNode> attributeMap = getInternalUiAttributes();
-
- UiAttributeNode attribute = attributeMap.get(id);
-
- if (attribute != null) {
- return attribute.getCurrentValue().length() > 0;
- }
-
- // look for the id in the unknown attributes.
- for (UiAttributeNode unknownAttr : mUnknownUiAttributes) {
- if (id == unknownAttr.getDescriptor()) {
- return unknownAttr.getCurrentValue().length() > 0;
- }
- }
-
- return false;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.views.properties.IPropertySource#resetPropertyValue(java.lang.Object)
- *
- * Reset the property to its default value. For now we simply empty it.
- */
- @Override
- public void resetPropertyValue(Object id) {
- HashMap<AttributeDescriptor, UiAttributeNode> attributeMap = getInternalUiAttributes();
-
- UiAttributeNode attribute = attributeMap.get(id);
- if (attribute != null) {
- // TODO: reset the value of the attribute
-
- return;
- }
-
- // look for the id in the unknown attributes.
- for (UiAttributeNode unknownAttr : mUnknownUiAttributes) {
- if (id == unknownAttr.getDescriptor()) {
- // TODO: reset the value of the attribute
-
- return;
- }
- }
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.views.properties.IPropertySource#setPropertyValue(java.lang.Object, java.lang.Object)
- *
- * Set the property value. id is the result of IPropertyDescriptor.getId(), which is the
- * AttributeDescriptor itself. Value should be a String.
- */
- @Override
- public void setPropertyValue(Object id, Object value) {
- HashMap<AttributeDescriptor, UiAttributeNode> attributeMap = getInternalUiAttributes();
-
- UiAttributeNode attribute = attributeMap.get(id);
-
- if (attribute == null) {
- // look for the id in the unknown attributes.
- for (UiAttributeNode unknownAttr : mUnknownUiAttributes) {
- if (id == unknownAttr.getDescriptor()) {
- attribute = unknownAttr;
- break;
- }
- }
- }
-
- if (attribute != null) {
-
- // get the current value and compare it to the new value
- String oldValue = attribute.getCurrentValue();
- final String newValue = (String)value;
-
- if (oldValue.equals(newValue)) {
- return;
- }
-
- final UiAttributeNode fAttribute = attribute;
- AndroidXmlEditor editor = getEditor();
- editor.wrapEditXmlModel(new Runnable() {
- @Override
- public void run() {
- commitAttributeToXml(fAttribute, newValue);
- }
- });
- }
- }
-
- /**
- * Returns true if this node is an ancestor (parent, grandparent, and so on)
- * of the given node. Note that a node is not considered an ancestor of
- * itself.
- *
- * @param node the node to test
- * @return true if this node is an ancestor of the given node
- */
- public boolean isAncestorOf(UiElementNode node) {
- node = node.getUiParent();
- while (node != null) {
- if (node == this) {
- return true;
- }
- node = node.getUiParent();
- }
- return false;
- }
-
- /**
- * Finds the nearest common parent of the two given nodes (which could be one of the
- * two nodes as well)
- *
- * @param node1 the first node to test
- * @param node2 the second node to test
- * @return the nearest common parent of the two given nodes
- */
- public static UiElementNode getCommonAncestor(UiElementNode node1, UiElementNode node2) {
- while (node2 != null) {
- UiElementNode current = node1;
- while (current != null && current != node2) {
- current = current.getUiParent();
- }
- if (current == node2) {
- return current;
- }
- node2 = node2.getUiParent();
- }
-
- return null;
- }
-
- // ---- Global node create/delete Listeners ----
-
- /** List of listeners to be notified of newly created nodes, or null */
- private static List<NodeCreationListener> sListeners;
-
- /** Notify listeners that a new node has been created */
- private void fireNodeCreated(UiElementNode newChild, int index) {
- // Nothing to do if there aren't any listeners. We don't need to worry about
- // the case where one thread is firing node changes while another is adding a listener
- // (in that case it's still okay for this node firing not to be heard) so perform
- // the check outside of synchronization.
- if (sListeners == null) {
- return;
- }
- synchronized (UiElementNode.class) {
- if (sListeners != null) {
- UiElementNode parent = newChild.getUiParent();
- for (NodeCreationListener listener : sListeners) {
- listener.nodeCreated(parent, newChild, index);
- }
- }
- }
- }
-
- /** Notify listeners that a new node has been deleted */
- private void fireNodeDeleted(UiElementNode oldChild, int index) {
- if (sListeners == null) {
- return;
- }
- synchronized (UiElementNode.class) {
- if (sListeners != null) {
- UiElementNode parent = oldChild.getUiParent();
- for (NodeCreationListener listener : sListeners) {
- listener.nodeDeleted(parent, oldChild, index);
- }
- }
- }
- }
-
- /**
- * Adds a {@link NodeCreationListener} to be notified when new nodes are created
- *
- * @param listener the listener to be notified
- */
- public static void addNodeCreationListener(NodeCreationListener listener) {
- synchronized (UiElementNode.class) {
- if (sListeners == null) {
- sListeners = new ArrayList<NodeCreationListener>(1);
- }
- sListeners.add(listener);
- }
- }
-
- /**
- * Removes a {@link NodeCreationListener} from the set of listeners such that it is
- * no longer notified when nodes are created.
- *
- * @param listener the listener to be removed from the notification list
- */
- public static void removeNodeCreationListener(NodeCreationListener listener) {
- synchronized (UiElementNode.class) {
- sListeners.remove(listener);
- if (sListeners.size() == 0) {
- sListeners = null;
- }
- }
- }
-
- /** Interface implemented by listeners to be notified of newly created nodes */
- public interface NodeCreationListener {
- /**
- * Called when a new child node is created and added to the given parent
- *
- * @param parent the parent of the created node
- * @param child the newly node
- * @param index the index among the siblings of the child <b>after</b>
- * insertion
- */
- void nodeCreated(UiElementNode parent, UiElementNode child, int index);
-
- /**
- * Called when a child node is removed from the given parent
- *
- * @param parent the parent of the removed node
- * @param child the removed node
- * @param previousIndex the index among the siblings of the child
- * <b>before</b> removal
- */
- void nodeDeleted(UiElementNode parent, UiElementNode child, int previousIndex);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiFlagAttributeNode.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiFlagAttributeNode.java
deleted file mode 100644
index 13fcdb6b2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiFlagAttributeNode.java
+++ /dev/null
@@ -1,310 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.uimodel;
-
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.FlagAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.TextAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.ui.SectionHelper;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.resource.FontDescriptor;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ControlAdapter;
-import org.eclipse.swt.events.ControlEvent;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.swt.widgets.TableItem;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.dialogs.SelectionStatusDialog;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.TableWrapData;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Set;
-
-/**
- * Represents an XML attribute that is defined by a set of flag values,
- * i.e. enum names separated by pipe (|) characters.
- *
- * Note: in Android resources, a "flag" is a list of fixed values where one or
- * more values can be selected using an "or", e.g. "align='left|top'".
- * By contrast, an "enum" is a list of fixed values of which only one can be
- * selected at a given time, e.g. "gravity='right'".
- * <p/>
- * This class handles the "flag" case.
- * The "enum" case is done using {@link UiListAttributeNode}.
- */
-public class UiFlagAttributeNode extends UiTextAttributeNode {
-
- public UiFlagAttributeNode(FlagAttributeDescriptor attributeDescriptor,
- UiElementNode uiParent) {
- super(attributeDescriptor, uiParent);
- }
-
- /* (non-java doc)
- * Creates a label widget and an associated text field.
- * <p/>
- * As most other parts of the android manifest editor, this assumes the
- * parent uses a table layout with 2 columns.
- */
- @Override
- public void createUiControl(Composite parent, IManagedForm managedForm) {
- setManagedForm(managedForm);
- FormToolkit toolkit = managedForm.getToolkit();
- TextAttributeDescriptor desc = (TextAttributeDescriptor) getDescriptor();
-
- Label label = toolkit.createLabel(parent, desc.getUiName());
- label.setLayoutData(new TableWrapData(TableWrapData.LEFT, TableWrapData.MIDDLE));
- SectionHelper.addControlTooltip(label, DescriptorsUtils.formatTooltip(desc.getTooltip()));
-
- Composite composite = toolkit.createComposite(parent);
- composite.setLayoutData(new TableWrapData(TableWrapData.FILL_GRAB, TableWrapData.MIDDLE));
- GridLayout gl = new GridLayout(2, false);
- gl.marginHeight = gl.marginWidth = 0;
- composite.setLayout(gl);
- // Fixes missing text borders under GTK... also requires adding a 1-pixel margin
- // for the text field below
- toolkit.paintBordersFor(composite);
-
- final Text text = toolkit.createText(composite, getCurrentValue());
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalIndent = 1; // Needed by the fixed composite borders under GTK
- text.setLayoutData(gd);
- final Button selectButton = toolkit.createButton(composite, "Select...", SWT.PUSH);
-
- setTextWidget(text);
-
- selectButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- super.widgetSelected(e);
-
- String currentText = getTextWidgetValue();
-
- String result = showDialog(selectButton.getShell(), currentText);
-
- if (result != null) {
- setTextWidgetValue(result);
- }
- }
- });
- }
-
- /**
- * Get the flag names, either from the initial names set in the attribute
- * or by querying the framework resource parser.
- *
- * {@inheritDoc}
- */
- @Override
- public String[] getPossibleValues(String prefix) {
- String attr_name = getDescriptor().getXmlLocalName();
- String element_name = getUiParent().getDescriptor().getXmlName();
-
- String[] values = null;
-
- if (getDescriptor() instanceof FlagAttributeDescriptor &&
- ((FlagAttributeDescriptor) getDescriptor()).getNames() != null) {
- // Get enum values from the descriptor
- values = ((FlagAttributeDescriptor) getDescriptor()).getNames();
- }
-
- if (values == null) {
- // or from the AndroidTargetData
- UiElementNode uiNode = getUiParent();
- AndroidXmlEditor editor = uiNode.getEditor();
- AndroidTargetData data = editor.getTargetData();
- if (data != null) {
- values = data.getAttributeValues(element_name, attr_name);
- }
- }
-
- return values;
- }
-
- /**
- * Shows a dialog letting the user choose a set of enum, and returns a string
- * containing the result.
- */
- public String showDialog(Shell shell, String currentValue) {
- FlagSelectionDialog dlg = new FlagSelectionDialog(
- shell, currentValue.trim().split("\\s*\\|\\s*")); //$NON-NLS-1$
- dlg.open();
- Object[] result = dlg.getResult();
- if (result != null) {
- StringBuilder buf = new StringBuilder();
- for (Object name : result) {
- if (name instanceof String) {
- if (buf.length() > 0) {
- buf.append('|');
- }
- buf.append(name);
- }
- }
-
- return buf.toString();
- }
-
- return null;
-
- }
-
- /**
- * Displays a list of flag names with checkboxes.
- */
- private class FlagSelectionDialog extends SelectionStatusDialog {
-
- private Set<String> mCurrentSet;
- private Table mTable;
-
- public FlagSelectionDialog(Shell parentShell, String[] currentNames) {
- super(parentShell);
-
- mCurrentSet = new HashSet<String>();
- for (String name : currentNames) {
- if (name.length() > 0) {
- mCurrentSet.add(name);
- }
- }
-
- int shellStyle = getShellStyle();
- setShellStyle(shellStyle | SWT.MAX | SWT.RESIZE);
- }
-
- @Override
- protected void computeResult() {
- if (mTable != null) {
- ArrayList<String> results = new ArrayList<String>();
-
- for (TableItem item : mTable.getItems()) {
- if (item.getChecked()) {
- results.add((String)item.getData());
- }
- }
-
- setResult(results);
- }
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite composite= new Composite(parent, SWT.NONE);
- composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- composite.setLayout(new GridLayout(1, true));
- composite.setFont(parent.getFont());
-
- Label label = new Label(composite, SWT.NONE);
- label.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false));
- label.setText(String.format("Select the flag values for attribute %1$s:",
- ((FlagAttributeDescriptor) getDescriptor()).getUiName()));
-
- mTable = new Table(composite, SWT.CHECK | SWT.BORDER);
- GridData data = new GridData();
- // The 60,18 hints are the ones used by AbstractElementListSelectionDialog
- data.widthHint = convertWidthInCharsToPixels(60);
- data.heightHint = convertHeightInCharsToPixels(18);
- data.grabExcessVerticalSpace = true;
- data.grabExcessHorizontalSpace = true;
- data.horizontalAlignment = GridData.FILL;
- data.verticalAlignment = GridData.FILL;
- mTable.setLayoutData(data);
-
- mTable.setHeaderVisible(false);
- final TableColumn column = new TableColumn(mTable, SWT.NONE);
-
- // List all the expected flag names and check those which are currently used
- String[] names = getPossibleValues(null);
- if (names != null) {
- for (String name : names) {
- TableItem item = new TableItem(mTable, SWT.NONE);
- item.setText(name);
- item.setData(name);
-
- boolean hasName = mCurrentSet.contains(name);
- item.setChecked(hasName);
- if (hasName) {
- mCurrentSet.remove(name);
- }
- }
- }
-
- // If there are unknown flag names currently used, display them at the end if the
- // table already checked.
- if (!mCurrentSet.isEmpty()) {
- FontDescriptor fontDesc = JFaceResources.getDialogFontDescriptor();
- fontDesc = fontDesc.withStyle(SWT.ITALIC);
- Font font = fontDesc.createFont(JFaceResources.getDialogFont().getDevice());
-
- for (String name : mCurrentSet) {
- TableItem item = new TableItem(mTable, SWT.NONE);
- item.setText(String.format("%1$s (unknown flag)", name));
- item.setData(name);
- item.setChecked(true);
- item.setFont(font);
- }
- }
-
- // Add a listener that will resize the column to the full width of the table
- // so that only one column appears in the table even if the dialog is resized.
- ControlAdapter listener = new ControlAdapter() {
- @Override
- public void controlResized(ControlEvent e) {
- Rectangle r = mTable.getClientArea();
- column.setWidth(r.width);
- }
- };
-
- mTable.addControlListener(listener);
- listener.controlResized(null /* event not used */);
-
- // Add a selection listener that will check/uncheck items when they are double-clicked
- mTable.addSelectionListener(new SelectionAdapter() {
- /** Default selection means double-click on "most" platforms */
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- if (e.item instanceof TableItem) {
- TableItem i = (TableItem) e.item;
- i.setChecked(!i.getChecked());
- }
- super.widgetDefaultSelected(e);
- }
- });
-
- Dialog.applyDialogFont(composite);
- setHelpAvailable(false);
-
- return composite;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiListAttributeNode.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiListAttributeNode.java
deleted file mode 100644
index 0fd317c1c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiListAttributeNode.java
+++ /dev/null
@@ -1,220 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.uimodel;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ListAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.TextAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.ui.SectionHelper;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.TableWrapData;
-
-/**
- * Represents an XML attribute which has possible built-in values, and can be modified by
- * an editable Combo box.
- * <p/>
- * See {@link UiTextAttributeNode} for more information.
- */
-public class UiListAttributeNode extends UiAbstractTextAttributeNode {
-
- protected Combo mCombo;
-
- public UiListAttributeNode(ListAttributeDescriptor attributeDescriptor,
- UiElementNode uiParent) {
- super(attributeDescriptor, uiParent);
- }
-
- /* (non-java doc)
- * Creates a label widget and an associated text field.
- * <p/>
- * As most other parts of the android manifest editor, this assumes the
- * parent uses a table layout with 2 columns.
- */
- @Override
- public final void createUiControl(final Composite parent, IManagedForm managedForm) {
- FormToolkit toolkit = managedForm.getToolkit();
- TextAttributeDescriptor desc = (TextAttributeDescriptor) getDescriptor();
-
- Label label = toolkit.createLabel(parent, desc.getUiName());
- label.setLayoutData(new TableWrapData(TableWrapData.LEFT, TableWrapData.MIDDLE));
- SectionHelper.addControlTooltip(label, DescriptorsUtils.formatTooltip(desc.getTooltip()));
-
- int style = SWT.DROP_DOWN;
- mCombo = new Combo(parent, style);
- TableWrapData twd = new TableWrapData(TableWrapData.FILL_GRAB, TableWrapData.MIDDLE);
- twd.maxWidth = 100;
- mCombo.setLayoutData(twd);
-
- fillCombo();
-
- setTextWidgetValue(getCurrentValue());
-
- mCombo.addModifyListener(new ModifyListener() {
- /**
- * Sent when the text is modified, whether by the user via manual
- * input or programmatic input via setText().
- */
- @Override
- public void modifyText(ModifyEvent e) {
- onComboChange();
- }
- });
-
- mCombo.addSelectionListener(new SelectionAdapter() {
- /** Sent when the text is changed from a list selection. */
- @Override
- public void widgetSelected(SelectionEvent e) {
- onComboChange();
- }
- });
-
- // Remove self-reference when the widget is disposed
- mCombo.addDisposeListener(new DisposeListener() {
- @Override
- public void widgetDisposed(DisposeEvent e) {
- mCombo = null;
- }
- });
- }
-
- protected void fillCombo() {
- String[] values = getPossibleValues(null);
-
- if (values == null) {
- AdtPlugin.log(IStatus.ERROR,
- "FrameworkResourceManager did not provide values yet for %1$s",
- getDescriptor().getXmlLocalName());
- } else {
- for (String value : values) {
- mCombo.add(value);
- }
- }
- }
-
- /**
- * Get the list values, either from the initial values set in the attribute
- * or by querying the framework resource parser.
- *
- * {@inheritDoc}
- */
- @Override
- public String[] getPossibleValues(String prefix) {
- AttributeDescriptor descriptor = getDescriptor();
- UiElementNode uiParent = getUiParent();
-
- String attr_name = descriptor.getXmlLocalName();
- String element_name = uiParent.getDescriptor().getXmlName();
-
- // FrameworkResourceManager expects a specific prefix for the attribute.
- String nsPrefix = "";
- if (SdkConstants.NS_RESOURCES.equals(descriptor.getNamespaceUri())) {
- nsPrefix = SdkConstants.ANDROID_NS_NAME + ':';
- } else if (SdkConstants.XMLNS_URI.equals(descriptor.getNamespaceUri())) {
- nsPrefix = SdkConstants.XMLNS_PREFIX;
- }
- attr_name = nsPrefix + attr_name;
-
- String[] values = null;
-
- if (descriptor instanceof ListAttributeDescriptor &&
- ((ListAttributeDescriptor) descriptor).getValues() != null) {
- // Get enum values from the descriptor
- values = ((ListAttributeDescriptor) descriptor).getValues();
- }
-
- if (values == null) {
- // or from the AndroidTargetData
- UiElementNode uiNode = getUiParent();
- AndroidXmlEditor editor = uiNode.getEditor();
- AndroidTargetData data = editor.getTargetData();
- if (data != null) {
- // get the great-grand-parent descriptor.
-
- // the parent should always exist.
- UiElementNode grandParentNode = uiParent.getUiParent();
-
- String greatGrandParentNodeName = null;
- if (grandParentNode != null) {
- UiElementNode greatGrandParentNode = grandParentNode.getUiParent();
- if (greatGrandParentNode != null) {
- greatGrandParentNodeName =
- greatGrandParentNode.getDescriptor().getXmlName();
- }
- }
-
- values = data.getAttributeValues(element_name, attr_name, greatGrandParentNodeName);
- }
- }
-
- return values;
- }
-
- @Override
- public String getTextWidgetValue() {
- if (mCombo != null) {
- return mCombo.getText();
- }
-
- return null;
- }
-
- @Override
- public final boolean isValid() {
- return mCombo != null;
- }
-
- @Override
- public void setTextWidgetValue(String value) {
- if (mCombo != null) {
- mCombo.setText(value);
- }
- }
-
- /**
- * Handles Combo change, either from text edit or from selection change.
- * <p/>
- * Simply mark the attribute as dirty if it really changed.
- * The container SectionPart will collect these flag and manage them.
- */
- private void onComboChange() {
- if (!isInInternalTextModification() &&
- !isDirty() &&
- mCombo != null &&
- getCurrentValue() != null &&
- !mCombo.getText().equals(getCurrentValue())) {
- setDirty(true);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiResourceAttributeNode.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiResourceAttributeNode.java
deleted file mode 100644
index eb51d3f86..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiResourceAttributeNode.java
+++ /dev/null
@@ -1,523 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.uimodel;
-
-import static com.android.SdkConstants.ANDROID_PKG;
-import static com.android.SdkConstants.ANDROID_PREFIX;
-import static com.android.SdkConstants.ANDROID_THEME_PREFIX;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ATTR_LAYOUT;
-import static com.android.SdkConstants.ATTR_STYLE;
-import static com.android.SdkConstants.PREFIX_RESOURCE_REF;
-import static com.android.SdkConstants.PREFIX_THEME_REF;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.IAttributeInfo;
-import com.android.ide.common.api.IAttributeInfo.Format;
-import com.android.ide.common.resources.ResourceItem;
-import com.android.ide.common.resources.ResourceRepository;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.TextAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.ui.SectionHelper;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.internal.ui.ReferenceChooserDialog;
-import com.android.ide.eclipse.adt.internal.ui.ResourceChooser;
-import com.android.resources.ResourceType;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.TableWrapData;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.EnumSet;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * Represents an XML attribute for a resource that can be modified using a simple text field or
- * a dialog to choose an existing resource.
- * <p/>
- * It can be configured to represent any kind of resource, by providing the desired
- * {@link ResourceType} in the constructor.
- * <p/>
- * See {@link UiTextAttributeNode} for more information.
- */
-public class UiResourceAttributeNode extends UiTextAttributeNode {
- private ResourceType mType;
-
- /**
- * Creates a new {@linkplain UiResourceAttributeNode}
- *
- * @param type the associated resource type
- * @param attributeDescriptor the attribute descriptor for this attribute
- * @param uiParent the parent ui node, if any
- */
- public UiResourceAttributeNode(ResourceType type,
- AttributeDescriptor attributeDescriptor, UiElementNode uiParent) {
- super(attributeDescriptor, uiParent);
-
- mType = type;
- }
-
- /* (non-java doc)
- * Creates a label widget and an associated text field.
- * <p/>
- * As most other parts of the android manifest editor, this assumes the
- * parent uses a table layout with 2 columns.
- */
- @Override
- public void createUiControl(final Composite parent, IManagedForm managedForm) {
- setManagedForm(managedForm);
- FormToolkit toolkit = managedForm.getToolkit();
- TextAttributeDescriptor desc = (TextAttributeDescriptor) getDescriptor();
-
- Label label = toolkit.createLabel(parent, desc.getUiName());
- label.setLayoutData(new TableWrapData(TableWrapData.LEFT, TableWrapData.MIDDLE));
- SectionHelper.addControlTooltip(label, DescriptorsUtils.formatTooltip(desc.getTooltip()));
-
- Composite composite = toolkit.createComposite(parent);
- composite.setLayoutData(new TableWrapData(TableWrapData.FILL_GRAB, TableWrapData.MIDDLE));
- GridLayout gl = new GridLayout(2, false);
- gl.marginHeight = gl.marginWidth = 0;
- composite.setLayout(gl);
- // Fixes missing text borders under GTK... also requires adding a 1-pixel margin
- // for the text field below
- toolkit.paintBordersFor(composite);
-
- final Text text = toolkit.createText(composite, getCurrentValue());
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalIndent = 1; // Needed by the fixed composite borders under GTK
- text.setLayoutData(gd);
- Button browseButton = toolkit.createButton(composite, "Browse...", SWT.PUSH);
-
- setTextWidget(text);
-
- // TODO Add a validator using onAddModifyListener
-
- browseButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- String result = showDialog(parent.getShell(), text.getText().trim());
- if (result != null) {
- text.setText(result);
- }
- }
- });
- }
-
- /**
- * Shows a dialog letting the user choose a set of enum, and returns a
- * string containing the result.
- *
- * @param shell the parent shell
- * @param currentValue an initial value, if any
- * @return the chosen string, or null
- */
- @Nullable
- public String showDialog(@NonNull Shell shell, @Nullable String currentValue) {
- // we need to get the project of the file being edited.
- UiElementNode uiNode = getUiParent();
- AndroidXmlEditor editor = uiNode.getEditor();
- IProject project = editor.getProject();
- if (project != null) {
- // get the resource repository for this project and the system resources.
- ResourceRepository projectRepository =
- ResourceManager.getInstance().getProjectResources(project);
-
- if (mType != null) {
- // get the Target Data to get the system resources
- AndroidTargetData data = editor.getTargetData();
- ResourceChooser dlg = ResourceChooser.create(project, mType, data, shell)
- .setCurrentResource(currentValue);
- if (dlg.open() == Window.OK) {
- return dlg.getCurrentResource();
- }
- } else {
- ReferenceChooserDialog dlg = new ReferenceChooserDialog(
- project,
- projectRepository,
- shell);
-
- dlg.setCurrentResource(currentValue);
-
- if (dlg.open() == Window.OK) {
- return dlg.getCurrentResource();
- }
- }
- }
-
- return null;
- }
-
- /**
- * Gets all the values one could use to auto-complete a "resource" value in an XML
- * content assist.
- * <p/>
- * Typically the user is editing the value of an attribute in a resource XML, e.g.
- * <pre> "&lt;Button android:test="@string/my_[caret]_string..." </pre>
- * <p/>
- *
- * "prefix" is the value that the user has typed so far (or more exactly whatever is on the
- * left side of the insertion point). In the example above it would be "@style/my_".
- * <p/>
- *
- * To avoid a huge long list of values, the completion works on two levels:
- * <ul>
- * <li> If a resource type as been typed so far (e.g. "@style/"), then limit the values to
- * the possible completions that match this type.
- * <li> If no resource type as been typed so far, then return the various types that could be
- * completed. So if the project has only strings and layouts resources, for example,
- * the returned list will only include "@string/" and "@layout/".
- * </ul>
- *
- * Finally if anywhere in the string we find the special token "android:", we use the
- * current framework system resources rather than the project resources.
- * This works for both "@android:style/foo" and "@style/android:foo" conventions even though
- * the reconstructed name will always be of the former form.
- *
- * Note that "android:" here is a keyword specific to Android resources and should not be
- * mixed with an XML namespace for an XML attribute name.
- */
- @Override
- public String[] getPossibleValues(String prefix) {
- return computeResourceStringMatches(getUiParent().getEditor(), getDescriptor(), prefix);
- }
-
- /**
- * Computes the set of resource string matches for a given resource prefix in a given editor
- *
- * @param editor the editor context
- * @param descriptor the attribute descriptor, if any
- * @param prefix the prefix, if any
- * @return an array of resource string matches
- */
- @Nullable
- public static String[] computeResourceStringMatches(
- @NonNull AndroidXmlEditor editor,
- @Nullable AttributeDescriptor descriptor,
- @Nullable String prefix) {
-
- if (prefix == null || !prefix.regionMatches(1, ANDROID_PKG, 0, ANDROID_PKG.length())) {
- IProject project = editor.getProject();
- if (project != null) {
- // get the resource repository for this project and the system resources.
- ResourceManager resourceManager = ResourceManager.getInstance();
- ResourceRepository repository = resourceManager.getProjectResources(project);
-
- List<IProject> libraries = null;
- ProjectState projectState = Sdk.getProjectState(project);
- if (projectState != null) {
- libraries = projectState.getFullLibraryProjects();
- }
-
- String[] projectMatches = computeResourceStringMatches(descriptor, prefix,
- repository, false);
-
- if (libraries == null || libraries.isEmpty()) {
- return projectMatches;
- }
-
- // Also compute matches for each of the libraries, and combine them
- Set<String> matches = new HashSet<String>(200);
- for (String s : projectMatches) {
- matches.add(s);
- }
-
- for (IProject library : libraries) {
- repository = resourceManager.getProjectResources(library);
- projectMatches = computeResourceStringMatches(descriptor, prefix,
- repository, false);
- for (String s : projectMatches) {
- matches.add(s);
- }
- }
-
- String[] sorted = matches.toArray(new String[matches.size()]);
- Arrays.sort(sorted);
- return sorted;
- }
- } else {
- // If there's a prefix with "android:" in it, use the system resources
- // Non-public framework resources are filtered out later.
- AndroidTargetData data = editor.getTargetData();
- if (data != null) {
- ResourceRepository repository = data.getFrameworkResources();
- return computeResourceStringMatches(descriptor, prefix, repository, true);
- }
- }
-
- return null;
- }
-
- /**
- * Computes the set of resource string matches for a given prefix and a
- * given resource repository
- *
- * @param attributeDescriptor the attribute descriptor, if any
- * @param prefix the prefix, if any
- * @param repository the repository to seaerch in
- * @param isSystem if true, the repository contains framework repository,
- * otherwise it contains project repositories
- * @return an array of resource string matches
- */
- @NonNull
- public static String[] computeResourceStringMatches(
- @Nullable AttributeDescriptor attributeDescriptor,
- @Nullable String prefix,
- @NonNull ResourceRepository repository,
- boolean isSystem) {
- // Get list of potential resource types, either specific to this project
- // or the generic list.
- Collection<ResourceType> resTypes = (repository != null) ?
- repository.getAvailableResourceTypes() :
- EnumSet.allOf(ResourceType.class);
-
- // Get the type name from the prefix, if any. It's any word before the / if there's one
- String typeName = null;
- if (prefix != null) {
- Matcher m = Pattern.compile(".*?([a-z]+)/.*").matcher(prefix); //$NON-NLS-1$
- if (m.matches()) {
- typeName = m.group(1);
- }
- }
-
- // Now collect results
- List<String> results = new ArrayList<String>();
-
- if (typeName == null) {
- // This prefix does not have a / in it, so the resource string is either empty
- // or does not have the resource type in it. Simply offer the list of potential
- // resource types.
- if (prefix != null && prefix.startsWith(PREFIX_THEME_REF)) {
- results.add(ANDROID_THEME_PREFIX + ResourceType.ATTR.getName() + '/');
- if (resTypes.contains(ResourceType.ATTR)
- || resTypes.contains(ResourceType.STYLE)) {
- results.add(PREFIX_THEME_REF + ResourceType.ATTR.getName() + '/');
- if (prefix != null && prefix.startsWith(ANDROID_THEME_PREFIX)) {
- // including attr isn't required
- for (ResourceItem item : repository.getResourceItemsOfType(
- ResourceType.ATTR)) {
- results.add(ANDROID_THEME_PREFIX + item.getName());
- }
- }
- }
- return results.toArray(new String[results.size()]);
- }
-
- for (ResourceType resType : resTypes) {
- if (isSystem) {
- results.add(ANDROID_PREFIX + resType.getName() + '/');
- } else {
- results.add('@' + resType.getName() + '/');
- }
- if (resType == ResourceType.ID) {
- // Also offer the + version to create an id from scratch
- results.add("@+" + resType.getName() + '/'); //$NON-NLS-1$
- }
- }
-
- // Also add in @android: prefix to completion such that if user has typed
- // "@an" we offer to complete it.
- if (prefix == null ||
- ANDROID_PKG.regionMatches(0, prefix, 1, prefix.length() - 1)) {
- results.add(ANDROID_PREFIX);
- }
- } else if (repository != null) {
- // We have a style name and a repository. Find all resources that match this
- // type and recreate suggestions out of them.
-
- String initial = prefix != null && prefix.startsWith(PREFIX_THEME_REF)
- ? PREFIX_THEME_REF : PREFIX_RESOURCE_REF;
- ResourceType resType = ResourceType.getEnum(typeName);
- if (resType != null) {
- StringBuilder sb = new StringBuilder();
- sb.append(initial);
- if (prefix != null && prefix.indexOf('+') >= 0) {
- sb.append('+');
- }
-
- if (isSystem) {
- sb.append(ANDROID_PKG).append(':');
- }
-
- sb.append(typeName).append('/');
- String base = sb.toString();
-
- for (ResourceItem item : repository.getResourceItemsOfType(resType)) {
- results.add(base + item.getName());
- }
-
- if (!isSystem && resType == ResourceType.ATTR) {
- for (ResourceItem item : repository.getResourceItemsOfType(
- ResourceType.STYLE)) {
- results.add(base + item.getName());
- }
- }
- }
- }
-
- if (attributeDescriptor != null) {
- sortAttributeChoices(attributeDescriptor, results);
- } else {
- Collections.sort(results);
- }
-
- return results.toArray(new String[results.size()]);
- }
-
- /**
- * Attempts to sort the attribute values to bubble up the most likely choices to
- * the top.
- * <p>
- * For example, if you are editing a style attribute, it's likely that among the
- * resource values you would rather see @style or @android than @string.
- * @param descriptor the descriptor that the resource values are being completed for,
- * used to prioritize some of the resource types
- * @param choices the set of string resource values
- */
- public static void sortAttributeChoices(AttributeDescriptor descriptor,
- List<String> choices) {
- final IAttributeInfo attributeInfo = descriptor.getAttributeInfo();
- Collections.sort(choices, new Comparator<String>() {
- @Override
- public int compare(String s1, String s2) {
- int compare = score(attributeInfo, s1) - score(attributeInfo, s2);
- if (compare == 0) {
- // Sort alphabetically as a fallback
- compare = s1.compareToIgnoreCase(s2);
- }
- return compare;
- }
- });
- }
-
- /** Compute a suitable sorting score for the given */
- private static final int score(IAttributeInfo attributeInfo, String value) {
- if (value.equals(ANDROID_PREFIX)) {
- return -1;
- }
-
- for (Format format : attributeInfo.getFormats()) {
- String type = null;
- switch (format) {
- case BOOLEAN:
- type = "bool"; //$NON-NLS-1$
- break;
- case COLOR:
- type = "color"; //$NON-NLS-1$
- break;
- case DIMENSION:
- type = "dimen"; //$NON-NLS-1$
- break;
- case INTEGER:
- type = "integer"; //$NON-NLS-1$
- break;
- case STRING:
- type = "string"; //$NON-NLS-1$
- break;
- // default: REFERENCE, FLAG, ENUM, etc - don't have type info about individual
- // elements to help make a decision
- }
-
- if (type != null) {
- if (value.startsWith(PREFIX_RESOURCE_REF)) {
- if (value.startsWith(PREFIX_RESOURCE_REF + type + '/')) {
- return -2;
- }
-
- if (value.startsWith(ANDROID_PREFIX + type + '/')) {
- return -2;
- }
- }
- if (value.startsWith(PREFIX_THEME_REF)) {
- if (value.startsWith(PREFIX_THEME_REF + type + '/')) {
- return -2;
- }
-
- if (value.startsWith(ANDROID_THEME_PREFIX + type + '/')) {
- return -2;
- }
- }
- }
- }
-
- // Handle a few more cases not covered by the Format metadata check
- String type = null;
-
- String attribute = attributeInfo.getName();
- if (attribute.equals(ATTR_ID)) {
- type = "id"; //$NON-NLS-1$
- } else if (attribute.equals(ATTR_STYLE)) {
- type = "style"; //$NON-NLS-1$
- } else if (attribute.equals(ATTR_LAYOUT)) {
- type = "layout"; //$NON-NLS-1$
- } else if (attribute.equals("drawable")) { //$NON-NLS-1$
- type = "drawable"; //$NON-NLS-1$
- } else if (attribute.equals("entries")) { //$NON-NLS-1$
- // Spinner
- type = "array"; //$NON-NLS-1$
- }
-
- if (type != null) {
- if (value.startsWith(PREFIX_RESOURCE_REF)) {
- if (value.startsWith(PREFIX_RESOURCE_REF + type + '/')) {
- return -2;
- }
-
- if (value.startsWith(ANDROID_PREFIX + type + '/')) {
- return -2;
- }
- }
- if (value.startsWith(PREFIX_THEME_REF)) {
- if (value.startsWith(PREFIX_THEME_REF + type + '/')) {
- return -2;
- }
-
- if (value.startsWith(ANDROID_THEME_PREFIX + type + '/')) {
- return -2;
- }
- }
- }
-
- return 0;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiSeparatorAttributeNode.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiSeparatorAttributeNode.java
deleted file mode 100644
index 3d2006299..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiSeparatorAttributeNode.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.uimodel;
-
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.SeparatorAttributeDescriptor;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.widgets.FormToolkit;
-import org.eclipse.ui.forms.widgets.TableWrapData;
-import org.eclipse.ui.forms.widgets.TableWrapLayout;
-import org.w3c.dom.Node;
-
-/**
- * {@link UiSeparatorAttributeNode} does not represent any real attribute.
- * <p/>
- * It is used to separate groups of attributes visually.
- */
-public class UiSeparatorAttributeNode extends UiAttributeNode {
-
- /** Creates a new {@link UiAttributeNode} linked to a specific {@link AttributeDescriptor} */
- public UiSeparatorAttributeNode(SeparatorAttributeDescriptor attrDesc,
- UiElementNode uiParent) {
- super(attrDesc, uiParent);
- }
-
- /** Returns the current value of the node. */
- @Override
- public String getCurrentValue() {
- // There is no value here.
- return null;
- }
-
- /**
- * Sets whether the attribute is dirty and also notifies the editor some part's dirty
- * flag as changed.
- * <p/>
- * Subclasses should set the to true as a result of user interaction with the widgets in
- * the section and then should set to false when the commit() method completed.
- */
- @Override
- public void setDirty(boolean isDirty) {
- // This is never dirty.
- }
-
- /**
- * Called once by the parent user interface to creates the necessary
- * user interface to edit this attribute.
- * <p/>
- * This method can be called more than once in the life cycle of an UI node,
- * typically when the UI is part of a master-detail tree, as pages are swapped.
- *
- * @param parent The composite where to create the user interface.
- * @param managedForm The managed form owning this part.
- */
- @Override
- public void createUiControl(Composite parent, IManagedForm managedForm) {
- FormToolkit toolkit = managedForm.getToolkit();
- Composite row = toolkit.createComposite(parent);
-
- TableWrapData twd = new TableWrapData(TableWrapData.FILL_GRAB);
- if (parent.getLayout() instanceof TableWrapLayout) {
- twd.colspan = ((TableWrapLayout) parent.getLayout()).numColumns;
- }
- row.setLayoutData(twd);
- row.setLayout(new GridLayout(3, false /* equal width */));
-
- Label sep = toolkit.createSeparator(row, SWT.HORIZONTAL);
- GridData gd = new GridData(SWT.LEFT, SWT.CENTER, false, false);
- gd.widthHint = 16;
- sep.setLayoutData(gd);
-
- Label label = toolkit.createLabel(row, getDescriptor().getXmlLocalName());
- label.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false));
-
- sep = toolkit.createSeparator(row, SWT.HORIZONTAL);
- sep.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
- }
-
- /**
- * No completion values for this UI attribute.
- *
- * {@inheritDoc}
- */
- @Override
- public String[] getPossibleValues(String prefix) {
- return null;
- }
-
- /**
- * Called when the XML is being loaded or has changed to
- * update the value held by this user interface attribute node.
- * <p/>
- * The XML Node <em>may</em> be null, which denotes that the attribute is not
- * specified in the XML model. In general, this means the "default" value of the
- * attribute should be used.
- * <p/>
- * The caller doesn't really know if attributes have changed,
- * so it will call this to refresh the attribute anyway. It's up to the
- * UI implementation to minimize refreshes.
- *
- * @param xml_attribute_node
- */
- @Override
- public void updateValue(Node xml_attribute_node) {
- // No value to update.
- }
-
- /**
- * Called by the user interface when the editor is saved or its state changed
- * and the modified attributes must be committed (i.e. written) to the XML model.
- * <p/>
- * Important behaviors:
- * <ul>
- * <li>The caller *must* have called IStructuredModel.aboutToChangeModel before.
- * The implemented methods must assume it is safe to modify the XML model.
- * <li>On success, the implementation *must* call setDirty(false).
- * <li>On failure, the implementation can fail with an exception, which
- * is trapped and logged by the caller, or do nothing, whichever is more
- * appropriate.
- * </ul>
- */
- @Override
- public void commit() {
- // No value to commit.
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiTextAttributeNode.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiTextAttributeNode.java
deleted file mode 100644
index 504ac3122..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiTextAttributeNode.java
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.uimodel;
-
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.TextAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.ui.SectionHelper;
-
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.widgets.TableWrapData;
-
-/**
- * Represents an XML attribute in that can be modified using a simple text field
- * in the XML editor's user interface.
- * <p/>
- * The XML attribute has no default value. When unset, the text field is blank.
- * When updating the XML, if the field is empty, the attribute will be removed
- * from the XML element.
- * <p/>
- * See {@link UiAttributeNode} for more information.
- */
-public class UiTextAttributeNode extends UiAbstractTextAttributeNode {
-
- /** Text field */
- private Text mText;
- /** The managed form, set only once createUiControl has been called. */
- private IManagedForm mManagedForm;
-
- public UiTextAttributeNode(AttributeDescriptor attributeDescriptor, UiElementNode uiParent) {
- super(attributeDescriptor, uiParent);
- }
-
- /* (non-java doc)
- * Creates a label widget and an associated text field.
- * <p/>
- * As most other parts of the android manifest editor, this assumes the
- * parent uses a table layout with 2 columns.
- */
- @Override
- public void createUiControl(Composite parent, IManagedForm managedForm) {
- setManagedForm(managedForm);
- TextAttributeDescriptor desc = (TextAttributeDescriptor) getDescriptor();
- Text text = SectionHelper.createLabelAndText(parent, managedForm.getToolkit(),
- desc.getUiName(), getCurrentValue(),
- DescriptorsUtils.formatTooltip(desc.getTooltip()));
-
- setTextWidget(text);
- }
-
- /**
- * No completion values for this UI attribute.
- *
- * {@inheritDoc}
- */
- @Override
- public String[] getPossibleValues(String prefix) {
- return null;
- }
-
- /**
- * Sets the internal managed form.
- * This is usually set by createUiControl.
- */
- protected void setManagedForm(IManagedForm managedForm) {
- mManagedForm = managedForm;
- }
-
- /**
- * @return The managed form, set only once createUiControl has been called.
- */
- protected IManagedForm getManagedForm() {
- return mManagedForm;
- }
-
- /* (non-java doc)
- * Returns if the attribute node is valid, and its UI has been created.
- */
- @Override
- public boolean isValid() {
- return mText != null;
- }
-
- @Override
- public String getTextWidgetValue() {
- if (mText != null) {
- return mText.getText();
- }
-
- return null;
- }
-
- @Override
- public void setTextWidgetValue(String value) {
- if (mText != null) {
- mText.setText(value);
- }
- }
-
- /**
- * Sets the Text widget object, and prepares it to handle modification and synchronization
- * with the XML node.
- * @param textWidget
- */
- protected final void setTextWidget(Text textWidget) {
- mText = textWidget;
-
- if (textWidget != null) {
- // Sets the with hint for the text field. Derived classes can always override it.
- // This helps the grid layout to resize correctly on smaller screen sizes.
- Object data = textWidget.getLayoutData();
- if (data == null) {
- } else if (data instanceof GridData) {
- ((GridData)data).widthHint = AndroidXmlEditor.TEXT_WIDTH_HINT;
- } else if (data instanceof TableWrapData) {
- ((TableWrapData)data).maxWidth = 100;
- }
-
- mText.addModifyListener(new ModifyListener() {
- /**
- * Sent when the text is modified, whether by the user via manual
- * input or programmatic input via setText().
- * <p/>
- * Simply mark the attribute as dirty if it really changed.
- * The container SectionPart will collect these flag and manage them.
- */
- @Override
- public void modifyText(ModifyEvent e) {
- if (!isInInternalTextModification() &&
- !isDirty() &&
- mText != null &&
- getCurrentValue() != null &&
- !mText.getText().equals(getCurrentValue())) {
- setDirty(true);
- }
- }
- });
-
- // Remove self-reference when the widget is disposed
- mText.addDisposeListener(new DisposeListener() {
- @Override
- public void widgetDisposed(DisposeEvent e) {
- mText = null;
- }
- });
- }
-
- onAddValidators(mText);
- }
-
- /**
- * Called after the text widget as been created.
- * <p/>
- * Derived classes typically want to:
- * <li> Create a new {@link ModifyListener} and attach it to the given {@link Text} widget.
- * <li> In the modify listener, call getManagedForm().getMessageManager().addMessage()
- * and getManagedForm().getMessageManager().removeMessage() as necessary.
- * <li> Call removeMessage in a new text.addDisposeListener.
- * <li> Call the validator once to setup the initial messages as needed.
- * <p/>
- * The base implementation does nothing.
- *
- * @param text The {@link Text} widget to validate.
- */
- protected void onAddValidators(Text text) {
- }
-
- /**
- * Returns the text widget.
- */
- protected final Text getTextWidget() {
- return mText;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiTextValueNode.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiTextValueNode.java
deleted file mode 100644
index 33fa9fc99..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/uimodel/UiTextValueNode.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.uimodel;
-
-import com.android.ide.eclipse.adt.internal.editors.descriptors.TextValueDescriptor;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-import org.w3c.dom.Text;
-
-/**
- * Represents an XML element value in that can be modified using a simple text field
- * in the XML editor's user interface.
- */
-public class UiTextValueNode extends UiTextAttributeNode {
-
- public UiTextValueNode(TextValueDescriptor attributeDescriptor, UiElementNode uiParent) {
- super(attributeDescriptor, uiParent);
- }
-
- /**
- * Updates the current text field's value when the XML has changed.
- * <p/>
- * The caller doesn't really know if value of the element has changed,
- * so it will call this to refresh the value anyway. The value
- * is only set if it has changed.
- * <p/>
- * This also resets the "dirty" flag.
- */
- @Override
- public void updateValue(Node xml_attribute_node) {
- setCurrentValue(DEFAULT_VALUE);
-
- // The argument xml_attribute_node is not used here. It should always be
- // null since this is not an attribute. What we want is the "text value" of
- // the parent element, which is actually the first text node of the element.
-
- UiElementNode parent = getUiParent();
- if (parent != null) {
- Node xml_node = parent.getXmlNode();
- if (xml_node != null) {
- for (Node xml_child = xml_node.getFirstChild();
- xml_child != null;
- xml_child = xml_child.getNextSibling()) {
- if (xml_child.getNodeType() == Node.TEXT_NODE) {
- setCurrentValue(xml_child.getNodeValue());
- break;
- }
- }
- }
- }
-
- if (isValid() && !getTextWidgetValue().equals(getCurrentValue())) {
- try {
- setInInternalTextModification(true);
- setTextWidgetValue(getCurrentValue());
- setDirty(false);
- } finally {
- setInInternalTextModification(false);
- }
- }
- }
-
- /* (non-java doc)
- * Called by the user interface when the editor is saved or its state changed
- * and the modified "attributes" must be committed (i.e. written) to the XML model.
- */
- @Override
- public void commit() {
- UiElementNode parent = getUiParent();
- if (parent != null && isValid() && isDirty()) {
- // Get (or create) the underlying XML element node that contains the value.
- Node element = parent.prepareCommit();
- if (element != null) {
- String value = getTextWidgetValue();
-
- // Try to find an existing text child to update.
- boolean updated = false;
-
- for (Node xml_child = element.getFirstChild();
- xml_child != null;
- xml_child = xml_child.getNextSibling()) {
- if (xml_child.getNodeType() == Node.TEXT_NODE) {
- xml_child.setNodeValue(value);
- updated = true;
- break;
- }
- }
-
- // If we didn't find a text child to update, we need to create one.
- if (!updated) {
- Document doc = element.getOwnerDocument();
- if (doc != null) {
- Text text = doc.createTextNode(value);
- element.appendChild(text);
- }
- }
-
- setCurrentValue(value);
- }
- }
- setDirty(false);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/ValuesContentAssist.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/ValuesContentAssist.java
deleted file mode 100644
index d0ee92ca1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/ValuesContentAssist.java
+++ /dev/null
@@ -1,242 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.values;
-
-import static com.android.SdkConstants.ANDROID_NS_NAME_PREFIX;
-import static com.android.SdkConstants.ANDROID_PREFIX;
-import static com.android.SdkConstants.ATTR_NAME;
-import static com.android.SdkConstants.ATTR_TYPE;
-import static com.android.SdkConstants.PREFIX_RESOURCE_REF;
-import static com.android.SdkConstants.TAG_ITEM;
-import static com.android.SdkConstants.TAG_STYLE;
-import static com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor.ATTRIBUTE_ICON_FILENAME;
-import static com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData.DESCRIPTOR_LAYOUT;
-
-import com.android.annotations.VisibleForTesting;
-import com.android.ide.eclipse.adt.internal.editors.AndroidContentAssist;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DocumentDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.IDescriptorProvider;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.SeparatorAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiResourceAttributeNode;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-
-import org.eclipse.jface.text.contentassist.CompletionProposal;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Content Assist Processor for /res/values and /res/drawable XML files
- * <p>
- * Further enhancements:
- * <ul>
- * <li> Complete prefixes in the style element itself for the name attribute
- * <li> Complete parent names
- * </ul>
- */
-@VisibleForTesting
-public class ValuesContentAssist extends AndroidContentAssist {
-
- /**
- * Constructor for ResourcesContentAssist
- */
- public ValuesContentAssist() {
- super(AndroidTargetData.DESCRIPTOR_RESOURCES);
- }
-
- @Override
- protected boolean computeAttributeValues(List<ICompletionProposal> proposals, int offset,
- String parentTagName, String attributeName, Node node, String wordPrefix,
- boolean skipEndTag, int replaceLength) {
- super.computeAttributeValues(proposals, offset, parentTagName, attributeName, node,
- wordPrefix, skipEndTag, replaceLength);
-
- if (parentTagName.equals(TAG_ITEM) && ATTR_NAME.equals(attributeName)) {
-
- // Special case: the user is code completing inside
- // <style><item name="^"/></style>
- // In this case, ALL attributes are valid so we need to synthesize
- // a choice list from all the layout descriptors
-
- // Add in android: as a completion item?
- if (startsWith(ANDROID_NS_NAME_PREFIX, wordPrefix)) {
- proposals.add(new CompletionProposal(ANDROID_NS_NAME_PREFIX,
- offset - wordPrefix.length(), // replacementOffset
- wordPrefix.length() + replaceLength, // replacementLength
- ANDROID_NS_NAME_PREFIX.length(), // cursorPosition
- IconFactory.getInstance().getIcon(ATTRIBUTE_ICON_FILENAME),
- null, null, null));
- }
-
-
- String attributePrefix = wordPrefix;
- if (startsWith(attributePrefix, ANDROID_NS_NAME_PREFIX)) {
- attributePrefix = attributePrefix.substring(ANDROID_NS_NAME_PREFIX.length());
- }
-
- AndroidTargetData data = mEditor.getTargetData();
- if (data != null) {
- IDescriptorProvider descriptorProvider =
- data.getDescriptorProvider(
- AndroidTargetData.DESCRIPTOR_LAYOUT);
- if (descriptorProvider != null) {
- ElementDescriptor[] rootElementDescriptors =
- descriptorProvider.getRootElementDescriptors();
- Map<String, AttributeDescriptor> matches =
- new HashMap<String, AttributeDescriptor>(180);
- for (ElementDescriptor elementDesc : rootElementDescriptors) {
- for (AttributeDescriptor desc : elementDesc.getAttributes()) {
- if (desc instanceof SeparatorAttributeDescriptor) {
- continue;
- }
- String name = desc.getXmlLocalName();
- if (startsWith(name, attributePrefix)) {
- matches.put(name, desc);
- }
- }
- }
-
- List<AttributeDescriptor> sorted =
- new ArrayList<AttributeDescriptor>(matches.size());
- sorted.addAll(matches.values());
- Collections.sort(sorted);
- char needTag = 0;
- addMatchingProposals(proposals, sorted.toArray(), offset, node, wordPrefix,
- needTag, true /* isAttribute */, false /* isNew */,
- skipEndTag /* skipEndTag */, replaceLength);
- return true;
- }
- }
- }
-
- return false;
- }
-
- @Override
- protected void computeTextValues(List<ICompletionProposal> proposals, int offset,
- Node parentNode, Node currentNode, UiElementNode uiParent,
- String prefix) {
- super.computeTextValues(proposals, offset, parentNode, currentNode, uiParent,
- prefix);
-
- if (parentNode.getNodeName().equals(TAG_ITEM) &&
- parentNode.getParentNode() != null &&
- TAG_STYLE.equals(parentNode.getParentNode().getNodeName())) {
-
- // Special case: the user is code completing inside
- // <style><item name="android:foo"/>|</style>
- // In this case, we need to find the right AttributeDescriptor
- // for the given attribute and offer its values
-
- AndroidTargetData data = mEditor.getTargetData();
- if (data != null) {
- IDescriptorProvider descriptorProvider =
- data.getDescriptorProvider(DESCRIPTOR_LAYOUT);
- if (descriptorProvider != null) {
-
- Element element = (Element) parentNode;
- String attrName = element.getAttribute(ATTR_NAME);
- int pos = attrName.indexOf(':');
- if (pos >= 0) {
- attrName = attrName.substring(pos + 1);
- }
-
- // Search for an attribute match
- ElementDescriptor[] rootElementDescriptors =
- descriptorProvider.getRootElementDescriptors();
- for (ElementDescriptor elementDesc : rootElementDescriptors) {
- for (AttributeDescriptor desc : elementDesc.getAttributes()) {
- if (desc.getXmlLocalName().equals(attrName)) {
- // Make a ui parent node such that we can attach our
- // newfound attribute node to something (the code we delegate
- // to for looking up attribute completions will look at the
- // parent node and ask for its editor etc.)
- if (uiParent == null) {
- DocumentDescriptor documentDescriptor =
- data.getLayoutDescriptors().getDescriptor();
- uiParent = documentDescriptor.createUiNode();
- uiParent.setEditor(mEditor);
- }
-
- UiAttributeNode currAttrNode = desc.createUiNode(uiParent);
- AttribInfo attrInfo = new AttribInfo();
- Object[] values = getAttributeValueChoices(currAttrNode, attrInfo,
- prefix);
- char needTag = attrInfo.needTag;
- if (attrInfo.correctedPrefix != null) {
- prefix = attrInfo.correctedPrefix;
- }
- boolean isAttribute = true;
- boolean isNew = false;
- int replaceLength = computeTextReplaceLength(currentNode, offset);
- addMatchingProposals(proposals, values, offset, currentNode,
- prefix, needTag, isAttribute, isNew,
- false /* skipEndTag */, replaceLength);
- return;
- }
- }
- }
- }
- }
- }
-
- if (parentNode.getNodeName().equals(TAG_ITEM)) {
- // Completing text content inside an <item> tag: offer @resource completion.
- if (prefix.startsWith(PREFIX_RESOURCE_REF) || prefix.trim().length() == 0) {
- String[] choices = UiResourceAttributeNode.computeResourceStringMatches(
- mEditor, null /*attributeDescriptor*/, prefix);
- if (choices == null || choices.length == 0) {
- return;
- }
-
- // If the parent item tag specifies a type, filter the results
- Node typeNode = parentNode.getAttributes().getNamedItem(ATTR_TYPE);
- if (typeNode != null) {
- String value = typeNode.getNodeValue();
- List<String> filtered = new ArrayList<String>();
- for (String s : choices) {
- if (s.startsWith(ANDROID_PREFIX) ||
- s.startsWith(PREFIX_RESOURCE_REF+ value)) {
- filtered.add(s);
- }
- }
- if (filtered.size() > 0) {
- choices = filtered.toArray(new String[filtered.size()]);
- }
- }
-
- int replaceLength = computeTextReplaceLength(currentNode, offset);
- addMatchingProposals(proposals, choices, offset, currentNode,
- prefix, (char) 0 /*needTag*/, true /* isAttribute */, false /*isNew*/,
- false /* skipEndTag*/,
- replaceLength);
-
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/ValuesEditorDelegate.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/ValuesEditorDelegate.java
deleted file mode 100644
index 10f105f85..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/ValuesEditorDelegate.java
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.values;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlDelegate;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.values.descriptors.ValuesDescriptors;
-import com.android.resources.ResourceFolderType;
-import com.android.xml.AndroidXPathFactory;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.ui.PartInitException;
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-
-import javax.xml.xpath.XPath;
-import javax.xml.xpath.XPathConstants;
-import javax.xml.xpath.XPathExpressionException;
-
-/**
- * Multi-page form editor for /res/values XML files.
- */
-public class ValuesEditorDelegate extends CommonXmlDelegate {
-
- public static class Creator implements IDelegateCreator {
- @Override
- @SuppressWarnings("unchecked")
- public ValuesEditorDelegate createForFile(
- @NonNull CommonXmlEditor delegator,
- @Nullable ResourceFolderType type) {
- if (ResourceFolderType.VALUES == type) {
- return new ValuesEditorDelegate(delegator);
- }
-
- return null;
- }
- }
-
- /**
- * Old standalone-editor ID.
- * Use {@link CommonXmlEditor#ID} instead.
- */
- public static final String LEGACY_EDITOR_ID =
- AdtConstants.EDITORS_NAMESPACE + ".resources.ResourcesEditor"; //$NON-NLS-1$
-
-
- /**
- * Creates the form editor for resources XML files.
- */
- private ValuesEditorDelegate(CommonXmlEditor editor) {
- super(editor, new ValuesContentAssist());
- editor.addDefaultTargetListener();
- }
-
- // ---- Base Class Overrides ----
-
- /**
- * Create the various form pages.
- */
- @Override
- public void delegateCreateFormPages() {
- try {
- getEditor().addPage(new ValuesTreePage(getEditor()));
- } catch (PartInitException e) {
- AdtPlugin.log(IStatus.ERROR, "Error creating nested page"); //$NON-NLS-1$
- AdtPlugin.getDefault().getLog().log(e.getStatus());
- }
- }
-
- /**
- * Processes the new XML Model, which XML root node is given.
- *
- * @param xml_doc The XML document, if available, or null if none exists.
- */
- @Override
- public void delegateXmlModelChanged(Document xml_doc) {
- // init the ui root on demand
- delegateInitUiRootNode(false /*force*/);
-
- getUiRootNode().setXmlDocument(xml_doc);
- if (xml_doc != null) {
- ElementDescriptor resources_desc =
- ValuesDescriptors.getInstance().getElementDescriptor();
- try {
- XPath xpath = AndroidXPathFactory.newXPath();
- Node node = (Node) xpath.evaluate("/" + resources_desc.getXmlName(), //$NON-NLS-1$
- xml_doc,
- XPathConstants.NODE);
- // Node can be null _or_ it must be the element we searched for.
- assert node == null || node.getNodeName().equals(resources_desc.getXmlName());
-
- // Refresh the manifest UI node and all its descendants
- getUiRootNode().loadFromXmlNode(node);
- } catch (XPathExpressionException e) {
- AdtPlugin.log(e, "XPath error when trying to find '%s' element in XML.", //$NON-NLS-1$
- resources_desc.getXmlName());
- }
- }
- }
-
- /**
- * Creates the initial UI Root Node, including the known mandatory elements.
- * @param force if true, a new UiRootNode is recreated even if it already exists.
- */
- @Override
- public void delegateInitUiRootNode(boolean force) {
- // The manifest UI node is always created, even if there's no corresponding XML node.
- if (getUiRootNode() == null || force) {
- ElementDescriptor resources_desc =
- ValuesDescriptors.getInstance().getElementDescriptor();
- setUiRootNode(resources_desc.createUiNode());
- getUiRootNode().setEditor(getEditor());
-
- onDescriptorsChanged();
- }
- }
-
- // ---- Local methods ----
-
- private void onDescriptorsChanged() {
- // nothing to be done, as the descriptor are static for now.
- // FIXME Update when the descriptors are not static
- }
-}
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/ValuesTreePage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/ValuesTreePage.java
deleted file mode 100644
index 224eb7301..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/ValuesTreePage.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.values;
-
-import com.android.ide.common.resources.ResourceFolder;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.IPageImageProvider;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.FlagManager;
-import com.android.ide.eclipse.adt.internal.editors.ui.tree.UiTreeBlock;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.forms.IManagedForm;
-import org.eclipse.ui.forms.editor.FormPage;
-import org.eclipse.ui.forms.widgets.ScrolledForm;
-import org.eclipse.ui.part.FileEditorInput;
-
-/**
- * Page for instrumentation settings, part of the AndroidManifest form editor.
- */
-public final class ValuesTreePage extends FormPage implements IPageImageProvider {
- /** Page id used for switching tabs programmatically */
- public final static String PAGE_ID = "res_tree_page"; //$NON-NLS-1$
-
- /** Container editor */
- CommonXmlEditor mEditor;
-
- public ValuesTreePage(CommonXmlEditor editor) {
- super(editor, PAGE_ID, "Resources"); // tab's label, keep it short
- mEditor = editor;
- }
-
- @Override
- public Image getPageImage() {
- // See if we should use a flag icon if this is a language-specific configuration
- IFile file = mEditor.getInputFile();
- if (file != null) {
- IContainer parent = file.getParent();
- if (parent != null) {
- Image flag = FlagManager.get().getFlagForFolderName(parent.getName());
- if (flag != null) {
- return flag;
- }
- }
- }
-
- return IconFactory.getInstance().getIcon("editor_page_design"); //$NON-NLS-1$
- }
-
- /**
- * Creates the content in the form hosted in this page.
- *
- * @param managedForm the form hosted in this page.
- */
- @Override
- protected void createFormContent(IManagedForm managedForm) {
- super.createFormContent(managedForm);
- ScrolledForm form = managedForm.getForm();
-
- String configText = null;
- IEditorInput input = mEditor.getEditorInput();
- if (input instanceof FileEditorInput) {
- FileEditorInput fileInput = (FileEditorInput)input;
- IFile iFile = fileInput.getFile();
-
- ResourceFolder resFolder = ResourceManager.getInstance().getResourceFolder(iFile);
- if (resFolder != null) {
- configText = resFolder.getConfiguration().toDisplayString();
- }
- }
-
- if (configText != null) {
- form.setText(String.format("Android Resources (%1$s)", configText));
- } else {
- form.setText("Android Resources");
- }
-
- form.setImage(AdtPlugin.getAndroidLogo());
-
- UiElementNode resources = mEditor.getUiRootNode();
- UiTreeBlock block = new UiTreeBlock(mEditor, resources,
- true /* autoCreateRoot */,
- null /* no element filters */,
- "Resources Elements",
- "List of all resources elements in this XML file.");
- block.createContent(managedForm);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/descriptors/ColorValueDescriptor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/descriptors/ColorValueDescriptor.java
deleted file mode 100644
index 012785020..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/descriptors/ColorValueDescriptor.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.values.descriptors;
-
-import com.android.ide.eclipse.adt.internal.editors.descriptors.TextValueDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiResourceAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.values.uimodel.UiColorValueNode;
-
-/**
- * Describes a Color XML element value displayed by an {@link UiColorValueNode}.
- */
-public final class ColorValueDescriptor extends TextValueDescriptor {
-
- public ColorValueDescriptor(String uiName, String tooltip) {
- super(uiName, tooltip);
- }
-
- /**
- * @return A new {@link UiResourceAttributeNode} linked to this theme descriptor.
- */
- @Override
- public UiAttributeNode createUiNode(UiElementNode uiParent) {
- return new UiColorValueNode(this, uiParent);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/descriptors/ItemElementDescriptor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/descriptors/ItemElementDescriptor.java
deleted file mode 100644
index 58ed36e45..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/descriptors/ItemElementDescriptor.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.values.descriptors;
-
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.editors.values.uimodel.UiItemElementNode;
-
-/**
- * {@link ItemElementDescriptor} is a special version of {@link ElementDescriptor} that
- * uses a specialized {@link UiItemElementNode} for display.
- */
-public class ItemElementDescriptor extends ElementDescriptor {
-
- /**
- * Constructs a new {@link ItemElementDescriptor} based on its XML name, UI name,
- * tooltip, SDK url, attributes list, children list and mandatory.
- *
- * @param xml_name The XML element node name. Case sensitive.
- * @param ui_name The XML element name for the user interface, typically capitalized.
- * @param tooltip An optional tooltip. Can be null or empty.
- * @param sdk_url An optional SKD URL. Can be null or empty.
- * @param attributes The list of allowed attributes. Can be null or empty.
- * @param children The list of allowed children. Can be null or empty.
- * @param mandatory Whether this node must always exist (even for empty models). A mandatory
- * UI node is never deleted and it may lack an actual XML node attached. A non-mandatory
- * UI node MUST have an XML node attached and it will cease to exist when the XML node
- * ceases to exist.
- */
- public ItemElementDescriptor(String xml_name, String ui_name,
- String tooltip, String sdk_url, AttributeDescriptor[] attributes,
- ElementDescriptor[] children, boolean mandatory) {
- super(xml_name, ui_name, tooltip, sdk_url, attributes, children, mandatory);
- }
-
- @Override
- public UiElementNode createUiNode() {
- return new UiItemElementNode(this);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/descriptors/ValuesDescriptors.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/descriptors/ValuesDescriptors.java
deleted file mode 100644
index 724e01932..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/descriptors/ValuesDescriptors.java
+++ /dev/null
@@ -1,337 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.values.descriptors;
-
-import static com.android.SdkConstants.ATTR_NAME;
-import static com.android.SdkConstants.ATTR_TYPE;
-import static com.android.SdkConstants.TAG_COLOR;
-import static com.android.SdkConstants.TAG_DIMEN;
-import static com.android.SdkConstants.TAG_DRAWABLE;
-import static com.android.SdkConstants.TAG_INTEGER_ARRAY;
-import static com.android.SdkConstants.TAG_ITEM;
-import static com.android.SdkConstants.TAG_PLURALS;
-import static com.android.SdkConstants.TAG_RESOURCES;
-import static com.android.SdkConstants.TAG_STRING;
-import static com.android.SdkConstants.TAG_STRING_ARRAY;
-import static com.android.SdkConstants.TAG_STYLE;
-
-import com.android.ide.common.api.IAttributeInfo.Format;
-import com.android.ide.common.resources.platform.AttributeInfo;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.EnumAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.FlagAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.IDescriptorProvider;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ListAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.TextAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.TextValueDescriptor;
-import com.android.resources.ResourceType;
-
-import java.util.EnumSet;
-
-
-/**
- * Complete description of the structure for resources XML files (under res/values/)
- */
-public final class ValuesDescriptors implements IDescriptorProvider {
- private static final ValuesDescriptors sThis = new ValuesDescriptors();
-
- /** The {@link ElementDescriptor} for the root Resources element. */
- public final ElementDescriptor mResourcesElement;
-
- public static ValuesDescriptors getInstance() {
- return sThis;
- }
-
- /*
- * @see com.android.ide.eclipse.editors.descriptors.IDescriptorProvider#getRootElementDescriptors()
- */
- @Override
- public ElementDescriptor[] getRootElementDescriptors() {
- return new ElementDescriptor[] { mResourcesElement };
- }
-
- @Override
- public ElementDescriptor getDescriptor() {
- return mResourcesElement;
- }
-
- public ElementDescriptor getElementDescriptor() {
- return mResourcesElement;
- }
-
- private ValuesDescriptors() {
-
- // Common attributes used in many placed
-
- // Elements
-
- AttributeInfo nameAttrInfo = new AttributeInfo(ATTR_NAME, Format.STRING_SET);
-
- ElementDescriptor color_element = new ElementDescriptor(
- TAG_COLOR,
- "Color",
- "A @color@ value specifies an RGB value with an alpha channel, which can be used in various places such as specifying a solid color for a Drawable or the color to use for text. It always begins with a # character and then is followed by the alpha-red-green-blue information in one of the following formats: #RGB, #ARGB, #RRGGBB or #AARRGGBB.",
- "http://code.google.com/android/reference/available-resources.html#colorvals", //$NON-NLS-1$
- new AttributeDescriptor[] {
- new TextAttributeDescriptor(ATTR_NAME,
- null /* nsUri */,
- nameAttrInfo),
- new ColorValueDescriptor(
- "Value*",
- "A mandatory color value.")
- .setTooltip("The mandatory name used in referring to this color.")
- },
- null, // no child nodes
- false /* not mandatory */);
-
- ElementDescriptor string_element = new ElementDescriptor(
- TAG_STRING,
- "String",
- "@Strings@, with optional simple formatting, can be stored and retrieved as resources. You can add formatting to your string by using three standard HTML tags: b, i, and u. If you use an apostrophe or a quote in your string, you must either escape it or enclose the whole string in the other kind of enclosing quotes.",
- "http://code.google.com/android/reference/available-resources.html#stringresources", //$NON-NLS-1$
- new AttributeDescriptor[] {
- new TextAttributeDescriptor(ATTR_NAME,
- null /* nsUri */,
- nameAttrInfo)
- .setTooltip("The mandatory name used in referring to this string."),
- new TextValueDescriptor(
- "Value*",
- "A mandatory string value.")
- },
- null, // no child nodes
- false /* not mandatory */);
-
- ElementDescriptor item_element = new ItemElementDescriptor(
- TAG_ITEM,
- "Item",
- null, // TODO find javadoc
- null, // TODO find link to javadoc
- new AttributeDescriptor[] {
- new TextAttributeDescriptor(ATTR_NAME,
- null /* nsUri */,
- nameAttrInfo)
- .setTooltip("The mandatory name used in referring to this resource."),
- new ListAttributeDescriptor(ATTR_TYPE,
- null /* nsUri */,
- new AttributeInfo(ATTR_TYPE,
- EnumSet.of(Format.STRING, Format.ENUM)
- ).setEnumValues(ResourceType.getNames())
- ).setTooltip("The mandatory type of this resource."),
- new FlagAttributeDescriptor("format", //$NON-NLS-1$
- null /* nsUri */,
- new AttributeInfo("format",
- EnumSet.of(Format.STRING, Format.FLAG)
- ).setFlagValues(
- new String[] {
- "boolean", //$NON-NLS-1$
- TAG_COLOR,
- "dimension", //$NON-NLS-1$
- "float", //$NON-NLS-1$
- "fraction", //$NON-NLS-1$
- "integer", //$NON-NLS-1$
- "reference", //$NON-NLS-1$
- "string" //$NON-NLS-1$
- } )
- ).setTooltip("The optional format of this resource."),
- new TextValueDescriptor(
- "Value",
- "A standard string, hex color value, or reference to any other resource type.")
- },
- null, // no child nodes
- false /* not mandatory */);
-
- ElementDescriptor drawable_element = new ElementDescriptor(
- TAG_DRAWABLE,
- "Drawable",
- "A @drawable@ defines a rectangle of color. Android accepts color values written in various web-style formats -- a hexadecimal constant in any of the following forms: #RGB, #ARGB, #RRGGBB, #AARRGGBB. Zero in the alpha channel means transparent. The default value is opaque.",
- "http://code.google.com/android/reference/available-resources.html#colordrawableresources", //$NON-NLS-1$
- new AttributeDescriptor[] {
- new TextAttributeDescriptor(ATTR_NAME,
- null /* nsUri */,
- nameAttrInfo)
- .setTooltip("The mandatory name used in referring to this drawable."),
- new TextValueDescriptor(
- "Value*",
- "A mandatory color value in the form #RGB, #ARGB, #RRGGBB or #AARRGGBB.")
- },
- null, // no child nodes
- false /* not mandatory */);
-
- ElementDescriptor dimen_element = new ElementDescriptor(
- TAG_DIMEN,
- "Dimension",
- "You can create common dimensions to use for various screen elements by defining @dimension@ values in XML. A dimension resource is a number followed by a unit of measurement. Supported units are px (pixels), in (inches), mm (millimeters), pt (points at 72 DPI), dp (density-independent pixels) and sp (scale-independent pixels)",
- "http://code.google.com/android/reference/available-resources.html#dimension", //$NON-NLS-1$
- new AttributeDescriptor[] {
- new TextAttributeDescriptor(ATTR_NAME,
- null /* nsUri */,
- nameAttrInfo)
- .setTooltip("The mandatory name used in referring to this dimension."),
- new TextValueDescriptor(
- "Value*",
- "A mandatory dimension value is a number followed by a unit of measurement. For example: 10px, 2in, 5sp.")
- },
- null, // no child nodes
- false /* not mandatory */);
-
- ElementDescriptor style_element = new ElementDescriptor(
- TAG_STYLE,
- "Style/Theme",
- "Both @styles and themes@ are defined in a style block containing one or more string or numerical values (typically color values), or references to other resources (drawables and so on).",
- "http://code.google.com/android/reference/available-resources.html#stylesandthemes", //$NON-NLS-1$
- new AttributeDescriptor[] {
- new TextAttributeDescriptor(ATTR_NAME,
- null /* nsUri */,
- nameAttrInfo)
- .setTooltip("The mandatory name used in referring to this theme."),
- new TextAttributeDescriptor("parent", //$NON-NLS-1$
- null /* nsUri */,
- new AttributeInfo("parent", //$NON-NLS-1$
- Format.STRING_SET))
- .setTooltip("An optional parent theme. All values from the specified theme will be inherited into this theme. Any values with identical names that you specify will override inherited values."),
- },
- new ElementDescriptor[] {
- new ElementDescriptor(
- TAG_ITEM,
- "Item",
- "A value to use in this @theme@. It can be a standard string, a hex color value, or a reference to any other resource type.",
- "http://code.google.com/android/reference/available-resources.html#stylesandthemes", //$NON-NLS-1$
- new AttributeDescriptor[] {
- new TextAttributeDescriptor(ATTR_NAME,
- null /* nsUri */,
- nameAttrInfo)
- .setTooltip("The mandatory name used in referring to this item."),
- new TextValueDescriptor(
- "Value*",
- "A mandatory standard string, hex color value, or reference to any other resource type.")
- },
- null, // no child nodes
- false /* not mandatory */)
- },
- false /* not mandatory */);
-
- ElementDescriptor string_array_element = new ElementDescriptor(
- TAG_STRING_ARRAY,
- "String Array",
- "An array of strings. Strings are added as underlying item elements to the array.",
- null, // tooltips
- new AttributeDescriptor[] {
- new TextAttributeDescriptor(ATTR_NAME,
- null /* nsUri */,
- nameAttrInfo)
- .setTooltip("The mandatory name used in referring to this string array."),
- },
- new ElementDescriptor[] {
- new ElementDescriptor(
- TAG_ITEM,
- "Item",
- "A string value to use in this string array.",
- null, // tooltip
- new AttributeDescriptor[] {
- new TextValueDescriptor(
- "Value*",
- "A mandatory string.")
- },
- null, // no child nodes
- false /* not mandatory */)
- },
- false /* not mandatory */);
-
- ElementDescriptor plurals_element = new ElementDescriptor(
- TAG_PLURALS,
- "Quantity Strings (Plurals)",
- "A quantity string",
- null, // tooltips
- new AttributeDescriptor[] {
- new TextAttributeDescriptor(ATTR_NAME,
- null /* nsUri */,
- nameAttrInfo)
- .setTooltip("A name for the pair of strings. This name will be used as the resource ID."),
- },
- new ElementDescriptor[] {
- new ElementDescriptor(
- TAG_ITEM,
- "Item",
- "A plural or singular string",
- null, // tooltip
- new AttributeDescriptor[] {
- new EnumAttributeDescriptor(
- "quantity", "Quantity", null,
- "A keyword value indicating when this string should be used",
- new AttributeInfo("quantity", Format.ENUM_SET)
- .setEnumValues(new String[] {
- "zero", //$NON-NLS-1$
- "one", //$NON-NLS-1$
- "two", //$NON-NLS-1$
- "few", //$NON-NLS-1$
- "many", //$NON-NLS-1$
- "other" //$NON-NLS-1$
- }))
- },
- null, // no child nodes
- false /* not mandatory */)
- },
- false /* not mandatory */);
-
- ElementDescriptor integer_array_element = new ElementDescriptor(
- TAG_INTEGER_ARRAY,
- "Integer Array",
- "An array of integers. Integers are added as underlying item elements to the array.",
- null, // tooltips
- new AttributeDescriptor[] {
- new TextAttributeDescriptor(ATTR_NAME,
- null /* nsUri */,
- nameAttrInfo)
- .setTooltip("The mandatory name used in referring to this integer array.")
- },
- new ElementDescriptor[] {
- new ElementDescriptor(
- TAG_ITEM,
- "Item",
- "An integer value to use in this integer array.",
- null, // tooltip
- new AttributeDescriptor[] {
- new TextValueDescriptor(
- "Value*",
- "A mandatory integer.")
- },
- null, // no child nodes
- false /* not mandatory */)
- },
- false /* not mandatory */);
-
- mResourcesElement = new ElementDescriptor(
- TAG_RESOURCES,
- "Resources",
- null,
- "http://code.google.com/android/reference/available-resources.html", //$NON-NLS-1$
- null, // no attributes
- new ElementDescriptor[] {
- string_element,
- color_element,
- dimen_element,
- drawable_element,
- style_element,
- item_element,
- string_array_element,
- integer_array_element,
- plurals_element,
- },
- true /* mandatory */);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/uimodel/UiColorValueNode.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/uimodel/UiColorValueNode.java
deleted file mode 100644
index 9c84b36f9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/uimodel/UiColorValueNode.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.values.uimodel;
-
-import com.android.ide.eclipse.adt.internal.editors.descriptors.TextValueDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiTextValueNode;
-
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.widgets.Text;
-
-import java.util.regex.Pattern;
-
-/**
- * Displays and edits a color XML element value with a custom validator.
- * <p/>
- * See {@link UiAttributeNode} for more information.
- */
-public class UiColorValueNode extends UiTextValueNode {
-
- /** Accepted RGBA formats are one of #RGB, #ARGB, #RRGGBB or #AARRGGBB. */
- private static final Pattern RGBA_REGEXP = Pattern.compile(
- "#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})"); //$NON-NLS-1$
-
- public UiColorValueNode(TextValueDescriptor attributeDescriptor, UiElementNode uiParent) {
- super(attributeDescriptor, uiParent);
- }
-
- /* (non-java doc)
- *
- * Add a modify listener that will check colors have the proper format,
- * that is one of #RGB, #ARGB, #RRGGBB or #AARRGGBB.
- */
- @Override
- protected void onAddValidators(final Text text) {
- ModifyListener listener = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- String color = text.getText();
- if (RGBA_REGEXP.matcher(color).matches()) {
- getManagedForm().getMessageManager().removeMessage(text, text);
- } else {
- getManagedForm().getMessageManager().addMessage(text,
- "Accepted color formats are one of #RGB, #ARGB, #RRGGBB or #AARRGGBB.",
- null /* data */, IMessageProvider.ERROR, text);
- }
- }
- };
-
- text.addModifyListener(listener);
-
- // Make sure the validator removes its message(s) when the widget is disposed
- text.addDisposeListener(new DisposeListener() {
- @Override
- public void widgetDisposed(DisposeEvent e) {
- getManagedForm().getMessageManager().removeMessage(text, text);
- }
- });
-
- // Finally call the validator once to make sure the initial value is processed
- listener.modifyText(null);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/uimodel/UiItemElementNode.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/uimodel/UiItemElementNode.java
deleted file mode 100644
index 88ac3e141..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/editors/values/uimodel/UiItemElementNode.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.values.uimodel;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.editors.values.descriptors.ItemElementDescriptor;
-
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-/**
- * {@link UiItemElementNode} is a special version of {@link UiElementNode} that
- * customizes the element display to include the item type attribute if present.
- */
-public class UiItemElementNode extends UiElementNode {
-
- /**
- * Creates a new {@link UiElementNode} described by a given {@link ItemElementDescriptor}.
- *
- * @param elementDescriptor The {@link ItemElementDescriptor} for the XML node. Cannot be null.
- */
- public UiItemElementNode(ItemElementDescriptor elementDescriptor) {
- super(elementDescriptor);
- }
-
- @Override
- public String getShortDescription() {
- Node xmlNode = getXmlNode();
- if (xmlNode != null && xmlNode instanceof Element && xmlNode.hasAttributes()) {
-
- Element elem = (Element) xmlNode;
- String type = elem.getAttribute(SdkConstants.ATTR_TYPE);
- String name = elem.getAttribute(SdkConstants.ATTR_NAME);
- if (type != null && name != null && type.length() > 0 && name.length() > 0) {
- type = AdtUtils.capitalize(type);
- return String.format("%1$s (%2$s %3$s)", name, type, getDescriptor().getUiName());
- }
- }
-
- return super.getShortDescription();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AMReceiver.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AMReceiver.java
deleted file mode 100644
index ea61945a2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AMReceiver.java
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.launch;
-
-import com.android.ddmlib.IDevice;
-import com.android.ddmlib.MultiLineReceiver;
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import java.util.ArrayList;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-
-/**
- * Output receiver for am process (Activity Manager)
- *
- * Monitors adb output for am errors, and retries launch as appropriate.
- */
-public class AMReceiver extends MultiLineReceiver {
-
- private static final int MAX_ATTEMPT_COUNT = 5;
- private static final Pattern sAmErrorType = Pattern.compile("Error type (\\d+)"); //$NON-NLS-1$
-
- private final DelayedLaunchInfo mLaunchInfo;
- private final IDevice mDevice;
- private final ILaunchController mLaunchController;
-
- /**
- * Basic constructor.
- *
- * @param launchInfo the {@link DelayedLaunchInfo} associated with the am process.
- * @param device the Android device on which the launch is done.
- * @param launchController the {@link ILaunchController} that is managing the launch
- */
- public AMReceiver(DelayedLaunchInfo launchInfo, IDevice device,
- ILaunchController launchController) {
- mLaunchInfo = launchInfo;
- mDevice = device;
- mLaunchController = launchController;
- }
-
- /**
- * Monitors the am process for error messages. If an error occurs, will reattempt launch up to
- * <code>MAX_ATTEMPT_COUNT</code> times.
- *
- * @param lines a portion of the am output
- *
- * @see MultiLineReceiver#processNewLines(String[])
- */
- @Override
- public void processNewLines(String[] lines) {
- // first we check if one starts with error
- ArrayList<String> array = new ArrayList<String>();
- boolean error = false;
- boolean warning = false;
- for (String s : lines) {
- // ignore empty lines.
- if (s.length() == 0) {
- continue;
- }
-
- // check for errors that output an error type, if the attempt count is still
- // valid. If not the whole text will be output in the console
- if (mLaunchInfo.getAttemptCount() < MAX_ATTEMPT_COUNT &&
- mLaunchInfo.isCancelled() == false) {
- Matcher m = sAmErrorType.matcher(s);
- if (m.matches()) {
- // get the error type
- int type = Integer.parseInt(m.group(1));
-
- final int waitTime = 3;
- String msg;
-
- switch (type) {
- case 1:
- /* Intended fall through */
- case 2:
- msg = String.format(
- "Device not ready. Waiting %1$d seconds before next attempt.",
- waitTime);
- break;
- case 3:
- msg = String.format(
- "New package not yet registered with the system. Waiting %1$d seconds before next attempt.",
- waitTime);
- break;
- default:
- msg = String.format(
- "Device not ready (%2$d). Waiting %1$d seconds before next attempt.",
- waitTime, type);
- break;
-
- }
-
- AdtPlugin.printToConsole(mLaunchInfo.getProject(), msg);
-
- // launch another thread, that waits a bit and attempts another launch
- new Thread("Delayed Launch attempt") {
- @Override
- public void run() {
- try {
- sleep(waitTime * 1000);
- } catch (InterruptedException e) {
- // ignore
- }
-
- mLaunchController.launchApp(mLaunchInfo, mDevice);
- }
- }.start();
-
- // no need to parse the rest
- return;
- }
- }
-
- // check for error if needed
- if (error == false && s.startsWith("Error:")) { //$NON-NLS-1$
- error = true;
- }
- if (warning == false && s.startsWith("Warning:")) { //$NON-NLS-1$
- warning = true;
- }
-
- // add the line to the list
- array.add("ActivityManager: " + s); //$NON-NLS-1$
- }
-
- // then we display them in the console
- if (warning || error) {
- AdtPlugin.printErrorToConsole(mLaunchInfo.getProject(), array.toArray());
- } else {
- AdtPlugin.printToConsole(mLaunchInfo.getProject(), array.toArray());
- }
-
- // if error then we cancel the launch, and remove the delayed info
- if (error) {
- mLaunchController.stopLaunch(mLaunchInfo);
- }
- }
-
- /**
- * Returns true if launch has been cancelled
- */
- @Override
- public boolean isCancelled() {
- return mLaunchInfo.isCancelled();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/ActivityLaunchAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/ActivityLaunchAction.java
deleted file mode 100644
index 311b19aa7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/ActivityLaunchAction.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.launch;
-
-import com.android.ddmlib.AdbCommandRejectedException;
-import com.android.ddmlib.IDevice;
-import com.android.ddmlib.ShellCommandUnresponsiveException;
-import com.android.ddmlib.TimeoutException;
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import java.io.IOException;
-import java.util.Collection;
-
-/**
- * Launches the given activity
- */
-public class ActivityLaunchAction implements IAndroidLaunchAction {
-
- private final String mActivity;
- private final ILaunchController mLaunchController;
-
- /**
- * Creates a ActivityLaunchAction
- *
- * @param activity fully qualified activity name to launch
- * @param controller the {@link ILaunchController} that performs launch
- */
- public ActivityLaunchAction(String activity, ILaunchController controller) {
- mActivity = activity;
- mLaunchController = controller;
- }
-
- public boolean doLaunchAction(DelayedLaunchInfo info, IDevice device) {
- String command = "am start" //$NON-NLS-1$
- + (info.isDebugMode() ? " -D" //$NON-NLS-1$
- : "") //$NON-NLS-1$
- + " -n " //$NON-NLS-1$
- + info.getPackageName() + "/" //$NON-NLS-1$
- + mActivity.replaceAll("\\$", "\\\\\\$") //$NON-NLS-1$ //$NON-NLS-2$
- + " -a android.intent.action.MAIN" //$NON-NLS-1$
- + " -c android.intent.category.LAUNCHER";
- try {
- String msg = String.format("Starting activity %1$s on device %2$s", mActivity,
- device);
- AdtPlugin.printToConsole(info.getProject(), msg);
-
- // In debug mode, we need to add the info to the list of application monitoring
- // client changes.
- // increment launch attempt count, to handle retries and timeouts
- info.incrementAttemptCount();
-
- // now we actually launch the app.
- device.executeShellCommand(command, new AMReceiver(info, device, mLaunchController));
-
- // if the app is not a debug app, we need to do some clean up, as
- // the process is done!
- if (info.isDebugMode() == false) {
- // stop the launch object, since there's no debug, and it can't
- // provide any control over the app
- return false;
- }
- } catch (TimeoutException e) {
- AdtPlugin.printErrorToConsole(info.getProject(), "Launch error: timeout");
- return false;
- } catch (AdbCommandRejectedException e) {
- AdtPlugin.printErrorToConsole(info.getProject(), String.format(
- "Launch error: adb rejected command: %1$s", e.getMessage()));
- return false;
- } catch (ShellCommandUnresponsiveException e) {
- // we didn't get the output but that's ok, just log it
- AdtPlugin.log(e, "No command output when running: '%1$s' on device %2$s", command,
- device);
- } catch (IOException e) {
- // something went wrong trying to launch the app.
- // lets stop the Launch
- AdtPlugin.printErrorToConsole(info.getProject(),
- String.format("Launch error: %s", e.getMessage()));
- return false;
- }
- return true;
- }
-
- /**
- * Launches the activity on targeted device
- *
- * @param info the {@link DelayedLaunchInfo} that contains launch details
- * @param devices list of Android devices on which the activity will be launched
- */
- @Override
- public boolean doLaunchAction(DelayedLaunchInfo info, Collection<IDevice> devices) {
- boolean result = true;
- for (IDevice d : devices) {
- // Note that this expression should not short circuit - even if an action fails
- // on a device, it should still be performed on all other devices.
- result = doLaunchAction(info, d) && result;
- }
-
- return result;
- }
-
- /**
- * Returns a description of the activity being launched
- *
- * @see IAndroidLaunchAction#getLaunchDescription()
- */
- @Override
- public String getLaunchDescription() {
- return String.format("%1$s activity launch", mActivity);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AndroidLaunch.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AndroidLaunch.java
deleted file mode 100644
index 8e2c133be..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AndroidLaunch.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.launch;
-
-import org.eclipse.debug.core.DebugException;
-import org.eclipse.debug.core.ILaunchConfiguration;
-import org.eclipse.debug.core.ILaunchManager;
-import org.eclipse.debug.core.Launch;
-import org.eclipse.debug.core.model.ISourceLocator;
-
-/**
- * Custom implementation of Launch to allow access to the LaunchManager
- *
- */
-public class AndroidLaunch extends Launch {
-
- /**
- * Basic constructor does nothing special
- * @param launchConfiguration
- * @param mode
- * @param locator
- */
- public AndroidLaunch(ILaunchConfiguration launchConfiguration, String mode,
- ISourceLocator locator) {
- super(launchConfiguration, mode, locator);
- }
-
- /** Stops the launch, and removes it from the launch manager */
- public void stopLaunch() {
- ILaunchManager mgr = getLaunchManager();
-
- if (canTerminate()) {
- try {
- terminate();
- } catch (DebugException e) {
- // well looks like we couldn't stop it. nothing else to be
- // done really
- }
- }
- // remove the launch
- mgr.removeLaunch(this);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AndroidLaunchConfiguration.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AndroidLaunchConfiguration.java
deleted file mode 100644
index 580bbbee5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AndroidLaunchConfiguration.java
+++ /dev/null
@@ -1,192 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.launch;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.debug.core.ILaunchConfiguration;
-
-/**
- * Launch configuration data. This stores the result of querying the
- * {@link ILaunchConfiguration} so that it's only done once.
- */
-public class AndroidLaunchConfiguration {
-
- /**
- * Launch action. See {@link LaunchConfigDelegate#ACTION_DEFAULT},
- * {@link LaunchConfigDelegate#ACTION_ACTIVITY},
- * {@link LaunchConfigDelegate#ACTION_DO_NOTHING}
- */
- public int mLaunchAction = LaunchConfigDelegate.DEFAULT_LAUNCH_ACTION;
-
- /** Target selection mode for the configuration. */
- public enum TargetMode {
- /** Automatic target selection mode. */
- AUTO,
- /** Manual target selection mode. */
- MANUAL,
- /** All active devices */
- ALL_DEVICES,
- /** All active emulators */
- ALL_EMULATORS,
- /** All active devices and emulators */
- ALL_DEVICES_AND_EMULATORS;
-
- public static TargetMode getMode(String s) {
- for (TargetMode m: values()) {
- if (m.toString().equals(s)) {
- return m;
- }
- }
-
- throw new IllegalArgumentException(String.format(
- "Invalid representation (%s) for TargetMode", s));
- }
-
- public boolean isMultiDevice() {
- return this == ALL_DEVICES
- || this == ALL_EMULATORS
- || this == ALL_DEVICES_AND_EMULATORS;
- }
- }
-
- /**
- * Target selection mode.
- * @see TargetMode
- */
- public TargetMode mTargetMode = LaunchConfigDelegate.DEFAULT_TARGET_MODE;
-
- /**
- * Indicates whether the emulator should be called with -wipe-data
- */
- public boolean mWipeData = LaunchConfigDelegate.DEFAULT_WIPE_DATA;
-
- /**
- * Indicates whether the emulator should be called with -no-boot-anim
- */
- public boolean mNoBootAnim = LaunchConfigDelegate.DEFAULT_NO_BOOT_ANIM;
-
- /**
- * AVD Name.
- */
- public String mAvdName = null;
-
- public String mNetworkSpeed = EmulatorConfigTab.getSpeed(
- LaunchConfigDelegate.DEFAULT_SPEED);
- public String mNetworkDelay = EmulatorConfigTab.getDelay(
- LaunchConfigDelegate.DEFAULT_DELAY);
-
- /**
- * Optional custom command line parameter to launch the emulator
- */
- public String mEmulatorCommandLine;
-
- /** Flag indicating whether the same device should be used for future launches. */
- public boolean mReuseLastUsedDevice = false;
-
- /** Serial number of the device used in the last launch of this config. */
- public String mLastUsedDevice = null;
-
- /**
- * Initialized the structure from an ILaunchConfiguration object.
- * @param config
- */
- public void set(ILaunchConfiguration config) {
- try {
- mLaunchAction = config.getAttribute(LaunchConfigDelegate.ATTR_LAUNCH_ACTION,
- mLaunchAction);
- } catch (CoreException e1) {
- // nothing to be done here, we'll use the default value
- }
-
- mTargetMode = parseTargetMode(config, mTargetMode);
-
- try {
- mReuseLastUsedDevice = config.getAttribute(
- LaunchConfigDelegate.ATTR_REUSE_LAST_USED_DEVICE, false);
- mLastUsedDevice = config.getAttribute(
- LaunchConfigDelegate.ATTR_LAST_USED_DEVICE, (String)null);
- } catch (CoreException e) {
- // nothing to be done here, we'll use the default value
- }
-
- try {
- mAvdName = config.getAttribute(LaunchConfigDelegate.ATTR_AVD_NAME, mAvdName);
- } catch (CoreException e) {
- // ignore
- }
-
- int index = LaunchConfigDelegate.DEFAULT_SPEED;
- try {
- index = config.getAttribute(LaunchConfigDelegate.ATTR_SPEED, index);
- } catch (CoreException e) {
- // nothing to be done here, we'll use the default value
- }
- mNetworkSpeed = EmulatorConfigTab.getSpeed(index);
-
- index = LaunchConfigDelegate.DEFAULT_DELAY;
- try {
- index = config.getAttribute(LaunchConfigDelegate.ATTR_DELAY, index);
- } catch (CoreException e) {
- // nothing to be done here, we'll use the default value
- }
- mNetworkDelay = EmulatorConfigTab.getDelay(index);
-
- try {
- mEmulatorCommandLine = config.getAttribute(
- LaunchConfigDelegate.ATTR_COMMANDLINE, ""); //$NON-NLS-1$
- } catch (CoreException e) {
- // lets not do anything here, we'll use the default value
- }
-
- try {
- mWipeData = config.getAttribute(LaunchConfigDelegate.ATTR_WIPE_DATA, mWipeData);
- } catch (CoreException e) {
- // nothing to be done here, we'll use the default value
- }
-
- try {
- mNoBootAnim = config.getAttribute(LaunchConfigDelegate.ATTR_NO_BOOT_ANIM,
- mNoBootAnim);
- } catch (CoreException e) {
- // nothing to be done here, we'll use the default value
- }
- }
-
- /**
- * Retrieve the {@link TargetMode} saved in the provided launch configuration.
- * Returns defaultMode if there are any errors while retrieving or parsing the saved setting.
- */
- public static TargetMode parseTargetMode(ILaunchConfiguration config, TargetMode defaultMode) {
- try {
- String value = config.getAttribute(LaunchConfigDelegate.ATTR_TARGET_MODE,
- defaultMode.toString());
- return TargetMode.getMode(value);
- } catch (CoreException e) {
- // ADT R20 changes the attribute type of ATTR_TARGET_MODE to be a string from a bool.
- // So if parsing as a string fails, attempt parsing as a boolean.
- try {
- boolean value = config.getAttribute(LaunchConfigDelegate.ATTR_TARGET_MODE, true);
- return value ? TargetMode.AUTO : TargetMode.MANUAL;
- } catch (CoreException e1) {
- return defaultMode;
- }
- } catch (IllegalArgumentException e) {
- return defaultMode;
- }
- }
-}
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AndroidLaunchController.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AndroidLaunchController.java
deleted file mode 100644
index a95ed6882..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AndroidLaunchController.java
+++ /dev/null
@@ -1,1872 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.launch;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ddmlib.AdbCommandRejectedException;
-import com.android.ddmlib.AndroidDebugBridge;
-import com.android.ddmlib.AndroidDebugBridge.IClientChangeListener;
-import com.android.ddmlib.AndroidDebugBridge.IDebugBridgeChangeListener;
-import com.android.ddmlib.AndroidDebugBridge.IDeviceChangeListener;
-import com.android.ddmlib.CanceledException;
-import com.android.ddmlib.Client;
-import com.android.ddmlib.ClientData;
-import com.android.ddmlib.ClientData.DebuggerStatus;
-import com.android.ddmlib.IDevice;
-import com.android.ddmlib.InstallException;
-import com.android.ddmlib.Log;
-import com.android.ddmlib.TimeoutException;
-import com.android.ide.common.xml.ManifestData;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.actions.AvdManagerAction;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.ide.eclipse.adt.internal.launch.AndroidLaunchConfiguration.TargetMode;
-import com.android.ide.eclipse.adt.internal.launch.DelayedLaunchInfo.InstallRetryMode;
-import com.android.ide.eclipse.adt.internal.launch.DeviceChooserDialog.DeviceChooserResponse;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.project.AndroidManifestHelper;
-import com.android.ide.eclipse.adt.internal.project.ApkInstallManager;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.project.ProjectHelper;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.ddms.DdmsPlugin;
-import com.android.prefs.AndroidLocation.AndroidLocationException;
-import com.android.sdklib.AndroidVersion;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.internal.avd.AvdInfo;
-import com.android.sdklib.internal.avd.AvdManager;
-import com.android.utils.NullLogger;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.debug.core.DebugPlugin;
-import org.eclipse.debug.core.ILaunchConfiguration;
-import org.eclipse.debug.core.ILaunchConfigurationType;
-import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
-import org.eclipse.debug.core.ILaunchManager;
-import org.eclipse.debug.core.model.IDebugTarget;
-import org.eclipse.debug.ui.DebugUITools;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
-import org.eclipse.jdt.launching.IVMConnector;
-import org.eclipse.jdt.launching.JavaRuntime;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * Controls the launch of Android application either on a device or on the
- * emulator. If an emulator is already running, this class will attempt to reuse
- * it.
- */
-public final class AndroidLaunchController implements IDebugBridgeChangeListener,
- IDeviceChangeListener, IClientChangeListener, ILaunchController {
-
- private static final String FLAG_AVD = "-avd"; //$NON-NLS-1$
- private static final String FLAG_NETDELAY = "-netdelay"; //$NON-NLS-1$
- private static final String FLAG_NETSPEED = "-netspeed"; //$NON-NLS-1$
- private static final String FLAG_WIPE_DATA = "-wipe-data"; //$NON-NLS-1$
- private static final String FLAG_NO_BOOT_ANIM = "-no-boot-anim"; //$NON-NLS-1$
-
- /**
- * Map to store {@link ILaunchConfiguration} objects that must be launched as simple connection
- * to running application. The integer is the port on which to connect.
- * <b>ALL ACCESS MUST BE INSIDE A <code>synchronized (sListLock)</code> block!</b>
- */
- private static final HashMap<ILaunchConfiguration, Integer> sRunningAppMap =
- new HashMap<ILaunchConfiguration, Integer>();
-
- private static final Object sListLock = sRunningAppMap;
-
- /**
- * List of {@link DelayedLaunchInfo} waiting for an emulator to connect.
- * <p>Once an emulator has connected, {@link DelayedLaunchInfo#getDevice()} is set and the
- * DelayedLaunchInfo object is moved to
- * {@link AndroidLaunchController#mWaitingForReadyEmulatorList}.
- * <b>ALL ACCESS MUST BE INSIDE A <code>synchronized (sListLock)</code> block!</b>
- */
- private final ArrayList<DelayedLaunchInfo> mWaitingForEmulatorLaunches =
- new ArrayList<DelayedLaunchInfo>();
-
- /**
- * List of application waiting to be launched on a device/emulator.<br>
- * <b>ALL ACCESS MUST BE INSIDE A <code>synchronized (sListLock)</code> block!</b>
- * */
- private final ArrayList<DelayedLaunchInfo> mWaitingForReadyEmulatorList =
- new ArrayList<DelayedLaunchInfo>();
-
- /**
- * Application waiting to show up as waiting for debugger.
- * <b>ALL ACCESS MUST BE INSIDE A <code>synchronized (sListLock)</code> block!</b>
- */
- private final ArrayList<DelayedLaunchInfo> mWaitingForDebuggerApplications =
- new ArrayList<DelayedLaunchInfo>();
-
- /**
- * List of clients that have appeared as waiting for debugger before their name was available.
- * <b>ALL ACCESS MUST BE INSIDE A <code>synchronized (sListLock)</code> block!</b>
- */
- private final ArrayList<Client> mUnknownClientsWaitingForDebugger = new ArrayList<Client>();
-
- /** static instance for singleton */
- private static AndroidLaunchController sThis = new AndroidLaunchController();
-
- /** private constructor to enforce singleton */
- private AndroidLaunchController() {
- AndroidDebugBridge.addDebugBridgeChangeListener(this);
- AndroidDebugBridge.addDeviceChangeListener(this);
- AndroidDebugBridge.addClientChangeListener(this);
- }
-
- /**
- * Returns the singleton reference.
- */
- public static AndroidLaunchController getInstance() {
- return sThis;
- }
-
-
- /**
- * Launches a remote java debugging session on an already running application
- * @param project The project of the application to debug.
- * @param debugPort The port to connect the debugger to.
- */
- public static void debugRunningApp(IProject project, int debugPort) {
- // get an existing or new launch configuration
- ILaunchConfiguration config = AndroidLaunchController.getLaunchConfig(project,
- LaunchConfigDelegate.ANDROID_LAUNCH_TYPE_ID);
-
- if (config != null) {
- setPortLaunchConfigAssociation(config, debugPort);
-
- // and launch
- DebugUITools.launch(config, ILaunchManager.DEBUG_MODE);
- }
- }
-
- /**
- * Returns an {@link ILaunchConfiguration} for the specified {@link IProject}.
- * @param project the project
- * @param launchTypeId launch delegate type id
- * @return a new or already existing <code>ILaunchConfiguration</code> or null if there was
- * an error when creating a new one.
- */
- public static ILaunchConfiguration getLaunchConfig(IProject project, String launchTypeId) {
- // get the launch manager
- ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
-
- // now get the config type for our particular android type.
- ILaunchConfigurationType configType = manager.getLaunchConfigurationType(launchTypeId);
-
- String name = project.getName();
-
- // search for an existing launch configuration
- ILaunchConfiguration config = findConfig(manager, configType, name);
-
- // test if we found one or not
- if (config == null) {
- // Didn't find a matching config, so we make one.
- // It'll be made in the "working copy" object first.
- ILaunchConfigurationWorkingCopy wc = null;
-
- try {
- // make the working copy object
- wc = configType.newInstance(null,
- manager.generateLaunchConfigurationName(name));
-
- // set the project name
- wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, name);
-
- // set the launch mode to default.
- wc.setAttribute(LaunchConfigDelegate.ATTR_LAUNCH_ACTION,
- LaunchConfigDelegate.DEFAULT_LAUNCH_ACTION);
-
- // set default target mode
- wc.setAttribute(LaunchConfigDelegate.ATTR_TARGET_MODE,
- LaunchConfigDelegate.DEFAULT_TARGET_MODE.toString());
-
- // default AVD: None
- wc.setAttribute(LaunchConfigDelegate.ATTR_AVD_NAME, (String) null);
-
- // set the default network speed
- wc.setAttribute(LaunchConfigDelegate.ATTR_SPEED,
- LaunchConfigDelegate.DEFAULT_SPEED);
-
- // and delay
- wc.setAttribute(LaunchConfigDelegate.ATTR_DELAY,
- LaunchConfigDelegate.DEFAULT_DELAY);
-
- // default wipe data mode
- wc.setAttribute(LaunchConfigDelegate.ATTR_WIPE_DATA,
- LaunchConfigDelegate.DEFAULT_WIPE_DATA);
-
- // default disable boot animation option
- wc.setAttribute(LaunchConfigDelegate.ATTR_NO_BOOT_ANIM,
- LaunchConfigDelegate.DEFAULT_NO_BOOT_ANIM);
-
- // set default emulator options
- IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore();
- String emuOptions = store.getString(AdtPrefs.PREFS_EMU_OPTIONS);
- wc.setAttribute(LaunchConfigDelegate.ATTR_COMMANDLINE, emuOptions);
-
- // map the config and the project
- wc.setMappedResources(getResourcesToMap(project));
-
- // save the working copy to get the launch config object which we return.
- return wc.doSave();
-
- } catch (CoreException e) {
- String msg = String.format(
- "Failed to create a Launch config for project '%1$s': %2$s",
- project.getName(), e.getMessage());
- AdtPlugin.printErrorToConsole(project, msg);
-
- // no launch!
- return null;
- }
- }
-
- return config;
- }
-
- /**
- * Returns the list of resources to map to a Launch Configuration.
- * @param project the project associated to the launch configuration.
- */
- public static IResource[] getResourcesToMap(IProject project) {
- ArrayList<IResource> array = new ArrayList<IResource>(2);
- array.add(project);
-
- IFile manifest = ProjectHelper.getManifest(project);
- if (manifest != null) {
- array.add(manifest);
- }
-
- return array.toArray(new IResource[array.size()]);
- }
-
- /**
- * Launches an android app on the device or emulator
- *
- * @param project The project we're launching
- * @param mode the mode in which to launch, one of the mode constants
- * defined by <code>ILaunchManager</code> - <code>RUN_MODE</code> or
- * <code>DEBUG_MODE</code>.
- * @param apk the resource to the apk to launch.
- * @param packageName the Android package name of the app
- * @param debugPackageName the Android package name to debug
- * @param debuggable the debuggable value of the app's manifest, or null if not set.
- * @param requiredApiVersionNumber the api version required by the app, or null if none.
- * @param launchAction the action to perform after app sync
- * @param config the launch configuration
- * @param launch the launch object
- */
- public void launch(final IProject project, String mode, IFile apk,
- String packageName, String debugPackageName, Boolean debuggable,
- String requiredApiVersionNumber, final IAndroidLaunchAction launchAction,
- final AndroidLaunchConfiguration config, final AndroidLaunch launch,
- IProgressMonitor monitor) {
-
- String message = String.format("Performing %1$s", launchAction.getLaunchDescription());
- AdtPlugin.printToConsole(project, message);
-
- // create the launch info
- final DelayedLaunchInfo launchInfo = new DelayedLaunchInfo(project, packageName,
- debugPackageName, launchAction, apk, debuggable, requiredApiVersionNumber, launch,
- monitor);
-
- // set the debug mode
- launchInfo.setDebugMode(mode.equals(ILaunchManager.DEBUG_MODE));
-
- // get the SDK
- Sdk currentSdk = Sdk.getCurrent();
- AvdManager avdManager = currentSdk.getAvdManager();
-
- // reload the AVDs to make sure we are up to date
- try {
- avdManager.reloadAvds(NullLogger.getLogger());
- } catch (AndroidLocationException e1) {
- // this happens if the AVD Manager failed to find the folder in which the AVDs are
- // stored. This is unlikely to happen, but if it does, we should force to go manual
- // to allow using physical devices.
- config.mTargetMode = TargetMode.MANUAL;
- }
-
- // get the sdk against which the project is built
- IAndroidTarget projectTarget = currentSdk.getTarget(project);
-
- // get the min required android version
- ManifestInfo mi = ManifestInfo.get(project);
- final int minApiLevel = mi.getMinSdkVersion();
- final String minApiCodeName = mi.getMinSdkCodeName();
- final AndroidVersion minApiVersion = new AndroidVersion(minApiLevel, minApiCodeName);
-
- // FIXME: check errors on missing sdk, AVD manager, or project target.
-
- // device chooser response object.
- final DeviceChooserResponse response = new DeviceChooserResponse();
-
- /*
- * Launch logic:
- * - Use Last Launched Device/AVD set.
- * If user requested to use same device for future launches, and the last launched
- * device/avd is still present, then simply launch on the same device/avd.
- * - Manual Mode
- * Always display a UI that lets a user see the current running emulators/devices.
- * The UI must show which devices are compatibles, and allow launching new emulators
- * with compatible (and not yet running) AVD.
- * - Automatic Way
- * * Preferred AVD set.
- * If Preferred AVD is not running: launch it.
- * Launch the application on the preferred AVD.
- * * No preferred AVD.
- * Count the number of compatible emulators/devices.
- * If != 1, display a UI similar to manual mode.
- * If == 1, launch the application on this AVD/device.
- * - Launch on multiple devices:
- * From the currently active devices & emulators, filter out those that cannot run
- * the app (by api level), and launch on all the others.
- */
- IDevice[] devices = AndroidDebugBridge.getBridge().getDevices();
- if (config.mReuseLastUsedDevice) {
- // check to see if the last used device is still online
- IDevice lastUsedDevice = getDeviceIfOnline(config.mLastUsedDevice,
- devices);
- if (lastUsedDevice != null) {
- response.setDeviceToUse(lastUsedDevice);
- continueLaunch(response, project, launch, launchInfo, config);
- return;
- }
- }
-
- if (config.mTargetMode == TargetMode.AUTO) {
- // first check if we have a preferred AVD name, and if it actually exists, and is valid
- // (ie able to run the project).
- // We need to check this in case the AVD was recreated with a different target that is
- // not compatible.
- AvdInfo preferredAvd = null;
- if (config.mAvdName != null) {
- preferredAvd = avdManager.getAvd(config.mAvdName, true /*validAvdOnly*/);
- }
-
- if (preferredAvd != null) {
- IAndroidTarget preferredAvdTarget = preferredAvd.getTarget();
- if (preferredAvdTarget != null
- && !preferredAvdTarget.getVersion().canRun(minApiVersion)) {
- preferredAvd = null;
-
- AdtPlugin.printErrorToConsole(project, String.format(
- "Preferred AVD '%1$s' (API Level: %2$d) cannot run application with minApi %3$s. Looking for a compatible AVD...",
- config.mAvdName,
- preferredAvdTarget.getVersion().getApiLevel(),
- minApiVersion));
- }
- }
-
- if (preferredAvd != null) {
- // We have a preferred avd that can actually run the application.
- // Now see if the AVD is running, and if so use it, otherwise launch it.
-
- for (IDevice d : devices) {
- String deviceAvd = d.getAvdName();
- if (deviceAvd != null && deviceAvd.equals(config.mAvdName)) {
- response.setDeviceToUse(d);
-
- AdtPlugin.printToConsole(project, String.format(
- "Automatic Target Mode: Preferred AVD '%1$s' is available on emulator '%2$s'",
- config.mAvdName, d));
-
- continueLaunch(response, project, launch, launchInfo, config);
- return;
- }
- }
-
- // at this point we have a valid preferred AVD that is not running.
- // We need to start it.
- response.setAvdToLaunch(preferredAvd);
-
- AdtPlugin.printToConsole(project, String.format(
- "Automatic Target Mode: Preferred AVD '%1$s' is not available. Launching new emulator.",
- config.mAvdName));
-
- continueLaunch(response, project, launch, launchInfo, config);
- return;
- }
-
- // no (valid) preferred AVD? look for one.
-
- // If the API level requested in the manifest is lower than the current project
- // target, when we will iterate devices/avds later ideally we will want to find
- // a device/avd which target is as close to the manifest as possible (instead of
- // a device which target is the same as the project's target) and use it as the
- // new default.
-
- if (minApiCodeName != null && minApiLevel < projectTarget.getVersion().getApiLevel()) {
- int maxDist = projectTarget.getVersion().getApiLevel() - minApiLevel;
- IAndroidTarget candidate = null;
-
- for (IAndroidTarget target : currentSdk.getTargets()) {
- if (target.canRunOn(projectTarget)) {
- int currDist = target.getVersion().getApiLevel() - minApiLevel;
- if (currDist >= 0 && currDist < maxDist) {
- maxDist = currDist;
- candidate = target;
- if (maxDist == 0) {
- // Found a perfect match
- break;
- }
- }
- }
- }
-
- if (candidate != null) {
- // We found a better SDK target candidate, that is closer to the
- // API level from minSdkVersion than the one currently used by the
- // project. Below (in the for...devices loop) we'll try to find
- // a device/AVD for it.
- projectTarget = candidate;
- }
- }
-
- HashMap<IDevice, AvdInfo> compatibleRunningAvds = new HashMap<IDevice, AvdInfo>();
- boolean hasDevice = false; // if there's 1+ device running, we may force manual mode,
- // as we cannot always detect proper compatibility with
- // devices. This is the case if the project target is not
- // a standard platform
- for (IDevice d : devices) {
- String deviceAvd = d.getAvdName();
- if (deviceAvd != null) { // physical devices return null.
- AvdInfo info = avdManager.getAvd(deviceAvd, true /*validAvdOnly*/);
- if (AvdCompatibility.canRun(info, projectTarget, minApiVersion)
- == AvdCompatibility.Compatibility.YES) {
- compatibleRunningAvds.put(d, info);
- }
- } else {
- if (projectTarget.isPlatform()) { // means this can run on any device as long
- // as api level is high enough
- AndroidVersion deviceVersion = Sdk.getDeviceVersion(d);
- // the deviceVersion may be null if it wasn't yet queried (device just
- // plugged in or emulator just booting up.
- if (deviceVersion != null &&
- deviceVersion.canRun(projectTarget.getVersion())) {
- // device is compatible with project
- compatibleRunningAvds.put(d, null);
- continue;
- }
- } else {
- // for non project platform, we can't be sure if a device can
- // run an application or not, since we don't query the device
- // for the list of optional libraries that it supports.
- }
- hasDevice = true;
- }
- }
-
- // depending on the number of devices, we'll simulate an automatic choice
- // from the device chooser or simply show up the device chooser.
- if (hasDevice == false && compatibleRunningAvds.size() == 0) {
- // if zero emulators/devices, we launch an emulator.
- // We need to figure out which AVD first.
-
- // we are going to take the closest AVD. ie a compatible AVD that has the API level
- // closest to the project target.
- AvdInfo defaultAvd = findMatchingAvd(avdManager, projectTarget, minApiVersion);
-
- if (defaultAvd != null) {
- response.setAvdToLaunch(defaultAvd);
-
- AdtPlugin.printToConsole(project, String.format(
- "Automatic Target Mode: launching new emulator with compatible AVD '%1$s'",
- defaultAvd.getName()));
-
- continueLaunch(response, project, launch, launchInfo, config);
- return;
- } else {
- AdtPlugin.printToConsole(project, String.format(
- "Failed to find an AVD compatible with target '%1$s'.",
- projectTarget.getName()));
-
- final Display display = AdtPlugin.getDisplay();
- final boolean[] searchAgain = new boolean[] { false };
- // ask the user to create a new one.
- display.syncExec(new Runnable() {
- @Override
- public void run() {
- Shell shell = display.getActiveShell();
- if (MessageDialog.openQuestion(shell, "Android AVD Error",
- "No compatible targets were found. Do you wish to add a new Android Virtual Device?")) {
- AvdManagerAction action = new AvdManagerAction();
- action.run(null /*action*/);
- searchAgain[0] = true;
- }
- }
- });
- if (searchAgain[0]) {
- // attempt to reload the AVDs and find one compatible.
- defaultAvd = findMatchingAvd(avdManager, projectTarget, minApiVersion);
-
- if (defaultAvd == null) {
- AdtPlugin.printErrorToConsole(project, String.format(
- "Still no compatible AVDs with target '%1$s': Aborting launch.",
- projectTarget.getName()));
- stopLaunch(launchInfo);
- } else {
- response.setAvdToLaunch(defaultAvd);
-
- AdtPlugin.printToConsole(project, String.format(
- "Launching new emulator with compatible AVD '%1$s'",
- defaultAvd.getName()));
-
- continueLaunch(response, project, launch, launchInfo, config);
- return;
- }
- }
- }
- } else if (hasDevice == false && compatibleRunningAvds.size() == 1) {
- Entry<IDevice, AvdInfo> e = compatibleRunningAvds.entrySet().iterator().next();
- response.setDeviceToUse(e.getKey());
-
- // get the AvdInfo, if null, the device is a physical device.
- AvdInfo avdInfo = e.getValue();
- if (avdInfo != null) {
- message = String.format("Automatic Target Mode: using existing emulator '%1$s' running compatible AVD '%2$s'",
- response.getDeviceToUse(), e.getValue().getName());
- } else {
- message = String.format("Automatic Target Mode: using device '%1$s'",
- response.getDeviceToUse());
- }
- AdtPlugin.printToConsole(project, message);
-
- continueLaunch(response, project, launch, launchInfo, config);
- return;
- }
-
- // if more than one device, we'll bring up the DeviceChooser dialog below.
- if (compatibleRunningAvds.size() >= 2) {
- message = "Automatic Target Mode: Several compatible targets. Please select a target device.";
- } else if (hasDevice) {
- message = "Automatic Target Mode: Unable to detect device compatibility. Please select a target device.";
- }
-
- AdtPlugin.printToConsole(project, message);
- } else if ((config.mTargetMode == TargetMode.ALL_DEVICES_AND_EMULATORS
- || config.mTargetMode == TargetMode.ALL_DEVICES
- || config.mTargetMode == TargetMode.ALL_EMULATORS)
- && ILaunchManager.RUN_MODE.equals(mode)) {
- // if running on multiple devices, identify all compatible devices
- boolean includeDevices = config.mTargetMode != TargetMode.ALL_EMULATORS;
- boolean includeAvds = config.mTargetMode != TargetMode.ALL_DEVICES;
- Collection<IDevice> compatibleDevices = findCompatibleDevices(devices,
- minApiVersion, includeDevices, includeAvds);
- if (compatibleDevices.size() == 0) {
- AdtPlugin.printErrorToConsole(project,
- "No active compatible AVD's or devices found. "
- + "Relaunch this configuration after connecting a device or starting an AVD.");
- stopLaunch(launchInfo);
- } else {
- multiLaunch(launchInfo, compatibleDevices);
- }
- return;
- }
-
- // bring up the device chooser.
- final IAndroidTarget desiredProjectTarget = projectTarget;
- final AtomicBoolean continueLaunch = new AtomicBoolean(false);
- AdtPlugin.getDisplay().syncExec(new Runnable() {
- @Override
- public void run() {
- try {
- // open the chooser dialog. It'll fill 'response' with the device to use
- // or the AVD to launch.
- DeviceChooserDialog dialog = new DeviceChooserDialog(
- AdtPlugin.getShell(),
- response, launchInfo.getPackageName(),
- desiredProjectTarget, minApiVersion,
- config.mReuseLastUsedDevice);
- if (dialog.open() == Dialog.OK) {
- updateLaunchConfigWithLastUsedDevice(launch.getLaunchConfiguration(),
- response);
- continueLaunch.set(true);
- } else {
- AdtPlugin.printErrorToConsole(project, "Launch canceled!");
- stopLaunch(launchInfo);
- return;
- }
- } catch (Exception e) {
- // there seems to be some case where the shell will be null. (might be
- // an OS X bug). Because of this the creation of the dialog will throw
- // and IllegalArg exception interrupting the launch with no user feedback.
- // So we trap all the exception and display something.
- String msg = e.getMessage();
- if (msg == null) {
- msg = e.getClass().getCanonicalName();
- }
- AdtPlugin.printErrorToConsole(project,
- String.format("Error during launch: %s", msg));
- stopLaunch(launchInfo);
- }
- }
- });
-
- if (continueLaunch.get()) {
- continueLaunch(response, project, launch, launchInfo, config);
- }
- }
-
- /**
- * Returns devices that can run a app of provided API level.
- * @param devices list of devices to filter from
- * @param requiredVersion minimum required API that should be supported
- * @param includeDevices include physical devices in the filtered list
- * @param includeAvds include emulators in the filtered list
- * @return set of compatible devices, may be an empty set
- */
- private Collection<IDevice> findCompatibleDevices(IDevice[] devices,
- AndroidVersion requiredVersion, boolean includeDevices, boolean includeAvds) {
- Set<IDevice> compatibleDevices = new HashSet<IDevice>(devices.length);
- AvdManager avdManager = Sdk.getCurrent().getAvdManager();
- for (IDevice d: devices) {
- boolean isEmulator = d.isEmulator();
- boolean canRun = false;
-
- if (isEmulator) {
- if (!includeAvds) {
- continue;
- }
-
- AvdInfo avdInfo = avdManager.getAvd(d.getAvdName(), true);
- if (avdInfo != null && avdInfo.getTarget() != null) {
- canRun = avdInfo.getTarget().getVersion().canRun(requiredVersion);
- }
- } else {
- if (!includeDevices) {
- continue;
- }
-
- AndroidVersion deviceVersion = Sdk.getDeviceVersion(d);
- if (deviceVersion != null) {
- canRun = deviceVersion.canRun(requiredVersion);
- }
- }
-
- if (canRun) {
- compatibleDevices.add(d);
- }
- }
-
- return compatibleDevices;
- }
-
- /**
- * Find a matching AVD.
- * @param minApiVersion
- */
- private AvdInfo findMatchingAvd(AvdManager avdManager, final IAndroidTarget projectTarget,
- AndroidVersion minApiVersion) {
- AvdInfo[] avds = avdManager.getValidAvds();
- AvdInfo bestAvd = null;
- for (AvdInfo avd : avds) {
- if (AvdCompatibility.canRun(avd, projectTarget, minApiVersion)
- == AvdCompatibility.Compatibility.YES) {
- // at this point we can ignore the code name issue since
- // AvdCompatibility.canRun() will already have filtered out the non compatible AVDs.
- if (bestAvd == null ||
- avd.getTarget().getVersion().getApiLevel() <
- bestAvd.getTarget().getVersion().getApiLevel()) {
- bestAvd = avd;
- }
- }
- }
- return bestAvd;
- }
-
- /**
- * Continues the launch based on the DeviceChooser response.
- * @param response the device chooser response
- * @param project The project being launched
- * @param launch The eclipse launch info
- * @param launchInfo The {@link DelayedLaunchInfo}
- * @param config The config needed to start a new emulator.
- */
- private void continueLaunch(final DeviceChooserResponse response, final IProject project,
- final AndroidLaunch launch, final DelayedLaunchInfo launchInfo,
- final AndroidLaunchConfiguration config) {
- if (response.getAvdToLaunch() != null) {
- // there was no selected device, we start a new emulator.
- synchronized (sListLock) {
- AvdInfo info = response.getAvdToLaunch();
- mWaitingForEmulatorLaunches.add(launchInfo);
- AdtPlugin.printToConsole(project, String.format(
- "Launching a new emulator with Virtual Device '%1$s'",
- info.getName()));
- boolean status = launchEmulator(config, info);
-
- if (status == false) {
- // launching the emulator failed!
- AdtPlugin.displayError("Emulator Launch",
- "Couldn't launch the emulator! Make sure the SDK directory is properly setup and the emulator is not missing.");
-
- // stop the launch and return
- mWaitingForEmulatorLaunches.remove(launchInfo);
- AdtPlugin.printErrorToConsole(project, "Launch canceled!");
- stopLaunch(launchInfo);
- return;
- }
-
- return;
- }
- } else if (response.getDeviceToUse() != null) {
- launchInfo.setDevice(response.getDeviceToUse());
- simpleLaunch(launchInfo, launchInfo.getDevice());
- }
- }
-
- /**
- * Queries for a debugger port for a specific {@link ILaunchConfiguration}.
- * <p/>
- * If the configuration and a debugger port where added through
- * {@link #setPortLaunchConfigAssociation(ILaunchConfiguration, int)}, then this method
- * will return the debugger port, and remove the configuration from the list.
- * @param launchConfig the {@link ILaunchConfiguration}
- * @return the debugger port or {@link LaunchConfigDelegate#INVALID_DEBUG_PORT} if the
- * configuration was not setup.
- */
- static int getPortForConfig(ILaunchConfiguration launchConfig) {
- synchronized (sListLock) {
- Integer port = sRunningAppMap.get(launchConfig);
- if (port != null) {
- sRunningAppMap.remove(launchConfig);
- return port;
- }
- }
-
- return LaunchConfigDelegate.INVALID_DEBUG_PORT;
- }
-
- /**
- * Set a {@link ILaunchConfiguration} and its associated debug port, in the list of
- * launch config to connect directly to a running app instead of doing full launch (sync,
- * launch, and connect to).
- * @param launchConfig the {@link ILaunchConfiguration} object.
- * @param port The debugger port to connect to.
- */
- private static void setPortLaunchConfigAssociation(ILaunchConfiguration launchConfig,
- int port) {
- synchronized (sListLock) {
- sRunningAppMap.put(launchConfig, port);
- }
- }
-
- /**
- * Checks the build information, and returns whether the launch should continue.
- * <p/>The value tested are:
- * <ul>
- * <li>Minimum API version requested by the application. If the target device does not match,
- * the launch is canceled.</li>
- * <li>Debuggable attribute of the application and whether or not the device requires it. If
- * the device requires it and it is not set in the manifest, the launch will be forced to
- * "release" mode instead of "debug"</li>
- * <ul>
- */
- private boolean checkBuildInfo(DelayedLaunchInfo launchInfo, IDevice device) {
- if (device != null) {
- // check the app required API level versus the target device API level
-
- String deviceVersion = device.getProperty(IDevice.PROP_BUILD_VERSION);
- String deviceApiLevelString = device.getProperty(IDevice.PROP_BUILD_API_LEVEL);
- String deviceCodeName = device.getProperty(IDevice.PROP_BUILD_CODENAME);
-
- int deviceApiLevel = -1;
- try {
- deviceApiLevel = Integer.parseInt(deviceApiLevelString);
- } catch (NumberFormatException e) {
- // pass, we'll keep the apiLevel value at -1.
- }
-
- String requiredApiString = launchInfo.getRequiredApiVersionNumber();
- if (requiredApiString != null) {
- int requiredApi = -1;
- try {
- requiredApi = Integer.parseInt(requiredApiString);
- } catch (NumberFormatException e) {
- // pass, we'll keep requiredApi value at -1.
- }
-
- if (requiredApi == -1) {
- // this means the manifest uses a codename for minSdkVersion
- // check that the device is using the same codename
- if (requiredApiString.equals(deviceCodeName) == false) {
- AdtPlugin.printErrorToConsole(launchInfo.getProject(), String.format(
- "ERROR: Application requires a device running '%1$s'!",
- requiredApiString));
- return false;
- }
- } else {
- // app requires a specific API level
- if (deviceApiLevel == -1) {
- AdtPlugin.printToConsole(launchInfo.getProject(),
- "WARNING: Unknown device API version!");
- } else if (deviceApiLevel < requiredApi) {
- String msg = String.format(
- "ERROR: Application requires API version %1$d. Device API version is %2$d (Android %3$s).",
- requiredApi, deviceApiLevel, deviceVersion);
- AdtPlugin.printErrorToConsole(launchInfo.getProject(), msg);
-
- // abort the launch
- return false;
- }
- }
- } else {
- // warn the application API level requirement is not set.
- AdtPlugin.printErrorToConsole(launchInfo.getProject(),
- "WARNING: Application does not specify an API level requirement!");
-
- // and display the target device API level (if known)
- if (deviceApiLevel == -1) {
- AdtPlugin.printErrorToConsole(launchInfo.getProject(),
- "WARNING: Unknown device API version!");
- } else {
- AdtPlugin.printErrorToConsole(launchInfo.getProject(), String.format(
- "Device API version is %1$d (Android %2$s)", deviceApiLevel,
- deviceVersion));
- }
- }
-
- // now checks that the device/app can be debugged (if needed)
- if (device.isEmulator() == false && launchInfo.isDebugMode()) {
- String debuggableDevice = device.getProperty(IDevice.PROP_DEBUGGABLE);
- if (debuggableDevice != null && debuggableDevice.equals("0")) { //$NON-NLS-1$
- // the device is "secure" and requires apps to declare themselves as debuggable!
- // launchInfo.getDebuggable() will return null if the manifest doesn't declare
- // anything. In this case this is fine since the build system does insert
- // debuggable=true. The only case to look for is if false is manually set
- // in the manifest.
- if (launchInfo.getDebuggable() == Boolean.FALSE) {
- String message = String.format("Application '%1$s' has its 'debuggable' attribute set to FALSE and cannot be debugged.",
- launchInfo.getPackageName());
- AdtPlugin.printErrorToConsole(launchInfo.getProject(), message);
-
- // because am -D does not check for ro.debuggable and the
- // 'debuggable' attribute, it is important we do not use the -D option
- // in this case or the app will wait for a debugger forever and never
- // really launch.
- launchInfo.setDebugMode(false);
- }
- }
- }
- }
-
- return true;
- }
-
- /**
- * Do a simple launch on the specified device, attempting to sync the new
- * package, and then launching the application. Failed sync/launch will
- * stop the current AndroidLaunch and return false;
- * @param launchInfo
- * @param device
- * @return true if succeed
- */
- private boolean simpleLaunch(DelayedLaunchInfo launchInfo, IDevice device) {
- if (!doPreLaunchActions(launchInfo, device)) {
- AdtPlugin.printErrorToConsole(launchInfo.getProject(), "Launch canceled!");
- stopLaunch(launchInfo);
- return false;
- }
-
- // launch the app
- launchApp(launchInfo, device);
-
- return true;
- }
-
- private boolean doPreLaunchActions(DelayedLaunchInfo launchInfo, IDevice device) {
- // API level check
- if (!checkBuildInfo(launchInfo, device)) {
- return false;
- }
-
- // sync app
- if (!syncApp(launchInfo, device)) {
- return false;
- }
-
- return true;
- }
-
- private void multiLaunch(DelayedLaunchInfo launchInfo, Collection<IDevice> devices) {
- for (IDevice d: devices) {
- boolean success = doPreLaunchActions(launchInfo, d);
- if (!success) {
- String deviceName = d.isEmulator() ? d.getAvdName() : d.getSerialNumber();
- AdtPlugin.printErrorToConsole(launchInfo.getProject(),
- "Launch failed on device: " + deviceName);
- continue;
- }
- }
-
- doLaunchAction(launchInfo, devices);
-
- // multiple launches are only supported for run configuration, so we can terminate
- // the launch itself
- stopLaunch(launchInfo);
- }
-
- /**
- * If needed, syncs the application and all its dependencies on the device/emulator.
- *
- * @param launchInfo The Launch information object.
- * @param device the device on which to sync the application
- * @return true if the install succeeded.
- */
- private boolean syncApp(DelayedLaunchInfo launchInfo, IDevice device) {
- boolean alreadyInstalled = ApkInstallManager.getInstance().isApplicationInstalled(
- launchInfo.getProject(), launchInfo.getPackageName(), device);
-
- if (alreadyInstalled) {
- AdtPlugin.printToConsole(launchInfo.getProject(),
- "Application already deployed. No need to reinstall.");
- } else {
- if (doSyncApp(launchInfo, device) == false) {
- return false;
- }
- }
-
- // The app is now installed, now try the dependent projects
- for (DelayedLaunchInfo dependentLaunchInfo : getDependenciesLaunchInfo(launchInfo)) {
- String msg = String.format("Project dependency found, installing: %s",
- dependentLaunchInfo.getProject().getName());
- AdtPlugin.printToConsole(launchInfo.getProject(), msg);
- if (syncApp(dependentLaunchInfo, device) == false) {
- return false;
- }
- }
-
- return true;
- }
-
- /**
- * Syncs the application on the device/emulator.
- *
- * @param launchInfo The Launch information object.
- * @param device the device on which to sync the application
- * @return true if the install succeeded.
- */
- private boolean doSyncApp(DelayedLaunchInfo launchInfo, IDevice device) {
- IPath path = launchInfo.getPackageFile().getLocation();
- String fileName = path.lastSegment();
- try {
- String message = String.format("Uploading %1$s onto device '%2$s'",
- fileName, device.getSerialNumber());
- AdtPlugin.printToConsole(launchInfo.getProject(), message);
-
- String remotePackagePath = device.syncPackageToDevice(path.toOSString());
- boolean installResult = installPackage(launchInfo, remotePackagePath, device);
- device.removeRemotePackage(remotePackagePath);
-
- // if the installation succeeded, we register it.
- if (installResult) {
- ApkInstallManager.getInstance().registerInstallation(
- launchInfo.getProject(), launchInfo.getPackageName(), device);
- }
- return installResult;
- }
- catch (IOException e) {
- String msg = String.format("Failed to install %1$s on device '%2$s': %3$s", fileName,
- device.getSerialNumber(), e.getMessage());
- AdtPlugin.printErrorToConsole(launchInfo.getProject(), msg, e);
- } catch (TimeoutException e) {
- String msg = String.format("Failed to install %1$s on device '%2$s': timeout", fileName,
- device.getSerialNumber());
- AdtPlugin.printErrorToConsole(launchInfo.getProject(), msg);
- } catch (AdbCommandRejectedException e) {
- String msg = String.format(
- "Failed to install %1$s on device '%2$s': adb rejected install command with: %3$s",
- fileName, device.getSerialNumber(), e.getMessage());
- AdtPlugin.printErrorToConsole(launchInfo.getProject(), msg, e);
- } catch (CanceledException e) {
- if (e.wasCanceled()) {
- AdtPlugin.printToConsole(launchInfo.getProject(),
- String.format("Install of %1$s canceled", fileName));
- } else {
- String msg = String.format("Failed to install %1$s on device '%2$s': %3$s",
- fileName, device.getSerialNumber(), e.getMessage());
- AdtPlugin.printErrorToConsole(launchInfo.getProject(), msg, e);
- }
- }
-
- return false;
- }
-
- /**
- * For the current launchInfo, create additional DelayedLaunchInfo that should be used to
- * sync APKs that we are dependent on to the device.
- *
- * @param launchInfo the original launch info that we want to find the
- * @return a list of DelayedLaunchInfo (may be empty if no dependencies were found or error)
- */
- public List<DelayedLaunchInfo> getDependenciesLaunchInfo(DelayedLaunchInfo launchInfo) {
- List<DelayedLaunchInfo> dependencies = new ArrayList<DelayedLaunchInfo>();
-
- // Convert to equivalent JavaProject
- IJavaProject javaProject;
- try {
- //assuming this is an Android (and Java) project since it is attached to the launchInfo.
- javaProject = BaseProjectHelper.getJavaProject(launchInfo.getProject());
- } catch (CoreException e) {
- // return empty dependencies
- AdtPlugin.printErrorToConsole(launchInfo.getProject(), e);
- return dependencies;
- }
-
- // Get all projects that this depends on
- List<IJavaProject> androidProjectList;
- try {
- androidProjectList = ProjectHelper.getAndroidProjectDependencies(javaProject);
- } catch (JavaModelException e) {
- // return empty dependencies
- AdtPlugin.printErrorToConsole(launchInfo.getProject(), e);
- return dependencies;
- }
-
- // for each project, parse manifest and create launch information
- for (IJavaProject androidProject : androidProjectList) {
- // Parse the Manifest to get various required information
- // copied from LaunchConfigDelegate
- ManifestData manifestData = AndroidManifestHelper.parseForData(
- androidProject.getProject());
-
- if (manifestData == null) {
- continue;
- }
-
- // Get the APK location (can return null)
- IFile apk = ProjectHelper.getApplicationPackage(androidProject.getProject());
- if (apk == null) {
- // getApplicationPackage will have logged an error message
- continue;
- }
-
- // Create new launchInfo as an hybrid between parent and dependency information
- DelayedLaunchInfo delayedLaunchInfo = new DelayedLaunchInfo(
- androidProject.getProject(),
- manifestData.getPackage(),
- manifestData.getPackage(),
- launchInfo.getLaunchAction(),
- apk,
- manifestData.getDebuggable(),
- manifestData.getMinSdkVersionString(),
- launchInfo.getLaunch(),
- launchInfo.getMonitor());
-
- // Add to the list
- dependencies.add(delayedLaunchInfo);
- }
-
- return dependencies;
- }
-
- /**
- * Installs the application package on the device, and handles return result
- * @param launchInfo The launch information
- * @param remotePath The remote path of the package.
- * @param device The device on which the launch is done.
- */
- private boolean installPackage(DelayedLaunchInfo launchInfo, final String remotePath,
- final IDevice device) {
- String message = String.format("Installing %1$s...", launchInfo.getPackageFile().getName());
- AdtPlugin.printToConsole(launchInfo.getProject(), message);
- try {
- // try a reinstall first, because the most common case is the app is already installed
- String result = doInstall(launchInfo, remotePath, device, true /* reinstall */);
-
- /* For now we force to retry the install (after uninstalling) because there's no
- * other way around it: adb install does not want to update a package w/o uninstalling
- * the old one first!
- */
- return checkInstallResult(result, device, launchInfo, remotePath,
- InstallRetryMode.ALWAYS);
- } catch (Exception e) {
- String msg = String.format(
- "Failed to install %1$s on device '%2$s!",
- launchInfo.getPackageFile().getName(), device.getSerialNumber());
- AdtPlugin.printErrorToConsole(launchInfo.getProject(), msg, e.getMessage());
- }
-
- return false;
- }
-
- /**
- * Checks the result of an installation, and takes optional actions based on it.
- * @param result the result string from the installation
- * @param device the device on which the installation occured.
- * @param launchInfo the {@link DelayedLaunchInfo}
- * @param remotePath the temporary path of the package on the device
- * @param retryMode indicates what to do in case, a package already exists.
- * @return <code>true<code> if success, <code>false</code> otherwise.
- * @throws InstallException
- */
- private boolean checkInstallResult(String result, IDevice device, DelayedLaunchInfo launchInfo,
- String remotePath, InstallRetryMode retryMode) throws InstallException {
- if (result == null) {
- AdtPlugin.printToConsole(launchInfo.getProject(), "Success!");
- return true;
- }
- else if (result.equals("INSTALL_FAILED_ALREADY_EXISTS")) { //$NON-NLS-1$
- // this should never happen, since reinstall mode is used on the first attempt
- if (retryMode == InstallRetryMode.PROMPT) {
- boolean prompt = AdtPlugin.displayPrompt("Application Install",
- "A previous installation needs to be uninstalled before the new package can be installed.\nDo you want to uninstall?");
- if (prompt) {
- retryMode = InstallRetryMode.ALWAYS;
- } else {
- AdtPlugin.printErrorToConsole(launchInfo.getProject(),
- "Installation error! The package already exists.");
- return false;
- }
- }
-
- if (retryMode == InstallRetryMode.ALWAYS) {
- /*
- * TODO: create a UI that gives the dev the choice to:
- * - clean uninstall on launch
- * - full uninstall if application exists.
- * - soft uninstall if application exists (keeps the app data around).
- * - always ask (choice of soft-reinstall, full reinstall)
- AdtPlugin.printErrorToConsole(launchInfo.mProject,
- "Application already exists, uninstalling...");
- String res = doUninstall(device, launchInfo);
- if (res == null) {
- AdtPlugin.printToConsole(launchInfo.mProject, "Success!");
- } else {
- AdtPlugin.printErrorToConsole(launchInfo.mProject,
- String.format("Failed to uninstall: %1$s", res));
- return false;
- }
- */
-
- AdtPlugin.printToConsole(launchInfo.getProject(),
- "Application already exists. Attempting to re-install instead...");
- String res = doInstall(launchInfo, remotePath, device, true /* reinstall */ );
- return checkInstallResult(res, device, launchInfo, remotePath,
- InstallRetryMode.NEVER);
- }
- AdtPlugin.printErrorToConsole(launchInfo.getProject(),
- "Installation error! The package already exists.");
- } else if (result.equals("INSTALL_FAILED_INVALID_APK")) { //$NON-NLS-1$
- AdtPlugin.printErrorToConsole(launchInfo.getProject(),
- "Installation failed due to invalid APK file!",
- "Please check logcat output for more details.");
- } else if (result.equals("INSTALL_FAILED_INVALID_URI")) { //$NON-NLS-1$
- AdtPlugin.printErrorToConsole(launchInfo.getProject(),
- "Installation failed due to invalid URI!",
- "Please check logcat output for more details.");
- } else if (result.equals("INSTALL_FAILED_COULDNT_COPY")) { //$NON-NLS-1$
- AdtPlugin.printErrorToConsole(launchInfo.getProject(),
- String.format("Installation failed: Could not copy %1$s to its final location!",
- launchInfo.getPackageFile().getName()),
- "Please check logcat output for more details.");
- } else if (result.equals("INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES")) { //$NON-NLS-1$
- if (retryMode != InstallRetryMode.NEVER) {
- boolean prompt = AdtPlugin.displayPrompt("Application Install",
- "Re-installation failed due to different application signatures. You must perform a full uninstall of the application. WARNING: This will remove the application data!\nDo you want to uninstall?");
- if (prompt) {
- doUninstall(device, launchInfo);
- String res = doInstall(launchInfo, remotePath, device, false);
- return checkInstallResult(res, device, launchInfo, remotePath,
- InstallRetryMode.NEVER);
- }
- }
- AdtPlugin.printErrorToConsole(launchInfo.getProject(),
- "Re-installation failed due to different application signatures.",
- "You must perform a full uninstall of the application. WARNING: This will remove the application data!",
- String.format("Please execute 'adb uninstall %1$s' in a shell.", launchInfo.getPackageName()));
- } else {
- AdtPlugin.printErrorToConsole(launchInfo.getProject(),
- String.format("Installation error: %1$s", result),
- "Please check logcat output for more details.");
- }
-
- return false;
- }
-
- /**
- * Performs the uninstallation of an application.
- * @param device the device on which to install the application.
- * @param launchInfo the {@link DelayedLaunchInfo}.
- * @return a {@link String} with an error code, or <code>null</code> if success.
- * @throws InstallException if the installation failed.
- */
- private String doUninstall(IDevice device, DelayedLaunchInfo launchInfo)
- throws InstallException {
- try {
- return device.uninstallPackage(launchInfo.getPackageName());
- } catch (InstallException e) {
- String msg = String.format(
- "Failed to uninstall %1$s: %2$s", launchInfo.getPackageName(), e.getMessage());
- AdtPlugin.printErrorToConsole(launchInfo.getProject(), msg);
- throw e;
- }
- }
-
- /**
- * Performs the installation of an application whose package has been uploaded on the device.
- *
- * @param launchInfo the {@link DelayedLaunchInfo}.
- * @param remotePath the path of the application package in the device tmp folder.
- * @param device the device on which to install the application.
- * @param reinstall
- * @return a {@link String} with an error code, or <code>null</code> if success.
- * @throws InstallException if the uninstallation failed.
- */
- private String doInstall(DelayedLaunchInfo launchInfo, final String remotePath,
- final IDevice device, boolean reinstall) throws InstallException {
- return device.installRemotePackage(remotePath, reinstall);
- }
-
- /**
- * launches an application on a device or emulator
- *
- * @param info the {@link DelayedLaunchInfo} that indicates the launch action
- * @param device the device or emulator to launch the application on
- */
- @Override
- public void launchApp(final DelayedLaunchInfo info, IDevice device) {
- if (info.isDebugMode()) {
- synchronized (sListLock) {
- if (mWaitingForDebuggerApplications.contains(info) == false) {
- mWaitingForDebuggerApplications.add(info);
- }
- }
- }
- if (doLaunchAction(info, device)) {
- // if the app is not a debug app, we need to do some clean up, as
- // the process is done!
- if (info.isDebugMode() == false) {
- // stop the launch object, since there's no debug, and it can't
- // provide any control over the app
- stopLaunch(info);
- }
- } else {
- // something went wrong or no further launch action needed
- // lets stop the Launch
- stopLaunch(info);
- }
- }
-
- private boolean doLaunchAction(final DelayedLaunchInfo info, Collection<IDevice> devices) {
- boolean result = info.getLaunchAction().doLaunchAction(info, devices);
-
- // Monitor the logcat output on the launched device to notify
- // the user if any significant error occurs that is visible from logcat
- for (IDevice d : devices) {
- DdmsPlugin.getDefault().startLogCatMonitor(d);
- }
-
- return result;
- }
-
- private boolean doLaunchAction(final DelayedLaunchInfo info, IDevice device) {
- return doLaunchAction(info, Collections.singletonList(device));
- }
-
- private boolean launchEmulator(AndroidLaunchConfiguration config, AvdInfo avdToLaunch) {
-
- // split the custom command line in segments
- ArrayList<String> customArgs = new ArrayList<String>();
- boolean hasWipeData = false;
- if (config.mEmulatorCommandLine != null && config.mEmulatorCommandLine.length() > 0) {
- String[] segments = config.mEmulatorCommandLine.split("\\s+"); //$NON-NLS-1$
-
- // we need to remove the empty strings
- for (String s : segments) {
- if (s.length() > 0) {
- customArgs.add(s);
- if (!hasWipeData && s.equals(FLAG_WIPE_DATA)) {
- hasWipeData = true;
- }
- }
- }
- }
-
- boolean needsWipeData = config.mWipeData && !hasWipeData;
- if (needsWipeData) {
- if (!AdtPlugin.displayPrompt("Android Launch", "Are you sure you want to wipe all user data when starting this emulator?")) {
- needsWipeData = false;
- }
- }
-
- // build the command line based on the available parameters.
- ArrayList<String> list = new ArrayList<String>();
-
- String path = AdtPlugin.getOsAbsoluteEmulator();
-
- list.add(path);
-
- list.add(FLAG_AVD);
- list.add(avdToLaunch.getName());
-
- if (config.mNetworkSpeed != null) {
- list.add(FLAG_NETSPEED);
- list.add(config.mNetworkSpeed);
- }
-
- if (config.mNetworkDelay != null) {
- list.add(FLAG_NETDELAY);
- list.add(config.mNetworkDelay);
- }
-
- if (needsWipeData) {
- list.add(FLAG_WIPE_DATA);
- }
-
- if (config.mNoBootAnim) {
- list.add(FLAG_NO_BOOT_ANIM);
- }
-
- list.addAll(customArgs);
-
- // convert the list into an array for the call to exec.
- String[] command = list.toArray(new String[list.size()]);
-
- // launch the emulator
- try {
- Process process = Runtime.getRuntime().exec(command);
- grabEmulatorOutput(process);
- } catch (IOException e) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Looks for and returns an existing {@link ILaunchConfiguration} object for a
- * specified project.
- * @param manager The {@link ILaunchManager}.
- * @param type The {@link ILaunchConfigurationType}.
- * @param projectName The name of the project
- * @return an existing <code>ILaunchConfiguration</code> object matching the project, or
- * <code>null</code>.
- */
- private static ILaunchConfiguration findConfig(ILaunchManager manager,
- ILaunchConfigurationType type, String projectName) {
- try {
- ILaunchConfiguration[] configs = manager.getLaunchConfigurations(type);
-
- for (ILaunchConfiguration config : configs) {
- if (config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME,
- "").equals(projectName)) { //$NON-NLS-1$
- return config;
- }
- }
- } catch (CoreException e) {
- MessageDialog.openError(AdtPlugin.getShell(),
- "Launch Error", e.getStatus().getMessage());
- }
-
- // didn't find anything that matches. Return null
- return null;
- }
-
-
- /**
- * Connects a remote debugger on the specified port.
- * @param debugPort The port to connect the debugger to
- * @param launch The associated AndroidLaunch object.
- * @param monitor A Progress monitor
- * @return false if cancelled by the monitor
- * @throws CoreException
- */
- @SuppressWarnings("deprecation")
- public static boolean connectRemoteDebugger(int debugPort,
- AndroidLaunch launch, IProgressMonitor monitor)
- throws CoreException {
- // get some default parameters.
- int connectTimeout = JavaRuntime.getPreferences().getInt(JavaRuntime.PREF_CONNECT_TIMEOUT);
-
- HashMap<String, String> newMap = new HashMap<String, String>();
-
- newMap.put("hostname", "localhost"); //$NON-NLS-1$ //$NON-NLS-2$
-
- newMap.put("port", Integer.toString(debugPort)); //$NON-NLS-1$
-
- newMap.put("timeout", Integer.toString(connectTimeout));
-
- // get the default VM connector
- IVMConnector connector = JavaRuntime.getDefaultVMConnector();
-
- // connect to remote VM
- connector.connect(newMap, monitor, launch);
-
- // check for cancellation
- if (monitor.isCanceled()) {
- IDebugTarget[] debugTargets = launch.getDebugTargets();
- for (IDebugTarget target : debugTargets) {
- if (target.canDisconnect()) {
- target.disconnect();
- }
- }
- return false;
- }
-
- return true;
- }
-
- /**
- * Launch a new thread that connects a remote debugger on the specified port.
- * @param debugPort The port to connect the debugger to
- * @param androidLaunch The associated AndroidLaunch object.
- * @param monitor A Progress monitor
- * @see #connectRemoteDebugger(int, AndroidLaunch, IProgressMonitor)
- */
- public static void launchRemoteDebugger(final int debugPort, final AndroidLaunch androidLaunch,
- final IProgressMonitor monitor) {
- new Thread("Debugger connection") { //$NON-NLS-1$
- @Override
- public void run() {
- try {
- connectRemoteDebugger(debugPort, androidLaunch, monitor);
- } catch (CoreException e) {
- androidLaunch.stopLaunch();
- }
- monitor.done();
- }
- }.start();
- }
-
- /**
- * Sent when a new {@link AndroidDebugBridge} is started.
- * <p/>
- * This is sent from a non UI thread.
- * @param bridge the new {@link AndroidDebugBridge} object.
- *
- * @see IDebugBridgeChangeListener#bridgeChanged(AndroidDebugBridge)
- */
- @Override
- public void bridgeChanged(AndroidDebugBridge bridge) {
- // The adb server has changed. We cancel any pending launches.
- String message = "adb server change: cancelling '%1$s'!";
- synchronized (sListLock) {
- for (DelayedLaunchInfo launchInfo : mWaitingForReadyEmulatorList) {
- AdtPlugin.printErrorToConsole(launchInfo.getProject(),
- String.format(message, launchInfo.getLaunchAction().getLaunchDescription()));
- stopLaunch(launchInfo);
- }
- for (DelayedLaunchInfo launchInfo : mWaitingForDebuggerApplications) {
- AdtPlugin.printErrorToConsole(launchInfo.getProject(),
- String.format(message,
- launchInfo.getLaunchAction().getLaunchDescription()));
- stopLaunch(launchInfo);
- }
-
- mWaitingForReadyEmulatorList.clear();
- mWaitingForDebuggerApplications.clear();
- }
- }
-
- /**
- * Sent when the a device is connected to the {@link AndroidDebugBridge}.
- * <p/>
- * This is sent from a non UI thread.
- * @param device the new device.
- *
- * @see IDeviceChangeListener#deviceConnected(IDevice)
- */
- @Override
- public void deviceConnected(IDevice device) {
- synchronized (sListLock) {
- // look if there's an app waiting for a device
- if (mWaitingForEmulatorLaunches.size() > 0) {
- // get/remove first launch item from the list
- // FIXME: what if we have multiple launches waiting?
- DelayedLaunchInfo launchInfo = mWaitingForEmulatorLaunches.get(0);
- mWaitingForEmulatorLaunches.remove(0);
-
- // give the launch item its device for later use.
- launchInfo.setDevice(device);
-
- // and move it to the other list
- mWaitingForReadyEmulatorList.add(launchInfo);
-
- // and tell the user about it
- AdtPlugin.printToConsole(launchInfo.getProject(),
- String.format("New emulator found: %1$s", device.getSerialNumber()));
- AdtPlugin.printToConsole(launchInfo.getProject(),
- String.format("Waiting for HOME ('%1$s') to be launched...",
- AdtPlugin.getDefault().getPreferenceStore().getString(
- AdtPrefs.PREFS_HOME_PACKAGE)));
- }
- }
- }
-
- /**
- * Sent when the a device is connected to the {@link AndroidDebugBridge}.
- * <p/>
- * This is sent from a non UI thread.
- * @param device the new device.
- *
- * @see IDeviceChangeListener#deviceDisconnected(IDevice)
- */
- @Override
- public void deviceDisconnected(IDevice device) {
- // any pending launch on this device must be canceled.
- String message = "%1$s disconnected! Cancelling '%2$s'!";
- synchronized (sListLock) {
- ArrayList<DelayedLaunchInfo> copyList =
- (ArrayList<DelayedLaunchInfo>) mWaitingForReadyEmulatorList.clone();
- for (DelayedLaunchInfo launchInfo : copyList) {
- if (launchInfo.getDevice() == device) {
- AdtPlugin.printErrorToConsole(launchInfo.getProject(),
- String.format(message, device.getSerialNumber(),
- launchInfo.getLaunchAction().getLaunchDescription()));
- stopLaunch(launchInfo);
- }
- }
- copyList = (ArrayList<DelayedLaunchInfo>) mWaitingForDebuggerApplications.clone();
- for (DelayedLaunchInfo launchInfo : copyList) {
- if (launchInfo.getDevice() == device) {
- AdtPlugin.printErrorToConsole(launchInfo.getProject(),
- String.format(message, device.getSerialNumber(),
- launchInfo.getLaunchAction().getLaunchDescription()));
- stopLaunch(launchInfo);
- }
- }
- }
- }
-
- /**
- * Sent when a device data changed, or when clients are started/terminated on the device.
- * <p/>
- * This is sent from a non UI thread.
- * @param device the device that was updated.
- * @param changeMask the mask indicating what changed.
- *
- * @see IDeviceChangeListener#deviceChanged(IDevice, int)
- */
- @Override
- public void deviceChanged(IDevice device, int changeMask) {
- // We could check if any starting device we care about is now ready, but we can wait for
- // its home app to show up, so...
- }
-
- /**
- * Sent when an existing client information changed.
- * <p/>
- * This is sent from a non UI thread.
- * @param client the updated client.
- * @param changeMask the bit mask describing the changed properties. It can contain
- * any of the following values: {@link Client#CHANGE_INFO}, {@link Client#CHANGE_NAME}
- * {@link Client#CHANGE_DEBUGGER_STATUS}, {@link Client#CHANGE_THREAD_MODE},
- * {@link Client#CHANGE_THREAD_DATA}, {@link Client#CHANGE_HEAP_MODE},
- * {@link Client#CHANGE_HEAP_DATA}, {@link Client#CHANGE_NATIVE_HEAP_DATA}
- *
- * @see IClientChangeListener#clientChanged(Client, int)
- */
- @Override
- public void clientChanged(final Client client, int changeMask) {
- boolean connectDebugger = false;
- if ((changeMask & Client.CHANGE_NAME) == Client.CHANGE_NAME) {
- String applicationName = client.getClientData().getClientDescription();
- if (applicationName != null) {
- IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore();
- String home = store.getString(AdtPrefs.PREFS_HOME_PACKAGE);
-
- if (home.equals(applicationName)) {
-
- // looks like home is up, get its device
- IDevice device = client.getDevice();
-
- // look for application waiting for home
- synchronized (sListLock) {
- for (int i = 0; i < mWaitingForReadyEmulatorList.size(); ) {
- DelayedLaunchInfo launchInfo = mWaitingForReadyEmulatorList.get(i);
- if (launchInfo.getDevice() == device) {
- // it's match, remove from the list
- mWaitingForReadyEmulatorList.remove(i);
-
- // We couldn't check earlier the API level of the device
- // (it's asynchronous when the device boot, and usually
- // deviceConnected is called before it's queried for its build info)
- // so we check now
- if (checkBuildInfo(launchInfo, device) == false) {
- // device is not the proper API!
- AdtPlugin.printErrorToConsole(launchInfo.getProject(),
- "Launch canceled!");
- stopLaunch(launchInfo);
- return;
- }
-
- AdtPlugin.printToConsole(launchInfo.getProject(),
- String.format("HOME is up on device '%1$s'",
- device.getSerialNumber()));
-
- // attempt to sync the new package onto the device.
- if (syncApp(launchInfo, device)) {
- // application package is sync'ed, lets attempt to launch it.
- launchApp(launchInfo, device);
- } else {
- // failure! Cancel and return
- AdtPlugin.printErrorToConsole(launchInfo.getProject(),
- "Launch canceled!");
- stopLaunch(launchInfo);
- }
-
- break;
- } else {
- i++;
- }
- }
- }
- }
-
- // check if it's already waiting for a debugger, and if so we connect to it.
- if (client.getClientData().getDebuggerConnectionStatus() == DebuggerStatus.WAITING) {
- // search for this client in the list;
- synchronized (sListLock) {
- int index = mUnknownClientsWaitingForDebugger.indexOf(client);
- if (index != -1) {
- connectDebugger = true;
- mUnknownClientsWaitingForDebugger.remove(client);
- }
- }
- }
- }
- }
-
- // if it's not home, it could be an app that is now in debugger mode that we're waiting for
- // lets check it
-
- if ((changeMask & Client.CHANGE_DEBUGGER_STATUS) == Client.CHANGE_DEBUGGER_STATUS) {
- ClientData clientData = client.getClientData();
- String applicationName = client.getClientData().getClientDescription();
- if (clientData.getDebuggerConnectionStatus() == DebuggerStatus.WAITING) {
- // Get the application name, and make sure its valid.
- if (applicationName == null) {
- // looks like we don't have the client yet, so we keep it around for when its
- // name becomes available.
- synchronized (sListLock) {
- mUnknownClientsWaitingForDebugger.add(client);
- }
- return;
- } else {
- connectDebugger = true;
- }
- }
- }
-
- if (connectDebugger) {
- Log.d("adt", "Debugging " + client);
- // now check it against the apps waiting for a debugger
- String applicationName = client.getClientData().getClientDescription();
- Log.d("adt", "App Name: " + applicationName);
- synchronized (sListLock) {
- for (int i = 0; i < mWaitingForDebuggerApplications.size(); ) {
- final DelayedLaunchInfo launchInfo = mWaitingForDebuggerApplications.get(i);
- if (client.getDevice() == launchInfo.getDevice() &&
- applicationName.equals(launchInfo.getDebugPackageName())) {
- // this is a match. We remove the launch info from the list
- mWaitingForDebuggerApplications.remove(i);
-
- // and connect the debugger.
- String msg = String.format(
- "Attempting to connect debugger to '%1$s' on port %2$d",
- launchInfo.getDebugPackageName(), client.getDebuggerListenPort());
- AdtPlugin.printToConsole(launchInfo.getProject(), msg);
-
- new Thread("Debugger Connection") { //$NON-NLS-1$
- @Override
- public void run() {
- try {
- if (connectRemoteDebugger(
- client.getDebuggerListenPort(),
- launchInfo.getLaunch(),
- launchInfo.getMonitor()) == false) {
- return;
- }
- } catch (CoreException e) {
- // well something went wrong.
- AdtPlugin.printErrorToConsole(launchInfo.getProject(),
- String.format("Launch error: %s", e.getMessage()));
- // stop the launch
- stopLaunch(launchInfo);
- }
-
- launchInfo.getMonitor().done();
- }
- }.start();
-
- // we're done processing this client.
- return;
-
- } else {
- i++;
- }
- }
- }
-
- // if we get here, we haven't found an app that we were launching, so we look
- // for opened android projects that contains the app asking for a debugger.
- // If we find one, we automatically connect to it.
- IProject project = ProjectHelper.findAndroidProjectByAppName(applicationName);
-
- if (project != null) {
- debugRunningApp(project, client.getDebuggerListenPort());
- }
- }
- }
-
- /**
- * Get the stderr/stdout outputs of a process and return when the process is done.
- * Both <b>must</b> be read or the process will block on windows.
- * @param process The process to get the output from
- */
- private void grabEmulatorOutput(final Process process) {
- // read the lines as they come. if null is returned, it's
- // because the process finished
- new Thread("") { //$NON-NLS-1$
- @Override
- public void run() {
- // create a buffer to read the stderr output
- InputStreamReader is = new InputStreamReader(process.getErrorStream());
- BufferedReader errReader = new BufferedReader(is);
-
- try {
- while (true) {
- String line = errReader.readLine();
- if (line != null) {
- AdtPlugin.printErrorToConsole("Emulator", line);
- } else {
- break;
- }
- }
- } catch (IOException e) {
- // do nothing.
- }
- }
- }.start();
-
- new Thread("") { //$NON-NLS-1$
- @Override
- public void run() {
- InputStreamReader is = new InputStreamReader(process.getInputStream());
- BufferedReader outReader = new BufferedReader(is);
-
- try {
- while (true) {
- String line = outReader.readLine();
- if (line != null) {
- AdtPlugin.printToConsole("Emulator", line);
- } else {
- break;
- }
- }
- } catch (IOException e) {
- // do nothing.
- }
- }
- }.start();
- }
-
- /* (non-Javadoc)
- * @see com.android.ide.eclipse.adt.launch.ILaunchController#stopLaunch(com.android.ide.eclipse.adt.launch.AndroidLaunchController.DelayedLaunchInfo)
- */
- @Override
- public void stopLaunch(DelayedLaunchInfo launchInfo) {
- launchInfo.getLaunch().stopLaunch();
- synchronized (sListLock) {
- mWaitingForReadyEmulatorList.remove(launchInfo);
- mWaitingForDebuggerApplications.remove(launchInfo);
- }
- }
-
- public static void updateLaunchConfigWithLastUsedDevice(
- ILaunchConfiguration launchConfiguration, DeviceChooserResponse response) {
- try {
- boolean configModified = false;
- boolean reuse = launchConfiguration.getAttribute(
- LaunchConfigDelegate.ATTR_REUSE_LAST_USED_DEVICE, false);
- String serial = launchConfiguration.getAttribute(
- LaunchConfigDelegate.ATTR_LAST_USED_DEVICE, (String)null);
-
- ILaunchConfigurationWorkingCopy wc = launchConfiguration.getWorkingCopy();
- if (reuse != response.useDeviceForFutureLaunches()) {
- reuse = response.useDeviceForFutureLaunches();
- wc.setAttribute(LaunchConfigDelegate.ATTR_REUSE_LAST_USED_DEVICE, reuse);
- configModified = true;
- }
-
- if (reuse) {
- String selected = getSerial(response);
- if (selected != null && !selected.equalsIgnoreCase(serial)) {
- wc.setAttribute(LaunchConfigDelegate.ATTR_LAST_USED_DEVICE, selected);
- configModified = true;
- }
- }
-
- if (configModified) {
- wc.doSave();
- }
- } catch (CoreException e) {
- // in such a case, users just won't see this setting take effect
- return;
- }
- }
-
- private static String getSerial(DeviceChooserResponse response) {
- AvdInfo avd = response.getAvdToLaunch();
- return (avd != null) ? avd.getName() : response.getDeviceToUse().getSerialNumber();
- }
-
- @Nullable
- public static IDevice getDeviceIfOnline(@Nullable String serial,
- @NonNull IDevice[] onlineDevices) {
- if (serial == null) {
- return null;
- }
-
- for (IDevice device : onlineDevices) {
- if (serial.equals(device.getAvdName()) ||
- serial.equals(device.getSerialNumber())) {
- return device;
- }
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AvdCompatibility.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AvdCompatibility.java
deleted file mode 100644
index 6133002bc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/AvdCompatibility.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.launch;
-
-import com.android.sdklib.AndroidVersion;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.internal.avd.AvdInfo;
-
-public class AvdCompatibility {
- public enum Compatibility {
- YES,
- NO,
- UNKNOWN,
- };
-
- /**
- * Returns whether the specified AVD can run the given project that is built against
- * a particular SDK and has the specified minApiLevel.
- * @param avd AVD to check compatibility for
- * @param projectTarget project build target
- * @param minApiVersion project min api level
- * @return whether the given AVD can run the given application
- */
- public static Compatibility canRun(AvdInfo avd, IAndroidTarget projectTarget,
- AndroidVersion minApiVersion) {
- if (avd == null) {
- return Compatibility.UNKNOWN;
- }
-
- IAndroidTarget avdTarget = avd.getTarget();
- if (avdTarget == null) {
- return Compatibility.UNKNOWN;
- }
-
- // for platform targets, we only need to check the min api version
- if (projectTarget.isPlatform()) {
- return avdTarget.getVersion().canRun(minApiVersion) ?
- Compatibility.YES : Compatibility.NO;
- }
-
- // for add-on targets, delegate to the add on target to check for compatibility
- return projectTarget.canRunOn(avdTarget) ? Compatibility.YES : Compatibility.NO;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/DelayedLaunchInfo.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/DelayedLaunchInfo.java
deleted file mode 100644
index b0a6dda20..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/DelayedLaunchInfo.java
+++ /dev/null
@@ -1,244 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.launch;
-
-import com.android.ddmlib.IDevice;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IProgressMonitor;
-
-/**
- * A delayed launch waiting for a device to be present or ready before the
- * application is launched.
- */
-public final class DelayedLaunchInfo {
-
- /**
- * Used to indicate behavior when Android app already exists
- */
- enum InstallRetryMode {
- NEVER, ALWAYS, PROMPT;
- }
-
- /** The device on which to launch the app */
- private IDevice mDevice = null;
-
- /** The eclipse project */
- private final IProject mProject;
-
- /** Package name */
- private final String mPackageName;
-
- /** Debug package name */
- private final String mDebugPackageName;
-
- /** IFile to the package (.apk) file */
- private final IFile mPackageFile;
-
- /** debuggable attribute of the manifest file. */
- private final Boolean mDebuggable;
-
- /** Required Api level by the app. null means no requirements */
- private final String mRequiredApiVersionNumber;
-
- private InstallRetryMode mRetryMode = InstallRetryMode.NEVER;
-
- /** Launch action. */
- private final IAndroidLaunchAction mLaunchAction;
-
- /** the launch object */
- private final AndroidLaunch mLaunch;
-
- /** the monitor object */
- private final IProgressMonitor mMonitor;
-
- /** debug mode flag */
- private boolean mDebugMode;
-
- /** current number of launch attempts */
- private int mAttemptCount = 0;
-
- /** cancellation state of launch */
- private boolean mCancelled = false;
-
- /**
- * Basic constructor with activity and package info.
- *
- * @param project the eclipse project that corresponds to Android app
- * @param packageName package name of Android app
- * @param debugPackageName the package name of the Andriod app to debug
- * @param launchAction action to perform after app install
- * @param pack IFile to the package (.apk) file
- * @param debuggable the debuggable value of the app's manifest, or null if not set.
- * @param requiredApiVersionNumber required SDK version by the app. null means no requirements.
- * @param launch the launch object
- * @param monitor progress monitor for launch
- */
- public DelayedLaunchInfo(IProject project, String packageName, String debugPackageName,
- IAndroidLaunchAction launchAction, IFile pack, Boolean debuggable,
- String requiredApiVersionNumber, AndroidLaunch launch, IProgressMonitor monitor) {
- mProject = project;
- mPackageName = packageName;
- mDebugPackageName = debugPackageName;
- mPackageFile = pack;
- mLaunchAction = launchAction;
- mLaunch = launch;
- mMonitor = monitor;
- mDebuggable = debuggable;
- mRequiredApiVersionNumber = requiredApiVersionNumber;
- }
-
- /**
- * @return the device on which to launch the app
- */
- public IDevice getDevice() {
- return mDevice;
- }
-
- /**
- * Set the device on which to launch the app
- */
- public void setDevice(IDevice device) {
- mDevice = device;
- }
-
- /**
- * @return the eclipse project that corresponds to Android app
- */
- public IProject getProject() {
- return mProject;
- }
-
- /**
- * @return the package name of the Android app
- */
- public String getPackageName() {
- return mPackageName;
- }
-
- /**
- * Returns the Android app process name that the debugger should connect to. Typically this is
- * the same value as {@link #getPackageName()}.
- */
- public String getDebugPackageName() {
- if (mDebugPackageName == null) {
- return getPackageName();
- }
- return mDebugPackageName;
- }
-
- /**
- * @return the application package file
- */
- public IFile getPackageFile() {
- return mPackageFile;
- }
-
- /**
- * Returns the value of the manifest debuggable attribute. If the attribute was not set,
- * then the method returns null.
- * @return the manifest debuggable attribute.
- */
- public Boolean getDebuggable() {
- return mDebuggable;
- }
-
- /**
- * @return the required api version number for the Android app.
- */
- public String getRequiredApiVersionNumber() {
- return mRequiredApiVersionNumber;
- }
-
- /**
- * @param retryMode the install retry mode to set
- */
- public void setRetryMode(InstallRetryMode retryMode) {
- this.mRetryMode = retryMode;
- }
-
- /**
- * @return the installation retry mode
- */
- public InstallRetryMode getRetryMode() {
- return mRetryMode;
- }
-
- /**
- * @return the launch action
- */
- public IAndroidLaunchAction getLaunchAction() {
- return mLaunchAction;
- }
-
- /**
- * @return the launch
- */
- public AndroidLaunch getLaunch() {
- return mLaunch;
- }
-
- /**
- * @return the launch progress monitor
- */
- public IProgressMonitor getMonitor() {
- return mMonitor;
- }
-
- /**
- * @param debugMode the debug mode to set
- */
- public void setDebugMode(boolean debugMode) {
- this.mDebugMode = debugMode;
- }
-
- /**
- * @return true if this is a debug launch
- */
- public boolean isDebugMode() {
- return mDebugMode;
- }
-
- /**
- * Increases the number of launch attempts
- */
- public void incrementAttemptCount() {
- mAttemptCount++;
- }
-
- /**
- * @return the number of launch attempts made
- */
- public int getAttemptCount() {
- return mAttemptCount;
- }
-
- /**
- * Set if launch has been cancelled
- */
- public void setCancelled(boolean cancelled) {
- this.mCancelled = cancelled;
- }
-
- /**
- * @return true if launch has been cancelled
- */
- public boolean isCancelled() {
- return mCancelled;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/DeviceChooserDialog.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/DeviceChooserDialog.java
deleted file mode 100644
index 995ccdf46..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/DeviceChooserDialog.java
+++ /dev/null
@@ -1,824 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.launch;
-
-import com.android.ddmlib.AndroidDebugBridge;
-import com.android.ddmlib.AndroidDebugBridge.IDeviceChangeListener;
-import com.android.ddmlib.Client;
-import com.android.ddmlib.IDevice;
-import com.android.ddmlib.IDevice.DeviceState;
-import com.android.ddmuilib.ImageLoader;
-import com.android.ddmuilib.TableHelper;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.sdk.AdtConsoleSdkLog;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.ddms.DdmsPlugin;
-import com.android.sdklib.AndroidVersion;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.internal.avd.AvdInfo;
-import com.android.sdkuilib.internal.widgets.AvdSelector;
-import com.android.sdkuilib.internal.widgets.AvdSelector.DisplayMode;
-import com.android.sdkuilib.internal.widgets.AvdSelector.IAvdFilter;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.SWTException;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Table;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * A dialog that lets the user choose a device to deploy an application.
- * The user can either choose an exiting running device (including running emulators)
- * or start a new emulator using an Android Virtual Device configuration that matches
- * the current project.
- */
-public class DeviceChooserDialog extends Dialog implements IDeviceChangeListener {
-
- private final static int ICON_WIDTH = 16;
-
- private Table mDeviceTable;
- private TableViewer mViewer;
- private AvdSelector mPreferredAvdSelector;
-
- private Image mDeviceImage;
- private Image mEmulatorImage;
- private Image mMatchImage;
- private Image mNoMatchImage;
- private Image mWarningImage;
-
- private final DeviceChooserResponse mResponse;
- private final String mPackageName;
- private final IAndroidTarget mProjectTarget;
- private final AndroidVersion mMinApiVersion;
- private final Sdk mSdk;
-
- private Button mDeviceRadioButton;
- private Button mUseDeviceForFutureLaunchesCheckbox;
- private boolean mUseDeviceForFutureLaunches;
-
- private boolean mDisableAvdSelectionChange = false;
-
- /**
- * Basic Content Provider for a table full of {@link IDevice} objects. The input is
- * a {@link AndroidDebugBridge}.
- */
- private class ContentProvider implements IStructuredContentProvider {
- @Override
- public Object[] getElements(Object inputElement) {
- if (inputElement instanceof AndroidDebugBridge) {
- return findCompatibleDevices(((AndroidDebugBridge)inputElement).getDevices());
- }
-
- return new Object[0];
- }
-
- private Object[] findCompatibleDevices(IDevice[] devices) {
- if (devices == null) {
- return null;
- }
-
- List<IDevice> compatibleDevices = new ArrayList<IDevice>(devices.length);
- for (IDevice device : devices) {
- AndroidVersion deviceVersion = Sdk.getDeviceVersion(device);
- if (deviceVersion == null || deviceVersion.canRun(mMinApiVersion)) {
- compatibleDevices.add(device);
- }
- }
-
- return compatibleDevices.toArray();
- }
-
- @Override
- public void dispose() {
- // pass
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- // pass
- }
- }
-
- /**
- * A Label Provider for the {@link TableViewer} in {@link DeviceChooserDialog}.
- * It provides labels and images for {@link IDevice} objects.
- */
- private class LabelProvider implements ITableLabelProvider {
-
- @Override
- public Image getColumnImage(Object element, int columnIndex) {
- if (element instanceof IDevice) {
- IDevice device = (IDevice)element;
- switch (columnIndex) {
- case 0:
- return device.isEmulator() ? mEmulatorImage : mDeviceImage;
-
- case 2:
- // check for compatibility.
- if (device.isEmulator() == false) { // physical device
- // get the version of the device
- AndroidVersion deviceVersion = Sdk.getDeviceVersion(device);
- if (deviceVersion == null) {
- return mWarningImage;
- } else {
- if (!deviceVersion.canRun(mMinApiVersion)) {
- return mNoMatchImage;
- }
-
- // if the project is compiling against an add-on,
- // the optional API may be missing from the device.
- return mProjectTarget.isPlatform() ?
- mMatchImage : mWarningImage;
- }
- } else {
- // get the AvdInfo
- AvdInfo info = mSdk.getAvdManager().getAvd(device.getAvdName(),
- true /*validAvdOnly*/);
- AvdCompatibility.Compatibility c =
- AvdCompatibility.canRun(info, mProjectTarget,
- mMinApiVersion);
- switch (c) {
- case YES:
- return mMatchImage;
- case NO:
- return mNoMatchImage;
- case UNKNOWN:
- return mWarningImage;
- }
- }
- }
- }
-
- return null;
- }
-
- @Override
- public String getColumnText(Object element, int columnIndex) {
- if (element instanceof IDevice) {
- IDevice device = (IDevice)element;
- switch (columnIndex) {
- case 0:
- return device.getName();
- case 1:
- if (device.isEmulator()) {
- return device.getAvdName();
- } else {
- return "N/A"; // devices don't have AVD names.
- }
- case 2:
- if (device.isEmulator()) {
- AvdInfo info = mSdk.getAvdManager().getAvd(device.getAvdName(),
- true /*validAvdOnly*/);
- if (info == null) {
- return "?";
- }
- return info.getTarget().getFullName();
- } else {
- String deviceBuild = device.getProperty(IDevice.PROP_BUILD_VERSION);
- if (deviceBuild == null) {
- return "unknown";
- }
- return deviceBuild;
- }
- case 3:
- String debuggable = device.getProperty(IDevice.PROP_DEBUGGABLE);
- if (debuggable != null && debuggable.equals("1")) { //$NON-NLS-1$
- return "Yes";
- } else {
- return "";
- }
- case 4:
- return getStateString(device);
- }
- }
-
- return null;
- }
-
- @Override
- public void addListener(ILabelProviderListener listener) {
- // pass
- }
-
- @Override
- public void dispose() {
- // pass
- }
-
- @Override
- public boolean isLabelProperty(Object element, String property) {
- // pass
- return false;
- }
-
- @Override
- public void removeListener(ILabelProviderListener listener) {
- // pass
- }
- }
-
- public static class DeviceChooserResponse {
- private AvdInfo mAvdToLaunch;
- private IDevice mDeviceToUse;
- private boolean mUseDeviceForFutureLaunches;
-
- public void setDeviceToUse(IDevice d) {
- mDeviceToUse = d;
- mAvdToLaunch = null;
- }
-
- public void setAvdToLaunch(AvdInfo avd) {
- mAvdToLaunch = avd;
- mDeviceToUse = null;
- }
-
- public IDevice getDeviceToUse() {
- return mDeviceToUse;
- }
-
- public AvdInfo getAvdToLaunch() {
- return mAvdToLaunch;
- }
-
- public void setUseDeviceForFutureLaunches(boolean en) {
- mUseDeviceForFutureLaunches = en;
- }
-
- public boolean useDeviceForFutureLaunches() {
- return mUseDeviceForFutureLaunches;
- }
- }
-
- public DeviceChooserDialog(Shell parent, DeviceChooserResponse response, String packageName,
- IAndroidTarget projectTarget, AndroidVersion minApiVersion,
- boolean useDeviceForFutureLaunches) {
- super(parent);
-
- mResponse = response;
- mPackageName = packageName;
- mProjectTarget = projectTarget;
- mMinApiVersion = minApiVersion;
- mSdk = Sdk.getCurrent();
- mUseDeviceForFutureLaunches = useDeviceForFutureLaunches;
-
- AndroidDebugBridge.addDeviceChangeListener(this);
- loadImages();
- }
-
- private void cleanup() {
- // done listening.
- AndroidDebugBridge.removeDeviceChangeListener(this);
- }
-
- @Override
- protected void okPressed() {
- cleanup();
- super.okPressed();
- }
-
- @Override
- protected void cancelPressed() {
- cleanup();
- super.cancelPressed();
- }
-
- @Override
- protected Control createContents(Composite parent) {
- Control content = super.createContents(parent);
-
- // this must be called after createContents() has happened so that the
- // ok button has been created (it's created after the call to createDialogArea)
- updateDefaultSelection();
-
- return content;
- }
-
- /**
- * Create the button bar: We override the Dialog implementation of this method
- * so that we can create the checkbox at the same level as the 'Cancel' and 'OK' buttons.
- */
- @Override
- protected Control createButtonBar(Composite parent) {
- Composite composite = new Composite(parent, SWT.NONE);
-
- GridLayout layout = new GridLayout(1, false);
- layout.marginHeight = convertVerticalDLUsToPixels(IDialogConstants.VERTICAL_MARGIN);
- composite.setLayout(layout);
- composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- mUseDeviceForFutureLaunchesCheckbox = new Button(composite, SWT.CHECK);
- mUseDeviceForFutureLaunchesCheckbox.setSelection(mUseDeviceForFutureLaunches);
- mResponse.setUseDeviceForFutureLaunches(mUseDeviceForFutureLaunches);
- mUseDeviceForFutureLaunchesCheckbox.setText("Use same device for future launches");
- mUseDeviceForFutureLaunchesCheckbox.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- mUseDeviceForFutureLaunches =
- mUseDeviceForFutureLaunchesCheckbox.getSelection();
- mResponse.setUseDeviceForFutureLaunches(mUseDeviceForFutureLaunches);
- }
- });
- mUseDeviceForFutureLaunchesCheckbox.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- createButton(composite, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
- createButton(composite, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
-
- return composite;
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- // set dialog title
- getShell().setText("Android Device Chooser");
-
- Composite top = new Composite(parent, SWT.NONE);
- top.setLayout(new GridLayout(1, true));
-
- String msg;
- if (mProjectTarget.isPlatform()) {
- msg = String.format("Select a device with min API level %s.",
- mMinApiVersion.getApiString());
- } else {
- msg = String.format("Select a device compatible with target %s.",
- mProjectTarget.getFullName());
- }
- Label label = new Label(top, SWT.NONE);
- label.setText(msg);
-
- mDeviceRadioButton = new Button(top, SWT.RADIO);
- mDeviceRadioButton.setText("Choose a running Android device");
- mDeviceRadioButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- boolean deviceMode = mDeviceRadioButton.getSelection();
-
- mDeviceTable.setEnabled(deviceMode);
- mPreferredAvdSelector.setEnabled(!deviceMode);
-
- if (deviceMode) {
- handleDeviceSelection();
- } else {
- mResponse.setAvdToLaunch(mPreferredAvdSelector.getSelected());
- }
-
- enableOkButton();
- }
- });
- mDeviceRadioButton.setSelection(true);
-
-
- // offset the selector from the radio button
- Composite offsetComp = new Composite(top, SWT.NONE);
- offsetComp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- GridLayout layout = new GridLayout(1, false);
- layout.marginRight = layout.marginHeight = 0;
- layout.marginLeft = 30;
- offsetComp.setLayout(layout);
-
- mDeviceTable = new Table(offsetComp, SWT.SINGLE | SWT.FULL_SELECTION | SWT.BORDER);
- GridData gd;
- mDeviceTable.setLayoutData(gd = new GridData(GridData.FILL_BOTH));
- gd.heightHint = 100;
-
- mDeviceTable.setHeaderVisible(true);
- mDeviceTable.setLinesVisible(true);
-
- TableHelper.createTableColumn(mDeviceTable, "Serial Number",
- SWT.LEFT, "AAA+AAAAAAAAAAAAAAAAAAA", //$NON-NLS-1$
- null /* prefs name */, null /* prefs store */);
-
- TableHelper.createTableColumn(mDeviceTable, "AVD Name",
- SWT.LEFT, "AAAAAAAAAAAAAAAAAAA", //$NON-NLS-1$
- null /* prefs name */, null /* prefs store */);
-
- TableHelper.createTableColumn(mDeviceTable, "Target",
- SWT.LEFT, "AAA+Android 9.9.9", //$NON-NLS-1$
- null /* prefs name */, null /* prefs store */);
-
- TableHelper.createTableColumn(mDeviceTable, "Debug",
- SWT.LEFT, "Debug", //$NON-NLS-1$
- null /* prefs name */, null /* prefs store */);
-
- TableHelper.createTableColumn(mDeviceTable, "State",
- SWT.LEFT, "bootloader", //$NON-NLS-1$
- null /* prefs name */, null /* prefs store */);
-
- // create the viewer for it
- mViewer = new TableViewer(mDeviceTable);
- mViewer.setContentProvider(new ContentProvider());
- mViewer.setLabelProvider(new LabelProvider());
- mViewer.setInput(AndroidDebugBridge.getBridge());
-
- mDeviceTable.addSelectionListener(new SelectionAdapter() {
- /**
- * Handles single-click selection on the device selector.
- * {@inheritDoc}
- */
- @Override
- public void widgetSelected(SelectionEvent e) {
- handleDeviceSelection();
- }
-
- /**
- * Handles double-click selection on the device selector.
- * Note that the single-click handler will probably already have been called.
- * {@inheritDoc}
- */
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- handleDeviceSelection();
- if (isOkButtonEnabled()) {
- okPressed();
- }
- }
- });
-
- Button radio2 = new Button(top, SWT.RADIO);
- radio2.setText("Launch a new Android Virtual Device");
-
- // offset the selector from the radio button
- offsetComp = new Composite(top, SWT.NONE);
- offsetComp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- layout = new GridLayout(1, false);
- layout.marginRight = layout.marginHeight = 0;
- layout.marginLeft = 30;
- offsetComp.setLayout(layout);
-
- mPreferredAvdSelector = new AvdSelector(offsetComp,
- mSdk.getSdkOsLocation(),
- mSdk.getAvdManager(),
- new NonRunningAvdFilter(),
- DisplayMode.SIMPLE_SELECTION,
- new AdtConsoleSdkLog());
- mPreferredAvdSelector.setTableHeightHint(100);
- mPreferredAvdSelector.setEnabled(false);
- mPreferredAvdSelector.setSelectionListener(new SelectionAdapter() {
- /**
- * Handles single-click selection on the AVD selector.
- * {@inheritDoc}
- */
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (mDisableAvdSelectionChange == false) {
- mResponse.setAvdToLaunch(mPreferredAvdSelector.getSelected());
- enableOkButton();
- }
- }
-
- /**
- * Handles double-click selection on the AVD selector.
- *
- * Note that the single-click handler will probably already have been called
- * but the selected item can have changed in between.
- *
- * {@inheritDoc}
- */
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- widgetSelected(e);
- if (isOkButtonEnabled()) {
- okPressed();
- }
- }
- });
-
- return top;
- }
-
- private void loadImages() {
- ImageLoader ddmUiLibLoader = ImageLoader.getDdmUiLibLoader();
- Display display = DdmsPlugin.getDisplay();
- IconFactory factory = IconFactory.getInstance();
-
- if (mDeviceImage == null) {
- mDeviceImage = ddmUiLibLoader.loadImage(display,
- "device.png", //$NON-NLS-1$
- ICON_WIDTH, ICON_WIDTH,
- display.getSystemColor(SWT.COLOR_RED));
- }
- if (mEmulatorImage == null) {
- mEmulatorImage = ddmUiLibLoader.loadImage(display,
- "emulator.png", ICON_WIDTH, ICON_WIDTH, //$NON-NLS-1$
- display.getSystemColor(SWT.COLOR_BLUE));
- }
-
- if (mMatchImage == null) {
- mMatchImage = factory.getIcon("match", //$NON-NLS-1$
- IconFactory.COLOR_GREEN,
- IconFactory.SHAPE_DEFAULT);
- }
-
- if (mNoMatchImage == null) {
- mNoMatchImage = factory.getIcon("error", //$NON-NLS-1$
- IconFactory.COLOR_RED,
- IconFactory.SHAPE_DEFAULT);
- }
-
- if (mWarningImage == null) {
- mWarningImage = factory.getIcon("warning", //$NON-NLS-1$
- SWT.COLOR_YELLOW,
- IconFactory.SHAPE_DEFAULT);
- }
-
- }
-
- /**
- * Returns a display string representing the state of the device.
- * @param d the device
- */
- private static String getStateString(IDevice d) {
- DeviceState deviceState = d.getState();
- if (deviceState == DeviceState.ONLINE) {
- return "Online";
- } else if (deviceState == DeviceState.OFFLINE) {
- return "Offline";
- } else if (deviceState == DeviceState.BOOTLOADER) {
- return "Bootloader";
- }
-
- return "??";
- }
-
- /**
- * Sent when the a device is connected to the {@link AndroidDebugBridge}.
- * <p/>
- * This is sent from a non UI thread.
- * @param device the new device.
- *
- * @see IDeviceChangeListener#deviceConnected(IDevice)
- */
- @Override
- public void deviceConnected(IDevice device) {
- final DeviceChooserDialog dialog = this;
- exec(new Runnable() {
- @Override
- public void run() {
- if (mDeviceTable.isDisposed() == false) {
- // refresh all
- mViewer.refresh();
-
- // update the selection
- updateDefaultSelection();
-
- // update the display of AvdInfo (since it's filtered to only display
- // non running AVD.)
- refillAvdList(false /*reloadAvds*/);
- } else {
- // table is disposed, we need to do something.
- // lets remove ourselves from the listener.
- AndroidDebugBridge.removeDeviceChangeListener(dialog);
- }
-
- }
- });
- }
-
- /**
- * Sent when the a device is connected to the {@link AndroidDebugBridge}.
- * <p/>
- * This is sent from a non UI thread.
- * @param device the new device.
- *
- * @see IDeviceChangeListener#deviceDisconnected(IDevice)
- */
- @Override
- public void deviceDisconnected(IDevice device) {
- deviceConnected(device);
- }
-
- /**
- * Sent when a device data changed, or when clients are started/terminated on the device.
- * <p/>
- * This is sent from a non UI thread.
- * @param device the device that was updated.
- * @param changeMask the mask indicating what changed.
- *
- * @see IDeviceChangeListener#deviceChanged(IDevice, int)
- */
- @Override
- public void deviceChanged(final IDevice device, int changeMask) {
- if ((changeMask & (IDevice.CHANGE_STATE | IDevice.CHANGE_BUILD_INFO)) != 0) {
- final DeviceChooserDialog dialog = this;
- exec(new Runnable() {
- @Override
- public void run() {
- if (mDeviceTable.isDisposed() == false) {
- // refresh the device
- mViewer.refresh(device);
-
- // update the defaultSelection.
- updateDefaultSelection();
-
- // update the display of AvdInfo (since it's filtered to only display
- // non running AVD). This is done on deviceChanged because the avd name
- // of a (emulator) device may be updated as the emulator boots.
-
- refillAvdList(false /*reloadAvds*/);
-
- // if the changed device is the current selection,
- // we update the OK button based on its state.
- if (device == mResponse.getDeviceToUse()) {
- enableOkButton();
- }
-
- } else {
- // table is disposed, we need to do something.
- // lets remove ourselves from the listener.
- AndroidDebugBridge.removeDeviceChangeListener(dialog);
- }
- }
- });
- }
- }
-
- /**
- * Returns whether the dialog is in "device" mode (true), or in "avd" mode (false).
- */
- private boolean isDeviceMode() {
- return mDeviceRadioButton.getSelection();
- }
-
- /**
- * Enables or disables the OK button of the dialog based on various selections in the dialog.
- */
- private void enableOkButton() {
- Button okButton = getButton(IDialogConstants.OK_ID);
-
- if (isDeviceMode()) {
- okButton.setEnabled(mResponse.getDeviceToUse() != null &&
- mResponse.getDeviceToUse().isOnline());
- } else {
- okButton.setEnabled(mResponse.getAvdToLaunch() != null);
- }
- }
-
- /**
- * Returns true if the ok button is enabled.
- */
- private boolean isOkButtonEnabled() {
- Button okButton = getButton(IDialogConstants.OK_ID);
- return okButton.isEnabled();
- }
-
- /**
- * Executes the {@link Runnable} in the UI thread.
- * @param runnable the runnable to execute.
- */
- private void exec(Runnable runnable) {
- try {
- Display display = mDeviceTable.getDisplay();
- display.asyncExec(runnable);
- } catch (SWTException e) {
- // tree is disposed, we need to do something. lets remove ourselves from the listener.
- AndroidDebugBridge.removeDeviceChangeListener(this);
- }
- }
-
- private void handleDeviceSelection() {
- int count = mDeviceTable.getSelectionCount();
- if (count != 1) {
- handleSelection(null);
- } else {
- int index = mDeviceTable.getSelectionIndex();
- Object data = mViewer.getElementAt(index);
- if (data instanceof IDevice) {
- handleSelection((IDevice)data);
- } else {
- handleSelection(null);
- }
- }
- }
-
- private void handleSelection(IDevice device) {
- mResponse.setDeviceToUse(device);
- enableOkButton();
- }
-
- /**
- * Look for a default device to select. This is done by looking for the running
- * clients on each device and finding one similar to the one being launched.
- * <p/>
- * This is done every time the device list changed unless there is a already selection.
- */
- private void updateDefaultSelection() {
- if (mDeviceTable.getSelectionCount() == 0) {
- AndroidDebugBridge bridge = AndroidDebugBridge.getBridge();
-
- IDevice[] devices = bridge.getDevices();
-
- for (IDevice device : devices) {
- Client[] clients = device.getClients();
-
- for (Client client : clients) {
-
- if (mPackageName.equals(client.getClientData().getClientDescription())) {
- // found a match! Select it.
- mViewer.setSelection(new StructuredSelection(device));
- handleSelection(device);
-
- // and we're done.
- return;
- }
- }
- }
- }
-
- handleDeviceSelection();
- }
-
- private final class NonRunningAvdFilter implements IAvdFilter {
-
- private IDevice[] mDevices;
-
- @Override
- public void prepare() {
- mDevices = AndroidDebugBridge.getBridge().getDevices();
- }
-
- @Override
- public boolean accept(AvdInfo avd) {
- if (mDevices != null) {
- for (IDevice d : mDevices) {
- // do not accept running avd's
- if (avd.getName().equals(d.getAvdName())) {
- return false;
- }
-
- // only accept avd's that can actually run the project
- AvdCompatibility.Compatibility c =
- AvdCompatibility.canRun(avd, mProjectTarget, mMinApiVersion);
- return (c == AvdCompatibility.Compatibility.NO) ? false : true;
- }
- }
-
- return true;
- }
-
- @Override
- public void cleanup() {
- mDevices = null;
- }
- }
-
- /**
- * Refills the AVD list keeping the current selection.
- */
- private void refillAvdList(boolean reloadAvds) {
- // save the current selection
- AvdInfo selected = mPreferredAvdSelector.getSelected();
-
- // disable selection change.
- mDisableAvdSelectionChange = true;
-
- // refresh the list
- mPreferredAvdSelector.refresh(false);
-
- // attempt to reselect the proper avd if needed
- if (selected != null) {
- if (mPreferredAvdSelector.setSelection(selected) == false) {
- // looks like the selection is lost. this can happen if an emulator
- // running the AVD that was selected was launched from outside of Eclipse).
- mResponse.setAvdToLaunch(null);
- enableOkButton();
- }
- }
-
- // enable the selection change
- mDisableAvdSelectionChange = false;
- }
-}
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/EmptyLaunchAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/EmptyLaunchAction.java
deleted file mode 100644
index a8bb414e9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/EmptyLaunchAction.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.launch;
-
-import com.android.ddmlib.IDevice;
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import java.util.Collection;
-
-/**
- * A launch action that does nothing after the application has been installed
- */
-public class EmptyLaunchAction implements IAndroidLaunchAction {
- @Override
- public boolean doLaunchAction(DelayedLaunchInfo info, Collection<IDevice> devices) {
- for (IDevice d : devices) {
- doLaunchAction(info, d);
- }
-
- return false;
- }
-
- public boolean doLaunchAction(DelayedLaunchInfo info, IDevice device) {
- // we're not supposed to do anything, just return;
- String msg = String.format("%1$s installed on device",
- info.getPackageFile().getFullPath().toOSString());
- AdtPlugin.printToConsole(info.getProject(), msg, "Done!");
- // return false so launch controller will not wait for debugger to attach
- return false;
- }
-
- @Override
- public String getLaunchDescription() {
- return "sync";
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/EmulatorConfigTab.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/EmulatorConfigTab.java
deleted file mode 100644
index 779dfa111..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/EmulatorConfigTab.java
+++ /dev/null
@@ -1,596 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.launch;
-
-import com.android.ddmuilib.ImageLoader;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.ide.eclipse.adt.internal.launch.AndroidLaunchConfiguration.TargetMode;
-import com.android.ide.eclipse.adt.internal.launch.AvdCompatibility.Compatibility;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.sdk.AdtConsoleSdkLog;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.prefs.AndroidLocation.AndroidLocationException;
-import com.android.sdklib.AndroidVersion;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.internal.avd.AvdInfo;
-import com.android.sdklib.internal.avd.AvdManager;
-import com.android.sdkuilib.internal.widgets.AvdSelector;
-import com.android.sdkuilib.internal.widgets.AvdSelector.DisplayMode;
-import com.android.sdkuilib.internal.widgets.AvdSelector.IAvdFilter;
-import com.android.utils.NullLogger;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.debug.core.ILaunchConfiguration;
-import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
-import org.eclipse.debug.ui.AbstractLaunchConfigurationTab;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-
-/**
- * Launch configuration tab to control the parameters of the Emulator
- */
-public class EmulatorConfigTab extends AbstractLaunchConfigurationTab {
-
- private final static String[][] NETWORK_SPEEDS = new String[][] {
- { "Full", "full" }, //$NON-NLS-2$
- { "GSM", "gsm" }, //$NON-NLS-2$
- { "HSCSD", "hscsd" }, //$NON-NLS-2$
- { "GPRS", "gprs" }, //$NON-NLS-2$
- { "EDGE", "edge" }, //$NON-NLS-2$
- { "UMTS", "umts" }, //$NON-NLS-2$
- { "HSPDA", "hsdpa" }, //$NON-NLS-2$
- };
-
- private final static String[][] NETWORK_LATENCIES = new String[][] {
- { "None", "none" }, //$NON-NLS-2$
- { "GPRS", "gprs" }, //$NON-NLS-2$
- { "EDGE", "edge" }, //$NON-NLS-2$
- { "UMTS", "umts" }, //$NON-NLS-2$
- };
-
- private Button mAutoTargetButton;
- private Button mManualTargetButton;
- private AvdSelector mPreferredAvdSelector;
- private Combo mSpeedCombo;
- private Combo mDelayCombo;
- private Group mEmulatorOptionsGroup;
- private Text mEmulatorCLOptions;
- private Button mWipeDataButton;
- private Button mNoBootAnimButton;
- private Label mPreferredAvdLabel;
- private IAndroidTarget mProjectTarget;
- private AndroidVersion mProjectMinApiVersion;
- private Button mFutureLaunchesOnSameDevice;
- private boolean mSupportMultiDeviceLaunch;
- private Button mAllDevicesTargetButton;
- private Combo mDeviceTypeCombo;
-
- private static final String DEVICES_AND_EMULATORS = "Active devices and AVD's";
- private static final String EMULATORS_ONLY = "Active AVD's";
- private static final String DEVICES_ONLY = "Active devices";
-
- /**
- * Returns the emulator ready speed option value.
- * @param value The index of the combo selection.
- */
- public static String getSpeed(int value) {
- try {
- return NETWORK_SPEEDS[value][1];
- } catch (ArrayIndexOutOfBoundsException e) {
- return NETWORK_SPEEDS[LaunchConfigDelegate.DEFAULT_SPEED][1];
- }
- }
-
- /**
- * Returns the emulator ready network latency value.
- * @param value The index of the combo selection.
- */
- public static String getDelay(int value) {
- try {
- return NETWORK_LATENCIES[value][1];
- } catch (ArrayIndexOutOfBoundsException e) {
- return NETWORK_LATENCIES[LaunchConfigDelegate.DEFAULT_DELAY][1];
- }
- }
-
- /**
- *
- */
- public EmulatorConfigTab(boolean supportMultiDeviceLaunch) {
- mSupportMultiDeviceLaunch = supportMultiDeviceLaunch;
- }
-
- /**
- * @wbp.parser.entryPoint
- */
- @Override
- public void createControl(Composite parent) {
- Font font = parent.getFont();
-
- // Reload the AVDs to make sure we are up to date
- try {
- // SDK can be null if the user opens the dialog before ADT finished
- // initializing the SDK itself. In this case just don't reload anything
- // so there's nothing obsolete yet.
- Sdk sdk = Sdk.getCurrent();
- if (sdk != null) {
- AvdManager avdMan = sdk.getAvdManager();
- assert avdMan != null;
- avdMan.reloadAvds(NullLogger.getLogger());
- }
- } catch (AndroidLocationException e1) {
- // this happens if the AVD Manager failed to find the folder in which the AVDs are
- // stored. There isn't much we can do at this point.
- }
-
- Composite topComp = new Composite(parent, SWT.NONE);
- setControl(topComp);
- GridLayout topLayout = new GridLayout();
- topLayout.numColumns = 1;
- topLayout.verticalSpacing = 0;
- topComp.setLayout(topLayout);
- topComp.setFont(font);
-
- GridData gd;
- GridLayout layout;
-
- // radio button for the target mode
- Group targetModeGroup = new Group(topComp, SWT.NONE);
- targetModeGroup.setText("Deployment Target Selection Mode");
- gd = new GridData(GridData.FILL_HORIZONTAL);
- targetModeGroup.setLayoutData(gd);
- layout = new GridLayout();
- layout.numColumns = 1;
- targetModeGroup.setLayout(layout);
- targetModeGroup.setFont(font);
-
- mManualTargetButton = new Button(targetModeGroup, SWT.RADIO);
- mManualTargetButton.setText("Always prompt to pick device");
-
- mAllDevicesTargetButton = new Button(targetModeGroup, SWT.RADIO);
- mAllDevicesTargetButton.setText("Launch on all compatible devices/AVD's");
- mAllDevicesTargetButton.setEnabled(mSupportMultiDeviceLaunch);
-
- Composite deviceTypeOffsetComp = new Composite(targetModeGroup, SWT.NONE);
- deviceTypeOffsetComp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- layout = new GridLayout(1, false);
- layout.marginRight = layout.marginHeight = 0;
- layout.marginLeft = 30;
- deviceTypeOffsetComp.setLayout(layout);
-
- mDeviceTypeCombo = new Combo(deviceTypeOffsetComp, SWT.READ_ONLY);
- mDeviceTypeCombo.setItems(new String[] {
- DEVICES_AND_EMULATORS,
- EMULATORS_ONLY,
- DEVICES_ONLY,
- });
- mDeviceTypeCombo.select(0);
- mDeviceTypeCombo.setEnabled(false);
-
- // add the radio button
- mAutoTargetButton = new Button(targetModeGroup, SWT.RADIO);
- mAutoTargetButton.setText("Automatically pick compatible device: "
- + "Always uses preferred AVD if set below, "
- + "launches on compatible device/AVD otherwise.");
- mAutoTargetButton.setSelection(true);
-
- SelectionListener targetModeChangeListener = new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- targetModeChanged();
- }
- };
-
- mAutoTargetButton.addSelectionListener(targetModeChangeListener);
- mAllDevicesTargetButton.addSelectionListener(targetModeChangeListener);
- mManualTargetButton.addSelectionListener(targetModeChangeListener);
-
- Composite avdOffsetComp = new Composite(targetModeGroup, SWT.NONE);
- avdOffsetComp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- layout = new GridLayout(1, false);
- layout.marginRight = layout.marginHeight = 0;
- layout.marginLeft = 30;
- avdOffsetComp.setLayout(layout);
-
- mPreferredAvdLabel = new Label(avdOffsetComp, SWT.NONE);
- mPreferredAvdLabel.setText("Select a preferred Android Virtual Device for deployment:");
-
- // create the selector with no manager, we'll reset the manager every time this is
- // displayed to ensure we have the latest one (dialog is reused but SDK could have
- // been changed in between.
- mPreferredAvdSelector = new AvdSelector(avdOffsetComp,
- Sdk.getCurrent().getSdkOsLocation(),
- null /* avd manager */,
- DisplayMode.SIMPLE_CHECK,
- new AdtConsoleSdkLog());
- mPreferredAvdSelector.setTableHeightHint(100);
- SelectionListener listener = new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateLaunchConfigurationDialog();
- }
- };
- mPreferredAvdSelector.setSelectionListener(listener);
- mDeviceTypeCombo.addSelectionListener(listener);
-
- mFutureLaunchesOnSameDevice = new Button(targetModeGroup, SWT.CHECK);
- mFutureLaunchesOnSameDevice.setText("Use same device for future launches");
- mFutureLaunchesOnSameDevice.addSelectionListener(listener);
-
- // emulator size
- mEmulatorOptionsGroup = new Group(topComp, SWT.NONE);
- mEmulatorOptionsGroup.setText("Emulator launch parameters:");
- mEmulatorOptionsGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- layout = new GridLayout();
- layout.numColumns = 2;
- mEmulatorOptionsGroup.setLayout(layout);
- mEmulatorOptionsGroup.setFont(font);
-
- // Explanation
- Label l = new Label(mEmulatorOptionsGroup, SWT.NONE);
- l.setText("If no compatible and active devices or AVD's are found, then an AVD "
- + "might be launched. Provide options for the AVD launch below.");
- gd = new GridData();
- gd.horizontalSpan = 2;
- l.setLayoutData(gd);
-
- // network options
- new Label(mEmulatorOptionsGroup, SWT.NONE).setText("Network Speed:");
-
- mSpeedCombo = new Combo(mEmulatorOptionsGroup, SWT.READ_ONLY);
- for (String[] speed : NETWORK_SPEEDS) {
- mSpeedCombo.add(speed[0]);
- }
- mSpeedCombo.addSelectionListener(listener);
- mSpeedCombo.pack();
-
- new Label(mEmulatorOptionsGroup, SWT.NONE).setText("Network Latency:");
-
- mDelayCombo = new Combo(mEmulatorOptionsGroup, SWT.READ_ONLY);
-
- for (String[] delay : NETWORK_LATENCIES) {
- mDelayCombo.add(delay[0]);
- }
- mDelayCombo.addSelectionListener(listener);
- mDelayCombo.pack();
-
- // wipe data option
- mWipeDataButton = new Button(mEmulatorOptionsGroup, SWT.CHECK);
- mWipeDataButton.setText("Wipe User Data");
- mWipeDataButton.setToolTipText("Check this if you want to wipe your user data each time you start the emulator. You will be prompted for confirmation when the emulator starts.");
- gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan = 2;
- mWipeDataButton.setLayoutData(gd);
- mWipeDataButton.addSelectionListener(listener);
-
- // no boot anim option
- mNoBootAnimButton = new Button(mEmulatorOptionsGroup, SWT.CHECK);
- mNoBootAnimButton.setText("Disable Boot Animation");
- mNoBootAnimButton.setToolTipText("Check this if you want to disable the boot animation. This can help the emulator start faster on slow machines.");
- gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan = 2;
- mNoBootAnimButton.setLayoutData(gd);
- mNoBootAnimButton.addSelectionListener(listener);
-
- // custom command line option for emulator
- l = new Label(mEmulatorOptionsGroup, SWT.NONE);
- l.setText("Additional Emulator Command Line Options");
- gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan = 2;
- l.setLayoutData(gd);
-
- mEmulatorCLOptions = new Text(mEmulatorOptionsGroup, SWT.BORDER);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan = 2;
- mEmulatorCLOptions.setLayoutData(gd);
- mEmulatorCLOptions.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- updateLaunchConfigurationDialog();
- }
- });
- }
-
- private void targetModeChanged() {
- updateLaunchConfigurationDialog();
-
- boolean auto = mAutoTargetButton.getSelection();
- mPreferredAvdSelector.setEnabled(auto);
- mPreferredAvdLabel.setEnabled(auto);
-
- boolean all = mAllDevicesTargetButton.getSelection();
- mDeviceTypeCombo.setEnabled(all);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.ui.ILaunchConfigurationTab#getName()
- */
- @Override
- public String getName() {
- return "Target";
- }
-
- @Override
- public Image getImage() {
- return ImageLoader.getDdmUiLibLoader().loadImage("emulator.png", null); //$NON-NLS-1$
- }
-
- private void updateAvdList(AvdManager avdManager) {
- if (avdManager == null) {
- avdManager = Sdk.getCurrent().getAvdManager();
- }
-
- mPreferredAvdSelector.setManager(avdManager);
- mPreferredAvdSelector.refresh(false);
-
- mPreferredAvdSelector.setFilter(new IAvdFilter() {
- @Override
- public void prepare() {
- }
-
- @Override
- public void cleanup() {
- }
-
- @Override
- public boolean accept(AvdInfo avd) {
- AvdCompatibility.Compatibility c =
- AvdCompatibility.canRun(avd, mProjectTarget, mProjectMinApiVersion);
- return (c == Compatibility.NO) ? false : true;
- }
- });
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.ui.ILaunchConfigurationTab#initializeFrom(org.eclipse.debug.core.ILaunchConfiguration)
- */
- @Override
- public void initializeFrom(ILaunchConfiguration configuration) {
- AvdManager avdManager = Sdk.getCurrent().getAvdManager();
-
- TargetMode mode = AndroidLaunchConfiguration.parseTargetMode(configuration,
- LaunchConfigDelegate.DEFAULT_TARGET_MODE);
-
- boolean multipleDevices = mode.isMultiDevice();
- if (multipleDevices && !mSupportMultiDeviceLaunch) {
- // The launch config says to run on multiple devices, but this launch type does not
- // suppport multiple devices. In such a case, switch back to default mode.
- // This could happen if a launch config used for Run is then used for Debug.
- multipleDevices = false;
- mode = LaunchConfigDelegate.DEFAULT_TARGET_MODE;
- }
-
- mAutoTargetButton.setSelection(mode == TargetMode.AUTO);
- mManualTargetButton.setSelection(mode == TargetMode.MANUAL);
- mAllDevicesTargetButton.setSelection(multipleDevices);
-
- targetModeChanged();
-
- boolean reuseLastUsedDevice;
- try {
- reuseLastUsedDevice = configuration.getAttribute(
- LaunchConfigDelegate.ATTR_REUSE_LAST_USED_DEVICE, false);
- } catch (CoreException ex) {
- reuseLastUsedDevice = false;
- }
- mFutureLaunchesOnSameDevice.setSelection(reuseLastUsedDevice);
-
- mDeviceTypeCombo.setEnabled(multipleDevices);
- if (multipleDevices) {
- int index = 0;
- if (mode == TargetMode.ALL_EMULATORS) {
- index = 1;
- } else if (mode == TargetMode.ALL_DEVICES) {
- index = 2;
- }
- mDeviceTypeCombo.select(index);
- }
-
- // look for the project name to get its target.
- String stringValue = "";
- try {
- stringValue = configuration.getAttribute(
- IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, stringValue);
- } catch (CoreException ce) {
- // let's not do anything here, we'll use the default value
- }
-
- IProject project = null;
-
- // get the list of existing Android projects from the workspace.
- IJavaProject[] projects = BaseProjectHelper.getAndroidProjects(null /*filter*/);
- if (projects != null) {
- // look for the project whose name we read from the configuration.
- for (IJavaProject p : projects) {
- if (p.getElementName().equals(stringValue)) {
- project = p.getProject();
- break;
- }
- }
- }
-
- // update the AVD list
- if (project != null) {
- mProjectTarget = Sdk.getCurrent().getTarget(project);
-
- ManifestInfo mi = ManifestInfo.get(project);
- final int minApiLevel = mi.getMinSdkVersion();
- final String minApiCodeName = mi.getMinSdkCodeName();
- mProjectMinApiVersion = new AndroidVersion(minApiLevel, minApiCodeName);
- }
-
- updateAvdList(avdManager);
-
- stringValue = "";
- try {
- stringValue = configuration.getAttribute(LaunchConfigDelegate.ATTR_AVD_NAME,
- stringValue);
- } catch (CoreException e) {
- // let's not do anything here, we'll use the default value
- }
-
- if (stringValue != null && stringValue.length() > 0 && avdManager != null) {
- AvdInfo targetAvd = avdManager.getAvd(stringValue, true /*validAvdOnly*/);
- mPreferredAvdSelector.setSelection(targetAvd);
- } else {
- mPreferredAvdSelector.setSelection(null);
- }
-
- boolean value = LaunchConfigDelegate.DEFAULT_WIPE_DATA;
- try {
- value = configuration.getAttribute(LaunchConfigDelegate.ATTR_WIPE_DATA, value);
- } catch (CoreException e) {
- // let's not do anything here, we'll use the default value
- }
- mWipeDataButton.setSelection(value);
-
- value = LaunchConfigDelegate.DEFAULT_NO_BOOT_ANIM;
- try {
- value = configuration.getAttribute(LaunchConfigDelegate.ATTR_NO_BOOT_ANIM, value);
- } catch (CoreException e) {
- // let's not do anything here, we'll use the default value
- }
- mNoBootAnimButton.setSelection(value);
-
- int index = -1;
-
- index = LaunchConfigDelegate.DEFAULT_SPEED;
- try {
- index = configuration.getAttribute(LaunchConfigDelegate.ATTR_SPEED,
- index);
- } catch (CoreException e) {
- // let's not do anything here, we'll use the default value
- }
- if (index == -1) {
- mSpeedCombo.clearSelection();
- } else {
- mSpeedCombo.select(index);
- }
-
- index = LaunchConfigDelegate.DEFAULT_DELAY;
- try {
- index = configuration.getAttribute(LaunchConfigDelegate.ATTR_DELAY,
- index);
- } catch (CoreException e) {
- // let's not do anything here, we'll put a proper value in
- // performApply anyway
- }
- if (index == -1) {
- mDelayCombo.clearSelection();
- } else {
- mDelayCombo.select(index);
- }
-
- String commandLine = null;
- try {
- commandLine = configuration.getAttribute(
- LaunchConfigDelegate.ATTR_COMMANDLINE, ""); //$NON-NLS-1$
- } catch (CoreException e) {
- // let's not do anything here, we'll use the default value
- }
- if (commandLine != null) {
- mEmulatorCLOptions.setText(commandLine);
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.ui.ILaunchConfigurationTab#performApply(org.eclipse.debug.core.ILaunchConfigurationWorkingCopy)
- */
- @Override
- public void performApply(ILaunchConfigurationWorkingCopy configuration) {
- configuration.setAttribute(LaunchConfigDelegate.ATTR_TARGET_MODE,
- getCurrentTargetMode().toString());
- configuration.setAttribute(LaunchConfigDelegate.ATTR_REUSE_LAST_USED_DEVICE,
- mFutureLaunchesOnSameDevice.getSelection());
- AvdInfo avd = mPreferredAvdSelector.getSelected();
- if (avd != null) {
- configuration.setAttribute(LaunchConfigDelegate.ATTR_AVD_NAME, avd.getName());
- } else {
- configuration.setAttribute(LaunchConfigDelegate.ATTR_AVD_NAME, (String)null);
- }
- configuration.setAttribute(LaunchConfigDelegate.ATTR_SPEED,
- mSpeedCombo.getSelectionIndex());
- configuration.setAttribute(LaunchConfigDelegate.ATTR_DELAY,
- mDelayCombo.getSelectionIndex());
- configuration.setAttribute(LaunchConfigDelegate.ATTR_COMMANDLINE,
- mEmulatorCLOptions.getText());
- configuration.setAttribute(LaunchConfigDelegate.ATTR_WIPE_DATA,
- mWipeDataButton.getSelection());
- configuration.setAttribute(LaunchConfigDelegate.ATTR_NO_BOOT_ANIM,
- mNoBootAnimButton.getSelection());
- }
-
- private TargetMode getCurrentTargetMode() {
- if (mAutoTargetButton.getSelection()) {
- return TargetMode.AUTO;
- } else if (mManualTargetButton.getSelection()) {
- return TargetMode.MANUAL;
- } else {
- String selection = mDeviceTypeCombo.getText();
- if (DEVICES_AND_EMULATORS.equals(selection)) {
- return TargetMode.ALL_DEVICES_AND_EMULATORS;
- } else if (DEVICES_ONLY.equals(selection)) {
- return TargetMode.ALL_DEVICES;
- } else if (EMULATORS_ONLY.equals(selection)) {
- return TargetMode.ALL_EMULATORS;
- }
- }
-
- return TargetMode.AUTO;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.ui.ILaunchConfigurationTab#setDefaults(org.eclipse.debug.core.ILaunchConfigurationWorkingCopy)
- */
- @Override
- public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
- configuration.setAttribute(LaunchConfigDelegate.ATTR_TARGET_MODE,
- LaunchConfigDelegate.DEFAULT_TARGET_MODE.toString());
- configuration.setAttribute(LaunchConfigDelegate.ATTR_SPEED,
- LaunchConfigDelegate.DEFAULT_SPEED);
- configuration.setAttribute(LaunchConfigDelegate.ATTR_DELAY,
- LaunchConfigDelegate.DEFAULT_DELAY);
- configuration.setAttribute(LaunchConfigDelegate.ATTR_WIPE_DATA,
- LaunchConfigDelegate.DEFAULT_WIPE_DATA);
- configuration.setAttribute(LaunchConfigDelegate.ATTR_NO_BOOT_ANIM,
- LaunchConfigDelegate.DEFAULT_NO_BOOT_ANIM);
-
- IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore();
- String emuOptions = store.getString(AdtPrefs.PREFS_EMU_OPTIONS);
- configuration.setAttribute(LaunchConfigDelegate.ATTR_COMMANDLINE, emuOptions);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/IAndroidLaunchAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/IAndroidLaunchAction.java
deleted file mode 100644
index 1ec46b603..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/IAndroidLaunchAction.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.launch;
-
-import com.android.ddmlib.IDevice;
-
-import java.util.Collection;
-
-/**
- * An action to perform after performing a launch of an Android application
- */
-public interface IAndroidLaunchAction {
-
- /**
- * Do the launch
- *
- * @param info the {@link DelayedLaunchInfo} that contains launch details
- * @param devices Android devices on which the action will be performed
- * @returns true if launch was successfully, and controller should wait for debugger to attach
- * (if applicable)
- */
- boolean doLaunchAction(DelayedLaunchInfo info, Collection<IDevice> devices);
-
- /**
- * Return a description of launch, to be used for logging and error messages
- */
- String getLaunchDescription();
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/ILaunchController.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/ILaunchController.java
deleted file mode 100644
index 6a5c00947..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/ILaunchController.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.launch;
-
-import com.android.ddmlib.IDevice;
-
-/**
- * Interface for managing Android launches
- */
-public interface ILaunchController {
-
- /**
- * Launches an application on a device or emulator
- *
- * @param launchInfo the {@link DelayedLaunchInfo} that indicates the launch action
- * @param device the device or emulator to launch the application on
- */
- public void launchApp(DelayedLaunchInfo launchInfo, IDevice device);
-
- /**
- * Cancels a launch
- *
- * @param launchInfo the {@link DelayedLaunchInfo} to cancel
- */
- void stopLaunch(DelayedLaunchInfo launchInfo);
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/JUnitLaunchConfigDelegate.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/JUnitLaunchConfigDelegate.java
deleted file mode 100644
index fdb1b305a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/JUnitLaunchConfigDelegate.java
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.launch;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.FileLocator;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.debug.core.ILaunchConfiguration;
-import org.eclipse.jdt.junit.launcher.JUnitLaunchConfigurationDelegate;
-import org.osgi.framework.Bundle;
-
-import java.io.IOException;
-import java.net.URL;
-
-/**
- * <p>
- * For Android projects, android.jar gets added to the launch configuration of
- * JUnit tests as a bootstrap entry. This breaks JUnit tests as android.jar
- * contains a skeleton version of JUnit classes and the JVM will stop with an error similar
- * to: <blockquote> Error occurred during initialization of VM
- * java/lang/NoClassDefFoundError: java/lang/ref/FinalReference </blockquote>
- * <p>
- * At compile time, Eclipse does not know that there is no valid junit.jar in
- * the classpath since it can find a correct reference to all the necessary
- * org.junit.* classes in the android.jar so it does not prompt the user to add
- * the JUnit3 or JUnit4 jar.
- * <p>
- * This delegates removes the android.jar from the bootstrap path and if
- * necessary also puts back the junit.jar in the user classpath.
- * <p>
- * This delegate will be present for both Java and Android projects (delegates
- * setting instead of only the current project) but the behavior for Java
- * projects should be neutral since:
- * <ol>
- * <li>Java tests can only compile (and then run) when a valid junit.jar is
- * present
- * <li>There is no android.jar in Java projects
- * </ol>
- */
-public class JUnitLaunchConfigDelegate extends JUnitLaunchConfigurationDelegate {
-
- private static final String JUNIT_JAR = "junit.jar"; //$NON-NLS-1$
-
- @Override
- public String[][] getBootpathExt(ILaunchConfiguration configuration) throws CoreException {
- String[][] bootpath = super.getBootpathExt(configuration);
- return fixBootpathExt(bootpath);
- }
-
- @Override
- public String[] getClasspath(ILaunchConfiguration configuration) throws CoreException {
- String[] classpath = super.getClasspath(configuration);
- return fixClasspath(classpath, getJavaProjectName(configuration));
- }
-
- /**
- * Removes the android.jar from the bootstrap path if present.
- *
- * @param bootpath Array of Arrays of bootstrap class paths
- * @return a new modified (if applicable) bootpath
- */
- public static String[][] fixBootpathExt(String[][] bootpath) {
- for (int i = 0; i < bootpath.length; i++) {
- if (bootpath[i] != null && bootpath[i].length > 0) {
- // we assume that the android.jar can only be present in the
- // bootstrap path of android tests
- if (bootpath[i][0].endsWith(SdkConstants.FN_FRAMEWORK_LIBRARY)) {
- bootpath[i] = null;
- }
- }
- }
- return bootpath;
- }
-
- /**
- * Add the junit.jar to the user classpath; since Eclipse was relying on
- * android.jar to provide the appropriate org.junit classes, it does not
- * know it actually needs the junit.jar.
- *
- * @param classpath Array containing classpath
- * @param projectName The name of the project (for logging purposes)
- *
- * @return a new modified (if applicable) classpath
- */
- public static String[] fixClasspath(String[] classpath, String projectName) {
- // search for junit.jar; if any are found return immediately
- for (int i = 0; i < classpath.length; i++) {
- if (classpath[i].endsWith(JUNIT_JAR)) {
- return classpath;
- }
- }
-
- // This delegate being called without a junit.jar present is only
- // possible for Android projects. In a non-Android project, the test
- // would not compile and would be unable to run.
- try {
- // junit4 is backward compatible with junit3 and they uses the
- // same junit.jar from bundle org.junit:
- // When a project has mixed JUnit3 and JUnit4 tests, if JUnit3 jar
- // is added first it is then replaced by the JUnit4 jar when user is
- // prompted to fix the JUnit4 test failure
- String jarLocation = getJunitJarLocation();
- // we extend the classpath by one element and append junit.jar
- String[] newClasspath = new String[classpath.length + 1];
- System.arraycopy(classpath, 0, newClasspath, 0, classpath.length);
- newClasspath[newClasspath.length - 1] = jarLocation;
- classpath = newClasspath;
- } catch (IOException e) {
- // This should not happen as we depend on the org.junit
- // plugin explicitly; the error is logged here so that the user can
- // trace back the cause when the test fails to run
- AdtPlugin.log(e, "Could not find a valid junit.jar");
- AdtPlugin.printErrorToConsole(projectName,
- "Could not find a valid junit.jar");
- // Return the classpath as-is (with no junit.jar) anyway because we
- // will let the actual launch config fails.
- }
-
- return classpath;
- }
-
- /**
- * Returns the path of the junit jar in the highest version bundle.
- *
- * (This is public only so that the test can call it)
- *
- * @return the path as a string
- * @throws IOException
- */
- public static String getJunitJarLocation() throws IOException {
- Bundle bundle = Platform.getBundle("org.junit"); //$NON-NLS-1$
- if (bundle == null) {
- throw new IOException("Cannot find org.junit bundle");
- }
- URL jarUrl = bundle.getEntry(AdtConstants.WS_SEP + JUNIT_JAR);
- return FileLocator.resolve(jarUrl).getFile();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/LaunchConfigDelegate.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/LaunchConfigDelegate.java
deleted file mode 100644
index 86fc2ffae..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/LaunchConfigDelegate.java
+++ /dev/null
@@ -1,424 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.launch;
-
-import com.android.ddmlib.AndroidDebugBridge;
-import com.android.ide.common.xml.ManifestData;
-import com.android.ide.common.xml.ManifestData.Activity;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.launch.AndroidLaunchConfiguration.TargetMode;
-import com.android.ide.eclipse.adt.internal.project.AndroidManifestHelper;
-import com.android.ide.eclipse.adt.internal.project.ProjectHelper;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.debug.core.ILaunch;
-import org.eclipse.debug.core.ILaunchConfiguration;
-import org.eclipse.debug.core.model.LaunchConfigurationDelegate;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
-
-/**
- * Implementation of an eclipse LauncConfigurationDelegate to launch android
- * application in debug.
- */
-public class LaunchConfigDelegate extends LaunchConfigurationDelegate {
- final static int INVALID_DEBUG_PORT = -1;
-
- public final static String ANDROID_LAUNCH_TYPE_ID =
- "com.android.ide.eclipse.adt.debug.LaunchConfigType"; //$NON-NLS-1$
-
- /** Target mode parameters: true is automatic, false is manual */
- public static final String ATTR_TARGET_MODE = AdtPlugin.PLUGIN_ID + ".target"; //$NON-NLS-1$
- public static final TargetMode DEFAULT_TARGET_MODE = TargetMode.AUTO;
-
- /** Flag indicating whether the last used device should be used for future launches. */
- public static final String ATTR_REUSE_LAST_USED_DEVICE =
- AdtPlugin.PLUGIN_ID + ".reuse.last.used.device"; //$NON-NLS-1$
-
- /** Device on which the last launch happened. */
- public static final String ATTR_LAST_USED_DEVICE =
- AdtPlugin.PLUGIN_ID + ".last.used.device"; //$NON-NLS-1$
-
- /**
- * Launch action:
- * <ul>
- * <li>0: launch default activity</li>
- * <li>1: launch specified activity. See {@link #ATTR_ACTIVITY}</li>
- * <li>2: Do Nothing</li>
- * </ul>
- */
- public final static String ATTR_LAUNCH_ACTION = AdtPlugin.PLUGIN_ID + ".action"; //$NON-NLS-1$
-
- /** Default launch action. This launches the activity that is setup to be found in the HOME
- * screen.
- */
- public final static int ACTION_DEFAULT = 0;
- /** Launch action starting a specific activity. */
- public final static int ACTION_ACTIVITY = 1;
- /** Launch action that does nothing. */
- public final static int ACTION_DO_NOTHING = 2;
- /** Default launch action value. */
- public final static int DEFAULT_LAUNCH_ACTION = ACTION_DEFAULT;
-
- /**
- * Activity to be launched if {@link #ATTR_LAUNCH_ACTION} is 1
- */
- public static final String ATTR_ACTIVITY = AdtPlugin.PLUGIN_ID + ".activity"; //$NON-NLS-1$
-
- public static final String ATTR_AVD_NAME = AdtPlugin.PLUGIN_ID + ".avd"; //$NON-NLS-1$
-
- public static final String ATTR_SPEED = AdtPlugin.PLUGIN_ID + ".speed"; //$NON-NLS-1$
-
- /**
- * Index of the default network speed setting for the emulator.<br>
- * Get the emulator option with <code>EmulatorConfigTab.getSpeed(index)</code>
- */
- public static final int DEFAULT_SPEED = 0;
-
- public static final String ATTR_DELAY = AdtPlugin.PLUGIN_ID + ".delay"; //$NON-NLS-1$
-
- /**
- * Index of the default network latency setting for the emulator.<br>
- * Get the emulator option with <code>EmulatorConfigTab.getDelay(index)</code>
- */
- public static final int DEFAULT_DELAY = 0;
-
- public static final String ATTR_COMMANDLINE = AdtPlugin.PLUGIN_ID + ".commandline"; //$NON-NLS-1$
-
- public static final String ATTR_WIPE_DATA = AdtPlugin.PLUGIN_ID + ".wipedata"; //$NON-NLS-1$
- public static final boolean DEFAULT_WIPE_DATA = false;
-
- public static final String ATTR_NO_BOOT_ANIM = AdtPlugin.PLUGIN_ID + ".nobootanim"; //$NON-NLS-1$
- public static final boolean DEFAULT_NO_BOOT_ANIM = false;
-
- public static final String ATTR_DEBUG_PORT =
- AdtPlugin.PLUGIN_ID + ".debugPort"; //$NON-NLS-1$
-
- @Override
- public void launch(ILaunchConfiguration configuration, String mode,
- ILaunch launch, IProgressMonitor monitor) throws CoreException {
- // We need to check if it's a standard launch or if it's a launch
- // to debug an application already running.
- int debugPort = AndroidLaunchController.getPortForConfig(configuration);
-
- // get the project
- IProject project = getProject(configuration);
-
- // first we make sure the launch is of the proper type
- AndroidLaunch androidLaunch = null;
- if (launch instanceof AndroidLaunch) {
- androidLaunch = (AndroidLaunch)launch;
- } else {
- // wrong type, not sure how we got there, but we don't do
- // anything else
- AdtPlugin.printErrorToConsole(project, "Wrong Launch Type!");
- return;
- }
-
- // if we have a valid debug port, this means we're debugging an app
- // that's already launched.
- if (debugPort != INVALID_DEBUG_PORT) {
- AndroidLaunchController.launchRemoteDebugger(debugPort, androidLaunch, monitor);
- return;
- }
-
- if (project == null) {
- AdtPlugin.printErrorToConsole("Couldn't get project object!");
- androidLaunch.stopLaunch();
- return;
- }
-
- // make sure the project and its dependencies are built
- // and PostCompilerBuilder runs.
- // This is a synchronous call which returns when the
- // build is done.
- ProjectHelper.doFullIncrementalDebugBuild(project, monitor);
-
- // check if the project has errors, and abort in this case.
- if (ProjectHelper.hasError(project, true)) {
- AdtPlugin.displayError("Android Launch",
- "Your project contains error(s), please fix them before running your application.");
- return;
- }
-
- AdtPlugin.printToConsole(project, "------------------------------"); //$NON-NLS-1$
- AdtPlugin.printToConsole(project, "Android Launch!");
-
- // check if the project is using the proper sdk.
- // if that throws an exception, we simply let it propagate to the caller.
- if (checkAndroidProject(project) == false) {
- AdtPlugin.printErrorToConsole(project, "Project is not an Android Project. Aborting!");
- androidLaunch.stopLaunch();
- return;
- }
-
- // Check adb status and abort if needed.
- AndroidDebugBridge bridge = AndroidDebugBridge.getBridge();
- if (bridge == null || bridge.isConnected() == false) {
- try {
- int connections = -1;
- int restarts = -1;
- if (bridge != null) {
- connections = bridge.getConnectionAttemptCount();
- restarts = bridge.getRestartAttemptCount();
- }
-
- // if we get -1, the device monitor is not even setup (anymore?).
- // We need to ask the user to restart eclipse.
- // This shouldn't happen, but it's better to let the user know in case it does.
- if (connections == -1 || restarts == -1) {
- AdtPlugin.printErrorToConsole(project,
- "The connection to adb is down, and a severe error has occured.",
- "You must restart adb and Eclipse.",
- String.format(
- "Please ensure that adb is correctly located at '%1$s' and can be executed.",
- AdtPlugin.getOsAbsoluteAdb()));
- return;
- }
-
- if (restarts == 0) {
- AdtPlugin.printErrorToConsole(project,
- "Connection with adb was interrupted.",
- String.format("%1$s attempts have been made to reconnect.", connections),
- "You may want to manually restart adb from the Devices view.");
- } else {
- AdtPlugin.printErrorToConsole(project,
- "Connection with adb was interrupted, and attempts to reconnect have failed.",
- String.format("%1$s attempts have been made to restart adb.", restarts),
- "You may want to manually restart adb from the Devices view.");
-
- }
- return;
- } finally {
- androidLaunch.stopLaunch();
- }
- }
-
- // since adb is working, we let the user know
- // TODO have a verbose mode for launch with more info (or some of the less useful info we now have).
- AdtPlugin.printToConsole(project, "adb is running normally.");
-
- // make a config class
- AndroidLaunchConfiguration config = new AndroidLaunchConfiguration();
-
- // fill it with the config coming from the ILaunchConfiguration object
- config.set(configuration);
-
- // get the launch controller singleton
- AndroidLaunchController controller = AndroidLaunchController.getInstance();
-
- // get the application package
- IFile applicationPackage = ProjectHelper.getApplicationPackage(project);
- if (applicationPackage == null) {
- androidLaunch.stopLaunch();
- return;
- }
-
- // we need some information from the manifest
- ManifestData manifestData = AndroidManifestHelper.parseForData(project);
-
- if (manifestData == null) {
- AdtPlugin.printErrorToConsole(project, "Failed to parse AndroidManifest: aborting!");
- androidLaunch.stopLaunch();
- return;
- }
-
- doLaunch(configuration, mode, monitor, project, androidLaunch, config, controller,
- applicationPackage, manifestData);
- }
-
- protected void doLaunch(ILaunchConfiguration configuration, String mode,
- IProgressMonitor monitor, IProject project, AndroidLaunch androidLaunch,
- AndroidLaunchConfiguration config, AndroidLaunchController controller,
- IFile applicationPackage, ManifestData manifestData) {
-
- String activityName = null;
-
- if (config.mLaunchAction == ACTION_ACTIVITY) {
- // Get the activity name defined in the config
- activityName = getActivityName(configuration);
-
- // Get the full activity list and make sure the one we got matches.
- Activity[] activities = manifestData.getActivities();
-
- // first we check that there are, in fact, activities.
- if (activities.length == 0) {
- // if the activities list is null, then the manifest is empty
- // and we can't launch the app. We'll revert to a sync-only launch
- AdtPlugin.printErrorToConsole(project,
- "The Manifest defines no activity!",
- "The launch will only sync the application package on the device!");
- config.mLaunchAction = ACTION_DO_NOTHING;
- } else if (activityName == null) {
- // if the activity we got is null, we look for the default one.
- AdtPlugin.printErrorToConsole(project,
- "No activity specified! Getting the launcher activity.");
- Activity launcherActivity = manifestData.getLauncherActivity();
- if (launcherActivity != null) {
- activityName = launcherActivity.getName();
- }
-
- // if there's no default activity. We revert to a sync-only launch.
- if (activityName == null) {
- revertToNoActionLaunch(project, config);
- }
- } else {
-
- // check the one we got from the config matches any from the list
- boolean match = false;
- for (Activity a : activities) {
- if (a != null && a.getName().equals(activityName)) {
- match = true;
- break;
- }
- }
-
- // if we didn't find a match, we revert to the default activity if any.
- if (match == false) {
- AdtPlugin.printErrorToConsole(project,
- "The specified activity does not exist! Getting the launcher activity.");
- Activity launcherActivity = manifestData.getLauncherActivity();
- if (launcherActivity != null) {
- activityName = launcherActivity.getName();
- } else {
- // if there's no default activity. We revert to a sync-only launch.
- revertToNoActionLaunch(project, config);
- }
- }
- }
- } else if (config.mLaunchAction == ACTION_DEFAULT) {
- Activity launcherActivity = manifestData.getLauncherActivity();
- if (launcherActivity != null) {
- activityName = launcherActivity.getName();
- }
-
- // if there's no default activity. We revert to a sync-only launch.
- if (activityName == null) {
- revertToNoActionLaunch(project, config);
- }
- }
-
- IAndroidLaunchAction launchAction = null;
- if (config.mLaunchAction == ACTION_DO_NOTHING || activityName == null) {
- launchAction = new EmptyLaunchAction();
- } else {
- launchAction = new ActivityLaunchAction(activityName, controller);
- }
-
- // everything seems fine, we ask the launch controller to handle
- // the rest
- controller.launch(project, mode, applicationPackage,manifestData.getPackage(),
- manifestData.getPackage(), manifestData.getDebuggable(),
- manifestData.getMinSdkVersionString(), launchAction, config, androidLaunch,
- monitor);
- }
-
- @Override
- public boolean buildForLaunch(ILaunchConfiguration configuration,
- String mode, IProgressMonitor monitor) throws CoreException {
- // if this returns true, this forces a full workspace rebuild which is not
- // what we want.
- // Instead in the #launch method, we'll rebuild only the launching project.
- return false;
- }
-
- /**
- * {@inheritDoc}
- * @throws CoreException
- */
- @Override
- public ILaunch getLaunch(ILaunchConfiguration configuration, String mode)
- throws CoreException {
- return new AndroidLaunch(configuration, mode, null);
- }
-
- /**
- * Returns the IProject object matching the name found in the configuration
- * object under the name
- * <code>IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME</code>
- * @param configuration
- * @return The IProject object or null
- */
- private IProject getProject(ILaunchConfiguration configuration){
- // get the project name from the config
- String projectName;
- try {
- projectName = configuration.getAttribute(
- IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, "");
- } catch (CoreException e) {
- return null;
- }
-
- // get the current workspace
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
-
- // and return the project with the name from the config
- return workspace.getRoot().getProject(projectName);
- }
-
- /**
- * Checks the project is an android project.
- * @param project The project to check
- * @return true if the project is an android SDK.
- * @throws CoreException
- */
- private boolean checkAndroidProject(IProject project) throws CoreException {
- // check if the project is a java and an android project.
- if (project.hasNature(JavaCore.NATURE_ID) == false) {
- String msg = String.format("%1$s is not a Java project!", project.getName());
- AdtPlugin.displayError("Android Launch", msg);
- return false;
- }
-
- if (project.hasNature(AdtConstants.NATURE_DEFAULT) == false) {
- String msg = String.format("%1$s is not an Android project!", project.getName());
- AdtPlugin.displayError("Android Launch", msg);
- return false;
- }
-
- return true;
- }
-
-
- /**
- * Returns the name of the activity.
- */
- private String getActivityName(ILaunchConfiguration configuration) {
- String empty = "";
- String activityName;
- try {
- activityName = configuration.getAttribute(ATTR_ACTIVITY, empty);
- } catch (CoreException e) {
- return null;
- }
-
- return (activityName != empty) ? activityName : null;
- }
-
- private final void revertToNoActionLaunch(IProject project, AndroidLaunchConfiguration config) {
- AdtPlugin.printErrorToConsole(project,
- "No Launcher activity found!",
- "The launch will only sync the application package on the device!");
- config.mLaunchAction = ACTION_DO_NOTHING;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/LaunchConfigTabGroup.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/LaunchConfigTabGroup.java
deleted file mode 100644
index fbf17ce63..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/LaunchConfigTabGroup.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.launch;
-
-import org.eclipse.debug.core.ILaunchManager;
-import org.eclipse.debug.ui.AbstractLaunchConfigurationTabGroup;
-import org.eclipse.debug.ui.CommonTab;
-import org.eclipse.debug.ui.ILaunchConfigurationDialog;
-import org.eclipse.debug.ui.ILaunchConfigurationTab;
-
-/**
- * Tab group object for Android Launch Config type.
- */
-public class LaunchConfigTabGroup extends AbstractLaunchConfigurationTabGroup {
-
- public LaunchConfigTabGroup() {
- }
-
- @Override
- public void createTabs(ILaunchConfigurationDialog dialog, String mode) {
- ILaunchConfigurationTab[] tabs = new ILaunchConfigurationTab[] {
- new MainLaunchConfigTab(),
- new EmulatorConfigTab(ILaunchManager.RUN_MODE.equals(mode)),
- new CommonTab()
- };
- setTabs(tabs);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/LaunchMessages.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/LaunchMessages.java
deleted file mode 100644
index 1fd2b5aa1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/LaunchMessages.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.launch;
-
-import org.eclipse.osgi.util.NLS;
-
-public class LaunchMessages extends NLS {
- private static final String BUNDLE_NAME = "com.android.ide.eclipse.adt.internal.launch.messages"; //$NON-NLS-1$
-
- // generic messages that could be used by multiple classes
- public static String LaunchDialogTitle;
- public static String NonAndroidProjectError;
- public static String ParseFileFailure_s;
-
- // specialized, class-specific messages
- public static String AndroidJUnitLaunchAction_LaunchDesc_s;
- public static String AndroidJUnitLaunchAction_LaunchFail;
- public static String AndroidJUnitLaunchAction_LaunchInstr_2s;
- public static String AndroidJUnitDelegate_NoRunnerConfigMsg_s;
- public static String AndroidJUnitDelegate_NoRunnerConsoleMsg_4s;
- public static String AndroidJUnitDelegate_NoRunnerMsg_s;
- public static String AndroidJUnitDelegate_NoTargetMsg_3s;
- public static String AndroidJUnitTab_LoaderLabel;
- public static String AndroidJUnitTab_LoadInstrError_s;
- public static String AndroidJUnitTab_NoRunnerError;
- public static String AndroidJUnitTab_SizeLabel;
- public static String AndroidJUnitTab_TestContainerText;
- public static String InstrValidator_NoTestLibMsg_s;
- public static String InstrValidator_WrongRunnerTypeMsg_s;
- public static String RemoteAdtTestRunner_RunCompleteMsg;
- public static String RemoteAdtTestRunner_RunFailedMsg_s;
-
- public static String RemoteAdtTestRunner_RunIOException_s;
- public static String RemoteAdtTestRunner_RunTimeoutException;
- public static String RemoteAdtTestRunner_RunAdbCommandRejectedException_s;
- public static String RemoteAdtTestRunner_RunShellCommandUnresponsiveException;
- public static String RemoteAdtTestRunner_RunStoppedMsg;
-
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, LaunchMessages.class);
- }
-
- private LaunchMessages() {
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/LaunchShortcut.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/LaunchShortcut.java
deleted file mode 100644
index bb02b29b6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/LaunchShortcut.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.launch;
-
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.debug.core.ILaunchConfiguration;
-import org.eclipse.debug.ui.DebugUITools;
-import org.eclipse.debug.ui.ILaunchShortcut;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.PlatformUI;
-
-/**
- * Launch shortcut to launch debug/run configuration directly.
- */
-public class LaunchShortcut implements ILaunchShortcut {
-
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.ui.ILaunchShortcut#launch(
- * org.eclipse.jface.viewers.ISelection, java.lang.String)
- */
- @Override
- public void launch(ISelection selection, String mode) {
- if (selection instanceof IStructuredSelection) {
-
- // get the object and the project from it
- IStructuredSelection structSelect = (IStructuredSelection)selection;
- Object o = structSelect.getFirstElement();
-
- // get the first (and normally only) element
- if (o instanceof IAdaptable) {
- IResource r = (IResource)((IAdaptable)o).getAdapter(IResource.class);
-
- // get the project from the resource
- if (r != null) {
- IProject project = r.getProject();
-
- if (project != null) {
- ProjectState state = Sdk.getProjectState(project);
- if (state != null && state.isLibrary()) {
-
- MessageDialog.openError(
- PlatformUI.getWorkbench().getDisplay().getActiveShell(),
- "Android Launch",
- "Android library projects cannot be launched.");
- } else{
- // and launch
- launch(project, mode);
- }
- }
- }
- }
- }
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.ui.ILaunchShortcut#launch(
- * org.eclipse.ui.IEditorPart, java.lang.String)
- */
- @Override
- public void launch(IEditorPart editor, String mode) {
- // since we force the shortcut to only work on selection in the
- // package explorer, this will never be called.
- }
-
-
- /**
- * Launch a config for the specified project.
- * @param project The project to launch
- * @param mode The launch mode ("debug", "run" or "profile")
- */
- private void launch(IProject project, String mode) {
- // get an existing or new launch configuration
- ILaunchConfiguration config = AndroidLaunchController.getLaunchConfig(project,
- LaunchConfigDelegate.ANDROID_LAUNCH_TYPE_ID);
-
- if (config != null) {
- // and launch!
- DebugUITools.launch(config, mode);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/MainLaunchConfigTab.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/MainLaunchConfigTab.java
deleted file mode 100644
index c66458fc9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/MainLaunchConfigTab.java
+++ /dev/null
@@ -1,494 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.launch;
-
-import com.android.ide.common.xml.ManifestData;
-import com.android.ide.common.xml.ManifestData.Activity;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.project.AndroidManifestHelper;
-import com.android.ide.eclipse.adt.internal.project.ProjectChooserHelper;
-import com.android.ide.eclipse.adt.internal.project.ProjectChooserHelper.IProjectChooserFilter;
-import com.android.ide.eclipse.adt.internal.project.ProjectChooserHelper.NonLibraryProjectOnlyFilter;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.debug.core.ILaunchConfiguration;
-import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
-import org.eclipse.debug.ui.AbstractLaunchConfigurationTab;
-import org.eclipse.debug.ui.ILaunchConfigurationTab;
-import org.eclipse.jdt.core.IJavaModel;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Text;
-
-import java.util.ArrayList;
-
-/**
- * Class for the main launch configuration tab.
- */
-public class MainLaunchConfigTab extends AbstractLaunchConfigurationTab {
-
- /**
- *
- */
- public static final String LAUNCH_TAB_IMAGE = "mainLaunchTab"; //$NON-NLS-1$
-
- protected static final String EMPTY_STRING = ""; //$NON-NLS-1$
-
- protected Text mProjText;
- private Button mProjButton;
-
- private Combo mActivityCombo;
- private final ArrayList<Activity> mActivities = new ArrayList<Activity>();
-
- private WidgetListener mListener = new WidgetListener();
-
- private Button mDefaultActionButton;
- private Button mActivityActionButton;
- private Button mDoNothingActionButton;
- private int mLaunchAction = LaunchConfigDelegate.DEFAULT_LAUNCH_ACTION;
-
- private ProjectChooserHelper mProjectChooserHelper;
-
- /**
- * A listener which handles widget change events for the controls in this
- * tab.
- */
- private class WidgetListener implements ModifyListener, SelectionListener {
-
- @Override
- public void modifyText(ModifyEvent e) {
- IProject project = checkParameters();
- loadActivities(project);
- setDirty(true);
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {/* do nothing */
- }
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- Object source = e.getSource();
- if (source == mProjButton) {
- handleProjectButtonSelected();
- } else {
- checkParameters();
- }
- }
- }
-
- public MainLaunchConfigTab() {
- }
-
- protected IProjectChooserFilter getProjectFilter() {
- return new NonLibraryProjectOnlyFilter();
- }
-
- @Override
- public void createControl(Composite parent) {
- mProjectChooserHelper = new ProjectChooserHelper(parent.getShell(), getProjectFilter());
-
- Font font = parent.getFont();
- Composite comp = new Composite(parent, SWT.NONE);
- setControl(comp);
- GridLayout topLayout = new GridLayout();
- topLayout.verticalSpacing = 0;
- comp.setLayout(topLayout);
- comp.setFont(font);
- createProjectEditor(comp);
- createVerticalSpacer(comp, 1);
-
- // create the combo for the activity chooser
- Group group = new Group(comp, SWT.NONE);
- group.setText("Launch Action:");
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- group.setLayoutData(gd);
- GridLayout layout = new GridLayout();
- layout.numColumns = 2;
- group.setLayout(layout);
- group.setFont(font);
-
- mDefaultActionButton = new Button(group, SWT.RADIO);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan = 2;
- mDefaultActionButton.setLayoutData(gd);
- mDefaultActionButton.setText("Launch Default Activity");
- mDefaultActionButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- // event are received for both selection and deselection, so we only process
- // the selection event to avoid doing it twice.
- if (mDefaultActionButton.getSelection() == true) {
- mLaunchAction = LaunchConfigDelegate.ACTION_DEFAULT;
- mActivityCombo.setEnabled(false);
- checkParameters();
- }
- }
- });
-
- mActivityActionButton = new Button(group, SWT.RADIO);
- mActivityActionButton.setText("Launch:");
- mActivityActionButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- // event are received for both selection and deselection, so we only process
- // the selection event to avoid doing it twice.
- if (mActivityActionButton.getSelection() == true) {
- mLaunchAction = LaunchConfigDelegate.ACTION_ACTIVITY;
- mActivityCombo.setEnabled(true);
- checkParameters();
- }
- }
- });
-
- mActivityCombo = new Combo(group, SWT.DROP_DOWN | SWT.READ_ONLY);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- mActivityCombo.setLayoutData(gd);
- mActivityCombo.clearSelection();
- mActivityCombo.setEnabled(false);
- mActivityCombo.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- checkParameters();
- }
- });
-
- mDoNothingActionButton = new Button(group, SWT.RADIO);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan = 2;
- mDoNothingActionButton.setLayoutData(gd);
- mDoNothingActionButton.setText("Do Nothing");
- mDoNothingActionButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- // event are received for both selection and deselection, so we only process
- // the selection event to avoid doing it twice.
- if (mDoNothingActionButton.getSelection() == true) {
- mLaunchAction = LaunchConfigDelegate.ACTION_DO_NOTHING;
- mActivityCombo.setEnabled(false);
- checkParameters();
- }
- }
- });
-
- }
-
- @Override
- public String getName() {
- return "Android";
- }
-
- @Override
- public Image getImage() {
- return IconFactory.getInstance().getIcon(LAUNCH_TAB_IMAGE);
- }
-
- @Override
- public void performApply(ILaunchConfigurationWorkingCopy configuration) {
- configuration.setAttribute(
- IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, mProjText.getText());
- configuration.setAttribute(
- IJavaLaunchConfigurationConstants.ATTR_ALLOW_TERMINATE, true);
-
- // add the launch mode
- configuration.setAttribute(LaunchConfigDelegate.ATTR_LAUNCH_ACTION, mLaunchAction);
-
- // add the activity
- int selection = mActivityCombo.getSelectionIndex();
- if (mActivities != null && selection >=0 && selection < mActivities.size()) {
- configuration.setAttribute(LaunchConfigDelegate.ATTR_ACTIVITY,
- mActivities.get(selection).getName());
- }
-
- // link the project and the launch config.
- mapResources(configuration);
- }
-
- @Override
- public void setDefaults(ILaunchConfigurationWorkingCopy configuration) {
- configuration.setAttribute(LaunchConfigDelegate.ATTR_LAUNCH_ACTION,
- LaunchConfigDelegate.DEFAULT_LAUNCH_ACTION);
- }
-
- /**
- * Creates the widgets for specifying a main type.
- *
- * @param parent the parent composite
- */
- protected void createProjectEditor(Composite parent) {
- Font font = parent.getFont();
- Group group = new Group(parent, SWT.NONE);
- group.setText("Project:");
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- group.setLayoutData(gd);
- GridLayout layout = new GridLayout();
- layout.numColumns = 2;
- group.setLayout(layout);
- group.setFont(font);
- mProjText = new Text(group, SWT.SINGLE | SWT.BORDER);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- mProjText.setLayoutData(gd);
- mProjText.setFont(font);
- mProjText.addModifyListener(mListener);
- mProjButton = createPushButton(group, "Browse...", null);
- mProjButton.addSelectionListener(mListener);
- }
-
- /**
- * returns the default listener from this class. For all subclasses this
- * listener will only provide the functi Jaonality of updating the current
- * tab
- *
- * @return a widget listener
- */
- protected WidgetListener getDefaultListener() {
- return mListener;
- }
-
- /**
- * Return the {@link IJavaProject} corresponding to the project name in the project
- * name text field, or null if the text does not match a project name.
- * @param javaModel the Java Model object corresponding for the current workspace root.
- * @return a IJavaProject object or null.
- */
- protected IJavaProject getJavaProject(IJavaModel javaModel) {
- String projectName = mProjText.getText().trim();
- if (projectName.length() < 1) {
- return null;
- }
- return javaModel.getJavaProject(projectName);
- }
-
- /**
- * Show a dialog that lets the user select a project. This in turn provides
- * context for the main type, allowing the user to key a main type name, or
- * constraining the search for main types to the specified project.
- */
- protected void handleProjectButtonSelected() {
- IJavaProject javaProject = mProjectChooserHelper.chooseJavaProject(
- mProjText.getText().trim(),
- "Please select a project to launch");
- if (javaProject == null) {
- return;
- }// end if
- String projectName = javaProject.getElementName();
- mProjText.setText(projectName);
-
- // get the list of activities and fill the combo
- IProject project = javaProject.getProject();
- loadActivities(project);
- }// end handle selected
-
- /**
- * Initializes this tab's controls with values from the given
- * launch configuration. This method is called when
- * a configuration is selected to view or edit, after this
- * tab's control has been created.
- *
- * @param config launch configuration
- *
- * @see ILaunchConfigurationTab
- */
- @Override
- public void initializeFrom(ILaunchConfiguration config) {
- String projectName = EMPTY_STRING;
- try {
- projectName = config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME,
- EMPTY_STRING);
- }// end try
- catch (CoreException ce) {
- }
- mProjText.setText(projectName);
-
- IProject proj = mProjectChooserHelper.getAndroidProject(projectName);
- loadActivities(proj);
-
- // load the launch action.
- mLaunchAction = LaunchConfigDelegate.DEFAULT_LAUNCH_ACTION;
- try {
- mLaunchAction = config.getAttribute(LaunchConfigDelegate.ATTR_LAUNCH_ACTION,
- mLaunchAction);
- } catch (CoreException e) {
- // nothing to be done really. launchAction will keep its default value.
- }
-
- mDefaultActionButton.setSelection(mLaunchAction == LaunchConfigDelegate.ACTION_DEFAULT);
- mActivityActionButton.setSelection(mLaunchAction == LaunchConfigDelegate.ACTION_ACTIVITY);
- mDoNothingActionButton.setSelection(
- mLaunchAction == LaunchConfigDelegate.ACTION_DO_NOTHING);
-
- // now look for the activity and load it if present, otherwise, revert
- // to the current one.
- String activityName = EMPTY_STRING;
- try {
- activityName = config.getAttribute(LaunchConfigDelegate.ATTR_ACTIVITY, EMPTY_STRING);
- }// end try
- catch (CoreException ce) {
- // nothing to be done really. activityName will stay empty
- }
-
- if (mLaunchAction != LaunchConfigDelegate.ACTION_ACTIVITY) {
- mActivityCombo.setEnabled(false);
- mActivityCombo.clearSelection();
- } else {
- mActivityCombo.setEnabled(true);
- if (activityName == null || activityName.equals(EMPTY_STRING)) {
- mActivityCombo.clearSelection();
- } else if (mActivities != null && mActivities.size() > 0) {
- // look for the name of the activity in the combo.
- boolean found = false;
- for (int i = 0 ; i < mActivities.size() ; i++) {
- if (activityName.equals(mActivities.get(i).getName())) {
- found = true;
- mActivityCombo.select(i);
- break;
- }
- }
-
- // if we haven't found a matching activity we clear the combo selection
- if (found == false) {
- mActivityCombo.clearSelection();
- }
- }
- }
- }
-
- /**
- * Associates the launch config and the project. This allows Eclipse to delete the launch
- * config when the project is deleted.
- *
- * @param config the launch config working copy.
- */
- protected void mapResources(ILaunchConfigurationWorkingCopy config) {
- // get the java model
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
- IJavaModel javaModel = JavaCore.create(workspaceRoot);
-
- // get the IJavaProject described by the text field.
- IJavaProject javaProject = getJavaProject(javaModel);
- IResource[] resources = null;
- if (javaProject != null) {
- resources = AndroidLaunchController.getResourcesToMap(javaProject.getProject());
- }
- config.setMappedResources(resources);
- }
-
- /**
- * Loads the ui with the activities of the specified project, and stores the
- * activities in <code>mActivities</code>.
- * <p/>
- * First activity is selected by default if present.
- *
- * @param project The project to load the activities from.
- */
- private void loadActivities(IProject project) {
- if (project != null) {
- // parse the manifest for the list of activities.
- ManifestData manifestData = AndroidManifestHelper.parseForData(project);
- if (manifestData != null) {
- Activity[] activities = manifestData.getActivities();
-
- mActivities.clear();
- mActivityCombo.removeAll();
-
- for (Activity activity : activities) {
- if (activity.isExported() && activity.hasAction()) {
- mActivities.add(activity);
- mActivityCombo.add(activity.getName());
- }
- }
-
- if (mActivities.size() > 0) {
- if (mLaunchAction == LaunchConfigDelegate.ACTION_ACTIVITY) {
- mActivityCombo.setEnabled(true);
- }
- } else {
- mActivityCombo.setEnabled(false);
- }
-
- // the selection will be set when we update the ui from the current
- // config object.
- mActivityCombo.clearSelection();
-
- return;
- }
- }
-
- // if we reach this point, either project is null, or we got an exception during
- // the parsing. In either case, we empty the activity list.
- mActivityCombo.removeAll();
- mActivities.clear();
- }
-
- /**
- * Checks the parameters for correctness, and update the error message and buttons.
- * @return the current IProject of this launch config.
- */
- private IProject checkParameters() {
- try {
- //test the project name first!
- String text = mProjText.getText();
- if (text.length() == 0) {
- setErrorMessage("Project Name is required!");
- } else if (text.matches("[a-zA-Z0-9_ \\.-]+") == false) {
- setErrorMessage("Project name contains unsupported characters!");
- } else {
- IJavaProject[] projects = mProjectChooserHelper.getAndroidProjects(null);
- IProject found = null;
- for (IJavaProject javaProject : projects) {
- if (javaProject.getProject().getName().equals(text)) {
- found = javaProject.getProject();
- break;
- }
-
- }
-
- if (found != null) {
- setErrorMessage(null);
- } else {
- setErrorMessage(String.format("There is no android project named '%1$s'",
- text));
- }
-
- return found;
- }
- } finally {
- updateLaunchConfigurationDialog();
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/AndroidJUnitLaunchAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/AndroidJUnitLaunchAction.java
deleted file mode 100644
index c773ab9ba..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/AndroidJUnitLaunchAction.java
+++ /dev/null
@@ -1,293 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.launch.junit;
-
-import com.android.ddmlib.IDevice;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.launch.DelayedLaunchInfo;
-import com.android.ide.eclipse.adt.internal.launch.IAndroidLaunchAction;
-import com.android.ide.eclipse.adt.internal.launch.LaunchMessages;
-import com.android.ide.eclipse.adt.internal.launch.junit.runtime.AndroidJUnitLaunchInfo;
-import com.android.ide.eclipse.adt.internal.launch.junit.runtime.RemoteAdtTestRunner;
-import com.google.common.base.Joiner;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.debug.core.ILaunch;
-import org.eclipse.debug.core.ILaunchConfiguration;
-import org.eclipse.debug.core.ILaunchManager;
-import org.eclipse.debug.core.model.IProcess;
-import org.eclipse.debug.core.model.IStreamsProxy;
-import org.eclipse.jdt.junit.launcher.JUnitLaunchConfigurationDelegate;
-import org.eclipse.jdt.launching.IVMRunner;
-import org.eclipse.jdt.launching.VMRunnerConfiguration;
-import org.eclipse.swt.widgets.Display;
-
-import java.util.Collection;
-
-/**
- * A launch action that executes a instrumentation test run on an Android device.
- */
-class AndroidJUnitLaunchAction implements IAndroidLaunchAction {
- private static final Joiner JOINER = Joiner.on(',').skipNulls();
- private final AndroidJUnitLaunchInfo mLaunchInfo;
-
- /**
- * Creates a AndroidJUnitLaunchAction.
- *
- * @param launchInfo the {@link AndroidJUnitLaunchInfo} for the JUnit run
- */
- public AndroidJUnitLaunchAction(AndroidJUnitLaunchInfo launchInfo) {
- mLaunchInfo = launchInfo;
- }
-
- /**
- * Launch a instrumentation test run on given Android devices.
- * Reuses JDT JUnit launch delegate so results can be communicated back to JDT JUnit UI.
- * <p/>
- * Note: Must be executed on non-UI thread.
- *
- * @see IAndroidLaunchAction#doLaunchActions(DelayedLaunchInfo, IDevice)
- */
- @Override
- public boolean doLaunchAction(DelayedLaunchInfo info, Collection<IDevice> devices) {
- String msg = String.format(LaunchMessages.AndroidJUnitLaunchAction_LaunchInstr_2s,
- mLaunchInfo.getRunner(), JOINER.join(devices));
- AdtPlugin.printToConsole(info.getProject(), msg);
-
- try {
- mLaunchInfo.setDebugMode(info.isDebugMode());
- mLaunchInfo.setDevices(devices);
- JUnitLaunchDelegate junitDelegate = new JUnitLaunchDelegate(mLaunchInfo);
- final String mode = info.isDebugMode() ? ILaunchManager.DEBUG_MODE :
- ILaunchManager.RUN_MODE;
-
- junitDelegate.launch(info.getLaunch().getLaunchConfiguration(), mode, info.getLaunch(),
- info.getMonitor());
-
- // TODO: need to add AMReceiver-type functionality somewhere
- } catch (CoreException e) {
- AdtPlugin.printErrorToConsole(info.getProject(),
- LaunchMessages.AndroidJUnitLaunchAction_LaunchFail);
- }
- return true;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String getLaunchDescription() {
- return String.format(LaunchMessages.AndroidJUnitLaunchAction_LaunchDesc_s,
- mLaunchInfo.getRunner());
- }
-
- /**
- * Extends the JDT JUnit launch delegate to allow for JUnit UI reuse.
- */
- private static class JUnitLaunchDelegate extends JUnitLaunchConfigurationDelegate {
-
- private AndroidJUnitLaunchInfo mLaunchInfo;
-
- public JUnitLaunchDelegate(AndroidJUnitLaunchInfo launchInfo) {
- mLaunchInfo = launchInfo;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jdt.junit.launcher.JUnitLaunchConfigurationDelegate#launch(org.eclipse.debug.core.ILaunchConfiguration, java.lang.String, org.eclipse.debug.core.ILaunch, org.eclipse.core.runtime.IProgressMonitor)
- */
- @Override
- public synchronized void launch(ILaunchConfiguration configuration, String mode,
- ILaunch launch, IProgressMonitor monitor) throws CoreException {
- // TODO: is progress monitor adjustment needed here?
- super.launch(configuration, mode, launch, monitor);
- }
-
- /**
- * {@inheritDoc}
- * @see org.eclipse.jdt.junit.launcher.JUnitLaunchConfigurationDelegate#verifyMainTypeName(org.eclipse.debug.core.ILaunchConfiguration)
- */
- @Override
- public String verifyMainTypeName(ILaunchConfiguration configuration) {
- return "com.android.ide.eclipse.adt.junit.internal.runner.RemoteAndroidTestRunner"; //$NON-NLS-1$
- }
-
- /**
- * Overrides parent to return a VM Runner implementation which launches a thread, rather
- * than a separate VM process
- */
- @Override
- public IVMRunner getVMRunner(ILaunchConfiguration configuration, String mode) {
- return new VMTestRunner(mLaunchInfo);
- }
-
- /**
- * {@inheritDoc}
- * @see org.eclipse.debug.core.model.LaunchConfigurationDelegate#getLaunch(org.eclipse.debug.core.ILaunchConfiguration, java.lang.String)
- */
- @Override
- public ILaunch getLaunch(ILaunchConfiguration configuration, String mode) {
- return mLaunchInfo.getLaunch();
- }
- }
-
- /**
- * Provides a VM runner implementation which starts a inline implementation of a launch process
- */
- private static class VMTestRunner implements IVMRunner {
-
- private final AndroidJUnitLaunchInfo mJUnitInfo;
-
- VMTestRunner(AndroidJUnitLaunchInfo info) {
- mJUnitInfo = info;
- }
-
- /**
- * {@inheritDoc}
- * @throws CoreException
- */
- @Override
- public void run(final VMRunnerConfiguration config, ILaunch launch,
- IProgressMonitor monitor) throws CoreException {
-
- TestRunnerProcess runnerProcess =
- new TestRunnerProcess(config, mJUnitInfo);
- launch.addProcess(runnerProcess);
- runnerProcess.run();
- }
- }
-
- /**
- * Launch process that executes the tests.
- */
- private static class TestRunnerProcess implements IProcess {
-
- private final VMRunnerConfiguration mRunConfig;
- private final AndroidJUnitLaunchInfo mJUnitInfo;
- private RemoteAdtTestRunner mTestRunner = null;
- private boolean mIsTerminated = false;
-
- TestRunnerProcess(VMRunnerConfiguration runConfig, AndroidJUnitLaunchInfo info) {
- mRunConfig = runConfig;
- mJUnitInfo = info;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.core.model.IProcess#getAttribute(java.lang.String)
- */
- @Override
- public String getAttribute(String key) {
- return null;
- }
-
- /**
- * {@inheritDoc}
- * @see org.eclipse.debug.core.model.IProcess#getExitValue()
- */
- @Override
- public int getExitValue() {
- return 0;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.core.model.IProcess#getLabel()
- */
- @Override
- public String getLabel() {
- return mJUnitInfo.getLaunch().getLaunchMode();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.core.model.IProcess#getLaunch()
- */
- @Override
- public ILaunch getLaunch() {
- return mJUnitInfo.getLaunch();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.core.model.IProcess#getStreamsProxy()
- */
- @Override
- public IStreamsProxy getStreamsProxy() {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.core.model.IProcess#setAttribute(java.lang.String,
- * java.lang.String)
- */
- @Override
- public void setAttribute(String key, String value) {
- // ignore
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
- */
- @Override
- public Object getAdapter(Class adapter) {
- return null;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.core.model.ITerminate#canTerminate()
- */
- @Override
- public boolean canTerminate() {
- return true;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.core.model.ITerminate#isTerminated()
- */
- @Override
- public boolean isTerminated() {
- return mIsTerminated;
- }
-
- /**
- * {@inheritDoc}
- * @see org.eclipse.debug.core.model.ITerminate#terminate()
- */
- @Override
- public void terminate() {
- if (mTestRunner != null) {
- mTestRunner.terminate();
- }
- mIsTerminated = true;
- }
-
- /**
- * Launches a test runner that will communicate results back to JDT JUnit UI.
- * <p/>
- * Must be executed on a non-UI thread.
- */
- public void run() {
- if (Display.getCurrent() != null) {
- AdtPlugin.log(IStatus.ERROR, "Adt test runner executed on UI thread");
- AdtPlugin.printErrorToConsole(mJUnitInfo.getProject(),
- "Test launch failed due to internal error: Running tests on UI thread");
- terminate();
- return;
- }
- mTestRunner = new RemoteAdtTestRunner();
- mTestRunner.runTests(mRunConfig.getProgramArguments(), mJUnitInfo);
- }
- }
-}
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/AndroidJUnitLaunchConfigDelegate.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/AndroidJUnitLaunchConfigDelegate.java
deleted file mode 100755
index 6e47ce91c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/AndroidJUnitLaunchConfigDelegate.java
+++ /dev/null
@@ -1,286 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.launch.junit;
-
-import com.android.SdkConstants;
-import com.android.ddmlib.testrunner.IRemoteAndroidTestRunner.TestSize;
-import com.android.ide.common.xml.ManifestData;
-import com.android.ide.common.xml.ManifestData.Instrumentation;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.launch.AndroidLaunch;
-import com.android.ide.eclipse.adt.internal.launch.AndroidLaunchConfiguration;
-import com.android.ide.eclipse.adt.internal.launch.AndroidLaunchController;
-import com.android.ide.eclipse.adt.internal.launch.IAndroidLaunchAction;
-import com.android.ide.eclipse.adt.internal.launch.LaunchConfigDelegate;
-import com.android.ide.eclipse.adt.internal.launch.LaunchMessages;
-import com.android.ide.eclipse.adt.internal.launch.junit.runtime.AndroidJUnitLaunchInfo;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.debug.core.ILaunchConfiguration;
-import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.internal.junit.launcher.JUnitLaunchConfigurationConstants;
-import org.eclipse.jdt.internal.junit.launcher.TestKindRegistry;
-import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
-import org.eclipse.swt.widgets.Display;
-
-/**
- * Run configuration that can execute JUnit tests on an Android platform.
- * <p/>
- * Will deploy apps on target Android platform by reusing functionality from ADT
- * LaunchConfigDelegate, and then run JUnits tests by reusing functionality from JDT
- * JUnitLaunchConfigDelegate.
- */
-@SuppressWarnings("restriction")
-public class AndroidJUnitLaunchConfigDelegate extends LaunchConfigDelegate {
-
- /** Launch config attribute that stores instrumentation runner. */
- static final String ATTR_INSTR_NAME = AdtPlugin.PLUGIN_ID + ".instrumentation"; //$NON-NLS-1$
-
- /** Launch config attribute that stores the test size annotation to run. */
- static final String ATTR_TEST_SIZE = AdtPlugin.PLUGIN_ID + ".testSize"; //$NON-NLS-1$
-
- private static final String EMPTY_STRING = ""; //$NON-NLS-1$
-
- @Override
- protected void doLaunch(final ILaunchConfiguration configuration, final String mode,
- final IProgressMonitor monitor, final IProject project,
- final AndroidLaunch androidLaunch, final AndroidLaunchConfiguration config,
- final AndroidLaunchController controller, final IFile applicationPackage,
- final ManifestData manifestData) {
-
- String runner = getRunner(project, configuration, manifestData);
- if (runner == null) {
- AdtPlugin.displayError(LaunchMessages.LaunchDialogTitle,
- String.format(LaunchMessages.AndroidJUnitDelegate_NoRunnerMsg_s,
- project.getName()));
- androidLaunch.stopLaunch();
- return;
- }
- // get the target app's package
- final String targetAppPackage = getTargetPackage(manifestData, runner);
- if (targetAppPackage == null) {
- AdtPlugin.displayError(LaunchMessages.LaunchDialogTitle,
- String.format(LaunchMessages.AndroidJUnitDelegate_NoTargetMsg_3s,
- project.getName(), runner, SdkConstants.FN_ANDROID_MANIFEST_XML));
- androidLaunch.stopLaunch();
- return;
- }
- final String testAppPackage = manifestData.getPackage();
- AndroidJUnitLaunchInfo junitLaunchInfo = new AndroidJUnitLaunchInfo(project,
- testAppPackage, runner);
- junitLaunchInfo.setTestClass(getTestClass(configuration));
- junitLaunchInfo.setTestPackage(getTestPackage(configuration));
- junitLaunchInfo.setTestMethod(getTestMethod(configuration));
- junitLaunchInfo.setLaunch(androidLaunch);
- junitLaunchInfo.setTestSize(getTestSize(configuration));
- final IAndroidLaunchAction junitLaunch = new AndroidJUnitLaunchAction(junitLaunchInfo);
-
- // launch on a separate thread if currently on the display thread
- if (Display.getCurrent() != null) {
- Job job = new Job("Junit Launch") { //$NON-NLS-1$
- @Override
- protected IStatus run(IProgressMonitor m) {
- controller.launch(project, mode, applicationPackage, testAppPackage,
- targetAppPackage, manifestData.getDebuggable(),
- manifestData.getMinSdkVersionString(),
- junitLaunch, config, androidLaunch, monitor);
- return Status.OK_STATUS;
- }
- };
- job.setPriority(Job.INTERACTIVE);
- job.schedule();
- } else {
- controller.launch(project, mode, applicationPackage, testAppPackage, targetAppPackage,
- manifestData.getDebuggable(), manifestData.getMinSdkVersionString(),
- junitLaunch, config, androidLaunch, monitor);
- }
- }
-
- /**
- * Get the target Android application's package for the given instrumentation runner, or
- * <code>null</code> if it could not be found.
- *
- * @param manifestParser the {@link ManifestData} for the test project
- * @param runner the instrumentation runner class name
- * @return the target package or <code>null</code>
- */
- private String getTargetPackage(ManifestData manifestParser, String runner) {
- for (Instrumentation instr : manifestParser.getInstrumentations()) {
- if (instr.getName().equals(runner)) {
- return instr.getTargetPackage();
- }
- }
- return null;
- }
-
- /**
- * Returns the test package stored in the launch configuration, or <code>null</code> if not
- * specified.
- *
- * @param configuration the {@link ILaunchConfiguration} to retrieve the test package info from
- * @return the test package or <code>null</code>.
- */
- private String getTestPackage(ILaunchConfiguration configuration) {
- // try to retrieve a package name from the JUnit container attribute
- String containerHandle = getStringLaunchAttribute(
- JUnitLaunchConfigurationConstants.ATTR_TEST_CONTAINER, configuration);
- if (containerHandle != null && containerHandle.length() > 0) {
- IJavaElement element = JavaCore.create(containerHandle);
- // containerHandle could be a IProject, check if its a java package
- if (element.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
- return element.getElementName();
- }
- }
- return null;
- }
-
- /**
- * Returns the test class stored in the launch configuration.
- *
- * @param configuration the {@link ILaunchConfiguration} to retrieve the test class info from
- * @return the test class. <code>null</code> if not specified.
- */
- private String getTestClass(ILaunchConfiguration configuration) {
- return getStringLaunchAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME,
- configuration);
- }
-
- /**
- * Returns the test method stored in the launch configuration.
- *
- * @param configuration the {@link ILaunchConfiguration} to retrieve the test method info from
- * @return the test method. <code>null</code> if not specified.
- */
- private String getTestMethod(ILaunchConfiguration configuration) {
- return getStringLaunchAttribute(JUnitLaunchConfigurationConstants.ATTR_TEST_METHOD_NAME,
- configuration);
- }
-
- /**
- * Returns the test sizes to run as saved in the launch configuration.
- * @return {@link TestSize} if only tests of specific sizes should be run,
- * null if all tests should be run
- */
- private TestSize getTestSize(ILaunchConfiguration configuration) {
- String testSizeAnnotation = getStringLaunchAttribute(
- AndroidJUnitLaunchConfigDelegate.ATTR_TEST_SIZE,
- configuration);
- if (AndroidJUnitLaunchConfigurationTab.SMALL_TEST_ANNOTATION.equals(
- testSizeAnnotation)){
- return TestSize.SMALL;
- } else if (AndroidJUnitLaunchConfigurationTab.MEDIUM_TEST_ANNOTATION.equals(
- testSizeAnnotation)) {
- return TestSize.MEDIUM;
- } else if (AndroidJUnitLaunchConfigurationTab.LARGE_TEST_ANNOTATION.equals(
- testSizeAnnotation)) {
- return TestSize.LARGE;
- } else {
- return null;
- }
- }
-
- /**
- * Gets a instrumentation runner for the launch.
- * <p/>
- * If a runner is stored in the given <code>configuration</code>, will return that.
- * Otherwise, will try to find the first valid runner for the project.
- * If a runner can still not be found, will return <code>null</code>, and will log an error
- * to the console.
- *
- * @param project the {@link IProject} for the app
- * @param configuration the {@link ILaunchConfiguration} for the launch
- * @param manifestData the {@link ManifestData} for the project
- *
- * @return <code>null</code> if no instrumentation runner can be found, otherwise return
- * the fully qualified runner name.
- */
- private String getRunner(IProject project, ILaunchConfiguration configuration,
- ManifestData manifestData) {
- try {
- String runner = getRunnerFromConfig(configuration);
- if (runner != null) {
- return runner;
- }
- final InstrumentationRunnerValidator instrFinder = new InstrumentationRunnerValidator(
- BaseProjectHelper.getJavaProject(project), manifestData);
- runner = instrFinder.getValidInstrumentationTestRunner();
- if (runner != null) {
- AdtPlugin.printErrorToConsole(project, String.format(
- LaunchMessages.AndroidJUnitDelegate_NoRunnerConfigMsg_s, runner));
- return runner;
- }
- AdtPlugin.printErrorToConsole(project, String.format(
- LaunchMessages.AndroidJUnitDelegate_NoRunnerConsoleMsg_4s,
- project.getName(),
- SdkConstants.CLASS_INSTRUMENTATION_RUNNER,
- AdtConstants.LIBRARY_TEST_RUNNER,
- SdkConstants.FN_ANDROID_MANIFEST_XML));
- return null;
- } catch (CoreException e) {
- AdtPlugin.log(e, "Error when retrieving instrumentation info"); //$NON-NLS-1$
- }
-
- return null;
- }
-
- private String getRunnerFromConfig(ILaunchConfiguration configuration) {
- return getStringLaunchAttribute(ATTR_INSTR_NAME, configuration);
- }
-
- /**
- * Helper method to retrieve a string attribute from the launch configuration
- *
- * @param attributeName name of the launch attribute
- * @param configuration the {@link ILaunchConfiguration} to retrieve the attribute from
- * @return the attribute's value. <code>null</code> if not found.
- */
- private String getStringLaunchAttribute(String attributeName,
- ILaunchConfiguration configuration) {
- try {
- String attrValue = configuration.getAttribute(attributeName, EMPTY_STRING);
- if (attrValue.length() < 1) {
- return null;
- }
- return attrValue;
- } catch (CoreException e) {
- AdtPlugin.log(e, String.format("Error when retrieving launch info %1$s", //$NON-NLS-1$
- attributeName));
- }
- return null;
- }
-
- /**
- * Helper method to set JUnit-related attributes expected by JDT JUnit runner
- *
- * @param config the launch configuration to modify
- */
- static void setJUnitDefaults(ILaunchConfigurationWorkingCopy config) {
- // set the test runner to JUnit3 to placate JDT JUnit runner logic
- config.setAttribute(JUnitLaunchConfigurationConstants.ATTR_TEST_RUNNER_KIND,
- TestKindRegistry.JUNIT3_TEST_KIND_ID);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/AndroidJUnitLaunchConfigurationTab.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/AndroidJUnitLaunchConfigurationTab.java
deleted file mode 100644
index 038f0b91f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/AndroidJUnitLaunchConfigurationTab.java
+++ /dev/null
@@ -1,1061 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.launch.junit;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.launch.LaunchMessages;
-import com.android.ide.eclipse.adt.internal.launch.MainLaunchConfigTab;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.project.ProjectChooserHelper;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.debug.core.ILaunchConfiguration;
-import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
-import org.eclipse.debug.ui.AbstractLaunchConfigurationTab;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IJavaModel;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jdt.core.IPackageFragmentRoot;
-import org.eclipse.jdt.core.ISourceReference;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.internal.junit.Messages;
-import org.eclipse.jdt.internal.junit.launcher.ITestKind;
-import org.eclipse.jdt.internal.junit.launcher.JUnitLaunchConfigurationConstants;
-import org.eclipse.jdt.internal.junit.launcher.JUnitMigrationDelegate;
-import org.eclipse.jdt.internal.junit.launcher.TestKindRegistry;
-import org.eclipse.jdt.internal.junit.launcher.TestSelectionDialog;
-import org.eclipse.jdt.internal.junit.ui.JUnitMessages;
-import org.eclipse.jdt.internal.junit.util.LayoutUtil;
-import org.eclipse.jdt.internal.junit.util.TestSearchEngine;
-import org.eclipse.jdt.internal.ui.wizards.TypedElementSelectionValidator;
-import org.eclipse.jdt.internal.ui.wizards.TypedViewerFilter;
-import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
-import org.eclipse.jdt.ui.JavaElementComparator;
-import org.eclipse.jdt.ui.JavaElementLabelProvider;
-import org.eclipse.jdt.ui.StandardJavaElementContentProvider;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.layout.GridDataFactory;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.ElementTreeSelectionDialog;
-import org.eclipse.ui.dialogs.SelectionDialog;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.Arrays;
-import java.util.List;
-
-/**
- * The launch config UI tab for Android JUnit
- * <p/>
- * Based on org.eclipse.jdt.junit.launcher.JUnitLaunchConfigurationTab
- */
-@SuppressWarnings("restriction")
-public class AndroidJUnitLaunchConfigurationTab extends AbstractLaunchConfigurationTab {
-
- // Project UI widgets
- private Label mProjLabel;
- private Text mProjText;
- private Button mProjButton;
-
- // Test class UI widgets
- private Text mTestText;
- private Button mSearchButton;
- private String mOriginalTestMethodName;
- private Label mTestMethodLabel;
- private Text mContainerText;
- private IJavaElement mContainerElement;
- private final ILabelProvider mJavaElementLabelProvider = new JavaElementLabelProvider();
-
- private Button mContainerSearchButton;
- private Button mTestContainerRadioButton;
- private Button mTestRadioButton;
- private Label mTestLabel;
-
- // Android specific members
- private Image mTabIcon = null;
- private Combo mInstrumentationCombo;
- private Combo mTestSizeCombo;
- private static final String EMPTY_STRING = ""; //$NON-NLS-1$
- private static final String TAG = "AndroidJUnitLaunchConfigurationTab"; //$NON-NLS-1$
- private String[] mInstrumentations = null;
- private InstrumentationRunnerValidator mInstrValidator = null;
- private ProjectChooserHelper mProjectChooserHelper;
-
- public static final String SMALL_TEST_ANNOTATION = "@SmallTest"; //$NON-NLS-1$
- public static final String MEDIUM_TEST_ANNOTATION = "@MediumTest"; //$NON-NLS-1$
- public static final String LARGE_TEST_ANNOTATION = "@LargeTest"; //$NON-NLS-1$
- private static final List<String> TEST_SIZE_OPTIONS = Arrays.asList(
- "All Tests",
- SMALL_TEST_ANNOTATION,
- MEDIUM_TEST_ANNOTATION,
- LARGE_TEST_ANNOTATION
- );
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.ui.ILaunchConfigurationTab#createControl(org.eclipse.swt.widgets.Composite)
- */
- @Override
- public void createControl(Composite parent) {
- mProjectChooserHelper = new ProjectChooserHelper(parent.getShell(), null /*filter*/);
-
- Composite comp = new Composite(parent, SWT.NONE);
- setControl(comp);
-
- GridLayout topLayout = new GridLayout();
- topLayout.numColumns = 3;
- comp.setLayout(topLayout);
-
- createSingleTestSection(comp);
- createTestContainerSelectionGroup(comp);
-
- createSpacer(comp);
-
- createInstrumentationGroup(comp);
- createSizeSelector(comp);
-
- Dialog.applyDialogFont(comp);
- // TODO: add help link here when available
- //PlatformUI.getWorkbench().getHelpSystem().setHelp(getControl(),
- // IJUnitHelpContextIds.LAUNCH_CONFIGURATION_DIALOG_JUNIT_MAIN_TAB);
- validatePage();
- }
-
-
- private void createSpacer(Composite comp) {
- Label label = new Label(comp, SWT.NONE);
- GridData gd = new GridData();
- gd.horizontalSpan = 3;
- label.setLayoutData(gd);
- }
-
- private void createSingleTestSection(Composite comp) {
- mTestRadioButton = new Button(comp, SWT.RADIO);
- mTestRadioButton.setText(JUnitMessages.JUnitLaunchConfigurationTab_label_oneTest);
- GridData gd = new GridData();
- gd.horizontalSpan = 3;
- mTestRadioButton.setLayoutData(gd);
- mTestRadioButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (mTestRadioButton.getSelection()) {
- testModeChanged();
- }
- }
- });
-
- mProjLabel = new Label(comp, SWT.NONE);
- mProjLabel.setText(JUnitMessages.JUnitLaunchConfigurationTab_label_project);
- gd = new GridData();
- gd.horizontalIndent = 25;
- mProjLabel.setLayoutData(gd);
-
- mProjText = new Text(comp, SWT.SINGLE | SWT.BORDER);
- mProjText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mProjText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent evt) {
- validatePage();
- updateLaunchConfigurationDialog();
- mSearchButton.setEnabled(mTestRadioButton.getSelection() &&
- mProjText.getText().length() > 0);
- }
- });
-
- mProjButton = new Button(comp, SWT.PUSH);
- mProjButton.setText(JUnitMessages.JUnitLaunchConfigurationTab_label_browse);
- mProjButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent evt) {
- handleProjectButtonSelected();
- }
- });
- setButtonGridData(mProjButton);
-
- mTestLabel = new Label(comp, SWT.NONE);
- gd = new GridData();
- gd.horizontalIndent = 25;
- mTestLabel.setLayoutData(gd);
- mTestLabel.setText(JUnitMessages.JUnitLaunchConfigurationTab_label_test);
-
-
- mTestText = new Text(comp, SWT.SINGLE | SWT.BORDER);
- mTestText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mTestText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent evt) {
- validatePage();
- updateLaunchConfigurationDialog();
- }
- });
-
- mSearchButton = new Button(comp, SWT.PUSH);
- mSearchButton.setEnabled(mProjText.getText().length() > 0);
- mSearchButton.setText(JUnitMessages.JUnitLaunchConfigurationTab_label_search);
- mSearchButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent evt) {
- handleSearchButtonSelected();
- }
- });
- setButtonGridData(mSearchButton);
-
- new Label(comp, SWT.NONE);
-
- mTestMethodLabel = new Label(comp, SWT.NONE);
- mTestMethodLabel.setText(""); //$NON-NLS-1$
- gd = new GridData();
- gd.horizontalSpan = 2;
- mTestMethodLabel.setLayoutData(gd);
- }
-
- private void createTestContainerSelectionGroup(Composite comp) {
- mTestContainerRadioButton = new Button(comp, SWT.RADIO);
- mTestContainerRadioButton.setText(
- LaunchMessages.AndroidJUnitTab_TestContainerText);
- GridData gd = new GridData();
- gd.horizontalSpan = 3;
- mTestContainerRadioButton.setLayoutData(gd);
- mTestContainerRadioButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (mTestContainerRadioButton.getSelection()) {
- testModeChanged();
- }
- }
- });
-
- mContainerText = new Text(comp, SWT.SINGLE | SWT.BORDER | SWT.READ_ONLY);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalIndent = 25;
- gd.horizontalSpan = 2;
- mContainerText.setLayoutData(gd);
- mContainerText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent evt) {
- updateLaunchConfigurationDialog();
- }
- });
-
- mContainerSearchButton = new Button(comp, SWT.PUSH);
- mContainerSearchButton.setText(JUnitMessages.JUnitLaunchConfigurationTab_label_search);
- mContainerSearchButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent evt) {
- handleContainerSearchButtonSelected();
- }
- });
- setButtonGridData(mContainerSearchButton);
- }
-
- private void createInstrumentationGroup(Composite comp) {
- Label loaderLabel = new Label(comp, SWT.NONE);
- loaderLabel.setText(LaunchMessages.AndroidJUnitTab_LoaderLabel);
- GridData gd = new GridData();
- gd.horizontalIndent = 0;
- loaderLabel.setLayoutData(gd);
-
- mInstrumentationCombo = new Combo(comp, SWT.DROP_DOWN | SWT.READ_ONLY);
- GridDataFactory.defaultsFor(mInstrumentationCombo)
- .span(2, 1)
- .applyTo(mInstrumentationCombo);
- mInstrumentationCombo.clearSelection();
- mInstrumentationCombo.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- validatePage();
- updateLaunchConfigurationDialog();
- }
- });
- }
-
- private void createSizeSelector(Composite comp) {
- Label l = new Label(comp, SWT.NONE);
- l.setText(LaunchMessages.AndroidJUnitTab_SizeLabel);
- GridData gd = new GridData();
- gd.horizontalIndent = 0;
- l.setLayoutData(gd);
-
- mTestSizeCombo = new Combo(comp, SWT.DROP_DOWN | SWT.READ_ONLY);
- mTestSizeCombo.setItems(TEST_SIZE_OPTIONS.toArray(new String[TEST_SIZE_OPTIONS.size()]));
- mTestSizeCombo.select(0);
- mTestSizeCombo.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateLaunchConfigurationDialog();
- }
- });
- }
-
- private void handleContainerSearchButtonSelected() {
- IJavaElement javaElement = chooseContainer(mContainerElement);
- if (javaElement != null) {
- setContainerElement(javaElement);
- }
- }
-
- private void setContainerElement(IJavaElement javaElement) {
- mContainerElement = javaElement;
- mContainerText.setText(getPresentationName(javaElement));
- validatePage();
- updateLaunchConfigurationDialog();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.ui.ILaunchConfigurationTab#initializeFrom(org.eclipse.debug.core.ILaunchConfiguration)
- */
- @Override
- public void initializeFrom(ILaunchConfiguration config) {
- String projectName = updateProjectFromConfig(config);
- String containerHandle = EMPTY_STRING;
- try {
- containerHandle = config.getAttribute(
- JUnitLaunchConfigurationConstants.ATTR_TEST_CONTAINER, EMPTY_STRING);
- } catch (CoreException ce) {
- // ignore
- }
-
- if (containerHandle.length() > 0) {
- updateTestContainerFromConfig(config);
- } else {
- updateTestTypeFromConfig(config);
- }
-
- IProject proj = mProjectChooserHelper.getAndroidProject(projectName);
- loadInstrumentations(proj);
- updateInstrumentationFromConfig(config);
- updateTestSizeFromConfig(config);
-
- validatePage();
- }
-
- private void updateInstrumentationFromConfig(ILaunchConfiguration config) {
- boolean found = false;
- try {
- String currentInstrumentation = config.getAttribute(
- AndroidJUnitLaunchConfigDelegate.ATTR_INSTR_NAME, EMPTY_STRING);
- if (mInstrumentations != null) {
- // look for the name of the instrumentation in the combo.
- for (int i = 0; i < mInstrumentations.length; i++) {
- if (currentInstrumentation.equals(mInstrumentations[i])) {
- found = true;
- mInstrumentationCombo.select(i);
- break;
- }
- }
- }
- } catch (CoreException ce) {
- // ignore
- }
- if (!found) {
- mInstrumentationCombo.clearSelection();
- }
- }
-
- private void updateTestSizeFromConfig(ILaunchConfiguration config) {
- try {
- String testSize = config.getAttribute(
- AndroidJUnitLaunchConfigDelegate.ATTR_TEST_SIZE, EMPTY_STRING);
- int index = TEST_SIZE_OPTIONS.indexOf(testSize);
- if (index >= 0 && mTestSizeCombo != null) {
- mTestSizeCombo.select(index);
- }
- } catch (CoreException e) {
- // ignore
- }
- }
-
- private String updateProjectFromConfig(ILaunchConfiguration config) {
- String projectName = EMPTY_STRING;
- try {
- projectName = config.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME,
- EMPTY_STRING);
- } catch (CoreException ce) {
- // ignore
- }
- mProjText.setText(projectName);
- return projectName;
- }
-
- private void updateTestTypeFromConfig(ILaunchConfiguration config) {
- String testTypeName = EMPTY_STRING;
- mOriginalTestMethodName = EMPTY_STRING;
- try {
- testTypeName = config.getAttribute(
- IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, ""); //$NON-NLS-1$
- mOriginalTestMethodName = config.getAttribute(
- JUnitLaunchConfigurationConstants.ATTR_TEST_METHOD_NAME, ""); //$NON-NLS-1$
- } catch (CoreException ce) {
- // ignore
- }
- mTestRadioButton.setSelection(true);
- setEnableSingleTestGroup(true);
- setEnableContainerTestGroup(false);
- mTestContainerRadioButton.setSelection(false);
- mTestText.setText(testTypeName);
- mContainerText.setText(EMPTY_STRING);
- setTestMethodLabel(mOriginalTestMethodName);
- }
-
- private void setTestMethodLabel(String testMethodName) {
- if (!EMPTY_STRING.equals(testMethodName)) {
- mTestMethodLabel.setText(
- JUnitMessages.JUnitLaunchConfigurationTab_label_method +
- mOriginalTestMethodName);
- } else {
- mTestMethodLabel.setText(EMPTY_STRING);
- }
- }
-
- private void updateTestContainerFromConfig(ILaunchConfiguration config) {
- String containerHandle = EMPTY_STRING;
- IJavaElement containerElement = null;
- try {
- containerHandle = config.getAttribute(
- JUnitLaunchConfigurationConstants.ATTR_TEST_CONTAINER, EMPTY_STRING);
- if (containerHandle.length() > 0) {
- containerElement = JavaCore.create(containerHandle);
- }
- } catch (CoreException ce) {
- // ignore
- }
- if (containerElement != null) {
- mContainerElement = containerElement;
- }
- mTestContainerRadioButton.setSelection(true);
- setEnableSingleTestGroup(false);
- setEnableContainerTestGroup(true);
- mTestRadioButton.setSelection(false);
- if (mContainerElement != null) {
- mContainerText.setText(getPresentationName(mContainerElement));
- }
- mTestText.setText(EMPTY_STRING);
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.debug.ui.ILaunchConfigurationTab#performApply(org.eclipse.debug.core.ILaunchConfigurationWorkingCopy)
- */
- @Override
- public void performApply(ILaunchConfigurationWorkingCopy config) {
- if (mTestContainerRadioButton.getSelection() && mContainerElement != null) {
- config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME,
- mContainerElement.getJavaProject().getElementName());
- config.setAttribute(JUnitLaunchConfigurationConstants.ATTR_TEST_CONTAINER,
- mContainerElement.getHandleIdentifier());
- config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME,
- EMPTY_STRING);
- //workaround for Eclipse bug 65399
- config.setAttribute(JUnitLaunchConfigurationConstants.ATTR_TEST_METHOD_NAME,
- EMPTY_STRING);
- } else {
- config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME,
- mProjText.getText());
- config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME,
- mTestText.getText());
- config.setAttribute(JUnitLaunchConfigurationConstants.ATTR_TEST_CONTAINER,
- EMPTY_STRING);
- config.setAttribute(JUnitLaunchConfigurationConstants.ATTR_TEST_METHOD_NAME,
- mOriginalTestMethodName);
- }
- try {
- mapResources(config);
- } catch (CoreException e) {
- // TODO: does the real error need to be extracted out of CoreException
- AdtPlugin.log(e, "Error occurred saving configuration"); //$NON-NLS-1$
- }
- AndroidJUnitLaunchConfigDelegate.setJUnitDefaults(config);
-
- config.setAttribute(AndroidJUnitLaunchConfigDelegate.ATTR_INSTR_NAME,
- getSelectedInstrumentation());
- config.setAttribute(AndroidJUnitLaunchConfigDelegate.ATTR_TEST_SIZE,
- getSelectedTestSize());
- }
-
- private void mapResources(ILaunchConfigurationWorkingCopy config) throws CoreException {
- JUnitMigrationDelegate.mapResources(config);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.ui.AbstractLaunchConfigurationTab#dispose()
- */
- @Override
- public void dispose() {
- super.dispose();
- mTabIcon = null;
- mJavaElementLabelProvider.dispose();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.ui.AbstractLaunchConfigurationTab#getImage()
- */
- @Override
- public Image getImage() {
- // reuse icon from the Android App Launch config tab
- if (mTabIcon == null) {
- mTabIcon = IconFactory.getInstance().getIcon(MainLaunchConfigTab.LAUNCH_TAB_IMAGE);
- }
- return mTabIcon;
- }
-
- /**
- * Show a dialog that lists all main types
- */
- private void handleSearchButtonSelected() {
- Shell shell = getShell();
-
- IJavaProject javaProject = getJavaProject();
-
- IType[] types = new IType[0];
- boolean[] radioSetting = new boolean[2];
- try {
- // fix for Eclipse bug 66922 Wrong radio behaviour when switching
- // remember the selected radio button
- radioSetting[0] = mTestRadioButton.getSelection();
- radioSetting[1] = mTestContainerRadioButton.getSelection();
-
- types = TestSearchEngine.findTests(getLaunchConfigurationDialog(), javaProject,
- getTestKind());
- } catch (InterruptedException e) {
- setErrorMessage(e.getMessage());
- return;
- } catch (InvocationTargetException e) {
- AdtPlugin.log(e.getTargetException(), "Error finding test types"); //$NON-NLS-1$
- return;
- } finally {
- mTestRadioButton.setSelection(radioSetting[0]);
- mTestContainerRadioButton.setSelection(radioSetting[1]);
- }
-
- SelectionDialog dialog = new TestSelectionDialog(shell, types);
- dialog.setTitle(JUnitMessages.JUnitLaunchConfigurationTab_testdialog_title);
- dialog.setMessage(JUnitMessages.JUnitLaunchConfigurationTab_testdialog_message);
- if (dialog.open() == Window.CANCEL) {
- return;
- }
-
- Object[] results = dialog.getResult();
- if ((results == null) || (results.length < 1)) {
- return;
- }
- IType type = (IType) results[0];
-
- if (type != null) {
- mTestText.setText(type.getFullyQualifiedName('.'));
- javaProject = type.getJavaProject();
- mProjText.setText(javaProject.getElementName());
- }
- }
-
- private ITestKind getTestKind() {
- // harddcode this to JUnit 3
- return TestKindRegistry.getDefault().getKind(TestKindRegistry.JUNIT3_TEST_KIND_ID);
- }
-
- /**
- * Show a dialog that lets the user select a Android project. This in turn provides
- * context for the main type, allowing the user to key a main type name, or
- * constraining the search for main types to the specified project.
- */
- private void handleProjectButtonSelected() {
- IJavaProject project = mProjectChooserHelper.chooseJavaProject(getProjectName(),
- "Please select a project to launch");
- if (project == null) {
- return;
- }
-
- String projectName = project.getElementName();
- mProjText.setText(projectName);
- loadInstrumentations(project.getProject());
- }
-
- /**
- * Return the IJavaProject corresponding to the project name in the project name
- * text field, or null if the text does not match a Android project name.
- */
- private IJavaProject getJavaProject() {
- String projectName = getProjectName();
- return getJavaModel().getJavaProject(projectName);
- }
-
- /**
- * Returns the name of the currently specified project. Null if no project is selected.
- */
- private String getProjectName() {
- String projectName = mProjText.getText().trim();
- if (projectName.length() < 1) {
- return null;
- }
- return projectName;
- }
-
- /**
- * Convenience method to get the workspace root.
- */
- private IWorkspaceRoot getWorkspaceRoot() {
- return ResourcesPlugin.getWorkspace().getRoot();
- }
-
- /**
- * Convenience method to get access to the java model.
- */
- private IJavaModel getJavaModel() {
- return JavaCore.create(getWorkspaceRoot());
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.ui.AbstractLaunchConfigurationTab#isValid(org.eclipse.debug.core.ILaunchConfiguration)
- */
- @Override
- public boolean isValid(ILaunchConfiguration config) {
- validatePage();
- return getErrorMessage() == null;
- }
-
- private void testModeChanged() {
- boolean isSingleTestMode = mTestRadioButton.getSelection();
- setEnableSingleTestGroup(isSingleTestMode);
- setEnableContainerTestGroup(!isSingleTestMode);
- if (!isSingleTestMode && mContainerText.getText().length() == 0) {
- String projText = mProjText.getText();
- if (Path.EMPTY.isValidSegment(projText)) {
- IJavaProject javaProject = getJavaModel().getJavaProject(projText);
- if (javaProject != null && javaProject.exists()) {
- setContainerElement(javaProject);
- }
- }
- }
- validatePage();
- updateLaunchConfigurationDialog();
- }
-
- private void validatePage() {
- setErrorMessage(null);
- setMessage(null);
-
- if (mTestContainerRadioButton.getSelection()) {
- if (mContainerElement == null) {
- setErrorMessage(JUnitMessages.JUnitLaunchConfigurationTab_error_noContainer);
- return;
- }
- validateJavaProject(mContainerElement.getJavaProject());
- return;
- }
-
- String projectName = mProjText.getText().trim();
- if (projectName.length() == 0) {
- setErrorMessage(JUnitMessages.JUnitLaunchConfigurationTab_error_projectnotdefined);
- return;
- }
-
- IStatus status = ResourcesPlugin.getWorkspace().validatePath(IPath.SEPARATOR + projectName,
- IResource.PROJECT);
- if (!status.isOK() || !Path.ROOT.isValidSegment(projectName)) {
- setErrorMessage(Messages.format(
- JUnitMessages.JUnitLaunchConfigurationTab_error_invalidProjectName,
- projectName));
- return;
- }
-
- IProject project = getWorkspaceRoot().getProject(projectName);
- if (!project.exists()) {
- setErrorMessage(JUnitMessages.JUnitLaunchConfigurationTab_error_projectnotexists);
- return;
- }
- IJavaProject javaProject = JavaCore.create(project);
- validateJavaProject(javaProject);
-
- try {
- if (!project.hasNature(AdtConstants.NATURE_DEFAULT)) {
- setErrorMessage(
- LaunchMessages.NonAndroidProjectError);
- return;
- }
- String className = mTestText.getText().trim();
- if (className.length() == 0) {
- setErrorMessage(JUnitMessages.JUnitLaunchConfigurationTab_error_testnotdefined);
- return;
- }
- if (javaProject.findType(className) == null) {
- setErrorMessage(Messages.format(
- JUnitMessages.JUnitLaunchConfigurationTab_error_test_class_not_found,
- new String[] { className, projectName }));
- return;
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, "validatePage failed"); //$NON-NLS-1$
- }
-
- validateInstrumentation();
- }
-
- private void validateJavaProject(IJavaProject javaProject) {
- if (!TestSearchEngine.hasTestCaseType(javaProject)) {
- setErrorMessage(JUnitMessages.JUnitLaunchConfigurationTab_error_testcasenotonpath);
- return;
- }
- }
-
- private void validateInstrumentation() {
- String instrumentation = getSelectedInstrumentation();
- if (instrumentation == null) {
- setErrorMessage(LaunchMessages.AndroidJUnitTab_NoRunnerError);
- return;
- }
- String result = mInstrValidator.validateInstrumentationRunner(instrumentation);
- if (result != InstrumentationRunnerValidator.INSTRUMENTATION_OK) {
- setErrorMessage(result);
- return;
- }
- }
-
- private String getSelectedInstrumentation() {
- int selectionIndex = mInstrumentationCombo.getSelectionIndex();
- if (mInstrumentations != null && selectionIndex >= 0 &&
- selectionIndex < mInstrumentations.length) {
- return mInstrumentations[selectionIndex];
- }
- return null;
- }
-
- private String getSelectedTestSize() {
- if (mTestSizeCombo != null) {
- int index = mTestSizeCombo.getSelectionIndex();
- return TEST_SIZE_OPTIONS.get(index);
- } else {
- return null;
- }
- }
-
- private void setEnableContainerTestGroup(boolean enabled) {
- mContainerSearchButton.setEnabled(enabled);
- mContainerText.setEnabled(enabled);
- }
-
- private void setEnableSingleTestGroup(boolean enabled) {
- mProjLabel.setEnabled(enabled);
- mProjText.setEnabled(enabled);
- mProjButton.setEnabled(enabled);
- mTestLabel.setEnabled(enabled);
- mTestText.setEnabled(enabled);
- mSearchButton.setEnabled(enabled && mProjText.getText().length() > 0);
- mTestMethodLabel.setEnabled(enabled);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.ui.ILaunchConfigurationTab#setDefaults(org.eclipse.debug.core.ILaunchConfigurationWorkingCopy)
- */
- @Override
- public void setDefaults(ILaunchConfigurationWorkingCopy config) {
- IJavaElement javaElement = getContext();
- if (javaElement != null) {
- initializeJavaProject(javaElement, config);
- } else {
- // We set empty attributes for project & main type so that when one config is
- // compared to another, the existence of empty attributes doesn't cause an
- // incorrect result (the performApply() method can result in empty values
- // for these attributes being set on a config if there is nothing in the
- // corresponding text boxes)
- config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, EMPTY_STRING);
- config.setAttribute(JUnitLaunchConfigurationConstants.ATTR_TEST_CONTAINER,
- EMPTY_STRING);
- }
- initializeTestAttributes(javaElement, config);
- }
-
- private void initializeTestAttributes(IJavaElement javaElement,
- ILaunchConfigurationWorkingCopy config) {
- if (javaElement != null && javaElement.getElementType() < IJavaElement.COMPILATION_UNIT) {
- initializeTestContainer(javaElement, config);
- } else {
- initializeTestType(javaElement, config);
- }
- }
-
- private void initializeTestContainer(IJavaElement javaElement,
- ILaunchConfigurationWorkingCopy config) {
- config.setAttribute(JUnitLaunchConfigurationConstants.ATTR_TEST_CONTAINER,
- javaElement.getHandleIdentifier());
- initializeName(config, javaElement.getElementName());
- }
-
- private void initializeName(ILaunchConfigurationWorkingCopy config, String name) {
- if (name == null) {
- name = EMPTY_STRING;
- }
- if (name.length() > 0) {
- int index = name.lastIndexOf('.');
- if (index > 0) {
- name = name.substring(index + 1);
- }
- name = getLaunchConfigurationDialog().generateName(name);
- config.rename(name);
- }
- }
-
- /**
- * Sets the main type & name attributes on the working copy based on the IJavaElement
- */
- private void initializeTestType(IJavaElement javaElement,
- ILaunchConfigurationWorkingCopy config) {
- String name = EMPTY_STRING;
- String testKindId = null;
- try {
- // only do a search for compilation units or class files or source references
- if (javaElement instanceof ISourceReference) {
- ITestKind testKind = TestKindRegistry.getContainerTestKind(javaElement);
- testKindId = testKind.getId();
-
- IType[] types = TestSearchEngine.findTests(getLaunchConfigurationDialog(),
- javaElement, testKind);
- if ((types == null) || (types.length < 1)) {
- return;
- }
- // Simply grab the first main type found in the searched element
- name = types[0].getFullyQualifiedName('.');
-
- }
- } catch (InterruptedException ie) {
- // ignore
- } catch (InvocationTargetException ite) {
- // ignore
- }
- config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_MAIN_TYPE_NAME, name);
- if (testKindId != null) {
- config.setAttribute(JUnitLaunchConfigurationConstants.ATTR_TEST_RUNNER_KIND,
- testKindId);
- }
- initializeName(config, name);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.ui.ILaunchConfigurationTab#getName()
- */
- @Override
- public String getName() {
- return JUnitMessages.JUnitLaunchConfigurationTab_tab_label;
- }
-
- private IJavaElement chooseContainer(IJavaElement initElement) {
- @SuppressWarnings("rawtypes")
- Class[] acceptedClasses = new Class[] { IJavaProject.class,
- IPackageFragment.class };
- TypedElementSelectionValidator validator = new TypedElementSelectionValidator(
- acceptedClasses, false) {
- @Override
- public boolean isSelectedValid(Object element) {
- return true;
- }
- };
-
- acceptedClasses = new Class[] { IJavaModel.class, IPackageFragmentRoot.class,
- IJavaProject.class, IPackageFragment.class };
- ViewerFilter filter = new TypedViewerFilter(acceptedClasses) {
- @Override
- public boolean select(Viewer viewer, Object parent, Object element) {
- if (element instanceof IPackageFragmentRoot &&
- ((IPackageFragmentRoot) element).isArchive()) {
- return false;
- }
- try {
- if (element instanceof IPackageFragment &&
- !((IPackageFragment) element).hasChildren()) {
- return false;
- }
- } catch (JavaModelException e) {
- return false;
- }
- return super.select(viewer, parent, element);
- }
- };
-
- AndroidJavaElementContentProvider provider = new AndroidJavaElementContentProvider();
- ILabelProvider labelProvider = new JavaElementLabelProvider(
- JavaElementLabelProvider.SHOW_DEFAULT);
- ElementTreeSelectionDialog dialog = new ElementTreeSelectionDialog(getShell(),
- labelProvider, provider);
- dialog.setValidator(validator);
- dialog.setComparator(new JavaElementComparator());
- dialog.setTitle(JUnitMessages.JUnitLaunchConfigurationTab_folderdialog_title);
- dialog.setMessage(JUnitMessages.JUnitLaunchConfigurationTab_folderdialog_message);
- dialog.addFilter(filter);
- dialog.setInput(JavaCore.create(getWorkspaceRoot()));
- dialog.setInitialSelection(initElement);
- dialog.setAllowMultiple(false);
-
- if (dialog.open() == Window.OK) {
- Object element = dialog.getFirstResult();
- return (IJavaElement) element;
- }
- return null;
- }
-
- private String getPresentationName(IJavaElement element) {
- return mJavaElementLabelProvider.getText(element);
- }
-
- /**
- * Returns the current Java element context from which to initialize
- * default settings, or <code>null</code> if none.
- *
- * @return Java element context.
- */
- private IJavaElement getContext() {
- IWorkbenchWindow activeWorkbenchWindow =
- PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- if (activeWorkbenchWindow == null) {
- return null;
- }
- IWorkbenchPage page = activeWorkbenchWindow.getActivePage();
- if (page != null) {
- ISelection selection = page.getSelection();
- if (selection instanceof IStructuredSelection) {
- IStructuredSelection ss = (IStructuredSelection) selection;
- if (!ss.isEmpty()) {
- Object obj = ss.getFirstElement();
- if (obj instanceof IJavaElement) {
- return (IJavaElement) obj;
- }
- if (obj instanceof IResource) {
- IJavaElement je = JavaCore.create((IResource) obj);
- if (je == null) {
- IProject pro = ((IResource) obj).getProject();
- je = JavaCore.create(pro);
- }
- if (je != null) {
- return je;
- }
- }
- }
- }
- IEditorPart part = page.getActiveEditor();
- if (part != null) {
- IEditorInput input = part.getEditorInput();
- return (IJavaElement) input.getAdapter(IJavaElement.class);
- }
- }
- return null;
- }
-
- private void initializeJavaProject(IJavaElement javaElement,
- ILaunchConfigurationWorkingCopy config) {
- IJavaProject javaProject = javaElement.getJavaProject();
- String name = null;
- if (javaProject != null && javaProject.exists()) {
- name = javaProject.getElementName();
- }
- config.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME, name);
- }
-
- private void setButtonGridData(Button button) {
- GridData gridData = new GridData();
- button.setLayoutData(gridData);
- LayoutUtil.setButtonDimensionHint(button);
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.debug.ui.AbstractLaunchConfigurationTab#getId()
- */
- @Override
- public String getId() {
- return "com.android.ide.eclipse.adt.launch.AndroidJUnitLaunchConfigurationTab"; //$NON-NLS-1$
- }
-
- /**
- * Loads the UI with the instrumentations of the specified project, and stores the
- * instrumentations in <code>mInstrumentations</code>.
- *
- * @param project the {@link IProject} to load the instrumentations from.
- */
- private void loadInstrumentations(IProject project) {
- try {
- mInstrValidator = new InstrumentationRunnerValidator(project);
- mInstrumentations = mInstrValidator.getInstrumentationNames();
- if (mInstrumentations.length > 0) {
- mInstrumentationCombo.removeAll();
- for (String instrumentation : mInstrumentations) {
- mInstrumentationCombo.add(instrumentation);
- }
- // the selection will be set when we update the ui from the current
- // config object.
- return;
- }
- } catch (CoreException e) {
- AdtPlugin.logAndPrintError(e, project.getName(),
- LaunchMessages.AndroidJUnitTab_LoadInstrError_s,
- SdkConstants.FN_ANDROID_MANIFEST_XML);
- }
- // if we reach this point, either project is null, or we got an exception during
- // the parsing. In either case, we empty the instrumentation list.
- mInstrValidator = null;
- mInstrumentations = null;
- mInstrumentationCombo.removeAll();
- }
-
- /**
- * Overrides the {@link StandardJavaElementContentProvider} to only display Android projects
- */
- private static class AndroidJavaElementContentProvider
- extends StandardJavaElementContentProvider {
-
- /**
- * Override parent to return only Android projects if at the root. Otherwise, use parent
- * functionality.
- */
- @Override
- public Object[] getChildren(Object element) {
- if (element instanceof IJavaModel) {
- return BaseProjectHelper.getAndroidProjects((IJavaModel) element, null /*filter*/);
- }
- return super.getChildren(element);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/AndroidJUnitLaunchShortcut.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/AndroidJUnitLaunchShortcut.java
deleted file mode 100755
index b94ced891..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/AndroidJUnitLaunchShortcut.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.launch.junit;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.junit.launcher.JUnitLaunchShortcut;
-
-/**
- * Launch shortcut to launch debug/run Android JUnit configuration directly.
- */
-public class AndroidJUnitLaunchShortcut extends JUnitLaunchShortcut {
-
- @Override
- protected String getLaunchConfigurationTypeId() {
- return "com.android.ide.eclipse.adt.junit.launchConfigurationType"; //$NON-NLS-1$
- }
-
- /**
- * Creates a default Android JUnit launch configuration. Sets the instrumentation runner to the
- * first instrumentation found in the AndroidManifest.
- */
- @Override
- protected ILaunchConfigurationWorkingCopy createLaunchConfiguration(IJavaElement element)
- throws CoreException {
- ILaunchConfigurationWorkingCopy config = super.createLaunchConfiguration(element);
- // just get first valid instrumentation runner
- String instrumentation = new InstrumentationRunnerValidator(element.getJavaProject()).
- getValidInstrumentationTestRunner();
- if (instrumentation != null) {
- config.setAttribute(AndroidJUnitLaunchConfigDelegate.ATTR_INSTR_NAME,
- instrumentation);
- }
- // if a valid runner is not found, rely on launch delegate to log error.
- // This method is called without explicit user action to launch Android JUnit, so avoid
- // logging an error here.
-
- AndroidJUnitLaunchConfigDelegate.setJUnitDefaults(config);
- return config;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/AndroidJUnitPropertyTester.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/AndroidJUnitPropertyTester.java
deleted file mode 100644
index 5172e09a7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/AndroidJUnitPropertyTester.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.launch.junit;
-
-import org.eclipse.core.expressions.PropertyTester;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jdt.core.IClassFile;
-import org.eclipse.jdt.core.ICompilationUnit;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IMember;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.internal.junit.util.TestSearchEngine;
-
-/**
- * A {@link PropertyTester} that checks if selected elements can be run as Android
- * JUnit tests.
- * <p/>
- * Based on org.eclipse.jdt.internal.junit.JUnitPropertyTester. The only substantial difference in
- * this implementation is source folders cannot be run as Android JUnit.
- */
-@SuppressWarnings("restriction")
-public class AndroidJUnitPropertyTester extends PropertyTester {
- private static final String PROPERTY_IS_TEST = "isTest"; //$NON-NLS-1$
-
- private static final String PROPERTY_CAN_LAUNCH_AS_JUNIT_TEST = "canLaunchAsJUnit"; //$NON-NLS-1$
-
- /* (non-Javadoc)
- * @see org.eclipse.jdt.internal.corext.refactoring.participants.properties.IPropertyEvaluator#test(java.lang.Object, java.lang.String, java.lang.String)
- */
- @Override
- public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
- if (!(receiver instanceof IAdaptable)) {
- final String elementName = (receiver == null ? "null" : //$NON-NLS-1$
- receiver.getClass().getName());
- throw new IllegalArgumentException(
- String.format("Element must be of type IAdaptable, is %s", //$NON-NLS-1$
- elementName));
- }
-
- IJavaElement element;
- if (receiver instanceof IJavaElement) {
- element = (IJavaElement) receiver;
- } else if (receiver instanceof IResource) {
- element = JavaCore.create((IResource) receiver);
- if (element == null) {
- return false;
- }
- } else { // is IAdaptable
- element= (IJavaElement) ((IAdaptable) receiver).getAdapter(IJavaElement.class);
- if (element == null) {
- IResource resource = (IResource) ((IAdaptable) receiver).getAdapter(
- IResource.class);
- element = JavaCore.create(resource);
- if (element == null) {
- return false;
- }
- }
- }
- if (PROPERTY_IS_TEST.equals(property)) {
- return isJUnitTest(element);
- } else if (PROPERTY_CAN_LAUNCH_AS_JUNIT_TEST.equals(property)) {
- return canLaunchAsJUnitTest(element);
- }
- throw new IllegalArgumentException(
- String.format("Unknown test property '%s'", property)); //$NON-NLS-1$
- }
-
- private boolean canLaunchAsJUnitTest(IJavaElement element) {
- try {
- switch (element.getElementType()) {
- case IJavaElement.JAVA_PROJECT:
- return true; // can run, let JDT detect if there are tests
- case IJavaElement.PACKAGE_FRAGMENT_ROOT:
- return false; // not supported by Android test runner
- case IJavaElement.PACKAGE_FRAGMENT:
- return ((IPackageFragment) element).hasChildren();
- case IJavaElement.COMPILATION_UNIT:
- case IJavaElement.CLASS_FILE:
- case IJavaElement.TYPE:
- case IJavaElement.METHOD:
- return isJUnitTest(element);
- default:
- return false;
- }
- } catch (JavaModelException e) {
- return false;
- }
- }
-
- /**
- * Return whether the target resource is a JUnit test.
- */
- private boolean isJUnitTest(IJavaElement element) {
- try {
- IType testType = null;
- if (element instanceof ICompilationUnit) {
- testType = (((ICompilationUnit) element)).findPrimaryType();
- } else if (element instanceof IClassFile) {
- testType = (((IClassFile) element)).getType();
- } else if (element instanceof IType) {
- testType = (IType) element;
- } else if (element instanceof IMember) {
- testType = ((IMember) element).getDeclaringType();
- }
- if (testType != null && testType.exists()) {
- return TestSearchEngine.isTestOrTestSuite(testType);
- }
- } catch (CoreException e) {
- // ignore, return false
- }
- return false;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/AndroidJUnitTabGroup.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/AndroidJUnitTabGroup.java
deleted file mode 100644
index deb30de01..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/AndroidJUnitTabGroup.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.launch.junit;
-
-import com.android.ide.eclipse.adt.internal.launch.EmulatorConfigTab;
-
-import org.eclipse.debug.core.ILaunchManager;
-import org.eclipse.debug.ui.AbstractLaunchConfigurationTabGroup;
-import org.eclipse.debug.ui.CommonTab;
-import org.eclipse.debug.ui.ILaunchConfigurationDialog;
-import org.eclipse.debug.ui.ILaunchConfigurationTab;
-
-/**
- * Tab group object for Android JUnit launch configuration type.
- */
-public class AndroidJUnitTabGroup extends AbstractLaunchConfigurationTabGroup {
-
- /**
- * Creates the UI tabs for the Android JUnit configuration
- */
- @Override
- public void createTabs(ILaunchConfigurationDialog dialog, String mode) {
- ILaunchConfigurationTab[] tabs = new ILaunchConfigurationTab[] {
- new AndroidJUnitLaunchConfigurationTab(),
- new EmulatorConfigTab(ILaunchManager.RUN_MODE.equals(mode)),
- new CommonTab()
- };
- setTabs(tabs);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/InstrumentationRunnerValidator.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/InstrumentationRunnerValidator.java
deleted file mode 100644
index 820fed7d3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/InstrumentationRunnerValidator.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.launch.junit;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.xml.ManifestData;
-import com.android.ide.common.xml.ManifestData.Instrumentation;
-import com.android.ide.common.xml.ManifestData.UsesLibrary;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.internal.launch.LaunchMessages;
-import com.android.ide.eclipse.adt.internal.project.AndroidManifestHelper;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jdt.core.IJavaProject;
-
-/**
- * Provides validation for Android instrumentation test runner
- */
-class InstrumentationRunnerValidator {
- private final IJavaProject mJavaProject;
- private String[] mInstrumentationNames = null;
- private boolean mHasRunnerLibrary = false;
-
- static final String INSTRUMENTATION_OK = null;
-
- /**
- * Initializes the InstrumentationRunnerValidator.
- *
- * @param javaProject the {@link IJavaProject} for the Android project to validate
- */
- InstrumentationRunnerValidator(IJavaProject javaProject) {
- mJavaProject = javaProject;
- ManifestData manifestData = AndroidManifestHelper.parseForData(javaProject.getProject());
- init(manifestData);
- }
-
- /**
- * Initializes the InstrumentationRunnerValidator.
- *
- * @param project the {@link IProject} for the Android project to validate
- * @throws CoreException if a fatal error occurred in initialization
- */
- InstrumentationRunnerValidator(IProject project) throws CoreException {
- this(BaseProjectHelper.getJavaProject(project));
- }
-
- /**
- * Initializes the InstrumentationRunnerValidator with an existing {@link AndroidManifestHelper}
- *
- * @param javaProject the {@link IJavaProject} for the Android project to validate
- * @param manifestData the {@link ManifestData} for the Android project
- */
- InstrumentationRunnerValidator(IJavaProject javaProject, ManifestData manifestData) {
- mJavaProject = javaProject;
- init(manifestData);
- }
-
- private void init(ManifestData manifestData) {
- if (manifestData == null) {
- mInstrumentationNames = new String[0];
- mHasRunnerLibrary = false;
- return;
- }
-
- Instrumentation[] instrumentations = manifestData.getInstrumentations();
- mInstrumentationNames = new String[instrumentations.length];
- for (int i = 0; i < instrumentations.length; i++) {
- mInstrumentationNames[i] = instrumentations[i].getName();
- }
- mHasRunnerLibrary = hasTestRunnerLibrary(manifestData);
- }
-
- /**
- * Helper method to determine if given manifest has a <code>SdkConstants.LIBRARY_TEST_RUNNER
- * </code> library reference
- *
- * @param manifestParser the {@link ManifestData} to search
- * @return true if test runner library found, false otherwise
- */
- private boolean hasTestRunnerLibrary(ManifestData manifestData) {
- for (UsesLibrary lib : manifestData.getUsesLibraries()) {
- if (AdtConstants.LIBRARY_TEST_RUNNER.equals(lib.getName())) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Return the set of instrumentation names for the Android project.
- *
- * @return array of instrumentation class names, possibly empty
- */
- @NonNull
- String[] getInstrumentationNames() {
- return mInstrumentationNames;
- }
-
- /**
- * Helper method to get the first instrumentation that can be used as a test runner.
- *
- * @return fully qualified instrumentation class name. <code>null</code> if no valid
- * instrumentation can be found.
- */
- @Nullable
- String getValidInstrumentationTestRunner() {
- for (String instrumentation : getInstrumentationNames()) {
- if (validateInstrumentationRunner(instrumentation) == INSTRUMENTATION_OK) {
- return instrumentation;
- }
- }
- return null;
- }
-
- /**
- * Helper method to determine if specified instrumentation can be used as a test runner
- *
- * @param instrumentation the instrumentation class name to validate. Assumes this
- * instrumentation is one of {@link #getInstrumentationNames()}
- * @return <code>INSTRUMENTATION_OK</code> if valid, otherwise returns error message
- */
- String validateInstrumentationRunner(String instrumentation) {
- if (!mHasRunnerLibrary) {
- return String.format(LaunchMessages.InstrValidator_NoTestLibMsg_s,
- AdtConstants.LIBRARY_TEST_RUNNER);
- }
- // check if this instrumentation is the standard test runner
- if (!instrumentation.equals(SdkConstants.CLASS_INSTRUMENTATION_RUNNER)) {
- // Ideally, we'd check if the class extends instrumentation test runner.
- // However, the Google Instrumentation Test Runner extends Google Instrumentation, and not a test runner,
- // so we just check that the super class is Instrumentation.
- String result = BaseProjectHelper.testClassForManifest(mJavaProject,
- instrumentation, SdkConstants.CLASS_INSTRUMENTATION, true);
- if (result != BaseProjectHelper.TEST_CLASS_OK) {
- return String.format(
- LaunchMessages.InstrValidator_WrongRunnerTypeMsg_s,
- SdkConstants.CLASS_INSTRUMENTATION);
- }
- }
- return INSTRUMENTATION_OK;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/runtime/AndroidJUnitLaunchInfo.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/runtime/AndroidJUnitLaunchInfo.java
deleted file mode 100644
index 08702f4e2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/runtime/AndroidJUnitLaunchInfo.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.launch.junit.runtime;
-
-import com.android.ddmlib.IDevice;
-import com.android.ddmlib.testrunner.IRemoteAndroidTestRunner.TestSize;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.debug.core.ILaunch;
-
-import java.util.Collection;
-import java.util.Collections;
-
-/**
- * Contains info about Android JUnit launch
- */
-public class AndroidJUnitLaunchInfo {
- private final IProject mProject;
- private final String mAppPackage;
- private final String mRunner;
-
- private boolean mDebugMode = false;
- private Collection<IDevice> mDevices = Collections.EMPTY_LIST;
- private String mTestPackage = null;
- private String mTestClass = null;
- private String mTestMethod = null;
- private ILaunch mLaunch = null;
- private TestSize mTestSize = null;
-
- public AndroidJUnitLaunchInfo(IProject project, String appPackage, String runner) {
- mProject = project;
- mAppPackage = appPackage;
- mRunner = runner;
- }
-
- public IProject getProject() {
- return mProject;
- }
-
- public String getAppPackage() {
- return mAppPackage;
- }
-
- public String getRunner() {
- return mRunner;
- }
-
- public boolean isDebugMode() {
- return mDebugMode;
- }
-
- public void setDebugMode(boolean debugMode) {
- mDebugMode = debugMode;
- }
-
- public TestSize getTestSize() {
- return mTestSize;
- }
-
- public void setTestSize(TestSize size) {
- mTestSize = size;
- }
-
- public Collection<IDevice> getDevices() {
- return mDevices;
- }
-
- public void setDevices(Collection<IDevice> devices) {
- mDevices = devices;
- }
-
- /**
- * Specify to run all tests within given package.
- *
- * @param testPackage fully qualified java package
- */
- public void setTestPackage(String testPackage) {
- mTestPackage = testPackage;
- }
-
- /**
- * Return the package of tests to run.
- *
- * @return fully qualified java package. <code>null</code> if not specified.
- */
- public String getTestPackage() {
- return mTestPackage;
- }
-
- /**
- * Sets the test class to run.
- *
- * @param testClass fully qualfied test class to run
- * Expected format: x.y.x.testclass
- */
- public void setTestClass(String testClass) {
- mTestClass = testClass;
- }
-
- /**
- * Returns the test class to run.
- *
- * @return fully qualfied test class to run.
- * <code>null</code> if not specified.
- */
- public String getTestClass() {
- return mTestClass;
- }
-
- /**
- * Sets the test method to run. testClass must also be set.
- *
- * @param testMethod test method to run
- */
- public void setTestMethod(String testMethod) {
- mTestMethod = testMethod;
- }
-
- /**
- * Returns the test method to run.
- *
- * @return test method to run. <code>null</code> if not specified.
- */
- public String getTestMethod() {
- return mTestMethod;
- }
-
- public ILaunch getLaunch() {
- return mLaunch;
- }
-
- public void setLaunch(ILaunch launch) {
- mLaunch = launch;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/runtime/AndroidTestReference.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/runtime/AndroidTestReference.java
deleted file mode 100644
index ec3104d91..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/runtime/AndroidTestReference.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.launch.junit.runtime;
-
-import org.eclipse.jdt.internal.junit.runner.ITestIdentifier;
-import org.eclipse.jdt.internal.junit.runner.ITestReference;
-import org.eclipse.jdt.internal.junit.runner.TestExecution;
-
-/**
- * Base implementation of the Eclipse {@link ITestReference} and {@link ITestIdentifier} interfaces
- * for Android tests.
- * <p/>
- * Provides generic equality/hashcode services
- */
-@SuppressWarnings("restriction")
-abstract class AndroidTestReference implements ITestReference, ITestIdentifier {
-
- /**
- * Gets the {@link ITestIdentifier} for this test reference.
- */
- @Override
- public ITestIdentifier getIdentifier() {
- // this class serves as its own test identifier
- return this;
- }
-
- /**
- * Not supported.
- */
- @Override
- public void run(TestExecution execution) {
- throw new UnsupportedOperationException();
- }
-
- /**
- * Compares {@link ITestIdentifier} using names
- */
- @Override
- public boolean equals(Object obj) {
- if (obj instanceof ITestIdentifier) {
- ITestIdentifier testid = (ITestIdentifier) obj;
- return getName().equals(testid.getName());
- }
- return false;
- }
-
- @Override
- public int hashCode() {
- return getName().hashCode();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/runtime/RemoteAdtTestRunner.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/runtime/RemoteAdtTestRunner.java
deleted file mode 100755
index a48acd324..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/runtime/RemoteAdtTestRunner.java
+++ /dev/null
@@ -1,524 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.launch.junit.runtime;
-
-import com.android.ddmlib.AdbCommandRejectedException;
-import com.android.ddmlib.IDevice;
-import com.android.ddmlib.ShellCommandUnresponsiveException;
-import com.android.ddmlib.TimeoutException;
-import com.android.ddmlib.testrunner.IRemoteAndroidTestRunner.TestSize;
-import com.android.ddmlib.testrunner.ITestRunListener;
-import com.android.ddmlib.testrunner.RemoteAndroidTestRunner;
-import com.android.ddmlib.testrunner.TestIdentifier;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.launch.LaunchMessages;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jdt.internal.junit.runner.IListensToTestExecutions;
-import org.eclipse.jdt.internal.junit.runner.ITestReference;
-import org.eclipse.jdt.internal.junit.runner.MessageIds;
-import org.eclipse.jdt.internal.junit.runner.RemoteTestRunner;
-import org.eclipse.jdt.internal.junit.runner.TestExecution;
-import org.eclipse.jdt.internal.junit.runner.TestReferenceFailure;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Supports Eclipse JUnit execution of Android tests.
- * <p/>
- * Communicates back to a Eclipse JDT JUnit client via a socket connection.
- *
- * @see org.eclipse.jdt.internal.junit.runner.RemoteTestRunner for more details on the protocol
- */
-@SuppressWarnings("restriction")
-public class RemoteAdtTestRunner extends RemoteTestRunner {
-
- private static final String DELAY_MSEC_KEY = "delay_msec";
- /** the delay between each test execution when in collecting test info */
- private static final String COLLECT_TEST_DELAY_MS = "15";
-
- private AndroidJUnitLaunchInfo mLaunchInfo;
- private TestExecution mExecution;
-
- /**
- * Initialize the JDT JUnit test runner parameters from the {@code args}.
- *
- * @param args name-value pair of arguments to pass to parent JUnit runner.
- * @param launchInfo the Android specific test launch info
- */
- protected void init(String[] args, AndroidJUnitLaunchInfo launchInfo) {
- defaultInit(args);
- mLaunchInfo = launchInfo;
- }
-
- /**
- * Runs a set of tests, and reports back results using parent class.
- * <p/>
- * JDT Unit expects to be sent data in the following sequence:
- * <ol>
- * <li>The total number of tests to be executed.</li>
- * <li>The test 'tree' data about the tests to be executed, which is composed of the set of
- * test class names, the number of tests in each class, and the names of each test in the
- * class.</li>
- * <li>The test execution result for each test method. Expects individual notifications of
- * the test execution start, any failures, and the end of the test execution.</li>
- * <li>The end of the test run, with its elapsed time.</li>
- * </ol>
- * <p/>
- * In order to satisfy this, this method performs two actual Android instrumentation runs.
- * The first is a 'log only' run that will collect the test tree data, without actually
- * executing the tests, and send it back to JDT JUnit. The second is the actual test execution,
- * whose results will be communicated back in real-time to JDT JUnit.
- *
- * The tests are run concurrently on all devices. The overall structure is as follows:
- * <ol>
- * <li> First, a separate job per device is run to collect test tree data. A per device
- * {@link TestCollector} records information regarding the tests run on the device.
- * </li>
- * <li> Once all the devices have finished collecting the test tree data, the tree info is
- * collected from all of them and passed to the Junit UI </li>
- * <li> A job per device is again launched to do the actual test run. A per device
- * {@link TestRunListener} notifies the shared {@link TestResultsNotifier} of test
- * status. </li>
- * <li> As tests complete, the test run listener updates the Junit UI </li>
- * </ol>
- *
- * @param testClassNames ignored - the AndroidJUnitLaunchInfo will be used to determine which
- * tests to run.
- * @param testName ignored
- * @param execution used to report test progress
- */
- @Override
- public void runTests(String[] testClassNames, String testName, TestExecution execution) {
- // hold onto this execution reference so it can be used to report test progress
- mExecution = execution;
-
- List<IDevice> devices = new ArrayList<IDevice>(mLaunchInfo.getDevices());
- List<RemoteAndroidTestRunner> runners =
- new ArrayList<RemoteAndroidTestRunner>(devices.size());
-
- for (IDevice device : devices) {
- RemoteAndroidTestRunner runner = new RemoteAndroidTestRunner(
- mLaunchInfo.getAppPackage(), mLaunchInfo.getRunner(), device);
-
- if (mLaunchInfo.getTestClass() != null) {
- if (mLaunchInfo.getTestMethod() != null) {
- runner.setMethodName(mLaunchInfo.getTestClass(), mLaunchInfo.getTestMethod());
- } else {
- runner.setClassName(mLaunchInfo.getTestClass());
- }
- }
-
- if (mLaunchInfo.getTestPackage() != null) {
- runner.setTestPackageName(mLaunchInfo.getTestPackage());
- }
-
- TestSize size = mLaunchInfo.getTestSize();
- if (size != null) {
- runner.setTestSize(size);
- }
-
- runners.add(runner);
- }
-
- // Launch all test info collector jobs
- List<TestTreeCollectorJob> collectorJobs =
- new ArrayList<TestTreeCollectorJob>(devices.size());
- List<TestCollector> perDeviceCollectors = new ArrayList<TestCollector>(devices.size());
- for (int i = 0; i < devices.size(); i++) {
- RemoteAndroidTestRunner runner = runners.get(i);
- String deviceName = devices.get(i).getName();
- TestCollector collector = new TestCollector(deviceName);
- perDeviceCollectors.add(collector);
-
- TestTreeCollectorJob job = new TestTreeCollectorJob(
- "Test Tree Collector for " + deviceName,
- runner, mLaunchInfo.isDebugMode(), collector);
- job.setPriority(Job.INTERACTIVE);
- job.schedule();
-
- collectorJobs.add(job);
- }
-
- // wait for all test info collector jobs to complete
- int totalTests = 0;
- for (TestTreeCollectorJob job : collectorJobs) {
- try {
- job.join();
- } catch (InterruptedException e) {
- endTestRunWithError(e.getMessage());
- return;
- }
-
- if (!job.getResult().isOK()) {
- endTestRunWithError(job.getResult().getMessage());
- return;
- }
-
- TestCollector collector = job.getCollector();
- String err = collector.getErrorMessage();
- if (err != null) {
- endTestRunWithError(err);
- return;
- }
-
- totalTests += collector.getTestCaseCount();
- }
-
- AdtPlugin.printToConsole(mLaunchInfo.getProject(), "Sending test information to Eclipse");
- notifyTestRunStarted(totalTests);
- sendTestTrees(perDeviceCollectors);
-
- List<TestRunnerJob> instrumentationRunnerJobs =
- new ArrayList<TestRunnerJob>(devices.size());
-
- TestResultsNotifier notifier = new TestResultsNotifier(mExecution.getListener(),
- devices.size());
-
- // Spawn all instrumentation runner jobs
- for (int i = 0; i < devices.size(); i++) {
- RemoteAndroidTestRunner runner = runners.get(i);
- String deviceName = devices.get(i).getName();
- TestRunListener testRunListener = new TestRunListener(deviceName, notifier);
- InstrumentationRunJob job = new InstrumentationRunJob(
- "Test Tree Collector for " + deviceName,
- runner, mLaunchInfo.isDebugMode(), testRunListener);
- job.setPriority(Job.INTERACTIVE);
- job.schedule();
-
- instrumentationRunnerJobs.add(job);
- }
-
- // Wait for all jobs to complete
- for (TestRunnerJob job : instrumentationRunnerJobs) {
- try {
- job.join();
- } catch (InterruptedException e) {
- endTestRunWithError(e.getMessage());
- return;
- }
-
- if (!job.getResult().isOK()) {
- endTestRunWithError(job.getResult().getMessage());
- return;
- }
- }
- }
-
- /** Sends info about the test tree to be executed (ie the suites and their enclosed tests) */
- private void sendTestTrees(List<TestCollector> perDeviceCollectors) {
- for (TestCollector c : perDeviceCollectors) {
- ITestReference ref = c.getDeviceSuite();
- ref.sendTree(this);
- }
- }
-
- private static abstract class TestRunnerJob extends Job {
- private ITestRunListener mListener;
- private RemoteAndroidTestRunner mRunner;
- private boolean mIsDebug;
-
- public TestRunnerJob(String name, RemoteAndroidTestRunner runner,
- boolean isDebug, ITestRunListener listener) {
- super(name);
-
- mRunner = runner;
- mIsDebug = isDebug;
- mListener = listener;
- }
-
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- setupRunner();
- mRunner.run(mListener);
- } catch (TimeoutException e) {
- return new Status(Status.ERROR, AdtPlugin.PLUGIN_ID,
- LaunchMessages.RemoteAdtTestRunner_RunTimeoutException,
- e);
- } catch (IOException e) {
- return new Status(Status.ERROR, AdtPlugin.PLUGIN_ID,
- String.format(LaunchMessages.RemoteAdtTestRunner_RunIOException_s,
- e.getMessage()),
- e);
- } catch (AdbCommandRejectedException e) {
- return new Status(Status.ERROR, AdtPlugin.PLUGIN_ID,
- String.format(
- LaunchMessages.RemoteAdtTestRunner_RunAdbCommandRejectedException_s,
- e.getMessage()),
- e);
- } catch (ShellCommandUnresponsiveException e) {
- return new Status(Status.ERROR, AdtPlugin.PLUGIN_ID,
- LaunchMessages.RemoteAdtTestRunner_RunTimeoutException,
- e);
- }
-
- return Status.OK_STATUS;
- }
-
- public RemoteAndroidTestRunner getRunner() {
- return mRunner;
- }
-
- public boolean isDebug() {
- return mIsDebug;
- }
-
- public ITestRunListener getListener() {
- return mListener;
- }
-
- protected abstract void setupRunner();
- }
-
- private static class TestTreeCollectorJob extends TestRunnerJob {
- public TestTreeCollectorJob(String name, RemoteAndroidTestRunner runner, boolean isDebug,
- TestCollector listener) {
- super(name, runner, isDebug, listener);
- }
-
- @Override
- protected void setupRunner() {
- RemoteAndroidTestRunner runner = getRunner();
-
- // set log only to just collect test case info,
- // so Eclipse has correct test case count/tree info
- runner.setLogOnly(true);
-
- // add a small delay between each test. Otherwise for large test suites framework may
- // report Binder transaction failures
- runner.addInstrumentationArg(DELAY_MSEC_KEY, COLLECT_TEST_DELAY_MS);
- }
-
- public TestCollector getCollector() {
- return (TestCollector) getListener();
- }
- }
-
- private static class InstrumentationRunJob extends TestRunnerJob {
- public InstrumentationRunJob(String name, RemoteAndroidTestRunner runner, boolean isDebug,
- ITestRunListener listener) {
- super(name, runner, isDebug, listener);
- }
-
- @Override
- protected void setupRunner() {
- RemoteAndroidTestRunner runner = getRunner();
- runner.setLogOnly(false);
- runner.removeInstrumentationArg(DELAY_MSEC_KEY);
- if (isDebug()) {
- runner.setDebug(true);
- }
- }
- }
-
- /**
- * Main entry method to run tests
- *
- * @param programArgs JDT JUnit program arguments to be processed by parent
- * @param junitInfo the {@link AndroidJUnitLaunchInfo} containing info about this test ru
- */
- public void runTests(String[] programArgs, AndroidJUnitLaunchInfo junitInfo) {
- init(programArgs, junitInfo);
- run();
- }
-
- /**
- * Stop the current test run.
- */
- public void terminate() {
- stop();
- }
-
- @Override
- protected void stop() {
- if (mExecution != null) {
- mExecution.stop();
- }
- }
-
- private void notifyTestRunEnded(long elapsedTime) {
- // copy from parent - not ideal, but method is private
- sendMessage(MessageIds.TEST_RUN_END + elapsedTime);
- flush();
- //shutDown();
- }
-
- /**
- * @param errorMessage
- */
- private void reportError(String errorMessage) {
- AdtPlugin.printErrorToConsole(mLaunchInfo.getProject(),
- String.format(LaunchMessages.RemoteAdtTestRunner_RunFailedMsg_s, errorMessage));
- // is this needed?
- //notifyTestRunStopped(-1);
- }
-
- private void endTestRunWithError(String message) {
- reportError(message);
- notifyTestRunEnded(0);
- }
-
- /**
- * This class provides the interface to notify the JDT UI regarding the status of tests.
- * When running tests on multiple devices, there is a {@link TestRunListener} that listens
- * to results from each device. Rather than all such listeners directly notifying JDT
- * from different threads, they all notify this class which notifies JDT. In addition,
- * the {@link #testRunEnded(String, long)} method make sure that JDT is notified that the
- * test run has completed only when tests on all devices have completed.
- * */
- private class TestResultsNotifier {
- private final IListensToTestExecutions mListener;
- private final int mDeviceCount;
-
- private int mCompletedRuns;
- private long mMaxElapsedTime;
-
- public TestResultsNotifier(IListensToTestExecutions listener, int nDevices) {
- mListener = listener;
- mDeviceCount = nDevices;
- }
-
- public synchronized void testEnded(TestCaseReference ref) {
- mListener.notifyTestEnded(ref);
- }
-
- public synchronized void testFailed(TestReferenceFailure ref) {
- mListener.notifyTestFailed(ref);
- }
-
- public synchronized void testRunEnded(String mDeviceName, long elapsedTime) {
- mCompletedRuns++;
-
- if (elapsedTime > mMaxElapsedTime) {
- mMaxElapsedTime = elapsedTime;
- }
-
- if (mCompletedRuns == mDeviceCount) {
- notifyTestRunEnded(mMaxElapsedTime);
- }
- }
-
- public synchronized void testStarted(TestCaseReference testId) {
- mListener.notifyTestStarted(testId);
- }
- }
-
- /**
- * TestRunListener that communicates results in real-time back to JDT JUnit via the
- * {@link TestResultsNotifier}.
- * */
- private class TestRunListener implements ITestRunListener {
- private final String mDeviceName;
- private TestResultsNotifier mNotifier;
-
- /**
- * Constructs a {@link ITestRunListener} that listens for test results on given device.
- * @param deviceName device on which the tests are being run
- * @param notifier notifier to inform of test status
- */
- public TestRunListener(String deviceName, TestResultsNotifier notifier) {
- mDeviceName = deviceName;
- mNotifier = notifier;
- }
-
- @Override
- public void testEnded(TestIdentifier test, Map<String, String> ignoredTestMetrics) {
- mNotifier.testEnded(new TestCaseReference(mDeviceName, test));
- }
-
- @Override
- public void testFailed(TestIdentifier test, String trace) {
- TestReferenceFailure failure =
- new TestReferenceFailure(new TestCaseReference(mDeviceName, test),
- MessageIds.TEST_FAILED, trace, null);
- mNotifier.testFailed(failure);
- }
-
- @Override
- public void testAssumptionFailure(TestIdentifier test, String trace) {
- TestReferenceFailure failure =
- new TestReferenceFailure(new TestCaseReference(mDeviceName, test),
- MessageIds.TEST_FAILED, trace, null);
- mNotifier.testFailed(failure);
- }
-
- @Override
- public void testIgnored(TestIdentifier test) {
- // TODO: implement me?
- }
-
- @Override
- public synchronized void testRunEnded(long elapsedTime, Map<String, String> runMetrics) {
- mNotifier.testRunEnded(mDeviceName, elapsedTime);
- AdtPlugin.printToConsole(mLaunchInfo.getProject(),
- LaunchMessages.RemoteAdtTestRunner_RunCompleteMsg);
- }
-
- @Override
- public synchronized void testRunFailed(String errorMessage) {
- reportError(errorMessage);
- }
-
- @Override
- public synchronized void testRunStarted(String runName, int testCount) {
- // ignore
- }
-
- @Override
- public synchronized void testRunStopped(long elapsedTime) {
- notifyTestRunStopped(elapsedTime);
- AdtPlugin.printToConsole(mLaunchInfo.getProject(),
- LaunchMessages.RemoteAdtTestRunner_RunStoppedMsg);
- }
-
- @Override
- public synchronized void testStarted(TestIdentifier test) {
- TestCaseReference testId = new TestCaseReference(mDeviceName, test);
- mNotifier.testStarted(testId);
- }
- }
-
- /** Override parent to get extra logs. */
- @Override
- protected boolean connect() {
- boolean result = super.connect();
- if (!result) {
- AdtPlugin.printErrorToConsole(mLaunchInfo.getProject(),
- "Connect to Eclipse test result listener failed");
- }
- return result;
- }
-
- /** Override parent to dump error message to console. */
- @Override
- public void runFailed(String message, Exception exception) {
- if (exception != null) {
- AdtPlugin.logAndPrintError(exception, mLaunchInfo.getProject().getName(),
- "Test launch failed: %s", message);
- } else {
- AdtPlugin.printErrorToConsole(mLaunchInfo.getProject(), "Test launch failed: %s",
- message);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/runtime/TestCaseReference.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/runtime/TestCaseReference.java
deleted file mode 100644
index e05e9b857..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/runtime/TestCaseReference.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.launch.junit.runtime;
-
-import com.android.ddmlib.testrunner.TestIdentifier;
-
-import org.eclipse.jdt.internal.junit.runner.IVisitsTestTrees;
-
-/**
- * Reference for a single Android test method.
- */
-@SuppressWarnings("restriction")
-class TestCaseReference extends AndroidTestReference {
- private final String mClassName;
- private final String mTestName;
- private final String mDeviceName;
-
- /**
- * Creates a TestCaseReference from a {@link TestIdentifier}
- * @param test
- */
- TestCaseReference(String deviceName, TestIdentifier test) {
- mDeviceName = deviceName;
- mClassName = test.getClassName();
- mTestName = test.getTestName();
- }
-
- /**
- * Returns a count of the number of test cases referenced. Is always one for this class.
- */
- @Override
- public int countTestCases() {
- return 1;
- }
-
- /**
- * Sends test identifier and test count information for this test
- *
- * @param notified the {@link IVisitsTestTrees} to send test info to
- */
- @Override
- public void sendTree(IVisitsTestTrees notified) {
- notified.visitTreeEntry(getIdentifier(), false, countTestCases());
- }
-
- /**
- * Returns the identifier of this test, in a format expected by JDT JUnit
- */
- @Override
- public String getName() {
- return String.format("%s (%s) [%s]", mTestName, mClassName, mDeviceName);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/runtime/TestCollector.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/runtime/TestCollector.java
deleted file mode 100644
index 32c5ef81e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/runtime/TestCollector.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.launch.junit.runtime;
-
-import com.android.ddmlib.testrunner.ITestRunListener;
-import com.android.ddmlib.testrunner.TestIdentifier;
-
-import java.util.Map;
-
-/**
- * Collects info about tests to be executed by listening to the results of an Android test run.
- */
-class TestCollector implements ITestRunListener {
- private final String mDeviceName;
- private final TestSuiteReference mDeviceSuiteRef;
-
- private int mTotalTestCount;
- /** test name to test suite reference map. */
-
- private String mErrorMessage = null;
-
- TestCollector(String deviceName) {
- mDeviceName = deviceName;
- mDeviceSuiteRef = new TestSuiteReference(deviceName);
-
- mTotalTestCount = 0;
- }
-
- @Override
- public synchronized void testEnded(TestIdentifier test, Map<String, String> testMetrics) {
- // ignore
- }
-
- /* (non-Javadoc)
- * @see com.android.ddmlib.testrunner.ITestRunListener#testFailed(com.android.ddmlib.testrunner.TestIdentifier, java.lang.String)
- */
- @Override
- public synchronized void testFailed(TestIdentifier test, String trace) {
- // ignore - should be impossible since this is only collecting test information
- }
-
- /* (non-Javadoc)
- * @see com.android.ddmlib.testrunner.ITestRunListener#testIgnored(com.android.ddmlib.testrunner.TestIdentifier)
- */
- @Override
- public synchronized void testIgnored(TestIdentifier test) {
- // ignore - should be impossible since this is only collecting test information
- }
-
- /* (non-Javadoc)
- * @see com.android.ddmlib.testrunner.ITestRunListener#testAssumptionFailure(com.android.ddmlib.testrunner.TestIdentifier, java.lang.String)
- */
- @Override
- public synchronized void testAssumptionFailure(TestIdentifier test, String trace) {
- // ignore - should be impossible since this is only collecting test information
- }
-
- /* (non-Javadoc)
- * @see com.android.ddmlib.testrunner.ITestRunListener#testRunEnded(long, Map<String, String>)
- */
- @Override
- public synchronized void testRunEnded(long elapsedTime, Map<String, String> runMetrics) {
- // ignore
- }
-
- /* (non-Javadoc)
- * @see com.android.ddmlib.testrunner.ITestRunListener#testRunFailed(java.lang.String)
- */
- @Override
- public synchronized void testRunFailed(String errorMessage) {
- mErrorMessage = errorMessage;
- }
-
- /* (non-Javadoc)
- * @see com.android.ddmlib.testrunner.ITestRunListener#testRunStarted(int)
- */
- @Override
- public synchronized void testRunStarted(String ignoredRunName, int testCount) {
- mTotalTestCount = testCount;
- }
-
- /* (non-Javadoc)
- * @see com.android.ddmlib.testrunner.ITestRunListener#testRunStopped(long)
- */
- @Override
- public synchronized void testRunStopped(long elapsedTime) {
- // ignore
- }
-
- /* (non-Javadoc)
- * @see com.android.ddmlib.testrunner.ITestRunListener#testStarted(com.android.ddmlib.testrunner.TestIdentifier)
- */
- @Override
- public synchronized void testStarted(TestIdentifier test) {
- TestSuiteReference suiteRef = mDeviceSuiteRef.getTestSuite(test.getClassName());
- if (suiteRef == null) {
- suiteRef = new TestSuiteReference(test.getClassName());
- mDeviceSuiteRef.addTest(suiteRef);
- }
-
- suiteRef.addTest(new TestCaseReference(mDeviceName, test));
- }
-
- /**
- * Returns the total test count in the test run.
- */
- public synchronized int getTestCaseCount() {
- return mTotalTestCount;
- }
-
- /**
- * Returns the error message that was reported when collecting test info.
- * Returns <code>null</code> if no error occurred.
- */
- public synchronized String getErrorMessage() {
- return mErrorMessage;
- }
-
- public TestSuiteReference getDeviceSuite() {
- return mDeviceSuiteRef;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/runtime/TestSuiteReference.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/runtime/TestSuiteReference.java
deleted file mode 100644
index dcc9f10ec..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/junit/runtime/TestSuiteReference.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.launch.junit.runtime;
-
-import org.eclipse.jdt.internal.junit.runner.IVisitsTestTrees;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Reference for an Android test suite aka class.
- */
-@SuppressWarnings("restriction")
-class TestSuiteReference extends AndroidTestReference {
-
- private final String mClassName;
- private List<AndroidTestReference> mTests;
-
- /**
- * Creates a TestSuiteReference
- *
- * @param className the fully qualified name of the test class
- */
- TestSuiteReference(String className) {
- mClassName = className;
- mTests = new ArrayList<AndroidTestReference>();
- }
-
- /**
- * Returns a count of the number of test cases included in this suite.
- */
- @Override
- public int countTestCases() {
- return mTests.size();
- }
-
- /**
- * Sends test identifier and test count information for this test class, and all its included
- * test methods.
- *
- * @param notified the {@link IVisitsTestTrees} to send test info too
- */
- @Override
- public void sendTree(IVisitsTestTrees notified) {
- notified.visitTreeEntry(getIdentifier(), true, countTestCases());
- for (AndroidTestReference ref: mTests) {
- ref.sendTree(notified);
- }
- }
-
- /**
- * Return the name of this test class.
- */
- @Override
- public String getName() {
- return mClassName;
- }
-
- /**
- * Adds a test method to this suite.
- *
- * @param testRef the {@link TestCaseReference} to add
- */
- void addTest(AndroidTestReference testRef) {
- mTests.add(testRef);
- }
-
- /** Returns the test suite of given name, null if no such test suite exists */
- public TestSuiteReference getTestSuite(String name) {
- for (AndroidTestReference ref: mTests) {
- if (ref instanceof TestSuiteReference && ref.getName().equals(name)) {
- return (TestSuiteReference) ref;
- }
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/messages.properties b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/messages.properties
deleted file mode 100644
index b27a3654e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/launch/messages.properties
+++ /dev/null
@@ -1,43 +0,0 @@
-#
-# Copyright (C) 2010 The Android Open Source Project
-#
-# Licensed under the Eclipse Public License, Version 1.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.eclipse.org/org/documents/epl-v10.php
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-# generic messages that could be used by multiple classes
-LaunchDialogTitle=Android Launch
-NonAndroidProjectError=Specified project is not an Android project
-ParseFileFailure_s=Failed to parse %1$s file
-
-# specialized, class-specific messages
-AndroidJUnitLaunchAction_LaunchDesc_s=%1$s JUnit launch
-AndroidJUnitLaunchAction_LaunchFail=Failed to launch test
-AndroidJUnitLaunchAction_LaunchInstr_2s=Launching instrumentation %1$s on %2$s
-AndroidJUnitDelegate_NoRunnerConfigMsg_s=Warning: No instrumentation runner found for the launch, using %1$s
-AndroidJUnitDelegate_NoRunnerConsoleMsg_4s=%1$s does not specify a %2$s instrumentation or does not declare uses-library %3$s in its %4$s
-AndroidJUnitDelegate_NoRunnerMsg_s=%1$s is not configured correctly for running tests. See Console for details.
-AndroidJUnitDelegate_NoTargetMsg_3s=%1$s is not configured correctly for running tests:\nA targetPackage attribute for instrumentation %2$s in its %3$s could not be found\!
-AndroidJUnitTab_LoaderLabel=Instrumentation runner:
-AndroidJUnitTab_LoadInstrError_s=Failed to load instrumentations from %1$s
-AndroidJUnitTab_NoRunnerError=Instrumentation runner not specified
-AndroidJUnitTab_SizeLabel=Only run test methods annotated with:
-AndroidJUnitTab_TestContainerText=Run all tests in the selected project, or package
-InstrValidator_NoTestLibMsg_s=The application does not declare uses-library %1$s
-InstrValidator_WrongRunnerTypeMsg_s=The instrumentation runner must be of type %1$s
-RemoteAdtTestRunner_RunCompleteMsg=Test run finished
-RemoteAdtTestRunner_RunFailedMsg_s=Test run failed: %1$s
-RemoteAdtTestRunner_RunTimeoutException=Connection with device timed out.
-RemoteAdtTestRunner_RunIOException_s=Lost connection with device: %s
-RemoteAdtTestRunner_RunStoppedMsg=Test run stopped
-RemoteAdtTestRunner_RunAdbCommandRejectedException_s=Adb rejected command: %s
-RemoteAdtTestRunner_RunShellCommandUnresponsiveException=Device stopped sending output
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/AddPrefixFix.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/AddPrefixFix.java
deleted file mode 100644
index d8ce657db..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/AddPrefixFix.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import static com.android.SdkConstants.ANDROID_URI;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.utils.XmlUtils;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.w3c.dom.Node;
-
-@SuppressWarnings("restriction") // DOM model
-final class AddPrefixFix extends DocumentFix {
- private AddPrefixFix(String id, IMarker marker) {
- super(id, marker);
- }
-
- @Override
- public boolean needsFocus() {
- return false;
- }
-
- @Override
- public boolean isCancelable() {
- return false;
- }
-
- @Override
- protected void apply(IDocument document, IStructuredModel model, Node node, int start,
- int end) {
- String prefix = XmlUtils.lookupNamespacePrefix(node, ANDROID_URI);
- try {
- document.replace(start, 0, prefix + ':');
- } catch (BadLocationException e) {
- AdtPlugin.log(e, null);
- }
- }
-
- @Override
- public String getDisplayString() {
- return "Add in an Android namespace prefix";
- }
-
- @Override
- public Image getImage() {
- ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages();
- return sharedImages.getImage(ISharedImages.IMG_OBJ_ADD);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/AddSuppressAnnotation.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/AddSuppressAnnotation.java
deleted file mode 100644
index 1a7fe5697..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/AddSuppressAnnotation.java
+++ /dev/null
@@ -1,424 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.lint;
-
-import static com.android.SdkConstants.FQCN_SUPPRESS_LINT;
-import static com.android.SdkConstants.FQCN_TARGET_API;
-import static com.android.SdkConstants.SUPPRESS_LINT;
-import static com.android.SdkConstants.TARGET_API;
-import static org.eclipse.jdt.core.dom.ArrayInitializer.EXPRESSIONS_PROPERTY;
-import static org.eclipse.jdt.core.dom.SingleMemberAnnotation.VALUE_PROPERTY;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.sdklib.SdkVersionInfo;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.tools.lint.checks.AnnotationDetector;
-import com.android.tools.lint.checks.ApiDetector;
-import com.android.tools.lint.detector.api.Issue;
-import com.android.tools.lint.detector.api.Scope;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jdt.core.ICompilationUnit;
-import org.eclipse.jdt.core.dom.AST;
-import org.eclipse.jdt.core.dom.ASTNode;
-import org.eclipse.jdt.core.dom.AnonymousClassDeclaration;
-import org.eclipse.jdt.core.dom.ArrayInitializer;
-import org.eclipse.jdt.core.dom.BodyDeclaration;
-import org.eclipse.jdt.core.dom.CompilationUnit;
-import org.eclipse.jdt.core.dom.Expression;
-import org.eclipse.jdt.core.dom.FieldDeclaration;
-import org.eclipse.jdt.core.dom.MethodDeclaration;
-import org.eclipse.jdt.core.dom.NodeFinder;
-import org.eclipse.jdt.core.dom.SingleMemberAnnotation;
-import org.eclipse.jdt.core.dom.StringLiteral;
-import org.eclipse.jdt.core.dom.TypeDeclaration;
-import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.jdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.jdt.core.dom.rewrite.ListRewrite;
-import org.eclipse.jdt.ui.IWorkingCopyManager;
-import org.eclipse.jdt.ui.JavaUI;
-import org.eclipse.jdt.ui.SharedASTProvider;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IMarkerResolution;
-import org.eclipse.ui.IMarkerResolution2;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.ui.texteditor.ITextEditor;
-
-import java.util.List;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * Marker resolution for adding {@code @SuppressLint} annotations in Java files.
- * It can also add {@code @TargetApi} annotations.
- */
-class AddSuppressAnnotation implements IMarkerResolution2 {
- private final IMarker mMarker;
- private final String mId;
- private final BodyDeclaration mNode;
- private final String mDescription;
- /**
- * Should it create a {@code @TargetApi} annotation instead of
- * {@code SuppressLint} ? If so pass a non null API level
- */
- private final String mTargetApi;
-
- private AddSuppressAnnotation(
- @NonNull String id,
- @NonNull IMarker marker,
- @NonNull BodyDeclaration node,
- @NonNull String description,
- @Nullable String targetApi) {
- mId = id;
- mMarker = marker;
- mNode = node;
- mDescription = description;
- mTargetApi = targetApi;
- }
-
- @Override
- public String getLabel() {
- return mDescription;
- }
-
- @Override
- public String getDescription() {
- return null;
- }
-
- @Override
- public Image getImage() {
- return IconFactory.getInstance().getIcon("newannotation"); //$NON-NLS-1$
- }
-
- @Override
- public void run(IMarker marker) {
- ITextEditor textEditor = AdtUtils.getActiveTextEditor();
- IDocumentProvider provider = textEditor.getDocumentProvider();
- IEditorInput editorInput = textEditor.getEditorInput();
- IDocument document = provider.getDocument(editorInput);
- if (document == null) {
- return;
- }
- IWorkingCopyManager manager = JavaUI.getWorkingCopyManager();
- ICompilationUnit compilationUnit = manager.getWorkingCopy(editorInput);
- try {
- MultiTextEdit edit;
- if (mTargetApi == null) {
- edit = addSuppressAnnotation(document, compilationUnit, mNode);
- } else {
- edit = addTargetApiAnnotation(document, compilationUnit, mNode);
- }
- if (edit != null) {
- edit.apply(document);
-
- // Remove the marker now that the suppress annotation has been added
- // (so the user doesn't have to re-run lint just to see it disappear,
- // and besides we don't want to keep offering marker resolutions on this
- // marker which could lead to duplicate annotations since the above code
- // assumes that the current id isn't in the list of values, since otherwise
- // lint shouldn't have complained here.
- mMarker.delete();
- }
- } catch (Exception ex) {
- AdtPlugin.log(ex, "Could not add suppress annotation");
- }
- }
-
- @SuppressWarnings({"rawtypes"}) // Java AST API has raw types
- private MultiTextEdit addSuppressAnnotation(
- IDocument document,
- ICompilationUnit compilationUnit,
- BodyDeclaration declaration) throws CoreException {
- List modifiers = declaration.modifiers();
- SingleMemberAnnotation existing = null;
- for (Object o : modifiers) {
- if (o instanceof SingleMemberAnnotation) {
- SingleMemberAnnotation annotation = (SingleMemberAnnotation) o;
- String type = annotation.getTypeName().getFullyQualifiedName();
- if (type.equals(FQCN_SUPPRESS_LINT) || type.endsWith(SUPPRESS_LINT)) {
- existing = annotation;
- break;
- }
- }
- }
-
- ImportRewrite importRewrite = ImportRewrite.create(compilationUnit, true);
- String local = importRewrite.addImport(FQCN_SUPPRESS_LINT);
- AST ast = declaration.getAST();
- ASTRewrite rewriter = ASTRewrite.create(ast);
- if (existing == null) {
- SingleMemberAnnotation newAnnotation = ast.newSingleMemberAnnotation();
- newAnnotation.setTypeName(ast.newSimpleName(local));
- StringLiteral value = ast.newStringLiteral();
- value.setLiteralValue(mId);
- newAnnotation.setValue(value);
- ListRewrite listRewrite = rewriter.getListRewrite(declaration,
- declaration.getModifiersProperty());
- listRewrite.insertFirst(newAnnotation, null);
- } else {
- Expression existingValue = existing.getValue();
- if (existingValue instanceof StringLiteral) {
- StringLiteral stringLiteral = (StringLiteral) existingValue;
- if (mId.equals(stringLiteral.getLiteralValue())) {
- // Already contains the id
- return null;
- }
- // Create a new array initializer holding the old string plus the new id
- ArrayInitializer array = ast.newArrayInitializer();
- StringLiteral old = ast.newStringLiteral();
- old.setLiteralValue(stringLiteral.getLiteralValue());
- array.expressions().add(old);
- StringLiteral value = ast.newStringLiteral();
- value.setLiteralValue(mId);
- array.expressions().add(value);
- rewriter.set(existing, VALUE_PROPERTY, array, null);
- } else if (existingValue instanceof ArrayInitializer) {
- // Existing array: just append the new string
- ArrayInitializer array = (ArrayInitializer) existingValue;
- List expressions = array.expressions();
- if (expressions != null) {
- for (Object o : expressions) {
- if (o instanceof StringLiteral) {
- if (mId.equals(((StringLiteral)o).getLiteralValue())) {
- // Already contains the id
- return null;
- }
- }
- }
- }
- StringLiteral value = ast.newStringLiteral();
- value.setLiteralValue(mId);
- ListRewrite listRewrite = rewriter.getListRewrite(array, EXPRESSIONS_PROPERTY);
- listRewrite.insertLast(value, null);
- } else {
- assert false : existingValue;
- return null;
- }
- }
-
- TextEdit importEdits = importRewrite.rewriteImports(new NullProgressMonitor());
- TextEdit annotationEdits = rewriter.rewriteAST(document, null);
-
- // Apply to the document
- MultiTextEdit edit = new MultiTextEdit();
- // Create the edit to change the imports, only if
- // anything changed
- if (importEdits.hasChildren()) {
- edit.addChild(importEdits);
- }
- edit.addChild(annotationEdits);
-
- return edit;
- }
-
- @SuppressWarnings({"rawtypes"}) // Java AST API has raw types
- private MultiTextEdit addTargetApiAnnotation(
- IDocument document,
- ICompilationUnit compilationUnit,
- BodyDeclaration declaration) throws CoreException {
- List modifiers = declaration.modifiers();
- SingleMemberAnnotation existing = null;
- for (Object o : modifiers) {
- if (o instanceof SingleMemberAnnotation) {
- SingleMemberAnnotation annotation = (SingleMemberAnnotation) o;
- String type = annotation.getTypeName().getFullyQualifiedName();
- if (type.equals(FQCN_TARGET_API) || type.endsWith(TARGET_API)) {
- existing = annotation;
- break;
- }
- }
- }
-
- ImportRewrite importRewrite = ImportRewrite.create(compilationUnit, true);
- importRewrite.addImport("android.os.Build"); //$NON-NLS-1$
- String local = importRewrite.addImport(FQCN_TARGET_API);
- AST ast = declaration.getAST();
- ASTRewrite rewriter = ASTRewrite.create(ast);
- if (existing == null) {
- SingleMemberAnnotation newAnnotation = ast.newSingleMemberAnnotation();
- newAnnotation.setTypeName(ast.newSimpleName(local));
- Expression value = createLiteral(ast);
- newAnnotation.setValue(value);
- ListRewrite listRewrite = rewriter.getListRewrite(declaration,
- declaration.getModifiersProperty());
- listRewrite.insertFirst(newAnnotation, null);
- } else {
- Expression value = createLiteral(ast);
- rewriter.set(existing, VALUE_PROPERTY, value, null);
- }
-
- TextEdit importEdits = importRewrite.rewriteImports(new NullProgressMonitor());
- TextEdit annotationEdits = rewriter.rewriteAST(document, null);
- MultiTextEdit edit = new MultiTextEdit();
- if (importEdits.hasChildren()) {
- edit.addChild(importEdits);
- }
- edit.addChild(annotationEdits);
-
- return edit;
- }
-
- private Expression createLiteral(AST ast) {
- Expression value;
- if (!isCodeName()) {
- value = ast.newQualifiedName(
- ast.newQualifiedName(ast.newSimpleName("Build"), //$NON-NLS-1$
- ast.newSimpleName("VERSION_CODES")), //$NON-NLS-1$
- ast.newSimpleName(mTargetApi));
- } else {
- value = ast.newNumberLiteral(mTargetApi);
- }
- return value;
- }
-
- private boolean isCodeName() {
- return Character.isDigit(mTargetApi.charAt(0));
- }
-
- /**
- * Adds any applicable suppress lint fix resolutions into the given list
- *
- * @param marker the marker to create fixes for
- * @param id the issue id
- * @param resolutions a list to add the created resolutions into, if any
- */
- public static void createFixes(IMarker marker, String id,
- List<IMarkerResolution> resolutions) {
- ITextEditor textEditor = AdtUtils.getActiveTextEditor();
- IDocumentProvider provider = textEditor.getDocumentProvider();
- IEditorInput editorInput = textEditor.getEditorInput();
- IDocument document = provider.getDocument(editorInput);
- if (document == null) {
- return;
- }
-
- IWorkingCopyManager manager = JavaUI.getWorkingCopyManager();
- ICompilationUnit compilationUnit = manager.getWorkingCopy(editorInput);
- int offset = 0;
- int length = 0;
- int start = marker.getAttribute(IMarker.CHAR_START, -1);
- int end = marker.getAttribute(IMarker.CHAR_END, -1);
- offset = start;
- length = end - start;
- CompilationUnit root = SharedASTProvider.getAST(compilationUnit,
- SharedASTProvider.WAIT_YES, null);
- if (root == null) {
- return;
- }
-
- int api = -1;
- if (id.equals(ApiDetector.UNSUPPORTED.getId()) ||
- id.equals(ApiDetector.INLINED.getId())) {
- String message = marker.getAttribute(IMarker.MESSAGE, null);
- if (message != null) {
- Pattern pattern = Pattern.compile("\\s(\\d+)\\s"); //$NON-NLS-1$
- Matcher matcher = pattern.matcher(message);
- if (matcher.find()) {
- api = Integer.parseInt(matcher.group(1));
- }
- }
- }
-
- Issue issue = EclipseLintClient.getRegistry().getIssue(id);
- boolean isClassDetector = issue != null && issue.getImplementation().getScope().contains(
- Scope.CLASS_FILE);
-
- // Don't offer to suppress (with an annotation) the annotation checks
- if (issue == AnnotationDetector.ISSUE) {
- return;
- }
-
- NodeFinder nodeFinder = new NodeFinder(root, offset, length);
- ASTNode coveringNode;
- if (offset <= 0) {
- // Error added on the first line of a Java class: typically from a class-based
- // detector which lacks line information. Map this to the top level class
- // in the file instead.
- coveringNode = root;
- if (root.types() != null && root.types().size() > 0) {
- Object type = root.types().get(0);
- if (type instanceof ASTNode) {
- coveringNode = (ASTNode) type;
- }
- }
- } else {
- coveringNode = nodeFinder.getCoveringNode();
- }
- for (ASTNode body = coveringNode; body != null; body = body.getParent()) {
- if (body instanceof BodyDeclaration) {
- BodyDeclaration declaration = (BodyDeclaration) body;
-
- String target = null;
- if (body instanceof MethodDeclaration) {
- target = ((MethodDeclaration) body).getName().toString() + "()"; //$NON-NLS-1$
- } else if (body instanceof FieldDeclaration) {
- target = "field";
- FieldDeclaration field = (FieldDeclaration) body;
- if (field.fragments() != null && field.fragments().size() > 0) {
- ASTNode first = (ASTNode) field.fragments().get(0);
- if (first instanceof VariableDeclarationFragment) {
- VariableDeclarationFragment decl = (VariableDeclarationFragment) first;
- target = decl.getName().toString();
- }
- }
- } else if (body instanceof AnonymousClassDeclaration) {
- target = "anonymous class";
- } else if (body instanceof TypeDeclaration) {
- target = ((TypeDeclaration) body).getName().toString();
- } else {
- target = body.getClass().getSimpleName();
- }
-
- // In class files, detectors can only find annotations on methods
- // and on classes, not on variable declarations
- if (isClassDetector && !(body instanceof MethodDeclaration
- || body instanceof TypeDeclaration
- || body instanceof AnonymousClassDeclaration
- || body instanceof FieldDeclaration)) {
- continue;
- }
-
- String desc = String.format("Add @SuppressLint '%1$s\' to '%2$s'", id, target);
- resolutions.add(new AddSuppressAnnotation(id, marker, declaration, desc, null));
-
- if (api != -1
- // @TargetApi is only valid on methods and classes, not fields etc
- && (body instanceof MethodDeclaration
- || body instanceof TypeDeclaration)) {
- String apiString = SdkVersionInfo.getBuildCode(api);
- if (apiString == null) {
- apiString = Integer.toString(api);
- }
- desc = String.format("Add @TargetApi(%1$s) to '%2$s'", apiString, target);
- resolutions.add(new AddSuppressAnnotation(id, marker, declaration, desc,
- apiString));
- }
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/AddSuppressAttribute.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/AddSuppressAttribute.java
deleted file mode 100644
index 88e0880e5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/AddSuppressAttribute.java
+++ /dev/null
@@ -1,237 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.lint;
-
-import static com.android.SdkConstants.ATTR_IGNORE;
-import static com.android.SdkConstants.ATTR_TARGET_API;
-import static com.android.SdkConstants.DOT_XML;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.sdklib.SdkVersionInfo;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-import com.android.tools.lint.checks.ApiDetector;
-import com.google.common.collect.Lists;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-import java.util.Collections;
-import java.util.List;
-import java.util.Locale;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * Fix for adding {@code tools:ignore="id"} attributes in XML files.
- */
-class AddSuppressAttribute implements ICompletionProposal {
- private final AndroidXmlEditor mEditor;
- private final String mId;
- private final IMarker mMarker;
- private final Element mElement;
- private final String mDescription;
- /**
- * Should it create a {@code tools:targetApi} attribute instead of a
- * {@code tools:ignore} attribute? If so pass a non null API level
- */
- private final String mTargetApi;
-
-
- private AddSuppressAttribute(
- @NonNull AndroidXmlEditor editor,
- @NonNull String id,
- @NonNull IMarker marker,
- @NonNull Element element,
- @NonNull String description,
- @Nullable String targetApi) {
- mEditor = editor;
- mId = id;
- mMarker = marker;
- mElement = element;
- mDescription = description;
- mTargetApi = targetApi;
- }
-
- @Override
- public Point getSelection(IDocument document) {
- return null;
- }
-
- @Override
- public String getAdditionalProposalInfo() {
- return null;
- }
-
- @Override
- public String getDisplayString() {
- return mDescription;
- }
-
- @Override
- public IContextInformation getContextInformation() {
- return null;
- }
-
- @Override
- public Image getImage() {
- return IconFactory.getInstance().getIcon("newannotation"); //$NON-NLS-1$
- }
-
- @Override
- public void apply(IDocument document) {
- String attribute;
- String value;
- if (mTargetApi != null) {
- attribute = ATTR_TARGET_API;
- value = mTargetApi;
- } else {
- attribute = ATTR_IGNORE;
- value = mId;
- }
- AdtUtils.setToolsAttribute(mEditor, mElement, mDescription, attribute, value,
- true /*reveal*/, true /*append*/);
-
- try {
- // Remove the marker now that the suppress attribute has been added
- // (so the user doesn't have to re-run lint just to see it disappear)
- mMarker.delete();
- } catch (CoreException e) {
- AdtPlugin.log(e, "Could not remove marker");
- }
- }
-
- /**
- * Returns a quickfix to suppress a specific lint issue id on the node corresponding to
- * the given marker.
- *
- * @param editor the associated editor containing the marker
- * @param marker the marker to create fixes for
- * @param id the issue id
- * @return a list of fixes for this marker, possibly empty
- */
- @NonNull
- public static List<AddSuppressAttribute> createFixes(
- @NonNull AndroidXmlEditor editor,
- @NonNull IMarker marker,
- @NonNull String id) {
- // This only applies to XML files:
- String fileName = marker.getResource().getName();
- if (!fileName.endsWith(DOT_XML)) {
- return Collections.emptyList();
- }
-
- int offset = marker.getAttribute(IMarker.CHAR_START, -1);
- Node node;
- if (offset == -1) {
- node = DomUtilities.getNode(editor.getStructuredDocument(), 0);
- if (node != null) {
- node = node.getOwnerDocument().getDocumentElement();
- }
- } else {
- node = DomUtilities.getNode(editor.getStructuredDocument(), offset);
- }
- if (node == null) {
- return Collections.emptyList();
- }
- Document document = node.getOwnerDocument();
- while (node != null && node.getNodeType() != Node.ELEMENT_NODE) {
- node = node.getParentNode();
- }
- if (node == null) {
- node = document.getDocumentElement();
- if (node == null) {
- return Collections.emptyList();
- }
- }
-
- String desc = String.format("Add ignore '%1$s\' to element", id);
- Element element = (Element) node;
- List<AddSuppressAttribute> fixes = Lists.newArrayListWithExpectedSize(2);
- fixes.add(new AddSuppressAttribute(editor, id, marker, element, desc, null));
-
- int api = -1;
- if (id.equals(ApiDetector.UNSUPPORTED.getId())
- || id.equals(ApiDetector.INLINED.getId())) {
- String message = marker.getAttribute(IMarker.MESSAGE, null);
- if (message != null) {
- Pattern pattern = Pattern.compile("\\s(\\d+)\\s"); //$NON-NLS-1$
- Matcher matcher = pattern.matcher(message);
- if (matcher.find()) {
- api = Integer.parseInt(matcher.group(1));
- String targetApi;
- String buildCode = SdkVersionInfo.getBuildCode(api);
- if (buildCode != null) {
- targetApi = buildCode.toLowerCase(Locale.US);
- fixes.add(new AddSuppressAttribute(editor, id, marker, element,
- String.format("Add targetApi '%1$s\' to element", targetApi),
- targetApi));
- }
- targetApi = Integer.toString(api);
- fixes.add(new AddSuppressAttribute(editor, id, marker, element,
- String.format("Add targetApi '%1$s\' to element", targetApi),
- targetApi));
- }
- }
- }
-
- return fixes;
- }
-
- /**
- * Returns a quickfix to suppress a given issue type on the <b>root element</b>
- * of the given editor.
- *
- * @param editor the associated editor containing the marker
- * @param marker the marker to create fixes for
- * @param id the issue id
- * @return a fix for this marker, or null if unable
- */
- @Nullable
- public static AddSuppressAttribute createFixForAll(
- @NonNull AndroidXmlEditor editor,
- @NonNull IMarker marker,
- @NonNull String id) {
- // This only applies to XML files:
- String fileName = marker.getResource().getName();
- if (!fileName.endsWith(DOT_XML)) {
- return null;
- }
-
- Node node = DomUtilities.getNode(editor.getStructuredDocument(), 0);
- if (node != null) {
- node = node.getOwnerDocument().getDocumentElement();
- String desc = String.format("Add ignore '%1$s\' to element", id);
- Element element = (Element) node;
- return new AddSuppressAttribute(editor, id, marker, element, desc, null);
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/ClearLintMarkersAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/ClearLintMarkersAction.java
deleted file mode 100644
index a10d39472..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/ClearLintMarkersAction.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.lint;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.ui.IActionDelegate;
-
-import java.util.List;
-
-/** Action which clear lint markers from the current project */
-public class ClearLintMarkersAction implements IActionDelegate {
-
- private ISelection mSelection;
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
- mSelection = selection;
- }
-
- @Override
- public void run(IAction action) {
- List<IProject> projects = RunLintAction.getProjects(mSelection, false /*warn*/);
- if (projects != null) {
- EclipseLintRunner.cancelCurrentJobs(false);
- EclipseLintClient.clearMarkers(projects);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/ColumnDialog.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/ColumnDialog.java
deleted file mode 100644
index be987d498..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/ColumnDialog.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.viewers.CheckboxTableViewer;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.ui.dialogs.SelectionStatusDialog;
-
-/**
- * Dialog for editing visible columns in the {@link LintList}
- */
-class ColumnDialog extends SelectionStatusDialog implements Listener, IStructuredContentProvider {
- private LintColumn[] mColumns;
- private LintColumn[] mSelectedColumns;
- private CheckboxTableViewer mViewer;
-
- public ColumnDialog(Shell parent, LintColumn[] fields, LintColumn[] selected) {
- super(parent);
- mColumns = fields;
- mSelectedColumns = selected;
- setTitle("Select Visible Columns");
- setHelpAvailable(false);
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite container = new Composite(parent, SWT.NONE);
- container.setLayout(new GridLayout(1, false));
- GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
- // Wide enough to accommodate the error label
- gridData.widthHint = 500;
- container.setLayoutData(gridData);
-
- Label lblSelectVisibleColumns = new Label(container, SWT.NONE);
- lblSelectVisibleColumns.setText("Select visible columns:");
-
- mViewer = CheckboxTableViewer.newCheckList(container,
- SWT.BORDER | SWT.FULL_SELECTION | SWT.HIDE_SELECTION);
- Table table = mViewer.getTable();
- table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
- mViewer.setContentProvider(this);
-
- mViewer.setInput(mColumns);
- mViewer.setCheckedElements(mSelectedColumns);
-
- validate();
-
- return container;
- }
-
- @Override
- protected void computeResult() {
- Object[] checked = mViewer.getCheckedElements();
- mSelectedColumns = new LintColumn[checked.length];
- for (int i = 0, n = checked.length; i < n; i++) {
- mSelectedColumns[i] = (LintColumn) checked[i];
- }
- }
-
- public LintColumn[] getSelectedColumns() {
- return mSelectedColumns;
- }
-
- @Override
- public void handleEvent(Event event) {
- validate();
- }
-
- private void validate() {
- IStatus status;
- computeResult();
-
- if (mViewer.getCheckedElements().length <= 1) {
- status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "Must selected at least one column");
- } else {
- status = new Status(IStatus.OK, AdtPlugin.PLUGIN_ID, null);
- }
- updateStatus(status);
- }
-
- // ---- Implements IStructuredContentProvider ----
-
- @Override
- public void dispose() {
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- @Override
- public Object[] getElements(Object inputElement) {
- return mColumns;
- }
- } \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/ConvertToDpFix.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/ConvertToDpFix.java
deleted file mode 100644
index 628972f8c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/ConvertToDpFix.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import static com.android.SdkConstants.UNIT_PX;
-import static com.android.SdkConstants.VALUE_N_DP;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.jface.dialogs.IInputValidator;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-@SuppressWarnings("restriction") // DOM model
-final class ConvertToDpFix extends DocumentFix implements IInputValidator {
- private ConvertToDpFix(String id, IMarker marker) {
- super(id, marker);
- }
-
- @Override
- public boolean needsFocus() {
- return false;
- }
-
- @Override
- public boolean isCancelable() {
- return true;
- }
-
- @Override
- protected void apply(IDocument document, IStructuredModel model, Node node, int start,
- int end) {
- Shell shell = AdtPlugin.getShell();
- InputDensityDialog densityDialog = new InputDensityDialog(shell);
- if (densityDialog.open() == Window.OK) {
- int dpi = densityDialog.getDensity();
- Element element = (Element) node;
- Pattern pattern = Pattern.compile("(\\d+)px"); //$NON-NLS-1$
- NamedNodeMap attributes = element.getAttributes();
- for (int i = 0, n = attributes.getLength(); i < n; i++) {
- Attr attribute = (Attr) attributes.item(i);
- String value = attribute.getValue();
- if (value.endsWith(UNIT_PX)) {
- Matcher matcher = pattern.matcher(value);
- if (matcher.matches()) {
- String numberString = matcher.group(1);
- try {
- int px = Integer.parseInt(numberString);
- int dp = px * 160 / dpi;
- String newValue = String.format(VALUE_N_DP, dp);
- attribute.setNodeValue(newValue);
- } catch (NumberFormatException nufe) {
- AdtPlugin.log(nufe, null);
- }
- }
- }
- }
- }
- }
-
- @Override
- public String getDisplayString() {
- return "Convert to \"dp\"...";
- }
-
- @Override
- public Image getImage() {
- return AdtPlugin.getAndroidLogo();
- }
-
- // ---- Implements IInputValidator ----
-
- @Override
- public String isValid(String input) {
- if (input == null || input.length() == 0)
- return " "; //$NON-NLS-1$
-
- try {
- int i = Integer.parseInt(input);
- if (i <= 0 || i > 1000) {
- return "Invalid range";
- }
- } catch (NumberFormatException x) {
- return "Enter a valid number";
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/DocumentFix.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/DocumentFix.java
deleted file mode 100644
index e17d5ec97..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/DocumentFix.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.wst.sse.core.StructuredModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.w3c.dom.Node;
-
-@SuppressWarnings("restriction") // DOM model
-abstract class DocumentFix extends LintFix {
-
- protected DocumentFix(String id, IMarker marker) {
- super(id, marker);
- }
-
- protected abstract void apply(IDocument document, IStructuredModel model, Node node,
- int start, int end);
-
- @Override
- public void apply(IDocument document) {
- if (!(document instanceof IStructuredDocument)) {
- AdtPlugin.log(null, "Unexpected document type: %1$s. Can't fix.",
- document.getClass().getName());
- return;
- }
- int start = mMarker.getAttribute(IMarker.CHAR_START, -1);
- int end = mMarker.getAttribute(IMarker.CHAR_END, -1);
- if (start != -1 && end != -1) {
- IModelManager manager = StructuredModelManager.getModelManager();
- IStructuredModel model = manager.getModelForEdit((IStructuredDocument) document);
- Node node = DomUtilities.getNode(document, start);
- try {
- apply(document, model, node, start, end);
- } finally {
- model.releaseFromEdit();
- }
-
- if (!isCancelable()) {
- deleteMarker();
- }
- }
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/DosLineEndingsFix.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/DosLineEndingsFix.java
deleted file mode 100644
index 9a5456b56..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/DosLineEndingsFix.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-
-/** Quickfix for correcting line endings in the file */
-class DosLineEndingsFix extends LintFix {
-
- protected DosLineEndingsFix(String id, IMarker marker) {
- super(id, marker);
- }
-
- @Override
- public boolean needsFocus() {
- return false;
- }
-
- @Override
- public boolean isCancelable() {
- return false;
- }
-
- @Override
- public String getDisplayString() {
- return "Fix line endings";
- }
-
- @Override
- public void apply(IDocument document) {
- char next = 0;
- for (int i = document.getLength() - 1; i >= 0; i--) {
- try {
- char c = document.getChar(i);
- if (c == '\r' && next != '\n') {
- document.replace(i, 1, "\n"); //$NON-NLS-1$
- }
- next = c;
- } catch (BadLocationException e) {
- AdtPlugin.log(e, null);
- return;
- }
- }
-
- deleteMarker();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/EclipseLintClient.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/EclipseLintClient.java
deleted file mode 100644
index 3dd424087..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/EclipseLintClient.java
+++ /dev/null
@@ -1,1306 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import static com.android.SdkConstants.DOT_JAR;
-import static com.android.SdkConstants.DOT_XML;
-import static com.android.SdkConstants.FD_NATIVE_LIBS;
-import static com.android.ide.eclipse.adt.AdtConstants.MARKER_LINT;
-import static com.android.ide.eclipse.adt.AdtUtils.workspacePathToFile;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.sdklib.IAndroidTarget;
-import com.android.tools.lint.checks.BuiltinIssueRegistry;
-import com.android.tools.lint.client.api.Configuration;
-import com.android.tools.lint.client.api.IssueRegistry;
-import com.android.tools.lint.client.api.JavaParser;
-import com.android.tools.lint.client.api.LintClient;
-import com.android.tools.lint.client.api.LintDriver;
-import com.android.tools.lint.client.api.XmlParser;
-import com.android.tools.lint.detector.api.ClassContext;
-import com.android.tools.lint.detector.api.Context;
-import com.android.tools.lint.detector.api.DefaultPosition;
-import com.android.tools.lint.detector.api.Detector;
-import com.android.tools.lint.detector.api.Issue;
-import com.android.tools.lint.detector.api.JavaContext;
-import com.android.tools.lint.detector.api.LintUtils;
-import com.android.tools.lint.detector.api.Location;
-import com.android.tools.lint.detector.api.Location.Handle;
-import com.android.tools.lint.detector.api.Position;
-import com.android.tools.lint.detector.api.Project;
-import com.android.tools.lint.detector.api.Severity;
-import com.android.tools.lint.detector.api.TextFormat;
-import com.android.tools.lint.detector.api.XmlContext;
-import com.android.utils.Pair;
-import com.android.utils.SdkUtils;
-import com.google.common.collect.Maps;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jdt.core.IClasspathEntry;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.core.ITypeHierarchy;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.internal.compiler.CompilationResult;
-import org.eclipse.jdt.internal.compiler.DefaultErrorHandlingPolicies;
-import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration;
-import org.eclipse.jdt.internal.compiler.batch.CompilationUnit;
-import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
-import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
-import org.eclipse.jdt.internal.compiler.parser.Parser;
-import org.eclipse.jdt.internal.compiler.problem.AbortCompilation;
-import org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory;
-import org.eclipse.jdt.internal.compiler.problem.ProblemReporter;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.editors.text.TextFileDocumentProvider;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.wst.sse.core.StructuredModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.WeakHashMap;
-
-import lombok.ast.ecj.EcjTreeConverter;
-import lombok.ast.grammar.ParseProblem;
-import lombok.ast.grammar.Source;
-
-/**
- * Eclipse implementation for running lint on workspace files and projects.
- */
-@SuppressWarnings("restriction") // DOM model
-public class EclipseLintClient extends LintClient {
- static final String MARKER_CHECKID_PROPERTY = "checkid"; //$NON-NLS-1$
- private static final String MODEL_PROPERTY = "model"; //$NON-NLS-1$
- private final List<? extends IResource> mResources;
- private final IDocument mDocument;
- private boolean mWasFatal;
- private boolean mFatalOnly;
- private EclipseJavaParser mJavaParser;
- private boolean mCollectNodes;
- private Map<Node, IMarker> mNodeMap;
-
- /**
- * Creates a new {@link EclipseLintClient}.
- *
- * @param registry the associated detector registry
- * @param resources the associated resources (project, file or null)
- * @param document the associated document, or null if the {@code resource}
- * param is not a file
- * @param fatalOnly whether only fatal issues should be reported (and therefore checked)
- */
- public EclipseLintClient(IssueRegistry registry, List<? extends IResource> resources,
- IDocument document, boolean fatalOnly) {
- mResources = resources;
- mDocument = document;
- mFatalOnly = fatalOnly;
- }
-
- /**
- * Returns true if lint should only check fatal issues
- *
- * @return true if lint should only check fatal issues
- */
- public boolean isFatalOnly() {
- return mFatalOnly;
- }
-
- /**
- * Sets whether the lint client should store associated XML nodes for each
- * reported issue
- *
- * @param collectNodes if true, collect node positions for errors in XML
- * files, retrievable via the {@link #getIssueForNode} method
- */
- public void setCollectNodes(boolean collectNodes) {
- mCollectNodes = collectNodes;
- }
-
- /**
- * Returns one of the issues for the given node (there could be more than one)
- *
- * @param node the node to look up lint issues for
- * @return the marker for one of the issues found for the given node
- */
- @Nullable
- public IMarker getIssueForNode(@NonNull UiViewElementNode node) {
- if (mNodeMap != null) {
- return mNodeMap.get(node.getXmlNode());
- }
-
- return null;
- }
-
- /**
- * Returns a collection of nodes that have one or more lint warnings
- * associated with them (retrievable via
- * {@link #getIssueForNode(UiViewElementNode)})
- *
- * @return a collection of nodes, which should <b>not</b> be modified by the
- * caller
- */
- @Nullable
- public Collection<Node> getIssueNodes() {
- if (mNodeMap != null) {
- return mNodeMap.keySet();
- }
-
- return null;
- }
-
- // ----- Extends LintClient -----
-
- @Override
- public void log(@NonNull Severity severity, @Nullable Throwable exception,
- @Nullable String format, @Nullable Object... args) {
- if (exception == null) {
- AdtPlugin.log(IStatus.WARNING, format, args);
- } else {
- AdtPlugin.log(exception, format, args);
- }
- }
-
- @Override
- public XmlParser getXmlParser() {
- return new XmlParser() {
- @Override
- public Document parseXml(@NonNull XmlContext context) {
- // Map File to IFile
- IFile file = AdtUtils.fileToIFile(context.file);
- if (file == null || !file.exists()) {
- String path = context.file.getPath();
- AdtPlugin.log(IStatus.ERROR, "Can't find file %1$s in workspace", path);
- return null;
- }
-
- IStructuredModel model = null;
- try {
- IModelManager modelManager = StructuredModelManager.getModelManager();
- if (modelManager == null) {
- // This can happen if incremental lint is running right as Eclipse is
- // shutting down
- return null;
- }
- model = modelManager.getModelForRead(file);
- if (model instanceof IDOMModel) {
- context.setProperty(MODEL_PROPERTY, model);
- IDOMModel domModel = (IDOMModel) model;
- return domModel.getDocument();
- }
- } catch (IOException e) {
- AdtPlugin.log(e, "Cannot read XML file");
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
-
- return null;
- }
-
- @Override
- public @NonNull Location getLocation(@NonNull XmlContext context, @NonNull Node node) {
- IStructuredModel model = (IStructuredModel) context.getProperty(MODEL_PROPERTY);
- return new LazyLocation(context.file, model.getStructuredDocument(),
- (IndexedRegion) node);
- }
-
- @Override
- public @NonNull Location getLocation(@NonNull XmlContext context, @NonNull Node node,
- int start, int end) {
- IndexedRegion region = (IndexedRegion) node;
- int nodeStart = region.getStartOffset();
-
- IStructuredModel model = (IStructuredModel) context.getProperty(MODEL_PROPERTY);
- // Get line number
- LazyLocation location = new LazyLocation(context.file,
- model.getStructuredDocument(), region);
- int line = location.getStart().getLine();
-
- Position startPos = new DefaultPosition(line, -1, nodeStart + start);
- Position endPos = new DefaultPosition(line, -1, nodeStart + end);
- return Location.create(context.file, startPos, endPos);
- }
-
- @Override
- public int getNodeStartOffset(@NonNull XmlContext context, @NonNull Node node) {
- IndexedRegion region = (IndexedRegion) node;
- return region.getStartOffset();
- }
-
- @Override
- public int getNodeEndOffset(@NonNull XmlContext context, @NonNull Node node) {
- IndexedRegion region = (IndexedRegion) node;
- return region.getEndOffset();
- }
-
- @Override
- public @NonNull Handle createLocationHandle(final @NonNull XmlContext context,
- final @NonNull Node node) {
- IStructuredModel model = (IStructuredModel) context.getProperty(MODEL_PROPERTY);
- return new LazyLocation(context.file, model.getStructuredDocument(),
- (IndexedRegion) node);
- }
-
- @Override
- public void dispose(@NonNull XmlContext context, @NonNull Document document) {
- IStructuredModel model = (IStructuredModel) context.getProperty(MODEL_PROPERTY);
- assert model != null : context.file;
- if (model != null) {
- model.releaseFromRead();
- }
- }
-
- @Override
- @NonNull
- public Location getNameLocation(@NonNull XmlContext context, @NonNull Node node) {
- return getLocation(context, node);
- }
-
- @Override
- @NonNull
- public Location getValueLocation(@NonNull XmlContext context, @NonNull Attr node) {
- return getLocation(context, node);
- }
-
- };
- }
-
- @Override
- public JavaParser getJavaParser(@Nullable Project project) {
- if (mJavaParser == null) {
- mJavaParser = new EclipseJavaParser();
- }
-
- return mJavaParser;
- }
-
- // Cache for {@link getProject}
- private IProject mLastEclipseProject;
- private Project mLastLintProject;
-
- private IProject getProject(Project project) {
- if (project == mLastLintProject) {
- return mLastEclipseProject;
- }
-
- mLastLintProject = project;
- mLastEclipseProject = null;
-
- if (mResources != null) {
- if (mResources.size() == 1) {
- IProject p = mResources.get(0).getProject();
- mLastEclipseProject = p;
- return p;
- }
-
- IProject last = null;
- for (IResource resource : mResources) {
- IProject p = resource.getProject();
- if (p != last) {
- if (project.getDir().equals(AdtUtils.getAbsolutePath(p).toFile())) {
- mLastEclipseProject = p;
- return p;
- }
- last = p;
- }
- }
- }
-
- return null;
- }
-
- @Override
- @NonNull
- public String getProjectName(@NonNull Project project) {
- // Initialize the lint project's name to the name of the Eclipse project,
- // which might differ from the directory name
- IProject eclipseProject = getProject(project);
- if (eclipseProject != null) {
- return eclipseProject.getName();
- }
-
- return super.getProjectName(project);
- }
-
- @NonNull
- @Override
- public Configuration getConfiguration(@NonNull Project project, @Nullable LintDriver driver) {
- return getConfigurationFor(project);
- }
-
- /**
- * Same as {@link #getConfiguration(Project)}, but {@code project} can be
- * null in which case the global configuration is returned.
- *
- * @param project the project to look up
- * @return a corresponding configuration
- */
- @NonNull
- public Configuration getConfigurationFor(@Nullable Project project) {
- if (project != null) {
- IProject eclipseProject = getProject(project);
- if (eclipseProject != null) {
- return ProjectLintConfiguration.get(this, eclipseProject, mFatalOnly);
- }
- }
-
- return GlobalLintConfiguration.get();
- }
- @Override
- public void report(@NonNull Context context, @NonNull Issue issue, @NonNull Severity s,
- @Nullable Location location,
- @NonNull String message, @NonNull TextFormat format) {
- message = format.toText(message);
- int severity = getMarkerSeverity(s);
- IMarker marker = null;
- if (location != null) {
- Position startPosition = location.getStart();
- if (startPosition == null) {
- if (location.getFile() != null) {
- IResource resource = AdtUtils.fileToResource(location.getFile());
- if (resource != null && resource.isAccessible()) {
- marker = BaseProjectHelper.markResource(resource, MARKER_LINT,
- message, 0, severity);
- }
- }
- } else {
- Position endPosition = location.getEnd();
- int line = startPosition.getLine() + 1; // Marker API is 1-based
- IFile file = AdtUtils.fileToIFile(location.getFile());
- if (file != null && file.isAccessible()) {
- Pair<Integer, Integer> r = getRange(file, mDocument,
- startPosition, endPosition);
- int startOffset = r.getFirst();
- int endOffset = r.getSecond();
- marker = BaseProjectHelper.markResource(file, MARKER_LINT,
- message, line, startOffset, endOffset, severity);
- }
- }
- }
-
- if (marker == null) {
- marker = BaseProjectHelper.markResource(mResources.get(0), MARKER_LINT,
- message, 0, severity);
- }
-
- if (marker != null) {
- // Store marker id such that we can recognize it from the suppress quickfix
- try {
- marker.setAttribute(MARKER_CHECKID_PROPERTY, issue.getId());
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- }
-
- if (s == Severity.FATAL) {
- mWasFatal = true;
- }
-
- if (mCollectNodes && location != null && marker != null) {
- if (location instanceof LazyLocation) {
- LazyLocation l = (LazyLocation) location;
- IndexedRegion region = l.mRegion;
- if (region instanceof Node) {
- Node node = (Node) region;
- if (node instanceof Attr) {
- node = ((Attr) node).getOwnerElement();
- }
- if (mNodeMap == null) {
- mNodeMap = new WeakHashMap<Node, IMarker>();
- }
- IMarker prev = mNodeMap.get(node);
- if (prev != null) {
- // Only replace the node if this node has higher priority
- int prevSeverity = prev.getAttribute(IMarker.SEVERITY, 0);
- if (prevSeverity < severity) {
- mNodeMap.put(node, marker);
- }
- } else {
- mNodeMap.put(node, marker);
- }
- }
- }
- }
- }
-
- @Override
- @Nullable
- public File findResource(@NonNull String relativePath) {
- // Look within the $ANDROID_SDK
- String sdkFolder = AdtPrefs.getPrefs().getOsSdkFolder();
- if (sdkFolder != null) {
- File file = new File(sdkFolder, relativePath);
- if (file.exists()) {
- return file;
- }
- }
-
- return null;
- }
-
- /**
- * Clears any lint markers from the given resource (project, folder or file)
- *
- * @param resource the resource to remove markers from
- */
- public static void clearMarkers(@NonNull IResource resource) {
- clearMarkers(Collections.singletonList(resource));
- }
-
- /** Clears any lint markers from the given list of resource (project, folder or file) */
- static void clearMarkers(List<? extends IResource> resources) {
- for (IResource resource : resources) {
- try {
- if (resource.isAccessible()) {
- resource.deleteMarkers(MARKER_LINT, false, IResource.DEPTH_INFINITE);
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- }
-
- IEditorPart activeEditor = AdtUtils.getActiveEditor();
- LayoutEditorDelegate delegate = LayoutEditorDelegate.fromEditor(activeEditor);
- if (delegate != null) {
- delegate.getGraphicalEditor().getLayoutActionBar().updateErrorIndicator();
- }
- }
-
- /**
- * Removes all markers of the given id from the given resource.
- *
- * @param resource the resource to remove markers from (file or project, or
- * null for all open projects)
- * @param id the id for the issue whose markers should be deleted
- */
- public static void removeMarkers(IResource resource, String id) {
- if (resource == null) {
- IJavaProject[] androidProjects = BaseProjectHelper.getAndroidProjects(null);
- for (IJavaProject project : androidProjects) {
- IProject p = project.getProject();
- if (p != null) {
- // Recurse, but with a different parameter so it will not continue recursing
- removeMarkers(p, id);
- }
- }
- return;
- }
- IMarker[] markers = getMarkers(resource);
- for (IMarker marker : markers) {
- if (id.equals(getId(marker))) {
- try {
- marker.delete();
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- }
- }
- }
-
- /**
- * Returns the lint marker for the given resource (which may be a project, folder or file)
- *
- * @param resource the resource to be checked, typically a source file
- * @return an array of markers, possibly empty but never null
- */
- public static IMarker[] getMarkers(IResource resource) {
- try {
- if (resource.isAccessible()) {
- return resource.findMarkers(MARKER_LINT, false, IResource.DEPTH_INFINITE);
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
-
- return new IMarker[0];
- }
-
- private static int getMarkerSeverity(Severity severity) {
- switch (severity) {
- case INFORMATIONAL:
- return IMarker.SEVERITY_INFO;
- case WARNING:
- return IMarker.SEVERITY_WARNING;
- case FATAL:
- case ERROR:
- default:
- return IMarker.SEVERITY_ERROR;
- }
- }
-
- private static Pair<Integer, Integer> getRange(IFile file, IDocument doc,
- Position startPosition, Position endPosition) {
- int startOffset = startPosition.getOffset();
- int endOffset = endPosition != null ? endPosition.getOffset() : -1;
- if (endOffset != -1) {
- // Attribute ranges often include trailing whitespace; trim this up
- if (doc == null) {
- IDocumentProvider provider = new TextFileDocumentProvider();
- try {
- provider.connect(file);
- doc = provider.getDocument(file);
- if (doc != null) {
- return adjustOffsets(doc, startOffset, endOffset);
- }
- } catch (Exception e) {
- AdtPlugin.log(e, "Can't find range information for %1$s", file.getName());
- } finally {
- provider.disconnect(file);
- }
- } else {
- return adjustOffsets(doc, startOffset, endOffset);
- }
- }
-
- return Pair.of(startOffset, startOffset);
- }
-
- /**
- * Trim off any trailing space on the given offset range in the given
- * document, and don't span multiple lines on ranges since it makes (for
- * example) the XML editor just glow with yellow underlines for all the
- * attributes etc. Highlighting just the element beginning gets the point
- * across. It also makes it more obvious where there are warnings on both
- * the overall element and on individual attributes since without this the
- * warnings on attributes would just overlap with the whole-element
- * highlighting.
- */
- private static Pair<Integer, Integer> adjustOffsets(IDocument doc, int startOffset,
- int endOffset) {
- int originalStart = startOffset;
- int originalEnd = endOffset;
-
- if (doc != null) {
- while (endOffset > startOffset && endOffset < doc.getLength()) {
- try {
- if (!Character.isWhitespace(doc.getChar(endOffset - 1))) {
- break;
- } else {
- endOffset--;
- }
- } catch (BadLocationException e) {
- // Pass - we've already validated offset range above
- break;
- }
- }
-
- // Also don't span lines
- int lineEnd = startOffset;
- while (lineEnd < endOffset) {
- try {
- char c = doc.getChar(lineEnd);
- if (c == '\n' || c == '\r') {
- endOffset = lineEnd;
- if (endOffset > 0 && doc.getChar(endOffset - 1) == '\r') {
- endOffset--;
- }
- break;
- }
- } catch (BadLocationException e) {
- // Pass - we've already validated offset range above
- break;
- }
- lineEnd++;
- }
- }
-
- if (startOffset >= endOffset) {
- // Selecting nothing (for example, for the mangled CRLF delimiter issue selecting
- // just the newline)
- // In that case, use the real range
- return Pair.of(originalStart, originalEnd);
- }
-
- return Pair.of(startOffset, endOffset);
- }
-
- /**
- * Returns true if a fatal error was encountered
- *
- * @return true if a fatal error was encountered
- */
- public boolean hasFatalErrors() {
- return mWasFatal;
- }
-
- /**
- * Describe the issue for the given marker
- *
- * @param marker the marker to look up
- * @return a full description of the corresponding issue, never null
- */
- public static String describe(IMarker marker) {
- IssueRegistry registry = getRegistry();
- String markerId = getId(marker);
- Issue issue = registry.getIssue(markerId);
- if (issue == null) {
- return "";
- }
-
- String summary = issue.getBriefDescription(TextFormat.TEXT);
- String explanation = issue.getExplanation(TextFormat.TEXT);
-
- StringBuilder sb = new StringBuilder(summary.length() + explanation.length() + 20);
- try {
- sb.append((String) marker.getAttribute(IMarker.MESSAGE));
- sb.append('\n').append('\n');
- } catch (CoreException e) {
- }
- sb.append("Issue: ");
- sb.append(summary);
- sb.append('\n');
- sb.append("Id: ");
- sb.append(issue.getId());
- sb.append('\n').append('\n');
- sb.append(explanation);
-
- if (issue.getMoreInfo() != null) {
- sb.append('\n').append('\n');
- sb.append(issue.getMoreInfo());
- }
-
- return sb.toString();
- }
-
- /**
- * Returns the id for the given marker
- *
- * @param marker the marker to look up
- * @return the corresponding issue id, or null
- */
- public static String getId(IMarker marker) {
- try {
- return (String) marker.getAttribute(MARKER_CHECKID_PROPERTY);
- } catch (CoreException e) {
- return null;
- }
- }
-
- /**
- * Shows the given marker in the editor
- *
- * @param marker the marker to be shown
- */
- public static void showMarker(IMarker marker) {
- IRegion region = null;
- try {
- int start = marker.getAttribute(IMarker.CHAR_START, -1);
- int end = marker.getAttribute(IMarker.CHAR_END, -1);
- if (start >= 0 && end >= 0) {
- region = new org.eclipse.jface.text.Region(start, end - start);
- }
-
- IResource resource = marker.getResource();
- if (resource instanceof IFile) {
- IEditorPart editor =
- AdtPlugin.openFile((IFile) resource, region, true /* showEditorTab */);
- if (editor != null) {
- IDE.gotoMarker(editor, marker);
- }
- }
- } catch (PartInitException ex) {
- AdtPlugin.log(ex, null);
- }
- }
-
- /**
- * Show a dialog with errors for the given file
- *
- * @param shell the parent shell to attach the dialog to
- * @param file the file to show the errors for
- * @param editor the editor for the file, if known
- */
- public static void showErrors(
- @NonNull Shell shell,
- @NonNull IFile file,
- @Nullable IEditorPart editor) {
- LintListDialog dialog = new LintListDialog(shell, file, editor);
- dialog.open();
- }
-
- @Override
- public @NonNull String readFile(@NonNull File f) {
- // Map File to IFile
- IFile file = AdtUtils.fileToIFile(f);
- if (file == null || !file.exists()) {
- String path = f.getPath();
- AdtPlugin.log(IStatus.ERROR, "Can't find file %1$s in workspace", path);
- return readPlainFile(f);
- }
-
- if (SdkUtils.endsWithIgnoreCase(file.getName(), DOT_XML)) {
- IStructuredModel model = null;
- try {
- IModelManager modelManager = StructuredModelManager.getModelManager();
- model = modelManager.getModelForRead(file);
- return model.getStructuredDocument().get();
- } catch (IOException e) {
- AdtPlugin.log(e, "Cannot read XML file");
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- } finally {
- if (model != null) {
- // TODO: This may be too early...
- model.releaseFromRead();
- }
- }
- }
-
- return readPlainFile(f);
- }
-
- private String readPlainFile(File file) {
- try {
- return LintUtils.getEncodedString(this, file);
- } catch (IOException e) {
- return ""; //$NON-NLS-1$
- }
- }
-
- private Map<Project, ClassPathInfo> mProjectInfo;
-
- @Override
- @NonNull
- protected ClassPathInfo getClassPath(@NonNull Project project) {
- ClassPathInfo info;
- if (mProjectInfo == null) {
- mProjectInfo = Maps.newHashMap();
- info = null;
- } else {
- info = mProjectInfo.get(project);
- }
-
- if (info == null) {
- List<File> sources = null;
- List<File> classes = null;
- List<File> libraries = null;
-
- IProject p = getProject(project);
- if (p != null) {
- try {
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(p);
-
- // Output path
- File file = workspacePathToFile(javaProject.getOutputLocation());
- classes = Collections.singletonList(file);
-
- // Source path
- IClasspathEntry[] entries = javaProject.getRawClasspath();
- sources = new ArrayList<File>(entries.length);
- libraries = new ArrayList<File>(entries.length);
- for (int i = 0; i < entries.length; i++) {
- IClasspathEntry entry = entries[i];
- int kind = entry.getEntryKind();
-
- if (kind == IClasspathEntry.CPE_VARIABLE) {
- entry = JavaCore.getResolvedClasspathEntry(entry);
- if (entry == null) {
- // It's possible that the variable is no longer valid; ignore
- continue;
- }
- kind = entry.getEntryKind();
- }
-
- if (kind == IClasspathEntry.CPE_SOURCE) {
- sources.add(workspacePathToFile(entry.getPath()));
- } else if (kind == IClasspathEntry.CPE_LIBRARY) {
- libraries.add(entry.getPath().toFile());
- }
- // Note that we ignore IClasspathEntry.CPE_CONTAINER:
- // Normal Android Eclipse projects supply both
- // AdtConstants.CONTAINER_FRAMEWORK
- // and
- // AdtConstants.CONTAINER_LIBRARIES
- // here. We ignore the framework classes for obvious reasons,
- // but we also ignore the library container because lint will
- // process the libraries differently. When Eclipse builds a
- // project, it gets the .jar output of the library projects
- // from this container, which means it doesn't have to process
- // the library sources. Lint on the other hand wants to process
- // the source code, so instead it actually looks at the
- // project.properties file to find the libraries, and then it
- // iterates over all the library projects in turn and analyzes
- // those separately (but passing the main project for context,
- // such that the including project's manifest declarations
- // are used for data like minSdkVersion level).
- //
- // Note that this container will also contain *other*
- // libraries (Java libraries, not library projects) that we
- // *should* include. However, we can't distinguish these
- // class path entries from the library project jars,
- // so instead of looking at these, we simply listFiles() in
- // the libs/ folder after processing the classpath info
- }
-
- // Add in libraries
- File libs = new File(project.getDir(), FD_NATIVE_LIBS);
- if (libs.isDirectory()) {
- File[] jars = libs.listFiles();
- if (jars != null) {
- for (File jar : jars) {
- if (SdkUtils.endsWith(jar.getPath(), DOT_JAR)) {
- libraries.add(jar);
- }
- }
- }
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- }
-
- if (sources == null) {
- sources = super.getClassPath(project).getSourceFolders();
- }
- if (classes == null) {
- classes = super.getClassPath(project).getClassFolders();
- }
- if (libraries == null) {
- libraries = super.getClassPath(project).getLibraries();
- }
-
-
- // No test folders in Eclipse:
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=224708
- List<File> tests = Collections.emptyList();
-
- info = new ClassPathInfo(sources, classes, libraries, tests);
- mProjectInfo.put(project, info);
- }
-
- return info;
- }
-
- /**
- * Returns the registry of issues to check from within Eclipse.
- *
- * @return the issue registry to use to access detectors and issues
- */
- public static IssueRegistry getRegistry() {
- return new EclipseLintIssueRegistry();
- }
-
- @Override
- public @NonNull Class<? extends Detector> replaceDetector(
- @NonNull Class<? extends Detector> detectorClass) {
- return detectorClass;
- }
-
- @Override
- @NonNull
- public IAndroidTarget[] getTargets() {
- Sdk sdk = Sdk.getCurrent();
- if (sdk != null) {
- return sdk.getTargets();
- } else {
- return new IAndroidTarget[0];
- }
- }
-
- private boolean mSearchForSuperClasses;
-
- /**
- * Sets whether this client should search for super types on its own. This
- * is typically not needed when doing a full lint run (because lint will
- * look at all classes and libraries), but is useful during incremental
- * analysis when lint is only looking at a subset of classes. In that case,
- * we want to use Eclipse's data structures for super classes.
- *
- * @param search whether to use a custom Eclipse search for super class
- * names
- */
- public void setSearchForSuperClasses(boolean search) {
- mSearchForSuperClasses = search;
- }
-
- /**
- * Whether this lint client is searching for super types. See
- * {@link #setSearchForSuperClasses(boolean)} for details.
- *
- * @return whether the client will search for super types
- */
- public boolean getSearchForSuperClasses() {
- return mSearchForSuperClasses;
- }
-
- @Override
- @Nullable
- public String getSuperClass(@NonNull Project project, @NonNull String name) {
- if (!mSearchForSuperClasses) {
- // Super type search using the Eclipse index is potentially slow, so
- // only do this when necessary
- return null;
- }
-
- IProject eclipseProject = getProject(project);
- if (eclipseProject == null) {
- return null;
- }
-
- try {
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(eclipseProject);
- if (javaProject == null) {
- return null;
- }
-
- String typeFqcn = ClassContext.getFqcn(name);
- IType type = javaProject.findType(typeFqcn);
- if (type != null) {
- ITypeHierarchy hierarchy = type.newSupertypeHierarchy(new NullProgressMonitor());
- IType superType = hierarchy.getSuperclass(type);
- if (superType != null) {
- String key = superType.getKey();
- if (!key.isEmpty()
- && key.charAt(0) == 'L'
- && key.charAt(key.length() - 1) == ';') {
- return key.substring(1, key.length() - 1);
- } else {
- String fqcn = superType.getFullyQualifiedName();
- return ClassContext.getInternalName(fqcn);
- }
- }
- }
- } catch (JavaModelException e) {
- log(Severity.INFORMATIONAL, e, null);
- } catch (CoreException e) {
- log(Severity.INFORMATIONAL, e, null);
- }
-
- return null;
- }
-
- @Override
- @Nullable
- public Boolean isSubclassOf(
- @NonNull Project project,
- @NonNull String name, @NonNull
- String superClassName) {
- if (!mSearchForSuperClasses) {
- // Super type search using the Eclipse index is potentially slow, so
- // only do this when necessary
- return null;
- }
-
- IProject eclipseProject = getProject(project);
- if (eclipseProject == null) {
- return null;
- }
-
- try {
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(eclipseProject);
- if (javaProject == null) {
- return null;
- }
-
- String typeFqcn = ClassContext.getFqcn(name);
- IType type = javaProject.findType(typeFqcn);
- if (type != null) {
- ITypeHierarchy hierarchy = type.newSupertypeHierarchy(new NullProgressMonitor());
- IType[] allSupertypes = hierarchy.getAllSuperclasses(type);
- if (allSupertypes != null) {
- String target = 'L' + superClassName + ';';
- for (IType superType : allSupertypes) {
- if (target.equals(superType.getKey())) {
- return Boolean.TRUE;
- }
- }
- return Boolean.FALSE;
- }
- }
- } catch (JavaModelException e) {
- log(Severity.INFORMATIONAL, e, null);
- } catch (CoreException e) {
- log(Severity.INFORMATIONAL, e, null);
- }
-
- return null;
- }
-
- private static class LazyLocation extends Location implements Location.Handle {
- private final IStructuredDocument mDocument;
- private final IndexedRegion mRegion;
- private Position mStart;
- private Position mEnd;
-
- public LazyLocation(File file, IStructuredDocument document, IndexedRegion region) {
- super(file, null /*start*/, null /*end*/);
- mDocument = document;
- mRegion = region;
- }
-
- @Override
- public Position getStart() {
- if (mStart == null) {
- int line = -1;
- int column = -1;
- int offset = mRegion.getStartOffset();
-
- if (mRegion instanceof org.w3c.dom.Text && mDocument != null) {
- // For text nodes, skip whitespace prefix, if any
- for (int i = offset;
- i < mRegion.getEndOffset() && i < mDocument.getLength(); i++) {
- try {
- char c = mDocument.getChar(i);
- if (!Character.isWhitespace(c)) {
- offset = i;
- break;
- }
- } catch (BadLocationException e) {
- break;
- }
- }
- }
-
- if (mDocument != null && offset < mDocument.getLength()) {
- line = mDocument.getLineOfOffset(offset);
- column = -1;
- try {
- int lineOffset = mDocument.getLineOffset(line);
- column = offset - lineOffset;
- } catch (BadLocationException e) {
- AdtPlugin.log(e, null);
- }
- }
-
- mStart = new DefaultPosition(line, column, offset);
- }
-
- return mStart;
- }
-
- @Override
- public Position getEnd() {
- if (mEnd == null) {
- mEnd = new DefaultPosition(-1, -1, mRegion.getEndOffset());
- }
-
- return mEnd;
- }
-
- @Override
- public @NonNull Location resolve() {
- return this;
- }
- }
-
- private static class EclipseJavaParser extends JavaParser {
- private static final boolean USE_ECLIPSE_PARSER = true;
- private final Parser mParser;
-
- EclipseJavaParser() {
- if (USE_ECLIPSE_PARSER) {
- CompilerOptions options = new CompilerOptions();
- // Always using JDK 7 rather than basing it on project metadata since we
- // don't do compilation error validation in lint (we leave that to the IDE's
- // error parser or the command line build's compilation step); we want an
- // AST that is as tolerant as possible.
- options.complianceLevel = ClassFileConstants.JDK1_7;
- options.sourceLevel = ClassFileConstants.JDK1_7;
- options.targetJDK = ClassFileConstants.JDK1_7;
- options.parseLiteralExpressionsAsConstants = true;
- ProblemReporter problemReporter = new ProblemReporter(
- DefaultErrorHandlingPolicies.exitOnFirstError(),
- options,
- new DefaultProblemFactory());
- mParser = new Parser(problemReporter, options.parseLiteralExpressionsAsConstants);
- mParser.javadocParser.checkDocComment = false;
- } else {
- mParser = null;
- }
- }
-
- @Override
- public void prepareJavaParse(@NonNull List<JavaContext> contexts) {
- // TODO: Use batch compiler from lint-cli.jar
- }
-
- @Override
- public lombok.ast.Node parseJava(@NonNull JavaContext context) {
- if (USE_ECLIPSE_PARSER) {
- // Use Eclipse's compiler
- EcjTreeConverter converter = new EcjTreeConverter();
- String code = context.getContents();
-
- CompilationUnit sourceUnit = new CompilationUnit(code.toCharArray(),
- context.file.getName(), "UTF-8"); //$NON-NLS-1$
- CompilationResult compilationResult = new CompilationResult(sourceUnit, 0, 0, 0);
- CompilationUnitDeclaration unit = null;
- try {
- unit = mParser.parse(sourceUnit, compilationResult);
- } catch (AbortCompilation e) {
- // No need to report Java parsing errors while running in Eclipse.
- // Eclipse itself will already provide problem markers for these files,
- // so all this achieves is creating "multiple annotations on this line"
- // tooltips instead.
- return null;
- }
- if (unit == null) {
- return null;
- }
-
- try {
- converter.visit(code, unit);
- List<? extends lombok.ast.Node> nodes = converter.getAll();
-
- // There could be more than one node when there are errors; pick out the
- // compilation unit node
- for (lombok.ast.Node node : nodes) {
- if (node instanceof lombok.ast.CompilationUnit) {
- return node;
- }
- }
-
- return null;
- } catch (Throwable t) {
- AdtPlugin.log(t, "Failed converting ECJ parse tree to Lombok for file %1$s",
- context.file.getPath());
- return null;
- }
- } else {
- // Use Lombok for now
- Source source = new Source(context.getContents(), context.file.getName());
- List<lombok.ast.Node> nodes = source.getNodes();
-
- // Don't analyze files containing errors
- List<ParseProblem> problems = source.getProblems();
- if (problems != null && problems.size() > 0) {
- /* Silently ignore the errors. There are still some bugs in Lombok/Parboiled
- * (triggered if you run lint on the AOSP framework directory for example),
- * and having these show up as fatal errors when it's really a tool bug
- * is bad. To make matters worse, the error messages aren't clear:
- * http://code.google.com/p/projectlombok/issues/detail?id=313
- for (ParseProblem problem : problems) {
- lombok.ast.Position position = problem.getPosition();
- Location location = Location.create(context.file,
- context.getContents(), position.getStart(), position.getEnd());
- String message = problem.getMessage();
- context.report(
- IssueRegistry.PARSER_ERROR, location,
- message,
- null);
-
- }
- */
- return null;
- }
-
- // There could be more than one node when there are errors; pick out the
- // compilation unit node
- for (lombok.ast.Node node : nodes) {
- if (node instanceof lombok.ast.CompilationUnit) {
- return node;
- }
- }
- return null;
- }
- }
-
- @Override
- public @NonNull Location getLocation(@NonNull JavaContext context,
- @NonNull lombok.ast.Node node) {
- lombok.ast.Position position = node.getPosition();
- return Location.create(context.file, context.getContents(),
- position.getStart(), position.getEnd());
- }
-
- @Override
- public @NonNull Handle createLocationHandle(@NonNull JavaContext context,
- @NonNull lombok.ast.Node node) {
- return new LocationHandle(context.file, node);
- }
-
- @Override
- public void dispose(@NonNull JavaContext context,
- @NonNull lombok.ast.Node compilationUnit) {
- }
-
- @Override
- @Nullable
- public ResolvedNode resolve(@NonNull JavaContext context,
- @NonNull lombok.ast.Node node) {
- return null;
- }
-
- @Override
- @Nullable
- public TypeDescriptor getType(@NonNull JavaContext context,
- @NonNull lombok.ast.Node node) {
- return null;
- }
-
- /* Handle for creating positions cheaply and returning full fledged locations later */
- private class LocationHandle implements Handle {
- private File mFile;
- private lombok.ast.Node mNode;
- private Object mClientData;
-
- public LocationHandle(File file, lombok.ast.Node node) {
- mFile = file;
- mNode = node;
- }
-
- @Override
- public @NonNull Location resolve() {
- lombok.ast.Position pos = mNode.getPosition();
- return Location.create(mFile, null /*contents*/, pos.getStart(), pos.getEnd());
- }
-
- @Override
- public void setClientData(@Nullable Object clientData) {
- mClientData = clientData;
- }
-
- @Override
- @Nullable
- public Object getClientData() {
- return mClientData;
- }
- }
- }
-}
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/EclipseLintIssueRegistry.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/EclipseLintIssueRegistry.java
deleted file mode 100644
index 3abbdeb84..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/EclipseLintIssueRegistry.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import com.android.annotations.NonNull;
-import com.android.tools.lint.checks.*;
-import com.android.tools.lint.detector.api.Issue;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class EclipseLintIssueRegistry extends BuiltinIssueRegistry {
- private static List<Issue> sFilteredIssues;
-
- public EclipseLintIssueRegistry() {
- }
-
- @NonNull
- @Override
- public List<Issue> getIssues() {
- if (sFilteredIssues == null) {
- // Remove issues that do not work properly in Eclipse
- List<Issue> sIssues = super.getIssues();
- List<Issue> result = new ArrayList<Issue>(sIssues.size());
- for (Issue issue : sIssues) {
- if (issue == MissingClassDetector.INSTANTIATABLE) {
- // Apparently violated by
- // android.support.v7.internal.widget.ActionBarView.HomeView
- // See issue 72760
- continue;
- } else if (issue == DuplicateIdDetector.WITHIN_LAYOUT) {
- // Apparently violated by
- // sdk/extras/android/support/v7/appcompat/abc_activity_chooser_view_include.xml
- // See issue 72760
- continue;
- } else if (issue == AppCompatResourceDetector.ISSUE
- || issue == AppCompatCallDetector.ISSUE) {
- // Apparently has some false positives in Eclipse; see issue
- // 72824
- continue;
- } else if (issue.getImplementation().getDetectorClass() == RtlDetector.class) {
- // False positives in Eclipse; see issue 78780
- continue;
- }
- result.add(issue);
- }
- sFilteredIssues = result;
- }
-
- return sFilteredIssues;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/EclipseLintRunner.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/EclipseLintRunner.java
deleted file mode 100644
index 43cd48d1b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/EclipseLintRunner.java
+++ /dev/null
@@ -1,238 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.tools.lint.client.api.IssueRegistry;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.widgets.Shell;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.IdentityHashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Eclipse implementation for running lint on workspace files and projects.
- */
-public class EclipseLintRunner {
- static final String MARKER_CHECKID_PROPERTY = "checkid"; //$NON-NLS-1$
-
- /**
- * Runs lint and updates the markers, and waits for the result. Returns
- * true if fatal errors were found.
- *
- * @param resources the resources (project, folder or file) to be analyzed
- * @param source if checking a single source file, the source file
- * @param doc the associated document, if known, or null
- * @param fatalOnly if true, only report fatal issues (severity=error)
- * @return true if any fatal errors were encountered.
- */
- private static boolean runLint(
- @NonNull List<? extends IResource> resources,
- @Nullable IResource source,
- @Nullable IDocument doc,
- boolean fatalOnly) {
- resources = addLibraries(resources);
- LintJob job = (LintJob) startLint(resources, source, doc, fatalOnly,
- false /*show*/);
- try {
- job.join();
- boolean fatal = job.isFatal();
-
- if (fatal) {
- LintViewPart.show(resources);
- }
-
- return fatal;
- } catch (InterruptedException e) {
- AdtPlugin.log(e, null);
- }
-
- return false;
- }
-
- /**
- * Runs lint and updates the markers. Does not wait for the job to finish -
- * just returns immediately.
- *
- * @param resources the resources (project, folder or file) to be analyzed
- * @param source if checking a single source file, the source file. When
- * single checking an XML file, this is typically the same as the
- * file passed in the list in the first parameter, but when
- * checking the .class files of a Java file for example, the
- * .class file and all the inner classes of the Java file are
- * passed in the first parameter, and the corresponding .java
- * source file is passed here.
- * @param doc the associated document, if known, or null
- * @param fatalOnly if true, only report fatal issues (severity=error)
- * @param show if true, show the results in a {@link LintViewPart}
- * @return the job running lint in the background.
- */
- public static Job startLint(
- @NonNull List<? extends IResource> resources,
- @Nullable IResource source,
- @Nullable IDocument doc,
- boolean fatalOnly,
- boolean show) {
- IssueRegistry registry = EclipseLintClient.getRegistry();
- EclipseLintClient client = new EclipseLintClient(registry, resources, doc, fatalOnly);
- return startLint(client, resources, source, show);
- }
-
- /**
- * Runs lint and updates the markers. Does not wait for the job to finish -
- * just returns immediately.
- *
- * @param client the lint client receiving issue reports etc
- * @param resources the resources (project, folder or file) to be analyzed
- * @param source if checking a single source file, the source file. When
- * single checking an XML file, this is typically the same as the
- * file passed in the list in the first parameter, but when
- * checking the .class files of a Java file for example, the
- * .class file and all the inner classes of the Java file are
- * passed in the first parameter, and the corresponding .java
- * source file is passed here.
- * @param show if true, show the results in a {@link LintViewPart}
- * @return the job running lint in the background.
- */
- public static Job startLint(
- @NonNull EclipseLintClient client,
- @NonNull List<? extends IResource> resources,
- @Nullable IResource source,
- boolean show) {
- if (resources != null && !resources.isEmpty()) {
- if (!AdtPrefs.getPrefs().getSkipLibrariesFromLint()) {
- resources = addLibraries(resources);
- }
-
- cancelCurrentJobs(false);
-
- LintJob job = new LintJob(client, resources, source);
- job.schedule();
-
- if (show) {
- // Show lint view where the results are listed
- LintViewPart.show(resources);
- }
- return job;
- }
-
- return null;
- }
-
- /**
- * Run Lint for an Export APK action. If it succeeds (no fatal errors)
- * returns true, and if it fails it will display an error message and return
- * false.
- *
- * @param shell the parent shell to show error messages in
- * @param project the project to run lint on
- * @return true if the lint run succeeded with no fatal errors
- */
- public static boolean runLintOnExport(Shell shell, IProject project) {
- if (AdtPrefs.getPrefs().isLintOnExport()) {
- boolean fatal = EclipseLintRunner.runLint(Collections.singletonList(project),
- null, null, true /*fatalOnly*/);
- if (fatal) {
- MessageDialog.openWarning(shell,
- "Export Aborted",
- "Export aborted because fatal lint errors were found. These " +
- "are listed in the Lint View. Either fix these before " +
- "running Export again, or turn off \"Run full error check " +
- "when exporting app\" in the Android > Lint Error Checking " +
- "preference page.");
- return false;
- }
- }
-
- return true;
- }
-
- /** Cancels the current lint jobs, if any, and optionally waits for them to finish */
- static void cancelCurrentJobs(boolean wait) {
- // Cancel any current running jobs first
- Job[] currentJobs = LintJob.getCurrentJobs();
- for (Job job : currentJobs) {
- job.cancel();
- }
-
- if (wait) {
- for (Job job : currentJobs) {
- try {
- job.join();
- } catch (InterruptedException e) {
- AdtPlugin.log(e, null);
- }
- }
- }
- }
-
- /** If the resource list contains projects, add in any library projects as well */
- private static List<? extends IResource> addLibraries(List<? extends IResource> resources) {
- if (resources != null && !resources.isEmpty()) {
- boolean haveProjects = false;
- for (IResource resource : resources) {
- if (resource instanceof IProject) {
- haveProjects = true;
- break;
- }
- }
-
- if (haveProjects) {
- List<IResource> result = new ArrayList<IResource>();
- Map<IProject, IProject> allProjects = new IdentityHashMap<IProject, IProject>();
- List<IProject> projects = new ArrayList<IProject>();
- for (IResource resource : resources) {
- if (resource instanceof IProject) {
- IProject project = (IProject) resource;
- allProjects.put(project, project);
- projects.add(project);
- } else {
- result.add(resource);
- }
- }
- for (IProject project : projects) {
- ProjectState state = Sdk.getProjectState(project);
- if (state != null) {
- for (IProject library : state.getFullLibraryProjects()) {
- allProjects.put(library, library);
- }
- }
- }
- for (IProject project : allProjects.keySet()) {
- result.add(project);
- }
-
- return result;
- }
- }
-
- return resources;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/ExtractStringFix.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/ExtractStringFix.java
deleted file mode 100644
index 7eafd4364..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/ExtractStringFix.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.refactorings.extractstring.ExtractStringRefactoring;
-import com.android.ide.eclipse.adt.internal.refactorings.extractstring.ExtractStringWizard;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.TextSelection;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.w3c.dom.Node;
-
-/**
- * Fix for extracting strings.
- * <p>
- * TODO: Look for existing string values, and if it matches one of the
- * existing Strings offer to just replace it with the given string!
- */
-@SuppressWarnings("restriction") // DOM model
-final class ExtractStringFix extends DocumentFix {
- private ExtractStringFix(String id, IMarker marker) {
- super(id, marker);
- }
-
- @Override
- public boolean needsFocus() {
- return true;
- }
-
- @Override
- public boolean isCancelable() {
- return true;
- }
-
- @Override
- protected void apply(IDocument document, IStructuredModel model, Node node, int start,
- int end) {
- IEditorPart editorPart = AdtUtils.getActiveEditor();
- if (editorPart instanceof AndroidXmlEditor) {
- IFile file = (IFile) mMarker.getResource();
- ITextSelection selection = new TextSelection(start, end - start);
-
- ExtractStringRefactoring refactoring =
- new ExtractStringRefactoring(file, editorPart, selection);
- RefactoringWizard wizard = new ExtractStringWizard(refactoring, file.getProject());
- RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation(wizard);
- try {
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- op.run(window.getShell(), wizard.getDefaultPageTitle());
- } catch (InterruptedException e) {
- }
- }
- }
-
- @Override
- public String getDisplayString() {
- return "Extract String";
- }
-
- @Override
- public Image getImage() {
- ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages();
- return sharedImages.getImage(ISharedImages.IMG_OBJ_ADD);
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/GlobalLintConfiguration.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/GlobalLintConfiguration.java
deleted file mode 100644
index 2f0261e7b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/GlobalLintConfiguration.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.tools.lint.client.api.Configuration;
-import com.android.tools.lint.client.api.IssueRegistry;
-import com.android.tools.lint.detector.api.Context;
-import com.android.tools.lint.detector.api.Issue;
-import com.android.tools.lint.detector.api.Location;
-import com.android.tools.lint.detector.api.Severity;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/** Global (non-project-specific) configuration for Lint in Eclipse */
-class GlobalLintConfiguration extends Configuration {
- private static final GlobalLintConfiguration sInstance = new GlobalLintConfiguration();
-
- private Map<Issue, Severity> mSeverities;
- private boolean mBulkEditing;
-
- private GlobalLintConfiguration() {
- }
-
- /**
- * Obtain a reference to the singleton
- *
- * @return the singleton configuration
- */
- @NonNull
- public static GlobalLintConfiguration get() {
- return sInstance;
- }
-
- @Override
- public Severity getSeverity(@NonNull Issue issue) {
- if (mSeverities == null) {
- IssueRegistry registry = EclipseLintClient.getRegistry();
- mSeverities = new HashMap<Issue, Severity>();
- IPreferenceStore store = getStore();
- String assignments = store.getString(AdtPrefs.PREFS_LINT_SEVERITIES);
- if (assignments != null && assignments.length() > 0) {
- for (String assignment : assignments.split(",")) { //$NON-NLS-1$
- String[] s = assignment.split("="); //$NON-NLS-1$
- if (s.length == 2) {
- Issue d = registry.getIssue(s[0]);
- if (d != null) {
- Severity severity = Severity.valueOf(s[1]);
- if (severity != null) {
- mSeverities.put(d, severity);
- }
- }
- }
- }
- }
- }
-
- Severity severity = mSeverities.get(issue);
- if (severity != null) {
- return severity;
- }
-
- if (!issue.isEnabledByDefault()) {
- return Severity.IGNORE;
- }
-
- return issue.getDefaultSeverity();
- }
-
- private IPreferenceStore getStore() {
- IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore();
- return store;
- }
-
- @Override
- public void ignore(@NonNull Context context, @NonNull Issue issue,
- @Nullable Location location, @NonNull String message) {
- throw new UnsupportedOperationException(
- "Can't ignore() in global configurations"); //$NON-NLS-1$
- }
-
- @Override
- public void setSeverity(@NonNull Issue issue, @Nullable Severity severity) {
- if (mSeverities == null) {
- // Force initialization
- getSeverity(issue);
- }
-
- if (severity == null) {
- mSeverities.remove(issue);
- } else {
- mSeverities.put(issue, severity);
- }
-
- if (!mBulkEditing) {
- setSeverities(mSeverities);
- }
- }
-
- /**
- * Sets the custom severities for the given issues, in bulk.
- *
- * @param severities a map from detector to severity to use from now on
- * @return true if something changed from the current settings
- */
- private boolean setSeverities(Map<Issue, Severity> severities) {
- mSeverities = severities;
-
- String value = "";
- if (severities.size() > 0) {
- List<Issue> sortedKeys = new ArrayList<Issue>(severities.keySet());
- Collections.sort(sortedKeys);
-
- StringBuilder sb = new StringBuilder(severities.size() * 20);
- for (Issue issue : sortedKeys) {
- Severity severity = severities.get(issue);
- if (severity != issue.getDefaultSeverity()) {
- if (sb.length() > 0) {
- sb.append(',');
- }
- sb.append(issue.getId());
- sb.append('=');
- sb.append(severity.name());
- }
- }
-
- value = sb.toString();
- }
-
- IPreferenceStore store = getStore();
- String previous = store.getString(AdtPrefs.PREFS_LINT_SEVERITIES);
- boolean changed = !value.equals(previous);
- if (changed) {
- if (value.length() == 0) {
- store.setToDefault(AdtPrefs.PREFS_LINT_SEVERITIES);
- } else {
- store.setValue(AdtPrefs.PREFS_LINT_SEVERITIES, value);
- }
- }
-
- return changed;
- }
-
- @Override
- public void startBulkEditing() {
- mBulkEditing = true;
- }
-
- @Override
- public void finishBulkEditing() {
- mBulkEditing = false;
- setSeverities(mSeverities);
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/InputDensityDialog.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/InputDensityDialog.java
deleted file mode 100644
index d102225b2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/InputDensityDialog.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import com.android.resources.Density;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-
-import java.util.ArrayList;
-import java.util.List;
-
-class InputDensityDialog extends Dialog {
- private Combo mCombo;
- /**
- * Density value being chosen - static to keep most recently chosen value
- * across repeated invocations
- */
- private static int sDpi = Density.DEFAULT_DENSITY;
-
- InputDensityDialog(Shell parentShell) {
- super(parentShell);
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite container = (Composite) super.createDialogArea(parent);
- container.setLayout(new GridLayout(1, false));
-
- Label lblWhatIsThe = new Label(container, SWT.WRAP);
- lblWhatIsThe.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1));
- lblWhatIsThe.setText("What is the screen density the current px value works with?");
-
- mCombo = new Combo(container, SWT.READ_ONLY);
- GridData gdCombo = new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1);
- gdCombo.widthHint = 200;
- mCombo.setLayoutData(gdCombo);
- int initialIndex = 0;
- List<String> s = new ArrayList<String>();
- int index = 0;
- for (Density density : Density.values()) {
- if (density == Density.NODPI) {
- continue;
- }
- if (density.getDpiValue() == sDpi) {
- initialIndex = index;
- }
- s.add(getLabel(density));
- index++;
- }
- String[] items = s.toArray(new String[s.size()]);
- mCombo.setItems(items);
- mCombo.select(initialIndex);
-
- return container;
- }
-
- private static String getLabel(Density density) {
- return String.format("%1$s (%2$d)", density.getShortDisplayValue(), density.getDpiValue());
- }
-
- @Override
- protected void createButtonsForButtonBar(Composite parent) {
- createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
- createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
- }
-
- @Override
- protected Point getInitialSize() {
- return new Point(450, 150);
- }
-
- @Override
- public boolean close() {
- String description = mCombo.getItem(mCombo.getSelectionIndex());
-
- for (Density density : Density.values()) {
- if (description.equals(getLabel(density))) {
- sDpi = density.getDpiValue();
- break;
- }
- }
-
- return super.close();
- }
-
- @Override
- protected void configureShell(Shell shell) {
- super.configureShell(shell);
- shell.setText("Choose Density");
- }
-
- int getDensity() {
- return sDpi;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LinearLayoutWeightFix.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LinearLayoutWeightFix.java
deleted file mode 100644
index af3fc74eb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LinearLayoutWeightFix.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.ATTR_ORIENTATION;
-import static com.android.SdkConstants.VALUE_VERTICAL;
-import static com.android.SdkConstants.VALUE_ZERO_DP;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-@SuppressWarnings("restriction") // DOM model
-final class LinearLayoutWeightFix extends DocumentFix {
- private LinearLayoutWeightFix(String id, IMarker marker) {
- super(id, marker);
- }
-
- @Override
- public boolean needsFocus() {
- return false;
- }
-
- @Override
- public boolean isCancelable() {
- return false;
- }
-
- @Override
- protected void apply(IDocument document, IStructuredModel model, Node node, int start,
- int end) {
- if (node instanceof Element && node.getParentNode() instanceof Element) {
- Element element = (Element) node;
- Element parent = (Element) node.getParentNode();
- String dimension;
- if (VALUE_VERTICAL.equals(parent.getAttributeNS(ANDROID_URI,
- ATTR_ORIENTATION))) {
- dimension = ATTR_LAYOUT_HEIGHT;
- } else {
- dimension = ATTR_LAYOUT_WIDTH;
- }
- element.setAttributeNS(ANDROID_URI, dimension, VALUE_ZERO_DP);
- }
- }
-
- @Override
- public String getDisplayString() {
- return "Replace size attribute with 0dp";
- }
-
- @Override
- public Image getImage() {
- ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages();
- // TODO: Need a better icon here
- return sharedImages.getImage(ISharedImages.IMG_OBJ_ELEMENT);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintColumn.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintColumn.java
deleted file mode 100644
index 297d94b79..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintColumn.java
+++ /dev/null
@@ -1,532 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.SwtUtils;
-import com.android.tools.lint.detector.api.Issue;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.viewers.StyledString;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-
-import java.io.File;
-import java.util.Comparator;
-
-/** A column shown in the {@link LintList} */
-abstract class LintColumn implements Comparator<IMarker> {
- protected final LintList mList;
-
- protected LintColumn(@NonNull LintList list) {
- mList = list;
- }
-
- /** @return true if this column should be shown by default */
- public boolean isVisibleByDefault() {
- return true;
- }
-
- /** @return true if this column's text should be left aligned */
- public boolean isLeftAligned() {
- return true;
- }
-
- /**
- * @return the number of pixels that this column should show by default
- */
- public int getPreferredWidth() {
- return getPreferredCharWidth() * SwtUtils.getAverageCharWidth(mList.getDisplay(),
- mList.getTree().getFont());
- }
-
- /**
- * @return the number of characters that this column should show by default
- */
- public int getPreferredCharWidth() {
- return 15;
- }
-
- /**
- * @return the title of the column
- */
- @NonNull
- public abstract String getColumnHeaderText();
-
- /**
- * @return the image of the column, or null
- */
- public Image getColumnHeaderImage() {
- return null;
- }
-
- /**
- * @param marker the {@link IMarker} to get the value for
- * @return the value of this column for the given marker
- */
- public abstract String getValue(@NonNull IMarker marker);
-
- /**
- * @param marker the {@link IMarker} to get the value for
- * @return the styled value of this column for the given marker
- */
- public StyledString getStyledValue(@NonNull IMarker marker) {
- return null;
- }
-
- /**
- * @param marker the {@link IMarker} to get the image for
- * @return The image for this particular column, or null
- */
- @Nullable
- public Image getImage(@NonNull IMarker marker) {
- return null;
- }
-
- /**
- * @param marker the {@link IMarker} to get the font for
- * @return The font for this particular column, or null
- */
- @Nullable
- public Font getFont(@NonNull IMarker marker) {
- return null;
- }
-
- /**
- * @return true if the sort should be in ascending order. If false, sort in descending order.
- */
- public boolean isAscending() {
- return true;
- }
-
- /**
- * @return true if this column should be visible by default
- */
- public boolean visibleByDefault() {
- return true;
- }
-
- @Override
- public int compare(IMarker o1, IMarker o2) {
- return getValue(o1).compareTo(getValue(o2));
- }
-
- // Used for default LabelProvider
- @Override
- public String toString() {
- return getColumnHeaderText();
- }
-
- static class MessageColumn extends LintColumn {
-
- public MessageColumn(LintList list) {
- super(list);
- }
-
- @Override
- public @NonNull String getColumnHeaderText() {
- return "Description";
- }
-
- @Override
- public int getPreferredCharWidth() {
- return 80;
- }
-
- @Override
- public String getValue(@NonNull IMarker marker) {
- return getStyledValue(marker).toString();
- }
-
- @Override
- public StyledString getStyledValue(@NonNull IMarker marker) {
- StyledString styledString = new StyledString();
-
- String message = marker.getAttribute(IMarker.MESSAGE, "");
- styledString.append(message);
-
- int count = mList.getCount(marker);
- if (count > 1) {
- styledString.append(String.format(" (%2$d items)", message, count),
- StyledString.COUNTER_STYLER);
- }
-
- return styledString;
- }
-
- @Override
- public Image getImage(@NonNull IMarker marker) {
- int severity = marker.getAttribute(IMarker.SEVERITY, 0);
- ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages();
- switch (severity) {
- case IMarker.SEVERITY_ERROR:
- if (LintFix.hasFix(EclipseLintClient.getId(marker))) {
- return IconFactory.getInstance().getIcon("quickfix_error"); //$NON-NLS-1$
- }
- return sharedImages.getImage(ISharedImages.IMG_OBJS_ERROR_TSK);
- case IMarker.SEVERITY_WARNING:
- if (LintFix.hasFix(EclipseLintClient.getId(marker))) {
- return IconFactory.getInstance().getIcon("quickfix_warning"); //$NON-NLS-1$
- }
- return sharedImages.getImage(ISharedImages.IMG_OBJS_WARN_TSK);
- case IMarker.SEVERITY_INFO:
- return sharedImages.getImage(ISharedImages.IMG_OBJS_INFO_TSK);
- default:
- return null;
- }
- }
-
- @Override
- public Font getFont(@NonNull IMarker marker) {
- int severity = marker.getAttribute(IMarker.SEVERITY, 0);
- if (severity == IMarker.SEVERITY_ERROR) {
- return JFaceResources.getFontRegistry().getBold(
- JFaceResources.DEFAULT_FONT);
- }
-
- return null;
- }
-
- @Override
- public boolean isAscending() {
- return false;
- }
-
- @Override
- public int compare(IMarker marker2, IMarker marker1) {
- // Reversing order marker1/marker2 here since we want to use a "descending" column
- // sorting marker to indicate priority. (Note that we return from isAscending too.)
-
- String id1 = EclipseLintClient.getId(marker1);
- String id2 = EclipseLintClient.getId(marker2);
- if (id1 == null || id2 == null) {
- return marker1.getResource().getName().compareTo(
- marker2.getResource().getName());
- }
- Issue issue1 = mList.getIssue(id1);
- Issue issue2 = mList.getIssue(id2);
- if (issue1 == null || issue2 == null) {
- // Unknown issue? Can happen if you have used a third party detector
- // which is no longer available but which left a persistent marker behind
- return id1.compareTo(id2);
- }
- int delta = mList.getSeverity(issue1).ordinal() -
- mList.getSeverity(issue2).ordinal();
- if (delta != 0) {
- return delta;
- }
- delta = issue2.getPriority() - issue1.getPriority();
- if (delta != 0) {
- return delta;
- }
- delta = issue1.getCategory().compareTo(issue2.getCategory());
- if (delta != 0) {
- return delta;
- }
- delta = id1.compareTo(id2);
- if (delta != 0) {
- return delta;
- }
-
- IResource resource1 = marker1.getResource();
- IResource resource2 = marker2.getResource();
-
- IProject project1 = resource1.getProject();
- IProject project2 = resource2.getProject();
- delta = project1.getName().compareTo(project2.getName());
- if (delta != 0) {
- return delta;
- }
-
- delta = resource1.getName().compareTo(resource2.getName());
- if (delta != 0) {
- return delta;
- }
-
- return marker1.getAttribute(IMarker.LINE_NUMBER, 0)
- - marker2.getAttribute(IMarker.LINE_NUMBER, 0);
- }
- }
-
- static class CategoryColumn extends LintColumn {
-
- public CategoryColumn(LintList list) {
- super(list);
- }
-
- @Override
- public @NonNull String getColumnHeaderText() {
- return "Category";
- }
-
- @Override
- public int getPreferredCharWidth() {
- return 20;
- }
-
- @Override
- public String getValue(@NonNull IMarker marker) {
- Issue issue = mList.getIssue(marker);
- if (issue != null) {
- return issue.getCategory().getFullName();
- } else {
- return "";
- }
- }
- }
-
- static class LocationColumn extends LintColumn {
- public LocationColumn(LintList list) {
- super(list);
- }
-
- @Override
- public @NonNull String getColumnHeaderText() {
- return "Location";
- }
-
- @Override
- public int getPreferredCharWidth() {
- return 35;
- }
-
- @Override
- public String getValue(@NonNull IMarker marker) {
- return getStyledValue(marker).toString();
- }
-
- @Override
- public StyledString getStyledValue(@NonNull IMarker marker) {
- StyledString styledString = new StyledString();
-
- // Combined location
- IResource resource = marker.getResource();
- if (resource instanceof IProject) {
- styledString.append(resource.getName());
- } else {
- // Show location as Parent/File:Line in Project
- styledString.append(resource.getName());
- if (resource instanceof IFile) {
- int line = marker.getAttribute(IMarker.LINE_NUMBER, -1);
- if (line > 1) {
- styledString.append(':').append(Integer.toString(line));
- }
- } else if (resource instanceof IFolder) {
- styledString.append(File.separatorChar);
- }
-
- if (!(resource.getParent() instanceof IProject)) {
- styledString.append(" in ");
- styledString.append(resource.getParent().getName(),
- StyledString.DECORATIONS_STYLER);
- }
-
- styledString.append(String.format(" (%1$s)", resource.getProject().getName()),
- StyledString.QUALIFIER_STYLER);
- }
-
- return styledString;
- }
-
- @Override
- public int compare(IMarker marker1, IMarker marker2) {
- IResource resource1 = marker1.getResource();
- IResource resource2 = marker2.getResource();
-
- IProject project1 = resource1.getProject();
- IProject project2 = resource2.getProject();
- int delta = project1.getName().compareTo(project2.getName());
- if (delta != 0) {
- return delta;
- }
-
- delta = resource1.getName().compareTo(resource2.getName());
- if (delta != 0) {
- return delta;
- }
-
- return marker1.getAttribute(IMarker.LINE_NUMBER, 0)
- - marker2.getAttribute(IMarker.LINE_NUMBER, 0);
- }
- }
-
- static class FileColumn extends LintColumn {
- public FileColumn(LintList list) {
- super(list);
- }
-
- @Override
- public @NonNull String getColumnHeaderText() {
- return "File";
- }
-
- @Override
- public boolean visibleByDefault() {
- return false;
- }
-
- @Override
- public int getPreferredCharWidth() {
- return 12;
- }
-
- @Override
- public String getValue(@NonNull IMarker marker) {
- if (marker.getResource() instanceof IFile) {
- return marker.getResource().getName();
- } else {
- return "";
- }
- }
- }
-
- static class PathColumn extends LintColumn {
- public PathColumn(LintList list) {
- super(list);
- }
-
- @Override
- public @NonNull String getColumnHeaderText() {
- return "Path";
- }
-
- @Override
- public boolean visibleByDefault() {
- return false;
- }
-
- @Override
- public int getPreferredCharWidth() {
- return 25;
- }
-
- @Override
- public String getValue(@NonNull IMarker marker) {
- return marker.getResource().getFullPath().toOSString();
- }
- }
-
- static class LineColumn extends LintColumn {
- public LineColumn(LintList list) {
- super(list);
- }
-
- @Override
- public @NonNull String getColumnHeaderText() {
- return "Line";
- }
-
- @Override
- public boolean visibleByDefault() {
- return false;
- }
-
- @Override
- public boolean isLeftAligned() {
- return false;
- }
-
- @Override
- public int getPreferredCharWidth() {
- return 4;
- }
-
- @Override
- public String getValue(@NonNull IMarker marker) {
- int line = getLine(marker);
- if (line >= 1) {
- return Integer.toString(line);
- } else {
- return "";
- }
- }
-
- private int getLine(IMarker marker) {
- if (marker.getResource() instanceof IFile) {
- int line = marker.getAttribute(IMarker.LINE_NUMBER, -1);
- return line;
- }
-
- return -1;
- }
- @Override
- public int compare(IMarker marker1, IMarker marker2) {
- return getLine(marker1) - getLine(marker2);
- }
- }
-
- static class PriorityColumn extends LintColumn {
- public PriorityColumn(LintList list) {
- super(list);
- }
-
- @Override
- public @NonNull String getColumnHeaderText() {
- return "Priority";
- }
-
- @Override
- public boolean visibleByDefault() {
- return false;
- }
-
- @Override
- public boolean isLeftAligned() {
- return false;
- }
-
- @Override
- public int getPreferredCharWidth() {
- return 2;
- }
-
- @Override
- public String getValue(@NonNull IMarker marker) {
- int priority = getPriority(marker);
- if (priority > 0) {
- return Integer.toString(priority);
- }
- return "";
- }
-
- private int getPriority(IMarker marker) {
- Issue issue = mList.getIssue(marker);
- if (issue != null) {
- return issue.getPriority();
- }
- return 0;
- }
-
- @Override
- public int compare(IMarker marker1, IMarker marker2) {
- return getPriority(marker1) - getPriority(marker2);
- }
-
- @Override
- public boolean isAscending() {
- return false;
- }
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintDeltaProcessor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintDeltaProcessor.java
deleted file mode 100644
index ebb9a591c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintDeltaProcessor.java
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import static com.android.SdkConstants.DOT_CLASS;
-import static com.android.SdkConstants.DOT_JAVA;
-import static com.android.SdkConstants.EXT_JAVA;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.resources.manager.GlobalProjectMonitor;
-import com.android.ide.eclipse.adt.internal.resources.manager.GlobalProjectMonitor.IFileListener;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarkerDelta;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.swt.widgets.Display;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * Delta processor for Java files, which runs single-file lints if it finds that
- * the currently active file has been updated.
- */
-public class LintDeltaProcessor implements Runnable {
- private List<IResource> mFiles;
- private IFile mActiveFile;
-
- private LintDeltaProcessor() {
- // Get the active editor file, if any
- Display display = AdtPlugin.getDisplay();
- if (display == null || display.isDisposed()) {
- return;
- }
- if (display.getThread() != Thread.currentThread()) {
- display.syncExec(this);
- } else {
- run();
- }
- }
-
- /**
- * Creates a new {@link LintDeltaProcessor}
- *
- * @return a visitor
- */
- @NonNull
- public static LintDeltaProcessor create() {
- return new LintDeltaProcessor();
- }
-
- /**
- * Process the given delta: update lint on any Java source and class files found.
- *
- * @param delta the delta describing recently changed files
- */
- public void process(@NonNull IResourceDelta delta) {
- if (mActiveFile == null || !mActiveFile.getName().endsWith(DOT_JAVA)) {
- return;
- }
-
- mFiles = new ArrayList<IResource>();
- gatherFiles(delta);
-
- if (!mFiles.isEmpty()) {
- EclipseLintRunner.startLint(mFiles, mActiveFile, null,
- false /*fatalOnly*/, false /*show*/);
- }
- }
-
- /**
- * Process edits in the given file: update lint on the Java source provided
- * it's the active file.
- *
- * @param file the file that was changed
- */
- public void process(@NonNull IFile file) {
- if (mActiveFile == null || !mActiveFile.getName().endsWith(DOT_JAVA)) {
- return;
- }
-
- if (file.equals(mActiveFile)) {
- mFiles = Collections.<IResource>singletonList(file);
- EclipseLintRunner.startLint(mFiles, mActiveFile, null,
- false /*fatalOnly*/, false /*show*/);
- }
- }
-
- /**
- * Collect .java and .class files to be run in lint. Only collects files
- * that match the active editor.
- */
- private void gatherFiles(@NonNull IResourceDelta delta) {
- IResource resource = delta.getResource();
- String name = resource.getName();
- if (name.endsWith(DOT_JAVA)) {
- if (resource.equals(mActiveFile)) {
- mFiles.add(resource);
- }
- } else if (name.endsWith(DOT_CLASS)) {
- // Make sure this class corresponds to the .java file, meaning it has
- // the same basename, or that it is an inner class of a class that
- // matches the same basename. (We could potentially make sure the package
- // names match too, but it's unlikely that the class names match without a
- // package match, and there's no harm in including some extra classes here,
- // since lint will resolve full paths and the resource markers won't go
- // to the wrong place, we simply end up analyzing some extra files.)
- String className = mActiveFile.getName();
- if (name.regionMatches(0, className, 0, className.length() - DOT_JAVA.length())) {
- if (name.length() == className.length() - DOT_JAVA.length() + DOT_CLASS.length()
- || name.charAt(className.length() - DOT_JAVA.length()) == '$') {
- mFiles.add(resource);
- }
- }
- } else {
- IResourceDelta[] children = delta.getAffectedChildren();
- if (children != null && children.length > 0) {
- for (IResourceDelta d : children) {
- gatherFiles(d);
- }
- }
- }
- }
-
- @Override
- public void run() {
- // Get the active file: this must be run on the GUI thread
- mActiveFile = AdtUtils.getActiveFile();
- }
-
- /**
- * Start listening to the resource monitor
- *
- * @param resourceMonitor the resource monitor
- */
- public static void startListening(@NonNull GlobalProjectMonitor resourceMonitor) {
- // Add a file listener which finds out when files have changed. This is listening
- // specifically for saves of Java files, in order to run incremental lint on them.
- // Note that the {@link PostCompilerBuilder} already handles incremental lint files
- // on Java files - and runs it for both the .java and .class files.
- //
- // However, if Project > Build Automatically is turned off, then the PostCompilerBuilder
- // isn't run after a save. THAT's what the below is for: it will run and *only*
- // run lint incrementally if build automatically is off.
- assert sListener == null; // Should only be called once on plugin activation
- sListener = new IFileListener() {
- @Override
- public void fileChanged(@NonNull IFile file,
- @NonNull IMarkerDelta[] markerDeltas,
- int kind, @Nullable String extension, int flags, boolean isAndroidProject) {
- if (!isAndroidProject || flags == IResourceDelta.MARKERS) {
- // If not an Android project or ONLY the markers changed.
- // Ignore these since they happen
- // when we add markers for lint errors found in the current file,
- // which would cause us to repeatedly enter this method over and over
- // again.
- return;
- }
- if (EXT_JAVA.equals(extension)
- && !ResourceManager.isAutoBuilding()
- && AdtPrefs.getPrefs().isLintOnSave()) {
- LintDeltaProcessor.create().process(file);
- }
- }
- };
- resourceMonitor.addFileListener(sListener, IResourceDelta.ADDED | IResourceDelta.CHANGED);
- }
-
- /**
- * Stop listening to the resource monitor
- *
- * @param resourceMonitor the resource monitor
- */
- public static void stopListening(@NonNull GlobalProjectMonitor resourceMonitor) {
- assert sListener != null;
- resourceMonitor.removeFileListener(sListener);
- sListener = null;
- }
-
- private static IFileListener sListener;
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintEditAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintEditAction.java
deleted file mode 100644
index bf05ce0b1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintEditAction.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import com.android.annotations.NonNull;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DelegatingAction;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.swt.widgets.Event;
-
-/**
- * Action intended to wrap an existing XML editor action, and then runs lint after
- * the edit.
- */
-public class LintEditAction extends DelegatingAction {
- private final AndroidXmlEditor mEditor;
-
- /**
- * Creates a new {@link LintEditAction} associated with the given editor to
- * wrap the given action
- *
- * @param action the action to be wrapped
- * @param editor the editor associated with the action
- */
- public LintEditAction(@NonNull IAction action, @NonNull AndroidXmlEditor editor) {
- super(action);
- mEditor = editor;
- }
-
- @Override
- public void runWithEvent(Event event) {
- super.runWithEvent(event);
- mEditor.runEditHooks();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintFix.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintFix.java
deleted file mode 100644
index 366e94945..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintFix.java
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.tools.lint.checks.AccessibilityDetector;
-import com.android.tools.lint.checks.DetectMissingPrefix;
-import com.android.tools.lint.checks.DosLineEndingDetector;
-import com.android.tools.lint.checks.HardcodedValuesDetector;
-import com.android.tools.lint.checks.InefficientWeightDetector;
-import com.android.tools.lint.checks.ManifestDetector;
-import com.android.tools.lint.checks.MissingIdDetector;
-import com.android.tools.lint.checks.ObsoleteLayoutParamsDetector;
-import com.android.tools.lint.checks.PxUsageDetector;
-import com.android.tools.lint.checks.ScrollViewChildDetector;
-import com.android.tools.lint.checks.SecurityDetector;
-import com.android.tools.lint.checks.TextFieldDetector;
-import com.android.tools.lint.checks.TranslationDetector;
-import com.android.tools.lint.checks.TypoDetector;
-import com.android.tools.lint.checks.TypographyDetector;
-import com.android.tools.lint.checks.UseCompoundDrawableDetector;
-import com.android.tools.lint.checks.UselessViewDetector;
-import com.android.tools.lint.detector.api.Issue;
-import com.android.tools.lint.detector.api.TextFormat;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-
-import java.lang.reflect.Constructor;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-abstract class LintFix implements ICompletionProposal {
- protected final IMarker mMarker;
- protected final String mId;
-
- protected LintFix(String id, IMarker marker) {
- mId = id;
- mMarker = marker;
- }
-
- /**
- * Returns true if this fix needs focus (which means that when the fix is
- * performed from for example a {@link LintListDialog}'s Fix button) the
- * editor needs to be given focus.
- *
- * @return true if this fix needs focus after being applied
- */
- public boolean needsFocus() {
- return true;
- }
-
- /**
- * Returns true if this fix can be performed along side other fixes
- *
- * @return true if this fix can be performed in a bulk operation with other
- * fixes
- */
- public boolean isBulkCapable() {
- return false;
- }
-
- /**
- * Returns true if this fix can be cancelled once it's invoked. This is the case
- * for fixes which shows a confirmation dialog (such as the Extract String etc).
- * This will be used to determine whether the marker can be deleted immediately
- * (for non-cancelable fixes) or if it should be left alone and detected fix
- * on the next save.
- *
- * @return true if the fix can be cancelled
- */
- public boolean isCancelable() {
- return true;
- }
-
- // ---- Implements ICompletionProposal ----
-
- @Override
- public String getDisplayString() {
- return null;
- }
-
- @Override
- public String getAdditionalProposalInfo() {
- Issue issue = EclipseLintClient.getRegistry().getIssue(mId);
- if (issue != null) {
- return issue.getExplanation(TextFormat.HTML);
- }
-
- return null;
- }
-
- public void deleteMarker() {
- try {
- mMarker.delete();
- } catch (PartInitException e) {
- AdtPlugin.log(e, null);
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- }
-
- @Override
- public Point getSelection(IDocument document) {
- return null;
- }
-
- @Override
- public Image getImage() {
- ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages();
- return sharedImages.getImage(ISharedImages.IMG_OBJS_WARN_TSK);
- }
-
- @Override
- public IContextInformation getContextInformation() {
- return null;
- }
-
- // --- Access to available fixes ---
-
- private static final Map<String, Class<? extends LintFix>> sFixes =
- new HashMap<String, Class<? extends LintFix>>();
- // Keep this map in sync with BuiltinIssueRegistry's hasAutoFix() data
- static {
- sFixes.put(InefficientWeightDetector.INEFFICIENT_WEIGHT.getId(),
- LinearLayoutWeightFix.class);
- sFixes.put(AccessibilityDetector.ISSUE.getId(), SetAttributeFix.class);
- sFixes.put(InefficientWeightDetector.BASELINE_WEIGHTS.getId(), SetAttributeFix.class);
- sFixes.put(ManifestDetector.ALLOW_BACKUP.getId(), SetAttributeFix.class);
- sFixes.put(MissingIdDetector.ISSUE.getId(), SetAttributeFix.class);
- sFixes.put(HardcodedValuesDetector.ISSUE.getId(), ExtractStringFix.class);
- sFixes.put(UselessViewDetector.USELESS_LEAF.getId(), RemoveUselessViewFix.class);
- sFixes.put(UselessViewDetector.USELESS_PARENT.getId(), RemoveUselessViewFix.class);
- sFixes.put(PxUsageDetector.PX_ISSUE.getId(), ConvertToDpFix.class);
- sFixes.put(TextFieldDetector.ISSUE.getId(), SetAttributeFix.class);
- sFixes.put(SecurityDetector.EXPORTED_SERVICE.getId(), SetAttributeFix.class);
- sFixes.put(TranslationDetector.MISSING.getId(), SetAttributeFix.class);
- sFixes.put(DetectMissingPrefix.MISSING_NAMESPACE.getId(), AddPrefixFix.class);
- sFixes.put(ScrollViewChildDetector.ISSUE.getId(), SetScrollViewSizeFix.class);
- sFixes.put(ObsoleteLayoutParamsDetector.ISSUE.getId(), ObsoleteLayoutParamsFix.class);
- sFixes.put(TypographyDetector.DASHES.getId(), TypographyFix.class);
- sFixes.put(TypographyDetector.ELLIPSIS.getId(), TypographyFix.class);
- sFixes.put(TypographyDetector.FRACTIONS.getId(), TypographyFix.class);
- sFixes.put(TypographyDetector.OTHER.getId(), TypographyFix.class);
- sFixes.put(TypographyDetector.QUOTES.getId(), TypographyFix.class);
- sFixes.put(UseCompoundDrawableDetector.ISSUE.getId(),
- UseCompoundDrawableDetectorFix.class);
- sFixes.put(TypoDetector.ISSUE.getId(), TypoFix.class);
- sFixes.put(DosLineEndingDetector.ISSUE.getId(), DosLineEndingsFix.class);
- // ApiDetector.UNSUPPORTED is provided as a marker resolution rather than
- // a quick assistant (the marker resolution adds a suitable @TargetApi annotation)
- }
-
- public static boolean hasFix(String id) {
- return sFixes.containsKey(id);
- }
-
- /**
- * Returns one or more fixes for the given issue, or null if no fixes are available
- *
- * @param id the id o the issue to obtain a fix for (see {@link Issue#getId()})
- * @param marker the marker corresponding to the error
- * @return a nonempty list of fix, or null
- */
- @Nullable
- public static List<LintFix> getFixes(@NonNull String id, @NonNull IMarker marker) {
- Class<? extends LintFix> clazz = sFixes.get(id);
- if (clazz != null) {
- try {
- Constructor<? extends LintFix> constructor = clazz.getDeclaredConstructor(
- String.class, IMarker.class);
- constructor.setAccessible(true);
- LintFix fix = constructor.newInstance(id, marker);
- List<LintFix> alternatives = fix.getAllFixes();
- if (alternatives != null) {
- return alternatives;
- } else {
- return Collections.singletonList(fix);
- }
- } catch (Throwable t) {
- AdtPlugin.log(t, null);
- }
- }
-
- return null;
- }
-
- /**
- * Returns a full list of fixes for this issue. This will produce a list of
- * multiple fixes, in the desired order, which provide alternative ways of
- * fixing the issue.
- *
- * @return a list of fixes to fix this issue, or null if there are no
- * variations
- */
- @Nullable
- protected List<LintFix> getAllFixes() {
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintFixGenerator.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintFixGenerator.java
deleted file mode 100644
index da100850a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintFixGenerator.java
+++ /dev/null
@@ -1,563 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import static com.android.SdkConstants.DOT_JAVA;
-import static com.android.SdkConstants.DOT_XML;
-
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.tools.lint.client.api.Configuration;
-import com.android.tools.lint.client.api.DefaultConfiguration;
-import com.android.tools.lint.client.api.IssueRegistry;
-import com.android.tools.lint.detector.api.Issue;
-import com.android.tools.lint.detector.api.TextFormat;
-import com.android.tools.lint.detector.api.Project;
-import com.android.tools.lint.detector.api.Severity;
-import com.android.utils.SdkUtils;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext;
-import org.eclipse.jface.text.quickassist.IQuickAssistProcessor;
-import org.eclipse.jface.text.source.Annotation;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IMarkerResolution;
-import org.eclipse.ui.IMarkerResolution2;
-import org.eclipse.ui.IMarkerResolutionGenerator2;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.part.FileEditorInput;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * A quickfix and marker resolution for disabling lint checks, and any
- * IDE specific implementations for fixing the warnings.
- * <p>
- * I would really like for this quickfix to show up as a light bulb on top of the error
- * icon in the editor, and I've spent a whole day trying to make it work. I did not
- * succeed, but here are the steps I tried in case I want to pick up the work again
- * later:
- * <ul>
- * <li>
- * The WST has some support for quick fixes, and I came across some forum posts
- * referencing the ability to show light bulbs. However, it turns out that the
- * quickfix support for annotations in WST is hardcoded to source validation
- * errors *only*.
- * <li>
- * I tried defining my own editor annotations, and customizing the icon directly
- * by either setting an icon or using the image provider. This works fine
- * if I make my marker be a new independent marker type. However, whenever I
- * switch the marker type back to extend the "Problem" type, then the icon reverts
- * back to the standard error icon and it ignores my custom settings.
- * And if I switch away from the Problems marker type, then the errors no longer
- * show up in the Problems view. (I also tried extending the JDT marker but that
- * still didn't work.)
- * <li>
- * It looks like only JDT handles quickfix icons. It has a bunch of custom code
- * to handle this, along with its own Annotation subclass used by the editor.
- * I tried duplicating some of this by subclassing StructuredTextEditor, but
- * it was evident that I'd have to pull in a *huge* amount of duplicated code to
- * make this work, which seems risky given that all this is internal code that
- * can change from one Eclipse version to the next.
- * </ul>
- * It looks like our best bet would be to reconsider whether these should show up
- * in the Problems view; perhaps we should use a custom view for these. That would also
- * make marker management more obvious.
- */
-@SuppressWarnings("restriction") // DOM model
-public class LintFixGenerator implements IMarkerResolutionGenerator2, IQuickAssistProcessor {
- /** Constructs a new {@link LintFixGenerator} */
- public LintFixGenerator() {
- }
-
- // ---- Implements IMarkerResolutionGenerator2 ----
-
- @Override
- public boolean hasResolutions(IMarker marker) {
- try {
- assert marker.getType().equals(AdtConstants.MARKER_LINT);
- } catch (CoreException e) {
- }
-
- return true;
- }
-
- @Override
- public IMarkerResolution[] getResolutions(IMarker marker) {
- String id = marker.getAttribute(EclipseLintRunner.MARKER_CHECKID_PROPERTY,
- ""); //$NON-NLS-1$
- IResource resource = marker.getResource();
-
- List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>();
-
- if (resource.getName().endsWith(DOT_JAVA)) {
- AddSuppressAnnotation.createFixes(marker, id, resolutions);
- }
-
- resolutions.add(new MoreInfoProposal(id, marker.getAttribute(IMarker.MESSAGE, null)));
- resolutions.add(new SuppressProposal(resource, id, false));
- resolutions.add(new SuppressProposal(resource.getProject(), id, true /* all */));
- resolutions.add(new SuppressProposal(resource, id, true /* all */));
- resolutions.add(new ClearMarkersProposal(resource, true /* all */));
-
- if (resolutions.size() > 0) {
- return resolutions.toArray(new IMarkerResolution[resolutions.size()]);
- }
-
- return null;
- }
-
- // ---- Implements IQuickAssistProcessor ----
-
- @Override
- public String getErrorMessage() {
- return "Disable Lint Error";
- }
-
- @Override
- public boolean canFix(Annotation annotation) {
- return true;
- }
-
- @Override
- public boolean canAssist(IQuickAssistInvocationContext invocationContext) {
- return true;
- }
-
- @Override
- public ICompletionProposal[] computeQuickAssistProposals(
- IQuickAssistInvocationContext invocationContext) {
- ISourceViewer sourceViewer = invocationContext.getSourceViewer();
- AndroidXmlEditor editor = AndroidXmlEditor.fromTextViewer(sourceViewer);
- if (editor != null) {
- IFile file = editor.getInputFile();
- if (file == null) {
- return null;
- }
- IDocument document = sourceViewer.getDocument();
- List<IMarker> markers = AdtUtils.findMarkersOnLine(AdtConstants.MARKER_LINT,
- file, document, invocationContext.getOffset());
- List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();
- if (markers.size() > 0) {
- for (IMarker marker : markers) {
- String id = marker.getAttribute(EclipseLintRunner.MARKER_CHECKID_PROPERTY,
- ""); //$NON-NLS-1$
-
- // TODO: Allow for more than one fix?
- List<LintFix> fixes = LintFix.getFixes(id, marker);
- if (fixes != null) {
- for (LintFix fix : fixes) {
- proposals.add(fix);
- }
- }
-
- String message = marker.getAttribute(IMarker.MESSAGE, null);
- proposals.add(new MoreInfoProposal(id, message));
-
- proposals.addAll(AddSuppressAttribute.createFixes(editor, marker, id));
- proposals.add(new SuppressProposal(file, id, false));
- proposals.add(new SuppressProposal(file.getProject(), id, true /* all */));
- proposals.add(new SuppressProposal(file, id, true /* all */));
-
- proposals.add(new ClearMarkersProposal(file, true /* all */));
- }
- }
- if (proposals.size() > 0) {
- return proposals.toArray(new ICompletionProposal[proposals.size()]);
- }
- }
-
- return null;
- }
-
- /**
- * Suppress the given detector, and rerun the checks on the file
- *
- * @param id the id of the detector to be suppressed, or null
- * @param updateMarkers if true, update all markers
- * @param resource the resource associated with the markers
- * @param thisFileOnly if true, only suppress this issue in this file
- */
- public static void suppressDetector(String id, boolean updateMarkers, IResource resource,
- boolean thisFileOnly) {
- IssueRegistry registry = EclipseLintClient.getRegistry();
- Issue issue = registry.getIssue(id);
- if (issue != null) {
- EclipseLintClient mClient = new EclipseLintClient(registry,
- Collections.singletonList(resource), null, false);
- Project project = null;
- IProject eclipseProject = resource.getProject();
- if (eclipseProject != null) {
- File dir = AdtUtils.getAbsolutePath(eclipseProject).toFile();
- project = mClient.getProject(dir, dir);
- }
- Configuration configuration = mClient.getConfigurationFor(project);
- if (thisFileOnly && configuration instanceof DefaultConfiguration) {
- File file = AdtUtils.getAbsolutePath(resource).toFile();
- ((DefaultConfiguration) configuration).ignore(issue, file);
- } else {
- configuration.setSeverity(issue, Severity.IGNORE);
- }
- }
-
- if (updateMarkers) {
- EclipseLintClient.removeMarkers(resource, id);
- }
- }
-
- /**
- * Adds a suppress lint annotation or attribute depending on whether the
- * error is in a Java or XML file.
- *
- * @param marker the marker pointing to the error to be suppressed
- */
- public static void addSuppressAnnotation(IMarker marker) {
- String id = EclipseLintClient.getId(marker);
- if (id != null) {
- IResource resource = marker.getResource();
- if (!(resource instanceof IFile)) {
- return;
- }
- IFile file = (IFile) resource;
- boolean isJava = file.getName().endsWith(DOT_JAVA);
- boolean isXml = SdkUtils.endsWith(file.getName(), DOT_XML);
- if (!isJava && !isXml) {
- return;
- }
-
- try {
- // See if the current active file is the one containing this marker;
- // if so we can take some shortcuts
- IEditorPart activeEditor = AdtUtils.getActiveEditor();
- IEditorPart part = null;
- if (activeEditor != null) {
- IEditorInput input = activeEditor.getEditorInput();
- if (input instanceof FileEditorInput
- && ((FileEditorInput)input).getFile().equals(file)) {
- part = activeEditor;
- }
- }
- if (part == null) {
- IRegion region = null;
- int start = marker.getAttribute(IMarker.CHAR_START, -1);
- int end = marker.getAttribute(IMarker.CHAR_END, -1);
- if (start != -1 && end != -1) {
- region = new Region(start, end - start);
- }
- part = AdtPlugin.openFile(file, region, true /* showEditor */);
- }
-
- if (isJava) {
- List<IMarkerResolution> resolutions = new ArrayList<IMarkerResolution>();
- AddSuppressAnnotation.createFixes(marker, id, resolutions);
- if (resolutions.size() > 0) {
- resolutions.get(0).run(marker);
- }
- } else {
- assert isXml;
- if (part instanceof AndroidXmlEditor) {
- AndroidXmlEditor editor = (AndroidXmlEditor) part;
- List<AddSuppressAttribute> fixes = AddSuppressAttribute.createFixes(editor,
- marker, id);
- if (fixes.size() > 0) {
- IStructuredDocument document = editor.getStructuredDocument();
- fixes.get(0).apply(document);
- }
- }
- }
- } catch (PartInitException pie) {
- AdtPlugin.log(pie, null);
- }
- }
- }
-
- private static class SuppressProposal implements ICompletionProposal, IMarkerResolution2 {
- private final String mId;
- private final boolean mGlobal;
- private final IResource mResource;
-
- private SuppressProposal(IResource resource, String check, boolean global) {
- mResource = resource;
- mId = check;
- mGlobal = global;
- }
-
- private void perform() {
- suppressDetector(mId, true, mResource, !mGlobal);
- }
-
- @Override
- public String getDisplayString() {
- if (mResource instanceof IProject) {
- return "Disable Check in This Project";
- } else if (mGlobal) {
- return "Disable Check";
- } else {
- return "Disable Check in This File Only";
- }
- }
-
- // ---- Implements MarkerResolution2 ----
-
- @Override
- public String getLabel() {
- return getDisplayString();
- }
-
- @Override
- public void run(IMarker marker) {
- perform();
- }
-
- @Override
- public String getDescription() {
- return getAdditionalProposalInfo();
- }
-
- // ---- Implements ICompletionProposal ----
-
- @Override
- public void apply(IDocument document) {
- perform();
- }
-
- @Override
- public Point getSelection(IDocument document) {
- return null;
- }
-
- @Override
- public String getAdditionalProposalInfo() {
- StringBuilder sb = new StringBuilder(200);
- if (mResource instanceof IProject) {
- sb.append("Suppresses this type of lint warning in the current project only.");
- } else if (mGlobal) {
- sb.append("Suppresses this type of lint warning in all files.");
- } else {
- sb.append("Suppresses this type of lint warning in the current file only.");
- }
- sb.append("<br><br>"); //$NON-NLS-1$
- sb.append("You can re-enable checks from the \"Android > Lint Error Checking\" preference page.");
-
- return sb.toString();
- }
-
- @Override
- public Image getImage() {
- ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages();
- return sharedImages.getImage(ISharedImages.IMG_OBJS_WARN_TSK);
- }
-
- @Override
- public IContextInformation getContextInformation() {
- return null;
- }
- }
-
- private static class ClearMarkersProposal implements ICompletionProposal, IMarkerResolution2 {
- private final boolean mGlobal;
- private final IResource mResource;
-
- public ClearMarkersProposal(IResource resource, boolean global) {
- mResource = resource;
- mGlobal = global;
- }
-
- private void perform() {
- IResource resource = mGlobal ? mResource.getProject() : mResource;
- EclipseLintClient.clearMarkers(resource);
- }
-
- @Override
- public String getDisplayString() {
- return mGlobal ? "Clear All Lint Markers" : "Clear Markers in This File Only";
- }
-
- // ---- Implements MarkerResolution2 ----
-
- @Override
- public String getLabel() {
- return getDisplayString();
- }
-
- @Override
- public void run(IMarker marker) {
- perform();
- }
-
- @Override
- public String getDescription() {
- return getAdditionalProposalInfo();
- }
-
- // ---- Implements ICompletionProposal ----
-
- @Override
- public void apply(IDocument document) {
- perform();
- }
-
- @Override
- public Point getSelection(IDocument document) {
- return null;
- }
-
- @Override
- public String getAdditionalProposalInfo() {
- StringBuilder sb = new StringBuilder(200);
- if (mGlobal) {
- sb.append("Clears all lint warning markers from the project.");
- } else {
- sb.append("Clears all lint warnings from this file.");
- }
- sb.append("<br><br>"); //$NON-NLS-1$
- sb.append("This temporarily hides the problem, but does not suppress it. " +
- "Running Lint again can bring the error back.");
- if (AdtPrefs.getPrefs().isLintOnSave()) {
- sb.append(' ');
- sb.append("This will happen the next time the file is saved since lint-on-save " +
- "is enabled. You can turn this off in the \"Lint Error Checking\" " +
- "preference page.");
- }
-
- return sb.toString();
- }
-
- @Override
- public Image getImage() {
- ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages();
- return sharedImages.getImage(ISharedImages.IMG_ELCL_REMOVE);
- }
-
- @Override
- public IContextInformation getContextInformation() {
- return null;
- }
- }
-
- private static class MoreInfoProposal implements ICompletionProposal, IMarkerResolution2 {
- private final String mId;
- private final String mMessage;
-
- public MoreInfoProposal(String id, String message) {
- mId = id;
- mMessage = message;
- }
-
- private void perform() {
- Issue issue = EclipseLintClient.getRegistry().getIssue(mId);
- assert issue != null : mId;
-
- StringBuilder sb = new StringBuilder(300);
- sb.append(mMessage);
- sb.append('\n').append('\n');
- sb.append("Issue Explanation:");
- sb.append('\n');
- String explanation = issue.getExplanation(TextFormat.TEXT);
- if (explanation != null && !explanation.isEmpty()) {
- sb.append('\n');
- sb.append(explanation);
- } else {
- sb.append(issue.getBriefDescription(TextFormat.TEXT));
- }
-
- if (issue.getMoreInfo() != null) {
- sb.append('\n').append('\n');
- sb.append("More Information: ");
- sb.append(issue.getMoreInfo());
- }
-
- MessageDialog.openInformation(AdtPlugin.getShell(), "More Info",
- sb.toString());
- }
-
- @Override
- public String getDisplayString() {
- return String.format("Explain Issue (%1$s)", mId);
- }
-
- // ---- Implements MarkerResolution2 ----
-
- @Override
- public String getLabel() {
- return getDisplayString();
- }
-
- @Override
- public void run(IMarker marker) {
- perform();
- }
-
- @Override
- public String getDescription() {
- return getAdditionalProposalInfo();
- }
-
- // ---- Implements ICompletionProposal ----
-
- @Override
- public void apply(IDocument document) {
- perform();
- }
-
- @Override
- public Point getSelection(IDocument document) {
- return null;
- }
-
- @Override
- public String getAdditionalProposalInfo() {
- return "Provides more information about this issue."
- + "<br><br>" //$NON-NLS-1$
- + EclipseLintClient.getRegistry().getIssue(mId).getExplanation(
- TextFormat.HTML);
- }
-
- @Override
- public Image getImage() {
- ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages();
- return sharedImages.getImage(ISharedImages.IMG_OBJS_INFO_TSK);
- }
-
- @Override
- public IContextInformation getContextInformation() {
- return null;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintJob.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintJob.java
deleted file mode 100644
index 51fa2d145..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintJob.java
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import static com.android.SdkConstants.DOT_CLASS;
-import static com.android.SdkConstants.DOT_JAVA;
-import static com.android.SdkConstants.DOT_XML;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.tools.lint.client.api.IssueRegistry;
-import com.android.tools.lint.client.api.LintDriver;
-import com.android.tools.lint.client.api.LintRequest;
-import com.android.tools.lint.detector.api.Issue;
-import com.android.tools.lint.detector.api.Scope;
-import com.android.utils.SdkUtils;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.IJobManager;
-import org.eclipse.core.runtime.jobs.Job;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.EnumSet;
-import java.util.List;
-
-/** Job to check lint on a set of resources */
-public final class LintJob extends Job {
- /** Job family */
- private static final Object FAMILY_RUN_LINT = new Object();
- private final EclipseLintClient mClient;
- private final List<? extends IResource> mResources;
- private final IResource mSource;
- private final IssueRegistry mRegistry;
- private LintDriver mLint;
- private boolean mFatal;
-
- public LintJob(
- @NonNull EclipseLintClient client,
- @NonNull List<? extends IResource> resources,
- @Nullable IResource source,
- @NonNull IssueRegistry registry) {
- super("Running Android Lint");
- mClient = client;
- mResources = resources;
- mSource = source;
- mRegistry = registry;
- }
-
- public LintJob(
- @NonNull EclipseLintClient client,
- @NonNull List<? extends IResource> resources,
- @Nullable IResource source) {
- this(client, resources, source, EclipseLintClient.getRegistry());
- }
-
- @Override
- public boolean belongsTo(Object family) {
- return family == FAMILY_RUN_LINT;
- }
-
- @Override
- protected void canceling() {
- super.canceling();
- if (mLint != null) {
- mLint.cancel();
- }
- }
-
- @Override
- @NonNull
- protected IStatus run(IProgressMonitor monitor) {
- try {
- monitor.beginTask("Looking for errors", IProgressMonitor.UNKNOWN);
- EnumSet<Scope> scope = null;
- List<File> files = new ArrayList<File>(mResources.size());
- for (IResource resource : mResources) {
- File file = AdtUtils.getAbsolutePath(resource).toFile();
- files.add(file);
-
- if (resource instanceof IProject && mSource == null) {
- scope = Scope.ALL;
- } else {
- String name = resource.getName();
- if (SdkUtils.endsWithIgnoreCase(name, DOT_XML)) {
- if (name.equals(SdkConstants.FN_ANDROID_MANIFEST_XML)) {
- scope = EnumSet.of(Scope.MANIFEST);
- } else {
- scope = Scope.RESOURCE_FILE_SCOPE;
- }
- } else if (name.endsWith(DOT_JAVA) && resource instanceof IFile) {
- if (scope != null) {
- if (!scope.contains(Scope.JAVA_FILE)) {
- scope = EnumSet.copyOf(scope);
- scope.add(Scope.JAVA_FILE);
- }
- } else {
- scope = Scope.JAVA_FILE_SCOPE;
- }
- } else if (name.endsWith(DOT_CLASS) && resource instanceof IFile) {
- if (scope != null) {
- if (!scope.contains(Scope.CLASS_FILE)) {
- scope = EnumSet.copyOf(scope);
- scope.add(Scope.CLASS_FILE);
- }
- } else {
- scope = Scope.CLASS_FILE_SCOPE;
- }
- } else {
- return new Status(Status.ERROR, AdtPlugin.PLUGIN_ID, Status.ERROR,
- "Only XML & Java files are supported for single file lint", null); //$NON-NLS-1$
- }
- }
- }
- if (scope == null) {
- scope = Scope.ALL;
- }
- if (mSource == null) {
- assert !Scope.checkSingleFile(scope) : scope + " with " + mResources;
- }
- // Check single file?
- if (mSource != null) {
- // Delete specific markers
- IMarker[] markers = EclipseLintClient.getMarkers(mSource);
- for (IMarker marker : markers) {
- String id = marker.getAttribute(EclipseLintRunner.MARKER_CHECKID_PROPERTY, "");
- Issue issue = mRegistry.getIssue(id);
- if (issue == null) {
- continue;
- }
- if (issue.getImplementation().isAdequate(scope)) {
- marker.delete();
- }
- }
- mClient.setSearchForSuperClasses(true);
- } else {
- EclipseLintClient.clearMarkers(mResources);
- }
-
- mLint = new LintDriver(mRegistry, mClient);
- mLint.analyze(new LintRequest(mClient, files).setScope(scope));
- mFatal = mClient.hasFatalErrors();
- return Status.OK_STATUS;
- } catch (Exception e) {
- return new Status(Status.ERROR, AdtPlugin.PLUGIN_ID, Status.ERROR,
- "Failed", e); //$NON-NLS-1$
- } finally {
- if (monitor != null) {
- monitor.done();
- }
- }
- }
-
- /**
- * Returns true if a fatal error was encountered
- *
- * @return true if a fatal error was encountered
- */
- public boolean isFatal() {
- return mFatal;
- }
-
- /**
- * Returns the associated lint client
- *
- * @return the associated lint client
- */
- @NonNull
- public EclipseLintClient getLintClient() {
- return mClient;
- }
-
- /** Returns the current lint jobs, if any (never returns null but array may be empty) */
- @NonNull
- static Job[] getCurrentJobs() {
- IJobManager jobManager = Job.getJobManager();
- return jobManager.find(LintJob.FAMILY_RUN_LINT);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintList.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintList.java
deleted file mode 100644
index ccb04bb6b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintList.java
+++ /dev/null
@@ -1,979 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.LayoutActionBar;
-import com.android.tools.lint.client.api.Configuration;
-import com.android.tools.lint.client.api.IssueRegistry;
-import com.android.tools.lint.client.api.LintClient;
-import com.android.tools.lint.detector.api.Issue;
-import com.android.tools.lint.detector.api.Severity;
-import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.Multimap;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IMarkerDelta;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.ColumnPixelData;
-import org.eclipse.jface.viewers.ColumnWeightData;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.StyledCellLabelProvider;
-import org.eclipse.jface.viewers.StyledString;
-import org.eclipse.jface.viewers.TableLayout;
-import org.eclipse.jface.viewers.TreeNodeContentProvider;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.TreeViewerColumn;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerCell;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.BusyIndicator;
-import org.eclipse.swt.events.ControlEvent;
-import org.eclipse.swt.events.ControlListener;
-import org.eclipse.swt.events.PaintEvent;
-import org.eclipse.swt.events.PaintListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.events.TreeEvent;
-import org.eclipse.swt.events.TreeListener;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeColumn;
-import org.eclipse.swt.widgets.TreeItem;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.progress.IWorkbenchSiteProgressService;
-import org.eclipse.ui.progress.WorkbenchJob;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * A tree-table widget which shows a list of lint warnings for an underlying
- * {@link IResource} such as a file, a project, or a list of projects.
- */
-class LintList extends Composite implements IResourceChangeListener, ControlListener {
- private static final Object UPDATE_MARKERS_FAMILY = new Object();
-
- // For persistence:
- private static final String KEY_WIDTHS = "lintColWidth"; //$NON-NLS-1$
- private static final String KEY_VISIBLE = "lintColVisible"; //$NON-NLS-1$
- // Mapping SWT TreeColumns to LintColumns
- private static final String KEY_COLUMN = "lintColumn"; //$NON-NLS-1$
-
- private final IWorkbenchPartSite mSite;
- private final TreeViewer mTreeViewer;
- private final Tree mTree;
- private Set<String> mExpandedIds;
- private ContentProvider mContentProvider;
- private String mSelectedId;
- private List<? extends IResource> mResources;
- private Configuration mConfiguration;
- private final boolean mSingleFile;
- private int mErrorCount;
- private int mWarningCount;
- private final UpdateMarkersJob mUpdateMarkersJob = new UpdateMarkersJob();
- private final IssueRegistry mRegistry;
- private final IMemento mMemento;
- private final LintColumn mMessageColumn = new LintColumn.MessageColumn(this);
- private final LintColumn mLineColumn = new LintColumn.LineColumn(this);
- private final LintColumn[] mColumns = new LintColumn[] {
- mMessageColumn,
- new LintColumn.PriorityColumn(this),
- new LintColumn.CategoryColumn(this),
- new LintColumn.LocationColumn(this),
- new LintColumn.FileColumn(this),
- new LintColumn.PathColumn(this),
- mLineColumn
- };
- private LintColumn[] mVisibleColumns;
-
- LintList(IWorkbenchPartSite site, Composite parent, IMemento memento, boolean singleFile) {
- super(parent, SWT.NONE);
- mSingleFile = singleFile;
- mMemento = memento;
- mSite = site;
- mRegistry = EclipseLintClient.getRegistry();
-
- GridLayout gridLayout = new GridLayout(1, false);
- gridLayout.marginWidth = 0;
- gridLayout.marginHeight = 0;
- setLayout(gridLayout);
-
- mTreeViewer = new TreeViewer(this, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI);
- mTree = mTreeViewer.getTree();
- mTree.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
-
- createColumns();
- mTreeViewer.setComparator(new TableComparator());
- setSortIndicators();
-
- mContentProvider = new ContentProvider();
- mTreeViewer.setContentProvider(mContentProvider);
-
- mTree.setLinesVisible(true);
- mTree.setHeaderVisible(true);
- mTree.addControlListener(this);
-
- ResourcesPlugin.getWorkspace().addResourceChangeListener(
- this,
- IResourceChangeEvent.POST_CHANGE
- | IResourceChangeEvent.PRE_BUILD
- | IResourceChangeEvent.POST_BUILD);
-
- // Workaround for https://bugs.eclipse.org/341865
- mTree.addPaintListener(new PaintListener() {
- @Override
- public void paintControl(PaintEvent e) {
- mTreePainted = true;
- mTreeViewer.getTree().removePaintListener(this);
- }
- });
-
- // Remember the most recently selected id category such that we can
- // attempt to reselect it after a refresh
- mTree.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- List<IMarker> markers = getSelectedMarkers();
- if (markers.size() > 0) {
- mSelectedId = EclipseLintClient.getId(markers.get(0));
- }
- }
- });
- mTree.addTreeListener(new TreeListener() {
- @Override
- public void treeExpanded(TreeEvent e) {
- Object data = e.item.getData();
- if (data instanceof IMarker) {
- String id = EclipseLintClient.getId((IMarker) data);
- if (id != null) {
- if (mExpandedIds == null) {
- mExpandedIds = new HashSet<String>();
- }
- mExpandedIds.add(id);
- }
- }
- }
-
- @Override
- public void treeCollapsed(TreeEvent e) {
- if (mExpandedIds != null) {
- Object data = e.item.getData();
- if (data instanceof IMarker) {
- String id = EclipseLintClient.getId((IMarker) data);
- if (id != null) {
- mExpandedIds.remove(id);
- }
- }
- }
- }
- });
- }
-
- private boolean mTreePainted;
-
- private void updateColumnWidths() {
- Rectangle r = mTree.getClientArea();
- int availableWidth = r.width;
- // Add all available size to the first column
- for (int i = 1; i < mTree.getColumnCount(); i++) {
- TreeColumn column = mTree.getColumn(i);
- availableWidth -= column.getWidth();
- }
- if (availableWidth > 100) {
- mTree.getColumn(0).setWidth(availableWidth);
- }
- }
-
- public void setResources(List<? extends IResource> resources) {
- mResources = resources;
-
- mConfiguration = null;
- for (IResource resource : mResources) {
- IProject project = resource.getProject();
- if (project != null) {
- // For logging only
- LintClient client = new EclipseLintClient(null, null, null, false);
- mConfiguration = ProjectLintConfiguration.get(client, project, false);
- break;
- }
- }
- if (mConfiguration == null) {
- mConfiguration = GlobalLintConfiguration.get();
- }
-
- List<IMarker> markerList = getMarkers();
- mTreeViewer.setInput(markerList);
- if (mSingleFile) {
- expandAll();
- }
-
- // Selecting the first item isn't a good idea since it may not be the first
- // item shown in the table (since it does its own sorting), and furthermore we
- // may not have all the data yet; this is called when scanning begins, not when
- // it's done:
- //if (mTree.getItemCount() > 0) {
- // mTree.select(mTree.getItem(0));
- //}
-
- updateColumnWidths(); // in case mSingleFile changed
- }
-
- /** Select the first item */
- public void selectFirst() {
- if (mTree.getItemCount() > 0) {
- mTree.select(mTree.getItem(0));
- }
- }
-
- private List<IMarker> getMarkers() {
- mErrorCount = mWarningCount = 0;
- List<IMarker> markerList = new ArrayList<IMarker>();
- if (mResources != null) {
- for (IResource resource : mResources) {
- IMarker[] markers = EclipseLintClient.getMarkers(resource);
- for (IMarker marker : markers) {
- markerList.add(marker);
- int severity = marker.getAttribute(IMarker.SEVERITY, 0);
- if (severity == IMarker.SEVERITY_ERROR) {
- mErrorCount++;
- } else if (severity == IMarker.SEVERITY_WARNING) {
- mWarningCount++;
- }
- }
- }
-
- // No need to sort the marker list here; it will be sorted by the tree table model
- }
- return markerList;
- }
-
- public int getErrorCount() {
- return mErrorCount;
- }
-
- public int getWarningCount() {
- return mWarningCount;
- }
-
- @Override
- protected void checkSubclass() {
- // Disable the check that prevents subclassing of SWT components
- }
-
- public void addSelectionListener(SelectionListener listener) {
- mTree.addSelectionListener(listener);
- }
-
- public void refresh() {
- mTreeViewer.refresh();
- }
-
- public List<IMarker> getSelectedMarkers() {
- TreeItem[] selection = mTree.getSelection();
- List<IMarker> markers = new ArrayList<IMarker>(selection.length);
- for (TreeItem item : selection) {
- Object data = item.getData();
- if (data instanceof IMarker) {
- markers.add((IMarker) data);
- }
- }
-
- return markers;
- }
-
- @Override
- public void dispose() {
- cancelJobs();
- ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
- super.dispose();
- }
-
- private class ContentProvider extends TreeNodeContentProvider {
- private Map<Object, Object[]> mChildren;
- private Map<IMarker, Integer> mTypeCount;
- private IMarker[] mTopLevels;
-
- @Override
- public Object[] getElements(Object inputElement) {
- if (inputElement == null) {
- mTypeCount = null;
- return new IMarker[0];
- }
-
- @SuppressWarnings("unchecked")
- List<IMarker> list = (List<IMarker>) inputElement;
-
- // Partition the children such that at the top level we have one
- // marker of each type, and below we have all the duplicates of
- // each one of those errors. And for errors with multiple locations,
- // there is a third level.
- Multimap<String, IMarker> types = ArrayListMultimap.<String, IMarker>create(100, 20);
- for (IMarker marker : list) {
- String id = EclipseLintClient.getId(marker);
- types.put(id, marker);
- }
-
- Set<String> ids = types.keySet();
-
- mChildren = new HashMap<Object, Object[]>(ids.size());
- mTypeCount = new HashMap<IMarker, Integer>(ids.size());
-
- List<IMarker> topLevel = new ArrayList<IMarker>(ids.size());
- for (String id : ids) {
- Collection<IMarker> markers = types.get(id);
- int childCount = markers.size();
-
- // Must sort the list items in order to have a stable first item
- // (otherwise preserving expanded paths etc won't work)
- TableComparator sorter = getTableSorter();
- IMarker[] array = markers.toArray(new IMarker[markers.size()]);
- sorter.sort(mTreeViewer, array);
-
- IMarker topMarker = array[0];
- mTypeCount.put(topMarker, childCount);
- topLevel.add(topMarker);
-
- IMarker[] children = Arrays.copyOfRange(array, 1, array.length);
- mChildren.put(topMarker, children);
- }
-
- mTopLevels = topLevel.toArray(new IMarker[topLevel.size()]);
- return mTopLevels;
- }
-
- @Override
- public boolean hasChildren(Object element) {
- Object[] children = mChildren != null ? mChildren.get(element) : null;
- return children != null && children.length > 0;
- }
-
- @Override
- public Object[] getChildren(Object parentElement) {
- Object[] children = mChildren.get(parentElement);
- if (children != null) {
- return children;
- }
-
- return new Object[0];
- }
-
- @Override
- public Object getParent(Object element) {
- return null;
- }
-
- public int getCount(IMarker marker) {
- if (mTypeCount != null) {
- Integer count = mTypeCount.get(marker);
- if (count != null) {
- return count.intValue();
- }
- }
-
- return -1;
- }
-
- IMarker[] getTopMarkers() {
- return mTopLevels;
- }
- }
-
- private class LintColumnLabelProvider extends StyledCellLabelProvider {
- private LintColumn mColumn;
-
- LintColumnLabelProvider(LintColumn column) {
- mColumn = column;
- }
-
- @Override
- public void update(ViewerCell cell) {
- Object element = cell.getElement();
- cell.setImage(mColumn.getImage((IMarker) element));
- StyledString styledString = mColumn.getStyledValue((IMarker) element);
- if (styledString == null) {
- cell.setText(mColumn.getValue((IMarker) element));
- cell.setStyleRanges(null);
- } else {
- cell.setText(styledString.toString());
- cell.setStyleRanges(styledString.getStyleRanges());
- }
- super.update(cell);
- }
- }
-
- TreeViewer getTreeViewer() {
- return mTreeViewer;
- }
-
- Tree getTree() {
- return mTree;
- }
-
- // ---- Implements IResourceChangeListener ----
-
- @Override
- public void resourceChanged(IResourceChangeEvent event) {
- if (mResources == null) {
- return;
- }
- IMarkerDelta[] deltas = event.findMarkerDeltas(AdtConstants.MARKER_LINT, true);
- if (deltas.length > 0) {
- // Update immediately for POST_BUILD events, otherwise do an unconditional
- // update after 30 seconds. This matches the logic in Eclipse's ProblemView
- // (see the MarkerView class).
- if (event.getType() == IResourceChangeEvent.POST_BUILD) {
- cancelJobs();
- getProgressService().schedule(mUpdateMarkersJob, 100);
- } else {
- IWorkbenchSiteProgressService progressService = getProgressService();
- if (progressService == null) {
- mUpdateMarkersJob.schedule(30000);
- } else {
- getProgressService().schedule(mUpdateMarkersJob, 30000);
- }
- }
- }
- }
-
- // ---- Implements ControlListener ----
-
- @Override
- public void controlMoved(ControlEvent e) {
- }
-
- @Override
- public void controlResized(ControlEvent e) {
- updateColumnWidths();
- }
-
- // ---- Updating Markers ----
-
- private void cancelJobs() {
- mUpdateMarkersJob.cancel();
- }
-
- protected IWorkbenchSiteProgressService getProgressService() {
- if (mSite != null) {
- Object siteService = mSite.getAdapter(IWorkbenchSiteProgressService.class);
- if (siteService != null) {
- return (IWorkbenchSiteProgressService) siteService;
- }
- }
- return null;
- }
-
- private class UpdateMarkersJob extends WorkbenchJob {
- UpdateMarkersJob() {
- super("Updating Lint Markers");
- setSystem(true);
- }
-
- @Override
- public IStatus runInUIThread(IProgressMonitor monitor) {
- if (mTree.isDisposed()) {
- return Status.CANCEL_STATUS;
- }
-
- mTreeViewer.setInput(null);
- List<IMarker> markerList = getMarkers();
- if (markerList.size() == 0) {
- LayoutEditorDelegate delegate =
- LayoutEditorDelegate.fromEditor(AdtUtils.getActiveEditor());
- if (delegate != null) {
- GraphicalEditorPart g = delegate.getGraphicalEditor();
- assert g != null;
- LayoutActionBar bar = g == null ? null : g.getLayoutActionBar();
- assert bar != null;
- if (bar != null) {
- bar.updateErrorIndicator();
- }
- }
- }
- // Trigger selection update
- Event updateEvent = new Event();
- updateEvent.widget = mTree;
- mTree.notifyListeners(SWT.Selection, updateEvent);
- mTreeViewer.setInput(markerList);
- mTreeViewer.refresh();
-
- if (mExpandedIds != null) {
- List<IMarker> expanded = new ArrayList<IMarker>(mExpandedIds.size());
- IMarker[] topMarkers = mContentProvider.getTopMarkers();
- if (topMarkers != null) {
- for (IMarker marker : topMarkers) {
- String id = EclipseLintClient.getId(marker);
- if (id != null && mExpandedIds.contains(id)) {
- expanded.add(marker);
- }
- }
- }
- if (!expanded.isEmpty()) {
- mTreeViewer.setExpandedElements(expanded.toArray());
- }
- }
-
- if (mSelectedId != null) {
- IMarker[] topMarkers = mContentProvider.getTopMarkers();
- for (IMarker marker : topMarkers) {
- if (mSelectedId.equals(EclipseLintClient.getId(marker))) {
- mTreeViewer.setSelection(new StructuredSelection(marker), true /*reveal*/);
- break;
- }
- }
- }
-
- return Status.OK_STATUS;
- }
-
- @Override
- public boolean shouldRun() {
- // Do not run if the change came in before there is a viewer
- return PlatformUI.isWorkbenchRunning();
- }
-
- @Override
- public boolean belongsTo(Object family) {
- return UPDATE_MARKERS_FAMILY == family;
- }
- }
-
- /**
- * Returns the list of resources being shown in the list
- *
- * @return the list of resources being shown in this composite
- */
- public List<? extends IResource> getResources() {
- return mResources;
- }
-
- /** Expands all nodes */
- public void expandAll() {
- mTreeViewer.expandAll();
-
- if (mExpandedIds == null) {
- mExpandedIds = new HashSet<String>();
- }
- IMarker[] topMarkers = mContentProvider.getTopMarkers();
- if (topMarkers != null) {
- for (IMarker marker : topMarkers) {
- String id = EclipseLintClient.getId(marker);
- if (id != null) {
- mExpandedIds.add(id);
- }
- }
- }
- }
-
- /** Collapses all nodes */
- public void collapseAll() {
- mTreeViewer.collapseAll();
- mExpandedIds = null;
- }
-
- // ---- Column Persistence ----
-
- public void saveState(IMemento memento) {
- if (mSingleFile) {
- // Don't use persistence for single-file lists: this is a special mode of the
- // window where we show a hardcoded set of columns for a single file, deliberately
- // omitting the location column etc
- return;
- }
-
- IMemento columnEntry = memento.createChild(KEY_WIDTHS);
- LintColumn[] columns = new LintColumn[mTree.getColumnCount()];
- int[] positions = mTree.getColumnOrder();
- for (int i = 0; i < columns.length; i++) {
- TreeColumn treeColumn = mTree.getColumn(i);
- LintColumn column = (LintColumn) treeColumn.getData(KEY_COLUMN);
- // Workaround for TeeColumn.getWidth() returning 0 in some cases,
- // see https://bugs.eclipse.org/341865 for details.
- int width = getColumnWidth(column, mTreePainted);
- columnEntry.putInteger(getKey(treeColumn), width);
- columns[positions[i]] = column;
- }
-
- if (getVisibleColumns() != null) {
- IMemento visibleEntry = memento.createChild(KEY_VISIBLE);
- for (LintColumn column : getVisibleColumns()) {
- visibleEntry.putBoolean(getKey(column), true);
- }
- }
- }
-
- private void createColumns() {
- LintColumn[] columns = getVisibleColumns();
- TableLayout layout = new TableLayout();
-
- for (int i = 0; i < columns.length; i++) {
- LintColumn column = columns[i];
- TreeViewerColumn viewerColumn = null;
- TreeColumn treeColumn;
- viewerColumn = new TreeViewerColumn(mTreeViewer, SWT.NONE);
- treeColumn = viewerColumn.getColumn();
- treeColumn.setData(KEY_COLUMN, column);
- treeColumn.setResizable(true);
- treeColumn.addSelectionListener(getHeaderListener());
- if (!column.isLeftAligned()) {
- treeColumn.setAlignment(SWT.RIGHT);
- }
- viewerColumn.setLabelProvider(new LintColumnLabelProvider(column));
- treeColumn.setText(column.getColumnHeaderText());
- treeColumn.setImage(column.getColumnHeaderImage());
- IMemento columnWidths = null;
- if (mMemento != null && !mSingleFile) {
- columnWidths = mMemento.getChild(KEY_WIDTHS);
- }
- int columnWidth = getColumnWidth(column, false);
- if (columnWidths != null) {
- columnWidths.putInteger(getKey(column), columnWidth);
- }
- if (i == 0) {
- // The first column should use layout -weights- to get all the
- // remaining room
- layout.addColumnData(new ColumnWeightData(1, true));
- } else if (columnWidth < 0) {
- int defaultColumnWidth = column.getPreferredWidth();
- layout.addColumnData(new ColumnPixelData(defaultColumnWidth, true, true));
- } else {
- layout.addColumnData(new ColumnPixelData(columnWidth, true));
- }
- }
- mTreeViewer.getTree().setLayout(layout);
- mTree.layout(true);
- }
-
- private int getColumnWidth(LintColumn column, boolean getFromUi) {
- Tree tree = mTreeViewer.getTree();
- if (getFromUi) {
- TreeColumn[] columns = tree.getColumns();
- for (int i = 0; i < columns.length; i++) {
- if (column.equals(columns[i].getData(KEY_COLUMN))) {
- return columns[i].getWidth();
- }
- }
- }
- int preferredWidth = -1;
- if (mMemento != null && !mSingleFile) {
- IMemento columnWidths = mMemento.getChild(KEY_WIDTHS);
- if (columnWidths != null) {
- Integer value = columnWidths.getInteger(getKey(column));
- // Make sure we get a useful value
- if (value != null && value.intValue() >= 0)
- preferredWidth = value.intValue();
- }
- }
- if (preferredWidth <= 0) {
- preferredWidth = Math.max(column.getPreferredWidth(), 30);
- }
- return preferredWidth;
- }
-
- private static String getKey(TreeColumn treeColumn) {
- return getKey((LintColumn) treeColumn.getData(KEY_COLUMN));
- }
-
- private static String getKey(LintColumn column) {
- return column.getClass().getSimpleName();
- }
-
- private LintColumn[] getVisibleColumns() {
- if (mVisibleColumns == null) {
- if (mSingleFile) {
- // Special mode where we show just lint warnings for a single file:
- // use a hardcoded list of columns, not including path/location etc but
- // including line numbers (which are normally not shown by default).
- mVisibleColumns = new LintColumn[] {
- mMessageColumn, mLineColumn
- };
- } else {
- // Generate visible columns based on (a) previously saved window state,
- // and (b) default window visible states provided by the columns themselves
- List<LintColumn> list = new ArrayList<LintColumn>();
- IMemento visibleColumns = null;
- if (mMemento != null) {
- visibleColumns = mMemento.getChild(KEY_VISIBLE);
- }
- for (LintColumn column : mColumns) {
- if (visibleColumns != null) {
- Boolean b = visibleColumns.getBoolean(getKey(column));
- if (b != null && b.booleanValue()) {
- list.add(column);
- }
- } else if (column.visibleByDefault()) {
- list.add(column);
- }
- }
- if (!list.contains(mMessageColumn)) {
- list.add(0, mMessageColumn);
- }
- mVisibleColumns = list.toArray(new LintColumn[list.size()]);
- }
- }
-
- return mVisibleColumns;
- }
-
- int getCount(IMarker marker) {
- return mContentProvider.getCount(marker);
- }
-
- Issue getIssue(String id) {
- return mRegistry.getIssue(id);
- }
-
- Issue getIssue(IMarker marker) {
- String id = EclipseLintClient.getId(marker);
- return mRegistry.getIssue(id);
- }
-
- Severity getSeverity(Issue issue) {
- return mConfiguration.getSeverity(issue);
- }
-
- // ---- Choosing visible columns ----
-
- public void configureColumns() {
- ColumnDialog dialog = new ColumnDialog(getShell(), mColumns, getVisibleColumns());
- if (dialog.open() == Window.OK) {
- mVisibleColumns = dialog.getSelectedColumns();
- // Clear out columns: Must recreate to set the right label provider etc
- for (TreeColumn column : mTree.getColumns()) {
- column.dispose();
- }
- createColumns();
- mTreeViewer.setComparator(new TableComparator());
- setSortIndicators();
- mTreeViewer.refresh();
- }
- }
-
- // ---- Table Sorting ----
-
- private SelectionListener getHeaderListener() {
- return new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- final TreeColumn treeColumn = (TreeColumn) e.widget;
- final LintColumn column = (LintColumn) treeColumn.getData(KEY_COLUMN);
-
- try {
- IWorkbenchSiteProgressService progressService = getProgressService();
- if (progressService == null) {
- BusyIndicator.showWhile(getShell().getDisplay(), new Runnable() {
- @Override
- public void run() {
- resortTable(treeColumn, column,
- new NullProgressMonitor());
- }
- });
- } else {
- getProgressService().busyCursorWhile(new IRunnableWithProgress() {
- @Override
- public void run(IProgressMonitor monitor) {
- resortTable(treeColumn, column, monitor);
- }
- });
- }
- } catch (InvocationTargetException e1) {
- AdtPlugin.log(e1, null);
- } catch (InterruptedException e1) {
- return;
- }
- }
-
- private void resortTable(final TreeColumn treeColumn, LintColumn column,
- IProgressMonitor monitor) {
- TableComparator sorter = getTableSorter();
- monitor.beginTask("Sorting", 100);
- monitor.worked(10);
- if (column.equals(sorter.getTopColumn())) {
- sorter.reverseTopPriority();
- } else {
- sorter.setTopPriority(column);
- }
- monitor.worked(15);
- PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- mTreeViewer.refresh();
- updateDirectionIndicator(treeColumn);
- }
- });
- monitor.done();
- }
- };
- }
-
- private void setSortIndicators() {
- LintColumn top = getTableSorter().getTopColumn();
- TreeColumn[] columns = mTreeViewer.getTree().getColumns();
- for (int i = 0; i < columns.length; i++) {
- TreeColumn column = columns[i];
- if (column.getData(KEY_COLUMN).equals(top)) {
- updateDirectionIndicator(column);
- return;
- }
- }
- }
-
- private void updateDirectionIndicator(TreeColumn column) {
- Tree tree = mTreeViewer.getTree();
- tree.setSortColumn(column);
- if (getTableSorter().isAscending()) {
- tree.setSortDirection(SWT.UP);
- } else {
- tree.setSortDirection(SWT.DOWN);
- }
- }
-
- private TableComparator getTableSorter() {
- return (TableComparator) mTreeViewer.getComparator();
- }
-
- /** Comparator used to sort the {@link LintList} tree.
- * <p>
- * This code is simplified from similar code in
- * org.eclipse.ui.views.markers.internal.TableComparator
- */
- private class TableComparator extends ViewerComparator {
- private int[] mPriorities;
- private boolean[] mDirections;
- private int[] mDefaultPriorities;
- private boolean[] mDefaultDirections;
-
- private TableComparator() {
- int[] defaultPriorities = new int[mColumns.length];
- for (int i = 0; i < defaultPriorities.length; i++) {
- defaultPriorities[i] = i;
- }
- mPriorities = defaultPriorities;
-
- boolean[] directions = new boolean[mColumns.length];
- for (int i = 0; i < directions.length; i++) {
- directions[i] = mColumns[i].isAscending();
- }
- mDirections = directions;
-
- mDefaultPriorities = new int[defaultPriorities.length];
- System.arraycopy(defaultPriorities, 0, this.mDefaultPriorities, 0,
- defaultPriorities.length);
- mDefaultDirections = new boolean[directions.length];
- System.arraycopy(directions, 0, this.mDefaultDirections, 0, directions.length);
- }
-
- private void resetState() {
- System.arraycopy(mDefaultPriorities, 0, mPriorities, 0, mPriorities.length);
- System.arraycopy(mDefaultDirections, 0, mDirections, 0, mDirections.length);
- }
-
- private void reverseTopPriority() {
- mDirections[mPriorities[0]] = !mDirections[mPriorities[0]];
- }
-
- private void setTopPriority(LintColumn property) {
- for (int i = 0; i < mColumns.length; i++) {
- if (mColumns[i].equals(property)) {
- setTopPriority(i);
- return;
- }
- }
- }
-
- private void setTopPriority(int priority) {
- if (priority < 0 || priority >= mPriorities.length) {
- return;
- }
- int index = -1;
- for (int i = 0; i < mPriorities.length; i++) {
- if (mPriorities[i] == priority) {
- index = i;
- }
- }
- if (index == -1) {
- resetState();
- return;
- }
- // shift the array
- for (int i = index; i > 0; i--) {
- mPriorities[i] = mPriorities[i - 1];
- }
- mPriorities[0] = priority;
- mDirections[priority] = mDefaultDirections[priority];
- }
-
- private boolean isAscending() {
- return mDirections[mPriorities[0]];
- }
-
- private int getTopPriority() {
- return mPriorities[0];
- }
-
- private LintColumn getTopColumn() {
- return mColumns[getTopPriority()];
- }
-
- @Override
- public int compare(Viewer viewer, Object e1, Object e2) {
- return compare((IMarker) e1, (IMarker) e2, 0, true);
- }
-
- private int compare(IMarker marker1, IMarker marker2, int depth,
- boolean continueSearching) {
- if (depth >= mPriorities.length) {
- return 0;
- }
- int column = mPriorities[depth];
- LintColumn property = mColumns[column];
- int result = property.compare(marker1, marker2);
- if (result == 0 && continueSearching) {
- return compare(marker1, marker2, depth + 1, continueSearching);
- }
- return result * (mDirections[column] ? 1 : -1);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintListDialog.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintListDialog.java
deleted file mode 100644
index f88c3772c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintListDialog.java
+++ /dev/null
@@ -1,303 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.TitleAreaDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-@SuppressWarnings("restriction") // WST DOM access
-class LintListDialog extends TitleAreaDialog implements SelectionListener {
- private static final String PROJECT_LOGO_LARGE = "android-64"; //$NON-NLS-1$
- private final IFile mFile;
- private final IEditorPart mEditor;
- private Button mFixButton;
- private Button mIgnoreButton;
- private Button mIgnoreAllButton;
- private Button mShowButton;
- private Text mDetailsText;
- private Button mIgnoreTypeButton;
- private LintList mList;
-
- LintListDialog(
- @NonNull Shell parentShell,
- @NonNull IFile file,
- @Nullable IEditorPart editor) {
- super(parentShell);
- mFile = file;
- mEditor = editor;
- setHelpAvailable(false);
- }
-
- @Override
- protected void setShellStyle(int newShellStyle) {
- // Allow resize
- super.setShellStyle(newShellStyle | SWT.TITLE | SWT.MODELESS | SWT.RESIZE);
- }
-
- @Override
- public boolean close() {
- mList.dispose();
- return super.close();
- }
-
- @Override
- protected Control createContents(Composite parent) {
- Control contents = super.createContents(parent);
- setTitle("Lint Warnings in Layout");
- setMessage("Lint Errors found for the current layout:");
- setTitleImage(IconFactory.getInstance().getIcon(PROJECT_LOGO_LARGE));
-
- return contents;
- }
-
- @SuppressWarnings("unused") // SWT constructors have side effects, they are not unused
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite area = (Composite) super.createDialogArea(parent);
- Composite container = new Composite(area, SWT.NONE);
- container.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- container.setLayout(new GridLayout(2, false));
- IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
- IWorkbenchPartSite site = null;
- if (page.getActivePart() != null) {
- site = page.getActivePart().getSite();
- }
-
- mList = new LintList(site, container, null /*memento*/, true /*singleFile*/);
- mList.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 6));
-
- mShowButton = new Button(container, SWT.NONE);
- mShowButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
- mShowButton.setText("Show");
- mShowButton.setToolTipText("Opens the editor to reveal the XML with the issue");
- mShowButton.addSelectionListener(this);
-
- mFixButton = new Button(container, SWT.NONE);
- mFixButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
- mFixButton.setText("Fix");
- mFixButton.setToolTipText("Automatically corrects the problem, if possible");
- mFixButton.setEnabled(false);
- mFixButton.addSelectionListener(this);
-
- mIgnoreButton = new Button(container, SWT.NONE);
- mIgnoreButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
- mIgnoreButton.setText("Suppress Issue");
- mIgnoreButton.setToolTipText("Adds a special attribute in the layout to suppress this specific warning");
- mIgnoreButton.addSelectionListener(this);
-
- mIgnoreAllButton = new Button(container, SWT.NONE);
- mIgnoreAllButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
- mIgnoreAllButton.setText("Suppress in Layout");
- mIgnoreAllButton.setEnabled(mEditor instanceof AndroidXmlEditor);
- mIgnoreAllButton.setToolTipText("Adds an attribute on the root element to suppress all issues of this type in this layout");
- mIgnoreAllButton.addSelectionListener(this);
-
- mIgnoreTypeButton = new Button(container, SWT.NONE);
- mIgnoreTypeButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
- mIgnoreTypeButton.setText("Disable Issue Type");
- mIgnoreTypeButton.setToolTipText("Turns off checking for this type of error everywhere");
- mIgnoreTypeButton.addSelectionListener(this);
-
- new Label(container, SWT.NONE);
-
- mDetailsText = new Text(container, SWT.BORDER | SWT.READ_ONLY | SWT.WRAP
- | SWT.V_SCROLL | SWT.MULTI);
- Display display = parent.getDisplay();
- mDetailsText.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
- mDetailsText.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
- GridData gdText = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
- gdText.heightHint = 80;
- mDetailsText.setLayoutData(gdText);
-
- new Label(container, SWT.NONE);
-
- mList.addSelectionListener(this);
-
- mList.setResources(Collections.<IResource>singletonList(mFile));
- mList.selectFirst();
- if (mList.getSelectedMarkers().size() > 0) {
- updateSelectionState();
- }
-
- return area;
- }
-
- /**
- * Create contents of the button bar.
- */
- @Override
- protected void createButtonsForButtonBar(Composite parent) {
- createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true);
- }
-
- /**
- * Return the initial size of the dialog.
- */
- @Override
- protected Point getInitialSize() {
- return new Point(600, 400);
- }
-
- private void selectMarker(IMarker marker) {
- if (marker == null) {
- mDetailsText.setText(""); //$NON-NLS-1$
- return;
- }
-
- mDetailsText.setText(EclipseLintClient.describe(marker));
- }
-
- // ---- Implements SelectionListener ----
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- Object source = e.getSource();
- if (source == mList.getTreeViewer().getControl()) {
- // Enable/disable buttons
- updateSelectionState();
- } else if (source == mShowButton) {
- List<IMarker> selection = mList.getSelectedMarkers();
- if (selection.size() > 0) {
- EclipseLintClient.showMarker(selection.get(0));
- }
- } else if (source == mFixButton) {
- List<IMarker> selection = mList.getSelectedMarkers();
- for (IMarker marker : selection) {
- List<LintFix> fixes = LintFix.getFixes(EclipseLintClient.getId(marker), marker);
- if (fixes == null) {
- continue;
- }
- LintFix fix = fixes.get(0);
- IEditorPart editor = AdtUtils.getActiveEditor();
- if (editor instanceof AndroidXmlEditor) {
- IStructuredDocument doc = ((AndroidXmlEditor) editor).getStructuredDocument();
- fix.apply(doc);
- if (fix.needsFocus()) {
- close();
- }
- } else {
- AdtPlugin.log(IStatus.ERROR, "Did not find associated editor to apply fix");
- }
- }
- } else if (source == mIgnoreTypeButton) {
- for (IMarker marker : mList.getSelectedMarkers()) {
- String id = EclipseLintClient.getId(marker);
- if (id != null) {
- LintFixGenerator.suppressDetector(id, true, mFile, true /*all*/);
- }
- }
- } else if (source == mIgnoreButton) {
- for (IMarker marker : mList.getSelectedMarkers()) {
- LintFixGenerator.addSuppressAnnotation(marker);
- }
- } else if (source == mIgnoreAllButton) {
- Set<String> ids = new HashSet<String>();
- for (IMarker marker : mList.getSelectedMarkers()) {
- String id = EclipseLintClient.getId(marker);
- if (id != null && !ids.contains(id)) {
- ids.add(id);
- if (mEditor instanceof AndroidXmlEditor) {
- AndroidXmlEditor editor = (AndroidXmlEditor) mEditor;
- AddSuppressAttribute fix = AddSuppressAttribute.createFixForAll(editor,
- marker, id);
- if (fix != null) {
- IStructuredDocument document = editor.getStructuredDocument();
- fix.apply(document);
- }
- }
- }
- }
- mList.refresh();
- }
- }
-
- private void updateSelectionState() {
- List<IMarker> selection = mList.getSelectedMarkers();
-
- if (selection.size() == 1) {
- selectMarker(selection.get(0));
- } else {
- selectMarker(null);
- }
-
- boolean canFix = selection.size() > 0;
- for (IMarker marker : selection) {
- if (!LintFix.hasFix(EclipseLintClient.getId(marker))) {
- canFix = false;
- break;
- }
-
- // Some fixes cannot be run in bulk
- if (selection.size() > 1) {
- List<LintFix> fixes = LintFix.getFixes(EclipseLintClient.getId(marker), marker);
- if (fixes == null || !fixes.get(0).isBulkCapable()) {
- canFix = false;
- break;
- }
- }
- }
-
- mFixButton.setEnabled(canFix);
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- Object source = e.getSource();
- if (source == mList.getTreeViewer().getControl()) {
- // Jump to editor
- List<IMarker> selection = mList.getSelectedMarkers();
- if (selection.size() > 0) {
- EclipseLintClient.showMarker(selection.get(0));
- close();
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintViewPart.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintViewPart.java
deleted file mode 100644
index 90b956e32..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/LintViewPart.java
+++ /dev/null
@@ -1,657 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import static com.android.SdkConstants.DOT_JAVA;
-import static com.android.SdkConstants.DOT_XML;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.preferences.LintPreferencePage;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.tools.lint.detector.api.LintUtils;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.jobs.IJobChangeEvent;
-import org.eclipse.core.runtime.jobs.IJobChangeListener;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IStatusLineManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.preference.IPreferenceNode;
-import org.eclipse.jface.preference.PreferenceDialog;
-import org.eclipse.jface.preference.PreferenceManager;
-import org.eclipse.jface.preference.PreferenceNode;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.SashForm;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IMemento;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.IViewSite;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.editors.text.TextFileDocumentProvider;
-import org.eclipse.ui.part.ViewPart;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * Eclipse View which shows lint warnings for the current project
- */
-public class LintViewPart extends ViewPart implements SelectionListener, IJobChangeListener {
- /** The view id for this view part */
- public static final String ID = "com.android.ide.eclipse.adt.internal.lint.LintViewPart"; //$NON-NLS-1$
- private static final String QUICKFIX_DISABLED_ICON = "quickfix-disabled"; //$NON-NLS-1$
- private static final String QUICKFIX_ICON = "quickfix"; //$NON-NLS-1$
- private static final String REFRESH_ICON = "refresh"; //$NON-NLS-1$
- private static final String EXPAND_DISABLED_ICON = "expandall-disabled"; //$NON-NLS-1$
- private static final String EXPAND_ICON = "expandall"; //$NON-NLS-1$
- private static final String COLUMNS_ICON = "columns"; //$NON-NLS-1$
- private static final String OPTIONS_ICON = "options"; //$NON-NLS-1$
- private static final String IGNORE_THIS_ICON = "ignore-this"; //$NON-NLS-1$
- private static final String IGNORE_THIS_DISABLED_ICON = "ignore-this-disabled"; //$NON-NLS-1$
- private static final String IGNORE_FILE_ICON = "ignore-file"; //$NON-NLS-1$
- private static final String IGNORE_FILE_DISABLED_ICON = "ignore-file-disabled"; //$NON-NLS-1$
- private static final String IGNORE_PRJ_ICON = "ignore-project"; //$NON-NLS-1$
- private static final String IGNORE_PRJ_DISABLED_ICON = "ignore-project-disabled"; //$NON-NLS-1$
- private static final String IGNORE_ALL_ICON = "ignore-all"; //$NON-NLS-1$
- private static final String IGNORE_ALL_DISABLED_ICON = "ignore-all-disabled"; //$NON-NLS-1$
- private IMemento mMemento;
- private LintList mLintView;
- private Text mDetailsText;
- private Label mErrorLabel;
- private SashForm mSashForm;
- private Action mFixAction;
- private Action mRemoveAction;
- private Action mIgnoreAction;
- private Action mAlwaysIgnoreAction;
- private Action mIgnoreFileAction;
- private Action mIgnoreProjectAction;
- private Action mRemoveAllAction;
- private Action mRefreshAction;
- private Action mExpandAll;
- private Action mCollapseAll;
- private Action mConfigureColumns;
- private Action mOptions;
-
- /**
- * Initial projects to show: this field is only briefly not null during the
- * construction initiated by {@link #show(List)}
- */
- private static List<? extends IResource> sInitialResources;
-
- /**
- * Constructs a new {@link LintViewPart}
- */
- public LintViewPart() {
- }
-
- @Override
- public void init(IViewSite site, IMemento memento) throws PartInitException {
- super.init(site, memento);
- mMemento = memento;
- }
-
- @Override
- public void saveState(IMemento memento) {
- super.saveState(memento);
-
- mLintView.saveState(memento);
- }
-
- @Override
- public void dispose() {
- if (mLintView != null) {
- mLintView.dispose();
- mLintView = null;
- }
- super.dispose();
- }
-
- @Override
- public void createPartControl(Composite parent) {
- GridLayout gridLayout = new GridLayout(1, false);
- gridLayout.verticalSpacing = 0;
- gridLayout.marginWidth = 0;
- gridLayout.marginHeight = 0;
- parent.setLayout(gridLayout);
-
- mErrorLabel = new Label(parent, SWT.NONE);
- mErrorLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
-
- mSashForm = new SashForm(parent, SWT.NONE);
- mSashForm.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
- mLintView = new LintList(getSite(), mSashForm, mMemento, false /*singleFile*/);
-
- mDetailsText = new Text(mSashForm,
- SWT.BORDER | SWT.READ_ONLY | SWT.WRAP | SWT.V_SCROLL | SWT.MULTI);
- Display display = parent.getDisplay();
- mDetailsText.setBackground(display.getSystemColor(SWT.COLOR_INFO_BACKGROUND));
- mDetailsText.setForeground(display.getSystemColor(SWT.COLOR_INFO_FOREGROUND));
-
- mLintView.addSelectionListener(this);
- mSashForm.setWeights(new int[] {8, 2});
-
- createActions();
- initializeToolBar();
-
- // If there are currently running jobs, listen for them such that we can update the
- // button state
- refreshStopIcon();
-
- if (sInitialResources != null) {
- mLintView.setResources(sInitialResources);
- sInitialResources = null;
- } else {
- // No supplied context: show lint warnings for all projects
- IJavaProject[] androidProjects = BaseProjectHelper.getAndroidProjects(null);
- if (androidProjects.length > 0) {
- List<IResource> projects = new ArrayList<IResource>();
- for (IJavaProject project : androidProjects) {
- projects.add(project.getProject());
- }
- mLintView.setResources(projects);
- }
- }
-
- updateIssueCount();
- }
-
- /**
- * Create the actions.
- */
- private void createActions() {
- ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages();
- IconFactory iconFactory = IconFactory.getInstance();
- mFixAction = new LintViewAction("Fix", ACTION_FIX,
- iconFactory.getImageDescriptor(QUICKFIX_ICON),
- iconFactory.getImageDescriptor(QUICKFIX_DISABLED_ICON));
-
- mIgnoreAction = new LintViewAction("Suppress this error with an annotation/attribute",
- ACTION_IGNORE_THIS,
- iconFactory.getImageDescriptor(IGNORE_THIS_ICON),
- iconFactory.getImageDescriptor(IGNORE_THIS_DISABLED_ICON));
- mIgnoreFileAction = new LintViewAction("Ignore in this file", ACTION_IGNORE_FILE,
- iconFactory.getImageDescriptor(IGNORE_FILE_ICON),
- iconFactory.getImageDescriptor(IGNORE_FILE_DISABLED_ICON));
- mIgnoreProjectAction = new LintViewAction("Ignore in this project", ACTION_IGNORE_TYPE,
- iconFactory.getImageDescriptor(IGNORE_PRJ_ICON),
- iconFactory.getImageDescriptor(IGNORE_PRJ_DISABLED_ICON));
- mAlwaysIgnoreAction = new LintViewAction("Always Ignore", ACTION_IGNORE_ALL,
- iconFactory.getImageDescriptor(IGNORE_ALL_ICON),
- iconFactory.getImageDescriptor(IGNORE_ALL_DISABLED_ICON));
-
- mRemoveAction = new LintViewAction("Remove", ACTION_REMOVE,
- sharedImages.getImageDescriptor(ISharedImages.IMG_ELCL_REMOVE),
- sharedImages.getImageDescriptor(ISharedImages.IMG_ELCL_REMOVE_DISABLED));
- mRemoveAllAction = new LintViewAction("Remove All", ACTION_REMOVE_ALL,
- sharedImages.getImageDescriptor(ISharedImages.IMG_ELCL_REMOVEALL),
- sharedImages.getImageDescriptor(ISharedImages.IMG_ELCL_REMOVEALL_DISABLED));
- mRefreshAction = new LintViewAction("Refresh (& Save Files)", ACTION_REFRESH,
- iconFactory.getImageDescriptor(REFRESH_ICON), null);
- mRemoveAllAction.setEnabled(true);
- mCollapseAll = new LintViewAction("Collapse All", ACTION_COLLAPSE,
- sharedImages.getImageDescriptor(ISharedImages.IMG_ELCL_COLLAPSEALL),
- sharedImages.getImageDescriptor(ISharedImages.IMG_ELCL_COLLAPSEALL_DISABLED));
- mCollapseAll.setEnabled(true);
- mExpandAll = new LintViewAction("Expand All", ACTION_EXPAND,
- iconFactory.getImageDescriptor(EXPAND_ICON),
- iconFactory.getImageDescriptor(EXPAND_DISABLED_ICON));
- mExpandAll.setEnabled(true);
-
- mConfigureColumns = new LintViewAction("Configure Columns...", ACTION_COLUMNS,
- iconFactory.getImageDescriptor(COLUMNS_ICON),
- null);
-
- mOptions = new LintViewAction("Options...", ACTION_OPTIONS,
- iconFactory.getImageDescriptor(OPTIONS_ICON),
- null);
-
- enableActions(Collections.<IMarker>emptyList(), false /*updateWidgets*/);
- }
-
- /**
- * Initialize the toolbar.
- */
- private void initializeToolBar() {
- IToolBarManager toolbarManager = getViewSite().getActionBars().getToolBarManager();
- toolbarManager.add(mRefreshAction);
- toolbarManager.add(mFixAction);
- toolbarManager.add(mIgnoreAction);
- toolbarManager.add(mIgnoreFileAction);
- toolbarManager.add(mIgnoreProjectAction);
- toolbarManager.add(mAlwaysIgnoreAction);
- toolbarManager.add(new Separator());
- toolbarManager.add(mRemoveAction);
- toolbarManager.add(mRemoveAllAction);
- toolbarManager.add(new Separator());
- toolbarManager.add(mExpandAll);
- toolbarManager.add(mCollapseAll);
- toolbarManager.add(mConfigureColumns);
- toolbarManager.add(mOptions);
- }
-
- @Override
- public void setFocus() {
- mLintView.setFocus();
- }
-
- /**
- * Sets the resource associated with the lint view
- *
- * @param resources the associated resources
- */
- public void setResources(List<? extends IResource> resources) {
- mLintView.setResources(resources);
-
- // Refresh the stop/refresh icon status
- refreshStopIcon();
- }
-
- private void refreshStopIcon() {
- Job[] currentJobs = LintJob.getCurrentJobs();
- if (currentJobs.length > 0) {
- ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages();
- mRefreshAction.setImageDescriptor(sharedImages.getImageDescriptor(
- ISharedImages.IMG_ELCL_STOP));
- for (Job job : currentJobs) {
- job.addJobChangeListener(this);
- }
- } else {
- mRefreshAction.setImageDescriptor(
- IconFactory.getInstance().getImageDescriptor(REFRESH_ICON));
-
- }
- }
-
- // ---- Implements SelectionListener ----
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- List<IMarker> markers = mLintView.getSelectedMarkers();
- if (markers.size() != 1) {
- mDetailsText.setText(""); //$NON-NLS-1$
- } else {
- mDetailsText.setText(EclipseLintClient.describe(markers.get(0)));
- }
-
- IStatusLineManager status = getViewSite().getActionBars().getStatusLineManager();
- status.setMessage(mDetailsText.getText());
-
- updateIssueCount();
-
- enableActions(markers, true /* updateWidgets */);
- }
-
- private void enableActions(List<IMarker> markers, boolean updateWidgets) {
- // Update enabled state of actions
- boolean hasSelection = markers.size() > 0;
- boolean canFix = hasSelection;
- for (IMarker marker : markers) {
- if (!LintFix.hasFix(EclipseLintClient.getId(marker))) {
- canFix = false;
- break;
- }
-
- // Some fixes cannot be run in bulk
- if (markers.size() > 1) {
- List<LintFix> fixes = LintFix.getFixes(EclipseLintClient.getId(marker), marker);
- if (fixes == null || !fixes.get(0).isBulkCapable()) {
- canFix = false;
- break;
- }
- }
- }
-
- boolean haveFile = false;
- boolean isJavaOrXml = true;
- for (IMarker marker : markers) {
- IResource resource = marker.getResource();
- if (resource instanceof IFile || resource instanceof IFolder) {
- haveFile = true;
- String name = resource.getName();
- if (!LintUtils.endsWith(name, DOT_XML) && !LintUtils.endsWith(name, DOT_JAVA)) {
- isJavaOrXml = false;
- }
- break;
- }
- }
-
- mFixAction.setEnabled(canFix);
- mIgnoreAction.setEnabled(hasSelection && haveFile && isJavaOrXml);
- mIgnoreFileAction.setEnabled(hasSelection && haveFile);
- mIgnoreProjectAction.setEnabled(hasSelection);
- mAlwaysIgnoreAction.setEnabled(hasSelection);
- mRemoveAction.setEnabled(hasSelection);
-
- if (updateWidgets) {
- getViewSite().getActionBars().getToolBarManager().update(false);
- }
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- Object source = e.getSource();
- if (source == mLintView.getTreeViewer().getControl()) {
- // Jump to editor
- List<IMarker> selection = mLintView.getSelectedMarkers();
- if (selection.size() > 0) {
- EclipseLintClient.showMarker(selection.get(0));
- }
- }
- }
-
- // --- Implements IJobChangeListener ----
-
- @Override
- public void done(IJobChangeEvent event) {
- mRefreshAction.setImageDescriptor(
- IconFactory.getInstance().getImageDescriptor(REFRESH_ICON));
-
- if (!mLintView.isDisposed()) {
- mLintView.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- if (!mLintView.isDisposed()) {
- updateIssueCount();
- }
- }
- });
- }
- }
-
- private void updateIssueCount() {
- int errors = mLintView.getErrorCount();
- int warnings = mLintView.getWarningCount();
- mErrorLabel.setText(String.format("%1$d errors, %2$d warnings", errors, warnings));
- }
-
- @Override
- public void aboutToRun(IJobChangeEvent event) {
- }
-
- @Override
- public void awake(IJobChangeEvent event) {
- }
-
- @Override
- public void running(IJobChangeEvent event) {
- }
-
- @Override
- public void scheduled(IJobChangeEvent event) {
- }
-
- @Override
- public void sleeping(IJobChangeEvent event) {
- }
-
- // ---- Actions ----
-
- private static final int ACTION_REFRESH = 1;
- private static final int ACTION_FIX = 2;
- private static final int ACTION_IGNORE_THIS = 3;
- private static final int ACTION_IGNORE_FILE = 4;
- private static final int ACTION_IGNORE_TYPE = 5;
- private static final int ACTION_IGNORE_ALL = 6;
- private static final int ACTION_REMOVE = 7;
- private static final int ACTION_REMOVE_ALL = 8;
- private static final int ACTION_COLLAPSE = 9;
- private static final int ACTION_EXPAND = 10;
- private static final int ACTION_COLUMNS = 11;
- private static final int ACTION_OPTIONS = 12;
-
- private class LintViewAction extends Action {
-
- private final int mAction;
-
- private LintViewAction(String label, int action,
- ImageDescriptor imageDesc, ImageDescriptor disabledImageDesc) {
- super(label);
- mAction = action;
- setImageDescriptor(imageDesc);
- if (disabledImageDesc != null) {
- setDisabledImageDescriptor(disabledImageDesc);
- }
- }
-
- @Override
- public void run() {
- switch (mAction) {
- case ACTION_REFRESH: {
- IWorkbench workbench = PlatformUI.getWorkbench();
- if (workbench != null) {
- workbench.saveAllEditors(false /*confirm*/);
- }
-
- Job[] jobs = LintJob.getCurrentJobs();
- if (jobs.length > 0) {
- EclipseLintRunner.cancelCurrentJobs(false);
- } else {
- List<? extends IResource> resources = mLintView.getResources();
- if (resources == null) {
- return;
- }
- Job job = EclipseLintRunner.startLint(resources, null, null,
- false /*fatalOnly*/, false /*show*/);
- if (job != null && workbench != null) {
- job.addJobChangeListener(LintViewPart.this);
- ISharedImages sharedImages = workbench.getSharedImages();
- setImageDescriptor(sharedImages.getImageDescriptor(
- ISharedImages.IMG_ELCL_STOP));
- }
- }
- break;
- }
- case ACTION_FIX: {
- List<IMarker> markers = mLintView.getSelectedMarkers();
- for (IMarker marker : markers) {
- List<LintFix> fixes = LintFix.getFixes(EclipseLintClient.getId(marker),
- marker);
- if (fixes == null) {
- continue;
- }
- LintFix fix = fixes.get(0);
- IResource resource = marker.getResource();
- if (fix.needsFocus() && resource instanceof IFile) {
- IRegion region = null;
- try {
- int start = marker.getAttribute(IMarker.CHAR_START, -1);
- int end = marker.getAttribute(IMarker.CHAR_END, -1);
- if (start != -1) {
- region = new Region(start, end - start);
- }
- AdtPlugin.openFile((IFile) resource, region);
- } catch (PartInitException e) {
- AdtPlugin.log(e, "Can't open file %1$s", resource);
- }
- }
- IDocumentProvider provider = new TextFileDocumentProvider();
- try {
- provider.connect(resource);
- IDocument document = provider.getDocument(resource);
- if (document != null) {
- fix.apply(document);
- if (!fix.needsFocus()) {
- provider.saveDocument(new NullProgressMonitor(), resource,
- document, true /*overwrite*/);
- }
- }
- } catch (Exception e) {
- AdtPlugin.log(e, "Did not find associated editor to apply fix: %1$s",
- resource.getName());
- } finally {
- provider.disconnect(resource);
- }
- }
- break;
- }
- case ACTION_REMOVE: {
- for (IMarker marker : mLintView.getSelectedMarkers()) {
- try {
- marker.delete();
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- }
- break;
- }
- case ACTION_REMOVE_ALL: {
- List<? extends IResource> resources = mLintView.getResources();
- if (resources != null) {
- for (IResource resource : resources) {
- EclipseLintClient.clearMarkers(resource);
- }
- }
- break;
- }
- case ACTION_IGNORE_ALL:
- assert false;
- break;
- case ACTION_IGNORE_TYPE:
- case ACTION_IGNORE_FILE: {
- boolean ignoreInFile = mAction == ACTION_IGNORE_FILE;
- for (IMarker marker : mLintView.getSelectedMarkers()) {
- String id = EclipseLintClient.getId(marker);
- if (id != null) {
- IResource resource = marker.getResource();
- LintFixGenerator.suppressDetector(id, true,
- ignoreInFile ? resource : resource.getProject(),
- ignoreInFile);
- }
- }
- break;
- }
- case ACTION_IGNORE_THIS: {
- for (IMarker marker : mLintView.getSelectedMarkers()) {
- LintFixGenerator.addSuppressAnnotation(marker);
- }
- break;
- }
- case ACTION_COLLAPSE: {
- mLintView.collapseAll();
- break;
- }
- case ACTION_EXPAND: {
- mLintView.expandAll();
- break;
- }
- case ACTION_COLUMNS: {
- mLintView.configureColumns();
- break;
- }
- case ACTION_OPTIONS: {
- PreferenceManager manager = new PreferenceManager();
-
- LintPreferencePage page = new LintPreferencePage();
- String title = "Default/Global Settings";
- page.setTitle(title);
- IPreferenceNode node = new PreferenceNode(title, page);
- manager.addToRoot(node);
-
-
- List<? extends IResource> resources = mLintView.getResources();
- if (resources != null) {
- Set<IProject> projects = new HashSet<IProject>();
- for (IResource resource : resources) {
- projects.add(resource.getProject());
- }
- if (projects.size() > 0) {
- for (IProject project : projects) {
- page = new LintPreferencePage();
- page.setTitle(String.format("Settings for %1$s",
- project.getName()));
- page.setElement(project);
- node = new PreferenceNode(project.getName(), page);
- manager.addToRoot(node);
- }
- }
- }
-
- Shell shell = LintViewPart.this.getSite().getShell();
- PreferenceDialog dialog = new PreferenceDialog(shell, manager);
- dialog.create();
- dialog.setSelectedNode(title);
- dialog.open();
- break;
- }
- default:
- assert false : mAction;
- }
- updateIssueCount();
- }
- }
-
- /**
- * Shows or reconfigures the LintView to show the lint warnings for the
- * given project
- *
- * @param projects the projects to show lint warnings for
- */
- public static void show(List<? extends IResource> projects) {
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- if (window != null) {
- IWorkbenchPage page = window.getActivePage();
- if (page != null) {
- try {
- // Pass initial project context via static field read by constructor
- sInitialResources = projects;
- IViewPart view = page.showView(LintViewPart.ID, null,
- IWorkbenchPage.VIEW_ACTIVATE);
- if (sInitialResources != null && view instanceof LintViewPart) {
- // The view must be showing already since the constructor was not
- // run, so reconfigure the view instead
- LintViewPart lintView = (LintViewPart) view;
- lintView.setResources(projects);
- }
- } catch (PartInitException e) {
- AdtPlugin.log(e, "Cannot open Lint View");
- } finally {
- sInitialResources = null;
- }
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/ObsoleteLayoutParamsFix.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/ObsoleteLayoutParamsFix.java
deleted file mode 100644
index 9db551733..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/ObsoleteLayoutParamsFix.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-
-@SuppressWarnings("restriction") // DOM model
-final class ObsoleteLayoutParamsFix extends DocumentFix {
- private ObsoleteLayoutParamsFix(String id, IMarker marker) {
- super(id, marker);
- }
-
- @Override
- public boolean needsFocus() {
- return false;
- }
-
- @Override
- public boolean isCancelable() {
- return false;
- }
-
- @Override
- public boolean isBulkCapable() {
- return false;
- }
-
- @Override
- protected void apply(IDocument document, IStructuredModel model, Node node, int start,
- int end) {
- if (node instanceof Element) {
- Element element = (Element) node;
- NamedNodeMap attributes = element.getAttributes();
- for (int i = 0, n = attributes.getLength(); i < n; i++) {
- Attr attribute = (Attr) attributes.item(i);
- if (attribute instanceof IndexedRegion) {
- IndexedRegion region = (IndexedRegion) attribute;
- if (region.getStartOffset() == start) {
- element.removeAttribute(attribute.getName());
- return;
- }
- }
- }
- }
- }
-
- @Override
- public String getDisplayString() {
- return "Remove attribute";
- }
-
- @Override
- public Image getImage() {
- ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages();
- return sharedImages.getImage(ISharedImages.IMG_ETOOL_DELETE);
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/ProjectLintConfiguration.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/ProjectLintConfiguration.java
deleted file mode 100644
index 9e4ca1226..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/ProjectLintConfiguration.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.VisibleForTesting;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.tools.lint.client.api.Configuration;
-import com.android.tools.lint.client.api.DefaultConfiguration;
-import com.android.tools.lint.client.api.LintClient;
-import com.android.tools.lint.detector.api.Issue;
-import com.android.tools.lint.detector.api.Project;
-import com.android.tools.lint.detector.api.Severity;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.QualifiedName;
-
-import java.io.File;
-
-/** Configuration for Lint in Eclipse projects */
-class ProjectLintConfiguration extends DefaultConfiguration {
- private boolean mFatalOnly;
-
- private final static QualifiedName CONFIGURATION_NAME = new QualifiedName(AdtPlugin.PLUGIN_ID,
- "lintconfig"); //$NON-NLS-1$
-
- @VisibleForTesting
- ProjectLintConfiguration(LintClient client, Project project,
- Configuration parent, boolean fatalOnly) {
- super(client, project, parent);
- mFatalOnly = fatalOnly;
- }
-
- private static ProjectLintConfiguration create(LintClient client, IProject project,
- Configuration parent, boolean fatalOnly) {
- File dir = AdtUtils.getAbsolutePath(project).toFile();
- Project lintProject = client.getProject(dir, dir);
- return new ProjectLintConfiguration(client, lintProject, parent, fatalOnly);
- }
-
- public static ProjectLintConfiguration get(LintClient client, IProject project,
- boolean fatalOnly) {
- // Don't cache fatal-only configurations: they're only used occasionally and typically
- // not repeatedly
- if (fatalOnly) {
- return create(client, project, GlobalLintConfiguration.get(), true);
- }
-
- ProjectLintConfiguration configuration = null;
- try {
- Object value = project.getSessionProperty(CONFIGURATION_NAME);
- configuration = (ProjectLintConfiguration) value;
- } catch (CoreException e) {
- // Not a problem; we will just create a new one
- }
- if (configuration == null) {
- configuration = create(client, project, GlobalLintConfiguration.get(), false);
- try {
- project.setSessionProperty(CONFIGURATION_NAME, configuration);
- } catch (CoreException e) {
- AdtPlugin.log(e, "Can't store lint configuration");
- }
- }
- return configuration;
- }
-
- @Override
- public @NonNull Severity getSeverity(@NonNull Issue issue) {
- Severity severity = super.getSeverity(issue);
- if (mFatalOnly && severity != Severity.FATAL) {
- return Severity.IGNORE;
- }
- return severity;
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/RemoveUselessViewFix.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/RemoveUselessViewFix.java
deleted file mode 100644
index 0e9f326bf..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/RemoveUselessViewFix.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.refactoring.UnwrapRefactoring;
-import com.android.tools.lint.checks.UselessViewDetector;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.TextSelection;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-@SuppressWarnings("restriction") // DOM model
-final class RemoveUselessViewFix extends DocumentFix {
- private RemoveUselessViewFix(String id, IMarker marker) {
- super(id, marker);
- }
-
- @Override
- public boolean needsFocus() {
- return isCancelable();
- }
-
- @Override
- public boolean isCancelable() {
- return mId.equals(mId.equals(UselessViewDetector.USELESS_PARENT.getId()));
- }
-
- @Override
- protected void apply(IDocument document, IStructuredModel model, Node node, int start,
- int end) {
- if (node instanceof Element && node.getParentNode() instanceof Element) {
- Element element = (Element) node;
- Element parent = (Element) node.getParentNode();
-
- if (mId.equals(UselessViewDetector.USELESS_LEAF.getId())) {
- parent.removeChild(element);
- } else {
- assert mId.equals(UselessViewDetector.USELESS_PARENT.getId());
- // Invoke refactoring
- LayoutEditorDelegate delegate =
- LayoutEditorDelegate.fromEditor(AdtUtils.getActiveEditor());
-
- if (delegate != null) {
- IFile file = (IFile) mMarker.getResource();
- ITextSelection textSelection = new TextSelection(start,
- end - start);
- UnwrapRefactoring refactoring =
- new UnwrapRefactoring(file, delegate, textSelection, null);
- RefactoringWizard wizard = refactoring.createWizard();
- RefactoringWizardOpenOperation op =
- new RefactoringWizardOpenOperation(wizard);
- try {
- IWorkbenchWindow window = PlatformUI.getWorkbench().
- getActiveWorkbenchWindow();
- op.run(window.getShell(), wizard.getDefaultPageTitle());
- } catch (InterruptedException e) {
- }
- }
- }
- }
- }
-
- @Override
- public String getDisplayString() {
- return "Remove unnecessary view";
- }
-
- @Override
- public Image getImage() {
- ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages();
- return sharedImages.getImage(ISharedImages.IMG_ETOOL_DELETE);
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/RunLintAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/RunLintAction.java
deleted file mode 100644
index 1de903e23..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/RunLintAction.java
+++ /dev/null
@@ -1,232 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.lint;
-
-import static com.android.SdkConstants.DOT_XML;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.tools.lint.detector.api.LintUtils;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.ui.JavaElementLabelProvider;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.ActionContributionItem;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuCreator;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Menu;
-import org.eclipse.ui.IObjectActionDelegate;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowPulldownDelegate;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.texteditor.ITextEditor;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Action which runs Lint on the currently projects (and also provides a
- * pulldown menu in the toolbar for selecting specifically which projects to
- * check)
- */
-public class RunLintAction implements IObjectActionDelegate, IMenuCreator,
- IWorkbenchWindowPulldownDelegate {
-
- private ISelection mSelection;
- private Menu mMenu;
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
- mSelection = selection;
- }
-
- @Override
- public void run(IAction action) {
- List<IProject> projects = getProjects(mSelection, true /* warn */);
-
- if (!projects.isEmpty()) {
- EclipseLintRunner.startLint(projects, null, null, false /*fatalOnly*/, true /*show*/);
- }
- }
-
- /** Returns the Android project(s) to apply a lint run to. */
- static List<IProject> getProjects(ISelection selection, boolean warn) {
- List<IProject> projects = AdtUtils.getSelectedProjects(selection);
-
- if (projects.isEmpty() && warn) {
- MessageDialog.openWarning(AdtPlugin.getShell(), "Lint",
- "Could not run Lint: Select an Android project first.");
- }
-
- return projects;
- }
-
- @Override
- public void setActivePart(IAction action, IWorkbenchPart targetPart) {
- }
-
- @Override
- public void dispose() {
- if (mMenu != null) {
- mMenu.dispose();
- }
- }
-
- @Override
- public void init(IWorkbenchWindow window) {
- }
-
- // ---- IMenuCreator ----
-
- @Override
- public Menu getMenu(Control parent) {
- mMenu = new Menu(parent);
-
- IconFactory iconFactory = IconFactory.getInstance();
- ImageDescriptor allIcon = iconFactory.getImageDescriptor("lintrun"); //$NON-NLS-1$
- LintMenuAction allAction = new LintMenuAction("Check All Projects", allIcon,
- ACTION_RUN, null);
-
- addAction(allAction);
- addSeparator();
- IJavaProject[] projects = AdtUtils.getOpenAndroidProjects();
- ILabelProvider provider = new JavaElementLabelProvider(
- JavaElementLabelProvider.SHOW_DEFAULT);
- for (IJavaProject project : projects) {
- IProject p = project.getProject();
- ImageDescriptor icon = ImageDescriptor.createFromImage(provider.getImage(p));
- String label = String.format("Check %1$s", p.getName());
- LintMenuAction projectAction = new LintMenuAction(label, icon, ACTION_RUN, p);
- addAction(projectAction);
- }
-
- ITextEditor textEditor = AdtUtils.getActiveTextEditor();
- if (textEditor != null) {
- IFile file = AdtUtils.getActiveFile();
- // Currently only supported for XML files
- if (file != null && LintUtils.endsWith(file.getName(), DOT_XML)) {
- ImageDescriptor icon = ImageDescriptor.createFromImage(provider.getImage(file));
- IAction fileAction = new LintMenuAction("Check Current File", icon, ACTION_RUN,
- file);
-
- addSeparator();
- addAction(fileAction);
- }
- }
-
- ISharedImages images = PlatformUI.getWorkbench().getSharedImages();
- ImageDescriptor clear = images.getImageDescriptor(ISharedImages.IMG_ELCL_REMOVEALL);
- LintMenuAction clearAction = new LintMenuAction("Clear Lint Warnings", clear, ACTION_CLEAR,
- null);
- addSeparator();
- addAction(clearAction);
-
- LintMenuAction excludeAction = new LintMenuAction("Skip Library Project Dependencies",
- allIcon, ACTION_TOGGLE_EXCLUDE, null);
- addSeparator();
- addAction(excludeAction);
- excludeAction.setChecked(AdtPrefs.getPrefs().getSkipLibrariesFromLint());
-
- return mMenu;
- }
-
- private void addAction(IAction action) {
- ActionContributionItem item = new ActionContributionItem(action);
- item.fill(mMenu, -1);
- }
-
- private void addSeparator() {
- new Separator().fill(mMenu, -1);
- }
-
- @Override
- public Menu getMenu(Menu parent) {
- return null;
- }
-
- private static final int ACTION_RUN = 1;
- private static final int ACTION_CLEAR = 2;
- private static final int ACTION_TOGGLE_EXCLUDE = 3;
-
- /**
- * Actions in the pulldown context menu: run lint or clear lint markers on
- * the given resource
- */
- private static class LintMenuAction extends Action {
- private final IResource mResource;
- private final int mAction;
-
- /**
- * Creates a new context menu action
- *
- * @param text the label
- * @param descriptor the icon
- * @param action the action to run: run lint, clear, or toggle exclude libraries
- * @param resource the resource to check or clear markers for, where
- * null means all projects
- */
- private LintMenuAction(String text, ImageDescriptor descriptor, int action,
- IResource resource) {
- super(text, action == ACTION_TOGGLE_EXCLUDE ? AS_CHECK_BOX : AS_PUSH_BUTTON);
- if (descriptor != null) {
- setImageDescriptor(descriptor);
- }
- mAction = action;
- mResource = resource;
- }
-
- @Override
- public void run() {
- if (mAction == ACTION_TOGGLE_EXCLUDE) {
- AdtPrefs prefs = AdtPrefs.getPrefs();
- prefs.setSkipLibrariesFromLint(!prefs.getSkipLibrariesFromLint());
- return;
- }
- List<IResource> resources = new ArrayList<IResource>();
- if (mResource == null) {
- // All projects
- IJavaProject[] open = AdtUtils.getOpenAndroidProjects();
- for (IJavaProject project : open) {
- resources.add(project.getProject());
- }
- } else {
- resources.add(mResource);
- }
- EclipseLintRunner.cancelCurrentJobs(false);
- if (mAction == ACTION_CLEAR) {
- EclipseLintClient.clearMarkers(resources);
- } else {
- assert mAction == ACTION_RUN;
- EclipseLintRunner.startLint(resources, null, null, false /*fatalOnly*/,
- true /*show*/);
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/SetAttributeFix.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/SetAttributeFix.java
deleted file mode 100644
index ea73b9a72..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/SetAttributeFix.java
+++ /dev/null
@@ -1,151 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_ALLOW_BACKUP;
-import static com.android.SdkConstants.ATTR_BASELINE_ALIGNED;
-import static com.android.SdkConstants.ATTR_CONTENT_DESCRIPTION;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ATTR_INPUT_TYPE;
-import static com.android.SdkConstants.ATTR_PERMISSION;
-import static com.android.SdkConstants.ATTR_TRANSLATABLE;
-import static com.android.SdkConstants.NEW_ID_PREFIX;
-import static com.android.SdkConstants.VALUE_FALSE;
-
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DescriptorsUtils;
-import com.android.tools.lint.checks.AccessibilityDetector;
-import com.android.tools.lint.checks.InefficientWeightDetector;
-import com.android.tools.lint.checks.ManifestDetector;
-import com.android.tools.lint.checks.MissingIdDetector;
-import com.android.tools.lint.checks.SecurityDetector;
-import com.android.tools.lint.checks.TextFieldDetector;
-import com.android.tools.lint.checks.TranslationDetector;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.ui.IEditorPart;
-import org.w3c.dom.Element;
-
-/** Shared fix class for various builtin attributes */
-final class SetAttributeFix extends SetPropertyFix {
- private SetAttributeFix(String id, IMarker marker) {
- super(id, marker);
- }
-
- @Override
- protected String getAttribute() {
- if (mId.equals(AccessibilityDetector.ISSUE.getId())) {
- return ATTR_CONTENT_DESCRIPTION;
- } else if (mId.equals(InefficientWeightDetector.BASELINE_WEIGHTS.getId())) {
- return ATTR_BASELINE_ALIGNED;
- } else if (mId.equals(SecurityDetector.EXPORTED_SERVICE.getId())) {
- return ATTR_PERMISSION;
- } else if (mId.equals(TextFieldDetector.ISSUE.getId())) {
- return ATTR_INPUT_TYPE;
- } else if (mId.equals(TranslationDetector.MISSING.getId())) {
- return ATTR_TRANSLATABLE;
- } else if (mId.equals(ManifestDetector.ALLOW_BACKUP.getId())) {
- return ATTR_ALLOW_BACKUP;
- } else if (mId.equals(MissingIdDetector.ISSUE.getId())) {
- return ATTR_ID;
- } else {
- assert false : mId;
- return "";
- }
- }
-
- @Override
- protected boolean isAndroidAttribute() {
- if (mId.equals(TranslationDetector.MISSING.getId())) {
- return false;
- }
-
- return true;
- }
-
- @Override
- public String getDisplayString() {
- if (mId.equals(AccessibilityDetector.ISSUE.getId())) {
- return "Add content description attribute";
- } else if (mId.equals(InefficientWeightDetector.BASELINE_WEIGHTS.getId())) {
- return "Set baseline attribute";
- } else if (mId.equals(TextFieldDetector.ISSUE.getId())) {
- return "Set input type";
- } else if (mId.equals(SecurityDetector.EXPORTED_SERVICE.getId())) {
- return "Add permission attribute";
- } else if (mId.equals(TranslationDetector.MISSING.getId())) {
- return "Mark this as a non-translatable resource";
- } else if (mId.equals(ManifestDetector.ALLOW_BACKUP.getId())) {
- return "Set the allowBackup attribute to true or false";
- } else if (mId.equals(MissingIdDetector.ISSUE.getId())) {
- return "Set the ID attribute";
- } else {
- assert false : mId;
- return "";
- }
- }
-
- @Override
- public String getAdditionalProposalInfo() {
- String help = super.getAdditionalProposalInfo();
-
- if (mId.equals(TranslationDetector.MISSING.getId())) {
- help = "<b>Adds translatable=\"false\" to this &lt;string&gt;.</b><br><br>" + help;
- }
-
- return help;
- }
-
- @Override
- protected boolean invokeCodeCompletion() {
- return mId.equals(SecurityDetector.EXPORTED_SERVICE.getId())
- || mId.equals(TextFieldDetector.ISSUE.getId())
- || mId.equals(ManifestDetector.ALLOW_BACKUP.getId());
- }
-
- @Override
- public boolean selectValue() {
- if (mId.equals(TranslationDetector.MISSING.getId())) {
- return false;
- } else {
- return super.selectValue();
- }
- }
-
- @Override
- protected String getProposal(Element element) {
- if (mId.equals(InefficientWeightDetector.BASELINE_WEIGHTS.getId())) {
- return VALUE_FALSE;
- } else if (mId.equals(TranslationDetector.MISSING.getId())) {
- return VALUE_FALSE;
- } else if (mId.equals(TextFieldDetector.ISSUE.getId())) {
- return element.getAttributeNS(ANDROID_URI, ATTR_INPUT_TYPE);
- } else if (mId.equals(MissingIdDetector.ISSUE.getId())) {
- IEditorPart editor = AdtUtils.getActiveEditor();
- if (editor instanceof AndroidXmlEditor) {
- AndroidXmlEditor xmlEditor = (AndroidXmlEditor) editor;
- return DescriptorsUtils.getFreeWidgetId(xmlEditor.getUiRootNode(),
- "fragment"); //$NON-NLS-1$
- } else {
- return NEW_ID_PREFIX;
- }
- }
-
- return super.getProposal(element);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/SetPropertyFix.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/SetPropertyFix.java
deleted file mode 100644
index a2b79c3c8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/SetPropertyFix.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import static com.android.SdkConstants.ANDROID_URI;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.utils.XmlUtils;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.Region;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-@SuppressWarnings("restriction") // DOM model
-abstract class SetPropertyFix extends DocumentFix {
- private Region mSelect;
-
- protected SetPropertyFix(String id, IMarker marker) {
- super(id, marker);
- }
-
- /** Attribute to be added */
- protected abstract String getAttribute();
-
- /** Whether it's in the android: namespace */
- protected abstract boolean isAndroidAttribute();
-
- protected String getProposal(Element element) {
- return invokeCodeCompletion() ? "" : "TODO"; //$NON-NLS-1$
- }
-
- protected boolean invokeCodeCompletion() {
- return false;
- }
-
- @Override
- public boolean isCancelable() {
- return false;
- }
-
- @Override
- protected void apply(IDocument document, IStructuredModel model, Node node, int start,
- int end) {
- mSelect = null;
-
- if (node instanceof Element) {
- Element element = (Element) node;
- String proposal = getProposal(element);
- String localAttribute = getAttribute();
- String prefix = null;
- if (isAndroidAttribute()) {
- prefix = XmlUtils.lookupNamespacePrefix(node, ANDROID_URI);
- }
- String attribute = prefix != null ? prefix + ':' + localAttribute : localAttribute;
-
- // This does not work even though it should: it does not include the prefix
- //element.setAttributeNS(ANDROID_URI, localAttribute, proposal);
- // So workaround instead:
- element.setAttribute(attribute, proposal);
-
- Attr attr = null;
- if (isAndroidAttribute()) {
- attr = element.getAttributeNodeNS(ANDROID_URI, localAttribute);
- } else {
- attr = element.getAttributeNode(localAttribute);
- }
- if (attr instanceof IndexedRegion) {
- IndexedRegion region = (IndexedRegion) attr;
- int offset = region.getStartOffset();
- // We only want to select the value part inside the quotes,
- // so skip the attribute and =" parts added by WST:
- offset += attribute.length() + 2;
- if (selectValue()) {
- mSelect = new Region(offset, proposal.length());
- }
- }
- }
- }
-
- protected boolean selectValue() {
- return true;
- }
-
- @Override
- public void apply(IDocument document) {
- try {
- IFile file = (IFile) mMarker.getResource();
- super.apply(document);
- AdtPlugin.openFile(file, mSelect, true);
- } catch (PartInitException e) {
- AdtPlugin.log(e, null);
- }
-
- // Invoke code assist
- if (invokeCodeCompletion()) {
- IEditorPart editor = AdtUtils.getActiveEditor();
- if (editor instanceof AndroidXmlEditor) {
- ((AndroidXmlEditor) editor).invokeContentAssist(-1);
- }
- }
- }
-
- @Override
- public boolean needsFocus() {
- // Because we need to show the editor with text selected
- return true;
- }
-
- @Override
- public Image getImage() {
- ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages();
- return sharedImages.getImage(ISharedImages.IMG_OBJ_ADD);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/SetScrollViewSizeFix.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/SetScrollViewSizeFix.java
deleted file mode 100644
index 52860cf85..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/SetScrollViewSizeFix.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.HORIZONTAL_SCROLL_VIEW;
-import static com.android.SdkConstants.VALUE_WRAP_CONTENT;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-@SuppressWarnings("restriction") // DOM model
-final class SetScrollViewSizeFix extends DocumentFix {
- private SetScrollViewSizeFix(String id, IMarker marker) {
- super(id, marker);
- }
-
- @Override
- public boolean needsFocus() {
- return false;
- }
-
- @Override
- public boolean isCancelable() {
- return false;
- }
-
- @Override
- protected void apply(IDocument document, IStructuredModel model, Node node, int start,
- int end) {
- if (node instanceof Element && node.getParentNode() instanceof Element) {
- Element element = (Element) node;
- Element parent = (Element) node.getParentNode();
-
- boolean isHorizontal = HORIZONTAL_SCROLL_VIEW.equals(parent.getTagName());
- String attributeName = isHorizontal ? ATTR_LAYOUT_WIDTH : ATTR_LAYOUT_HEIGHT;
- element.setAttributeNS(ANDROID_URI, attributeName, VALUE_WRAP_CONTENT);
- }
- }
-
- @Override
- public String getDisplayString() {
- return "Replace size attribute with wrap_content";
- }
-
- @Override
- public Image getImage() {
- ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages();
- // TODO: Need a better icon here
- return sharedImages.getImage(ISharedImages.IMG_OBJ_ELEMENT);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/TypoFix.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/TypoFix.java
deleted file mode 100644
index 7cc05d203..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/TypoFix.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.tools.lint.checks.TypoDetector;
-import com.android.tools.lint.detector.api.TextFormat;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.FindReplaceDocumentAdapter;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.w3c.dom.Node;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/** Quickfix for fixing typos */
-@SuppressWarnings("restriction") // DOM model
-final class TypoFix extends DocumentFix {
- private String mTypo;
- private String mReplacement;
-
- private TypoFix(String id, IMarker marker) {
- super(id, marker);
- }
-
- @Override
- public String getDisplayString() {
- return String.format("Replace \"%1$s\" by \"%2$s\"", mTypo, mReplacement);
- }
-
- @Override
- public boolean needsFocus() {
- return false;
- }
-
- @Override
- public boolean isCancelable() {
- return false;
- }
-
- @Override
- protected void apply(IDocument document, IStructuredModel model, Node node,
- int start, int end) {
- String message = mMarker.getAttribute(IMarker.MESSAGE, "");
- String typo = TypoDetector.getTypo(message, TextFormat.TEXT);
- if (typo == null) {
- return;
- }
- List<String> replacements = TypoDetector.getSuggestions(message, TextFormat.TEXT);
- if (replacements == null || replacements.isEmpty()) {
- return;
- }
-
- try {
- String current = document.get(start, end-start);
- if (current.equals(typo)) {
- document.replace(start, end - start, replacements.get(0));
- } else {
- // The buffer has been edited; try to find the typo.
- FindReplaceDocumentAdapter finder = new FindReplaceDocumentAdapter(document);
- IRegion forward = finder.find(start, typo, true /*forward*/, true, true, false);
- IRegion backward = finder.find(start, typo, false /*forward*/, true, true, false);
- if (forward != null && backward != null) {
- // Pick the closest one
- int forwardDelta = forward.getOffset() - start;
- int backwardDelta = start - backward.getOffset();
- if (forwardDelta < backwardDelta) {
- start = forward.getOffset();
- } else {
- start = backward.getOffset();
- }
- } else if (forward != null) {
- start = forward.getOffset();
- } else if (backward != null) {
- start = backward.getOffset();
- } else {
- return;
- }
- end = start + typo.length();
- document.replace(start, end - start, replacements.get(0));
- }
- } catch (BadLocationException e) {
- AdtPlugin.log(e, null);
- }
- }
-
- @Override
- protected List<LintFix> getAllFixes() {
- String message = mMarker.getAttribute(IMarker.MESSAGE, "");
- String typo = TypoDetector.getTypo(message, TextFormat.TEXT);
- List<String> replacements = TypoDetector.getSuggestions(message, TextFormat.TEXT);
- if (replacements != null && !replacements.isEmpty() && typo != null) {
- List<LintFix> allFixes = new ArrayList<LintFix>(replacements.size());
- for (String replacement : replacements) {
- TypoFix fix = new TypoFix(mId, mMarker);
- fix.mTypo = typo;
- fix.mReplacement = replacement;
- allFixes.add(fix);
- }
-
- return allFixes;
- }
-
- return null;
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/TypographyFix.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/TypographyFix.java
deleted file mode 100644
index 535e02350..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/TypographyFix.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.tools.lint.checks.TypographyDetector;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import java.util.List;
-
-@SuppressWarnings("restriction") // DOM model
-final class TypographyFix extends DocumentFix {
- private TypographyFix(String id, IMarker marker) {
- super(id, marker);
- }
-
- @Override
- public boolean needsFocus() {
- return false;
- }
-
- @Override
- public boolean isCancelable() {
- return false;
- }
-
- @Override
- public boolean isBulkCapable() {
- return false;
- }
-
- @Override
- protected void apply(IDocument document, IStructuredModel model, Node node, int start,
- int end) {
- if (node instanceof Element) {
- Element element = (Element) node;
- // Find the text node which contains the character in question
- NodeList childNodes = element.getChildNodes();
- for (int i = 0, n = childNodes.getLength(); i < n; i++) {
- Node child = childNodes.item(i);
- if (child.getNodeType() == Node.TEXT_NODE) {
- IndexedRegion region = (IndexedRegion) child;
- String message = mMarker.getAttribute(IMarker.MESSAGE, "");
- List<TypographyDetector.ReplaceEdit> edits =
- TypographyDetector.getEdits(mId, message, child);
- for (TypographyDetector.ReplaceEdit edit : edits) {
- try {
- document.replace(edit.offset + region.getStartOffset(),
- edit.length, edit.replaceWith);
- } catch (BadLocationException e) {
- AdtPlugin.log(e, null);
- }
- }
- }
- }
- }
- }
-
- @Override
- public String getDisplayString() {
- return "Replace with suggested characters";
- }
-
- @Override
- public Image getImage() {
- ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages();
- // TODO: Need a better icon here
- return sharedImages.getImage(ISharedImages.IMG_OBJ_ELEMENT);
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/UseCompoundDrawableDetectorFix.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/UseCompoundDrawableDetectorFix.java
deleted file mode 100644
index bf3cc9ac0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/lint/UseCompoundDrawableDetectorFix.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.lint;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.refactoring.UseCompoundDrawableRefactoring;
-import com.android.tools.lint.checks.UseCompoundDrawableDetector;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.TextSelection;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.w3c.dom.Node;
-
-/** Quickfix for the {@link UseCompoundDrawableDetector} */
-@SuppressWarnings("restriction") // DOM model
-class UseCompoundDrawableDetectorFix extends DocumentFix {
- protected UseCompoundDrawableDetectorFix(String id, IMarker marker) {
- super(id, marker);
- }
-
- @Override
- public String getDisplayString() {
- return "Convert to a compound drawable";
- }
-
- @Override
- public Image getImage() {
- return AdtPlugin.getAndroidLogo();
- }
-
- @Override
- public boolean needsFocus() {
- return false;
- }
-
- @Override
- public boolean isCancelable() {
- return false;
- }
-
- @Override
- public boolean isBulkCapable() {
- return false;
- }
-
- @Override
- protected void apply(IDocument document, IStructuredModel model, Node node,
- int start, int end) {
-
- // Invoke refactoring
- LayoutEditorDelegate delegate =
- LayoutEditorDelegate.fromEditor(AdtUtils.getActiveEditor());
-
- if (delegate != null) {
- IFile file = (IFile) mMarker.getResource();
- ITextSelection textSelection = new TextSelection(start,
- end - start);
- UseCompoundDrawableRefactoring refactoring =
- new UseCompoundDrawableRefactoring(file, delegate, textSelection, null);
- RefactoringWizard wizard = refactoring.createWizard();
- RefactoringWizardOpenOperation op =
- new RefactoringWizardOpenOperation(wizard);
- try {
- IWorkbenchWindow window = PlatformUI.getWorkbench().
- getActiveWorkbenchWindow();
- op.run(window.getShell(), wizard.getDefaultPageTitle());
- } catch (InterruptedException e) {
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/AdtPrefs.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/AdtPrefs.java
deleted file mode 100644
index aed4bd4be..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/AdtPrefs.java
+++ /dev/null
@@ -1,647 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.preferences;
-
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.xml.XmlAttributeSortOrder;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderPreviewMode;
-import com.android.prefs.AndroidLocation.AndroidLocationException;
-import com.android.sdklib.internal.build.DebugKeyProvider;
-import com.android.sdklib.internal.build.DebugKeyProvider.KeytoolException;
-import com.android.sdkstats.DdmsPreferenceStore;
-
-import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.util.PropertyChangeEvent;
-
-import java.io.File;
-import java.util.Locale;
-
-public final class AdtPrefs extends AbstractPreferenceInitializer {
- public final static String PREFS_SDK_DIR = AdtPlugin.PLUGIN_ID + ".sdk"; //$NON-NLS-1$
-
- public final static String PREFS_BUILD_RES_AUTO_REFRESH = AdtPlugin.PLUGIN_ID + ".resAutoRefresh"; //$NON-NLS-1$
-
- public final static String PREFS_BUILD_FORCE_ERROR_ON_NATIVELIB_IN_JAR = AdtPlugin.PLUGIN_ID + ".forceErrorNativeLibInJar"; //$NON-NLS-1$
-
- public final static String PREFS_BUILD_SKIP_POST_COMPILE_ON_FILE_SAVE = AdtPlugin.PLUGIN_ID + ".skipPostCompileOnFileSave"; //$NON-NLS-1$
-
- public final static String PREFS_BUILD_VERBOSITY = AdtPlugin.PLUGIN_ID + ".buildVerbosity"; //$NON-NLS-1$
-
- public final static String PREFS_DEFAULT_DEBUG_KEYSTORE = AdtPlugin.PLUGIN_ID + ".defaultDebugKeyStore"; //$NON-NLS-1$
-
- public final static String PREFS_CUSTOM_DEBUG_KEYSTORE = AdtPlugin.PLUGIN_ID + ".customDebugKeyStore"; //$NON-NLS-1$
-
- public final static String PREFS_HOME_PACKAGE = AdtPlugin.PLUGIN_ID + ".homePackage"; //$NON-NLS-1$
-
- public final static String PREFS_EMU_OPTIONS = AdtPlugin.PLUGIN_ID + ".emuOptions"; //$NON-NLS-1$
-
- public final static String PREFS_MONITOR_DENSITY = AdtPlugin.PLUGIN_ID + ".monitorDensity"; //$NON-NLS-1$
-
- public final static String PREFS_FORMAT_GUI_XML = AdtPlugin.PLUGIN_ID + ".formatXml"; //$NON-NLS-1$
- public final static String PREFS_PREFER_XML = AdtPlugin.PLUGIN_ID + ".xmlEditor"; //$NON-NLS-1$
- public final static String PREFS_USE_CUSTOM_XML_FORMATTER = AdtPlugin.PLUGIN_ID + ".androidForm"; //$NON-NLS-1$
-
- public final static String PREFS_PALETTE_MODE = AdtPlugin.PLUGIN_ID + ".palette"; //$NON-NLS-1$
-
- public final static String PREFS_USE_ECLIPSE_INDENT = AdtPlugin.PLUGIN_ID + ".eclipseIndent"; //$NON-NLS-1$
- public final static String PREVS_REMOVE_EMPTY_LINES = AdtPlugin.PLUGIN_ID + ".removeEmpty"; //$NON-NLS-1$
- public final static String PREFS_ONE_ATTR_PER_LINE = AdtPlugin.PLUGIN_ID + ".oneAttrPerLine"; //$NON-NLS-1$
- public final static String PREFS_SPACE_BEFORE_CLOSE = AdtPlugin.PLUGIN_ID + ".spaceBeforeClose"; //$NON-NLS-1$
- public final static String PREFS_FORMAT_ON_SAVE = AdtPlugin.PLUGIN_ID + ".formatOnSave"; //$NON-NLS-1$
- public final static String PREFS_LINT_ON_SAVE = AdtPlugin.PLUGIN_ID + ".lintOnSave"; //$NON-NLS-1$
- public final static String PREFS_LINT_ON_EXPORT = AdtPlugin.PLUGIN_ID + ".lintOnExport"; //$NON-NLS-1$
- public final static String PREFS_ATTRIBUTE_SORT = AdtPlugin.PLUGIN_ID + ".attrSort"; //$NON-NLS-1$
- public final static String PREFS_LINT_SEVERITIES = AdtPlugin.PLUGIN_ID + ".lintSeverities"; //$NON-NLS-1$
- public final static String PREFS_FIX_LEGACY_EDITORS = AdtPlugin.PLUGIN_ID + ".fixLegacyEditors"; //$NON-NLS-1$
- public final static String PREFS_SHARED_LAYOUT_EDITOR = AdtPlugin.PLUGIN_ID + ".sharedLayoutEditor"; //$NON-NLS-1$
- public final static String PREFS_PREVIEWS = AdtPlugin.PLUGIN_ID + ".previews"; //$NON-NLS-1$
- public final static String PREFS_SKIP_LINT_LIBS = AdtPlugin.PLUGIN_ID + ".skipLintLibs"; //$NON-NLS-1$
- public final static String PREFS_AUTO_PICK_TARGET = AdtPlugin.PLUGIN_ID + ".autoPickTarget"; //$NON-NLS-1$
- public final static String PREFS_REFACTOR_IDS = AdtPlugin.PLUGIN_ID + ".refactorIds"; //$NON-NLS-1$
-
- /** singleton instance */
- private final static AdtPrefs sThis = new AdtPrefs();
-
- /** default store, provided by eclipse */
- private IPreferenceStore mStore;
-
- /** cached location for the sdk folder */
- private String mOsSdkLocation;
-
- /** Verbosity of the build */
- private BuildVerbosity mBuildVerbosity = BuildVerbosity.NORMAL;
-
- private boolean mBuildForceResResfresh = false;
- private boolean mBuildForceErrorOnNativeLibInJar = true;
- private boolean mBuildSkipPostCompileOnFileSave = true;
- private float mMonitorDensity = 0.f;
- private String mPalette;
-
- private boolean mFormatGuiXml;
- private boolean mCustomXmlFormatter;
- private boolean mUseEclipseIndent;
- private boolean mRemoveEmptyLines;
- private boolean mOneAttributeOnFirstLine;
- private boolean mSpaceBeforeClose;
- private boolean mFormatOnSave;
- private boolean mLintOnSave;
- private boolean mLintOnExport;
- private XmlAttributeSortOrder mAttributeSort;
- private boolean mSharedLayoutEditor;
- private boolean mAutoPickTarget;
- private RenderPreviewMode mPreviewMode = RenderPreviewMode.NONE;
- private int mPreferXmlEditor;
- private boolean mSkipLibrariesFromLint;
-
- public static enum BuildVerbosity {
- /** Build verbosity "Always". Those messages are always displayed, even in silent mode */
- ALWAYS(0),
- /** Build verbosity level "Normal" */
- NORMAL(1),
- /** Build verbosity level "Verbose". Those messages are only displayed in verbose mode */
- VERBOSE(2);
-
- private int mLevel;
-
- BuildVerbosity(int level) {
- mLevel = level;
- }
-
- public int getLevel() {
- return mLevel;
- }
-
- /**
- * Finds and returns a {@link BuildVerbosity} whose {@link #name()} matches a given name.
- * <p/>This is different from {@link Enum#valueOf(Class, String)} in that it returns null
- * if no matches are found.
- *
- * @param name the name to look up.
- * @return returns the matching enum or null of no match where found.
- */
- public static BuildVerbosity find(String name) {
- for (BuildVerbosity v : values()) {
- if (v.name().equals(name)) {
- return v;
- }
- }
-
- return null;
- }
- }
-
- public static void init(IPreferenceStore preferenceStore) {
- sThis.mStore = preferenceStore;
- }
-
- public static AdtPrefs getPrefs() {
- return sThis;
- }
-
- public synchronized void loadValues(PropertyChangeEvent event) {
- // get the name of the property that changed, if any
- String property = event != null ? event.getProperty() : null;
-
- if (property == null || PREFS_SDK_DIR.equals(property)) {
- mOsSdkLocation = mStore.getString(PREFS_SDK_DIR);
-
- // Make it possible to override the SDK path using an environment variable.
- // The value will only be used if it matches an existing directory.
- // Useful for testing from Eclipse.
- // Note: this is a hack that does not change the preferences, so if the user
- // looks at Window > Preferences > Android, the path will be the preferences
- // one and not the overridden one.
- String override = System.getenv("ADT_TEST_SDK_PATH"); //$NON-NLS-1$
- if (override != null && override.length() > 0 && new File(override).isDirectory()) {
- mOsSdkLocation = override;
- }
-
- // make sure it ends with a separator. Normally this is done when the preference
- // is set. But to make sure older version still work, we fix it here as well.
- if (mOsSdkLocation.length() > 0 && mOsSdkLocation.endsWith(File.separator) == false) {
- mOsSdkLocation = mOsSdkLocation + File.separator;
- }
- }
-
- if (property == null || PREFS_BUILD_VERBOSITY.equals(property)) {
- mBuildVerbosity = BuildVerbosity.find(mStore.getString(PREFS_BUILD_VERBOSITY));
- if (mBuildVerbosity == null) {
- mBuildVerbosity = BuildVerbosity.NORMAL;
- }
- }
-
- if (property == null || PREFS_BUILD_RES_AUTO_REFRESH.equals(property)) {
- mBuildForceResResfresh = mStore.getBoolean(PREFS_BUILD_RES_AUTO_REFRESH);
- }
-
- if (property == null || PREFS_BUILD_FORCE_ERROR_ON_NATIVELIB_IN_JAR.equals(property)) {
- mBuildForceErrorOnNativeLibInJar =
- mStore.getBoolean(PREFS_BUILD_FORCE_ERROR_ON_NATIVELIB_IN_JAR);
- }
-
- if (property == null || PREFS_BUILD_SKIP_POST_COMPILE_ON_FILE_SAVE.equals(property)) {
- mBuildSkipPostCompileOnFileSave =
- mStore.getBoolean(PREFS_BUILD_SKIP_POST_COMPILE_ON_FILE_SAVE);
- }
-
- if (property == null || PREFS_MONITOR_DENSITY.equals(property)) {
- mMonitorDensity = mStore.getFloat(PREFS_MONITOR_DENSITY);
- }
-
- if (property == null || PREFS_FORMAT_GUI_XML.equals(property)) {
- mFormatGuiXml = mStore.getBoolean(PREFS_FORMAT_GUI_XML);
- }
-
- if (property == null || PREFS_PREFER_XML.equals(property)) {
- mPreferXmlEditor = mStore.getInt(PREFS_PREFER_XML);
- }
-
- if (property == null || PREFS_USE_CUSTOM_XML_FORMATTER.equals(property)) {
- mCustomXmlFormatter = mStore.getBoolean(PREFS_USE_CUSTOM_XML_FORMATTER);
- }
-
- if (property == null || PREFS_PALETTE_MODE.equals(property)) {
- mPalette = mStore.getString(PREFS_PALETTE_MODE);
- }
-
- if (property == null || PREFS_USE_ECLIPSE_INDENT.equals(property)) {
- mUseEclipseIndent = mStore.getBoolean(PREFS_USE_ECLIPSE_INDENT);
- }
-
- if (property == null || PREVS_REMOVE_EMPTY_LINES.equals(property)) {
- mRemoveEmptyLines = mStore.getBoolean(PREVS_REMOVE_EMPTY_LINES);
- }
-
- if (property == null || PREFS_ONE_ATTR_PER_LINE.equals(property)) {
- mOneAttributeOnFirstLine = mStore.getBoolean(PREFS_ONE_ATTR_PER_LINE);
- }
-
- if (property == null || PREFS_ATTRIBUTE_SORT.equals(property)) {
- String order = mStore.getString(PREFS_ATTRIBUTE_SORT);
- mAttributeSort = XmlAttributeSortOrder.LOGICAL;
- if (XmlAttributeSortOrder.ALPHABETICAL.key.equals(order)) {
- mAttributeSort = XmlAttributeSortOrder.ALPHABETICAL;
- } else if (XmlAttributeSortOrder.NO_SORTING.key.equals(order)) {
- mAttributeSort = XmlAttributeSortOrder.NO_SORTING;
- }
- }
-
- if (property == null || PREFS_SPACE_BEFORE_CLOSE.equals(property)) {
- mSpaceBeforeClose = mStore.getBoolean(PREFS_SPACE_BEFORE_CLOSE);
- }
-
- if (property == null || PREFS_FORMAT_ON_SAVE.equals(property)) {
- mFormatOnSave = mStore.getBoolean(PREFS_FORMAT_ON_SAVE);
- }
-
- if (property == null || PREFS_LINT_ON_SAVE.equals(property)) {
- mLintOnSave = mStore.getBoolean(PREFS_LINT_ON_SAVE);
- }
-
- if (property == null || PREFS_LINT_ON_EXPORT.equals(property)) {
- mLintOnExport = mStore.getBoolean(PREFS_LINT_ON_EXPORT);
- }
-
- if (property == null || PREFS_SHARED_LAYOUT_EDITOR.equals(property)) {
- mSharedLayoutEditor = mStore.getBoolean(PREFS_SHARED_LAYOUT_EDITOR);
- }
-
- if (property == null || PREFS_AUTO_PICK_TARGET.equals(property)) {
- mAutoPickTarget = mStore.getBoolean(PREFS_AUTO_PICK_TARGET);
- }
-
- if (property == null || PREFS_PREVIEWS.equals(property)) {
- mPreviewMode = RenderPreviewMode.NONE;
- String previewMode = mStore.getString(PREFS_PREVIEWS);
- if (previewMode != null && !previewMode.isEmpty()) {
- try {
- mPreviewMode = RenderPreviewMode.valueOf(previewMode.toUpperCase(Locale.US));
- } catch (IllegalArgumentException iae) {
- // Ignore: Leave it as RenderPreviewMode.NONE
- }
- }
- }
-
- if (property == null || PREFS_SKIP_LINT_LIBS.equals(property)) {
- mSkipLibrariesFromLint = mStore.getBoolean(PREFS_SKIP_LINT_LIBS);
- }
- }
-
- /**
- * Returns the SDK folder.
- * Guaranteed to be terminated by a platform-specific path separator.
- */
- public synchronized String getOsSdkFolder() {
- return mOsSdkLocation;
- }
-
- public synchronized BuildVerbosity getBuildVerbosity() {
- return mBuildVerbosity;
- }
-
- public boolean getBuildForceResResfresh() {
- return mBuildForceResResfresh;
- }
-
- /**
- * Should changes made by GUI editors automatically format the corresponding XML nodes
- * affected by the edit?
- *
- * @return true if the GUI editors should format affected XML regions
- */
- public boolean getFormatGuiXml() {
- // The format-GUI-editors flag only applies when the custom formatter is used,
- // since the built-in formatter has problems editing partial documents
- return mFormatGuiXml && mCustomXmlFormatter;
- }
-
- /**
- * Should the XML formatter use a custom Android XML formatter (following
- * Android code style) or use the builtin Eclipse XML formatter?
- *
- * @return true if the Android formatter should be used instead of the
- * default Eclipse one
- */
- public boolean getUseCustomXmlFormatter() {
- return mCustomXmlFormatter;
- }
-
- /**
- * Should the Android XML formatter use the Eclipse XML indentation settings
- * (usually one tab character) instead of the default 4 space character
- * indent?
- *
- * @return true if the Eclipse XML indentation settings should be use
- */
- public boolean isUseEclipseIndent() {
- return mUseEclipseIndent;
- }
-
- /**
- * Should the Android XML formatter try to avoid inserting blank lines to
- * make the format as compact as possible (no blank lines between elements,
- * no blank lines surrounding comments, etc).
- *
- * @return true to remove blank lines
- */
- public boolean isRemoveEmptyLines() {
- return mRemoveEmptyLines;
- }
-
- /**
- * Should the Android XML formatter attempt to place a single attribute on
- * the same line as the element open tag?
- *
- * @return true if single-attribute elements should place the attribute on
- * the same line as the element open tag
- */
- public boolean isOneAttributeOnFirstLine() {
- return mOneAttributeOnFirstLine;
- }
-
- /**
- * Returns the sort order to be applied to the attributes (one of which can
- * be {@link com.android.ide.common.xml.XmlAttributeSortOrder#NO_SORTING}).
- *
- * @return the sort order to apply to the attributes
- */
- public XmlAttributeSortOrder getAttributeSort() {
- if (mAttributeSort == null) {
- return XmlAttributeSortOrder.LOGICAL;
- }
- return mAttributeSort;
- }
-
- /**
- * Returns whether a space should be inserted before the closing {@code >}
- * character in open tags and before the closing {@code />} characters in
- * empty tag. Note that the {@link com.android.ide.common.xml.XmlFormatStyle#RESOURCE} style overrides
- * this setting to make it more compact for the {@code <item>} elements.
- *
- * @return true if an empty space should be inserted before {@code >} or
- * {@code />}.
- */
- public boolean isSpaceBeforeClose() {
- return mSpaceBeforeClose;
- }
-
- /**
- * Returns whether the file should be automatically formatted on save.
- *
- * @return true if the XML files should be formatted on save.
- */
- public boolean isFormatOnSave() {
- return mFormatOnSave;
- }
-
- public boolean isLintOnSave() {
- return mLintOnSave;
- }
-
- public void setLintOnSave(boolean on) {
- mLintOnSave = on;
- IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore();
- store.setValue(PREFS_LINT_ON_SAVE, on);
- }
-
- public boolean isLintOnExport() {
- return mLintOnExport;
- }
-
- public void setLintOnExport(boolean on) {
- mLintOnExport = on;
- IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore();
- store.setValue(PREFS_LINT_ON_EXPORT, on);
- }
-
- /**
- * Returns whether the layout editor is sharing a single editor for all variations
- * of a single resource. The default is false.
- *
- * @return true if the editor should be shared
- */
- public boolean isSharedLayoutEditor() {
- return mSharedLayoutEditor;
- }
-
- /**
- * Sets whether the layout editor should share a single editor for all variations
- * of a single resource
- *
- * @param on if true, use a single editor
- */
- public void setSharedLayoutEditor(boolean on) {
- mSharedLayoutEditor = on;
- IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore();
- store.setValue(PREFS_SHARED_LAYOUT_EDITOR, on);
-
- // TODO: If enabling a shared editor, go and close all editors that are aliasing
- // the same resource except for one of them.
- }
-
-
- public boolean getBuildForceErrorOnNativeLibInJar() {
- return mBuildForceErrorOnNativeLibInJar;
- }
-
- public boolean getBuildSkipPostCompileOnFileSave() {
- return mBuildSkipPostCompileOnFileSave;
- }
-
- public String getPaletteModes() {
- return mPalette;
- }
-
- public void setPaletteModes(String palette) {
- mPalette = palette;
-
- // need to save this new value to the store
- IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore();
- store.setValue(PREFS_PALETTE_MODE, palette);
- }
-
- public float getMonitorDensity() {
- return mMonitorDensity;
- }
-
- public void setMonitorDensity(float density) {
- mMonitorDensity = density;
-
- // need to save this new value to the store
- IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore();
- store.setValue(PREFS_MONITOR_DENSITY, density);
- }
-
- /**
- * Sets the new location of the SDK
- *
- * @param location the location of the SDK
- */
- public void setSdkLocation(File location) {
- mOsSdkLocation = location != null ? location.getPath() : null;
-
- // TODO: Also store this location in the .android settings directory
- // such that we can support using multiple workspaces without asking
- // over and over.
- if (mOsSdkLocation != null && mOsSdkLocation.length() > 0) {
- DdmsPreferenceStore ddmsStore = new DdmsPreferenceStore();
- ddmsStore.setLastSdkPath(mOsSdkLocation);
- }
-
- // need to save this new value to the store
- IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore();
- store.setValue(PREFS_SDK_DIR, mOsSdkLocation);
- }
-
- @Override
- public void initializeDefaultPreferences() {
- IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore();
- initializeStoreWithDefaults(store);
- }
-
- public void initializeStoreWithDefaults(IPreferenceStore store) {
- store.setDefault(PREFS_BUILD_RES_AUTO_REFRESH, true);
- store.setDefault(PREFS_BUILD_FORCE_ERROR_ON_NATIVELIB_IN_JAR, true);
- store.setDefault(PREFS_BUILD_SKIP_POST_COMPILE_ON_FILE_SAVE, true);
-
- store.setDefault(PREFS_BUILD_VERBOSITY, BuildVerbosity.ALWAYS.name());
-
- store.setDefault(PREFS_HOME_PACKAGE, "android.process.acore"); //$NON-NLS-1$
-
- store.setDefault(PREFS_MONITOR_DENSITY, 0.f);
-
- store.setDefault(PREFS_FORMAT_GUI_XML, true);
- store.setDefault(PREFS_USE_CUSTOM_XML_FORMATTER, true);
- store.setDefault(PREFS_ONE_ATTR_PER_LINE, true);
- store.setDefault(PREFS_SPACE_BEFORE_CLOSE, true);
- store.setDefault(PREFS_LINT_ON_SAVE, true);
- store.setDefault(PREFS_LINT_ON_EXPORT, true);
- store.setDefault(PREFS_AUTO_PICK_TARGET, true);
-
- // Defaults already handled; no need to write into map:
- //store.setDefault(PREFS_ATTRIBUTE_SORT, XmlAttributeSortOrder.LOGICAL.key);
- //store.setDefault(PREFS_USE_ECLIPSE_INDENT, false);
- //store.setDefault(PREVS_REMOVE_EMPTY_LINES, false);
- //store.setDefault(PREFS_FORMAT_ON_SAVE, false);
- //store.setDefault(PREFS_SHARED_LAYOUT_EDITOR, false);
- //store.setDefault(PREFS_SKIP_LINT_LIBS, false);
-
- try {
- store.setDefault(PREFS_DEFAULT_DEBUG_KEYSTORE,
- DebugKeyProvider.getDefaultKeyStoreOsPath());
- } catch (KeytoolException e) {
- AdtPlugin.log(e, "Get default debug keystore path failed"); //$NON-NLS-1$
- } catch (AndroidLocationException e) {
- AdtPlugin.log(e, "Get default debug keystore path failed"); //$NON-NLS-1$
- }
- }
-
- /**
- * Returns whether the most recent page switch was to XML
- *
- * @param editorType the editor to check a preference for; corresponds to
- * one of the persistence class ids returned by
- * {@link AndroidXmlEditor#getPersistenceCategory}
- * @return whether the most recent page switch in the given editor was to
- * XML
- */
- public boolean isXmlEditorPreferred(int editorType) {
- return (mPreferXmlEditor & editorType) != 0;
- }
-
- /**
- * Set whether the most recent page switch for a given editor type was to
- * XML
- *
- * @param editorType the editor to check a preference for; corresponds to
- * one of the persistence class ids returned by
- * {@link AndroidXmlEditor#getPersistenceCategory}
- * @param xml whether the last manual page switch in the given editor type
- * was to XML
- */
- public void setXmlEditorPreferred(int editorType, boolean xml) {
- if (xml != isXmlEditorPreferred(editorType)) {
- if (xml) {
- mPreferXmlEditor |= editorType;
- } else {
- mPreferXmlEditor &= ~editorType;
- }
- assert ((mPreferXmlEditor & editorType) != 0) == xml;
- IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore();
- store.setValue(PREFS_PREFER_XML, xml);
- }
- }
-
- /**
- * Gets the {@link RenderPreviewMode}
- *
- * @return the preview mode
- */
- @NonNull
- public RenderPreviewMode getRenderPreviewMode() {
- return mPreviewMode;
- }
-
- /**
- * Sets the {@link RenderPreviewMode}
- *
- * @param previewMode the preview mode
- */
- public void setPreviewMode(@NonNull RenderPreviewMode previewMode) {
- mPreviewMode = previewMode;
- IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore();
- if (previewMode != RenderPreviewMode.NONE) {
- store.setValue(PREFS_PREVIEWS, previewMode.name().toLowerCase(Locale.US));
- } else {
- store.setToDefault(PREFS_PREVIEWS);
- }
- }
-
- /**
- * Sets whether auto-pick render target mode is enabled.
- *
- * @return whether the layout editor should automatically pick the best render target
- */
- public boolean isAutoPickRenderTarget() {
- return mAutoPickTarget;
- }
-
- /**
- * Sets whether auto-pick render target mode is enabled.
- *
- * @param autoPick if true, auto pick the best render target in the layout editor
- */
- public void setAutoPickRenderTarget(boolean autoPick) {
- mAutoPickTarget = autoPick;
- IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore();
- if (autoPick) {
- store.setToDefault(PREFS_AUTO_PICK_TARGET);
- } else {
- store.setValue(PREFS_AUTO_PICK_TARGET, autoPick);
- }
- }
-
- /**
- * Sets whether libraries should be excluded when running lint on a project
- *
- * @param exclude if true, exclude library projects
- */
- public void setSkipLibrariesFromLint(boolean exclude) {
- if (exclude != mSkipLibrariesFromLint) {
- mSkipLibrariesFromLint = exclude;
- IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore();
- if (exclude) {
- store.setValue(PREFS_SKIP_LINT_LIBS, true);
- } else {
- store.setToDefault(PREFS_SKIP_LINT_LIBS);
- }
- }
- }
-
- /**
- * Returns whether libraries should be excluded when running lint on a project
- *
- * @return if true, exclude library projects
- */
- public boolean getSkipLibrariesFromLint() {
- return mSkipLibrariesFromLint;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/AndroidPreferencePage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/AndroidPreferencePage.java
deleted file mode 100644
index 4fbc01351..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/AndroidPreferencePage.java
+++ /dev/null
@@ -1,266 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.preferences;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtPlugin.CheckSdkErrorHandler;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk.ITargetChangeListener;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdkstats.DdmsPreferenceStore;
-import com.android.sdkstats.SdkStatsService;
-import com.android.sdkuilib.internal.widgets.SdkTargetSelector;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.preference.DirectoryFieldEditor;
-import org.eclipse.jface.preference.FieldEditorPreferencePage;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-
-import java.io.File;
-
-/**
- * This class represents a preference page that is contributed to the
- * Preferences dialog. By subclassing <samp>FieldEditorPreferencePage</samp>,
- * we can use the field support built into JFace that allows us to create a page
- * that is small and knows how to save, restore and apply itself.
- * <p>
- * This page is used to modify preferences only. They are stored in the
- * preference store that belongs to the main plug-in class. That way,
- * preferences can be accessed directly via the preference store.
- */
-
-public class AndroidPreferencePage extends FieldEditorPreferencePage implements
- IWorkbenchPreferencePage {
-
- private SdkDirectoryFieldEditor mDirectoryField;
-
- public AndroidPreferencePage() {
- super(GRID);
- setPreferenceStore(AdtPlugin.getDefault().getPreferenceStore());
- setDescription(Messages.AndroidPreferencePage_Title);
- }
-
- /**
- * Creates the field editors. Field editors are abstractions of the common
- * GUI blocks needed to manipulate various types of preferences. Each field
- * editor knows how to save and restore itself.
- */
- @Override
- public void createFieldEditors() {
-
- mDirectoryField = new SdkDirectoryFieldEditor(AdtPrefs.PREFS_SDK_DIR,
- Messages.AndroidPreferencePage_SDK_Location_, getFieldEditorParent());
-
- addField(mDirectoryField);
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
- */
- @Override
- public void init(IWorkbench workbench) {
- }
-
- @Override
- public void dispose() {
- super.dispose();
-
- if (mDirectoryField != null) {
- mDirectoryField.dispose();
- mDirectoryField = null;
- }
- }
-
- /**
- * Custom version of DirectoryFieldEditor which validates that the directory really
- * contains an SDK.
- *
- * There's a known issue here, which is really a rare edge-case: if the pref dialog is open
- * which a given sdk directory and the *content* of the directory changes such that the sdk
- * state changed (i.e. from valid to invalid or vice versa), the pref panel will display or
- * hide the error as appropriate but the pref panel will fail to validate the apply/ok buttons
- * appropriately. The easy workaround is to cancel the pref panel and enter it again.
- */
- private static class SdkDirectoryFieldEditor extends DirectoryFieldEditor {
-
- private SdkTargetSelector mTargetSelector;
- private TargetChangedListener mTargetChangeListener;
-
- public SdkDirectoryFieldEditor(String name, String labelText, Composite parent) {
- super(name, labelText, parent);
- setEmptyStringAllowed(false);
- }
-
- /**
- * Method declared on StringFieldEditor and overridden in DirectoryFieldEditor.
- * Checks whether the text input field contains a valid directory.
- *
- * @return True if the apply/ok button should be enabled in the pref panel
- */
- @Override
- protected boolean doCheckState() {
- String fileName = getTextControl().getText();
- fileName = fileName.trim();
-
- if (fileName.indexOf(',') >= 0 || fileName.indexOf(';') >= 0) {
- setErrorMessage(Messages.AndroidPreferencePage_ERROR_Reserved_Char);
- return false; // Apply/OK must be disabled
- }
-
- File file = new File(fileName);
- if (!file.isDirectory()) {
- setErrorMessage(JFaceResources.getString(
- "DirectoryFieldEditor.errorMessage")); //$NON-NLS-1$
- return false;
- }
-
- boolean ok = AdtPlugin.getDefault().checkSdkLocationAndId(fileName,
- new AdtPlugin.CheckSdkErrorHandler() {
- @Override
- public boolean handleError(
- CheckSdkErrorHandler.Solution solution,
- String message) {
- setErrorMessage(message.replaceAll("\n", " ")); //$NON-NLS-1$ //$NON-NLS-2$
- return false; // Apply/OK must be disabled
- }
-
- @Override
- public boolean handleWarning(
- CheckSdkErrorHandler.Solution solution,
- String message) {
- showMessage(message.replaceAll("\n", " ")); //$NON-NLS-1$ //$NON-NLS-2$
- return true; // Apply/OK must be enabled
- }
- });
- if (ok) clearMessage();
- return ok;
- }
-
- @Override
- protected void doStore() {
- super.doStore();
-
- // Also sync the value to the ~/.android preference settings such that we can
- // share it with future new workspaces
- String path = AdtPrefs.getPrefs().getOsSdkFolder();
- if (path != null && path.length() > 0 && new File(path).exists()) {
- DdmsPreferenceStore ddmsStore = new DdmsPreferenceStore();
- ddmsStore.setLastSdkPath(path);
- }
- }
-
- @Override
- public Text getTextControl(Composite parent) {
- setValidateStrategy(VALIDATE_ON_KEY_STROKE);
- return super.getTextControl(parent);
- }
-
- /* (non-Javadoc)
- * Method declared on StringFieldEditor (and FieldEditor).
- */
- @Override
- protected void doFillIntoGrid(Composite parent, int numColumns) {
- super.doFillIntoGrid(parent, numColumns);
-
- GridData gd;
- Label l = new Label(parent, SWT.NONE);
- l.setText("Note: The list of SDK Targets below is only reloaded once you hit 'Apply' or 'OK'.");
- gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan = numColumns;
- l.setLayoutData(gd);
-
- try {
- // We may not have an sdk if the sdk path pref is empty or not valid.
- Sdk sdk = Sdk.getCurrent();
- IAndroidTarget[] targets = sdk != null ? sdk.getTargets() : null;
-
- mTargetSelector = new SdkTargetSelector(parent,
- targets,
- false /*allowSelection*/);
- gd = (GridData) mTargetSelector.getLayoutData();
- gd.horizontalSpan = numColumns;
-
- if (mTargetChangeListener == null) {
- mTargetChangeListener = new TargetChangedListener();
- AdtPlugin.getDefault().addTargetListener(mTargetChangeListener);
-
- // Trigger a check to see if the SDK needs to be reloaded (which will
- // invoke onSdkLoaded asynchronously as needed).
- AdtPlugin.getDefault().refreshSdk();
- }
- } catch (Exception e) {
- // We need to catch *any* exception that arises here, otherwise it disables
- // the whole pref panel. We can live without the Sdk target selector but
- // not being able to actually set an sdk path.
- AdtPlugin.log(e, "SdkTargetSelector failed");
- }
- }
-
- @Override
- public void dispose() {
- super.dispose();
- if (mTargetChangeListener != null) {
- AdtPlugin.getDefault().removeTargetListener(mTargetChangeListener);
- mTargetChangeListener = null;
- }
- }
-
- private class TargetChangedListener implements ITargetChangeListener {
- @Override
- public void onSdkLoaded() {
- if (mTargetSelector != null) {
- // We may not have an sdk if the sdk path pref is empty or not valid.
- Sdk sdk = Sdk.getCurrent();
- IAndroidTarget[] targets = sdk != null ? sdk.getTargets() : null;
-
- mTargetSelector.setTargets(targets);
- }
- }
-
- @Override
- public void onProjectTargetChange(IProject changedProject) {
- // do nothing.
- }
-
- @Override
- public void onTargetLoaded(IAndroidTarget target) {
- // do nothing.
- }
- }
- }
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
-
- /* When the ADT preferences page is made visible, display the dialog to obtain
- * permissions for the ping service. */
- SdkStatsService stats = new SdkStatsService();
- Shell parent = getShell();
- stats.checkUserPermissionForPing(parent);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/BuildPreferencePage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/BuildPreferencePage.java
deleted file mode 100644
index f5f4633ea..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/BuildPreferencePage.java
+++ /dev/null
@@ -1,386 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.preferences;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs.BuildVerbosity;
-import com.android.ide.eclipse.adt.internal.utils.FingerprintUtils;
-import com.android.prefs.AndroidLocation.AndroidLocationException;
-import com.android.sdklib.internal.build.DebugKeyProvider;
-import com.android.sdklib.internal.build.DebugKeyProvider.KeytoolException;
-
-import org.eclipse.jface.preference.BooleanFieldEditor;
-import org.eclipse.jface.preference.FieldEditorPreferencePage;
-import org.eclipse.jface.preference.FileFieldEditor;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.preference.RadioGroupFieldEditor;
-import org.eclipse.jface.preference.StringFieldEditor;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-
-import java.io.File;
-import java.io.IOException;
-import java.security.GeneralSecurityException;
-import java.security.PrivateKey;
-import java.security.cert.Certificate;
-import java.security.cert.X509Certificate;
-import java.util.Date;
-
-/**
- * Preference page for build options.
- *
- */
-public class BuildPreferencePage extends FieldEditorPreferencePage implements
- IWorkbenchPreferencePage {
-
- private IPreferenceStore mPrefStore = null;
-
- // default key store
- private ReadOnlyFieldEditor mDefaultKeyStore = null;
- private LabelField mDefaultFingerprintMd5 = null;
- private LabelField mDefaultFingerprintSha1 = null;
-
- // custom key store
- private KeystoreFieldEditor mCustomKeyStore = null;
- private LabelField mCustomFingerprintMd5 = null;
- private LabelField mCustomFingerprintSha1 = null;
-
- public BuildPreferencePage() {
- super(GRID);
- mPrefStore = AdtPlugin.getDefault().getPreferenceStore();
- setPreferenceStore(mPrefStore);
- setDescription(Messages.BuildPreferencePage_Title);
- }
-
- @Override
- protected void createFieldEditors() {
- addField(new BooleanFieldEditor(AdtPrefs.PREFS_BUILD_RES_AUTO_REFRESH,
- Messages.BuildPreferencePage_Auto_Refresh_Resources_on_Build,
- getFieldEditorParent()));
-
- addField(new BooleanFieldEditor(AdtPrefs.PREFS_BUILD_FORCE_ERROR_ON_NATIVELIB_IN_JAR,
- "Force error when external jars contain native libraries",
- getFieldEditorParent()));
-
- addField(new BooleanFieldEditor(AdtPrefs.PREFS_BUILD_SKIP_POST_COMPILE_ON_FILE_SAVE,
- "Skip packaging and dexing until export or launch. (Speeds up automatic builds on file save)",
- getFieldEditorParent()));
-
- RadioGroupFieldEditor rgfe = new RadioGroupFieldEditor(
- AdtPrefs.PREFS_BUILD_VERBOSITY,
- Messages.BuildPreferencePage_Build_Output, 1, new String[][] {
- { Messages.BuildPreferencePage_Silent, BuildVerbosity.ALWAYS.name() },
- { Messages.BuildPreferencePage_Normal, BuildVerbosity.NORMAL.name() },
- { Messages.BuildPreferencePage_Verbose, BuildVerbosity.VERBOSE.name() }
- },
- getFieldEditorParent(), true);
- addField(rgfe);
-
- // default debug keystore fingerprints
- Fingerprints defaultFingerprints = getFingerprints(
- mPrefStore.getString(AdtPrefs.PREFS_DEFAULT_DEBUG_KEYSTORE));
-
- // default debug key store fields
- mDefaultKeyStore = new ReadOnlyFieldEditor(AdtPrefs.PREFS_DEFAULT_DEBUG_KEYSTORE,
- Messages.BuildPreferencePage_Default_KeyStore, getFieldEditorParent());
- mDefaultFingerprintMd5 = new LabelField(
- Messages.BuildPreferencePage_Default_Certificate_Fingerprint_MD5,
- defaultFingerprints != null ? defaultFingerprints.md5 : "",
- getFieldEditorParent());
- mDefaultFingerprintSha1 = new LabelField(
- Messages.BuildPreferencePage_Default_Certificate_Fingerprint_SHA1,
- defaultFingerprints != null ? defaultFingerprints.sha1 : "",
- getFieldEditorParent());
-
- addField(mDefaultKeyStore);
- addField(mDefaultFingerprintMd5);
- addField(mDefaultFingerprintSha1);
-
- // custom debug keystore fingerprints
- Fingerprints customFingerprints = null;
-
- String customDebugKeystorePath = mPrefStore.getString(AdtPrefs.PREFS_CUSTOM_DEBUG_KEYSTORE);
- if (new File(customDebugKeystorePath).isFile()) {
- customFingerprints = getFingerprints(customDebugKeystorePath);
- } else {
- // file does not exist.
- setErrorMessage("Not a valid keystore path.");
- }
-
- // custom debug key store fields
- mCustomKeyStore = new KeystoreFieldEditor(AdtPrefs.PREFS_CUSTOM_DEBUG_KEYSTORE,
- Messages.BuildPreferencePage_Custom_Keystore, getFieldEditorParent());
- mCustomFingerprintMd5 = new LabelField(
- Messages.BuildPreferencePage_Default_Certificate_Fingerprint_MD5,
- customFingerprints != null ? customFingerprints.md5 : "",
- getFieldEditorParent());
- mCustomFingerprintSha1 = new LabelField(
- Messages.BuildPreferencePage_Default_Certificate_Fingerprint_SHA1,
- customFingerprints != null ? customFingerprints.sha1 : "",
- getFieldEditorParent());
-
- // set fingerprint fields
- mCustomKeyStore.setFingerprintMd5Field(mCustomFingerprintMd5);
- mCustomKeyStore.setFingerprintSha1Field(mCustomFingerprintSha1);
-
- addField(mCustomKeyStore);
- addField(mCustomFingerprintMd5);
- addField(mCustomFingerprintSha1);
- }
-
- /**
- * MD5 & SHA1 fingerprints.
- */
- private static class Fingerprints {
- final String md5;
- final String sha1;
-
- Fingerprints(String md5Val, String sha1Val) {
- md5 = md5Val;
- sha1 = sha1Val;
- }
- }
-
- private Fingerprints getFingerprints(String keystorePath) {
- // attempt to load the debug key.
- try {
- DebugKeyProvider keyProvider = new DebugKeyProvider(keystorePath,
- null /* storeType */, null /* key gen output */);
-
- return new Fingerprints(
- FingerprintUtils.getFingerprint(keyProvider.getCertificate(), "MD5"),
- FingerprintUtils.getFingerprint(keyProvider.getCertificate(), "SHA1"));
- } catch (GeneralSecurityException e) {
- setErrorMessage(e.getMessage());
- } catch (IOException e) {
- setErrorMessage(e.getMessage());
- } catch (KeytoolException e) {
- setErrorMessage(e.getMessage());
- } catch (AndroidLocationException e) {
- setErrorMessage(e.getMessage());
- }
- return null;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench)
- */
- @Override
- public void init(IWorkbench workbench) {
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.jface.preference.FieldEditorPreferencePage#performDefaults
- * (org.eclipse.jface.preference.PreferencePage#performDefaults)
- */
- @Override
- protected void performDefaults() {
- super.performDefaults();
-
- // restore the default key store fingerprints
- Fingerprints defaultFingerprints = getFingerprints(mPrefStore
- .getString(AdtPrefs.PREFS_DEFAULT_DEBUG_KEYSTORE));
- mDefaultFingerprintMd5.setStringValue(defaultFingerprints.md5);
- mDefaultFingerprintSha1.setStringValue(defaultFingerprints.sha1);
-
- // set custom fingerprint fields to blank
- mCustomFingerprintMd5.setStringValue("");
- mCustomFingerprintSha1.setStringValue("");
- }
-
- /**
- * A read-only string field editor.
- */
- private static class ReadOnlyFieldEditor extends StringFieldEditor {
-
- public ReadOnlyFieldEditor(String name, String labelText, Composite parent) {
- super(name, labelText, parent);
- }
-
- @Override
- protected void createControl(Composite parent) {
- super.createControl(parent);
-
- Text control = getTextControl();
- control.setEditable(false);
- }
- }
-
- /**
- * A read-only string field.
- */
- private static class LabelField extends StringFieldEditor {
- private String text;
-
- public LabelField(String labelText, String value, Composite parent) {
- super("", labelText, parent);
- text = value;
- }
-
- @Override
- protected void createControl(Composite parent) {
- super.createControl(parent);
-
- Text control = getTextControl();
- control.setEditable(false);
- }
-
- @Override
- protected void doLoad() {
- setStringValue(text);
- }
-
- @Override
- protected void doStore() {
- // Do nothing
- }
- }
-
- /**
- * Custom {@link FileFieldEditor} that checks that the keystore is valid.
- */
- private static class KeystoreFieldEditor extends FileFieldEditor {
- private StringFieldEditor fingerprintMd5 = null;
- private StringFieldEditor fingerprintSha1 = null;
-
- public void setFingerprintMd5Field(StringFieldEditor field) {
- fingerprintMd5 = field;
- }
-
- public void setFingerprintSha1Field(StringFieldEditor field) {
- fingerprintSha1 = field;
- }
-
- public KeystoreFieldEditor(String name, String label, Composite parent) {
- super(name, label, parent);
- setValidateStrategy(VALIDATE_ON_KEY_STROKE);
- }
-
- @Override
- protected boolean checkState() {
- String fileName = getTextControl().getText();
- fileName = fileName.trim();
-
- if (fingerprintMd5 != null) {
- fingerprintMd5.setStringValue("");
- }
-
- if (fingerprintSha1 != null) {
- fingerprintSha1.setStringValue("");
- }
-
- // empty values are considered ok.
- if (fileName.length() > 0) {
- File file = new File(fileName);
- if (file.isFile()) {
- // attempt to load the debug key.
- try {
- DebugKeyProvider provider = new DebugKeyProvider(fileName,
- null /* storeType */, null /* key gen output */);
- PrivateKey key = provider.getDebugKey();
- X509Certificate certificate = (X509Certificate)provider.getCertificate();
-
- if (key == null || certificate == null) {
- showErrorMessage("Unable to find debug key in keystore!");
- return false;
- }
-
- if (fingerprintMd5 != null) {
- fingerprintMd5.setStringValue(
- FingerprintUtils.getFingerprint(certificate, "MD5"));
- }
-
- if (fingerprintSha1 != null) {
- fingerprintSha1.setStringValue(
- FingerprintUtils.getFingerprint(certificate, "SHA1"));
- }
-
- Date today = new Date();
- if (certificate.getNotAfter().compareTo(today) < 0) {
- showErrorMessage("Certificate is expired!");
- return false;
- }
-
- if (certificate.getNotBefore().compareTo(today) > 0) {
- showErrorMessage("Certificate validity is in the future!");
- return false;
- }
-
- // we're good!
- clearErrorMessage();
- return true;
- } catch (GeneralSecurityException e) {
- handleException(e);
- return false;
- } catch (IOException e) {
- handleException(e);
- return false;
- } catch (KeytoolException e) {
- handleException(e);
- return false;
- } catch (AndroidLocationException e) {
- handleException(e);
- return false;
- }
-
-
- } else {
- // file does not exist.
- showErrorMessage("Not a valid keystore path.");
- return false; // Apply/OK must be disabled
- }
- }
-
- clearErrorMessage();
- return true;
- }
-
- @Override
- public Text getTextControl(Composite parent) {
- setValidateStrategy(VALIDATE_ON_KEY_STROKE);
- return super.getTextControl(parent);
- }
-
- /**
- * Set the error message from a {@link Throwable}. If the exception has no message, try
- * to get the message from the cause.
- * @param t the Throwable.
- */
- private void handleException(Throwable t) {
- String msg = t.getMessage();
- if (msg == null) {
- Throwable cause = t.getCause();
- if (cause != null) {
- handleException(cause);
- } else {
- setErrorMessage("Uknown error when getting the debug key!");
- }
-
- return;
- }
-
- // valid text, display it.
- showErrorMessage(msg);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/EditorsPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/EditorsPage.java
deleted file mode 100644
index d33b49f6d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/EditorsPage.java
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.preferences;
-
-import static com.android.ide.common.xml.XmlAttributeSortOrder.ALPHABETICAL;
-import static com.android.ide.common.xml.XmlAttributeSortOrder.LOGICAL;
-import static com.android.ide.common.xml.XmlAttributeSortOrder.NO_SORTING;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.sdkuilib.internal.widgets.ResolutionChooserDialog;
-
-import org.eclipse.jface.preference.BooleanFieldEditor;
-import org.eclipse.jface.preference.FieldEditorPreferencePage;
-import org.eclipse.jface.preference.RadioGroupFieldEditor;
-import org.eclipse.jface.preference.StringButtonFieldEditor;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-
-/**
- * Preference page for the editors.
- */
-public class EditorsPage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage {
- private BooleanFieldEditor mIndentEditor;
- private BooleanFieldEditor mRemoveEmptyEditor;
- private BooleanFieldEditor mOneAttrPerLineEditor;
- private BooleanFieldEditor mSpaceBeforeCloseEditor;
- private BooleanFieldEditor mFormatGuiXmlEditor;
-
- /**
- * Constructs a new Android editors preference page
- */
- public EditorsPage() {
- super(GRID);
- setPreferenceStore(AdtPlugin.getDefault().getPreferenceStore());
- }
-
- @Override
- public void init(IWorkbench workbench) {
- // pass
- }
-
- @Override
- protected void createFieldEditors() {
- Composite parent = getFieldEditorParent();
-
- addField(new DensityFieldEditor(AdtPrefs.PREFS_MONITOR_DENSITY,
- "Monitor Density", parent));
-
- final MyBooleanFieldEditor editor = new MyBooleanFieldEditor(
- AdtPrefs.PREFS_USE_CUSTOM_XML_FORMATTER,
- "Format XML files using the standard Android XML style rather than the \n" +
- "configured Eclipse XML style (additional options below)",
- parent);
- addField(editor);
-
- // Add a listener which fires whenever the checkbox for the custom formatter
- // is toggled -- this will be used to enable/disable the formatting related options
- // on the page. To do this we subclass the BooleanFieldEditor to make the protected
- // method getChangeControl public (so we can access it and add a listener on it).
- // This is pretty ugly but I found several posts in the Eclipse forums asking
- // how to do it and they were all unanswered. (No, calling setPropertyChangeListener
- // does not work.)
- Button checkbox = editor.getChangeControl(parent);
- checkbox.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateCustomFormattingOptions(editor.getBooleanValue());
- }
- });
-
- mIndentEditor = new BooleanFieldEditor(AdtPrefs.PREFS_USE_ECLIPSE_INDENT,
- "Use Eclipse setting for indentation width and space or tab character "
- + "indentation \n(Android default is 4 space characters)",
- parent);
- addField(mIndentEditor);
-
- mRemoveEmptyEditor = new BooleanFieldEditor(AdtPrefs.PREVS_REMOVE_EMPTY_LINES,
- "Always remove empty lines between elements",
- parent);
- addField(mRemoveEmptyEditor);
-
- mOneAttrPerLineEditor = new BooleanFieldEditor(AdtPrefs.PREFS_ONE_ATTR_PER_LINE,
- "Allow single attributes to appear on the same line as their elements",
- parent);
- addField(mOneAttrPerLineEditor);
-
- mSpaceBeforeCloseEditor = new BooleanFieldEditor(AdtPrefs.PREFS_SPACE_BEFORE_CLOSE,
- "Add a space before the > or /> in opening tags",
- parent);
- addField(mSpaceBeforeCloseEditor);
-
- addField(new RadioGroupFieldEditor(AdtPrefs.PREFS_ATTRIBUTE_SORT,
- "Sort Attributes", 1,
- new String[][] {
- { "&Logical (id, style, layout attributes, remaining attributes alphabetically)",
- LOGICAL.key },
- { "&Alphabetical", ALPHABETICAL.key },
- { "&None", NO_SORTING.key },
- },
- parent, true));
-
- mFormatGuiXmlEditor = new BooleanFieldEditor(AdtPrefs.PREFS_FORMAT_GUI_XML,
- "Automatically format the XML edited by the visual layout editor",
- parent);
- addField(mFormatGuiXmlEditor);
-
- addField(new BooleanFieldEditor(AdtPrefs.PREFS_FORMAT_ON_SAVE,
- "Format on Save",
- parent));
-
- addField(new BooleanFieldEditor(AdtPrefs.PREFS_SHARED_LAYOUT_EDITOR,
- "Use a single layout editor for all configuration variations of a layout",
- parent));
-
- boolean enabled = getPreferenceStore().getBoolean(AdtPrefs.PREFS_USE_CUSTOM_XML_FORMATTER);
- updateCustomFormattingOptions(enabled);
- }
-
- private void updateCustomFormattingOptions(boolean enabled) {
- Composite parent = getFieldEditorParent();
- mIndentEditor.setEnabled(enabled, parent);
- mRemoveEmptyEditor.setEnabled(enabled, parent);
- mOneAttrPerLineEditor.setEnabled(enabled, parent);
- mSpaceBeforeCloseEditor.setEnabled(enabled, parent);
- mFormatGuiXmlEditor.setEnabled(enabled, parent);
- }
-
- /**
- * Overridden solely so that I can get access to the checkbox button to listen to
- * state changes
- */
- private class MyBooleanFieldEditor extends BooleanFieldEditor {
- public MyBooleanFieldEditor(String name, String label, Composite parent) {
- super(name, label, parent);
- }
- @Override
- protected Button getChangeControl(Composite parent) {
- return super.getChangeControl(parent);
- }
- }
-
- /**
- * Custom {@link StringButtonFieldEditor} to call out to {@link ResolutionChooserDialog}
- * when the button is called.
- */
- private static class DensityFieldEditor extends StringButtonFieldEditor {
-
- public DensityFieldEditor(String name, String labelText, Composite parent) {
- super(name, labelText, parent);
- setChangeButtonText("Compute...");
- }
-
- @Override
- protected String changePressed() {
- ResolutionChooserDialog dialog = new ResolutionChooserDialog(getShell());
- if (dialog.open() == Window.OK) {
- return Integer.toString(dialog.getDensity());
- }
-
- return null;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/LaunchPreferencePage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/LaunchPreferencePage.java
deleted file mode 100644
index 0ac1f0f39..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/LaunchPreferencePage.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.preferences;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import org.eclipse.jface.preference.FieldEditorPreferencePage;
-import org.eclipse.jface.preference.StringFieldEditor;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-
-/**
- * Settings page for launch related preferences.
- */
-public class LaunchPreferencePage extends FieldEditorPreferencePage implements
- IWorkbenchPreferencePage {
-
- public LaunchPreferencePage() {
- super(GRID);
- setPreferenceStore(AdtPlugin.getDefault().getPreferenceStore());
- setDescription(Messages.LaunchPreferencePage_Title);
- }
-
- @Override
- protected void createFieldEditors() {
- addField(new StringFieldEditor(AdtPrefs.PREFS_EMU_OPTIONS,
- Messages.LaunchPreferencePage_Default_Emu_Options, getFieldEditorParent()));
-
- addField(new StringFieldEditor(AdtPrefs.PREFS_HOME_PACKAGE,
- Messages.LaunchPreferencePage_Default_HOME_Package, getFieldEditorParent()));
- }
-
- @Override
- public void init(IWorkbench workbench) {
- // pass
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/LintPreferencePage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/LintPreferencePage.java
deleted file mode 100644
index 5cb94ba4b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/LintPreferencePage.java
+++ /dev/null
@@ -1,752 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.preferences;
-
-import static com.android.tools.lint.detector.api.TextFormat.RAW;
-import static com.android.tools.lint.detector.api.TextFormat.TEXT;
-
-import com.android.annotations.NonNull;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.lint.EclipseLintClient;
-import com.android.ide.eclipse.adt.internal.lint.EclipseLintRunner;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.tools.lint.client.api.Configuration;
-import com.android.tools.lint.client.api.IssueRegistry;
-import com.android.tools.lint.detector.api.Category;
-import com.android.tools.lint.detector.api.Issue;
-import com.android.tools.lint.detector.api.Project;
-import com.android.tools.lint.detector.api.Severity;
-import com.android.tools.lint.detector.api.TextFormat;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.IColorProvider;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.TreeNodeContentProvider;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.TreeViewerColumn;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ControlEvent;
-import org.eclipse.swt.events.ControlListener;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.events.TraverseEvent;
-import org.eclipse.swt.events.TraverseListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeColumn;
-import org.eclipse.swt.widgets.TreeItem;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.PreferencesUtil;
-import org.eclipse.ui.dialogs.PropertyPage;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-
-/** Preference page for configuring Lint preferences */
-public class LintPreferencePage extends PropertyPage implements IWorkbenchPreferencePage,
- SelectionListener, ControlListener, ModifyListener {
- private static final String ID =
- "com.android.ide.eclipse.common.preferences.LintPreferencePage"; //$NON-NLS-1$
- private static final int ID_COLUMN_WIDTH = 150;
-
- private EclipseLintClient mClient;
- private IssueRegistry mRegistry;
- private Configuration mConfiguration;
- private IProject mProject;
- private Map<Issue, Severity> mSeverities = new HashMap<Issue, Severity>();
- private Map<Issue, Severity> mInitialSeverities = Collections.<Issue, Severity>emptyMap();
- private boolean mIgnoreEvent;
-
- private Tree mTree;
- private TreeViewer mTreeViewer;
- private Text mDetailsText;
- private Button mCheckFileCheckbox;
- private Button mCheckExportCheckbox;
- private Link mWorkspaceLink;
- private TreeColumn mNameColumn;
- private TreeColumn mIdColumn;
- private Combo mSeverityCombo;
- private Button mIncludeAll;
- private Button mIgnoreAll;
- private Text mSearch;
-
- /**
- * Create the preference page.
- */
- public LintPreferencePage() {
- setPreferenceStore(AdtPlugin.getDefault().getPreferenceStore());
- }
-
- @Override
- public Control createContents(Composite parent) {
- IAdaptable resource = getElement();
- if (resource != null) {
- mProject = (IProject) resource.getAdapter(IProject.class);
- }
-
- Composite container = new Composite(parent, SWT.NULL);
- container.setLayout(new GridLayout(2, false));
-
- if (mProject != null) {
- Label projectLabel = new Label(container, SWT.CHECK);
- projectLabel.setLayoutData(new GridData(SWT.LEFT, SWT.BOTTOM, false, false, 1,
- 1));
- projectLabel.setText("Project-specific configuration:");
-
- mWorkspaceLink = new Link(container, SWT.NONE);
- mWorkspaceLink.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- mWorkspaceLink.setText("<a>Configure Workspace Settings...</a>");
- mWorkspaceLink.addSelectionListener(this);
- } else {
- mCheckFileCheckbox = new Button(container, SWT.CHECK);
- mCheckFileCheckbox.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false,
- 2, 1));
- mCheckFileCheckbox.setSelection(true);
- mCheckFileCheckbox.setText("When saving files, check for errors");
-
- mCheckExportCheckbox = new Button(container, SWT.CHECK);
- mCheckExportCheckbox.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false,
- 2, 1));
- mCheckExportCheckbox.setSelection(true);
- mCheckExportCheckbox.setText("Run full error check when exporting app and abort if fatal errors are found");
-
- Label separator = new Label(container, SWT.SEPARATOR | SWT.HORIZONTAL);
- separator.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1));
-
- Label checkListLabel = new Label(container, SWT.NONE);
- checkListLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
- checkListLabel.setText("Issues:");
- }
-
- mRegistry = EclipseLintClient.getRegistry();
- mClient = new EclipseLintClient(mRegistry,
- mProject != null ? Collections.singletonList(mProject) : null, null, false);
- Project project = null;
- if (mProject != null) {
- File dir = AdtUtils.getAbsolutePath(mProject).toFile();
- project = mClient.getProject(dir, dir);
- }
- mConfiguration = mClient.getConfigurationFor(project);
-
- mSearch = new Text(container, SWT.SEARCH | SWT.ICON_CANCEL | SWT.ICON_SEARCH);
- mSearch.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
- mSearch.addSelectionListener(this);
- mSearch.addModifyListener(this);
- // Grab the Enter key such that pressing return in the search box filters (instead
- // of closing the options dialog)
- mSearch.setMessage("type filter text (use ~ to filter by severity, e.g. ~ignore)");
- mSearch.addTraverseListener(new TraverseListener() {
- @Override
- public void keyTraversed(TraverseEvent e) {
- if (e.keyCode == SWT.CR) {
- updateFilter();
- e.doit = false;
- } else if (e.keyCode == SWT.ARROW_DOWN) {
- // Allow moving from the search into the table
- if (mTree.getItemCount() > 0) {
- TreeItem firstCategory = mTree.getItem(0);
- if (firstCategory.getItemCount() > 0) {
- TreeItem first = firstCategory.getItem(0);
- mTree.setFocus();
- mTree.select(first);
- }
- }
- }
- }
- });
-
- mTreeViewer = new TreeViewer(container, SWT.BORDER | SWT.FULL_SELECTION);
- mTree = mTreeViewer.getTree();
- GridData gdTable = new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1);
- gdTable.widthHint = 500;
- gdTable.heightHint = 160;
- mTree.setLayoutData(gdTable);
- mTree.setLinesVisible(true);
- mTree.setHeaderVisible(true);
-
- TreeViewerColumn column1 = new TreeViewerColumn(mTreeViewer, SWT.NONE);
- mIdColumn = column1.getColumn();
- mIdColumn.setWidth(100);
- mIdColumn.setText("Id");
-
- TreeViewerColumn column2 = new TreeViewerColumn(mTreeViewer, SWT.FILL);
- mNameColumn = column2.getColumn();
- mNameColumn.setWidth(100);
- mNameColumn.setText("Name");
-
- mTreeViewer.setContentProvider(new ContentProvider());
- mTreeViewer.setLabelProvider(new LabelProvider());
-
- mDetailsText = new Text(container, SWT.BORDER | SWT.READ_ONLY | SWT.WRAP |SWT.V_SCROLL
- | SWT.MULTI);
- GridData gdText = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 2);
- gdText.heightHint = 80;
- mDetailsText.setLayoutData(gdText);
-
- Label severityLabel = new Label(container, SWT.NONE);
- severityLabel.setText("Severity:");
-
- mSeverityCombo = new Combo(container, SWT.READ_ONLY);
- mSeverityCombo.setItems(new String[] {
- "(Default)", "Fatal", "Error", "Warning", "Information", "Ignore"
- });
- GridData gdSeverityCombo = new GridData(SWT.FILL, SWT.TOP, false, false, 1, 1);
- gdSeverityCombo.widthHint = 90;
- mSeverityCombo.setLayoutData(gdSeverityCombo);
- mSeverityCombo.setText("");
- mSeverityCombo.addSelectionListener(this);
-
- List<Issue> issues = mRegistry.getIssues();
- for (Issue issue : issues) {
- Severity severity = mConfiguration.getSeverity(issue);
- mSeverities.put(issue, severity);
- }
- mInitialSeverities = new HashMap<Issue, Severity>(mSeverities);
-
- mTreeViewer.setInput(mRegistry);
-
- mTree.addSelectionListener(this);
- // Add a listener to resize the column to the full width of the table
- mTree.addControlListener(this);
-
- loadSettings(false);
-
- mTreeViewer.expandAll();
-
- return container;
- }
-
- /**
- * Initialize the preference page.
- */
- @Override
- public void init(IWorkbench workbench) {
- // Initialize the preference page
- }
-
- @Override
- protected void contributeButtons(Composite parent) {
- super.contributeButtons(parent);
-
- // Add "Include All" button for quickly enabling all the detectors, including
- // those disabled by default
- mIncludeAll = new Button(parent, SWT.PUSH);
- mIncludeAll.setText("Include All");
- mIncludeAll.addSelectionListener(this);
-
- // Add "Ignore All" button for quickly disabling all the detectors
- mIgnoreAll = new Button(parent, SWT.PUSH);
- mIgnoreAll.setText("Ignore All");
- mIgnoreAll.addSelectionListener(this);
-
- // As per the contributeButton javadoc: increase parent's column count for each
- // added button
- ((GridLayout) parent.getLayout()).numColumns += 2;
- }
-
- @Override
- public void dispose() {
- super.dispose();
- cancelPendingSearch();
- }
-
- @Override
- protected void performDefaults() {
- super.performDefaults();
-
- mConfiguration.startBulkEditing();
-
- List<Issue> issues = mRegistry.getIssues();
- for (Issue issue : issues) {
- mConfiguration.setSeverity(issue, null);
- }
-
- mConfiguration.finishBulkEditing();
-
- loadSettings(true);
- }
-
- @Override
- public boolean performOk() {
- storeSettings();
- return true;
- }
-
- private void loadSettings(boolean refresh) {
- if (mCheckExportCheckbox != null) {
- AdtPrefs prefs = AdtPrefs.getPrefs();
- mCheckFileCheckbox.setSelection(prefs.isLintOnSave());
- mCheckExportCheckbox.setSelection(prefs.isLintOnExport());
- }
-
- mSeverities.clear();
- List<Issue> issues = mRegistry.getIssues();
- for (Issue issue : issues) {
- Severity severity = mConfiguration.getSeverity(issue);
- mSeverities.put(issue, severity);
- }
-
- if (refresh) {
- mTreeViewer.refresh();
- }
- }
-
- private void storeSettings() {
- // Lint on Save, Lint on Export
- if (mCheckExportCheckbox != null) {
- AdtPrefs prefs = AdtPrefs.getPrefs();
- prefs.setLintOnExport(mCheckExportCheckbox.getSelection());
- prefs.setLintOnSave(mCheckFileCheckbox.getSelection());
- }
-
- if (mConfiguration == null) {
- return;
- }
-
- mConfiguration.startBulkEditing();
- try {
- // Severities
- for (Map.Entry<Issue, Severity> entry : mSeverities.entrySet()) {
- Issue issue = entry.getKey();
- Severity severity = entry.getValue();
- if (mConfiguration.getSeverity(issue) != severity) {
- if ((severity == issue.getDefaultSeverity()) && issue.isEnabledByDefault()) {
- severity = null;
- }
- mConfiguration.setSeverity(issue, severity);
- }
- }
- } finally {
- mConfiguration.finishBulkEditing();
- }
-
- if (!mInitialSeverities.equals(mSeverities)) {
- // Ask user whether we should re-run the rules.
- MessageDialog dialog = new MessageDialog(
- null, "Lint Settings Have Changed", null,
- "The list of enabled checks has changed. Would you like to run lint now " +
- "to update the results?",
- MessageDialog.QUESTION,
- new String[] {
- "Yes", "No"
- },
- 0); // yes is the default
- int result = dialog.open();
- if (result == 0) {
- // Run lint on all the open Android projects
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IProject[] projects = workspace.getRoot().getProjects();
- List<IProject> androidProjects = new ArrayList<IProject>(projects.length);
- for (IProject project : projects) {
- if (project.isOpen() && BaseProjectHelper.isAndroidProject(project)) {
- androidProjects.add(project);
- }
- }
-
- EclipseLintRunner.startLint(androidProjects, null, null, false /*fatalOnly*/,
- true /*show*/);
- }
- }
- }
-
- private void updateFilter() {
- cancelPendingSearch();
- if (!mSearch.isDisposed()) {
- // Clear selection before refiltering since otherwise it might be showing
- // items no longer available in the list.
- mTree.setSelection(new TreeItem[0]);
- mDetailsText.setText("");
- try {
- mIgnoreEvent = true;
- mSeverityCombo.setText("");
- mSeverityCombo.setEnabled(false);
- } finally {
- mIgnoreEvent = false;
- }
-
- mTreeViewer.getContentProvider().inputChanged(mTreeViewer, null, mRegistry);
- mTreeViewer.refresh();
- mTreeViewer.expandAll();
- }
- }
-
- private void cancelPendingSearch() {
- if (mPendingUpdate != null) {
- Shell shell = getShell();
- if (!shell.isDisposed()) {
- getShell().getDisplay().timerExec(-1, mPendingUpdate);
- }
- mPendingUpdate = null;
- }
- }
-
- private Runnable mPendingUpdate;
-
- private void scheduleSearch() {
- if (mPendingUpdate == null) {
- mPendingUpdate = new Runnable() {
- @Override
- public void run() {
- mPendingUpdate = null;
- updateFilter();
- }
- };
- }
- getShell().getDisplay().timerExec(250 /*ms*/, mPendingUpdate);
- }
-
- // ---- Implements SelectionListener ----
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (mIgnoreEvent) {
- return;
- }
-
- Object source = e.getSource();
- if (source == mTree) {
- TreeItem item = (TreeItem) e.item;
- Object data = item != null ? item.getData() : null;
- if (data instanceof Issue) {
- Issue issue = (Issue) data;
- String summary = issue.getBriefDescription(TextFormat.TEXT);
- String explanation = issue.getExplanation(TextFormat.TEXT);
-
- StringBuilder sb = new StringBuilder(summary.length() + explanation.length() + 20);
- sb.append(summary);
- sb.append('\n').append('\n');
- sb.append(explanation);
- mDetailsText.setText(sb.toString());
- try {
- mIgnoreEvent = true;
- Severity severity = getSeverity(issue);
- mSeverityCombo.select(severity.ordinal() + 1); // Skip the default option
- mSeverityCombo.setEnabled(true);
- } finally {
- mIgnoreEvent = false;
- }
- } else {
- mDetailsText.setText("");
- try {
- mIgnoreEvent = true;
- mSeverityCombo.setText("");
- mSeverityCombo.setEnabled(false);
- } finally {
- mIgnoreEvent = false;
- }
- }
- } else if (source == mWorkspaceLink) {
- int result = PreferencesUtil.createPreferenceDialogOn(getShell(), ID,
- new String[] { ID }, null).open();
- if (result == Window.OK) {
- loadSettings(true);
- }
- } else if (source == mSeverityCombo) {
- int index = mSeverityCombo.getSelectionIndex();
- Issue issue = (Issue) mTree.getSelection()[0].getData();
- Severity severity;
- if (index == -1 || index == 0) {
- // "(Default)"
- severity = issue.getDefaultSeverity();
- } else {
- // -1: Skip the "(Default)"
- severity = Severity.values()[index - 1];
- }
- mSeverities.put(issue, severity);
- mTreeViewer.refresh();
- } else if (source == mIncludeAll) {
- List<Issue> issues = mRegistry.getIssues();
- for (Issue issue : issues) {
- // The default severity is never ignore; for disabled-by-default
- // issues the {@link Issue#isEnabledByDefault()} method is false instead
- mSeverities.put(issue, issue.getDefaultSeverity());
- }
- mTreeViewer.refresh();
- } else if (source == mIgnoreAll) {
- List<Issue> issues = mRegistry.getIssues();
- for (Issue issue : issues) {
- mSeverities.put(issue, Severity.IGNORE);
- }
- mTreeViewer.refresh();
- } else if (source == mSearch) {
- updateFilter();
- }
- }
-
- private Severity getSeverity(Issue issue) {
- Severity severity = mSeverities.get(issue);
- if (severity != null) {
- return severity;
- }
-
- return mConfiguration.getSeverity(issue);
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- Object source = e.getSource();
- if (source == mTree) {
- widgetSelected(e);
- } else if (source == mSearch) {
- if (e.detail == SWT.CANCEL) {
- // Cancel the search
- mSearch.setText("");
- }
- updateFilter();
- }
- }
-
- // ---- Implements ModifyListener ----
- @Override
- public void modifyText(ModifyEvent e) {
- if (e.getSource() == mSearch) {
- scheduleSearch();
- }
- }
-
- // ---- Implements ControlListener ----
-
- @Override
- public void controlMoved(ControlEvent e) {
- }
-
- @Override
- public void controlResized(ControlEvent e) {
- Rectangle r = mTree.getClientArea();
- int availableWidth = r.width;
-
- mIdColumn.setWidth(ID_COLUMN_WIDTH);
- availableWidth -= ID_COLUMN_WIDTH;
-
- // Name absorbs everything else
- mNameColumn.setWidth(availableWidth);
- }
-
- private boolean filterMatches(@NonNull String filter, @NonNull Issue issue) {
- return (filter.startsWith("~") //$NON-NLS-1$
- && mConfiguration.getSeverity(issue).getDescription()
- .toLowerCase(Locale.US).startsWith(filter.substring(1)))
- || issue.getCategory().getName().toLowerCase(Locale.US).startsWith(filter)
- || issue.getCategory().getFullName().toLowerCase(Locale.US).startsWith(filter)
- || issue.getId().toLowerCase(Locale.US).contains(filter)
- || issue.getBriefDescription(RAW).toLowerCase(Locale.US).contains(filter);
- }
-
- private class ContentProvider extends TreeNodeContentProvider {
- private Map<Category, List<Issue>> mCategoryToIssues;
- private Object[] mElements;
-
- @Override
- public Object[] getElements(Object inputElement) {
- return mElements;
- }
-
- @Override
- public boolean hasChildren(Object element) {
- return element instanceof Category;
- }
-
- @Override
- public Object[] getChildren(Object parentElement) {
- assert mCategoryToIssues != null;
- List<Issue> list = mCategoryToIssues.get(parentElement);
- if (list == null) {
- return new Object[0];
- } else {
- return list.toArray();
- }
- }
-
- @Override
- public Object getParent(Object element) {
- return null;
- }
-
- @Override
- public void inputChanged(final Viewer viewer, final Object oldInput,
- final Object newInput) {
- mCategoryToIssues = null;
-
- String filter = mSearch.isDisposed() ? "" : mSearch.getText().trim();
- if (filter.length() == 0) {
- filter = null;
- } else {
- filter = filter.toLowerCase(Locale.US);
- }
-
- mCategoryToIssues = new HashMap<Category, List<Issue>>();
- List<Issue> issues = mRegistry.getIssues();
- for (Issue issue : issues) {
- if (filter == null || filterMatches(filter, issue)) {
- List<Issue> list = mCategoryToIssues.get(issue.getCategory());
- if (list == null) {
- list = new ArrayList<Issue>();
- mCategoryToIssues.put(issue.getCategory(), list);
- }
- list.add(issue);
- }
- }
-
- if (filter == null) {
- // Not filtering: show all categories
- mElements = mRegistry.getCategories().toArray();
- } else {
- // Filtering: only include categories that contain matches
- if (mCategoryToIssues == null) {
- getChildren(null);
- }
-
- // Preserve the current category order, so instead of
- // just creating a list of the mCategoryToIssues keyset, add them
- // in the order they appear in in the registry
- List<Category> categories = new ArrayList<Category>(mCategoryToIssues.size());
- for (Category category : mRegistry.getCategories()) {
- if (mCategoryToIssues.containsKey(category)) {
- categories.add(category);
- }
- }
- mElements = categories.toArray();
- }
- }
- }
-
- private class LabelProvider implements ITableLabelProvider, IColorProvider {
-
- @Override
- public void addListener(ILabelProviderListener listener) {
- }
-
- @Override
- public void dispose() {
- }
-
- @Override
- public boolean isLabelProperty(Object element, String property) {
- return true;
- }
-
- @Override
- public void removeListener(ILabelProviderListener listener) {
- }
-
- @Override
- public Image getColumnImage(Object element, int columnIndex) {
- if (element instanceof Category) {
- return null;
- }
-
- if (columnIndex == 1) {
- Issue issue = (Issue) element;
- Severity severity = mSeverities.get(issue);
- if (severity == null) {
- return null;
- }
-
- ISharedImages sharedImages = PlatformUI.getWorkbench().getSharedImages();
- switch (severity) {
- case FATAL:
- case ERROR:
- return sharedImages.getImage(ISharedImages.IMG_OBJS_ERROR_TSK);
- case WARNING:
- return sharedImages.getImage(ISharedImages.IMG_OBJS_WARN_TSK);
- case INFORMATIONAL:
- return sharedImages.getImage(ISharedImages.IMG_OBJS_INFO_TSK);
- case IGNORE:
- return sharedImages.getImage(ISharedImages.IMG_ELCL_REMOVE_DISABLED);
- }
- }
- return null;
- }
-
- @Override
- public String getColumnText(Object element, int columnIndex) {
- if (element instanceof Category) {
- if (columnIndex == 0) {
- return ((Category) element).getFullName();
- } else {
- return null;
- }
- }
-
- Issue issue = (Issue) element;
- switch (columnIndex) {
- case 0:
- return issue.getId();
- case 1:
- return issue.getBriefDescription(TEXT);
- }
-
- return null;
- }
-
- // ---- IColorProvider ----
-
- @Override
- public Color getForeground(Object element) {
- if (element instanceof Category) {
- return mTree.getDisplay().getSystemColor(SWT.COLOR_INFO_FOREGROUND);
- }
-
- if (element instanceof Issue) {
- Issue issue = (Issue) element;
- Severity severity = mSeverities.get(issue);
- if (severity == Severity.IGNORE) {
- return mTree.getDisplay().getSystemColor(SWT.COLOR_DARK_GRAY);
- }
- }
-
- return null;
- }
-
- @Override
- public Color getBackground(Object element) {
- if (element instanceof Category) {
- return mTree.getDisplay().getSystemColor(SWT.COLOR_INFO_BACKGROUND);
- }
- return null;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/Messages.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/Messages.java
deleted file mode 100644
index 70b97517c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/Messages.java
+++ /dev/null
@@ -1,51 +0,0 @@
-
-package com.android.ide.eclipse.adt.internal.preferences;
-
-import org.eclipse.osgi.util.NLS;
-
-public class Messages extends NLS {
- private static final String BUNDLE_NAME = "com.android.ide.eclipse.adt.internal.preferences.messages"; //$NON-NLS-1$
-
- public static String AndroidPreferencePage_ERROR_Reserved_Char;
-
- public static String AndroidPreferencePage_SDK_Location_;
-
- public static String AndroidPreferencePage_Title;
-
- public static String BuildPreferencePage_Auto_Refresh_Resources_on_Build;
-
- public static String BuildPreferencePage_Build_Output;
-
- public static String BuildPreferencePage_Custom_Keystore;
-
- public static String BuildPreferencePage_Custom_Certificate_Fingerprint_MD5;
-
- public static String BuildPreferencePage_Custom_Certificate_Fingerprint_SHA1;
-
- public static String BuildPreferencePage_Default_KeyStore;
-
- public static String BuildPreferencePage_Default_Certificate_Fingerprint_MD5;
-
- public static String BuildPreferencePage_Default_Certificate_Fingerprint_SHA1;
-
- public static String BuildPreferencePage_Normal;
-
- public static String BuildPreferencePage_Silent;
-
- public static String BuildPreferencePage_Title;
-
- public static String BuildPreferencePage_Verbose;
-
- public static String LaunchPreferencePage_Default_Emu_Options;
-
- public static String LaunchPreferencePage_Default_HOME_Package;
-
- public static String LaunchPreferencePage_Title;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
-
- private Messages() {
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/messages.properties b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/messages.properties
deleted file mode 100644
index 61894fd4e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/preferences/messages.properties
+++ /dev/null
@@ -1,18 +0,0 @@
-BuildPreferencePage_Title=Build Settings:
-BuildPreferencePage_Auto_Refresh_Resources_on_Build=Automatically refresh Resources and Assets folder on build
-BuildPreferencePage_Build_Output=Build output
-BuildPreferencePage_Silent=Silent
-BuildPreferencePage_Normal=Normal
-BuildPreferencePage_Verbose=Verbose
-BuildPreferencePage_Default_KeyStore=Default debug keystore:
-BuildPreferencePage_Default_Certificate_Fingerprint_MD5=MD5 fingerprint:
-BuildPreferencePage_Default_Certificate_Fingerprint_SHA1=SHA1 fingerprint:
-BuildPreferencePage_Custom_Keystore=Custom debug keystore:
-BuildPreferencePage_Custom_Certificate_Fingerprint_MD5=MD5 fingerprint:
-BuildPreferencePage_Custom_Certificate_Fingerprint_SHA1=SHA1 fingerprint:
-LaunchPreferencePage_Title=Launch Settings:
-LaunchPreferencePage_Default_Emu_Options=Default emulator options:
-LaunchPreferencePage_Default_HOME_Package=Default HOME package:
-AndroidPreferencePage_Title=Android Preferences
-AndroidPreferencePage_SDK_Location_=SDK Location:
-AndroidPreferencePage_ERROR_Reserved_Char=Reserved characters ',' and ';' cannot be used in the SDK Location.
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/AndroidClasspathContainer.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/AndroidClasspathContainer.java
deleted file mode 100644
index 475dd5a44..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/AndroidClasspathContainer.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.project;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jdt.core.IClasspathContainer;
-import org.eclipse.jdt.core.IClasspathEntry;
-
-/**
- * Classpath container for the Android projects.
- * This supports both the System classpath and the library dependencies.
- */
-class AndroidClasspathContainer implements IClasspathContainer {
-
- private final IClasspathEntry[] mClasspathEntry;
- private final IPath mContainerPath;
- private final String mName;
- private final int mKind;
-
- /**
- * Constructs the container with the {@link IClasspathEntry} representing the android
- * framework jar file and the container id
- * @param entries the entries representing the android framework and optional libraries.
- * @param path the path containing the classpath container id.
- * @param name the name of the container to display.
- * @param the container kind. Can be {@link IClasspathContainer#K_DEFAULT_SYSTEM} or
- * {@link IClasspathContainer#K_APPLICATION}
- */
- AndroidClasspathContainer(IClasspathEntry[] entries, IPath path, String name, int kind) {
- mClasspathEntry = entries;
- mContainerPath = path;
- mName = name;
- mKind = kind;
- }
-
- @Override
- public IClasspathEntry[] getClasspathEntries() {
- return mClasspathEntry;
- }
-
- @Override
- public String getDescription() {
- return mName;
- }
-
- @Override
- public int getKind() {
- return mKind;
- }
-
- @Override
- public IPath getPath() {
- return mContainerPath;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/AndroidClasspathContainerInitializer.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/AndroidClasspathContainerInitializer.java
deleted file mode 100644
index f9382c5ae..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/AndroidClasspathContainerInitializer.java
+++ /dev/null
@@ -1,823 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.project;
-
-import com.android.SdkConstants;
-import com.android.ide.common.sdk.LoadStatus;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.sdklib.AndroidVersion;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.IAndroidTarget.IOptionalLibrary;
-import com.google.common.collect.Maps;
-import com.google.common.io.Closeables;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.FileLocator;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.jdt.core.IAccessRule;
-import org.eclipse.jdt.core.IClasspathAttribute;
-import org.eclipse.jdt.core.IClasspathContainer;
-import org.eclipse.jdt.core.IClasspathEntry;
-import org.eclipse.jdt.core.IJavaModel;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.JavaModelException;
-import org.osgi.framework.Bundle;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.net.URLConnection;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.regex.Pattern;
-
-/**
- * Classpath container initializer responsible for binding {@link AndroidClasspathContainer} to
- * {@link IProject}s. This removes the hard-coded path to the android.jar.
- */
-public class AndroidClasspathContainerInitializer extends BaseClasspathContainerInitializer {
-
- public static final String NULL_API_URL = "<null>"; //$NON-NLS-1$
-
- public static final String SOURCES_ZIP = "/sources.zip"; //$NON-NLS-1$
-
- public static final String COM_ANDROID_IDE_ECLIPSE_ADT_SOURCE =
- "com.android.ide.eclipse.source"; //$NON-NLS-1$
-
- private static final String ANDROID_API_REFERENCE =
- "http://developer.android.com/reference/"; //$NON-NLS-1$
-
- private final static String PROPERTY_ANDROID_API = "androidApi"; //$NON-NLS-1$
-
- private final static String PROPERTY_ANDROID_SOURCE = "androidSource"; //$NON-NLS-1$
-
- /** path separator to store multiple paths in a single property. This is guaranteed to not
- * be in a path.
- */
- private final static String PATH_SEPARATOR = "\u001C"; //$NON-NLS-1$
-
- private final static String PROPERTY_CONTAINER_CACHE = "androidContainerCache"; //$NON-NLS-1$
- private final static String PROPERTY_TARGET_NAME = "androidTargetCache"; //$NON-NLS-1$
- private final static String CACHE_VERSION = "01"; //$NON-NLS-1$
- private final static String CACHE_VERSION_SEP = CACHE_VERSION + PATH_SEPARATOR;
-
- private final static int CACHE_INDEX_JAR = 0;
- private final static int CACHE_INDEX_SRC = 1;
- private final static int CACHE_INDEX_DOCS_URI = 2;
- private final static int CACHE_INDEX_OPT_DOCS_URI = 3;
- private final static int CACHE_INDEX_ADD_ON_START = CACHE_INDEX_OPT_DOCS_URI;
-
- public AndroidClasspathContainerInitializer() {
- // pass
- }
-
- /**
- * Binds a classpath container to a {@link IClasspathContainer} for a given project,
- * or silently fails if unable to do so.
- * @param containerPath the container path that is the container id.
- * @param project the project to bind
- */
- @Override
- public void initialize(IPath containerPath, IJavaProject project) throws CoreException {
- if (AdtConstants.CONTAINER_FRAMEWORK.equals(containerPath.toString())) {
- IClasspathContainer container = allocateAndroidContainer(project);
- if (container != null) {
- JavaCore.setClasspathContainer(new Path(AdtConstants.CONTAINER_FRAMEWORK),
- new IJavaProject[] { project },
- new IClasspathContainer[] { container },
- new NullProgressMonitor());
- }
- }
- }
-
- /**
- * Updates the {@link IJavaProject} objects with new android framework container. This forces
- * JDT to recompile them.
- * @param androidProjects the projects to update.
- * @return <code>true</code> if success, <code>false</code> otherwise.
- */
- static boolean updateProjects(IJavaProject[] androidProjects) {
- try {
- // Allocate a new AndroidClasspathContainer, and associate it to the android framework
- // container id for each projects.
- // By providing a new association between a container id and a IClasspathContainer,
- // this forces the JDT to query the IClasspathContainer for new IClasspathEntry (with
- // IClasspathContainer#getClasspathEntries()), and therefore force recompilation of
- // the projects.
- int projectCount = androidProjects.length;
-
- IClasspathContainer[] containers = new IClasspathContainer[projectCount];
- for (int i = 0 ; i < projectCount; i++) {
- containers[i] = allocateAndroidContainer(androidProjects[i]);
- }
-
- // give each project their new container in one call.
- JavaCore.setClasspathContainer(
- new Path(AdtConstants.CONTAINER_FRAMEWORK),
- androidProjects, containers, new NullProgressMonitor());
-
- return true;
- } catch (JavaModelException e) {
- return false;
- }
- }
-
- /**
- * Allocates and returns an {@link AndroidClasspathContainer} object with the proper
- * path to the framework jar file.
- * @param javaProject The java project that will receive the container.
- */
- private static IClasspathContainer allocateAndroidContainer(IJavaProject javaProject) {
- final IProject iProject = javaProject.getProject();
-
- String markerMessage = null;
- boolean outputToConsole = true;
- IAndroidTarget target = null;
-
- try {
- AdtPlugin plugin = AdtPlugin.getDefault();
- if (plugin == null) { // This is totally weird, but I've seen it happen!
- return null;
- }
-
- synchronized (Sdk.getLock()) {
- boolean sdkIsLoaded = plugin.getSdkLoadStatus() == LoadStatus.LOADED;
-
- // check if the project has a valid target.
- ProjectState state = Sdk.getProjectState(iProject);
- if (state == null) {
- // looks like the project state (project.properties) couldn't be read!
- markerMessage = String.format(
- "Project has no %1$s file! Edit the project properties to set one.",
- SdkConstants.FN_PROJECT_PROPERTIES);
- } else {
- // this might be null if the sdk is not yet loaded.
- target = state.getTarget();
-
- // if we are loaded and the target is non null, we create a valid
- // ClassPathContainer
- if (sdkIsLoaded && target != null) {
- // check the renderscript support mode. If support mode is enabled,
- // target API must be 18+
- if (!state.getRenderScriptSupportMode() ||
- target.getVersion().getApiLevel() >= 18) {
- // first make sure the target has loaded its data
- Sdk.getCurrent().checkAndLoadTargetData(target, null /*project*/);
-
- String targetName = target.getClasspathName();
-
- return new AndroidClasspathContainer(
- createClasspathEntries(iProject, target, targetName),
- new Path(AdtConstants.CONTAINER_FRAMEWORK),
- targetName,
- IClasspathContainer.K_DEFAULT_SYSTEM);
- } else {
- markerMessage = "Renderscript support mode requires compilation target API to be 18+.";
- }
- } else {
- // In case of error, we'll try different thing to provide the best error message
- // possible.
- // Get the project's target's hash string (if it exists)
- String hashString = state.getTargetHashString();
-
- if (hashString == null || hashString.length() == 0) {
- // if there is no hash string we only show this if the SDK is loaded.
- // For a project opened at start-up with no target, this would be displayed
- // twice, once when the project is opened, and once after the SDK has
- // finished loading.
- // By testing the sdk is loaded, we only show this once in the console.
- if (sdkIsLoaded) {
- markerMessage = String.format(
- "Project has no target set. Edit the project properties to set one.");
- }
- } else if (sdkIsLoaded) {
- markerMessage = String.format(
- "Unable to resolve target '%s'", hashString);
- } else {
- // this is the case where there is a hashString but the SDK is not yet
- // loaded and therefore we can't get the target yet.
- // We check if there is a cache of the needed information.
- AndroidClasspathContainer container = getContainerFromCache(iProject,
- target);
-
- if (container == null) {
- // either the cache was wrong (ie folder does not exists anymore), or
- // there was no cache. In this case we need to make sure the project
- // is resolved again after the SDK is loaded.
- plugin.setProjectToResolve(javaProject);
-
- markerMessage = String.format(
- "Unable to resolve target '%s' until the SDK is loaded.",
- hashString);
-
- // let's not log this one to the console as it will happen at
- // every boot, and it's expected. (we do keep the error marker though).
- outputToConsole = false;
-
- } else {
- // we created a container from the cache, so we register the project
- // to be checked for cache validity once the SDK is loaded
- plugin.setProjectToCheck(javaProject);
-
- // and return the container
- return container;
- }
- }
- }
- }
-
- // return a dummy container to replace the one we may have had before.
- // It'll be replaced by the real when if/when the target is resolved if/when the
- // SDK finishes loading.
- return new IClasspathContainer() {
- @Override
- public IClasspathEntry[] getClasspathEntries() {
- return new IClasspathEntry[0];
- }
-
- @Override
- public String getDescription() {
- return "Unable to get system library for the project";
- }
-
- @Override
- public int getKind() {
- return IClasspathContainer.K_DEFAULT_SYSTEM;
- }
-
- @Override
- public IPath getPath() {
- return null;
- }
- };
- }
- } finally {
- processError(iProject, markerMessage, AdtConstants.MARKER_TARGET, outputToConsole);
- }
- }
-
- /**
- * Creates and returns an array of {@link IClasspathEntry} objects for the android
- * framework and optional libraries.
- * <p/>This references the OS path to the android.jar and the
- * java doc directory. This is dynamically created when a project is opened,
- * and never saved in the project itself, so there's no risk of storing an
- * obsolete path.
- * The method also stores the paths used to create the entries in the project persistent
- * properties. A new {@link AndroidClasspathContainer} can be created from the stored path
- * using the {@link #getContainerFromCache(IProject)} method.
- * @param project
- * @param target The target that contains the libraries.
- * @param targetName
- */
- private static IClasspathEntry[] createClasspathEntries(IProject project,
- IAndroidTarget target, String targetName) {
-
- // get the path from the target
- String[] paths = getTargetPaths(target);
-
- // create the classpath entry from the paths
- IClasspathEntry[] entries = createClasspathEntriesFromPaths(paths, target);
-
- // paths now contains all the path required to recreate the IClasspathEntry with no
- // target info. We encode them in a single string, with each path separated by
- // OS path separator.
- StringBuilder sb = new StringBuilder(CACHE_VERSION);
- for (String p : paths) {
- sb.append(PATH_SEPARATOR);
- sb.append(p);
- }
-
- // store this in a project persistent property
- ProjectHelper.saveStringProperty(project, PROPERTY_CONTAINER_CACHE, sb.toString());
- ProjectHelper.saveStringProperty(project, PROPERTY_TARGET_NAME, targetName);
-
- return entries;
- }
-
- /**
- * Generates an {@link AndroidClasspathContainer} from the project cache, if possible.
- */
- private static AndroidClasspathContainer getContainerFromCache(IProject project,
- IAndroidTarget target) {
- // get the cached info from the project persistent properties.
- String cache = ProjectHelper.loadStringProperty(project, PROPERTY_CONTAINER_CACHE);
- String targetNameCache = ProjectHelper.loadStringProperty(project, PROPERTY_TARGET_NAME);
- if (cache == null || targetNameCache == null) {
- return null;
- }
-
- // the first 2 chars must match CACHE_VERSION. The 3rd char is the normal separator.
- if (cache.startsWith(CACHE_VERSION_SEP) == false) {
- return null;
- }
-
- cache = cache.substring(CACHE_VERSION_SEP.length());
-
- // the cache contains multiple paths, separated by a character guaranteed to not be in
- // the path (\u001C).
- // The first 3 are for android.jar (jar, source, doc), the rest are for the optional
- // libraries and should contain at least one doc and a jar (if there are any libraries).
- // Therefore, the path count should be 3 or 5+
- String[] paths = cache.split(Pattern.quote(PATH_SEPARATOR));
- if (paths.length < 3 || paths.length == 4) {
- return null;
- }
-
- // now we check the paths actually exist.
- // There's an exception: If the source folder for android.jar does not exist, this is
- // not a problem, so we skip it.
- // Also paths[CACHE_INDEX_DOCS_URI] is a URI to the javadoc, so we test it a
- // bit differently.
- try {
- if (new File(paths[CACHE_INDEX_JAR]).exists() == false ||
- new File(new URI(paths[CACHE_INDEX_DOCS_URI])).exists() == false) {
- return null;
- }
-
- // check the path for the add-ons, if they exist.
- if (paths.length > CACHE_INDEX_ADD_ON_START) {
-
- // check the docs path separately from the rest of the paths as it's a URI.
- if (new File(new URI(paths[CACHE_INDEX_OPT_DOCS_URI])).exists() == false) {
- return null;
- }
-
- // now just check the remaining paths.
- for (int i = CACHE_INDEX_ADD_ON_START + 1; i < paths.length; i++) {
- String path = paths[i];
- if (path.length() > 0) {
- File f = new File(path);
- if (f.exists() == false) {
- return null;
- }
- }
- }
- }
- } catch (URISyntaxException e) {
- return null;
- }
-
- IClasspathEntry[] entries = createClasspathEntriesFromPaths(paths, target);
-
- return new AndroidClasspathContainer(entries,
- new Path(AdtConstants.CONTAINER_FRAMEWORK),
- targetNameCache, IClasspathContainer.K_DEFAULT_SYSTEM);
- }
-
- /**
- * Generates an array of {@link IClasspathEntry} from a set of paths.
- * @see #getTargetPaths(IAndroidTarget)
- */
- private static IClasspathEntry[] createClasspathEntriesFromPaths(String[] paths,
- IAndroidTarget target) {
- ArrayList<IClasspathEntry> list = new ArrayList<IClasspathEntry>();
-
- // First, we create the IClasspathEntry for the framework.
- // now add the android framework to the class path.
- // create the path object.
- IPath androidLib = new Path(paths[CACHE_INDEX_JAR]);
-
- IPath androidSrc = null;
- String androidSrcOsPath = null;
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- if (target != null) {
- androidSrcOsPath =
- ProjectHelper.loadStringProperty(root, getAndroidSourceProperty(target));
- }
- if (androidSrcOsPath != null && androidSrcOsPath.trim().length() > 0) {
- androidSrc = new Path(androidSrcOsPath);
- }
- if (androidSrc == null) {
- androidSrc = new Path(paths[CACHE_INDEX_SRC]);
- File androidSrcFile = new File(paths[CACHE_INDEX_SRC]);
- if (!androidSrcFile.isDirectory()) {
- androidSrc = null;
- }
- }
-
- if (androidSrc == null && target != null) {
- Bundle bundle = getSourceBundle();
-
- if (bundle != null) {
- AndroidVersion version = target.getVersion();
- String apiString = version.getApiString();
- String sourcePath = apiString + SOURCES_ZIP;
- URL sourceURL = bundle.getEntry(sourcePath);
- if (sourceURL != null) {
- URL url = null;
- try {
- url = FileLocator.resolve(sourceURL);
- } catch (IOException ignore) {
- }
- if (url != null) {
- androidSrcOsPath = url.getFile();
- if (new File(androidSrcOsPath).isFile()) {
- androidSrc = new Path(androidSrcOsPath);
- }
- }
- }
- }
- }
-
- // create the java doc link.
- String androidApiURL = ProjectHelper.loadStringProperty(root, PROPERTY_ANDROID_API);
- String apiURL = null;
- if (androidApiURL != null && testURL(androidApiURL)) {
- apiURL = androidApiURL;
- } else {
- if (testURL(paths[CACHE_INDEX_DOCS_URI])) {
- apiURL = paths[CACHE_INDEX_DOCS_URI];
- } else if (testURL(ANDROID_API_REFERENCE)) {
- apiURL = ANDROID_API_REFERENCE;
- }
- }
-
- IClasspathAttribute[] attributes = null;
- if (apiURL != null && !NULL_API_URL.equals(apiURL)) {
- IClasspathAttribute cpAttribute = JavaCore.newClasspathAttribute(
- IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME, apiURL);
- attributes = new IClasspathAttribute[] {
- cpAttribute
- };
- }
- // create the access rule to restrict access to classes in
- // com.android.internal
- IAccessRule accessRule = JavaCore.newAccessRule(new Path("com/android/internal/**"), //$NON-NLS-1$
- IAccessRule.K_NON_ACCESSIBLE);
-
- IClasspathEntry frameworkClasspathEntry = JavaCore.newLibraryEntry(androidLib,
- androidSrc, // source attachment path
- null, // default source attachment root path.
- new IAccessRule[] { accessRule },
- attributes,
- false // not exported.
- );
-
- list.add(frameworkClasspathEntry);
-
- // now deal with optional libraries
- if (paths.length >= 5) {
- String docPath = paths[CACHE_INDEX_OPT_DOCS_URI];
- int i = 4;
- while (i < paths.length) {
- Path jarPath = new Path(paths[i++]);
-
- attributes = null;
- if (docPath.length() > 0) {
- attributes = new IClasspathAttribute[] {
- JavaCore.newClasspathAttribute(
- IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME, docPath)
- };
- }
-
- IClasspathEntry entry = JavaCore.newLibraryEntry(
- jarPath,
- null, // source attachment path
- null, // default source attachment root path.
- null,
- attributes,
- false // not exported.
- );
- list.add(entry);
- }
- }
-
- if (apiURL != null) {
- ProjectHelper.saveStringProperty(root, PROPERTY_ANDROID_API, apiURL);
- }
- if (androidSrc != null && target != null) {
- ProjectHelper.saveStringProperty(root, getAndroidSourceProperty(target),
- androidSrc.toOSString());
- }
- return list.toArray(new IClasspathEntry[list.size()]);
- }
-
- private static Bundle getSourceBundle() {
- String bundleId = System.getProperty(COM_ANDROID_IDE_ECLIPSE_ADT_SOURCE,
- COM_ANDROID_IDE_ECLIPSE_ADT_SOURCE);
- Bundle bundle = Platform.getBundle(bundleId);
- return bundle;
- }
-
- private static String getAndroidSourceProperty(IAndroidTarget target) {
- if (target == null) {
- return null;
- }
- String androidSourceProperty = PROPERTY_ANDROID_SOURCE + "_"
- + target.getVersion().getApiString();
- return androidSourceProperty;
- }
-
- /**
- * Cache results for testURL: Some are expensive to compute, and this is
- * called repeatedly (perhaps for each open project)
- */
- private static final Map<String, Boolean> sRecentUrlValidCache =
- Maps.newHashMapWithExpectedSize(4);
-
- @SuppressWarnings("resource") // Eclipse does not handle Closeables#closeQuietly
- private static boolean testURL(String androidApiURL) {
- Boolean cached = sRecentUrlValidCache.get(androidApiURL);
- if (cached != null) {
- return cached.booleanValue();
- }
- boolean valid = false;
- InputStream is = null;
- try {
- URL testURL = new URL(androidApiURL);
- URLConnection connection = testURL.openConnection();
- // Only try for 5 seconds (though some implementations ignore this flag)
- connection.setConnectTimeout(5000);
- connection.setReadTimeout(5000);
- is = connection.getInputStream();
- valid = true;
- } catch (Exception ignore) {
- } finally {
- Closeables.closeQuietly(is);
- }
-
- sRecentUrlValidCache.put(androidApiURL, valid);
-
- return valid;
- }
-
- /**
- * Checks the projects' caches. If the cache was valid, the project is removed from the list.
- * @param projects the list of projects to check.
- */
- public static void checkProjectsCache(ArrayList<IJavaProject> projects) {
- Sdk currentSdk = Sdk.getCurrent();
- int i = 0;
- projectLoop: while (i < projects.size()) {
- IJavaProject javaProject = projects.get(i);
- IProject iProject = javaProject.getProject();
-
- // check if the project is opened
- if (iProject.isOpen() == false) {
- // remove from the list
- // we do not increment i in this case.
- projects.remove(i);
-
- continue;
- }
-
- // project that have been resolved before the sdk was loaded
- // will have a ProjectState where the IAndroidTarget is null
- // so we load the target now that the SDK is loaded.
- IAndroidTarget target = currentSdk.loadTargetAndBuildTools(
- Sdk.getProjectState(iProject));
- if (target == null) {
- // this is really not supposed to happen. This would mean there are cached paths,
- // but project.properties was deleted. Keep the project in the list to force
- // a resolve which will display the error.
- i++;
- continue;
- }
-
- String[] targetPaths = getTargetPaths(target);
-
- // now get the cached paths
- String cache = ProjectHelper.loadStringProperty(iProject, PROPERTY_CONTAINER_CACHE);
- if (cache == null) {
- // this should not happen. We'll force resolve again anyway.
- i++;
- continue;
- }
-
- String[] cachedPaths = cache.split(Pattern.quote(PATH_SEPARATOR));
- if (cachedPaths.length < 3 || cachedPaths.length == 4) {
- // paths length is wrong. simply resolve the project again
- i++;
- continue;
- }
-
- // Now we compare the paths. The first 4 can be compared directly.
- // because of case sensitiveness we need to use File objects
-
- if (targetPaths.length != cachedPaths.length) {
- // different paths, force resolve again.
- i++;
- continue;
- }
-
- // compare the main paths (android.jar, main sources, main javadoc)
- if (new File(targetPaths[CACHE_INDEX_JAR]).equals(
- new File(cachedPaths[CACHE_INDEX_JAR])) == false ||
- new File(targetPaths[CACHE_INDEX_SRC]).equals(
- new File(cachedPaths[CACHE_INDEX_SRC])) == false ||
- new File(targetPaths[CACHE_INDEX_DOCS_URI]).equals(
- new File(cachedPaths[CACHE_INDEX_DOCS_URI])) == false) {
- // different paths, force resolve again.
- i++;
- continue;
- }
-
- if (cachedPaths.length > CACHE_INDEX_OPT_DOCS_URI) {
- // compare optional libraries javadoc
- if (new File(targetPaths[CACHE_INDEX_OPT_DOCS_URI]).equals(
- new File(cachedPaths[CACHE_INDEX_OPT_DOCS_URI])) == false) {
- // different paths, force resolve again.
- i++;
- continue;
- }
-
- // testing the optional jar files is a little bit trickier.
- // The order is not guaranteed to be identical.
- // From a previous test, we do know however that there is the same number.
- // The number of libraries should be low enough that we can simply go through the
- // lists manually.
- targetLoop: for (int tpi = 4 ; tpi < targetPaths.length; tpi++) {
- String targetPath = targetPaths[tpi];
-
- // look for a match in the other array
- for (int cpi = 4 ; cpi < cachedPaths.length; cpi++) {
- if (new File(targetPath).equals(new File(cachedPaths[cpi]))) {
- // found a match. Try the next targetPath
- continue targetLoop;
- }
- }
-
- // if we stop here, we haven't found a match, which means there's a
- // discrepancy in the libraries. We force a resolve.
- i++;
- continue projectLoop;
- }
- }
-
- // at the point the check passes, and we can remove the project from the list.
- // we do not increment i in this case.
- projects.remove(i);
- }
- }
-
- /**
- * Returns the paths necessary to create the {@link IClasspathEntry} for this targets.
- * <p/>The paths are always in the same order.
- * <ul>
- * <li>Path to android.jar</li>
- * <li>Path to the source code for android.jar</li>
- * <li>Path to the javadoc for the android platform</li>
- * </ul>
- * Additionally, if there are optional libraries, the array will contain:
- * <ul>
- * <li>Path to the libraries javadoc</li>
- * <li>Path to the first .jar file</li>
- * <li>(more .jar as needed)</li>
- * </ul>
- */
- private static String[] getTargetPaths(IAndroidTarget target) {
- ArrayList<String> paths = new ArrayList<String>();
-
- // first, we get the path for android.jar
- // The order is: android.jar, source folder, docs folder
- paths.add(target.getPath(IAndroidTarget.ANDROID_JAR));
- paths.add(target.getPath(IAndroidTarget.SOURCES));
- paths.add(AdtPlugin.getUrlDoc());
-
- // now deal with optional libraries.
- IOptionalLibrary[] libraries = target.getOptionalLibraries();
- if (libraries != null) {
- // all the optional libraries use the same javadoc, so we start with this
- String targetDocPath = target.getPath(IAndroidTarget.DOCS);
- if (targetDocPath != null) {
- paths.add(ProjectHelper.getJavaDocPath(targetDocPath));
- } else {
- // we add an empty string, to always have the same count.
- paths.add("");
- }
-
- // because different libraries could use the same jar file, we make sure we add
- // each jar file only once.
- HashSet<String> visitedJars = new HashSet<String>();
- for (IOptionalLibrary library : libraries) {
- String jarPath = library.getJarPath();
- if (visitedJars.contains(jarPath) == false) {
- visitedJars.add(jarPath);
- paths.add(jarPath);
- }
- }
- }
-
- return paths.toArray(new String[paths.size()]);
- }
-
- @Override
- public boolean canUpdateClasspathContainer(IPath containerPath, IJavaProject project) {
- return true;
- }
-
- @Override
- public void requestClasspathContainerUpdate(IPath containerPath, IJavaProject project,
- IClasspathContainer containerSuggestion) throws CoreException {
- AdtPlugin plugin = AdtPlugin.getDefault();
-
- synchronized (Sdk.getLock()) {
- boolean sdkIsLoaded = plugin.getSdkLoadStatus() == LoadStatus.LOADED;
-
- // check if the project has a valid target.
- IAndroidTarget target = null;
- if (sdkIsLoaded) {
- target = Sdk.getCurrent().getTarget(project.getProject());
- }
- if (sdkIsLoaded && target != null) {
- String[] paths = getTargetPaths(target);
- IPath android_lib = new Path(paths[CACHE_INDEX_JAR]);
- IClasspathEntry[] entries = containerSuggestion.getClasspathEntries();
- for (int i = 0; i < entries.length; i++) {
- IClasspathEntry entry = entries[i];
- if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
- IPath entryPath = entry.getPath();
-
- if (entryPath != null) {
- if (entryPath.equals(android_lib)) {
- IPath entrySrcPath = entry.getSourceAttachmentPath();
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- if (entrySrcPath != null) {
- ProjectHelper.saveStringProperty(root,
- getAndroidSourceProperty(target),
- entrySrcPath.toString());
- } else {
- ProjectHelper.saveStringProperty(root,
- getAndroidSourceProperty(target), null);
- }
- IClasspathAttribute[] extraAttributtes = entry.getExtraAttributes();
- if (extraAttributtes.length == 0) {
- ProjectHelper.saveStringProperty(root, PROPERTY_ANDROID_API,
- NULL_API_URL);
- }
- for (int j = 0; j < extraAttributtes.length; j++) {
- IClasspathAttribute extraAttribute = extraAttributtes[j];
- String value = extraAttribute.getValue();
- if ((value == null || value.trim().length() == 0)
- && IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME
- .equals(extraAttribute.getName())) {
- value = NULL_API_URL;
- }
- if (IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME
- .equals(extraAttribute.getName())) {
- ProjectHelper.saveStringProperty(root,
- PROPERTY_ANDROID_API, value);
-
- }
- }
- }
- }
- }
- }
- rebindClasspathEntries(project.getJavaModel(), containerPath);
- }
- }
- }
-
- private static void rebindClasspathEntries(IJavaModel model, IPath containerPath)
- throws JavaModelException {
- ArrayList<IJavaProject> affectedProjects = new ArrayList<IJavaProject>();
-
- IJavaProject[] projects = model.getJavaProjects();
- for (int i = 0; i < projects.length; i++) {
- IJavaProject project = projects[i];
- IClasspathEntry[] entries = project.getRawClasspath();
- for (int k = 0; k < entries.length; k++) {
- IClasspathEntry curr = entries[k];
- if (curr.getEntryKind() == IClasspathEntry.CPE_CONTAINER
- && containerPath.equals(curr.getPath())) {
- affectedProjects.add(project);
- }
- }
- }
- if (!affectedProjects.isEmpty()) {
- IJavaProject[] affected = affectedProjects
- .toArray(new IJavaProject[affectedProjects.size()]);
- updateProjects(affected);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/AndroidClasspathContainerPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/AndroidClasspathContainerPage.java
deleted file mode 100644
index b02765012..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/AndroidClasspathContainerPage.java
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *******************************************************************************/
-
-package com.android.ide.eclipse.adt.internal.project;
-
-import com.android.ide.eclipse.adt.AdtConstants;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jdt.core.IClasspathEntry;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
-import org.eclipse.jdt.internal.ui.dialogs.StatusUtil;
-import org.eclipse.jdt.ui.wizards.IClasspathContainerPage;
-import org.eclipse.jdt.ui.wizards.IClasspathContainerPageExtension;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-
-import java.util.Arrays;
-
-public class AndroidClasspathContainerPage extends WizardPage implements IClasspathContainerPage,
- IClasspathContainerPageExtension {
-
- private IProject mOwnerProject;
-
- private String mLibsProjectName;
-
- private Combo mProjectsCombo;
-
- private IStatus mCurrStatus;
-
- private boolean mPageVisible;
-
- public AndroidClasspathContainerPage() {
- super("AndroidClasspathContainerPage"); //$NON-NLS-1$
- mPageVisible = false;
- mCurrStatus = new StatusInfo();
- setTitle("Android Libraries");
- setDescription("This container manages classpath entries for Android container");
- }
-
- @Override
- public IClasspathEntry getSelection() {
- IPath path = new Path(AdtConstants.CONTAINER_FRAMEWORK);
-
- final int index = this.mProjectsCombo.getSelectionIndex();
- if (index != -1) {
- final String selectedProjectName = this.mProjectsCombo.getItem(index);
-
- if (this.mOwnerProject == null
- || !selectedProjectName.equals(this.mOwnerProject.getName())) {
- path = path.append(selectedProjectName);
- }
- }
-
- return JavaCore.newContainerEntry(path);
- }
-
- @Override
- public void setSelection(final IClasspathEntry cpentry) {
- final IPath path = cpentry == null ? null : cpentry.getPath();
-
- if (path == null || path.segmentCount() == 1) {
- if (this.mOwnerProject != null) {
- this.mLibsProjectName = this.mOwnerProject.getName();
- }
- } else {
- this.mLibsProjectName = path.segment(1);
- }
- }
-
- @Override
- public void createControl(final Composite parent) {
- final Composite composite = new Composite(parent, SWT.NONE);
- composite.setLayout(new GridLayout(2, false));
-
- final Label label = new Label(composite, SWT.NONE);
- label.setText("Project:");
-
- final String[] androidProjects = getAndroidProjects();
-
- this.mProjectsCombo = new Combo(composite, SWT.READ_ONLY);
- this.mProjectsCombo.setItems(androidProjects);
-
- final int index;
-
- if (this.mOwnerProject != null) {
- index = indexOf(androidProjects, this.mLibsProjectName);
- } else {
- if (this.mProjectsCombo.getItemCount() > 0) {
- index = 0;
- } else {
- index = -1;
- }
- }
-
- if (index != -1) {
- this.mProjectsCombo.select(index);
- }
-
- final GridData gd = new GridData();
- gd.grabExcessHorizontalSpace = true;
- gd.minimumWidth = 100;
-
- this.mProjectsCombo.setLayoutData(gd);
-
- setControl(composite);
- }
-
- @Override
- public boolean finish() {
- return true;
- }
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- mPageVisible = visible;
- // policy: wizards are not allowed to come up with an error message
- if (visible && mCurrStatus.matches(IStatus.ERROR)) {
- StatusInfo status = new StatusInfo();
- status.setError(""); //$NON-NLS-1$
- mCurrStatus = status;
- }
- updateStatus(mCurrStatus);
- }
-
- /**
- * Updates the status line and the OK button according to the given status
- *
- * @param status status to apply
- */
- protected void updateStatus(IStatus status) {
- mCurrStatus = status;
- setPageComplete(!status.matches(IStatus.ERROR));
- if (mPageVisible) {
- StatusUtil.applyToStatusLine(this, status);
- }
- }
-
- /**
- * Updates the status line and the OK button according to the status
- * evaluate from an array of status. The most severe error is taken. In case
- * that two status with the same severity exists, the status with lower
- * index is taken.
- *
- * @param status the array of status
- */
- protected void updateStatus(IStatus[] status) {
- updateStatus(StatusUtil.getMostSevere(status));
- }
-
- @Override
- public void initialize(final IJavaProject project, final IClasspathEntry[] currentEntries) {
- this.mOwnerProject = (project == null ? null : project.getProject());
- }
-
- private static String[] getAndroidProjects() {
- IProject[] projects = ResourcesPlugin.getWorkspace().getRoot().getProjects();
- final String[] names = new String[projects.length];
- for (int i = 0; i < projects.length; i++) {
- names[i] = projects[i].getName();
- }
- Arrays.sort(names);
- return names;
- }
-
- private static int indexOf(final String[] array, final String str) {
- for (int i = 0; i < array.length; i++) {
- if (array[i].equals(str)) {
- return i;
- }
- }
- return -1;
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/AndroidExportNature.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/AndroidExportNature.java
deleted file mode 100644
index 218cffe5e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/AndroidExportNature.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.project;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IProjectNature;
-import org.eclipse.core.runtime.CoreException;
-
-/**
- * Project nature for the Android Export Projects.
- */
-public class AndroidExportNature implements IProjectNature {
-
- /** the project this nature object is associated with */
- private IProject mProject;
-
- /**
- * Configures this nature for its project. This is called by the workspace
- * when natures are added to the project using
- * <code>IProject.setDescription</code> and should not be called directly
- * by clients. The nature extension id is added to the list of natures
- * before this method is called, and need not be added here.
- *
- * Exceptions thrown by this method will be propagated back to the caller of
- * <code>IProject.setDescription</code>, but the nature will remain in
- * the project description.
- *
- * @see org.eclipse.core.resources.IProjectNature#configure()
- * @throws CoreException if configuration fails.
- */
- @Override
- public void configure() throws CoreException {
- // nothing to do.
- }
-
- /**
- * De-configures this nature for its project. This is called by the
- * workspace when natures are removed from the project using
- * <code>IProject.setDescription</code> and should not be called directly
- * by clients. The nature extension id is removed from the list of natures
- * before this method is called, and need not be removed here.
- *
- * Exceptions thrown by this method will be propagated back to the caller of
- * <code>IProject.setDescription</code>, but the nature will still be
- * removed from the project description.
- *
- * The Android nature removes the custom pre builder and APK builder.
- *
- * @see org.eclipse.core.resources.IProjectNature#deconfigure()
- * @throws CoreException if configuration fails.
- */
- @Override
- public void deconfigure() throws CoreException {
- // nothing to do
- }
-
- /**
- * Returns the project to which this project nature applies.
- *
- * @return the project handle
- * @see org.eclipse.core.resources.IProjectNature#getProject()
- */
- @Override
- public IProject getProject() {
- return mProject;
- }
-
- /**
- * Sets the project to which this nature applies. Used when instantiating
- * this project nature runtime. This is called by
- * <code>IProject.create()</code> or
- * <code>IProject.setDescription()</code> and should not be called
- * directly by clients.
- *
- * @param project the project to which this nature applies
- * @see org.eclipse.core.resources.IProjectNature#setProject(org.eclipse.core.resources.IProject)
- */
- @Override
- public void setProject(IProject project) {
- mProject = project;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/AndroidManifestHelper.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/AndroidManifestHelper.java
deleted file mode 100644
index eaa309668..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/AndroidManifestHelper.java
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.project;
-
-import com.android.ide.common.xml.AndroidManifestParser;
-import com.android.ide.common.xml.ManifestData;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.project.XmlErrorHandler.XmlErrorListener;
-import com.android.ide.eclipse.adt.io.IFileWrapper;
-import com.android.io.FileWrapper;
-import com.android.io.IAbstractFile;
-import com.android.io.StreamException;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jdt.core.IJavaProject;
-import org.xml.sax.SAXException;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-
-import javax.xml.parsers.ParserConfigurationException;
-
-public class AndroidManifestHelper {
-
- /**
- * Parses the Android Manifest, and returns an object containing the result of the parsing.
- * <p/>
- * This method can also gather XML error during the parsing. This is done by using an
- * {@link XmlErrorHandler} to mark the files in case of error, as well as a given
- * {@link XmlErrorListener}. To use a different error handler, consider using
- * {@link AndroidManifestParser#parse(IAbstractFile, boolean, com.android.sdklib.xml.AndroidManifestParser.ManifestErrorHandler)}
- * directly.
- *
- * @param manifestFile the {@link IFile} representing the manifest file.
- * @param gatherData indicates whether the parsing will extract data from the manifest. If null,
- * the method will always return null.
- * @param errorListener an optional error listener. If non null, then the parser will also
- * look for XML errors.
- * @return an {@link ManifestData} or null if the parsing failed.
- * @throws ParserConfigurationException
- * @throws StreamException
- * @throws IOException
- * @throws SAXException
- */
- public static ManifestData parseUnchecked(
- IAbstractFile manifestFile,
- boolean gatherData,
- XmlErrorListener errorListener) throws SAXException, IOException,
- StreamException, ParserConfigurationException {
- if (manifestFile != null) {
- IFile eclipseFile = null;
- if (manifestFile instanceof IFileWrapper) {
- eclipseFile = ((IFileWrapper)manifestFile).getIFile();
- }
- XmlErrorHandler errorHandler = null;
- if (errorListener != null) {
- errorHandler = new XmlErrorHandler(eclipseFile, errorListener);
- }
-
- return AndroidManifestParser.parse(manifestFile, gatherData, errorHandler);
- }
-
- return null;
- }
-
- /**
- * Parses the Android Manifest, and returns an object containing the result of the parsing.
- * <p/>
- * This method can also gather XML error during the parsing. This is done by using an
- * {@link XmlErrorHandler} to mark the files in case of error, as well as a given
- * {@link XmlErrorListener}. To use a different error handler, consider using
- * {@link AndroidManifestParser#parse(IAbstractFile, boolean, com.android.sdklib.xml.AndroidManifestParser.ManifestErrorHandler)}
- * directly.
- *
- * @param manifestFile the {@link IFile} representing the manifest file.
- * @param gatherData indicates whether the parsing will extract data from the manifest. If null,
- * the method will always return null.
- * @param errorListener an optional error listener. If non null, then the parser will also
- * look for XML errors.
- * @return an {@link ManifestData} or null if the parsing failed.
- */
- public static ManifestData parse(
- IAbstractFile manifestFile,
- boolean gatherData,
- XmlErrorListener errorListener) {
- try {
- return parseUnchecked(manifestFile, gatherData, errorListener);
- } catch (ParserConfigurationException e) {
- AdtPlugin.logAndPrintError(e, AndroidManifestHelper.class.getCanonicalName(),
- "Bad parser configuration for %s: %s",
- manifestFile.getOsLocation(),
- e.getMessage());
- } catch (SAXException e) {
- AdtPlugin.logAndPrintError(e, AndroidManifestHelper.class.getCanonicalName(),
- "Parser exception for %s: %s",
- manifestFile.getOsLocation(),
- e.getMessage());
- } catch (IOException e) {
- // Don't log a console error when failing to read a non-existing file
- if (!(e instanceof FileNotFoundException)) {
- AdtPlugin.logAndPrintError(e, AndroidManifestHelper.class.getCanonicalName(),
- "I/O error for %s: %s",
- manifestFile.getOsLocation(),
- e.getMessage());
- }
- } catch (StreamException e) {
- AdtPlugin.logAndPrintError(e, AndroidManifestHelper.class.getCanonicalName(),
- "Unable to read %s: %s",
- manifestFile.getOsLocation(),
- e.getMessage());
- }
-
- return null;
- }
-
- /**
- * Parses the Android Manifest for a given project, and returns an object containing
- * the result of the parsing.
- * <p/>
- * This method can also gather XML error during the parsing. This is done by using an
- * {@link XmlErrorHandler} to mark the files in case of error, as well as a given
- * {@link XmlErrorListener}. To use a different error handler, consider using
- * {@link AndroidManifestParser#parse(IAbstractFile, boolean, com.android.sdklib.xml.AndroidManifestParser.ManifestErrorHandler)}
- * directly.
- *
- * @param javaProject the project containing the manifest to parse.
- * @param gatherData indicates whether the parsing will extract data from the manifest. If null,
- * the method will always return null.
- * @param errorListener an optional error listener. If non null, then the parser will also
- * look for XML errors.
- * @return an {@link ManifestData} or null if the parsing failed.
- */
- public static ManifestData parse(
- IJavaProject javaProject,
- boolean gatherData,
- XmlErrorListener errorListener) {
-
- IFile manifestFile = ProjectHelper.getManifest(javaProject.getProject());
- if (manifestFile != null) {
- return parse(new IFileWrapper(manifestFile), gatherData, errorListener);
- }
-
- return null;
- }
-
- /**
- * Parses the manifest file only for error check.
- * @param manifestFile The manifest file to parse.
- * @param errorListener the {@link XmlErrorListener} object being notified of the presence
- * of errors.
- */
- public static void parseForError(IFile manifestFile, XmlErrorListener errorListener) {
- parse(new IFileWrapper(manifestFile), false, errorListener);
- }
-
- /**
- * Parses the manifest file, and collects data.
- * @param manifestFile The manifest file to parse.
- * @return an {@link ManifestData} or null if the parsing failed.
- */
- public static ManifestData parseForData(IFile manifestFile) {
- return parse(new IFileWrapper(manifestFile), true, null);
- }
-
- /**
- * Parses the manifest file, and collects data.
- * @param project the project containing the manifest.
- * @return an {@link AndroidManifestHelper} or null if the parsing failed.
- */
- public static ManifestData parseForData(IProject project) {
- IFile manifestFile = ProjectHelper.getManifest(project);
- if (manifestFile != null) {
- return parse(new IFileWrapper(manifestFile), true, null);
- }
-
- return null;
- }
-
- /**
- * Parses the manifest file, and collects data.
- *
- * @param osManifestFilePath The OS path of the manifest file to parse.
- * @return an {@link AndroidManifestHelper} or null if the parsing failed.
- */
- public static ManifestData parseForData(String osManifestFilePath) {
- return parse(new FileWrapper(osManifestFilePath), true, null);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/AndroidNature.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/AndroidNature.java
deleted file mode 100644
index 3b1c29fe9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/AndroidNature.java
+++ /dev/null
@@ -1,299 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.project;
-
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.internal.build.builders.PostCompilerBuilder;
-import com.android.ide.eclipse.adt.internal.build.builders.PreCompilerBuilder;
-import com.android.ide.eclipse.adt.internal.build.builders.ResourceManagerBuilder;
-
-import org.eclipse.core.resources.ICommand;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IProjectDescription;
-import org.eclipse.core.resources.IProjectNature;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jdt.core.JavaCore;
-
-/**
- * Project nature for the Android Projects.
- */
-public class AndroidNature implements IProjectNature {
-
- /** the project this nature object is associated with */
- private IProject mProject;
-
- /**
- * Configures this nature for its project. This is called by the workspace
- * when natures are added to the project using
- * <code>IProject.setDescription</code> and should not be called directly
- * by clients. The nature extension id is added to the list of natures
- * before this method is called, and need not be added here.
- *
- * Exceptions thrown by this method will be propagated back to the caller of
- * <code>IProject.setDescription</code>, but the nature will remain in
- * the project description.
- *
- * The Android nature adds the pre-builder and the APK builder if necessary.
- *
- * @see org.eclipse.core.resources.IProjectNature#configure()
- * @throws CoreException if configuration fails.
- */
- @Override
- public void configure() throws CoreException {
- configureResourceManagerBuilder(mProject);
- configurePreBuilder(mProject);
- configureApkBuilder(mProject);
- }
-
- /**
- * De-configures this nature for its project. This is called by the
- * workspace when natures are removed from the project using
- * <code>IProject.setDescription</code> and should not be called directly
- * by clients. The nature extension id is removed from the list of natures
- * before this method is called, and need not be removed here.
- *
- * Exceptions thrown by this method will be propagated back to the caller of
- * <code>IProject.setDescription</code>, but the nature will still be
- * removed from the project description.
- *
- * The Android nature removes the custom pre builder and APK builder.
- *
- * @see org.eclipse.core.resources.IProjectNature#deconfigure()
- * @throws CoreException if configuration fails.
- */
- @Override
- public void deconfigure() throws CoreException {
- // remove the android builders
- removeBuilder(mProject, ResourceManagerBuilder.ID);
- removeBuilder(mProject, PreCompilerBuilder.ID);
- removeBuilder(mProject, PostCompilerBuilder.ID);
- }
-
- /**
- * Returns the project to which this project nature applies.
- *
- * @return the project handle
- * @see org.eclipse.core.resources.IProjectNature#getProject()
- */
- @Override
- public IProject getProject() {
- return mProject;
- }
-
- /**
- * Sets the project to which this nature applies. Used when instantiating
- * this project nature runtime. This is called by
- * <code>IProject.create()</code> or
- * <code>IProject.setDescription()</code> and should not be called
- * directly by clients.
- *
- * @param project the project to which this nature applies
- * @see org.eclipse.core.resources.IProjectNature#setProject(org.eclipse.core.resources.IProject)
- */
- @Override
- public void setProject(IProject project) {
- mProject = project;
- }
-
- /**
- * Adds the Android Nature and the Java Nature to the project if it doesn't
- * already have them.
- *
- * @param project An existing or new project to update
- * @param monitor An optional progress monitor. Can be null.
- * @param addAndroidNature true if the Android Nature should be added to the project; false to
- * add only the Java nature.
- * @throws CoreException if fails to change the nature.
- */
- public static synchronized void setupProjectNatures(IProject project,
- IProgressMonitor monitor, boolean addAndroidNature) throws CoreException {
- if (project == null || !project.isOpen()) return;
- if (monitor == null) monitor = new NullProgressMonitor();
-
- // Add the natures. We need to add the Java nature first, so it adds its builder to the
- // project first. This way, when the android nature is added, we can control where to put
- // the android builders in relation to the java builder.
- // Adding the java nature after the android one, would place the java builder before the
- // android builders.
- addNatureToProjectDescription(project, JavaCore.NATURE_ID, monitor);
- if (addAndroidNature) {
- addNatureToProjectDescription(project, AdtConstants.NATURE_DEFAULT, monitor);
- }
- }
-
- /**
- * Add the specified nature to the specified project. The nature is only
- * added if not already present.
- * <p/>
- * Android Natures are always inserted at the beginning of the list of natures in order to
- * have the jdt views/dialogs display the proper icon.
- *
- * @param project The project to modify.
- * @param natureId The Id of the nature to add.
- * @param monitor An existing progress monitor.
- * @throws CoreException if fails to change the nature.
- */
- private static void addNatureToProjectDescription(IProject project,
- String natureId, IProgressMonitor monitor) throws CoreException {
- if (!project.hasNature(natureId)) {
-
- IProjectDescription description = project.getDescription();
- String[] natures = description.getNatureIds();
- String[] newNatures = new String[natures.length + 1];
-
- // Android natures always come first.
- if (natureId.equals(AdtConstants.NATURE_DEFAULT)) {
- System.arraycopy(natures, 0, newNatures, 1, natures.length);
- newNatures[0] = natureId;
- } else {
- System.arraycopy(natures, 0, newNatures, 0, natures.length);
- newNatures[natures.length] = natureId;
- }
-
- description.setNatureIds(newNatures);
- project.setDescription(description, new SubProgressMonitor(monitor, 10));
- }
- }
-
- /**
- * Adds the ResourceManagerBuilder, if its not already there. It'll insert
- * itself as the first builder.
- * @throws CoreException
- *
- */
- public static void configureResourceManagerBuilder(IProject project)
- throws CoreException {
- // get the builder list
- IProjectDescription desc = project.getDescription();
- ICommand[] commands = desc.getBuildSpec();
-
- // look for the builder in case it's already there.
- for (int i = 0; i < commands.length; ++i) {
- if (ResourceManagerBuilder.ID.equals(commands[i].getBuilderName())) {
- return;
- }
- }
-
- // it's not there, lets add it at the beginning of the builders
- ICommand[] newCommands = new ICommand[commands.length + 1];
- System.arraycopy(commands, 0, newCommands, 1, commands.length);
- ICommand command = desc.newCommand();
- command.setBuilderName(ResourceManagerBuilder.ID);
- newCommands[0] = command;
- desc.setBuildSpec(newCommands);
- project.setDescription(desc, null);
- }
-
- /**
- * Adds the PreCompilerBuilder if its not already there. It'll check for
- * presence of the ResourceManager and insert itself right after.
- * @param project
- * @throws CoreException
- */
- public static void configurePreBuilder(IProject project)
- throws CoreException {
- // get the builder list
- IProjectDescription desc = project.getDescription();
- ICommand[] commands = desc.getBuildSpec();
-
- // look for the builder in case it's already there.
- for (int i = 0; i < commands.length; ++i) {
- if (PreCompilerBuilder.ID.equals(commands[i].getBuilderName())) {
- return;
- }
- }
-
- // we need to add it after the resource manager builder.
- // Let's look for it
- int index = -1;
- for (int i = 0; i < commands.length; ++i) {
- if (ResourceManagerBuilder.ID.equals(commands[i].getBuilderName())) {
- index = i;
- break;
- }
- }
-
- // we're inserting after
- index++;
-
- // do the insertion
-
- // copy the builders before.
- ICommand[] newCommands = new ICommand[commands.length + 1];
- System.arraycopy(commands, 0, newCommands, 0, index);
-
- // insert the new builder
- ICommand command = desc.newCommand();
- command.setBuilderName(PreCompilerBuilder.ID);
- newCommands[index] = command;
-
- // copy the builder after
- System.arraycopy(commands, index, newCommands, index + 1, commands.length-index);
-
- // set the new builders in the project
- desc.setBuildSpec(newCommands);
- project.setDescription(desc, null);
- }
-
- public static void configureApkBuilder(IProject project)
- throws CoreException {
- // Add the .apk builder at the end if it's not already there
- IProjectDescription desc = project.getDescription();
- ICommand[] commands = desc.getBuildSpec();
-
- for (int i = 0; i < commands.length; ++i) {
- if (PostCompilerBuilder.ID.equals(commands[i].getBuilderName())) {
- return;
- }
- }
-
- ICommand[] newCommands = new ICommand[commands.length + 1];
- System.arraycopy(commands, 0, newCommands, 0, commands.length);
- ICommand command = desc.newCommand();
- command.setBuilderName(PostCompilerBuilder.ID);
- newCommands[commands.length] = command;
- desc.setBuildSpec(newCommands);
- project.setDescription(desc, null);
- }
-
- /**
- * Removes a builder from the project.
- * @param project The project to remove the builder from.
- * @param id The String ID of the builder to remove.
- * @return true if the builder was found and removed.
- * @throws CoreException
- */
- public static boolean removeBuilder(IProject project, String id) throws CoreException {
- IProjectDescription description = project.getDescription();
- ICommand[] commands = description.getBuildSpec();
- for (int i = 0; i < commands.length; ++i) {
- if (id.equals(commands[i].getBuilderName())) {
- ICommand[] newCommands = new ICommand[commands.length - 1];
- System.arraycopy(commands, 0, newCommands, 0, i);
- System.arraycopy(commands, i + 1, newCommands, i, commands.length - i - 1);
- description.setBuildSpec(newCommands);
- project.setDescription(description, null);
- return true;
- }
- }
-
- return false;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/ApkInstallManager.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/ApkInstallManager.java
deleted file mode 100644
index 903914684..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/ApkInstallManager.java
+++ /dev/null
@@ -1,278 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.project;
-
-import com.android.ddmlib.AndroidDebugBridge;
-import com.android.ddmlib.AndroidDebugBridge.IDebugBridgeChangeListener;
-import com.android.ddmlib.AndroidDebugBridge.IDeviceChangeListener;
-import com.android.ddmlib.IDevice;
-import com.android.ddmlib.MultiLineReceiver;
-import com.android.ide.eclipse.adt.internal.resources.manager.GlobalProjectMonitor;
-import com.android.ide.eclipse.adt.internal.resources.manager.GlobalProjectMonitor.IProjectListener;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IPath;
-
-import java.util.HashSet;
-import java.util.Iterator;
-
-/**
- * Registers which apk was installed on which device.
- * <p/>
- * The goal of this class is to remember the installation of APKs on devices, and provide
- * information about whether a new APK should be installed on a device prior to running the
- * application from a launch configuration.
- * <p/>
- * The manager uses {@link IProject} and {@link IDevice} to identify the target device and the
- * (project generating the) APK. This ensures that disconnected and reconnected devices will
- * always receive new APKs (since the version may not match).
- * <p/>
- * This is a singleton. To get the instance, use {@link #getInstance()}
- */
-public final class ApkInstallManager {
-
- private final static ApkInstallManager sThis = new ApkInstallManager();
-
- /**
- * Internal struct to associate a project and a device.
- */
- private final static class ApkInstall {
- public ApkInstall(IProject project, String packageName, IDevice device) {
- this.project = project;
- this.packageName = packageName;
- this.device = device;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj instanceof ApkInstall) {
- ApkInstall apkObj = (ApkInstall)obj;
-
- return (device == apkObj.device && project.equals(apkObj.project) &&
- packageName.equals(apkObj.packageName));
- }
-
- return false;
- }
-
- @Override
- public int hashCode() {
- return (device.getSerialNumber() + project.getName() + packageName).hashCode();
- }
-
- final IProject project;
- final String packageName;
- final IDevice device;
- }
-
- /**
- * Receiver and parser for the "pm path package" command.
- */
- private final static class PmReceiver extends MultiLineReceiver {
- boolean foundPackage = false;
- @Override
- public void processNewLines(String[] lines) {
- // if the package if found, then pm will show a line starting with "package:/"
- if (foundPackage == false) { // just in case this is called several times for multilines
- for (String line : lines) {
- if (line.startsWith("package:/")) {
- foundPackage = true;
- break;
- }
- }
- }
- }
-
- @Override
- public boolean isCancelled() {
- return false;
- }
- }
-
- /**
- * Hashset of the list of installed package. Hashset used to ensure we don't re-add new
- * objects for the same app.
- */
- private final HashSet<ApkInstall> mInstallList = new HashSet<ApkInstall>();
-
- public static ApkInstallManager getInstance() {
- return sThis;
- }
-
- /**
- * Registers an installation of <var>project</var> onto <var>device</var>
- * @param project The project that was installed.
- * @param packageName the package name of the apk
- * @param device The device that received the installation.
- */
- public void registerInstallation(IProject project, String packageName, IDevice device) {
- synchronized (mInstallList) {
- mInstallList.add(new ApkInstall(project, packageName, device));
- }
- }
-
- /**
- * Returns whether a <var>project</var> was installed on the <var>device</var>.
- * @param project the project that may have been installed.
- * @param device the device that may have received the installation.
- * @return
- */
- public boolean isApplicationInstalled(IProject project, String packageName, IDevice device) {
- synchronized (mInstallList) {
- ApkInstall found = null;
- for (ApkInstall install : mInstallList) {
- if (project.equals(install.project) && packageName.equals(install.packageName) &&
- device == install.device) {
- found = install;
- break;
- }
- }
-
- // check the app is still installed.
- if (found != null) {
- try {
- PmReceiver receiver = new PmReceiver();
- found.device.executeShellCommand("pm path " + packageName, receiver);
- if (receiver.foundPackage == false) {
- mInstallList.remove(found);
- }
-
- return receiver.foundPackage;
- } catch (Exception e) {
- // failed to query pm? force reinstall.
- return false;
- }
- }
- }
- return false;
- }
-
- /**
- * Resets registered installations for a specific {@link IProject}.
- * <p/>This ensures that {@link #isApplicationInstalled(IProject, IDevice)} will always return
- * <code>null</code> for this specified project, for any device.
- * @param project the project for which to reset all installations.
- */
- public void resetInstallationFor(IProject project) {
- synchronized (mInstallList) {
- Iterator<ApkInstall> iterator = mInstallList.iterator();
- while (iterator.hasNext()) {
- ApkInstall install = iterator.next();
- if (install.project.equals(project)) {
- iterator.remove();
- }
- }
- }
- }
-
- private ApkInstallManager() {
- AndroidDebugBridge.addDeviceChangeListener(mDeviceChangeListener);
- AndroidDebugBridge.addDebugBridgeChangeListener(mDebugBridgeListener);
- GlobalProjectMonitor.getMonitor().addProjectListener(mProjectListener);
- }
-
- private IDebugBridgeChangeListener mDebugBridgeListener = new IDebugBridgeChangeListener() {
- /**
- * Responds to a bridge change by clearing the full installation list.
- *
- * @see IDebugBridgeChangeListener#bridgeChanged(AndroidDebugBridge)
- */
- @Override
- public void bridgeChanged(AndroidDebugBridge bridge) {
- // the bridge changed, there is no way to know which IDevice will be which.
- // We reset everything
- synchronized (mInstallList) {
- mInstallList.clear();
- }
- }
- };
-
- private IDeviceChangeListener mDeviceChangeListener = new IDeviceChangeListener() {
- /**
- * Responds to a device being disconnected by removing all installations related
- * to this device.
- *
- * @see IDeviceChangeListener#deviceDisconnected(IDevice)
- */
- @Override
- public void deviceDisconnected(IDevice device) {
- synchronized (mInstallList) {
- Iterator<ApkInstall> iterator = mInstallList.iterator();
- while (iterator.hasNext()) {
- ApkInstall install = iterator.next();
- if (install.device == device) {
- iterator.remove();
- }
- }
- }
- }
-
- @Override
- public void deviceChanged(IDevice device, int changeMask) {
- // nothing to do.
- }
-
- @Override
- public void deviceConnected(IDevice device) {
- // nothing to do.
- }
- };
-
- private IProjectListener mProjectListener = new IProjectListener() {
- /**
- * Responds to a closed project by resetting all its installation.
- *
- * @see IProjectListener#projectClosed(IProject)
- */
- @Override
- public void projectClosed(IProject project) {
- resetInstallationFor(project);
- }
-
- /**
- * Responds to a deleted project by resetting all its installation.
- *
- * @see IProjectListener#projectDeleted(IProject)
- */
- @Override
- public void projectDeleted(IProject project) {
- resetInstallationFor(project);
- }
-
- @Override
- public void projectOpened(IProject project) {
- // nothing to do.
- }
-
- @Override
- public void projectOpenedWithWorkspace(IProject project) {
- // nothing to do.
- }
-
- @Override
- public void allProjectsOpenedWithWorkspace() {
- // nothing to do.
- }
-
- @Override
- public void projectRenamed(IProject project, IPath from) {
- // project renaming also triggers delete/open events so
- // there's nothing to do here (since delete will remove
- // whatever's linked to the project from the list).
- }
- };
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/BaseClasspathContainerInitializer.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/BaseClasspathContainerInitializer.java
deleted file mode 100644
index a58f27d61..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/BaseClasspathContainerInitializer.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.project;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jdt.core.ClasspathContainerInitializer;
-
-/**
- * Base CPC initializer providing support to all our initializer.
- *
- */
-abstract class BaseClasspathContainerInitializer extends ClasspathContainerInitializer {
-
-
- /**
- * Adds an error to a project, or remove all markers if error message is null
- * @param project the project to modify
- * @param errorMessage the errorMessage or null to remove errors.
- * @param markerType the marker type to be used.
- * @param outputToConsole whether to output to the console.
- */
- protected static void processError(final IProject project, final String errorMessage,
- final String markerType, boolean outputToConsole) {
- if (errorMessage != null) {
- // log the error and put the marker on the project if we can.
- if (outputToConsole) {
- AdtPlugin.printErrorToConsole(project, errorMessage);
- }
-
- // Use a job to prevent requiring a workspace lock in this thread.
- final String fmessage = errorMessage;
- Job markerJob = new Job("Android SDK: Resolving error markers") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- BaseProjectHelper.markProject(project,
- markerType,
- fmessage, IMarker.SEVERITY_ERROR,
- IMarker.PRIORITY_HIGH);
- } catch (CoreException e2) {
- AdtPlugin.log(e2, null);
- // Don't return e2.getStatus(); the job control will then produce
- // a popup with this error, which isn't very interesting for the
- // user.
- }
-
- return Status.OK_STATUS;
- }
- };
-
- // build jobs are run after other interactive jobs
- markerJob.setPriority(Job.BUILD);
- markerJob.setRule(ResourcesPlugin.getWorkspace().getRoot());
- markerJob.schedule();
- } else {
- // Use a job to prevent requiring a workspace lock in this thread.
- Job markerJob = new Job("Android SDK: Resolving error markers") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- if (project.isAccessible()) {
- project.deleteMarkers(markerType, true,
- IResource.DEPTH_INFINITE);
- }
- } catch (CoreException e2) {
- AdtPlugin.log(e2, null);
- }
-
- return Status.OK_STATUS;
- }
- };
-
- // build jobs are run after other interactive jobs
- markerJob.setPriority(Job.BUILD);
- markerJob.setRule(ResourcesPlugin.getWorkspace().getRoot());
- markerJob.schedule();
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/BaseProjectHelper.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/BaseProjectHelper.java
deleted file mode 100644
index 57632ea87..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/BaseProjectHelper.java
+++ /dev/null
@@ -1,527 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.project;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.google.common.collect.Lists;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jdt.core.Flags;
-import org.eclipse.jdt.core.IClasspathEntry;
-import org.eclipse.jdt.core.IJavaModel;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IMethod;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.core.ITypeHierarchy;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.ui.JavaUI;
-import org.eclipse.jdt.ui.actions.OpenJavaPerspectiveAction;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.ui.texteditor.ITextEditor;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Utility methods to manipulate projects.
- */
-public final class BaseProjectHelper {
-
- public static final String TEST_CLASS_OK = null;
-
- /**
- * Project filter to be used with {@link BaseProjectHelper#getAndroidProjects(IProjectFilter)}.
- */
- public static interface IProjectFilter {
- boolean accept(IProject project);
- }
-
- /**
- * returns a list of source classpath for a specified project
- * @param javaProject
- * @return a list of path relative to the workspace root.
- */
- @NonNull
- public static List<IPath> getSourceClasspaths(IJavaProject javaProject) {
- List<IPath> sourceList = Lists.newArrayList();
- IClasspathEntry[] classpaths = javaProject.readRawClasspath();
- if (classpaths != null) {
- for (IClasspathEntry e : classpaths) {
- if (e.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
- sourceList.add(e.getPath());
- }
- }
- }
-
- return sourceList;
- }
-
- /**
- * returns a list of source classpath for a specified project
- * @param project
- * @return a list of path relative to the workspace root.
- */
- public static List<IPath> getSourceClasspaths(IProject project) {
- IJavaProject javaProject = JavaCore.create(project);
- return getSourceClasspaths(javaProject);
- }
-
- /**
- * Adds a marker to a file on a specific line. This methods catches thrown
- * {@link CoreException}, and returns null instead.
- * @param resource the resource to be marked
- * @param markerId The id of the marker to add.
- * @param message the message associated with the mark
- * @param lineNumber the line number where to put the mark. If line is < 1, it puts the marker
- * on line 1,
- * @param severity the severity of the marker.
- * @return the IMarker that was added or null if it failed to add one.
- */
- public final static IMarker markResource(IResource resource, String markerId,
- String message, int lineNumber, int severity) {
- return markResource(resource, markerId, message, lineNumber, -1, -1, severity);
- }
-
- /**
- * Adds a marker to a file on a specific line, for a specific range of text. This
- * methods catches thrown {@link CoreException}, and returns null instead.
- *
- * @param resource the resource to be marked
- * @param markerId The id of the marker to add.
- * @param message the message associated with the mark
- * @param lineNumber the line number where to put the mark. If line is < 1, it puts
- * the marker on line 1,
- * @param startOffset the beginning offset of the marker (relative to the beginning of
- * the document, not the line), or -1 for no range
- * @param endOffset the ending offset of the marker
- * @param severity the severity of the marker.
- * @return the IMarker that was added or null if it failed to add one.
- */
- @Nullable
- public final static IMarker markResource(IResource resource, String markerId,
- String message, int lineNumber, int startOffset, int endOffset, int severity) {
- if (!resource.isAccessible()) {
- return null;
- }
-
- try {
- IMarker marker = resource.createMarker(markerId);
- marker.setAttribute(IMarker.MESSAGE, message);
- marker.setAttribute(IMarker.SEVERITY, severity);
-
- // if marker is text type, enforce a line number so that it shows in the editor
- // somewhere (line 1)
- if (lineNumber < 1 && marker.isSubtypeOf(IMarker.TEXT)) {
- lineNumber = 1;
- }
-
- if (lineNumber >= 1) {
- marker.setAttribute(IMarker.LINE_NUMBER, lineNumber);
- }
-
- if (startOffset != -1) {
- marker.setAttribute(IMarker.CHAR_START, startOffset);
- marker.setAttribute(IMarker.CHAR_END, endOffset);
- }
-
- // on Windows, when adding a marker to a project, it takes a refresh for the marker
- // to show. In order to fix this we're forcing a refresh of elements receiving
- // markers (and only the element, not its children), to force the marker display.
- resource.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor());
-
- return marker;
- } catch (CoreException e) {
- AdtPlugin.log(e, "Failed to add marker '%1$s' to '%2$s'", //$NON-NLS-1$
- markerId, resource.getFullPath());
- }
-
- return null;
- }
-
- /**
- * Adds a marker to a resource. This methods catches thrown {@link CoreException},
- * and returns null instead.
- * @param resource the file to be marked
- * @param markerId The id of the marker to add.
- * @param message the message associated with the mark
- * @param severity the severity of the marker.
- * @return the IMarker that was added or null if it failed to add one.
- */
- @Nullable
- public final static IMarker markResource(IResource resource, String markerId,
- String message, int severity) {
- return markResource(resource, markerId, message, -1, severity);
- }
-
- /**
- * Adds a marker to an {@link IProject}. This method does not catch {@link CoreException}, like
- * {@link #markResource(IResource, String, String, int)}.
- *
- * @param project the project to be marked
- * @param markerId The id of the marker to add.
- * @param message the message associated with the mark
- * @param severity the severity of the marker.
- * @param priority the priority of the marker
- * @return the IMarker that was added.
- * @throws CoreException if the marker cannot be added
- */
- @Nullable
- public final static IMarker markProject(IProject project, String markerId,
- String message, int severity, int priority) throws CoreException {
- if (!project.isAccessible()) {
- return null;
- }
-
- IMarker marker = project.createMarker(markerId);
- marker.setAttribute(IMarker.MESSAGE, message);
- marker.setAttribute(IMarker.SEVERITY, severity);
- marker.setAttribute(IMarker.PRIORITY, priority);
-
- // on Windows, when adding a marker to a project, it takes a refresh for the marker
- // to show. In order to fix this we're forcing a refresh of elements receiving
- // markers (and only the element, not its children), to force the marker display.
- project.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor());
-
- return marker;
- }
-
- /**
- * Tests that a class name is valid for usage in the manifest.
- * <p/>
- * This tests the class existence, that it can be instantiated (ie it must not be abstract,
- * nor non static if enclosed), and that it extends the proper super class (not necessarily
- * directly)
- * @param javaProject the {@link IJavaProject} containing the class.
- * @param className the fully qualified name of the class to test.
- * @param superClassName the fully qualified name of the expected super class.
- * @param testVisibility if <code>true</code>, the method will check the visibility of the class
- * or of its constructors.
- * @return {@link #TEST_CLASS_OK} or an error message.
- */
- public final static String testClassForManifest(IJavaProject javaProject, String className,
- String superClassName, boolean testVisibility) {
- try {
- // replace $ by .
- String javaClassName = className.replaceAll("\\$", "\\."); //$NON-NLS-1$ //$NON-NLS-2$
-
- // look for the IType object for this class
- IType type = javaProject.findType(javaClassName);
- if (type != null && type.exists()) {
- // test that the class is not abstract
- int flags = type.getFlags();
- if (Flags.isAbstract(flags)) {
- return String.format("%1$s is abstract", className);
- }
-
- // test whether the class is public or not.
- if (testVisibility && Flags.isPublic(flags) == false) {
- // if its not public, it may have a public default constructor,
- // which would then be fine.
- IMethod basicConstructor = type.getMethod(type.getElementName(), new String[0]);
- if (basicConstructor != null && basicConstructor.exists()) {
- int constructFlags = basicConstructor.getFlags();
- if (Flags.isPublic(constructFlags) == false) {
- return String.format(
- "%1$s or its default constructor must be public for the system to be able to instantiate it",
- className);
- }
- } else {
- return String.format(
- "%1$s must be public, or the system will not be able to instantiate it.",
- className);
- }
- }
-
- // If it's enclosed, test that it's static. If its declaring class is enclosed
- // as well, test that it is also static, and public.
- IType declaringType = type;
- do {
- IType tmpType = declaringType.getDeclaringType();
- if (tmpType != null) {
- if (tmpType.exists()) {
- flags = declaringType.getFlags();
- if (Flags.isStatic(flags) == false) {
- return String.format("%1$s is enclosed, but not static",
- declaringType.getFullyQualifiedName());
- }
-
- flags = tmpType.getFlags();
- if (testVisibility && Flags.isPublic(flags) == false) {
- return String.format("%1$s is not public",
- tmpType.getFullyQualifiedName());
- }
- } else {
- // if it doesn't exist, we need to exit so we may as well mark it null.
- tmpType = null;
- }
- }
- declaringType = tmpType;
- } while (declaringType != null);
-
- // test the class inherit from the specified super class.
- // get the type hierarchy
- ITypeHierarchy hierarchy = type.newSupertypeHierarchy(new NullProgressMonitor());
-
- // if the super class is not the reference class, it may inherit from
- // it so we get its supertype. At some point it will be null and we
- // will stop
- IType superType = type;
- boolean foundProperSuperClass = false;
- while ((superType = hierarchy.getSuperclass(superType)) != null &&
- superType.exists()) {
- if (superClassName.equals(superType.getFullyQualifiedName())) {
- foundProperSuperClass = true;
- }
- }
-
- // didn't find the proper superclass? return false.
- if (foundProperSuperClass == false) {
- return String.format("%1$s does not extend %2$s", className, superClassName);
- }
-
- return TEST_CLASS_OK;
- } else {
- return String.format("Class %1$s does not exist", className);
- }
- } catch (JavaModelException e) {
- return String.format("%1$s: %2$s", className, e.getMessage());
- }
- }
-
- /**
- * Returns the {@link IJavaProject} for a {@link IProject} object.
- * <p/>
- * This checks if the project has the Java Nature first.
- * @param project
- * @return the IJavaProject or null if the project couldn't be created or if the project
- * does not have the Java Nature.
- * @throws CoreException if this method fails. Reasons include:
- * <ul><li>This project does not exist.</li><li>This project is not open.</li></ul>
- */
- public static IJavaProject getJavaProject(IProject project) throws CoreException {
- if (project != null && project.hasNature(JavaCore.NATURE_ID)) {
- return JavaCore.create(project);
- }
- return null;
- }
-
- /**
- * Reveals a specific line in the source file defining a specified class,
- * for a specific project.
- * @param project
- * @param className
- * @param line
- * @return true if the source was revealed
- */
- public static boolean revealSource(IProject project, String className, int line) {
- // Inner classes are pointless: All we need is the enclosing type to find the file, and the
- // line number.
- // Since the anonymous ones will cause IJavaProject#findType to fail, we remove
- // all of them.
- int pos = className.indexOf('$');
- if (pos != -1) {
- className = className.substring(0, pos);
- }
-
- // get the java project
- IJavaProject javaProject = JavaCore.create(project);
-
- try {
- // look for the IType matching the class name.
- IType result = javaProject.findType(className);
- if (result != null && result.exists()) {
- // before we show the type in an editor window, we make sure the current
- // workbench page has an editor area (typically the ddms perspective doesn't).
- IWorkbench workbench = PlatformUI.getWorkbench();
- IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
- IWorkbenchPage page = window.getActivePage();
- if (page.isEditorAreaVisible() == false) {
- // no editor area? we open the java perspective.
- new OpenJavaPerspectiveAction().run();
- }
-
- IEditorPart editor = JavaUI.openInEditor(result);
- if (editor instanceof ITextEditor) {
- // get the text editor that was just opened.
- ITextEditor textEditor = (ITextEditor)editor;
-
- IEditorInput input = textEditor.getEditorInput();
-
- // get the location of the line to show.
- IDocumentProvider documentProvider = textEditor.getDocumentProvider();
- IDocument document = documentProvider.getDocument(input);
- IRegion lineInfo = document.getLineInformation(line - 1);
-
- // select and reveal the line.
- textEditor.selectAndReveal(lineInfo.getOffset(), lineInfo.getLength());
- }
-
- return true;
- }
- } catch (JavaModelException e) {
- } catch (PartInitException e) {
- } catch (BadLocationException e) {
- }
-
- return false;
- }
-
- /**
- * Returns the list of android-flagged projects. This list contains projects that are opened
- * in the workspace and that are flagged as android project (through the android nature)
- * @param filter an optional filter to control which android project are returned. Can be null.
- * @return an array of IJavaProject, which can be empty if no projects match.
- */
- public static @NonNull IJavaProject[] getAndroidProjects(@Nullable IProjectFilter filter) {
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
- IJavaModel javaModel = JavaCore.create(workspaceRoot);
-
- return getAndroidProjects(javaModel, filter);
- }
-
- /**
- * Returns the list of android-flagged projects for the specified java Model.
- * This list contains projects that are opened in the workspace and that are flagged as android
- * project (through the android nature)
- * @param javaModel the Java Model object corresponding for the current workspace root.
- * @param filter an optional filter to control which android project are returned. Can be null.
- * @return an array of IJavaProject, which can be empty if no projects match.
- */
- @NonNull
- public static IJavaProject[] getAndroidProjects(@NonNull IJavaModel javaModel,
- @Nullable IProjectFilter filter) {
- // get the java projects
- IJavaProject[] javaProjectList = null;
- try {
- javaProjectList = javaModel.getJavaProjects();
- }
- catch (JavaModelException jme) {
- return new IJavaProject[0];
- }
-
- // temp list to build the android project array
- ArrayList<IJavaProject> androidProjectList = new ArrayList<IJavaProject>();
-
- // loop through the projects and add the android flagged projects to the temp list.
- for (IJavaProject javaProject : javaProjectList) {
- // get the workspace project object
- IProject project = javaProject.getProject();
-
- // check if it's an android project based on its nature
- if (isAndroidProject(project)) {
- if (filter == null || filter.accept(project)) {
- androidProjectList.add(javaProject);
- }
- }
- }
-
- // return the android projects list.
- return androidProjectList.toArray(new IJavaProject[androidProjectList.size()]);
- }
-
- /**
- * Returns true if the given project is an Android project (e.g. is a Java project
- * that also has the Android nature)
- *
- * @param project the project to test
- * @return true if the given project is an Android project
- */
- public static boolean isAndroidProject(IProject project) {
- // check if it's an android project based on its nature
- try {
- return project.hasNature(AdtConstants.NATURE_DEFAULT);
- } catch (CoreException e) {
- // this exception, thrown by IProject.hasNature(), means the project either doesn't
- // exist or isn't opened. So, in any case we just skip it (the exception will
- // bypass the ArrayList.add()
- }
-
- return false;
- }
-
- /**
- * Returns the {@link IFolder} representing the output for the project for Android specific
- * files.
- * <p>
- * The project must be a java project and be opened, or the method will return null.
- * @param project the {@link IProject}
- * @return an IFolder item or null.
- */
- public final static IFolder getJavaOutputFolder(IProject project) {
- try {
- if (project.isOpen() && project.hasNature(JavaCore.NATURE_ID)) {
- // get a java project from the normal project object
- IJavaProject javaProject = JavaCore.create(project);
-
- IPath path = javaProject.getOutputLocation();
- path = path.removeFirstSegments(1);
- return project.getFolder(path);
- }
- } catch (JavaModelException e) {
- // Let's do nothing and return null
- } catch (CoreException e) {
- // Let's do nothing and return null
- }
- return null;
- }
-
- /**
- * Returns the {@link IFolder} representing the output for the project for compiled Java
- * files.
- * <p>
- * The project must be a java project and be opened, or the method will return null.
- * @param project the {@link IProject}
- * @return an IFolder item or null.
- */
- @Nullable
- public final static IFolder getAndroidOutputFolder(IProject project) {
- try {
- if (project.isOpen() && project.hasNature(JavaCore.NATURE_ID)) {
- return project.getFolder(SdkConstants.FD_OUTPUT);
- }
- } catch (JavaModelException e) {
- // Let's do nothing and return null
- } catch (CoreException e) {
- // Let's do nothing and return null
- }
- return null;
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/ExportHelper.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/ExportHelper.java
deleted file mode 100644
index 56e0c0938..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/ExportHelper.java
+++ /dev/null
@@ -1,448 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.project;
-
-import static com.android.sdklib.internal.project.ProjectProperties.PROPERTY_SDK;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AndroidPrintStream;
-import com.android.ide.eclipse.adt.internal.build.BuildHelper;
-import com.android.ide.eclipse.adt.internal.build.DexException;
-import com.android.ide.eclipse.adt.internal.build.NativeLibInJarException;
-import com.android.ide.eclipse.adt.internal.build.ProguardExecException;
-import com.android.ide.eclipse.adt.internal.build.ProguardResultException;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.io.IFileWrapper;
-import com.android.sdklib.BuildToolInfo;
-import com.android.sdklib.build.ApkCreationException;
-import com.android.sdklib.build.DuplicateFileException;
-import com.android.sdklib.internal.project.ProjectProperties;
-import com.android.tools.lint.detector.api.LintUtils;
-import com.android.xml.AndroidManifest;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IncrementalProjectBuilder;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Shell;
-
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.security.PrivateKey;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.jar.JarEntry;
-import java.util.jar.JarOutputStream;
-
-/**
- * Export helper to export release version of APKs.
- */
-public final class ExportHelper {
- private static final String HOME_PROPERTY = "user.home"; //$NON-NLS-1$
- private static final String HOME_PROPERTY_REF = "${" + HOME_PROPERTY + '}'; //$NON-NLS-1$
- private static final String SDK_PROPERTY_REF = "${" + PROPERTY_SDK + '}'; //$NON-NLS-1$
- private final static String TEMP_PREFIX = "android_"; //$NON-NLS-1$
-
- /**
- * Exports a release version of the application created by the given project.
- * @param project the project to export
- * @param outputFile the file to write
- * @param key the key to used for signing. Can be null.
- * @param certificate the certificate used for signing. Can be null.
- * @param monitor progress monitor
- * @throws CoreException if an error occurs
- */
- public static void exportReleaseApk(IProject project, File outputFile, PrivateKey key,
- X509Certificate certificate, IProgressMonitor monitor) throws CoreException {
-
- // the export, takes the output of the precompiler & Java builders so it's
- // important to call build in case the auto-build option of the workspace is disabled.
- // Also enable dependency building to make sure everything is up to date.
- // However do not package the APK since we're going to do it manually here, using a
- // different output location.
- ProjectHelper.compileInReleaseMode(project, monitor);
-
- // if either key or certificate is null, ensure the other is null.
- if (key == null) {
- certificate = null;
- } else if (certificate == null) {
- key = null;
- }
-
- try {
- // check if the manifest declares debuggable as true. While this is a release build,
- // debuggable in the manifest will override this and generate a debug build
- IResource manifestResource = project.findMember(SdkConstants.FN_ANDROID_MANIFEST_XML);
- if (manifestResource.getType() != IResource.FILE) {
- throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- String.format("%1$s missing.", SdkConstants.FN_ANDROID_MANIFEST_XML)));
- }
-
- IFileWrapper manifestFile = new IFileWrapper((IFile) manifestResource);
- boolean debugMode = AndroidManifest.getDebuggable(manifestFile);
-
- AndroidPrintStream fakeStream = new AndroidPrintStream(null, null, new OutputStream() {
- @Override
- public void write(int b) throws IOException {
- // do nothing
- }
- });
-
- ProjectState projectState = Sdk.getProjectState(project);
-
- // get the jumbo mode option
- String forceJumboStr = projectState.getProperty(AdtConstants.DEX_OPTIONS_FORCEJUMBO);
- Boolean jumbo = Boolean.valueOf(forceJumboStr);
-
- String dexMergerStr = projectState.getProperty(AdtConstants.DEX_OPTIONS_DISABLE_MERGER);
- Boolean dexMerger = Boolean.valueOf(dexMergerStr);
-
- BuildToolInfo buildToolInfo = getBuildTools(projectState);
-
- BuildHelper helper = new BuildHelper(
- projectState,
- buildToolInfo,
- fakeStream, fakeStream,
- jumbo.booleanValue(),
- dexMerger.booleanValue(),
- debugMode, false /*verbose*/,
- null /*resourceMarker*/);
-
- // get the list of library projects
- List<IProject> libProjects = projectState.getFullLibraryProjects();
-
- // Step 1. Package the resources.
-
- // tmp file for the packaged resource file. To not disturb the incremental builders
- // output, all intermediary files are created in tmp files.
- File resourceFile = File.createTempFile(TEMP_PREFIX, SdkConstants.DOT_RES);
- resourceFile.deleteOnExit();
-
- // Make sure the PNG crunch cache is up to date
- helper.updateCrunchCache();
-
- // get the merged manifest
- IFolder androidOutputFolder = BaseProjectHelper.getAndroidOutputFolder(project);
- IFile mergedManifestFile = androidOutputFolder.getFile(
- SdkConstants.FN_ANDROID_MANIFEST_XML);
-
-
- // package the resources.
- helper.packageResources(
- mergedManifestFile,
- libProjects,
- null, // res filter
- 0, // versionCode
- resourceFile.getParent(),
- resourceFile.getName());
-
- // Step 2. Convert the byte code to Dalvik bytecode
-
- // tmp file for the packaged resource file.
- File dexFile = File.createTempFile(TEMP_PREFIX, SdkConstants.DOT_DEX);
- dexFile.deleteOnExit();
-
- ProjectState state = Sdk.getProjectState(project);
- String proguardConfig = state.getProperties().getProperty(
- ProjectProperties.PROPERTY_PROGUARD_CONFIG);
-
- boolean runProguard = false;
- List<File> proguardConfigFiles = null;
- if (proguardConfig != null && proguardConfig.length() > 0) {
- // Be tolerant with respect to file and path separators just like
- // Ant is. Allow "/" in the property file to mean whatever the file
- // separator character is:
- if (File.separatorChar != '/' && proguardConfig.indexOf('/') != -1) {
- proguardConfig = proguardConfig.replace('/', File.separatorChar);
- }
-
- Iterable<String> paths = LintUtils.splitPath(proguardConfig);
- for (String path : paths) {
- if (path.startsWith(SDK_PROPERTY_REF)) {
- path = AdtPrefs.getPrefs().getOsSdkFolder() +
- path.substring(SDK_PROPERTY_REF.length());
- } else if (path.startsWith(HOME_PROPERTY_REF)) {
- path = System.getProperty(HOME_PROPERTY) +
- path.substring(HOME_PROPERTY_REF.length());
- }
- File proguardConfigFile = new File(path);
- if (proguardConfigFile.isAbsolute() == false) {
- proguardConfigFile = new File(project.getLocation().toFile(), path);
- }
- if (proguardConfigFile.isFile()) {
- if (proguardConfigFiles == null) {
- proguardConfigFiles = new ArrayList<File>();
- }
- proguardConfigFiles.add(proguardConfigFile);
- runProguard = true;
- } else {
- throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "Invalid proguard configuration file path " + proguardConfigFile
- + " does not exist or is not a regular file", null));
- }
- }
-
- // get the proguard file output by aapt
- if (proguardConfigFiles != null) {
- IFile proguardFile = androidOutputFolder.getFile(AdtConstants.FN_AAPT_PROGUARD);
- proguardConfigFiles.add(proguardFile.getLocation().toFile());
- }
- }
-
- Collection<String> dxInput;
-
- if (runProguard) {
- // get all the compiled code paths. This will contain both project output
- // folder and jar files.
- Collection<String> paths = helper.getCompiledCodePaths();
-
- // create a jar file containing all the project output (as proguard cannot
- // process folders of .class files).
- File inputJar = File.createTempFile(TEMP_PREFIX, SdkConstants.DOT_JAR);
- inputJar.deleteOnExit();
- JarOutputStream jos = new JarOutputStream(new FileOutputStream(inputJar));
-
- // a list of the other paths (jar files.)
- List<String> jars = new ArrayList<String>();
-
- for (String path : paths) {
- File root = new File(path);
- if (root.isDirectory()) {
- addFileToJar(jos, root, root);
- } else if (root.isFile()) {
- jars.add(path);
- }
- }
- jos.close();
-
- // destination file for proguard
- File obfuscatedJar = File.createTempFile(TEMP_PREFIX, SdkConstants.DOT_JAR);
- obfuscatedJar.deleteOnExit();
-
- // run proguard
- helper.runProguard(proguardConfigFiles, inputJar, jars, obfuscatedJar,
- new File(project.getLocation().toFile(), SdkConstants.FD_PROGUARD));
-
- helper.setProguardOutput(obfuscatedJar.getAbsolutePath());
-
- // dx input is proguard's output
- dxInput = Collections.singletonList(obfuscatedJar.getAbsolutePath());
- } else {
- // no proguard, simply get all the compiled code path: project output(s) +
- // jar file(s)
- dxInput = helper.getCompiledCodePaths();
- }
-
- IJavaProject javaProject = JavaCore.create(project);
-
- helper.executeDx(javaProject, dxInput, dexFile.getAbsolutePath());
-
- // Step 3. Final package
-
- helper.finalPackage(
- resourceFile.getAbsolutePath(),
- dexFile.getAbsolutePath(),
- outputFile.getAbsolutePath(),
- libProjects,
- key,
- certificate,
- null); //resourceMarker
-
- // success!
- } catch (CoreException e) {
- throw e;
- } catch (ProguardResultException e) {
- String msg = String.format("Proguard returned with error code %d. See console",
- e.getErrorCode());
- AdtPlugin.printErrorToConsole(project, msg);
- AdtPlugin.printErrorToConsole(project, (Object[]) e.getOutput());
- throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- msg, e));
- } catch (ProguardExecException e) {
- String msg = String.format("Failed to run proguard: %s", e.getMessage());
- AdtPlugin.printErrorToConsole(project, msg);
- throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- msg, e));
- } catch (DuplicateFileException e) {
- String msg = String.format(
- "Found duplicate file for APK: %1$s\nOrigin 1: %2$s\nOrigin 2: %3$s",
- e.getArchivePath(), e.getFile1(), e.getFile2());
- AdtPlugin.printErrorToConsole(project, msg);
- throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- e.getMessage(), e));
- } catch (NativeLibInJarException e) {
- String msg = e.getMessage();
-
- AdtPlugin.printErrorToConsole(project, msg);
- AdtPlugin.printErrorToConsole(project, (Object[]) e.getAdditionalInfo());
- throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- e.getMessage(), e));
- } catch (DexException e) {
- throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- e.getMessage(), e));
- } catch (ApkCreationException e) {
- throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- e.getMessage(), e));
- } catch (Exception e) {
- throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "Failed to export application", e));
- } finally {
- // move back to a debug build.
- // By using a normal build, we'll simply rebuild the debug version, and let the
- // builder decide whether to build the full package or not.
- ProjectHelper.buildWithDeps(project, IncrementalProjectBuilder.FULL_BUILD, monitor);
- project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
- }
- }
-
- public static BuildToolInfo getBuildTools(ProjectState projectState)
- throws CoreException {
- BuildToolInfo buildToolInfo = projectState.getBuildToolInfo();
- if (buildToolInfo == null) {
- buildToolInfo = Sdk.getCurrent().getLatestBuildTool();
- }
-
- if (buildToolInfo == null) {
- throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "No Build Tools installed in the SDK."));
- }
- return buildToolInfo;
- }
-
- /**
- * Exports an unsigned release APK after prompting the user for a location.
- *
- * <strong>Must be called from the UI thread.</strong>
- *
- * @param project the project to export
- */
- public static void exportUnsignedReleaseApk(final IProject project) {
- Shell shell = Display.getCurrent().getActiveShell();
-
- // create a default file name for the apk.
- String fileName = project.getName() + SdkConstants.DOT_ANDROID_PACKAGE;
-
- // Pop up the file save window to get the file location
- FileDialog fileDialog = new FileDialog(shell, SWT.SAVE);
-
- fileDialog.setText("Export Project");
- fileDialog.setFileName(fileName);
-
- final String saveLocation = fileDialog.open();
- if (saveLocation != null) {
- new Job("Android Release Export") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- exportReleaseApk(project,
- new File(saveLocation),
- null, //key
- null, //certificate
- monitor);
-
- // this is unsigned export. Let's tell the developers to run zip align
- AdtPlugin.displayWarning("Android IDE Plug-in", String.format(
- "An unsigned package of the application was saved at\n%1$s\n\n" +
- "Before publishing the application you will need to:\n" +
- "- Sign the application with your release key,\n" +
- "- run zipalign on the signed package. ZipAlign is located in <SDK>/tools/\n\n" +
- "Aligning applications allows Android to use application resources\n" +
- "more efficiently.", saveLocation));
-
- return Status.OK_STATUS;
- } catch (CoreException e) {
- AdtPlugin.displayError("Android IDE Plug-in", String.format(
- "Error exporting application:\n\n%1$s", e.getMessage()));
- return e.getStatus();
- }
- }
- }.schedule();
- }
- }
-
- /**
- * Adds a file to a jar file.
- * The <var>rootDirectory</var> dictates the path of the file inside the jar file. It must be
- * a parent of <var>file</var>.
- * @param jar the jar to add the file to
- * @param file the file to add
- * @param rootDirectory the rootDirectory.
- * @throws IOException
- */
- private static void addFileToJar(JarOutputStream jar, File file, File rootDirectory)
- throws IOException {
- if (file.isDirectory()) {
- if (file.getName().equals("META-INF") == false) {
- for (File child: file.listFiles()) {
- addFileToJar(jar, child, rootDirectory);
- }
- }
- } else if (file.isFile()) {
- String rootPath = rootDirectory.getAbsolutePath();
- String path = file.getAbsolutePath();
- path = path.substring(rootPath.length()).replace("\\", "/"); //$NON-NLS-1$ //$NON-NLS-2$
- if (path.charAt(0) == '/') {
- path = path.substring(1);
- }
-
- JarEntry entry = new JarEntry(path);
- entry.setTime(file.lastModified());
- jar.putNextEntry(entry);
-
- // put the content of the file.
- byte[] buffer = new byte[1024];
- int count;
- BufferedInputStream bis = null;
- try {
- bis = new BufferedInputStream(new FileInputStream(file));
- while ((count = bis.read(buffer)) != -1) {
- jar.write(buffer, 0, count);
- }
- } finally {
- if (bis != null) {
- try {
- bis.close();
- } catch (IOException ignore) {
- }
- }
- }
- jar.closeEntry();
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/FixLaunchConfig.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/FixLaunchConfig.java
deleted file mode 100644
index e311bfb0b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/FixLaunchConfig.java
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.project;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.launch.LaunchConfigDelegate;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.debug.core.DebugPlugin;
-import org.eclipse.debug.core.ILaunchConfiguration;
-import org.eclipse.debug.core.ILaunchConfigurationType;
-import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
-import org.eclipse.debug.core.ILaunchManager;
-import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
-
-import java.util.ArrayList;
-
-/**
- * Class to fix the launch configuration of a project if the java package
- * defined in the manifest has been changed.<br>
- * This fix can be done synchronously, or asynchronously.<br>
- * <code>start()</code> will start a thread that will do the fix.<br>
- * <code>run()</code> will do the fix in the current thread.<br><br>
- * By default, the fix first display a dialog to the user asking if he/she wants to
- * do the fix. This can be overriden by calling <code>setDisplayPrompt(false)</code>.
- *
- */
-public class FixLaunchConfig extends Thread {
-
- private IProject mProject;
- private String mOldPackage;
- private String mNewPackage;
-
- private boolean mDisplayPrompt = true;
-
- public FixLaunchConfig(IProject project, String oldPackage, String newPackage) {
- super();
-
- mProject = project;
- mOldPackage = oldPackage;
- mNewPackage = newPackage;
- }
-
- /**
- * Set the display prompt. If true run()/start() first ask the user if he/she wants
- * to fix the Launch Config
- * @param displayPrompt
- */
- public void setDisplayPrompt(boolean displayPrompt) {
- mDisplayPrompt = displayPrompt;
- }
-
- /**
- * Fix the Launch configurations.
- */
- @Override
- public void run() {
-
- if (mDisplayPrompt) {
- // ask the user if he really wants to fix the launch config
- boolean res = AdtPlugin.displayPrompt(
- "Launch Configuration Update",
- "The package definition in the manifest changed.\nDo you want to update your Launch Configuration(s)?");
-
- if (res == false) {
- return;
- }
- }
-
- // get the list of config for the project
- String projectName = mProject.getName();
- ILaunchConfiguration[] configs = findConfigs(mProject.getName());
-
- // loop through all the config and update the package
- for (ILaunchConfiguration config : configs) {
- try {
- // get the working copy so that we can make changes.
- ILaunchConfigurationWorkingCopy copy = config.getWorkingCopy();
-
- // get the attributes for the activity
- String activity = config.getAttribute(LaunchConfigDelegate.ATTR_ACTIVITY,
- ""); //$NON-NLS-1$
-
- // manifests can define activities that are not in the defined package,
- // so we need to make sure the activity is inside the old package.
- if (activity.startsWith(mOldPackage)) {
- // create the new activity
- activity = mNewPackage + activity.substring(mOldPackage.length());
-
- // put it in the copy
- copy.setAttribute(LaunchConfigDelegate.ATTR_ACTIVITY, activity);
-
- // save the config
- copy.doSave();
- }
- } catch (CoreException e) {
- // couldn't get the working copy. we output the error in the console
- String msg = String.format("Failed to modify %1$s: %2$s", projectName,
- e.getMessage());
- AdtPlugin.printErrorToConsole(mProject, msg);
- }
- }
-
- }
-
- /**
- * Looks for and returns all existing Launch Configuration object for a
- * specified project.
- * @param projectName The name of the project
- * @return all the ILaunchConfiguration object. If none are present, an empty array is
- * returned.
- */
- private static ILaunchConfiguration[] findConfigs(String projectName) {
- // get the launch manager
- ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
-
- // now get the config type for our particular android type.
- ILaunchConfigurationType configType = manager.
- getLaunchConfigurationType(LaunchConfigDelegate.ANDROID_LAUNCH_TYPE_ID);
-
- // create a temp list to hold all the valid configs
- ArrayList<ILaunchConfiguration> list = new ArrayList<ILaunchConfiguration>();
-
- try {
- ILaunchConfiguration[] configs = manager.getLaunchConfigurations(configType);
-
- for (ILaunchConfiguration config : configs) {
- if (config.getAttribute(
- IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME,
- "").equals(projectName)) { //$NON-NLS-1$
- list.add(config);
- }
- }
- } catch (CoreException e) {
- }
-
- return list.toArray(new ILaunchConfiguration[list.size()]);
-
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/FolderDecorator.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/FolderDecorator.java
deleted file mode 100644
index 054890f86..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/FolderDecorator.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.project;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.IDecoration;
-import org.eclipse.jface.viewers.ILabelDecorator;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.jface.viewers.ILightweightLabelDecorator;
-
-/**
- * A {@link ILabelDecorator} associated with an org.eclipse.ui.decorators extension.
- * This is used to add android icons in some special folders in the package explorer.
- */
-public class FolderDecorator implements ILightweightLabelDecorator {
-
- private ImageDescriptor mDescriptor;
-
- public FolderDecorator() {
- mDescriptor = AdtPlugin.getImageDescriptor("/icons/android_project.png"); //$NON-NLS-1$
- }
-
- @Override
- public void decorate(Object element, IDecoration decoration) {
- if (element instanceof IFolder) {
- IFolder folder = (IFolder)element;
-
- // get the project and make sure this is an android project
- IProject project = folder.getProject();
- if (project == null || !project.exists() || !folder.exists()) {
- return;
- }
-
- try {
- if (project.hasNature(AdtConstants.NATURE_DEFAULT)) {
- // check the folder is directly under the project.
- if (folder.getParent().getType() == IResource.PROJECT) {
- String name = folder.getName();
- if (name.equals(SdkConstants.FD_ASSETS)) {
- doDecoration(decoration, null);
- } else if (name.equals(SdkConstants.FD_RESOURCES)) {
- doDecoration(decoration, null);
- } else if (name.equals(SdkConstants.FD_GEN_SOURCES)) {
- doDecoration(decoration, " [Generated Java Files]");
- } else if (name.equals(SdkConstants.FD_NATIVE_LIBS)) {
- doDecoration(decoration, null);
- } else if (name.equals(SdkConstants.FD_OUTPUT)) {
- doDecoration(decoration, null);
- }
- }
- }
- } catch (CoreException e) {
- // log the error
- AdtPlugin.log(e, "Unable to get nature of project '%s'.", project.getName());
- }
- }
- }
-
- public void doDecoration(IDecoration decoration, String suffix) {
- decoration.addOverlay(mDescriptor, IDecoration.TOP_LEFT);
-
- if (suffix != null) {
- decoration.addSuffix(suffix);
- }
- }
-
- @Override
- public boolean isLabelProperty(Object element, String property) {
- // Property change do not affect the label
- return false;
- }
-
- @Override
- public void addListener(ILabelProviderListener listener) {
- // No state change will affect the rendering.
- }
-
- @Override
- public void removeListener(ILabelProviderListener listener) {
- // No state change will affect the rendering.
- }
-
- @Override
- public void dispose() {
- // nothing to dispose
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/LibraryClasspathContainerInitializer.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/LibraryClasspathContainerInitializer.java
deleted file mode 100644
index 8fbee4089..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/LibraryClasspathContainerInitializer.java
+++ /dev/null
@@ -1,641 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.project;
-
-import static com.android.ide.eclipse.adt.AdtConstants.CONTAINER_DEPENDENCIES;
-
-import com.android.SdkConstants;
-import com.android.ide.common.sdk.LoadStatus;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AndroidPrintStream;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.sdklib.BuildToolInfo;
-import com.android.sdklib.build.JarListSanitizer;
-import com.android.sdklib.build.JarListSanitizer.DifferentLibException;
-import com.android.sdklib.build.JarListSanitizer.Sha1Exception;
-import com.android.sdklib.build.RenderScriptProcessor;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jdt.core.IAccessRule;
-import org.eclipse.jdt.core.IClasspathAttribute;
-import org.eclipse.jdt.core.IClasspathContainer;
-import org.eclipse.jdt.core.IClasspathEntry;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.JavaModelException;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.MalformedURLException;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Properties;
-import java.util.Set;
-
-public class LibraryClasspathContainerInitializer extends BaseClasspathContainerInitializer {
-
- private final static String ATTR_SRC = "src"; //$NON-NLS-1$
- private final static String ATTR_DOC = "doc"; //$NON-NLS-1$
- private final static String DOT_PROPERTIES = ".properties"; //$NON-NLS-1$
-
- public LibraryClasspathContainerInitializer() {
- }
-
- /**
- * Updates the {@link IJavaProject} objects with new library.
- * @param androidProjects the projects to update.
- * @return <code>true</code> if success, <code>false</code> otherwise.
- */
- public static boolean updateProjects(IJavaProject[] androidProjects) {
- try {
- // Allocate a new AndroidClasspathContainer, and associate it to the library
- // container id for each projects.
- int projectCount = androidProjects.length;
-
- IClasspathContainer[] libraryContainers = new IClasspathContainer[projectCount];
- IClasspathContainer[] dependencyContainers = new IClasspathContainer[projectCount];
- for (int i = 0 ; i < projectCount; i++) {
- libraryContainers[i] = allocateLibraryContainer(androidProjects[i]);
- dependencyContainers[i] = allocateDependencyContainer(androidProjects[i]);
- }
-
- // give each project their new container in one call.
- JavaCore.setClasspathContainer(
- new Path(AdtConstants.CONTAINER_PRIVATE_LIBRARIES),
- androidProjects, libraryContainers, new NullProgressMonitor());
-
- JavaCore.setClasspathContainer(
- new Path(AdtConstants.CONTAINER_DEPENDENCIES),
- androidProjects, dependencyContainers, new NullProgressMonitor());
- return true;
- } catch (JavaModelException e) {
- return false;
- }
- }
-
- /**
- * Updates the {@link IJavaProject} objects with new library.
- * @param androidProjects the projects to update.
- * @return <code>true</code> if success, <code>false</code> otherwise.
- */
- public static boolean updateProject(List<ProjectState> projects) {
- List<IJavaProject> javaProjectList = new ArrayList<IJavaProject>(projects.size());
- for (ProjectState p : projects) {
- IJavaProject javaProject = JavaCore.create(p.getProject());
- if (javaProject != null) {
- javaProjectList.add(javaProject);
- }
- }
-
- IJavaProject[] javaProjects = javaProjectList.toArray(
- new IJavaProject[javaProjectList.size()]);
-
- return updateProjects(javaProjects);
- }
-
- @Override
- public void initialize(IPath containerPath, IJavaProject project) throws CoreException {
- if (AdtConstants.CONTAINER_PRIVATE_LIBRARIES.equals(containerPath.toString())) {
- IClasspathContainer libraries = allocateLibraryContainer(project);
- if (libraries != null) {
- JavaCore.setClasspathContainer(new Path(AdtConstants.CONTAINER_PRIVATE_LIBRARIES),
- new IJavaProject[] { project },
- new IClasspathContainer[] { libraries },
- new NullProgressMonitor());
- }
-
- } else if(AdtConstants.CONTAINER_DEPENDENCIES.equals(containerPath.toString())) {
- IClasspathContainer dependencies = allocateDependencyContainer(project);
- if (dependencies != null) {
- JavaCore.setClasspathContainer(new Path(AdtConstants.CONTAINER_DEPENDENCIES),
- new IJavaProject[] { project },
- new IClasspathContainer[] { dependencies },
- new NullProgressMonitor());
- }
- }
- }
-
- private static IClasspathContainer allocateLibraryContainer(IJavaProject javaProject) {
- final IProject iProject = javaProject.getProject();
-
- // check if the project has a valid target.
- ProjectState state = Sdk.getProjectState(iProject);
- if (state == null) {
- // getProjectState should already have logged an error. Just bail out.
- return null;
- }
-
- /*
- * At this point we're going to gather a list of all that need to go in the
- * dependency container.
- * - Library project outputs (direct and indirect)
- * - Java project output (those can be indirectly referenced through library projects
- * or other other Java projects)
- * - Jar files:
- * + inside this project's libs/
- * + inside the library projects' libs/
- * + inside the referenced Java projects' classpath
- */
- List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();
-
- // list of java project dependencies and jar files that will be built while
- // going through the library projects.
- Set<File> jarFiles = new HashSet<File>();
- Set<IProject> refProjects = new HashSet<IProject>();
-
- // process all the libraries
-
- List<IProject> libProjects = state.getFullLibraryProjects();
- for (IProject libProject : libProjects) {
- // process all of the library project's dependencies
- getDependencyListFromClasspath(libProject, refProjects, jarFiles, true);
- }
-
- // now process this projects' referenced projects only.
- processReferencedProjects(iProject, refProjects, jarFiles);
-
- // and the content of its libs folder
- getJarListFromLibsFolder(iProject, jarFiles);
-
- // now add a classpath entry for each Java project (this is a set so dups are already
- // removed)
- for (IProject p : refProjects) {
- entries.add(JavaCore.newProjectEntry(p.getFullPath(), true /*isExported*/));
- }
-
- entries.addAll(convertJarsToClasspathEntries(iProject, jarFiles));
-
- return allocateContainer(javaProject, entries, new Path(AdtConstants.CONTAINER_PRIVATE_LIBRARIES),
- "Android Private Libraries");
- }
-
- private static List<IClasspathEntry> convertJarsToClasspathEntries(final IProject iProject,
- Set<File> jarFiles) {
- List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>(jarFiles.size());
-
- // and process the jar files list, but first sanitize it to remove dups.
- JarListSanitizer sanitizer = new JarListSanitizer(
- iProject.getFolder(SdkConstants.FD_OUTPUT).getLocation().toFile(),
- new AndroidPrintStream(iProject, null /*prefix*/,
- AdtPlugin.getOutStream()));
-
- String errorMessage = null;
-
- try {
- List<File> sanitizedList = sanitizer.sanitize(jarFiles);
-
- for (File jarFile : sanitizedList) {
- if (jarFile instanceof CPEFile) {
- CPEFile cpeFile = (CPEFile) jarFile;
- IClasspathEntry e = cpeFile.getClasspathEntry();
-
- entries.add(JavaCore.newLibraryEntry(
- e.getPath(),
- e.getSourceAttachmentPath(),
- e.getSourceAttachmentRootPath(),
- e.getAccessRules(),
- e.getExtraAttributes(),
- true /*isExported*/));
- } else {
- String jarPath = jarFile.getAbsolutePath();
-
- IPath sourceAttachmentPath = null;
- IClasspathAttribute javaDocAttribute = null;
-
- File jarProperties = new File(jarPath + DOT_PROPERTIES);
- if (jarProperties.isFile()) {
- Properties p = new Properties();
- InputStream is = null;
- try {
- p.load(is = new FileInputStream(jarProperties));
-
- String value = p.getProperty(ATTR_SRC);
- if (value != null) {
- File srcPath = getFile(jarFile, value);
-
- if (srcPath.exists()) {
- sourceAttachmentPath = new Path(srcPath.getAbsolutePath());
- }
- }
-
- value = p.getProperty(ATTR_DOC);
- if (value != null) {
- File docPath = getFile(jarFile, value);
- if (docPath.exists()) {
- try {
- javaDocAttribute = JavaCore.newClasspathAttribute(
- IClasspathAttribute.JAVADOC_LOCATION_ATTRIBUTE_NAME,
- docPath.toURI().toURL().toString());
- } catch (MalformedURLException e) {
- AdtPlugin.log(e, "Failed to process 'doc' attribute for %s",
- jarProperties.getAbsolutePath());
- }
- }
- }
-
- } catch (FileNotFoundException e) {
- // shouldn't happen since we check upfront
- } catch (IOException e) {
- AdtPlugin.log(e, "Failed to read %s", jarProperties.getAbsolutePath());
- } finally {
- if (is != null) {
- try {
- is.close();
- } catch (IOException e) {
- // ignore
- }
- }
- }
- }
-
- if (javaDocAttribute != null) {
- entries.add(JavaCore.newLibraryEntry(new Path(jarPath),
- sourceAttachmentPath, null /*sourceAttachmentRootPath*/,
- new IAccessRule[0],
- new IClasspathAttribute[] { javaDocAttribute },
- true /*isExported*/));
- } else {
- entries.add(JavaCore.newLibraryEntry(new Path(jarPath),
- sourceAttachmentPath, null /*sourceAttachmentRootPath*/,
- true /*isExported*/));
- }
- }
- }
- } catch (DifferentLibException e) {
- errorMessage = e.getMessage();
- AdtPlugin.printErrorToConsole(iProject, (Object[]) e.getDetails());
- } catch (Sha1Exception e) {
- errorMessage = e.getMessage();
- }
-
- processError(iProject, errorMessage, AdtConstants.MARKER_DEPENDENCY,
- true /*outputToConsole*/);
-
- return entries;
- }
-
- private static IClasspathContainer allocateDependencyContainer(IJavaProject javaProject) {
- final IProject iProject = javaProject.getProject();
- final List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();
- final Set<File> jarFiles = new HashSet<File>();
- final IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
-
- AdtPlugin plugin = AdtPlugin.getDefault();
- if (plugin == null) { // This is totally weird, but I've seen it happen!
- return null;
- }
-
- synchronized (Sdk.getLock()) {
- boolean sdkIsLoaded = plugin.getSdkLoadStatus() == LoadStatus.LOADED;
-
- // check if the project has a valid target.
- final ProjectState state = Sdk.getProjectState(iProject);
- if (state == null) {
- // getProjectState should already have logged an error. Just bail out.
- return null;
- }
-
- // annotations support for older version of android
- if (state.getTarget() != null && state.getTarget().getVersion().getApiLevel() <= 15) {
- File annotationsJar = new File(Sdk.getCurrent().getSdkOsLocation(),
- SdkConstants.FD_TOOLS + File.separator + SdkConstants.FD_SUPPORT +
- File.separator + SdkConstants.FN_ANNOTATIONS_JAR);
-
- jarFiles.add(annotationsJar);
- }
-
- if (state.getRenderScriptSupportMode()) {
- if (!sdkIsLoaded) {
- return null;
- }
- BuildToolInfo buildToolInfo = state.getBuildToolInfo();
- if (buildToolInfo == null) {
- buildToolInfo = Sdk.getCurrent().getLatestBuildTool();
-
- if (buildToolInfo == null) {
- return null;
- }
- }
-
- File renderScriptSupportJar = RenderScriptProcessor.getSupportJar(
- buildToolInfo.getLocation().getAbsolutePath());
-
- jarFiles.add(renderScriptSupportJar);
- }
-
- // process all the libraries
-
- List<IProject> libProjects = state.getFullLibraryProjects();
- for (IProject libProject : libProjects) {
- // get the project output
- IFolder outputFolder = BaseProjectHelper.getAndroidOutputFolder(libProject);
-
- if (outputFolder != null) { // can happen when closing/deleting a library)
- IFile jarIFile = outputFolder.getFile(libProject.getName().toLowerCase() +
- SdkConstants.DOT_JAR);
-
- // get the source folder for the library project
- List<IPath> srcs = BaseProjectHelper.getSourceClasspaths(libProject);
- // find the first non-derived source folder.
- IPath sourceFolder = null;
- for (IPath src : srcs) {
- IFolder srcFolder = workspaceRoot.getFolder(src);
- if (srcFolder.isDerived() == false) {
- sourceFolder = src;
- break;
- }
- }
-
- // we can directly add a CPE for this jar as there's no risk of a duplicate.
- IClasspathEntry entry = JavaCore.newLibraryEntry(
- jarIFile.getLocation(),
- sourceFolder, // source attachment path
- null, // default source attachment root path.
- true /*isExported*/);
-
- entries.add(entry);
- }
- }
-
- entries.addAll(convertJarsToClasspathEntries(iProject, jarFiles));
-
- return allocateContainer(javaProject, entries, new Path(CONTAINER_DEPENDENCIES),
- "Android Dependencies");
- }
- }
-
- private static IClasspathContainer allocateContainer(IJavaProject javaProject,
- List<IClasspathEntry> entries, IPath id, String description) {
-
- if (AdtPlugin.getDefault() == null) { // This is totally weird, but I've seen it happen!
- return null;
- }
-
- // First check that the project has a library-type container.
- try {
- IClasspathEntry[] rawClasspath = javaProject.getRawClasspath();
- final IClasspathEntry[] oldRawClasspath = rawClasspath;
-
- boolean foundContainer = false;
- for (IClasspathEntry entry : rawClasspath) {
- // get the entry and kind
- final int kind = entry.getEntryKind();
-
- if (kind == IClasspathEntry.CPE_CONTAINER) {
- String path = entry.getPath().toString();
- String idString = id.toString();
- if (idString.equals(path)) {
- foundContainer = true;
- break;
- }
- }
- }
-
- // if there isn't any, add it.
- if (foundContainer == false) {
- // add the android container to the array
- rawClasspath = ProjectHelper.addEntryToClasspath(rawClasspath,
- JavaCore.newContainerEntry(id, true /*isExported*/));
- }
-
- // set the new list of entries to the project
- if (rawClasspath != oldRawClasspath) {
- javaProject.setRawClasspath(rawClasspath, new NullProgressMonitor());
- }
- } catch (JavaModelException e) {
- // This really shouldn't happen, but if it does, simply return null (the calling
- // method will fails as well)
- return null;
- }
-
- return new AndroidClasspathContainer(
- entries.toArray(new IClasspathEntry[entries.size()]),
- id,
- description,
- IClasspathContainer.K_APPLICATION);
- }
-
- private static File getFile(File root, String value) {
- File file = new File(value);
- if (file.isAbsolute() == false) {
- file = new File(root.getParentFile(), value);
- }
-
- return file;
- }
-
- /**
- * Finds all the jar files inside a project's libs folder.
- * @param project
- * @param jarFiles
- */
- private static void getJarListFromLibsFolder(IProject project, Set<File> jarFiles) {
- IFolder libsFolder = project.getFolder(SdkConstants.FD_NATIVE_LIBS);
- if (libsFolder.exists()) {
- try {
- IResource[] members = libsFolder.members();
- for (IResource member : members) {
- if (member.getType() == IResource.FILE &&
- SdkConstants.EXT_JAR.equalsIgnoreCase(member.getFileExtension())) {
- IPath location = member.getLocation();
- if (location != null) {
- jarFiles.add(location.toFile());
- }
- }
- }
- } catch (CoreException e) {
- // can't get the list? ignore this folder.
- }
- }
- }
-
- /**
- * Process reference projects from the main projects to add indirect dependencies coming
- * from Java project.
- * @param project the main project
- * @param projects the project list to add to
- * @param jarFiles the jar list to add to.
- */
- private static void processReferencedProjects(IProject project,
- Set<IProject> projects, Set<File> jarFiles) {
- try {
- IProject[] refs = project.getReferencedProjects();
- for (IProject p : refs) {
- // ignore if it's an Android project, or if it's not a Java
- // Project
- if (p.hasNature(JavaCore.NATURE_ID)
- && p.hasNature(AdtConstants.NATURE_DEFAULT) == false) {
-
- // process this project's dependencies
- getDependencyListFromClasspath(p, projects, jarFiles, true /*includeJarFiles*/);
- }
- }
- } catch (CoreException e) {
- // can't get the referenced projects? ignore
- }
- }
-
- /**
- * Finds all the dependencies of a given project and add them to a project list and
- * a jar list.
- * Only classpath entries that are exported are added, and only Java project (not Android
- * project) are added.
- *
- * @param project the project to query
- * @param projects the referenced project list to add to
- * @param jarFiles the jar list to add to
- * @param includeJarFiles whether to include jar files or just projects. This is useful when
- * calling on an Android project (value should be <code>false</code>)
- */
- private static void getDependencyListFromClasspath(IProject project, Set<IProject> projects,
- Set<File> jarFiles, boolean includeJarFiles) {
- IJavaProject javaProject = JavaCore.create(project);
- IWorkspaceRoot wsRoot = ResourcesPlugin.getWorkspace().getRoot();
-
- // we could use IJavaProject.getResolvedClasspath directly, but we actually
- // want to see the containers themselves.
- IClasspathEntry[] classpaths = javaProject.readRawClasspath();
- if (classpaths != null) {
- for (IClasspathEntry e : classpaths) {
- // ignore entries that are not exported
- if (!e.getPath().toString().equals(CONTAINER_DEPENDENCIES) && e.isExported()) {
- processCPE(e, javaProject, wsRoot, projects, jarFiles, includeJarFiles);
- }
- }
- }
- }
-
- /**
- * Processes a {@link IClasspathEntry} and add it to one of the list if applicable.
- * @param entry the entry to process
- * @param javaProject the {@link IJavaProject} from which this entry came.
- * @param wsRoot the {@link IWorkspaceRoot}
- * @param projects the project list to add to
- * @param jarFiles the jar list to add to
- * @param includeJarFiles whether to include jar files or just projects. This is useful when
- * calling on an Android project (value should be <code>false</code>)
- */
- private static void processCPE(IClasspathEntry entry, IJavaProject javaProject,
- IWorkspaceRoot wsRoot,
- Set<IProject> projects, Set<File> jarFiles, boolean includeJarFiles) {
-
- // if this is a classpath variable reference, we resolve it.
- if (entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
- entry = JavaCore.getResolvedClasspathEntry(entry);
- }
-
- if (entry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
- IProject refProject = wsRoot.getProject(entry.getPath().lastSegment());
- try {
- // ignore if it's an Android project, or if it's not a Java Project
- if (refProject.hasNature(JavaCore.NATURE_ID) &&
- refProject.hasNature(AdtConstants.NATURE_DEFAULT) == false) {
- // add this project to the list
- projects.add(refProject);
-
- // also get the dependency from this project.
- getDependencyListFromClasspath(refProject, projects, jarFiles,
- true /*includeJarFiles*/);
- }
- } catch (CoreException exception) {
- // can't query the project nature? ignore
- }
- } else if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
- if (includeJarFiles) {
- handleClasspathLibrary(entry, wsRoot, jarFiles);
- }
- } else if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
- // get the container and its content
- try {
- IClasspathContainer container = JavaCore.getClasspathContainer(
- entry.getPath(), javaProject);
- // ignore the system and default_system types as they represent
- // libraries that are part of the runtime.
- if (container != null &&
- container.getKind() == IClasspathContainer.K_APPLICATION) {
- IClasspathEntry[] entries = container.getClasspathEntries();
- for (IClasspathEntry cpe : entries) {
- processCPE(cpe, javaProject, wsRoot, projects, jarFiles, includeJarFiles);
- }
- }
- } catch (JavaModelException jme) {
- // can't resolve the container? ignore it.
- AdtPlugin.log(jme, "Failed to resolve ClasspathContainer: %s", entry.getPath());
- }
- }
- }
-
- private static final class CPEFile extends File {
- private static final long serialVersionUID = 1L;
-
- private final IClasspathEntry mClasspathEntry;
-
- public CPEFile(String pathname, IClasspathEntry classpathEntry) {
- super(pathname);
- mClasspathEntry = classpathEntry;
- }
-
- public CPEFile(File file, IClasspathEntry classpathEntry) {
- super(file.getAbsolutePath());
- mClasspathEntry = classpathEntry;
- }
-
- public IClasspathEntry getClasspathEntry() {
- return mClasspathEntry;
- }
- }
-
- private static void handleClasspathLibrary(IClasspathEntry e, IWorkspaceRoot wsRoot,
- Set<File> jarFiles) {
- // get the IPath
- IPath path = e.getPath();
-
- IResource resource = wsRoot.findMember(path);
-
- if (SdkConstants.EXT_JAR.equalsIgnoreCase(path.getFileExtension())) {
- // case of a jar file (which could be relative to the workspace or a full path)
- if (resource != null && resource.exists() &&
- resource.getType() == IResource.FILE) {
- jarFiles.add(new CPEFile(resource.getLocation().toFile(), e));
- } else {
- // if the jar path doesn't match a workspace resource,
- // then we get an OSString and check if this links to a valid file.
- String osFullPath = path.toOSString();
-
- File f = new CPEFile(osFullPath, e);
- if (f.isFile()) {
- jarFiles.add(f);
- }
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/ProjectChooserHelper.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/ProjectChooserHelper.java
deleted file mode 100644
index 9de8ad06e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/ProjectChooserHelper.java
+++ /dev/null
@@ -1,304 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.project;
-
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper.IProjectFilter;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.jdt.core.IJavaModel;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.ui.JavaElementLabelProvider;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.dialogs.ElementListSelectionDialog;
-
-/**
- * Helper class to deal with displaying a project choosing dialog that lists only the
- * projects with the Android nature.
- */
-public class ProjectChooserHelper {
-
- private final Shell mParentShell;
- private final IProjectChooserFilter mFilter;
-
- /**
- * List of current android projects. Since the dialog is modal, we'll just get
- * the list once on-demand.
- */
- private IJavaProject[] mAndroidProjects;
-
- /**
- * Interface to filter out some project displayed by {@link ProjectChooserHelper}.
- *
- * @see IProjectFilter
- */
- public interface IProjectChooserFilter extends IProjectFilter {
- /**
- * Whether the Project Chooser can compute the project list once and cache the result.
- * </p>If false the project list is recomputed every time the dialog is opened.
- */
- boolean useCache();
- }
-
- /**
- * An implementation of {@link IProjectChooserFilter} that only displays non-library projects.
- */
- public final static class NonLibraryProjectOnlyFilter implements IProjectChooserFilter {
- @Override
- public boolean accept(IProject project) {
- ProjectState state = Sdk.getProjectState(project);
- if (state != null) {
- return state.isLibrary() == false;
- }
-
- return false;
- }
-
- @Override
- public boolean useCache() {
- return true;
- }
- }
-
- /**
- * An implementation of {@link IProjectChooserFilter} that only displays library projects.
- */
- public final static class LibraryProjectOnlyFilter implements IProjectChooserFilter {
- @Override
- public boolean accept(IProject project) {
- ProjectState state = Sdk.getProjectState(project);
- if (state != null ) {
- return state.isLibrary();
- }
-
- return false;
- }
-
- @Override
- public boolean useCache() {
- return true;
- }
- }
-
- /**
- * Creates a new project chooser.
- * @param parentShell the parent {@link Shell} for the dialog.
- * @param filter a filter to only accept certain projects. Can be null.
- */
- public ProjectChooserHelper(Shell parentShell, IProjectChooserFilter filter) {
- mParentShell = parentShell;
- mFilter = filter;
- }
-
- /**
- * Displays a project chooser dialog which lists all available projects with the Android nature.
- * <p/>
- * The list of project is built from Android flagged projects currently opened in the workspace.
- *
- * @param projectName If non null and not empty, represents the name of an Android project
- * that will be selected by default.
- * @param message Message for the dialog box. Can be null in which case a default message
- * is displayed.
- * @return the project chosen by the user in the dialog, or null if the dialog was canceled.
- */
- public IJavaProject chooseJavaProject(String projectName, String message) {
- ILabelProvider labelProvider = new JavaElementLabelProvider(
- JavaElementLabelProvider.SHOW_DEFAULT);
- ElementListSelectionDialog dialog = new ElementListSelectionDialog(
- mParentShell, labelProvider);
- dialog.setTitle("Project Selection");
- if (message == null) {
- message = "Please select a project";
- }
- dialog.setMessage(message);
-
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
- IJavaModel javaModel = JavaCore.create(workspaceRoot);
-
- // set the elements in the dialog. These are opened android projects.
- dialog.setElements(getAndroidProjects(javaModel));
-
- // look for the project matching the given project name
- IJavaProject javaProject = null;
- if (projectName != null && projectName.length() > 0) {
- javaProject = javaModel.getJavaProject(projectName);
- }
-
- // if we found it, we set the initial selection in the dialog to this one.
- if (javaProject != null) {
- dialog.setInitialSelections(new Object[] { javaProject });
- }
-
- // open the dialog and return the object selected if OK was clicked, or null otherwise
- if (dialog.open() == Window.OK) {
- return (IJavaProject) dialog.getFirstResult();
- }
- return null;
- }
-
- /**
- * Returns the list of Android projects.
- * <p/>
- * Because this list can be time consuming, this class caches the list of project.
- * It is recommended to call this method instead of
- * {@link BaseProjectHelper#getAndroidProjects()}.
- *
- * @param javaModel the java model. Can be null.
- */
- public IJavaProject[] getAndroidProjects(IJavaModel javaModel) {
- // recompute only if we don't have the projects already or the filter is dynamic
- // and prevent usage of a cache.
- if (mAndroidProjects == null || (mFilter != null && mFilter.useCache() == false)) {
- if (javaModel == null) {
- mAndroidProjects = BaseProjectHelper.getAndroidProjects(mFilter);
- } else {
- mAndroidProjects = BaseProjectHelper.getAndroidProjects(javaModel, mFilter);
- }
- }
-
- return mAndroidProjects;
- }
-
- /**
- * Helper method to get the Android project with the given name
- *
- * @param projectName the name of the project to find
- * @return the {@link IProject} for the Android project. <code>null</code> if not found.
- */
- public IProject getAndroidProject(String projectName) {
- IProject iproject = null;
- IJavaProject[] javaProjects = getAndroidProjects(null);
- if (javaProjects != null) {
- for (IJavaProject javaProject : javaProjects) {
- if (javaProject.getElementName().equals(projectName)) {
- iproject = javaProject.getProject();
- break;
- }
- }
- }
- return iproject;
- }
-
- /**
- * A selector combo for showing the currently selected project and for
- * changing the selection
- */
- public static class ProjectCombo extends Combo implements SelectionListener {
- /** Currently chosen project, or null when no project has been initialized or selected */
- private IProject mProject;
- private IJavaProject[] mAvailableProjects;
-
- /**
- * Creates a new project selector combo
- *
- * @param helper associated {@link ProjectChooserHelper} for looking up
- * projects
- * @param parent parent composite to add the combo to
- * @param initialProject the initial project to select, or null (which
- * will show a "Please Choose Project..." label instead.)
- */
- public ProjectCombo(ProjectChooserHelper helper, Composite parent,
- IProject initialProject) {
- super(parent, SWT.BORDER | SWT.FLAT | SWT.READ_ONLY);
- mProject = initialProject;
-
- mAvailableProjects = helper.getAndroidProjects(null);
- String[] items = new String[mAvailableProjects.length + 1];
- items[0] = "--- Choose Project ---";
-
- ILabelProvider labelProvider = new JavaElementLabelProvider(
- JavaElementLabelProvider.SHOW_DEFAULT);
- int selectionIndex = 0;
- for (int i = 0, n = mAvailableProjects.length; i < n; i++) {
- IProject project = mAvailableProjects[i].getProject();
- items[i + 1] = labelProvider.getText(project);
- if (project == initialProject) {
- selectionIndex = i + 1;
- }
- }
- setItems(items);
- select(selectionIndex);
-
- addSelectionListener(this);
- }
-
- /**
- * Returns the project selected by this chooser (or the initial project
- * passed to the constructor if the user did not change it)
- *
- * @return the selected project
- */
- public IProject getSelectedProject() {
- return mProject;
- }
-
- /**
- * Sets the project selected by this chooser
- *
- * @param project the selected project
- */
- public void setSelectedProject(IProject project) {
- mProject = project;
-
- int selectionIndex = 0;
- for (int i = 0, n = mAvailableProjects.length; i < n; i++) {
- if (project == mAvailableProjects[i].getProject()) {
- selectionIndex = i + 1; // +1: Slot 0 is reserved for "Choose Project"
- select(selectionIndex);
- break;
- }
- }
- }
-
- /**
- * Click handler for the button: Open the {@link ProjectChooserHelper}
- * dialog for selecting a new project.
- */
- @Override
- public void widgetSelected(SelectionEvent e) {
- int selectionIndex = getSelectionIndex();
- if (selectionIndex > 0 && mAvailableProjects != null
- && selectionIndex <= mAvailableProjects.length) {
- // selection index 0 is "Choose Project", all other projects are offset
- // by 1 from the selection index
- mProject = mAvailableProjects[selectionIndex - 1].getProject();
- } else {
- mProject = null;
- }
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
-
- @Override
- protected void checkSubclass() {
- // Disable the check that prevents subclassing of SWT components
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/ProjectHelper.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/ProjectHelper.java
deleted file mode 100644
index a32b4ca8b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/ProjectHelper.java
+++ /dev/null
@@ -1,1153 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.project;
-
-import static com.android.ide.eclipse.adt.AdtConstants.COMPILER_COMPLIANCE_PREFERRED;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.ide.common.xml.ManifestData;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.build.builders.PostCompilerBuilder;
-import com.android.ide.eclipse.adt.internal.build.builders.PreCompilerBuilder;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.sdklib.BuildToolInfo;
-import com.android.sdklib.IAndroidTarget;
-import com.android.utils.Pair;
-
-import org.eclipse.core.resources.ICommand;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IProjectDescription;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.IncrementalProjectBuilder;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.QualifiedName;
-import org.eclipse.jdt.core.IClasspathEntry;
-import org.eclipse.jdt.core.IJavaModel;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
-import org.eclipse.jdt.launching.IVMInstall;
-import org.eclipse.jdt.launching.IVMInstall2;
-import org.eclipse.jdt.launching.IVMInstallType;
-import org.eclipse.jdt.launching.JavaRuntime;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.TreeMap;
-
-/**
- * Utility class to manipulate Project parameters/properties.
- */
-public final class ProjectHelper {
- public final static int COMPILER_COMPLIANCE_OK = 0;
- public final static int COMPILER_COMPLIANCE_LEVEL = 1;
- public final static int COMPILER_COMPLIANCE_SOURCE = 2;
- public final static int COMPILER_COMPLIANCE_CODEGEN_TARGET = 3;
-
- /**
- * Adds the given ClasspathEntry object to the class path entries.
- * This method does not check whether the entry is already defined in the project.
- *
- * @param entries The class path entries to read. A copy will be returned.
- * @param newEntry The new class path entry to add.
- * @return A new class path entries array.
- */
- public static IClasspathEntry[] addEntryToClasspath(
- IClasspathEntry[] entries, IClasspathEntry newEntry) {
- int n = entries.length;
- IClasspathEntry[] newEntries = new IClasspathEntry[n + 1];
- System.arraycopy(entries, 0, newEntries, 0, n);
- newEntries[n] = newEntry;
- return newEntries;
- }
-
- /**
- * Replaces the given ClasspathEntry in the classpath entries.
- *
- * If the classpath does not yet exists (Check is based on entry path), then it is added.
- *
- * @param entries The class path entries to read. The same array (replace) or a copy (add)
- * will be returned.
- * @param newEntry The new class path entry to add.
- * @return The same array (replace) or a copy (add) will be returned.
- *
- * @see IClasspathEntry#getPath()
- */
- public static IClasspathEntry[] replaceEntryInClasspath(
- IClasspathEntry[] entries, IClasspathEntry newEntry) {
-
- IPath path = newEntry.getPath();
- for (int i = 0, count = entries.length; i < count ; i++) {
- if (path.equals(entries[i].getPath())) {
- entries[i] = newEntry;
- return entries;
- }
- }
-
- return addEntryToClasspath(entries, newEntry);
- }
-
- /**
- * Adds the corresponding source folder to the project's class path entries.
- * This method does not check whether the entry is already defined in the project.
- *
- * @param javaProject The java project of which path entries to update.
- * @param newEntry The new class path entry to add.
- * @throws JavaModelException
- */
- public static void addEntryToClasspath(IJavaProject javaProject, IClasspathEntry newEntry)
- throws JavaModelException {
-
- IClasspathEntry[] entries = javaProject.getRawClasspath();
- entries = addEntryToClasspath(entries, newEntry);
- javaProject.setRawClasspath(entries, new NullProgressMonitor());
- }
-
- /**
- * Checks whether the given class path entry is already defined in the project.
- *
- * @param javaProject The java project of which path entries to check.
- * @param newEntry The parent source folder to remove.
- * @return True if the class path entry is already defined.
- * @throws JavaModelException
- */
- public static boolean isEntryInClasspath(IJavaProject javaProject, IClasspathEntry newEntry)
- throws JavaModelException {
-
- IClasspathEntry[] entries = javaProject.getRawClasspath();
- for (IClasspathEntry entry : entries) {
- if (entry.equals(newEntry)) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Remove a classpath entry from the array.
- * @param entries The class path entries to read. A copy will be returned
- * @param index The index to remove.
- * @return A new class path entries array.
- */
- public static IClasspathEntry[] removeEntryFromClasspath(
- IClasspathEntry[] entries, int index) {
- int n = entries.length;
- IClasspathEntry[] newEntries = new IClasspathEntry[n-1];
-
- // copy the entries before index
- System.arraycopy(entries, 0, newEntries, 0, index);
-
- // copy the entries after index
- System.arraycopy(entries, index + 1, newEntries, index,
- entries.length - index - 1);
-
- return newEntries;
- }
-
- /**
- * Converts a OS specific path into a path valid for the java doc location
- * attributes of a project.
- * @param javaDocOSLocation The OS specific path.
- * @return a valid path for the java doc location.
- */
- public static String getJavaDocPath(String javaDocOSLocation) {
- // first thing we do is convert the \ into /
- String javaDoc = javaDocOSLocation.replaceAll("\\\\", //$NON-NLS-1$
- AdtConstants.WS_SEP);
-
- // then we add file: at the beginning for unix path, and file:/ for non
- // unix path
- if (javaDoc.startsWith(AdtConstants.WS_SEP)) {
- return "file:" + javaDoc; //$NON-NLS-1$
- }
-
- return "file:/" + javaDoc; //$NON-NLS-1$
- }
-
- /**
- * Look for a specific classpath entry by full path and return its index.
- * @param entries The entry array to search in.
- * @param entryPath The OS specific path of the entry.
- * @param entryKind The kind of the entry. Accepted values are 0
- * (no filter), IClasspathEntry.CPE_LIBRARY, IClasspathEntry.CPE_PROJECT,
- * IClasspathEntry.CPE_SOURCE, IClasspathEntry.CPE_VARIABLE,
- * and IClasspathEntry.CPE_CONTAINER
- * @return the index of the found classpath entry or -1.
- */
- public static int findClasspathEntryByPath(IClasspathEntry[] entries,
- String entryPath, int entryKind) {
- for (int i = 0 ; i < entries.length ; i++) {
- IClasspathEntry entry = entries[i];
-
- int kind = entry.getEntryKind();
-
- if (kind == entryKind || entryKind == 0) {
- // get the path
- IPath path = entry.getPath();
-
- String osPathString = path.toOSString();
- if (osPathString.equals(entryPath)) {
- return i;
- }
- }
- }
-
- // not found, return bad index.
- return -1;
- }
-
- /**
- * Look for a specific classpath entry for file name only and return its
- * index.
- * @param entries The entry array to search in.
- * @param entryName The filename of the entry.
- * @param entryKind The kind of the entry. Accepted values are 0
- * (no filter), IClasspathEntry.CPE_LIBRARY, IClasspathEntry.CPE_PROJECT,
- * IClasspathEntry.CPE_SOURCE, IClasspathEntry.CPE_VARIABLE,
- * and IClasspathEntry.CPE_CONTAINER
- * @param startIndex Index where to start the search
- * @return the index of the found classpath entry or -1.
- */
- public static int findClasspathEntryByName(IClasspathEntry[] entries,
- String entryName, int entryKind, int startIndex) {
- if (startIndex < 0) {
- startIndex = 0;
- }
- for (int i = startIndex ; i < entries.length ; i++) {
- IClasspathEntry entry = entries[i];
-
- int kind = entry.getEntryKind();
-
- if (kind == entryKind || entryKind == 0) {
- // get the path
- IPath path = entry.getPath();
- String name = path.segment(path.segmentCount()-1);
-
- if (name.equals(entryName)) {
- return i;
- }
- }
- }
-
- // not found, return bad index.
- return -1;
- }
-
- public static boolean updateProject(IJavaProject project) {
- return updateProjects(new IJavaProject[] { project});
- }
-
- /**
- * Update the android-specific projects's classpath containers.
- * @param projects the projects to update
- * @return
- */
- public static boolean updateProjects(IJavaProject[] projects) {
- boolean r = AndroidClasspathContainerInitializer.updateProjects(projects);
- if (r) {
- return LibraryClasspathContainerInitializer.updateProjects(projects);
- }
- return false;
- }
-
- /**
- * Fix the project. This checks the SDK location.
- * @param project The project to fix.
- * @throws JavaModelException
- */
- public static void fixProject(IProject project) throws JavaModelException {
- if (AdtPlugin.getOsSdkFolder().length() == 0) {
- AdtPlugin.printToConsole(project, "Unknown SDK Location, project not fixed.");
- return;
- }
-
- // get a java project
- IJavaProject javaProject = JavaCore.create(project);
- fixProjectClasspathEntries(javaProject);
- }
-
- /**
- * Fix the project classpath entries. The method ensures that:
- * <ul>
- * <li>The project does not reference any old android.zip/android.jar archive.</li>
- * <li>The project does not use its output folder as a sourc folder.</li>
- * <li>The project does not reference a desktop JRE</li>
- * <li>The project references the AndroidClasspathContainer.
- * </ul>
- * @param javaProject The project to fix.
- * @throws JavaModelException
- */
- public static void fixProjectClasspathEntries(IJavaProject javaProject)
- throws JavaModelException {
-
- // get the project classpath
- IClasspathEntry[] entries = javaProject.getRawClasspath();
- IClasspathEntry[] oldEntries = entries;
- boolean forceRewriteOfCPE = false;
-
- // check if the JRE is set as library
- int jreIndex = ProjectHelper.findClasspathEntryByPath(entries, JavaRuntime.JRE_CONTAINER,
- IClasspathEntry.CPE_CONTAINER);
- if (jreIndex != -1) {
- // the project has a JRE included, we remove it
- entries = ProjectHelper.removeEntryFromClasspath(entries, jreIndex);
- }
-
- // get the output folder
- IPath outputFolder = javaProject.getOutputLocation();
-
- boolean foundFrameworkContainer = false;
- IClasspathEntry foundLibrariesContainer = null;
- IClasspathEntry foundDependenciesContainer = null;
-
- for (int i = 0 ; i < entries.length ;) {
- // get the entry and kind
- IClasspathEntry entry = entries[i];
- int kind = entry.getEntryKind();
-
- if (kind == IClasspathEntry.CPE_SOURCE) {
- IPath path = entry.getPath();
-
- if (path.equals(outputFolder)) {
- entries = ProjectHelper.removeEntryFromClasspath(entries, i);
-
- // continue, to skip the i++;
- continue;
- }
- } else if (kind == IClasspathEntry.CPE_CONTAINER) {
- String path = entry.getPath().toString();
- if (AdtConstants.CONTAINER_FRAMEWORK.equals(path)) {
- foundFrameworkContainer = true;
- } else if (AdtConstants.CONTAINER_PRIVATE_LIBRARIES.equals(path)) {
- foundLibrariesContainer = entry;
- } else if (AdtConstants.CONTAINER_DEPENDENCIES.equals(path)) {
- foundDependenciesContainer = entry;
- }
- }
-
- i++;
- }
-
- // look to see if we have the m2eclipse nature
- boolean m2eNature = false;
- try {
- m2eNature = javaProject.getProject().hasNature("org.eclipse.m2e.core.maven2Nature");
- } catch (CoreException e) {
- AdtPlugin.log(e, "Failed to query project %s for m2e nature",
- javaProject.getProject().getName());
- }
-
-
- // if the framework container is not there, we add it
- if (!foundFrameworkContainer) {
- // add the android container to the array
- entries = ProjectHelper.addEntryToClasspath(entries,
- JavaCore.newContainerEntry(new Path(AdtConstants.CONTAINER_FRAMEWORK)));
- }
-
- // same thing for the library container
- if (foundLibrariesContainer == null) {
- // add the exported libraries android container to the array
- entries = ProjectHelper.addEntryToClasspath(entries,
- JavaCore.newContainerEntry(
- new Path(AdtConstants.CONTAINER_PRIVATE_LIBRARIES), true));
- } else if (!m2eNature && !foundLibrariesContainer.isExported()) {
- // the container is present but it's not exported and since there's no m2e nature
- // we do want it to be exported.
- // keep all the other parameters the same.
- entries = ProjectHelper.replaceEntryInClasspath(entries,
- JavaCore.newContainerEntry(
- new Path(AdtConstants.CONTAINER_PRIVATE_LIBRARIES),
- foundLibrariesContainer.getAccessRules(),
- foundLibrariesContainer.getExtraAttributes(),
- true));
- forceRewriteOfCPE = true;
- }
-
- // same thing for the dependencies container
- if (foundDependenciesContainer == null) {
- // add the android dependencies container to the array
- entries = ProjectHelper.addEntryToClasspath(entries,
- JavaCore.newContainerEntry(
- new Path(AdtConstants.CONTAINER_DEPENDENCIES), true));
- } else if (!m2eNature && !foundDependenciesContainer.isExported()) {
- // the container is present but it's not exported and since there's no m2e nature
- // we do want it to be exported.
- // keep all the other parameters the same.
- entries = ProjectHelper.replaceEntryInClasspath(entries,
- JavaCore.newContainerEntry(
- new Path(AdtConstants.CONTAINER_DEPENDENCIES),
- foundDependenciesContainer.getAccessRules(),
- foundDependenciesContainer.getExtraAttributes(),
- true));
- forceRewriteOfCPE = true;
- }
-
- // set the new list of entries to the project
- if (entries != oldEntries || forceRewriteOfCPE) {
- javaProject.setRawClasspath(entries, new NullProgressMonitor());
- }
-
- // If needed, check and fix compiler compliance and source compatibility
- ProjectHelper.checkAndFixCompilerCompliance(javaProject);
- }
-
-
- /**
- * Checks the project compiler compliance level is supported.
- * @param javaProject The project to check
- * @return A pair with the first integer being an error code, and the second value
- * being the invalid value found or null. The error code can be: <ul>
- * <li><code>COMPILER_COMPLIANCE_OK</code> if the project is properly configured</li>
- * <li><code>COMPILER_COMPLIANCE_LEVEL</code> for unsupported compiler level</li>
- * <li><code>COMPILER_COMPLIANCE_SOURCE</code> for unsupported source compatibility</li>
- * <li><code>COMPILER_COMPLIANCE_CODEGEN_TARGET</code> for unsupported .class format</li>
- * </ul>
- */
- public static final Pair<Integer, String> checkCompilerCompliance(IJavaProject javaProject) {
- // get the project compliance level option
- String compliance = javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);
-
- // check it against a list of valid compliance level strings.
- if (!checkCompliance(javaProject, compliance)) {
- // if we didn't find the proper compliance level, we return an error
- return Pair.of(COMPILER_COMPLIANCE_LEVEL, compliance);
- }
-
- // otherwise we check source compatibility
- String source = javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
-
- // check it against a list of valid compliance level strings.
- if (!checkCompliance(javaProject, source)) {
- // if we didn't find the proper compliance level, we return an error
- return Pair.of(COMPILER_COMPLIANCE_SOURCE, source);
- }
-
- // otherwise check codegen level
- String codeGen = javaProject.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, true);
-
- // check it against a list of valid compliance level strings.
- if (!checkCompliance(javaProject, codeGen)) {
- // if we didn't find the proper compliance level, we return an error
- return Pair.of(COMPILER_COMPLIANCE_CODEGEN_TARGET, codeGen);
- }
-
- return Pair.of(COMPILER_COMPLIANCE_OK, null);
- }
-
- /**
- * Checks the project compiler compliance level is supported.
- * @param project The project to check
- * @return A pair with the first integer being an error code, and the second value
- * being the invalid value found or null. The error code can be: <ul>
- * <li><code>COMPILER_COMPLIANCE_OK</code> if the project is properly configured</li>
- * <li><code>COMPILER_COMPLIANCE_LEVEL</code> for unsupported compiler level</li>
- * <li><code>COMPILER_COMPLIANCE_SOURCE</code> for unsupported source compatibility</li>
- * <li><code>COMPILER_COMPLIANCE_CODEGEN_TARGET</code> for unsupported .class format</li>
- * </ul>
- */
- public static final Pair<Integer, String> checkCompilerCompliance(IProject project) {
- // get the java project from the IProject resource object
- IJavaProject javaProject = JavaCore.create(project);
-
- // check and return the result.
- return checkCompilerCompliance(javaProject);
- }
-
-
- /**
- * Checks, and fixes if needed, the compiler compliance level, and the source compatibility
- * level
- * @param project The project to check and fix.
- */
- public static final void checkAndFixCompilerCompliance(IProject project) {
- // FIXME This method is never used. Shall we just removed it?
- // {@link #checkAndFixCompilerCompliance(IJavaProject)} is used instead.
-
- // get the java project from the IProject resource object
- IJavaProject javaProject = JavaCore.create(project);
-
- // Now we check the compiler compliance level and make sure it is valid
- checkAndFixCompilerCompliance(javaProject);
- }
-
- /**
- * Checks, and fixes if needed, the compiler compliance level, and the source compatibility
- * level
- * @param javaProject The Java project to check and fix.
- */
- public static final void checkAndFixCompilerCompliance(IJavaProject javaProject) {
- Pair<Integer, String> result = checkCompilerCompliance(javaProject);
- if (result.getFirst().intValue() != COMPILER_COMPLIANCE_OK) {
- // setup the preferred compiler compliance level.
- javaProject.setOption(JavaCore.COMPILER_COMPLIANCE,
- AdtConstants.COMPILER_COMPLIANCE_PREFERRED);
- javaProject.setOption(JavaCore.COMPILER_SOURCE,
- AdtConstants.COMPILER_COMPLIANCE_PREFERRED);
- javaProject.setOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM,
- AdtConstants.COMPILER_COMPLIANCE_PREFERRED);
-
- // clean the project to make sure we recompile
- try {
- javaProject.getProject().build(IncrementalProjectBuilder.CLEAN_BUILD,
- new NullProgressMonitor());
- } catch (CoreException e) {
- AdtPlugin.printErrorToConsole(javaProject.getProject(),
- "Project compiler settings changed. Clean your project.");
- }
- }
- }
-
- /**
- * Makes the given project use JDK 6 (or more specifically,
- * {@link AdtConstants#COMPILER_COMPLIANCE_PREFERRED} as the compilation
- * target, regardless of what the default IDE JDK level is, provided a JRE
- * of the given level is installed.
- *
- * @param javaProject the Java project
- * @throws CoreException if the IDE throws an exception setting the compiler
- * level
- */
- @SuppressWarnings("restriction") // JDT API for setting compliance options
- public static void enforcePreferredCompilerCompliance(@NonNull IJavaProject javaProject)
- throws CoreException {
- String compliance = javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true);
- if (compliance == null ||
- JavaModelUtil.isVersionLessThan(compliance, COMPILER_COMPLIANCE_PREFERRED)) {
- IVMInstallType[] types = JavaRuntime.getVMInstallTypes();
- for (int i = 0; i < types.length; i++) {
- IVMInstallType type = types[i];
- IVMInstall[] installs = type.getVMInstalls();
- for (int j = 0; j < installs.length; j++) {
- IVMInstall install = installs[j];
- if (install instanceof IVMInstall2) {
- IVMInstall2 install2 = (IVMInstall2) install;
- // Java version can be 1.6.0, and preferred is 1.6
- if (install2.getJavaVersion().startsWith(COMPILER_COMPLIANCE_PREFERRED)) {
- Map<String, String> options = javaProject.getOptions(false);
- JavaCore.setComplianceOptions(COMPILER_COMPLIANCE_PREFERRED, options);
- JavaModelUtil.setDefaultClassfileOptions(options,
- COMPILER_COMPLIANCE_PREFERRED);
- javaProject.setOptions(options);
- return;
- }
- }
- }
- }
- }
- }
-
- /**
- * Returns a {@link IProject} by its running application name, as it returned by the AVD.
- * <p/>
- * <var>applicationName</var> will in most case be the package declared in the manifest, but
- * can, in some cases, be a custom process name declared in the manifest, in the
- * <code>application</code>, <code>activity</code>, <code>receiver</code>, or
- * <code>service</code> nodes.
- * @param applicationName The application name.
- * @return a project or <code>null</code> if no matching project were found.
- */
- public static IProject findAndroidProjectByAppName(String applicationName) {
- // Get the list of project for the current workspace
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IProject[] projects = workspace.getRoot().getProjects();
-
- // look for a project that matches the packageName of the app
- // we're trying to debug
- for (IProject p : projects) {
- if (p.isOpen()) {
- try {
- if (p.hasNature(AdtConstants.NATURE_DEFAULT) == false) {
- // ignore non android projects
- continue;
- }
- } catch (CoreException e) {
- // failed to get the nature? skip project.
- continue;
- }
-
- // check that there is indeed a manifest file.
- IFile manifestFile = getManifest(p);
- if (manifestFile == null) {
- // no file? skip this project.
- continue;
- }
-
- ManifestData data = AndroidManifestHelper.parseForData(manifestFile);
- if (data == null) {
- // skip this project.
- continue;
- }
-
- String manifestPackage = data.getPackage();
-
- if (manifestPackage != null && manifestPackage.equals(applicationName)) {
- // this is the project we were looking for!
- return p;
- } else {
- // if the package and application name don't match,
- // we look for other possible process names declared in the manifest.
- String[] processes = data.getProcesses();
- for (String process : processes) {
- if (process.equals(applicationName)) {
- return p;
- }
- }
- }
- }
- }
-
- return null;
-
- }
-
- public static void fixProjectNatureOrder(IProject project) throws CoreException {
- IProjectDescription description = project.getDescription();
- String[] natures = description.getNatureIds();
-
- // if the android nature is not the first one, we reorder them
- if (AdtConstants.NATURE_DEFAULT.equals(natures[0]) == false) {
- // look for the index
- for (int i = 0 ; i < natures.length ; i++) {
- if (AdtConstants.NATURE_DEFAULT.equals(natures[i])) {
- // if we try to just reorder the array in one pass, this doesn't do
- // anything. I guess JDT check that we are actually adding/removing nature.
- // So, first we'll remove the android nature, and then add it back.
-
- // remove the android nature
- removeNature(project, AdtConstants.NATURE_DEFAULT);
-
- // now add it back at the first index.
- description = project.getDescription();
- natures = description.getNatureIds();
-
- String[] newNatures = new String[natures.length + 1];
-
- // first one is android
- newNatures[0] = AdtConstants.NATURE_DEFAULT;
-
- // next the rest that was before the android nature
- System.arraycopy(natures, 0, newNatures, 1, natures.length);
-
- // set the new natures
- description.setNatureIds(newNatures);
- project.setDescription(description, null);
-
- // and stop
- break;
- }
- }
- }
- }
-
-
- /**
- * Removes a specific nature from a project.
- * @param project The project to remove the nature from.
- * @param nature The nature id to remove.
- * @throws CoreException
- */
- public static void removeNature(IProject project, String nature) throws CoreException {
- IProjectDescription description = project.getDescription();
- String[] natures = description.getNatureIds();
-
- // check if the project already has the android nature.
- for (int i = 0; i < natures.length; ++i) {
- if (nature.equals(natures[i])) {
- String[] newNatures = new String[natures.length - 1];
- if (i > 0) {
- System.arraycopy(natures, 0, newNatures, 0, i);
- }
- System.arraycopy(natures, i + 1, newNatures, i, natures.length - i - 1);
- description.setNatureIds(newNatures);
- project.setDescription(description, null);
-
- return;
- }
- }
-
- }
-
- /**
- * Returns if the project has error level markers.
- * @param includeReferencedProjects flag to also test the referenced projects.
- * @throws CoreException
- */
- public static boolean hasError(IProject project, boolean includeReferencedProjects)
- throws CoreException {
- IMarker[] markers = project.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE);
- if (markers != null && markers.length > 0) {
- // the project has marker(s). even though they are "problem" we
- // don't know their severity. so we loop on them and figure if they
- // are warnings or errors
- for (IMarker m : markers) {
- int s = m.getAttribute(IMarker.SEVERITY, -1);
- if (s == IMarker.SEVERITY_ERROR) {
- return true;
- }
- }
- }
-
- // test the referenced projects if needed.
- if (includeReferencedProjects) {
- List<IProject> projects = getReferencedProjects(project);
-
- for (IProject p : projects) {
- if (hasError(p, false)) {
- return true;
- }
- }
- }
-
- return false;
- }
-
- /**
- * Saves a String property into the persistent storage of a resource.
- * @param resource The resource into which the string value is saved.
- * @param propertyName the name of the property. The id of the plug-in is added to this string.
- * @param value the value to save
- * @return true if the save succeeded.
- */
- public static boolean saveStringProperty(IResource resource, String propertyName,
- String value) {
- QualifiedName qname = new QualifiedName(AdtPlugin.PLUGIN_ID, propertyName);
-
- try {
- resource.setPersistentProperty(qname, value);
- } catch (CoreException e) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Loads a String property from the persistent storage of a resource.
- * @param resource The resource from which the string value is loaded.
- * @param propertyName the name of the property. The id of the plug-in is added to this string.
- * @return the property value or null if it was not found.
- */
- public static String loadStringProperty(IResource resource, String propertyName) {
- QualifiedName qname = new QualifiedName(AdtPlugin.PLUGIN_ID, propertyName);
-
- try {
- String value = resource.getPersistentProperty(qname);
- return value;
- } catch (CoreException e) {
- return null;
- }
- }
-
- /**
- * Saves a property into the persistent storage of a resource.
- * @param resource The resource into which the boolean value is saved.
- * @param propertyName the name of the property. The id of the plug-in is added to this string.
- * @param value the value to save
- * @return true if the save succeeded.
- */
- public static boolean saveBooleanProperty(IResource resource, String propertyName,
- boolean value) {
- return saveStringProperty(resource, propertyName, Boolean.toString(value));
- }
-
- /**
- * Loads a boolean property from the persistent storage of a resource.
- * @param resource The resource from which the boolean value is loaded.
- * @param propertyName the name of the property. The id of the plug-in is added to this string.
- * @param defaultValue The default value to return if the property was not found.
- * @return the property value or the default value if the property was not found.
- */
- public static boolean loadBooleanProperty(IResource resource, String propertyName,
- boolean defaultValue) {
- String value = loadStringProperty(resource, propertyName);
- if (value != null) {
- return Boolean.parseBoolean(value);
- }
-
- return defaultValue;
- }
-
- public static Boolean loadBooleanProperty(IResource resource, String propertyName) {
- String value = loadStringProperty(resource, propertyName);
- if (value != null) {
- return Boolean.valueOf(value);
- }
-
- return null;
- }
-
- /**
- * Saves the path of a resource into the persistent storage of a resource.
- * @param resource The resource into which the resource path is saved.
- * @param propertyName the name of the property. The id of the plug-in is added to this string.
- * @param value The resource to save. It's its path that is actually stored. If null, an
- * empty string is stored.
- * @return true if the save succeeded
- */
- public static boolean saveResourceProperty(IResource resource, String propertyName,
- IResource value) {
- if (value != null) {
- IPath iPath = value.getFullPath();
- return saveStringProperty(resource, propertyName, iPath.toString());
- }
-
- return saveStringProperty(resource, propertyName, ""); //$NON-NLS-1$
- }
-
- /**
- * Loads the path of a resource from the persistent storage of a resource, and returns the
- * corresponding IResource object.
- * @param resource The resource from which the resource path is loaded.
- * @param propertyName the name of the property. The id of the plug-in is added to this string.
- * @return The corresponding IResource object (or children interface) or null
- */
- public static IResource loadResourceProperty(IResource resource, String propertyName) {
- String value = loadStringProperty(resource, propertyName);
-
- if (value != null && value.length() > 0) {
- return ResourcesPlugin.getWorkspace().getRoot().findMember(new Path(value));
- }
-
- return null;
- }
-
- /**
- * Returns the list of referenced project that are opened and Java projects.
- * @param project
- * @return a new list object containing the opened referenced java project.
- * @throws CoreException
- */
- public static List<IProject> getReferencedProjects(IProject project) throws CoreException {
- IProject[] projects = project.getReferencedProjects();
-
- ArrayList<IProject> list = new ArrayList<IProject>();
-
- for (IProject p : projects) {
- if (p.isOpen() && p.hasNature(JavaCore.NATURE_ID)) {
- list.add(p);
- }
- }
-
- return list;
- }
-
-
- /**
- * Checks a Java project compiler level option against a list of supported versions.
- * @param optionValue the Compiler level option.
- * @return true if the option value is supported.
- */
- private static boolean checkCompliance(@NonNull IJavaProject project, String optionValue) {
- for (String s : AdtConstants.COMPILER_COMPLIANCE) {
- if (s != null && s.equals(optionValue)) {
- return true;
- }
- }
-
- if (JavaCore.VERSION_1_7.equals(optionValue)) {
- // Requires API 19 and buildTools 19
- Sdk currentSdk = Sdk.getCurrent();
- if (currentSdk != null) {
- IProject p = project.getProject();
- IAndroidTarget target = currentSdk.getTarget(p);
- if (target == null || target.getVersion().getApiLevel() < 19) {
- return false;
- }
-
- ProjectState projectState = Sdk.getProjectState(p);
- if (projectState != null) {
- BuildToolInfo buildToolInfo = projectState.getBuildToolInfo();
- if (buildToolInfo == null) {
- buildToolInfo = currentSdk.getLatestBuildTool();
- }
- if (buildToolInfo == null || buildToolInfo.getRevision().getMajor() < 19) {
- return false;
- }
- }
-
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Returns the apk filename for the given project
- * @param project The project.
- * @param config An optional config name. Can be null.
- */
- public static String getApkFilename(IProject project, String config) {
- if (config != null) {
- return project.getName() + "-" + config + SdkConstants.DOT_ANDROID_PACKAGE; //$NON-NLS-1$
- }
-
- return project.getName() + SdkConstants.DOT_ANDROID_PACKAGE;
- }
-
- /**
- * Find the list of projects on which this JavaProject is dependent on at the compilation level.
- *
- * @param javaProject Java project that we are looking for the dependencies.
- * @return A list of Java projects for which javaProject depend on.
- * @throws JavaModelException
- */
- public static List<IJavaProject> getAndroidProjectDependencies(IJavaProject javaProject)
- throws JavaModelException {
- String[] requiredProjectNames = javaProject.getRequiredProjectNames();
-
- // Go from java project name to JavaProject name
- IJavaModel javaModel = javaProject.getJavaModel();
-
- // loop through all dependent projects and keep only those that are Android projects
- List<IJavaProject> projectList = new ArrayList<IJavaProject>(requiredProjectNames.length);
- for (String javaProjectName : requiredProjectNames) {
- IJavaProject androidJavaProject = javaModel.getJavaProject(javaProjectName);
-
- //Verify that the project has also the Android Nature
- try {
- if (!androidJavaProject.getProject().hasNature(AdtConstants.NATURE_DEFAULT)) {
- continue;
- }
- } catch (CoreException e) {
- continue;
- }
-
- projectList.add(androidJavaProject);
- }
-
- return projectList;
- }
-
- /**
- * Returns the android package file as an IFile object for the specified
- * project.
- * @param project The project
- * @return The android package as an IFile object or null if not found.
- */
- public static IFile getApplicationPackage(IProject project) {
- // get the output folder
- IFolder outputLocation = BaseProjectHelper.getAndroidOutputFolder(project);
-
- if (outputLocation == null) {
- AdtPlugin.printErrorToConsole(project,
- "Failed to get the output location of the project. Check build path properties"
- );
- return null;
- }
-
-
- // get the package path
- String packageName = project.getName() + SdkConstants.DOT_ANDROID_PACKAGE;
- IResource r = outputLocation.findMember(packageName);
-
- // check the package is present
- if (r instanceof IFile && r.exists()) {
- return (IFile)r;
- }
-
- String msg = String.format("Could not find %1$s!", packageName);
- AdtPlugin.printErrorToConsole(project, msg);
-
- return null;
- }
-
- /**
- * Returns an {@link IFile} object representing the manifest for the given project.
- *
- * @param project The project containing the manifest file.
- * @return An IFile object pointing to the manifest or null if the manifest
- * is missing.
- */
- public static IFile getManifest(IProject project) {
- IResource r = project.findMember(AdtConstants.WS_SEP
- + SdkConstants.FN_ANDROID_MANIFEST_XML);
-
- if (r == null || r.exists() == false || (r instanceof IFile) == false) {
- return null;
- }
- return (IFile) r;
- }
-
- /**
- * Does a full release build of the application, including the libraries. Do not build the
- * package.
- *
- * @param project The project to be built.
- * @param monitor A eclipse runtime progress monitor to be updated by the builders.
- * @throws CoreException
- */
- @SuppressWarnings("unchecked")
- public static void compileInReleaseMode(IProject project, IProgressMonitor monitor)
- throws CoreException {
- compileInReleaseMode(project, true /*includeDependencies*/, monitor);
- }
-
- /**
- * Does a full release build of the application, including the libraries. Do not build the
- * package.
- *
- * @param project The project to be built.
- * @param monitor A eclipse runtime progress monitor to be updated by the builders.
- * @throws CoreException
- */
- @SuppressWarnings("unchecked")
- private static void compileInReleaseMode(IProject project, boolean includeDependencies,
- IProgressMonitor monitor)
- throws CoreException {
-
- if (includeDependencies) {
- ProjectState projectState = Sdk.getProjectState(project);
-
- // this gives us all the library projects, direct and indirect dependencies,
- // so no need to run this method recursively.
- List<IProject> libraries = projectState.getFullLibraryProjects();
-
- // build dependencies in reverse order to prevent libraries being rebuilt
- // due to refresh of other libraries (they would be compiled in the wrong mode).
- for (int i = libraries.size() - 1 ; i >= 0 ; i--) {
- IProject lib = libraries.get(i);
- compileInReleaseMode(lib, false /*includeDependencies*/, monitor);
-
- // force refresh of the dependency.
- lib.refreshLocal(IResource.DEPTH_INFINITE, monitor);
- }
- }
-
- // do a full build on all the builders to guarantee that the builders are called.
- // (Eclipse does an optimization where builders are not called if there aren't any
- // deltas).
-
- ICommand[] commands = project.getDescription().getBuildSpec();
- for (ICommand command : commands) {
- String name = command.getBuilderName();
- if (PreCompilerBuilder.ID.equals(name)) {
- Map newArgs = new HashMap();
- newArgs.put(PreCompilerBuilder.RELEASE_REQUESTED, "");
- if (command.getArguments() != null) {
- newArgs.putAll(command.getArguments());
- }
-
- project.build(IncrementalProjectBuilder.FULL_BUILD,
- PreCompilerBuilder.ID, newArgs, monitor);
- } else if (PostCompilerBuilder.ID.equals(name)) {
- if (includeDependencies == false) {
- // this is a library, we need to build it!
- project.build(IncrementalProjectBuilder.FULL_BUILD, name,
- command.getArguments(), monitor);
- }
- } else {
-
- project.build(IncrementalProjectBuilder.FULL_BUILD, name,
- command.getArguments(), monitor);
- }
- }
- }
-
- /**
- * Force building the project and all its dependencies.
- *
- * @param project the project to build
- * @param kind the build kind
- * @param monitor
- * @throws CoreException
- */
- public static void buildWithDeps(IProject project, int kind, IProgressMonitor monitor)
- throws CoreException {
- // Get list of projects that we depend on
- ProjectState projectState = Sdk.getProjectState(project);
-
- // this gives us all the library projects, direct and indirect dependencies,
- // so no need to run this method recursively.
- List<IProject> libraries = projectState.getFullLibraryProjects();
-
- // build dependencies in reverse order to prevent libraries being rebuilt
- // due to refresh of other libraries (they would be compiled in the wrong mode).
- for (int i = libraries.size() - 1 ; i >= 0 ; i--) {
- IProject lib = libraries.get(i);
- lib.build(kind, monitor);
- lib.refreshLocal(IResource.DEPTH_INFINITE, monitor);
- }
-
- project.build(kind, monitor);
- }
-
-
- /**
- * Build project incrementally, including making the final packaging even if it is disabled
- * by default.
- *
- * @param project The project to be built.
- * @param monitor A eclipse runtime progress monitor to be updated by the builders.
- * @throws CoreException
- */
- public static void doFullIncrementalDebugBuild(IProject project, IProgressMonitor monitor)
- throws CoreException {
- // Get list of projects that we depend on
- List<IJavaProject> androidProjectList = new ArrayList<IJavaProject>();
- try {
- androidProjectList = getAndroidProjectDependencies(
- BaseProjectHelper.getJavaProject(project));
- } catch (JavaModelException e) {
- AdtPlugin.printErrorToConsole(project, e);
- }
- // Recursively build dependencies
- for (IJavaProject dependency : androidProjectList) {
- doFullIncrementalDebugBuild(dependency.getProject(), monitor);
- }
-
- // Do an incremental build to pick up all the deltas
- project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, monitor);
-
- // If the preferences indicate not to use post compiler optimization
- // then the incremental build will have done everything necessary, otherwise,
- // we have to run the final builder manually (if requested).
- if (AdtPrefs.getPrefs().getBuildSkipPostCompileOnFileSave()) {
- // Create the map to pass to the PostC builder
- Map<String, String> args = new TreeMap<String, String>();
- args.put(PostCompilerBuilder.POST_C_REQUESTED, ""); //$NON-NLS-1$
-
- // call the post compiler manually, forcing FULL_BUILD otherwise Eclipse won't
- // call the builder since the delta is empty.
- project.build(IncrementalProjectBuilder.FULL_BUILD,
- PostCompilerBuilder.ID, args, monitor);
- }
-
- // because the post compiler builder does a delayed refresh due to
- // library not picking the refresh up if it's done during the build,
- // we want to force a refresh here as this call is generally asking for
- // a build to use the apk right after the call.
- project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/SupportLibraryHelper.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/SupportLibraryHelper.java
deleted file mode 100644
index e1819b283..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/SupportLibraryHelper.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.project;
-
-import static com.android.SdkConstants.FQCN_GRID_LAYOUT;
-import static com.android.SdkConstants.FQCN_GRID_LAYOUT_V7;
-import static com.android.SdkConstants.FQCN_SPACE;
-import static com.android.SdkConstants.FQCN_SPACE_V7;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.actions.AddSupportJarAction;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState.LibraryState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.swt.widgets.Display;
-
-/**
- * Helper class for the Android Support Library. The support library provides
- * (for example) a backport of GridLayout, which must be used as a library
- * project rather than a jar library since it has resources. This class provides
- * support for finding the library project, or downloading and installing it on
- * demand if it does not, as well as translating tags such as
- * {@code <GridLayout>} into {@code <com.android.support.v7.GridLayout>} if it
- * does not.
- */
-public class SupportLibraryHelper {
- /**
- * Returns the correct tag to use for the given view tag. This is normally
- * the same as the tag itself. However, for some views which are not available
- * on all platforms, this will:
- * <ul>
- * <li> Check if the view is available in the compatibility library,
- * and if so, if the support library is not installed, will offer to
- * install it via the SDK manager.
- * <li> (The tool may also offer to adjust the minimum SDK of the project
- * up to a level such that the given tag is supported directly, and then
- * this method will return the original tag.)
- * <li> Check whether the compatibility library is included in the project, and
- * if not, offer to copy it into the workspace and add a library dependency.
- * <li> Return the alternative tag. For example, for "GridLayout", it will
- * (if the minimum SDK is less than 14) return "com.android.support.v7.GridLayout"
- * instead.
- * </ul>
- *
- * @param project the project to add the dependency into
- * @param tag the tag to look up, such as "GridLayout"
- * @return the tag to use in the layout, normally the same as the input tag but possibly
- * an equivalent compatibility library tag instead.
- */
- @NonNull
- public static String getTagFor(@NonNull IProject project, @NonNull String tag) {
- boolean isGridLayout = tag.equals(FQCN_GRID_LAYOUT);
- boolean isSpace = tag.equals(FQCN_SPACE);
- if (isGridLayout || isSpace) {
- int minSdk = ManifestInfo.get(project).getMinSdkVersion();
- if (minSdk < 14) {
- // See if the support library is installed in the SDK area
- // See if there is a local project in the workspace providing the
- // project
- IProject supportProject = getSupportProjectV7();
- if (supportProject != null) {
- // Make sure I have a dependency on it
- ProjectState state = Sdk.getProjectState(project);
- if (state != null) {
- for (LibraryState library : state.getLibraries()) {
- if (supportProject.equals(library.getProjectState().getProject())) {
- // Found it: you have the compatibility library and have linked
- // to it: use the alternative tag
- return isGridLayout ? FQCN_GRID_LAYOUT_V7 : FQCN_SPACE_V7;
- }
- }
- }
- }
-
- // Ask user to install it
- String message = String.format(
- "%1$s requires API level 14 or higher, or a compatibility "
- + "library for older versions.\n\n"
- + " Do you want to install the compatibility library?", tag);
- MessageDialog dialog =
- new MessageDialog(
- Display.getCurrent().getActiveShell(),
- "Warning",
- null,
- message,
- MessageDialog.QUESTION,
- new String[] {
- "Install", "Cancel"
- },
- 1 /* default button: Cancel */);
- int answer = dialog.open();
- if (answer == 0) {
- if (supportProject != null) {
- // Just add library dependency
- if (!AddSupportJarAction.addLibraryDependency(
- supportProject,
- project,
- true /* waitForFinish */)) {
- return tag;
- }
- } else {
- // Install library AND add dependency
- if (!AddSupportJarAction.installGridLayoutLibrary(
- project,
- true /* waitForFinish */)) {
- return tag;
- }
- }
-
- return isGridLayout ? FQCN_GRID_LAYOUT_V7 : FQCN_SPACE_V7;
- }
- }
- }
-
- return tag;
- }
-
- /** Cache for {@link #getSupportProjectV7()} */
- private static IProject sCachedProject;
-
- /**
- * Finds and returns the support project in the workspace, if any.
- *
- * @return the android support library project, or null if not found
- */
- @Nullable
- public static IProject getSupportProjectV7() {
- if (sCachedProject != null) {
- if (sCachedProject.isAccessible()) {
- return sCachedProject;
- } else {
- sCachedProject = null;
- }
- }
-
- sCachedProject = findSupportProjectV7();
- return sCachedProject;
- }
-
- @Nullable
- private static IProject findSupportProjectV7() {
- for (IJavaProject javaProject : AdtUtils.getOpenAndroidProjects()) {
- IProject project = javaProject.getProject();
- ProjectState state = Sdk.getProjectState(project);
- if (state != null && state.isLibrary()) {
- ManifestInfo manifestInfo = ManifestInfo.get(project);
- if (manifestInfo.getPackage().equals("android.support.v7.gridlayout")) { //$NON-NLS-1$
- return project;
- }
- }
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/XmlErrorHandler.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/XmlErrorHandler.java
deleted file mode 100644
index c496c7e57..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/XmlErrorHandler.java
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.project;
-
-import com.android.ide.common.xml.AndroidManifestParser.ManifestErrorHandler;
-import com.android.ide.eclipse.adt.AdtConstants;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jdt.core.IJavaProject;
-import org.xml.sax.Locator;
-import org.xml.sax.SAXException;
-import org.xml.sax.SAXParseException;
-import org.xml.sax.helpers.DefaultHandler;
-
-/**
- * XML error handler used by the parser to report errors/warnings.
- */
-public class XmlErrorHandler extends DefaultHandler implements ManifestErrorHandler {
-
- private final IJavaProject mJavaProject;
- /** file being parsed */
- private final IFile mFile;
- /** link to the delta visitor, to set the xml error flag */
- private final XmlErrorListener mErrorListener;
-
- /**
- * Classes which implement this interface provide a method that deals
- * with XML errors.
- */
- public interface XmlErrorListener {
- /**
- * Sent when an XML error is detected.
- */
- public void errorFound();
- }
-
- public static class BasicXmlErrorListener implements XmlErrorListener {
- public boolean mHasXmlError = false;
-
- @Override
- public void errorFound() {
- mHasXmlError = true;
- }
- }
-
- public XmlErrorHandler(IJavaProject javaProject, IFile file, XmlErrorListener errorListener) {
- mJavaProject = javaProject;
- mFile = file;
- mErrorListener = errorListener;
- }
-
- public XmlErrorHandler(IFile file, XmlErrorListener errorListener) {
- this(null, file, errorListener);
- }
-
- /**
- * Xml Error call back
- * @param exception the parsing exception
- * @throws SAXException
- */
- @Override
- public void error(SAXParseException exception) throws SAXException {
- handleError(exception, exception.getLineNumber());
- }
-
- /**
- * Xml Fatal Error call back
- * @param exception the parsing exception
- * @throws SAXException
- */
- @Override
- public void fatalError(SAXParseException exception) throws SAXException {
- handleError(exception, exception.getLineNumber());
- }
-
- /**
- * Xml Warning call back
- * @param exception the parsing exception
- * @throws SAXException
- */
- @Override
- public void warning(SAXParseException exception) throws SAXException {
- if (mFile != null) {
- BaseProjectHelper.markResource(mFile,
- AdtConstants.MARKER_XML,
- exception.getMessage(),
- exception.getLineNumber(),
- IMarker.SEVERITY_WARNING);
- }
- }
-
- protected final IFile getFile() {
- return mFile;
- }
-
- /**
- * Handles a parsing error and an optional line number.
- * @param exception
- * @param lineNumber
- */
- @Override
- public void handleError(Exception exception, int lineNumber) {
- if (mErrorListener != null) {
- mErrorListener.errorFound();
- }
-
- String message = exception.getMessage();
- if (message == null) {
- message = "Unknown error " + exception.getClass().getCanonicalName();
- }
-
- if (mFile != null) {
- BaseProjectHelper.markResource(mFile,
- AdtConstants.MARKER_XML,
- message,
- lineNumber,
- IMarker.SEVERITY_ERROR);
- }
- }
-
- /**
- * Checks that a class is valid and can be used in the Android Manifest.
- * <p/>
- * Errors are put as {@link IMarker} on the manifest file.
- * @param locator
- * @param className the fully qualified name of the class to test.
- * @param superClassName the fully qualified name of the class it is supposed to extend.
- * @param testVisibility if <code>true</code>, the method will check the visibility of
- * the class or of its constructors.
- */
- @Override
- public void checkClass(Locator locator, String className, String superClassName,
- boolean testVisibility) {
- if (mJavaProject == null) {
- return;
- }
- // we need to check the validity of the activity.
- String result = BaseProjectHelper.testClassForManifest(mJavaProject,
- className, superClassName, testVisibility);
- if (result != BaseProjectHelper.TEST_CLASS_OK) {
- // get the line number
- int line = locator.getLineNumber();
-
- // mark the file
- IMarker marker = BaseProjectHelper.markResource(getFile(),
- AdtConstants.MARKER_ANDROID, result, line, IMarker.SEVERITY_ERROR);
-
- // add custom attributes to be used by the manifest editor.
- if (marker != null) {
- try {
- marker.setAttribute(AdtConstants.MARKER_ATTR_TYPE,
- AdtConstants.MARKER_ATTR_TYPE_ACTIVITY);
- marker.setAttribute(AdtConstants.MARKER_ATTR_CLASS, className);
- } catch (CoreException e) {
- }
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/properties/AndroidPropertyPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/properties/AndroidPropertyPage.java
deleted file mode 100644
index 6e0e9be5b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/properties/AndroidPropertyPage.java
+++ /dev/null
@@ -1,191 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.properties;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.internal.project.ProjectProperties;
-import com.android.sdklib.internal.project.ProjectPropertiesWorkingCopy;
-import com.android.sdkuilib.internal.widgets.SdkTargetSelector;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.ui.dialogs.PropertyPage;
-
-/**
- * Property page for "Android" project.
- * This is accessible from the Package Explorer when right clicking a project and choosing
- * "Properties".
- *
- */
-public class AndroidPropertyPage extends PropertyPage {
-
- private IProject mProject;
- private SdkTargetSelector mSelector;
- private Button mIsLibrary;
- // APK-SPLIT: This is not yet supported, so we hide the UI
-// private Button mSplitByDensity;
- private LibraryProperties mLibraryDependencies;
- private ProjectPropertiesWorkingCopy mPropertiesWorkingCopy;
-
- public AndroidPropertyPage() {
- // pass
- }
-
- @Override
- protected Control createContents(Composite parent) {
- // get the element (this is not yet valid in the constructor).
- mProject = (IProject)getElement();
-
- // get the targets from the sdk
- IAndroidTarget[] targets = null;
- if (Sdk.getCurrent() != null) {
- targets = Sdk.getCurrent().getTargets();
- }
-
- // build the UI.
- Composite top = new Composite(parent, SWT.NONE);
- top.setLayoutData(new GridData(GridData.FILL_BOTH));
- top.setLayout(new GridLayout(1, false));
-
- Group targetGroup = new Group(top, SWT.NONE);
- targetGroup.setLayoutData(new GridData(GridData.FILL_BOTH));
- targetGroup.setLayout(new GridLayout(1, false));
- targetGroup.setText("Project Build Target");
-
- mSelector = new SdkTargetSelector(targetGroup, targets);
-
- Group libraryGroup = new Group(top, SWT.NONE);
- libraryGroup.setLayoutData(new GridData(GridData.FILL_BOTH));
- libraryGroup.setLayout(new GridLayout(1, false));
- libraryGroup.setText("Library");
-
- mIsLibrary = new Button(libraryGroup, SWT.CHECK);
- mIsLibrary.setText("Is Library");
-
- mLibraryDependencies = new LibraryProperties(libraryGroup);
-
- // fill the ui
- fillUi();
-
- // add callbacks
- mSelector.setSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateValidity();
- }
- });
-
- if (mProject.isOpen() == false) {
- // disable the ui.
- }
-
- return top;
- }
-
- @Override
- public boolean performOk() {
- Sdk currentSdk = Sdk.getCurrent();
- if (currentSdk != null && mProject.isOpen()) {
- ProjectState state = Sdk.getProjectState(mProject);
-
- // simply update the properties copy. Eclipse will be notified of the file change
- // and will reload it smartly (detecting differences) and updating the ProjectState.
- // See Sdk.mFileListener
- boolean mustSaveProp = false;
-
- IAndroidTarget newTarget = mSelector.getSelected();
- if (state == null || newTarget != state.getTarget()) {
- mPropertiesWorkingCopy.setProperty(ProjectProperties.PROPERTY_TARGET,
- newTarget.hashString());
- mustSaveProp = true;
- }
-
- if (state == null || mIsLibrary.getSelection() != state.isLibrary()) {
- mPropertiesWorkingCopy.setProperty(ProjectProperties.PROPERTY_LIBRARY,
- Boolean.toString(mIsLibrary.getSelection()));
- mustSaveProp = true;
- }
-
- if (mLibraryDependencies.save()) {
- mustSaveProp = true;
- }
-
- if (mustSaveProp) {
- try {
- mPropertiesWorkingCopy.save();
-
- IResource projectProp = mProject.findMember(SdkConstants.FN_PROJECT_PROPERTIES);
- if (projectProp != null) {
- projectProp.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor());
- }
- } catch (Exception e) {
- String msg = String.format(
- "Failed to save %1$s for project %2$s",
- SdkConstants.FN_PROJECT_PROPERTIES, mProject.getName());
- AdtPlugin.log(e, msg);
- }
- }
- }
-
- return true;
- }
-
- @Override
- protected void performDefaults() {
- fillUi();
- updateValidity();
- }
-
- private void fillUi() {
- if (Sdk.getCurrent() != null && mProject.isOpen()) {
- ProjectState state = Sdk.getProjectState(mProject);
-
- // make a working copy of the properties
- mPropertiesWorkingCopy = state.getProperties().makeWorkingCopy();
-
- // get the target
- IAndroidTarget target = state.getTarget();
- if (target != null) {
- mSelector.setSelection(target);
- }
-
- mIsLibrary.setSelection(state.isLibrary());
- mLibraryDependencies.setContent(state, mPropertiesWorkingCopy);
- }
-
- }
-
- private void updateValidity() {
- // look for the selection and validate the page if there is a selection
- IAndroidTarget target = mSelector.getSelected();
- setValid(target != null);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/properties/LibraryProperties.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/properties/LibraryProperties.java
deleted file mode 100644
index a734b4168..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/properties/LibraryProperties.java
+++ /dev/null
@@ -1,374 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.properties;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.project.ProjectChooserHelper;
-import com.android.ide.eclipse.adt.internal.project.ProjectChooserHelper.IProjectChooserFilter;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState.LibraryState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.sdklib.internal.project.ProjectProperties;
-import com.android.sdklib.internal.project.ProjectPropertiesWorkingCopy;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ControlAdapter;
-import org.eclipse.swt.events.ControlEvent;
-import org.eclipse.swt.events.DisposeEvent;
-import org.eclipse.swt.events.DisposeListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.swt.widgets.TableItem;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-
-
-/**
- * Self-contained UI to edit the library dependencies of a Project.
- */
-final class LibraryProperties {
-
- private Composite mTop;
- private Table mTable;
- private Image mMatchIcon;
- private Image mErrorIcon;
- private Button mAddButton;
- private Button mRemoveButton;
- private Button mUpButton;
- private Button mDownButton;
- private ProjectChooserHelper mProjectChooser;
-
- /**
- * Original ProjectState being edited. This is read-only.
- * @see #mPropertiesWorkingCopy
- */
- private ProjectState mState;
- /**
- * read-write copy of the properties being edited.
- */
- private ProjectPropertiesWorkingCopy mPropertiesWorkingCopy;
-
- private final List<ItemData> mItemDataList = new ArrayList<ItemData>();
- private boolean mMustSave = false;
-
- /**
- * Internal struct to store library info in the table item.
- */
- private final static class ItemData {
- String relativePath;
- IProject project;
- }
-
- /**
- * {@link IProjectChooserFilter} implementation that dynamically ignores libraries
- * that are already dependencies.
- */
- IProjectChooserFilter mFilter = new IProjectChooserFilter() {
- @Override
- public boolean accept(IProject project) {
- // first check if it's a library
- ProjectState state = Sdk.getProjectState(project);
- if (state != null) {
- if (state.isLibrary() == false || project == mState.getProject()) {
- return false;
- }
-
- // then check if the library is not already part of the dependencies.
- for (ItemData data : mItemDataList) {
- if (data.project == project) {
- return false;
- }
- }
-
- return true;
- }
-
- return false;
- }
-
- @Override
- public boolean useCache() {
- return false;
- }
- };
-
- LibraryProperties(Composite parent) {
-
- mMatchIcon = AdtPlugin.getImageDescriptor("/icons/match.png").createImage(); //$NON-NLS-1$
- mErrorIcon = AdtPlugin.getImageDescriptor("/icons/error.png").createImage(); //$NON-NLS-1$
-
- // Layout has 2 column
- mTop = new Composite(parent, SWT.NONE);
- mTop.setLayout(new GridLayout(2, false));
- mTop.setLayoutData(new GridData(GridData.FILL_BOTH));
- mTop.setFont(parent.getFont());
- mTop.addDisposeListener(new DisposeListener() {
- @Override
- public void widgetDisposed(DisposeEvent e) {
- mMatchIcon.dispose();
- mErrorIcon.dispose();
- }
- });
-
- mTable = new Table(mTop, SWT.BORDER | SWT.FULL_SELECTION | SWT.SINGLE);
- mTable.setLayoutData(new GridData(GridData.FILL_BOTH));
- mTable.setHeaderVisible(true);
- mTable.setLinesVisible(false);
- mTable.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- resetEnabled();
- }
- });
-
- final TableColumn column0 = new TableColumn(mTable, SWT.NONE);
- column0.setText("Reference");
- final TableColumn column1 = new TableColumn(mTable, SWT.NONE);
- column1.setText("Project");
-
- Composite buttons = new Composite(mTop, SWT.NONE);
- buttons.setLayout(new GridLayout());
- buttons.setLayoutData(new GridData(GridData.FILL_VERTICAL));
-
- mProjectChooser = new ProjectChooserHelper(parent.getShell(), mFilter);
-
- mAddButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
- mAddButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mAddButton.setText("Add...");
- mAddButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- IJavaProject javaProject = mProjectChooser.chooseJavaProject(null /*projectName*/,
- "Please select a library project");
- if (javaProject != null) {
- IProject iProject = javaProject.getProject();
- IPath relativePath = iProject.getLocation().makeRelativeTo(
- mState.getProject().getLocation());
-
- addItem(relativePath.toString(), iProject, -1);
- resetEnabled();
- mMustSave = true;
- }
- }
- });
-
- mRemoveButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
- mRemoveButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mRemoveButton.setText("Remove");
- mRemoveButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- // selection is ensured and in single mode.
- TableItem selection = mTable.getSelection()[0];
- ItemData data = (ItemData) selection.getData();
- mItemDataList.remove(data);
- mTable.remove(mTable.getSelectionIndex());
- resetEnabled();
- mMustSave = true;
- }
- });
-
- Label l = new Label(buttons, SWT.SEPARATOR | SWT.HORIZONTAL);
- l.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- mUpButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
- mUpButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mUpButton.setText("Up");
- mUpButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- int index = mTable.getSelectionIndex();
- ItemData data = mItemDataList.remove(index);
- mTable.remove(index);
-
- // add at a lower index.
- addItem(data.relativePath, data.project, index - 1);
-
- // reset the selection
- mTable.select(index - 1);
- resetEnabled();
- mMustSave = true;
- }
- });
-
- mDownButton = new Button(buttons, SWT.PUSH | SWT.FLAT);
- mDownButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mDownButton.setText("Down");
- mDownButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- int index = mTable.getSelectionIndex();
- ItemData data = mItemDataList.remove(index);
- mTable.remove(index);
-
- // add at a higher index.
- addItem(data.relativePath, data.project, index + 1);
-
- // reset the selection
- mTable.select(index + 1);
- resetEnabled();
- mMustSave = true;
- }
- });
-
- adjustColumnsWidth(mTable, column0, column1);
- }
-
- /**
- * Sets or reset the content.
- * @param state the {@link ProjectState} to display. This is read-only.
- * @param propertiesWorkingCopy the working copy of {@link ProjectProperties} to modify.
- */
- void setContent(ProjectState state, ProjectPropertiesWorkingCopy propertiesWorkingCopy) {
- mState = state;
- mPropertiesWorkingCopy = propertiesWorkingCopy;
-
- // reset content
- mTable.removeAll();
- mItemDataList.clear();
-
- // get the libraries and make a copy of the data we need.
- List<LibraryState> libs = state.getLibraries();
-
- for (LibraryState lib : libs) {
- ProjectState libState = lib.getProjectState();
- addItem(lib.getRelativePath(), libState != null ? libState.getProject() : null, -1);
- }
-
- mMustSave = false;
-
- resetEnabled();
- }
-
- /**
- * Saves the state of the UI into the {@link ProjectProperties} object that was returned by
- * {@link #setContent}.
- * <p/>This does not update the {@link ProjectState} object that was provided, nor does it save
- * the new properties on disk. Saving the properties on disk, via
- * {@link ProjectPropertiesWorkingCopy#save()}, and updating the {@link ProjectState} instance,
- * via {@link ProjectState#reloadProperties()} must be done by the caller.
- * @return <code>true</code> if there was actually new data saved in the project state, false
- * otherwise.
- */
- boolean save() {
- boolean mustSave = mMustSave;
- if (mMustSave) {
- // remove all previous library dependencies.
- Set<String> keys = mPropertiesWorkingCopy.keySet();
- for (String key : keys) {
- if (key.startsWith(ProjectProperties.PROPERTY_LIB_REF)) {
- mPropertiesWorkingCopy.removeProperty(key);
- }
- }
-
- // now add the new libraries.
- int index = 1;
- for (ItemData data : mItemDataList) {
- mPropertiesWorkingCopy.setProperty(ProjectProperties.PROPERTY_LIB_REF + index++,
- data.relativePath);
- }
- }
-
- mMustSave = false;
- return mustSave;
- }
-
- /**
- * Enables or disables the whole widget.
- * @param enabled whether the widget must be enabled or not.
- */
- void setEnabled(boolean enabled) {
- if (enabled == false) {
- mTable.setEnabled(false);
- mAddButton.setEnabled(false);
- mRemoveButton.setEnabled(false);
- mUpButton.setEnabled(false);
- mDownButton.setEnabled(false);
- } else {
- mTable.setEnabled(true);
- mAddButton.setEnabled(true);
- resetEnabled();
- }
- }
-
- private void resetEnabled() {
- int index = mTable.getSelectionIndex();
- mRemoveButton.setEnabled(index != -1);
- mUpButton.setEnabled(index > 0);
- mDownButton.setEnabled(index != -1 && index < mTable.getItemCount() - 1);
- }
-
- /**
- * Adds a new item and stores a {@link Stuff} into {@link #mStuff}.
- *
- * @param relativePath the relative path of the library entry
- * @param project the associated IProject
- * @param index if different than -1, the index at which to insert the item.
- */
- private void addItem(String relativePath, IProject project, int index) {
- ItemData data = new ItemData();
- data.relativePath = relativePath;
- data.project = project;
- TableItem item;
- if (index == -1) {
- mItemDataList.add(data);
- item = new TableItem(mTable, SWT.NONE);
- } else {
- mItemDataList.add(index, data);
- item = new TableItem(mTable, SWT.NONE, index);
- }
- item.setData(data);
- item.setText(0, data.relativePath);
- item.setImage(data.project != null ? mMatchIcon : mErrorIcon);
- item.setText(1, data.project != null ? data.project.getName() : "?");
- }
-
- /**
- * Adds a listener to adjust the columns width when the parent is resized.
- * <p/>
- * If we need something more fancy, we might want to use this:
- * http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet77.java?view=co
- */
- private void adjustColumnsWidth(final Table table,
- final TableColumn column0,
- final TableColumn column1) {
- // Add a listener to resize the column to the full width of the table
- table.addControlListener(new ControlAdapter() {
- @Override
- public void controlResized(ControlEvent e) {
- Rectangle r = table.getClientArea();
- column0.setWidth(r.width * 50 / 100); // 50%
- column1.setWidth(r.width * 50 / 100); // 50%
- }
- });
- }
-}
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/AndroidPackageRenameParticipant.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/AndroidPackageRenameParticipant.java
deleted file mode 100644
index b821777a5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/AndroidPackageRenameParticipant.java
+++ /dev/null
@@ -1,547 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.refactorings.core;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_CLASS;
-import static com.android.SdkConstants.ATTR_CONTEXT;
-import static com.android.SdkConstants.ATTR_NAME;
-import static com.android.SdkConstants.ATTR_PACKAGE;
-import static com.android.SdkConstants.DOT_XML;
-import static com.android.SdkConstants.EXT_XML;
-import static com.android.SdkConstants.TOOLS_URI;
-import static com.android.SdkConstants.VIEW_FRAGMENT;
-import static com.android.SdkConstants.VIEW_TAG;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.ide.common.xml.ManifestData;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-import com.android.ide.eclipse.adt.internal.project.AndroidManifestHelper;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.resources.ResourceFolderType;
-import com.android.utils.SdkUtils;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.internal.corext.refactoring.changes.RenamePackageChange;
-import org.eclipse.jdt.internal.corext.refactoring.rename.RenameCompilationUnitProcessor;
-import org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.ltk.core.refactoring.FileStatusContext;
-import org.eclipse.ltk.core.refactoring.NullChange;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
-import org.eclipse.ltk.core.refactoring.participants.RenameParticipant;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.sse.core.StructuredModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-/**
- * A participant to participate in refactorings that rename a package in an Android project.
- * The class updates android manifest and the layout file
- * The user can suppress refactoring by disabling the "Update references" checkbox
- * <p>
- * Rename participants are registered via the extension point <code>
- * org.eclipse.ltk.core.refactoring.renameParticipants</code>.
- * Extensions to this extension point must therefore extend
- * <code>org.eclipse.ltk.core.refactoring.participants.RenameParticipant</code>.
- * </p>
- */
-@SuppressWarnings("restriction")
-public class AndroidPackageRenameParticipant extends RenameParticipant {
-
- private IProject mProject;
- private IFile mManifestFile;
- private IPackageFragment mPackageFragment;
- private String mOldPackage;
- private String mNewPackage;
- private String mAppPackage;
- private boolean mRefactoringAppPackage;
-
- @Override
- public String getName() {
- return "Android Package Rename";
- }
-
- @Override
- public RefactoringStatus checkConditions(IProgressMonitor pm, CheckConditionsContext context)
- throws OperationCanceledException {
- if (mAppPackage.equals(mOldPackage) && !mRefactoringAppPackage) {
- IRegion region = null;
- Document document = DomUtilities.getDocument(mManifestFile);
- if (document != null && document.getDocumentElement() != null) {
- Attr attribute = document.getDocumentElement().getAttributeNode(ATTR_PACKAGE);
- if (attribute instanceof IndexedRegion) {
- IndexedRegion ir = (IndexedRegion) attribute;
- int start = ir.getStartOffset();
- region = new Region(start, ir.getEndOffset() - start);
- }
- }
- if (region == null) {
- region = new Region(0, 0);
- }
- // There's no line wrapping in the error dialog, so split up the message into
- // individually digestible pieces of information
- RefactoringStatusContext ctx = new FileStatusContext(mManifestFile, region);
- RefactoringStatus status = RefactoringStatus.createInfoStatus(
- "You are refactoring the same package as your application's " +
- "package (specified in the manifest).\n", ctx);
- status.addInfo(
- "Note that this refactoring does NOT also update your " +
- "application package.", ctx);
- status.addInfo("The application package defines your application's identity.", ctx);
- status.addInfo(
- "If you change it, then it is considered to be a different application.", ctx);
- status.addInfo("(Users of the previous version cannot update to the new version.)",
- ctx);
- status.addInfo(
- "The application package, and the package containing the code, can differ.",
- ctx);
- status.addInfo(
- "To really change application package, " +
- "choose \"Android Tools\" > \"Rename Application Package.\" " +
- "from the project context menu.", ctx);
- return status;
- }
-
- return new RefactoringStatus();
- }
-
- @Override
- protected boolean initialize(final Object element) {
- mRefactoringAppPackage = false;
- try {
- // Only propose this refactoring if the "Update References" checkbox is set.
- if (!getArguments().getUpdateReferences()) {
- return false;
- }
-
- if (element instanceof IPackageFragment) {
- mPackageFragment = (IPackageFragment) element;
- if (!mPackageFragment.containsJavaResources()) {
- return false;
- }
- IJavaProject javaProject = (IJavaProject) mPackageFragment
- .getAncestor(IJavaElement.JAVA_PROJECT);
- mProject = javaProject.getProject();
- IResource manifestResource = mProject.findMember(AdtConstants.WS_SEP
- + SdkConstants.FN_ANDROID_MANIFEST_XML);
-
- if (manifestResource == null || !manifestResource.exists()
- || !(manifestResource instanceof IFile)) {
- RefactoringUtil.logInfo("Invalid or missing the "
- + SdkConstants.FN_ANDROID_MANIFEST_XML + " in the "
- + mProject.getName() + " project.");
- return false;
- }
- mManifestFile = (IFile) manifestResource;
- String packageName = mPackageFragment.getElementName();
- ManifestData manifestData;
- manifestData = AndroidManifestHelper.parseForData(mManifestFile);
- if (manifestData == null) {
- return false;
- }
- mAppPackage = manifestData.getPackage();
- mOldPackage = packageName;
- mNewPackage = getArguments().getNewName();
- if (mOldPackage == null || mNewPackage == null) {
- return false;
- }
-
- if (RefactoringUtil.isRefactorAppPackage()
- && mAppPackage != null
- && mAppPackage.equals(packageName)) {
- mRefactoringAppPackage = true;
- }
-
- return true;
- }
- } catch (JavaModelException ignore) {
- }
- return false;
- }
-
-
- @Override
- public Change createChange(IProgressMonitor pm) throws CoreException,
- OperationCanceledException {
- if (pm.isCanceled()) {
- return null;
- }
- if (!getArguments().getUpdateReferences()) {
- return null;
- }
-
- RefactoringProcessor p = getProcessor();
- if (p instanceof RenameCompilationUnitProcessor) {
- RenameTypeProcessor rtp =
- ((RenameCompilationUnitProcessor) p).getRenameTypeProcessor();
- if (rtp != null) {
- String pattern = rtp.getFilePatterns();
- boolean updQualf = rtp.getUpdateQualifiedNames();
- if (updQualf && pattern != null && pattern.contains("xml")) { //$NON-NLS-1$
- // Do not propose this refactoring if the
- // "Update fully qualified names in non-Java files" option is
- // checked and the file patterns mention XML. [c.f. SDK bug 21589]
- return null;
- }
- }
- }
-
- IPath pkgPath = mPackageFragment.getPath();
- IPath genPath = mProject.getFullPath().append(SdkConstants.FD_GEN_SOURCES);
- if (genPath.isPrefixOf(pkgPath)) {
- RefactoringUtil.logInfo(getName() + ": Cannot rename generated package.");
- return null;
- }
- CompositeChange result = new CompositeChange(getName());
- result.markAsSynthetic();
-
- addManifestFileChanges(result);
-
- // Update layout files; we don't just need to react to custom view
- // changes, we need to update fragment references and even tool:context activity
- // references
- addLayoutFileChanges(mProject, result);
-
- // Also update in dependent projects
- ProjectState projectState = Sdk.getProjectState(mProject);
- if (projectState != null) {
- Collection<ProjectState> parentProjects = projectState.getFullParentProjects();
- for (ProjectState parentProject : parentProjects) {
- IProject project = parentProject.getProject();
- addLayoutFileChanges(project, result);
- }
- }
-
- if (mRefactoringAppPackage) {
- Change genChange = getGenPackageChange(pm);
- if (genChange != null) {
- result.add(genChange);
- }
-
- return new NullChange("Update Imports") {
- @Override
- public Change perform(IProgressMonitor monitor) throws CoreException {
- FixImportsJob job = new FixImportsJob("Fix Rename Package",
- mManifestFile, mNewPackage);
- job.schedule(500);
-
- // Not undoable: just return null instead of an undo-change.
- return null;
- }
- };
- }
-
- return (result.getChildren().length == 0) ? null : result;
- }
-
- /**
- * Returns Android gen package text change
- *
- * @param pm the progress monitor
- *
- * @return Android gen package text change
- * @throws CoreException if an error happens
- * @throws OperationCanceledException if the operation is canceled
- */
- public Change getGenPackageChange(IProgressMonitor pm) throws CoreException,
- OperationCanceledException {
- if (mRefactoringAppPackage) {
- IPackageFragment genJavaPackageFragment = getGenPackageFragment();
- if (genJavaPackageFragment != null && genJavaPackageFragment.exists()) {
- return new RenamePackageChange(genJavaPackageFragment, mNewPackage, true);
- }
- }
- return null;
- }
-
- /**
- * Return the gen package fragment
- */
- private IPackageFragment getGenPackageFragment() throws JavaModelException {
- IJavaProject javaProject = (IJavaProject) mPackageFragment
- .getAncestor(IJavaElement.JAVA_PROJECT);
- if (javaProject != null && javaProject.isOpen()) {
- IProject project = javaProject.getProject();
- IFolder genFolder = project.getFolder(SdkConstants.FD_GEN_SOURCES);
- if (genFolder.exists()) {
- String javaPackagePath = mAppPackage.replace('.', '/');
- IPath genJavaPackagePath = genFolder.getFullPath().append(javaPackagePath);
- IPackageFragment genPackageFragment = javaProject
- .findPackageFragment(genJavaPackagePath);
- return genPackageFragment;
- }
- }
- return null;
- }
-
- /**
- * Returns the new class name
- *
- * @param fqcn the fully qualified class name in the renamed package
- * @return the new class name
- */
- private String getNewClassName(String fqcn) {
- assert isInRenamedPackage(fqcn) : fqcn;
- int lastDot = fqcn.lastIndexOf('.');
- if (lastDot < 0) {
- return mNewPackage;
- }
- String name = fqcn.substring(lastDot, fqcn.length());
- String newClassName = mNewPackage + name;
- return newClassName;
- }
-
- private void addManifestFileChanges(CompositeChange result) {
- addXmlFileChanges(mManifestFile, result, true);
- }
-
- private void addLayoutFileChanges(IProject project, CompositeChange result) {
- try {
- // Update references in XML resource files
- IFolder resFolder = project.getFolder(SdkConstants.FD_RESOURCES);
-
- IResource[] folders = resFolder.members();
- for (IResource folder : folders) {
- String folderName = folder.getName();
- ResourceFolderType folderType = ResourceFolderType.getFolderType(folderName);
- if (folderType != ResourceFolderType.LAYOUT) {
- continue;
- }
- if (!(folder instanceof IFolder)) {
- continue;
- }
- IResource[] files = ((IFolder) folder).members();
- for (int i = 0; i < files.length; i++) {
- IResource member = files[i];
- if ((member instanceof IFile) && member.exists()) {
- IFile file = (IFile) member;
- String fileName = member.getName();
-
- if (SdkUtils.endsWith(fileName, DOT_XML)) {
- addXmlFileChanges(file, result, false);
- }
- }
- }
- }
- } catch (CoreException e) {
- RefactoringUtil.log(e);
- }
- }
-
- private boolean addXmlFileChanges(IFile file, CompositeChange changes, boolean isManifest) {
- IModelManager modelManager = StructuredModelManager.getModelManager();
- IStructuredModel model = null;
- try {
- model = modelManager.getExistingModelForRead(file);
- if (model == null) {
- model = modelManager.getModelForRead(file);
- }
- if (model != null) {
- IStructuredDocument document = model.getStructuredDocument();
- if (model instanceof IDOMModel) {
- IDOMModel domModel = (IDOMModel) model;
- Element root = domModel.getDocument().getDocumentElement();
- if (root != null) {
- List<TextEdit> edits = new ArrayList<TextEdit>();
- if (isManifest) {
- addManifestReplacements(edits, root, document);
- } else {
- addLayoutReplacements(edits, root, document);
- }
- if (!edits.isEmpty()) {
- MultiTextEdit rootEdit = new MultiTextEdit();
- rootEdit.addChildren(edits.toArray(new TextEdit[edits.size()]));
- TextFileChange change = new TextFileChange(file.getName(), file);
- change.setTextType(EXT_XML);
- change.setEdit(rootEdit);
- changes.add(change);
- }
- }
- } else {
- return false;
- }
- }
-
- return true;
- } catch (IOException e) {
- AdtPlugin.log(e, null);
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- } finally {
- if (model != null) {
- model.releaseFromRead();
- }
- }
-
- return false;
- }
-
- private boolean isInRenamedPackage(String fqcn) {
- return fqcn.startsWith(mOldPackage)
- && fqcn.length() > mOldPackage.length()
- && fqcn.indexOf('.', mOldPackage.length() + 1) == -1;
- }
-
- private void addLayoutReplacements(
- @NonNull List<TextEdit> edits,
- @NonNull Element element,
- @NonNull IStructuredDocument document) {
- String tag = element.getTagName();
- if (isInRenamedPackage(tag)) {
- int start = RefactoringUtil.getTagNameRangeStart(element, document);
- if (start != -1) {
- int end = start + tag.length();
- edits.add(new ReplaceEdit(start, end - start, getNewClassName(tag)));
- }
- } else {
- Attr classNode = null;
- if (tag.equals(VIEW_TAG)) {
- classNode = element.getAttributeNode(ATTR_CLASS);
- } else if (tag.equals(VIEW_FRAGMENT)) {
- classNode = element.getAttributeNode(ATTR_CLASS);
- if (classNode == null) {
- classNode = element.getAttributeNodeNS(ANDROID_URI, ATTR_NAME);
- }
- } else if (element.hasAttributeNS(TOOLS_URI, ATTR_CONTEXT)) {
- classNode = element.getAttributeNodeNS(TOOLS_URI, ATTR_CONTEXT);
- if (classNode != null && classNode.getValue().startsWith(".")) { //$NON-NLS-1$
- classNode = null;
- }
- }
- if (classNode != null) {
- String fqcn = classNode.getValue();
- if (isInRenamedPackage(fqcn)) {
- int start = RefactoringUtil.getAttributeValueRangeStart(classNode, document);
- if (start != -1) {
- int end = start + fqcn.length();
- edits.add(new ReplaceEdit(start, end - start, getNewClassName(fqcn)));
- }
- }
- }
- }
-
- NodeList children = element.getChildNodes();
- for (int i = 0, n = children.getLength(); i < n; i++) {
- Node child = children.item(i);
- if (child.getNodeType() == Node.ELEMENT_NODE) {
- addLayoutReplacements(edits, (Element) child, document);
- }
- }
- }
-
- private void addManifestReplacements(
- @NonNull List<TextEdit> edits,
- @NonNull Element element,
- @NonNull IStructuredDocument document) {
- if (mRefactoringAppPackage &&
- element == element.getOwnerDocument().getDocumentElement()) {
- // Update the app package declaration
- Attr pkg = element.getAttributeNode(ATTR_PACKAGE);
- if (pkg != null && pkg.getValue().equals(mOldPackage)) {
- int start = RefactoringUtil.getAttributeValueRangeStart(pkg, document);
- if (start != -1) {
- int end = start + mOldPackage.length();
- edits.add(new ReplaceEdit(start, end - start, mNewPackage));
- }
- }
- }
-
- NamedNodeMap attributes = element.getAttributes();
- for (int i = 0, n = attributes.getLength(); i < n; i++) {
- Attr attr = (Attr) attributes.item(i);
- if (!RefactoringUtil.isManifestClassAttribute(attr)) {
- continue;
- }
-
- String value = attr.getValue();
- if (isInRenamedPackage(value)) {
- int start = RefactoringUtil.getAttributeValueRangeStart(attr, document);
- if (start != -1) {
- int end = start + value.length();
- edits.add(new ReplaceEdit(start, end - start, getNewClassName(value)));
- }
- } else if (value.startsWith(".")) {
- // If we're renaming the app package
- String fqcn = mAppPackage + value;
- if (isInRenamedPackage(fqcn)) {
- int start = RefactoringUtil.getAttributeValueRangeStart(attr, document);
- if (start != -1) {
- int end = start + value.length();
- String newClassName = getNewClassName(fqcn);
- if (mRefactoringAppPackage) {
- newClassName = newClassName.substring(mNewPackage.length());
- } else if (newClassName.startsWith(mOldPackage)
- && newClassName.charAt(mOldPackage.length()) == '.') {
- newClassName = newClassName.substring(mOldPackage.length());
- }
-
- if (!newClassName.equals(value)) {
- edits.add(new ReplaceEdit(start, end - start, newClassName));
- }
- }
- }
- }
- }
-
- NodeList children = element.getChildNodes();
- for (int i = 0, n = children.getLength(); i < n; i++) {
- Node child = children.item(i);
- if (child.getNodeType() == Node.ELEMENT_NODE) {
- addManifestReplacements(edits, (Element) child, document);
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/AndroidTypeMoveParticipant.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/AndroidTypeMoveParticipant.java
deleted file mode 100644
index 2146184c8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/AndroidTypeMoveParticipant.java
+++ /dev/null
@@ -1,362 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.refactorings.core;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_CLASS;
-import static com.android.SdkConstants.ATTR_CONTEXT;
-import static com.android.SdkConstants.ATTR_NAME;
-import static com.android.SdkConstants.DOT_XML;
-import static com.android.SdkConstants.EXT_XML;
-import static com.android.SdkConstants.TOOLS_URI;
-import static com.android.SdkConstants.VIEW_FRAGMENT;
-import static com.android.SdkConstants.VIEW_TAG;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.ide.common.xml.ManifestData;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.project.AndroidManifestHelper;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.resources.ResourceFolderType;
-import com.android.utils.SdkUtils;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.MoveParticipant;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.sse.core.StructuredModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-/**
- * A participant to participate in refactorings that move a type in an Android project.
- * The class updates android manifest and the layout file
- * The user can suppress refactoring by disabling the "Update references" checkbox
- * <p>
- * Rename participants are registered via the extension point <code>
- * org.eclipse.ltk.core.refactoring.moveParticipants</code>.
- * Extensions to this extension point must therefore extend <code>org.eclipse.ltk.core.refactoring.participants.MoveParticipant</code>.
- * </p>
- */
-@SuppressWarnings("restriction")
-public class AndroidTypeMoveParticipant extends MoveParticipant {
-
- private IProject mProject;
- protected IFile mManifestFile;
- protected String mOldFqcn;
- protected String mNewFqcn;
- protected String mAppPackage;
-
- @Override
- public String getName() {
- return "Android Type Move";
- }
-
- @Override
- public RefactoringStatus checkConditions(IProgressMonitor pm, CheckConditionsContext context)
- throws OperationCanceledException {
- return new RefactoringStatus();
- }
-
- @Override
- protected boolean initialize(Object element) {
- if (element instanceof IType) {
- IType type = (IType) element;
- IJavaProject javaProject = (IJavaProject) type.getAncestor(IJavaElement.JAVA_PROJECT);
- mProject = javaProject.getProject();
- IResource manifestResource = mProject.findMember(AdtConstants.WS_SEP
- + SdkConstants.FN_ANDROID_MANIFEST_XML);
-
- if (manifestResource == null || !manifestResource.exists()
- || !(manifestResource instanceof IFile)) {
- RefactoringUtil.logInfo("Invalid or missing the "
- + SdkConstants.FN_ANDROID_MANIFEST_XML + " in the " + mProject.getName()
- + " project.");
- return false;
- }
- mManifestFile = (IFile) manifestResource;
- ManifestData manifestData;
- manifestData = AndroidManifestHelper.parseForData(mManifestFile);
- if (manifestData == null) {
- return false;
- }
- mAppPackage = manifestData.getPackage();
- mOldFqcn = type.getFullyQualifiedName();
- Object destination = getArguments().getDestination();
- if (destination instanceof IPackageFragment) {
- IPackageFragment packageFragment = (IPackageFragment) destination;
- mNewFqcn = packageFragment.getElementName() + "." + type.getElementName();
- } else if (destination instanceof IResource) {
- try {
- IPackageFragment[] fragments = javaProject.getPackageFragments();
- for (IPackageFragment fragment : fragments) {
- IResource resource = fragment.getResource();
- if (resource.equals(destination)) {
- mNewFqcn = fragment.getElementName() + '.' + type.getElementName();
- break;
- }
- }
- } catch (JavaModelException e) {
- // pass
- }
- }
- return mOldFqcn != null && mNewFqcn != null;
- }
-
- return false;
- }
-
- @Override
- public Change createChange(IProgressMonitor pm) throws CoreException,
- OperationCanceledException {
- if (pm.isCanceled()) {
- return null;
- }
- if (!getArguments().getUpdateReferences()) {
- return null;
- }
- CompositeChange result = new CompositeChange(getName());
- result.markAsSynthetic();
-
- addManifestFileChanges(result);
-
- // Update layout files; we don't just need to react to custom view
- // changes, we need to update fragment references and even tool:context activity
- // references
- addLayoutFileChanges(mProject, result);
-
- // Also update in dependent projects
- ProjectState projectState = Sdk.getProjectState(mProject);
- if (projectState != null) {
- Collection<ProjectState> parentProjects = projectState.getFullParentProjects();
- for (ProjectState parentProject : parentProjects) {
- IProject project = parentProject.getProject();
- addLayoutFileChanges(project, result);
- }
- }
-
- return (result.getChildren().length == 0) ? null : result;
- }
-
- private void addManifestFileChanges(CompositeChange result) {
- addXmlFileChanges(mManifestFile, result, true);
- }
-
- private void addLayoutFileChanges(IProject project, CompositeChange result) {
- try {
- // Update references in XML resource files
- IFolder resFolder = project.getFolder(SdkConstants.FD_RESOURCES);
-
- IResource[] folders = resFolder.members();
- for (IResource folder : folders) {
- String folderName = folder.getName();
- ResourceFolderType folderType = ResourceFolderType.getFolderType(folderName);
- if (folderType != ResourceFolderType.LAYOUT) {
- continue;
- }
- if (!(folder instanceof IFolder)) {
- continue;
- }
- IResource[] files = ((IFolder) folder).members();
- for (int i = 0; i < files.length; i++) {
- IResource member = files[i];
- if ((member instanceof IFile) && member.exists()) {
- IFile file = (IFile) member;
- String fileName = member.getName();
-
- if (SdkUtils.endsWith(fileName, DOT_XML)) {
- addXmlFileChanges(file, result, false);
- }
- }
- }
- }
- } catch (CoreException e) {
- RefactoringUtil.log(e);
- }
- }
-
- private boolean addXmlFileChanges(IFile file, CompositeChange changes, boolean isManifest) {
- IModelManager modelManager = StructuredModelManager.getModelManager();
- IStructuredModel model = null;
- try {
- model = modelManager.getExistingModelForRead(file);
- if (model == null) {
- model = modelManager.getModelForRead(file);
- }
- if (model != null) {
- IStructuredDocument document = model.getStructuredDocument();
- if (model instanceof IDOMModel) {
- IDOMModel domModel = (IDOMModel) model;
- Element root = domModel.getDocument().getDocumentElement();
- if (root != null) {
- List<TextEdit> edits = new ArrayList<TextEdit>();
- if (isManifest) {
- addManifestReplacements(edits, root, document);
- } else {
- addLayoutReplacements(edits, root, document);
- }
- if (!edits.isEmpty()) {
- MultiTextEdit rootEdit = new MultiTextEdit();
- rootEdit.addChildren(edits.toArray(new TextEdit[edits.size()]));
- TextFileChange change = new TextFileChange(file.getName(), file);
- change.setTextType(EXT_XML);
- change.setEdit(rootEdit);
- changes.add(change);
- }
- }
- } else {
- return false;
- }
- }
-
- return true;
- } catch (IOException e) {
- AdtPlugin.log(e, null);
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- } finally {
- if (model != null) {
- model.releaseFromRead();
- }
- }
-
- return false;
- }
-
- private void addLayoutReplacements(
- @NonNull List<TextEdit> edits,
- @NonNull Element element,
- @NonNull IStructuredDocument document) {
- String tag = element.getTagName();
- if (tag.equals(mOldFqcn)) {
- int start = RefactoringUtil.getTagNameRangeStart(element, document);
- if (start != -1) {
- int end = start + mOldFqcn.length();
- edits.add(new ReplaceEdit(start, end - start, mNewFqcn));
- }
- } else if (tag.equals(VIEW_TAG)) {
- Attr classNode = element.getAttributeNode(ATTR_CLASS);
- if (classNode != null && classNode.getValue().equals(mOldFqcn)) {
- int start = RefactoringUtil.getAttributeValueRangeStart(classNode, document);
- if (start != -1) {
- int end = start + mOldFqcn.length();
- edits.add(new ReplaceEdit(start, end - start, mNewFqcn));
- }
- }
- } else if (tag.equals(VIEW_FRAGMENT)) {
- Attr classNode = element.getAttributeNode(ATTR_CLASS);
- if (classNode == null) {
- classNode = element.getAttributeNodeNS(ANDROID_URI, ATTR_NAME);
- }
- if (classNode != null && classNode.getValue().equals(mOldFqcn)) {
- int start = RefactoringUtil.getAttributeValueRangeStart(classNode, document);
- if (start != -1) {
- int end = start + mOldFqcn.length();
- edits.add(new ReplaceEdit(start, end - start, mNewFqcn));
- }
- }
- } else if (element.hasAttributeNS(TOOLS_URI, ATTR_CONTEXT)) {
- Attr classNode = element.getAttributeNodeNS(TOOLS_URI, ATTR_CONTEXT);
- if (classNode != null && classNode.getValue().equals(mOldFqcn)) {
- int start = RefactoringUtil.getAttributeValueRangeStart(classNode, document);
- if (start != -1) {
- int end = start + mOldFqcn.length();
- edits.add(new ReplaceEdit(start, end - start, mNewFqcn));
- }
- }
- }
-
- NodeList children = element.getChildNodes();
- for (int i = 0, n = children.getLength(); i < n; i++) {
- Node child = children.item(i);
- if (child.getNodeType() == Node.ELEMENT_NODE) {
- addLayoutReplacements(edits, (Element) child, document);
- }
- }
- }
-
- private void addManifestReplacements(
- @NonNull List<TextEdit> edits,
- @NonNull Element element,
- @NonNull IStructuredDocument document) {
- NamedNodeMap attributes = element.getAttributes();
- for (int i = 0, n = attributes.getLength(); i < n; i++) {
- Attr attr = (Attr) attributes.item(i);
- if (!RefactoringUtil.isManifestClassAttribute(attr)) {
- continue;
- }
-
- String value = attr.getValue();
- if (value.equals(mOldFqcn)) {
- int start = RefactoringUtil.getAttributeValueRangeStart(attr, document);
- if (start != -1) {
- int end = start + mOldFqcn.length();
- edits.add(new ReplaceEdit(start, end - start, mNewFqcn));
- }
- } else if (value.startsWith(".")) { //$NON-NLS-1$
- String fqcn = mAppPackage + value;
- if (fqcn.equals(mOldFqcn)) {
- int start = RefactoringUtil.getAttributeValueRangeStart(attr, document);
- if (start != -1) {
- int end = start + value.length();
- edits.add(new ReplaceEdit(start, end - start, mNewFqcn));
- }
- }
- }
- }
-
- NodeList children = element.getChildNodes();
- for (int i = 0, n = children.getLength(); i < n; i++) {
- Node child = children.item(i);
- if (child.getNodeType() == Node.ELEMENT_NODE) {
- addManifestReplacements(edits, (Element) child, document);
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/AndroidTypeRenameParticipant.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/AndroidTypeRenameParticipant.java
deleted file mode 100644
index 7843ab3b4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/AndroidTypeRenameParticipant.java
+++ /dev/null
@@ -1,529 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.refactorings.core;
-
-import static com.android.SdkConstants.ANDROID_MANIFEST_XML;
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_CLASS;
-import static com.android.SdkConstants.ATTR_CONTEXT;
-import static com.android.SdkConstants.ATTR_NAME;
-import static com.android.SdkConstants.CLASS_VIEW;
-import static com.android.SdkConstants.DOT_XML;
-import static com.android.SdkConstants.EXT_XML;
-import static com.android.SdkConstants.R_CLASS;
-import static com.android.SdkConstants.TOOLS_URI;
-import static com.android.SdkConstants.VIEW_FRAGMENT;
-import static com.android.SdkConstants.VIEW_TAG;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.ide.common.xml.ManifestData;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.ide.eclipse.adt.internal.project.AndroidManifestHelper;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.resources.ResourceFolderType;
-import com.android.resources.ResourceType;
-import com.android.utils.SdkUtils;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.jdt.core.IField;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.core.ITypeHierarchy;
-import org.eclipse.jdt.internal.corext.refactoring.rename.RenameCompilationUnitProcessor;
-import org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
-import org.eclipse.ltk.core.refactoring.participants.RenameParticipant;
-import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.sse.core.StructuredModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-
-/**
- * A participant to participate in refactorings that rename a type in an Android project.
- * The class updates android manifest and the layout file
- * The user can suppress refactoring by disabling the "Update references" checkbox.
- * <p>
- * Rename participants are registered via the extension point <code>
- * org.eclipse.ltk.core.refactoring.renameParticipants</code>.
- * Extensions to this extension point must therefore extend
- * <code>org.eclipse.ltk.core.refactoring.participants.RenameParticipant</code>.
- */
-@SuppressWarnings("restriction")
-public class AndroidTypeRenameParticipant extends RenameParticipant {
- private IProject mProject;
- private IFile mManifestFile;
- private String mOldFqcn;
- private String mNewFqcn;
- private String mOldSimpleName;
- private String mNewSimpleName;
- private String mOldDottedName;
- private String mNewDottedName;
- private boolean mIsCustomView;
-
- /**
- * Set while we are creating an embedded Java refactoring. This could cause a recursive
- * invocation of the XML renaming refactoring to react to the field, so this is flag
- * during the call to the Java processor, and is used to ignore requests for adding in
- * field reactions during that time.
- */
- private static boolean sIgnore;
-
- @Override
- public String getName() {
- return "Android Type Rename";
- }
-
- @Override
- public RefactoringStatus checkConditions(IProgressMonitor pm, CheckConditionsContext context)
- throws OperationCanceledException {
- return new RefactoringStatus();
- }
-
- @Override
- protected boolean initialize(Object element) {
- if (sIgnore) {
- return false;
- }
-
- if (element instanceof IType) {
- IType type = (IType) element;
- IJavaProject javaProject = (IJavaProject) type.getAncestor(IJavaElement.JAVA_PROJECT);
- mProject = javaProject.getProject();
- IResource manifestResource = mProject.findMember(AdtConstants.WS_SEP
- + SdkConstants.FN_ANDROID_MANIFEST_XML);
-
- if (manifestResource == null || !manifestResource.exists()
- || !(manifestResource instanceof IFile)) {
- RefactoringUtil.logInfo(
- String.format("Invalid or missing file %1$s in project %2$s",
- SdkConstants.FN_ANDROID_MANIFEST_XML,
- mProject.getName()));
- return false;
- }
-
- try {
- IType classView = javaProject.findType(CLASS_VIEW);
- if (classView != null) {
- ITypeHierarchy hierarchy = type.newSupertypeHierarchy(new NullProgressMonitor());
- if (hierarchy.contains(classView)) {
- mIsCustomView = true;
- }
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
-
- mManifestFile = (IFile) manifestResource;
- ManifestData manifestData;
- manifestData = AndroidManifestHelper.parseForData(mManifestFile);
- if (manifestData == null) {
- return false;
- }
- mOldSimpleName = type.getElementName();
- mOldDottedName = '.' + mOldSimpleName;
- mOldFqcn = type.getFullyQualifiedName();
- String packageName = type.getPackageFragment().getElementName();
- mNewSimpleName = getArguments().getNewName();
- mNewDottedName = '.' + mNewSimpleName;
- if (packageName != null) {
- mNewFqcn = packageName + mNewDottedName;
- } else {
- mNewFqcn = mNewSimpleName;
- }
- if (mOldFqcn == null || mNewFqcn == null) {
- return false;
- }
- if (!RefactoringUtil.isRefactorAppPackage() && mNewFqcn.indexOf('.') == -1) {
- mNewFqcn = packageName + mNewDottedName;
- }
- return true;
- }
- return false;
- }
-
- @Override
- public Change createChange(IProgressMonitor pm) throws CoreException,
- OperationCanceledException {
- if (pm.isCanceled()) {
- return null;
- }
-
- // Only propose this refactoring if the "Update References" checkbox is set.
- if (!getArguments().getUpdateReferences()) {
- return null;
- }
-
- RefactoringProcessor p = getProcessor();
- if (p instanceof RenameCompilationUnitProcessor) {
- RenameTypeProcessor rtp =
- ((RenameCompilationUnitProcessor) p).getRenameTypeProcessor();
- if (rtp != null) {
- String pattern = rtp.getFilePatterns();
- boolean updQualf = rtp.getUpdateQualifiedNames();
- if (updQualf && pattern != null && pattern.contains("xml")) { //$NON-NLS-1$
- // Do not propose this refactoring if the
- // "Update fully qualified names in non-Java files" option is
- // checked and the file patterns mention XML. [c.f. SDK bug 21589]
- return null;
- }
- }
- }
-
- CompositeChange result = new CompositeChange(getName());
-
- // Only show the children in the refactoring preview dialog
- result.markAsSynthetic();
-
- addManifestFileChanges(mManifestFile, result);
- addLayoutFileChanges(mProject, result);
- addJavaChanges(mProject, result, pm);
-
- // Also update in dependent projects
- // TODO: Also do the Java elements, if they are in Jar files, since the library
- // projects do this (and the JDT refactoring does not include them)
- ProjectState projectState = Sdk.getProjectState(mProject);
- if (projectState != null) {
- Collection<ProjectState> parentProjects = projectState.getFullParentProjects();
- for (ProjectState parentProject : parentProjects) {
- IProject project = parentProject.getProject();
- IResource manifestResource = project.findMember(AdtConstants.WS_SEP
- + SdkConstants.FN_ANDROID_MANIFEST_XML);
- if (manifestResource != null && manifestResource.exists()
- && manifestResource instanceof IFile) {
- addManifestFileChanges((IFile) manifestResource, result);
- }
- addLayoutFileChanges(project, result);
- addJavaChanges(project, result, pm);
- }
- }
-
- // Look for the field change on the R.java class; it's a derived file
- // and will generate file modified manually warnings. Disable it.
- RenameResourceParticipant.disableRClassChanges(result);
-
- return (result.getChildren().length == 0) ? null : result;
- }
-
- private void addJavaChanges(IProject project, CompositeChange result, IProgressMonitor monitor) {
- if (!mIsCustomView) {
- return;
- }
-
- // Also rename styleables, if any
- try {
- // Find R class
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
- ManifestInfo info = ManifestInfo.get(project);
- info.getPackage();
- String rFqcn = info.getPackage() + '.' + R_CLASS;
- IType styleable = javaProject.findType(rFqcn + '.' + ResourceType.STYLEABLE.getName());
- if (styleable != null) {
- IField[] fields = styleable.getFields();
- CompositeChange fieldChanges = null;
- for (IField field : fields) {
- String name = field.getElementName();
- if (name.equals(mOldSimpleName) || name.startsWith(mOldSimpleName)
- && name.length() > mOldSimpleName.length()
- && name.charAt(mOldSimpleName.length()) == '_') {
- // Rename styleable fields
- String newName = name.equals(mOldSimpleName) ? mNewSimpleName :
- mNewSimpleName + name.substring(mOldSimpleName.length());
- RenameRefactoring refactoring =
- RenameResourceParticipant.createFieldRefactoring(field,
- newName, true);
-
- try {
- sIgnore = true;
- RefactoringStatus status = refactoring.checkAllConditions(monitor);
- if (status != null && !status.hasError()) {
- Change fieldChange = refactoring.createChange(monitor);
- if (fieldChange != null) {
- if (fieldChanges == null) {
- fieldChanges = new CompositeChange(
- "Update custom view styleable fields");
- // Disable these changes. They sometimes end up
- // editing the wrong offsets. It looks like Eclipse
- // doesn't ensure that after applying each change it
- // also adjusts the other field offsets. I poked around
- // and couldn't find a way to do this properly, but
- // at least by listing the diffs here it shows what should
- // be done.
- fieldChanges.setEnabled(false);
- }
- // Disable change: see comment above.
- fieldChange.setEnabled(false);
- fieldChanges.add(fieldChange);
- }
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- } finally {
- sIgnore = false;
- }
- }
- }
- if (fieldChanges != null) {
- result.add(fieldChanges);
- }
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- }
-
- private void addManifestFileChanges(IFile manifestFile, CompositeChange result) {
- addXmlFileChanges(manifestFile, result, null);
- }
-
- private void addLayoutFileChanges(IProject project, CompositeChange result) {
- try {
- // Update references in XML resource files
- IFolder resFolder = project.getFolder(SdkConstants.FD_RESOURCES);
-
- IResource[] folders = resFolder.members();
- for (IResource folder : folders) {
- String folderName = folder.getName();
- ResourceFolderType folderType = ResourceFolderType.getFolderType(folderName);
- if (folderType != ResourceFolderType.LAYOUT &&
- folderType != ResourceFolderType.VALUES) {
- continue;
- }
- if (!(folder instanceof IFolder)) {
- continue;
- }
- IResource[] files = ((IFolder) folder).members();
- for (int i = 0; i < files.length; i++) {
- IResource member = files[i];
- if ((member instanceof IFile) && member.exists()) {
- IFile file = (IFile) member;
- String fileName = member.getName();
-
- if (SdkUtils.endsWith(fileName, DOT_XML)) {
- addXmlFileChanges(file, result, folderType);
- }
- }
- }
- }
- } catch (CoreException e) {
- RefactoringUtil.log(e);
- }
- }
-
- private boolean addXmlFileChanges(IFile file, CompositeChange changes,
- ResourceFolderType folderType) {
- IModelManager modelManager = StructuredModelManager.getModelManager();
- IStructuredModel model = null;
- try {
- model = modelManager.getExistingModelForRead(file);
- if (model == null) {
- model = modelManager.getModelForRead(file);
- }
- if (model != null) {
- IStructuredDocument document = model.getStructuredDocument();
- if (model instanceof IDOMModel) {
- IDOMModel domModel = (IDOMModel) model;
- Element root = domModel.getDocument().getDocumentElement();
- if (root != null) {
- List<TextEdit> edits = new ArrayList<TextEdit>();
- if (folderType == null) {
- assert file.getName().equals(ANDROID_MANIFEST_XML);
- addManifestReplacements(edits, root, document);
- } else if (folderType == ResourceFolderType.VALUES) {
- addValueReplacements(edits, root, document);
- } else {
- assert folderType == ResourceFolderType.LAYOUT;
- addLayoutReplacements(edits, root, document);
- }
- if (!edits.isEmpty()) {
- MultiTextEdit rootEdit = new MultiTextEdit();
- rootEdit.addChildren(edits.toArray(new TextEdit[edits.size()]));
- TextFileChange change = new TextFileChange(file.getName(), file);
- change.setTextType(EXT_XML);
- change.setEdit(rootEdit);
- changes.add(change);
- }
- }
- } else {
- return false;
- }
- }
-
- return true;
- } catch (IOException e) {
- AdtPlugin.log(e, null);
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- } finally {
- if (model != null) {
- model.releaseFromRead();
- }
- }
-
- return false;
- }
-
- private void addLayoutReplacements(
- @NonNull List<TextEdit> edits,
- @NonNull Element element,
- @NonNull IStructuredDocument document) {
- String tag = element.getTagName();
- if (tag.equals(mOldFqcn)) {
- int start = RefactoringUtil.getTagNameRangeStart(element, document);
- if (start != -1) {
- int end = start + mOldFqcn.length();
- edits.add(new ReplaceEdit(start, end - start, mNewFqcn));
- }
- } else if (tag.equals(VIEW_TAG)) {
- // TODO: Handle inner classes ($ vs .) ?
- Attr classNode = element.getAttributeNode(ATTR_CLASS);
- if (classNode != null && classNode.getValue().equals(mOldFqcn)) {
- int start = RefactoringUtil.getAttributeValueRangeStart(classNode, document);
- if (start != -1) {
- int end = start + mOldFqcn.length();
- edits.add(new ReplaceEdit(start, end - start, mNewFqcn));
- }
- }
- } else if (tag.equals(VIEW_FRAGMENT)) {
- Attr classNode = element.getAttributeNode(ATTR_CLASS);
- if (classNode == null) {
- classNode = element.getAttributeNodeNS(ANDROID_URI, ATTR_NAME);
- }
- if (classNode != null && classNode.getValue().equals(mOldFqcn)) {
- int start = RefactoringUtil.getAttributeValueRangeStart(classNode, document);
- if (start != -1) {
- int end = start + mOldFqcn.length();
- edits.add(new ReplaceEdit(start, end - start, mNewFqcn));
- }
- }
- } else if (element.hasAttributeNS(TOOLS_URI, ATTR_CONTEXT)) {
- Attr classNode = element.getAttributeNodeNS(TOOLS_URI, ATTR_CONTEXT);
- if (classNode != null && classNode.getValue().equals(mOldFqcn)) {
- int start = RefactoringUtil.getAttributeValueRangeStart(classNode, document);
- if (start != -1) {
- int end = start + mOldFqcn.length();
- edits.add(new ReplaceEdit(start, end - start, mNewFqcn));
- }
- } else if (classNode != null && classNode.getValue().equals(mOldDottedName)) {
- int start = RefactoringUtil.getAttributeValueRangeStart(classNode, document);
- if (start != -1) {
- int end = start + mOldDottedName.length();
- edits.add(new ReplaceEdit(start, end - start, mNewDottedName));
- }
- }
- }
-
- NodeList children = element.getChildNodes();
- for (int i = 0, n = children.getLength(); i < n; i++) {
- Node child = children.item(i);
- if (child.getNodeType() == Node.ELEMENT_NODE) {
- addLayoutReplacements(edits, (Element) child, document);
- }
- }
- }
-
- private void addValueReplacements(
- @NonNull List<TextEdit> edits,
- @NonNull Element root,
- @NonNull IStructuredDocument document) {
- // Look for styleable renames for custom views
- String declareStyleable = ResourceType.DECLARE_STYLEABLE.getName();
- List<Element> topLevel = DomUtilities.getChildren(root);
- for (Element element : topLevel) {
- String tag = element.getTagName();
- if (declareStyleable.equals(tag)) {
- Attr nameNode = element.getAttributeNode(ATTR_NAME);
- if (nameNode != null && mOldSimpleName.equals(nameNode.getValue())) {
- int start = RefactoringUtil.getAttributeValueRangeStart(nameNode, document);
- if (start != -1) {
- int end = start + mOldSimpleName.length();
- edits.add(new ReplaceEdit(start, end - start, mNewSimpleName));
- }
- }
- }
- }
- }
-
- private void addManifestReplacements(
- @NonNull List<TextEdit> edits,
- @NonNull Element element,
- @NonNull IStructuredDocument document) {
- NamedNodeMap attributes = element.getAttributes();
- for (int i = 0, n = attributes.getLength(); i < n; i++) {
- Attr attr = (Attr) attributes.item(i);
- if (!RefactoringUtil.isManifestClassAttribute(attr)) {
- continue;
- }
-
- String value = attr.getValue();
- if (value.equals(mOldFqcn)) {
- int start = RefactoringUtil.getAttributeValueRangeStart(attr, document);
- if (start != -1) {
- int end = start + mOldFqcn.length();
- edits.add(new ReplaceEdit(start, end - start, mNewFqcn));
- }
- } else if (value.equals(mOldDottedName)) {
- int start = RefactoringUtil.getAttributeValueRangeStart(attr, document);
- if (start != -1) {
- int end = start + mOldDottedName.length();
- edits.add(new ReplaceEdit(start, end - start, mNewDottedName));
- }
- }
- }
-
- NodeList children = element.getChildNodes();
- for (int i = 0, n = children.getLength(); i < n; i++) {
- Node child = children.item(i);
- if (child.getNodeType() == Node.ELEMENT_NODE) {
- addManifestReplacements(edits, (Element) child, document);
- }
- }
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/FixImportsJob.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/FixImportsJob.java
deleted file mode 100644
index 552e6a845..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/FixImportsJob.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.refactorings.core;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IncrementalProjectBuilder;
-import org.eclipse.core.resources.WorkspaceJob;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jdt.core.ICompilationUnit;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jdt.core.ISourceRange;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.dom.CompilationUnit;
-import org.eclipse.jdt.core.search.TypeNameMatch;
-import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
-import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation;
-import org.eclipse.jdt.internal.corext.codemanipulation.OrganizeImportsOperation.IChooseImportQuery;
-import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
-import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
-import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
-import org.eclipse.jdt.ui.SharedASTProvider;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.progress.IProgressService;
-
-/**
- * The helper class which fixes the import errors after refactoring
- *
- */
-@SuppressWarnings("restriction")
-public class FixImportsJob extends WorkspaceJob {
-
- private IFile mAndroidManifest;
-
- private String mJavaPackage;
-
- /**
- * Creates a new <code>FixImportsJob</code>
- *
- * @param name the job name
- * @param androidManifest the android manifest file
- * @param javaPackage the android java package
- */
- public FixImportsJob(String name, IFile androidManifest, String javaPackage) {
- super(name);
- this.mAndroidManifest = androidManifest;
- this.mJavaPackage = javaPackage;
- }
-
- @Override
- public IStatus runInWorkspace(final IProgressMonitor monitor) throws CoreException {
- if (mJavaPackage == null || mAndroidManifest == null || !mAndroidManifest.exists()) {
- return Status.CANCEL_STATUS;
- }
- IProject project = mAndroidManifest.getProject();
- IJavaProject javaProject = JavaCore.create(project);
- if (javaProject == null || !javaProject.isOpen()) {
- return Status.CANCEL_STATUS;
- }
-
- project.build(IncrementalProjectBuilder.INCREMENTAL_BUILD, monitor);
-
- IMarker[] markers = project.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE);
- for (int i = 0; i < markers.length; i++) {
- IMarker marker = markers[i];
- IResource resource = marker.getResource();
- try {
- IJavaElement element = JavaCore.create(resource);
- if (element != null && (element instanceof ICompilationUnit)) {
- final ICompilationUnit cu = (ICompilationUnit) element;
- IPackageFragment packageFragment = (IPackageFragment) cu
- .getAncestor(IJavaElement.PACKAGE_FRAGMENT);
- if (packageFragment != null && packageFragment.exists()) {
- String packageName = packageFragment.getElementName();
- if (packageName != null && packageName.startsWith(mJavaPackage)) {
- CompilationUnit astRoot = SharedASTProvider.getAST(cu,
- SharedASTProvider.WAIT_ACTIVE_ONLY, null);
- CodeGenerationSettings settings = JavaPreferencesSettings
- .getCodeGenerationSettings(cu.getJavaProject());
- final boolean hasAmbiguity[] = new boolean[] {
- false
- };
- IChooseImportQuery query = new IChooseImportQuery() {
- @Override
- public TypeNameMatch[] chooseImports(TypeNameMatch[][] openChoices,
- ISourceRange[] ranges) {
- hasAmbiguity[0] = true;
- return new TypeNameMatch[0];
- }
- };
- final OrganizeImportsOperation op = new OrganizeImportsOperation(cu,
- astRoot, settings.importIgnoreLowercase, !cu.isWorkingCopy(),
- true, query);
- Display.getDefault().asyncExec(new Runnable() {
-
- @Override
- public void run() {
- try {
- IProgressService progressService = PlatformUI
- .getWorkbench().getProgressService();
- progressService.run(
- true,
- true,
- new WorkbenchRunnableAdapter(op, op
- .getScheduleRule()));
- IEditorPart openEditor = EditorUtility.isOpenInEditor(cu);
- if (openEditor != null) {
- openEditor.doSave(monitor);
- }
- } catch (Throwable e) {
- RefactoringUtil.log(e);
- }
- }
- });
-
- }
- }
- }
- } catch (Throwable e) {
- RefactoringUtil.log(e);
- }
- }
- return Status.OK_STATUS;
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RefactoringUtil.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RefactoringUtil.java
deleted file mode 100644
index 04ebcfa26..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RefactoringUtil.java
+++ /dev/null
@@ -1,224 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.refactorings.core;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_NAME;
-import static com.android.xml.AndroidManifest.ATTRIBUTE_BACKUP_AGENT;
-import static com.android.xml.AndroidManifest.ATTRIBUTE_MANAGE_SPACE_ACTIVITY;
-import static com.android.xml.AndroidManifest.ATTRIBUTE_PARENT_ACTIVITY_NAME;
-import static com.android.xml.AndroidManifest.ATTRIBUTE_TARGET_ACTIVITY;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.xml.AndroidManifest;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.wst.sse.core.StructuredModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Element;
-
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-
-/**
- * The utility class for android refactoring
- *
- */
-@SuppressWarnings("restriction")
-public class RefactoringUtil {
-
- private static boolean sRefactorAppPackage = false;
-
- /**
- * Releases SSE read model; saves SSE model if exists edit model
- * Called in dispose method of refactoring change classes
- *
- * @param model the SSE model
- * @param document the document
- */
- public static void fixModel(IStructuredModel model, IDocument document) {
- if (model != null) {
- model.releaseFromRead();
- }
- model = null;
- if (document == null) {
- return;
- }
- try {
- model = StructuredModelManager.getModelManager().getExistingModelForEdit(document);
- if (model != null) {
- model.save();
- }
- } catch (UnsupportedEncodingException e1) {
- // ignore
- } catch (IOException e1) {
- // ignore
- } catch (CoreException e1) {
- // ignore
- } finally {
- if (model != null) {
- model.releaseFromEdit();
- }
- }
- }
-
- /**
- * Logs the info message
- *
- * @param message the message
- */
- public static void logInfo(String message) {
- AdtPlugin.log(IStatus.INFO, AdtPlugin.PLUGIN_ID, message);
- }
-
- /**
- * Logs the the exception
- *
- * @param e the exception
- */
- public static void log(Throwable e) {
- AdtPlugin.log(e, e.getMessage());
- }
-
- /**
- * @return true if Rename/Move package needs to change the application package
- * default is false
- *
- */
- public static boolean isRefactorAppPackage() {
- return sRefactorAppPackage;
- }
-
- /**
- * @param refactorAppPackage true if Rename/Move package needs to change the application package
- */
- public static void setRefactorAppPackage(boolean refactorAppPackage) {
- RefactoringUtil.sRefactorAppPackage = refactorAppPackage;
- }
-
- /**
- * Returns the range of the attribute value in the given document
- *
- * @param attr the attribute to look up
- * @param document the document containing the attribute
- * @return the range of the value text, not including quotes, in the document
- */
- public static int getAttributeValueRangeStart(
- @NonNull Attr attr,
- @NonNull IDocument document) {
- IndexedRegion region = (IndexedRegion) attr;
- int potentialStart = attr.getName().length() + 2; // + 2: add ="
- String text;
- try {
- text = document.get(region.getStartOffset(),
- region.getEndOffset() - region.getStartOffset());
- } catch (BadLocationException e) {
- return -1;
- }
- String value = attr.getValue();
- int index = text.indexOf(value, potentialStart);
- if (index != -1) {
- return region.getStartOffset() + index;
- } else {
- return -1;
- }
- }
-
- /**
- * Returns the start of the tag name of the given element
- *
- * @param element the element to look up
- * @param document the document containing the attribute
- * @return the index of the start tag in the document
- */
- public static int getTagNameRangeStart(
- @NonNull Element element,
- @NonNull IDocument document) {
- IndexedRegion region = (IndexedRegion) element;
- int potentialStart = 1; // add '<'
- String text;
- try {
- text = document.get(region.getStartOffset(),
- region.getEndOffset() - region.getStartOffset());
- } catch (BadLocationException e) {
- return -1;
- }
- int index = text.indexOf(element.getTagName(), potentialStart);
- if (index != -1) {
- return region.getStartOffset() + index;
- } else {
- return -1;
- }
- }
-
- /**
- * Returns whether the given manifest attribute should be considered to describe
- * a class name. These will be eligible for refactoring when classes are renamed
- * or moved.
- *
- * @param attribute the manifest attribute
- * @return true if this attribute can describe a class
- */
- public static boolean isManifestClassAttribute(@NonNull Attr attribute) {
- return isManifestClassAttribute(
- attribute.getOwnerElement().getTagName(),
- attribute.getNamespaceURI(),
- attribute.getLocalName());
- }
-
- /**
- * Returns whether the given manifest attribute should be considered to describe
- * a class name. These will be eligible for refactoring when classes are renamed
- * or moved.
- *
- * @param tag the tag, if known
- * @param uri the attribute namespace, if any
- * @param name the attribute local name, if any
- * @return true if this attribute can describe a class
- */
- public static boolean isManifestClassAttribute(
- @Nullable String tag,
- @Nullable String uri,
- @Nullable String name) {
- if (name == null) {
- return false;
- }
-
- if ((name.equals(ATTR_NAME)
- && (AndroidManifest.NODE_ACTIVITY.equals(tag)
- || AndroidManifest.NODE_APPLICATION.equals(tag)
- || AndroidManifest.NODE_INSTRUMENTATION.equals(tag)
- || AndroidManifest.NODE_PROVIDER.equals(tag)
- || AndroidManifest.NODE_SERVICE.equals(tag)
- || AndroidManifest.NODE_RECEIVER.equals(tag)))
- || name.equals(ATTRIBUTE_TARGET_ACTIVITY)
- || name.equals(ATTRIBUTE_MANAGE_SPACE_ACTIVITY)
- || name.equals(ATTRIBUTE_BACKUP_AGENT)
- || name.equals(ATTRIBUTE_PARENT_ACTIVITY_NAME)) {
- return ANDROID_URI.equals(uri);
- }
-
- return false;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourcePage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourcePage.java
deleted file mode 100644
index 6779fd322..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourcePage.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.refactorings.core;
-
-import static com.android.SdkConstants.PREFIX_RESOURCE_REF;
-import static com.android.SdkConstants.R_CLASS;
-
-import com.android.ide.eclipse.adt.internal.resources.ResourceNameValidator;
-import com.android.resources.ResourceType;
-
-import org.eclipse.jdt.internal.ui.refactoring.TextInputWizardPage;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-
-import java.util.Set;
-
-@SuppressWarnings("restriction") // JDT refactoring UI
-class RenameResourcePage extends TextInputWizardPage implements SelectionListener {
- private Label mXmlLabel;
- private Label mJavaLabel;
- private Button mUpdateReferences;
- private boolean mCanClear;
- private ResourceType mType;
- private ResourceNameValidator mValidator;
-
- /**
- * Create the wizard.
- * @param type the type of the resource to be renamed
- * @param initial initial renamed value
- * @param canClear whether the dialog should allow clearing the field
- */
- public RenameResourcePage(ResourceType type, String initial, boolean canClear) {
- super(type.getName(), true, initial);
- mType = type;
- mCanClear = canClear;
-
- mValidator = ResourceNameValidator.create(false /*allowXmlExtension*/,
- (Set<String>) null, mType);
- }
-
- @SuppressWarnings("unused") // SWT constructors aren't really unused, they have side effects
- @Override
- public void createControl(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
- setControl(container);
- initializeDialogUnits(container);
- container.setLayout(new GridLayout(2, false));
- Label nameLabel = new Label(container, SWT.NONE);
- nameLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- nameLabel.setText("New Name:");
- Text text = super.createTextInputField(container);
- text.selectAll();
- text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- Label xmlLabel = new Label(container, SWT.NONE);
- xmlLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- xmlLabel.setText("XML:");
- mXmlLabel = new Label(container, SWT.NONE);
- mXmlLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
- Label javaLabel = new Label(container, SWT.NONE);
- javaLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- javaLabel.setText("Java:");
- mJavaLabel = new Label(container, SWT.NONE);
- mJavaLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
- new Label(container, SWT.NONE);
- new Label(container, SWT.NONE);
- mUpdateReferences = new Button(container, SWT.CHECK);
- mUpdateReferences.setSelection(true);
- mUpdateReferences.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
- mUpdateReferences.setText("Update References");
- mUpdateReferences.addSelectionListener(this);
-
- Dialog.applyDialogFont(container);
- }
-
- @Override
- public void setVisible(boolean visible) {
- if (visible) {
- RenameResourceProcessor processor = getProcessor();
- String newName = processor.getNewName();
- if (newName != null && newName.length() > 0
- && !newName.equals(getInitialValue())) {
- Text textField = getTextField();
- textField.setText(newName);
- textField.setSelection(0, newName.length());
- }
- }
-
- super.setVisible(visible);
- }
-
- @Override
- protected RefactoringStatus validateTextField(String newName) {
- if (newName.isEmpty() && isEmptyInputValid()) {
- getProcessor().setNewName("");
- return RefactoringStatus.createWarningStatus(
- "The resource definition will be deleted");
- }
-
- String error = mValidator.isValid(newName);
- if (error != null) {
- return RefactoringStatus.createErrorStatus(error);
- }
-
- RenameResourceProcessor processor = getProcessor();
- processor.setNewName(newName);
- return processor.checkNewName(newName);
- }
-
- private RenameResourceProcessor getProcessor() {
- RenameRefactoring refactoring = (RenameRefactoring) getRefactoring();
- return (RenameResourceProcessor) refactoring.getProcessor();
- }
-
- @Override
- protected boolean isEmptyInputValid() {
- return mCanClear;
- }
-
- @Override
- protected boolean isInitialInputValid() {
- RenameResourceProcessor processor = getProcessor();
- return processor.getNewName() != null
- && !processor.getNewName().equals(processor.getCurrentName());
- }
-
- @Override
- protected void textModified(String text) {
- super.textModified(text);
- if (mXmlLabel != null && mJavaLabel != null) {
- String xml = PREFIX_RESOURCE_REF + mType.getName() + '/' + text;
- String java = R_CLASS + '.' + mType.getName() + '.' + text;
- if (text.isEmpty()) {
- xml = java = "";
- }
- mXmlLabel.setText(xml);
- mJavaLabel.setText(java);
- }
- }
-
- // ---- Implements SelectionListener ----
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (e.getSource() == mUpdateReferences) {
- RenameResourceProcessor processor = getProcessor();
- boolean update = mUpdateReferences.getSelection();
- processor.setUpdateReferences(update);
- }
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourceParticipant.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourceParticipant.java
deleted file mode 100644
index 438e82223..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourceParticipant.java
+++ /dev/null
@@ -1,752 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.refactorings.core;
-
-import static com.android.SdkConstants.ANDROID_PREFIX;
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ATTR_NAME;
-import static com.android.SdkConstants.ATTR_TYPE;
-import static com.android.SdkConstants.DOT_XML;
-import static com.android.SdkConstants.EXT_XML;
-import static com.android.SdkConstants.FD_RES;
-import static com.android.SdkConstants.FN_RESOURCE_CLASS;
-import static com.android.SdkConstants.NEW_ID_PREFIX;
-import static com.android.SdkConstants.PREFIX_RESOURCE_REF;
-import static com.android.SdkConstants.PREFIX_THEME_REF;
-import static com.android.SdkConstants.R_CLASS;
-import static com.android.SdkConstants.TAG_ITEM;
-import static com.android.SdkConstants.TOOLS_URI;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.resources.ResourceNameValidator;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.resources.ResourceFolderType;
-import com.android.resources.ResourceType;
-import com.android.utils.SdkUtils;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.jdt.core.IField;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.internal.corext.refactoring.rename.RenameFieldProcessor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.RenameParticipant;
-import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
-import org.eclipse.ltk.core.refactoring.resource.RenameResourceChange;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.sse.core.StructuredModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * A rename participant handling renames of resources (such as R.id.foo and R.layout.bar).
- * This reacts to refactorings of fields in the R inner classes (such as R.id), and updates
- * the XML files as appropriate; renaming .xml files, updating XML attributes, resource
- * references in style declarations, and so on.
- */
-@SuppressWarnings("restriction") // WTP API
-public class RenameResourceParticipant extends RenameParticipant {
- /** The project we're refactoring in */
- private @NonNull IProject mProject;
-
- /** The type of the resource we're refactoring, such as {@link ResourceType#ID} */
- private @NonNull ResourceType mType;
- /**
- * The type of the resource folder we're refactoring in, such as
- * {@link ResourceFolderType#VALUES}. When refactoring non value files, we need to
- * rename the files as well.
- */
- private @NonNull ResourceFolderType mFolderType;
-
- /** The previous name of the resource */
- private @NonNull String mOldName;
-
- /** The new name of the resource */
- private @NonNull String mNewName;
-
- /** Whether references to the resource should be updated */
- private boolean mUpdateReferences;
-
- /** A match pattern to look for in XML, such as {@code @attr/foo} */
- private @NonNull String mXmlMatch1;
-
- /** A match pattern to look for in XML, such as {@code ?attr/foo} */
- private @Nullable String mXmlMatch2;
-
- /** A match pattern to look for in XML, such as {@code ?foo} */
- private @Nullable String mXmlMatch3;
-
- /** The value to replace a reference to {@link #mXmlMatch1} with, such as {@code @attr/bar} */
- private @NonNull String mXmlNewValue1;
-
- /** The value to replace a reference to {@link #mXmlMatch2} with, such as {@code ?attr/bar} */
- private @Nullable String mXmlNewValue2;
-
- /** The value to replace a reference to {@link #mXmlMatch3} with, such as {@code ?bar} */
- private @Nullable String mXmlNewValue3;
-
- /**
- * If non null, this refactoring was initiated as a file rename of an XML file (and if
- * null, we are just reacting to a Java field rename)
- */
- private IFile mRenamedFile;
-
- /**
- * If renaming a field, we need to create an embedded field refactoring to update the
- * Java sources referring to the corresponding R class field. This is stored as an
- * instance such that we can have it participate in both the condition check methods
- * as well as the {@link #createChange(IProgressMonitor)} refactoring operation.
- */
- private RenameRefactoring mFieldRefactoring;
-
- /**
- * Set while we are creating an embedded Java refactoring. This could cause a recursive
- * invocation of the XML renaming refactoring to react to the field, so this is flag
- * during the call to the Java processor, and is used to ignore requests for adding in
- * field reactions during that time.
- */
- private static boolean sIgnore;
-
- /**
- * Creates a new {@linkplain RenameResourceParticipant}
- */
- public RenameResourceParticipant() {
- }
-
- @Override
- public String getName() {
- return "Android Rename Field Participant";
- }
-
- @Override
- protected boolean initialize(Object element) {
- if (sIgnore) {
- return false;
- }
-
- if (element instanceof IField) {
- IField field = (IField) element;
- IType declaringType = field.getDeclaringType();
- if (declaringType != null) {
- if (R_CLASS.equals(declaringType.getParent().getElementName())) {
- String typeName = declaringType.getElementName();
- mType = ResourceType.getEnum(typeName);
- if (mType != null) {
- mUpdateReferences = getArguments().getUpdateReferences();
- mFolderType = AdtUtils.getFolderTypeFor(mType);
- IJavaProject javaProject = (IJavaProject) field.getAncestor(
- IJavaElement.JAVA_PROJECT);
- mProject = javaProject.getProject();
- mOldName = field.getElementName();
- mNewName = getArguments().getNewName();
- mFieldRefactoring = null;
- mRenamedFile = null;
- createXmlSearchPatterns();
- return true;
- }
- }
- }
-
- return false;
- } else if (element instanceof IFile) {
- IFile file = (IFile) element;
- mProject = file.getProject();
- if (BaseProjectHelper.isAndroidProject(mProject)) {
- IPath path = file.getFullPath();
- int segments = path.segmentCount();
- if (segments == 4 && path.segment(1).equals(FD_RES)) {
- String parentName = file.getParent().getName();
- mFolderType = ResourceFolderType.getFolderType(parentName);
- if (mFolderType != null && mFolderType != ResourceFolderType.VALUES) {
- mType = AdtUtils.getResourceTypeFor(mFolderType);
- if (mType != null) {
- mUpdateReferences = getArguments().getUpdateReferences();
- mProject = file.getProject();
- mOldName = AdtUtils.stripAllExtensions(file.getName());
- mNewName = AdtUtils.stripAllExtensions(getArguments().getNewName());
- mRenamedFile = file;
- createXmlSearchPatterns();
-
- mFieldRefactoring = null;
- IField field = getResourceField(mProject, mType, mOldName);
- if (field != null) {
- mFieldRefactoring = createFieldRefactoring(field);
- } else {
- // no corresponding field; aapt has not run yet. Perhaps user has
- // turned off auto build.
- mFieldRefactoring = null;
- }
-
- return true;
- }
- }
- }
- }
- } else if (element instanceof String) {
- String uri = (String) element;
- if (uri.startsWith(PREFIX_RESOURCE_REF) && !uri.startsWith(ANDROID_PREFIX)) {
- RenameResourceProcessor processor = (RenameResourceProcessor) getProcessor();
- mProject = processor.getProject();
- mType = processor.getType();
- mFolderType = AdtUtils.getFolderTypeFor(mType);
- mOldName = processor.getCurrentName();
- mNewName = processor.getNewName();
- assert uri.endsWith(mOldName) && uri.contains(mType.getName()) : uri;
- mUpdateReferences = getArguments().getUpdateReferences();
- if (mNewName.isEmpty()) {
- mUpdateReferences = false;
- }
- mRenamedFile = null;
- createXmlSearchPatterns();
- mFieldRefactoring = null;
- if (!mNewName.isEmpty()) {
- IField field = getResourceField(mProject, mType, mOldName);
- if (field != null) {
- mFieldRefactoring = createFieldRefactoring(field);
- }
- }
-
- return true;
- }
- }
-
- return false;
- }
-
- /** Create nested Java refactoring which updates the R field references, if applicable */
- private RenameRefactoring createFieldRefactoring(IField field) {
- return createFieldRefactoring(field, mNewName, mUpdateReferences);
- }
-
- /**
- * Create nested Java refactoring which updates the R field references, if
- * applicable
- *
- * @param field the field to be refactored
- * @param newName the new name
- * @param updateReferences whether references should be updated
- * @return a new rename refactoring
- */
- public static RenameRefactoring createFieldRefactoring(
- @NonNull IField field,
- @NonNull String newName,
- boolean updateReferences) {
- RenameFieldProcessor processor = new RenameFieldProcessor(field);
- processor.setRenameGetter(false);
- processor.setRenameSetter(false);
- RenameRefactoring refactoring = new RenameRefactoring(processor);
- processor.setUpdateReferences(updateReferences);
- processor.setUpdateTextualMatches(false);
- processor.setNewElementName(newName);
- try {
- if (refactoring.isApplicable()) {
- return refactoring;
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
-
- return null;
- }
-
- private void createXmlSearchPatterns() {
- // Set up search strings for the attribute iterator. This will
- // identify string matches for mXmlMatch1, 2 and 3, and when matched,
- // will add a replacement edit for mXmlNewValue1, 2, or 3.
- mXmlMatch2 = null;
- mXmlNewValue2 = null;
- mXmlMatch3 = null;
- mXmlNewValue3 = null;
-
- String typeName = mType.getName();
- if (mUpdateReferences) {
- mXmlMatch1 = PREFIX_RESOURCE_REF + typeName + '/' + mOldName;
- mXmlNewValue1 = PREFIX_RESOURCE_REF + typeName + '/' + mNewName;
- if (mType == ResourceType.ID) {
- mXmlMatch2 = NEW_ID_PREFIX + mOldName;
- mXmlNewValue2 = NEW_ID_PREFIX + mNewName;
- } else if (mType == ResourceType.ATTR) {
- // When renaming @attr/foo, also edit ?attr/foo
- mXmlMatch2 = PREFIX_THEME_REF + typeName + '/' + mOldName;
- mXmlNewValue2 = PREFIX_THEME_REF + typeName + '/' + mNewName;
- // as well as ?foo
- mXmlMatch3 = PREFIX_THEME_REF + mOldName;
- mXmlNewValue3 = PREFIX_THEME_REF + mNewName;
- }
- } else if (mType == ResourceType.ID) {
- mXmlMatch1 = NEW_ID_PREFIX + mOldName;
- mXmlNewValue1 = NEW_ID_PREFIX + mNewName;
- }
- }
-
- @Override
- public RefactoringStatus checkConditions(IProgressMonitor pm, CheckConditionsContext context)
- throws OperationCanceledException {
- if (mRenamedFile != null && getArguments().getNewName().indexOf('.') == -1
- && mRenamedFile.getName().indexOf('.') != -1) {
- return RefactoringStatus.createErrorStatus(
- String.format("You must include the file extension (%1$s?)",
- mRenamedFile.getName().substring(mRenamedFile.getName().indexOf('.'))));
- }
-
- // Ensure that the new name is valid
- if (mNewName != null && !mNewName.isEmpty()) {
- ResourceNameValidator validator = ResourceNameValidator.create(false, mProject, mType);
- String error = validator.isValid(mNewName);
- if (error != null) {
- return RefactoringStatus.createErrorStatus(error);
- }
- }
-
- if (mFieldRefactoring != null) {
- try {
- sIgnore = true;
- return mFieldRefactoring.checkAllConditions(pm);
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- } finally {
- sIgnore = false;
- }
- }
-
- return new RefactoringStatus();
- }
-
- @Override
- public Change createChange(IProgressMonitor monitor) throws CoreException,
- OperationCanceledException {
- if (monitor.isCanceled()) {
- return null;
- }
-
- CompositeChange result = new CompositeChange("Update resource references");
-
- // Only show the children in the refactoring preview dialog
- result.markAsSynthetic();
-
- addResourceFileChanges(result, mProject, monitor);
-
- // If renaming resources in a library project, also offer to rename references
- // in including projects
- if (mUpdateReferences) {
- ProjectState projectState = Sdk.getProjectState(mProject);
- if (projectState != null && projectState.isLibrary()) {
- List<ProjectState> parentProjects = projectState.getParentProjects();
- for (ProjectState state : parentProjects) {
- IProject project = state.getProject();
- CompositeChange nested = new CompositeChange(
- String.format("Update references in %1$s", project.getName()));
- addResourceFileChanges(nested, project, monitor);
- if (nested.getChildren().length > 0) {
- result.add(nested);
- }
- }
- }
- }
-
- if (mFieldRefactoring != null) {
- // We have to add in Java field refactoring
- try {
- sIgnore = true;
- addJavaChanges(result, monitor);
- } finally {
- sIgnore = false;
- }
- } else {
- // Disable field refactoring added by the default Java field rename handler
- disableExistingResourceFileChange();
- }
-
- return (result.getChildren().length == 0) ? null : result;
- }
-
- /**
- * Adds all changes to resource files (typically XML but also renaming drawable files
- *
- * @param project the Android project
- * @param className the layout classes
- */
- private void addResourceFileChanges(
- CompositeChange change,
- IProject project,
- IProgressMonitor monitor)
- throws OperationCanceledException {
- if (monitor.isCanceled()) {
- return;
- }
-
- try {
- // Update resource references in the manifest
- IFile manifest = project.getFile(SdkConstants.ANDROID_MANIFEST_XML);
- if (manifest != null) {
- addResourceXmlChanges(manifest, change, null);
- }
-
- // Update references in XML resource files
- IFolder resFolder = project.getFolder(SdkConstants.FD_RESOURCES);
-
- IResource[] folders = resFolder.members();
- for (IResource folder : folders) {
- if (!(folder instanceof IFolder)) {
- continue;
- }
- String folderName = folder.getName();
- ResourceFolderType folderType = ResourceFolderType.getFolderType(folderName);
- IResource[] files = ((IFolder) folder).members();
- for (int i = 0; i < files.length; i++) {
- IResource member = files[i];
- if ((member instanceof IFile) && member.exists()) {
- IFile file = (IFile) member;
- String fileName = member.getName();
-
- if (SdkUtils.endsWith(fileName, DOT_XML)) {
- addResourceXmlChanges(file, change, folderType);
- }
-
- if ((mRenamedFile == null || !mRenamedFile.equals(file))
- && fileName.startsWith(mOldName)
- && fileName.length() > mOldName.length()
- && fileName.charAt(mOldName.length()) == '.'
- && mFolderType != ResourceFolderType.VALUES
- && mFolderType == folderType) {
- // Rename this file
- String newFile = mNewName + fileName.substring(mOldName.length());
- IPath path = file.getFullPath();
- change.add(new RenameResourceChange(path, newFile));
- }
- }
- }
- }
- } catch (CoreException e) {
- RefactoringUtil.log(e);
- }
- }
-
- private void addJavaChanges(CompositeChange result, IProgressMonitor monitor)
- throws CoreException, OperationCanceledException {
- if (monitor.isCanceled()) {
- return;
- }
-
- RefactoringStatus status = mFieldRefactoring.checkAllConditions(monitor);
- if (status != null && !status.hasError()) {
- Change fieldChanges = mFieldRefactoring.createChange(monitor);
- if (fieldChanges != null) {
- result.add(fieldChanges);
-
- // Look for the field change on the R.java class; it's a derived file
- // and will generate file modified manually warnings. Disable it.
- disableRClassChanges(fieldChanges);
- }
- }
- }
-
- private boolean addResourceXmlChanges(
- IFile file,
- CompositeChange changes,
- ResourceFolderType folderType) {
- IModelManager modelManager = StructuredModelManager.getModelManager();
- IStructuredModel model = null;
- try {
- model = modelManager.getExistingModelForRead(file);
- if (model == null) {
- model = modelManager.getModelForRead(file);
- }
- if (model != null) {
- IStructuredDocument document = model.getStructuredDocument();
- if (model instanceof IDOMModel) {
- IDOMModel domModel = (IDOMModel) model;
- Element root = domModel.getDocument().getDocumentElement();
- if (root != null) {
- List<TextEdit> edits = new ArrayList<TextEdit>();
- addReplacements(edits, root, document, folderType);
- if (!edits.isEmpty()) {
- MultiTextEdit rootEdit = new MultiTextEdit();
- rootEdit.addChildren(edits.toArray(new TextEdit[edits.size()]));
- TextFileChange change = new TextFileChange(file.getName(), file);
- change.setTextType(EXT_XML);
- change.setEdit(rootEdit);
- changes.add(change);
- }
- }
- } else {
- return false;
- }
- }
-
- return true;
- } catch (IOException e) {
- AdtPlugin.log(e, null);
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- } finally {
- if (model != null) {
- model.releaseFromRead();
- }
- }
-
- return false;
- }
-
- private void addReplacements(
- @NonNull List<TextEdit> edits,
- @NonNull Element element,
- @NonNull IStructuredDocument document,
- @Nullable ResourceFolderType folderType) {
- String tag = element.getTagName();
- if (folderType == ResourceFolderType.VALUES) {
- // Look for
- // <item name="main_layout" type="layout">...</item>
- // <item name="myid" type="id"/>
- // <string name="mystring">...</string>
- // etc
- if (tag.equals(mType.getName())
- || (tag.equals(TAG_ITEM)
- && (mType == ResourceType.ID
- || mType.getName().equals(element.getAttribute(ATTR_TYPE))))) {
- Attr nameNode = element.getAttributeNode(ATTR_NAME);
- if (nameNode != null && nameNode.getValue().equals(mOldName)) {
- int start = RefactoringUtil.getAttributeValueRangeStart(nameNode, document);
- if (start != -1) {
- int end = start + mOldName.length();
- edits.add(new ReplaceEdit(start, end - start, mNewName));
- }
- }
- }
- }
-
- NamedNodeMap attributes = element.getAttributes();
- for (int i = 0, n = attributes.getLength(); i < n; i++) {
- Attr attr = (Attr) attributes.item(i);
- String value = attr.getValue();
-
- // If not updating references, only update XML matches that define the id
- if (!mUpdateReferences && (!ATTR_ID.equals(attr.getLocalName()) ||
- !ANDROID_URI.equals(attr.getNamespaceURI()))) {
-
- if (TOOLS_URI.equals(attr.getNamespaceURI()) && value.equals(mXmlMatch1)) {
- int start = RefactoringUtil.getAttributeValueRangeStart(attr, document);
- if (start != -1) {
- int end = start + mXmlMatch1.length();
- edits.add(new ReplaceEdit(start, end - start, mXmlNewValue1));
- }
- }
-
- continue;
- }
-
- // Replace XML attribute reference, such as
- // android:id="@+id/oldName" => android:id="+id/newName"
-
- String match = null;
- String matchedValue = null;
-
- if (value.equals(mXmlMatch1)) {
- match = mXmlMatch1;
- matchedValue = mXmlNewValue1;
- } else if (value.equals(mXmlMatch2)) {
- match = mXmlMatch2;
- matchedValue = mXmlNewValue2;
- } else if (value.equals(mXmlMatch3)) {
- match = mXmlMatch3;
- matchedValue = mXmlNewValue3;
- } else {
- continue;
- }
-
- if (match != null) {
- if (mNewName.isEmpty() && ATTR_ID.equals(attr.getLocalName()) &&
- ANDROID_URI.equals(attr.getNamespaceURI())) {
- // Delete attribute
- IndexedRegion region = (IndexedRegion) attr;
- int start = region.getStartOffset();
- int end = region.getEndOffset();
- edits.add(new ReplaceEdit(start, end - start, ""));
- } else {
- int start = RefactoringUtil.getAttributeValueRangeStart(attr, document);
- if (start != -1) {
- int end = start + match.length();
- edits.add(new ReplaceEdit(start, end - start, matchedValue));
- }
- }
- }
- }
-
- NodeList children = element.getChildNodes();
- for (int i = 0, n = children.getLength(); i < n; i++) {
- Node child = children.item(i);
- if (child.getNodeType() == Node.ELEMENT_NODE) {
- addReplacements(edits, (Element) child, document, folderType);
- } else if (child.getNodeType() == Node.TEXT_NODE && mUpdateReferences) {
- // Replace XML text, such as @color/custom_theme_color in
- // <item name="android:windowBackground">@color/custom_theme_color</item>
- //
- String text = child.getNodeValue();
- int index = getFirstNonBlankIndex(text);
- if (index != -1) {
- String match = null;
- String matchedValue = null;
- if (mXmlMatch1 != null
- && text.startsWith(mXmlMatch1) && text.trim().equals(mXmlMatch1)) {
- match = mXmlMatch1;
- matchedValue = mXmlNewValue1;
- } else if (mXmlMatch2 != null
- && text.startsWith(mXmlMatch2) && text.trim().equals(mXmlMatch2)) {
- match = mXmlMatch2;
- matchedValue = mXmlNewValue2;
- } else if (mXmlMatch3 != null
- && text.startsWith(mXmlMatch3) && text.trim().equals(mXmlMatch3)) {
- match = mXmlMatch3;
- matchedValue = mXmlNewValue3;
- }
- if (match != null) {
- IndexedRegion region = (IndexedRegion) child;
- int start = region.getStartOffset() + index;
- int end = start + match.length();
- edits.add(new ReplaceEdit(start, end - start, matchedValue));
- }
- }
- }
- }
- }
-
- /**
- * Returns the index of the first non-space character in the string, or -1
- * if the string is empty or has only whitespace
- *
- * @param s the string to check
- * @return the index of the first non whitespace character
- */
- private int getFirstNonBlankIndex(String s) {
- for (int i = 0, n = s.length(); i < n; i++) {
- if (!Character.isWhitespace(s.charAt(i))) {
- return i;
- }
- }
-
- return -1;
- }
-
- /**
- * Initiates a renaming of a resource item
- *
- * @param project the project containing the resource references
- * @param type the type of resource
- * @param name the name of the resource
- * @return false if initiating the rename failed
- */
- @Nullable
- private static IField getResourceField(
- @NonNull IProject project,
- @NonNull ResourceType type,
- @NonNull String name) {
- try {
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
- if (javaProject == null) {
- return null;
- }
-
- String pkg = ManifestInfo.get(project).getPackage();
- // TODO: Rename in all libraries too?
- IType t = javaProject.findType(pkg + '.' + R_CLASS + '.' + type.getName());
- if (t == null) {
- return null;
- }
-
- return t.getField(name);
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
-
- return null;
- }
-
- /**
- * Searches for existing changes in the refactoring which modifies the R
- * field to rename it. it's derived so performing this change will generate
- * a "generated code was modified manually" warning
- */
- private void disableExistingResourceFileChange() {
- IFolder genFolder = mProject.getFolder(SdkConstants.FD_GEN_SOURCES);
- if (genFolder != null && genFolder.exists()) {
- ManifestInfo manifestInfo = ManifestInfo.get(mProject);
- String pkg = manifestInfo.getPackage();
- if (pkg != null) {
- IFile rFile = genFolder.getFile(pkg.replace('.', '/') + '/' + FN_RESOURCE_CLASS);
- TextChange change = getTextChange(rFile);
- if (change != null) {
- change.setEnabled(false);
- }
- }
- }
- }
-
- /**
- * Searches for existing changes in the refactoring which modifies the R
- * field to rename it. it's derived so performing this change will generate
- * a "generated code was modified manually" warning
- *
- * @param change the change to disable R file changes in
- */
- public static void disableRClassChanges(Change change) {
- if (change.getName().equals(FN_RESOURCE_CLASS)) {
- change.setEnabled(false);
- }
- // Look for the field change on the R.java class; it's a derived file
- // and will generate file modified manually warnings. Disable it.
- if (change instanceof CompositeChange) {
- for (Change outer : ((CompositeChange) change).getChildren()) {
- disableRClassChanges(outer);
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourceProcessor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourceProcessor.java
deleted file mode 100644
index 5ea99411c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourceProcessor.java
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.refactorings.core;
-
-import static com.android.SdkConstants.PREFIX_RESOURCE_REF;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.internal.resources.ResourceNameValidator;
-import com.android.resources.ResourceType;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
-import org.eclipse.ltk.core.refactoring.participants.ParticipantManager;
-import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
-import org.eclipse.ltk.core.refactoring.participants.RenameArguments;
-import org.eclipse.ltk.core.refactoring.participants.RenameProcessor;
-import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
-
-/**
- * A rename processor for Android resources.
- */
-public class RenameResourceProcessor extends RenameProcessor {
- private IProject mProject;
- private ResourceType mType;
- private String mCurrentName;
- private String mNewName;
- private boolean mUpdateReferences = true;
- private ResourceNameValidator mValidator;
- private RenameArguments mRenameArguments;
-
- /**
- * Creates a new rename resource processor.
- *
- * @param project the project containing the renamed resource
- * @param type the type of the resource
- * @param currentName the current name of the resource
- * @param newName the new name of the resource, or null if not known
- */
- public RenameResourceProcessor(
- @NonNull IProject project,
- @NonNull ResourceType type,
- @NonNull String currentName,
- @Nullable String newName) {
- mProject = project;
- mType = type;
- mCurrentName = currentName;
- mNewName = newName != null ? newName : currentName;
- mUpdateReferences= true;
- mValidator = ResourceNameValidator.create(false, mProject, mType);
- }
-
- /**
- * Returns the project containing the renamed resource
- *
- * @return the project containing the renamed resource
- */
- @NonNull
- public IProject getProject() {
- return mProject;
- }
-
- /**
- * Returns the new resource name
- *
- * @return the new resource name
- */
- @NonNull
- public String getNewName() {
- return mNewName;
- }
-
- /**
- * Returns the current name of the resource
- *
- * @return the current name of the resource
- */
- public String getCurrentName() {
- return mCurrentName;
- }
-
- /**
- * Returns the type of the resource
- *
- * @return the type of the resource
- */
- @NonNull
- public ResourceType getType() {
- return mType;
- }
-
- /**
- * Sets the new name
- *
- * @param newName the new name
- */
- public void setNewName(@NonNull String newName) {
- mNewName = newName;
- }
-
- /**
- * Returns {@code true} if the refactoring processor also updates references
- *
- * @return {@code true} if the refactoring processor also updates references
- */
- public boolean isUpdateReferences() {
- return mUpdateReferences;
- }
-
- /**
- * Specifies if the refactoring processor also updates references. The
- * default behavior is to update references.
- *
- * @param updateReferences {@code true} if the refactoring processor should
- * also updates references
- */
- public void setUpdateReferences(boolean updateReferences) {
- mUpdateReferences = updateReferences;
- }
-
- /**
- * Checks the given new potential name and returns a {@link RefactoringStatus} indicating
- * whether the potential new name is valid
- *
- * @param name the name to check
- * @return a {@link RefactoringStatus} with the validation result
- */
- public RefactoringStatus checkNewName(String name) {
- String error = mValidator.isValid(name);
- if (error != null) {
- return RefactoringStatus.createFatalErrorStatus(error);
- }
-
- return new RefactoringStatus();
- }
-
- @Override
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm) throws CoreException {
- return new RefactoringStatus();
- }
-
- @Override
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm,
- CheckConditionsContext context) throws CoreException {
- pm.beginTask("", 1);
- try {
- mRenameArguments = new RenameArguments(getNewName(), isUpdateReferences());
- return new RefactoringStatus();
- } finally {
- pm.done();
- }
- }
-
- @Override
- public Change createChange(IProgressMonitor pm) throws CoreException {
- pm.beginTask("", 1);
- try {
- // Added by {@link RenameResourceParticipant}
- return null;
- } finally {
- pm.done();
- }
- }
-
- @Override
- public Object[] getElements() {
- return new Object[0];
- }
-
- @Override
- public String getIdentifier() {
- return "com.android.ide.renameResourceProcessor"; //$NON-NLS-1$
- }
-
- @Override
- public String getProcessorName() {
- return "Rename Android Resource";
- }
-
- @Override
- public boolean isApplicable() {
- return true;
- }
-
- @Override
- public RefactoringParticipant[] loadParticipants(RefactoringStatus status,
- SharableParticipants shared) throws CoreException {
- String[] affectedNatures = new String[] { AdtConstants.NATURE_DEFAULT };
- String url = PREFIX_RESOURCE_REF + mType.getName() + '/' + mCurrentName;
- return ParticipantManager.loadRenameParticipants(status, this, url, mRenameArguments,
- null, affectedNatures, shared);
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourceWizard.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourceWizard.java
deleted file mode 100644
index 6ffe25d22..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourceWizard.java
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.refactorings.core;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.resources.ResourceType;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
-import org.eclipse.jdt.internal.ui.JavaPluginImages;
-import org.eclipse.jdt.internal.ui.refactoring.reorg.RenameRefactoringWizard;
-import org.eclipse.jdt.ui.refactoring.RefactoringSaveHelper;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
-import org.eclipse.swt.widgets.Shell;
-
-/**
- * Rename refactoring wizard for Android resources such as {@code @id/foo}
- */
-@SuppressWarnings("restriction") // JDT refactoring UI
-public class RenameResourceWizard extends RenameRefactoringWizard {
- private ResourceType mType;
- private boolean mCanClear;
-
- /**
- * Constructs a new {@linkplain RenameResourceWizard}
- *
- * @param refactoring the refactoring
- * @param type the type of resource being renamed
- * @param canClear whether the user can clear the value
- */
- public RenameResourceWizard(
- @NonNull RenameRefactoring refactoring,
- @NonNull ResourceType type,
- boolean canClear) {
- super(refactoring,
- "Rename Resource",
- "Enter the new name for this resource",
- JavaPluginImages.DESC_WIZBAN_REFACTOR_FIELD,
- IJavaHelpContextIds.RENAME_FIELD_WIZARD_PAGE);
- mType = type;
- mCanClear = canClear;
- }
-
- @Override
- protected void addUserInputPages() {
- RenameRefactoring refactoring = (RenameRefactoring) getRefactoring();
- RenameResourceProcessor processor = (RenameResourceProcessor) refactoring.getProcessor();
- String name = processor.getNewName();
- addPage(new RenameResourcePage(mType, name, mCanClear));
- }
-
- /**
- * Initiates a renaming of a resource item
- *
- * @param shell the shell to parent the dialog to
- * @param project the project containing the resource references
- * @param type the type of resource
- * @param currentName the name of the resource
- * @param newName the new name, or null if not known
- * @param canClear whether the name is allowed to be cleared
- * @return false if initiating the rename failed
- */
- public static RenameResult renameResource(
- @NonNull Shell shell,
- @NonNull IProject project,
- @NonNull ResourceType type,
- @NonNull String currentName,
- @Nullable String newName,
- boolean canClear) {
- try {
- RenameResourceProcessor processor = new RenameResourceProcessor(project, type,
- currentName, newName);
- RenameRefactoring refactoring = new RenameRefactoring(processor);
- if (!refactoring.isApplicable()) {
- return RenameResult.unavailable();
- }
-
- if (!show(refactoring, processor, shell, type, canClear)) {
- return RenameResult.canceled();
- }
- return RenameResult.name(processor.getNewName());
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
-
- return RenameResult.unavailable();
- }
-
- /**
- * Show a refactoring dialog for the given resource refactoring operation
- *
- * @param refactoring the rename refactoring
- * @param processor the field processor
- * @param parent the parent shell
- * @param type the resource type
- * @param canClear whether the user is allowed to clear/reset the name to
- * nothing
- * @return true if the refactoring was performed, and false if it was
- * canceled
- * @throws CoreException if an unexpected error occurs
- */
- private static boolean show(
- @NonNull RenameRefactoring refactoring,
- @NonNull RenameResourceProcessor processor,
- @NonNull Shell parent,
- @NonNull ResourceType type,
- boolean canClear) throws CoreException {
- RefactoringSaveHelper saveHelper = new RefactoringSaveHelper(
- RefactoringSaveHelper.SAVE_REFACTORING);
- if (!saveHelper.saveEditors(parent)) {
- return false;
- }
-
- try {
- RenameResourceWizard wizard = new RenameResourceWizard(refactoring, type, canClear);
- RefactoringWizardOpenOperation operation = new RefactoringWizardOpenOperation(wizard);
- String dialogTitle = wizard.getDefaultPageTitle();
- int result = operation.run(parent, dialogTitle == null ? "" : dialogTitle);
- RefactoringStatus status = operation.getInitialConditionCheckingStatus();
- if (status.hasFatalError()) {
- return false;
- }
- if (result == RefactoringWizardOpenOperation.INITIAL_CONDITION_CHECKING_FAILED
- || result == IDialogConstants.CANCEL_ID) {
- saveHelper.triggerIncrementalBuild();
- return false;
- }
-
- // Save modified resources; need to trigger R file regeneration
- saveHelper.saveEditors(parent);
-
- return true;
- } catch (InterruptedException e) {
- return false; // Canceled
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourceXmlTextAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourceXmlTextAction.java
deleted file mode 100644
index 8ecb08836..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourceXmlTextAction.java
+++ /dev/null
@@ -1,410 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.refactorings.core;
-
-import static com.android.SdkConstants.ANDROID_MANIFEST_XML;
-import static com.android.SdkConstants.ANDROID_PREFIX;
-import static com.android.SdkConstants.ANDROID_THEME_PREFIX;
-import static com.android.SdkConstants.ATTR_NAME;
-import static com.android.SdkConstants.ATTR_TYPE;
-import static com.android.SdkConstants.TAG_ITEM;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.resources.ResourceUrl;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.resources.ResourceType;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor;
-import org.eclipse.jdt.internal.ui.refactoring.reorg.RenameTypeWizard;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.ui.texteditor.ITextEditor;
-import org.eclipse.ui.texteditor.ITextEditorExtension;
-import org.eclipse.ui.texteditor.ITextEditorExtension2;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-import java.util.List;
-
-/**
- * Text action for XML files to invoke renaming
- * <p>
- * TODO: Handle other types of renaming: invoking class renaming when editing
- * class names in layout files and manifest files, renaming attribute names when
- * editing a styleable attribute, etc.
- */
-@SuppressWarnings("restriction") // Java rename refactoring
-public final class RenameResourceXmlTextAction extends Action {
- private final ITextEditor mEditor;
-
- /**
- * Creates a new {@linkplain RenameResourceXmlTextAction}
- *
- * @param editor the associated editor
- */
- public RenameResourceXmlTextAction(@NonNull ITextEditor editor) {
- super("Rename");
- mEditor = editor;
- }
-
- @Override
- public void run() {
- if (!validateEditorInputState()) {
- return;
- }
- IFile file = getFile();
- if (file == null) {
- return;
- }
- IProject project = file.getProject();
- if (project == null) {
- return;
- }
- IDocument document = getDocument();
- if (document == null) {
- return;
- }
- ITextSelection selection = getSelection();
- if (selection == null) {
- return;
- }
-
- ResourceUrl resource = findResource(document, selection.getOffset());
-
- if (resource == null) {
- resource = findItemDefinition(document, selection.getOffset());
- }
-
- if (resource != null) {
- ResourceType type = resource.type;
- String name = resource.name;
- Shell shell = mEditor.getSite().getShell();
- boolean canClear = false;
-
- RenameResourceWizard.renameResource(shell, project, type, name, null, canClear);
- return;
- }
-
- String className = findClassName(document, file, selection.getOffset());
- if (className != null) {
- assert className.equals(className.trim());
- IType type = findType(className, project);
- if (type != null) {
- RenameTypeProcessor processor = new RenameTypeProcessor(type);
- //processor.setNewElementName(className);
- processor.setUpdateQualifiedNames(true);
- processor.setUpdateSimilarDeclarations(false);
- //processor.setMatchStrategy(?);
- //processor.setFilePatterns(patterns);
- processor.setUpdateReferences(true);
-
- RenameRefactoring refactoring = new RenameRefactoring(processor);
- RenameTypeWizard wizard = new RenameTypeWizard(refactoring);
- RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation(wizard);
- try {
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- op.run(window.getShell(), wizard.getDefaultPageTitle());
- } catch (InterruptedException e) {
- }
- }
-
- return;
- }
-
- // Fallback: tell user the cursor isn't in the right place
- MessageDialog.openInformation(mEditor.getSite().getShell(),
- "Rename",
- "Operation unavailable on the current selection.\n"
- + "Select an Android resource name or class.");
- }
-
- private boolean validateEditorInputState() {
- if (mEditor instanceof ITextEditorExtension2)
- return ((ITextEditorExtension2) mEditor).validateEditorInputState();
- else if (mEditor instanceof ITextEditorExtension)
- return !((ITextEditorExtension) mEditor).isEditorInputReadOnly();
- else if (mEditor != null)
- return mEditor.isEditable();
- else
- return false;
- }
-
- /**
- * Searches for a resource URL around the caret, such as {@code @string/foo}
- *
- * @param document the document to search in
- * @param offset the offset to search at
- * @return a resource pair, or null if not found
- */
- @Nullable
- public static ResourceUrl findResource(@NonNull IDocument document, int offset) {
- try {
- int max = document.getLength();
- if (offset >= max) {
- offset = max - 1;
- } else if (offset < 0) {
- offset = 0;
- } else if (offset > 0) {
- // If the caret is right after a resource name (meaning getChar(offset) points
- // to the following character), back up
- char c = document.getChar(offset);
- if (!isValidResourceNameChar(c)) {
- offset--;
- }
- }
-
- int start = offset;
- boolean valid = true;
- for (; start >= 0; start--) {
- char c = document.getChar(start);
- if (c == '@' || c == '?') {
- break;
- } else if (!isValidResourceNameChar(c)) {
- valid = false;
- break;
- }
- }
- if (valid) {
- // Search forwards for the end
- int end = start + 1;
- for (; end < max; end++) {
- char c = document.getChar(end);
- if (!isValidResourceNameChar(c)) {
- break;
- }
- }
- if (end > start + 1) {
- String url = document.get(start, end - start);
-
- // Don't allow renaming framework resources -- @android:string/ok etc
- if (url.startsWith(ANDROID_PREFIX) || url.startsWith(ANDROID_THEME_PREFIX)) {
- return null;
- }
-
- return ResourceUrl.parse(url);
- }
- }
- } catch (BadLocationException e) {
- AdtPlugin.log(e, null);
- }
-
- return null;
- }
-
- private static boolean isValidResourceNameChar(char c) {
- return c == '@' || c == '?' || c == '/' || c == '+' || Character.isJavaIdentifierPart(c);
- }
-
- /**
- * Searches for an item definition around the caret, such as
- * {@code <string name="foo">My String</string>}
- */
- private ResourceUrl findItemDefinition(IDocument document, int offset) {
- Node node = DomUtilities.getNode(document, offset);
- if (node == null) {
- return null;
- }
- if (node.getNodeType() == Node.TEXT_NODE) {
- node = node.getParentNode();
- }
- if (node == null || node.getNodeType() != Node.ELEMENT_NODE) {
- return null;
- }
-
- Element element = (Element) node;
- String name = element.getAttribute(ATTR_NAME);
- if (name == null || name.isEmpty()) {
- return null;
- }
- String typeString = element.getTagName();
- if (TAG_ITEM.equals(typeString)) {
- typeString = element.getAttribute(ATTR_TYPE);
- if (typeString == null || typeString.isEmpty()) {
- return null;
- }
- }
- ResourceType type = ResourceType.getEnum(typeString);
- if (type != null) {
- return ResourceUrl.create(type, name, false, false);
- }
-
- return null;
- }
-
- /**
- * Searches for a fully qualified class name around the caret, such as {@code foo.bar.MyClass}
- *
- * @param document the document to search in
- * @param file the file, if known
- * @param offset the offset to search at
- * @return a resource pair, or null if not found
- */
- @Nullable
- public static String findClassName(
- @NonNull IDocument document,
- @Nullable IFile file,
- int offset) {
- try {
- int max = document.getLength();
- if (offset >= max) {
- offset = max - 1;
- } else if (offset < 0) {
- offset = 0;
- } else if (offset > 0) {
- // If the caret is right after a resource name (meaning getChar(offset) points
- // to the following character), back up
- char c = document.getChar(offset);
- if (Character.isJavaIdentifierPart(c)) {
- offset--;
- }
- }
-
- int start = offset;
- for (; start >= 0; start--) {
- char c = document.getChar(start);
- if (c == '"' || c == '<' || c == '/') {
- start++;
- break;
- } else if (c != '.' && !Character.isJavaIdentifierPart(c)) {
- return null;
- }
- }
- // Search forwards for the end
- int end = start + 1;
- for (; end < max; end++) {
- char c = document.getChar(end);
- if (c != '.' && !Character.isJavaIdentifierPart(c)) {
- if (c != '"' && c != '>' && !Character.isWhitespace(c)) {
- return null;
- }
- break;
- }
- }
- if (end > start + 1) {
- String fqcn = document.get(start, end - start);
- int dot = fqcn.indexOf('.');
- if (dot == -1) { // Only support fully qualified names
- return null;
- }
- if (dot == 0) { // Special case for manifests: prepend package
- if (file != null && file.getName().equals(ANDROID_MANIFEST_XML)) {
- ManifestInfo info = ManifestInfo.get(file.getProject());
- return info.getPackage() + fqcn;
- }
- return null;
- }
-
- return fqcn;
- }
- } catch (BadLocationException e) {
- AdtPlugin.log(e, null);
- }
-
- return null;
- }
-
- @Nullable
- private IType findType(@NonNull String className, @NonNull IProject project) {
- IType type = null;
- try {
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
- type = javaProject.findType(className);
- if (type == null || !type.exists()) {
- return null;
- }
- if (!type.isBinary()) {
- return type;
- }
- // See if this class is coming through a library project jar file and
- // if so locate the real class
- ProjectState projectState = Sdk.getProjectState(project);
- if (projectState != null) {
- List<IProject> libraries = projectState.getFullLibraryProjects();
- for (IProject library : libraries) {
- javaProject = BaseProjectHelper.getJavaProject(library);
- type = javaProject.findType(className);
- if (type != null && type.exists() && !type.isBinary()) {
- return type;
- }
- }
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
-
- return null;
- }
-
- private ITextSelection getSelection() {
- ISelectionProvider selectionProvider = mEditor.getSelectionProvider();
- if (selectionProvider == null) {
- return null;
- }
- ISelection selection = selectionProvider.getSelection();
- if (!(selection instanceof ITextSelection)) {
- return null;
- }
- return (ITextSelection) selection;
- }
-
- private IDocument getDocument() {
- IDocumentProvider documentProvider = mEditor.getDocumentProvider();
- if (documentProvider == null) {
- return null;
- }
- IDocument document = documentProvider.getDocument(mEditor.getEditorInput());
- if (document == null) {
- return null;
- }
- return document;
- }
-
- @Nullable
- private IFile getFile() {
- IEditorInput input = mEditor.getEditorInput();
- if (input instanceof IFileEditorInput) {
- IFileEditorInput fileInput = (IFileEditorInput) input;
- return fileInput.getFile();
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResult.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResult.java
deleted file mode 100644
index ade346fa9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResult.java
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.refactorings.core;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-
-/**
- * A result from a renaming operation
- */
-public class RenameResult {
- private boolean mCanceled;
- private boolean mUnavailable;
- private @Nullable String mName;
- private boolean mClear;
-
- /**
- * Constructs a new rename result
- */
- private RenameResult() {
- }
-
- /**
- * Creates a new blank {@linkplain RenameResult}
- * @return a new result
- */
- @NonNull
- public static RenameResult create() {
- return new RenameResult();
- }
-
- /**
- * Creates a new {@linkplain RenameResult} for a user canceled renaming operation
- * @return a canceled operation
- */
- @NonNull
- public static RenameResult canceled() {
- return new RenameResult().setCanceled(true);
- }
-
- /**
- * Creates a {@linkplain RenameResult} for a renaming operation that was
- * not available (for example because the field attempted to be renamed
- * does not yet exist (or does not exist any more)
- *
- * @return a new result
- */
- @NonNull
- public static RenameResult unavailable() {
- return new RenameResult().setUnavailable(true);
- }
-
- /**
- * Creates a new {@linkplain RenameResult} for a successful renaming
- * operation to the given name
- *
- * @param name the new name
- * @return a new result
- */
- @NonNull
- public static RenameResult name(@Nullable String name) {
- return new RenameResult().setName(name);
- }
-
- /**
- * Marks this result as canceled
- *
- * @param canceled whether the result was canceled
- * @return this, for constructor chaining
- */
- @NonNull
- public RenameResult setCanceled(boolean canceled) {
- mCanceled = canceled;
- return this;
- }
-
- /**
- * Marks this result as unavailable
- *
- * @param unavailable whether this result was unavailable
- * @return this, for constructor chaining
- */
- @NonNull
- public RenameResult setUnavailable(boolean unavailable) {
- mUnavailable = unavailable;
- return this;
- }
-
- /**
- * Sets the new name of the renaming operation
- *
- * @param name the new name
- * @return this, for constructor chaining
- */
- @NonNull
- public RenameResult setName(@Nullable String name) {
- mName = name;
- return this;
- }
-
- /**
- * Marks this result as clearing the name (reverting it back to the default)
- *
- * @param clear whether the name was cleared
- * @return this, for constructor chaining
- */
- @NonNull
- public RenameResult setCleared(boolean clear) {
- mClear = clear;
- return this;
- }
-
- /**
- * Returns whether this result represents a canceled renaming operation
- *
- * @return true if the operation was canceled
- */
- public boolean isCanceled() {
- return mCanceled;
- }
-
- /**
- * Returns whether this result represents an unavailable renaming operation
- *
- * @return true if the operation was not available
- */
- public boolean isUnavailable() {
- return mUnavailable;
- }
-
- /**
- * Returns whether this result represents a renaming back to the default (possibly
- * clear) name. In this case, {@link #getName()} will return {@code null}.
- *
- * @return true if the name should be reset
- */
- public boolean isCleared() {
- return mClear;
- }
-
- /**
- * Returns the new name.
- *
- * @return the new name
- */
- @Nullable
- public String getName() {
- return mName;
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/EnabledTextEditGroup.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/EnabledTextEditGroup.java
deleted file mode 100644
index 15f6c4719..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/EnabledTextEditGroup.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.refactorings.extractstring;
-
-import org.eclipse.text.edits.TextEditGroup;
-
-/**
- * A {@link TextEditGroup} that we want to enable or disable by default.
- * This is used to propose a change that may not compile, so we'll create
- * a change that is disabled.
- * <p/>
- * Disabling the change is done by the refactoring class when processing
- * the text edit groups generated by the Java AST visitor.
- */
-class EnabledTextEditGroup extends TextEditGroup {
- private final boolean mEnabled;
-
- public EnabledTextEditGroup(String name, boolean enabled) {
- super(name);
- mEnabled = enabled;
- }
-
- public boolean isEnabled() {
- return mEnabled;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringAction.java
deleted file mode 100644
index 14556fd9f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringAction.java
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.refactorings.extractstring;
-
-import com.android.ide.eclipse.adt.AdtConstants;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jdt.core.ICompilationUnit;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.part.FileEditorInput;
-
-/*
- * Quick Reference Link:
- * http://www.eclipse.org/articles/article.php?file=Article-Unleashing-the-Power-of-Refactoring/index.html
- * and
- * http://www.ibm.com/developerworks/opensource/library/os-ecjdt/
- */
-
-/**
- * Action executed when the "Extract String" menu item is invoked.
- * <p/>
- * The intent of the action is to start a refactoring that extracts a source string and
- * replaces it by an Android string resource ID.
- * <p/>
- * Workflow:
- * <ul>
- * <li> The action is currently located in the Refactoring menu in the main menu.
- * <li> TODO: extend the popup refactoring menu in a Java or Android XML file.
- * <li> The action is only enabled if the selection is 1 character or more. That is at least part
- * of the string must be selected, it's not enough to just move the insertion point. This is
- * a limitation due to {@link #selectionChanged(IAction, ISelection)} not being called when
- * the insertion point is merely moved. TODO: address this limitation.
- * <ul> The action gets the current {@link ISelection}. It also knows the current
- * {@link IWorkbenchWindow}. However for the refactoring we are also interested in having the
- * actual resource file. By looking at the Active Window > Active Page > Active Editor we
- * can get the {@link IEditorInput} and find the {@link ICompilationUnit} (aka Java file)
- * that is being edited.
- * <ul> TODO: change this to find the {@link IFile} being manipulated. The {@link ICompilationUnit}
- * can be inferred using {@link JavaCore#createCompilationUnitFrom(IFile)}. This will allow
- * us to be able to work with a selection from an Android XML file later.
- * <li> The action creates a new {@link ExtractStringRefactoring} and make it run on in a new
- * {@link ExtractStringWizard}.
- * <ul>
- */
-public class ExtractStringAction implements IWorkbenchWindowActionDelegate {
-
- /** Keep track of the current workbench window. */
- private IWorkbenchWindow mWindow;
- private ITextSelection mSelection;
- private IEditorPart mEditor;
- private IFile mFile;
-
- /**
- * Keep track of the current workbench window.
- */
- @Override
- public void init(IWorkbenchWindow window) {
- mWindow = window;
- }
-
- @Override
- public void dispose() {
- // Nothing to do
- }
-
- /**
- * Examine the selection to determine if the action should be enabled or not.
- * <p/>
- * Keep a link to the relevant selection structure (i.e. a part of the Java AST).
- */
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
-
- // Note, two kinds of selections are returned here:
- // ITextSelection on a Java source window
- // IStructuredSelection in the outline or navigator
- // This simply deals with the refactoring based on a non-empty selection.
- // At that point, just enable the action and later decide if it's valid when it actually
- // runs since we don't have access to the AST yet.
-
- mSelection = null;
- mFile = null;
-
- if (selection instanceof ITextSelection) {
- mSelection = (ITextSelection) selection;
- if (mSelection.getLength() > 0) {
- mEditor = getActiveEditor();
- mFile = getSelectedFile(mEditor);
- }
- }
-
- action.setEnabled(mSelection != null && mFile != null);
- }
-
- /**
- * Create a new instance of our refactoring and a wizard to configure it.
- */
- @Override
- public void run(IAction action) {
- if (mSelection != null && mFile != null) {
- ExtractStringRefactoring ref = new ExtractStringRefactoring(mFile, mEditor, mSelection);
- RefactoringWizard wizard = new ExtractStringWizard(ref, mFile.getProject());
- RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation(wizard);
- try {
- op.run(mWindow.getShell(), wizard.getDefaultPageTitle());
- } catch (InterruptedException e) {
- // Interrupted. Pass.
- }
- }
- }
-
- /**
- * Returns the active editor (hopefully matching our selection) or null.
- */
- private IEditorPart getActiveEditor() {
- IWorkbenchWindow wwin = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- if (wwin != null) {
- IWorkbenchPage page = wwin.getActivePage();
- if (page != null) {
- return page.getActiveEditor();
- }
- }
-
- return null;
- }
-
- /**
- * Returns the active {@link IFile} (hopefully matching our selection) or null.
- * The file is only returned if it's a file from a project with an Android nature.
- * <p/>
- * At that point we do not try to analyze if the selection nor the file is suitable
- * for the refactoring. This check is performed when the refactoring is invoked since
- * it can then produce meaningful error messages as needed.
- */
- private IFile getSelectedFile(IEditorPart editor) {
- if (editor != null) {
- IEditorInput input = editor.getEditorInput();
-
- if (input instanceof FileEditorInput) {
- FileEditorInput fi = (FileEditorInput) input;
- IFile file = fi.getFile();
- if (file.exists()) {
- IProject proj = file.getProject();
- try {
- if (proj != null && proj.hasNature(AdtConstants.NATURE_DEFAULT)) {
- return file;
- }
- } catch (CoreException e) {
- // ignore
- }
- }
- }
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringContribution.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringContribution.java
deleted file mode 100644
index 61bd06e81..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringContribution.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.refactorings.extractstring;
-
-import org.eclipse.ltk.core.refactoring.RefactoringContribution;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-
-import java.util.Map;
-
-/**
- * @see ExtractStringDescriptor
- */
-public class ExtractStringContribution extends RefactoringContribution {
-
- /* (non-Javadoc)
- * @see org.eclipse.ltk.core.refactoring.RefactoringContribution#createDescriptor(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.util.Map, int)
- */
- @SuppressWarnings({"unchecked", "rawtypes"})
- @Override
- public RefactoringDescriptor createDescriptor(
- String id,
- String project,
- String description,
- String comment,
- Map arguments,
- int flags)
- throws IllegalArgumentException {
- return new ExtractStringDescriptor(project, description, comment, arguments);
- }
-
- @SuppressWarnings("rawtypes")
- @Override
- public Map retrieveArgumentMap(RefactoringDescriptor descriptor) {
- if (descriptor instanceof ExtractStringDescriptor) {
- return ((ExtractStringDescriptor) descriptor).getArguments();
- }
- return super.retrieveArgumentMap(descriptor);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringDescriptor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringDescriptor.java
deleted file mode 100644
index 190736aad..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringDescriptor.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.refactorings.extractstring;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-
-import java.util.Map;
-
-/**
- * A descriptor that allows an {@link ExtractStringRefactoring} to be created from
- * a previous instance of itself.
- */
-public class ExtractStringDescriptor extends RefactoringDescriptor {
-
- public static final String ID =
- "com.android.ide.eclipse.adt.refactoring.extract.string"; //$NON-NLS-1$
-
- private final Map<String, String> mArguments;
-
- public ExtractStringDescriptor(String project, String description, String comment,
- Map<String, String> arguments) {
- super(ID, project, description, comment,
- RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE //flags
- );
- mArguments = arguments;
- }
-
- public Map<String, String> getArguments() {
- return mArguments;
- }
-
- /**
- * Creates a new refactoring instance for this refactoring descriptor based on
- * an argument map. The argument map is created by the refactoring itself in
- * {@link ExtractStringRefactoring#createChange(org.eclipse.core.runtime.IProgressMonitor)}
- * <p/>
- * This is apparently used to replay a refactoring.
- *
- * {@inheritDoc}
- *
- * @throws CoreException
- */
- @Override
- public Refactoring createRefactoring(RefactoringStatus status) throws CoreException {
- try {
- ExtractStringRefactoring ref = new ExtractStringRefactoring(mArguments);
- return ref;
- } catch (NullPointerException e) {
- status.addFatalError("Failed to recreate ExtractStringRefactoring from descriptor");
- return null;
- }
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringInputPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringInputPage.java
deleted file mode 100644
index 5ac5f5c4e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringInputPage.java
+++ /dev/null
@@ -1,606 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.refactorings.extractstring;
-
-
-import com.android.SdkConstants;
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.internal.ui.ConfigurationSelector;
-import com.android.ide.eclipse.adt.internal.ui.ConfigurationSelector.SelectorMode;
-import com.android.resources.ResourceFolderType;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.ltk.ui.refactoring.UserInputWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-
-import java.util.HashMap;
-import java.util.Locale;
-import java.util.Map;
-import java.util.TreeSet;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * @see ExtractStringRefactoring
- */
-class ExtractStringInputPage extends UserInputWizardPage {
-
- /** Last res file path used, shared across the session instances but specific to the
- * current project. The default for unknown projects is {@link #DEFAULT_RES_FILE_PATH}. */
- private static HashMap<String, String> sLastResFilePath = new HashMap<String, String>();
-
- /** The project where the user selection happened. */
- private final IProject mProject;
-
- /** Text field where the user enters the new ID to be generated or replaced with. */
- private Combo mStringIdCombo;
- /** Text field where the user enters the new string value. */
- private Text mStringValueField;
- /** The configuration selector, to select the resource path of the XML file. */
- private ConfigurationSelector mConfigSelector;
- /** The combo to display the existing XML files or enter a new one. */
- private Combo mResFileCombo;
- /** Checkbox asking whether to replace in all Java files. */
- private Button mReplaceAllJava;
- /** Checkbox asking whether to replace in all XML files with same name but other res config */
- private Button mReplaceAllXml;
-
- /** Regex pattern to read a valid res XML file path. It checks that the are 2 folders and
- * a leaf file name ending with .xml */
- private static final Pattern RES_XML_FILE_REGEX = Pattern.compile(
- "/res/[a-z][a-zA-Z0-9_-]+/[^.]+\\.xml"); //$NON-NLS-1$
- /** Absolute destination folder root, e.g. "/res/" */
- private static final String RES_FOLDER_ABS =
- AdtConstants.WS_RESOURCES + AdtConstants.WS_SEP;
- /** Relative destination folder root, e.g. "res/" */
- private static final String RES_FOLDER_REL =
- SdkConstants.FD_RESOURCES + AdtConstants.WS_SEP;
-
- private static final String DEFAULT_RES_FILE_PATH = "/res/values/strings.xml"; //$NON-NLS-1$
-
- private XmlStringFileHelper mXmlHelper = new XmlStringFileHelper();
-
- private final OnConfigSelectorUpdated mOnConfigSelectorUpdated = new OnConfigSelectorUpdated();
-
- private ModifyListener mValidateOnModify = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- validatePage();
- }
- };
-
- private SelectionListener mValidateOnSelection = new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- validatePage();
- }
- };
-
- public ExtractStringInputPage(IProject project) {
- super("ExtractStringInputPage"); //$NON-NLS-1$
- mProject = project;
- }
-
- /**
- * Create the UI for the refactoring wizard.
- * <p/>
- * Note that at that point the initial conditions have been checked in
- * {@link ExtractStringRefactoring}.
- * <p/>
- *
- * Note: the special tag below defines this as the entry point for the WindowsDesigner Editor.
- * @wbp.parser.entryPoint
- */
- @Override
- public void createControl(Composite parent) {
- Composite content = new Composite(parent, SWT.NONE);
- GridLayout layout = new GridLayout();
- content.setLayout(layout);
-
- createStringGroup(content);
- createResFileGroup(content);
- createOptionGroup(content);
-
- initUi();
- setControl(content);
- }
-
- /**
- * Creates the top group with the field to replace which string and by what
- * and by which options.
- *
- * @param content A composite with a 1-column grid layout
- */
- public void createStringGroup(Composite content) {
-
- final ExtractStringRefactoring ref = getOurRefactoring();
-
- Group group = new Group(content, SWT.NONE);
- group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- group.setText("New String");
- if (ref.getMode() == ExtractStringRefactoring.Mode.EDIT_SOURCE) {
- group.setText("String Replacement");
- }
-
- GridLayout layout = new GridLayout();
- layout.numColumns = 2;
- group.setLayout(layout);
-
- // line: Textfield for string value (based on selection, if any)
-
- Label label = new Label(group, SWT.NONE);
- label.setText("&String");
-
- String selectedString = ref.getTokenString();
-
- mStringValueField = new Text(group, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
- mStringValueField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mStringValueField.setText(selectedString != null ? selectedString : ""); //$NON-NLS-1$
-
- ref.setNewStringValue(mStringValueField.getText());
-
- mStringValueField.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- validatePage();
- }
- });
-
- // line : Textfield for new ID
-
- label = new Label(group, SWT.NONE);
- label.setText("ID &R.string.");
- if (ref.getMode() == ExtractStringRefactoring.Mode.EDIT_SOURCE) {
- label.setText("&Replace by R.string.");
- } else if (ref.getMode() == ExtractStringRefactoring.Mode.SELECT_NEW_ID) {
- label.setText("New &R.string.");
- }
-
- mStringIdCombo = new Combo(group, SWT.SINGLE | SWT.LEFT | SWT.BORDER | SWT.DROP_DOWN);
- mStringIdCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mStringIdCombo.setText(guessId(selectedString));
- mStringIdCombo.forceFocus();
-
- ref.setNewStringId(mStringIdCombo.getText().trim());
-
- mStringIdCombo.addModifyListener(mValidateOnModify);
- mStringIdCombo.addSelectionListener(mValidateOnSelection);
- }
-
- /**
- * Creates the lower group with the fields to choose the resource confirmation and
- * the target XML file.
- *
- * @param content A composite with a 1-column grid layout
- */
- private void createResFileGroup(Composite content) {
-
- Group group = new Group(content, SWT.NONE);
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.grabExcessVerticalSpace = true;
- group.setLayoutData(gd);
- group.setText("XML resource to edit");
-
- GridLayout layout = new GridLayout();
- layout.numColumns = 2;
- group.setLayout(layout);
-
- // line: selection of the res config
-
- Label label;
- label = new Label(group, SWT.NONE);
- label.setText("&Configuration:");
-
- mConfigSelector = new ConfigurationSelector(group, SelectorMode.DEFAULT);
- gd = new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
- gd.horizontalSpan = 2;
- gd.widthHint = ConfigurationSelector.WIDTH_HINT;
- gd.heightHint = ConfigurationSelector.HEIGHT_HINT;
- mConfigSelector.setLayoutData(gd);
- mConfigSelector.setOnChangeListener(mOnConfigSelectorUpdated);
-
- // line: selection of the output file
-
- label = new Label(group, SWT.NONE);
- label.setText("Resource &file:");
-
- mResFileCombo = new Combo(group, SWT.DROP_DOWN);
- mResFileCombo.select(0);
- mResFileCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mResFileCombo.addModifyListener(mOnConfigSelectorUpdated);
- }
-
- /**
- * Creates the bottom option groups with a few checkboxes.
- *
- * @param content A composite with a 1-column grid layout
- */
- private void createOptionGroup(Composite content) {
- Group options = new Group(content, SWT.NONE);
- options.setText("Options");
- GridData gd_Options = new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1);
- gd_Options.widthHint = 77;
- options.setLayoutData(gd_Options);
- options.setLayout(new GridLayout(1, false));
-
- mReplaceAllJava = new Button(options, SWT.CHECK);
- mReplaceAllJava.setToolTipText("When checked, the exact same string literal will be replaced in all Java files.");
- mReplaceAllJava.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- mReplaceAllJava.setText("Replace in all &Java files");
- mReplaceAllJava.addSelectionListener(mValidateOnSelection);
-
- mReplaceAllXml = new Button(options, SWT.CHECK);
- mReplaceAllXml.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- mReplaceAllXml.setToolTipText("When checked, string literals will be replaced in other XML resource files having the same name but located in different resource configuration folders.");
- mReplaceAllXml.setText("Replace in all &XML files for different configuration");
- mReplaceAllXml.addSelectionListener(mValidateOnSelection);
- }
-
- // -- Start of internal part ----------
- // Hide everything down-below from WindowsDesigner Editor
- //$hide>>$
-
- /**
- * Init UI just after it has been created the first time.
- */
- private void initUi() {
- // set output file name to the last one used
- String projPath = mProject.getFullPath().toPortableString();
- String filePath = sLastResFilePath.get(projPath);
-
- mResFileCombo.setText(filePath != null ? filePath : DEFAULT_RES_FILE_PATH);
- mOnConfigSelectorUpdated.run();
- validatePage();
- }
-
- /**
- * Utility method to guess a suitable new XML ID based on the selected string.
- */
- public static String guessId(String text) {
- if (text == null) {
- return ""; //$NON-NLS-1$
- }
-
- // make lower case
- text = text.toLowerCase(Locale.US);
-
- // everything not alphanumeric becomes an underscore
- text = text.replaceAll("[^a-zA-Z0-9]+", "_"); //$NON-NLS-1$ //$NON-NLS-2$
-
- // the id must be a proper Java identifier, so it can't start with a number
- if (text.length() > 0 && !Character.isJavaIdentifierStart(text.charAt(0))) {
- text = "_" + text; //$NON-NLS-1$
- }
- return text;
- }
-
- /**
- * Returns the {@link ExtractStringRefactoring} instance used by this wizard page.
- */
- private ExtractStringRefactoring getOurRefactoring() {
- return (ExtractStringRefactoring) getRefactoring();
- }
-
- /**
- * Validates fields of the wizard input page. Displays errors as appropriate and
- * enable the "Next" button (or not) by calling {@link #setPageComplete(boolean)}.
- *
- * If validation succeeds, this updates the text id & value in the refactoring object.
- *
- * @return True if the page has been positively validated. It may still have warnings.
- */
- private boolean validatePage() {
- boolean success = true;
-
- ExtractStringRefactoring ref = getOurRefactoring();
-
- ref.setReplaceAllJava(mReplaceAllJava.getSelection());
- ref.setReplaceAllXml(mReplaceAllXml.isEnabled() && mReplaceAllXml.getSelection());
-
- // Analyze fatal errors.
-
- String text = mStringIdCombo.getText().trim();
- if (text == null || text.length() < 1) {
- setErrorMessage("Please provide a resource ID.");
- success = false;
- } else {
- for (int i = 0; i < text.length(); i++) {
- char c = text.charAt(i);
- boolean ok = i == 0 ?
- Character.isJavaIdentifierStart(c) :
- Character.isJavaIdentifierPart(c);
- if (!ok) {
- setErrorMessage(String.format(
- "The resource ID must be a valid Java identifier. The character %1$c at position %2$d is not acceptable.",
- c, i+1));
- success = false;
- break;
- }
- }
-
- // update the field in the refactoring object in case of success
- if (success) {
- ref.setNewStringId(text);
- }
- }
-
- String resFile = mResFileCombo.getText();
- if (success) {
- if (resFile == null || resFile.length() == 0) {
- setErrorMessage("A resource file name is required.");
- success = false;
- } else if (!RES_XML_FILE_REGEX.matcher(resFile).matches()) {
- setErrorMessage("The XML file name is not valid.");
- success = false;
- }
- }
-
- // Analyze info & warnings.
-
- if (success) {
- setErrorMessage(null);
-
- ref.setTargetFile(resFile);
- sLastResFilePath.put(mProject.getFullPath().toPortableString(), resFile);
-
- String idValue = mXmlHelper.valueOfStringId(mProject, resFile, text);
- if (idValue != null) {
- String msg = String.format("%1$s already contains a string ID '%2$s' with value '%3$s'.",
- resFile,
- text,
- idValue);
- if (ref.getMode() == ExtractStringRefactoring.Mode.SELECT_NEW_ID) {
- setErrorMessage(msg);
- success = false;
- } else {
- setMessage(msg, WizardPage.WARNING);
- }
- } else if (mProject.findMember(resFile) == null) {
- setMessage(
- String.format("File %2$s does not exist and will be created.",
- text, resFile),
- WizardPage.INFORMATION);
- } else {
- setMessage(null);
- }
- }
-
- if (success) {
- // Also update the text value in case of success.
- ref.setNewStringValue(mStringValueField.getText());
- }
-
- setPageComplete(success);
- return success;
- }
-
- private void updateStringValueCombo() {
- String resFile = mResFileCombo.getText();
- Map<String, String> ids = mXmlHelper.getResIdsForFile(mProject, resFile);
-
- // get the current text from the combo, to make sure we don't change it
- String currText = mStringIdCombo.getText();
-
- // erase the choices and fill with the given ids
- mStringIdCombo.removeAll();
- mStringIdCombo.setItems(ids.keySet().toArray(new String[ids.size()]));
-
- // set the current text to preserve it in case it changed
- if (!currText.equals(mStringIdCombo.getText())) {
- mStringIdCombo.setText(currText);
- }
- }
-
- private class OnConfigSelectorUpdated implements Runnable, ModifyListener {
-
- /** Regex pattern to parse a valid res path: it reads (/res/folder-name/)+(filename). */
- private final Pattern mPathRegex = Pattern.compile(
- "(/res/[a-z][a-zA-Z0-9_-]+/)(.+)"); //$NON-NLS-1$
-
- /** Temporary config object used to retrieve the Config Selector value. */
- private FolderConfiguration mTempConfig = new FolderConfiguration();
-
- private HashMap<String, TreeSet<String>> mFolderCache =
- new HashMap<String, TreeSet<String>>();
- private String mLastFolderUsedInCombo = null;
- private boolean mInternalConfigChange;
- private boolean mInternalFileComboChange;
-
- /**
- * Callback invoked when the {@link ConfigurationSelector} has been changed.
- * <p/>
- * The callback does the following:
- * <ul>
- * <li> Examine the current file name to retrieve the XML filename, if any.
- * <li> Recompute the path based on the configuration selector (e.g. /res/values-fr/).
- * <li> Examine the path to retrieve all the files in it. Keep those in a local cache.
- * <li> If the XML filename from step 1 is not in the file list, it's a custom file name.
- * Insert it and sort it.
- * <li> Re-populate the file combo with all the choices.
- * <li> Select the original XML file.
- */
- @Override
- public void run() {
- if (mInternalConfigChange) {
- return;
- }
-
- // get current leafname, if any
- String leafName = ""; //$NON-NLS-1$
- String currPath = mResFileCombo.getText();
- Matcher m = mPathRegex.matcher(currPath);
- if (m.matches()) {
- // Note: groups 1 and 2 cannot be null.
- leafName = m.group(2);
- currPath = m.group(1);
- } else {
- // There was a path but it was invalid. Ignore it.
- currPath = ""; //$NON-NLS-1$
- }
-
- // recreate the res path from the current configuration
- mConfigSelector.getConfiguration(mTempConfig);
- StringBuffer sb = new StringBuffer(RES_FOLDER_ABS);
- sb.append(mTempConfig.getFolderName(ResourceFolderType.VALUES));
- sb.append(AdtConstants.WS_SEP);
-
- String newPath = sb.toString();
-
- if (newPath.equals(currPath) && newPath.equals(mLastFolderUsedInCombo)) {
- // Path has not changed. No need to reload.
- return;
- }
-
- // Get all the files at the new path
-
- TreeSet<String> filePaths = mFolderCache.get(newPath);
-
- if (filePaths == null) {
- filePaths = new TreeSet<String>();
-
- IFolder folder = mProject.getFolder(newPath);
- if (folder != null && folder.exists()) {
- try {
- for (IResource res : folder.members()) {
- String name = res.getName();
- if (res.getType() == IResource.FILE && name.endsWith(".xml")) {
- filePaths.add(newPath + name);
- }
- }
- } catch (CoreException e) {
- // Ignore.
- }
- }
-
- mFolderCache.put(newPath, filePaths);
- }
-
- currPath = newPath + leafName;
- if (leafName.length() > 0 && !filePaths.contains(currPath)) {
- filePaths.add(currPath);
- }
-
- // Fill the combo
- try {
- mInternalFileComboChange = true;
-
- mResFileCombo.removeAll();
-
- for (String filePath : filePaths) {
- mResFileCombo.add(filePath);
- }
-
- int index = -1;
- if (leafName.length() > 0) {
- index = mResFileCombo.indexOf(currPath);
- if (index >= 0) {
- mResFileCombo.select(index);
- }
- }
-
- if (index == -1) {
- mResFileCombo.setText(currPath);
- }
-
- mLastFolderUsedInCombo = newPath;
-
- } finally {
- mInternalFileComboChange = false;
- }
-
- // finally validate the whole page
- updateStringValueCombo();
- validatePage();
- }
-
- /**
- * Callback invoked when {@link ExtractStringInputPage#mResFileCombo} has been
- * modified.
- */
- @Override
- public void modifyText(ModifyEvent e) {
- if (mInternalFileComboChange) {
- return;
- }
-
- String wsFolderPath = mResFileCombo.getText();
-
- // This is a custom path, we need to sanitize it.
- // First it should start with "/res/". Then we need to make sure there are no
- // relative paths, things like "../" or "./" or even "//".
- wsFolderPath = wsFolderPath.replaceAll("/+\\.\\./+|/+\\./+|//+|\\\\+|^/+", "/"); //$NON-NLS-1$ //$NON-NLS-2$
- wsFolderPath = wsFolderPath.replaceAll("^\\.\\./+|^\\./+", ""); //$NON-NLS-1$ //$NON-NLS-2$
- wsFolderPath = wsFolderPath.replaceAll("/+\\.\\.$|/+\\.$|/+$", ""); //$NON-NLS-1$ //$NON-NLS-2$
-
- // We get "res/foo" from selections relative to the project when we want a "/res/foo" path.
- if (wsFolderPath.startsWith(RES_FOLDER_REL)) {
- wsFolderPath = RES_FOLDER_ABS + wsFolderPath.substring(RES_FOLDER_REL.length());
-
- mInternalFileComboChange = true;
- mResFileCombo.setText(wsFolderPath);
- mInternalFileComboChange = false;
- }
-
- if (wsFolderPath.startsWith(RES_FOLDER_ABS)) {
- wsFolderPath = wsFolderPath.substring(RES_FOLDER_ABS.length());
-
- int pos = wsFolderPath.indexOf(AdtConstants.WS_SEP_CHAR);
- if (pos >= 0) {
- wsFolderPath = wsFolderPath.substring(0, pos);
- }
-
- String[] folderSegments = wsFolderPath.split(SdkConstants.RES_QUALIFIER_SEP);
-
- if (folderSegments.length > 0) {
- String folderName = folderSegments[0];
-
- if (folderName != null && !folderName.equals(wsFolderPath)) {
- // update config selector
- mInternalConfigChange = true;
- mConfigSelector.setConfiguration(folderSegments);
- mInternalConfigChange = false;
- }
- }
- }
-
- updateStringValueCombo();
- validatePage();
- }
- }
-
- // End of hiding from SWT Designer
- //$hide<<$
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringProposal.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringProposal.java
deleted file mode 100644
index 5400be4e4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringProposal.java
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.refactorings.extractstring;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.jdt.core.IBuffer;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.core.dom.ASTNode;
-import org.eclipse.jdt.ui.text.java.IInvocationContext;
-import org.eclipse.jdt.ui.text.java.IJavaCompletionProposal;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.TextSelection;
-import org.eclipse.jface.text.contentassist.IContextInformation;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-
-/**
- * Proposal for extracting strings in Java files
- */
-public class ExtractStringProposal implements IJavaCompletionProposal {
- private IInvocationContext mContext;
-
- public ExtractStringProposal(IInvocationContext context) {
- mContext = context;
- }
-
- @Override
- public void apply(IDocument document) {
- IEditorPart editor = AdtUtils.getActiveEditor();
- IFile file = AdtUtils.getActiveFile();
- if (editor == null || file == null) {
- return;
- }
-
- ASTNode coveringNode = mContext.getCoveringNode();
- int start = coveringNode.getStartPosition();
- int length = coveringNode.getLength();
- ITextSelection selection = new TextSelection(start, length);
-
- ExtractStringRefactoring refactoring = new ExtractStringRefactoring(file, editor,
- selection);
-
- RefactoringWizard wizard = new ExtractStringWizard(refactoring, file.getProject());
- RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation(wizard);
- try {
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- op.run(window.getShell(), wizard.getDefaultPageTitle());
- } catch (InterruptedException e) {
- }
- }
-
- @Override
- public Point getSelection(IDocument document) {
- return null;
- }
-
- @Override
- public String getAdditionalProposalInfo() {
- try {
- ASTNode coveringNode = mContext.getCoveringNode();
- int start = coveringNode.getStartPosition();
- int length = coveringNode.getLength();
- IBuffer buffer = mContext.getCompilationUnit().getBuffer();
- StringBuilder sb = new StringBuilder();
- String string = buffer.getText(start, length);
- string = ExtractStringRefactoring.unquoteAttrValue(string);
- String token = ExtractStringInputPage.guessId(string);
-
- // Look up the beginning and the end of the line (outside of the extracted string)
- // such that we can show a preview of the diff, e.g. if you have
- // foo.setTitle("Hello"); we want to show foo.setTitle(R.string.hello);
- // so we need to extract "foo.setTitle(" and ");".
-
- // Look backwards to the beginning of the line (and strip whitespace)
- int i = start - 1;
- while (i > 0) {
- char c = buffer.getChar(i);
- if (c == '\r' || (c == '\n')) {
- break;
- }
- i--;
- }
- String linePrefix = buffer.getText(i + 1, start - (i + 1)).trim();
-
- // Look forwards to the end of the line (and strip whitespace)
- i = start + length;
- while (i < buffer.getLength()) {
- char c = buffer.getChar(i);
- if (c == '\r' || (c == '\n')) {
- break;
- }
- i++;
- }
- String lineSuffix = buffer.getText(start + length, i - (start + length));
-
- // Should we show the replacement as just R.string.foo or
- // context.getString(R.string.foo) ?
- boolean useContext = false;
- ASTNode parent = coveringNode.getParent();
- if (parent != null) {
- int type = parent.getNodeType();
- if (type == ASTNode.ASSIGNMENT
- || type == ASTNode.VARIABLE_DECLARATION_STATEMENT
- || type == ASTNode.VARIABLE_DECLARATION_FRAGMENT
- || type == ASTNode.VARIABLE_DECLARATION_EXPRESSION) {
- useContext = true;
- }
- }
-
- // Display .java change:
- sb.append("...<br>"); //$NON-NLS-1$
- sb.append(linePrefix);
- sb.append("<b>"); //$NON-NLS-1$
- if (useContext) {
- sb.append("context.getString("); //$NON-NLS-1$
- }
- sb.append("R.string."); //$NON-NLS-1$
- sb.append(token);
- if (useContext) {
- sb.append(")"); //$NON-NLS-1$
- }
- sb.append("</b>"); //$NON-NLS-1$
- sb.append(lineSuffix);
- sb.append("<br>...<br>"); //$NON-NLS-1$
-
- // Display strings.xml change:
- sb.append("<br>"); //$NON-NLS-1$
- sb.append("&lt;resources&gt;<br>"); //$NON-NLS-1$
- sb.append(" <b>&lt;string name=\""); //$NON-NLS-1$
- sb.append(token);
- sb.append("\"&gt;"); //$NON-NLS-1$
- sb.append(string);
- sb.append("&lt;/string&gt;</b><br>"); //$NON-NLS-1$
- sb.append("&lt;/resources&gt;"); //$NON-NLS-1$
-
- return sb.toString();
- } catch (JavaModelException e) {
- AdtPlugin.log(e, null);
- }
-
- return "Initiates the Extract String refactoring operation";
- }
-
- @Override
- public String getDisplayString() {
- return "Extract String";
- }
-
- @Override
- public Image getImage() {
- return AdtPlugin.getAndroidLogo();
- }
-
- @Override
- public IContextInformation getContextInformation() {
- return null;
- }
-
- @Override
- public int getRelevance() {
- return 80;
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringRefactoring.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringRefactoring.java
deleted file mode 100644
index db0b0967d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringRefactoring.java
+++ /dev/null
@@ -1,1933 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.refactorings.extractstring;
-
-import static com.android.SdkConstants.QUOT_ENTITY;
-import static com.android.SdkConstants.STRING_PREFIX;
-
-import com.android.SdkConstants;
-import com.android.ide.common.res2.ValueXmlHelper;
-import com.android.ide.common.xml.ManifestData;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ReferenceAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiAttributeNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.project.AndroidManifestHelper;
-import com.android.resources.ResourceFolderType;
-import com.android.resources.ResourceType;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourceAttributes;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.SubMonitor;
-import org.eclipse.jdt.core.IBuffer;
-import org.eclipse.jdt.core.ICompilationUnit;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jdt.core.IPackageFragmentRoot;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.core.ToolFactory;
-import org.eclipse.jdt.core.compiler.IScanner;
-import org.eclipse.jdt.core.compiler.ITerminalSymbols;
-import org.eclipse.jdt.core.compiler.InvalidInputException;
-import org.eclipse.jdt.core.dom.AST;
-import org.eclipse.jdt.core.dom.ASTNode;
-import org.eclipse.jdt.core.dom.ASTParser;
-import org.eclipse.jdt.core.dom.CompilationUnit;
-import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.jdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.ChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringChangeDescriptor;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextEditChangeGroup;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.text.edits.InsertEdit;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.wst.sse.core.StructuredModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList;
-import org.eclipse.wst.xml.core.internal.regions.DOMRegionContext;
-import org.w3c.dom.Node;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Queue;
-
-/**
- * This refactoring extracts a string from a file and replaces it by an Android resource ID
- * such as R.string.foo.
- * <p/>
- * There are a number of scenarios, which are not all supported yet. The workflow works as
- * such:
- * <ul>
- * <li> User selects a string in a Java and invokes the {@link ExtractStringAction}.
- * <li> The action finds the {@link ICompilationUnit} being edited as well as the current
- * {@link ITextSelection}. The action creates a new instance of this refactoring as
- * well as an {@link ExtractStringWizard} and runs the operation.
- * <li> Step 1 of the refactoring is to check the preliminary conditions. Right now we check
- * that the java source is not read-only and is in sync. We also try to find a string under
- * the selection. If this fails, the refactoring is aborted.
- * <li> On success, the wizard is shown, which lets the user input the new ID to use.
- * <li> The wizard sets the user input values into this refactoring instance, e.g. the new string
- * ID, the XML file to update, etc. The wizard does use the utility method
- * {@link XmlStringFileHelper#valueOfStringId(IProject, String, String)} to check whether
- * the new ID is already defined in the target XML file.
- * <li> Once Preview or Finish is selected in the wizard, the
- * {@link #checkFinalConditions(IProgressMonitor)} is called to double-check the user input
- * and compute the actual changes.
- * <li> When all changes are computed, {@link #createChange(IProgressMonitor)} is invoked.
- * </ul>
- *
- * The list of changes are:
- * <ul>
- * <li> If the target XML does not exist, create it with the new string ID.
- * <li> If the target XML exists, find the <resources> node and add the new string ID right after.
- * If the node is <resources/>, it needs to be opened.
- * <li> Create an AST rewriter to edit the source Java file and replace all occurrences by the
- * new computed R.string.foo. Also need to rewrite imports to import R as needed.
- * If there's already a conflicting R included, we need to insert the FQCN instead.
- * <li> TODO: Have a pref in the wizard: [x] Change other XML Files
- * <li> TODO: Have a pref in the wizard: [x] Change other Java Files
- * </ul>
- */
-@SuppressWarnings("restriction")
-public class ExtractStringRefactoring extends Refactoring {
-
- public enum Mode {
- /**
- * the Extract String refactoring is called on an <em>existing</em> source file.
- * Its purpose is then to get the selected string of the source and propose to
- * change it by an XML id. The XML id may be a new one or an existing one.
- */
- EDIT_SOURCE,
- /**
- * The Extract String refactoring is called without any source file.
- * Its purpose is then to create a new XML string ID or select/modify an existing one.
- */
- SELECT_ID,
- /**
- * The Extract String refactoring is called without any source file.
- * Its purpose is then to create a new XML string ID. The ID must not already exist.
- */
- SELECT_NEW_ID
- }
-
- /** The {@link Mode} of operation of the refactoring. */
- private final Mode mMode;
- /** Non-null when editing an Android Resource XML file: identifies the attribute name
- * of the value being edited. When null, the source is an Android Java file. */
- private String mXmlAttributeName;
- /** The file model being manipulated.
- * Value is null when not on {@link Mode#EDIT_SOURCE} mode. */
- private final IFile mFile;
- /** The editor. Non-null when invoked from {@link ExtractStringAction}. Null otherwise. */
- private final IEditorPart mEditor;
- /** The project that contains {@link #mFile} and that contains the target XML file to modify. */
- private final IProject mProject;
- /** The start of the selection in {@link #mFile}.
- * Value is -1 when not on {@link Mode#EDIT_SOURCE} mode. */
- private final int mSelectionStart;
- /** The end of the selection in {@link #mFile}.
- * Value is -1 when not on {@link Mode#EDIT_SOURCE} mode. */
- private final int mSelectionEnd;
-
- /** The compilation unit, only defined if {@link #mFile} points to a usable Java source file. */
- private ICompilationUnit mUnit;
- /** The actual string selected, after UTF characters have been escaped, good for display.
- * Value is null when not on {@link Mode#EDIT_SOURCE} mode. */
- private String mTokenString;
-
- /** The XML string ID selected by the user in the wizard. */
- private String mXmlStringId;
- /** The XML string value. Might be different than the initial selected string. */
- private String mXmlStringValue;
- /** The path of the XML file that will define {@link #mXmlStringId}, selected by the user
- * in the wizard. This is relative to the project, e.g. "/res/values/string.xml" */
- private String mTargetXmlFileWsPath;
- /** True if we should find & replace in all Java files. */
- private boolean mReplaceAllJava;
- /** True if we should find & replace in all XML files of the same name in other res configs
- * (other than the main {@link #mTargetXmlFileWsPath}.) */
- private boolean mReplaceAllXml;
-
- /** The list of changes computed by {@link #checkFinalConditions(IProgressMonitor)} and
- * used by {@link #createChange(IProgressMonitor)}. */
- private ArrayList<Change> mChanges;
-
- private XmlStringFileHelper mXmlHelper = new XmlStringFileHelper();
-
- private static final String KEY_MODE = "mode"; //$NON-NLS-1$
- private static final String KEY_FILE = "file"; //$NON-NLS-1$
- private static final String KEY_PROJECT = "proj"; //$NON-NLS-1$
- private static final String KEY_SEL_START = "sel-start"; //$NON-NLS-1$
- private static final String KEY_SEL_END = "sel-end"; //$NON-NLS-1$
- private static final String KEY_TOK_ESC = "tok-esc"; //$NON-NLS-1$
- private static final String KEY_XML_ATTR_NAME = "xml-attr-name"; //$NON-NLS-1$
- private static final String KEY_RPLC_ALL_JAVA = "rplc-all-java"; //$NON-NLS-1$
- private static final String KEY_RPLC_ALL_XML = "rplc-all-xml"; //$NON-NLS-1$
-
- /**
- * This constructor is solely used by {@link ExtractStringDescriptor},
- * to replay a previous refactoring.
- * <p/>
- * To create a refactoring from code, please use one of the two other constructors.
- *
- * @param arguments A map previously created using {@link #createArgumentMap()}.
- * @throws NullPointerException
- */
- public ExtractStringRefactoring(Map<String, String> arguments) throws NullPointerException {
-
- mReplaceAllJava = Boolean.parseBoolean(arguments.get(KEY_RPLC_ALL_JAVA));
- mReplaceAllXml = Boolean.parseBoolean(arguments.get(KEY_RPLC_ALL_XML));
- mMode = Mode.valueOf(arguments.get(KEY_MODE));
-
- IPath path = Path.fromPortableString(arguments.get(KEY_PROJECT));
- mProject = (IProject) ResourcesPlugin.getWorkspace().getRoot().findMember(path);
-
- if (mMode == Mode.EDIT_SOURCE) {
- path = Path.fromPortableString(arguments.get(KEY_FILE));
- mFile = (IFile) ResourcesPlugin.getWorkspace().getRoot().findMember(path);
-
- mSelectionStart = Integer.parseInt(arguments.get(KEY_SEL_START));
- mSelectionEnd = Integer.parseInt(arguments.get(KEY_SEL_END));
- mTokenString = arguments.get(KEY_TOK_ESC);
- mXmlAttributeName = arguments.get(KEY_XML_ATTR_NAME);
- } else {
- mFile = null;
- mSelectionStart = mSelectionEnd = -1;
- mTokenString = null;
- mXmlAttributeName = null;
- }
-
- mEditor = null;
- }
-
- private Map<String, String> createArgumentMap() {
- HashMap<String, String> args = new HashMap<String, String>();
- args.put(KEY_RPLC_ALL_JAVA, Boolean.toString(mReplaceAllJava));
- args.put(KEY_RPLC_ALL_XML, Boolean.toString(mReplaceAllXml));
- args.put(KEY_MODE, mMode.name());
- args.put(KEY_PROJECT, mProject.getFullPath().toPortableString());
- if (mMode == Mode.EDIT_SOURCE) {
- args.put(KEY_FILE, mFile.getFullPath().toPortableString());
- args.put(KEY_SEL_START, Integer.toString(mSelectionStart));
- args.put(KEY_SEL_END, Integer.toString(mSelectionEnd));
- args.put(KEY_TOK_ESC, mTokenString);
- args.put(KEY_XML_ATTR_NAME, mXmlAttributeName);
- }
- return args;
- }
-
- /**
- * Constructor to use when the Extract String refactoring is called on an
- * *existing* source file. Its purpose is then to get the selected string of
- * the source and propose to change it by an XML id. The XML id may be a new one
- * or an existing one.
- *
- * @param file The source file to process. Cannot be null. File must exist in workspace.
- * @param editor The editor.
- * @param selection The selection in the source file. Cannot be null or empty.
- */
- public ExtractStringRefactoring(IFile file, IEditorPart editor, ITextSelection selection) {
- mMode = Mode.EDIT_SOURCE;
- mFile = file;
- mEditor = editor;
- mProject = file.getProject();
- mSelectionStart = selection.getOffset();
- mSelectionEnd = mSelectionStart + Math.max(0, selection.getLength() - 1);
- }
-
- /**
- * Constructor to use when the Extract String refactoring is called without
- * any source file. Its purpose is then to create a new XML string ID.
- * <p/>
- * For example this is currently invoked by the ResourceChooser when
- * the user wants to create a new string rather than select an existing one.
- *
- * @param project The project where the target XML file to modify is located. Cannot be null.
- * @param enforceNew If true the XML ID must be a new one.
- * If false, an existing ID can be used.
- */
- public ExtractStringRefactoring(IProject project, boolean enforceNew) {
- mMode = enforceNew ? Mode.SELECT_NEW_ID : Mode.SELECT_ID;
- mFile = null;
- mEditor = null;
- mProject = project;
- mSelectionStart = mSelectionEnd = -1;
- }
-
- /**
- * Sets the replacement string ID. Used by the wizard to set the user input.
- */
- public void setNewStringId(String newStringId) {
- mXmlStringId = newStringId;
- }
-
- /**
- * Sets the replacement string ID. Used by the wizard to set the user input.
- */
- public void setNewStringValue(String newStringValue) {
- mXmlStringValue = newStringValue;
- }
-
- /**
- * Sets the target file. This is a project path, e.g. "/res/values/strings.xml".
- * Used by the wizard to set the user input.
- */
- public void setTargetFile(String targetXmlFileWsPath) {
- mTargetXmlFileWsPath = targetXmlFileWsPath;
- }
-
- public void setReplaceAllJava(boolean replaceAllJava) {
- mReplaceAllJava = replaceAllJava;
- }
-
- public void setReplaceAllXml(boolean replaceAllXml) {
- mReplaceAllXml = replaceAllXml;
- }
-
- /**
- * @see org.eclipse.ltk.core.refactoring.Refactoring#getName()
- */
- @Override
- public String getName() {
- if (mMode == Mode.SELECT_ID) {
- return "Create or Use Android String";
- } else if (mMode == Mode.SELECT_NEW_ID) {
- return "Create New Android String";
- }
-
- return "Extract Android String";
- }
-
- public Mode getMode() {
- return mMode;
- }
-
- /**
- * Gets the actual string selected, after UTF characters have been escaped,
- * good for display. Value can be null.
- */
- public String getTokenString() {
- return mTokenString;
- }
-
- /** Returns the XML string ID selected by the user in the wizard. */
- public String getXmlStringId() {
- return mXmlStringId;
- }
-
- /**
- * Step 1 of 3 of the refactoring:
- * Checks that the current selection meets the initial condition before the ExtractString
- * wizard is shown. The check is supposed to be lightweight and quick. Note that at that
- * point the wizard has not been created yet.
- * <p/>
- * Here we scan the source buffer to find the token matching the selection.
- * The check is successful is a Java string literal is selected, the source is in sync
- * and is not read-only.
- * <p/>
- * This is also used to extract the string to be modified, so that we can display it in
- * the refactoring wizard.
- *
- * @see org.eclipse.ltk.core.refactoring.Refactoring#checkInitialConditions(org.eclipse.core.runtime.IProgressMonitor)
- *
- * @throws CoreException
- */
- @Override
- public RefactoringStatus checkInitialConditions(IProgressMonitor monitor)
- throws CoreException, OperationCanceledException {
-
- mUnit = null;
- mTokenString = null;
-
- RefactoringStatus status = new RefactoringStatus();
-
- try {
- monitor.beginTask("Checking preconditions...", 6);
-
- if (mMode != Mode.EDIT_SOURCE) {
- monitor.worked(6);
- return status;
- }
-
- if (!checkSourceFile(mFile, status, monitor)) {
- return status;
- }
-
- // Try to get a compilation unit from this file. If it fails, mUnit is null.
- try {
- mUnit = JavaCore.createCompilationUnitFrom(mFile);
-
- // Make sure the unit is not read-only, e.g. it's not a class file or inside a Jar
- if (mUnit.isReadOnly()) {
- status.addFatalError("The file is read-only, please make it writeable first.");
- return status;
- }
-
- // This is a Java file. Check if it contains the selection we want.
- if (!findSelectionInJavaUnit(mUnit, status, monitor)) {
- return status;
- }
-
- } catch (Exception e) {
- // That was not a Java file. Ignore.
- }
-
- if (mUnit != null) {
- monitor.worked(1);
- return status;
- }
-
- // Check this a Layout XML file and get the selection and its context.
- if (mFile != null && SdkConstants.EXT_XML.equals(mFile.getFileExtension())) {
-
- // Currently we only support Android resource XML files, so they must have a path
- // similar to
- // project/res/<type>[-<configuration>]/*.xml
- // project/AndroidManifest.xml
- // There is no support for sub folders, so the segment count must be 4 or 2.
- // We don't need to check the type folder name because a/ we only accept
- // an AndroidXmlEditor source and b/ aapt generates a compilation error for
- // unknown folders.
-
- IPath path = mFile.getFullPath();
- if ((path.segmentCount() == 4 &&
- path.segment(1).equalsIgnoreCase(SdkConstants.FD_RESOURCES)) ||
- (path.segmentCount() == 2 &&
- path.segment(1).equalsIgnoreCase(SdkConstants.FN_ANDROID_MANIFEST_XML))) {
- if (!findSelectionInXmlFile(mFile, status, monitor)) {
- return status;
- }
- }
- }
-
- if (!status.isOK()) {
- status.addFatalError(
- "Selection must be inside a Java source or an Android Layout XML file.");
- }
-
- } finally {
- monitor.done();
- }
-
- return status;
- }
-
- /**
- * Try to find the selected Java element in the compilation unit.
- *
- * If selection matches a string literal, capture it, otherwise add a fatal error
- * to the status.
- *
- * On success, advance the monitor by 3.
- * Returns status.isOK().
- */
- private boolean findSelectionInJavaUnit(ICompilationUnit unit,
- RefactoringStatus status, IProgressMonitor monitor) {
- try {
- IBuffer buffer = unit.getBuffer();
-
- IScanner scanner = ToolFactory.createScanner(
- false, //tokenizeComments
- false, //tokenizeWhiteSpace
- false, //assertMode
- false //recordLineSeparator
- );
- scanner.setSource(buffer.getCharacters());
- monitor.worked(1);
-
- for(int token = scanner.getNextToken();
- token != ITerminalSymbols.TokenNameEOF;
- token = scanner.getNextToken()) {
- if (scanner.getCurrentTokenStartPosition() <= mSelectionStart &&
- scanner.getCurrentTokenEndPosition() >= mSelectionEnd) {
- // found the token, but only keep if the right type
- if (token == ITerminalSymbols.TokenNameStringLiteral) {
- mTokenString = new String(scanner.getCurrentTokenSource());
- }
- break;
- } else if (scanner.getCurrentTokenStartPosition() > mSelectionEnd) {
- // scanner is past the selection, abort.
- break;
- }
- }
- } catch (JavaModelException e1) {
- // Error in unit.getBuffer. Ignore.
- } catch (InvalidInputException e2) {
- // Error in scanner.getNextToken. Ignore.
- } finally {
- monitor.worked(1);
- }
-
- if (mTokenString != null) {
- // As a literal string, the token should have surrounding quotes. Remove them.
- // Note: unquoteAttrValue technically removes either " or ' paired quotes, whereas
- // the Java token should only have " quotes. Since we know the type to be a string
- // literal, there should be no confusion here.
- mTokenString = unquoteAttrValue(mTokenString);
-
- // We need a non-empty string literal
- if (mTokenString.length() == 0) {
- mTokenString = null;
- }
- }
-
- if (mTokenString == null) {
- status.addFatalError("Please select a Java string literal.");
- }
-
- monitor.worked(1);
- return status.isOK();
- }
-
- /**
- * Try to find the selected XML element. This implementation replies on the refactoring
- * originating from an Android Layout Editor. We rely on some internal properties of the
- * Structured XML editor to retrieve file content to avoid parsing it again. We also rely
- * on our specific Android XML model to get element & attribute descriptor properties.
- *
- * If selection matches a string literal, capture it, otherwise add a fatal error
- * to the status.
- *
- * On success, advance the monitor by 1.
- * Returns status.isOK().
- */
- private boolean findSelectionInXmlFile(IFile file,
- RefactoringStatus status,
- IProgressMonitor monitor) {
-
- try {
- if (!(mEditor instanceof AndroidXmlEditor)) {
- status.addFatalError("Only the Android XML Editor is currently supported.");
- return status.isOK();
- }
-
- AndroidXmlEditor editor = (AndroidXmlEditor) mEditor;
- IStructuredModel smodel = null;
- Node node = null;
- String currAttrName = null;
-
- try {
- // See the portability note in AndroidXmlEditor#getModelForRead() javadoc.
- smodel = editor.getModelForRead();
- if (smodel != null) {
- // The structured model gives the us the actual XML Node element where the
- // offset is. By using this Node, we can find the exact UiElementNode of our
- // model and thus we'll be able to get the properties of the attribute -- to
- // check if it accepts a string reference. This does not however tell us if
- // the selection is actually in an attribute value, nor which attribute is
- // being edited.
- for(int offset = mSelectionStart; offset >= 0 && node == null; --offset) {
- node = (Node) smodel.getIndexedRegion(offset);
- }
-
- if (node == null) {
- status.addFatalError(
- "The selection does not match any element in the XML document.");
- return status.isOK();
- }
-
- if (node.getNodeType() != Node.ELEMENT_NODE) {
- status.addFatalError("The selection is not inside an actual XML element.");
- return status.isOK();
- }
-
- IStructuredDocument sdoc = smodel.getStructuredDocument();
- if (sdoc != null) {
- // Portability note: all the structured document implementation is
- // under wst.sse.core.internal.provisional so we can expect it to change in
- // a distant future if they start cleaning their codebase, however unlikely
- // that is.
-
- int selStart = mSelectionStart;
- IStructuredDocumentRegion region =
- sdoc.getRegionAtCharacterOffset(selStart);
- if (region != null &&
- DOMRegionContext.XML_TAG_NAME.equals(region.getType())) {
- // Find if any sub-region representing an attribute contains the
- // selection. If it does, returns the name of the attribute in
- // currAttrName and returns the value in the field mTokenString.
- currAttrName = findSelectionInRegion(region, selStart);
-
- if (mTokenString == null) {
- status.addFatalError(
- "The selection is not inside an actual XML attribute value.");
- }
- }
- }
-
- if (mTokenString != null && node != null && currAttrName != null) {
-
- // Validate that the attribute accepts a string reference.
- // This sets mTokenString to null by side-effect when it fails and
- // adds a fatal error to the status as needed.
- validateSelectedAttribute(editor, node, currAttrName, status);
-
- } else {
- // We shouldn't get here: we're missing one of the token string, the node
- // or the attribute name. All of them have been checked earlier so don't
- // set any specific error.
- mTokenString = null;
- }
- }
- } catch (Throwable t) {
- // Since we use some internal APIs, use a broad catch-all to report any
- // unexpected issue rather than crash the whole refactoring.
- status.addFatalError(
- String.format("XML parsing error: %1$s", t.getMessage()));
- } finally {
- if (smodel != null) {
- smodel.releaseFromRead();
- }
- }
-
- } finally {
- monitor.worked(1);
- }
-
- return status.isOK();
- }
-
- /**
- * The region gives us the textual representation of the XML element
- * where the selection starts, split using sub-regions. We now just
- * need to iterate through the sub-regions to find which one
- * contains the actual selection. We're interested in an attribute
- * value however when we find one we want to memorize the attribute
- * name that was defined just before.
- *
- * @return When the cursor is on a valid attribute name or value, returns the string of
- * attribute name. As a side-effect, returns the value of the attribute in {@link #mTokenString}
- */
- private String findSelectionInRegion(IStructuredDocumentRegion region, int selStart) {
-
- String currAttrName = null;
-
- int startInRegion = selStart - region.getStartOffset();
-
- int nb = region.getNumberOfRegions();
- ITextRegionList list = region.getRegions();
- String currAttrValue = null;
-
- for (int i = 0; i < nb; i++) {
- ITextRegion subRegion = list.get(i);
- String type = subRegion.getType();
-
- if (DOMRegionContext.XML_TAG_ATTRIBUTE_NAME.equals(type)) {
- currAttrName = region.getText(subRegion);
-
- // I like to select the attribute definition and invoke
- // the extract string wizard. So if the selection is on
- // the attribute name part, find the value that is just
- // after and use it as if it were the selection.
-
- if (subRegion.getStart() <= startInRegion &&
- startInRegion < subRegion.getTextEnd()) {
- // A well-formed attribute is composed of a name,
- // an equal sign and the value. There can't be any space
- // in between, which makes the parsing a lot easier.
- if (i <= nb - 3 &&
- DOMRegionContext.XML_TAG_ATTRIBUTE_EQUALS.equals(
- list.get(i + 1).getType())) {
- subRegion = list.get(i + 2);
- type = subRegion.getType();
- if (DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE.equals(
- type)) {
- currAttrValue = region.getText(subRegion);
- }
- }
- }
-
- } else if (subRegion.getStart() <= startInRegion &&
- startInRegion < subRegion.getTextEnd() &&
- DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE.equals(type)) {
- currAttrValue = region.getText(subRegion);
- }
-
- if (currAttrValue != null) {
- // We found the value. Only accept it if not empty
- // and if we found an attribute name before.
- String text = currAttrValue;
-
- // The attribute value contains XML quotes. Remove them.
- text = unquoteAttrValue(text);
- if (text.length() > 0 && currAttrName != null) {
- // Setting mTokenString to non-null marks the fact we
- // accept this attribute.
- mTokenString = text;
- }
-
- break;
- }
- }
-
- return currAttrName;
- }
-
- /**
- * Attribute values found as text for {@link DOMRegionContext#XML_TAG_ATTRIBUTE_VALUE}
- * contain XML quotes. This removes the quotes (either single or double quotes).
- *
- * @param attrValue The attribute value, as extracted by
- * {@link IStructuredDocumentRegion#getText(ITextRegion)}.
- * Must not be null.
- * @return The attribute value, without quotes. Whitespace is not trimmed, if any.
- * String may be empty, but not null.
- */
- static String unquoteAttrValue(String attrValue) {
- int len = attrValue.length();
- int len1 = len - 1;
- if (len >= 2 &&
- attrValue.charAt(0) == '"' &&
- attrValue.charAt(len1) == '"') {
- attrValue = attrValue.substring(1, len1);
- } else if (len >= 2 &&
- attrValue.charAt(0) == '\'' &&
- attrValue.charAt(len1) == '\'') {
- attrValue = attrValue.substring(1, len1);
- }
-
- return attrValue;
- }
-
- /**
- * Validates that the attribute accepts a string reference.
- * This sets mTokenString to null by side-effect when it fails and
- * adds a fatal error to the status as needed.
- */
- private void validateSelectedAttribute(AndroidXmlEditor editor, Node node,
- String attrName, RefactoringStatus status) {
- UiElementNode rootUiNode = editor.getUiRootNode();
- UiElementNode currentUiNode =
- rootUiNode == null ? null : rootUiNode.findXmlNode(node);
- ReferenceAttributeDescriptor attrDesc = null;
-
- if (currentUiNode != null) {
- // remove any namespace prefix from the attribute name
- String name = attrName;
- int pos = name.indexOf(':');
- if (pos > 0 && pos < name.length() - 1) {
- name = name.substring(pos + 1);
- }
-
- for (UiAttributeNode attrNode : currentUiNode.getAllUiAttributes()) {
- if (attrNode.getDescriptor().getXmlLocalName().equals(name)) {
- AttributeDescriptor desc = attrNode.getDescriptor();
- if (desc instanceof ReferenceAttributeDescriptor) {
- attrDesc = (ReferenceAttributeDescriptor) desc;
- }
- break;
- }
- }
- }
-
- // The attribute descriptor is a resource reference. It must either accept
- // of any resource type or specifically accept string types.
- if (attrDesc != null &&
- (attrDesc.getResourceType() == null ||
- attrDesc.getResourceType() == ResourceType.STRING)) {
- // We have one more check to do: is the current string value already
- // an Android XML string reference? If so, we can't edit it.
- if (mTokenString != null && mTokenString.startsWith("@")) { //$NON-NLS-1$
- int pos1 = 0;
- if (mTokenString.length() > 1 && mTokenString.charAt(1) == '+') {
- pos1++;
- }
- int pos2 = mTokenString.indexOf('/');
- if (pos2 > pos1) {
- String kind = mTokenString.substring(pos1 + 1, pos2);
- if (ResourceType.STRING.getName().equals(kind)) {
- mTokenString = null;
- status.addFatalError(String.format(
- "The attribute %1$s already contains a %2$s reference.",
- attrName,
- kind));
- }
- }
- }
-
- if (mTokenString != null) {
- // We're done with all our checks. mTokenString contains the
- // current attribute value. We don't memorize the region nor the
- // attribute, however we memorize the textual attribute name so
- // that we can offer replacement for all its occurrences.
- mXmlAttributeName = attrName;
- }
-
- } else {
- mTokenString = null;
- status.addFatalError(String.format(
- "The attribute %1$s does not accept a string reference.",
- attrName));
- }
- }
-
- /**
- * Tests from org.eclipse.jdt.internal.corext.refactoringChecks#validateEdit()
- * Might not be useful.
- *
- * On success, advance the monitor by 2.
- *
- * @return False if caller should abort, true if caller should continue.
- */
- private boolean checkSourceFile(IFile file,
- RefactoringStatus status,
- IProgressMonitor monitor) {
- // check whether the source file is in sync
- if (!file.isSynchronized(IResource.DEPTH_ZERO)) {
- status.addFatalError("The file is not synchronized. Please save it first.");
- return false;
- }
- monitor.worked(1);
-
- // make sure we can write to it.
- ResourceAttributes resAttr = file.getResourceAttributes();
- if (resAttr == null || resAttr.isReadOnly()) {
- status.addFatalError("The file is read-only, please make it writeable first.");
- return false;
- }
- monitor.worked(1);
-
- return true;
- }
-
- /**
- * Step 2 of 3 of the refactoring:
- * Check the conditions once the user filled values in the refactoring wizard,
- * then prepare the changes to be applied.
- * <p/>
- * In this case, most of the sanity checks are done by the wizard so essentially this
- * should only be called if the wizard positively validated the user input.
- *
- * Here we do check that the target resource XML file either does not exists or
- * is not read-only.
- *
- * @see org.eclipse.ltk.core.refactoring.Refactoring#checkFinalConditions(IProgressMonitor)
- *
- * @throws CoreException
- */
- @Override
- public RefactoringStatus checkFinalConditions(IProgressMonitor monitor)
- throws CoreException, OperationCanceledException {
- RefactoringStatus status = new RefactoringStatus();
-
- try {
- monitor.beginTask("Checking post-conditions...", 5);
-
- if (mXmlStringId == null || mXmlStringId.length() <= 0) {
- // this is not supposed to happen
- status.addFatalError("Missing replacement string ID");
- } else if (mTargetXmlFileWsPath == null || mTargetXmlFileWsPath.length() <= 0) {
- // this is not supposed to happen
- status.addFatalError("Missing target xml file path");
- }
- monitor.worked(1);
-
- // Either that resource must not exist or it must be a writable file.
- IResource targetXml = getTargetXmlResource(mTargetXmlFileWsPath);
- if (targetXml != null) {
- if (targetXml.getType() != IResource.FILE) {
- status.addFatalError(
- String.format("XML file '%1$s' is not a file.", mTargetXmlFileWsPath));
- } else {
- ResourceAttributes attr = targetXml.getResourceAttributes();
- if (attr != null && attr.isReadOnly()) {
- status.addFatalError(
- String.format("XML file '%1$s' is read-only.",
- mTargetXmlFileWsPath));
- }
- }
- }
- monitor.worked(1);
-
- if (status.hasError()) {
- return status;
- }
-
- mChanges = new ArrayList<Change>();
-
-
- // Prepare the change to create/edit the String ID in the res/values XML file.
- if (!mXmlStringValue.equals(
- mXmlHelper.valueOfStringId(mProject, mTargetXmlFileWsPath, mXmlStringId))) {
- // We actually change it only if the ID doesn't exist yet or has a different value
- Change change = createXmlChanges((IFile) targetXml, mXmlStringId, mXmlStringValue,
- status, SubMonitor.convert(monitor, 1));
- if (change != null) {
- mChanges.add(change);
- }
- }
-
- if (status.hasError()) {
- return status;
- }
-
- if (mMode == Mode.EDIT_SOURCE) {
- List<Change> changes = null;
- if (mXmlAttributeName != null) {
- // Prepare the change to the Android resource XML file
- changes = computeXmlSourceChanges(mFile,
- mXmlStringId,
- mTokenString,
- mXmlAttributeName,
- true, // allConfigurations
- status,
- monitor);
-
- } else if (mUnit != null) {
- // Prepare the change to the Java compilation unit
- changes = computeJavaChanges(mUnit, mXmlStringId, mTokenString,
- status, SubMonitor.convert(monitor, 1));
- }
- if (changes != null) {
- mChanges.addAll(changes);
- }
- }
-
- if (mReplaceAllJava) {
- String currentIdentifier = mUnit != null ? mUnit.getHandleIdentifier() : ""; //$NON-NLS-1$
-
- SubMonitor submon = SubMonitor.convert(monitor, 1);
- for (ICompilationUnit unit : findAllJavaUnits()) {
- // Only process Java compilation units that exist, are not derived
- // and are not read-only.
- if (unit == null || !unit.exists()) {
- continue;
- }
- IResource resource = unit.getResource();
- if (resource == null || resource.isDerived()) {
- continue;
- }
-
- // Ensure that we don't process the current compilation unit (processed
- // as mUnit above) twice
- if (currentIdentifier.equals(unit.getHandleIdentifier())) {
- continue;
- }
-
- ResourceAttributes attrs = resource.getResourceAttributes();
- if (attrs != null && attrs.isReadOnly()) {
- continue;
- }
-
- List<Change> changes = computeJavaChanges(
- unit, mXmlStringId, mTokenString,
- status, SubMonitor.convert(submon, 1));
- if (changes != null) {
- mChanges.addAll(changes);
- }
- }
- }
-
- if (mReplaceAllXml) {
- SubMonitor submon = SubMonitor.convert(monitor, 1);
- for (IFile xmlFile : findAllResXmlFiles()) {
- if (xmlFile != null) {
- List<Change> changes = computeXmlSourceChanges(xmlFile,
- mXmlStringId,
- mTokenString,
- mXmlAttributeName,
- false, // allConfigurations
- status,
- SubMonitor.convert(submon, 1));
- if (changes != null) {
- mChanges.addAll(changes);
- }
- }
- }
- }
-
- monitor.worked(1);
- } finally {
- monitor.done();
- }
-
- return status;
- }
-
- // --- XML changes ---
-
- /**
- * Returns a foreach-compatible iterator over all XML files in the project's
- * /res folder, excluding the target XML file (the one where we'll write/edit
- * the string id).
- */
- private Iterable<IFile> findAllResXmlFiles() {
- return new Iterable<IFile>() {
- @Override
- public Iterator<IFile> iterator() {
- return new Iterator<IFile>() {
- final Queue<IFile> mFiles = new LinkedList<IFile>();
- final Queue<IResource> mFolders = new LinkedList<IResource>();
- IPath mFilterPath1 = null;
- IPath mFilterPath2 = null;
- {
- // Filter out the XML file where we'll be writing the XML string id.
- IResource filterRes = mProject.findMember(mTargetXmlFileWsPath);
- if (filterRes != null) {
- mFilterPath1 = filterRes.getFullPath();
- }
- // Filter out the XML source file, if any (e.g. typically a layout)
- if (mFile != null) {
- mFilterPath2 = mFile.getFullPath();
- }
-
- // We want to process the manifest
- IResource man = mProject.findMember("AndroidManifest.xml"); // TODO find a constant
- if (man.exists() && man instanceof IFile && !man.equals(mFile)) {
- mFiles.add((IFile) man);
- }
-
- // Add all /res folders (technically we don't need to process /res/values
- // XML files that contain resources/string elements, but it's easier to
- // not filter them out.)
- IFolder f = mProject.getFolder(AdtConstants.WS_RESOURCES);
- if (f.exists()) {
- try {
- mFolders.addAll(
- Arrays.asList(f.members(IContainer.EXCLUDE_DERIVED)));
- } catch (CoreException e) {
- // pass
- }
- }
- }
-
- @Override
- public boolean hasNext() {
- if (!mFiles.isEmpty()) {
- return true;
- }
-
- while (!mFolders.isEmpty()) {
- IResource res = mFolders.poll();
- if (res.exists() && res instanceof IFolder) {
- IFolder f = (IFolder) res;
- try {
- getFileList(f);
- if (!mFiles.isEmpty()) {
- return true;
- }
- } catch (CoreException e) {
- // pass
- }
- }
- }
- return false;
- }
-
- private void getFileList(IFolder folder) throws CoreException {
- for (IResource res : folder.members(IContainer.EXCLUDE_DERIVED)) {
- // Only accept file resources which are not derived and actually exist
- if (res.exists() && !res.isDerived() && res instanceof IFile) {
- IFile file = (IFile) res;
- // Must have an XML extension
- if (SdkConstants.EXT_XML.equals(file.getFileExtension())) {
- IPath p = file.getFullPath();
- // And not be either paths we want to filter out
- if ((mFilterPath1 != null && mFilterPath1.equals(p)) ||
- (mFilterPath2 != null && mFilterPath2.equals(p))) {
- continue;
- }
- mFiles.add(file);
- }
- }
- }
- }
-
- @Override
- public IFile next() {
- IFile file = mFiles.poll();
- hasNext();
- return file;
- }
-
- @Override
- public void remove() {
- throw new UnsupportedOperationException(
- "This iterator does not support removal"); //$NON-NLS-1$
- }
- };
- }
- };
- }
-
- /**
- * Internal helper that actually prepares the {@link Change} that adds the given
- * ID to the given XML File.
- * <p/>
- * This does not actually modify the file.
- *
- * @param targetXml The file resource to modify.
- * @param xmlStringId The new ID to insert.
- * @param tokenString The old string, which will be the value in the XML string.
- * @return A new {@link TextEdit} that describes how to change the file.
- */
- private Change createXmlChanges(IFile targetXml,
- String xmlStringId,
- String tokenString,
- RefactoringStatus status,
- SubMonitor monitor) {
-
- TextFileChange xmlChange = new TextFileChange(getName(), targetXml);
- xmlChange.setTextType(SdkConstants.EXT_XML);
-
- String error = ""; //$NON-NLS-1$
- TextEdit edit = null;
- TextEditGroup editGroup = null;
-
- try {
- if (!targetXml.exists()) {
- // Kludge: use targetXml==null as a signal this is a new file being created
- targetXml = null;
- }
-
- edit = createXmlReplaceEdit(targetXml, xmlStringId, tokenString, status,
- SubMonitor.convert(monitor, 1));
- } catch (IOException e) {
- error = e.toString();
- } catch (CoreException e) {
- // Failed to read file. Ignore. Will handle error below.
- error = e.toString();
- }
-
- if (edit == null) {
- status.addFatalError(String.format("Failed to modify file %1$s%2$s",
- targetXml == null ? "" : targetXml.getFullPath(), //$NON-NLS-1$
- error == null ? "" : ": " + error)); //$NON-NLS-1$
- return null;
- }
-
- editGroup = new TextEditGroup(targetXml == null ? "Create <string> in new XML file"
- : "Insert <string> in XML file",
- edit);
-
- xmlChange.setEdit(edit);
- // The TextEditChangeGroup let the user toggle this change on and off later.
- xmlChange.addTextEditChangeGroup(new TextEditChangeGroup(xmlChange, editGroup));
-
- monitor.worked(1);
- return xmlChange;
- }
-
- /**
- * Scan the XML file to find the best place where to insert the new string element.
- * <p/>
- * This handles a variety of cases, including replacing existing ids in place,
- * adding the top resources element if missing and the XML PI if not present.
- * It tries to preserve indentation when adding new elements at the end of an existing XML.
- *
- * @param file The XML file to modify, that must be present in the workspace.
- * Pass null to create a change for a new file that doesn't exist yet.
- * @param xmlStringId The new ID to insert.
- * @param tokenString The old string, which will be the value in the XML string.
- * @param status The in-out refactoring status. Used to log a more detailed error if the
- * XML has a top element that is not a resources element.
- * @param monitor A monitor to track progress.
- * @return A new {@link TextEdit} for either a replace or an insert operation, or null in case
- * of error.
- * @throws CoreException - if the file's contents or description can not be read.
- * @throws IOException - if the file's contents can not be read or its detected encoding does
- * not support its contents.
- */
- private TextEdit createXmlReplaceEdit(IFile file,
- String xmlStringId,
- String tokenString,
- RefactoringStatus status,
- SubMonitor monitor)
- throws IOException, CoreException {
-
- IModelManager modelMan = StructuredModelManager.getModelManager();
-
- final String NODE_RESOURCES = SdkConstants.TAG_RESOURCES;
- final String NODE_STRING = SdkConstants.TAG_STRING;
- final String ATTR_NAME = SdkConstants.ATTR_NAME;
-
-
- // Scan the source to find the best insertion point.
-
- // 1- The most common case we need to handle is the one of inserting at the end
- // of a valid XML document, respecting the whitespace last used.
- //
- // Ideally we have this structure:
- // <xml ...>
- // <resource>
- // ...ws1...<string>blah</string>...ws2...
- // </resource>
- //
- // where ws1 and ws2 are the whitespace respectively before and after the last element
- // just before the closing </resource>.
- // In this case we want to generate the new string just before ws2...</resource> with
- // the same whitespace as ws1.
- //
- // 2- Another expected case is there's already an existing string which "name" attribute
- // equals to xmlStringId and we just want to replace its value.
- //
- // Other cases we need to handle:
- // 3- There is no element at all -> create a full new <resource>+<string> content.
- // 4- There is <resource/>, that is the tag is not opened. This can be handled as the
- // previous case, generating full content but also replacing <resource/>.
- // 5- There is a top element that is not <resource>. That's a fatal error and we abort.
-
- IStructuredModel smodel = null;
-
- // Single and double quotes must be escaped in the <string>value</string> declaration
- tokenString = ValueXmlHelper.escapeResourceString(tokenString);
-
- try {
- IStructuredDocument sdoc = null;
- boolean checkTopElement = true;
- boolean replaceStringContent = false;
- boolean hasPiXml = false;
- int newResStart = 0;
- int newResLength = 0;
- String lineSep = "\n"; //$NON-NLS-1$
-
- if (file != null) {
- smodel = modelMan.getExistingModelForRead(file);
- if (smodel != null) {
- sdoc = smodel.getStructuredDocument();
- } else if (smodel == null) {
- // The model is not currently open.
- if (file.exists()) {
- sdoc = modelMan.createStructuredDocumentFor(file);
- } else {
- sdoc = modelMan.createNewStructuredDocumentFor(file);
- }
- }
- }
-
- if (sdoc == null && file != null) {
- // Get a document matching the actual saved file
- sdoc = modelMan.createStructuredDocumentFor(file);
- }
-
- if (sdoc != null) {
- String wsBefore = ""; //$NON-NLS-1$
- String lastWs = null;
-
- lineSep = sdoc.getLineDelimiter();
- if (lineSep == null || lineSep.length() == 0) {
- // That wasn't too useful, let's go back to a reasonable default
- lineSep = "\n"; //$NON-NLS-1$
- }
-
- for (IStructuredDocumentRegion regions : sdoc.getStructuredDocumentRegions()) {
- String type = regions.getType();
-
- if (DOMRegionContext.XML_CONTENT.equals(type)) {
-
- if (replaceStringContent) {
- // Generate a replacement for a <string> value matching the string ID.
- return new ReplaceEdit(
- regions.getStartOffset(), regions.getLength(), tokenString);
- }
-
- // Otherwise capture what should be whitespace content
- lastWs = regions.getFullText();
- continue;
-
- } else if (DOMRegionContext.XML_PI_OPEN.equals(type) && !hasPiXml) {
-
- int nb = regions.getNumberOfRegions();
- ITextRegionList list = regions.getRegions();
- for (int i = 0; i < nb; i++) {
- ITextRegion region = list.get(i);
- type = region.getType();
- if (DOMRegionContext.XML_TAG_NAME.equals(type)) {
- String name = regions.getText(region);
- if ("xml".equals(name)) { //$NON-NLS-1$
- hasPiXml = true;
- break;
- }
- }
- }
- continue;
-
- } else if (!DOMRegionContext.XML_TAG_NAME.equals(type)) {
- // ignore things which are not a tag nor text content (such as comments)
- continue;
- }
-
- int nb = regions.getNumberOfRegions();
- ITextRegionList list = regions.getRegions();
-
- String name = null;
- String attrName = null;
- String attrValue = null;
- boolean isEmptyTag = false;
- boolean isCloseTag = false;
-
- for (int i = 0; i < nb; i++) {
- ITextRegion region = list.get(i);
- type = region.getType();
-
- if (DOMRegionContext.XML_END_TAG_OPEN.equals(type)) {
- isCloseTag = true;
- } else if (DOMRegionContext.XML_EMPTY_TAG_CLOSE.equals(type)) {
- isEmptyTag = true;
- } else if (DOMRegionContext.XML_TAG_NAME.equals(type)) {
- name = regions.getText(region);
- } else if (DOMRegionContext.XML_TAG_ATTRIBUTE_NAME.equals(type) &&
- NODE_STRING.equals(name)) {
- // Record the attribute names into a <string> element.
- attrName = regions.getText(region);
- } else if (DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE.equals(type) &&
- ATTR_NAME.equals(attrName)) {
- // Record the value of a <string name=...> attribute
- attrValue = regions.getText(region);
-
- if (attrValue != null &&
- unquoteAttrValue(attrValue).equals(xmlStringId)) {
- // We found a <string name=> matching the string ID to replace.
- // We'll generate a replacement when we process the string value
- // (that is the next XML_CONTENT region.)
- replaceStringContent = true;
- }
- }
- }
-
- if (checkTopElement) {
- // Check the top element has a resource name
- checkTopElement = false;
- if (!NODE_RESOURCES.equals(name)) {
- status.addFatalError(
- String.format("XML file lacks a <resource> tag: %1$s",
- mTargetXmlFileWsPath));
- return null;
-
- }
-
- if (isEmptyTag) {
- // The top element is an empty "<resource/>" tag. We need to do
- // a full new resource+string replacement.
- newResStart = regions.getStartOffset();
- newResLength = regions.getLength();
- }
- }
-
- if (NODE_RESOURCES.equals(name)) {
- if (isCloseTag) {
- // We found the </resource> tag and we want
- // to insert just before this one.
-
- StringBuilder content = new StringBuilder();
- content.append(wsBefore)
- .append("<string name=\"") //$NON-NLS-1$
- .append(xmlStringId)
- .append("\">") //$NON-NLS-1$
- .append(tokenString)
- .append("</string>"); //$NON-NLS-1$
-
- // Backup to insert before the whitespace preceding </resource>
- IStructuredDocumentRegion insertBeforeReg = regions;
- while (true) {
- IStructuredDocumentRegion previous = insertBeforeReg.getPrevious();
- if (previous != null &&
- DOMRegionContext.XML_CONTENT.equals(previous.getType()) &&
- previous.getText().trim().length() == 0) {
- insertBeforeReg = previous;
- } else {
- break;
- }
- }
- if (insertBeforeReg == regions) {
- // If we have not found any whitespace before </resources>,
- // at least add a line separator.
- content.append(lineSep);
- }
-
- return new InsertEdit(insertBeforeReg.getStartOffset(),
- content.toString());
- }
- } else {
- // For any other tag than <resource>, capture whitespace before and after.
- if (!isCloseTag) {
- wsBefore = lastWs;
- }
- }
- }
- }
-
- // We reach here either because there's no XML content at all or because
- // there's an empty <resource/>.
- // Provide a full new resource+string replacement.
- StringBuilder content = new StringBuilder();
- if (!hasPiXml) {
- content.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); //$NON-NLS-1$
- content.append(lineSep);
- } else if (newResLength == 0 && sdoc != null) {
- // If inserting at the end, check if the last region is some whitespace.
- // If there's no newline, insert one ourselves.
- IStructuredDocumentRegion lastReg = sdoc.getLastStructuredDocumentRegion();
- if (lastReg != null && lastReg.getText().indexOf('\n') == -1) {
- content.append('\n');
- }
- }
-
- // FIXME how to access formatting preferences to generate the proper indentation?
- content.append("<resources>").append(lineSep); //$NON-NLS-1$
- content.append(" <string name=\"") //$NON-NLS-1$
- .append(xmlStringId)
- .append("\">") //$NON-NLS-1$
- .append(tokenString)
- .append("</string>") //$NON-NLS-1$
- .append(lineSep);
- content.append("</resources>").append(lineSep); //$NON-NLS-1$
-
- if (newResLength > 0) {
- // Replace existing piece
- return new ReplaceEdit(newResStart, newResLength, content.toString());
- } else {
- // Insert at the end.
- int offset = sdoc == null ? 0 : sdoc.getLength();
- return new InsertEdit(offset, content.toString());
- }
- } catch (IOException e) {
- // This is expected to happen and is properly reported to the UI.
- throw e;
- } catch (CoreException e) {
- // This is expected to happen and is properly reported to the UI.
- throw e;
- } catch (Throwable t) {
- // Since we use some internal APIs, use a broad catch-all to report any
- // unexpected issue rather than crash the whole refactoring.
- status.addFatalError(
- String.format("XML replace error: %1$s", t.getMessage()));
- } finally {
- if (smodel != null) {
- smodel.releaseFromRead();
- }
- }
-
- return null;
- }
-
- /**
- * Computes the changes to be made to the source Android XML file and
- * returns a list of {@link Change}.
- * <p/>
- * This function scans an XML file, looking for an attribute value equals to
- * <code>tokenString</code>. If non null, <code>xmlAttrName</code> limit the search
- * to only attributes that have that name.
- * If found, a change is made to replace each occurrence of <code>tokenString</code>
- * by a new "@string/..." using the new <code>xmlStringId</code>.
- *
- * @param sourceFile The file to process.
- * A status error will be generated if it does not exists.
- * Must not be null.
- * @param tokenString The string to find. Must not be null or empty.
- * @param xmlAttrName Optional attribute name to limit the search. Can be null.
- * @param allConfigurations True if this function should can all XML files with the same
- * name and the same resource type folder but with different configurations.
- * @param status Status used to report fatal errors.
- * @param monitor Used to log progress.
- */
- private List<Change> computeXmlSourceChanges(IFile sourceFile,
- String xmlStringId,
- String tokenString,
- String xmlAttrName,
- boolean allConfigurations,
- RefactoringStatus status,
- IProgressMonitor monitor) {
-
- if (!sourceFile.exists()) {
- status.addFatalError(String.format("XML file '%1$s' does not exist.",
- sourceFile.getFullPath().toOSString()));
- return null;
- }
-
- // We shouldn't be trying to replace a null or empty string.
- assert tokenString != null && tokenString.length() > 0;
- if (tokenString == null || tokenString.length() == 0) {
- return null;
- }
-
- // Note: initially this method was only processing files using a pattern
- // /project/res/<type>-<configuration>/<filename.xml>
- // However the last version made that more generic to be able to process any XML
- // files. We should probably revisit and simplify this later.
- HashSet<IFile> files = new HashSet<IFile>();
- files.add(sourceFile);
-
- if (allConfigurations && SdkConstants.EXT_XML.equals(sourceFile.getFileExtension())) {
- IPath path = sourceFile.getFullPath();
- if (path.segmentCount() == 4 && path.segment(1).equals(SdkConstants.FD_RESOURCES)) {
- IProject project = sourceFile.getProject();
- String filename = path.segment(3);
- String initialTypeName = path.segment(2);
- ResourceFolderType type = ResourceFolderType.getFolderType(initialTypeName);
-
- IContainer res = sourceFile.getParent().getParent();
- if (type != null && res != null && res.getType() == IResource.FOLDER) {
- try {
- for (IResource r : res.members()) {
- if (r != null && r.getType() == IResource.FOLDER) {
- String name = r.getName();
- // Skip the initial folder name, it's already in the list.
- if (!name.equals(initialTypeName)) {
- // Only accept the same folder type (e.g. layout-*)
- ResourceFolderType t =
- ResourceFolderType.getFolderType(name);
- if (type.equals(t)) {
- // recompute the path
- IPath p = res.getProjectRelativePath().append(name).
- append(filename);
- IResource f = project.findMember(p);
- if (f != null && f instanceof IFile) {
- files.add((IFile) f);
- }
- }
- }
- }
- }
- } catch (CoreException e) {
- // Ignore.
- }
- }
- }
- }
-
- SubMonitor subMonitor = SubMonitor.convert(monitor, Math.min(1, files.size()));
-
- ArrayList<Change> changes = new ArrayList<Change>();
-
- // Portability note: getModelManager is part of wst.sse.core however the
- // interface returned is part of wst.sse.core.internal.provisional so we can
- // expect it to change in a distant future if they start cleaning their codebase,
- // however unlikely that is.
- IModelManager modelManager = StructuredModelManager.getModelManager();
-
- for (IFile file : files) {
-
- IStructuredModel smodel = null;
- MultiTextEdit multiEdit = null;
- TextFileChange xmlChange = null;
- ArrayList<TextEditGroup> editGroups = null;
-
- try {
- IStructuredDocument sdoc = null;
-
- smodel = modelManager.getExistingModelForRead(file);
- if (smodel != null) {
- sdoc = smodel.getStructuredDocument();
- } else if (smodel == null) {
- // The model is not currently open.
- if (file.exists()) {
- sdoc = modelManager.createStructuredDocumentFor(file);
- } else {
- sdoc = modelManager.createNewStructuredDocumentFor(file);
- }
- }
-
- if (sdoc == null) {
- status.addFatalError("XML structured document not found"); //$NON-NLS-1$
- continue;
- }
-
- multiEdit = new MultiTextEdit();
- editGroups = new ArrayList<TextEditGroup>();
- xmlChange = new TextFileChange(getName(), file);
- xmlChange.setTextType("xml"); //$NON-NLS-1$
-
- String quotedReplacement = quotedAttrValue(STRING_PREFIX + xmlStringId);
-
- // Prepare the change set
- for (IStructuredDocumentRegion regions : sdoc.getStructuredDocumentRegions()) {
- // Only look at XML "top regions"
- if (!DOMRegionContext.XML_TAG_NAME.equals(regions.getType())) {
- continue;
- }
-
- int nb = regions.getNumberOfRegions();
- ITextRegionList list = regions.getRegions();
- String lastAttrName = null;
-
- for (int i = 0; i < nb; i++) {
- ITextRegion subRegion = list.get(i);
- String type = subRegion.getType();
-
- if (DOMRegionContext.XML_TAG_ATTRIBUTE_NAME.equals(type)) {
- // Memorize the last attribute name seen
- lastAttrName = regions.getText(subRegion);
-
- } else if (DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE.equals(type)) {
- // Check this is the attribute and the original string
- String text = regions.getText(subRegion);
-
- // Remove " or ' quoting present in the attribute value
- text = unquoteAttrValue(text);
-
- if (tokenString.equals(text) &&
- (xmlAttrName == null || xmlAttrName.equals(lastAttrName))) {
-
- // Found an occurrence. Create a change for it.
- TextEdit edit = new ReplaceEdit(
- regions.getStartOffset() + subRegion.getStart(),
- subRegion.getTextLength(),
- quotedReplacement);
- TextEditGroup editGroup = new TextEditGroup(
- "Replace attribute string by ID",
- edit);
-
- multiEdit.addChild(edit);
- editGroups.add(editGroup);
- }
- }
- }
- }
- } catch (Throwable t) {
- // Since we use some internal APIs, use a broad catch-all to report any
- // unexpected issue rather than crash the whole refactoring.
- status.addFatalError(
- String.format("XML refactoring error: %1$s", t.getMessage()));
- } finally {
- if (smodel != null) {
- smodel.releaseFromRead();
- }
-
- if (multiEdit != null &&
- xmlChange != null &&
- editGroups != null &&
- multiEdit.hasChildren()) {
- xmlChange.setEdit(multiEdit);
- for (TextEditGroup group : editGroups) {
- xmlChange.addTextEditChangeGroup(
- new TextEditChangeGroup(xmlChange, group));
- }
- changes.add(xmlChange);
- }
- subMonitor.worked(1);
- }
- } // for files
-
- if (changes.size() > 0) {
- return changes;
- }
- return null;
- }
-
- /**
- * Returns a quoted attribute value suitable to be placed after an attributeName=
- * statement in an XML stream.
- *
- * According to http://www.w3.org/TR/2008/REC-xml-20081126/#NT-AttValue
- * the attribute value can be either quoted using ' or " and the corresponding
- * entities &apos; or &quot; must be used inside.
- */
- private String quotedAttrValue(String attrValue) {
- if (attrValue.indexOf('"') == -1) {
- // no double-quotes inside, use double-quotes around.
- return '"' + attrValue + '"';
- }
- if (attrValue.indexOf('\'') == -1) {
- // no single-quotes inside, use single-quotes around.
- return '\'' + attrValue + '\'';
- }
- // If we get here, there's a mix. Opt for double-quote around and replace
- // inner double-quotes.
- attrValue = attrValue.replace("\"", QUOT_ENTITY); //$NON-NLS-1$
- return '"' + attrValue + '"';
- }
-
- // --- Java changes ---
-
- /**
- * Returns a foreach compatible iterator over all ICompilationUnit in the project.
- */
- private Iterable<ICompilationUnit> findAllJavaUnits() {
- final IJavaProject javaProject = JavaCore.create(mProject);
-
- return new Iterable<ICompilationUnit>() {
- @Override
- public Iterator<ICompilationUnit> iterator() {
- return new Iterator<ICompilationUnit>() {
- final Queue<ICompilationUnit> mUnits = new LinkedList<ICompilationUnit>();
- final Queue<IPackageFragment> mFragments = new LinkedList<IPackageFragment>();
- {
- try {
- IPackageFragment[] tmpFrags = javaProject.getPackageFragments();
- if (tmpFrags != null && tmpFrags.length > 0) {
- mFragments.addAll(Arrays.asList(tmpFrags));
- }
- } catch (JavaModelException e) {
- // pass
- }
- }
-
- @Override
- public boolean hasNext() {
- if (!mUnits.isEmpty()) {
- return true;
- }
-
- while (!mFragments.isEmpty()) {
- try {
- IPackageFragment fragment = mFragments.poll();
- if (fragment.getKind() == IPackageFragmentRoot.K_SOURCE) {
- ICompilationUnit[] tmpUnits = fragment.getCompilationUnits();
- if (tmpUnits != null && tmpUnits.length > 0) {
- mUnits.addAll(Arrays.asList(tmpUnits));
- return true;
- }
- }
- } catch (JavaModelException e) {
- // pass
- }
- }
- return false;
- }
-
- @Override
- public ICompilationUnit next() {
- ICompilationUnit unit = mUnits.poll();
- hasNext();
- return unit;
- }
-
- @Override
- public void remove() {
- throw new UnsupportedOperationException(
- "This iterator does not support removal"); //$NON-NLS-1$
- }
- };
- }
- };
- }
-
- /**
- * Computes the changes to be made to Java file(s) and returns a list of {@link Change}.
- * <p/>
- * This function scans a Java compilation unit using {@link ReplaceStringsVisitor}, looking
- * for a string literal equals to <code>tokenString</code>.
- * If found, a change is made to replace each occurrence of <code>tokenString</code> by
- * a piece of Java code that somehow accesses R.string.<code>xmlStringId</code>.
- *
- * @param unit The compilated unit to process. Must not be null.
- * @param tokenString The string to find. Must not be null or empty.
- * @param status Status used to report fatal errors.
- * @param monitor Used to log progress.
- */
- private List<Change> computeJavaChanges(ICompilationUnit unit,
- String xmlStringId,
- String tokenString,
- RefactoringStatus status,
- SubMonitor monitor) {
-
- // We shouldn't be trying to replace a null or empty string.
- assert tokenString != null && tokenString.length() > 0;
- if (tokenString == null || tokenString.length() == 0) {
- return null;
- }
-
- // Get the Android package name from the Android Manifest. We need it to create
- // the FQCN of the R class.
- String packageName = null;
- String error = null;
- IResource manifestFile = mProject.findMember(SdkConstants.FN_ANDROID_MANIFEST_XML);
- if (manifestFile == null || manifestFile.getType() != IResource.FILE) {
- error = "File not found";
- } else {
- ManifestData manifestData = AndroidManifestHelper.parseForData((IFile) manifestFile);
- if (manifestData == null) {
- error = "Invalid content";
- } else {
- packageName = manifestData.getPackage();
- if (packageName == null) {
- error = "Missing package definition";
- }
- }
- }
-
- if (error != null) {
- status.addFatalError(
- String.format("Failed to parse file %1$s: %2$s.",
- manifestFile == null ? "" : manifestFile.getFullPath(), //$NON-NLS-1$
- error));
- return null;
- }
-
- // Right now the changes array will contain one TextFileChange at most.
- ArrayList<Change> changes = new ArrayList<Change>();
-
- // This is the unit that will be modified.
- TextFileChange change = new TextFileChange(getName(), (IFile) unit.getResource());
- change.setTextType("java"); //$NON-NLS-1$
-
- // Create an AST for this compilation unit
- ASTParser parser = ASTParser.newParser(AST.JLS3);
- parser.setProject(unit.getJavaProject());
- parser.setSource(unit);
- parser.setResolveBindings(true);
- ASTNode node = parser.createAST(monitor.newChild(1));
-
- // The ASTNode must be a CompilationUnit, by design
- if (!(node instanceof CompilationUnit)) {
- status.addFatalError(String.format("Internal error: ASTNode class %s", //$NON-NLS-1$
- node.getClass()));
- return null;
- }
-
- // ImportRewrite will allow us to add the new type to the imports and will resolve
- // what the Java source must reference, e.g. the FQCN or just the simple name.
- ImportRewrite importRewrite = ImportRewrite.create((CompilationUnit) node, true);
- String Rqualifier = packageName + ".R"; //$NON-NLS-1$
- Rqualifier = importRewrite.addImport(Rqualifier);
-
- // Rewrite the AST itself via an ASTVisitor
- AST ast = node.getAST();
- ASTRewrite astRewrite = ASTRewrite.create(ast);
- ArrayList<TextEditGroup> astEditGroups = new ArrayList<TextEditGroup>();
- ReplaceStringsVisitor visitor = new ReplaceStringsVisitor(
- ast, astRewrite, astEditGroups,
- tokenString, Rqualifier, xmlStringId);
- node.accept(visitor);
-
- // Finally prepare the change set
- try {
- MultiTextEdit edit = new MultiTextEdit();
-
- // Create the edit to change the imports, only if anything changed
- TextEdit subEdit = importRewrite.rewriteImports(monitor.newChild(1));
- if (subEdit.hasChildren()) {
- edit.addChild(subEdit);
- }
-
- // Create the edit to change the Java source, only if anything changed
- subEdit = astRewrite.rewriteAST();
- if (subEdit.hasChildren()) {
- edit.addChild(subEdit);
- }
-
- // Only create a change set if any edit was collected
- if (edit.hasChildren()) {
- change.setEdit(edit);
-
- // Create TextEditChangeGroups which let the user turn changes on or off
- // individually. This must be done after the change.setEdit() call above.
- for (TextEditGroup editGroup : astEditGroups) {
- TextEditChangeGroup group = new TextEditChangeGroup(change, editGroup);
- if (editGroup instanceof EnabledTextEditGroup) {
- group.setEnabled(((EnabledTextEditGroup) editGroup).isEnabled());
- }
- change.addTextEditChangeGroup(group);
- }
-
- changes.add(change);
- }
-
- monitor.worked(1);
-
- if (changes.size() > 0) {
- return changes;
- }
-
- } catch (CoreException e) {
- // ImportRewrite.rewriteImports failed.
- status.addFatalError(e.getMessage());
- }
- return null;
- }
-
- // ----
-
- /**
- * Step 3 of 3 of the refactoring: returns the {@link Change} that will be able to do the
- * work and creates a descriptor that can be used to replay that refactoring later.
- *
- * @see org.eclipse.ltk.core.refactoring.Refactoring#createChange(org.eclipse.core.runtime.IProgressMonitor)
- *
- * @throws CoreException
- */
- @Override
- public Change createChange(IProgressMonitor monitor)
- throws CoreException, OperationCanceledException {
-
- try {
- monitor.beginTask("Applying changes...", 1);
-
- CompositeChange change = new CompositeChange(
- getName(),
- mChanges.toArray(new Change[mChanges.size()])) {
- @Override
- public ChangeDescriptor getDescriptor() {
-
- String comment = String.format(
- "Extracts string '%1$s' into R.string.%2$s",
- mTokenString,
- mXmlStringId);
-
- ExtractStringDescriptor desc = new ExtractStringDescriptor(
- mProject.getName(), //project
- comment, //description
- comment, //comment
- createArgumentMap());
-
- return new RefactoringChangeDescriptor(desc);
- }
- };
-
- monitor.worked(1);
-
- return change;
-
- } finally {
- monitor.done();
- }
-
- }
-
- /**
- * Given a file project path, returns its resource in the same project than the
- * compilation unit. The resource may not exist.
- */
- private IResource getTargetXmlResource(String xmlFileWsPath) {
- IResource resource = mProject.getFile(xmlFileWsPath);
- return resource;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringWizard.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringWizard.java
deleted file mode 100644
index 556dff0df..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ExtractStringWizard.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.refactorings.extractstring;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-
-/**
- * A wizard for ExtractString based on a simple dialog with one page.
- *
- * @see ExtractStringInputPage
- * @see ExtractStringRefactoring
- */
-public class ExtractStringWizard extends RefactoringWizard {
-
- private final IProject mProject;
-
- /**
- * Create a wizard for ExtractString based on a simple dialog with one page.
- *
- * @param ref The instance of {@link ExtractStringRefactoring} to associate to the wizard.
- * @param project The project where the wizard was invoked from (e.g. where the user selection
- * happened, so that we can retrieve project resources.)
- */
- public ExtractStringWizard(ExtractStringRefactoring ref, IProject project) {
- super(ref, DIALOG_BASED_USER_INTERFACE | PREVIEW_EXPAND_FIRST_NODE);
- mProject = project;
- setDefaultPageTitle(ref.getName());
- }
-
- @Override
- protected void addUserInputPages() {
- addPage(new ExtractStringInputPage(mProject));
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ReplaceStringsVisitor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ReplaceStringsVisitor.java
deleted file mode 100644
index e058ce1ba..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/ReplaceStringsVisitor.java
+++ /dev/null
@@ -1,480 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.refactorings.extractstring;
-
-import org.eclipse.jdt.core.dom.AST;
-import org.eclipse.jdt.core.dom.ASTNode;
-import org.eclipse.jdt.core.dom.ASTVisitor;
-import org.eclipse.jdt.core.dom.Assignment;
-import org.eclipse.jdt.core.dom.ClassInstanceCreation;
-import org.eclipse.jdt.core.dom.Expression;
-import org.eclipse.jdt.core.dom.IMethodBinding;
-import org.eclipse.jdt.core.dom.ITypeBinding;
-import org.eclipse.jdt.core.dom.IVariableBinding;
-import org.eclipse.jdt.core.dom.MethodDeclaration;
-import org.eclipse.jdt.core.dom.MethodInvocation;
-import org.eclipse.jdt.core.dom.Modifier;
-import org.eclipse.jdt.core.dom.Name;
-import org.eclipse.jdt.core.dom.SimpleName;
-import org.eclipse.jdt.core.dom.SimpleType;
-import org.eclipse.jdt.core.dom.SingleVariableDeclaration;
-import org.eclipse.jdt.core.dom.StringLiteral;
-import org.eclipse.jdt.core.dom.Type;
-import org.eclipse.jdt.core.dom.TypeDeclaration;
-import org.eclipse.jdt.core.dom.VariableDeclarationExpression;
-import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
-import org.eclipse.jdt.core.dom.VariableDeclarationStatement;
-import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.text.edits.TextEditGroup;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.TreeMap;
-
-/**
- * Visitor used by {@link ExtractStringRefactoring} to extract a string from an existing
- * Java source and replace it by an Android XML string reference.
- *
- * @see ExtractStringRefactoring#computeJavaChanges
- */
-class ReplaceStringsVisitor extends ASTVisitor {
-
- private static final String CLASS_ANDROID_CONTEXT = "android.content.Context"; //$NON-NLS-1$
- private static final String CLASS_JAVA_CHAR_SEQUENCE = "java.lang.CharSequence"; //$NON-NLS-1$
- private static final String CLASS_JAVA_STRING = "java.lang.String"; //$NON-NLS-1$
-
-
- private final AST mAst;
- private final ASTRewrite mRewriter;
- private final String mOldString;
- private final String mRQualifier;
- private final String mXmlId;
- private final ArrayList<TextEditGroup> mEditGroups;
-
- public ReplaceStringsVisitor(AST ast,
- ASTRewrite astRewrite,
- ArrayList<TextEditGroup> editGroups,
- String oldString,
- String rQualifier,
- String xmlId) {
- mAst = ast;
- mRewriter = astRewrite;
- mEditGroups = editGroups;
- mOldString = oldString;
- mRQualifier = rQualifier;
- mXmlId = xmlId;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public boolean visit(StringLiteral node) {
- if (node.getLiteralValue().equals(mOldString)) {
-
- // We want to analyze the calling context to understand whether we can
- // just replace the string literal by the named int constant (R.id.foo)
- // or if we should generate a Context.getString() call.
- boolean useGetResource = false;
- useGetResource = examineVariableDeclaration(node) ||
- examineMethodInvocation(node) ||
- examineAssignment(node);
-
- Name qualifierName = mAst.newName(mRQualifier + ".string"); //$NON-NLS-1$
- SimpleName idName = mAst.newSimpleName(mXmlId);
- ASTNode newNode = mAst.newQualifiedName(qualifierName, idName);
- boolean disabledChange = false;
- String title = "Replace string by ID";
-
- if (useGetResource) {
- Expression context = methodHasContextArgument(node);
- if (context == null && !isClassDerivedFromContext(node)) {
- // if we don't have a class that derives from Context and
- // we don't have a Context method argument, then try a bit harder:
- // can we find a method or a field that will give us a context?
- context = findContextFieldOrMethod(node);
-
- if (context == null) {
- // If not, let's write Context.getString(), which is technically
- // invalid but makes it a good clue on how to fix it. Since these
- // will not compile, we create a disabled change by default.
- context = mAst.newSimpleName("Context"); //$NON-NLS-1$
- disabledChange = true;
- }
- }
-
- MethodInvocation mi2 = mAst.newMethodInvocation();
- mi2.setName(mAst.newSimpleName("getString")); //$NON-NLS-1$
- mi2.setExpression(context);
- mi2.arguments().add(newNode);
-
- newNode = mi2;
- title = "Replace string by Context.getString(R.string...)";
- }
-
- TextEditGroup editGroup = new EnabledTextEditGroup(title, !disabledChange);
- mEditGroups.add(editGroup);
- mRewriter.replace(node, newNode, editGroup);
- }
- return super.visit(node);
- }
-
- /**
- * Examines if the StringLiteral is part of an assignment corresponding to the
- * a string variable declaration, e.g. String foo = id.
- *
- * The parent fragment is of syntax "var = expr" or "var[] = expr".
- * We want the type of the variable, which is either held by a
- * VariableDeclarationStatement ("type [fragment]") or by a
- * VariableDeclarationExpression. In either case, the type can be an array
- * but for us all that matters is to know whether the type is an int or
- * a string.
- */
- private boolean examineVariableDeclaration(StringLiteral node) {
- VariableDeclarationFragment fragment = findParentClass(node,
- VariableDeclarationFragment.class);
-
- if (fragment != null) {
- ASTNode parent = fragment.getParent();
-
- Type type = null;
- if (parent instanceof VariableDeclarationStatement) {
- type = ((VariableDeclarationStatement) parent).getType();
- } else if (parent instanceof VariableDeclarationExpression) {
- type = ((VariableDeclarationExpression) parent).getType();
- }
-
- if (type instanceof SimpleType) {
- return isJavaString(type.resolveBinding());
- }
- }
-
- return false;
- }
-
- /**
- * Examines if the StringLiteral is part of a assignment to a variable that
- * is a string. We need to lookup the variable to find its type, either in the
- * enclosing method or class type.
- */
- private boolean examineAssignment(StringLiteral node) {
-
- Assignment assignment = findParentClass(node, Assignment.class);
- if (assignment != null) {
- Expression left = assignment.getLeftHandSide();
-
- ITypeBinding typeBinding = left.resolveTypeBinding();
- return isJavaString(typeBinding);
- }
-
- return false;
- }
-
- /**
- * If the expression is part of a method invocation (aka a function call) or a
- * class instance creation (aka a "new SomeClass" constructor call), we try to
- * find the type of the argument being used. If it is a String (most likely), we
- * want to return true (to generate a getString() call). However if there might
- * be a similar method that takes an int, in which case we don't want to do that.
- *
- * This covers the case of Activity.setTitle(int resId) vs setTitle(String str).
- */
- @SuppressWarnings("rawtypes")
- private boolean examineMethodInvocation(StringLiteral node) {
-
- ASTNode parent = null;
- List arguments = null;
- IMethodBinding methodBinding = null;
-
- MethodInvocation invoke = findParentClass(node, MethodInvocation.class);
- if (invoke != null) {
- parent = invoke;
- arguments = invoke.arguments();
- methodBinding = invoke.resolveMethodBinding();
- } else {
- ClassInstanceCreation newclass = findParentClass(node, ClassInstanceCreation.class);
- if (newclass != null) {
- parent = newclass;
- arguments = newclass.arguments();
- methodBinding = newclass.resolveConstructorBinding();
- }
- }
-
- if (parent != null && arguments != null && methodBinding != null) {
- // We want to know which argument this is.
- // Walk up the hierarchy again to find the immediate child of the parent,
- // which should turn out to be one of the invocation arguments.
- ASTNode child = null;
- for (ASTNode n = node; n != parent; ) {
- ASTNode p = n.getParent();
- if (p == parent) {
- child = n;
- break;
- }
- n = p;
- }
- if (child == null) {
- // This can't happen: a parent of 'node' must be the child of 'parent'.
- return false;
- }
-
- // Find the index
- int index = 0;
- for (Object arg : arguments) {
- if (arg == child) {
- break;
- }
- index++;
- }
-
- if (index == arguments.size()) {
- // This can't happen: one of the arguments of 'invoke' must be 'child'.
- return false;
- }
-
- // Eventually we want to determine if the parameter is a string type,
- // in which case a Context.getString() call must be generated.
- boolean useStringType = false;
-
- // Find the type of that argument
- ITypeBinding[] types = methodBinding.getParameterTypes();
- if (index < types.length) {
- ITypeBinding type = types[index];
- useStringType = isJavaString(type);
- }
-
- // Now that we know that this method takes a String parameter, can we find
- // a variant that would accept an int for the same parameter position?
- if (useStringType) {
- String name = methodBinding.getName();
- ITypeBinding clazz = methodBinding.getDeclaringClass();
- nextMethod: for (IMethodBinding mb2 : clazz.getDeclaredMethods()) {
- if (methodBinding == mb2 || !mb2.getName().equals(name)) {
- continue;
- }
- // We found a method with the same name. We want the same parameters
- // except that the one at 'index' must be an int type.
- ITypeBinding[] types2 = mb2.getParameterTypes();
- int len2 = types2.length;
- if (types.length == len2) {
- for (int i = 0; i < len2; i++) {
- if (i == index) {
- ITypeBinding type2 = types2[i];
- if (!("int".equals(type2.getQualifiedName()))) { //$NON-NLS-1$
- // The argument at 'index' is not an int.
- continue nextMethod;
- }
- } else if (!types[i].equals(types2[i])) {
- // One of the other arguments do not match our original method
- continue nextMethod;
- }
- }
- // If we got here, we found a perfect match: a method with the same
- // arguments except the one at 'index' is an int. In this case we
- // don't need to convert our R.id into a string.
- useStringType = false;
- break;
- }
- }
- }
-
- return useStringType;
- }
- return false;
- }
-
- /**
- * Examines if the StringLiteral is part of a method declaration (a.k.a. a function
- * definition) which takes a Context argument.
- * If such, it returns the name of the variable as a {@link SimpleName}.
- * Otherwise it returns null.
- */
- private SimpleName methodHasContextArgument(StringLiteral node) {
- MethodDeclaration decl = findParentClass(node, MethodDeclaration.class);
- if (decl != null) {
- for (Object obj : decl.parameters()) {
- if (obj instanceof SingleVariableDeclaration) {
- SingleVariableDeclaration var = (SingleVariableDeclaration) obj;
- if (isAndroidContext(var.getType())) {
- return mAst.newSimpleName(var.getName().getIdentifier());
- }
- }
- }
- }
- return null;
- }
-
- /**
- * Walks up the node hierarchy to find the class (aka type) where this statement
- * is used and returns true if this class derives from android.content.Context.
- */
- private boolean isClassDerivedFromContext(StringLiteral node) {
- TypeDeclaration clazz = findParentClass(node, TypeDeclaration.class);
- if (clazz != null) {
- // This is the class that the user is currently writing, so it can't be
- // a Context by itself, it has to be derived from it.
- return isAndroidContext(clazz.getSuperclassType());
- }
- return false;
- }
-
- private Expression findContextFieldOrMethod(StringLiteral node) {
- TypeDeclaration clazz = findParentClass(node, TypeDeclaration.class);
- return clazz == null ? null : findContextFieldOrMethod(clazz.resolveBinding());
- }
-
- private Expression findContextFieldOrMethod(ITypeBinding clazzType) {
- TreeMap<Integer, Expression> results = new TreeMap<Integer, Expression>();
- findContextCandidates(results, clazzType, 0 /*superType*/);
- if (results.size() > 0) {
- Integer bestRating = results.keySet().iterator().next();
- return results.get(bestRating);
- }
- return null;
- }
-
- /**
- * Find all method or fields that are candidates for providing a Context.
- * There can be various choices amongst this class or its super classes.
- * Sort them by rating in the results map.
- *
- * The best ever choice is to find a method with no argument that returns a Context.
- * The second suitable choice is to find a Context field.
- * The least desirable choice is to find a method with arguments. It's not really
- * desirable since we can't generate these arguments automatically.
- *
- * Methods and fields from supertypes are ignored if they are private.
- *
- * The rating is reversed: the lowest rating integer is used for the best candidate.
- * Because the superType argument is actually a recursion index, this makes the most
- * immediate classes more desirable.
- *
- * @param results The map that accumulates the rating=>expression results. The lower
- * rating number is the best candidate.
- * @param clazzType The class examined.
- * @param superType The recursion index.
- * 0 for the immediate class, 1 for its super class, etc.
- */
- private void findContextCandidates(TreeMap<Integer, Expression> results,
- ITypeBinding clazzType,
- int superType) {
- for (IMethodBinding mb : clazzType.getDeclaredMethods()) {
- // If we're looking at supertypes, we can't use private methods.
- if (superType != 0 && Modifier.isPrivate(mb.getModifiers())) {
- continue;
- }
-
- if (isAndroidContext(mb.getReturnType())) {
- // We found a method that returns something derived from Context.
-
- int argsLen = mb.getParameterTypes().length;
- if (argsLen == 0) {
- // We'll favor any method that takes no argument,
- // That would be the best candidate ever, so we can stop here.
- MethodInvocation mi = mAst.newMethodInvocation();
- mi.setName(mAst.newSimpleName(mb.getName()));
- results.put(Integer.MIN_VALUE, mi);
- return;
- } else {
- // A method with arguments isn't as interesting since we wouldn't
- // know how to populate such arguments. We'll use it if there are
- // no other alternatives. We'll favor the one with the less arguments.
- Integer rating = Integer.valueOf(10000 + 1000 * superType + argsLen);
- if (!results.containsKey(rating)) {
- MethodInvocation mi = mAst.newMethodInvocation();
- mi.setName(mAst.newSimpleName(mb.getName()));
- results.put(rating, mi);
- }
- }
- }
- }
-
- // A direct Context field would be more interesting than a method with
- // arguments. Try to find one.
- for (IVariableBinding var : clazzType.getDeclaredFields()) {
- // If we're looking at supertypes, we can't use private field.
- if (superType != 0 && Modifier.isPrivate(var.getModifiers())) {
- continue;
- }
-
- if (isAndroidContext(var.getType())) {
- // We found such a field. Let's use it.
- Integer rating = Integer.valueOf(superType);
- results.put(rating, mAst.newSimpleName(var.getName()));
- break;
- }
- }
-
- // Examine the super class to see if we can locate a better match
- clazzType = clazzType.getSuperclass();
- if (clazzType != null) {
- findContextCandidates(results, clazzType, superType + 1);
- }
- }
-
- /**
- * Walks up the node hierarchy and returns the first ASTNode of the requested class.
- * Only look at parents.
- *
- * Implementation note: this is a generic method so that it returns the node already
- * casted to the requested type.
- */
- @SuppressWarnings("unchecked")
- private <T extends ASTNode> T findParentClass(ASTNode node, Class<T> clazz) {
- if (node != null) {
- for (node = node.getParent(); node != null; node = node.getParent()) {
- if (node.getClass().equals(clazz)) {
- return (T) node;
- }
- }
- }
- return null;
- }
-
- /**
- * Returns true if the given type is or derives from android.content.Context.
- */
- private boolean isAndroidContext(Type type) {
- if (type != null) {
- return isAndroidContext(type.resolveBinding());
- }
- return false;
- }
-
- /**
- * Returns true if the given type is or derives from android.content.Context.
- */
- private boolean isAndroidContext(ITypeBinding type) {
- for (; type != null; type = type.getSuperclass()) {
- if (CLASS_ANDROID_CONTEXT.equals(type.getQualifiedName())) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Returns true if this type binding represents a String or CharSequence type.
- */
- private boolean isJavaString(ITypeBinding type) {
- for (; type != null; type = type.getSuperclass()) {
- if (CLASS_JAVA_STRING.equals(type.getQualifiedName()) ||
- CLASS_JAVA_CHAR_SEQUENCE.equals(type.getQualifiedName())) {
- return true;
- }
- }
- return false;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/XmlStringFileHelper.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/XmlStringFileHelper.java
deleted file mode 100644
index 01e814ef2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/extractstring/XmlStringFileHelper.java
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.refactorings.extractstring;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.wst.sse.core.StructuredModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMDocument;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.TreeMap;
-
-/**
- * An helper utility to get IDs out of an Android XML resource file.
- */
-@SuppressWarnings("restriction")
-class XmlStringFileHelper {
-
- /** A temporary cache of R.string IDs defined by a given xml file. The key is the
- * project path of the file, the data is a set of known string Ids for that file.
- *
- * Map type: map [String filename] => map [String id => String value].
- */
- private HashMap<String, Map<String, String>> mResIdCache =
- new HashMap<String, Map<String, String>>();
-
- public XmlStringFileHelper() {
- }
-
- /**
- * Utility method used by the wizard to retrieve the actual value definition of a given
- * string ID.
- *
- * @param project The project contain the XML file.
- * @param xmlFileWsPath The project path of the XML file, e.g. "/res/values/strings.xml".
- * The given file may or may not exist.
- * @param stringId The string ID to find.
- * @return The value string if the ID is defined, null otherwise.
- */
- public String valueOfStringId(IProject project, String xmlFileWsPath, String stringId) {
- Map<String, String> cache = getResIdsForFile(project, xmlFileWsPath);
- return cache.get(stringId);
- }
-
- /**
- * Utility method that retrieves all the *string* IDs defined in the given Android resource
- * file. The instance maintains an internal cache so a given file is retrieved only once.
- * Callers should consider the set to be read-only.
- *
- * @param project The project contain the XML file.
- * @param xmlFileWsPath The project path of the XML file, e.g. "/res/values/strings.xml".
- * The given file may or may not exist.
- * @return The map of string IDs => values defined in the given file. Cached. Never null.
- */
- public Map<String, String> getResIdsForFile(IProject project, String xmlFileWsPath) {
- Map<String, String> cache = mResIdCache.get(xmlFileWsPath);
- if (cache == null) {
- cache = internalGetResIdsForFile(project, xmlFileWsPath);
- mResIdCache.put(xmlFileWsPath, cache);
- }
- return cache;
- }
-
- /**
- * Extract all the defined string IDs from a given file using XPath.
- * @param project The project contain the XML file.
- * @param xmlFileWsPath The project path of the file to parse. It may not exist.
- * @return The map of all string IDs => values defined in the file.
- * The returned set is always non null. It is empty if the file does not exist.
- */
- private Map<String, String> internalGetResIdsForFile(IProject project, String xmlFileWsPath) {
-
- TreeMap<String, String> ids = new TreeMap<String, String>();
-
- // Access the project that contains the resource that contains the compilation unit
- IResource resource = project.getFile(xmlFileWsPath);
-
- if (resource != null && resource.exists() && resource.getType() == IResource.FILE) {
- IStructuredModel smodel = null;
-
- try {
- IFile file = (IFile) resource;
- IModelManager modelMan = StructuredModelManager.getModelManager();
- smodel = modelMan.getExistingModelForRead(file);
- if (smodel == null) {
- smodel = modelMan.getModelForRead(file);
- }
-
- if (smodel instanceof IDOMModel) {
- IDOMDocument doc = ((IDOMModel) smodel).getDocument();
-
- // We want all the IDs in an XML structure like this:
- // <resources>
- // <string name="ID">something</string>
- // </resources>
-
- Node root = findChild(doc, null, SdkConstants.TAG_RESOURCES);
- if (root != null) {
- for (Node strNode = findChild(root, null,
- SdkConstants.TAG_STRING);
- strNode != null;
- strNode = findChild(null, strNode,
- SdkConstants.TAG_STRING)) {
- NamedNodeMap attrs = strNode.getAttributes();
- Node nameAttr = attrs.getNamedItem(SdkConstants.ATTR_NAME);
- if (nameAttr != null) {
- String id = nameAttr.getNodeValue();
-
- // Find the TEXT node right after the element.
- // Whitespace matters so we don't try to normalize it.
- String text = ""; //$NON-NLS-1$
- for (Node txtNode = strNode.getFirstChild();
- txtNode != null && txtNode.getNodeType() == Node.TEXT_NODE;
- txtNode = txtNode.getNextSibling()) {
- text += txtNode.getNodeValue();
- }
-
- ids.put(id, text);
- }
- }
- }
- }
-
- } catch (Throwable e) {
- AdtPlugin.log(e, "GetResIds failed in %1$s", xmlFileWsPath); //$NON-NLS-1$
- } finally {
- if (smodel != null) {
- smodel.releaseFromRead();
- }
- }
- }
-
- return ids;
- }
-
- /**
- * Utility method that finds the next node of the requested element name.
- *
- * @param parent The parent node. If not null, will to start searching its children.
- * Set to null when iterating through children.
- * @param lastChild The last child returned. Use null when visiting a parent the first time.
- * @param elementName The element name of the node to find.
- * @return The next children or sibling nide with the requested element name or null.
- */
- private Node findChild(Node parent, Node lastChild, String elementName) {
- if (lastChild == null && parent != null) {
- lastChild = parent.getFirstChild();
- } else if (lastChild != null) {
- lastChild = lastChild.getNextSibling();
- }
-
- for ( ; lastChild != null ; lastChild = lastChild.getNextSibling()) {
- if (lastChild.getNodeType() == Node.ELEMENT_NODE &&
- lastChild.getNamespaceURI() == null && // resources don't have any NS URI
- elementName.equals(lastChild.getLocalName())) {
- return lastChild;
- }
- }
-
- return null;
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/renamepackage/ApplicationPackageNameRefactoring.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/renamepackage/ApplicationPackageNameRefactoring.java
deleted file mode 100644
index 406cebca4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/renamepackage/ApplicationPackageNameRefactoring.java
+++ /dev/null
@@ -1,586 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.refactorings.renamepackage;
-
-import static com.android.SdkConstants.FN_BUILD_CONFIG_BASE;
-import static com.android.SdkConstants.FN_MANIFEST_BASE;
-import static com.android.SdkConstants.FN_RESOURCE_BASE;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.xml.AndroidManifest;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceVisitor;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jdt.core.ICompilationUnit;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.core.dom.AST;
-import org.eclipse.jdt.core.dom.ASTParser;
-import org.eclipse.jdt.core.dom.ASTVisitor;
-import org.eclipse.jdt.core.dom.CompilationUnit;
-import org.eclipse.jdt.core.dom.ImportDeclaration;
-import org.eclipse.jdt.core.dom.Name;
-import org.eclipse.jdt.core.dom.QualifiedName;
-import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
-import org.eclipse.jdt.core.dom.rewrite.ImportRewrite;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextEditChangeGroup;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.text.edits.TextEditGroup;
-import org.eclipse.wst.sse.core.StructuredModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocumentRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.ITextRegionList;
-import org.eclipse.wst.xml.core.internal.regions.DOMRegionContext;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * Wrapper class defining the stages of the refactoring process
- */
-@SuppressWarnings("restriction")
-class ApplicationPackageNameRefactoring extends Refactoring {
- private final IProject mProject;
- private final Name mOldPackageName;
- private final Name mNewPackageName;
-
- List<String> MAIN_COMPONENT_TYPES_LIST = Arrays.asList(MAIN_COMPONENT_TYPES);
-
- ApplicationPackageNameRefactoring(
- IProject project,
- Name oldPackageName,
- Name newPackageName) {
- mProject = project;
- mOldPackageName = oldPackageName;
- mNewPackageName = newPackageName;
- }
-
- @Override
- public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
- throws CoreException, OperationCanceledException {
-
- // Accurate refactoring of the "shorthand" names in
- // AndroidManifest.xml depends on not having compilation errors.
- if (mProject.findMaxProblemSeverity(
- IMarker.PROBLEM,
- true,
- IResource.DEPTH_INFINITE) == IMarker.SEVERITY_ERROR) {
- return
- RefactoringStatus.createFatalErrorStatus("Fix the errors in your project, first.");
- }
-
- return new RefactoringStatus();
- }
-
- @Override
- public RefactoringStatus checkFinalConditions(IProgressMonitor pm)
- throws OperationCanceledException {
-
- return new RefactoringStatus();
- }
-
- @Override
- public Change createChange(IProgressMonitor pm) throws CoreException,
- OperationCanceledException {
-
- // Traverse all files in the project, building up a list of changes
- JavaFileVisitor fileVisitor = new JavaFileVisitor();
- mProject.accept(fileVisitor);
- return fileVisitor.getChange();
- }
-
- @Override
- public String getName() {
- return "AndroidPackageNameRefactoring"; //$NON-NLS-1$
- }
-
- public final static String[] MAIN_COMPONENT_TYPES = {
- AndroidManifest.NODE_ACTIVITY, AndroidManifest.NODE_SERVICE,
- AndroidManifest.NODE_RECEIVER, AndroidManifest.NODE_PROVIDER,
- AndroidManifest.NODE_APPLICATION
- };
-
-
- TextEdit updateJavaFileImports(CompilationUnit cu) {
-
- ImportVisitor importVisitor = new ImportVisitor(cu.getAST());
- cu.accept(importVisitor);
- TextEdit rewrittenImports = importVisitor.getTextEdit();
-
- // If the import of R was potentially implicit, insert an import statement
- if (rewrittenImports != null && cu.getPackage().getName().getFullyQualifiedName()
- .equals(mOldPackageName.getFullyQualifiedName())) {
-
- UsageVisitor usageVisitor = new UsageVisitor();
- cu.accept(usageVisitor);
-
- if (usageVisitor.seenAny()) {
- ImportRewrite irw = ImportRewrite.create(cu, true);
- if (usageVisitor.hasSeenR()) {
- irw.addImport(mNewPackageName.getFullyQualifiedName() + '.'
- + FN_RESOURCE_BASE);
- }
- if (usageVisitor.hasSeenBuildConfig()) {
- irw.addImport(mNewPackageName.getFullyQualifiedName() + '.'
- + FN_BUILD_CONFIG_BASE);
- }
- if (usageVisitor.hasSeenManifest()) {
- irw.addImport(mNewPackageName.getFullyQualifiedName() + '.'
- + FN_MANIFEST_BASE);
- }
-
- try {
- rewrittenImports.addChild( irw.rewriteImports(null) );
- } catch (MalformedTreeException e) {
- Status s = new Status(Status.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e);
- AdtPlugin.getDefault().getLog().log(s);
- } catch (CoreException e) {
- Status s = new Status(Status.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e);
- AdtPlugin.getDefault().getLog().log(s);
- }
- }
- }
-
- return rewrittenImports;
- }
-
- // XML utility functions
- private String stripQuotes(String text) {
- int len = text.length();
- if (len >= 2 && text.charAt(0) == '"' && text.charAt(len - 1) == '"') {
- return text.substring(1, len - 1);
- } else if (len >= 2 && text.charAt(0) == '\'' && text.charAt(len - 1) == '\'') {
- return text.substring(1, len - 1);
- }
- return text;
- }
-
- private String addQuotes(String text) {
- return '"' + text + '"';
- }
-
- /*
- * Make the appropriate package name changes to a resource file,
- * e.g. .xml files in res/layout. This entails updating the namespace
- * declarations for custom styleable attributes. The namespace prefix
- * is user-defined and may be declared in any element where or parent
- * element of where the prefix is used.
- */
- TextFileChange editXmlResourceFile(IFile file) {
-
- IModelManager modelManager = StructuredModelManager.getModelManager();
- IStructuredDocument sdoc = null;
- try {
- sdoc = modelManager.createStructuredDocumentFor(file);
- } catch (IOException e) {
- Status s = new Status(Status.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e);
- AdtPlugin.getDefault().getLog().log(s);
- } catch (CoreException e) {
- Status s = new Status(Status.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e);
- AdtPlugin.getDefault().getLog().log(s);
- }
-
- if (sdoc == null) {
- return null;
- }
-
- TextFileChange xmlChange = new TextFileChange("XML resource file edit", file);
- xmlChange.setTextType(SdkConstants.EXT_XML);
-
- MultiTextEdit multiEdit = new MultiTextEdit();
- ArrayList<TextEditGroup> editGroups = new ArrayList<TextEditGroup>();
-
- final String oldAppNamespaceString = String.format(AdtConstants.NS_CUSTOM_RESOURCES,
- mOldPackageName.getFullyQualifiedName());
- final String newAppNamespaceString = String.format(AdtConstants.NS_CUSTOM_RESOURCES,
- mNewPackageName.getFullyQualifiedName());
-
- // Prepare the change set
- for (IStructuredDocumentRegion region : sdoc.getStructuredDocumentRegions()) {
-
- if (!DOMRegionContext.XML_TAG_NAME.equals(region.getType())) {
- continue;
- }
-
- int nb = region.getNumberOfRegions();
- ITextRegionList list = region.getRegions();
- String lastAttrName = null;
-
- for (int i = 0; i < nb; i++) {
- ITextRegion subRegion = list.get(i);
- String type = subRegion.getType();
-
- if (DOMRegionContext.XML_TAG_ATTRIBUTE_NAME.equals(type)) {
- // Memorize the last attribute name seen
- lastAttrName = region.getText(subRegion);
-
- } else if (DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE.equals(type)) {
- // Check this is the attribute and the original string
-
- if (lastAttrName != null &&
- lastAttrName.startsWith(SdkConstants.XMLNS_PREFIX)) {
-
- String lastAttrValue = region.getText(subRegion);
- if (oldAppNamespaceString.equals(stripQuotes(lastAttrValue))) {
-
- // Found an occurrence. Create a change for it.
- TextEdit edit = new ReplaceEdit(
- region.getStartOffset() + subRegion.getStart(),
- subRegion.getTextLength(),
- addQuotes(newAppNamespaceString));
- TextEditGroup editGroup = new TextEditGroup(
- "Replace package name in custom namespace prefix", edit);
-
- multiEdit.addChild(edit);
- editGroups.add(editGroup);
- }
- }
- }
- }
- }
-
- if (multiEdit.hasChildren()) {
- xmlChange.setEdit(multiEdit);
- for (TextEditGroup group : editGroups) {
- xmlChange.addTextEditChangeGroup(new TextEditChangeGroup(xmlChange, group));
- }
-
- return xmlChange;
- }
- return null;
- }
-
- /*
- * Replace all instances of the package name in AndroidManifest.xml.
- * This includes expanding shorthand paths for each Component (Activity,
- * Service, etc.) and of course updating the application package name.
- * The namespace prefix might not be "android", so we resolve it
- * dynamically.
- */
- TextFileChange editAndroidManifest(IFile file) {
-
- IModelManager modelManager = StructuredModelManager.getModelManager();
- IStructuredDocument sdoc = null;
- try {
- sdoc = modelManager.createStructuredDocumentFor(file);
- } catch (IOException e) {
- Status s = new Status(Status.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e);
- AdtPlugin.getDefault().getLog().log(s);
- } catch (CoreException e) {
- Status s = new Status(Status.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e);
- AdtPlugin.getDefault().getLog().log(s);
- }
-
- if (sdoc == null) {
- return null;
- }
-
- TextFileChange xmlChange = new TextFileChange("Make Manifest edits", file);
- xmlChange.setTextType(SdkConstants.EXT_XML);
-
- MultiTextEdit multiEdit = new MultiTextEdit();
- ArrayList<TextEditGroup> editGroups = new ArrayList<TextEditGroup>();
-
- // The namespace prefix is guaranteed to be resolved before
- // the first use of this attribute
- String android_name_attribute = null;
-
- // Prepare the change set
- for (IStructuredDocumentRegion region : sdoc.getStructuredDocumentRegions()) {
-
- // Only look at XML "top regions"
- if (!DOMRegionContext.XML_TAG_NAME.equals(region.getType())) {
- continue;
- }
-
- int nb = region.getNumberOfRegions();
- ITextRegionList list = region.getRegions();
- String lastTagName = null, lastAttrName = null;
-
- for (int i = 0; i < nb; i++) {
- ITextRegion subRegion = list.get(i);
- String type = subRegion.getType();
-
- if (DOMRegionContext.XML_TAG_NAME.equals(type)) {
- // Memorize the last tag name seen
- lastTagName = region.getText(subRegion);
-
- } else if (DOMRegionContext.XML_TAG_ATTRIBUTE_NAME.equals(type)) {
- // Memorize the last attribute name seen
- lastAttrName = region.getText(subRegion);
-
- } else if (DOMRegionContext.XML_TAG_ATTRIBUTE_VALUE.equals(type)) {
-
- String lastAttrValue = region.getText(subRegion);
- if (lastAttrName != null &&
- lastAttrName.startsWith(SdkConstants.XMLNS_PREFIX)) {
-
- // Resolves the android namespace prefix for this file
- if (SdkConstants.ANDROID_URI.equals(stripQuotes(lastAttrValue))) {
- String android_namespace_prefix = lastAttrName
- .substring(SdkConstants.XMLNS_PREFIX.length());
- android_name_attribute = android_namespace_prefix + ':'
- + AndroidManifest.ATTRIBUTE_NAME;
- }
- } else if (AndroidManifest.NODE_MANIFEST.equals(lastTagName)
- && AndroidManifest.ATTRIBUTE_PACKAGE.equals(lastAttrName)) {
-
- // Found an occurrence. Create a change for it.
- TextEdit edit = new ReplaceEdit(region.getStartOffset()
- + subRegion.getStart(), subRegion.getTextLength(),
- addQuotes(mNewPackageName.getFullyQualifiedName()));
-
- multiEdit.addChild(edit);
- editGroups.add(new TextEditGroup("Change Android package name", edit));
-
- } else if (MAIN_COMPONENT_TYPES_LIST.contains(lastTagName)
- && lastAttrName != null
- && lastAttrName.equals(android_name_attribute)) {
-
- String package_path = stripQuotes(lastAttrValue);
- String old_package_name_string = mOldPackageName.getFullyQualifiedName();
-
- String absolute_path = AndroidManifest.combinePackageAndClassName(
- old_package_name_string, package_path);
-
- TextEdit edit = new ReplaceEdit(region.getStartOffset()
- + subRegion.getStart(), subRegion.getTextLength(),
- addQuotes(absolute_path));
-
- multiEdit.addChild(edit);
-
- editGroups.add(new TextEditGroup("Update component path", edit));
- }
- }
- }
- }
-
- if (multiEdit.hasChildren()) {
- xmlChange.setEdit(multiEdit);
- for (TextEditGroup group : editGroups) {
- xmlChange.addTextEditChangeGroup(new TextEditChangeGroup(xmlChange, group));
- }
-
- return xmlChange;
- }
- return null;
- }
-
-
- /*
- * Iterates through all project files, taking distinct actions based on
- * whether the file is:
- * 1) a .java file (replaces or inserts the "import" statements)
- * 2) a .xml layout file (updates namespace declarations)
- * 3) the AndroidManifest.xml
- */
- class JavaFileVisitor implements IResourceVisitor {
-
- final List<TextFileChange> mChanges = new ArrayList<TextFileChange>();
-
- final ASTParser mParser = ASTParser.newParser(AST.JLS3);
-
- public CompositeChange getChange() {
-
- Collections.reverse(mChanges);
- CompositeChange change = new CompositeChange("Refactoring Application package name",
- mChanges.toArray(new Change[mChanges.size()]));
- change.markAsSynthetic();
- return change;
- }
-
- @Override
- public boolean visit(IResource resource) throws CoreException {
- if (resource instanceof IFile) {
- IFile file = (IFile) resource;
- if (SdkConstants.EXT_JAVA.equals(file.getFileExtension())) {
-
- ICompilationUnit icu = JavaCore.createCompilationUnitFrom(file);
-
- mParser.setSource(icu);
- CompilationUnit cu = (CompilationUnit) mParser.createAST(null);
-
- TextEdit textEdit = updateJavaFileImports(cu);
- if (textEdit != null && textEdit.hasChildren()) {
- MultiTextEdit edit = new MultiTextEdit();
- edit.addChild(textEdit);
-
- TextFileChange text_file_change = new TextFileChange(file.getName(), file);
- text_file_change.setTextType(SdkConstants.EXT_JAVA);
- text_file_change.setEdit(edit);
- mChanges.add(text_file_change);
- }
-
- // XXX Partially taken from ExtractStringRefactoring.java
- // Check this a Layout XML file and get the selection and
- // its context.
- } else if (SdkConstants.EXT_XML.equals(file.getFileExtension())) {
-
- if (SdkConstants.FN_ANDROID_MANIFEST_XML.equals(file.getName())) {
- // Ensure that this is the root manifest, not some other copy
- // (such as the one in bin/)
- IPath path = file.getFullPath();
- if (path.segmentCount() == 2) {
- TextFileChange manifest_change = editAndroidManifest(file);
- mChanges.add(manifest_change);
- }
- } else {
-
- // Currently we only support Android resource XML files,
- // so they must have a path similar to
- // project/res/<type>[-<configuration>]/*.xml
- // There is no support for sub folders, so the segment count must be 4.
- // We don't need to check the type folder name because
- // a/ we only accept an AndroidXmlEditor source and
- // b/ aapt generates a compilation error for unknown folders.
- IPath path = file.getFullPath();
- // check if we are inside the project/res/* folder.
- if (path.segmentCount() == 4) {
- if (path.segment(1).equalsIgnoreCase(SdkConstants.FD_RESOURCES)) {
-
-
- TextFileChange xmlChange = editXmlResourceFile(file);
- if (xmlChange != null) {
- mChanges.add(xmlChange);
- }
- }
- }
- }
- }
-
- return false;
-
- } else if (resource instanceof IFolder) {
- return !SdkConstants.FD_GEN_SOURCES.equals(resource.getName());
- }
-
- return true;
- }
- }
-
- private static class UsageVisitor extends ASTVisitor {
- private boolean mSeenManifest;
- private boolean mSeenR;
- private boolean mSeenBuildConfig;
-
- @Override
- public boolean visit(QualifiedName node) {
- Name qualifier = node.getQualifier();
- if (qualifier.isSimpleName()) {
- String name = qualifier.toString();
- if (name.equals(FN_RESOURCE_BASE)) {
- mSeenR = true;
- } else if (name.equals(FN_BUILD_CONFIG_BASE)) {
- mSeenBuildConfig = true;
- } else if (name.equals(FN_MANIFEST_BASE)) {
- mSeenManifest = true;
- }
- }
- return super.visit(node);
- };
-
- public boolean seenAny() {
- return mSeenR || mSeenBuildConfig || mSeenManifest;
- }
-
- public boolean hasSeenBuildConfig() {
- return mSeenBuildConfig;
- }
- public boolean hasSeenManifest() {
- return mSeenManifest;
- }
- public boolean hasSeenR() {
- return mSeenR;
- }
- }
-
- private class ImportVisitor extends ASTVisitor {
-
- final AST mAst;
- final ASTRewrite mRewriter;
-
- ImportVisitor(AST ast) {
- mAst = ast;
- mRewriter = ASTRewrite.create(ast);
- }
-
- public TextEdit getTextEdit() {
- try {
- return this.mRewriter.rewriteAST();
- } catch (JavaModelException e) {
- Status s = new Status(Status.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e);
- AdtPlugin.getDefault().getLog().log(s);
- } catch (IllegalArgumentException e) {
- Status s = new Status(Status.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e);
- AdtPlugin.getDefault().getLog().log(s);
- }
- return null;
- }
-
- @Override
- public boolean visit(ImportDeclaration id) {
-
- Name importName = id.getName();
- if (importName.isQualifiedName()) {
- QualifiedName qualifiedImportName = (QualifiedName) importName;
-
- String identifier = qualifiedImportName.getName().getIdentifier();
- if (identifier.equals(FN_RESOURCE_BASE)) {
- mRewriter.replace(qualifiedImportName.getQualifier(), mNewPackageName,
- null);
- } else if (identifier.equals(FN_BUILD_CONFIG_BASE)
- && mOldPackageName.toString().equals(
- qualifiedImportName.getQualifier().toString())) {
- mRewriter.replace(qualifiedImportName.getQualifier(), mNewPackageName,
- null);
-
- } else if (identifier.equals(FN_MANIFEST_BASE)
- && mOldPackageName.toString().equals(
- qualifiedImportName.getQualifier().toString())) {
- mRewriter.replace(qualifiedImportName.getQualifier(), mNewPackageName,
- null);
- }
- }
-
- return true;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/renamepackage/ApplicationPackageNameRefactoringWizard.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/renamepackage/ApplicationPackageNameRefactoringWizard.java
deleted file mode 100644
index 3651855a7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/renamepackage/ApplicationPackageNameRefactoringWizard.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.refactorings.renamepackage;
-
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-
-/**
- * @see RenamePackageAction
- */
-class ApplicationPackageNameRefactoringWizard extends RefactoringWizard {
-
- public ApplicationPackageNameRefactoringWizard(Refactoring refactoring) {
- super(refactoring, 0);
- }
-
- @Override
- protected void addUserInputPages() {
- }
-}
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/renamepackage/RenamePackageAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/renamepackage/RenamePackageAction.java
deleted file mode 100644
index bb475aab1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/refactorings/renamepackage/RenamePackageAction.java
+++ /dev/null
@@ -1,174 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.refactorings.renamepackage;
-
-import com.android.ide.common.xml.ManifestData;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.project.AndroidManifestHelper;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jdt.core.dom.AST;
-import org.eclipse.jdt.core.dom.Name;
-import org.eclipse.jdt.ui.refactoring.RefactoringSaveHelper;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.IInputValidator;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
-import org.eclipse.ui.IObjectActionDelegate;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-
-import java.util.Iterator;
-
-/**
- * Refactoring steps:
- * <ol>
- * <li>Update the "package" attribute of the &lt;manifest&gt; tag with the new
- * name.</li>
- * <li>Replace all values for the "android:name" attribute in the
- * &lt;application&gt; and "component class" (&lt;activity&gt;, &lt;service&gt;,
- * &lt;receiver&gt;, and &lt;provider&gt;) tags with the non-shorthand version
- * of the class name</li>
- * <li>Replace package resource imports (*.R) in .java files</li>
- * <li>Update package name in the namespace declarations (e.g. "xmlns:app")
- * used for custom styleable attributes in layout resource files</li>
- * </ol>
- * Caveat: Sometimes it is necessary to perform a project-wide
- * "Organize Imports" afterwards. (CTRL+SHIFT+O when a project has active
- * selection)
- */
-public class RenamePackageAction implements IObjectActionDelegate {
-
- private ISelection mSelection;
- @SuppressWarnings("unused") private IWorkbenchPart mTargetPart; // TODO cleanup
-
- /**
- * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
- */
- @Override
- public void setActivePart(IAction action, IWorkbenchPart targetPart) {
- mTargetPart = targetPart;
- }
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
- mSelection = selection;
- }
-
- /**
- * @see IWorkbenchWindowActionDelegate#init
- */
- public void init(IWorkbenchWindow window) {
- // pass
- }
-
- @Override
- public void run(IAction action) {
-
- // Prompt for refactoring on the selected project
- if (mSelection instanceof IStructuredSelection) {
- for (Iterator<?> it = ((IStructuredSelection) mSelection).iterator(); it.hasNext();) {
- Object element = it.next();
- IProject project = null;
- if (element instanceof IProject) {
- project = (IProject) element;
- } else if (element instanceof IAdaptable) {
- project = (IProject) ((IAdaptable) element).getAdapter(IProject.class);
- }
- if (project != null) {
- // It is advisable that the user saves before proceeding,
- // revealing any compilation errors. The following lines
- // enforce a save as a convenience.
- RefactoringSaveHelper save_helper = new RefactoringSaveHelper(
- RefactoringSaveHelper.SAVE_ALL_ALWAYS_ASK);
- if (save_helper.saveEditors(AdtPlugin.getShell())) {
- promptNewName(project);
- }
- }
- }
- }
- }
-
- /*
- * Validate the new package name and start the refactoring wizard
- */
- private void promptNewName(final IProject project) {
-
- ManifestData manifestData = AndroidManifestHelper.parseForData(project);
- if (manifestData == null) {
- return;
- }
-
- final String oldPackageNameString = manifestData.getPackage();
-
- final AST astValidator = AST.newAST(AST.JLS3);
- Name oldPackageName = astValidator.newName(oldPackageNameString);
-
- IInputValidator validator = new IInputValidator() {
-
- @Override
- public String isValid(String newText) {
- try {
- astValidator.newName(newText);
- } catch (IllegalArgumentException e) {
- return "Illegal package name.";
- }
-
- if (newText.equals(oldPackageNameString))
- return "No change.";
- else
- return null;
- }
- };
-
- InputDialog dialog = new InputDialog(AdtPlugin.getShell(),
- "Rename Application Package", "Enter new package name:", oldPackageNameString,
- validator);
-
- if (dialog.open() == Window.OK) {
- Name newPackageName = astValidator.newName(dialog.getValue());
- initiateAndroidPackageRefactoring(project, oldPackageName, newPackageName);
- }
- }
-
-
- private void initiateAndroidPackageRefactoring(
- final IProject project,
- Name oldPackageName,
- Name newPackageName) {
-
- Refactoring package_name_refactoring =
- new ApplicationPackageNameRefactoring(project, oldPackageName, newPackageName);
-
- ApplicationPackageNameRefactoringWizard wizard =
- new ApplicationPackageNameRefactoringWizard(package_name_refactoring);
- RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation(wizard);
- try {
- op.run(AdtPlugin.getShell(), package_name_refactoring.getName());
- } catch (InterruptedException e) {
- Status s = new Status(Status.ERROR, AdtPlugin.PLUGIN_ID, e.getMessage(), e);
- AdtPlugin.getDefault().getLog().log(s);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/CyclicDependencyValidator.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/CyclicDependencyValidator.java
deleted file mode 100644
index a2b13c6a8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/CyclicDependencyValidator.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.resources;
-
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.IncludeFinder;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.dialogs.IInputValidator;
-
-import java.util.Collection;
-
-/** A validator which checks for cyclic dependencies */
-public class CyclicDependencyValidator implements IInputValidator {
- private final Collection<String> mInvalidIds;
-
- private CyclicDependencyValidator(Collection<String> invalid) {
- this.mInvalidIds = invalid;
- }
-
- @Override
- public String isValid(String newText) {
- if (mInvalidIds.contains(newText)) {
- return "Cyclic include, not valid";
- }
- return null;
- }
-
- /**
- * Creates a validator which ensures that the chosen id is not for a layout that is
- * directly or indirectly including the given layout. Used to avoid cyclic
- * dependencies when offering layouts to be included within a given file, etc.
- *
- * @param file the target file that candidate layouts should not directly or
- * indirectly include
- * @return a validator which checks whether resource ids are valid or whether they
- * could result in a cyclic dependency
- */
- @Nullable
- public static IInputValidator create(@Nullable IFile file) {
- if (file == null) {
- return null;
- }
-
- IProject project = file.getProject();
- IncludeFinder includeFinder = IncludeFinder.get(project);
- final Collection<String> invalid =
- includeFinder.getInvalidIncludes(file);
-
- return new CyclicDependencyValidator(invalid);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/ResourceHelper.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/ResourceHelper.java
deleted file mode 100644
index b0e3d43d0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/ResourceHelper.java
+++ /dev/null
@@ -1,628 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.resources;
-
-import static com.android.SdkConstants.ANDROID_PREFIX;
-import static com.android.SdkConstants.ANDROID_STYLE_RESOURCE_PREFIX;
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_COLOR;
-import static com.android.SdkConstants.ATTR_NAME;
-import static com.android.SdkConstants.ATTR_TYPE;
-import static com.android.SdkConstants.DOT_XML;
-import static com.android.SdkConstants.EXT_XML;
-import static com.android.SdkConstants.FD_RESOURCES;
-import static com.android.SdkConstants.FD_RES_VALUES;
-import static com.android.SdkConstants.PREFIX_RESOURCE_REF;
-import static com.android.SdkConstants.STYLE_RESOURCE_PREFIX;
-import static com.android.SdkConstants.TAG_ITEM;
-import static com.android.SdkConstants.TAG_RESOURCES;
-import static com.android.ide.eclipse.adt.AdtConstants.WS_SEP;
-
-import com.android.ide.common.rendering.api.ResourceValue;
-import com.android.ide.common.resources.ResourceDeltaKind;
-import com.android.ide.common.resources.ResourceResolver;
-import com.android.ide.common.resources.ResourceUrl;
-import com.android.ide.common.resources.configuration.CountryCodeQualifier;
-import com.android.ide.common.resources.configuration.DensityQualifier;
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.common.resources.configuration.KeyboardStateQualifier;
-import com.android.ide.common.resources.configuration.LayoutDirectionQualifier;
-import com.android.ide.common.resources.configuration.LocaleQualifier;
-import com.android.ide.common.resources.configuration.NavigationMethodQualifier;
-import com.android.ide.common.resources.configuration.NavigationStateQualifier;
-import com.android.ide.common.resources.configuration.NetworkCodeQualifier;
-import com.android.ide.common.resources.configuration.NightModeQualifier;
-import com.android.ide.common.resources.configuration.ResourceQualifier;
-import com.android.ide.common.resources.configuration.ScreenDimensionQualifier;
-import com.android.ide.common.resources.configuration.ScreenHeightQualifier;
-import com.android.ide.common.resources.configuration.ScreenOrientationQualifier;
-import com.android.ide.common.resources.configuration.ScreenRatioQualifier;
-import com.android.ide.common.resources.configuration.ScreenSizeQualifier;
-import com.android.ide.common.resources.configuration.ScreenWidthQualifier;
-import com.android.ide.common.resources.configuration.SmallestScreenWidthQualifier;
-import com.android.ide.common.resources.configuration.TextInputMethodQualifier;
-import com.android.ide.common.resources.configuration.TouchScreenQualifier;
-import com.android.ide.common.resources.configuration.UiModeQualifier;
-import com.android.ide.common.resources.configuration.VersionQualifier;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.Hyperlinks;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.ImageUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.refactoring.VisualRefactoring;
-import com.android.ide.eclipse.adt.internal.wizards.newxmlfile.NewXmlFileWizard;
-import com.android.resources.FolderTypeRelationship;
-import com.android.resources.ResourceFolderType;
-import com.android.resources.ResourceType;
-import com.android.utils.Pair;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.wst.sse.core.StructuredModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.eclipse.wst.xml.core.internal.document.ElementImpl;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.w3c.dom.Text;
-import org.xml.sax.InputSource;
-
-import java.io.BufferedInputStream;
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.UnsupportedEncodingException;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-
-/**
- * Helper class to deal with SWT specifics for the resources.
- */
-@SuppressWarnings("restriction") // XML model
-public class ResourceHelper {
-
- private final static Map<Class<?>, Image> sIconMap = new HashMap<Class<?>, Image>(
- FolderConfiguration.getQualifierCount());
-
- static {
- try {
- IconFactory factory = IconFactory.getInstance();
- sIconMap.put(CountryCodeQualifier.class, factory.getIcon("mcc")); //$NON-NLS-1$
- sIconMap.put(NetworkCodeQualifier.class, factory.getIcon("mnc")); //$NON-NLS-1$
- sIconMap.put(LocaleQualifier.class, factory.getIcon("language")); //$NON-NLS-1$
- sIconMap.put(LayoutDirectionQualifier.class, factory.getIcon("bidi")); //$NON-NLS-1$
- sIconMap.put(ScreenSizeQualifier.class, factory.getIcon("size")); //$NON-NLS-1$
- sIconMap.put(ScreenRatioQualifier.class, factory.getIcon("ratio")); //$NON-NLS-1$
- sIconMap.put(ScreenOrientationQualifier.class, factory.getIcon("orientation")); //$NON-NLS-1$
- sIconMap.put(UiModeQualifier.class, factory.getIcon("dockmode")); //$NON-NLS-1$
- sIconMap.put(NightModeQualifier.class, factory.getIcon("nightmode")); //$NON-NLS-1$
- sIconMap.put(DensityQualifier.class, factory.getIcon("dpi")); //$NON-NLS-1$
- sIconMap.put(TouchScreenQualifier.class, factory.getIcon("touch")); //$NON-NLS-1$
- sIconMap.put(KeyboardStateQualifier.class, factory.getIcon("keyboard")); //$NON-NLS-1$
- sIconMap.put(TextInputMethodQualifier.class, factory.getIcon("text_input")); //$NON-NLS-1$
- sIconMap.put(NavigationStateQualifier.class, factory.getIcon("navpad")); //$NON-NLS-1$
- sIconMap.put(NavigationMethodQualifier.class, factory.getIcon("navpad")); //$NON-NLS-1$
- sIconMap.put(ScreenDimensionQualifier.class, factory.getIcon("dimension")); //$NON-NLS-1$
- sIconMap.put(VersionQualifier.class, factory.getIcon("version")); //$NON-NLS-1$
- sIconMap.put(ScreenWidthQualifier.class, factory.getIcon("width")); //$NON-NLS-1$
- sIconMap.put(ScreenHeightQualifier.class, factory.getIcon("height")); //$NON-NLS-1$
- sIconMap.put(SmallestScreenWidthQualifier.class,factory.getIcon("swidth")); //$NON-NLS-1$
- } catch (Throwable t) {
- AdtPlugin.log(t , null);
- }
- }
-
- /**
- * Returns the icon for the qualifier.
- */
- public static Image getIcon(Class<? extends ResourceQualifier> theClass) {
- return sIconMap.get(theClass);
- }
-
- /**
- * Returns a {@link ResourceDeltaKind} from an {@link IResourceDelta} value.
- * @param kind a {@link IResourceDelta} integer constant.
- * @return a matching {@link ResourceDeltaKind} or null.
- *
- * @see IResourceDelta#ADDED
- * @see IResourceDelta#REMOVED
- * @see IResourceDelta#CHANGED
- */
- public static ResourceDeltaKind getResourceDeltaKind(int kind) {
- switch (kind) {
- case IResourceDelta.ADDED:
- return ResourceDeltaKind.ADDED;
- case IResourceDelta.REMOVED:
- return ResourceDeltaKind.REMOVED;
- case IResourceDelta.CHANGED:
- return ResourceDeltaKind.CHANGED;
- }
-
- return null;
- }
-
- /**
- * Is this a resource that can be defined in any file within the "values" folder?
- * <p>
- * Some resource types can be defined <b>both</b> as a separate XML file as well
- * as defined within a value XML file. This method will return true for these types
- * as well. In other words, a ResourceType can return true for both
- * {@link #isValueBasedResourceType} and {@link #isFileBasedResourceType}.
- *
- * @param type the resource type to check
- * @return true if the given resource type can be represented as a value under the
- * values/ folder
- */
- public static boolean isValueBasedResourceType(ResourceType type) {
- List<ResourceFolderType> folderTypes = FolderTypeRelationship.getRelatedFolders(type);
- for (ResourceFolderType folderType : folderTypes) {
- if (folderType == ResourceFolderType.VALUES) {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Is this a resource that is defined in a file named by the resource plus the XML
- * extension?
- * <p>
- * Some resource types can be defined <b>both</b> as a separate XML file as well as
- * defined within a value XML file along with other properties. This method will
- * return true for these resource types as well. In other words, a ResourceType can
- * return true for both {@link #isValueBasedResourceType} and
- * {@link #isFileBasedResourceType}.
- *
- * @param type the resource type to check
- * @return true if the given resource type is stored in a file named by the resource
- */
- public static boolean isFileBasedResourceType(ResourceType type) {
- List<ResourceFolderType> folderTypes = FolderTypeRelationship.getRelatedFolders(type);
- for (ResourceFolderType folderType : folderTypes) {
- if (folderType != ResourceFolderType.VALUES) {
-
- if (type == ResourceType.ID) {
- // The folder types for ID is not only VALUES but also
- // LAYOUT and MENU. However, unlike resources, they are only defined
- // inline there so for the purposes of isFileBasedResourceType
- // (where the intent is to figure out files that are uniquely identified
- // by a resource's name) this method should return false anyway.
- return false;
- }
-
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Returns true if this class can create the given resource
- *
- * @param resource the resource to be created
- * @return true if the {@link #createResource} method can create this resource
- */
- public static boolean canCreateResource(String resource) {
- // Cannot create framework resources
- if (resource.startsWith(ANDROID_PREFIX)) {
- return false;
- }
-
- ResourceUrl parsed = ResourceUrl.parse(resource);
- if (parsed != null) {
- if (parsed.framework) {
- return false;
- }
- ResourceType type = parsed.type;
- String name = parsed.name;
-
- // Make sure the name is valid
- ResourceNameValidator validator =
- ResourceNameValidator.create(false, (Set<String>) null /* existing */, type);
- if (validator.isValid(name) != null) {
- return false;
- }
-
- return canCreateResourceType(type);
- }
-
- return false;
- }
-
- /**
- * Returns true if this class can create resources of the given resource
- * type
- *
- * @param type the type of resource to be created
- * @return true if the {@link #createResource} method can create resources
- * of this type (provided the name parameter is also valid)
- */
- public static boolean canCreateResourceType(ResourceType type) {
- // We can create all value types
- if (isValueBasedResourceType(type)) {
- return true;
- }
-
- // We can create -some- file-based types - those supported by the New XML wizard:
- for (ResourceFolderType folderType : FolderTypeRelationship.getRelatedFolders(type)) {
- if (NewXmlFileWizard.canCreateXmlFile(folderType)) {
- return true;
- }
- }
-
- return false;
- }
-
- /** Creates a file-based resource, like a layout. Used by {@link #createResource} */
- private static Pair<IFile,IRegion> createFileResource(IProject project, ResourceType type,
- String name) {
-
- ResourceFolderType folderType = null;
- for (ResourceFolderType f : FolderTypeRelationship.getRelatedFolders(type)) {
- if (NewXmlFileWizard.canCreateXmlFile(f)) {
- folderType = f;
- break;
- }
- }
- if (folderType == null) {
- return null;
- }
-
- // Find "dimens.xml" file in res/values/ (or corresponding name for other
- // value types)
- IPath projectPath = new Path(FD_RESOURCES + WS_SEP + folderType.getName() + WS_SEP
- + name + '.' + EXT_XML);
- IFile file = project.getFile(projectPath);
- return NewXmlFileWizard.createXmlFile(project, file, folderType);
- }
-
- /**
- * Creates a resource of a given type, name and (if applicable) value
- *
- * @param project the project to contain the resource
- * @param type the type of resource
- * @param name the name of the resource
- * @param value the value of the resource, if it is a value-type resource
- * @return a pair of the file containing the resource and a region where the value
- * appears
- */
- public static Pair<IFile,IRegion> createResource(IProject project, ResourceType type,
- String name, String value) {
- if (!isValueBasedResourceType(type)) {
- return createFileResource(project, type, name);
- }
-
- // Find "dimens.xml" file in res/values/ (or corresponding name for other
- // value types)
- String typeName = type.getName();
- String fileName = typeName + 's';
- String projectPath = FD_RESOURCES + WS_SEP + FD_RES_VALUES + WS_SEP
- + fileName + '.' + EXT_XML;
- Object editRequester = project;
- IResource member = project.findMember(projectPath);
- String tagName = Hyperlinks.getTagName(type);
- boolean createEmptyTag = type == ResourceType.ID;
- if (member != null) {
- if (member instanceof IFile) {
- IFile file = (IFile) member;
- // File exists: Must add item to the XML
- IModelManager manager = StructuredModelManager.getModelManager();
- IStructuredModel model = null;
- try {
- model = manager.getExistingModelForEdit(file);
- if (model == null) {
- model = manager.getModelForEdit(file);
- }
- if (model instanceof IDOMModel) {
- model.beginRecording(editRequester, String.format("Add %1$s",
- type.getDisplayName()));
- IDOMModel domModel = (IDOMModel) model;
- Document document = domModel.getDocument();
- Element root = document.getDocumentElement();
- IStructuredDocument structuredDocument = model.getStructuredDocument();
- Node lastElement = null;
- NodeList childNodes = root.getChildNodes();
- String indent = null;
- for (int i = childNodes.getLength() - 1; i >= 0; i--) {
- Node node = childNodes.item(i);
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- lastElement = node;
- indent = AndroidXmlEditor.getIndent(structuredDocument, node);
- break;
- }
- }
- if (indent == null || indent.length() == 0) {
- indent = " "; //$NON-NLS-1$
- }
- Node nextChild = lastElement != null ? lastElement.getNextSibling() : null;
- Text indentNode = document.createTextNode('\n' + indent);
- root.insertBefore(indentNode, nextChild);
- Element element = document.createElement(tagName);
- if (createEmptyTag) {
- if (element instanceof ElementImpl) {
- ElementImpl elementImpl = (ElementImpl) element;
- elementImpl.setEmptyTag(true);
- }
- }
- element.setAttribute(ATTR_NAME, name);
- if (!tagName.equals(typeName)) {
- element.setAttribute(ATTR_TYPE, typeName);
- }
- root.insertBefore(element, nextChild);
- IRegion region = null;
-
- if (createEmptyTag) {
- IndexedRegion domRegion = VisualRefactoring.getRegion(element);
- int endOffset = domRegion.getEndOffset();
- region = new Region(endOffset, 0);
- } else {
- Node valueNode = document.createTextNode(value);
- element.appendChild(valueNode);
-
- IndexedRegion domRegion = VisualRefactoring.getRegion(valueNode);
- int startOffset = domRegion.getStartOffset();
- int length = domRegion.getLength();
- region = new Region(startOffset, length);
- }
- model.save();
- return Pair.of(file, region);
- }
- } catch (Exception e) {
- AdtPlugin.log(e, "Cannot access XML value model");
- } finally {
- if (model != null) {
- model.endRecording(editRequester);
- model.releaseFromEdit();
- }
- }
- }
-
- return null;
- } else {
- // No such file exists: just create it
- String prolog = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"; //$NON-NLS-1$
- StringBuilder sb = new StringBuilder(prolog);
-
- String root = TAG_RESOURCES;
- sb.append('<').append(root).append('>').append('\n');
- sb.append(" "); //$NON-NLS-1$
- sb.append('<');
- sb.append(tagName);
- sb.append(" name=\""); //$NON-NLS-1$
- sb.append(name);
- sb.append('"');
- if (!tagName.equals(typeName)) {
- sb.append(" type=\""); //$NON-NLS-1$
- sb.append(typeName);
- sb.append('"');
- }
- int start, end;
- if (createEmptyTag) {
- sb.append("/>"); //$NON-NLS-1$
- start = sb.length();
- end = sb.length();
- } else {
- sb.append('>');
- start = sb.length();
- sb.append(value);
- end = sb.length();
- sb.append('<').append('/');
- sb.append(tagName);
- sb.append('>');
- }
- sb.append('\n').append('<').append('/').append(root).append('>').append('\n');
- String result = sb.toString();
- // TODO: Pretty print string (wait until that CL is integrated)
- String error = null;
- try {
- byte[] buf = result.getBytes("UTF8"); //$NON-NLS-1$
- InputStream stream = new ByteArrayInputStream(buf);
- IFile file = project.getFile(new Path(projectPath));
- file.create(stream, true /*force*/, null /*progress*/);
- IRegion region = new Region(start, end - start);
- return Pair.of(file, region);
- } catch (UnsupportedEncodingException e) {
- error = e.getMessage();
- } catch (CoreException e) {
- error = e.getMessage();
- }
-
- error = String.format("Failed to generate %1$s: %2$s", name, error);
- AdtPlugin.displayError("New Android XML File", error);
- }
- return null;
- }
-
- /**
- * Returns the theme name to be shown for theme styles, e.g. for "@style/Theme" it
- * returns "Theme"
- *
- * @param style a theme style string
- * @return the user visible theme name
- */
- public static String styleToTheme(String style) {
- if (style.startsWith(STYLE_RESOURCE_PREFIX)) {
- style = style.substring(STYLE_RESOURCE_PREFIX.length());
- } else if (style.startsWith(ANDROID_STYLE_RESOURCE_PREFIX)) {
- style = style.substring(ANDROID_STYLE_RESOURCE_PREFIX.length());
- } else if (style.startsWith(PREFIX_RESOURCE_REF)) {
- // @package:style/foo
- int index = style.indexOf('/');
- if (index != -1) {
- style = style.substring(index + 1);
- }
- }
- return style;
- }
-
- /**
- * Returns true if the given style represents a project theme
- *
- * @param style a theme style string
- * @return true if the style string represents a project theme, as opposed
- * to a framework theme
- */
- public static boolean isProjectStyle(String style) {
- assert style.startsWith(STYLE_RESOURCE_PREFIX)
- || style.startsWith(ANDROID_STYLE_RESOURCE_PREFIX) : style;
-
- return style.startsWith(STYLE_RESOURCE_PREFIX);
- }
-
- /**
- * Returns the layout resource name for the given layout file, e.g. for
- * /res/layout/foo.xml returns foo.
- *
- * @param layoutFile the layout file whose name we want to look up
- * @return the layout name
- */
- public static String getLayoutName(IFile layoutFile) {
- String layoutName = layoutFile.getName();
- int dotIndex = layoutName.indexOf('.');
- if (dotIndex != -1) {
- layoutName = layoutName.substring(0, dotIndex);
- }
- return layoutName;
- }
-
- /**
- * Tries to resolve the given resource value to an actual RGB color. For state lists
- * it will pick the simplest/fallback color.
- *
- * @param resources the resource resolver to use to follow color references
- * @param color the color to resolve
- * @return the corresponding {@link RGB} color, or null
- */
- public static RGB resolveColor(ResourceResolver resources, ResourceValue color) {
- color = resources.resolveResValue(color);
- if (color == null) {
- return null;
- }
- String value = color.getValue();
-
- while (value != null) {
- if (value.startsWith("#")) { //$NON-NLS-1$
- try {
- int rgba = ImageUtils.getColor(value);
- // Drop alpha channel
- return ImageUtils.intToRgb(rgba);
- } catch (NumberFormatException nfe) {
- // Pass
- }
- return null;
- }
- if (value.startsWith(PREFIX_RESOURCE_REF)) {
- boolean isFramework = color.isFramework();
- color = resources.findResValue(value, isFramework);
- if (color != null) {
- value = color.getValue();
- } else {
- break;
- }
- } else {
- File file = new File(value);
- if (file.exists() && file.getName().endsWith(DOT_XML)) {
- // Parse
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- BufferedInputStream bis = null;
- try {
- bis = new BufferedInputStream(new FileInputStream(file));
- InputSource is = new InputSource(bis);
- factory.setNamespaceAware(true);
- factory.setValidating(false);
- DocumentBuilder builder = factory.newDocumentBuilder();
- Document document = builder.parse(is);
- NodeList items = document.getElementsByTagName(TAG_ITEM);
-
- value = findColorValue(items);
- continue;
- } catch (Exception e) {
- AdtPlugin.log(e, "Failed parsing color file %1$s", file.getName());
- } finally {
- if (bis != null) {
- try {
- bis.close();
- } catch (IOException e) {
- // Nothing useful can be done here
- }
- }
- }
- }
-
- return null;
- }
- }
-
- return null;
- }
-
- /**
- * Searches a color XML file for the color definition element that does not
- * have an associated state and returns its color
- */
- private static String findColorValue(NodeList items) {
- for (int i = 0, n = items.getLength(); i < n; i++) {
- // Find non-state color definition
- Node item = items.item(i);
- boolean hasState = false;
- if (item.getNodeType() == Node.ELEMENT_NODE) {
- Element element = (Element) item;
- if (element.hasAttributeNS(ANDROID_URI, ATTR_COLOR)) {
- NamedNodeMap attributes = element.getAttributes();
- for (int j = 0, m = attributes.getLength(); j < m; j++) {
- Attr attribute = (Attr) attributes.item(j);
- if (attribute.getLocalName().startsWith("state_")) { //$NON-NLS-1$
- hasState = true;
- break;
- }
- }
-
- if (!hasState) {
- return element.getAttributeNS(ANDROID_URI, ATTR_COLOR);
- }
- }
- }
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/ResourceNameValidator.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/ResourceNameValidator.java
deleted file mode 100644
index 5ea1edc0e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/ResourceNameValidator.java
+++ /dev/null
@@ -1,242 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.resources;
-
-import static com.android.SdkConstants.DOT_XML;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.resources.ResourceItem;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.ImageUtils;
-import com.android.ide.eclipse.adt.internal.resources.manager.ProjectResources;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.resources.ResourceFolderType;
-import com.android.resources.ResourceType;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jdt.core.JavaConventions;
-import org.eclipse.jface.dialogs.IInputValidator;
-
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Set;
-
-/**
- * Validator which ensures that new Android resource names are valid.
- */
-public class ResourceNameValidator implements IInputValidator {
- /** Set of existing names to check for conflicts with */
- private Set<String> mExisting;
-
- /** If true, the validated name must be unique */
- private boolean mUnique = true;
-
- /** If true, the validated name must exist */
- private boolean mExist;
-
- /**
- * True if the resource name being considered is a "file" based resource (where the
- * resource name is the actual file name, rather than just a value attribute inside an
- * XML file name of arbitrary name
- */
- private boolean mIsFileType;
-
- /**
- * True if the resource type can point to image resources
- */
- private boolean mIsImageType;
-
- /** If true, allow .xml as a name suffix */
- private boolean mAllowXmlExtension;
-
- private ResourceNameValidator(boolean allowXmlExtension, Set<String> existing,
- boolean isFileType, boolean isImageType) {
- mAllowXmlExtension = allowXmlExtension;
- mExisting = existing;
- mIsFileType = isFileType;
- mIsImageType = isImageType;
- }
-
- /**
- * Makes the resource name validator require that names are unique.
- *
- * @return this, for construction chaining
- */
- public ResourceNameValidator unique() {
- mUnique = true;
- mExist = false;
-
- return this;
- }
-
- /**
- * Makes the resource name validator require that names already exist
- *
- * @return this, for construction chaining
- */
- public ResourceNameValidator exist() {
- mExist = true;
- mUnique = false;
-
- return this;
- }
-
- @Override
- public String isValid(String newText) {
- // IValidator has the same interface as SWT's IInputValidator
- try {
- if (newText == null || newText.trim().length() == 0) {
- return "Enter a new name";
- }
-
- if (mAllowXmlExtension && newText.endsWith(DOT_XML)) {
- newText = newText.substring(0, newText.length() - DOT_XML.length());
- }
-
- if (mAllowXmlExtension && mIsImageType
- && ImageUtils.hasImageExtension(newText)) {
- newText = newText.substring(0, newText.lastIndexOf('.'));
- }
-
- if (!mIsFileType) {
- newText = newText.replace('.', '_');
- }
-
- if (newText.indexOf('.') != -1 && !newText.endsWith(DOT_XML)) {
- if (mIsImageType) {
- return "The filename must end with .xml or .png";
- } else {
- return "The filename must end with .xml";
- }
- }
-
- // Resource names must be valid Java identifiers, since they will
- // be represented as Java identifiers in the R file:
- if (!Character.isJavaIdentifierStart(newText.charAt(0))) {
- return "The resource name must begin with a character";
- }
- for (int i = 1, n = newText.length(); i < n; i++) {
- char c = newText.charAt(i);
- if (!Character.isJavaIdentifierPart(c)) {
- return String.format("'%1$c' is not a valid resource name character", c);
- }
- }
-
- if (mIsFileType) {
- char first = newText.charAt(0);
- if (!(first >= 'a' && first <= 'z')) {
- return String.format(
- "File-based resource names must start with a lowercase letter.");
- }
-
- // AAPT only allows lowercase+digits+_:
- // "%s: Invalid file name: must contain only [a-z0-9_.]","
- for (int i = 0, n = newText.length(); i < n; i++) {
- char c = newText.charAt(i);
- if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_')) {
- return String.format(
- "File-based resource names must contain only lowercase a-z, 0-9, or _.");
- }
- }
- }
-
- String level = "1.5"; //$NON-NLS-1$
- IStatus validIdentifier = JavaConventions.validateIdentifier(newText, level, level);
- if (!validIdentifier.isOK()) {
- return String.format("%1$s is not a valid name (reserved Java keyword)", newText);
- }
-
-
- if (mExisting != null && (mUnique || mExist)) {
- boolean exists = mExisting.contains(newText);
- if (mUnique && exists) {
- return String.format("%1$s already exists", newText);
- } else if (mExist && !exists) {
- return String.format("%1$s does not exist", newText);
- }
- }
-
- return null;
- } catch (Exception e) {
- AdtPlugin.log(e, "Validation failed: %s", e.toString());
- return ""; //$NON-NLS-1$
- }
- }
-
- /**
- * Creates a new {@link ResourceNameValidator}
- *
- * @param allowXmlExtension if true, allow .xml to be entered as a suffix for the
- * resource name
- * @param type the resource type of the resource name being validated
- * @return a new {@link ResourceNameValidator}
- */
- public static ResourceNameValidator create(boolean allowXmlExtension,
- ResourceFolderType type) {
- boolean isFileType = type != ResourceFolderType.VALUES;
- return new ResourceNameValidator(allowXmlExtension, null, isFileType,
- type == ResourceFolderType.DRAWABLE);
- }
-
- /**
- * Creates a new {@link ResourceNameValidator}
- *
- * @param allowXmlExtension if true, allow .xml to be entered as a suffix for the
- * resource name
- * @param existing An optional set of names that already exist (and therefore will not
- * be considered valid if entered as the new name)
- * @param type the resource type of the resource name being validated
- * @return a new {@link ResourceNameValidator}
- */
- public static ResourceNameValidator create(boolean allowXmlExtension, Set<String> existing,
- ResourceType type) {
- boolean isFileType = ResourceHelper.isFileBasedResourceType(type);
- return new ResourceNameValidator(allowXmlExtension, existing, isFileType,
- type == ResourceType.DRAWABLE).unique();
- }
-
- /**
- * Creates a new {@link ResourceNameValidator}. By default, the name will need to be
- * unique in the project.
- *
- * @param allowXmlExtension if true, allow .xml to be entered as a suffix for the
- * resource name
- * @param project the project to validate new resource names for
- * @param type the resource type of the resource name being validated
- * @return a new {@link ResourceNameValidator}
- */
- public static ResourceNameValidator create(boolean allowXmlExtension,
- @Nullable IProject project,
- @NonNull ResourceType type) {
- Set<String> existing = null;
- if (project != null) {
- existing = new HashSet<String>();
- ResourceManager manager = ResourceManager.getInstance();
- ProjectResources projectResources = manager.getProjectResources(project);
- Collection<ResourceItem> items = projectResources.getResourceItemsOfType(type);
- for (ResourceItem item : items) {
- existing.add(item.getName());
- }
- }
-
- boolean isFileType = ResourceHelper.isFileBasedResourceType(type);
- return new ResourceNameValidator(allowXmlExtension, existing, isFileType,
- type == ResourceType.DRAWABLE);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/CompiledResourcesMonitor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/CompiledResourcesMonitor.java
deleted file mode 100644
index ab5ae4070..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/CompiledResourcesMonitor.java
+++ /dev/null
@@ -1,313 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.resources.manager;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.resources.IntArrayWrapper;
-import com.android.ide.common.xml.ManifestData;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.project.AndroidManifestHelper;
-import com.android.ide.eclipse.adt.internal.project.ProjectHelper;
-import com.android.ide.eclipse.adt.internal.resources.manager.GlobalProjectMonitor.IFileListener;
-import com.android.ide.eclipse.adt.internal.resources.manager.GlobalProjectMonitor.IProjectListener;
-import com.android.resources.ResourceType;
-import com.android.util.Pair;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarkerDelta;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-
-import java.io.File;
-import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
-import java.util.EnumMap;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.regex.Pattern;
-
-/**
- * A monitor for the compiled resources. This only monitors changes in the resources of type
- * {@link ResourceType#ID}.
- */
-public final class CompiledResourcesMonitor implements IFileListener, IProjectListener {
-
- private final static CompiledResourcesMonitor sThis = new CompiledResourcesMonitor();
-
- /**
- * Sets up the monitoring system.
- * @param monitor The main Resource Monitor.
- */
- public static void setupMonitor(GlobalProjectMonitor monitor) {
- monitor.addFileListener(sThis, IResourceDelta.ADDED | IResourceDelta.CHANGED);
- monitor.addProjectListener(sThis);
- }
-
- /**
- * private constructor to prevent construction.
- */
- private CompiledResourcesMonitor() {
- }
-
-
- /* (non-Javadoc)
- * Sent when a file changed : if the file is the R class, then it is parsed again to update
- * the internal data.
- *
- * @param file The file that changed.
- * @param markerDeltas The marker deltas for the file.
- * @param kind The change kind. This is equivalent to
- * {@link IResourceDelta#accept(IResourceDeltaVisitor)}
- *
- * @see IFileListener#fileChanged
- */
- @Override
- public void fileChanged(@NonNull IFile file, @NonNull IMarkerDelta[] markerDeltas,
- int kind, @Nullable String extension, int flags, boolean isAndroidProject) {
- if (!isAndroidProject || flags == IResourceDelta.MARKERS) {
- // Not Android or only the markers changed: not relevant
- return;
- }
-
- IProject project = file.getProject();
-
- if (file.getName().equals(SdkConstants.FN_COMPILED_RESOURCE_CLASS)) {
- // create the classname
- String className = getRClassName(project);
- if (className == null) {
- // We need to abort.
- AdtPlugin.log(IStatus.ERROR,
- "fileChanged: failed to find manifest package for project %1$s", //$NON-NLS-1$
- project.getName());
- return;
- }
- // path will begin with /projectName/bin/classes so we'll ignore that
- IPath relativeClassPath = file.getFullPath().removeFirstSegments(3);
- if (packagePathMatches(relativeClassPath.toString(), className)) {
- loadAndParseRClass(project, className);
- }
- }
- }
-
- /**
- * Check to see if the package section of the given path matches the packageName.
- * For example, /project/bin/classes/com/foo/app/R.class should match com.foo.app.R
- * @param path the pathname of the file to look at
- * @param packageName the package qualified name of the class
- * @return true if the package section of the path matches the package qualified name
- */
- private boolean packagePathMatches(String path, String packageName) {
- // First strip the ".class" off the end of the path
- String pathWithoutExtension = path.substring(0, path.indexOf(SdkConstants.DOT_CLASS));
-
- // then split the components of each path by their separators
- String [] pathArray = pathWithoutExtension.split(Pattern.quote(File.separator));
- String [] packageArray = packageName.split(AdtConstants.RE_DOT);
-
-
- int pathIndex = 0;
- int packageIndex = 0;
-
- while (pathIndex < pathArray.length && packageIndex < packageArray.length) {
- if (pathArray[pathIndex].equals(packageArray[packageIndex]) == false) {
- return false;
- }
- pathIndex++;
- packageIndex++;
- }
- // We may have matched all the way up to this point, but we're not sure it's a match
- // unless BOTH paths done
- return (pathIndex == pathArray.length && packageIndex == packageArray.length);
- }
-
- /**
- * Processes project close event.
- */
- @Override
- public void projectClosed(IProject project) {
- // the ProjectResources object will be removed by the ResourceManager.
- }
-
- /**
- * Processes project delete event.
- */
- @Override
- public void projectDeleted(IProject project) {
- // the ProjectResources object will be removed by the ResourceManager.
- }
-
- /**
- * Processes project open event.
- */
- @Override
- public void projectOpened(IProject project) {
- // when the project is opened, we get an ADDED event for each file, so we don't
- // need to do anything here.
- }
-
- @Override
- public void projectRenamed(IProject project, IPath from) {
- // renamed projects also trigger delete/open event,
- // so nothing to be done here.
- }
-
- /**
- * Processes existing project at init time.
- */
- @Override
- public void projectOpenedWithWorkspace(IProject project) {
- try {
- // check this is an android project
- if (project.hasNature(AdtConstants.NATURE_DEFAULT)) {
- String className = getRClassName(project);
- // Find the classname
- if (className == null) {
- // We need to abort.
- AdtPlugin.log(IStatus.ERROR,
- "projectOpenedWithWorkspace: failed to find manifest package for project %1$s", //$NON-NLS-1$
- project.getName());
- return;
- }
- loadAndParseRClass(project, className);
- }
- } catch (CoreException e) {
- // pass
- }
- }
-
- @Override
- public void allProjectsOpenedWithWorkspace() {
- // nothing to do.
- }
-
-
- private void loadAndParseRClass(IProject project, String className) {
- try {
- // first check there's a ProjectResources to store the content
- ProjectResources projectResources = ResourceManager.getInstance().getProjectResources(
- project);
-
- if (projectResources != null) {
- // create a temporary class loader to load the class
- ProjectClassLoader loader = new ProjectClassLoader(null /* parentClassLoader */,
- project);
-
- try {
- Class<?> clazz = loader.loadClass(className);
-
- if (clazz != null) {
- // create the maps to store the result of the parsing
- Map<ResourceType, Map<String, Integer>> resourceValueMap =
- new EnumMap<ResourceType, Map<String, Integer>>(ResourceType.class);
- Map<Integer, Pair<ResourceType, String>> genericValueToNameMap =
- new HashMap<Integer, Pair<ResourceType, String>>();
- Map<IntArrayWrapper, String> styleableValueToNameMap =
- new HashMap<IntArrayWrapper, String>();
-
- // parse the class
- if (parseClass(clazz, genericValueToNameMap, styleableValueToNameMap,
- resourceValueMap)) {
- // now we associate the maps to the project.
- projectResources.setCompiledResources(genericValueToNameMap,
- styleableValueToNameMap, resourceValueMap);
- }
- }
- } catch (Error e) {
- // Log this error with the class name we're trying to load and abort.
- AdtPlugin.log(e, "loadAndParseRClass failed to find class %1$s", className); //$NON-NLS-1$
- }
- }
- } catch (ClassNotFoundException e) {
- // pass
- }
- }
-
- /**
- * Parses a R class, and fills maps.
- * @param rClass the class to parse
- * @param genericValueToNameMap
- * @param styleableValueToNameMap
- * @param resourceValueMap
- * @return True if we managed to parse the R class.
- */
- private boolean parseClass(Class<?> rClass,
- Map<Integer, Pair<ResourceType, String>> genericValueToNameMap,
- Map<IntArrayWrapper, String> styleableValueToNameMap, Map<ResourceType,
- Map<String, Integer>> resourceValueMap) {
- try {
- for (Class<?> inner : rClass.getDeclaredClasses()) {
- String resTypeName = inner.getSimpleName();
- ResourceType resType = ResourceType.getEnum(resTypeName);
-
- if (resType != null) {
- Map<String, Integer> fullMap = new HashMap<String, Integer>();
- resourceValueMap.put(resType, fullMap);
-
- for (Field f : inner.getDeclaredFields()) {
- // only process static final fields.
- int modifiers = f.getModifiers();
- if (Modifier.isStatic(modifiers)) {
- Class<?> type = f.getType();
- if (type.isArray() && type.getComponentType() == int.class) {
- // if the object is an int[] we put it in the styleable map
- styleableValueToNameMap.put(
- new IntArrayWrapper((int[]) f.get(null)),
- f.getName());
- } else if (type == int.class) {
- Integer value = (Integer) f.get(null);
- genericValueToNameMap.put(value, Pair.of(resType, f.getName()));
- fullMap.put(f.getName(), value);
- } else {
- assert false;
- }
- }
- }
- }
- }
-
- return true;
- } catch (IllegalArgumentException e) {
- } catch (IllegalAccessException e) {
- }
- return false;
- }
-
- /**
- * Returns the class name of the R class, based on the project's manifest's package.
- *
- * @return A class name (e.g. "my.app.R") or null if there's no valid package in the manifest.
- */
- private String getRClassName(IProject project) {
- IFile manifestFile = ProjectHelper.getManifest(project);
- if (manifestFile != null && manifestFile.isSynchronized(IResource.DEPTH_ZERO)) {
- ManifestData data = AndroidManifestHelper.parseForData(manifestFile);
- if (data != null) {
- String javaPackage = data.getPackage();
- return javaPackage + ".R"; //$NON-NLS-1$
- }
- }
- return null;
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/DynamicIdMap.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/DynamicIdMap.java
deleted file mode 100644
index 7bab4fd54..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/DynamicIdMap.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.resources.manager;
-
-import com.android.resources.ResourceType;
-import com.android.util.Pair;
-import com.android.utils.SparseArray;
-
-import java.util.HashMap;
-import java.util.Map;
-
-public class DynamicIdMap {
-
- private final Map<Pair<ResourceType, String>, Integer> mDynamicIds = new HashMap<Pair<ResourceType, String>, Integer>();
- private final SparseArray<Pair<ResourceType, String>> mRevDynamicIds = new SparseArray<Pair<ResourceType, String>>();
- private int mDynamicSeed;
-
- public DynamicIdMap(int seed) {
- mDynamicSeed = seed;
- }
-
- public void reset(int seed) {
- mDynamicIds.clear();
- mRevDynamicIds.clear();
- mDynamicSeed = seed;
- }
-
- /**
- * Returns a dynamic integer for the given resource type/name, creating it if it doesn't
- * already exist.
- *
- * @param type the type of the resource
- * @param name the name of the resource
- * @return an integer.
- */
- public Integer getId(ResourceType type, String name) {
- return getId(Pair.of(type, name));
- }
-
- /**
- * Returns a dynamic integer for the given resource type/name, creating it if it doesn't
- * already exist.
- *
- * @param resource the type/name of the resource
- * @return an integer.
- */
- public Integer getId(Pair<ResourceType, String> resource) {
- Integer value = mDynamicIds.get(resource);
- if (value == null) {
- value = Integer.valueOf(++mDynamicSeed);
- mDynamicIds.put(resource, value);
- mRevDynamicIds.put(value, resource);
- }
-
- return value;
- }
-
- public Pair<ResourceType, String> resolveId(int id) {
- return mRevDynamicIds.get(id);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/GlobalProjectMonitor.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/GlobalProjectMonitor.java
deleted file mode 100644
index 674a601d0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/GlobalProjectMonitor.java
+++ /dev/null
@@ -1,546 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.resources.manager;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.resources.ResourceFile;
-import com.android.ide.common.resources.ResourceFolder;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IMarkerDelta;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IResourceDeltaVisitor;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jdt.core.IJavaModel;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.JavaCore;
-
-import java.util.ArrayList;
-
-/**
- * The Global Project Monitor tracks project file changes, and forward them to simple project,
- * file, and folder listeners.
- * Those listeners can be setup with masks to listen to particular events.
- * <p/>
- * To track project resource changes, use the monitor in the {@link ResourceManager}. It is more
- * efficient and while the global ProjectMonitor can track any file, deleted resource files
- * cannot be matched to previous {@link ResourceFile} or {@link ResourceFolder} objects by the
- * time the listeners get the event notifications.
- *
- * @see IProjectListener
- * @see IFolderListener
- * @see IFileListener
- */
-public final class GlobalProjectMonitor {
-
- private final static GlobalProjectMonitor sThis = new GlobalProjectMonitor();
-
- /**
- * Classes which implement this interface provide a method that deals
- * with file change events.
- */
- public interface IFileListener {
- /**
- * Sent when a file changed.
- *
- * @param file The file that changed.
- * @param markerDeltas The marker deltas for the file.
- * @param kind The change kind. This is equivalent to
- * {@link IResourceDelta#accept(IResourceDeltaVisitor)}
- * @param extension the extension of the file or null if the file does
- * not have an extension
- * @param flags the {@link IResourceDelta#getFlags()} value with details
- * on what changed in the file
- * @param isAndroidProject whether the parent project is an Android Project
- */
- public void fileChanged(@NonNull IFile file, @NonNull IMarkerDelta[] markerDeltas,
- int kind, @Nullable String extension, int flags, boolean isAndroidProject);
- }
-
- /**
- * Classes which implements this interface provide methods dealing with project events.
- */
- public interface IProjectListener {
- /**
- * Sent for each opened android project at the time the listener is put in place.
- * @param project the opened project.
- */
- public void projectOpenedWithWorkspace(IProject project);
-
- /**
- * Sent once after all Android projects have been opened,
- * at the time the listener is put in place.
- * <p/>
- * This is called after {@link #projectOpenedWithWorkspace(IProject)} has
- * been called on all known Android projects.
- */
- public void allProjectsOpenedWithWorkspace();
-
- /**
- * Sent when a project is opened.
- * @param project the project being opened.
- */
- public void projectOpened(IProject project);
-
- /**
- * Sent when a project is closed.
- * @param project the project being closed.
- */
- public void projectClosed(IProject project);
-
- /**
- * Sent when a project is deleted.
- * @param project the project about to be deleted.
- */
- public void projectDeleted(IProject project);
-
- /**
- * Sent when a project is renamed. During a project rename
- * {@link #projectDeleted(IProject)} and {@link #projectOpened(IProject)} are also called.
- * This is called last.
- *
- * @param project the new {@link IProject} object.
- * @param from the path of the project before the rename action.
- */
- public void projectRenamed(IProject project, IPath from);
- }
-
- /**
- * Classes which implement this interface provide a method that deals
- * with folder change events
- */
- public interface IFolderListener {
- /**
- * Sent when a folder changed.
- * @param folder The file that was changed
- * @param kind The change kind. This is equivalent to {@link IResourceDelta#getKind()}
- * @param isAndroidProject whether the parent project is an Android Project
- */
- public void folderChanged(IFolder folder, int kind, boolean isAndroidProject);
- }
-
- /**
- * Interface for a listener to be notified when resource change event starts and ends.
- */
- public interface IResourceEventListener {
- public void resourceChangeEventStart();
- public void resourceChangeEventEnd();
- }
-
- /**
- * Interface for a listener that gets passed the raw delta without processing.
- */
- public interface IRawDeltaListener {
- public void visitDelta(IResourceDelta delta);
- }
-
- /**
- * Base listener bundle to associate a listener to an event mask.
- */
- private static class ListenerBundle {
- /** Mask value to accept all events */
- public final static int MASK_NONE = -1;
-
- /**
- * Event mask. Values accepted are IResourceDelta.###
- * @see IResourceDelta#ADDED
- * @see IResourceDelta#REMOVED
- * @see IResourceDelta#CHANGED
- * @see IResourceDelta#ADDED_PHANTOM
- * @see IResourceDelta#REMOVED_PHANTOM
- * */
- int kindMask;
- }
-
- /**
- * Listener bundle for file event.
- */
- private static class FileListenerBundle extends ListenerBundle {
-
- /** The file listener */
- IFileListener listener;
- }
-
- /**
- * Listener bundle for folder event.
- */
- private static class FolderListenerBundle extends ListenerBundle {
- /** The file listener */
- IFolderListener listener;
- }
-
- private final ArrayList<FileListenerBundle> mFileListeners =
- new ArrayList<FileListenerBundle>();
-
- private final ArrayList<FolderListenerBundle> mFolderListeners =
- new ArrayList<FolderListenerBundle>();
-
- private final ArrayList<IProjectListener> mProjectListeners = new ArrayList<IProjectListener>();
-
- private final ArrayList<IResourceEventListener> mEventListeners =
- new ArrayList<IResourceEventListener>();
-
- private final ArrayList<IRawDeltaListener> mRawDeltaListeners =
- new ArrayList<IRawDeltaListener>();
-
- private IWorkspace mWorkspace;
-
- private boolean mIsAndroidProject;
-
- /**
- * Delta visitor for resource changes.
- */
- private final class DeltaVisitor implements IResourceDeltaVisitor {
-
- @Override
- public boolean visit(IResourceDelta delta) {
- // Find the other resource listeners to notify
- IResource r = delta.getResource();
- int type = r.getType();
- if (type == IResource.FILE) {
- int kind = delta.getKind();
- // notify the listeners.
- for (FileListenerBundle bundle : mFileListeners) {
- if (bundle.kindMask == ListenerBundle.MASK_NONE
- || (bundle.kindMask & kind) != 0) {
- try {
- bundle.listener.fileChanged((IFile)r, delta.getMarkerDeltas(), kind,
- r.getFileExtension(), delta.getFlags(), mIsAndroidProject);
- } catch (Throwable t) {
- AdtPlugin.log(t,"Failed to call IFileListener.fileChanged");
- }
- }
- }
- return false;
- } else if (type == IResource.FOLDER) {
- int kind = delta.getKind();
- // notify the listeners.
- for (FolderListenerBundle bundle : mFolderListeners) {
- if (bundle.kindMask == ListenerBundle.MASK_NONE
- || (bundle.kindMask & kind) != 0) {
- try {
- bundle.listener.folderChanged((IFolder)r, kind, mIsAndroidProject);
- } catch (Throwable t) {
- AdtPlugin.log(t,"Failed to call IFileListener.folderChanged");
- }
- }
- }
- return true;
- } else if (type == IResource.PROJECT) {
- IProject project = (IProject)r;
-
- try {
- mIsAndroidProject = project.hasNature(AdtConstants.NATURE_DEFAULT);
- } catch (CoreException e) {
- // this can only happen if the project does not exist or is not open, neither
- // of which can happen here since we are processing changes in the project
- // or at worst a project post-open event.
- return false;
- }
-
- if (mIsAndroidProject == false) {
- // for non android project, skip the project listeners but return true
- // to visit the children and notify the IFileListeners
- return true;
- }
-
- int flags = delta.getFlags();
-
- if ((flags & IResourceDelta.OPEN) != 0) {
- // the project is opening or closing.
-
- if (project.isOpen()) {
- // notify the listeners.
- for (IProjectListener pl : mProjectListeners) {
- try {
- pl.projectOpened(project);
- } catch (Throwable t) {
- AdtPlugin.log(t,"Failed to call IProjectListener.projectOpened");
- }
- }
- } else {
- // notify the listeners.
- for (IProjectListener pl : mProjectListeners) {
- try {
- pl.projectClosed(project);
- } catch (Throwable t) {
- AdtPlugin.log(t,"Failed to call IProjectListener.projectClosed");
- }
- }
- }
-
- if ((flags & IResourceDelta.MOVED_FROM) != 0) {
- IPath from = delta.getMovedFromPath();
- // notify the listeners.
- for (IProjectListener pl : mProjectListeners) {
- try {
- pl.projectRenamed(project, from);
- } catch (Throwable t) {
- AdtPlugin.log(t,"Failed to call IProjectListener.projectRenamed");
- }
- }
- }
- }
- }
-
- return true;
- }
- }
-
- public static GlobalProjectMonitor getMonitor() {
- return sThis;
- }
-
-
- /**
- * Starts the resource monitoring.
- * @param ws The current workspace.
- * @return The monitor object.
- */
- public static GlobalProjectMonitor startMonitoring(IWorkspace ws) {
- if (sThis != null) {
- ws.addResourceChangeListener(sThis.mResourceChangeListener,
- IResourceChangeEvent.POST_CHANGE | IResourceChangeEvent.PRE_DELETE);
- sThis.mWorkspace = ws;
- }
- return sThis;
- }
-
- /**
- * Stops the resource monitoring.
- * @param ws The current workspace.
- */
- public static void stopMonitoring(IWorkspace ws) {
- if (sThis != null) {
- ws.removeResourceChangeListener(sThis.mResourceChangeListener);
-
- synchronized (sThis) {
- sThis.mFileListeners.clear();
- sThis.mProjectListeners.clear();
- }
- }
- }
-
- /**
- * Adds a file listener.
- * @param listener The listener to receive the events.
- * @param kindMask The event mask to filter out specific events.
- * {@link ListenerBundle#MASK_NONE} will forward all events.
- * See {@link ListenerBundle#kindMask} for more values.
- */
- public synchronized void addFileListener(IFileListener listener, int kindMask) {
- FileListenerBundle bundle = new FileListenerBundle();
- bundle.listener = listener;
- bundle.kindMask = kindMask;
-
- mFileListeners.add(bundle);
- }
-
- /**
- * Removes an existing file listener.
- * @param listener the listener to remove.
- */
- public synchronized void removeFileListener(IFileListener listener) {
- for (int i = 0 ; i < mFileListeners.size() ; i++) {
- FileListenerBundle bundle = mFileListeners.get(i);
- if (bundle.listener == listener) {
- mFileListeners.remove(i);
- return;
- }
- }
- }
-
- /**
- * Adds a folder listener.
- * @param listener The listener to receive the events.
- * @param kindMask The event mask to filter out specific events.
- * {@link ListenerBundle#MASK_NONE} will forward all events.
- * See {@link ListenerBundle#kindMask} for more values.
- */
- public synchronized void addFolderListener(IFolderListener listener, int kindMask) {
- FolderListenerBundle bundle = new FolderListenerBundle();
- bundle.listener = listener;
- bundle.kindMask = kindMask;
-
- mFolderListeners.add(bundle);
- }
-
- /**
- * Removes an existing folder listener.
- * @param listener the listener to remove.
- */
- public synchronized void removeFolderListener(IFolderListener listener) {
- for (int i = 0 ; i < mFolderListeners.size() ; i++) {
- FolderListenerBundle bundle = mFolderListeners.get(i);
- if (bundle.listener == listener) {
- mFolderListeners.remove(i);
- return;
- }
- }
- }
-
- /**
- * Adds a project listener.
- * @param listener The listener to receive the events.
- */
- public synchronized void addProjectListener(IProjectListener listener) {
- mProjectListeners.add(listener);
-
- // we need to look at the opened projects and give them to the listener.
-
- // get the list of opened android projects.
- IWorkspaceRoot workspaceRoot = mWorkspace.getRoot();
- IJavaModel javaModel = JavaCore.create(workspaceRoot);
- IJavaProject[] androidProjects = BaseProjectHelper.getAndroidProjects(javaModel,
- null /*filter*/);
-
-
- notifyResourceEventStart();
-
- for (IJavaProject androidProject : androidProjects) {
- listener.projectOpenedWithWorkspace(androidProject.getProject());
- }
-
- listener.allProjectsOpenedWithWorkspace();
-
- notifyResourceEventEnd();
- }
-
- /**
- * Removes an existing project listener.
- * @param listener the listener to remove.
- */
- public synchronized void removeProjectListener(IProjectListener listener) {
- mProjectListeners.remove(listener);
- }
-
- /**
- * Adds a resource event listener.
- * @param listener The listener to receive the events.
- */
- public synchronized void addResourceEventListener(IResourceEventListener listener) {
- mEventListeners.add(listener);
- }
-
- /**
- * Removes an existing Resource Event listener.
- * @param listener the listener to remove.
- */
- public synchronized void removeResourceEventListener(IResourceEventListener listener) {
- mEventListeners.remove(listener);
- }
-
- /**
- * Adds a raw delta listener.
- * @param listener The listener to receive the deltas.
- */
- public synchronized void addRawDeltaListener(IRawDeltaListener listener) {
- mRawDeltaListeners.add(listener);
- }
-
- /**
- * Removes an existing Raw Delta listener.
- * @param listener the listener to remove.
- */
- public synchronized void removeRawDeltaListener(IRawDeltaListener listener) {
- mRawDeltaListeners.remove(listener);
- }
-
- private void notifyResourceEventStart() {
- for (IResourceEventListener listener : mEventListeners) {
- try {
- listener.resourceChangeEventStart();
- } catch (Throwable t) {
- AdtPlugin.log(t,"Failed to call IResourceEventListener.resourceChangeEventStart");
- }
- }
- }
-
- private void notifyResourceEventEnd() {
- for (IResourceEventListener listener : mEventListeners) {
- try {
- listener.resourceChangeEventEnd();
- } catch (Throwable t) {
- AdtPlugin.log(t,"Failed to call IResourceEventListener.resourceChangeEventEnd");
- }
- }
- }
-
- private IResourceChangeListener mResourceChangeListener = new IResourceChangeListener() {
- /**
- * Processes the workspace resource change events.
- *
- * @see IResourceChangeListener#resourceChanged(IResourceChangeEvent)
- */
- @Override
- public synchronized void resourceChanged(IResourceChangeEvent event) {
- // notify the event listeners of a start.
- notifyResourceEventStart();
-
- if (event.getType() == IResourceChangeEvent.PRE_DELETE) {
- // a project is being deleted. Lets get the project object and remove
- // its compiled resource list.
- IResource r = event.getResource();
- IProject project = r.getProject();
-
- // notify the listeners.
- for (IProjectListener pl : mProjectListeners) {
- try {
- if (project.hasNature(AdtConstants.NATURE_DEFAULT)) {
- try {
- pl.projectDeleted(project);
- } catch (Throwable t) {
- AdtPlugin.log(t,"Failed to call IProjectListener.projectDeleted");
- }
- }
- } catch (CoreException e) {
- // just ignore this project.
- }
- }
- } else {
- // this a regular resource change. We get the delta and go through it with a visitor.
- IResourceDelta delta = event.getDelta();
-
- // notify the raw delta listeners
- for (IRawDeltaListener listener : mRawDeltaListeners) {
- listener.visitDelta(delta);
- }
-
- DeltaVisitor visitor = new DeltaVisitor();
- try {
- delta.accept(visitor);
- } catch (CoreException e) {
- }
- }
-
- // we're done, notify the event listeners.
- notifyResourceEventEnd();
- }
- };
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/IdeScanningContext.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/IdeScanningContext.java
deleted file mode 100644
index d61324937..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/IdeScanningContext.java
+++ /dev/null
@@ -1,234 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.resources.manager;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.ide.eclipse.adt.AdtConstants.MARKER_AAPT_COMPILE;
-import static org.eclipse.core.resources.IResource.DEPTH_ONE;
-import static org.eclipse.core.resources.IResource.DEPTH_ZERO;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.resources.ResourceRepository;
-import com.android.ide.common.resources.ScanningContext;
-import com.android.ide.common.resources.platform.AttributeInfo;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.build.AaptParser;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.utils.Pair;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * An {@link IdeScanningContext} is a specialized {@link ScanningContext} which
- * carries extra information about the scanning state, such as which file is
- * currently being scanned, and which files have been scanned in the past, such
- * that at the end of a scan we can mark and clear errors, etc.
- */
-public class IdeScanningContext extends ScanningContext {
- private final IProject mProject;
- private final List<IResource> mScannedResources = new ArrayList<IResource>();
- private IResource mCurrentFile;
- private List<Pair<IResource, String>> mErrors;
- private Set<IProject> mFullAaptProjects;
- private boolean mValidate;
- private Map<String, AttributeInfo> mAttributeMap;
- private ResourceRepository mFrameworkResources;
-
- /**
- * Constructs a new {@link IdeScanningContext}
- *
- * @param repository the associated {@link ResourceRepository}
- * @param project the associated project
- * @param validate if true, check that the attributes and resources are
- * valid and if not request a full AAPT check
- */
- public IdeScanningContext(@NonNull ResourceRepository repository, @NonNull IProject project,
- boolean validate) {
- super(repository);
- mProject = project;
- mValidate = validate;
-
- Sdk sdk = Sdk.getCurrent();
- if (sdk != null) {
- AndroidTargetData targetData = sdk.getTargetData(project);
- if (targetData != null) {
- mAttributeMap = targetData.getAttributeMap();
- mFrameworkResources = targetData.getFrameworkResources();
- }
- }
- }
-
- @Override
- public void addError(@NonNull String error) {
- super.addError(error);
-
- if (mErrors == null) {
- mErrors = new ArrayList<Pair<IResource,String>>();
- }
- mErrors.add(Pair.of(mCurrentFile, error));
- }
-
- /**
- * Notifies the context that the given resource is about to be scanned.
- *
- * @param resource the resource about to be scanned
- */
- public void startScanning(@NonNull IResource resource) {
- assert mCurrentFile == null : mCurrentFile;
- mCurrentFile = resource;
- mScannedResources.add(resource);
- }
-
- /**
- * Notifies the context that the given resource has been scanned.
- *
- * @param resource the resource that was scanned
- */
- public void finishScanning(@NonNull IResource resource) {
- assert mCurrentFile != null;
- mCurrentFile = null;
- }
-
- /**
- * Process any errors found to add error markers in the affected files (and
- * also clear up any aapt errors in files that are no longer applicable)
- *
- * @param async if true, delay updating markers until the next display
- * thread event loop update
- */
- public void updateMarkers(boolean async) {
- // Run asynchronously? This is necessary for example when adding markers
- // as the result of a resource change notification, since at that point the
- // resource tree is locked for modifications and attempting to create a
- // marker will throw a org.eclipse.core.internal.resources.ResourceException.
- if (async) {
- AdtPlugin.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- updateMarkers(false);
- }
- });
- return;
- }
-
- // First clear out old/previous markers
- for (IResource resource : mScannedResources) {
- try {
- if (resource.exists()) {
- int depth = resource instanceof IFolder ? DEPTH_ONE : DEPTH_ZERO;
- resource.deleteMarkers(MARKER_AAPT_COMPILE, true, depth);
- }
- } catch (CoreException ce) {
- // Pass
- }
- }
-
- // Add new errors
- if (mErrors != null && mErrors.size() > 0) {
- List<String> errors = new ArrayList<String>();
- for (Pair<IResource, String> pair : mErrors) {
- errors.add(pair.getSecond());
- }
- AaptParser.parseOutput(errors, mProject);
- }
- }
-
- @Override
- public boolean needsFullAapt() {
- // returns true if it was explicitly requested or if a file that has errors was modified.
- // This handles the case where an edit doesn't add any new id but fix a compile error.
- return super.needsFullAapt() || hasModifiedFilesWithErrors();
- }
-
- /**
- * Returns true if any of the scanned resources has an error marker on it.
- */
- private boolean hasModifiedFilesWithErrors() {
- for (IResource resource : mScannedResources) {
- try {
- int depth = resource instanceof IFolder ? DEPTH_ONE : DEPTH_ZERO;
- if (resource.exists()) {
- IMarker[] markers = resource.findMarkers(IMarker.PROBLEM,
- true /*includeSubtypes*/, depth);
- for (IMarker marker : markers) {
- if (marker.getAttribute(IMarker.SEVERITY, IMarker.SEVERITY_INFO) ==
- IMarker.SEVERITY_ERROR) {
- return true;
- }
- }
- }
- } catch (CoreException ce) {
- // Pass
- }
- }
-
- return false;
- }
-
- @Override
- protected void requestFullAapt() {
- super.requestFullAapt();
-
- if (mCurrentFile != null) {
- if (mFullAaptProjects == null) {
- mFullAaptProjects = new HashSet<IProject>();
- }
- mFullAaptProjects.add(mCurrentFile.getProject());
- } else {
- assert false : "No current context to apply IdeScanningContext to";
- }
- }
-
- /**
- * Returns the collection of projects that scanned resources have requested
- * a full aapt for.
- *
- * @return a collection of projects that scanned resources requested full
- * aapt runs for, or null
- */
- public Collection<IProject> getAaptRequestedProjects() {
- return mFullAaptProjects;
- }
-
- @Override
- public boolean checkValue(@Nullable String uri, @NonNull String name, @NonNull String value) {
- if (!mValidate) {
- return true;
- }
-
- if (!needsFullAapt() && mAttributeMap != null && ANDROID_URI.equals(uri)) {
- AttributeInfo info = mAttributeMap.get(name);
- if (info != null && !info.isValid(value, mRepository, mFrameworkResources)) {
- return false;
- }
- }
-
- return super.checkValue(uri, name, value);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ProjectClassLoader.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ProjectClassLoader.java
deleted file mode 100644
index e07f09927..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ProjectClassLoader.java
+++ /dev/null
@@ -1,376 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.resources.manager;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.build.BuildHelper;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jdt.core.IClasspathContainer;
-import org.eclipse.jdt.core.IClasspathEntry;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.JavaModelException;
-import org.objectweb.asm.ClassReader;
-import org.objectweb.asm.ClassVisitor;
-import org.objectweb.asm.ClassWriter;
-import org.objectweb.asm.Opcodes;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLClassLoader;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * ClassLoader able to load class from output of an Eclipse project.
- */
-public final class ProjectClassLoader extends ClassLoader {
-
- private final IJavaProject mJavaProject;
- private URLClassLoader mJarClassLoader;
- private boolean mInsideJarClassLoader = false;
-
- public ProjectClassLoader(ClassLoader parentClassLoader, IProject project) {
- super(parentClassLoader);
- mJavaProject = JavaCore.create(project);
- }
-
- @Override
- protected Class<?> findClass(String name) throws ClassNotFoundException {
- // if we are here through a child classloader, throw an exception.
- if (mInsideJarClassLoader) {
- throw new ClassNotFoundException(name);
- }
-
- // attempt to load the class from the main project
- Class<?> clazz = loadFromProject(mJavaProject, name);
-
- if (clazz != null) {
- return clazz;
- }
-
- // attempt to load the class from the jar dependencies
- clazz = loadClassFromJar(name);
- if (clazz != null) {
- return clazz;
- }
-
- // attempt to load the class from the libraries
- try {
- // get the project info
- ProjectState projectState = Sdk.getProjectState(mJavaProject.getProject());
-
- // this can happen if the project has no project.properties.
- if (projectState != null) {
-
- List<IProject> libProjects = projectState.getFullLibraryProjects();
- List<IJavaProject> referencedJavaProjects = BuildHelper.getJavaProjects(
- libProjects);
-
- for (IJavaProject javaProject : referencedJavaProjects) {
- clazz = loadFromProject(javaProject, name);
-
- if (clazz != null) {
- return clazz;
- }
- }
- }
- } catch (CoreException e) {
- // log exception?
- }
-
- throw new ClassNotFoundException(name);
- }
-
- /**
- * Attempts to load a class from a project output folder.
- * @param project the project to load the class from
- * @param name the name of the class
- * @return a class object if found, null otherwise.
- */
- private Class<?> loadFromProject(IJavaProject project, String name) {
- try {
- // get the project output folder.
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- IPath outputLocation = project.getOutputLocation();
- IResource outRes = root.findMember(outputLocation);
- if (outRes == null) {
- return null;
- }
-
- File outFolder = new File(outRes.getLocation().toOSString());
-
- // get the class name segments
- String[] segments = name.split("\\."); //$NON-NLS-1$
-
- // try to load the class from the bin folder of the project.
- File classFile = getFile(outFolder, segments, 0);
- if (classFile == null) {
- return null;
- }
-
- // load the content of the file and create the class.
- FileInputStream fis = new FileInputStream(classFile);
- byte[] data = new byte[(int)classFile.length()];
- int read = 0;
- try {
- read = fis.read(data);
- } catch (IOException e) {
- data = null;
- }
- fis.close();
-
- if (data != null) {
- try {
- Class<?> clazz = defineClass(null, data, 0, read);
- if (clazz != null) {
- return clazz;
- }
- } catch (UnsupportedClassVersionError e) {
- // Attempt to reload on lower version
- int maxVersion = 50; // JDK 1.6
- try {
- byte[] rewritten = rewriteClass(data, maxVersion, 0);
- return defineClass(null, rewritten, 0, rewritten.length);
- } catch (UnsupportedClassVersionError e2) {
- throw e; // throw *original* exception, not attempt to rewrite
- }
- }
- }
- } catch (Exception e) {
- // log the exception?
- }
-
- return null;
- }
-
- /**
- * Rewrites the given class to the given target class file version.
- */
- public static byte[] rewriteClass(byte[] classData, final int maxVersion, final int minVersion) {
- assert maxVersion >= minVersion;
- ClassWriter classWriter = new ClassWriter(0);
- ClassVisitor classVisitor = new ClassVisitor(Opcodes.ASM5, classWriter) {
- @Override
- public void visit(int version, int access, String name, String signature,
- String superName, String[] interfaces) {
- if (version > maxVersion) {
- version = maxVersion;
- }
- if (version < minVersion) {
- version = minVersion;
- }
- super.visit(version, access, name, signature, superName, interfaces);
- }
- };
- ClassReader reader = new ClassReader(classData);
- reader.accept(classVisitor, 0);
- return classWriter.toByteArray();
- }
-
- /**
- * Returns the File matching the a certain path from a root {@link File}.
- * <p/>The methods checks that the file ends in .class even though the last segment
- * does not.
- * @param parent the root of the file.
- * @param segments the segments containing the path of the file
- * @param index the offset at which to start looking into segments.
- * @throws FileNotFoundException
- */
- private File getFile(File parent, String[] segments, int index)
- throws FileNotFoundException {
- // reached the end with no match?
- if (index == segments.length) {
- throw new FileNotFoundException();
- }
-
- String toMatch = segments[index];
- File[] files = parent.listFiles();
-
- // we're at the last segments. we look for a matching <file>.class
- if (index == segments.length - 1) {
- toMatch = toMatch + ".class";
-
- if (files != null) {
- for (File file : files) {
- if (file.isFile() && file.getName().equals(toMatch)) {
- return file;
- }
- }
- }
-
- // no match? abort.
- throw new FileNotFoundException();
- }
-
- String innerClassName = null;
-
- if (files != null) {
- for (File file : files) {
- if (file.isDirectory()) {
- if (toMatch.equals(file.getName())) {
- return getFile(file, segments, index+1);
- }
- } else if (file.getName().startsWith(toMatch)) {
- if (innerClassName == null) {
- StringBuilder sb = new StringBuilder(segments[index]);
- for (int i = index + 1 ; i < segments.length ; i++) {
- sb.append('$');
- sb.append(segments[i]);
- }
- sb.append(".class");
-
- innerClassName = sb.toString();
- }
-
- if (file.getName().equals(innerClassName)) {
- return file;
- }
- }
- }
- }
-
- return null;
- }
-
- /**
- * Loads a class from the 3rd party jar present in the project
- *
- * @return the class loader or null if not found.
- */
- private Class<?> loadClassFromJar(String name) {
- if (mJarClassLoader == null) {
- // get the OS path to all the external jars
- URL[] jars = getExternalJars();
-
- mJarClassLoader = new URLClassLoader(jars, this /* parent */);
- }
-
- try {
- // because a class loader always look in its parent loader first, we need to know
- // that we are querying the jar classloader. This will let us know to not query
- // it again for classes we don't find, or this would create an infinite loop.
- mInsideJarClassLoader = true;
- return mJarClassLoader.loadClass(name);
- } catch (ClassNotFoundException e) {
- // not found? return null.
- return null;
- } finally {
- mInsideJarClassLoader = false;
- }
- }
-
- /**
- * Returns an array of external jar files used by the project.
- * @return an array of OS-specific absolute file paths
- */
- private final URL[] getExternalJars() {
- // get a java project from it
- IJavaProject javaProject = JavaCore.create(mJavaProject.getProject());
-
- ArrayList<URL> oslibraryList = new ArrayList<URL>();
- IClasspathEntry[] classpaths = javaProject.readRawClasspath();
- if (classpaths != null) {
- for (IClasspathEntry e : classpaths) {
- if (e.getEntryKind() == IClasspathEntry.CPE_LIBRARY ||
- e.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
- // if this is a classpath variable reference, we resolve it.
- if (e.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
- e = JavaCore.getResolvedClasspathEntry(e);
- }
-
- handleClassPathEntry(e, oslibraryList);
- } else if (e.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
- // get the container.
- try {
- IClasspathContainer container = JavaCore.getClasspathContainer(
- e.getPath(), javaProject);
- // ignore the system and default_system types as they represent
- // libraries that are part of the runtime.
- if (container != null &&
- container.getKind() == IClasspathContainer.K_APPLICATION) {
- IClasspathEntry[] entries = container.getClasspathEntries();
- for (IClasspathEntry entry : entries) {
- // TODO: Xav -- is this necessary?
- if (entry.getEntryKind() == IClasspathEntry.CPE_VARIABLE) {
- entry = JavaCore.getResolvedClasspathEntry(entry);
- }
-
- handleClassPathEntry(entry, oslibraryList);
- }
- }
- } catch (JavaModelException jme) {
- // can't resolve the container? ignore it.
- AdtPlugin.log(jme, "Failed to resolve ClasspathContainer: %s",
- e.getPath());
- }
- }
- }
- }
-
- return oslibraryList.toArray(new URL[oslibraryList.size()]);
- }
-
- private void handleClassPathEntry(IClasspathEntry e, ArrayList<URL> oslibraryList) {
- // get the IPath
- IPath path = e.getPath();
-
- // check the name ends with .jar
- if (SdkConstants.EXT_JAR.equalsIgnoreCase(path.getFileExtension())) {
- boolean local = false;
- IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(path);
- if (resource != null && resource.exists() &&
- resource.getType() == IResource.FILE) {
- local = true;
- try {
- oslibraryList.add(new File(resource.getLocation().toOSString())
- .toURI().toURL());
- } catch (MalformedURLException mue) {
- // pass
- }
- }
-
- if (local == false) {
- // if the jar path doesn't match a workspace resource,
- // then we get an OSString and check if this links to a valid file.
- String osFullPath = path.toOSString();
-
- File f = new File(osFullPath);
- if (f.exists()) {
- try {
- oslibraryList.add(f.toURI().toURL());
- } catch (MalformedURLException mue) {
- // pass
- }
- }
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ProjectResources.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ProjectResources.java
deleted file mode 100644
index 7c3fd4c13..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ProjectResources.java
+++ /dev/null
@@ -1,271 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.resources.manager;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.ide.common.rendering.api.ResourceValue;
-import com.android.ide.common.resources.IntArrayWrapper;
-import com.android.ide.common.resources.ResourceFolder;
-import com.android.ide.common.resources.ResourceItem;
-import com.android.ide.common.resources.ResourceRepository;
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.io.IFolderWrapper;
-import com.android.io.IAbstractFolder;
-import com.android.resources.ResourceType;
-import com.android.util.Pair;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-
-import java.util.EnumMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-/**
- * Represents the resources of a project.
- * On top of the regular {@link ResourceRepository} features it provides:
- *<ul>
- *<li>configured resources contain the resources coming from the libraries.</li>
- *<li>resolution to and from resource integer (compiled value in R.java).</li>
- *<li>handles resource integer for non existing values of type ID. This is used when rendering.</li>
- *<li>layouts that have no been saved yet. This is handled by generating dynamic IDs
- * on the fly.</li>
- *</ul>
- */
-@SuppressWarnings("deprecation")
-public class ProjectResources extends ResourceRepository {
- // project resources are defined as 0x7FXX#### where XX is the resource type (layout, drawable,
- // etc...). Using FF as the type allows for 255 resource types before we get a collision
- // which should be fine.
- private final static int DYNAMIC_ID_SEED_START = 0x7fff0000;
-
- /** Map of (name, id) for resources of type {@link ResourceType#ID} coming from R.java */
- private Map<ResourceType, Map<String, Integer>> mResourceValueMap;
- /** Map of (id, [name, resType]) for all resources coming from R.java */
- private Map<Integer, Pair<ResourceType, String>> mResIdValueToNameMap;
- /** Map of (int[], name) for styleable resources coming from R.java */
- private Map<IntArrayWrapper, String> mStyleableValueToNameMap;
-
- private final DynamicIdMap mDynamicIdMap = new DynamicIdMap(DYNAMIC_ID_SEED_START);
- private final IntArrayWrapper mWrapper = new IntArrayWrapper(null);
- private final IProject mProject;
-
- public static ProjectResources create(IProject project) {
- IFolder resFolder = project.getFolder(SdkConstants.FD_RESOURCES);
-
- return new ProjectResources(project, new IFolderWrapper(resFolder));
- }
-
- /**
- * Makes a ProjectResources for a given <var>project</var>.
- * @param project the project.
- */
- private ProjectResources(IProject project, IAbstractFolder resFolder) {
- super(resFolder, false /*isFrameworkRepository*/);
- mProject = project;
- }
-
- /**
- * Returns the resources values matching a given {@link FolderConfiguration}, this will
- * include library dependency.
- *
- * @param referenceConfig the configuration that each value must match.
- * @return a map with guaranteed to contain an entry for each {@link ResourceType}
- */
- @Override
- @NonNull
- public Map<ResourceType, Map<String, ResourceValue>> getConfiguredResources(
- @NonNull FolderConfiguration referenceConfig) {
- ensureInitialized();
-
- Map<ResourceType, Map<String, ResourceValue>> resultMap =
- new EnumMap<ResourceType, Map<String, ResourceValue>>(ResourceType.class);
-
- // if the project contains libraries, we need to add the libraries resources here
- // so that they are accessible to the layout rendering.
- if (mProject != null) {
- ProjectState state = Sdk.getProjectState(mProject);
- if (state != null) {
- List<IProject> libraries = state.getFullLibraryProjects();
-
- ResourceManager resMgr = ResourceManager.getInstance();
-
- // because aapt put all the library in their order in this array, the first
- // one will have priority over the 2nd one. So it's better to loop in the inverse
- // order and fill the map with resources that will be overwritten by higher
- // priority resources
- for (int i = libraries.size() - 1 ; i >= 0 ; i--) {
- IProject library = libraries.get(i);
-
- ProjectResources libRes = resMgr.getProjectResources(library);
- if (libRes != null) {
- // get the library resources, and only the library, not the dependencies
- // so call doGetConfiguredResources() directly.
- Map<ResourceType, Map<String, ResourceValue>> libMap =
- libRes.doGetConfiguredResources(referenceConfig);
-
- // we don't want to simply replace the whole map, but instead merge the
- // content of any sub-map
- for (Entry<ResourceType, Map<String, ResourceValue>> libEntry :
- libMap.entrySet()) {
-
- // get the map currently in the result map for this resource type
- Map<String, ResourceValue> tempMap = resultMap.get(libEntry.getKey());
- if (tempMap == null) {
- // since there's no current map for this type, just add the map
- // directly coming from the library resources
- resultMap.put(libEntry.getKey(), libEntry.getValue());
- } else {
- // already a map for this type. add the resources from the
- // library, this will override existing value, which is why
- // we loop in a specific library order.
- tempMap.putAll(libEntry.getValue());
- }
- }
- }
- }
- }
- }
-
- // now the project resources themselves.
- Map<ResourceType, Map<String, ResourceValue>> thisProjectMap =
- doGetConfiguredResources(referenceConfig);
-
- // now merge the maps.
- for (Entry<ResourceType, Map<String, ResourceValue>> entry : thisProjectMap.entrySet()) {
- ResourceType type = entry.getKey();
- Map<String, ResourceValue> typeMap = resultMap.get(type);
- if (typeMap == null) {
- resultMap.put(type, entry.getValue());
- } else {
- typeMap.putAll(entry.getValue());
- }
- }
-
- return resultMap;
- }
-
- /**
- * Returns the {@link ResourceFolder} associated with a {@link IFolder}.
- * @param folder The {@link IFolder} object.
- * @return the {@link ResourceFolder} or null if it was not found.
- *
- * @see ResourceRepository#getResourceFolder(com.android.io.IAbstractFolder)
- */
- public ResourceFolder getResourceFolder(IFolder folder) {
- return getResourceFolder(new IFolderWrapper(folder));
- }
-
- /**
- * Resolves a compiled resource id into the resource name and type
- * @param id the resource integer id.
- * @return a {@link Pair} of 2 strings { name, type } or null if the id could not be resolved
- */
- public Pair<ResourceType, String> resolveResourceId(int id) {
- Pair<ResourceType, String> result = null;
- if (mResIdValueToNameMap != null) {
- result = mResIdValueToNameMap.get(id);
- }
-
- if (result == null) {
- synchronized (mDynamicIdMap) {
- result = mDynamicIdMap.resolveId(id);
- }
- }
-
- return result;
- }
-
- /**
- * Resolves a compiled styleable id of type int[] into the styleable name.
- */
- public String resolveStyleable(int[] id) {
- if (mStyleableValueToNameMap != null) {
- mWrapper.set(id);
- return mStyleableValueToNameMap.get(mWrapper);
- }
-
- return null;
- }
-
- /**
- * Returns the integer id of a resource given its type and name.
- * <p/>If the resource is of type {@link ResourceType#ID} and does not exist in the
- * internal map, then new id values are dynamically generated (and stored so that queries
- * with the same names will return the same value).
- */
- public Integer getResourceId(ResourceType type, String name) {
- Integer result = null;
- if (mResourceValueMap != null) {
- Map<String, Integer> map = mResourceValueMap.get(type);
- if (map != null) {
- result = map.get(name);
- }
- }
-
- if (result == null) {
- synchronized (mDynamicIdMap) {
- result = mDynamicIdMap.getId(type, name);
- }
- }
-
- return result;
- }
-
- /**
- * Resets the list of dynamic Ids. This list is used by
- * {@link #getResourceId(String, String)} when the resource query is an ID that doesn't
- * exist (for example for ID automatically generated in layout files that are not saved yet.)
- * <p/>This method resets those dynamic ID and must be called whenever the actual list of IDs
- * change.
- */
- public void resetDynamicIds() {
- synchronized (mDynamicIdMap) {
- mDynamicIdMap.reset(DYNAMIC_ID_SEED_START);
- }
- }
-
- @Override
- @NonNull
- protected ResourceItem createResourceItem(@NonNull String name) {
- return new ResourceItem(name);
- }
-
- /**
- * Sets compiled resource information.
- *
- * @param resIdValueToNameMap a map of compiled resource id to resource name.
- * The map is acquired by the {@link ProjectResources} object.
- * @param styleableValueMap a map of (int[], name) for the styleable information. The map is
- * acquired by the {@link ProjectResources} object.
- * @param resourceValueMap a map of (name, id) for resources of type {@link ResourceType#ID}.
- * The list is acquired by the {@link ProjectResources} object.
- */
- void setCompiledResources(Map<Integer, Pair<ResourceType, String>> resIdValueToNameMap,
- Map<IntArrayWrapper, String> styleableValueMap,
- Map<ResourceType, Map<String, Integer>> resourceValueMap) {
- mResourceValueMap = resourceValueMap;
- mResIdValueToNameMap = resIdValueToNameMap;
- mStyleableValueToNameMap = styleableValueMap;
-
- resetDynamicIds();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ResourceManager.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ResourceManager.java
deleted file mode 100644
index e407b6a78..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/resources/manager/ResourceManager.java
+++ /dev/null
@@ -1,655 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.resources.manager;
-
-import com.android.SdkConstants;
-import com.android.ide.common.resources.FrameworkResources;
-import com.android.ide.common.resources.ResourceFile;
-import com.android.ide.common.resources.ResourceFolder;
-import com.android.ide.common.resources.ResourceRepository;
-import com.android.ide.common.resources.ScanningContext;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.resources.ResourceHelper;
-import com.android.ide.eclipse.adt.internal.resources.manager.GlobalProjectMonitor.IProjectListener;
-import com.android.ide.eclipse.adt.internal.resources.manager.GlobalProjectMonitor.IRawDeltaListener;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.io.IFileWrapper;
-import com.android.ide.eclipse.adt.io.IFolderWrapper;
-import com.android.io.FolderWrapper;
-import com.android.resources.ResourceFolderType;
-import com.android.sdklib.IAndroidTarget;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IMarkerDelta;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IResourceDeltaVisitor;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.QualifiedName;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * The ResourceManager tracks resources for all opened projects.
- * <p/>
- * It provide direct access to all the resources of a project as a {@link ProjectResources}
- * object that allows accessing the resources through their file representation or as Android
- * resources (similar to what is seen by an Android application).
- * <p/>
- * The ResourceManager automatically tracks file changes to update its internal representation
- * of the resources so that they are always up to date.
- * <p/>
- * It also gives access to a monitor that is more resource oriented than the
- * {@link GlobalProjectMonitor}.
- * This monitor will let you track resource changes by giving you direct access to
- * {@link ResourceFile}, or {@link ResourceFolder}.
- *
- * @see ProjectResources
- */
-public final class ResourceManager {
- public final static boolean DEBUG = false;
-
- private final static ResourceManager sThis = new ResourceManager();
-
- /**
- * Map associating project resource with project objects.
- * <p/><b>All accesses must be inside a synchronized(mMap) block</b>, and do as a little as
- * possible and <b>not call out to other classes</b>.
- */
- private final Map<IProject, ProjectResources> mMap =
- new HashMap<IProject, ProjectResources>();
-
- /**
- * Interface to be notified of resource changes.
- *
- * @see ResourceManager#addListener(IResourceListener)
- * @see ResourceManager#removeListener(IResourceListener)
- */
- public interface IResourceListener {
- /**
- * Notification for resource file change.
- * @param project the project of the file.
- * @param file the {@link ResourceFile} representing the file.
- * @param eventType the type of event. See {@link IResourceDelta}.
- */
- void fileChanged(IProject project, ResourceFile file, int eventType);
- /**
- * Notification for resource folder change.
- * @param project the project of the file.
- * @param folder the {@link ResourceFolder} representing the folder.
- * @param eventType the type of event. See {@link IResourceDelta}.
- */
- void folderChanged(IProject project, ResourceFolder folder, int eventType);
- }
-
- private final ArrayList<IResourceListener> mListeners = new ArrayList<IResourceListener>();
-
- /**
- * Sets up the resource manager with the global project monitor.
- * @param monitor The global project monitor
- */
- public static void setup(GlobalProjectMonitor monitor) {
- monitor.addProjectListener(sThis.mProjectListener);
- monitor.addRawDeltaListener(sThis.mRawDeltaListener);
-
- CompiledResourcesMonitor.setupMonitor(monitor);
- }
-
- /**
- * Returns the singleton instance.
- */
- public static ResourceManager getInstance() {
- return sThis;
- }
-
- /**
- * Adds a new {@link IResourceListener} to be notified of resource changes.
- * @param listener the listener to be added.
- */
- public void addListener(IResourceListener listener) {
- synchronized (mListeners) {
- mListeners.add(listener);
- }
- }
-
- /**
- * Removes an {@link IResourceListener}, so that it's not notified of resource changes anymore.
- * @param listener the listener to be removed.
- */
- public void removeListener(IResourceListener listener) {
- synchronized (mListeners) {
- mListeners.remove(listener);
- }
- }
-
- /**
- * Returns the resources of a project.
- * @param project The project
- * @return a ProjectResources object
- */
- public ProjectResources getProjectResources(IProject project) {
- synchronized (mMap) {
- ProjectResources resources = mMap.get(project);
-
- if (resources == null) {
- resources = ProjectResources.create(project);
- mMap.put(project, resources);
- }
-
- return resources;
- }
- }
-
- /**
- * Update the resource repository with a delta
- *
- * @param delta the resource changed delta to process.
- * @param context a context object with state for the current update, such
- * as a place to stash errors encountered
- */
- public void processDelta(IResourceDelta delta, IdeScanningContext context) {
- doProcessDelta(delta, context);
-
- // when a project is added to the workspace it is possible this is called before the
- // repo is actually created so this will return null.
- ResourceRepository repo = context.getRepository();
- if (repo != null) {
- repo.postUpdateCleanUp();
- }
- }
-
- /**
- * Update the resource repository with a delta
- *
- * @param delta the resource changed delta to process.
- * @param context a context object with state for the current update, such
- * as a place to stash errors encountered
- */
- private void doProcessDelta(IResourceDelta delta, IdeScanningContext context) {
- // Skip over deltas that don't fit our mask
- int mask = IResourceDelta.ADDED | IResourceDelta.REMOVED | IResourceDelta.CHANGED;
- int kind = delta.getKind();
- if ( (mask & kind) == 0) {
- return;
- }
-
- // Process this delta first as we need to make sure new folders are created before
- // we process their content
- IResource r = delta.getResource();
- int type = r.getType();
-
- if (type == IResource.FILE) {
- context.startScanning(r);
- updateFile((IFile)r, delta.getMarkerDeltas(), kind, context);
- context.finishScanning(r);
- } else if (type == IResource.FOLDER) {
- updateFolder((IFolder)r, kind, context);
- } // We only care about files and folders.
- // Project deltas are handled by our project listener
-
- // Now, process children recursively
- IResourceDelta[] children = delta.getAffectedChildren();
- for (IResourceDelta child : children) {
- processDelta(child, context);
- }
- }
-
- /**
- * Update a resource folder that we know about
- * @param folder the folder that was updated
- * @param kind the delta type (added/removed/updated)
- */
- private void updateFolder(IFolder folder, int kind, IdeScanningContext context) {
- ProjectResources resources;
-
- final IProject project = folder.getProject();
-
- try {
- if (project.hasNature(AdtConstants.NATURE_DEFAULT) == false) {
- return;
- }
- } catch (CoreException e) {
- // can't get the project nature? return!
- return;
- }
-
- switch (kind) {
- case IResourceDelta.ADDED:
- // checks if the folder is under res.
- IPath path = folder.getFullPath();
-
- // the path will be project/res/<something>
- if (path.segmentCount() == 3) {
- if (isInResFolder(path)) {
- // get the project and its resource object.
- synchronized (mMap) {
- resources = mMap.get(project);
-
- // if it doesn't exist, we create it.
- if (resources == null) {
- resources = ProjectResources.create(project);
- mMap.put(project, resources);
- }
- }
-
- ResourceFolder newFolder = resources.processFolder(
- new IFolderWrapper(folder));
- if (newFolder != null) {
- notifyListenerOnFolderChange(project, newFolder, kind);
- }
- }
- }
- break;
- case IResourceDelta.CHANGED:
- // only call the listeners.
- synchronized (mMap) {
- resources = mMap.get(folder.getProject());
- }
- if (resources != null) {
- ResourceFolder resFolder = resources.getResourceFolder(folder);
- if (resFolder != null) {
- notifyListenerOnFolderChange(project, resFolder, kind);
- }
- }
- break;
- case IResourceDelta.REMOVED:
- synchronized (mMap) {
- resources = mMap.get(folder.getProject());
- }
- if (resources != null) {
- // lets get the folder type
- ResourceFolderType type = ResourceFolderType.getFolderType(
- folder.getName());
-
- context.startScanning(folder);
- ResourceFolder removedFolder = resources.removeFolder(type,
- new IFolderWrapper(folder), context);
- context.finishScanning(folder);
- if (removedFolder != null) {
- notifyListenerOnFolderChange(project, removedFolder, kind);
- }
- }
- break;
- }
- }
-
- /**
- * Called when a delta indicates that a file has changed. Depending on the
- * file being changed, and the type of change (ADDED, REMOVED, CHANGED), the
- * file change is processed to update the resource manager data.
- *
- * @param file The file that changed.
- * @param markerDeltas The marker deltas for the file.
- * @param kind The change kind. This is equivalent to
- * {@link IResourceDelta#accept(IResourceDeltaVisitor)}
- * @param context a context object with state for the current update, such
- * as a place to stash errors encountered
- */
- private void updateFile(IFile file, IMarkerDelta[] markerDeltas, int kind,
- ScanningContext context) {
- final IProject project = file.getProject();
-
- try {
- if (project.hasNature(AdtConstants.NATURE_DEFAULT) == false) {
- return;
- }
- } catch (CoreException e) {
- // can't get the project nature? return!
- return;
- }
-
- // get the project resources
- ProjectResources resources;
- synchronized (mMap) {
- resources = mMap.get(project);
- }
-
- if (resources == null) {
- return;
- }
-
- // checks if the file is under res/something or bin/res/something
- IPath path = file.getFullPath();
-
- if (path.segmentCount() == 4 || path.segmentCount() == 5) {
- if (isInResFolder(path)) {
- IContainer container = file.getParent();
- if (container instanceof IFolder) {
-
- ResourceFolder folder = resources.getResourceFolder(
- (IFolder)container);
-
- // folder can be null as when the whole folder is deleted, the
- // REMOVED event for the folder comes first. In this case, the
- // folder will have taken care of things.
- if (folder != null) {
- ResourceFile resFile = folder.processFile(
- new IFileWrapper(file),
- ResourceHelper.getResourceDeltaKind(kind), context);
- notifyListenerOnFileChange(project, resFile, kind);
- }
- }
- }
- }
- }
-
- /**
- * Implementation of the {@link IProjectListener} as an internal class so that the methods
- * do not appear in the public API of {@link ResourceManager}.
- */
- private final IProjectListener mProjectListener = new IProjectListener() {
- @Override
- public void projectClosed(IProject project) {
- synchronized (mMap) {
- mMap.remove(project);
- }
- }
-
- @Override
- public void projectDeleted(IProject project) {
- synchronized (mMap) {
- mMap.remove(project);
- }
- }
-
- @Override
- public void projectOpened(IProject project) {
- createProject(project);
- }
-
- @Override
- public void projectOpenedWithWorkspace(IProject project) {
- createProject(project);
- }
-
- @Override
- public void allProjectsOpenedWithWorkspace() {
- // nothing to do.
- }
-
- @Override
- public void projectRenamed(IProject project, IPath from) {
- // renamed project get a delete/open event too, so this can be ignored.
- }
- };
-
- /**
- * Implementation of {@link IRawDeltaListener} as an internal class so that the methods
- * do not appear in the public API of {@link ResourceManager}. Delta processing can be
- * accessed through the {@link ResourceManager#visitDelta(IResourceDelta delta)} method.
- */
- private final IRawDeltaListener mRawDeltaListener = new IRawDeltaListener() {
- @Override
- public void visitDelta(IResourceDelta workspaceDelta) {
- // If we're auto-building, then PreCompilerBuilder will pass us deltas and
- // they will be processed as part of the build.
- if (isAutoBuilding()) {
- return;
- }
-
- // When *not* auto building, we need to process the deltas immediately on save,
- // even if the user is not building yet, such that for example resource ids
- // are updated in the resource repositories so rendering etc. can work for
- // those new ids.
-
- IResourceDelta[] projectDeltas = workspaceDelta.getAffectedChildren();
- for (IResourceDelta delta : projectDeltas) {
- if (delta.getResource() instanceof IProject) {
- IProject project = (IProject) delta.getResource();
-
- try {
- if (project.hasNature(AdtConstants.NATURE_DEFAULT) == false) {
- continue;
- }
- } catch (CoreException e) {
- // only happens if the project is closed or doesn't exist.
- }
-
- IdeScanningContext context =
- new IdeScanningContext(getProjectResources(project), project, true);
-
- processDelta(delta, context);
-
- Collection<IProject> projects = context.getAaptRequestedProjects();
- if (projects != null) {
- for (IProject p : projects) {
- markAaptRequested(p);
- }
- }
- } else {
- AdtPlugin.log(IStatus.WARNING, "Unexpected delta type: %1$s",
- delta.getResource().toString());
- }
- }
- }
- };
-
- /**
- * Returns the {@link ResourceFolder} for the given file or <code>null</code> if none exists.
- */
- public ResourceFolder getResourceFolder(IFile file) {
- IContainer container = file.getParent();
- if (container.getType() == IResource.FOLDER) {
- IFolder parent = (IFolder)container;
- IProject project = file.getProject();
-
- ProjectResources resources = getProjectResources(project);
- if (resources != null) {
- return resources.getResourceFolder(parent);
- }
- }
-
- return null;
- }
-
- /**
- * Returns the {@link ResourceFolder} for the given folder or <code>null</code> if none exists.
- */
- public ResourceFolder getResourceFolder(IFolder folder) {
- IProject project = folder.getProject();
-
- ProjectResources resources = getProjectResources(project);
- if (resources != null) {
- return resources.getResourceFolder(folder);
- }
-
- return null;
- }
-
- /**
- * Loads and returns the resources for a given {@link IAndroidTarget}
- * @param androidTarget the target from which to load the framework resources
- */
- public ResourceRepository loadFrameworkResources(IAndroidTarget androidTarget) {
- String osResourcesPath = androidTarget.getPath(IAndroidTarget.RESOURCES);
-
- FolderWrapper frameworkRes = new FolderWrapper(osResourcesPath);
- if (frameworkRes.exists()) {
- FrameworkResources resources = new FrameworkResources(frameworkRes);
-
- resources.loadResources();
- resources.loadPublicResources(AdtPlugin.getDefault());
- return resources;
- }
-
- return null;
- }
-
- /**
- * Initial project parsing to gather resource info.
- * @param project
- */
- private void createProject(IProject project) {
- if (project.isOpen()) {
- synchronized (mMap) {
- ProjectResources projectResources = mMap.get(project);
- if (projectResources == null) {
- projectResources = ProjectResources.create(project);
- mMap.put(project, projectResources);
- }
- }
- }
- }
-
-
- /**
- * Returns true if the path is under /project/res/
- * @param path a workspace relative path
- * @return true if the path is under /project res/
- */
- private boolean isInResFolder(IPath path) {
- return SdkConstants.FD_RESOURCES.equalsIgnoreCase(path.segment(1));
- }
-
- private void notifyListenerOnFolderChange(IProject project, ResourceFolder folder,
- int eventType) {
- synchronized (mListeners) {
- for (IResourceListener listener : mListeners) {
- try {
- listener.folderChanged(project, folder, eventType);
- } catch (Throwable t) {
- AdtPlugin.log(t,
- "Failed to execute ResourceManager.IResouceListener.folderChanged()"); //$NON-NLS-1$
- }
- }
- }
- }
-
- private void notifyListenerOnFileChange(IProject project, ResourceFile file, int eventType) {
- synchronized (mListeners) {
- for (IResourceListener listener : mListeners) {
- try {
- listener.fileChanged(project, file, eventType);
- } catch (Throwable t) {
- AdtPlugin.log(t,
- "Failed to execute ResourceManager.IResouceListener.fileChanged()"); //$NON-NLS-1$
- }
- }
- }
- }
-
- /**
- * Private constructor to enforce singleton design.
- */
- private ResourceManager() {
- }
-
- // debug only
- @SuppressWarnings("unused")
- private String getKindString(int kind) {
- if (DEBUG) {
- switch (kind) {
- case IResourceDelta.ADDED: return "ADDED";
- case IResourceDelta.REMOVED: return "REMOVED";
- case IResourceDelta.CHANGED: return "CHANGED";
- }
- }
-
- return Integer.toString(kind);
- }
-
- /**
- * Returns true if the Project > Build Automatically option is turned on
- * (default).
- *
- * @return true if the Project > Build Automatically option is turned on
- * (default).
- */
- public static boolean isAutoBuilding() {
- return ResourcesPlugin.getWorkspace().getDescription().isAutoBuilding();
- }
-
- /** Qualified name for the per-project persistent property "needs aapt" */
- private final static QualifiedName NEED_AAPT = new QualifiedName(AdtPlugin.PLUGIN_ID,
- "aapt");//$NON-NLS-1$
-
- /**
- * Mark the given project, and any projects which depend on it as a library
- * project, as needing a full aapt build the next time the project is built.
- *
- * @param project the project to mark as needing aapt
- */
- public static void markAaptRequested(IProject project) {
- try {
- String needsAapt = Boolean.TRUE.toString();
- project.setPersistentProperty(NEED_AAPT, needsAapt);
-
- ProjectState state = Sdk.getProjectState(project);
- if (state.isLibrary()) {
- // For library projects also mark the dependent projects as needing full aapt
- for (ProjectState parent : state.getFullParentProjects()) {
- IProject parentProject = parent.getProject();
- // Mark the project, but only if it's open. Resource#setPersistentProperty
- // only works on open projects.
- if (parentProject.isOpen()) {
- parentProject.setPersistentProperty(NEED_AAPT, needsAapt);
- }
- }
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- }
-
- /**
- * Clear the "needs aapt" flag set by {@link #markAaptRequested(IProject)}.
- * This is usually called when a project is built. Note that this will only
- * clean the build flag on the given project, not on any downstream projects
- * that depend on this project as a library project.
- *
- * @param project the project to clear from the needs aapt list
- */
- public static void clearAaptRequest(IProject project) {
- try {
- project.setPersistentProperty(NEED_AAPT, null);
- // Note that even if this project is a library project, we -don't- clear
- // the aapt flags on the dependent projects since they may still depend
- // on other dirty projects. When they are built, they will issue their
- // own clear flag requests.
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- }
-
- /**
- * Returns whether the given project needs a full aapt build.
- *
- * @param project the project to check
- * @return true if the project needs a full aapt run
- */
- public static boolean isAaptRequested(IProject project) {
- try {
- String b = project.getPersistentProperty(NEED_AAPT);
- return b != null && Boolean.valueOf(b);
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
-
- return false;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/AdtConsoleSdkLog.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/AdtConsoleSdkLog.java
deleted file mode 100755
index 2396a4c46..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/AdtConsoleSdkLog.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.sdk;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.utils.ILogger;
-
-/**
- * An {@link ILogger} logger that outputs to the ADT console.
- */
-public class AdtConsoleSdkLog implements ILogger {
-
- private static final String TAG = "SDK Manager"; //$NON-NLS-1$
-
- @Override
- public void error(@Nullable Throwable t, @Nullable String errorFormat, Object... args) {
- if (t != null) {
- AdtPlugin.logAndPrintError(t, TAG, "Error: " + errorFormat, args);
- } else {
- AdtPlugin.printErrorToConsole(TAG, String.format(errorFormat, args));
- }
- }
-
- @Override
- public void info(@NonNull String msgFormat, Object... args) {
- String msg = String.format(msgFormat, args);
- for (String s : msg.split("\n")) {
- if (s.trim().length() > 0) {
- AdtPlugin.printToConsole(TAG, s);
- }
- }
- }
-
- @Override
- public void verbose(@NonNull String msgFormat, Object... args) {
- info(msgFormat, args);
- }
-
- @Override
- public void warning(@NonNull String warningFormat, Object... args) {
- AdtPlugin.printToConsole(TAG, String.format("Warning: " + warningFormat, args));
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/AdtManifestMergeCallback.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/AdtManifestMergeCallback.java
deleted file mode 100755
index dc539dcaa..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/AdtManifestMergeCallback.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.sdk;
-
-import com.android.annotations.NonNull;
-import com.android.manifmerger.ICallback;
-import com.android.manifmerger.ManifestMerger;
-import com.android.sdklib.AndroidTargetHash;
-import com.android.sdklib.AndroidVersion;
-import com.android.sdklib.IAndroidTarget;
-
-/**
- * A {@link ManifestMerger} {@link ICallback} that returns the
- * proper API level for known API codenames.
- */
-public class AdtManifestMergeCallback implements ICallback {
- @Override
- public int queryCodenameApiLevel(@NonNull String codename) {
- Sdk sdk = Sdk.getCurrent();
- if (sdk != null) {
- try {
- AndroidVersion version = new AndroidVersion(codename);
- String hashString = AndroidTargetHash.getPlatformHashString(version);
- IAndroidTarget t = sdk.getTargetFromHashString(hashString);
- if (t != null) {
- return t.getVersion().getApiLevel();
- }
- } catch (AndroidVersion.AndroidVersionException ignore) {}
- }
- return ICallback.UNKNOWN_CODENAME;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/AndroidJarLoader.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/AndroidJarLoader.java
deleted file mode 100644
index 754cedf79..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/AndroidJarLoader.java
+++ /dev/null
@@ -1,458 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.sdk;
-
-import com.android.SdkConstants;
-import com.google.common.io.Closeables;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubMonitor;
-
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.lang.reflect.Modifier;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.zip.ZipEntry;
-import java.util.zip.ZipInputStream;
-
-import javax.management.InvalidAttributeValueException;
-
-/**
- * Custom class loader able to load a class from the SDK jar file.
- */
-public class AndroidJarLoader extends ClassLoader implements IAndroidClassLoader {
-
- /**
- * Wrapper around a {@link Class} to provide the methods of
- * {@link IAndroidClassLoader.IClassDescriptor}.
- */
- public final static class ClassWrapper implements IClassDescriptor {
- private Class<?> mClass;
-
- public ClassWrapper(Class<?> clazz) {
- mClass = clazz;
- }
-
- @Override
- public String getFullClassName() {
- return mClass.getCanonicalName();
- }
-
- @Override
- public IClassDescriptor[] getDeclaredClasses() {
- Class<?>[] classes = mClass.getDeclaredClasses();
- IClassDescriptor[] iclasses = new IClassDescriptor[classes.length];
- for (int i = 0 ; i < classes.length ; i++) {
- iclasses[i] = new ClassWrapper(classes[i]);
- }
-
- return iclasses;
- }
-
- @Override
- public IClassDescriptor getEnclosingClass() {
- return new ClassWrapper(mClass.getEnclosingClass());
- }
-
- @Override
- public String getSimpleName() {
- return mClass.getSimpleName();
- }
-
- @Override
- public IClassDescriptor getSuperclass() {
- return new ClassWrapper(mClass.getSuperclass());
- }
-
- @Override
- public boolean equals(Object clazz) {
- if (clazz instanceof ClassWrapper) {
- return mClass.equals(((ClassWrapper)clazz).mClass);
- }
- return super.equals(clazz);
- }
-
- @Override
- public int hashCode() {
- return mClass.hashCode();
- }
-
-
- @Override
- public boolean isInstantiable() {
- int modifiers = mClass.getModifiers();
- return Modifier.isAbstract(modifiers) == false && Modifier.isPublic(modifiers) == true;
- }
-
- public Class<?> wrappedClass() {
- return mClass;
- }
-
- }
-
- private String mOsFrameworkLocation;
-
- /** A cache for binary data extracted from the zip */
- private final HashMap<String, byte[]> mEntryCache = new HashMap<String, byte[]>();
- /** A cache for already defined Classes */
- private final HashMap<String, Class<?> > mClassCache = new HashMap<String, Class<?> >();
-
- /**
- * Creates the class loader by providing the os path to the framework jar archive
- *
- * @param osFrameworkLocation OS Path of the framework JAR file
- */
- public AndroidJarLoader(String osFrameworkLocation) {
- super();
- mOsFrameworkLocation = osFrameworkLocation;
- }
-
- @Override
- public String getSource() {
- return mOsFrameworkLocation;
- }
-
- /**
- * Pre-loads all class binary data that belong to the given package by reading the archive
- * once and caching them internally.
- * <p/>
- * This does not actually preload "classes", it just reads the unzipped bytes for a given
- * class. To obtain a class, one must call {@link #findClass(String)} later.
- * <p/>
- * All classes which package name starts with "packageFilter" will be included and can be
- * found later.
- * <p/>
- * May throw some exceptions if the framework JAR cannot be read.
- *
- * @param packageFilter The package that contains all the class data to preload, using a fully
- * qualified binary name (.e.g "com.my.package."). The matching algorithm
- * is simple "startsWith". Use an empty string to include everything.
- * @param taskLabel An optional task name for the sub monitor. Can be null.
- * @param monitor A progress monitor. Can be null. Caller is responsible for calling done.
- * @throws IOException
- * @throws InvalidAttributeValueException
- * @throws ClassFormatError
- */
- public void preLoadClasses(String packageFilter, String taskLabel, IProgressMonitor monitor)
- throws IOException, InvalidAttributeValueException, ClassFormatError {
- // Transform the package name into a zip entry path
- String pathFilter = packageFilter.replaceAll("\\.", "/"); //$NON-NLS-1$ //$NON-NLS-2$
-
- SubMonitor progress = SubMonitor.convert(monitor, taskLabel == null ? "" : taskLabel, 100);
-
- // create streams to read the intermediary archive
- FileInputStream fis = new FileInputStream(mOsFrameworkLocation);
- ZipInputStream zis = new ZipInputStream(fis);
- ZipEntry entry;
- while ((entry = zis.getNextEntry()) != null) {
- // get the name of the entry.
- String entryPath = entry.getName();
-
- if (!entryPath.endsWith(SdkConstants.DOT_CLASS)) {
- // only accept class files
- continue;
- }
-
- // check if it is part of the package to preload
- if (pathFilter.length() > 0 && !entryPath.startsWith(pathFilter)) {
- continue;
- }
- String className = entryPathToClassName(entryPath);
-
- if (!mEntryCache.containsKey(className)) {
- long entrySize = entry.getSize();
- if (entrySize > Integer.MAX_VALUE) {
- throw new InvalidAttributeValueException();
- }
- byte[] data = readZipData(zis, (int)entrySize);
- mEntryCache.put(className, data);
- }
-
- // advance 5% of whatever is allocated on the progress bar
- progress.setWorkRemaining(100);
- progress.worked(5);
- progress.subTask(String.format("Preload %1$s", className));
- }
- }
-
- /**
- * Finds and loads all classes that derive from a given set of super classes.
- * <p/>
- * As a side-effect this will load and cache most, if not all, classes in the input JAR file.
- *
- * @param packageFilter Base name of package of classes to find.
- * Use an empty string to find everyting.
- * @param superClasses The super classes of all the classes to find.
- * @return An hash map which keys are the super classes looked for and which values are
- * ArrayList of the classes found. The array lists are always created for all the
- * valid keys, they are simply empty if no deriving class is found for a given
- * super class.
- * @throws IOException
- * @throws InvalidAttributeValueException
- * @throws ClassFormatError
- */
- @SuppressWarnings("resource") // Eclipse doesn't understand Closeables.closeQuietly
- @Override
- public HashMap<String, ArrayList<IClassDescriptor>> findClassesDerivingFrom(
- String packageFilter,
- String[] superClasses)
- throws IOException, InvalidAttributeValueException, ClassFormatError {
-
- packageFilter = packageFilter.replaceAll("\\.", "/"); //$NON-NLS-1$ //$NON-NLS-2$
-
- HashMap<String, ArrayList<IClassDescriptor>> mClassesFound =
- new HashMap<String, ArrayList<IClassDescriptor>>();
-
- for (String className : superClasses) {
- mClassesFound.put(className, new ArrayList<IClassDescriptor>());
- }
-
- // create streams to read the intermediary archive
- FileInputStream fis = new FileInputStream(mOsFrameworkLocation);
- ZipInputStream zis = new ZipInputStream(fis);
- try {
- ZipEntry entry;
- while ((entry = zis.getNextEntry()) != null) {
- // get the name of the entry and convert to a class binary name
- String entryPath = entry.getName();
- if (!entryPath.endsWith(SdkConstants.DOT_CLASS)) {
- // only accept class files
- continue;
- }
- if (packageFilter.length() > 0 && !entryPath.startsWith(packageFilter)) {
- // only accept stuff from the requested root package.
- continue;
- }
- String className = entryPathToClassName(entryPath);
-
- Class<?> loaded_class = mClassCache.get(className);
- if (loaded_class == null) {
- byte[] data = mEntryCache.get(className);
- if (data == null) {
- // Get the class and cache it
- long entrySize = entry.getSize();
- if (entrySize > Integer.MAX_VALUE) {
- throw new InvalidAttributeValueException();
- }
- data = readZipData(zis, (int)entrySize);
- }
- try {
- loaded_class = defineAndCacheClass(className, data);
- } catch (NoClassDefFoundError error) {
- if (error.getMessage().startsWith("java/")) {
- // Can't define these; we just need to stop
- // iteration here
- continue;
- }
- throw error;
- }
- }
-
- for (Class<?> superClass = loaded_class.getSuperclass();
- superClass != null;
- superClass = superClass.getSuperclass()) {
- String superName = superClass.getCanonicalName();
- if (mClassesFound.containsKey(superName)) {
- mClassesFound.get(superName).add(new ClassWrapper(loaded_class));
- break;
- }
- }
- }
- } finally {
- Closeables.closeQuietly(zis);
- }
-
- return mClassesFound;
- }
-
- /** Helper method that converts a Zip entry path into a corresponding
- * Java full qualified binary class name.
- * <p/>
- * F.ex, this converts "com/my/package/Foo.class" into "com.my.package.Foo".
- */
- private String entryPathToClassName(String entryPath) {
- return entryPath.replaceFirst("\\.class$", "").replaceAll("[/\\\\]", "."); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- }
-
- /**
- * Finds the class with the specified binary name.
- *
- * {@inheritDoc}
- */
- @Override
- protected Class<?> findClass(String name) throws ClassNotFoundException {
- try {
- // try to find the class in the cache
- Class<?> cached_class = mClassCache.get(name);
- if (cached_class == ClassNotFoundException.class) {
- // we already know we can't find this class, don't try again
- throw new ClassNotFoundException(name);
- } else if (cached_class != null) {
- return cached_class;
- }
-
- // if not found, look it up and cache it
- byte[] data = loadClassData(name);
- if (data != null) {
- return defineAndCacheClass(name, data);
- } else {
- // if the class can't be found, record a CNFE class in the map so
- // that we don't try to reload it next time
- mClassCache.put(name, ClassNotFoundException.class);
- throw new ClassNotFoundException(name);
- }
- } catch (ClassNotFoundException e) {
- throw e;
- } catch (Exception e) {
- throw new ClassNotFoundException(e.getMessage());
- }
- }
-
- /**
- * Defines a class based on its binary data and caches the resulting class object.
- *
- * @param name The binary name of the class (i.e. package.class1$class2)
- * @param data The binary data from the loader.
- * @return The class defined
- * @throws ClassFormatError if defineClass failed.
- */
- private Class<?> defineAndCacheClass(String name, byte[] data) throws ClassFormatError {
- Class<?> cached_class;
- cached_class = defineClass(null, data, 0, data.length);
-
- if (cached_class != null) {
- // Add new class to the cache class and remove it from the zip entry data cache
- mClassCache.put(name, cached_class);
- mEntryCache.remove(name);
- }
- return cached_class;
- }
-
- /**
- * Loads a class data from its binary name.
- * <p/>
- * This uses the class binary data that has been preloaded earlier by the preLoadClasses()
- * method if possible.
- *
- * @param className the binary name
- * @return an array of bytes representing the class data or null if not found
- * @throws InvalidAttributeValueException
- * @throws IOException
- */
- private synchronized byte[] loadClassData(String className)
- throws InvalidAttributeValueException, IOException {
-
- byte[] data = mEntryCache.get(className);
- if (data != null) {
- return data;
- }
-
- // The name is a binary name. Something like "android.R", or "android.R$id".
- // Make a path out of it.
- String entryName = className.replaceAll("\\.", "/") + SdkConstants.DOT_CLASS; //$NON-NLS-1$ //$NON-NLS-2$
-
- // create streams to read the intermediary archive
- FileInputStream fis = new FileInputStream(mOsFrameworkLocation);
- ZipInputStream zis = new ZipInputStream(fis);
- try {
- // loop on the entries of the intermediary package and put them in the final package.
- ZipEntry entry;
-
- while ((entry = zis.getNextEntry()) != null) {
- // get the name of the entry.
- String currEntryName = entry.getName();
-
- if (currEntryName.equals(entryName)) {
- long entrySize = entry.getSize();
- if (entrySize > Integer.MAX_VALUE) {
- throw new InvalidAttributeValueException();
- }
-
- data = readZipData(zis, (int)entrySize);
- return data;
- }
- }
-
- return null;
- } finally {
- zis.close();
- }
- }
-
- /**
- * Reads data for the <em>current</em> entry from the zip input stream.
- *
- * @param zis The Zip input stream
- * @param entrySize The entry size. -1 if unknown.
- * @return The new data for the <em>current</em> entry.
- * @throws IOException If ZipInputStream.read() fails.
- */
- private byte[] readZipData(ZipInputStream zis, int entrySize) throws IOException {
- int block_size = 1024;
- int data_size = entrySize < 1 ? block_size : entrySize;
- int offset = 0;
- byte[] data = new byte[data_size];
-
- while(zis.available() != 0) {
- int count = zis.read(data, offset, data_size - offset);
- if (count < 0) { // read data is done
- break;
- }
- offset += count;
-
- if (entrySize >= 1 && offset >= entrySize) { // we know the size and we're done
- break;
- }
-
- // if we don't know the entry size and we're not done reading,
- // expand the data buffer some more.
- if (offset >= data_size) {
- byte[] temp = new byte[data_size + block_size];
- System.arraycopy(data, 0, temp, 0, data_size);
- data_size += block_size;
- data = temp;
- block_size *= 2;
- }
- }
-
- if (offset < data_size) {
- // buffer was allocated too large, trim it
- byte[] temp = new byte[offset];
- if (offset > 0) {
- System.arraycopy(data, 0, temp, 0, offset);
- }
- data = temp;
- }
-
- return data;
- }
-
- /**
- * Returns a {@link IAndroidClassLoader.IClassDescriptor} by its fully-qualified name.
- * @param className the fully-qualified name of the class to return.
- * @throws ClassNotFoundException
- */
- @Override
- public IClassDescriptor getClass(String className) throws ClassNotFoundException {
- try {
- return new ClassWrapper(loadClass(className));
- } catch (ClassNotFoundException e) {
- throw e; // useful for debugging
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/AndroidTargetData.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/AndroidTargetData.java
deleted file mode 100644
index 85ae9fdc0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/AndroidTargetData.java
+++ /dev/null
@@ -1,417 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.sdk;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.rendering.LayoutLibrary;
-import com.android.ide.common.rendering.api.LayoutLog;
-import com.android.ide.common.resources.ResourceRepository;
-import com.android.ide.common.resources.platform.AttributeInfo;
-import com.android.ide.common.sdk.LoadStatus;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.animator.AnimDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.animator.AnimatorDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.color.ColorDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.IDescriptorProvider;
-import com.android.ide.eclipse.adt.internal.editors.drawable.DrawableDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.LayoutDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.manifest.descriptors.AndroidManifestDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.menu.descriptors.MenuDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.otherxml.descriptors.OtherXmlDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.values.descriptors.ValuesDescriptors;
-import com.android.ide.eclipse.adt.internal.resources.manager.ProjectResources;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.IAndroidTarget.IOptionalLibrary;
-
-import org.eclipse.core.runtime.IStatus;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Hashtable;
-import java.util.Map;
-
-/**
- * This class contains the data of an Android Target as loaded from the SDK.
- */
-public class AndroidTargetData {
-
- public final static int DESCRIPTOR_MANIFEST = 1;
- public final static int DESCRIPTOR_LAYOUT = 2;
- public final static int DESCRIPTOR_MENU = 3;
- public final static int DESCRIPTOR_OTHER_XML = 4;
- public final static int DESCRIPTOR_RESOURCES = 5;
- public final static int DESCRIPTOR_SEARCHABLE = 6;
- public final static int DESCRIPTOR_PREFERENCES = 7;
- public final static int DESCRIPTOR_APPWIDGET_PROVIDER = 8;
- public final static int DESCRIPTOR_DRAWABLE = 9;
- public final static int DESCRIPTOR_ANIMATOR = 10;
- public final static int DESCRIPTOR_ANIM = 11;
- public final static int DESCRIPTOR_COLOR = 12;
-
- private final IAndroidTarget mTarget;
-
- /**
- * mAttributeValues is a map { key => list [ values ] }.
- * The key for the map is "(element-xml-name,attribute-namespace:attribute-xml-local-name)".
- * The attribute namespace prefix must be:
- * - "android" for SdkConstants.NS_RESOURCES
- * - "xmlns" for the XMLNS URI.
- *
- * This is used for attributes that do not have a unique name, but still need to be populated
- * with values in the UI. Uniquely named attributes have their values in {@link #mEnumValueMap}.
- */
- private Hashtable<String, String[]> mAttributeValues = new Hashtable<String, String[]>();
-
- private AndroidManifestDescriptors mManifestDescriptors;
- private DrawableDescriptors mDrawableDescriptors;
- private AnimatorDescriptors mAnimatorDescriptors;
- private AnimDescriptors mAnimDescriptors;
- private ColorDescriptors mColorDescriptors;
- private LayoutDescriptors mLayoutDescriptors;
- private MenuDescriptors mMenuDescriptors;
- private OtherXmlDescriptors mOtherXmlDescriptors;
-
- private Map<String, Map<String, Integer>> mEnumValueMap;
-
- private ResourceRepository mFrameworkResources;
- private LayoutLibrary mLayoutLibrary;
- private Map<String, AttributeInfo> mAttributeMap;
-
- private boolean mLayoutBridgeInit = false;
-
- AndroidTargetData(IAndroidTarget androidTarget) {
- mTarget = androidTarget;
- }
-
- /**
- * Sets the associated map from string attribute name to
- * {@link AttributeInfo}
- *
- * @param attributeMap the map
- */
- public void setAttributeMap(@NonNull Map<String, AttributeInfo> attributeMap) {
- mAttributeMap = attributeMap;
- }
-
- /**
- * Returns the associated map from string attribute name to
- * {@link AttributeInfo}
- *
- * @return the map
- */
- @Nullable
- public Map<String, AttributeInfo> getAttributeMap() {
- return mAttributeMap;
- }
-
- /**
- * Creates an AndroidTargetData object.
- */
- void setExtraData(
- AndroidManifestDescriptors manifestDescriptors,
- LayoutDescriptors layoutDescriptors,
- MenuDescriptors menuDescriptors,
- OtherXmlDescriptors otherXmlDescriptors,
- DrawableDescriptors drawableDescriptors,
- AnimatorDescriptors animatorDescriptors,
- AnimDescriptors animDescriptors,
- ColorDescriptors colorDescriptors,
- Map<String, Map<String, Integer>> enumValueMap,
- String[] permissionValues,
- String[] activityIntentActionValues,
- String[] broadcastIntentActionValues,
- String[] serviceIntentActionValues,
- String[] intentCategoryValues,
- String[] platformLibraries,
- IOptionalLibrary[] optionalLibraries,
- ResourceRepository frameworkResources,
- LayoutLibrary layoutLibrary) {
-
- mManifestDescriptors = manifestDescriptors;
- mDrawableDescriptors = drawableDescriptors;
- mAnimatorDescriptors = animatorDescriptors;
- mAnimDescriptors = animDescriptors;
- mColorDescriptors = colorDescriptors;
- mLayoutDescriptors = layoutDescriptors;
- mMenuDescriptors = menuDescriptors;
- mOtherXmlDescriptors = otherXmlDescriptors;
- mEnumValueMap = enumValueMap;
- mFrameworkResources = frameworkResources;
- mLayoutLibrary = layoutLibrary;
-
- setPermissions(permissionValues);
- setIntentFilterActionsAndCategories(activityIntentActionValues, broadcastIntentActionValues,
- serviceIntentActionValues, intentCategoryValues);
- setOptionalLibraries(platformLibraries, optionalLibraries);
- }
-
- /**
- * Returns an {@link IDescriptorProvider} from a given Id.
- * The Id can be one of {@link #DESCRIPTOR_MANIFEST}, {@link #DESCRIPTOR_LAYOUT},
- * {@link #DESCRIPTOR_MENU}, or {@link #DESCRIPTOR_OTHER_XML}.
- * All other values will throw an {@link IllegalArgumentException}.
- */
- public IDescriptorProvider getDescriptorProvider(int descriptorId) {
- switch (descriptorId) {
- case DESCRIPTOR_MANIFEST:
- return mManifestDescriptors;
- case DESCRIPTOR_LAYOUT:
- return mLayoutDescriptors;
- case DESCRIPTOR_MENU:
- return mMenuDescriptors;
- case DESCRIPTOR_OTHER_XML:
- return mOtherXmlDescriptors;
- case DESCRIPTOR_RESOURCES:
- // FIXME: since it's hard-coded the Resources Descriptors are not platform dependent.
- return ValuesDescriptors.getInstance();
- case DESCRIPTOR_PREFERENCES:
- return mOtherXmlDescriptors.getPreferencesProvider();
- case DESCRIPTOR_APPWIDGET_PROVIDER:
- return mOtherXmlDescriptors.getAppWidgetProvider();
- case DESCRIPTOR_SEARCHABLE:
- return mOtherXmlDescriptors.getSearchableProvider();
- case DESCRIPTOR_DRAWABLE:
- return mDrawableDescriptors;
- case DESCRIPTOR_ANIMATOR:
- return mAnimatorDescriptors;
- case DESCRIPTOR_ANIM:
- return mAnimDescriptors;
- case DESCRIPTOR_COLOR:
- return mColorDescriptors;
- default :
- throw new IllegalArgumentException();
- }
- }
-
- /**
- * Returns the manifest descriptors.
- */
- public AndroidManifestDescriptors getManifestDescriptors() {
- return mManifestDescriptors;
- }
-
- /**
- * Returns the drawable descriptors
- */
- public DrawableDescriptors getDrawableDescriptors() {
- return mDrawableDescriptors;
- }
-
- /**
- * Returns the animation descriptors
- */
- public AnimDescriptors getAnimDescriptors() {
- return mAnimDescriptors;
- }
-
- /**
- * Returns the color descriptors
- */
- public ColorDescriptors getColorDescriptors() {
- return mColorDescriptors;
- }
-
- /**
- * Returns the animator descriptors
- */
- public AnimatorDescriptors getAnimatorDescriptors() {
- return mAnimatorDescriptors;
- }
-
- /**
- * Returns the layout Descriptors.
- */
- public LayoutDescriptors getLayoutDescriptors() {
- return mLayoutDescriptors;
- }
-
- /**
- * Returns the menu descriptors.
- */
- public MenuDescriptors getMenuDescriptors() {
- return mMenuDescriptors;
- }
-
- /**
- * Returns the XML descriptors
- */
- public OtherXmlDescriptors getXmlDescriptors() {
- return mOtherXmlDescriptors;
- }
-
- /**
- * Returns this list of possible values for an XML attribute.
- * <p/>This should only be called for attributes for which possible values depend on the
- * parent element node.
- * <p/>For attributes that have the same values no matter the parent node, use
- * {@link #getEnumValueMap()}.
- * @param elementName the name of the element containing the attribute.
- * @param attributeName the name of the attribute
- * @return an array of String with the possible values, or <code>null</code> if no values were
- * found.
- */
- public String[] getAttributeValues(String elementName, String attributeName) {
- String key = String.format("(%1$s,%2$s)", elementName, attributeName); //$NON-NLS-1$
- return mAttributeValues.get(key);
- }
-
- /**
- * Returns this list of possible values for an XML attribute.
- * <p/>This should only be called for attributes for which possible values depend on the
- * parent and great-grand-parent element node.
- * <p/>The typical example of this is for the 'name' attribute under
- * activity/intent-filter/action
- * <p/>For attributes that have the same values no matter the parent node, use
- * {@link #getEnumValueMap()}.
- * @param elementName the name of the element containing the attribute.
- * @param attributeName the name of the attribute
- * @param greatGrandParentElementName the great-grand-parent node.
- * @return an array of String with the possible values, or <code>null</code> if no values were
- * found.
- */
- public String[] getAttributeValues(String elementName, String attributeName,
- String greatGrandParentElementName) {
- if (greatGrandParentElementName != null) {
- String key = String.format("(%1$s,%2$s,%3$s)", //$NON-NLS-1$
- greatGrandParentElementName, elementName, attributeName);
- String[] values = mAttributeValues.get(key);
- if (values != null) {
- return values;
- }
- }
-
- return getAttributeValues(elementName, attributeName);
- }
-
- /**
- * Returns the enum values map.
- * <p/>The map defines the possible values for XML attributes. The key is the attribute name
- * and the value is a map of (string, integer) in which the key (string) is the name of
- * the value, and the Integer is the numerical value in the compiled binary XML files.
- */
- public Map<String, Map<String, Integer>> getEnumValueMap() {
- return mEnumValueMap;
- }
-
- /**
- * Returns the {@link ProjectResources} containing the Framework Resources.
- */
- public ResourceRepository getFrameworkResources() {
- return mFrameworkResources;
- }
-
- /**
- * Returns a {@link LayoutLibrary} object possibly containing a {@link LayoutBridge} object.
- * <p/>If {@link LayoutLibrary#getBridge()} is <code>null</code>,
- * {@link LayoutBridge#getStatus()} will contain the reason (either {@link LoadStatus#LOADING}
- * or {@link LoadStatus#FAILED}).
- * <p/>Valid {@link LayoutBridge} objects are always initialized before being returned.
- */
- public synchronized LayoutLibrary getLayoutLibrary() {
- if (mLayoutBridgeInit == false && mLayoutLibrary.getStatus() == LoadStatus.LOADED) {
- boolean ok = mLayoutLibrary.init(
- mTarget.getProperties(),
- new File(mTarget.getPath(IAndroidTarget.FONTS)),
- getEnumValueMap(),
- new LayoutLog() {
-
- @Override
- public void error(String tag, String message, Throwable throwable,
- Object data) {
- AdtPlugin.log(throwable, message);
- }
-
- @Override
- public void error(String tag, String message, Object data) {
- AdtPlugin.log(IStatus.ERROR, message);
- }
-
- @Override
- public void warning(String tag, String message, Object data) {
- AdtPlugin.log(IStatus.WARNING, message);
- }
- });
- if (!ok) {
- AdtPlugin.log(IStatus.ERROR,
- "LayoutLibrary initialization failed");
- }
- mLayoutBridgeInit = true;
- }
-
- return mLayoutLibrary;
- }
-
- /**
- * Sets the permission values
- * @param permissionValues the list of permissions
- */
- private void setPermissions(String[] permissionValues) {
- setValues("(uses-permission,android:name)", permissionValues); //$NON-NLS-1$
- setValues("(application,android:permission)", permissionValues); //$NON-NLS-1$
- setValues("(activity,android:permission)", permissionValues); //$NON-NLS-1$
- setValues("(receiver,android:permission)", permissionValues); //$NON-NLS-1$
- setValues("(service,android:permission)", permissionValues); //$NON-NLS-1$
- setValues("(provider,android:permission)", permissionValues); //$NON-NLS-1$
- }
-
- private void setIntentFilterActionsAndCategories(String[] activityIntentActions,
- String[] broadcastIntentActions, String[] serviceIntentActions,
- String[] intentCategoryValues) {
- setValues("(activity,action,android:name)", activityIntentActions); //$NON-NLS-1$
- setValues("(receiver,action,android:name)", broadcastIntentActions); //$NON-NLS-1$
- setValues("(service,action,android:name)", serviceIntentActions); //$NON-NLS-1$
- setValues("(category,android:name)", intentCategoryValues); //$NON-NLS-1$
- }
-
- private void setOptionalLibraries(String[] platformLibraries,
- IOptionalLibrary[] optionalLibraries) {
-
- ArrayList<String> libs = new ArrayList<String>();
-
- if (platformLibraries != null) {
- for (String name : platformLibraries) {
- libs.add(name);
- }
- }
-
- if (optionalLibraries != null) {
- for (int i = 0; i < optionalLibraries.length; i++) {
- libs.add(optionalLibraries[i].getName());
- }
- }
- setValues("(uses-library,android:name)", libs.toArray(new String[libs.size()]));
- }
-
- /**
- * Sets a (name, values) pair in the hash map.
- * <p/>
- * If the name is already present in the map, it is first removed.
- * @param name the name associated with the values.
- * @param values The values to add.
- */
- private void setValues(String name, String[] values) {
- mAttributeValues.remove(name);
- mAttributeValues.put(name, values);
- }
-
- public void dispose() {
- if (mLayoutLibrary != null) {
- mLayoutLibrary.dispose();
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/AndroidTargetParser.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/AndroidTargetParser.java
deleted file mode 100644
index 9a1fd3dc9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/AndroidTargetParser.java
+++ /dev/null
@@ -1,605 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.sdk;
-
-import com.android.SdkConstants;
-import com.android.ide.common.rendering.LayoutLibrary;
-import com.android.ide.common.resources.ResourceRepository;
-import com.android.ide.common.resources.platform.AttrsXmlParser;
-import com.android.ide.common.resources.platform.DeclareStyleableInfo;
-import com.android.ide.common.resources.platform.ViewClassInfo;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.animator.AnimDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.animator.AnimatorDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.color.ColorDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.drawable.DrawableDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.LayoutDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.manifest.descriptors.AndroidManifestDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.menu.descriptors.MenuDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.otherxml.descriptors.OtherXmlDescriptors;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.sdklib.IAndroidTarget;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubMonitor;
-
-import java.io.BufferedReader;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.management.InvalidAttributeValueException;
-
-/**
- * Parser for the platform data in an SDK.
- * <p/>
- * This gather the following information:
- * <ul>
- * <li>Resource ID from <code>android.R</code></li>
- * <li>The list of permissions values from <code>android.Manifest$permission</code></li>
- * <li></li>
- * </ul>
- */
-public final class AndroidTargetParser {
-
- private static final String TAG = "Framework Resource Parser";
- private final IAndroidTarget mAndroidTarget;
-
- /**
- * Creates a platform data parser.
- */
- public AndroidTargetParser(IAndroidTarget platformTarget) {
- mAndroidTarget = platformTarget;
- }
-
- /**
- * Parses the framework, collects all interesting information and stores them in the
- * {@link IAndroidTarget} given to the constructor.
- *
- * @param monitor A progress monitor. Can be null. Caller is responsible for calling done.
- * @return True if the SDK path was valid and parsing has been attempted.
- */
- public IStatus run(IProgressMonitor monitor) {
- try {
- SubMonitor progress = SubMonitor.convert(monitor,
- String.format("Parsing SDK %1$s", mAndroidTarget.getName()),
- 16);
-
- AndroidTargetData targetData = new AndroidTargetData(mAndroidTarget);
-
- // parse the rest of the data.
-
- AndroidJarLoader classLoader =
- new AndroidJarLoader(mAndroidTarget.getPath(IAndroidTarget.ANDROID_JAR));
-
- preload(classLoader, progress.newChild(40, SubMonitor.SUPPRESS_NONE));
-
- if (progress.isCanceled()) {
- return Status.CANCEL_STATUS;
- }
-
- // get the permissions
- progress.subTask("Permissions");
- String[] permissionValues = collectPermissions(classLoader);
- progress.worked(1);
-
- if (progress.isCanceled()) {
- return Status.CANCEL_STATUS;
- }
-
- // get the action and category values for the Intents.
- progress.subTask("Intents");
- ArrayList<String> activity_actions = new ArrayList<String>();
- ArrayList<String> broadcast_actions = new ArrayList<String>();
- ArrayList<String> service_actions = new ArrayList<String>();
- ArrayList<String> categories = new ArrayList<String>();
- collectIntentFilterActionsAndCategories(activity_actions, broadcast_actions,
- service_actions, categories);
- progress.worked(1);
-
- if (progress.isCanceled()) {
- return Status.CANCEL_STATUS;
- }
-
- // gather the attribute definition
- progress.subTask("Attributes definitions");
- AttrsXmlParser attrsXmlParser = new AttrsXmlParser(
- mAndroidTarget.getPath(IAndroidTarget.ATTRIBUTES),
- AdtPlugin.getDefault(),
- 1000);
- attrsXmlParser.preload();
-
- progress.worked(1);
-
- progress.subTask("Manifest definitions");
- AttrsXmlParser attrsManifestXmlParser = new AttrsXmlParser(
- mAndroidTarget.getPath(IAndroidTarget.MANIFEST_ATTRIBUTES),
- attrsXmlParser,
- AdtPlugin.getDefault(), 1100);
- attrsManifestXmlParser.preload();
- progress.worked(1);
-
- Collection<ViewClassInfo> mainList = new ArrayList<ViewClassInfo>();
- Collection<ViewClassInfo> groupList = new ArrayList<ViewClassInfo>();
-
- // collect the layout/widgets classes
- progress.subTask("Widgets and layouts");
- collectLayoutClasses(classLoader, attrsXmlParser, mainList, groupList,
- progress.newChild(1));
-
- if (progress.isCanceled()) {
- return Status.CANCEL_STATUS;
- }
-
- ViewClassInfo[] layoutViewsInfo = mainList.toArray(
- new ViewClassInfo[mainList.size()]);
- ViewClassInfo[] layoutGroupsInfo = groupList.toArray(
- new ViewClassInfo[groupList.size()]);
- mainList.clear();
- groupList.clear();
-
- // collect the preferences classes.
- collectPreferenceClasses(classLoader, attrsXmlParser, mainList, groupList,
- progress.newChild(1));
-
- if (progress.isCanceled()) {
- return Status.CANCEL_STATUS;
- }
-
- ViewClassInfo[] preferencesInfo = mainList.toArray(new ViewClassInfo[mainList.size()]);
- ViewClassInfo[] preferenceGroupsInfo = groupList.toArray(
- new ViewClassInfo[groupList.size()]);
-
- Map<String, DeclareStyleableInfo> xmlMenuMap = collectMenuDefinitions(attrsXmlParser);
- Map<String, DeclareStyleableInfo> xmlSearchableMap = collectSearchableDefinitions(
- attrsXmlParser);
- Map<String, DeclareStyleableInfo> manifestMap = collectManifestDefinitions(
- attrsManifestXmlParser);
- Map<String, Map<String, Integer>> enumValueMap = attrsXmlParser.getEnumFlagValues();
-
- Map<String, DeclareStyleableInfo> xmlAppWidgetMap = null;
- if (mAndroidTarget.getVersion().getApiLevel() >= 3) {
- xmlAppWidgetMap = collectAppWidgetDefinitions(attrsXmlParser);
- }
-
- if (progress.isCanceled()) {
- return Status.CANCEL_STATUS;
- }
-
- // From the information that was collected, create the pieces that will be put in
- // the PlatformData object.
- AndroidManifestDescriptors manifestDescriptors = new AndroidManifestDescriptors();
- manifestDescriptors.updateDescriptors(manifestMap);
- progress.worked(1);
-
- if (progress.isCanceled()) {
- return Status.CANCEL_STATUS;
- }
-
- LayoutDescriptors layoutDescriptors = new LayoutDescriptors();
- layoutDescriptors.updateDescriptors(layoutViewsInfo, layoutGroupsInfo,
- attrsXmlParser.getDeclareStyleableList(), mAndroidTarget);
- progress.worked(1);
-
- if (progress.isCanceled()) {
- return Status.CANCEL_STATUS;
- }
-
- MenuDescriptors menuDescriptors = new MenuDescriptors();
- menuDescriptors.updateDescriptors(xmlMenuMap);
- progress.worked(1);
-
- if (progress.isCanceled()) {
- return Status.CANCEL_STATUS;
- }
-
- OtherXmlDescriptors otherXmlDescriptors = new OtherXmlDescriptors();
- otherXmlDescriptors.updateDescriptors(
- xmlSearchableMap,
- xmlAppWidgetMap,
- preferencesInfo,
- preferenceGroupsInfo);
- progress.worked(1);
-
- if (progress.isCanceled()) {
- return Status.CANCEL_STATUS;
- }
-
- DrawableDescriptors drawableDescriptors = new DrawableDescriptors();
- Map<String, DeclareStyleableInfo> map = attrsXmlParser.getDeclareStyleableList();
- drawableDescriptors.updateDescriptors(map);
- progress.worked(1);
-
- if (progress.isCanceled()) {
- return Status.CANCEL_STATUS;
- }
-
- AnimatorDescriptors animatorDescriptors = new AnimatorDescriptors();
- animatorDescriptors.updateDescriptors(map);
- progress.worked(1);
-
- if (progress.isCanceled()) {
- return Status.CANCEL_STATUS;
- }
-
- AnimDescriptors animDescriptors = new AnimDescriptors();
- animDescriptors.updateDescriptors(map);
- progress.worked(1);
-
- if (progress.isCanceled()) {
- return Status.CANCEL_STATUS;
- }
-
- ColorDescriptors colorDescriptors = new ColorDescriptors();
- colorDescriptors.updateDescriptors(map);
- progress.worked(1);
-
- // load the framework resources.
- ResourceRepository frameworkResources =
- ResourceManager.getInstance().loadFrameworkResources(mAndroidTarget);
- progress.worked(1);
-
- // now load the layout lib bridge
- LayoutLibrary layoutBridge = LayoutLibrary.load(
- mAndroidTarget.getPath(IAndroidTarget.LAYOUT_LIB),
- AdtPlugin.getDefault(),
- "ADT plug-in");
-
- progress.worked(1);
-
- // and finally create the PlatformData with all that we loaded.
- targetData.setExtraData(
- manifestDescriptors,
- layoutDescriptors,
- menuDescriptors,
- otherXmlDescriptors,
- drawableDescriptors,
- animatorDescriptors,
- animDescriptors,
- colorDescriptors,
- enumValueMap,
- permissionValues,
- activity_actions.toArray(new String[activity_actions.size()]),
- broadcast_actions.toArray(new String[broadcast_actions.size()]),
- service_actions.toArray(new String[service_actions.size()]),
- categories.toArray(new String[categories.size()]),
- mAndroidTarget.getPlatformLibraries(),
- mAndroidTarget.getOptionalLibraries(),
- frameworkResources,
- layoutBridge);
-
- targetData.setAttributeMap(attrsXmlParser.getAttributeMap());
-
- Sdk.getCurrent().setTargetData(mAndroidTarget, targetData);
-
- return Status.OK_STATUS;
- } catch (Exception e) {
- AdtPlugin.logAndPrintError(e, TAG, "SDK parser failed"); //$NON-NLS-1$
- AdtPlugin.printToConsole("SDK parser failed", e.getMessage());
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, "SDK parser failed", e);
- }
- }
-
- /**
- * Preloads all "interesting" classes from the framework SDK jar.
- * <p/>
- * Currently this preloads all classes from the framework jar
- *
- * @param classLoader The framework SDK jar classloader
- * @param monitor A progress monitor. Can be null. Caller is responsible for calling done.
- */
- private void preload(AndroidJarLoader classLoader, IProgressMonitor monitor) {
- try {
- classLoader.preLoadClasses("" /* all classes */, //$NON-NLS-1$
- mAndroidTarget.getName(), // monitor task label
- monitor);
- } catch (InvalidAttributeValueException e) {
- AdtPlugin.log(e, "Problem preloading classes"); //$NON-NLS-1$
- } catch (IOException e) {
- AdtPlugin.log(e, "Problem preloading classes"); //$NON-NLS-1$
- }
- }
-
- /**
- * Loads, collects and returns the list of default permissions from the framework.
- *
- * @param classLoader The framework SDK jar classloader
- * @return a non null (but possibly empty) array containing the permission values.
- */
- private String[] collectPermissions(AndroidJarLoader classLoader) {
- try {
- Class<?> permissionClass =
- classLoader.loadClass(SdkConstants.CLASS_MANIFEST_PERMISSION);
-
- if (permissionClass != null) {
- ArrayList<String> list = new ArrayList<String>();
-
- Field[] fields = permissionClass.getFields();
-
- for (Field f : fields) {
- int modifiers = f.getModifiers();
- if (Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers) &&
- Modifier.isPublic(modifiers)) {
- try {
- Object value = f.get(null);
- if (value instanceof String) {
- list.add((String)value);
- }
- } catch (IllegalArgumentException e) {
- // since we provide null this should not happen
- } catch (IllegalAccessException e) {
- // if the field is inaccessible we ignore it.
- } catch (NullPointerException npe) {
- // looks like this is not a static field. we can ignore.
- } catch (ExceptionInInitializerError eiie) {
- // lets just ignore the field again
- }
- }
- }
-
- return list.toArray(new String[list.size()]);
- }
- } catch (ClassNotFoundException e) {
- AdtPlugin.logAndPrintError(e, TAG,
- "Collect permissions failed, class %1$s not found in %2$s", //$NON-NLS-1$
- SdkConstants.CLASS_MANIFEST_PERMISSION,
- mAndroidTarget.getPath(IAndroidTarget.ANDROID_JAR));
- }
-
- return new String[0];
- }
-
- /**
- * Loads and collects the action and category default values from the framework.
- * The values are added to the <code>actions</code> and <code>categories</code> lists.
- *
- * @param activityActions the list which will receive the activity action values.
- * @param broadcastActions the list which will receive the broadcast action values.
- * @param serviceActions the list which will receive the service action values.
- * @param categories the list which will receive the category values.
- */
- private void collectIntentFilterActionsAndCategories(ArrayList<String> activityActions,
- ArrayList<String> broadcastActions,
- ArrayList<String> serviceActions, ArrayList<String> categories) {
- collectValues(mAndroidTarget.getPath(IAndroidTarget.ACTIONS_ACTIVITY),
- activityActions);
- collectValues(mAndroidTarget.getPath(IAndroidTarget.ACTIONS_BROADCAST),
- broadcastActions);
- collectValues(mAndroidTarget.getPath(IAndroidTarget.ACTIONS_SERVICE),
- serviceActions);
- collectValues(mAndroidTarget.getPath(IAndroidTarget.CATEGORIES),
- categories);
- }
-
- /**
- * Collects values from a text file located in the SDK
- * @param osFilePath The path to the text file.
- * @param values the {@link ArrayList} to fill with the values.
- */
- private void collectValues(String osFilePath, ArrayList<String> values) {
- FileReader fr = null;
- BufferedReader reader = null;
- try {
- fr = new FileReader(osFilePath);
- reader = new BufferedReader(fr);
-
- String line;
- while ((line = reader.readLine()) != null) {
- line = line.trim();
- if (line.length() > 0 && line.startsWith("#") == false) { //$NON-NLS-1$
- values.add(line);
- }
- }
- } catch (IOException e) {
- AdtPlugin.log(e, "Failed to read SDK values"); //$NON-NLS-1$
- } finally {
- try {
- if (reader != null) {
- reader.close();
- }
- } catch (IOException e) {
- AdtPlugin.log(e, "Failed to read SDK values"); //$NON-NLS-1$
- }
-
- try {
- if (fr != null) {
- fr.close();
- }
- } catch (IOException e) {
- AdtPlugin.log(e, "Failed to read SDK values"); //$NON-NLS-1$
- }
- }
- }
-
- /**
- * Collects all layout classes information from the class loader and the
- * attrs.xml and sets the corresponding structures in the resource manager.
- *
- * @param classLoader The framework SDK jar classloader in case we cannot get the widget from
- * the platform directly
- * @param attrsXmlParser The parser of the attrs.xml file
- * @param mainList the Collection to receive the main list of {@link ViewClassInfo}.
- * @param groupList the Collection to receive the group list of {@link ViewClassInfo}.
- * @param monitor A progress monitor. Can be null. Caller is responsible for calling done.
- */
- private void collectLayoutClasses(AndroidJarLoader classLoader,
- AttrsXmlParser attrsXmlParser,
- Collection<ViewClassInfo> mainList,
- Collection<ViewClassInfo> groupList,
- IProgressMonitor monitor) {
- LayoutParamsParser ldp = null;
- try {
- WidgetClassLoader loader = new WidgetClassLoader(
- mAndroidTarget.getPath(IAndroidTarget.WIDGETS));
- if (loader.parseWidgetList(monitor)) {
- ldp = new LayoutParamsParser(loader, attrsXmlParser);
- }
- // if the parsing failed, we'll use the old loader below.
- } catch (FileNotFoundException e) {
- AdtPlugin.log(e, "Android Framework Parser"); //$NON-NLS-1$
- // the file does not exist, we'll use the old loader below.
- }
-
- if (ldp == null) {
- ldp = new LayoutParamsParser(classLoader, attrsXmlParser);
- }
- ldp.parseLayoutClasses(monitor);
-
- List<ViewClassInfo> views = ldp.getViews();
- List<ViewClassInfo> groups = ldp.getGroups();
-
- if (views != null && groups != null) {
- mainList.addAll(views);
- groupList.addAll(groups);
- }
- }
-
- /**
- * Collects all preferences definition information from the attrs.xml and
- * sets the corresponding structures in the resource manager.
- *
- * @param classLoader The framework SDK jar classloader
- * @param attrsXmlParser The parser of the attrs.xml file
- * @param mainList the Collection to receive the main list of {@link ViewClassInfo}.
- * @param groupList the Collection to receive the group list of {@link ViewClassInfo}.
- * @param monitor A progress monitor. Can be null. Caller is responsible for calling done.
- */
- private void collectPreferenceClasses(AndroidJarLoader classLoader,
- AttrsXmlParser attrsXmlParser, Collection<ViewClassInfo> mainList,
- Collection<ViewClassInfo> groupList, IProgressMonitor monitor) {
- LayoutParamsParser ldp = new LayoutParamsParser(classLoader, attrsXmlParser);
-
- try {
- ldp.parsePreferencesClasses(monitor);
-
- List<ViewClassInfo> prefs = ldp.getViews();
- List<ViewClassInfo> groups = ldp.getGroups();
-
- if (prefs != null && groups != null) {
- mainList.addAll(prefs);
- groupList.addAll(groups);
- }
- } catch (NoClassDefFoundError e) {
- AdtPlugin.logAndPrintError(e, TAG,
- "Collect preferences failed, class %1$s not found in %2$s",
- e.getMessage(),
- classLoader.getSource());
- } catch (Throwable e) {
- AdtPlugin.log(e, "Android Framework Parser: failed to collect preference classes"); //$NON-NLS-1$
- AdtPlugin.printErrorToConsole("Android Framework Parser",
- "failed to collect preference classes");
- }
- }
-
- /**
- * Collects all menu definition information from the attrs.xml and returns it.
- *
- * @param attrsXmlParser The parser of the attrs.xml file
- */
- private Map<String, DeclareStyleableInfo> collectMenuDefinitions(
- AttrsXmlParser attrsXmlParser) {
- Map<String, DeclareStyleableInfo> map = attrsXmlParser.getDeclareStyleableList();
- Map<String, DeclareStyleableInfo> map2 = new HashMap<String, DeclareStyleableInfo>();
- for (String key : new String[] { "Menu", //$NON-NLS-1$
- "MenuItem", //$NON-NLS-1$
- "MenuGroup" }) { //$NON-NLS-1$
- if (map.containsKey(key)) {
- map2.put(key, map.get(key));
- } else {
- AdtPlugin.log(IStatus.WARNING,
- "Menu declare-styleable %1$s not found in file %2$s", //$NON-NLS-1$
- key, attrsXmlParser.getOsAttrsXmlPath());
- AdtPlugin.printErrorToConsole("Android Framework Parser",
- String.format("Menu declare-styleable %1$s not found in file %2$s", //$NON-NLS-1$
- key, attrsXmlParser.getOsAttrsXmlPath()));
- }
- }
-
- return Collections.unmodifiableMap(map2);
- }
-
- /**
- * Collects all searchable definition information from the attrs.xml and returns it.
- *
- * @param attrsXmlParser The parser of the attrs.xml file
- */
- private Map<String, DeclareStyleableInfo> collectSearchableDefinitions(
- AttrsXmlParser attrsXmlParser) {
- Map<String, DeclareStyleableInfo> map = attrsXmlParser.getDeclareStyleableList();
- Map<String, DeclareStyleableInfo> map2 = new HashMap<String, DeclareStyleableInfo>();
- for (String key : new String[] { "Searchable", //$NON-NLS-1$
- "SearchableActionKey" }) { //$NON-NLS-1$
- if (map.containsKey(key)) {
- map2.put(key, map.get(key));
- } else {
- AdtPlugin.log(IStatus.WARNING,
- "Searchable declare-styleable %1$s not found in file %2$s", //$NON-NLS-1$
- key, attrsXmlParser.getOsAttrsXmlPath());
- AdtPlugin.printErrorToConsole("Android Framework Parser",
- String.format("Searchable declare-styleable %1$s not found in file %2$s", //$NON-NLS-1$
- key, attrsXmlParser.getOsAttrsXmlPath()));
- }
- }
-
- return Collections.unmodifiableMap(map2);
- }
-
- /**
- * Collects all appWidgetProviderInfo definition information from the attrs.xml and returns it.
- *
- * @param attrsXmlParser The parser of the attrs.xml file
- */
- private Map<String, DeclareStyleableInfo> collectAppWidgetDefinitions(
- AttrsXmlParser attrsXmlParser) {
- Map<String, DeclareStyleableInfo> map = attrsXmlParser.getDeclareStyleableList();
- Map<String, DeclareStyleableInfo> map2 = new HashMap<String, DeclareStyleableInfo>();
- for (String key : new String[] { "AppWidgetProviderInfo" }) { //$NON-NLS-1$
- if (map.containsKey(key)) {
- map2.put(key, map.get(key));
- } else {
- AdtPlugin.log(IStatus.WARNING,
- "AppWidget declare-styleable %1$s not found in file %2$s", //$NON-NLS-1$
- key, attrsXmlParser.getOsAttrsXmlPath());
- AdtPlugin.printErrorToConsole("Android Framework Parser",
- String.format("AppWidget declare-styleable %1$s not found in file %2$s", //$NON-NLS-1$
- key, attrsXmlParser.getOsAttrsXmlPath()));
- }
- }
-
- return Collections.unmodifiableMap(map2);
- }
-
- /**
- * Collects all manifest definition information from the attrs_manifest.xml and returns it.
- */
- private Map<String, DeclareStyleableInfo> collectManifestDefinitions(
- AttrsXmlParser attrsXmlParser) {
-
- return attrsXmlParser.getDeclareStyleableList();
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/IAndroidClassLoader.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/IAndroidClassLoader.java
deleted file mode 100644
index ab78d2a9b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/IAndroidClassLoader.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.sdk;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import javax.management.InvalidAttributeValueException;
-
-/**
- * Classes which implements this interface provide methods to access framework resource
- * data loaded from the SDK.
- */
-interface IAndroidClassLoader {
-
- /**
- * Classes which implement this interface provide methods to describe a class.
- */
- public interface IClassDescriptor {
-
- String getFullClassName();
-
- IClassDescriptor getSuperclass();
-
- String getSimpleName();
-
- IClassDescriptor getEnclosingClass();
-
- IClassDescriptor[] getDeclaredClasses();
-
- boolean isInstantiable();
- }
-
- /**
- * Finds and loads all classes that derive from a given set of super classes.
- *
- * @param rootPackage Root package of classes to find. Use an empty string to find everyting.
- * @param superClasses The super classes of all the classes to find.
- * @return An hash map which keys are the super classes looked for and which values are
- * ArrayList of the classes found. The array lists are always created for all the
- * valid keys, they are simply empty if no deriving class is found for a given
- * super class.
- * @throws IOException
- * @throws InvalidAttributeValueException
- * @throws ClassFormatError
- */
- public HashMap<String, ArrayList<IClassDescriptor>> findClassesDerivingFrom(
- String rootPackage, String[] superClasses)
- throws IOException, InvalidAttributeValueException, ClassFormatError;
-
- /**
- * Returns a {@link IClassDescriptor} by its fully-qualified name.
- * @param className the fully-qualified name of the class to return.
- * @throws ClassNotFoundException
- */
- public IClassDescriptor getClass(String className) throws ClassNotFoundException;
-
- /**
- * Returns a string indicating the source of the classes, typically for debugging
- * or in error messages. This would typically be a JAR file name or some kind of
- * identifier that would mean something to the user when looking at error messages.
- *
- * @return An informal string representing the source of the classes.
- */
- public String getSource();
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/LayoutParamsParser.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/LayoutParamsParser.java
deleted file mode 100644
index d05c12a9e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/LayoutParamsParser.java
+++ /dev/null
@@ -1,378 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.sdk;
-
-import com.android.SdkConstants;
-import com.android.ide.common.resources.platform.AttrsXmlParser;
-import com.android.ide.common.resources.platform.ViewClassInfo;
-import com.android.ide.common.resources.platform.ViewClassInfo.LayoutParamsInfo;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.sdk.IAndroidClassLoader.IClassDescriptor;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubMonitor;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.List;
-import java.util.SortedMap;
-import java.util.TreeMap;
-
-import javax.management.InvalidAttributeValueException;
-
-/*
- * TODO: refactor this. Could use some cleanup.
- */
-
-/**
- * Parser for the framework library.
- * <p/>
- * This gather the following information:
- * <ul>
- * <li>Resource ID from <code>android.R</code></li>
- * <li>The list of permissions values from <code>android.Manifest$permission</code></li>
- * <li></li>
- * </ul>
- */
-public class LayoutParamsParser {
-
- /**
- * Class extending {@link ViewClassInfo} by adding the notion of instantiability.
- * {@link LayoutParamsParser#getViews()} and {@link LayoutParamsParser#getGroups()} should
- * only return classes that can be instantiated.
- */
- final static class ExtViewClassInfo extends ViewClassInfo {
-
- private boolean mIsInstantiable;
-
- ExtViewClassInfo(boolean instantiable, boolean isLayout, String canonicalClassName,
- String shortClassName) {
- super(isLayout, canonicalClassName, shortClassName);
- mIsInstantiable = instantiable;
- }
-
- boolean isInstantiable() {
- return mIsInstantiable;
- }
- }
-
- /* Note: protected members/methods are overridden in unit tests */
-
- /** Reference to android.view.View */
- protected IClassDescriptor mTopViewClass;
- /** Reference to android.view.ViewGroup */
- protected IClassDescriptor mTopGroupClass;
- /** Reference to android.view.ViewGroup$LayoutParams */
- protected IClassDescriptor mTopLayoutParamsClass;
-
- /** Input list of all classes deriving from android.view.View */
- protected ArrayList<IClassDescriptor> mViewList;
- /** Input list of all classes deriving from android.view.ViewGroup */
- protected ArrayList<IClassDescriptor> mGroupList;
-
- /** Output map of FQCN => info on View classes */
- protected TreeMap<String, ExtViewClassInfo> mViewMap;
- /** Output map of FQCN => info on ViewGroup classes */
- protected TreeMap<String, ExtViewClassInfo> mGroupMap;
- /** Output map of FQCN => info on LayoutParams classes */
- protected HashMap<String, LayoutParamsInfo> mLayoutParamsMap;
-
- /** The attrs.xml parser */
- protected AttrsXmlParser mAttrsXmlParser;
-
- /** The android.jar class loader */
- protected IAndroidClassLoader mClassLoader;
-
- /**
- * Instantiate a new LayoutParamsParser.
- * @param classLoader The android.jar class loader
- * @param attrsXmlParser The parser of the attrs.xml file
- */
- public LayoutParamsParser(IAndroidClassLoader classLoader,
- AttrsXmlParser attrsXmlParser) {
- mClassLoader = classLoader;
- mAttrsXmlParser = attrsXmlParser;
- }
-
- /** Returns the map of FQCN => info on View classes */
- public List<ViewClassInfo> getViews() {
- return getInstantiables(mViewMap);
- }
-
- /** Returns the map of FQCN => info on ViewGroup classes */
- public List<ViewClassInfo> getGroups() {
- return getInstantiables(mGroupMap);
- }
-
- /**
- * TODO: doc here.
- * <p/>
- * Note: on output we should have NO dependency on {@link IClassDescriptor},
- * otherwise we wouldn't be able to unload the class loader later.
- * <p/>
- * Note on Vocabulary: FQCN=Fully Qualified Class Name (e.g. "my.package.class$innerClass")
- * @param monitor A progress monitor. Can be null. Caller is responsible for calling done.
- */
- public void parseLayoutClasses(IProgressMonitor monitor) {
- parseClasses(monitor,
- SdkConstants.CLASS_VIEW,
- SdkConstants.CLASS_VIEWGROUP,
- SdkConstants.CLASS_VIEWGROUP_LAYOUTPARAMS);
- }
-
- public void parsePreferencesClasses(IProgressMonitor monitor) {
- parseClasses(monitor,
- SdkConstants.CLASS_PREFERENCE,
- SdkConstants.CLASS_PREFERENCEGROUP,
- null /* paramsClassName */ );
- }
-
- private void parseClasses(IProgressMonitor monitor,
- String rootClassName,
- String groupClassName,
- String paramsClassName) {
- try {
- SubMonitor progress = SubMonitor.convert(monitor, 100);
-
- String[] superClasses = new String[2 + (paramsClassName == null ? 0 : 1)];
- superClasses[0] = groupClassName;
- superClasses[1] = rootClassName;
- if (paramsClassName != null) {
- superClasses[2] = paramsClassName;
- }
- HashMap<String, ArrayList<IClassDescriptor>> found =
- mClassLoader.findClassesDerivingFrom("android.", superClasses); //$NON-NLS-1$
- mTopViewClass = mClassLoader.getClass(rootClassName);
- mTopGroupClass = mClassLoader.getClass(groupClassName);
- if (paramsClassName != null) {
- mTopLayoutParamsClass = mClassLoader.getClass(paramsClassName);
- }
-
- mViewList = found.get(rootClassName);
- mGroupList = found.get(groupClassName);
-
- mViewMap = new TreeMap<String, ExtViewClassInfo>();
- mGroupMap = new TreeMap<String, ExtViewClassInfo>();
- if (mTopLayoutParamsClass != null) {
- mLayoutParamsMap = new HashMap<String, LayoutParamsInfo>();
- }
-
- // Add top classes to the maps since by design they are not listed in classes deriving
- // from themselves.
- if (mTopGroupClass != null) {
- addGroup(mTopGroupClass);
- }
- if (mTopViewClass != null) {
- addView(mTopViewClass);
- }
-
- // ViewGroup derives from View
- ExtViewClassInfo vg = mGroupMap.get(groupClassName);
- if (vg != null) {
- vg.setSuperClass(mViewMap.get(rootClassName));
- }
-
- progress.setWorkRemaining(mGroupList.size() + mViewList.size());
-
- for (IClassDescriptor groupChild : mGroupList) {
- addGroup(groupChild);
- progress.worked(1);
- }
-
- for (IClassDescriptor viewChild : mViewList) {
- if (viewChild != mTopGroupClass) {
- addView(viewChild);
- }
- progress.worked(1);
- }
- } catch (ClassNotFoundException e) {
- AdtPlugin.log(e, "Problem loading class %1$s or %2$s", //$NON-NLS-1$
- rootClassName, groupClassName);
- } catch (InvalidAttributeValueException e) {
- AdtPlugin.log(e, "Problem loading classes"); //$NON-NLS-1$
- } catch (ClassFormatError e) {
- AdtPlugin.log(e, "Problem loading classes"); //$NON-NLS-1$
- } catch (IOException e) {
- AdtPlugin.log(e, "Problem loading classes"); //$NON-NLS-1$
- }
- }
-
- /**
- * Parses a View class and adds a ExtViewClassInfo for it in mViewMap.
- * It calls itself recursively to handle super classes which are also Views.
- */
- private ExtViewClassInfo addView(IClassDescriptor viewClass) {
- String fqcn = viewClass.getFullClassName();
- if (mViewMap.containsKey(fqcn)) {
- return mViewMap.get(fqcn);
- } else if (mGroupMap.containsKey(fqcn)) {
- return mGroupMap.get(fqcn);
- }
-
- ExtViewClassInfo info = new ExtViewClassInfo(viewClass.isInstantiable(),
- false /* layout */, fqcn, viewClass.getSimpleName());
- mViewMap.put(fqcn, info);
-
- // All view classes derive from mTopViewClass by design.
- // Do not lookup the super class for mTopViewClass itself.
- if (viewClass.equals(mTopViewClass) == false) {
- IClassDescriptor superClass = viewClass.getSuperclass();
- ExtViewClassInfo superClassInfo = addView(superClass);
- info.setSuperClass(superClassInfo);
- }
-
- mAttrsXmlParser.loadViewAttributes(info);
- return info;
- }
-
- /**
- * Parses a ViewGroup class and adds a ExtViewClassInfo for it in mGroupMap.
- * It calls itself recursively to handle super classes which are also ViewGroups.
- */
- private ExtViewClassInfo addGroup(IClassDescriptor groupClass) {
- String fqcn = groupClass.getFullClassName();
- if (mGroupMap.containsKey(fqcn)) {
- return mGroupMap.get(fqcn);
- }
-
- ExtViewClassInfo info = new ExtViewClassInfo(groupClass.isInstantiable(),
- true /* layout */, fqcn, groupClass.getSimpleName());
- mGroupMap.put(fqcn, info);
-
- // All groups derive from android.view.ViewGroup, which in turns derives from
- // android.view.View (i.e. mTopViewClass here). So the only group that can have View as
- // its super class is the ViewGroup base class and we don't try to resolve it since groups
- // are loaded before views.
- IClassDescriptor superClass = groupClass.getSuperclass();
-
- // Assertion: at this point, we should have
- // superClass != mTopViewClass || fqcn.equals(SdkConstants.CLASS_VIEWGROUP);
-
- if (superClass != null && superClass.equals(mTopViewClass) == false) {
- ExtViewClassInfo superClassInfo = addGroup(superClass);
-
- // Assertion: we should have superClassInfo != null && superClassInfo != info;
- if (superClassInfo != null && superClassInfo != info) {
- info.setSuperClass(superClassInfo);
- }
- }
-
- mAttrsXmlParser.loadViewAttributes(info);
- if (mTopLayoutParamsClass != null) {
- info.setLayoutParams(addLayoutParams(groupClass));
- }
- return info;
- }
-
- /**
- * Parses a ViewGroup class and returns an info object on its inner LayoutParams.
- *
- * @return The {@link LayoutParamsInfo} for the ViewGroup class or null.
- */
- private LayoutParamsInfo addLayoutParams(IClassDescriptor groupClass) {
-
- // Is there a LayoutParams in this group class?
- IClassDescriptor layoutParamsClass = findLayoutParams(groupClass);
-
- // if there's no layout data in the group class, link to the one from the
- // super class.
- if (layoutParamsClass == null) {
- for (IClassDescriptor superClass = groupClass.getSuperclass();
- layoutParamsClass == null &&
- superClass != null &&
- superClass.equals(mTopViewClass) == false;
- superClass = superClass.getSuperclass()) {
- layoutParamsClass = findLayoutParams(superClass);
- }
- }
-
- if (layoutParamsClass != null) {
- return getLayoutParamsInfo(layoutParamsClass);
- }
-
- return null;
- }
-
- /**
- * Parses a LayoutParams class and returns a LayoutParamsInfo object for it.
- * It calls itself recursively to handle the super class of the LayoutParams.
- */
- private LayoutParamsInfo getLayoutParamsInfo(IClassDescriptor layoutParamsClass) {
- String fqcn = layoutParamsClass.getFullClassName();
- LayoutParamsInfo layoutParamsInfo = mLayoutParamsMap.get(fqcn);
-
- if (layoutParamsInfo != null) {
- return layoutParamsInfo;
- }
-
- // Find the link on the LayoutParams super class
- LayoutParamsInfo superClassInfo = null;
- if (layoutParamsClass.equals(mTopLayoutParamsClass) == false) {
- IClassDescriptor superClass = layoutParamsClass.getSuperclass();
- superClassInfo = getLayoutParamsInfo(superClass);
- }
-
- // Find the link on the enclosing ViewGroup
- ExtViewClassInfo enclosingGroupInfo = addGroup(layoutParamsClass.getEnclosingClass());
-
- layoutParamsInfo = new ExtViewClassInfo.LayoutParamsInfo(
- enclosingGroupInfo, layoutParamsClass.getSimpleName(), superClassInfo);
- mLayoutParamsMap.put(fqcn, layoutParamsInfo);
-
- mAttrsXmlParser.loadLayoutParamsAttributes(layoutParamsInfo);
-
- return layoutParamsInfo;
- }
-
- /**
- * Given a ViewGroup-derived class, looks for an inner class named LayoutParams
- * and if found returns its class definition.
- * <p/>
- * This uses the actual defined inner classes and does not look at inherited classes.
- *
- * @param groupClass The ViewGroup derived class
- * @return The Class of the inner LayoutParams or null if none is declared.
- */
- private IClassDescriptor findLayoutParams(IClassDescriptor groupClass) {
- IClassDescriptor[] innerClasses = groupClass.getDeclaredClasses();
- for (IClassDescriptor innerClass : innerClasses) {
- if (innerClass.getSimpleName().equals(SdkConstants.CLASS_NAME_LAYOUTPARAMS)) {
- return innerClass;
- }
- }
- return null;
- }
-
- /**
- * Computes and return a list of ViewClassInfo from a map by filtering out the class that
- * cannot be instantiated.
- */
- private List<ViewClassInfo> getInstantiables(SortedMap<String, ExtViewClassInfo> map) {
- Collection<ExtViewClassInfo> values = map.values();
- ArrayList<ViewClassInfo> list = new ArrayList<ViewClassInfo>();
-
- for (ExtViewClassInfo info : values) {
- if (info.isInstantiable()) {
- list.add(info);
- }
- }
-
- return list;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/ProjectState.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/ProjectState.java
deleted file mode 100644
index 74c985784..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/ProjectState.java
+++ /dev/null
@@ -1,740 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.sdk;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.sdklib.BuildToolInfo;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.internal.project.ProjectProperties;
-import com.android.sdklib.internal.project.ProjectPropertiesWorkingCopy;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.regex.Matcher;
-
-/**
- * Centralized state for Android Eclipse project.
- * <p>This gives raw access to the properties (from <code>project.properties</code>), as well
- * as direct access to target and library information.
- *
- * This also gives access to library information.
- *
- * {@link #isLibrary()} indicates if the project is a library.
- * {@link #hasLibraries()} and {@link #getLibraries()} give access to the libraries through
- * instances of {@link LibraryState}. A {@link LibraryState} instance is a link between a main
- * project and its library. Theses instances are owned by the {@link ProjectState}.
- *
- * {@link #isMissingLibraries()} will indicate if the project has libraries that are not resolved.
- * Unresolved libraries are libraries that do not have any matching opened Eclipse project.
- * When there are missing libraries, the {@link LibraryState} instance for them will return null
- * for {@link LibraryState#getProjectState()}.
- *
- */
-public final class ProjectState {
-
- /**
- * A class that represents a library linked to a project.
- * <p/>It does not represent the library uniquely. Instead the {@link LibraryState} is linked
- * to the main project which is accessible through {@link #getMainProjectState()}.
- * <p/>If a library is used by two different projects, then there will be two different
- * instances of {@link LibraryState} for the library.
- *
- * @see ProjectState#getLibrary(IProject)
- */
- public final class LibraryState {
- private String mRelativePath;
- private ProjectState mProjectState;
- private String mPath;
-
- private LibraryState(String relativePath) {
- mRelativePath = relativePath;
- }
-
- /**
- * Returns the {@link ProjectState} of the main project using this library.
- */
- public ProjectState getMainProjectState() {
- return ProjectState.this;
- }
-
- /**
- * Closes the library. This resets the IProject from this object ({@link #getProjectState()} will
- * return <code>null</code>), and updates the main project data so that the library
- * {@link IProject} object does not show up in the return value of
- * {@link ProjectState#getFullLibraryProjects()}.
- */
- public void close() {
- mProjectState.removeParentProject(getMainProjectState());
- mProjectState = null;
- mPath = null;
-
- getMainProjectState().updateFullLibraryList();
- }
-
- private void setRelativePath(String relativePath) {
- mRelativePath = relativePath;
- }
-
- private void setProject(ProjectState project) {
- mProjectState = project;
- mPath = project.getProject().getLocation().toOSString();
- mProjectState.addParentProject(getMainProjectState());
-
- getMainProjectState().updateFullLibraryList();
- }
-
- /**
- * Returns the relative path of the library from the main project.
- * <p/>This is identical to the value defined in the main project's project.properties.
- */
- public String getRelativePath() {
- return mRelativePath;
- }
-
- /**
- * Returns the {@link ProjectState} item for the library. This can be null if the project
- * is not actually opened in Eclipse.
- */
- public ProjectState getProjectState() {
- return mProjectState;
- }
-
- /**
- * Returns the OS-String location of the library project.
- * <p/>This is based on location of the Eclipse project that matched
- * {@link #getRelativePath()}.
- *
- * @return The project location, or null if the project is not opened in Eclipse.
- */
- public String getProjectLocation() {
- return mPath;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj instanceof LibraryState) {
- // the only thing that's always non-null is the relative path.
- LibraryState objState = (LibraryState)obj;
- return mRelativePath.equals(objState.mRelativePath) &&
- getMainProjectState().equals(objState.getMainProjectState());
- } else if (obj instanceof ProjectState || obj instanceof IProject) {
- return mProjectState != null && mProjectState.equals(obj);
- } else if (obj instanceof String) {
- return normalizePath(mRelativePath).equals(normalizePath((String) obj));
- }
-
- return false;
- }
-
- @Override
- public int hashCode() {
- return normalizePath(mRelativePath).hashCode();
- }
- }
-
- private final IProject mProject;
- private final ProjectProperties mProperties;
- private IAndroidTarget mTarget;
- private BuildToolInfo mBuildToolInfo;
-
- /**
- * list of libraries. Access to this list must be protected by
- * <code>synchronized(mLibraries)</code>, but it is important that such code do not call
- * out to other classes (especially those protected by {@link Sdk#getLock()}.)
- */
- private final ArrayList<LibraryState> mLibraries = new ArrayList<LibraryState>();
- /** Cached list of all IProject instances representing the resolved libraries, including
- * indirect dependencies. This must never be null. */
- private List<IProject> mLibraryProjects = Collections.emptyList();
- /**
- * List of parent projects. When this instance is a library ({@link #isLibrary()} returns
- * <code>true</code>) then this is filled with projects that depends on this project.
- */
- private final ArrayList<ProjectState> mParentProjects = new ArrayList<ProjectState>();
-
- ProjectState(IProject project, ProjectProperties properties) {
- if (project == null || properties == null) {
- throw new NullPointerException();
- }
-
- mProject = project;
- mProperties = properties;
-
- // load the libraries
- synchronized (mLibraries) {
- int index = 1;
- while (true) {
- String propName = ProjectProperties.PROPERTY_LIB_REF + Integer.toString(index++);
- String rootPath = mProperties.getProperty(propName);
-
- if (rootPath == null) {
- break;
- }
-
- mLibraries.add(new LibraryState(convertPath(rootPath)));
- }
- }
- }
-
- public IProject getProject() {
- return mProject;
- }
-
- public ProjectProperties getProperties() {
- return mProperties;
- }
-
- public @Nullable String getProperty(@NonNull String name) {
- if (mProperties != null) {
- return mProperties.getProperty(name);
- }
-
- return null;
- }
-
- public void setTarget(IAndroidTarget target) {
- mTarget = target;
- }
-
- /**
- * Returns the project's target's hash string.
- * <p/>If {@link #getTarget()} returns a valid object, then this returns the value of
- * {@link IAndroidTarget#hashString()}.
- * <p/>Otherwise this will return the value of the property
- * {@link ProjectProperties#PROPERTY_TARGET} from {@link #getProperties()} (if valid).
- * @return the target hash string or null if not found.
- */
- public String getTargetHashString() {
- if (mTarget != null) {
- return mTarget.hashString();
- }
-
- return mProperties.getProperty(ProjectProperties.PROPERTY_TARGET);
- }
-
- public IAndroidTarget getTarget() {
- return mTarget;
- }
-
- public void setBuildToolInfo(BuildToolInfo buildToolInfo) {
- mBuildToolInfo = buildToolInfo;
- }
-
- public BuildToolInfo getBuildToolInfo() {
- return mBuildToolInfo;
- }
-
- /**
- * Returns the build tools version from the project's properties.
- * @return the value or null
- */
- @Nullable
- public String getBuildToolInfoVersion() {
- return mProperties.getProperty(ProjectProperties.PROPERTY_BUILD_TOOLS);
- }
-
- public boolean getRenderScriptSupportMode() {
- String supportModeValue = mProperties.getProperty(ProjectProperties.PROPERTY_RS_SUPPORT);
- if (supportModeValue != null) {
- return Boolean.parseBoolean(supportModeValue);
- }
-
- return false;
- }
-
- public static class LibraryDifference {
- public boolean removed = false;
- public boolean added = false;
-
- public boolean hasDiff() {
- return removed || added;
- }
- }
-
- /**
- * Reloads the content of the properties.
- * <p/>This also reset the reference to the target as it may have changed, therefore this
- * should be followed by a call to {@link Sdk#loadTarget(ProjectState)}.
- *
- * <p/>If the project libraries changes, they are updated to a certain extent.<br>
- * Removed libraries are removed from the state list, and added to the {@link LibraryDifference}
- * object that is returned so that they can be processed.<br>
- * Added libraries are added to the state (as new {@link LibraryState} objects), but their
- * IProject is not resolved. {@link ProjectState#needs(ProjectState)} should be called
- * afterwards to properly initialize the libraries.
- *
- * @return an instance of {@link LibraryDifference} describing the change in libraries.
- */
- public LibraryDifference reloadProperties() {
- mTarget = null;
- mProperties.reload();
-
- // compare/reload the libraries.
-
- // if the order change it won't impact the java part, so instead try to detect removed/added
- // libraries.
-
- LibraryDifference diff = new LibraryDifference();
-
- synchronized (mLibraries) {
- List<LibraryState> oldLibraries = new ArrayList<LibraryState>(mLibraries);
- mLibraries.clear();
-
- // load the libraries
- int index = 1;
- while (true) {
- String propName = ProjectProperties.PROPERTY_LIB_REF + Integer.toString(index++);
- String rootPath = mProperties.getProperty(propName);
-
- if (rootPath == null) {
- break;
- }
-
- // search for a library with the same path (not exact same string, but going
- // to the same folder).
- String convertedPath = convertPath(rootPath);
- boolean found = false;
- for (int i = 0 ; i < oldLibraries.size(); i++) {
- LibraryState libState = oldLibraries.get(i);
- if (libState.equals(convertedPath)) {
- // it's a match. move it back to mLibraries and remove it from the
- // old library list.
- found = true;
- mLibraries.add(libState);
- oldLibraries.remove(i);
- break;
- }
- }
-
- if (found == false) {
- diff.added = true;
- mLibraries.add(new LibraryState(convertedPath));
- }
- }
-
- // whatever's left in oldLibraries is removed.
- diff.removed = oldLibraries.size() > 0;
-
- // update the library with what IProjet are known at the time.
- updateFullLibraryList();
- }
-
- return diff;
- }
-
- /**
- * Returns the list of {@link LibraryState}.
- */
- public List<LibraryState> getLibraries() {
- synchronized (mLibraries) {
- return Collections.unmodifiableList(mLibraries);
- }
- }
-
- /**
- * Returns all the <strong>resolved</strong> library projects, including indirect dependencies.
- * The list is ordered to match the library priority order for resource processing with
- * <code>aapt</code>.
- * <p/>If some dependencies are not resolved (or their projects is not opened in Eclipse),
- * they will not show up in this list.
- * @return the resolved projects as an unmodifiable list. May be an empty.
- */
- public List<IProject> getFullLibraryProjects() {
- return mLibraryProjects;
- }
-
- /**
- * Returns whether this is a library project.
- */
- public boolean isLibrary() {
- String value = mProperties.getProperty(ProjectProperties.PROPERTY_LIBRARY);
- return value != null && Boolean.valueOf(value);
- }
-
- /**
- * Returns whether the project depends on one or more libraries.
- */
- public boolean hasLibraries() {
- synchronized (mLibraries) {
- return mLibraries.size() > 0;
- }
- }
-
- /**
- * Returns whether the project is missing some required libraries.
- */
- public boolean isMissingLibraries() {
- synchronized (mLibraries) {
- for (LibraryState state : mLibraries) {
- if (state.getProjectState() == null) {
- return true;
- }
- }
- }
-
- return false;
- }
-
- /**
- * Returns the {@link LibraryState} object for a given {@link IProject}.
- * </p>This can only return a non-null object if the link between the main project's
- * {@link IProject} and the library's {@link IProject} was done.
- *
- * @return the matching LibraryState or <code>null</code>
- *
- * @see #needs(ProjectState)
- */
- public LibraryState getLibrary(IProject library) {
- synchronized (mLibraries) {
- for (LibraryState state : mLibraries) {
- ProjectState ps = state.getProjectState();
- if (ps != null && ps.getProject().equals(library)) {
- return state;
- }
- }
- }
-
- return null;
- }
-
- /**
- * Returns the {@link LibraryState} object for a given <var>name</var>.
- * </p>This can only return a non-null object if the link between the main project's
- * {@link IProject} and the library's {@link IProject} was done.
- *
- * @return the matching LibraryState or <code>null</code>
- *
- * @see #needs(IProject)
- */
- public LibraryState getLibrary(String name) {
- synchronized (mLibraries) {
- for (LibraryState state : mLibraries) {
- ProjectState ps = state.getProjectState();
- if (ps != null && ps.getProject().getName().equals(name)) {
- return state;
- }
- }
- }
-
- return null;
- }
-
-
- /**
- * Returns whether a given library project is needed by the receiver.
- * <p/>If the library is needed, this finds the matching {@link LibraryState}, initializes it
- * so that it contains the library's {@link IProject} object (so that
- * {@link LibraryState#getProjectState()} does not return null) and then returns it.
- *
- * @param libraryProject the library project to check.
- * @return a non null object if the project is a library dependency,
- * <code>null</code> otherwise.
- *
- * @see LibraryState#getProjectState()
- */
- public LibraryState needs(ProjectState libraryProject) {
- // compute current location
- File projectFile = mProject.getLocation().toFile();
-
- // get the location of the library.
- File libraryFile = libraryProject.getProject().getLocation().toFile();
-
- // loop on all libraries and check if the path match
- synchronized (mLibraries) {
- for (LibraryState state : mLibraries) {
- if (state.getProjectState() == null) {
- File library = new File(projectFile, state.getRelativePath());
- try {
- File absPath = library.getCanonicalFile();
- if (absPath.equals(libraryFile)) {
- state.setProject(libraryProject);
- return state;
- }
- } catch (IOException e) {
- // ignore this library
- }
- }
- }
- }
-
- return null;
- }
-
- /**
- * Returns whether the project depends on a given <var>library</var>
- * @param library the library to check.
- * @return true if the project depends on the library. This is not affected by whether the link
- * was done through {@link #needs(ProjectState)}.
- */
- public boolean dependsOn(ProjectState library) {
- synchronized (mLibraries) {
- for (LibraryState state : mLibraries) {
- if (state != null && state.getProjectState() != null &&
- library.getProject().equals(state.getProjectState().getProject())) {
- return true;
- }
- }
- }
-
- return false;
- }
-
-
- /**
- * Updates a library with a new path.
- * <p/>This method acts both as a check and an action. If the project does not depend on the
- * given <var>oldRelativePath</var> then no action is done and <code>null</code> is returned.
- * <p/>If the project depends on the library, then the project is updated with the new path,
- * and the {@link LibraryState} for the library is returned.
- * <p/>Updating the project does two things:<ul>
- * <li>Update LibraryState with new relative path and new {@link IProject} object.</li>
- * <li>Update the main project's <code>project.properties</code> with the new relative path
- * for the changed library.</li>
- * </ul>
- *
- * @param oldRelativePath the old library path relative to this project
- * @param newRelativePath the new library path relative to this project
- * @param newLibraryState the new {@link ProjectState} object.
- * @return a non null object if the project depends on the library.
- *
- * @see LibraryState#getProjectState()
- */
- public LibraryState updateLibrary(String oldRelativePath, String newRelativePath,
- ProjectState newLibraryState) {
- // compute current location
- File projectFile = mProject.getLocation().toFile();
-
- // loop on all libraries and check if the path matches
- synchronized (mLibraries) {
- for (LibraryState state : mLibraries) {
- if (state.getProjectState() == null) {
- try {
- // oldRelativePath may not be the same exact string as the
- // one in the project properties (trailing separator could be different
- // for instance).
- // Use java.io.File to deal with this and also do a platform-dependent
- // path comparison
- File library1 = new File(projectFile, oldRelativePath);
- File library2 = new File(projectFile, state.getRelativePath());
- if (library1.getCanonicalPath().equals(library2.getCanonicalPath())) {
- // save the exact property string to replace.
- String oldProperty = state.getRelativePath();
-
- // then update the LibraryPath.
- state.setRelativePath(newRelativePath);
- state.setProject(newLibraryState);
-
- // update the project.properties file
- IStatus status = replaceLibraryProperty(oldProperty, newRelativePath);
- if (status != null) {
- if (status.getSeverity() != IStatus.OK) {
- // log the error somehow.
- }
- } else {
- // This should not happen since the library wouldn't be here in the
- // first place
- }
-
- // return the LibraryState object.
- return state;
- }
- } catch (IOException e) {
- // ignore this library
- }
- }
- }
- }
-
- return null;
- }
-
-
- private void addParentProject(ProjectState parentState) {
- mParentProjects.add(parentState);
- }
-
- private void removeParentProject(ProjectState parentState) {
- mParentProjects.remove(parentState);
- }
-
- public List<ProjectState> getParentProjects() {
- return Collections.unmodifiableList(mParentProjects);
- }
-
- /**
- * Computes the transitive closure of projects referencing this project as a
- * library project
- *
- * @return a collection (in any order) of project states for projects that
- * directly or indirectly include this project state's project as a
- * library project
- */
- public Collection<ProjectState> getFullParentProjects() {
- Set<ProjectState> result = new HashSet<ProjectState>();
- addParentProjects(result, this);
- return result;
- }
-
- /** Adds all parent projects of the given project, transitively, into the given parent set */
- private static void addParentProjects(Set<ProjectState> parents, ProjectState state) {
- for (ProjectState s : state.mParentProjects) {
- if (!parents.contains(s)) {
- parents.add(s);
- addParentProjects(parents, s);
- }
- }
- }
-
- /**
- * Update the value of a library dependency.
- * <p/>This loops on all current dependency looking for the value to replace and then replaces
- * it.
- * <p/>This both updates the in-memory {@link #mProperties} values and on-disk
- * project.properties file.
- * @param oldValue the old value to replace
- * @param newValue the new value to set.
- * @return the status of the replacement. If null, no replacement was done (value not found).
- */
- private IStatus replaceLibraryProperty(String oldValue, String newValue) {
- int index = 1;
- while (true) {
- String propName = ProjectProperties.PROPERTY_LIB_REF + Integer.toString(index++);
- String rootPath = mProperties.getProperty(propName);
-
- if (rootPath == null) {
- break;
- }
-
- if (rootPath.equals(oldValue)) {
- // need to update the properties. Get a working copy to change it and save it on
- // disk since ProjectProperties is read-only.
- ProjectPropertiesWorkingCopy workingCopy = mProperties.makeWorkingCopy();
- workingCopy.setProperty(propName, newValue);
- try {
- workingCopy.save();
-
- // reload the properties with the new values from the disk.
- mProperties.reload();
- } catch (Exception e) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, String.format(
- "Failed to save %1$s for project %2$s",
- mProperties.getType() .getFilename(), mProject.getName()),
- e);
-
- }
- return Status.OK_STATUS;
- }
- }
-
- return null;
- }
-
- /**
- * Update the full library list, including indirect dependencies. The result is returned by
- * {@link #getFullLibraryProjects()}.
- */
- void updateFullLibraryList() {
- ArrayList<IProject> list = new ArrayList<IProject>();
- synchronized (mLibraries) {
- buildFullLibraryDependencies(mLibraries, list);
- }
-
- mLibraryProjects = Collections.unmodifiableList(list);
- }
-
- /**
- * Resolves a given list of libraries, finds out if they depend on other libraries, and
- * returns a full list of all the direct and indirect dependencies in the proper order (first
- * is higher priority when calling aapt).
- * @param inLibraries the libraries to resolve
- * @param outLibraries where to store all the libraries.
- */
- private void buildFullLibraryDependencies(List<LibraryState> inLibraries,
- ArrayList<IProject> outLibraries) {
- // loop in the inverse order to resolve dependencies on the libraries, so that if a library
- // is required by two higher level libraries it can be inserted in the correct place
- for (int i = inLibraries.size() - 1 ; i >= 0 ; i--) {
- LibraryState library = inLibraries.get(i);
-
- // get its libraries if possible
- ProjectState libProjectState = library.getProjectState();
- if (libProjectState != null) {
- List<LibraryState> dependencies = libProjectState.getLibraries();
-
- // build the dependencies for those libraries
- buildFullLibraryDependencies(dependencies, outLibraries);
-
- // and add the current library (if needed) in front (higher priority)
- if (outLibraries.contains(libProjectState.getProject()) == false) {
- outLibraries.add(0, libProjectState.getProject());
- }
- }
- }
- }
-
-
- /**
- * Converts a path containing only / by the proper platform separator.
- */
- private String convertPath(String path) {
- return path.replaceAll("/", Matcher.quoteReplacement(File.separator)); //$NON-NLS-1$
- }
-
- /**
- * Normalizes a relative path.
- */
- private String normalizePath(String path) {
- path = convertPath(path);
- if (path.endsWith("/")) { //$NON-NLS-1$
- path = path.substring(0, path.length() - 1);
- }
- return path;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj instanceof ProjectState) {
- return mProject.equals(((ProjectState) obj).mProject);
- } else if (obj instanceof IProject) {
- return mProject.equals(obj);
- }
-
- return false;
- }
-
- @Override
- public int hashCode() {
- return mProject.hashCode();
- }
-
- @Override
- public String toString() {
- return mProject.getName();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/Sdk.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/Sdk.java
deleted file mode 100644
index 7ff06fc40..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/Sdk.java
+++ /dev/null
@@ -1,1620 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.sdk;
-
-import static com.android.SdkConstants.DOT_XML;
-import static com.android.SdkConstants.EXT_JAR;
-import static com.android.SdkConstants.FD_RES;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ddmlib.IDevice;
-import com.android.ide.common.rendering.LayoutLibrary;
-import com.android.ide.common.sdk.LoadStatus;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.build.DexWrapper;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.project.LibraryClasspathContainerInitializer;
-import com.android.ide.eclipse.adt.internal.project.ProjectHelper;
-import com.android.ide.eclipse.adt.internal.resources.manager.GlobalProjectMonitor;
-import com.android.ide.eclipse.adt.internal.resources.manager.GlobalProjectMonitor.IFileListener;
-import com.android.ide.eclipse.adt.internal.resources.manager.GlobalProjectMonitor.IProjectListener;
-import com.android.ide.eclipse.adt.internal.resources.manager.GlobalProjectMonitor.IResourceEventListener;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState.LibraryDifference;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState.LibraryState;
-import com.android.io.StreamException;
-import com.android.prefs.AndroidLocation.AndroidLocationException;
-import com.android.sdklib.AndroidVersion;
-import com.android.sdklib.BuildToolInfo;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.SdkManager;
-import com.android.sdklib.devices.DeviceManager;
-import com.android.sdklib.internal.avd.AvdManager;
-import com.android.sdklib.internal.project.ProjectProperties;
-import com.android.sdklib.internal.project.ProjectProperties.PropertyType;
-import com.android.sdklib.internal.project.ProjectPropertiesWorkingCopy;
-import com.android.sdklib.repository.FullRevision;
-import com.android.utils.ILogger;
-import com.google.common.collect.Maps;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IMarkerDelta;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IncrementalProjectBuilder;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.QualifiedName;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.ui.IEditorDescriptor;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IEditorReference;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPartSite;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.ide.IDE;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * Central point to load, manipulate and deal with the Android SDK. Only one SDK can be used
- * at the same time.
- *
- * To start using an SDK, call {@link #loadSdk(String)} which returns the instance of
- * the Sdk object.
- *
- * To get the list of platforms or add-ons present in the SDK, call {@link #getTargets()}.
- */
-public final class Sdk {
- private final static boolean DEBUG = false;
-
- private final static Object LOCK = new Object();
-
- private static Sdk sCurrentSdk = null;
-
- /**
- * Map associating {@link IProject} and their state {@link ProjectState}.
- * <p/>This <b>MUST NOT</b> be accessed directly. Instead use {@link #getProjectState(IProject)}.
- */
- private final static HashMap<IProject, ProjectState> sProjectStateMap =
- new HashMap<IProject, ProjectState>();
-
- /**
- * Data bundled using during the load of Target data.
- * <p/>This contains the {@link LoadStatus} and a list of projects that attempted
- * to compile before the loading was finished. Those projects will be recompiled
- * at the end of the loading.
- */
- private final static class TargetLoadBundle {
- LoadStatus status;
- final HashSet<IJavaProject> projectsToReload = new HashSet<IJavaProject>();
- }
-
- private final SdkManager mManager;
- private final Map<String, DexWrapper> mDexWrappers = Maps.newHashMap();
- private final AvdManager mAvdManager;
- private final DeviceManager mDeviceManager;
-
- /** Map associating an {@link IAndroidTarget} to an {@link AndroidTargetData} */
- private final HashMap<IAndroidTarget, AndroidTargetData> mTargetDataMap =
- new HashMap<IAndroidTarget, AndroidTargetData>();
- /** Map associating an {@link IAndroidTarget} and its {@link TargetLoadBundle}. */
- private final HashMap<IAndroidTarget, TargetLoadBundle> mTargetDataStatusMap =
- new HashMap<IAndroidTarget, TargetLoadBundle>();
-
- /**
- * If true the target data will never load anymore. The only way to reload them is to
- * completely reload the SDK with {@link #loadSdk(String)}
- */
- private boolean mDontLoadTargetData = false;
-
- private final String mDocBaseUrl;
-
- /**
- * Classes implementing this interface will receive notification when targets are changed.
- */
- public interface ITargetChangeListener {
- /**
- * Sent when project has its target changed.
- */
- void onProjectTargetChange(IProject changedProject);
-
- /**
- * Called when the targets are loaded (either the SDK finished loading when Eclipse starts,
- * or the SDK is changed).
- */
- void onTargetLoaded(IAndroidTarget target);
-
- /**
- * Called when the base content of the SDK is parsed.
- */
- void onSdkLoaded();
- }
-
- /**
- * Basic abstract implementation of the ITargetChangeListener for the case where both
- * {@link #onProjectTargetChange(IProject)} and {@link #onTargetLoaded(IAndroidTarget)}
- * use the same code based on a simple test requiring to know the current IProject.
- */
- public static abstract class TargetChangeListener implements ITargetChangeListener {
- /**
- * Returns the {@link IProject} associated with the listener.
- */
- public abstract IProject getProject();
-
- /**
- * Called when the listener needs to take action on the event. This is only called
- * if {@link #getProject()} and the {@link IAndroidTarget} associated with the project
- * match the values received in {@link #onProjectTargetChange(IProject)} and
- * {@link #onTargetLoaded(IAndroidTarget)}.
- */
- public abstract void reload();
-
- @Override
- public void onProjectTargetChange(IProject changedProject) {
- if (changedProject != null && changedProject.equals(getProject())) {
- reload();
- }
- }
-
- @Override
- public void onTargetLoaded(IAndroidTarget target) {
- IProject project = getProject();
- if (target != null && target.equals(Sdk.getCurrent().getTarget(project))) {
- reload();
- }
- }
-
- @Override
- public void onSdkLoaded() {
- // do nothing;
- }
- }
-
- /**
- * Returns the lock object used to synchronize all operations dealing with SDK, targets and
- * projects.
- */
- @NonNull
- public static final Object getLock() {
- return LOCK;
- }
-
- /**
- * Loads an SDK and returns an {@link Sdk} object if success.
- * <p/>If the SDK failed to load, it displays an error to the user.
- * @param sdkLocation the OS path to the SDK.
- */
- @Nullable
- public static Sdk loadSdk(String sdkLocation) {
- synchronized (LOCK) {
- if (sCurrentSdk != null) {
- sCurrentSdk.dispose();
- sCurrentSdk = null;
- }
-
- final AtomicBoolean hasWarning = new AtomicBoolean();
- final AtomicBoolean hasError = new AtomicBoolean();
- final ArrayList<String> logMessages = new ArrayList<String>();
- ILogger log = new ILogger() {
- @Override
- public void error(@Nullable Throwable throwable, @Nullable String errorFormat,
- Object... arg) {
- hasError.set(true);
- if (errorFormat != null) {
- logMessages.add(String.format("Error: " + errorFormat, arg));
- }
-
- if (throwable != null) {
- logMessages.add(throwable.getMessage());
- }
- }
-
- @Override
- public void warning(@NonNull String warningFormat, Object... arg) {
- hasWarning.set(true);
- logMessages.add(String.format("Warning: " + warningFormat, arg));
- }
-
- @Override
- public void info(@NonNull String msgFormat, Object... arg) {
- logMessages.add(String.format(msgFormat, arg));
- }
-
- @Override
- public void verbose(@NonNull String msgFormat, Object... arg) {
- info(msgFormat, arg);
- }
- };
-
- // get an SdkManager object for the location
- SdkManager manager = SdkManager.createManager(sdkLocation, log);
- try {
- if (manager == null) {
- hasError.set(true);
- } else {
- // create the AVD Manager
- AvdManager avdManager = null;
- try {
- avdManager = AvdManager.getInstance(manager.getLocalSdk(), log);
- } catch (AndroidLocationException e) {
- log.error(e, "Error parsing the AVDs");
- }
- sCurrentSdk = new Sdk(manager, avdManager);
- return sCurrentSdk;
- }
- } finally {
- if (hasError.get() || hasWarning.get()) {
- StringBuilder sb = new StringBuilder(
- String.format("%s when loading the SDK:\n",
- hasError.get() ? "Error" : "Warning"));
- for (String msg : logMessages) {
- sb.append('\n');
- sb.append(msg);
- }
- if (hasError.get()) {
- AdtPlugin.printErrorToConsole("Android SDK", sb.toString());
- AdtPlugin.displayError("Android SDK", sb.toString());
- } else {
- AdtPlugin.printToConsole("Android SDK", sb.toString());
- }
- }
- }
- return null;
- }
- }
-
- /**
- * Returns the current {@link Sdk} object.
- */
- @Nullable
- public static Sdk getCurrent() {
- synchronized (LOCK) {
- return sCurrentSdk;
- }
- }
-
- /**
- * Returns the location of the current SDK as an OS path string.
- * Guaranteed to be terminated by a platform-specific path separator.
- * <p/>
- * Due to {@link File} canonicalization, this MAY differ from the string used to initialize
- * the SDK path.
- *
- * @return The SDK OS path or null if no SDK is setup.
- * @deprecated Consider using {@link #getSdkFileLocation()} instead.
- * @see #getSdkFileLocation()
- */
- @Deprecated
- @Nullable
- public String getSdkOsLocation() {
- String path = mManager == null ? null : mManager.getLocation();
- if (path != null) {
- // For backward compatibility make sure it ends with a separator.
- // This used to be the case when the SDK Manager was created from a String path
- // but now that a File is internally used the trailing dir separator is lost.
- if (path.length() > 0 && !path.endsWith(File.separator)) {
- path = path + File.separator;
- }
- }
- return path;
- }
-
- /**
- * Returns the location of the current SDK as a {@link File} or null.
- *
- * @return The SDK OS path or null if no SDK is setup.
- */
- @Nullable
- public File getSdkFileLocation() {
- if (mManager == null || mManager.getLocalSdk() == null) {
- return null;
- }
- return mManager.getLocalSdk().getLocation();
- }
-
- /**
- * Returns a <em>new</em> {@link SdkManager} that can parse the SDK located
- * at the current {@link #getSdkOsLocation()}.
- * <p/>
- * Implementation detail: The {@link Sdk} has its own internal manager with
- * a custom logger which is not designed to be useful for outsiders. Callers
- * who need their own {@link SdkManager} for parsing will often want to control
- * the logger for their own need.
- * <p/>
- * This is just a convenient method equivalent to writing:
- * <pre>SdkManager.createManager(Sdk.getCurrent().getSdkLocation(), log);</pre>
- *
- * @param log The logger for the {@link SdkManager}.
- * @return A new {@link SdkManager} parsing the same location.
- */
- public @Nullable SdkManager getNewSdkManager(@NonNull ILogger log) {
- return SdkManager.createManager(getSdkOsLocation(), log);
- }
-
- /**
- * Returns the URL to the local documentation.
- * Can return null if no documentation is found in the current SDK.
- *
- * @return A file:// URL on the local documentation folder if it exists or null.
- */
- @Nullable
- public String getDocumentationBaseUrl() {
- return mDocBaseUrl;
- }
-
- /**
- * Returns the list of targets that are available in the SDK.
- */
- public IAndroidTarget[] getTargets() {
- return mManager.getTargets();
- }
-
- /**
- * Queries the underlying SDK Manager to check whether the platforms or addons
- * directories have changed on-disk. Does not reload the SDK.
- * <p/>
- * This is a quick test based on the presence of the directories, their timestamps
- * and a quick checksum of the source.properties files. It's possible to have
- * false positives (e.g. if a file is manually modified in a platform) or false
- * negatives (e.g. if a platform data file is changed manually in a 2nd level
- * directory without altering the source.properties.)
- */
- public boolean haveTargetsChanged() {
- return mManager.hasChanged();
- }
-
- /**
- * Returns a target from a hash that was generated by {@link IAndroidTarget#hashString()}.
- *
- * @param hash the {@link IAndroidTarget} hash string.
- * @return The matching {@link IAndroidTarget} or null.
- */
- @Nullable
- public IAndroidTarget getTargetFromHashString(@NonNull String hash) {
- return mManager.getTargetFromHashString(hash);
- }
-
- @Nullable
- public BuildToolInfo getBuildToolInfo(@Nullable String buildToolVersion) {
- if (buildToolVersion != null) {
- try {
- return mManager.getBuildTool(FullRevision.parseRevision(buildToolVersion));
- } catch (Exception e) {
- // ignore, return null below.
- }
- }
-
- return null;
- }
-
- @Nullable
- public BuildToolInfo getLatestBuildTool() {
- return mManager.getLatestBuildTool();
- }
-
- /**
- * Initializes a new project with a target. This creates the <code>project.properties</code>
- * file.
- * @param project the project to initialize
- * @param target the project's target.
- * @throws IOException if creating the file failed in any way.
- * @throws StreamException if processing the project property file fails
- */
- public void initProject(@Nullable IProject project, @Nullable IAndroidTarget target)
- throws IOException, StreamException {
- if (project == null || target == null) {
- return;
- }
-
- synchronized (LOCK) {
- // check if there's already a state?
- ProjectState state = getProjectState(project);
-
- ProjectPropertiesWorkingCopy properties = null;
-
- if (state != null) {
- properties = state.getProperties().makeWorkingCopy();
- }
-
- if (properties == null) {
- IPath location = project.getLocation();
- if (location == null) { // can return null when the project is being deleted.
- // do nothing and return null;
- return;
- }
-
- properties = ProjectProperties.create(location.toOSString(), PropertyType.PROJECT);
- }
-
- // save the target hash string in the project persistent property
- properties.setProperty(ProjectProperties.PROPERTY_TARGET, target.hashString());
- properties.save();
- }
- }
-
- /**
- * Returns the {@link ProjectState} object associated with a given project.
- * <p/>
- * This method is the only way to properly get the project's {@link ProjectState}
- * If the project has not yet been loaded, then it is loaded.
- * <p/>Because this methods deals with projects, it's not linked to an actual {@link Sdk}
- * objects, and therefore is static.
- * <p/>The value returned by {@link ProjectState#getTarget()} will change as {@link Sdk} objects
- * are replaced.
- * @param project the request project
- * @return the ProjectState for the project.
- */
- @Nullable
- @SuppressWarnings("deprecation")
- public static ProjectState getProjectState(IProject project) {
- if (project == null) {
- return null;
- }
-
- synchronized (LOCK) {
- ProjectState state = sProjectStateMap.get(project);
- if (state == null) {
- // load the project.properties from the project folder.
- IPath location = project.getLocation();
- if (location == null) { // can return null when the project is being deleted.
- // do nothing and return null;
- return null;
- }
-
- String projectLocation = location.toOSString();
-
- ProjectProperties properties = ProjectProperties.load(projectLocation,
- PropertyType.PROJECT);
- if (properties == null) {
- // legacy support: look for default.properties and rename it if needed.
- properties = ProjectProperties.load(projectLocation,
- PropertyType.LEGACY_DEFAULT);
-
- if (properties == null) {
- AdtPlugin.log(IStatus.ERROR,
- "Failed to load properties file for project '%s'",
- project.getName());
- return null;
- } else {
- //legacy mode.
- // get a working copy with the new type "project"
- ProjectPropertiesWorkingCopy wc = properties.makeWorkingCopy(
- PropertyType.PROJECT);
- // and save it
- try {
- wc.save();
-
- // delete the old file.
- ProjectProperties.delete(projectLocation, PropertyType.LEGACY_DEFAULT);
-
- // make sure to use the new properties
- properties = ProjectProperties.load(projectLocation,
- PropertyType.PROJECT);
- } catch (Exception e) {
- AdtPlugin.log(IStatus.ERROR,
- "Failed to rename properties file to %1$s for project '%s2$'",
- PropertyType.PROJECT.getFilename(), project.getName());
- }
- }
- }
-
- state = new ProjectState(project, properties);
- sProjectStateMap.put(project, state);
-
- // try to resolve the target
- if (AdtPlugin.getDefault().getSdkLoadStatus() == LoadStatus.LOADED) {
- sCurrentSdk.loadTargetAndBuildTools(state);
- }
- }
-
- return state;
- }
- }
-
- /**
- * Returns the {@link IAndroidTarget} object associated with the given {@link IProject}.
- */
- @Nullable
- public IAndroidTarget getTarget(IProject project) {
- if (project == null) {
- return null;
- }
-
- ProjectState state = getProjectState(project);
- if (state != null) {
- return state.getTarget();
- }
-
- return null;
- }
-
- /**
- * Loads the {@link IAndroidTarget} and BuildTools for a given project.
- * <p/>This method will get the target hash string from the project properties, and resolve
- * it to an {@link IAndroidTarget} object and store it inside the {@link ProjectState}.
- * @param state the state representing the project to load.
- * @return the target that was loaded.
- */
- @Nullable
- public IAndroidTarget loadTargetAndBuildTools(ProjectState state) {
- IAndroidTarget target = null;
- if (state != null) {
- String hash = state.getTargetHashString();
- if (hash != null) {
- state.setTarget(target = getTargetFromHashString(hash));
- }
-
- String markerMessage = null;
- String buildToolInfoVersion = state.getBuildToolInfoVersion();
- if (buildToolInfoVersion != null) {
- BuildToolInfo buildToolsInfo = getBuildToolInfo(buildToolInfoVersion);
-
- if (buildToolsInfo != null) {
- state.setBuildToolInfo(buildToolsInfo);
- } else {
- markerMessage = String.format("Unable to resolve %s property value '%s'",
- ProjectProperties.PROPERTY_BUILD_TOOLS,
- buildToolInfoVersion);
- }
- } else {
- // this is ok, we'll use the latest one automatically.
- state.setBuildToolInfo(null);
- }
-
- handleBuildToolsMarker(state.getProject(), markerMessage);
- }
-
- return target;
- }
-
- /**
- * Adds or edit a build tools marker from the given project. This is done through a Job.
- * @param project the project
- * @param markerMessage the message. if null the marker is removed.
- */
- private void handleBuildToolsMarker(final IProject project, final String markerMessage) {
- Job markerJob = new Job("Android SDK: Build Tools Marker") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- if (project.isAccessible()) {
- // always delete existing marker first
- project.deleteMarkers(AdtConstants.MARKER_BUILD_TOOLS, true,
- IResource.DEPTH_ZERO);
-
- // add the new one if needed.
- if (markerMessage != null) {
- BaseProjectHelper.markProject(project,
- AdtConstants.MARKER_BUILD_TOOLS,
- markerMessage, IMarker.SEVERITY_ERROR,
- IMarker.PRIORITY_HIGH);
- }
- }
- } catch (CoreException e2) {
- AdtPlugin.log(e2, null);
- // Don't return e2.getStatus(); the job control will then produce
- // a popup with this error, which isn't very interesting for the
- // user.
- }
-
- return Status.OK_STATUS;
- }
- };
-
- // build jobs are run after other interactive jobs
- markerJob.setPriority(Job.BUILD);
- markerJob.setRule(ResourcesPlugin.getWorkspace().getRoot());
- markerJob.schedule();
- }
-
- /**
- * Checks and loads (if needed) the data for a given target.
- * <p/> The data is loaded in a separate {@link Job}, and opened editors will be notified
- * through their implementation of {@link ITargetChangeListener#onTargetLoaded(IAndroidTarget)}.
- * <p/>An optional project as second parameter can be given to be recompiled once the target
- * data is finished loading.
- * <p/>The return value is non-null only if the target data has already been loaded (and in this
- * case is the status of the load operation)
- * @param target the target to load.
- * @param project an optional project to be recompiled when the target data is loaded.
- * If the target is already loaded, nothing happens.
- * @return The load status if the target data is already loaded.
- */
- @NonNull
- public LoadStatus checkAndLoadTargetData(final IAndroidTarget target, IJavaProject project) {
- boolean loadData = false;
-
- synchronized (LOCK) {
- if (mDontLoadTargetData) {
- return LoadStatus.FAILED;
- }
-
- TargetLoadBundle bundle = mTargetDataStatusMap.get(target);
- if (bundle == null) {
- bundle = new TargetLoadBundle();
- mTargetDataStatusMap.put(target,bundle);
-
- // set status to loading
- bundle.status = LoadStatus.LOADING;
-
- // add project to bundle
- if (project != null) {
- bundle.projectsToReload.add(project);
- }
-
- // and set the flag to start the loading below
- loadData = true;
- } else if (bundle.status == LoadStatus.LOADING) {
- // add project to bundle
- if (project != null) {
- bundle.projectsToReload.add(project);
- }
-
- return bundle.status;
- } else if (bundle.status == LoadStatus.LOADED || bundle.status == LoadStatus.FAILED) {
- return bundle.status;
- }
- }
-
- if (loadData) {
- Job job = new Job(String.format("Loading data for %1$s", target.getFullName())) {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- AdtPlugin plugin = AdtPlugin.getDefault();
- try {
- IStatus status = new AndroidTargetParser(target).run(monitor);
-
- IJavaProject[] javaProjectArray = null;
-
- synchronized (LOCK) {
- TargetLoadBundle bundle = mTargetDataStatusMap.get(target);
-
- if (status.getCode() != IStatus.OK) {
- bundle.status = LoadStatus.FAILED;
- bundle.projectsToReload.clear();
- } else {
- bundle.status = LoadStatus.LOADED;
-
- // Prepare the array of project to recompile.
- // The call is done outside of the synchronized block.
- javaProjectArray = bundle.projectsToReload.toArray(
- new IJavaProject[bundle.projectsToReload.size()]);
-
- // and update the UI of the editors that depend on the target data.
- plugin.updateTargetListeners(target);
- }
- }
-
- if (javaProjectArray != null) {
- ProjectHelper.updateProjects(javaProjectArray);
- }
-
- return status;
- } catch (Throwable t) {
- synchronized (LOCK) {
- TargetLoadBundle bundle = mTargetDataStatusMap.get(target);
- bundle.status = LoadStatus.FAILED;
- }
-
- AdtPlugin.log(t, "Exception in checkAndLoadTargetData."); //$NON-NLS-1$
- String message = String.format("Parsing Data for %1$s failed", target.hashString());
- if (t instanceof UnsupportedClassVersionError) {
- message = "To use this platform, run Eclipse with JDK 7 or later. (" + message + ")";
- }
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, message, t);
- }
- }
- };
- job.setPriority(Job.BUILD); // build jobs are run after other interactive jobs
- job.setRule(ResourcesPlugin.getWorkspace().getRoot());
- job.schedule();
- }
-
- // The only way to go through here is when the loading starts through the Job.
- // Therefore the current status of the target is LOADING.
- return LoadStatus.LOADING;
- }
-
- /**
- * Return the {@link AndroidTargetData} for a given {@link IAndroidTarget}.
- */
- @Nullable
- public AndroidTargetData getTargetData(IAndroidTarget target) {
- synchronized (LOCK) {
- return mTargetDataMap.get(target);
- }
- }
-
- /**
- * Return the {@link AndroidTargetData} for a given {@link IProject}.
- */
- @Nullable
- public AndroidTargetData getTargetData(IProject project) {
- synchronized (LOCK) {
- IAndroidTarget target = getTarget(project);
- if (target != null) {
- return getTargetData(target);
- }
- }
-
- return null;
- }
-
- /**
- * Returns a {@link DexWrapper} object to be used to execute dx commands. If dx.jar was not
- * loaded properly, then this will return <code>null</code>.
- */
- @Nullable
- public DexWrapper getDexWrapper(@Nullable BuildToolInfo buildToolInfo) {
- if (buildToolInfo == null) {
- return null;
- }
- synchronized (LOCK) {
- String dexLocation = buildToolInfo.getPath(BuildToolInfo.PathId.DX_JAR);
- DexWrapper dexWrapper = mDexWrappers.get(dexLocation);
-
- if (dexWrapper == null) {
- // load DX.
- dexWrapper = new DexWrapper();
- IStatus res = dexWrapper.loadDex(dexLocation);
- if (res != Status.OK_STATUS) {
- AdtPlugin.log(null, res.getMessage());
- dexWrapper = null;
- } else {
- mDexWrappers.put(dexLocation, dexWrapper);
- }
- }
-
- return dexWrapper;
- }
- }
-
- public void unloadDexWrappers() {
- synchronized (LOCK) {
- for (DexWrapper wrapper : mDexWrappers.values()) {
- wrapper.unload();
- }
- mDexWrappers.clear();
- }
- }
-
- /**
- * Returns the {@link AvdManager}. If the AvdManager failed to parse the AVD folder, this could
- * be <code>null</code>.
- */
- @Nullable
- public AvdManager getAvdManager() {
- return mAvdManager;
- }
-
- @Nullable
- public static AndroidVersion getDeviceVersion(@NonNull IDevice device) {
- try {
- Map<String, String> props = device.getProperties();
- String apiLevel = props.get(IDevice.PROP_BUILD_API_LEVEL);
- if (apiLevel == null) {
- return null;
- }
-
- return new AndroidVersion(Integer.parseInt(apiLevel),
- props.get((IDevice.PROP_BUILD_CODENAME)));
- } catch (NumberFormatException e) {
- return null;
- }
- }
-
- @NonNull
- public DeviceManager getDeviceManager() {
- return mDeviceManager;
- }
-
- /**
- * Returns a list of {@link ProjectState} representing projects depending, directly or
- * indirectly on a given library project.
- * @param project the library project.
- * @return a possibly empty list of ProjectState.
- */
- @NonNull
- public static Set<ProjectState> getMainProjectsFor(IProject project) {
- synchronized (LOCK) {
- // first get the project directly depending on this.
- Set<ProjectState> list = new HashSet<ProjectState>();
-
- // loop on all project and see if ProjectState.getLibrary returns a non null
- // project.
- for (Entry<IProject, ProjectState> entry : sProjectStateMap.entrySet()) {
- if (project != entry.getKey()) {
- LibraryState library = entry.getValue().getLibrary(project);
- if (library != null) {
- list.add(entry.getValue());
- }
- }
- }
-
- // now look for projects depending on the projects directly depending on the library.
- HashSet<ProjectState> result = new HashSet<ProjectState>(list);
- for (ProjectState p : list) {
- if (p.isLibrary()) {
- Set<ProjectState> set = getMainProjectsFor(p.getProject());
- result.addAll(set);
- }
- }
-
- return result;
- }
- }
-
- /**
- * Unload the SDK's target data.
- *
- * If <var>preventReload</var>, this effect is final until the SDK instance is changed
- * through {@link #loadSdk(String)}.
- *
- * The goal is to unload the targets to be able to replace existing targets with new ones,
- * before calling {@link #loadSdk(String)} to fully reload the SDK.
- *
- * @param preventReload prevent the data from being loaded again for the remaining live of
- * this {@link Sdk} instance.
- */
- public void unloadTargetData(boolean preventReload) {
- synchronized (LOCK) {
- mDontLoadTargetData = preventReload;
-
- // dispose of the target data.
- for (AndroidTargetData data : mTargetDataMap.values()) {
- data.dispose();
- }
-
- mTargetDataMap.clear();
- }
- }
-
- private Sdk(SdkManager manager, AvdManager avdManager) {
- mManager = manager;
- mAvdManager = avdManager;
-
- // listen to projects closing
- GlobalProjectMonitor monitor = GlobalProjectMonitor.getMonitor();
- // need to register the resource event listener first because the project listener
- // is called back during registration with project opened in the workspace.
- monitor.addResourceEventListener(mResourceEventListener);
- monitor.addProjectListener(mProjectListener);
- monitor.addFileListener(mFileListener,
- IResourceDelta.CHANGED | IResourceDelta.ADDED | IResourceDelta.REMOVED);
-
- // pre-compute some paths
- mDocBaseUrl = getDocumentationBaseUrl(manager.getLocation() +
- SdkConstants.OS_SDK_DOCS_FOLDER);
-
- mDeviceManager = DeviceManager.createInstance(manager.getLocalSdk().getLocation(),
- AdtPlugin.getDefault());
-
- // update whatever ProjectState is already present with new IAndroidTarget objects.
- synchronized (LOCK) {
- for (Entry<IProject, ProjectState> entry: sProjectStateMap.entrySet()) {
- loadTargetAndBuildTools(entry.getValue());
- }
- }
- }
-
- /**
- * Cleans and unloads the SDK.
- */
- private void dispose() {
- GlobalProjectMonitor monitor = GlobalProjectMonitor.getMonitor();
- monitor.removeProjectListener(mProjectListener);
- monitor.removeFileListener(mFileListener);
- monitor.removeResourceEventListener(mResourceEventListener);
-
- // the IAndroidTarget objects are now obsolete so update the project states.
- synchronized (LOCK) {
- for (Entry<IProject, ProjectState> entry: sProjectStateMap.entrySet()) {
- entry.getValue().setTarget(null);
- }
-
- // dispose of the target data.
- for (AndroidTargetData data : mTargetDataMap.values()) {
- data.dispose();
- }
-
- mTargetDataMap.clear();
- }
- }
-
- void setTargetData(IAndroidTarget target, AndroidTargetData data) {
- synchronized (LOCK) {
- mTargetDataMap.put(target, data);
- }
- }
-
- /**
- * Returns the URL to the local documentation.
- * Can return null if no documentation is found in the current SDK.
- *
- * @param osDocsPath Path to the documentation folder in the current SDK.
- * The folder may not actually exist.
- * @return A file:// URL on the local documentation folder if it exists or null.
- */
- private String getDocumentationBaseUrl(String osDocsPath) {
- File f = new File(osDocsPath);
-
- if (f.isDirectory()) {
- try {
- // Note: to create a file:// URL, one would typically use something like
- // f.toURI().toURL().toString(). However this generates a broken path on
- // Windows, namely "C:\\foo" is converted to "file:/C:/foo" instead of
- // "file:///C:/foo" (i.e. there should be 3 / after "file:"). So we'll
- // do the correct thing manually.
-
- String path = f.getAbsolutePath();
- if (File.separatorChar != '/') {
- path = path.replace(File.separatorChar, '/');
- }
-
- // For some reason the URL class doesn't add the mandatory "//" after
- // the "file:" protocol name, so it has to be hacked into the path.
- URL url = new URL("file", null, "//" + path); //$NON-NLS-1$ //$NON-NLS-2$
- String result = url.toString();
- return result;
- } catch (MalformedURLException e) {
- // ignore malformed URLs
- }
- }
-
- return null;
- }
-
- /**
- * Delegate listener for project changes.
- */
- private IProjectListener mProjectListener = new IProjectListener() {
- @Override
- public void projectClosed(IProject project) {
- onProjectRemoved(project, false /*deleted*/);
- }
-
- @Override
- public void projectDeleted(IProject project) {
- onProjectRemoved(project, true /*deleted*/);
- }
-
- private void onProjectRemoved(IProject removedProject, boolean deleted) {
- if (DEBUG) {
- System.out.println(">>> CLOSED: " + removedProject.getName());
- }
-
- // get the target project
- synchronized (LOCK) {
- // Don't use getProject() as it could create the ProjectState if it's not
- // there yet and this is not what we want. We want the current object.
- // Therefore, direct access to the map.
- ProjectState removedState = sProjectStateMap.get(removedProject);
- if (removedState != null) {
- // 1. clear the layout lib cache associated with this project
- IAndroidTarget target = removedState.getTarget();
- if (target != null) {
- // get the bridge for the target, and clear the cache for this project.
- AndroidTargetData data = mTargetDataMap.get(target);
- if (data != null) {
- LayoutLibrary layoutLib = data.getLayoutLibrary();
- if (layoutLib != null && layoutLib.getStatus() == LoadStatus.LOADED) {
- layoutLib.clearCaches(removedProject);
- }
- }
- }
-
- // 2. if the project is a library, make sure to update the
- // LibraryState for any project referencing it.
- // Also, record the updated projects that are libraries, to update
- // projects that depend on them.
- for (ProjectState projectState : sProjectStateMap.values()) {
- LibraryState libState = projectState.getLibrary(removedProject);
- if (libState != null) {
- // Close the library right away.
- // This remove links between the LibraryState and the projectState.
- // This is because in case of a rename of a project, projectClosed and
- // projectOpened will be called before any other job is run, so we
- // need to make sure projectOpened is closed with the main project
- // state up to date.
- libState.close();
-
- // record that this project changed, and in case it's a library
- // that its parents need to be updated as well.
- markProject(projectState, projectState.isLibrary());
- }
- }
-
- // now remove the project for the project map.
- sProjectStateMap.remove(removedProject);
- }
- }
-
- if (DEBUG) {
- System.out.println("<<<");
- }
- }
-
- @Override
- public void projectOpened(IProject project) {
- onProjectOpened(project);
- }
-
- @Override
- public void projectOpenedWithWorkspace(IProject project) {
- // no need to force recompilation when projects are opened with the workspace.
- onProjectOpened(project);
- }
-
- @Override
- public void allProjectsOpenedWithWorkspace() {
- // Correct currently open editors
- fixOpenLegacyEditors();
- }
-
- private void onProjectOpened(final IProject openedProject) {
-
- ProjectState openedState = getProjectState(openedProject);
- if (openedState != null) {
- if (DEBUG) {
- System.out.println(">>> OPENED: " + openedProject.getName());
- }
-
- synchronized (LOCK) {
- final boolean isLibrary = openedState.isLibrary();
- final boolean hasLibraries = openedState.hasLibraries();
-
- if (isLibrary || hasLibraries) {
- boolean foundLibraries = false;
- // loop on all the existing project and update them based on this new
- // project
- for (ProjectState projectState : sProjectStateMap.values()) {
- if (projectState != openedState) {
- // If the project has libraries, check if this project
- // is a reference.
- if (hasLibraries) {
- // ProjectState#needs() both checks if this is a missing library
- // and updates LibraryState to contains the new values.
- // This must always be called.
- LibraryState libState = openedState.needs(projectState);
-
- if (libState != null) {
- // found a library! Add the main project to the list of
- // modified project
- foundLibraries = true;
- }
- }
-
- // if the project is a library check if the other project depend
- // on it.
- if (isLibrary) {
- // ProjectState#needs() both checks if this is a missing library
- // and updates LibraryState to contains the new values.
- // This must always be called.
- LibraryState libState = projectState.needs(openedState);
-
- if (libState != null) {
- // There's a dependency! Add the project to the list of
- // modified project, but also to a list of projects
- // that saw one of its dependencies resolved.
- markProject(projectState, projectState.isLibrary());
- }
- }
- }
- }
-
- // if the project has a libraries and we found at least one, we add
- // the project to the list of modified project.
- // Since we already went through the parent, no need to update them.
- if (foundLibraries) {
- markProject(openedState, false /*updateParents*/);
- }
- }
- }
-
- // Correct file editor associations.
- fixEditorAssociations(openedProject);
-
- // Fix classpath entries in a job since the workspace might be locked now.
- Job fixCpeJob = new Job("Adjusting Android Project Classpath") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- ProjectHelper.fixProjectClasspathEntries(
- JavaCore.create(openedProject));
- } catch (JavaModelException e) {
- AdtPlugin.log(e, "error fixing classpath entries");
- // Don't return e2.getStatus(); the job control will then produce
- // a popup with this error, which isn't very interesting for the
- // user.
- }
-
- return Status.OK_STATUS;
- }
- };
-
- // build jobs are run after other interactive jobs
- fixCpeJob.setPriority(Job.BUILD);
- fixCpeJob.setRule(ResourcesPlugin.getWorkspace().getRoot());
- fixCpeJob.schedule();
-
-
- if (DEBUG) {
- System.out.println("<<<");
- }
- }
- }
-
- @Override
- public void projectRenamed(IProject project, IPath from) {
- // we don't actually care about this anymore.
- }
- };
-
- /**
- * Delegate listener for file changes.
- */
- private IFileListener mFileListener = new IFileListener() {
- @Override
- public void fileChanged(final @NonNull IFile file, @NonNull IMarkerDelta[] markerDeltas,
- int kind, @Nullable String extension, int flags, boolean isAndroidPRoject) {
- if (!isAndroidPRoject) {
- return;
- }
-
- if (SdkConstants.FN_PROJECT_PROPERTIES.equals(file.getName()) &&
- file.getParent() == file.getProject()) {
- try {
- // reload the content of the project.properties file and update
- // the target.
- IProject iProject = file.getProject();
-
- ProjectState state = Sdk.getProjectState(iProject);
-
- // get the current target and build tools
- IAndroidTarget oldTarget = state.getTarget();
- boolean oldRsSupportMode = state.getRenderScriptSupportMode();
-
- // get the current library flag
- boolean wasLibrary = state.isLibrary();
-
- LibraryDifference diff = state.reloadProperties();
-
- // load the (possibly new) target.
- IAndroidTarget newTarget = loadTargetAndBuildTools(state);
-
- // reload the libraries if needed
- if (diff.hasDiff()) {
- if (diff.added) {
- synchronized (LOCK) {
- for (ProjectState projectState : sProjectStateMap.values()) {
- if (projectState != state) {
- // need to call needs to do the libraryState link,
- // but no need to look at the result, as we'll compare
- // the result of getFullLibraryProjects()
- // this is easier to due to indirect dependencies.
- state.needs(projectState);
- }
- }
- }
- }
-
- markProject(state, wasLibrary || state.isLibrary());
- }
-
- // apply the new target if needed.
- if (newTarget != oldTarget ||
- oldRsSupportMode != state.getRenderScriptSupportMode()) {
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(
- file.getProject());
- if (javaProject != null) {
- ProjectHelper.updateProject(javaProject);
- }
-
- // update the editors to reload with the new target
- AdtPlugin.getDefault().updateTargetListeners(iProject);
- }
- } catch (CoreException e) {
- // This can't happen as it's only for closed project (or non existing)
- // but in that case we can't get a fileChanged on this file.
- }
- } else if (kind == IResourceDelta.ADDED || kind == IResourceDelta.REMOVED) {
- // check if it's an add/remove on a jar files inside libs
- if (EXT_JAR.equals(extension) &&
- file.getProjectRelativePath().segmentCount() == 2 &&
- file.getParent().getName().equals(SdkConstants.FD_NATIVE_LIBS)) {
- // need to update the project and whatever depend on it.
-
- processJarFileChange(file);
- }
- }
- }
-
- private void processJarFileChange(final IFile file) {
- try {
- IProject iProject = file.getProject();
-
- if (iProject.hasNature(AdtConstants.NATURE_DEFAULT) == false) {
- return;
- }
-
- List<IJavaProject> projectList = new ArrayList<IJavaProject>();
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(iProject);
- if (javaProject != null) {
- projectList.add(javaProject);
- }
-
- ProjectState state = Sdk.getProjectState(iProject);
-
- if (state != null) {
- Collection<ProjectState> parents = state.getFullParentProjects();
- for (ProjectState s : parents) {
- javaProject = BaseProjectHelper.getJavaProject(s.getProject());
- if (javaProject != null) {
- projectList.add(javaProject);
- }
- }
-
- ProjectHelper.updateProjects(
- projectList.toArray(new IJavaProject[projectList.size()]));
- }
- } catch (CoreException e) {
- // This can't happen as it's only for closed project (or non existing)
- // but in that case we can't get a fileChanged on this file.
- }
- }
- };
-
- /** List of modified projects. This is filled in
- * {@link IProjectListener#projectOpened(IProject)},
- * {@link IProjectListener#projectOpenedWithWorkspace(IProject)},
- * {@link IProjectListener#projectClosed(IProject)}, and
- * {@link IProjectListener#projectDeleted(IProject)} and processed in
- * {@link IResourceEventListener#resourceChangeEventEnd()}.
- */
- private final List<ProjectState> mModifiedProjects = new ArrayList<ProjectState>();
- private final List<ProjectState> mModifiedChildProjects = new ArrayList<ProjectState>();
-
- private void markProject(ProjectState projectState, boolean updateParents) {
- if (mModifiedProjects.contains(projectState) == false) {
- if (DEBUG) {
- System.out.println("\tMARKED: " + projectState.getProject().getName());
- }
- mModifiedProjects.add(projectState);
- }
-
- // if the project is resolved also add it to this list.
- if (updateParents) {
- if (mModifiedChildProjects.contains(projectState) == false) {
- if (DEBUG) {
- System.out.println("\tMARKED(child): " + projectState.getProject().getName());
- }
- mModifiedChildProjects.add(projectState);
- }
- }
- }
-
- /**
- * Delegate listener for resource changes. This is called before and after any calls to the
- * project and file listeners (for a given resource change event).
- */
- private IResourceEventListener mResourceEventListener = new IResourceEventListener() {
- @Override
- public void resourceChangeEventStart() {
- mModifiedProjects.clear();
- mModifiedChildProjects.clear();
- }
-
- @Override
- public void resourceChangeEventEnd() {
- if (mModifiedProjects.size() == 0) {
- return;
- }
-
- // first make sure all the parents are updated
- updateParentProjects();
-
- // for all modified projects, update their library list
- // and gather their IProject
- final List<IJavaProject> projectList = new ArrayList<IJavaProject>();
- for (ProjectState state : mModifiedProjects) {
- state.updateFullLibraryList();
- projectList.add(JavaCore.create(state.getProject()));
- }
-
- Job job = new Job("Android Library Update") { //$NON-NLS-1$
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- LibraryClasspathContainerInitializer.updateProjects(
- projectList.toArray(new IJavaProject[projectList.size()]));
-
- for (IJavaProject javaProject : projectList) {
- try {
- javaProject.getProject().build(IncrementalProjectBuilder.FULL_BUILD,
- monitor);
- } catch (CoreException e) {
- // pass
- }
- }
- return Status.OK_STATUS;
- }
- };
- job.setPriority(Job.BUILD);
- job.setRule(ResourcesPlugin.getWorkspace().getRoot());
- job.schedule();
- }
- };
-
- /**
- * Updates all existing projects with a given list of new/updated libraries.
- * This loops through all opened projects and check if they depend on any of the given
- * library project, and if they do, they are linked together.
- */
- private void updateParentProjects() {
- if (mModifiedChildProjects.size() == 0) {
- return;
- }
-
- ArrayList<ProjectState> childProjects = new ArrayList<ProjectState>(mModifiedChildProjects);
- mModifiedChildProjects.clear();
- synchronized (LOCK) {
- // for each project for which we must update its parent, we loop on the parent
- // projects and adds them to the list of modified projects. If they are themselves
- // libraries, we add them too.
- for (ProjectState state : childProjects) {
- if (DEBUG) {
- System.out.println(">>> Updating parents of " + state.getProject().getName());
- }
- List<ProjectState> parents = state.getParentProjects();
- for (ProjectState parent : parents) {
- markProject(parent, parent.isLibrary());
- }
- if (DEBUG) {
- System.out.println("<<<");
- }
- }
- }
-
- // done, but there may be parents that are also libraries. Need to update their parents.
- updateParentProjects();
- }
-
- /**
- * Fix editor associations for the given project, if not already done.
- * <p/>
- * Eclipse has a per-file setting for which editor should be used for each file
- * (see {@link IDE#setDefaultEditor(IFile, String)}).
- * We're using this flag to pick between the various XML editors (layout, drawable, etc)
- * since they all have the same file name extension.
- * <p/>
- * Unfortunately, the file setting can be "wrong" for two reasons:
- * <ol>
- * <li> The editor type was added <b>after</b> a file had been seen by the IDE.
- * For example, we added new editors for animations and for drawables around
- * ADT 12, but any file seen by ADT in earlier versions will continue to use
- * the vanilla Eclipse XML editor instead.
- * <li> A bug in ADT 14 and ADT 15 (see issue 21124) meant that files created in new
- * folders would end up with wrong editor associations. Even though that bug
- * is fixed in ADT 16, the fix only affects new files, it cannot retroactively
- * fix editor associations that were set incorrectly by ADT 14 or 15.
- * </ol>
- * <p/>
- * This method attempts to fix the editor bindings retroactively by scanning all the
- * resource XML files and resetting the editor associations.
- * Since this is a potentially slow operation, this is only done "once"; we use a
- * persistent project property to avoid looking repeatedly. In the future if we add
- * additional editors, we can rev the scanned version value.
- */
- private void fixEditorAssociations(final IProject project) {
- QualifiedName KEY = new QualifiedName(AdtPlugin.PLUGIN_ID, "editorbinding"); //$NON-NLS-1$
-
- try {
- String value = project.getPersistentProperty(KEY);
- int currentVersion = 0;
- if (value != null) {
- try {
- currentVersion = Integer.parseInt(value);
- } catch (Exception ingore) {
- }
- }
-
- // The target version we're comparing to. This must be incremented each time
- // we change the processing here so that a new version of the plugin would
- // try to fix existing user projects.
- final int targetVersion = 2;
-
- if (currentVersion >= targetVersion) {
- return;
- }
-
- // Set to specific version such that we can rev the version in the future
- // to trigger further scanning
- project.setPersistentProperty(KEY, Integer.toString(targetVersion));
-
- // Now update the actual editor associations.
- Job job = new Job("Update Android editor bindings") { //$NON-NLS-1$
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- for (IResource folderResource : project.getFolder(FD_RES).members()) {
- if (folderResource instanceof IFolder) {
- IFolder folder = (IFolder) folderResource;
-
- for (IResource resource : folder.members()) {
- if (resource instanceof IFile &&
- resource.getName().endsWith(DOT_XML)) {
- fixXmlFile((IFile) resource);
- }
- }
- }
- }
-
- // TODO change AndroidManifest.xml ID too
-
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
-
- return Status.OK_STATUS;
- }
-
- /**
- * Attempt to fix the editor ID for the given /res XML file.
- */
- private void fixXmlFile(final IFile file) {
- // Fix the default editor ID for this resource.
- // This has no effect on currently open editors.
- IEditorDescriptor desc = IDE.getDefaultEditor(file);
-
- if (desc == null || !CommonXmlEditor.ID.equals(desc.getId())) {
- IDE.setDefaultEditor(file, CommonXmlEditor.ID);
- }
- }
- };
- job.setPriority(Job.BUILD);
- job.schedule();
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- }
-
- /**
- * Tries to fix all currently open Android legacy editors.
- * <p/>
- * If an editor is found to match one of the legacy ids, we'll try to close it.
- * If that succeeds, we try to reopen it using the new common editor ID.
- * <p/>
- * This method must be run from the UI thread.
- */
- private void fixOpenLegacyEditors() {
-
- AdtPlugin adt = AdtPlugin.getDefault();
- if (adt == null) {
- return;
- }
-
- final IPreferenceStore store = adt.getPreferenceStore();
- int currentValue = store.getInt(AdtPrefs.PREFS_FIX_LEGACY_EDITORS);
- // The target version we're comparing to. This must be incremented each time
- // we change the processing here so that a new version of the plugin would
- // try to fix existing editors.
- final int targetValue = 1;
-
- if (currentValue >= targetValue) {
- return;
- }
-
- // To be able to close and open editors we need to make sure this is done
- // in the UI thread, which this isn't invoked from.
- PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- HashSet<String> legacyIds =
- new HashSet<String>(Arrays.asList(CommonXmlEditor.LEGACY_EDITOR_IDS));
-
- for (IWorkbenchWindow win : PlatformUI.getWorkbench().getWorkbenchWindows()) {
- for (IWorkbenchPage page : win.getPages()) {
- for (IEditorReference ref : page.getEditorReferences()) {
- try {
- IEditorInput input = ref.getEditorInput();
- if (input instanceof IFileEditorInput) {
- IFile file = ((IFileEditorInput)input).getFile();
- IEditorPart part = ref.getEditor(true /*restore*/);
- if (part != null) {
- IWorkbenchPartSite site = part.getSite();
- if (site != null) {
- String id = site.getId();
- if (legacyIds.contains(id)) {
- // This editor matches one of legacy editor IDs.
- fixEditor(page, part, input, file, id);
- }
- }
- }
- }
- } catch (Exception e) {
- // ignore
- }
- }
- }
- }
-
- // Remember that we managed to do fix all editors
- store.setValue(AdtPrefs.PREFS_FIX_LEGACY_EDITORS, targetValue);
- }
-
- private void fixEditor(
- IWorkbenchPage page,
- IEditorPart part,
- IEditorInput input,
- IFile file,
- String id) {
- IDE.setDefaultEditor(file, CommonXmlEditor.ID);
-
- boolean ok = page.closeEditor(part, true /*save*/);
-
- AdtPlugin.log(IStatus.INFO,
- "Closed legacy editor ID %s for %s: %s", //$NON-NLS-1$
- id,
- file.getFullPath(),
- ok ? "Success" : "Failed");//$NON-NLS-1$ //$NON-NLS-2$
-
- if (ok) {
- // Try to reopen it with the new ID
- try {
- page.openEditor(input, CommonXmlEditor.ID);
- } catch (PartInitException e) {
- AdtPlugin.log(e,
- "Failed to reopen %s", //$NON-NLS-1$
- file.getFullPath());
- }
- }
- }
- });
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/WidgetClassLoader.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/WidgetClassLoader.java
deleted file mode 100644
index 682d6e538..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/WidgetClassLoader.java
+++ /dev/null
@@ -1,343 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.sdk;
-
-import com.android.SdkConstants;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-
-import java.io.BufferedReader;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.TreeMap;
-
-import javax.management.InvalidAttributeValueException;
-
-/**
- * Parser for the text file containing the list of widgets, layouts and layout params.
- * <p/>
- * The file is a straight text file containing one class per line.<br>
- * Each line is in the following format<br>
- * <code>[code][class name] [super class name] [super class name]...</code>
- * where code is a single letter (W for widget, L for layout, P for layout params), and class names
- * are the fully qualified name of the classes.
- */
-public final class WidgetClassLoader implements IAndroidClassLoader {
-
- /**
- * Basic class containing the class descriptions found in the text file.
- */
- private final static class ClassDescriptor implements IClassDescriptor {
-
- private String mFqcn;
- private String mSimpleName;
- private ClassDescriptor mSuperClass;
- private ClassDescriptor mEnclosingClass;
- private final ArrayList<IClassDescriptor> mDeclaredClasses =
- new ArrayList<IClassDescriptor>();
- private boolean mIsInstantiable = false;
-
- ClassDescriptor(String fqcn) {
- mFqcn = fqcn;
- mSimpleName = getSimpleName(fqcn);
- }
-
- @Override
- public String getFullClassName() {
- return mFqcn;
- }
-
- @Override
- public String getSimpleName() {
- return mSimpleName;
- }
-
- @Override
- public IClassDescriptor[] getDeclaredClasses() {
- return mDeclaredClasses.toArray(new IClassDescriptor[mDeclaredClasses.size()]);
- }
-
- private void addDeclaredClass(ClassDescriptor declaredClass) {
- mDeclaredClasses.add(declaredClass);
- }
-
- @Override
- public IClassDescriptor getEnclosingClass() {
- return mEnclosingClass;
- }
-
- void setEnclosingClass(ClassDescriptor enclosingClass) {
- // set the enclosing class.
- mEnclosingClass = enclosingClass;
-
- // add this to the list of declared class in the enclosing class.
- mEnclosingClass.addDeclaredClass(this);
-
- // finally change the name of declared class to make sure it uses the
- // convention: package.enclosing$declared instead of package.enclosing.declared
- mFqcn = enclosingClass.mFqcn + "$" + mFqcn.substring(enclosingClass.mFqcn.length() + 1);
- }
-
- @Override
- public IClassDescriptor getSuperclass() {
- return mSuperClass;
- }
-
- void setSuperClass(ClassDescriptor superClass) {
- mSuperClass = superClass;
- }
-
- @Override
- public boolean equals(Object clazz) {
- if (clazz instanceof ClassDescriptor) {
- return mFqcn.equals(((ClassDescriptor)clazz).mFqcn);
- }
- return super.equals(clazz);
- }
-
- @Override
- public int hashCode() {
- return mFqcn.hashCode();
- }
-
- @Override
- public boolean isInstantiable() {
- return mIsInstantiable;
- }
-
- void setInstantiable(boolean state) {
- mIsInstantiable = state;
- }
-
- private String getSimpleName(String fqcn) {
- String[] segments = fqcn.split("\\.");
- return segments[segments.length-1];
- }
- }
-
- private BufferedReader mReader;
-
- /** Output map of FQCN => descriptor on all classes */
- private final Map<String, ClassDescriptor> mMap = new TreeMap<String, ClassDescriptor>();
- /** Output map of FQCN => descriptor on View classes */
- private final Map<String, ClassDescriptor> mWidgetMap = new TreeMap<String, ClassDescriptor>();
- /** Output map of FQCN => descriptor on ViewGroup classes */
- private final Map<String, ClassDescriptor> mLayoutMap = new TreeMap<String, ClassDescriptor>();
- /** Output map of FQCN => descriptor on LayoutParams classes */
- private final Map<String, ClassDescriptor> mLayoutParamsMap =
- new HashMap<String, ClassDescriptor>();
- /** File path of the source text file */
- private String mOsFilePath;
-
- /**
- * Creates a loader with a given file path.
- * @param osFilePath the OS path of the file to load.
- * @throws FileNotFoundException if the file is not found.
- */
- WidgetClassLoader(String osFilePath) throws FileNotFoundException {
- mOsFilePath = osFilePath;
- mReader = new BufferedReader(new FileReader(osFilePath));
- }
-
- @Override
- public String getSource() {
- return mOsFilePath;
- }
-
- /**
- * Parses the text file and return true if the file was successfully parsed.
- * @param monitor
- */
- boolean parseWidgetList(IProgressMonitor monitor) {
- try {
- String line;
- while ((line = mReader.readLine()) != null) {
- if (line.length() > 0) {
- char prefix = line.charAt(0);
- String[] classes = null;
- ClassDescriptor clazz = null;
- switch (prefix) {
- case 'W':
- classes = line.substring(1).split(" ");
- clazz = processClass(classes, 0, null /* map */);
- if (clazz != null) {
- clazz.setInstantiable(true);
- mWidgetMap.put(classes[0], clazz);
- }
- break;
- case 'L':
- classes = line.substring(1).split(" ");
- clazz = processClass(classes, 0, null /* map */);
- if (clazz != null) {
- clazz.setInstantiable(true);
- mLayoutMap.put(classes[0], clazz);
- }
- break;
- case 'P':
- classes = line.substring(1).split(" ");
- clazz = processClass(classes, 0, mLayoutParamsMap);
- if (clazz != null) {
- clazz.setInstantiable(true);
- }
- break;
- case '#':
- // comment, do nothing
- break;
- default:
- throw new IllegalArgumentException();
- }
- }
- }
-
- // reconciliate the layout and their layout params
- postProcess();
-
- return true;
- } catch (IOException e) {
- } finally {
- try {
- mReader.close();
- } catch (IOException e) {
- }
- }
-
- return false;
- }
-
- /**
- * Parses a View class and adds a ViewClassInfo for it in mWidgetMap.
- * It calls itself recursively to handle super classes which are also Views.
- * @param classes the inheritance list of the class to process.
- * @param index the index of the class to process in the <code>classes</code> array.
- * @param map an optional map in which to put every {@link ClassDescriptor} created.
- */
- private ClassDescriptor processClass(String[] classes, int index,
- Map<String, ClassDescriptor> map) {
- if (index >= classes.length) {
- return null;
- }
-
- String fqcn = classes[index];
-
- if ("java.lang.Object".equals(fqcn)) { //$NON-NLS-1$
- return null;
- }
-
- // check if the ViewInfoClass has not yet been created.
- if (mMap.containsKey(fqcn)) {
- return mMap.get(fqcn);
- }
-
- // create the custom class.
- ClassDescriptor clazz = new ClassDescriptor(fqcn);
- mMap.put(fqcn, clazz);
- if (map != null) {
- map.put(fqcn, clazz);
- }
-
- // get the super class
- ClassDescriptor superClass = processClass(classes, index+1, map);
- if (superClass != null) {
- clazz.setSuperClass(superClass);
- }
-
- return clazz;
- }
-
- /**
- * Goes through the layout params and look for the enclosed class. If the layout params
- * has no known enclosed type it is dropped.
- */
- private void postProcess() {
- Collection<ClassDescriptor> params = mLayoutParamsMap.values();
-
- for (ClassDescriptor param : params) {
- String fqcn = param.getFullClassName();
-
- // get the enclosed name.
- String enclosed = getEnclosedName(fqcn);
-
- // look for a match in the layouts. We don't use the layout map as it only contains the
- // end classes, but in this case we also need to process the layout params for the base
- // layout classes.
- ClassDescriptor enclosingType = mMap.get(enclosed);
- if (enclosingType != null) {
- param.setEnclosingClass(enclosingType);
-
- // remove the class from the map, and put it back with the fixed name
- mMap.remove(fqcn);
- mMap.put(param.getFullClassName(), param);
- }
- }
- }
-
- private String getEnclosedName(String fqcn) {
- int index = fqcn.lastIndexOf('.');
- return fqcn.substring(0, index);
- }
-
- /**
- * Finds and loads all classes that derive from a given set of super classes.
- *
- * @param rootPackage Root package of classes to find. Use an empty string to find everyting.
- * @param superClasses The super classes of all the classes to find.
- * @return An hash map which keys are the super classes looked for and which values are
- * ArrayList of the classes found. The array lists are always created for all the
- * valid keys, they are simply empty if no deriving class is found for a given
- * super class.
- * @throws IOException
- * @throws InvalidAttributeValueException
- * @throws ClassFormatError
- */
- @Override
- public HashMap<String, ArrayList<IClassDescriptor>> findClassesDerivingFrom(String rootPackage,
- String[] superClasses) throws IOException, InvalidAttributeValueException,
- ClassFormatError {
- HashMap<String, ArrayList<IClassDescriptor>> map =
- new HashMap<String, ArrayList<IClassDescriptor>>();
-
- ArrayList<IClassDescriptor> list = new ArrayList<IClassDescriptor>();
- list.addAll(mWidgetMap.values());
- map.put(SdkConstants.CLASS_VIEW, list);
-
- list = new ArrayList<IClassDescriptor>();
- list.addAll(mLayoutMap.values());
- map.put(SdkConstants.CLASS_VIEWGROUP, list);
-
- list = new ArrayList<IClassDescriptor>();
- list.addAll(mLayoutParamsMap.values());
- map.put(SdkConstants.CLASS_VIEWGROUP_LAYOUTPARAMS, list);
-
- return map;
- }
-
- /**
- * Returns a {@link IAndroidClassLoader.IClassDescriptor} by its fully-qualified name.
- * @param className the fully-qualified name of the class to return.
- * @throws ClassNotFoundException
- */
- @Override
- public IClassDescriptor getClass(String className) throws ClassNotFoundException {
- return mMap.get(className);
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/layout-devices.xsd b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/layout-devices.xsd
deleted file mode 100755
index a4ea6c42e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sdk/layout-devices.xsd
+++ /dev/null
@@ -1,345 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
--->
-<xsd:schema
- targetNamespace="http://schemas.android.com/sdk/android/layout-devices/1"
- xmlns:xsd="http://www.w3.org/2001/XMLSchema"
- xmlns:c="http://schemas.android.com/sdk/android/layout-devices/1"
- elementFormDefault="qualified"
- attributeFormDefault="unqualified"
- version="1">
-
- <!-- The root element layout-devices defines a sequence of 0..n device elements. -->
-
- <xsd:element name="layout-devices" type="c:layoutDevicesType" />
-
- <xsd:complexType name="layoutDevicesType">
- <xsd:annotation>
- <xsd:documentation xml:lang="en">
- The "layout-devices" element is the root element of this schema.
-
- It must contain zero or more "device" elements that each define the configurations
- available for a given device.
-
- These definitions are used in the Graphical Layout Editor in the
- Android Development Tools (ADT) plugin for Eclipse.
- </xsd:documentation>
- </xsd:annotation>
-
- <xsd:sequence>
- <!-- layout-devices defines a sequence of 0..n device elements. -->
- <xsd:element name="device" minOccurs="0" maxOccurs="unbounded">
-
- <xsd:annotation>
- <xsd:documentation xml:lang="en">
- A device element must contain at most one "default" element
- followed by one or more "config" elements.
-
- The "default" element defines all the default parameters
- inherited by the following "config" elements.
- Each "config" element can override the default values, if any.
-
- A "device" element also has a required "name" attribute that
- represents the user-interface name of this device.
- </xsd:documentation>
- </xsd:annotation>
-
- <xsd:complexType>
- <!-- device defines a choice of 0..1 default element
- and 1..n config elements. -->
-
- <xsd:sequence>
- <xsd:element name="default" type="c:parametersType"
- minOccurs="0" maxOccurs="1" />
- <xsd:element name="config" type="c:configType"
- minOccurs="1" maxOccurs="unbounded" />
- </xsd:sequence>
-
- <xsd:attribute name="name" type="xsd:normalizedString" use="required" />
- </xsd:complexType>
-
- </xsd:element>
- </xsd:sequence>
- </xsd:complexType>
-
- <!-- The type of a device>default element.
- This is overridden by configType below for the device>config element.
- -->
- <xsd:complexType name="parametersType">
- <xsd:annotation>
- <xsd:documentation xml:lang="en">
- The parametersType define all the parameters that can happen either in a
- "default" element or in a named "config" element.
- Each parameter element can appear once at most.
-
- Parameters here are the same as those used to specify alternate Android
- resources, as documented by
- http://d.android.com/guide/topics/resources/resources-i18n.html#AlternateResources
- </xsd:documentation>
- </xsd:annotation>
-
- <xsd:all>
- <!-- parametersType says that 0..1 of each of these elements must be declared. -->
-
- <xsd:element name="country-code" minOccurs="0">
- <xsd:annotation>
- <xsd:documentation xml:lang="en">
- Specifies the configuration is for a particular Mobile Country Code.
- </xsd:documentation>
- </xsd:annotation>
- <xsd:simpleType>
- <xsd:restriction base="xsd:float">
- <xsd:minInclusive value="100" />
- <xsd:maxInclusive value="999" />
- </xsd:restriction>
- </xsd:simpleType>
- </xsd:element>
-
- <xsd:element name="network-code" minOccurs="0">
- <xsd:annotation>
- <xsd:documentation xml:lang="en">
- Specifies the configuration is for a particular Mobile Network Code.
- </xsd:documentation>
- </xsd:annotation>
- <xsd:simpleType>
- <xsd:restriction base="xsd:float">
- <xsd:minExclusive value="0" />
- <xsd:maxExclusive value="1000" />
- </xsd:restriction>
- </xsd:simpleType>
- </xsd:element>
-
- <xsd:element name="screen-size" minOccurs="0">
- <xsd:annotation>
- <xsd:documentation xml:lang="en">
- Specifies that the configuration is for a particular class of screen.
- </xsd:documentation>
- </xsd:annotation>
- <xsd:simpleType>
- <xsd:restriction base="xsd:token">
- <xsd:enumeration value="small" />
- <xsd:enumeration value="normal" />
- <xsd:enumeration value="large" />
- <xsd:enumeration value="xlarge" />
- </xsd:restriction>
- </xsd:simpleType>
- </xsd:element>
-
- <xsd:element name="screen-ratio" minOccurs="0">
- <xsd:annotation>
- <xsd:documentation xml:lang="en">
- Specifies that the configuration is for a taller/wider than traditional
- screen. This is based purely on the aspect ration of the screen: QVGA,
- HVGA, and VGA are notlong; WQVGA, WVGA, FWVGA are long. Note that long
- may mean either wide or tall, depending on the current orientation.
- </xsd:documentation>
- </xsd:annotation>
- <xsd:simpleType>
- <xsd:restriction base="xsd:token">
- <xsd:enumeration value="long" />
- <xsd:enumeration value="notlong" />
- </xsd:restriction>
- </xsd:simpleType>
- </xsd:element>
-
- <xsd:element name="screen-orientation" minOccurs="0">
- <xsd:annotation>
- <xsd:documentation xml:lang="en">
- Specifies that the configuration is for a screen that is tall (port) or
- wide (land).
- </xsd:documentation>
- </xsd:annotation>
- <xsd:simpleType>
- <xsd:restriction base="xsd:token">
- <xsd:enumeration value="port" />
- <xsd:enumeration value="land" />
- <xsd:enumeration value="square" />
- </xsd:restriction>
- </xsd:simpleType>
- </xsd:element>
-
- <xsd:element name="pixel-density" minOccurs="0">
- <xsd:annotation>
- <xsd:documentation xml:lang="en">
- Specifies the screen density the configuration is defined for. The medium
- density of traditional HVGA screens (mdpi) is defined to be approximately
- 160dpi; low density (ldpi) is 120, and high density (hdpi) is 240. There
- is thus a 4:3 scaling factor between each density, so a 9x9 bitmap in ldpi
- would be 12x12 is mdpi and 16x16 in hdpi.
- The special nodpi density that can be used in resource qualifiers is not
- a valid keyword here.
- </xsd:documentation>
- </xsd:annotation>
- <xsd:simpleType>
- <xsd:restriction base="xsd:token">
- <xsd:enumeration value="ldpi" />
- <xsd:enumeration value="mdpi" />
- <xsd:enumeration value="tvdpi" />
- <xsd:enumeration value="hdpi" />
- <xsd:enumeration value="xhdpi" />
- </xsd:restriction>
- </xsd:simpleType>
- </xsd:element>
-
- <xsd:element name="touch-type" minOccurs="0">
- <xsd:annotation>
- <xsd:documentation xml:lang="en">
- Specifies the touch type the configuration is defined for.
- </xsd:documentation>
- </xsd:annotation>
- <xsd:simpleType>
- <xsd:restriction base="xsd:token">
- <xsd:enumeration value="notouch" />
- <xsd:enumeration value="stylus" />
- <xsd:enumeration value="finger" />
- </xsd:restriction>
- </xsd:simpleType>
- </xsd:element>
-
- <xsd:element name="keyboard-state" minOccurs="0">
- <xsd:annotation>
- <xsd:documentation xml:lang="en">
- If your configuration uses a soft keyboard, use the keyssoft value.
- If it doesn't and has a real keyboard, use keysexposed or keyshidden.
- </xsd:documentation>
- </xsd:annotation>
- <xsd:simpleType>
- <xsd:restriction base="xsd:token">
- <xsd:enumeration value="keysexposed" />
- <xsd:enumeration value="keyshidden" />
- <xsd:enumeration value="keyssoft" />
- </xsd:restriction>
- </xsd:simpleType>
- </xsd:element>
-
- <xsd:element name="text-input-method" minOccurs="0">
- <xsd:annotation>
- <xsd:documentation xml:lang="en">
- Specifies the primary text input method the configuration is designed for.
- </xsd:documentation>
- </xsd:annotation>
- <xsd:simpleType>
- <xsd:restriction base="xsd:token">
- <xsd:enumeration value="nokeys" />
- <xsd:enumeration value="qwerty" />
- <xsd:enumeration value="12key" />
- </xsd:restriction>
- </xsd:simpleType>
- </xsd:element>
-
- <xsd:element name="nav-state" minOccurs="0">
- <xsd:annotation>
- <xsd:documentation xml:lang="en">
- Specifies whether the primary non-touchscreen navigation control is
- exposed or hidden.
- </xsd:documentation>
- </xsd:annotation>
- <xsd:simpleType>
- <xsd:restriction base="xsd:token">
- <xsd:enumeration value="navexposed" />
- <xsd:enumeration value="navhidden" />
- </xsd:restriction>
- </xsd:simpleType>
- </xsd:element>
-
- <xsd:element name="nav-method" minOccurs="0">
- <xsd:annotation>
- <xsd:documentation xml:lang="en">
- Specifies the primary non-touchscreen navigation method the configuration
- is designed for.
- </xsd:documentation>
- </xsd:annotation>
- <xsd:simpleType>
- <xsd:restriction base="xsd:token">
- <xsd:enumeration value="dpad" />
- <xsd:enumeration value="trackball" />
- <xsd:enumeration value="wheel" />
- <xsd:enumeration value="nonav" />
- </xsd:restriction>
- </xsd:simpleType>
- </xsd:element>
-
- <xsd:element name="screen-dimension" minOccurs="0">
- <xsd:annotation>
- <xsd:documentation xml:lang="en">
- Specifies the device screen resolution, in pixels.
- </xsd:documentation>
- </xsd:annotation>
- <xsd:complexType>
- <xsd:sequence minOccurs="2" maxOccurs="2">
-
- <xsd:element name="size">
- <xsd:simpleType>
- <xsd:restriction base="xsd:positiveInteger" />
- </xsd:simpleType>
- </xsd:element>
-
- </xsd:sequence>
- </xsd:complexType>
- </xsd:element>
-
- <xsd:element name="xdpi" minOccurs="0">
- <xsd:annotation>
- <xsd:documentation xml:lang="en">
- Specifies the actual density in X of the device screen.
- </xsd:documentation>
- </xsd:annotation>
- <xsd:simpleType>
- <xsd:restriction base="xsd:float">
- <xsd:minExclusive value="0" />
- </xsd:restriction>
- </xsd:simpleType>
- </xsd:element>
-
- <xsd:element name="ydpi" minOccurs="0">
- <xsd:annotation>
- <xsd:documentation xml:lang="en">
- Specifies the actual density in Y of the device screen.
- </xsd:documentation>
- </xsd:annotation>
- <xsd:simpleType>
- <xsd:restriction base="xsd:float">
- <xsd:minExclusive value="0" />
- </xsd:restriction>
- </xsd:simpleType>
- </xsd:element>
-
- </xsd:all>
- </xsd:complexType>
-
- <!-- The type definition of a device>config element.
- This type is basically all the element defined by parametersType and an extra
- required "name" attribute for the user-interface configuration name.
- -->
- <xsd:complexType name="configType">
- <xsd:annotation>
- <xsd:documentation>
- The configType defines the content of a "config" element in a "device" element.
-
- A "config" element can have all the parameters elements defined by
- "parameterType". It also has a required "name" attribute that indicates the
- user-interface name for this configuration.
- </xsd:documentation>
- </xsd:annotation>
-
- <xsd:complexContent>
- <xsd:extension base="c:parametersType">
- <xsd:attribute name="name" type="xsd:normalizedString" use="required" />
- </xsd:extension>
- </xsd:complexContent>
- </xsd:complexType>
-
-</xsd:schema>
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sourcelookup/AdtSourceLookupDirector.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sourcelookup/AdtSourceLookupDirector.java
deleted file mode 100755
index bcb9c48b1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/sourcelookup/AdtSourceLookupDirector.java
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- *******************************************************************************/
-
-package com.android.ide.eclipse.adt.internal.sourcelookup;
-
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.sdklib.IAndroidTarget;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.debug.core.ILaunchConfiguration;
-import org.eclipse.debug.core.sourcelookup.ISourceContainer;
-import org.eclipse.debug.core.sourcelookup.containers.DefaultSourceContainer;
-import org.eclipse.debug.core.sourcelookup.containers.DirectorySourceContainer;
-import org.eclipse.debug.core.sourcelookup.containers.ExternalArchiveSourceContainer;
-import org.eclipse.jdt.core.IClasspathEntry;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.internal.launching.JavaSourceLookupDirector;
-import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
-
-import java.io.File;
-
-public class AdtSourceLookupDirector extends JavaSourceLookupDirector {
-
- @Override
- public void initializeDefaults(ILaunchConfiguration configuration) throws CoreException {
- dispose();
- setLaunchConfiguration(configuration);
- String projectName =
- configuration.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME,
- ""); //$NON-NLS-1$
- if (projectName != null && projectName.length() > 0) {
- IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
- if (project != null && project.isOpen()) {
- ProjectState state = Sdk.getProjectState(project);
- if (state == null) {
- initDefaults();
- return;
- }
- IAndroidTarget target = state.getTarget();
- if (target == null) {
- initDefaults();
- return;
- }
- String path = target.getPath(IAndroidTarget.ANDROID_JAR);
- if (path == null) {
- initDefaults();
- return;
- }
- IJavaProject javaProject = JavaCore.create(project);
- if (javaProject != null && javaProject.isOpen()) {
- IClasspathEntry[] entries = javaProject.getResolvedClasspath(true);
- IClasspathEntry androidEntry = null;
- for (int i = 0; i < entries.length; i++) {
- IClasspathEntry entry = entries[i];
- if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY
- && path.equals(entry.getPath().toString())) {
- androidEntry = entry;
- break;
- }
- }
- if (androidEntry != null) {
- IPath sourceAttachmentPath = androidEntry.getSourceAttachmentPath();
- if (sourceAttachmentPath != null) {
- String androidSrc = sourceAttachmentPath.toString();
- if (androidSrc != null && androidSrc.trim().length() > 0) {
- File srcFile = new File(androidSrc);
- ISourceContainer adtContainer = null;
- if (srcFile.isFile()) {
- adtContainer = new ExternalArchiveSourceContainer(androidSrc,
- true);
- }
- if (srcFile.isDirectory()) {
- adtContainer = new DirectorySourceContainer(srcFile, false);
- }
- if (adtContainer != null) {
- ISourceContainer defaultContainer =
- new DefaultSourceContainer();
- setSourceContainers(new ISourceContainer[] {
- adtContainer, defaultContainer
- });
- initializeParticipants();
- return;
- }
- }
- }
- }
- }
- }
- }
- initDefaults();
- }
-
- private void initDefaults() {
- setSourceContainers(new ISourceContainer[] {
- new DefaultSourceContainer()
- });
- initializeParticipants();
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ConfigurationSelector.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ConfigurationSelector.java
deleted file mode 100644
index 44f90822a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ConfigurationSelector.java
+++ /dev/null
@@ -1,1989 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.ui;
-
-import com.android.SdkConstants;
-import com.android.ide.common.resources.LocaleManager;
-import com.android.ide.common.resources.configuration.CountryCodeQualifier;
-import com.android.ide.common.resources.configuration.DensityQualifier;
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.common.resources.configuration.KeyboardStateQualifier;
-import com.android.ide.common.resources.configuration.LayoutDirectionQualifier;
-import com.android.ide.common.resources.configuration.LocaleQualifier;
-import com.android.ide.common.resources.configuration.NavigationMethodQualifier;
-import com.android.ide.common.resources.configuration.NavigationStateQualifier;
-import com.android.ide.common.resources.configuration.NetworkCodeQualifier;
-import com.android.ide.common.resources.configuration.NightModeQualifier;
-import com.android.ide.common.resources.configuration.ResourceQualifier;
-import com.android.ide.common.resources.configuration.ScreenDimensionQualifier;
-import com.android.ide.common.resources.configuration.ScreenHeightQualifier;
-import com.android.ide.common.resources.configuration.ScreenOrientationQualifier;
-import com.android.ide.common.resources.configuration.ScreenRatioQualifier;
-import com.android.ide.common.resources.configuration.ScreenSizeQualifier;
-import com.android.ide.common.resources.configuration.ScreenWidthQualifier;
-import com.android.ide.common.resources.configuration.SmallestScreenWidthQualifier;
-import com.android.ide.common.resources.configuration.TextInputMethodQualifier;
-import com.android.ide.common.resources.configuration.TouchScreenQualifier;
-import com.android.ide.common.resources.configuration.UiModeQualifier;
-import com.android.ide.common.resources.configuration.VersionQualifier;
-import com.android.ide.eclipse.adt.internal.resources.ResourceHelper;
-import com.android.resources.Density;
-import com.android.resources.Keyboard;
-import com.android.resources.KeyboardState;
-import com.android.resources.LayoutDirection;
-import com.android.resources.Navigation;
-import com.android.resources.NavigationState;
-import com.android.resources.NightMode;
-import com.android.resources.ResourceEnum;
-import com.android.resources.ScreenOrientation;
-import com.android.resources.ScreenRatio;
-import com.android.resources.ScreenSize;
-import com.android.resources.TouchScreen;
-import com.android.resources.UiMode;
-
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StackLayout;
-import org.eclipse.swt.events.ControlAdapter;
-import org.eclipse.swt.events.ControlEvent;
-import org.eclipse.swt.events.FocusAdapter;
-import org.eclipse.swt.events.FocusEvent;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.events.VerifyEvent;
-import org.eclipse.swt.events.VerifyListener;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.swt.widgets.Text;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Locale;
-
-/**
- * Custom UI widget to let user build a Folder configuration.
- * <p/>
- * To use this, instantiate somewhere in the UI and then:
- * <ul>
- * <li>Use {@link #setConfiguration(String)} or {@link #setConfiguration(FolderConfiguration)}.
- * <li>Retrieve the configuration using {@link #getConfiguration(FolderConfiguration)}.
- * </ul>
- */
-public class ConfigurationSelector extends Composite {
-
- public static final int WIDTH_HINT = 600;
- public static final int HEIGHT_HINT = 250;
-
- private Runnable mOnChangeListener;
-
- private TableViewer mFullTableViewer;
- private TableViewer mSelectionTableViewer;
- private Button mAddButton;
- private Button mRemoveButton;
- private StackLayout mStackLayout;
-
- private boolean mOnRefresh = false;
-
- private final FolderConfiguration mBaseConfiguration = new FolderConfiguration();
- private final FolderConfiguration mSelectedConfiguration = new FolderConfiguration();
-
- private final HashMap<Class<? extends ResourceQualifier>, QualifierEditBase> mUiMap =
- new HashMap<Class<? extends ResourceQualifier>, QualifierEditBase>();
- private final SelectorMode mMode;
- private Composite mQualifierEditParent;
- private IQualifierFilter mQualifierFilter;
-
- /**
- * Basic of {@link VerifyListener} to only accept digits.
- */
- private static class DigitVerifier implements VerifyListener {
- @Override
- public void verifyText(VerifyEvent e) {
- // check for digit only.
- for (int i = 0 ; i < e.text.length(); i++) {
- char letter = e.text.charAt(i);
- if (letter < '0' || letter > '9') {
- e.doit = false;
- return;
- }
- }
- }
- }
-
- /**
- * Implementation of {@link VerifyListener} for Country Code qualifiers.
- */
- public static class MobileCodeVerifier extends DigitVerifier {
- @Override
- public void verifyText(VerifyEvent e) {
- super.verifyText(e);
-
- // basic tests passed?
- if (e.doit) {
- // check the max 3 digits.
- if (e.text.length() - e.end + e.start +
- ((Text)e.getSource()).getText().length() > 3) {
- e.doit = false;
- }
- }
- }
- }
-
- /**
- * Implementation of {@link VerifyListener} for the Language and Region qualifiers.
- */
- public static class LanguageRegionVerifier implements VerifyListener {
- @Override
- public void verifyText(VerifyEvent e) {
- // check for length
- if (e.text.length() - e.end + e.start + ((Combo)e.getSource()).getText().length() > 6) {
- e.doit = false;
- return;
- }
-
- // check for lower case only.
- for (int i = 0 ; i < e.text.length(); i++) {
- char letter = e.text.charAt(i);
- if (letter == '-') {
- if (i+e.start != 2) {
- e.doit = false;
- return;
- } else {
- continue;
- }
- }
- if (i+e.start == 3 && letter != 'r') {
- e.doit = false;
- return;
- }
- if ((letter < 'a' || letter > 'z') && (letter < 'A' || letter > 'Z')) {
- e.doit = false;
- return;
- }
- }
- }
- }
-
- /**
- * Implementation of {@link VerifyListener} for the Density qualifier.
- */
- public static class DensityVerifier extends DigitVerifier { }
-
- /**
- * Implementation of {@link VerifyListener} for the Screen Dimension qualifier.
- */
- public static class DimensionVerifier extends DigitVerifier { }
-
- /**
- * Enum for the state of the configuration being created.
- */
- public enum ConfigurationState {
- OK, INVALID_CONFIG, REGION_WITHOUT_LANGUAGE;
- }
-
- /**
- * Behavior mode for the Selector.
- *
- * @see #DEFAULT
- * @see #DEVICE_ONLY
- * @see #CONFIG_ONLY
- */
- public enum SelectorMode {
- /** the default mode */
- DEFAULT,
- /** mode forcing the qualifier values to be valid on a device.
- * For instance {@link Density#NODPI} is a valid qualifier for a resource configuration but
- * this is not valid on a device */
- DEVICE_ONLY,
- /** mode where only the specific config can be edited. The user can only select
- * which non-empty qualifier to select. */
- CONFIG_ONLY;
- }
-
- /**
- * A filter for {@link ResourceQualifier}.
- * @see ConfigurationSelector#setQualifierFilter(IQualifierFilter)
- */
- public interface IQualifierFilter {
- /**
- * Returns true of the qualifier is accepted.
- */
- boolean accept(ResourceQualifier qualifier);
- }
-
- /**
- * Creates the selector.
- * <p/>
- * The {@link SelectorMode} changes the behavior of the selector depending on what is being
- * edited (a device config, a resource config, a given configuration).
- *
- * @param parent the composite parent.
- * @param mode the mode for the selector.
- */
- public ConfigurationSelector(Composite parent, SelectorMode mode) {
- super(parent, SWT.NONE);
-
- mMode = mode;
- mBaseConfiguration.createDefault();
-
- GridLayout gl = new GridLayout(4, false);
- gl.marginWidth = gl.marginHeight = 0;
- setLayout(gl);
-
- // first column is the first table
- final Table fullTable = new Table(this, SWT.SINGLE | SWT.FULL_SELECTION | SWT.BORDER);
- fullTable.setLayoutData(new GridData(GridData.FILL_BOTH));
- fullTable.setHeaderVisible(true);
- fullTable.setLinesVisible(true);
-
- // create the column
- final TableColumn fullTableColumn = new TableColumn(fullTable, SWT.LEFT);
- // set the header
- fullTableColumn.setText("Available Qualifiers");
-
- fullTable.addControlListener(new ControlAdapter() {
- @Override
- public void controlResized(ControlEvent e) {
- Rectangle r = fullTable.getClientArea();
- fullTableColumn.setWidth(r.width);
- }
- });
-
- mFullTableViewer = new TableViewer(fullTable);
- mFullTableViewer.setContentProvider(new QualifierContentProvider());
- // the label provider must return the value of the label only if the mode is
- // CONFIG_ONLY
- mFullTableViewer.setLabelProvider(new QualifierLabelProvider(
- mMode == SelectorMode.CONFIG_ONLY));
- mFullTableViewer.setInput(mBaseConfiguration);
- mFullTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- ISelection selection = event.getSelection();
- if (selection instanceof IStructuredSelection) {
- IStructuredSelection structSelection = (IStructuredSelection)selection;
- Object first = structSelection.getFirstElement();
-
- if (first instanceof ResourceQualifier) {
- mAddButton.setEnabled(true);
- return;
- }
- }
-
- mAddButton.setEnabled(false);
- }
- });
-
- // 2nd column is the left/right arrow button
- Composite buttonComposite = new Composite(this, SWT.NONE);
- gl = new GridLayout(1, false);
- gl.marginWidth = gl.marginHeight = 0;
- buttonComposite.setLayout(gl);
- buttonComposite.setLayoutData(new GridData(GridData.FILL_VERTICAL));
-
- new Composite(buttonComposite, SWT.NONE);
- mAddButton = new Button(buttonComposite, SWT.BORDER | SWT.PUSH);
- mAddButton.setText("->");
- mAddButton.setEnabled(false);
- mAddButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- IStructuredSelection selection =
- (IStructuredSelection)mFullTableViewer.getSelection();
-
- Object first = selection.getFirstElement();
- if (first instanceof ResourceQualifier) {
- ResourceQualifier qualifier = (ResourceQualifier)first;
-
- mBaseConfiguration.removeQualifier(qualifier);
- mSelectedConfiguration.addQualifier(qualifier);
-
- mFullTableViewer.refresh();
- mSelectionTableViewer.refresh();
- mSelectionTableViewer.setSelection(new StructuredSelection(qualifier), true);
-
- onChange(false /* keepSelection */);
- }
- }
- });
-
- mRemoveButton = new Button(buttonComposite, SWT.BORDER | SWT.PUSH);
- mRemoveButton.setText("<-");
- mRemoveButton.setEnabled(false);
- mRemoveButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- IStructuredSelection selection =
- (IStructuredSelection)mSelectionTableViewer.getSelection();
-
- Object first = selection.getFirstElement();
- if (first instanceof ResourceQualifier) {
- ResourceQualifier qualifier = (ResourceQualifier)first;
-
- mSelectedConfiguration.removeQualifier(qualifier);
- mBaseConfiguration.addQualifier(qualifier);
-
- mFullTableViewer.refresh();
- mSelectionTableViewer.refresh();
-
- onChange(false /* keepSelection */);
- }
- }
- });
-
- // 3rd column is the selected config table
- final Table selectionTable = new Table(this, SWT.SINGLE | SWT.FULL_SELECTION | SWT.BORDER);
- selectionTable.setLayoutData(new GridData(GridData.FILL_BOTH));
- selectionTable.setHeaderVisible(true);
- selectionTable.setLinesVisible(true);
-
- // create the column
- final TableColumn selectionTableColumn = new TableColumn(selectionTable, SWT.LEFT);
- // set the header
- selectionTableColumn.setText("Chosen Qualifiers");
-
- selectionTable.addControlListener(new ControlAdapter() {
- @Override
- public void controlResized(ControlEvent e) {
- Rectangle r = selectionTable.getClientArea();
- selectionTableColumn.setWidth(r.width);
- }
- });
- mSelectionTableViewer = new TableViewer(selectionTable);
- mSelectionTableViewer.setContentProvider(new QualifierContentProvider());
- // always show the qualifier value in this case.
- mSelectionTableViewer.setLabelProvider(new QualifierLabelProvider(
- true /* showQualifierValue */));
- mSelectionTableViewer.setInput(mSelectedConfiguration);
- mSelectionTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- // ignore selection changes during resfreshes in some cases.
- if (mOnRefresh) {
- return;
- }
-
- ISelection selection = event.getSelection();
- if (selection instanceof IStructuredSelection) {
- IStructuredSelection structSelection = (IStructuredSelection)selection;
-
- if (structSelection.isEmpty() == false) {
- Object first = structSelection.getFirstElement();
-
- if (first instanceof ResourceQualifier) {
- mRemoveButton.setEnabled(true);
-
- if (mMode != SelectorMode.CONFIG_ONLY) {
- QualifierEditBase composite = mUiMap.get(first.getClass());
-
- if (composite != null) {
- composite.setQualifier((ResourceQualifier)first);
- }
-
- mStackLayout.topControl = composite;
- mQualifierEditParent.layout();
- }
-
- return;
- }
- } else {
- if (mMode != SelectorMode.CONFIG_ONLY) {
- mStackLayout.topControl = null;
- mQualifierEditParent.layout();
- }
- }
- }
-
- mRemoveButton.setEnabled(false);
- }
- });
-
- if (mMode != SelectorMode.CONFIG_ONLY) {
- // 4th column is the detail of the selected qualifier
- mQualifierEditParent = new Composite(this, SWT.NONE);
- mQualifierEditParent.setLayout(mStackLayout = new StackLayout());
- mQualifierEditParent.setLayoutData(new GridData(GridData.FILL_VERTICAL));
-
- // create the UI for all the qualifiers, and associate them to the
- // ResourceQualifer class.
- mUiMap.put(CountryCodeQualifier.class, new MCCEdit(mQualifierEditParent));
- mUiMap.put(NetworkCodeQualifier.class, new MNCEdit(mQualifierEditParent));
- mUiMap.put(LocaleQualifier.class, new LocaleEdit(mQualifierEditParent));
- mUiMap.put(LayoutDirectionQualifier.class,
- new LayoutDirectionEdit(mQualifierEditParent));
- mUiMap.put(SmallestScreenWidthQualifier.class,
- new SmallestScreenWidthEdit(mQualifierEditParent));
- mUiMap.put(ScreenWidthQualifier.class, new ScreenWidthEdit(mQualifierEditParent));
- mUiMap.put(ScreenHeightQualifier.class, new ScreenHeightEdit(mQualifierEditParent));
- mUiMap.put(ScreenSizeQualifier.class, new ScreenSizeEdit(mQualifierEditParent));
- mUiMap.put(ScreenRatioQualifier.class, new ScreenRatioEdit(mQualifierEditParent));
- mUiMap.put(ScreenOrientationQualifier.class, new OrientationEdit(mQualifierEditParent));
- mUiMap.put(UiModeQualifier.class, new UiModeEdit(mQualifierEditParent));
- mUiMap.put(NightModeQualifier.class, new NightModeEdit(mQualifierEditParent));
- mUiMap.put(DensityQualifier.class, new DensityEdit(mQualifierEditParent));
- mUiMap.put(TouchScreenQualifier.class, new TouchEdit(mQualifierEditParent));
- mUiMap.put(KeyboardStateQualifier.class, new KeyboardEdit(mQualifierEditParent));
- mUiMap.put(TextInputMethodQualifier.class, new TextInputEdit(mQualifierEditParent));
- mUiMap.put(NavigationStateQualifier.class,
- new NavigationStateEdit(mQualifierEditParent));
- mUiMap.put(NavigationMethodQualifier.class, new NavigationEdit(mQualifierEditParent));
- mUiMap.put(ScreenDimensionQualifier.class,
- new ScreenDimensionEdit(mQualifierEditParent));
- mUiMap.put(VersionQualifier.class, new VersionEdit(mQualifierEditParent));
- }
- }
-
- /**
- * Sets a {@link IQualifierFilter}. If non null, this will restrict the qualifiers that
- * can be chosen.
- * @param filter the filter to set.
- */
- public void setQualifierFilter(IQualifierFilter filter) {
- mQualifierFilter = filter;
- }
-
- /**
- * Sets a listener to be notified when the configuration changes.
- * @param listener A {@link Runnable} whose <code>run()</code> method is called when the
- * configuration is changed. The method is called from the UI thread.
- */
- public void setOnChangeListener(Runnable listener) {
- mOnChangeListener = listener;
- }
-
- /**
- * Initialize the UI with a given {@link FolderConfiguration}. This must
- * be called from the UI thread.
- * @param config The configuration.
- */
- public void setConfiguration(FolderConfiguration config) {
-
- if (mMode != SelectorMode.CONFIG_ONLY) {
- mSelectedConfiguration.set(config, true /*nonFakeValuesOnly*/);
-
- // create the base config, which is the default config minus the qualifiers
- // in SelectedConfiguration
- mBaseConfiguration.substract(mSelectedConfiguration);
- } else {
- // set the base config to the edited config.
- // reset the config to be empty
- mBaseConfiguration.reset();
- mBaseConfiguration.set(config, true /*nonFakeValuesOnly*/);
- }
-
- mSelectionTableViewer.refresh();
- mFullTableViewer.refresh();
- }
-
- /**
- * Initialize the UI with the configuration represented by a resource folder name.
- * This must be called from the UI thread.
- *
- * @param folderSegments the segments of the folder name,
- * split using {@link FolderConfiguration#QUALIFIER_SEP}.
- * @return true if success, or false if the folder name is not a valid name.
- */
- public boolean setConfiguration(String[] folderSegments) {
- FolderConfiguration config = FolderConfiguration.getConfig(folderSegments);
-
- if (config == null) {
- return false;
- }
-
- setConfiguration(config);
-
- return true;
- }
-
- /**
- * Initialize the UI with the configuration represented by a resource folder name.
- * This must be called from the UI thread.
- * @param folderName the name of the folder.
- * @return true if success, or false if the folder name is not a valid name.
- */
- public boolean setConfiguration(String folderName) {
- // split the name of the folder in segments.
- String[] folderSegments = folderName.split(SdkConstants.RES_QUALIFIER_SEP);
-
- return setConfiguration(folderSegments);
- }
-
- /**
- * Gets the configuration as setup by the widget.
- * @param config the {@link FolderConfiguration} object to be filled with the information
- * from the UI.
- */
- public void getConfiguration(FolderConfiguration config) {
- config.set(mSelectedConfiguration);
- }
-
- /**
- * Returns the state of the configuration being edited/created.
- */
- public ConfigurationState getState() {
- if (mSelectedConfiguration.getInvalidQualifier() != null) {
- return ConfigurationState.INVALID_CONFIG;
- }
-
- return ConfigurationState.OK;
- }
-
- /**
- * Returns the first invalid qualifier of the configuration being edited/created,
- * or <code>null<code> if they are all valid (or if none exists).
- * <p/>If {@link #getState()} return {@link ConfigurationState#INVALID_CONFIG} then this will
- * not return <code>null</code>.
- */
- public ResourceQualifier getInvalidQualifier() {
- return mSelectedConfiguration.getInvalidQualifier();
- }
-
- /**
- * Handle changes in the configuration.
- * @param keepSelection if <code>true</code> attemps to avoid triggering selection change in
- * {@link #mSelectedConfiguration}.
- */
- private void onChange(boolean keepSelection) {
- ISelection selection = null;
- if (keepSelection) {
- mOnRefresh = true;
- selection = mSelectionTableViewer.getSelection();
- }
-
- mSelectionTableViewer.refresh(true);
-
- if (keepSelection) {
- mSelectionTableViewer.setSelection(selection);
- mOnRefresh = false;
- }
-
- if (mOnChangeListener != null) {
- mOnChangeListener.run();
- }
- }
-
- private void fillCombo(Combo combo, ResourceEnum[] resEnums) {
- for (ResourceEnum resEnum : resEnums) {
- // only add the enum if:
- // not in device mode OR (device mode is true and) it's a valid device value.
- // Also, always ignore fake values.
- if ((mMode == SelectorMode.DEFAULT || resEnum.isValidValueForDevice()) &&
- resEnum.isFakeValue() == false) {
- combo.add(resEnum.getShortDisplayValue());
- }
- }
- }
-
- /**
- * Content provider around a {@link FolderConfiguration}.
- */
- private class QualifierContentProvider implements IStructuredContentProvider {
-
- private FolderConfiguration mInput;
-
- public QualifierContentProvider() {
- }
-
- @Override
- public void dispose() {
- // pass
- }
-
- @Override
- public Object[] getElements(Object inputElement) {
- // default easy case
- if (mQualifierFilter == null) {
- return mInput.getQualifiers();
- }
-
- // in this case we have to compute the list
- ArrayList<ResourceQualifier> list = new ArrayList<ResourceQualifier>();
- for (ResourceQualifier qual : mInput.getQualifiers()) {
- if (mQualifierFilter.accept(qual)) {
- list.add(qual);
- }
- }
-
- return list.toArray();
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- mInput = null;
- if (newInput instanceof FolderConfiguration) {
- mInput = (FolderConfiguration)newInput;
- }
- }
- }
-
- /**
- * Label provider for {@link ResourceQualifier} objects.
- */
- private static class QualifierLabelProvider implements ITableLabelProvider {
-
- private final boolean mShowQualifierValue;
-
- public QualifierLabelProvider(boolean showQualifierValue) {
- mShowQualifierValue = showQualifierValue;
- }
-
- @Override
- public String getColumnText(Object element, int columnIndex) {
- // only one column, so we can ignore columnIndex
- if (element instanceof ResourceQualifier) {
- if (mShowQualifierValue) {
- String value = ((ResourceQualifier)element).getShortDisplayValue();
- if (value == null || value.length() == 0) {
- return String.format("%1$s (?)",
- ((ResourceQualifier)element).getShortName());
- } else {
- return value;
- }
-
- } else {
- return ((ResourceQualifier)element).getShortName();
- }
- }
-
- return null;
- }
-
- @Override
- public Image getColumnImage(Object element, int columnIndex) {
- // only one column, so we can ignore columnIndex
- if (element instanceof ResourceQualifier) {
- return ResourceHelper.getIcon(((ResourceQualifier)element).getClass());
- }
-
- return null;
- }
-
- @Override
- public void addListener(ILabelProviderListener listener) {
- // pass
- }
-
- @Override
- public void dispose() {
- // pass
- }
-
- @Override
- public boolean isLabelProperty(Object element, String property) {
- // pass
- return false;
- }
-
- @Override
- public void removeListener(ILabelProviderListener listener) {
- // pass
- }
- }
-
- /**
- * Base class for Edit widget for {@link ResourceQualifier}.
- */
- private abstract static class QualifierEditBase extends Composite {
-
- public QualifierEditBase(Composite parent, String title) {
- super(parent, SWT.NONE);
- setLayout(new GridLayout(1, false));
-
- new Label(this, SWT.NONE).setText(title);
- }
-
- public abstract void setQualifier(ResourceQualifier qualifier);
- }
-
- /**
- * Edit widget for {@link CountryCodeQualifier}.
- */
- private class MCCEdit extends QualifierEditBase {
-
- private final Text mText;
-
- public MCCEdit(Composite parent) {
- super(parent, CountryCodeQualifier.NAME);
-
- mText = new Text(this, SWT.BORDER);
- mText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mText.addVerifyListener(new MobileCodeVerifier());
- mText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- onTextChange();
- }
- });
-
- mText.addFocusListener(new FocusAdapter() {
- @Override
- public void focusLost(FocusEvent e) {
- onTextChange();
- }
- });
-
- new Label(this, SWT.NONE).setText("(3 digit code)");
- }
-
- private void onTextChange() {
- String value = mText.getText();
-
- if (value.length() == 0) {
- // empty string, means a qualifier with no value.
- // Since the qualifier classes are immutable, and we don't want to
- // remove the qualifier from the configuration, we create a new default one.
- mSelectedConfiguration.setCountryCodeQualifier(new CountryCodeQualifier());
- } else {
- try {
- CountryCodeQualifier qualifier = CountryCodeQualifier.getQualifier(
- CountryCodeQualifier.getFolderSegment(Integer.parseInt(value)));
- if (qualifier != null) {
- mSelectedConfiguration.setCountryCodeQualifier(qualifier);
- } else {
- // Failure! Looks like the value is wrong
- // (for instance not exactly 3 digits).
- mSelectedConfiguration.setCountryCodeQualifier(new CountryCodeQualifier());
- }
- } catch (NumberFormatException nfe) {
- // Looks like the code is not a number. This should not happen since the text
- // field has a VerifyListener that prevents it.
- mSelectedConfiguration.setCountryCodeQualifier(new CountryCodeQualifier());
- }
- }
-
- // notify of change
- onChange(true /* keepSelection */);
- }
-
- @Override
- public void setQualifier(ResourceQualifier qualifier) {
- CountryCodeQualifier q = (CountryCodeQualifier)qualifier;
-
- mText.setText(Integer.toString(q.getCode()));
- }
- }
-
- /**
- * Edit widget for {@link NetworkCodeQualifier}.
- */
- private class MNCEdit extends QualifierEditBase {
- private final Text mText;
-
- public MNCEdit(Composite parent) {
- super(parent, NetworkCodeQualifier.NAME);
-
- mText = new Text(this, SWT.BORDER);
- mText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mText.addVerifyListener(new MobileCodeVerifier());
- mText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- onTextChange();
- }
- });
- mText.addFocusListener(new FocusAdapter() {
- @Override
- public void focusLost(FocusEvent e) {
- onTextChange();
- }
- });
-
- new Label(this, SWT.NONE).setText("(1-3 digit code)");
- }
-
- private void onTextChange() {
- String value = mText.getText();
-
- if (value.length() == 0) {
- // empty string, means a qualifier with no value.
- // Since the qualifier classes are immutable, and we don't want to
- // remove the qualifier from the configuration, we create a new default one.
- mSelectedConfiguration.setNetworkCodeQualifier(new NetworkCodeQualifier());
- } else {
- try {
- NetworkCodeQualifier qualifier = NetworkCodeQualifier.getQualifier(
- NetworkCodeQualifier.getFolderSegment(Integer.parseInt(value)));
- if (qualifier != null) {
- mSelectedConfiguration.setNetworkCodeQualifier(qualifier);
- } else {
- // Failure! Looks like the value is wrong
- // (for instance not exactly 3 digits).
- mSelectedConfiguration.setNetworkCodeQualifier(new NetworkCodeQualifier());
- }
- } catch (NumberFormatException nfe) {
- // Looks like the code is not a number. This should not happen since the text
- // field has a VerifyListener that prevents it.
- mSelectedConfiguration.setNetworkCodeQualifier(new NetworkCodeQualifier());
- }
- }
-
- // notify of change
- onChange(true /* keepSelection */);
- }
-
- @Override
- public void setQualifier(ResourceQualifier qualifier) {
- NetworkCodeQualifier q = (NetworkCodeQualifier)qualifier;
-
- mText.setText(Integer.toString(q.getCode()));
- }
- }
-
- /**
- * Edit widget for {@link LanguageQualifier}.
- */
- private class LocaleEdit extends QualifierEditBase {
- private final Combo mLanguage;
- private final Label mName;
-
- public LocaleEdit(Composite parent) {
- super(parent, LocaleQualifier.NAME);
-
- mLanguage = new Combo(this, SWT.DROP_DOWN);
- List<String> codes = LocaleManager.getLanguageCodes();
- String[] items = codes.toArray(new String[codes.size()]);
- Arrays.sort(items);
- mLanguage.setItems(items);
-
- mLanguage.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mLanguage.addVerifyListener(new LanguageRegionVerifier());
- mLanguage.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- onLanguageChange();
- }
- @Override
- public void widgetSelected(SelectionEvent e) {
- onLanguageChange();
- }
- });
- mLanguage.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- onLanguageChange();
- }
- });
-
- new Label(this, SWT.NONE).setText("(2 letter code or language-rRegion)");
-
- mName = new Label(this, SWT.NONE);
- mName.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- }
-
- private void onLanguageChange() {
- // update the current config
- String value = mLanguage.getText();
-
- String newName = "";
- if (value.length() == 2) {
- String name = LocaleManager.getLanguageName(value.toLowerCase(Locale.US));
- if (name != null) {
- newName = name;
- }
- }
- mName.setText(newName);
-
- if (value.length() == 0) {
- // empty string, means no qualifier.
- // Since the qualifier classes are immutable, and we don't want to
- // remove the qualifier from the configuration, we create a new default one.
- mSelectedConfiguration.setLocaleQualifier(new LocaleQualifier());
- } else {
- LocaleQualifier qualifier = LocaleQualifier.getQualifier(value);
- if (qualifier != null) {
- mSelectedConfiguration.setLocaleQualifier(qualifier);
- } else {
- // Failure! Looks like the value is wrong (for instance a one letter string).
- mSelectedConfiguration.setLocaleQualifier(new LocaleQualifier());
- }
- }
-
- // notify of change
- onChange(true /* keepSelection */);
- }
-
- @Override
- public void setQualifier(ResourceQualifier qualifier) {
- LocaleQualifier q = (LocaleQualifier)qualifier;
-
- String value = q.getValue();
- if (value != null) {
- mLanguage.setText(value);
- }
- }
- }
-
- /**
- * Edit widget for {@link LayoutDirectionQualifier}.
- */
- private class LayoutDirectionEdit extends QualifierEditBase {
-
- private final Combo mDirection;
-
- public LayoutDirectionEdit(Composite parent) {
- super(parent, LayoutDirectionQualifier.NAME);
-
- mDirection = new Combo(this, SWT.DROP_DOWN | SWT.READ_ONLY);
- fillCombo(mDirection, LayoutDirection.values());
-
- mDirection.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mDirection.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- onDirectionChange();
- }
- @Override
- public void widgetSelected(SelectionEvent e) {
- onDirectionChange();
- }
- });
- }
-
- protected void onDirectionChange() {
- // update the current config
- int index = mDirection.getSelectionIndex();
-
- if (index != -1) {
- mSelectedConfiguration.setLayoutDirectionQualifier(new LayoutDirectionQualifier(
- LayoutDirection.getByIndex(index)));
- } else {
- // empty selection, means no qualifier.
- // Since the qualifier classes are immutable, and we don't want to
- // remove the qualifier from the configuration, we create a new default one.
- mSelectedConfiguration.setLayoutDirectionQualifier(
- new LayoutDirectionQualifier());
- }
-
- // notify of change
- onChange(true /* keepSelection */);
- }
-
- @Override
- public void setQualifier(ResourceQualifier qualifier) {
- LayoutDirectionQualifier q = (LayoutDirectionQualifier)qualifier;
-
- LayoutDirection value = q.getValue();
- if (value == null) {
- mDirection.clearSelection();
- } else {
- mDirection.select(LayoutDirection.getIndex(value));
- }
- }
- }
-
-
- /**
- * Edit widget for {@link SmallestScreenWidthQualifier}.
- */
- private class SmallestScreenWidthEdit extends QualifierEditBase {
-
- private final Text mSize;
-
- public SmallestScreenWidthEdit(Composite parent) {
- super(parent, SmallestScreenWidthQualifier.NAME);
-
- ModifyListener modifyListener = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- onSizeChange();
- }
- };
-
- FocusAdapter focusListener = new FocusAdapter() {
- @Override
- public void focusLost(FocusEvent e) {
- onSizeChange();
- }
- };
-
- mSize = new Text(this, SWT.BORDER);
- mSize.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mSize.addVerifyListener(new DimensionVerifier());
- mSize.addModifyListener(modifyListener);
- mSize.addFocusListener(focusListener);
- }
-
- private void onSizeChange() {
- // update the current config
- String size = mSize.getText();
-
- if (size.length() == 0) {
- // if one of the strings is empty, reset to no qualifier.
- // Since the qualifier classes are immutable, and we don't want to
- // remove the qualifier from the configuration, we create a new default one.
- mSelectedConfiguration.setSmallestScreenWidthQualifier(
- new SmallestScreenWidthQualifier());
- } else {
- SmallestScreenWidthQualifier qualifier = SmallestScreenWidthQualifier.getQualifier(
- size);
-
- if (qualifier != null) {
- mSelectedConfiguration.setSmallestScreenWidthQualifier(qualifier);
- } else {
- // Failure! Looks like the value is wrong, reset the qualifier
- // Since the qualifier classes are immutable, and we don't want to
- // remove the qualifier from the configuration, we create a new default one.
- mSelectedConfiguration.setSmallestScreenWidthQualifier(
- new SmallestScreenWidthQualifier());
- }
- }
-
- // notify of change
- onChange(true /* keepSelection */);
- }
-
- @Override
- public void setQualifier(ResourceQualifier qualifier) {
- SmallestScreenWidthQualifier q = (SmallestScreenWidthQualifier)qualifier;
-
- mSize.setText(Integer.toString(q.getValue()));
- }
- }
-
- /**
- * Edit widget for {@link ScreenWidthQualifier}.
- */
- private class ScreenWidthEdit extends QualifierEditBase {
-
- private final Text mSize;
-
- public ScreenWidthEdit(Composite parent) {
- super(parent, ScreenWidthQualifier.NAME);
-
- ModifyListener modifyListener = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- onSizeChange();
- }
- };
-
- FocusAdapter focusListener = new FocusAdapter() {
- @Override
- public void focusLost(FocusEvent e) {
- onSizeChange();
- }
- };
-
- mSize = new Text(this, SWT.BORDER);
- mSize.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mSize.addVerifyListener(new DimensionVerifier());
- mSize.addModifyListener(modifyListener);
- mSize.addFocusListener(focusListener);
- }
-
- private void onSizeChange() {
- // update the current config
- String size = mSize.getText();
-
- if (size.length() == 0) {
- // if one of the strings is empty, reset to no qualifier.
- // Since the qualifier classes are immutable, and we don't want to
- // remove the qualifier from the configuration, we create a new default one.
- mSelectedConfiguration.setScreenWidthQualifier(new ScreenWidthQualifier());
- } else {
- ScreenWidthQualifier qualifier = ScreenWidthQualifier.getQualifier(size);
-
- if (qualifier != null) {
- mSelectedConfiguration.setScreenWidthQualifier(qualifier);
- } else {
- // Failure! Looks like the value is wrong, reset the qualifier
- // Since the qualifier classes are immutable, and we don't want to
- // remove the qualifier from the configuration, we create a new default one.
- mSelectedConfiguration.setScreenWidthQualifier(
- new ScreenWidthQualifier());
- }
- }
-
- // notify of change
- onChange(true /* keepSelection */);
- }
-
- @Override
- public void setQualifier(ResourceQualifier qualifier) {
- ScreenWidthQualifier q = (ScreenWidthQualifier)qualifier;
-
- mSize.setText(Integer.toString(q.getValue()));
- }
- }
-
- /**
- * Edit widget for {@link ScreenHeightQualifier}.
- */
- private class ScreenHeightEdit extends QualifierEditBase {
-
- private final Text mSize;
-
- public ScreenHeightEdit(Composite parent) {
- super(parent, ScreenHeightQualifier.NAME);
-
- ModifyListener modifyListener = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- onSizeChange();
- }
- };
-
- FocusAdapter focusListener = new FocusAdapter() {
- @Override
- public void focusLost(FocusEvent e) {
- onSizeChange();
- }
- };
-
- mSize = new Text(this, SWT.BORDER);
- mSize.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mSize.addVerifyListener(new DimensionVerifier());
- mSize.addModifyListener(modifyListener);
- mSize.addFocusListener(focusListener);
- }
-
- private void onSizeChange() {
- // update the current config
- String size = mSize.getText();
-
- if (size.length() == 0) {
- // if one of the strings is empty, reset to no qualifier.
- // Since the qualifier classes are immutable, and we don't want to
- // remove the qualifier from the configuration, we create a new default one.
- mSelectedConfiguration.setScreenHeightQualifier(new ScreenHeightQualifier());
- } else {
- ScreenHeightQualifier qualifier = ScreenHeightQualifier.getQualifier(size);
-
- if (qualifier != null) {
- mSelectedConfiguration.setScreenHeightQualifier(qualifier);
- } else {
- // Failure! Looks like the value is wrong, reset the qualifier
- // Since the qualifier classes are immutable, and we don't want to
- // remove the qualifier from the configuration, we create a new default one.
- mSelectedConfiguration.setScreenHeightQualifier(
- new ScreenHeightQualifier());
- }
- }
-
- // notify of change
- onChange(true /* keepSelection */);
- }
-
- @Override
- public void setQualifier(ResourceQualifier qualifier) {
- ScreenHeightQualifier q = (ScreenHeightQualifier)qualifier;
-
- mSize.setText(Integer.toString(q.getValue()));
- }
- }
-
-
- /**
- * Edit widget for {@link ScreenSizeQualifier}.
- */
- private class ScreenSizeEdit extends QualifierEditBase {
-
- private final Combo mSize;
-
- public ScreenSizeEdit(Composite parent) {
- super(parent, ScreenSizeQualifier.NAME);
-
- mSize = new Combo(this, SWT.DROP_DOWN | SWT.READ_ONLY);
- fillCombo(mSize, ScreenSize.values());
-
- mSize.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mSize.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- onScreenSizeChange();
- }
- @Override
- public void widgetSelected(SelectionEvent e) {
- onScreenSizeChange();
- }
- });
- }
-
- protected void onScreenSizeChange() {
- // update the current config
- int index = mSize.getSelectionIndex();
-
- if (index != -1) {
- mSelectedConfiguration.setScreenSizeQualifier(new ScreenSizeQualifier(
- ScreenSize.getByIndex(index)));
- } else {
- // empty selection, means no qualifier.
- // Since the qualifier classes are immutable, and we don't want to
- // remove the qualifier from the configuration, we create a new default one.
- mSelectedConfiguration.setScreenSizeQualifier(
- new ScreenSizeQualifier());
- }
-
- // notify of change
- onChange(true /* keepSelection */);
- }
-
- @Override
- public void setQualifier(ResourceQualifier qualifier) {
- ScreenSizeQualifier q = (ScreenSizeQualifier)qualifier;
-
- ScreenSize value = q.getValue();
- if (value == null) {
- mSize.clearSelection();
- } else {
- mSize.select(ScreenSize.getIndex(value));
- }
- }
- }
-
- /**
- * Edit widget for {@link ScreenRatioQualifier}.
- */
- private class ScreenRatioEdit extends QualifierEditBase {
-
- private final Combo mRatio;
-
- public ScreenRatioEdit(Composite parent) {
- super(parent, ScreenRatioQualifier.NAME);
-
- mRatio = new Combo(this, SWT.DROP_DOWN | SWT.READ_ONLY);
- fillCombo(mRatio, ScreenRatio.values());
-
- mRatio.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mRatio.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- onScreenRatioChange();
- }
- @Override
- public void widgetSelected(SelectionEvent e) {
- onScreenRatioChange();
- }
- });
- }
-
- protected void onScreenRatioChange() {
- // update the current config
- int index = mRatio.getSelectionIndex();
-
- if (index != -1) {
- mSelectedConfiguration.setScreenRatioQualifier(new ScreenRatioQualifier(
- ScreenRatio.getByIndex(index)));
- } else {
- // empty selection, means no qualifier.
- // Since the qualifier classes are immutable, and we don't want to
- // remove the qualifier from the configuration, we create a new default one.
- mSelectedConfiguration.setScreenRatioQualifier(
- new ScreenRatioQualifier());
- }
-
- // notify of change
- onChange(true /* keepSelection */);
- }
-
- @Override
- public void setQualifier(ResourceQualifier qualifier) {
- ScreenRatioQualifier q = (ScreenRatioQualifier)qualifier;
-
- ScreenRatio value = q.getValue();
- if (value == null) {
- mRatio.clearSelection();
- } else {
- mRatio.select(ScreenRatio.getIndex(value));
- }
- }
- }
-
- /**
- * Edit widget for {@link ScreenOrientationQualifier}.
- */
- private class OrientationEdit extends QualifierEditBase {
-
- private final Combo mOrientation;
-
- public OrientationEdit(Composite parent) {
- super(parent, ScreenOrientationQualifier.NAME);
-
- mOrientation = new Combo(this, SWT.DROP_DOWN | SWT.READ_ONLY);
- fillCombo(mOrientation, ScreenOrientation.values());
-
- mOrientation.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mOrientation.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- onOrientationChange();
- }
- @Override
- public void widgetSelected(SelectionEvent e) {
- onOrientationChange();
- }
- });
- }
-
- protected void onOrientationChange() {
- // update the current config
- int index = mOrientation.getSelectionIndex();
-
- if (index != -1) {
- mSelectedConfiguration.setScreenOrientationQualifier(new ScreenOrientationQualifier(
- ScreenOrientation.getByIndex(index)));
- } else {
- // empty selection, means no qualifier.
- // Since the qualifier classes are immutable, and we don't want to
- // remove the qualifier from the configuration, we create a new default one.
- mSelectedConfiguration.setScreenOrientationQualifier(
- new ScreenOrientationQualifier());
- }
-
- // notify of change
- onChange(true /* keepSelection */);
- }
-
- @Override
- public void setQualifier(ResourceQualifier qualifier) {
- ScreenOrientationQualifier q = (ScreenOrientationQualifier)qualifier;
-
- ScreenOrientation value = q.getValue();
- if (value == null) {
- mOrientation.clearSelection();
- } else {
- mOrientation.select(ScreenOrientation.getIndex(value));
- }
- }
- }
-
- /**
- * Edit widget for {@link DockModeQualifier}.
- */
- private class UiModeEdit extends QualifierEditBase {
-
- private final Combo mUiMode;
-
- public UiModeEdit(Composite parent) {
- super(parent, UiModeQualifier.NAME);
-
- mUiMode = new Combo(this, SWT.DROP_DOWN | SWT.READ_ONLY);
- fillCombo(mUiMode, UiMode.values());
-
- mUiMode.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mUiMode.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- onDockModeChange();
- }
- @Override
- public void widgetSelected(SelectionEvent e) {
- onDockModeChange();
- }
- });
- }
-
- protected void onDockModeChange() {
- // update the current config
- int index = mUiMode.getSelectionIndex();
-
- if (index != -1) {
- mSelectedConfiguration.setUiModeQualifier(
- new UiModeQualifier(UiMode.getByIndex(index)));
- } else {
- // empty selection, means no qualifier.
- // Since the qualifier classes are immutable, and we don't want to
- // remove the qualifier from the configuration, we create a new default one.
- mSelectedConfiguration.setUiModeQualifier(new UiModeQualifier());
- }
-
- // notify of change
- onChange(true /* keepSelection */);
- }
-
- @Override
- public void setQualifier(ResourceQualifier qualifier) {
- UiModeQualifier q = (UiModeQualifier)qualifier;
-
- UiMode value = q.getValue();
- if (value == null) {
- mUiMode.clearSelection();
- } else {
- mUiMode.select(UiMode.getIndex(value));
- }
- }
- }
-
- /**
- * Edit widget for {@link NightModeQualifier}.
- */
- private class NightModeEdit extends QualifierEditBase {
-
- private final Combo mNightMode;
-
- public NightModeEdit(Composite parent) {
- super(parent, NightModeQualifier.NAME);
-
- mNightMode = new Combo(this, SWT.DROP_DOWN | SWT.READ_ONLY);
- fillCombo(mNightMode, NightMode.values());
-
- mNightMode.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mNightMode.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- onNightModeChange();
- }
- @Override
- public void widgetSelected(SelectionEvent e) {
- onNightModeChange();
- }
- });
- }
-
- protected void onNightModeChange() {
- // update the current config
- int index = mNightMode.getSelectionIndex();
-
- if (index != -1) {
- mSelectedConfiguration.setNightModeQualifier(
- new NightModeQualifier(NightMode.getByIndex(index)));
- } else {
- // empty selection, means no qualifier.
- // Since the qualifier classes are immutable, and we don't want to
- // remove the qualifier from the configuration, we create a new default one.
- mSelectedConfiguration.setNightModeQualifier(new NightModeQualifier());
- }
-
- // notify of change
- onChange(true /* keepSelection */);
- }
-
- @Override
- public void setQualifier(ResourceQualifier qualifier) {
- NightModeQualifier q = (NightModeQualifier)qualifier;
-
- NightMode value = q.getValue();
- if (value == null) {
- mNightMode.clearSelection();
- } else {
- mNightMode.select(NightMode.getIndex(value));
- }
- }
- }
-
-
- /**
- * Edit widget for {@link DensityQualifier}.
- */
- private class DensityEdit extends QualifierEditBase {
- private final Combo mDensity;
-
- public DensityEdit(Composite parent) {
- super(parent, DensityQualifier.NAME);
-
- mDensity = new Combo(this, SWT.DROP_DOWN | SWT.READ_ONLY);
- fillCombo(mDensity, Density.values());
-
- mDensity.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mDensity.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- onDensityChange();
- }
- @Override
- public void widgetSelected(SelectionEvent e) {
- onDensityChange();
- }
- });
- }
-
- private void onDensityChange() {
- // update the current config
- int index = mDensity.getSelectionIndex();
-
- if (index != -1) {
- mSelectedConfiguration.setDensityQualifier(new DensityQualifier(
- Density.getByIndex(index)));
- } else {
- // empty selection, means no qualifier.
- // Since the qualifier classes are immutable, and we don't want to
- // remove the qualifier from the configuration, we create a new default one.
- mSelectedConfiguration.setDensityQualifier(
- new DensityQualifier());
- }
-
- // notify of change
- onChange(true /* keepSelection */);
- }
-
- @Override
- public void setQualifier(ResourceQualifier qualifier) {
- DensityQualifier q = (DensityQualifier)qualifier;
-
- Density value = q.getValue();
- if (value == null) {
- mDensity.clearSelection();
- } else {
- mDensity.select(Density.getIndex(value));
- }
- }
- }
-
- /**
- * Edit widget for {@link TouchScreenQualifier}.
- */
- private class TouchEdit extends QualifierEditBase {
-
- private final Combo mTouchScreen;
-
- public TouchEdit(Composite parent) {
- super(parent, TouchScreenQualifier.NAME);
-
- mTouchScreen = new Combo(this, SWT.DROP_DOWN | SWT.READ_ONLY);
- fillCombo(mTouchScreen, TouchScreen.values());
-
- mTouchScreen.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mTouchScreen.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- onTouchChange();
- }
- @Override
- public void widgetSelected(SelectionEvent e) {
- onTouchChange();
- }
- });
- }
-
- protected void onTouchChange() {
- // update the current config
- int index = mTouchScreen.getSelectionIndex();
-
- if (index != -1) {
- mSelectedConfiguration.setTouchTypeQualifier(new TouchScreenQualifier(
- TouchScreen.getByIndex(index)));
- } else {
- // empty selection, means no qualifier.
- // Since the qualifier classes are immutable, and we don't want to
- // remove the qualifier from the configuration, we create a new default one.
- mSelectedConfiguration.setTouchTypeQualifier(new TouchScreenQualifier());
- }
-
- // notify of change
- onChange(true /* keepSelection */);
- }
-
- @Override
- public void setQualifier(ResourceQualifier qualifier) {
- TouchScreenQualifier q = (TouchScreenQualifier)qualifier;
-
- TouchScreen value = q.getValue();
- if (value == null) {
- mTouchScreen.clearSelection();
- } else {
- mTouchScreen.select(TouchScreen.getIndex(value));
- }
- }
- }
-
- /**
- * Edit widget for {@link KeyboardStateQualifier}.
- */
- private class KeyboardEdit extends QualifierEditBase {
-
- private final Combo mKeyboardState;
-
- public KeyboardEdit(Composite parent) {
- super(parent, KeyboardStateQualifier.NAME);
-
- mKeyboardState = new Combo(this, SWT.DROP_DOWN | SWT.READ_ONLY);
- fillCombo(mKeyboardState, KeyboardState.values());
-
- mKeyboardState.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mKeyboardState.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- onKeyboardChange();
- }
- @Override
- public void widgetSelected(SelectionEvent e) {
- onKeyboardChange();
- }
- });
- }
-
- protected void onKeyboardChange() {
- // update the current config
- int index = mKeyboardState.getSelectionIndex();
-
- if (index != -1) {
- mSelectedConfiguration.setKeyboardStateQualifier(new KeyboardStateQualifier(
- KeyboardState.getByIndex(index)));
- } else {
- // empty selection, means no qualifier.
- // Since the qualifier classes are immutable, and we don't want to
- // remove the qualifier from the configuration, we create a new default one.
- mSelectedConfiguration.setKeyboardStateQualifier(
- new KeyboardStateQualifier());
- }
-
- // notify of change
- onChange(true /* keepSelection */);
- }
-
- @Override
- public void setQualifier(ResourceQualifier qualifier) {
- KeyboardStateQualifier q = (KeyboardStateQualifier)qualifier;
-
- KeyboardState value = q.getValue();
- if (value == null) {
- mKeyboardState.clearSelection();
- } else {
- mKeyboardState.select(KeyboardState.getIndex(value));
- }
- }
- }
-
- /**
- * Edit widget for {@link TextInputMethodQualifier}.
- */
- private class TextInputEdit extends QualifierEditBase {
-
- private final Combo mTextInput;
-
- public TextInputEdit(Composite parent) {
- super(parent, TextInputMethodQualifier.NAME);
-
- mTextInput = new Combo(this, SWT.DROP_DOWN | SWT.READ_ONLY);
- fillCombo(mTextInput, Keyboard.values());
-
- mTextInput.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mTextInput.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- onTextInputChange();
- }
- @Override
- public void widgetSelected(SelectionEvent e) {
- onTextInputChange();
- }
- });
- }
-
- protected void onTextInputChange() {
- // update the current config
- int index = mTextInput.getSelectionIndex();
-
- if (index != -1) {
- mSelectedConfiguration.setTextInputMethodQualifier(new TextInputMethodQualifier(
- Keyboard.getByIndex(index)));
- } else {
- // empty selection, means no qualifier.
- // Since the qualifier classes are immutable, and we don't want to
- // remove the qualifier from the configuration, we create a new default one.
- mSelectedConfiguration.setTextInputMethodQualifier(
- new TextInputMethodQualifier());
- }
-
- // notify of change
- onChange(true /* keepSelection */);
- }
-
- @Override
- public void setQualifier(ResourceQualifier qualifier) {
- TextInputMethodQualifier q = (TextInputMethodQualifier)qualifier;
-
- Keyboard value = q.getValue();
- if (value == null) {
- mTextInput.clearSelection();
- } else {
- mTextInput.select(Keyboard.getIndex(value));
- }
- }
- }
-
- /**
- * Edit widget for {@link NavigationStateQualifier}.
- */
- private class NavigationStateEdit extends QualifierEditBase {
-
- private final Combo mNavigationState;
-
- public NavigationStateEdit(Composite parent) {
- super(parent, NavigationStateQualifier.NAME);
-
- mNavigationState = new Combo(this, SWT.DROP_DOWN | SWT.READ_ONLY);
- fillCombo(mNavigationState, NavigationState.values());
-
- mNavigationState.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mNavigationState.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- onNavigationChange();
- }
- @Override
- public void widgetSelected(SelectionEvent e) {
- onNavigationChange();
- }
- });
- }
-
- protected void onNavigationChange() {
- // update the current config
- int index = mNavigationState.getSelectionIndex();
-
- if (index != -1) {
- mSelectedConfiguration.setNavigationStateQualifier(
- new NavigationStateQualifier(NavigationState.getByIndex(index)));
- } else {
- // empty selection, means no qualifier.
- // Since the qualifier classes are immutable, and we don't want to
- // remove the qualifier from the configuration, we create a new default one.
- mSelectedConfiguration.setNavigationStateQualifier(new NavigationStateQualifier());
- }
-
- // notify of change
- onChange(true /* keepSelection */);
- }
-
- @Override
- public void setQualifier(ResourceQualifier qualifier) {
- NavigationStateQualifier q = (NavigationStateQualifier)qualifier;
-
- NavigationState value = q.getValue();
- if (value == null) {
- mNavigationState.clearSelection();
- } else {
- mNavigationState.select(NavigationState.getIndex(value));
- }
- }
- }
-
-
- /**
- * Edit widget for {@link NavigationMethodQualifier}.
- */
- private class NavigationEdit extends QualifierEditBase {
-
- private final Combo mNavigation;
-
- public NavigationEdit(Composite parent) {
- super(parent, NavigationMethodQualifier.NAME);
-
- mNavigation = new Combo(this, SWT.DROP_DOWN | SWT.READ_ONLY);
- fillCombo(mNavigation, Navigation.values());
-
- mNavigation.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mNavigation.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- onNavigationChange();
- }
- @Override
- public void widgetSelected(SelectionEvent e) {
- onNavigationChange();
- }
- });
- }
-
- protected void onNavigationChange() {
- // update the current config
- int index = mNavigation.getSelectionIndex();
-
- if (index != -1) {
- mSelectedConfiguration.setNavigationMethodQualifier(new NavigationMethodQualifier(
- Navigation.getByIndex(index)));
- } else {
- // empty selection, means no qualifier.
- // Since the qualifier classes are immutable, and we don't want to
- // remove the qualifier from the configuration, we create a new default one.
- mSelectedConfiguration.setNavigationMethodQualifier(
- new NavigationMethodQualifier());
- }
-
- // notify of change
- onChange(true /* keepSelection */);
- }
-
- @Override
- public void setQualifier(ResourceQualifier qualifier) {
- NavigationMethodQualifier q = (NavigationMethodQualifier)qualifier;
-
- Navigation value = q.getValue();
- if (value == null) {
- mNavigation.clearSelection();
- } else {
- mNavigation.select(Navigation.getIndex(value));
- }
- }
- }
-
- /**
- * Edit widget for {@link ScreenDimensionQualifier}.
- */
- private class ScreenDimensionEdit extends QualifierEditBase {
-
- private final Text mSize1;
- private final Text mSize2;
-
- public ScreenDimensionEdit(Composite parent) {
- super(parent, ScreenDimensionQualifier.NAME);
-
- ModifyListener modifyListener = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- onSizeChange();
- }
- };
-
- FocusAdapter focusListener = new FocusAdapter() {
- @Override
- public void focusLost(FocusEvent e) {
- onSizeChange();
- }
- };
-
- mSize1 = new Text(this, SWT.BORDER);
- mSize1.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mSize1.addVerifyListener(new DimensionVerifier());
- mSize1.addModifyListener(modifyListener);
- mSize1.addFocusListener(focusListener);
-
- mSize2 = new Text(this, SWT.BORDER);
- mSize2.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mSize2.addVerifyListener(new DimensionVerifier());
- mSize2.addModifyListener(modifyListener);
- mSize2.addFocusListener(focusListener);
- }
-
- private void onSizeChange() {
- // update the current config
- String size1 = mSize1.getText();
- String size2 = mSize2.getText();
-
- if (size1.length() == 0 || size2.length() == 0) {
- // if one of the strings is empty, reset to no qualifier.
- // Since the qualifier classes are immutable, and we don't want to
- // remove the qualifier from the configuration, we create a new default one.
- mSelectedConfiguration.setScreenDimensionQualifier(new ScreenDimensionQualifier());
- } else {
- ScreenDimensionQualifier qualifier = ScreenDimensionQualifier.getQualifier(size1,
- size2);
-
- if (qualifier != null) {
- mSelectedConfiguration.setScreenDimensionQualifier(qualifier);
- } else {
- // Failure! Looks like the value is wrong, reset the qualifier
- // Since the qualifier classes are immutable, and we don't want to
- // remove the qualifier from the configuration, we create a new default one.
- mSelectedConfiguration.setScreenDimensionQualifier(
- new ScreenDimensionQualifier());
- }
- }
-
- // notify of change
- onChange(true /* keepSelection */);
- }
-
- @Override
- public void setQualifier(ResourceQualifier qualifier) {
- ScreenDimensionQualifier q = (ScreenDimensionQualifier)qualifier;
-
- mSize1.setText(Integer.toString(q.getValue1()));
- mSize2.setText(Integer.toString(q.getValue2()));
- }
- }
-
- /**
- * Edit widget for {@link VersionQualifier}.
- */
- private class VersionEdit extends QualifierEditBase {
- private final Text mText;
-
- public VersionEdit(Composite parent) {
- super(parent, VersionQualifier.NAME);
-
- mText = new Text(this, SWT.BORDER);
- mText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mText.addVerifyListener(new MobileCodeVerifier());
- mText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- onVersionChange();
- }
- });
- mText.addFocusListener(new FocusAdapter() {
- @Override
- public void focusLost(FocusEvent e) {
- onVersionChange();
- }
- });
-
- new Label(this, SWT.NONE).setText("(Platform API level)");
- }
-
- private void onVersionChange() {
- String value = mText.getText();
-
- if (value.length() == 0) {
- // empty string, means a qualifier with no value.
- // Since the qualifier classes are immutable, and we don't want to
- // remove the qualifier from the configuration, we create a new default one.
- mSelectedConfiguration.setVersionQualifier(new VersionQualifier());
- } else {
- try {
- VersionQualifier qualifier = VersionQualifier.getQualifier(
- VersionQualifier.getFolderSegment(Integer.parseInt(value)));
- if (qualifier != null) {
- mSelectedConfiguration.setVersionQualifier(qualifier);
- } else {
- // Failure! Looks like the value is wrong
- mSelectedConfiguration.setVersionQualifier(new VersionQualifier());
- }
- } catch (NumberFormatException nfe) {
- // Looks like the code is not a number. This should not happen since the text
- // field has a VerifyListener that prevents it.
- mSelectedConfiguration.setVersionQualifier(new VersionQualifier());
- }
- }
-
- // notify of change
- onChange(true /* keepSelection */);
- }
-
- @Override
- public void setQualifier(ResourceQualifier qualifier) {
- VersionQualifier q = (VersionQualifier)qualifier;
-
- mText.setText(Integer.toString(q.getVersion()));
- }
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/EclipseUiHelper.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/EclipseUiHelper.java
deleted file mode 100644
index f0fd23135..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/EclipseUiHelper.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.ui;
-
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-
-/**
- * Helpers for Eclipse UI related stuff.
- */
-public final class EclipseUiHelper {
-
- /** View Id for the default Eclipse Content Outline view. */
- public static final String CONTENT_OUTLINE_VIEW_ID = "org.eclipse.ui.views.ContentOutline";
- /** View Id for the default Eclipse Property Sheet view. */
- public static final String PROPERTY_SHEET_VIEW_ID = "org.eclipse.ui.views.PropertySheet";
-
- /** This class never gets instantiated. */
- private EclipseUiHelper() {
- }
-
- /**
- * Shows the corresponding view.
- * <p/>
- * Silently fails in case of error.
- *
- * @param viewId One of {@link #CONTENT_OUTLINE_VIEW_ID}, {@link #PROPERTY_SHEET_VIEW_ID}.
- * @param activate True to force activate (i.e. takes focus), false to just make visible (i.e.
- * does not steal focus.)
- */
- public static void showView(String viewId, boolean activate) {
- IWorkbenchWindow win = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- if (win != null) {
- IWorkbenchPage page = win.getActivePage();
- if (page != null) {
- try {
- IViewPart part = page.showView(viewId,
- null /* secondaryId */,
- activate ? IWorkbenchPage.VIEW_ACTIVATE : IWorkbenchPage.VIEW_VISIBLE);
- } catch (PartInitException e) {
- // ignore
- }
- }
- }
-
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/IUpdateWizardDialog.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/IUpdateWizardDialog.java
deleted file mode 100755
index c49b58953..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/IUpdateWizardDialog.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.ui;
-
-import org.eclipse.jface.wizard.WizardDialog;
-
-
-/**
- * An interface that enables a client to update {@link WizardDialog} after its creation.
- */
-public interface IUpdateWizardDialog {
- /**
- * Invoked after {@link WizardDialog#create()} to let the caller update the dialog.
- */
- public void updateWizardDialog(WizardDialogEx dialog);
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/MarginChooser.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/MarginChooser.java
deleted file mode 100644
index c2a5f71b2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/MarginChooser.java
+++ /dev/null
@@ -1,229 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.ui;
-
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.resources.ResourceType;
-
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.dialogs.SelectionStatusDialog;
-
-/**
- * Dialog for choosing margins
- */
-public class MarginChooser extends SelectionStatusDialog implements Listener {
- private GraphicalEditorPart mEditor;
- private AndroidTargetData mTargetData;
- private Text mLeftField;
- private Text mRightField;
- private Text mTopField;
- private Text mBottomField;
- private Text mAllField;
- private String mInitialAll;
- private String mInitialLeft;
- private String mInitialRight;
- private String mInitialTop;
- private String mInitialBottom;
- private Label mErrorLabel;
- private String[] mMargins;
-
- // Client data key for resource buttons pointing to the associated text field
- private final static String PROP_TEXTFIELD = "textField"; //$NON-NLS-1$
-
- /**
- * Constructs a new margin chooser dialog.
- *
- * @param parent parent widget
- * @param editor associated layout editor
- * @param targetData current SDK target
- * @param all current value for the all margins attribute
- * @param left current value for the left margin
- * @param right current value for the right margin
- * @param top current value for the top margin
- * @param bottom current value for the bottom margin
- */
- public MarginChooser(Shell parent, GraphicalEditorPart editor, AndroidTargetData targetData, String all,
- String left, String right, String top, String bottom) {
- super(parent);
- setTitle("Edit Margins");
- mEditor = editor;
- mTargetData = targetData;
- mInitialAll = all;
- mInitialLeft = left;
- mInitialRight = right;
- mInitialTop = top;
- mInitialBottom = bottom;
- }
-
- @SuppressWarnings("unused") // SWT constructors have side effects, "new Label" is not unused.
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite container = new Composite(parent, SWT.NONE);
- container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
-
- container.setLayout(new GridLayout(3, false));
-
- Label allLabel = new Label(container, SWT.NONE);
- allLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- allLabel.setText("All:");
-
- mAllField = new Text(container, SWT.BORDER | SWT.LEFT);
- mAllField.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- mAllField.setText(mInitialAll != null ? mInitialAll : ""); //$NON-NLS-1$
-
- Button allButton = new Button(container, SWT.NONE);
- allButton.setText("Resource...");
- allButton.setData(PROP_TEXTFIELD, mAllField);
-
- Label label = new Label(container, SWT.SEPARATOR | SWT.HORIZONTAL);
- label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 3, 1));
-
- Label leftLabel = new Label(container, SWT.NONE);
- leftLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- leftLabel.setText("Left:");
-
- mLeftField = new Text(container, SWT.BORDER | SWT.LEFT);
- mLeftField.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- mLeftField.setText(mInitialLeft != null ? mInitialLeft : ""); //$NON-NLS-1$
-
- Button leftButton = new Button(container, SWT.NONE);
- leftButton.setText("Resource...");
- leftButton.setData(PROP_TEXTFIELD, mLeftField);
-
- Label rightLabel = new Label(container, SWT.NONE);
- rightLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- rightLabel.setText("Right:");
-
- mRightField = new Text(container, SWT.BORDER | SWT.LEFT);
- mRightField.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- mRightField.setText(mInitialRight != null ? mInitialRight : ""); //$NON-NLS-1$
-
- Button rightButton = new Button(container, SWT.NONE);
- rightButton.setText("Resource...");
- rightButton.setData(PROP_TEXTFIELD, mRightField);
-
- Label topLabel = new Label(container, SWT.NONE);
- topLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- topLabel.setText("Top:");
-
- mTopField = new Text(container, SWT.BORDER | SWT.LEFT);
- mTopField.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- mTopField.setText(mInitialTop != null ? mInitialTop : ""); //$NON-NLS-1$
-
- Button topButton = new Button(container, SWT.NONE);
- topButton.setText("Resource...");
- topButton.setData(PROP_TEXTFIELD, mTopField);
-
- Label bottomLabel = new Label(container, SWT.NONE);
- bottomLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- bottomLabel.setText("Bottom:");
-
- mBottomField = new Text(container, SWT.BORDER | SWT.LEFT);
- mBottomField.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- mBottomField.setText(mInitialBottom != null ? mInitialBottom : ""); //$NON-NLS-1$
-
- Button bottomButton = new Button(container, SWT.NONE);
- bottomButton.setText("Resource...");
- bottomButton.setData(PROP_TEXTFIELD, mBottomField);
-
- allButton.addListener(SWT.Selection, this);
- leftButton.addListener(SWT.Selection, this);
- rightButton.addListener(SWT.Selection, this);
- topButton.addListener(SWT.Selection, this);
- bottomButton.addListener(SWT.Selection, this);
-
- mAllField.addListener(SWT.Modify, this);
- mLeftField.addListener(SWT.Modify, this);
- mRightField.addListener(SWT.Modify, this);
- mTopField.addListener(SWT.Modify, this);
- mBottomField.addListener(SWT.Modify, this);
-
- new Label(container, SWT.NONE);
- mErrorLabel = new Label(container, SWT.WRAP);
- mErrorLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, false, 2, 1));
- mErrorLabel.setForeground(parent.getDisplay().getSystemColor(SWT.COLOR_RED));
- return container;
- }
-
- @Override
- protected void computeResult() {
- mMargins = new String[] {
- mAllField.getText().trim(),
- mLeftField.getText().trim(), mRightField.getText().trim(),
- mTopField.getText().trim(), mBottomField.getText().trim()
- };
- }
-
- /**
- * Returns the margins in the order all, left, right, top, bottom
- *
- * @return the margins in the order all, left, right, top, bottom, never
- * null
- */
- public String[] getMargins() {
- return mMargins;
- }
-
- @Override
- public void handleEvent(Event event) {
- if (event.type == SWT.Modify) {
- // Text field modification -- warn about non-dip numbers
- if (event.widget instanceof Text) {
- Text text = (Text) event.widget;
- String input = text.getText().trim();
- boolean isNumber = false;
- try {
- if (Integer.parseInt(input) > 0) {
- isNumber = true;
- }
- } catch (NumberFormatException nufe) {
- // Users are allowed to enter non-numbers here, not an error
- }
- if (isNumber) {
- String message = String.format("Hint: Use \"%1$sdp\" instead", input);
- mErrorLabel.setText(message);
- } else {
- mErrorLabel.setText("");
- }
- }
- } else if (event.type == SWT.Selection) {
- // Button pressed - open resource chooser
- if (event.widget instanceof Button) {
- Button button = (Button) event.widget;
- Text text = (Text) button.getData(PROP_TEXTFIELD);
-
- // Open a resource chooser dialog for specified resource type.
- ResourceChooser chooser = ResourceChooser.create(mEditor, ResourceType.DIMEN)
- .setCurrentResource(text.getText().trim());
- if (chooser.open() == Window.OK) {
- text.setText(chooser.getCurrentResource());
- }
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ReferenceChooserDialog.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ReferenceChooserDialog.java
deleted file mode 100644
index 6c628658a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ReferenceChooserDialog.java
+++ /dev/null
@@ -1,396 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.ui;
-
-import com.android.ide.common.resources.ResourceItem;
-import com.android.ide.common.resources.ResourceRepository;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.layout.properties.PropertyFactory;
-import com.android.ide.eclipse.adt.internal.refactorings.extractstring.ExtractStringRefactoring;
-import com.android.ide.eclipse.adt.internal.refactorings.extractstring.ExtractStringWizard;
-import com.android.resources.ResourceType;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.DialogSettings;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.IDialogSettings;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.TreePath;
-import org.eclipse.jface.viewers.TreeSelection;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.FilteredTree;
-import org.eclipse.ui.dialogs.PatternFilter;
-import org.eclipse.ui.dialogs.SelectionStatusDialog;
-
-import java.util.Collection;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * A dialog to let the user choose a reference to a resource.
- *
- */
-public class ReferenceChooserDialog extends SelectionStatusDialog {
-
- private static Pattern sResourcePattern = Pattern.compile("@(.*)/(.+)"); //$NON-NLS-1$
- private static Pattern sInlineIdResourcePattern = Pattern.compile("@\\+id/(.+)"); //$NON-NLS-1$
-
- private static IDialogSettings sDialogSettings = new DialogSettings("");
-
- private ResourceRepository mProjectResources;
- private String mCurrentResource;
- private FilteredTree mFilteredTree;
- private Button mNewResButton;
- private final IProject mProject;
- private TreeViewer mTreeViewer;
- private ResourcePreviewHelper mPreviewHelper;
-
- /**
- * @param project
- * @param parent
- */
- public ReferenceChooserDialog(IProject project, ResourceRepository projectResources,
- Shell parent) {
- super(parent);
- mProject = project;
- mProjectResources = projectResources;
-
- int shellStyle = getShellStyle();
- setShellStyle(shellStyle | SWT.MAX | SWT.RESIZE);
-
- setTitle("Reference Chooser");
- setMessage(String.format("Choose a resource"));
-
- setDialogBoundsSettings(sDialogSettings, getDialogBoundsStrategy());
- }
-
- public void setPreviewHelper(ResourcePreviewHelper previewHelper) {
- mPreviewHelper = previewHelper;
- }
-
- public void setCurrentResource(String resource) {
- mCurrentResource = resource;
- }
-
- public String getCurrentResource() {
- return mCurrentResource;
- }
-
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.dialogs.SelectionStatusDialog#computeResult()
- */
- @Override
- protected void computeResult() {
- // get the selection
- TreePath treeSelection = getSelection();
- if (treeSelection != null) {
- if (treeSelection.getSegmentCount() == 2) {
- // get the resource type and the resource item
- ResourceType resourceType = (ResourceType)treeSelection.getFirstSegment();
- ResourceItem resourceItem = (ResourceItem)treeSelection.getLastSegment();
-
- mCurrentResource = resourceItem.getXmlString(resourceType, false /* system */);
- }
- }
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite top = (Composite)super.createDialogArea(parent);
-
- // create the standard message area
- createMessageArea(top);
-
- // create the filtered tree
- createFilteredTree(top);
-
- // setup the initial selection
- if (mCurrentResource != null) {
- setupInitialSelection();
- }
-
- // create the "New Resource" button
- createNewResButtons(top);
-
- Composite workaround = PropertyFactory.addWorkaround(top);
- if (workaround != null) {
- workaround.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1));
- }
-
- return top;
- }
-
- /**
- * Creates the "New Resource" button.
- * @param top the parent composite
- */
- private void createNewResButtons(Composite top) {
- mNewResButton = new Button(top, SWT.NONE);
- mNewResButton.addSelectionListener(new OnNewResButtonSelected());
- updateNewResButton();
- }
-
- private void createFilteredTree(Composite parent) {
- mFilteredTree = new FilteredTree(parent, SWT.BORDER | SWT.SINGLE | SWT.FULL_SELECTION,
- new PatternFilter());
-
- GridData data = new GridData();
- data.widthHint = convertWidthInCharsToPixels(60);
- data.heightHint = convertHeightInCharsToPixels(18);
- data.grabExcessVerticalSpace = true;
- data.grabExcessHorizontalSpace = true;
- data.horizontalAlignment = GridData.FILL;
- data.verticalAlignment = GridData.FILL;
- mFilteredTree.setLayoutData(data);
- mFilteredTree.setFont(parent.getFont());
-
- mTreeViewer = mFilteredTree.getViewer();
- Tree tree = mTreeViewer.getTree();
-
- tree.addSelectionListener(new SelectionListener() {
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- handleDoubleClick();
- }
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- handleSelection();
- }
- });
-
- mTreeViewer.setLabelProvider(new ResourceLabelProvider());
- mTreeViewer.setContentProvider(new ResourceContentProvider(false /* fullLevels */));
- mTreeViewer.setInput(mProjectResources);
- }
-
- protected void handleSelection() {
- validateCurrentSelection();
- updateNewResButton();
-
- if (mPreviewHelper != null) {
- TreePath treeSelection = getSelection();
- ResourceType type = null;
- if (treeSelection != null && treeSelection.getSegmentCount() == 2) {
- Object segment = treeSelection.getSegment(0);
- if (segment instanceof ResourceType) {
- type = (ResourceType) segment;
- // Ensure that mCurrentResource is valid
- computeResult();
- }
- }
-
- mPreviewHelper.updatePreview(type, mCurrentResource);
- }
- }
-
- protected void handleDoubleClick() {
- if (validateCurrentSelection()) {
- buttonPressed(IDialogConstants.OK_ID);
- }
- }
-
- /**
- * Returns the selected item in the tree as a {@link TreePath} object.
- * @return the <code>TreePath</code> object or <code>null</code> if there was no selection.
- */
- private TreePath getSelection() {
- ISelection selection = mFilteredTree.getViewer().getSelection();
- if (selection instanceof TreeSelection) {
- TreeSelection treeSelection = (TreeSelection)selection;
- TreePath[] treePaths = treeSelection.getPaths();
-
- // the selection mode is SWT.SINGLE, so we just get the first one.
- if (treePaths.length > 0) {
- return treePaths[0];
- }
- }
-
- return null;
- }
-
- private boolean validateCurrentSelection() {
- TreePath treeSelection = getSelection();
-
- IStatus status;
- if (treeSelection != null) {
- if (treeSelection.getSegmentCount() == 2) {
- status = new Status(IStatus.OK, AdtPlugin.PLUGIN_ID,
- IStatus.OK, "", //$NON-NLS-1$
- null);
- } else {
- status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- IStatus.ERROR, "You must select a Resource Item",
- null);
- }
- } else {
- status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- IStatus.ERROR, "", //$NON-NLS-1$
- null);
- }
-
- updateStatus(status);
-
- return status.isOK();
- }
-
- /**
- * Updates the new res button when the list selection changes.
- * The name of the button changes depending on the resource.
- */
- private void updateNewResButton() {
- ResourceType type = getSelectedResourceType();
-
- // We only support adding new strings right now
- mNewResButton.setEnabled(type == ResourceType.STRING);
-
- String title = String.format("New %1$s...",
- type == null ? "Resource" : type.getDisplayName());
- mNewResButton.setText(title);
- mNewResButton.pack();
- }
-
- /**
- * Callback invoked when the mNewResButton is selected by the user.
- */
- private class OnNewResButtonSelected extends SelectionAdapter {
- @Override
- public void widgetSelected(SelectionEvent e) {
- super.widgetSelected(e);
-
- ResourceType type = getSelectedResourceType();
-
- // We currently only support strings
- if (type == ResourceType.STRING) {
-
- ExtractStringRefactoring ref = new ExtractStringRefactoring(
- mProject, true /*enforceNew*/);
- RefactoringWizard wizard = new ExtractStringWizard(ref, mProject);
- RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation(wizard);
- try {
- IWorkbench w = PlatformUI.getWorkbench();
- if (op.run(w.getDisplay().getActiveShell(), wizard.getDefaultPageTitle()) ==
- IDialogConstants.OK_ID) {
- mTreeViewer.refresh();
-
- // select it if possible
- setupInitialSelection(type, ref.getXmlStringId());
- }
- } catch (InterruptedException ex) {
- // Interrupted. Pass.
- }
- }
- }
- }
-
- /**
- * Returns the {@link ResourceType} of the selected element, if any.
- * Returns null if nothing suitable is selected.
- */
- private ResourceType getSelectedResourceType() {
- ResourceType type = null;
-
- TreePath selection = getSelection();
- if (selection != null && selection.getSegmentCount() > 0) {
- Object first = selection.getFirstSegment();
- if (first instanceof ResourceType) {
- type = (ResourceType) first;
- }
- }
- return type;
- }
-
- /**
- * Sets up the initial selection.
- * <p/>
- * This parses {@link #mCurrentResource} to find out the resource type and the resource name.
- */
- private void setupInitialSelection() {
- // checks the inline id pattern first as it's more restrictive than the other one.
- Matcher m = sInlineIdResourcePattern.matcher(mCurrentResource);
- if (m.matches()) {
- // get the matching name
- String resourceName = m.group(1);
-
- // setup initial selection
- setupInitialSelection(ResourceType.ID, resourceName);
- } else {
- // attempts the inline id pattern
- m = sResourcePattern.matcher(mCurrentResource);
- if (m.matches()) {
- // get the resource type.
- ResourceType resourceType = ResourceType.getEnum(m.group(1));
- if (resourceType != null) {
- // get the matching name
- String resourceName = m.group(2);
-
- // setup initial selection
- setupInitialSelection(resourceType, resourceName);
- }
- }
- }
- }
-
- /**
- * Sets up the initial selection based on a {@link ResourceType} and a resource name.
- * @param resourceType the resource type.
- * @param resourceName the resource name.
- */
- private void setupInitialSelection(ResourceType resourceType, String resourceName) {
- // get all the resources of this type
- Collection<ResourceItem> resourceItems =
- mProjectResources.getResourceItemsOfType(resourceType);
-
- for (ResourceItem resourceItem : resourceItems) {
- if (resourceName.equals(resourceItem.getName())) {
- // name of the resource match, we select it,
- TreePath treePath = new TreePath(new Object[] { resourceType, resourceItem });
- mFilteredTree.getViewer().setSelection(
- new TreeSelection(treePath),
- true /*reveal*/);
-
- // and we're done.
- return;
- }
- }
-
- // if we get here, the resource type is valid, but the resource is missing.
- // we select and expand the resource type element.
- TreePath treePath = new TreePath(new Object[] { resourceType });
- mFilteredTree.getViewer().setSelection(
- new TreeSelection(treePath),
- true /*reveal*/);
- mFilteredTree.getViewer().setExpandedState(resourceType, true /* expanded */);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ResourceChooser.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ResourceChooser.java
deleted file mode 100644
index ce828cf2a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ResourceChooser.java
+++ /dev/null
@@ -1,958 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.ui;
-
-import static com.android.SdkConstants.ANDROID_PREFIX;
-import static com.android.SdkConstants.PREFIX_RESOURCE_REF;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.rendering.api.ResourceValue;
-import com.android.ide.common.resources.ResourceItem;
-import com.android.ide.common.resources.ResourceRepository;
-import com.android.ide.common.resources.ResourceResolver;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.assetstudio.OpenCreateAssetSetWizardAction;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart;
-import com.android.ide.eclipse.adt.internal.editors.layout.properties.PropertyFactory;
-import com.android.ide.eclipse.adt.internal.refactorings.extractstring.ExtractStringRefactoring;
-import com.android.ide.eclipse.adt.internal.refactorings.extractstring.ExtractStringWizard;
-import com.android.ide.eclipse.adt.internal.resources.ResourceHelper;
-import com.android.ide.eclipse.adt.internal.resources.ResourceNameValidator;
-import com.android.ide.eclipse.adt.internal.resources.manager.ProjectResources;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.resources.ResourceType;
-import com.android.utils.Pair;
-import com.google.common.collect.Maps;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.IInputValidator;
-import org.eclipse.jface.dialogs.InputDialog;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.window.Window;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizard;
-import org.eclipse.ltk.ui.refactoring.RefactoringWizardOpenOperation;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.AbstractElementListSelectionDialog;
-import org.eclipse.ui.dialogs.SelectionStatusDialog;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * A dialog to let the user select a resource based on a resource type.
- */
-public class ResourceChooser extends AbstractElementListSelectionDialog implements ModifyListener {
- /** The return code from the dialog for the user choosing "Clear" */
- public static final int CLEAR_RETURN_CODE = -5;
- /** The dialog button ID for the user choosing "Clear" */
- private static final int CLEAR_BUTTON_ID = CLEAR_RETURN_CODE;
-
- private Pattern mProjectResourcePattern;
- private ResourceType mResourceType;
- private final List<ResourceRepository> mProjectResources;
- private final ResourceRepository mFrameworkResources;
- private Pattern mSystemResourcePattern;
- private Button mProjectButton;
- private Button mSystemButton;
- private Button mNewButton;
- private String mCurrentResource;
- private final IProject mProject;
- private IInputValidator mInputValidator;
-
- /** Helper object used to draw previews for drawables and colors. */
- private ResourcePreviewHelper mPreviewHelper;
-
- /**
- * Textfield for editing the actual returned value, updated when selection
- * changes. Only shown if {@link #mShowValueText} is true.
- */
- private Text mEditValueText;
-
- /**
- * Whether the {@link #mEditValueText} textfield should be shown when the dialog is created.
- */
- private boolean mShowValueText;
-
- /**
- * Flag indicating whether it's the first time {@link #handleSelectionChanged()} is called.
- * This is used to filter out the first selection event, always called by the superclass
- * when the widget is created, to distinguish between "the dialog was created" and
- * "the user clicked on a selection result", since only the latter should wipe out the
- * manual user edit shown in the value text.
- */
- private boolean mFirstSelect = true;
-
- /**
- * Label used to show the resolved value in the resource chooser. Only shown
- * if the {@link #mResourceResolver} field is set.
- */
- private Label mResolvedLabel;
-
- /** Resource resolver used to show actual values for resources selected. (Optional). */
- private ResourceResolver mResourceResolver;
-
- /**
- * Creates a Resource Chooser dialog.
- * @param project Project being worked on
- * @param type The type of the resource to choose
- * @param projectResources The repository for the project
- * @param frameworkResources The Framework resource repository
- * @param parent the parent shell
- */
- private ResourceChooser(
- @NonNull IProject project,
- @NonNull ResourceType type,
- @NonNull List<ResourceRepository> projectResources,
- @Nullable ResourceRepository frameworkResources,
- @NonNull Shell parent) {
- super(parent, new ResourceLabelProvider());
- mProject = project;
-
- mResourceType = type;
- mProjectResources = projectResources;
- mFrameworkResources = frameworkResources;
-
- mProjectResourcePattern = Pattern.compile(
- PREFIX_RESOURCE_REF + mResourceType.getName() + "/(.+)"); //$NON-NLS-1$
-
- mSystemResourcePattern = Pattern.compile(
- ANDROID_PREFIX + mResourceType.getName() + "/(.+)"); //$NON-NLS-1$
-
- setTitle("Resource Chooser");
- setMessage(String.format("Choose a %1$s resource",
- mResourceType.getDisplayName().toLowerCase(Locale.US)));
- }
-
- /**
- * Creates a new {@link ResourceChooser}
- *
- * @param editor the associated layout editor
- * @param type the resource type to choose
- * @return a new {@link ResourceChooser}
- */
- @NonNull
- public static ResourceChooser create(
- @NonNull GraphicalEditorPart editor,
- @NonNull ResourceType type) {
- IProject project = editor.getProject();
- Shell parent = editor.getCanvasControl().getShell();
- AndroidTargetData targetData = editor.getEditorDelegate().getEditor().getTargetData();
- ResourceChooser chooser = create(project, type, targetData, parent);
-
- // When editing Strings, allow editing the value text directly. When we
- // get inline editing support (where values entered directly into the
- // textual widget are translated automatically into a resource) this can
- // go away.
- if (type == ResourceType.STRING) {
- chooser.setResourceResolver(editor.getResourceResolver());
- chooser.setShowValueText(true);
- } else if (type == ResourceType.DIMEN || type == ResourceType.INTEGER) {
- chooser.setResourceResolver(editor.getResourceResolver());
- }
-
- chooser.setPreviewHelper(new ResourcePreviewHelper(chooser, editor));
- return chooser;
- }
-
- /**
- * Creates a new {@link ResourceChooser}
- *
- * @param project the associated project
- * @param type the resource type to choose
- * @param targetData the associated framework target data
- * @param parent the target shell
- * @return a new {@link ResourceChooser}
- */
- @NonNull
- public static ResourceChooser create(
- @NonNull IProject project,
- @NonNull ResourceType type,
- @Nullable AndroidTargetData targetData,
- @NonNull Shell parent) {
- ResourceManager manager = ResourceManager.getInstance();
-
- List<ResourceRepository> projectResources = new ArrayList<ResourceRepository>();
- ProjectResources resources = manager.getProjectResources(project);
- projectResources.add(resources);
-
- // Add in library project resources
- ProjectState projectState = Sdk.getProjectState(project);
- if (projectState != null) {
- List<IProject> libraries = projectState.getFullLibraryProjects();
- if (libraries != null && !libraries.isEmpty()) {
- for (IProject library : libraries) {
- projectResources.add(manager.getProjectResources(library));
- }
- }
- }
-
- ResourceRepository frameworkResources =
- targetData != null ? targetData.getFrameworkResources() : null;
- return new ResourceChooser(project, type, projectResources, frameworkResources, parent);
- }
-
- /**
- * Sets whether this dialog should show the value field as a separate text
- * value (and take the resulting value of the dialog from this text field
- * rather than from the selection)
- *
- * @param showValueText if true, show the value text field
- * @return this, for constructor chaining
- */
- public ResourceChooser setShowValueText(boolean showValueText) {
- mShowValueText = showValueText;
-
- return this;
- }
-
- /**
- * Sets the resource resolver to use to show resolved values for the current
- * selection
- *
- * @param resourceResolver the resource resolver to use
- * @return this, for constructor chaining
- */
- public ResourceChooser setResourceResolver(ResourceResolver resourceResolver) {
- mResourceResolver = resourceResolver;
-
- return this;
- }
-
- /**
- * Sets the {@link ResourcePreviewHelper} to use to preview drawable
- * resources, if any
- *
- * @param previewHelper the helper to use
- * @return this, for constructor chaining
- */
- public ResourceChooser setPreviewHelper(ResourcePreviewHelper previewHelper) {
- mPreviewHelper = previewHelper;
-
- return this;
- }
-
- /**
- * Sets the initial dialog size
- *
- * @param width the initial width
- * @param height the initial height
- * @return this, for constructor chaining
- */
- public ResourceChooser setInitialSize(int width, int height) {
- setSize(width, height);
-
- return this;
- }
-
- @Override
- public void create() {
- super.create();
-
- if (mShowValueText) {
- mEditValueText.selectAll();
- mEditValueText.setFocus();
- }
- }
-
- @Override
- protected void createButtonsForButtonBar(Composite parent) {
- createButton(parent, CLEAR_BUTTON_ID, "Clear", false /*defaultButton*/);
- super.createButtonsForButtonBar(parent);
- }
-
- @Override
- protected void buttonPressed(int buttonId) {
- super.buttonPressed(buttonId);
-
- if (buttonId == CLEAR_BUTTON_ID) {
- assert CLEAR_RETURN_CODE != Window.OK && CLEAR_RETURN_CODE != Window.CANCEL;
- setReturnCode(CLEAR_RETURN_CODE);
- close();
- }
- }
-
- /**
- * Sets the currently selected item
- *
- * @param resource the resource url for the currently selected item
- * @return this, for constructor chaining
- */
- public ResourceChooser setCurrentResource(@Nullable String resource) {
- mCurrentResource = resource;
-
- if (mShowValueText && mEditValueText != null) {
- mEditValueText.setText(resource);
- }
-
- return this;
- }
-
- /**
- * Returns the currently selected url
- *
- * @return the currently selected url
- */
- @Nullable
- public String getCurrentResource() {
- return mCurrentResource;
- }
-
- /**
- * Sets the input validator to use, if any
- *
- * @param inputValidator the validator
- * @return this, for constructor chaining
- */
- public ResourceChooser setInputValidator(@Nullable IInputValidator inputValidator) {
- mInputValidator = inputValidator;
-
- return this;
- }
-
- @Override
- protected void computeResult() {
- if (mShowValueText) {
- mCurrentResource = mEditValueText.getText();
- if (mCurrentResource.length() == 0) {
- mCurrentResource = null;
- }
- return;
- }
-
- computeResultFromSelection();
- }
-
- private void computeResultFromSelection() {
- if (getSelectionIndex() == -1) {
- mCurrentResource = null;
- return;
- }
-
- Object[] elements = getSelectedElements();
- if (elements.length == 1 && elements[0] instanceof ResourceItem) {
- ResourceItem item = (ResourceItem)elements[0];
-
- mCurrentResource = item.getXmlString(mResourceType, mSystemButton.getSelection());
-
- if (mInputValidator != null && mInputValidator.isValid(mCurrentResource) != null) {
- mCurrentResource = null;
- }
- }
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite top = (Composite)super.createDialogArea(parent);
-
- createMessageArea(top);
-
- createButtons(top);
- createFilterText(top);
- createFilteredList(top);
-
- // create the "New Resource" button
- createNewResButtons(top);
-
- // Optionally create the value text field, if {@link #mShowValueText} is true
- createValueField(top);
-
- setupResourceList();
- selectResourceString(mCurrentResource);
-
- return top;
- }
-
- /**
- * Creates the radio button to switch between project and system resources.
- * @param top the parent composite
- */
- private void createButtons(Composite top) {
- mProjectButton = new Button(top, SWT.RADIO);
- mProjectButton.setText("Project Resources");
- mProjectButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- super.widgetSelected(e);
- if (mProjectButton.getSelection()) {
- // Clear selection before changing the list contents. This works around
- // a bug in the superclass where switching to the framework resources,
- // choosing one of the last resources, then switching to the project
- // resources would cause an exception when calling getSelection() because
- // selection state doesn't get cleared when we set new contents on
- // the filtered list.
- fFilteredList.setSelection(new int[0]);
- setupResourceList();
- updateNewButton(false /*isSystem*/);
- updateValue();
- }
- }
- });
- mSystemButton = new Button(top, SWT.RADIO);
- mSystemButton.setText("System Resources");
- mSystemButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- super.widgetSelected(e);
- if (mSystemButton.getSelection()) {
- fFilteredList.setSelection(new int[0]);
- setupResourceList();
- updateNewButton(true /*isSystem*/);
- updateValue();
- }
- }
- });
- if (mFrameworkResources == null) {
- mSystemButton.setVisible(false);
- }
- }
-
- /**
- * Creates the "New Resource" button.
- * @param top the parent composite
- */
- private void createNewResButtons(Composite top) {
- mNewButton = new Button(top, SWT.NONE);
-
- String title = String.format("New %1$s...", mResourceType.getDisplayName());
- if (mResourceType == ResourceType.DRAWABLE) {
- title = "Create New Icon...";
- }
- mNewButton.setText(title);
-
- mNewButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- super.widgetSelected(e);
-
- if (mResourceType == ResourceType.STRING) {
- // Special case: Use Extract String refactoring wizard UI
- String newName = createNewString();
- selectAddedItem(newName);
- } else if (mResourceType == ResourceType.DRAWABLE) {
- // Special case: Use the "Create Icon Set" wizard
- OpenCreateAssetSetWizardAction action =
- new OpenCreateAssetSetWizardAction(mProject);
- action.run();
- List<IResource> files = action.getCreatedFiles();
- if (files != null && files.size() > 0) {
- String newName = AdtUtils.stripAllExtensions(files.get(0).getName());
- // Recompute the "current resource" to select the new id
- ResourceItem[] items = setupResourceList();
- selectItemName(newName, items);
- }
- } else {
- if (ResourceHelper.isValueBasedResourceType(mResourceType)) {
- String newName = createNewValue(mResourceType);
- if (newName != null) {
- selectAddedItem(newName);
- }
- } else {
- String newName = createNewFile(mResourceType);
- if (newName != null) {
- selectAddedItem(newName);
- }
- }
- }
- }
-
- private void selectAddedItem(@NonNull String newName) {
- // Recompute the "current resource" to select the new id
- ResourceItem[] items = setupResourceList();
-
- // Ensure that the name is in the list. There's a delay after
- // an item is added (until the builder runs and processes the delta)
- // so if it's not in the list, add it
- boolean found = false;
- for (ResourceItem item : items) {
- if (newName.equals(item.getName())) {
- found = true;
- break;
- }
- }
- if (!found) {
- ResourceItem[] newItems = new ResourceItem[items.length + 1];
- System.arraycopy(items, 0, newItems, 0, items.length);
- newItems[items.length] = new ResourceItem(newName);
- items = newItems;
- Arrays.sort(items);
- setListElements(items);
- fFilteredList.setEnabled(newItems.length > 0);
- }
-
- selectItemName(newName, items);
- }
- });
- }
-
- /**
- * Creates the value text field.
- *
- * @param top the parent composite
- */
- private void createValueField(Composite top) {
- if (mShowValueText) {
- mEditValueText = new Text(top, SWT.BORDER);
- if (mCurrentResource != null) {
- mEditValueText.setText(mCurrentResource);
- }
- mEditValueText.addModifyListener(this);
-
- GridData data = new GridData();
- data.grabExcessVerticalSpace = false;
- data.grabExcessHorizontalSpace = true;
- data.horizontalAlignment = GridData.FILL;
- data.verticalAlignment = GridData.BEGINNING;
- mEditValueText.setLayoutData(data);
- mEditValueText.setFont(top.getFont());
- }
-
- if (mResourceResolver != null) {
- mResolvedLabel = new Label(top, SWT.NONE);
- GridData data = new GridData();
- data.grabExcessVerticalSpace = false;
- data.grabExcessHorizontalSpace = true;
- data.horizontalAlignment = GridData.FILL;
- data.verticalAlignment = GridData.BEGINNING;
- mResolvedLabel.setLayoutData(data);
- }
-
- Composite workaround = PropertyFactory.addWorkaround(top);
- if (workaround != null) {
- workaround.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1));
- }
- }
-
- private void updateResolvedLabel() {
- if (mResourceResolver == null) {
- return;
- }
-
- String v = null;
- if (mCurrentResource != null) {
- v = mCurrentResource;
- if (mCurrentResource.startsWith(PREFIX_RESOURCE_REF)) {
- ResourceValue value = mResourceResolver.findResValue(mCurrentResource, false);
- if (value != null) {
- v = value.getValue();
- }
- }
- }
-
- if (v == null) {
- v = "";
- }
-
- mResolvedLabel.setText(String.format("Resolved Value: %1$s", v));
- }
-
- @Override
- protected void handleSelectionChanged() {
- super.handleSelectionChanged();
- if (mInputValidator != null) {
- Object[] elements = getSelectedElements();
- if (elements.length == 1 && elements[0] instanceof ResourceItem) {
- ResourceItem item = (ResourceItem)elements[0];
- String current = item.getXmlString(mResourceType, mSystemButton.getSelection());
- String error = mInputValidator.isValid(current);
- IStatus status;
- if (error != null) {
- status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, error);
- } else {
- status = new Status(IStatus.OK, AdtPlugin.PLUGIN_ID, null);
- }
- updateStatus(status);
- }
- }
-
- updateValue();
- }
-
- private void updateValue() {
- if (mPreviewHelper != null) {
- computeResult();
- mPreviewHelper.updatePreview(mResourceType, mCurrentResource);
- }
-
- if (mShowValueText) {
- if (mFirstSelect) {
- mFirstSelect = false;
- mEditValueText.selectAll();
- } else {
- computeResultFromSelection();
- mEditValueText.setText(mCurrentResource != null ? mCurrentResource : "");
- }
- }
-
- if (mResourceResolver != null) {
- if (!mShowValueText) {
- computeResultFromSelection();
- }
- updateResolvedLabel();
- }
- }
-
- @Nullable
- private String createNewFile(ResourceType type) {
- // Show a name/value dialog entering the key name and the value
- Shell shell = AdtPlugin.getShell();
- if (shell == null) {
- return null;
- }
-
- ResourceNameValidator validator = ResourceNameValidator.create(true /*allowXmlExtension*/,
- mProject, mResourceType);
- InputDialog d = new InputDialog(
- AdtPlugin.getShell(),
- "Enter name", // title
- "Enter name",
- "", //$NON-NLS-1$
- validator);
- if (d.open() == Window.OK) {
- String name = d.getValue().trim();
- if (name.length() == 0) {
- return null;
- }
-
- Pair<IFile, IRegion> resource = ResourceHelper.createResource(mProject, type, name,
- null);
- if (resource != null) {
- return name;
- }
- }
-
- return null;
- }
-
-
- @Nullable
- private String createNewValue(ResourceType type) {
- // Show a name/value dialog entering the key name and the value
- Shell shell = AdtPlugin.getShell();
- if (shell == null) {
- return null;
- }
- NameValueDialog dialog = new NameValueDialog(shell, getFilter());
- if (dialog.open() != Window.OK) {
- return null;
- }
-
- String name = dialog.getName();
- String value = dialog.getValue();
- if (name.length() == 0 || value.length() == 0) {
- return null;
- }
-
- Pair<IFile, IRegion> resource = ResourceHelper.createResource(mProject, type, name, value);
- if (resource != null) {
- return name;
- }
-
- return null;
- }
-
- private String createNewString() {
- ExtractStringRefactoring ref = new ExtractStringRefactoring(
- mProject, true /*enforceNew*/);
- RefactoringWizard wizard = new ExtractStringWizard(ref, mProject);
- RefactoringWizardOpenOperation op = new RefactoringWizardOpenOperation(wizard);
- try {
- IWorkbench w = PlatformUI.getWorkbench();
- if (op.run(w.getDisplay().getActiveShell(), wizard.getDefaultPageTitle()) ==
- IDialogConstants.OK_ID) {
- return ref.getXmlStringId();
- }
- } catch (InterruptedException ex) {
- // Interrupted. Pass.
- }
-
- return null;
- }
-
- /**
- * Setups the current list.
- */
- private ResourceItem[] setupResourceList() {
- Collection<ResourceItem> items = null;
- if (mProjectButton.getSelection()) {
- if (mProjectResources.size() == 1) {
- items = mProjectResources.get(0).getResourceItemsOfType(mResourceType);
- } else {
- Map<String, ResourceItem> merged = Maps.newHashMapWithExpectedSize(200);
- for (ResourceRepository repository : mProjectResources) {
- for (ResourceItem item : repository.getResourceItemsOfType(mResourceType)) {
- if (!merged.containsKey(item.getName())) {
- merged.put(item.getName(), item);
- }
- }
- }
- items = merged.values();
- }
- } else if (mSystemButton.getSelection()) {
- items = mFrameworkResources.getResourceItemsOfType(mResourceType);
- }
-
- if (items == null) {
- items = Collections.emptyList();
- }
-
- ResourceItem[] arrayItems = items.toArray(new ResourceItem[items.size()]);
-
- // sort the array
- Arrays.sort(arrayItems);
-
- setListElements(arrayItems);
- fFilteredList.setEnabled(arrayItems.length > 0);
-
- return arrayItems;
- }
-
- /**
- * Select an item by its name, if possible.
- */
- private void selectItemName(String itemName, ResourceItem[] items) {
- if (itemName == null || items == null) {
- return;
- }
-
- for (ResourceItem item : items) {
- if (itemName.equals(item.getName())) {
- setSelection(new Object[] { item });
- break;
- }
- }
- }
-
- /**
- * Select an item by its full resource string.
- * This also selects between project and system repository based on the resource string.
- */
- private void selectResourceString(String resourceString) {
- boolean isSystem = false;
- String itemName = null;
-
- if (resourceString != null) {
- // Is this a system resource?
- // If not a system resource or if they are not available, this will be a project res.
- Matcher m = mSystemResourcePattern.matcher(resourceString);
- if (m.matches()) {
- itemName = m.group(1);
- isSystem = true;
- }
-
- if (!isSystem && itemName == null) {
- // Try to match project resource name
- m = mProjectResourcePattern.matcher(resourceString);
- if (m.matches()) {
- itemName = m.group(1);
- }
- }
- }
-
- // Update the repository selection
- mProjectButton.setSelection(!isSystem);
- mSystemButton.setSelection(isSystem);
- updateNewButton(isSystem);
-
- // Update the list
- ResourceItem[] items = setupResourceList();
-
- // If we have a selection name, select it
- if (itemName != null) {
- selectItemName(itemName, items);
- }
- }
-
- private void updateNewButton(boolean isSystem) {
- mNewButton.setEnabled(!isSystem && ResourceHelper.canCreateResourceType(mResourceType));
- }
-
- // ---- Implements ModifyListener ----
-
- @Override
- public void modifyText(ModifyEvent e) {
- if (e.getSource() == mEditValueText && mResourceResolver != null) {
- mCurrentResource = mEditValueText.getText();
-
- if (mCurrentResource.startsWith(PREFIX_RESOURCE_REF)) {
- if (mProjectResourcePattern.matcher(mCurrentResource).matches() ||
- mSystemResourcePattern.matcher(mCurrentResource).matches()) {
- updateResolvedLabel();
- }
- } else {
- updateResolvedLabel();
- }
- }
- }
-
- /** Dialog asking for a Name/Value pair */
- private class NameValueDialog extends SelectionStatusDialog implements Listener {
- private org.eclipse.swt.widgets.Text mNameText;
- private org.eclipse.swt.widgets.Text mValueText;
- private String mInitialName;
- private String mName;
- private String mValue;
- private ResourceNameValidator mValidator;
-
- public NameValueDialog(Shell parent, String initialName) {
- super(parent);
- mInitialName = initialName;
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite container = new Composite(parent, SWT.NONE);
- container.setLayout(new GridLayout(2, false));
- GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1);
- // Wide enough to accommodate the error label
- gridData.widthHint = 500;
- container.setLayoutData(gridData);
-
-
- Label nameLabel = new Label(container, SWT.NONE);
- nameLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- nameLabel.setText("Name:");
-
- mNameText = new org.eclipse.swt.widgets.Text(container, SWT.BORDER);
- mNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- if (mInitialName != null) {
- mNameText.setText(mInitialName);
- mNameText.selectAll();
- }
-
- Label valueLabel = new Label(container, SWT.NONE);
- valueLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- valueLabel.setText("Value:");
-
- mValueText = new org.eclipse.swt.widgets.Text(container, SWT.BORDER);
- mValueText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
-
- mNameText.addListener(SWT.Modify, this);
- mValueText.addListener(SWT.Modify, this);
-
- validate();
-
- return container;
- }
-
- @Override
- protected void computeResult() {
- mName = mNameText.getText().trim();
- mValue = mValueText.getText().trim();
- }
-
- private String getName() {
- return mName;
- }
-
- private String getValue() {
- return mValue;
- }
-
- @Override
- public void handleEvent(Event event) {
- validate();
- }
-
- private void validate() {
- IStatus status;
- computeResult();
- if (mName.length() == 0) {
- status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, "Enter a name");
- } else if (mValue.length() == 0) {
- status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, "Enter a value");
- } else {
- if (mValidator == null) {
- mValidator = ResourceNameValidator.create(false, mProject, mResourceType);
- }
- String error = mValidator.isValid(mName);
- if (error != null) {
- status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, error);
- } else {
- status = new Status(IStatus.OK, AdtPlugin.PLUGIN_ID, null);
- }
- }
- updateStatus(status);
- }
- }
-
- /**
- * Open the resource chooser for the given type, associated with the given
- * editor
- *
- * @param graphicalEditor the editor associated with the resource to be
- * chosen (used to find the associated Android target to be used
- * for framework resources etc)
- * @param type the resource type to be chosen
- * @param currentValue the current value, or null
- * @param validator a validator to be used, or null
- * @return the chosen resource, null if cancelled and "" if value should be
- * cleared
- */
- public static String chooseResource(
- @NonNull GraphicalEditorPart graphicalEditor,
- @NonNull ResourceType type,
- String currentValue, IInputValidator validator) {
- ResourceChooser chooser = create(graphicalEditor, type).
- setCurrentResource(currentValue);
- if (validator != null) {
- // Ensure wide enough to accommodate validator error message
- chooser.setSize(85, 10);
- chooser.setInputValidator(validator);
- }
- int result = chooser.open();
- if (result == ResourceChooser.CLEAR_RETURN_CODE) {
- return ""; //$NON-NLS-1$
- } else if (result == Window.OK) {
- return chooser.getCurrentResource();
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ResourceContentProvider.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ResourceContentProvider.java
deleted file mode 100644
index d26dfaf4a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ResourceContentProvider.java
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.ui;
-
-import com.android.ide.common.resources.ResourceFile;
-import com.android.ide.common.resources.ResourceItem;
-import com.android.ide.common.resources.ResourceRepository;
-import com.android.resources.ResourceType;
-
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * Content provider for the Resource Explorer TreeView.
- * Each level of the tree is represented by a different class.
- * <ul>
- * <li>{@link ResourceType}. This represents the list of existing Resource Type present
- * in the resources. This can be matched to the subclasses inside the class <code>R</code>
- * </li>
- * <ul>
- * <li>{@link ResourceItem}. This represents one resource (which can existing in various alternate
- * versions). This is similar to the resource Ids defined as <code>R.sometype.id</code>.
- * </li>
- * <ul>
- * <li>{@link ResourceFile}. (optional) This represents a particular version of the
- * {@link ResourceItem}. It is displayed as a list of resource qualifier.
- * </li>
- * </ul>
- * </ul>
- * </ul>
- *
- * @see ResourceLabelProvider
- */
-public class ResourceContentProvider implements ITreeContentProvider {
-
- /**
- * The current ProjectResources being displayed.
- */
- private ResourceRepository mResources;
-
- private boolean mFullLevels;
-
- /**
- * Constructs a new content providers for resource display.
- * @param fullLevels if <code>true</code> the content provider will suppport all 3 levels. If
- * <code>false</code>, only two levels are provided.
- */
- public ResourceContentProvider(boolean fullLevels) {
- mFullLevels = fullLevels;
- }
-
- @Override
- public Object[] getChildren(Object parentElement) {
- if (parentElement instanceof ResourceType) {
- Object[] array = mResources.getResourceItemsOfType(
- (ResourceType)parentElement).toArray();
- Arrays.sort(array);
- return array;
- } else if (mFullLevels && parentElement instanceof ResourceItem) {
- return ((ResourceItem)parentElement).getSourceFileArray();
- }
- return null;
- }
-
- @Override
- public Object getParent(Object element) {
- // pass
- return null;
- }
-
- @Override
- public boolean hasChildren(Object element) {
- if (element instanceof ResourceType) {
- return mResources.hasResourcesOfType((ResourceType)element);
- } else if (mFullLevels && element instanceof ResourceItem) {
- return ((ResourceItem)element).hasAlternates();
- }
- return false;
- }
-
- @Override
- public Object[] getElements(Object inputElement) {
- if (inputElement instanceof ResourceRepository) {
- if ((ResourceRepository)inputElement == mResources) {
- // get the top level resources.
- List<ResourceType> types = mResources.getAvailableResourceTypes();
- Collections.sort(types);
- return types.toArray();
- }
- }
-
- return new Object[0];
- }
-
- @Override
- public void dispose() {
- // pass
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- if (newInput instanceof ResourceRepository) {
- mResources = (ResourceRepository)newInput;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ResourceExplorerView.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ResourceExplorerView.java
deleted file mode 100644
index f48423c84..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ResourceExplorerView.java
+++ /dev/null
@@ -1,353 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.ui;
-
-import com.android.ide.common.resources.ResourceFile;
-import com.android.ide.common.resources.ResourceItem;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.resources.manager.GlobalProjectMonitor.IResourceEventListener;
-import com.android.ide.eclipse.adt.internal.resources.manager.ProjectResources;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.ide.eclipse.adt.io.IFileWrapper;
-import com.android.io.IAbstractFile;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.viewers.DoubleClickEvent;
-import org.eclipse.jface.viewers.IDoubleClickListener;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.SWTException;
-import org.eclipse.swt.events.ControlEvent;
-import org.eclipse.swt.events.ControlListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeColumn;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IFileEditorInput;
-import org.eclipse.ui.ISelectionListener;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.ui.part.ViewPart;
-
-import java.util.Iterator;
-
-/**
- * Resource Explorer View.
- * <p/>
- * This contains a basic Tree view, and uses a TreeViewer to handle the data.
- * <p/>
- * The view listener to change in selection in the workbench, and update to show the resource
- * of the project of the current selected item (either item in the package explorer, or of the
- * current editor).
- *
- * @see ResourceContentProvider
- */
-public class ResourceExplorerView extends ViewPart implements ISelectionListener,
- IResourceEventListener {
-
- // Note: keep using the obsolete SdkConstants.EDITORS_NAMESPACE (which used
- // to be the Editors Plugin ID) to keep existing preferences functional.
- private final static String PREFS_COLUMN_RES =
- AdtConstants.EDITORS_NAMESPACE + "ResourceExplorer.Col1"; //$NON-NLS-1$
- private final static String PREFS_COLUMN_2 =
- AdtConstants.EDITORS_NAMESPACE + "ResourceExplorer.Col2"; //$NON-NLS-1$
-
- private Tree mTree;
- private TreeViewer mTreeViewer;
-
- private IProject mCurrentProject;
-
- public ResourceExplorerView() {
- }
-
- @Override
- public void createPartControl(Composite parent) {
- mTree = new Tree(parent, SWT.SINGLE | SWT.VIRTUAL);
- mTree.setLayoutData(new GridData(GridData.FILL_BOTH));
- mTree.setHeaderVisible(true);
- mTree.setLinesVisible(true);
-
- final IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore();
-
- // create 2 columns. The main one with the resources, and an "info" column.
- createTreeColumn(mTree, "Resources", SWT.LEFT,
- "abcdefghijklmnopqrstuvwxz", -1, PREFS_COLUMN_RES, store); //$NON-NLS-1$
- createTreeColumn(mTree, "Info", SWT.LEFT,
- "0123456789", -1, PREFS_COLUMN_2, store); //$NON-NLS-1$
-
- // create the jface wrapper
- mTreeViewer = new TreeViewer(mTree);
-
- mTreeViewer.setContentProvider(new ResourceContentProvider(true /* fullLevels */));
- mTreeViewer.setLabelProvider(new ResourceLabelProvider());
-
- // listen to selection change in the workbench.
- IWorkbenchPage page = getSite().getPage();
-
- page.addSelectionListener(this);
-
- // init with current selection
- selectionChanged(getSite().getPart(), page.getSelection());
-
- // add support for double click.
- mTreeViewer.addDoubleClickListener(new IDoubleClickListener() {
- @Override
- public void doubleClick(DoubleClickEvent event) {
- ISelection sel = event.getSelection();
-
- if (sel instanceof IStructuredSelection) {
- IStructuredSelection selection = (IStructuredSelection) sel;
-
- if (selection.size() == 1) {
- Object element = selection.getFirstElement();
-
- // if it's a resourceFile, we directly open it.
- if (element instanceof ResourceFile) {
- try {
- IAbstractFile iAbstractFile = ((ResourceFile)element).getFile();
- if (iAbstractFile instanceof IFileWrapper) {
- IDE.openEditor(getSite().getWorkbenchWindow().getActivePage(),
- ((IFileWrapper)iAbstractFile).getIFile());
- }
- } catch (PartInitException e) {
- }
- } else if (element instanceof ResourceItem) {
- // if it's a ResourceItem, we open the first file, but only if
- // there's no alternate files.
- ResourceItem item = (ResourceItem)element;
-
- if (item.isEditableDirectly()) {
- ResourceFile[] files = item.getSourceFileArray();
- if (files[0] != null) {
- try {
- IAbstractFile iAbstractFile = files[0].getFile();
- if (iAbstractFile instanceof IFileWrapper) {
- IDE.openEditor(
- getSite().getWorkbenchWindow().getActivePage(),
- ((IFileWrapper)iAbstractFile).getIFile());
- }
- } catch (PartInitException e) {
- }
- }
- }
- }
- }
- }
- }
- });
-
- // set up the resource manager to send us resource change notification
- AdtPlugin.getDefault().getResourceMonitor().addResourceEventListener(this);
- }
-
- @Override
- public void dispose() {
- AdtPlugin.getDefault().getResourceMonitor().removeResourceEventListener(this);
-
- super.dispose();
- }
-
- @Override
- public void setFocus() {
- mTree.setFocus();
- }
-
- /**
- * Processes a new selection.
- */
- @Override
- public void selectionChanged(IWorkbenchPart part, ISelection selection) {
- // first we test if the part is an editor.
- if (part instanceof IEditorPart) {
- // if it is, we check if it's a file editor.
- IEditorInput input = ((IEditorPart)part).getEditorInput();
-
- if (input instanceof IFileEditorInput) {
- // from the file editor we can get the IFile object, and from it, the IProject.
- IFile file = ((IFileEditorInput)input).getFile();
-
- // get the file project
- IProject project = file.getProject();
-
- handleProjectSelection(project);
- }
- } else if (selection instanceof IStructuredSelection) {
- // if it's not an editor, we look for structured selection.
- for (Iterator<?> it = ((IStructuredSelection) selection).iterator();
- it.hasNext();) {
- Object element = it.next();
- IProject project = null;
-
- // if we are in the navigator or package explorer, the selection could contain a
- // IResource object.
- if (element instanceof IResource) {
- project = ((IResource) element).getProject();
- } else if (element instanceof IJavaElement) {
- // if we are in the package explorer on a java element, we handle that too.
- IJavaElement javaElement = (IJavaElement)element;
- IJavaProject javaProject = javaElement.getJavaProject();
- if (javaProject != null) {
- project = javaProject.getProject();
- }
- } else if (element instanceof IAdaptable) {
- // finally we try to get a project object from IAdaptable.
- project = (IProject) ((IAdaptable) element)
- .getAdapter(IProject.class);
- }
-
- // if we found a project, handle it, and return.
- if (project != null) {
- if (handleProjectSelection(project)) {
- return;
- }
- }
- }
- }
- }
-
- /**
- * Handles a project selection.
- * @param project the new selected project
- * @return true if the project could be processed.
- */
- private boolean handleProjectSelection(IProject project) {
- try {
- // if it's an android project, then we get its resources, and feed them
- // to the tree viewer.
- if (project.hasNature(AdtConstants.NATURE_DEFAULT)) {
- if (mCurrentProject != project) {
- ProjectResources projRes = ResourceManager.getInstance().getProjectResources(
- project);
- if (projRes != null) {
- mTreeViewer.setInput(projRes);
- mCurrentProject = project;
- return true;
- }
- }
- }
- } catch (CoreException e) {
- }
-
- return false;
- }
-
- /**
- * Create a TreeColumn with the specified parameters. If a
- * <code>PreferenceStore</code> object and a preference entry name String
- * object are provided then the column will listen to change in its width
- * and update the preference store accordingly.
- *
- * @param parent The Table parent object
- * @param header The header string
- * @param style The column style
- * @param sample_text A sample text to figure out column width if preference
- * value is missing
- * @param fixedSize a fixed size. If != -1 the column is non resizable
- * @param pref_name The preference entry name for column width
- * @param prefs The preference store
- */
- public void createTreeColumn(Tree parent, String header, int style,
- String sample_text, int fixedSize, final String pref_name,
- final IPreferenceStore prefs) {
-
- // create the column
- TreeColumn col = new TreeColumn(parent, style);
-
- if (fixedSize != -1) {
- col.setWidth(fixedSize);
- col.setResizable(false);
- } else {
- // if there is no pref store or the entry is missing, we use the sample
- // text and pack the column.
- // Otherwise we just read the width from the prefs and apply it.
- if (prefs == null || prefs.contains(pref_name) == false) {
- col.setText(sample_text);
- col.pack();
-
- // init the prefs store with the current value
- if (prefs != null) {
- prefs.setValue(pref_name, col.getWidth());
- }
- } else {
- col.setWidth(prefs.getInt(pref_name));
- }
-
- // if there is a pref store and a pref entry name, then we setup a
- // listener to catch column resize to put the new width value into the store.
- if (prefs != null && pref_name != null) {
- col.addControlListener(new ControlListener() {
- @Override
- public void controlMoved(ControlEvent e) {
- }
-
- @Override
- public void controlResized(ControlEvent e) {
- // get the new width
- int w = ((TreeColumn)e.widget).getWidth();
-
- // store in pref store
- prefs.setValue(pref_name, w);
- }
- });
- }
- }
-
- // set the header
- col.setText(header);
- }
-
- /**
- * Processes a start in a resource event change.
- */
- @Override
- public void resourceChangeEventStart() {
- // pass
- }
-
- /**
- * Processes the end of a resource change event.
- */
- @Override
- public void resourceChangeEventEnd() {
- try {
- mTree.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- if (mTree.isDisposed() == false) {
- mTreeViewer.refresh();
- }
- }
- });
- } catch (SWTException e) {
- // display is disposed. nothing to do.
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ResourceLabelProvider.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ResourceLabelProvider.java
deleted file mode 100644
index 5bf8615d8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ResourceLabelProvider.java
+++ /dev/null
@@ -1,142 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.ui;
-
-import com.android.ide.common.resources.ResourceFile;
-import com.android.ide.common.resources.ResourceItem;
-import com.android.resources.ResourceType;
-
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.viewers.ILabelProviderListener;
-import org.eclipse.jface.viewers.ITableLabelProvider;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-
-/**
- * Label provider for the Resource Explorer TreeView.
- * Each level of the tree is represented by a different class.
- * <ul>
- * <li>{@link ResourceType}. This represents the list of existing Resource Type present
- * in the resources. This can be matched to the subclasses inside the class <code>R</code>
- * </li>
- * <ul>
- * <li>{@link ResourceItem}. This represents one resource. The actual type can be
- * {@link ConfigurableResourceItem} (which can exist in various alternate versions),
- * or {@link IdResourceItem}.
- * This is similar to the resource Ids defined as <code>R.sometype.id</code>.
- * </li>
- * <ul>
- * <li>{@link ResourceFile}. This represents a particular version of the {@link ResourceItem}.
- * It is displayed as a list of resource qualifier.
- * </li>
- * </ul>
- * </ul>
- * </ul>
- *
- * @see ResourceContentProvider
- */
-public class ResourceLabelProvider implements ILabelProvider, ITableLabelProvider {
- private Image mWarningImage;
-
- public ResourceLabelProvider() {
- mWarningImage = PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(
- ISharedImages.IMG_OBJS_WARN_TSK).createImage();
- }
-
- /**
- * @see #getColumnImage(Object, int)
- */
- @Override
- public Image getImage(Object element) {
- // pass
- return null;
- }
-
- /**
- * @see #getColumnText(Object, int)
- */
- @Override
- public String getText(Object element) {
- return getColumnText(element, 0);
- }
-
- @Override
- public void addListener(ILabelProviderListener listener) {
- // pass
- }
-
- @Override
- public void dispose() {
- mWarningImage.dispose();
- }
-
- @Override
- public boolean isLabelProperty(Object element, String property) {
- return false;
- }
-
- @Override
- public void removeListener(ILabelProviderListener listener) {
- // pass
- }
-
- @Override
- public Image getColumnImage(Object element, int columnIndex) {
- if (columnIndex == 1) {
- if (element instanceof ResourceItem) {
- ResourceItem item = (ResourceItem)element;
- if (item.hasDefault() == false) {
- return mWarningImage;
- }
- }
- }
- return null;
- }
-
- @Override
- public String getColumnText(Object element, int columnIndex) {
- switch (columnIndex) {
- case 0:
- if (element instanceof ResourceType) {
- return ((ResourceType)element).getDisplayName();
- } else if (element instanceof ResourceItem) {
- return ((ResourceItem)element).getName();
- } else if (element instanceof ResourceFile) {
- return ((ResourceFile)element).getFolder().getConfiguration().toDisplayString();
- }
- break;
- case 1:
- if (element instanceof ResourceItem) {
- ResourceItem item = (ResourceItem)element;
- if (item.isDeclaredInline()) {
- return "Declared inline";
- } else {
- int count = item.getAlternateCount();
- if (count > 0) {
- if (item.hasDefault()) {
- count++;
- }
- return String.format("%1$d version(s)", count);
- }
- }
- }
- return null;
- }
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ResourcePreviewHelper.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ResourcePreviewHelper.java
deleted file mode 100644
index afd1df92d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/ResourcePreviewHelper.java
+++ /dev/null
@@ -1,195 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.ui;
-
-import static com.android.SdkConstants.DOT_9PNG;
-import static com.android.utils.SdkUtils.endsWithIgnoreCase;
-
-import com.android.ide.common.rendering.api.ResourceValue;
-import com.android.ide.common.resources.ResourceResolver;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.ImageControl;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.ImageUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderService;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.SwtUtils;
-import com.android.ide.eclipse.adt.internal.resources.ResourceHelper;
-import com.android.resources.ResourceType;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.DialogTray;
-import org.eclipse.jface.dialogs.TrayDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-
-import java.awt.image.BufferedImage;
-import java.io.File;
-import java.io.IOException;
-
-import javax.imageio.ImageIO;
-
-/**
- * The {@link ResourcePreviewHelper} provides help to {@link TrayDialog} resource choosers
- * where some resources (such as drawables and colors) are previewed in the tray area.
- */
-public class ResourcePreviewHelper {
- /**
- * The width of the preview rendering
- * <p>
- * TODO: Make the preview rendering resize if the tray area is resized
- */
- private static final int WIDTH = 100;
- /** The height of the preview rendering */
- private static final int HEIGHT = 100;
-
- private final GraphicalEditorPart mEditor;
- private final TrayDialog mTrayDialog;
-
- private boolean mShowingPreview;
- private DialogTray mPreviewTray;
- private ImageControl mPreviewImageControl;
-
- /**
- * Constructs a new {@link ResourcePreviewHelper}.
- * <p>
- * TODO: Add support for performing previews without an associated graphical editor,
- * such as previewing icons from the manifest form editor; just pick default
- * configuration settings in that case.
- *
- * @param trayDialog the associated tray-capable dialog
- * @param editor a graphical editor. This is currently needed in order to provide
- * configuration data for the rendering.
- */
- public ResourcePreviewHelper(TrayDialog trayDialog, GraphicalEditorPart editor) {
- this.mTrayDialog = trayDialog;
- this.mEditor = editor;
- }
-
- /**
- * Updates the preview based on the current selection and resource type, possibly
- * hiding or opening the tray in the process.
- *
- * @param type the resource type for the selected resource
- * @param resource the full resource url
- */
- public void updatePreview(ResourceType type, String resource) {
- boolean showPreview = type == ResourceType.DRAWABLE || type == ResourceType.COLOR;
- if (showPreview) {
- if (mPreviewTray == null) {
- mPreviewTray = new DialogTray() {
- @Override
- protected Control createContents(Composite parent) {
- // This creates a centered image control
- Composite panel = new Composite(parent, SWT.NONE);
- panel.setLayout(new GridLayout(3, false));
- Label dummy1 = new Label(panel, SWT.NONE);
- dummy1.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1));
- mPreviewImageControl = new ImageControl(panel, SWT.NONE, SwtUtils
- .createEmptyImage(parent.getDisplay(), WIDTH, HEIGHT));
- GridData gd = new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1);
- gd.widthHint = WIDTH;
- gd.heightHint = HEIGHT;
- mPreviewImageControl.setLayoutData(gd);
- Label dummy2 = new Label(panel, SWT.NONE);
- dummy2.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, true, 1, 1));
-
- return panel;
- }
-
- };
- }
-
- if (!mShowingPreview) {
- mTrayDialog.openTray(mPreviewTray);
- }
-
- BufferedImage image = null;
- try {
- if (type == ResourceType.COLOR) {
- ResourceResolver resources = mEditor.getResourceResolver();
- ResourceValue value = resources.findResValue(resource, false);
- if (value != null) {
- RGB color = ResourceHelper.resolveColor(resources, value);
- if (color != null) {
- image = ImageUtils.createColoredImage(WIDTH, HEIGHT, color);
- }
- }
- } else {
- assert type == ResourceType.DRAWABLE;
-
- ResourceResolver resources = mEditor.getResourceResolver();
- ResourceValue drawable = resources.findResValue(resource, false);
- if (drawable != null) {
- String path = drawable.getValue();
-
- // Special-case image files (other than 9-patch files) and render these
- // directly, in order to provide proper aspect ratio handling and
- // to handle scaling to show the full contents:
- if (ImageUtils.hasImageExtension(path)
- && !endsWithIgnoreCase(path, DOT_9PNG)) {
- File file = new File(path);
- if (file.exists()) {
- try {
- image = ImageIO.read(file);
- int width = image.getWidth();
- int height = image.getHeight();
- if (width > WIDTH || height > HEIGHT) {
- double xScale = WIDTH / (double) width;
- double yScale = HEIGHT / (double) height;
- double scale = Math.min(xScale, yScale);
- image = ImageUtils.scale(image, scale, scale);
- }
- } catch (IOException e) {
- AdtPlugin.log(e, "Can't read preview image %1$s", path);
- }
- }
- }
-
- if (image == null) {
- RenderService renderService = RenderService.create(mEditor);
- renderService.setOverrideRenderSize(WIDTH, HEIGHT);
- image = renderService.renderDrawable(drawable);
- }
- }
- }
- } catch (Throwable t) {
- // Some kind of rendering error occurred. However, we don't want to use
- // AdtPlugin.log(t, "Can't generate preview for %1$s", resource);
- // because if it's a severe type of error (such as an InternalError shown
- // in issue #18623) then a dialog will pop up and interfere with the
- // preview, so just log a warning (unfortunately without the trace) instead.
- AdtPlugin.log(IStatus.WARNING, "Can't generate preview for %1$s", resource);
- }
-
- Display display = mEditor.getSite().getShell().getDisplay();
- if (image != null) {
- mPreviewImageControl.setImage(SwtUtils.convertToSwt(display, image, true, -1));
- } else {
- mPreviewImageControl.setImage(SwtUtils.createEmptyImage(display, WIDTH, HEIGHT));
- }
- mPreviewImageControl.redraw();
- } else if (mPreviewTray != null && mShowingPreview) {
- mTrayDialog.closeTray();
- }
- mShowingPreview = showPreview;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/WizardDialogEx.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/WizardDialogEx.java
deleted file mode 100755
index ee1ac9725..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/ui/WizardDialogEx.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.ui;
-
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.wizard.IWizard;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Shell;
-
-/**
- * A {@link WizardDialog} that gives access to some inner controls.
- */
-public final class WizardDialogEx extends WizardDialog {
-
- /**
- * @see WizardDialog#WizardDialog(Shell, IWizard)
- */
- public WizardDialogEx(Shell parentShell, IWizard newWizard) {
- super(parentShell, newWizard);
- }
-
- /**
- * Returns the cancel button.
- * <p/>
- * Note: there is already a protected, deprecated method that does the same thing.
- * To avoid overriding a deprecated method, the name as be changed to ...Ex.
- */
- public Button getCancelButtonEx() {
- return getButton(IDialogConstants.CANCEL_ID);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/utils/FingerprintUtils.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/utils/FingerprintUtils.java
deleted file mode 100644
index bfe301e36..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/utils/FingerprintUtils.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.utils;
-
-import java.util.Locale;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.security.cert.Certificate;
-import java.security.cert.CertificateEncodingException;
-
-public class FingerprintUtils {
-
- /**
- * Returns the {@link Certificate} fingerprint as returned by <code>keytool</code>.
- *
- * @param certificate
- * @param hashAlgorithm
- */
- public static String getFingerprint(Certificate cert, String hashAlgorithm) {
- if (cert == null) {
- return null;
- }
- try {
- MessageDigest digest = MessageDigest.getInstance(hashAlgorithm);
- return toHexadecimalString(digest.digest(cert.getEncoded()));
- } catch(NoSuchAlgorithmException e) {
- // ignore
- } catch(CertificateEncodingException e) {
- // ignore
- }
- return null;
- }
-
- private static String toHexadecimalString(byte[] value) {
- StringBuffer sb = new StringBuffer();
- int len = value.length;
- for (int i = 0; i < len; i++) {
- int num = ((int) value[i]) & 0xff;
- if (num < 0x10) {
- sb.append('0');
- }
- sb.append(Integer.toHexString(num));
- if (i < len - 1) {
- sb.append(':');
- }
- }
- return sb.toString().toUpperCase(Locale.US);
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/welcome/AdtStartup.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/welcome/AdtStartup.java
deleted file mode 100644
index b07893dc0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/welcome/AdtStartup.java
+++ /dev/null
@@ -1,366 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.welcome;
-
-import com.android.SdkConstants;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtPlugin.CheckSdkErrorHandler;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.LayoutWindowCoordinator;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.base.InstallDetails;
-import com.android.utils.GrabProcessOutput;
-import com.android.utils.GrabProcessOutput.IProcessOutput;
-import com.android.utils.GrabProcessOutput.Wait;
-import com.android.sdkstats.DdmsPreferenceStore;
-import com.android.sdkstats.SdkStatsService;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Plugin;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.osgi.service.datalocation.Location;
-import org.eclipse.ui.IStartup;
-import org.eclipse.ui.IWindowListener;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.osgi.framework.Constants;
-import org.osgi.framework.Version;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.concurrent.atomic.AtomicReference;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * ADT startup tasks (other than those performed in {@link AdtPlugin#start(org.osgi.framework.BundleContext)}
- * when the plugin is initializing.
- * <p>
- * The main tasks currently performed are:
- * <ul>
- * <li> See if the user has ever run the welcome wizard, and if not, run it
- * <li> Ping the usage statistics server, if enabled by the user. This is done here
- * rather than during the plugin start since this task is run later (when the workspace
- * is fully initialized) and we want to ask the user for permission for usage
- * tracking before running it (and if we don't, then the usage tracking permissions
- * dialog will run instead.)
- * </ul>
- */
-public class AdtStartup implements IStartup, IWindowListener {
-
- private DdmsPreferenceStore mStore = new DdmsPreferenceStore();
-
- @Override
- public void earlyStartup() {
- if (!isSdkSpecified()) {
- File bundledSdk = getBundledSdk();
- if (bundledSdk != null) {
- AdtPrefs.getPrefs().setSdkLocation(bundledSdk);
- }
- }
-
- boolean showSdkInstallationPage = !isSdkSpecified() && isFirstTime();
- boolean showOptInDialogPage = !mStore.hasPingId();
-
- if (showSdkInstallationPage || showOptInDialogPage) {
- showWelcomeWizard(showSdkInstallationPage, showOptInDialogPage);
- }
-
- if (mStore.isPingOptIn()) {
- sendUsageStats();
- }
-
- initializeWindowCoordinator();
-
- AdtPlugin.getDefault().workbenchStarted();
- }
-
- private boolean isSdkSpecified() {
- String osSdkFolder = AdtPrefs.getPrefs().getOsSdkFolder();
- return (osSdkFolder != null && !osSdkFolder.isEmpty());
- }
-
- /**
- * Returns the path to the bundled SDK if this is part of the ADT package.
- * The ADT package has the following structure:
- * root
- * |--eclipse
- * |--sdk
- * @return path to bundled SDK, null if no valid bundled SDK detected.
- */
- private File getBundledSdk() {
- Location install = Platform.getInstallLocation();
- if (install != null && install.getURL() != null) {
- File toolsFolder = new File(install.getURL().getFile()).getParentFile();
- if (toolsFolder != null) {
- File sdkFolder = new File(toolsFolder, "sdk");
- if (sdkFolder.exists() && AdtPlugin.getDefault().checkSdkLocationAndId(
- sdkFolder.getAbsolutePath(),
- new SdkValidator())) {
- return sdkFolder;
- }
- }
- }
-
- return null;
- }
-
- private boolean isFirstTime() {
- for (int i = 0; i < 2; i++) {
- String osSdkPath = null;
-
- if (i == 0) {
- // If we've recorded an SDK location in the .android settings, then the user
- // has run ADT before but possibly in a different workspace. We don't want to pop up
- // the welcome wizard each time if we can simply use the existing SDK install.
- osSdkPath = mStore.getLastSdkPath();
- } else if (i == 1) {
- osSdkPath = getSdkPathFromWindowsRegistry();
- }
-
- if (osSdkPath != null && osSdkPath.length() > 0) {
- boolean ok = new File(osSdkPath).isDirectory();
-
- if (!ok) {
- osSdkPath = osSdkPath.trim();
- ok = new File(osSdkPath).isDirectory();
- }
-
- if (ok) {
- // Verify that the SDK is valid
- ok = AdtPlugin.getDefault().checkSdkLocationAndId(
- osSdkPath, new SdkValidator());
- if (ok) {
- // Yes, we've seen an SDK location before and we can use it again,
- // no need to pester the user with the welcome wizard.
- // This also implies that the user has responded to the usage statistics
- // question.
- AdtPrefs.getPrefs().setSdkLocation(new File(osSdkPath));
- return false;
- }
- }
- }
- }
-
- // Check whether we've run this wizard before.
- return !mStore.isAdtUsed();
- }
-
- private static class SdkValidator extends AdtPlugin.CheckSdkErrorHandler {
- @Override
- public boolean handleError(
- CheckSdkErrorHandler.Solution solution,
- String message) {
- return false;
- }
-
- @Override
- public boolean handleWarning(
- CheckSdkErrorHandler.Solution solution,
- String message) {
- return true;
- }
- }
-
- private String getSdkPathFromWindowsRegistry() {
- if (SdkConstants.CURRENT_PLATFORM != SdkConstants.PLATFORM_WINDOWS) {
- return null;
- }
-
- final String valueName = "Path"; //$NON-NLS-1$
- final AtomicReference<String> result = new AtomicReference<String>();
- final Pattern regexp =
- Pattern.compile("^\\s+" + valueName + "\\s+REG_SZ\\s+(.*)$");//$NON-NLS-1$ //$NON-NLS-2$
-
- for (String key : new String[] {
- "HKLM\\Software\\Android SDK Tools", //$NON-NLS-1$
- "HKLM\\Software\\Wow6432Node\\Android SDK Tools" }) { //$NON-NLS-1$
-
- String[] command = new String[] {
- "reg", "query", key, "/v", valueName //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- };
-
- Process process;
- try {
- process = Runtime.getRuntime().exec(command);
-
- GrabProcessOutput.grabProcessOutput(
- process,
- Wait.WAIT_FOR_READERS,
- new IProcessOutput() {
- @Override
- public void out(@Nullable String line) {
- if (line != null) {
- Matcher m = regexp.matcher(line);
- if (m.matches()) {
- result.set(m.group(1));
- }
- }
- }
-
- @Override
- public void err(@Nullable String line) {
- // ignore stderr
- }
- });
- } catch (IOException ignore) {
- } catch (InterruptedException ignore) {
- }
-
- String str = result.get();
- if (str != null) {
- if (new File(str).isDirectory()) {
- return str;
- }
- str = str.trim();
- if (new File(str).isDirectory()) {
- return str;
- }
- }
- }
-
- return null;
- }
-
- private void initializeWindowCoordinator() {
- final IWorkbench workbench = PlatformUI.getWorkbench();
- workbench.addWindowListener(this);
- workbench.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- for (IWorkbenchWindow window : workbench.getWorkbenchWindows()) {
- LayoutWindowCoordinator.get(window, true /*create*/);
- }
- }
- });
- }
-
- private void showWelcomeWizard(final boolean showSdkInstallPage,
- final boolean showUsageOptInPage) {
- final IWorkbench workbench = PlatformUI.getWorkbench();
- workbench.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
- if (window != null) {
- WelcomeWizard wizard = new WelcomeWizard(mStore, showSdkInstallPage,
- showUsageOptInPage);
- WizardDialog dialog = new WizardDialog(window.getShell(), wizard);
- dialog.open();
- }
-
- // Record the fact that we've run the wizard so we don't attempt to do it again,
- // even if the user just cancels out of the wizard.
- mStore.setAdtUsed(true);
-
- if (mStore.isPingOptIn()) {
- sendUsageStats();
- }
- }
- });
- }
-
- private void sendUsageStats() {
- // Ping the usage server and parse the SDK content.
- // This is deferred in separate jobs to avoid blocking the bundle start.
- // We also serialize them to avoid too many parallel jobs when Eclipse starts.
- Job pingJob = createPingUsageServerJob();
- // build jobs are run after other interactive jobs
- pingJob.setPriority(Job.BUILD);
- // Wait another 30 seconds before starting the ping job. This gives other
- // startup tasks time to finish since it's not vital to get the usage ping
- // immediately.
- pingJob.schedule(30000 /*milliseconds*/);
- }
-
- /**
- * Creates a job than can ping the usage server.
- */
- private Job createPingUsageServerJob() {
- // In order to not block the plugin loading, so we spawn another thread.
- Job job = new Job("Android SDK Ping") { // Job name, visible in progress view
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- pingUsageServer();
-
- return Status.OK_STATUS;
- } catch (Throwable t) {
- AdtPlugin.log(t, "pingUsageServer failed"); //$NON-NLS-1$
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "pingUsageServer failed", t); //$NON-NLS-1$
- }
- }
- };
- return job;
- }
-
- private static Version getVersion(Plugin plugin) {
- @SuppressWarnings("cast") // Cast required in Eclipse 3.5; prevent auto-removal in 3.7
- String version = (String) plugin.getBundle().getHeaders().get(Constants.BUNDLE_VERSION);
- // Parse the string using the Version class.
- return new Version(version);
- }
-
- /**
- * Pings the usage start server.
- */
- private void pingUsageServer() {
- // Report the version of the ADT plugin to the stat server
- Version version = getVersion(AdtPlugin.getDefault());
- String adtVersionString = String.format("%1$d.%2$d.%3$d", version.getMajor(), //$NON-NLS-1$
- version.getMinor(), version.getMicro());
-
- // Report the version of Eclipse to the stat server.
- // Get the version of eclipse by getting the version of one of the runtime plugins.
- Version eclipseVersion = InstallDetails.getPlatformVersion();
- String eclipseVersionString = String.format("%1$d.%2$d", //$NON-NLS-1$
- eclipseVersion.getMajor(), eclipseVersion.getMinor());
-
- SdkStatsService stats = new SdkStatsService();
- stats.ping("adt", adtVersionString); //$NON-NLS-1$
- stats.ping("eclipse", eclipseVersionString); //$NON-NLS-1$
- }
-
- // ---- Implements IWindowListener ----
-
- @Override
- public void windowActivated(IWorkbenchWindow window) {
- }
-
- @Override
- public void windowDeactivated(IWorkbenchWindow window) {
- }
-
- @Override
- public void windowClosed(IWorkbenchWindow window) {
- LayoutWindowCoordinator listener = LayoutWindowCoordinator.get(window, false /*create*/);
- if (listener != null) {
- listener.dispose();
- }
- }
-
- @Override
- public void windowOpened(IWorkbenchWindow window) {
- LayoutWindowCoordinator.get(window, true /*create*/);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/welcome/UsagePermissionPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/welcome/UsagePermissionPage.java
deleted file mode 100644
index d8413bb45..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/welcome/UsagePermissionPage.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.welcome;
-
-import com.android.sdkstats.SdkStatsPermissionDialog;
-
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.browser.IWebBrowser;
-
-import java.net.URL;
-
-/** Page which displays the permission dialog for collecting usage statistics */
-public class UsagePermissionPage extends WizardPage implements SelectionListener {
- private Link mLink;
- private Button mYesRadio;
- private Button mNoRadio;
-
- /**
- * Create the wizard.
- */
- public UsagePermissionPage() {
- super("usageData");
- setTitle("Contribute Usage Statistics?");
- setDescription(SdkStatsPermissionDialog.NOTICE_TEXT);
- }
-
- /**
- * Create contents of the wizard.
- *
- * @param parent parent to create page into
- */
- @Override
- public void createControl(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
-
- setControl(container);
- container.setLayout(new GridLayout(1, false));
-
- Label label = new Label(container, SWT.WRAP);
- GridData gd_lblByChoosingTo = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
- gd_lblByChoosingTo.widthHint = 580;
- label.setLayoutData(gd_lblByChoosingTo);
- label.setText(SdkStatsPermissionDialog.BODY_TEXT);
-
- Label blankLine = new Label(container, SWT.NONE);
-
- Label questionLabel = new Label(container, SWT.NONE);
- questionLabel.setText("Send usage statistics to Google?");
-
- mYesRadio = new Button(container, SWT.RADIO);
- mYesRadio.setText("Yes");
- mYesRadio.addSelectionListener(this);
-
- mNoRadio = new Button(container, SWT.RADIO);
- mNoRadio.setText("No");
- mNoRadio.addSelectionListener(this);
-
- Label laterLabel = new Label(container, SWT.WRAP);
- GridData gdLaterLabel = new GridData(SWT.FILL, SWT.BOTTOM, false, true, 1, 1);
- gdLaterLabel.widthHint = 580;
- laterLabel.setLayoutData(gdLaterLabel);
- laterLabel.setText("If you later decide to change this setting, you can do so in the " +
- "options panel under Android > Usage Stats");
-
- mLink = new Link(container, SWT.NONE);
- mLink.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- mLink.setText(SdkStatsPermissionDialog.PRIVACY_POLICY_LINK_TEXT);
- mLink.addSelectionListener(this);
-
- validatePage();
- }
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- mYesRadio.setFocus();
- }
-
- boolean isUsageCollectionApproved() {
- return mYesRadio.getSelection();
- }
-
- @Override
- public void widgetSelected(SelectionEvent event) {
- if (event.getSource() == mLink) {
- try {
- IWorkbench workbench = PlatformUI.getWorkbench();
- IWebBrowser browser = workbench.getBrowserSupport().getExternalBrowser();
- browser.openURL(new URL(event.text));
- } catch (Exception e) {
- String message = String.format("Could not open browser. Vist\n%1$s\ninstead.",
- event.text);
- MessageDialog.openError(getWizard().getContainer().getShell(),
- "Browser Error", message);
- }
- } else {
- // Radio buttons selected
- validatePage();
- }
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
-
- private void validatePage() {
- String error = null;
-
- if (!mYesRadio.getSelection() && !mNoRadio.getSelection()) {
- error = "Select Yes or No";
- }
-
- setPageComplete(error == null);
- if (error != null) {
- setMessage(error, IMessageProvider.ERROR);
- } else {
- setErrorMessage(null);
- setMessage(null);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/welcome/WelcomeWizard.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/welcome/WelcomeWizard.java
deleted file mode 100644
index 916924e99..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/welcome/WelcomeWizard.java
+++ /dev/null
@@ -1,207 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.welcome;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.sdk.AdtConsoleSdkLog;
-import com.android.sdkstats.DdmsPreferenceStore;
-import com.android.sdkuilib.internal.repository.ui.AdtUpdateDialog;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-
-import java.io.File;
-import java.util.HashSet;
-import java.util.Set;
-
-/**
- * Wizard shown on first start for new users: configure SDK location, accept or
- * reject usage data collection, etc
- */
-public class WelcomeWizard extends Wizard {
- private final DdmsPreferenceStore mStore;
-
- private WelcomeWizardPage mWelcomePage;
- private UsagePermissionPage mUsagePage;
-
- private final boolean mShowWelcomePage;
- private final boolean mShowUsagePage;
-
- /**
- * Creates a new {@link WelcomeWizard}
- *
- * @param store preferences for usage statistics collection etc
- * @param showInstallSdkPage show page to install SDK's
- * @param showUsageOptinPage show page to get user consent for usage data collection
- */
- public WelcomeWizard(DdmsPreferenceStore store, boolean showInstallSdkPage,
- boolean showUsageOptinPage) {
- mStore = store;
- mShowWelcomePage = showInstallSdkPage;
- mShowUsagePage = showUsageOptinPage;
-
- setWindowTitle("Welcome to Android Development");
- ImageDescriptor image = AdtPlugin.getImageDescriptor("icons/android-64.png"); //$NON-NLS-1$
- setDefaultPageImageDescriptor(image);
- }
-
- @Override
- public void addPages() {
- if (mShowWelcomePage) {
- mWelcomePage = new WelcomeWizardPage();
- addPage(mWelcomePage);
- }
-
- // It's possible that the user has already run the command line tools
- // such as ddms and has agreed to usage statistics collection, but has never
- // run ADT which is why the wizard was opened. No need to ask again.
- if (mShowUsagePage && !mStore.hasPingId()) {
- mUsagePage = new UsagePermissionPage();
- addPage(mUsagePage);
- }
- }
-
- @Override
- public boolean performFinish() {
- if (mUsagePage != null) {
- boolean isUsageCollectionApproved = mUsagePage.isUsageCollectionApproved();
- DdmsPreferenceStore store = new DdmsPreferenceStore();
-
- // Workaround: Store a new ping id if one doesn't exist, regardless of
- // whether usage statistics gathering is enabled, to ensure that ddms and
- // ADT agree upon whether usage data collection is enabled. The reason this
- // is necessary is that the Eclipse PreferenceStore optimizes out writing
- // property values that equal their default values, and in our case, the
- // default value for usage-collection is "false", so it just doesn't write
- // it into the config file is the user opts out - which means that nothing
- // is written in ddms.config. That works in the sense that the getter returns
- // "usage collection"=false, but it doesn't work in the sense that it looks
- // like the property has not yet been decided by the user. DDMS will look at
- // the existence of a ping id to see whether we've already considered the
- // question, so do the same here.
- if (!store.hasPingId()) {
- store.generateNewPingId();
- }
-
- store.setPingOptIn(isUsageCollectionApproved);
- }
-
- if (mWelcomePage != null) {
- // Read out wizard settings immediately; we will perform the actual work
- // after the wizard window has been taken down and it's too late to read the
- // settings then
- final File path = mWelcomePage.getPath();
- final boolean installCommon = mWelcomePage.isInstallCommon();
- final boolean installLatest = mWelcomePage.isInstallLatest();
- final boolean createNew = mWelcomePage.isCreateNew();
-
- // Perform installation asynchronously since it takes a while.
- getShell().getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- if (createNew) {
- try {
- Set<Integer> apiLevels = new HashSet<Integer>();
- if (installCommon) {
- apiLevels.add(8);
- }
- if (installLatest) {
- apiLevels.add(AdtUpdateDialog.USE_MAX_REMOTE_API_LEVEL);
- }
- installSdk(path, apiLevels);
- } catch (Exception e) {
- AdtPlugin.logAndPrintError(e, "ADT Welcome Wizard",
- "Installation failed");
- }
- }
-
- // Set SDK path after installation since this will trigger a SDK refresh.
- AdtPrefs.getPrefs().setSdkLocation(path);
- }
- });
- }
-
- // The wizard always succeeds, even if installation fails or is aborted
- return true;
- }
-
- /**
- * Trigger the install window. It will connect to the repository, display
- * a confirmation window showing which packages are selected for install
- * and display a progress dialog during installation.
- */
- private boolean installSdk(File path, Set<Integer> apiLevels) {
- if (!path.isDirectory()) {
- if (!path.mkdirs()) {
- AdtPlugin.logAndPrintError(null, "ADT Welcome Wizard",
- "Failed to create directory %1$s",
- path.getAbsolutePath());
- return false;
- }
- }
-
- // Get a shell to use for the SDK installation. There are cases where getActiveShell
- // returns null so attempt to obtain it through other means.
- Display display = AdtPlugin.getDisplay();
- Shell shell = display.getActiveShell();
- if (shell == null) {
- IWorkbench workbench = PlatformUI.getWorkbench();
- IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
- if (window != null) {
- shell = window.getShell();
- }
- }
- boolean disposeShell = false;
- if (shell == null) {
- shell = new Shell(display);
- AdtPlugin.log(IStatus.WARNING, "No parent shell for SDK installation dialog");
- disposeShell = true;
- }
-
- AdtUpdateDialog updater = new AdtUpdateDialog(
- shell,
- new AdtConsoleSdkLog(),
- path.getAbsolutePath());
- // Note: we don't have to specify tools & platform-tools since they
- // are required dependencies of any platform.
- boolean result = updater.installNewSdk(apiLevels);
-
- // TODO: Install extra package here as well since it is now core to most of
- // the templates
- // if (result) {
- // updater.installExtraPackage(vendor, path);
- // }
-
- if (disposeShell) {
- shell.dispose();
- }
-
- if (!result) {
- AdtPlugin.printErrorToConsole("Failed to install Android SDK.");
- return false;
- }
-
- return true;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/welcome/WelcomeWizardPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/welcome/WelcomeWizardPage.java
deleted file mode 100644
index bcee88703..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/welcome/WelcomeWizardPage.java
+++ /dev/null
@@ -1,302 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.welcome;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtPlugin.CheckSdkErrorHandler;
-
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.DirectoryDialog;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-
-import java.io.File;
-import java.util.concurrent.atomic.AtomicReference;
-
-/** Main page shown in the {@link WelcomeWizard} */
-public class WelcomeWizardPage extends WizardPage implements ModifyListener, SelectionListener {
- private Text mExistingDirText;
- private Button mExistingDirButton;
- private Button mInstallLatestCheckbox;
- private Button mInstallCommonCheckbox;
- private Button mInstallNewRadio;
- private Button mUseExistingRadio;
- private Text mNewDirText;
- private Button mNewDirButton;
-
- /**
- * Create the wizard.
- */
- public WelcomeWizardPage() {
- super("welcomePage");
- setTitle("Welcome to Android Development");
- setDescription("Configure SDK");
- }
-
- /**
- * Create contents of the wizard.
- * @param parent parent widget to add page to
- */
- @Override
- @SuppressWarnings("unused") // SWT constructors have side effects so "new Label" is not unused
- public void createControl(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
-
- setControl(container);
- container.setLayout(new GridLayout(4, false));
-
- Label overviewLabel = new Label(container, SWT.WRAP | SWT.SHADOW_NONE);
- GridData gdOverviewLabel = new GridData(SWT.FILL, SWT.CENTER, false, false, 4, 1);
- gdOverviewLabel.widthHint = 580;
- overviewLabel.setLayoutData(gdOverviewLabel);
- overviewLabel.setText("To develop for Android, you need an Android SDK, and at least one version of the Android APIs to compile against. You may also want additional versions of Android to test with.");
-
- Label spacing = new Label(container, SWT.NONE);
- spacing.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 4, 1));
-
- mInstallNewRadio = new Button(container, SWT.RADIO);
- mInstallNewRadio.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 4, 1));
- mInstallNewRadio.setSelection(true);
- mInstallNewRadio.setText("Install new SDK");
- mInstallNewRadio.addSelectionListener(this);
-
- Label indentLabel = new Label(container, SWT.NONE);
- GridData gdIndentLabel = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
- gdIndentLabel.widthHint = 20;
- indentLabel.setLayoutData(gdIndentLabel);
-
- mInstallLatestCheckbox = new Button(container, SWT.CHECK);
- mInstallLatestCheckbox.setSelection(true);
- mInstallLatestCheckbox.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 3,
- 1));
- mInstallLatestCheckbox.setText("Install the latest available version of Android APIs (supports all the latest features)");
- mInstallLatestCheckbox.addSelectionListener(this);
-
- new Label(container, SWT.NONE);
- mInstallCommonCheckbox = new Button(container, SWT.CHECK);
- mInstallCommonCheckbox.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 3,
- 1));
- mInstallCommonCheckbox.setText("Install Android 2.2, a version which is supported by ~96% phones and tablets");
- mInstallCommonCheckbox.addSelectionListener(this);
-
- new Label(container, SWT.NONE);
- Label addHintLabel = new Label(container, SWT.NONE);
- addHintLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 3, 1));
- addHintLabel.setText(" (You can add additional platforms using the SDK Manager.)");
-
- new Label(container, SWT.NONE);
- Label targetLabel = new Label(container, SWT.NONE);
- targetLabel.setText("Target Location:");
-
- mNewDirText = new Text(container, SWT.BORDER);
- mNewDirText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- String defaultPath = System.getProperty("user.home") + File.separator + "android-sdks"; //$NON-NLS-1$
- mNewDirText.setText(defaultPath);
- mNewDirText.addModifyListener(this);
-
- mNewDirButton = new Button(container, SWT.FLAT);
- mNewDirButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- mNewDirButton.setText("Browse...");
- mNewDirButton.addSelectionListener(this);
-
- Label spacing2 = new Label(container, SWT.NONE);
- spacing2.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 4, 1));
-
- mUseExistingRadio = new Button(container, SWT.RADIO);
- mUseExistingRadio.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 4, 1));
- mUseExistingRadio.setText("Use existing SDKs");
- mUseExistingRadio.addSelectionListener(this);
-
- new Label(container, SWT.NONE);
- Label installationLabel = new Label(container, SWT.NONE);
- installationLabel.setText("Existing Location:");
-
- mExistingDirText = new Text(container, SWT.BORDER);
- mExistingDirText.setEnabled(false);
- mExistingDirText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- mExistingDirText.addModifyListener(this);
-
- mExistingDirButton = new Button(container, SWT.FLAT);
- mExistingDirButton.setEnabled(false);
- mExistingDirButton.setText("Browse...");
- mExistingDirButton.addSelectionListener(this);
- }
-
- boolean isCreateNew() {
- return mInstallNewRadio.getSelection();
- }
-
- boolean isInstallLatest() {
- return mInstallLatestCheckbox.getSelection();
- }
-
- boolean isInstallCommon() {
- return mInstallCommonCheckbox.getSelection();
- }
-
- File getPath() {
- Text text = isCreateNew() ? mNewDirText : mExistingDirText;
- return new File(text.getText());
- }
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- Object source = e.getSource();
-
- if (source == mExistingDirButton) {
- DirectoryDialog dialog = new DirectoryDialog(mExistingDirButton.getShell(), SWT.OPEN);
- String file = dialog.open();
- String path = mExistingDirText.getText().trim();
- if (path.length() > 0) {
- // TODO: Shouldn't this be done before the open() call?
- dialog.setFilterPath(path);
- }
- if (file != null) {
- mExistingDirText.setText(file);
- }
- } else if (source == mNewDirButton) {
- DirectoryDialog dialog = new DirectoryDialog(mNewDirButton.getShell(), SWT.OPEN);
- String path = mNewDirText.getText().trim();
- if (path.length() > 0) {
- dialog.setFilterPath(path);
- }
- String file = dialog.open();
- if (file != null) {
- mNewDirText.setText(file);
- }
- } else if (source == mInstallNewRadio) {
- mExistingDirButton.setEnabled(false);
- mExistingDirText.setEnabled(false);
- mNewDirButton.setEnabled(true);
- mNewDirText.setEnabled(true);
- } else if (source == mUseExistingRadio) {
- mExistingDirButton.setEnabled(true);
- mExistingDirText.setEnabled(true);
- mNewDirButton.setEnabled(false);
- mNewDirText.setEnabled(false);
- }
-
- validatePage();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
-
- @Override
- public void modifyText(ModifyEvent e) {
- validatePage();
- }
-
- private void validatePage() {
- String error = null;
- String warning = null;
-
- if (isCreateNew()) {
- // Make sure that the target installation directory is empty or doesn't exist
- // (and that it can be created)
- String path = mNewDirText.getText().trim();
- if (path.length() == 0) {
- error = "Please enter a new directory to install the SDK into";
- } else {
- File file = new File(path);
- if (file.exists()) {
- if (file.isDirectory()) {
- if (!file.canWrite()) {
- error = "Missing write permission in target directory";
- }
- File[] children = file.listFiles();
- if (children != null && children.length > 0) {
- warning = "The directory is not empty";
- }
- } else {
- error = "The target must be a directory";
- }
- } else {
- File parent = file.getParentFile();
- if (parent == null || !parent.exists()) {
- error = "The parent directory does not exist";
- } else if (!parent.canWrite()) {
- error = "No write permission in parent directory";
- }
- }
- }
-
- if (error == null && !mInstallLatestCheckbox.getSelection()
- && !mInstallCommonCheckbox.getSelection()) {
- error = "You must choose at least one Android version to install";
- }
- } else {
- // Make sure that the existing installation directory exists and is valid
- String path = mExistingDirText.getText().trim();
- if (path.length() == 0) {
- error = "Please enter an existing SDK installation directory";
- } else {
- File file = new File(path);
- if (!file.exists()) {
- error = "The chosen installation directory does not exist";
- } else {
- final AtomicReference<String> errorReference = new AtomicReference<String>();
- final AtomicReference<String> warningReference = new AtomicReference<String>();
- AdtPlugin.getDefault().checkSdkLocationAndId(path,
- new AdtPlugin.CheckSdkErrorHandler() {
- @Override
- public boolean handleError(
- CheckSdkErrorHandler.Solution solution,
- String message) {
- message = message.replaceAll("\n", " "); //$NON-NLS-1$ //$NON-NLS-2$
- errorReference.set(message);
- return false; // Apply/OK must be disabled
- }
-
- @Override
- public boolean handleWarning(
- CheckSdkErrorHandler.Solution solution,
- String message) {
- message = message.replaceAll("\n", " "); //$NON-NLS-1$ //$NON-NLS-2$
- warningReference.set(message);
- return true; // Apply/OK must be enabled
- }
- });
- error = errorReference.get();
- if (warning == null) {
- warning = warningReference.get();
- }
- }
- }
- }
-
- setPageComplete(error == null);
- if (error != null) {
- setMessage(error, IMessageProvider.ERROR);
- } else if (warning != null) {
- setMessage(warning, IMessageProvider.WARNING);
- } else {
- setErrorMessage(null);
- setMessage(null);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/actions/ExportAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/actions/ExportAction.java
deleted file mode 100644
index 4d3870b86..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/actions/ExportAction.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.actions;
-
-import com.android.ide.eclipse.adt.internal.lint.EclipseLintRunner;
-import com.android.ide.eclipse.adt.internal.project.ExportHelper;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IObjectActionDelegate;
-import org.eclipse.ui.IWorkbenchPart;
-
-public class ExportAction implements IObjectActionDelegate {
-
- private ISelection mSelection;
- private Shell mShell;
-
- /**
- * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
- */
- @Override
- public void setActivePart(IAction action, IWorkbenchPart targetPart) {
- mShell = targetPart.getSite().getShell();
- }
-
- @Override
- public void run(IAction action) {
- if (mSelection instanceof IStructuredSelection) {
- IStructuredSelection selection = (IStructuredSelection)mSelection;
- // get the unique selected item.
- if (selection.size() == 1) {
- Object element = selection.getFirstElement();
-
- // get the project object from it.
- IProject project = null;
- if (element instanceof IProject) {
- project = (IProject) element;
- } else if (element instanceof IAdaptable) {
- project = (IProject) ((IAdaptable) element).getAdapter(IProject.class);
- }
-
- // and finally do the action
- if (project != null) {
- if (!EclipseLintRunner.runLintOnExport(mShell, project)) {
- return;
- }
-
- ProjectState state = Sdk.getProjectState(project);
- if (state.isLibrary()) {
- MessageDialog.openError(mShell, "Android Export",
- "Android library projects cannot be exported.");
- } else {
- ExportHelper.exportUnsignedReleaseApk(project);
- }
- }
- }
- }
- }
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
- mSelection = selection;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/actions/ExportWizardAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/actions/ExportWizardAction.java
deleted file mode 100644
index 673d9569f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/actions/ExportWizardAction.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.actions;
-
-import com.android.ide.eclipse.adt.internal.lint.EclipseLintRunner;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.internal.wizards.export.ExportWizard;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.ui.IObjectActionDelegate;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPart;
-
-public class ExportWizardAction implements IObjectActionDelegate {
-
- private ISelection mSelection;
- private IWorkbench mWorkbench;
-
- /**
- * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
- */
- @Override
- public void setActivePart(IAction action, IWorkbenchPart targetPart) {
- mWorkbench = targetPart.getSite().getWorkbenchWindow().getWorkbench();
- }
-
- @Override
- public void run(IAction action) {
- if (mSelection instanceof IStructuredSelection) {
- IStructuredSelection selection = (IStructuredSelection)mSelection;
-
- // get the unique selected item.
- if (selection.size() == 1) {
- Object element = selection.getFirstElement();
-
- // get the project object from it.
- IProject project = null;
- if (element instanceof IProject) {
- project = (IProject) element;
- } else if (element instanceof IAdaptable) {
- project = (IProject) ((IAdaptable) element).getAdapter(IProject.class);
- }
-
- // and finally do the action
- if (project != null) {
- if (!EclipseLintRunner.runLintOnExport(
- mWorkbench.getActiveWorkbenchWindow().getShell(), project)) {
- return;
- }
-
- ProjectState state = Sdk.getProjectState(project);
- if (state.isLibrary()) {
- MessageDialog.openError(mWorkbench.getDisplay().getActiveShell(),
- "Android Export",
- "Android library projects cannot be exported.");
- } else {
- // call the export wizard on the current selection.
- ExportWizard wizard = new ExportWizard();
- wizard.init(mWorkbench, selection);
- WizardDialog dialog = new WizardDialog(
- mWorkbench.getDisplay().getActiveShell(), wizard);
- dialog.open();
- }
- }
- }
- }
- }
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
- mSelection = selection;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/actions/NewProjectAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/actions/NewProjectAction.java
deleted file mode 100644
index 38f4768b1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/actions/NewProjectAction.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.actions;
-
-import com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.ui.IWorkbenchWizard;
-
-/**
- * Delegate for the toolbar action "Android Project".
- * It displays the Android New Project wizard to create a new Android Project (not a test project).
- *
- * @see NewTestProjectAction
- */
-public class NewProjectAction extends OpenWizardAction {
-
- @Override
- protected IWorkbenchWizard instanciateWizard(IAction action) {
- return new NewProjectWizard();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/actions/NewTestProjectAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/actions/NewTestProjectAction.java
deleted file mode 100755
index c8e45ef1a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/actions/NewTestProjectAction.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.actions;
-
-import com.android.ide.eclipse.adt.internal.wizards.newproject.NewTestProjectWizard;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.ui.IWorkbenchWizard;
-
-/**
- * Delegate for the toolbar action "Android Test Project".
- * It displays the Android New Project wizard to create a new Test Project.
- */
-public class NewTestProjectAction extends OpenWizardAction {
-
- @Override
- protected IWorkbenchWizard instanciateWizard(IAction action) {
- return new NewTestProjectWizard();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/actions/NewXmlFileAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/actions/NewXmlFileAction.java
deleted file mode 100644
index ba349c30a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/actions/NewXmlFileAction.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.actions;
-
-import com.android.ide.eclipse.adt.internal.wizards.newxmlfile.NewXmlFileWizard;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.ui.IWorkbenchWizard;
-
-/**
- * Delegate for the toolbar action "Android Project" or for the
- * project > Android Project context menu.
- *
- * It displays the Android New XML file wizard.
- */
-public class NewXmlFileAction extends OpenWizardAction {
-
- @Override
- protected IWorkbenchWizard instanciateWizard(IAction action) {
- return new NewXmlFileWizard();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/actions/OpenWizardAction.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/actions/OpenWizardAction.java
deleted file mode 100644
index a3e6135e5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/actions/OpenWizardAction.java
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.actions;
-
-import com.android.ide.eclipse.adt.internal.ui.IUpdateWizardDialog;
-import com.android.ide.eclipse.adt.internal.ui.WizardDialogEx;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.StructuredSelection;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IObjectActionDelegate;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-import org.eclipse.ui.IWorkbenchWizard;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.internal.IWorkbenchHelpContextIds;
-import org.eclipse.ui.internal.LegacyResourceSupport;
-import org.eclipse.ui.internal.actions.NewWizardShortcutAction;
-import org.eclipse.ui.internal.util.Util;
-
-/**
- * An abstract action that displays one of our wizards.
- * Derived classes must provide the actual wizard to display.
- */
-/*package*/ abstract class OpenWizardAction
- implements IWorkbenchWindowActionDelegate, IObjectActionDelegate {
-
- /**
- * The wizard dialog width, extracted from {@link NewWizardShortcutAction}
- */
- private static final int SIZING_WIZARD_WIDTH = 500;
-
- /**
- * The wizard dialog height, extracted from {@link NewWizardShortcutAction}
- */
- private static final int SIZING_WIZARD_HEIGHT = 500;
-
- /** The wizard that was created by {@link #run(IAction)}. */
- private IWorkbenchWizard mWizard;
- /** The result from the dialog */
- private int mDialogResult;
-
- private ISelection mSelection;
- private IWorkbench mWorkbench;
-
- /** Returns the wizard that was created by {@link #run(IAction)}. */
- public IWorkbenchWizard getWizard() {
- return mWizard;
- }
-
- /** Returns the result from {@link Dialog#open()}, available after
- * the completion of {@link #run(IAction)}. */
- public int getDialogResult() {
- return mDialogResult;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#dispose()
- */
- @Override
- public void dispose() {
- // pass
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IWorkbenchWindowActionDelegate#init(org.eclipse.ui.IWorkbenchWindow)
- */
- @Override
- public void init(IWorkbenchWindow window) {
- // pass
- }
-
- /**
- * Opens and display the Android New Project Wizard.
- * <p/>
- * Most of this implementation is extracted from {@link NewWizardShortcutAction#run()}.
- *
- * @param action The action that got us here. Can be null when used internally.
- * @see org.eclipse.ui.IActionDelegate#run(org.eclipse.jface.action.IAction)
- */
- @Override
- public void run(IAction action) {
-
- // get the workbench and the current window
- IWorkbench workbench = mWorkbench != null ? mWorkbench : PlatformUI.getWorkbench();
- IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
-
- // This code from NewWizardShortcutAction#run() gets the current window selection
- // and converts it to a workbench structured selection for the wizard, if possible.
- ISelection selection = mSelection;
- if (selection == null) {
- selection = window.getSelectionService().getSelection();
- }
-
- IStructuredSelection selectionToPass = StructuredSelection.EMPTY;
- if (selection instanceof IStructuredSelection) {
- selectionToPass = (IStructuredSelection) selection;
- } else {
- // Build the selection from the IFile of the editor
- IWorkbenchPart part = window.getPartService().getActivePart();
- if (part instanceof IEditorPart) {
- IEditorInput input = ((IEditorPart) part).getEditorInput();
- Class<?> fileClass = LegacyResourceSupport.getFileClass();
- if (input != null && fileClass != null) {
- Object file = Util.getAdapter(input, fileClass);
- if (file != null) {
- selectionToPass = new StructuredSelection(file);
- }
- }
- }
- }
-
- // Create the wizard and initialize it with the selection
- mWizard = instanciateWizard(action);
- mWizard.init(workbench, selectionToPass);
-
- // It's not visible yet until a dialog is created and opened
- Shell parent = window.getShell();
- WizardDialogEx dialog = new WizardDialogEx(parent, mWizard);
- dialog.create();
-
- if (mWizard instanceof IUpdateWizardDialog) {
- ((IUpdateWizardDialog) mWizard).updateWizardDialog(dialog);
- }
-
- // This code comes straight from NewWizardShortcutAction#run()
- Point defaultSize = dialog.getShell().getSize();
- dialog.getShell().setSize(
- Math.max(SIZING_WIZARD_WIDTH, defaultSize.x),
- Math.max(SIZING_WIZARD_HEIGHT, defaultSize.y));
- window.getWorkbench().getHelpSystem().setHelp(dialog.getShell(),
- IWorkbenchHelpContextIds.NEW_WIZARD_SHORTCUT);
-
- mDialogResult = dialog.open();
- }
-
- /**
- * Called by {@link #run(IAction)} to instantiate the actual wizard.
- *
- * @param action The action parameter from {@link #run(IAction)}.
- * This can be null.
- * @return A new wizard instance. Must not be null.
- */
- protected abstract IWorkbenchWizard instanciateWizard(IAction action);
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IActionDelegate#selectionChanged(org.eclipse.jface.action.IAction, org.eclipse.jface.viewers.ISelection)
- */
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
- mSelection = selection;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.ui.IObjectActionDelegate#setActivePart(org.eclipse.jface.action.IAction, org.eclipse.ui.IWorkbenchPart)
- */
- @Override
- public void setActivePart(IAction action, IWorkbenchPart targetPart) {
- mWorkbench = targetPart.getSite().getWorkbenchWindow().getWorkbench();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/export/ExportWizard.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/export/ExportWizard.java
deleted file mode 100644
index 170da6d33..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/export/ExportWizard.java
+++ /dev/null
@@ -1,626 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.export;
-
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.internal.utils.FingerprintUtils;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs.BuildVerbosity;
-import com.android.ide.eclipse.adt.internal.project.ExportHelper;
-import com.android.ide.eclipse.adt.internal.project.ProjectHelper;
-import com.android.sdklib.BuildToolInfo;
-import com.android.sdklib.BuildToolInfo.PathId;
-import com.android.sdklib.internal.build.DebugKeyProvider.IKeyGenOutput;
-import com.android.sdklib.internal.build.KeystoreHelper;
-import com.android.utils.GrabProcessOutput;
-import com.android.utils.GrabProcessOutput.IProcessOutput;
-import com.android.utils.GrabProcessOutput.Wait;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.events.VerifyEvent;
-import org.eclipse.swt.events.VerifyListener;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IExportWizard;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.PlatformUI;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.PrintStream;
-import java.lang.reflect.InvocationTargetException;
-import java.security.KeyStore;
-import java.security.KeyStore.PrivateKeyEntry;
-import java.security.PrivateKey;
-import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Export wizard to export an apk signed with a release key/certificate.
- */
-public final class ExportWizard extends Wizard implements IExportWizard {
-
- private static final String PROJECT_LOGO_LARGE = "icons/android-64.png"; //$NON-NLS-1$
-
- private static final String PAGE_PROJECT_CHECK = "Page_ProjectCheck"; //$NON-NLS-1$
- private static final String PAGE_KEYSTORE_SELECTION = "Page_KeystoreSelection"; //$NON-NLS-1$
- private static final String PAGE_KEY_CREATION = "Page_KeyCreation"; //$NON-NLS-1$
- private static final String PAGE_KEY_SELECTION = "Page_KeySelection"; //$NON-NLS-1$
- private static final String PAGE_KEY_CHECK = "Page_KeyCheck"; //$NON-NLS-1$
-
- static final String PROPERTY_KEYSTORE = "keystore"; //$NON-NLS-1$
- static final String PROPERTY_ALIAS = "alias"; //$NON-NLS-1$
- static final String PROPERTY_DESTINATION = "destination"; //$NON-NLS-1$
-
- static final int APK_FILE_SOURCE = 0;
- static final int APK_FILE_DEST = 1;
- static final int APK_COUNT = 2;
-
- /**
- * Base page class for the ExportWizard page. This class add the {@link #onShow()} callback.
- */
- static abstract class ExportWizardPage extends WizardPage {
-
- /** bit mask constant for project data change event */
- protected static final int DATA_PROJECT = 0x001;
- /** bit mask constant for keystore data change event */
- protected static final int DATA_KEYSTORE = 0x002;
- /** bit mask constant for key data change event */
- protected static final int DATA_KEY = 0x004;
-
- protected static final VerifyListener sPasswordVerifier = new VerifyListener() {
- @Override
- public void verifyText(VerifyEvent e) {
- // verify the characters are valid for password.
- int len = e.text.length();
-
- // first limit to 127 characters max
- if (len + ((Text)e.getSource()).getText().length() > 127) {
- e.doit = false;
- return;
- }
-
- // now only take non control characters
- for (int i = 0 ; i < len ; i++) {
- if (e.text.charAt(i) < 32) {
- e.doit = false;
- return;
- }
- }
- }
- };
-
- /**
- * Bit mask indicating what changed while the page was hidden.
- * @see #DATA_PROJECT
- * @see #DATA_KEYSTORE
- * @see #DATA_KEY
- */
- protected int mProjectDataChanged = 0;
-
- ExportWizardPage(String name) {
- super(name);
- }
-
- abstract void onShow();
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- if (visible) {
- onShow();
- mProjectDataChanged = 0;
- }
- }
-
- final void projectDataChanged(int changeMask) {
- mProjectDataChanged |= changeMask;
- }
-
- /**
- * Calls {@link #setErrorMessage(String)} and {@link #setPageComplete(boolean)} based on a
- * {@link Throwable} object.
- */
- protected void onException(Throwable t) {
- String message = getExceptionMessage(t);
-
- setErrorMessage(message);
- setPageComplete(false);
- }
- }
-
- private ExportWizardPage mPages[] = new ExportWizardPage[5];
-
- private IProject mProject;
-
- private String mKeystore;
- private String mKeystorePassword;
- private boolean mKeystoreCreationMode;
-
- private String mKeyAlias;
- private String mKeyPassword;
- private int mValidity;
- private String mDName;
-
- private PrivateKey mPrivateKey;
- private X509Certificate mCertificate;
-
- private File mDestinationFile;
-
- private ExportWizardPage mKeystoreSelectionPage;
- private ExportWizardPage mKeyCreationPage;
- private ExportWizardPage mKeySelectionPage;
- private ExportWizardPage mKeyCheckPage;
-
- private boolean mKeyCreationMode;
-
- private List<String> mExistingAliases;
-
- public ExportWizard() {
- setHelpAvailable(false); // TODO have help
- setWindowTitle("Export Android Application");
- setImageDescriptor();
- }
-
- @Override
- public void addPages() {
- addPage(mPages[0] = new ProjectCheckPage(this, PAGE_PROJECT_CHECK));
- addPage(mKeystoreSelectionPage = mPages[1] = new KeystoreSelectionPage(this,
- PAGE_KEYSTORE_SELECTION));
- addPage(mKeyCreationPage = mPages[2] = new KeyCreationPage(this, PAGE_KEY_CREATION));
- addPage(mKeySelectionPage = mPages[3] = new KeySelectionPage(this, PAGE_KEY_SELECTION));
- addPage(mKeyCheckPage = mPages[4] = new KeyCheckPage(this, PAGE_KEY_CHECK));
- }
-
- @Override
- public boolean performFinish() {
- // save the properties
- ProjectHelper.saveStringProperty(mProject, PROPERTY_KEYSTORE, mKeystore);
- ProjectHelper.saveStringProperty(mProject, PROPERTY_ALIAS, mKeyAlias);
- ProjectHelper.saveStringProperty(mProject, PROPERTY_DESTINATION,
- mDestinationFile.getAbsolutePath());
-
- // run the export in an UI runnable.
- IWorkbench workbench = PlatformUI.getWorkbench();
- final boolean[] result = new boolean[1];
- try {
- workbench.getProgressService().busyCursorWhile(new IRunnableWithProgress() {
- /**
- * Run the export.
- * @throws InvocationTargetException
- * @throws InterruptedException
- */
- @Override
- public void run(IProgressMonitor monitor) throws InvocationTargetException,
- InterruptedException {
- try {
- result[0] = doExport(monitor);
- } finally {
- monitor.done();
- }
- }
- });
- } catch (InvocationTargetException e) {
- return false;
- } catch (InterruptedException e) {
- return false;
- }
-
- return result[0];
- }
-
- private boolean doExport(IProgressMonitor monitor) {
- try {
- // if needed, create the keystore and/or key.
- if (mKeystoreCreationMode || mKeyCreationMode) {
- final ArrayList<String> output = new ArrayList<String>();
- boolean createdStore = KeystoreHelper.createNewStore(
- mKeystore,
- null /*storeType*/,
- mKeystorePassword,
- mKeyAlias,
- mKeyPassword,
- mDName,
- mValidity,
- new IKeyGenOutput() {
- @Override
- public void err(String message) {
- output.add(message);
- }
- @Override
- public void out(String message) {
- output.add(message);
- }
- });
-
- if (createdStore == false) {
- // keystore creation error!
- displayError(output.toArray(new String[output.size()]));
- return false;
- }
-
- // keystore is created, now load the private key and certificate.
- KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
- FileInputStream fis = new FileInputStream(mKeystore);
- keyStore.load(fis, mKeystorePassword.toCharArray());
- fis.close();
- PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry)keyStore.getEntry(
- mKeyAlias, new KeyStore.PasswordProtection(mKeyPassword.toCharArray()));
-
- if (entry != null) {
- mPrivateKey = entry.getPrivateKey();
- mCertificate = (X509Certificate)entry.getCertificate();
-
- AdtPlugin.printToConsole(mProject,
- String.format("New keystore %s has been created.",
- mDestinationFile.getAbsolutePath()),
- "Certificate fingerprints:",
- String.format(" MD5 : %s", getCertMd5Fingerprint()),
- String.format(" SHA1: %s", getCertSha1Fingerprint()));
-
- } else {
- // this really shouldn't happen since we now let the user choose the key
- // from a list read from the store.
- displayError("Could not find key");
- return false;
- }
- }
-
- // check the private key/certificate again since it may have been created just above.
- if (mPrivateKey != null && mCertificate != null) {
- // check whether we can run zipalign.
- boolean runZipAlign = false;
-
- ProjectState projectState = Sdk.getProjectState(mProject);
- BuildToolInfo buildToolInfo = ExportHelper.getBuildTools(projectState);
-
- String zipAlignPath = buildToolInfo.getPath(PathId.ZIP_ALIGN);
- runZipAlign = zipAlignPath != null && new File(zipAlignPath).isFile();
-
- File apkExportFile = mDestinationFile;
- if (runZipAlign) {
- // create a temp file for the original export.
- apkExportFile = File.createTempFile("androidExport_", ".apk");
- }
-
- // export the signed apk.
- ExportHelper.exportReleaseApk(mProject, apkExportFile,
- mPrivateKey, mCertificate, monitor);
-
- // align if we can
- if (runZipAlign) {
- String message = zipAlign(zipAlignPath, apkExportFile, mDestinationFile);
- if (message != null) {
- displayError(message);
- return false;
- }
- } else {
- AdtPlugin.displayWarning("Export Wizard",
- "The zipalign tool was not found in the SDK.\n\n" +
- "Please update to the latest SDK and re-export your application\n" +
- "or run zipalign manually.\n\n" +
- "Aligning applications allows Android to use application resources\n" +
- "more efficiently.");
- }
-
- return true;
- }
- } catch (Throwable t) {
- displayError(t);
- }
-
- return false;
- }
-
- @Override
- public boolean canFinish() {
- // check if we have the apk to resign, the destination location, and either
- // a private key/certificate or the creation mode. In creation mode, unless
- // all the key/keystore info is valid, the user cannot reach the last page, so there's
- // no need to check them again here.
- return ((mPrivateKey != null && mCertificate != null)
- || mKeystoreCreationMode || mKeyCreationMode) &&
- mDestinationFile != null;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench,
- * org.eclipse.jface.viewers.IStructuredSelection)
- */
- @Override
- public void init(IWorkbench workbench, IStructuredSelection selection) {
- // get the project from the selection
- Object selected = selection.getFirstElement();
-
- if (selected instanceof IProject) {
- mProject = (IProject)selected;
- } else if (selected instanceof IAdaptable) {
- IResource r = (IResource)((IAdaptable)selected).getAdapter(IResource.class);
- if (r != null) {
- mProject = r.getProject();
- }
- }
- }
-
- ExportWizardPage getKeystoreSelectionPage() {
- return mKeystoreSelectionPage;
- }
-
- ExportWizardPage getKeyCreationPage() {
- return mKeyCreationPage;
- }
-
- ExportWizardPage getKeySelectionPage() {
- return mKeySelectionPage;
- }
-
- ExportWizardPage getKeyCheckPage() {
- return mKeyCheckPage;
- }
-
- /**
- * Returns an image descriptor for the wizard logo.
- */
- private void setImageDescriptor() {
- ImageDescriptor desc = AdtPlugin.getImageDescriptor(PROJECT_LOGO_LARGE);
- setDefaultPageImageDescriptor(desc);
- }
-
- IProject getProject() {
- return mProject;
- }
-
- void setProject(IProject project) {
- mProject = project;
-
- updatePageOnChange(ExportWizardPage.DATA_PROJECT);
- }
-
- void setKeystore(String path) {
- mKeystore = path;
- mPrivateKey = null;
- mCertificate = null;
-
- updatePageOnChange(ExportWizardPage.DATA_KEYSTORE);
- }
-
- String getKeystore() {
- return mKeystore;
- }
-
- void setKeystoreCreationMode(boolean createStore) {
- mKeystoreCreationMode = createStore;
- updatePageOnChange(ExportWizardPage.DATA_KEYSTORE);
- }
-
- boolean getKeystoreCreationMode() {
- return mKeystoreCreationMode;
- }
-
-
- void setKeystorePassword(String password) {
- mKeystorePassword = password;
- mPrivateKey = null;
- mCertificate = null;
-
- updatePageOnChange(ExportWizardPage.DATA_KEYSTORE);
- }
-
- String getKeystorePassword() {
- return mKeystorePassword;
- }
-
- void setKeyCreationMode(boolean createKey) {
- mKeyCreationMode = createKey;
- updatePageOnChange(ExportWizardPage.DATA_KEY);
- }
-
- boolean getKeyCreationMode() {
- return mKeyCreationMode;
- }
-
- void setExistingAliases(List<String> aliases) {
- mExistingAliases = aliases;
- }
-
- List<String> getExistingAliases() {
- return mExistingAliases;
- }
-
- void setKeyAlias(String name) {
- mKeyAlias = name;
- mPrivateKey = null;
- mCertificate = null;
-
- updatePageOnChange(ExportWizardPage.DATA_KEY);
- }
-
- String getKeyAlias() {
- return mKeyAlias;
- }
-
- void setKeyPassword(String password) {
- mKeyPassword = password;
- mPrivateKey = null;
- mCertificate = null;
-
- updatePageOnChange(ExportWizardPage.DATA_KEY);
- }
-
- String getKeyPassword() {
- return mKeyPassword;
- }
-
- void setValidity(int validity) {
- mValidity = validity;
- updatePageOnChange(ExportWizardPage.DATA_KEY);
- }
-
- int getValidity() {
- return mValidity;
- }
-
- void setDName(String dName) {
- mDName = dName;
- updatePageOnChange(ExportWizardPage.DATA_KEY);
- }
-
- String getDName() {
- return mDName;
- }
-
- String getCertSha1Fingerprint() {
- return FingerprintUtils.getFingerprint(mCertificate, "SHA1");
- }
-
- String getCertMd5Fingerprint() {
- return FingerprintUtils.getFingerprint(mCertificate, "MD5");
- }
-
- void setSigningInfo(PrivateKey privateKey, X509Certificate certificate) {
- mPrivateKey = privateKey;
- mCertificate = certificate;
- }
-
- void setDestination(File destinationFile) {
- mDestinationFile = destinationFile;
- }
-
- void resetDestination() {
- mDestinationFile = null;
- }
-
- void updatePageOnChange(int changeMask) {
- for (ExportWizardPage page : mPages) {
- page.projectDataChanged(changeMask);
- }
- }
-
- private void displayError(String... messages) {
- String message = null;
- if (messages.length == 1) {
- message = messages[0];
- } else {
- StringBuilder sb = new StringBuilder(messages[0]);
- for (int i = 1; i < messages.length; i++) {
- sb.append('\n');
- sb.append(messages[i]);
- }
-
- message = sb.toString();
- }
-
- AdtPlugin.displayError("Export Wizard", message);
- }
-
- private void displayError(Throwable t) {
- String message = getExceptionMessage(t);
- displayError(message);
-
- AdtPlugin.log(t, "Export Wizard Error");
- }
-
- /**
- * Executes zipalign
- * @param zipAlignPath location of the zipalign too
- * @param source file to zipalign
- * @param destination where to write the resulting file
- * @return null if success, the error otherwise
- * @throws IOException
- */
- private String zipAlign(String zipAlignPath, File source, File destination) throws IOException {
- // command line: zipaling -f 4 tmp destination
- String[] command = new String[5];
- command[0] = zipAlignPath;
- command[1] = "-f"; //$NON-NLS-1$
- command[2] = "4"; //$NON-NLS-1$
- command[3] = source.getAbsolutePath();
- command[4] = destination.getAbsolutePath();
-
- Process process = Runtime.getRuntime().exec(command);
- final ArrayList<String> output = new ArrayList<String>();
- try {
- final IProject project = getProject();
-
- int status = GrabProcessOutput.grabProcessOutput(
- process,
- Wait.WAIT_FOR_READERS,
- new IProcessOutput() {
- @Override
- public void out(@Nullable String line) {
- if (line != null) {
- AdtPlugin.printBuildToConsole(BuildVerbosity.VERBOSE,
- project, line);
- }
- }
-
- @Override
- public void err(@Nullable String line) {
- if (line != null) {
- output.add(line);
- }
- }
- });
-
- if (status != 0) {
- // build a single message from the array list
- StringBuilder sb = new StringBuilder("Error while running zipalign:");
- for (String msg : output) {
- sb.append('\n');
- sb.append(msg);
- }
-
- return sb.toString();
- }
- } catch (InterruptedException e) {
- // ?
- }
- return null;
- }
-
- /**
- * Returns the {@link Throwable#getMessage()}. If the {@link Throwable#getMessage()} returns
- * <code>null</code>, the method is called again on the cause of the Throwable object.
- * <p/>If no Throwable in the chain has a valid message, the canonical name of the first
- * exception is returned.
- */
- static String getExceptionMessage(Throwable t) {
- String message = t.getMessage();
- if (message == null) {
- // no error info? get the stack call to display it
- // At least that'll give us a better bug report.
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- t.printStackTrace(new PrintStream(baos));
- message = baos.toString();
- }
-
- return message;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/export/KeyCheckPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/export/KeyCheckPage.java
deleted file mode 100644
index c17f43e38..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/export/KeyCheckPage.java
+++ /dev/null
@@ -1,378 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.export;
-
-import com.android.ide.eclipse.adt.internal.project.ProjectHelper;
-import com.android.ide.eclipse.adt.internal.wizards.export.ExportWizard.ExportWizardPage;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.ScrolledComposite;
-import org.eclipse.swt.events.ControlAdapter;
-import org.eclipse.swt.events.ControlEvent;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.forms.widgets.FormText;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.security.KeyStore;
-import java.security.KeyStore.PrivateKeyEntry;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.PrivateKey;
-import java.security.UnrecoverableEntryException;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-import java.util.Calendar;
-
-/**
- * Final page of the wizard that checks the key and ask for the ouput location.
- */
-final class KeyCheckPage extends ExportWizardPage {
-
- private static final int REQUIRED_YEARS = 25;
-
- private static final String VALIDITY_WARNING =
- "<p>Make sure the certificate is valid for the planned lifetime of the product.</p>"
- + "<p>If the certificate expires, you will be forced to sign your application with "
- + "a different one.</p>"
- + "<p>Applications cannot be upgraded if their certificate changes from "
- + "one version to another, forcing a full uninstall/install, which will make "
- + "the user lose his/her data.</p>"
- + "<p>Google Play(Android Market) currently requires certificates to be valid "
- + "until 2033.</p>";
-
- private final ExportWizard mWizard;
- private PrivateKey mPrivateKey;
- private X509Certificate mCertificate;
- private Text mDestination;
- private boolean mFatalSigningError;
- private FormText mDetailText;
- private ScrolledComposite mScrolledComposite;
-
- private String mKeyDetails;
- private String mDestinationDetails;
-
- protected KeyCheckPage(ExportWizard wizard, String pageName) {
- super(pageName);
- mWizard = wizard;
-
- setTitle("Destination and key/certificate checks");
- setDescription(""); // TODO
- }
-
- @Override
- public void createControl(Composite parent) {
- setErrorMessage(null);
- setMessage(null);
-
- // build the ui.
- Composite composite = new Composite(parent, SWT.NULL);
- composite.setLayoutData(new GridData(GridData.FILL_BOTH));
- GridLayout gl = new GridLayout(3, false);
- gl.verticalSpacing *= 3;
- composite.setLayout(gl);
-
- GridData gd;
-
- new Label(composite, SWT.NONE).setText("Destination APK file:");
- mDestination = new Text(composite, SWT.BORDER);
- mDestination.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
- mDestination.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- onDestinationChange(false /*forceDetailUpdate*/);
- }
- });
- final Button browseButton = new Button(composite, SWT.PUSH);
- browseButton.setText("Browse...");
- browseButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- FileDialog fileDialog = new FileDialog(browseButton.getShell(), SWT.SAVE);
-
- fileDialog.setText("Destination file name");
- // get a default apk name based on the project
- String filename = ProjectHelper.getApkFilename(mWizard.getProject(),
- null /*config*/);
- fileDialog.setFileName(filename);
-
- String saveLocation = fileDialog.open();
- if (saveLocation != null) {
- mDestination.setText(saveLocation);
- }
- }
- });
-
- mScrolledComposite = new ScrolledComposite(composite, SWT.V_SCROLL);
- mScrolledComposite.setLayoutData(gd = new GridData(GridData.FILL_BOTH));
- gd.horizontalSpan = 3;
- mScrolledComposite.setExpandHorizontal(true);
- mScrolledComposite.setExpandVertical(true);
-
- mDetailText = new FormText(mScrolledComposite, SWT.NONE);
- mScrolledComposite.setContent(mDetailText);
-
- mScrolledComposite.addControlListener(new ControlAdapter() {
- @Override
- public void controlResized(ControlEvent e) {
- updateScrolling();
- }
- });
-
- setControl(composite);
- }
-
- @Override
- void onShow() {
- // fill the texts with information loaded from the project.
- if ((mProjectDataChanged & DATA_PROJECT) != 0) {
- // reset the destination from the content of the project
- IProject project = mWizard.getProject();
-
- String destination = ProjectHelper.loadStringProperty(project,
- ExportWizard.PROPERTY_DESTINATION);
- if (destination != null) {
- mDestination.setText(destination);
- }
- }
-
- // if anything change we basically reload the data.
- if (mProjectDataChanged != 0) {
- mFatalSigningError = false;
-
- // reset the wizard with no key/cert to make it not finishable, unless a valid
- // key/cert is found.
- mWizard.setSigningInfo(null, null);
- mPrivateKey = null;
- mCertificate = null;
- mKeyDetails = null;
-
- if (mWizard.getKeystoreCreationMode() || mWizard.getKeyCreationMode()) {
- int validity = mWizard.getValidity();
- StringBuilder sb = new StringBuilder(
- String.format("<p>Certificate expires in %d years.</p>",
- validity));
-
- if (validity < REQUIRED_YEARS) {
- sb.append(VALIDITY_WARNING);
- }
-
- mKeyDetails = sb.toString();
- } else {
- try {
- KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
- FileInputStream fis = new FileInputStream(mWizard.getKeystore());
- keyStore.load(fis, mWizard.getKeystorePassword().toCharArray());
- fis.close();
- PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry)keyStore.getEntry(
- mWizard.getKeyAlias(),
- new KeyStore.PasswordProtection(
- mWizard.getKeyPassword().toCharArray()));
-
- if (entry != null) {
- mPrivateKey = entry.getPrivateKey();
- mCertificate = (X509Certificate)entry.getCertificate();
- } else {
- setErrorMessage("Unable to find key.");
-
- setPageComplete(false);
- }
- } catch (FileNotFoundException e) {
- // this was checked at the first previous step and will not happen here, unless
- // the file was removed during the export wizard execution.
- onException(e);
- } catch (KeyStoreException e) {
- onException(e);
- } catch (NoSuchAlgorithmException e) {
- onException(e);
- } catch (UnrecoverableEntryException e) {
- onException(e);
- } catch (CertificateException e) {
- onException(e);
- } catch (IOException e) {
- onException(e);
- }
-
- if (mPrivateKey != null && mCertificate != null) {
- Calendar expirationCalendar = Calendar.getInstance();
- expirationCalendar.setTime(mCertificate.getNotAfter());
- Calendar today = Calendar.getInstance();
-
- if (expirationCalendar.before(today)) {
- mKeyDetails = String.format(
- "<p>Certificate expired on %s</p>",
- mCertificate.getNotAfter().toString());
-
- // fatal error = nothing can make the page complete.
- mFatalSigningError = true;
-
- setErrorMessage("Certificate is expired.");
- setPageComplete(false);
- } else {
- // valid, key/cert: put it in the wizard so that it can be finished
- mWizard.setSigningInfo(mPrivateKey, mCertificate);
-
- StringBuilder sb = new StringBuilder(String.format(
- "<p>Certificate expires on %s.</p>",
- mCertificate.getNotAfter().toString()));
-
- int expirationYear = expirationCalendar.get(Calendar.YEAR);
- int thisYear = today.get(Calendar.YEAR);
-
- if (thisYear + REQUIRED_YEARS < expirationYear) {
- // do nothing
- } else {
- if (expirationYear == thisYear) {
- sb.append("<p>The certificate expires this year.</p>");
- } else {
- int count = expirationYear-thisYear;
- sb.append(String.format(
- "<p>The Certificate expires in %1$s %2$s.</p>",
- count, count == 1 ? "year" : "years"));
- }
- sb.append(VALIDITY_WARNING);
- }
-
- // show certificate fingerprints
- String sha1 = mWizard.getCertSha1Fingerprint();
- String md5 = mWizard.getCertMd5Fingerprint();
-
- sb.append("<p></p>" /*blank line*/);
- sb.append("<p>Certificate fingerprints:</p>");
- sb.append(String.format("<li>MD5 : %s</li>", md5));
- sb.append(String.format("<li>SHA1: %s</li>", sha1));
- sb.append("<p></p>" /*blank line*/);
-
- mKeyDetails = sb.toString();
- }
- } else {
- // fatal error = nothing can make the page complete.
- mFatalSigningError = true;
- }
- }
- }
-
- onDestinationChange(true /*forceDetailUpdate*/);
- }
-
- /**
- * Callback for destination field edition
- * @param forceDetailUpdate if true, the detail {@link FormText} is updated even if a fatal
- * error has happened in the signing.
- */
- private void onDestinationChange(boolean forceDetailUpdate) {
- if (mFatalSigningError == false) {
- // reset messages for now.
- setErrorMessage(null);
- setMessage(null);
-
- String path = mDestination.getText().trim();
-
- if (path.length() == 0) {
- setErrorMessage("Enter destination for the APK file.");
- // reset canFinish in the wizard.
- mWizard.resetDestination();
- setPageComplete(false);
- return;
- }
-
- File file = new File(path);
- if (file.isDirectory()) {
- setErrorMessage("Destination is a directory.");
- // reset canFinish in the wizard.
- mWizard.resetDestination();
- setPageComplete(false);
- return;
- }
-
- File parentFolder = file.getParentFile();
- if (parentFolder == null || parentFolder.isDirectory() == false) {
- setErrorMessage("Not a valid directory.");
- // reset canFinish in the wizard.
- mWizard.resetDestination();
- setPageComplete(false);
- return;
- }
-
- if (file.isFile()) {
- mDestinationDetails = "<li>WARNING: destination file already exists</li>";
- setMessage("Destination file already exists.", WARNING);
- }
-
- // no error, set the destination in the wizard.
- mWizard.setDestination(file);
- setPageComplete(true);
-
- updateDetailText();
- } else if (forceDetailUpdate) {
- updateDetailText();
- }
- }
-
- /**
- * Updates the scrollbar to match the content of the {@link FormText} or the new size
- * of the {@link ScrolledComposite}.
- */
- private void updateScrolling() {
- if (mDetailText != null) {
- Rectangle r = mScrolledComposite.getClientArea();
- mScrolledComposite.setMinSize(mDetailText.computeSize(r.width, SWT.DEFAULT));
- mScrolledComposite.layout();
- }
- }
-
- private void updateDetailText() {
- StringBuilder sb = new StringBuilder("<form>");
- if (mKeyDetails != null) {
- sb.append(mKeyDetails);
- }
-
- if (mDestinationDetails != null && mFatalSigningError == false) {
- sb.append(mDestinationDetails);
- }
-
- sb.append("</form>");
-
- mDetailText.setText(sb.toString(), true /* parseTags */,
- true /* expandURLs */);
-
- mDetailText.getParent().layout();
-
- updateScrolling();
- }
-
- @Override
- protected void onException(Throwable t) {
- super.onException(t);
-
- mKeyDetails = String.format("ERROR: %1$s", ExportWizard.getExceptionMessage(t));
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/export/KeyCreationPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/export/KeyCreationPage.java
deleted file mode 100644
index aea94ad8d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/export/KeyCreationPage.java
+++ /dev/null
@@ -1,339 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.export;
-
-import com.android.ide.eclipse.adt.internal.project.ProjectHelper;
-import com.android.ide.eclipse.adt.internal.wizards.export.ExportWizard.ExportWizardPage;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.VerifyEvent;
-import org.eclipse.swt.events.VerifyListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-
-import java.util.List;
-
-/**
- * Key creation page.
- */
-final class KeyCreationPage extends ExportWizardPage {
-
- private final ExportWizard mWizard;
- private Text mAlias;
- private Text mKeyPassword;
- private Text mKeyPassword2;
- private Text mCnField;
- private boolean mDisableOnChange = false;
- private Text mOuField;
- private Text mOField;
- private Text mLField;
- private Text mStField;
- private Text mCField;
- private String mDName;
- private int mValidity = 0;
- private List<String> mExistingAliases;
-
-
- protected KeyCreationPage(ExportWizard wizard, String pageName) {
- super(pageName);
- mWizard = wizard;
-
- setTitle("Key Creation");
- setDescription(""); // TODO?
- }
-
- @Override
- public void createControl(Composite parent) {
- Composite composite = new Composite(parent, SWT.NULL);
- composite.setLayoutData(new GridData(GridData.FILL_BOTH));
- GridLayout gl = new GridLayout(2, false);
- composite.setLayout(gl);
-
- GridData gd;
-
- new Label(composite, SWT.NONE).setText("Alias:");
- mAlias = new Text(composite, SWT.BORDER);
- mAlias.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
-
- new Label(composite, SWT.NONE).setText("Password:");
- mKeyPassword = new Text(composite, SWT.BORDER | SWT.PASSWORD);
- mKeyPassword.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
- mKeyPassword.addVerifyListener(sPasswordVerifier);
-
- new Label(composite, SWT.NONE).setText("Confirm:");
- mKeyPassword2 = new Text(composite, SWT.BORDER | SWT.PASSWORD);
- mKeyPassword2.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
- mKeyPassword2.addVerifyListener(sPasswordVerifier);
-
- new Label(composite, SWT.NONE).setText("Validity (years):");
- final Text validityText = new Text(composite, SWT.BORDER);
- validityText.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
- validityText.addVerifyListener(new VerifyListener() {
- @Override
- public void verifyText(VerifyEvent e) {
- // check for digit only.
- for (int i = 0 ; i < e.text.length(); i++) {
- char letter = e.text.charAt(i);
- if (letter < '0' || letter > '9') {
- e.doit = false;
- return;
- }
- }
- }
- });
-
- new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL).setLayoutData(
- gd = new GridData(GridData.FILL_HORIZONTAL));
- gd.horizontalSpan = 2;
-
- new Label(composite, SWT.NONE).setText("First and Last Name:");
- mCnField = new Text(composite, SWT.BORDER);
- mCnField.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
-
- new Label(composite, SWT.NONE).setText("Organizational Unit:");
- mOuField = new Text(composite, SWT.BORDER);
- mOuField.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
-
- new Label(composite, SWT.NONE).setText("Organization:");
- mOField = new Text(composite, SWT.BORDER);
- mOField.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
-
- new Label(composite, SWT.NONE).setText("City or Locality:");
- mLField = new Text(composite, SWT.BORDER);
- mLField.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
-
- new Label(composite, SWT.NONE).setText("State or Province:");
- mStField = new Text(composite, SWT.BORDER);
- mStField.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
-
- new Label(composite, SWT.NONE).setText("Country Code (XX):");
- mCField = new Text(composite, SWT.BORDER);
- mCField.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
-
- // Show description the first time
- setErrorMessage(null);
- setMessage(null);
- setControl(composite);
-
- mAlias.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- mWizard.setKeyAlias(mAlias.getText().trim());
- onChange();
- }
- });
- mKeyPassword.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- mWizard.setKeyPassword(mKeyPassword.getText());
- onChange();
- }
- });
- mKeyPassword2.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- onChange();
- }
- });
-
- validityText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- try {
- mValidity = Integer.parseInt(validityText.getText());
- } catch (NumberFormatException e2) {
- // this should only happen if the text field is empty due to the verifyListener.
- mValidity = 0;
- }
- mWizard.setValidity(mValidity);
- onChange();
- }
- });
-
- ModifyListener dNameListener = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- onDNameChange();
- }
- };
-
- mCnField.addModifyListener(dNameListener);
- mOuField.addModifyListener(dNameListener);
- mOField.addModifyListener(dNameListener);
- mLField.addModifyListener(dNameListener);
- mStField.addModifyListener(dNameListener);
- mCField.addModifyListener(dNameListener);
- }
-
- @Override
- void onShow() {
- // fill the texts with information loaded from the project.
- if ((mProjectDataChanged & (DATA_PROJECT | DATA_KEYSTORE)) != 0) {
- // reset the keystore/alias from the content of the project
- IProject project = mWizard.getProject();
-
- // disable onChange for now. we'll call it once at the end.
- mDisableOnChange = true;
-
- String alias = ProjectHelper.loadStringProperty(project, ExportWizard.PROPERTY_ALIAS);
- if (alias != null) {
- mAlias.setText(alias);
- }
-
- // get the existing list of keys if applicable
- if (mWizard.getKeyCreationMode()) {
- mExistingAliases = mWizard.getExistingAliases();
- } else {
- mExistingAliases = null;
- }
-
- // reset the passwords
- mKeyPassword.setText(""); //$NON-NLS-1$
- mKeyPassword2.setText(""); //$NON-NLS-1$
-
- // enable onChange, and call it to display errors and enable/disable pageCompleted.
- mDisableOnChange = false;
- onChange();
- }
- }
-
- @Override
- public IWizardPage getPreviousPage() {
- if (mWizard.getKeyCreationMode()) { // this means we create a key from an existing store
- return mWizard.getKeySelectionPage();
- }
-
- return mWizard.getKeystoreSelectionPage();
- }
-
- @Override
- public IWizardPage getNextPage() {
- return mWizard.getKeyCheckPage();
- }
-
- /**
- * Handles changes and update the error message and calls {@link #setPageComplete(boolean)}.
- */
- private void onChange() {
- if (mDisableOnChange) {
- return;
- }
-
- setErrorMessage(null);
- setMessage(null);
-
- if (mAlias.getText().trim().length() == 0) {
- setErrorMessage("Enter key alias.");
- setPageComplete(false);
- return;
- } else if (mExistingAliases != null) {
- // we cannot use indexOf, because we need to do a case-insensitive check
- String keyAlias = mAlias.getText().trim();
- for (String alias : mExistingAliases) {
- if (alias.equalsIgnoreCase(keyAlias)) {
- setErrorMessage("Key alias already exists in keystore.");
- setPageComplete(false);
- return;
- }
- }
- }
-
- String value = mKeyPassword.getText();
- if (value.length() == 0) {
- setErrorMessage("Enter key password.");
- setPageComplete(false);
- return;
- } else if (value.length() < 6) {
- setErrorMessage("Key password is too short - must be at least 6 characters.");
- setPageComplete(false);
- return;
- }
-
- if (value.equals(mKeyPassword2.getText()) == false) {
- setErrorMessage("Key passwords don't match.");
- setPageComplete(false);
- return;
- }
-
- if (mValidity == 0) {
- setErrorMessage("Key certificate validity is required.");
- setPageComplete(false);
- return;
- } else if (mValidity < 25) {
- setMessage("A 25 year certificate validity is recommended.", WARNING);
- } else if (mValidity > 1000) {
- setErrorMessage("Key certificate validity must be between 1 and 1000 years.");
- setPageComplete(false);
- return;
- }
-
- if (mDName == null || mDName.length() == 0) {
- setErrorMessage("At least one Certificate issuer field is required to be non-empty.");
- setPageComplete(false);
- return;
- }
-
- setPageComplete(true);
- }
-
- /**
- * Handles changes in the DName fields.
- */
- private void onDNameChange() {
- StringBuilder sb = new StringBuilder();
-
- buildDName("CN", mCnField, sb);
- buildDName("OU", mOuField, sb);
- buildDName("O", mOField, sb);
- buildDName("L", mLField, sb);
- buildDName("ST", mStField, sb);
- buildDName("C", mCField, sb);
-
- mDName = sb.toString();
- mWizard.setDName(mDName);
-
- onChange();
- }
-
- /**
- * Builds the distinguished name string with the provided {@link StringBuilder}.
- * @param prefix the prefix of the entry.
- * @param textField The {@link Text} field containing the entry value.
- * @param sb the string builder containing the dname.
- */
- private void buildDName(String prefix, Text textField, StringBuilder sb) {
- if (textField != null) {
- String value = textField.getText().trim();
- if (value.length() > 0) {
- if (sb.length() > 0) {
- sb.append(",");
- }
-
- sb.append(prefix);
- sb.append('=');
- sb.append(value);
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/export/KeySelectionPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/export/KeySelectionPage.java
deleted file mode 100644
index 604a208e6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/export/KeySelectionPage.java
+++ /dev/null
@@ -1,268 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.export;
-
-import com.android.ide.eclipse.adt.internal.project.ProjectHelper;
-import com.android.ide.eclipse.adt.internal.wizards.export.ExportWizard.ExportWizardPage;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.security.KeyStore;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.security.cert.CertificateException;
-import java.util.ArrayList;
-import java.util.Enumeration;
-
-/**
- * Key Selection Page. This is used when an existing keystore is used.
- */
-final class KeySelectionPage extends ExportWizardPage {
-
- private final ExportWizard mWizard;
- private Label mKeyAliasesLabel;
- private Combo mKeyAliases;
- private Label mKeyPasswordLabel;
- private Text mKeyPassword;
- private boolean mDisableOnChange = false;
- private Button mUseExistingKey;
- private Button mCreateKey;
-
- protected KeySelectionPage(ExportWizard wizard, String pageName) {
- super(pageName);
- mWizard = wizard;
-
- setTitle("Key alias selection");
- setDescription(""); // TODO
- }
-
- @Override
- public void createControl(Composite parent) {
- Composite composite = new Composite(parent, SWT.NULL);
- composite.setLayoutData(new GridData(GridData.FILL_BOTH));
- GridLayout gl = new GridLayout(3, false);
- composite.setLayout(gl);
-
- GridData gd;
-
- mUseExistingKey = new Button(composite, SWT.RADIO);
- mUseExistingKey.setText("Use existing key");
- mUseExistingKey.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
- gd.horizontalSpan = 3;
- mUseExistingKey.setSelection(true);
-
- new Composite(composite, SWT.NONE).setLayoutData(gd = new GridData());
- gd.heightHint = 0;
- gd.widthHint = 50;
- mKeyAliasesLabel = new Label(composite, SWT.NONE);
- mKeyAliasesLabel.setText("Alias:");
- mKeyAliases = new Combo(composite, SWT.READ_ONLY);
- mKeyAliases.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- new Composite(composite, SWT.NONE).setLayoutData(gd = new GridData());
- gd.heightHint = 0;
- gd.widthHint = 50;
- mKeyPasswordLabel = new Label(composite, SWT.NONE);
- mKeyPasswordLabel.setText("Password:");
- mKeyPassword = new Text(composite, SWT.BORDER | SWT.PASSWORD);
- mKeyPassword.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- mCreateKey = new Button(composite, SWT.RADIO);
- mCreateKey.setText("Create new key");
- mCreateKey.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
- gd.horizontalSpan = 3;
-
- // Show description the first time
- setErrorMessage(null);
- setMessage(null);
- setControl(composite);
-
- mUseExistingKey.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- mWizard.setKeyCreationMode(!mUseExistingKey.getSelection());
- enableWidgets();
- onChange();
- }
- });
-
- mKeyAliases.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- mWizard.setKeyAlias(mKeyAliases.getItem(mKeyAliases.getSelectionIndex()));
- onChange();
- }
- });
-
- mKeyPassword.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- mWizard.setKeyPassword(mKeyPassword.getText());
- onChange();
- }
- });
- }
-
- @Override
- void onShow() {
- // fill the texts with information loaded from the project.
- if ((mProjectDataChanged & (DATA_PROJECT | DATA_KEYSTORE)) != 0) {
- // disable onChange for now. we'll call it once at the end.
- mDisableOnChange = true;
-
- // reset the alias from the content of the project
- try {
- // reset to using a key
- mWizard.setKeyCreationMode(false);
- mUseExistingKey.setSelection(true);
- mCreateKey.setSelection(false);
- enableWidgets();
-
- // remove the content of the alias combo always and first, in case the
- // keystore password is wrong
- mKeyAliases.removeAll();
-
- // get the alias list (also used as a keystore password test)
- KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
- FileInputStream fis = new FileInputStream(mWizard.getKeystore());
- keyStore.load(fis, mWizard.getKeystorePassword().toCharArray());
- fis.close();
-
- Enumeration<String> aliases = keyStore.aliases();
-
- // get the alias from the project previous export, and look for a match as
- // we add the aliases to the combo.
- IProject project = mWizard.getProject();
-
- String keyAlias = ProjectHelper.loadStringProperty(project,
- ExportWizard.PROPERTY_ALIAS);
-
- ArrayList<String> aliasList = new ArrayList<String>();
-
- int selection = -1;
- int count = 0;
- while (aliases.hasMoreElements()) {
- String alias = aliases.nextElement();
- mKeyAliases.add(alias);
- aliasList.add(alias);
- if (selection == -1 && alias.equalsIgnoreCase(keyAlias)) {
- selection = count;
- }
- count++;
- }
-
- mWizard.setExistingAliases(aliasList);
-
- if (selection != -1) {
- mKeyAliases.select(selection);
-
- // since a match was found and is selected, we need to give it to
- // the wizard as well
- mWizard.setKeyAlias(keyAlias);
- } else {
- mKeyAliases.clearSelection();
- }
-
- // reset the password
- mKeyPassword.setText(""); //$NON-NLS-1$
-
- // enable onChange, and call it to display errors and enable/disable pageCompleted.
- mDisableOnChange = false;
- onChange();
- } catch (KeyStoreException e) {
- onException(e);
- } catch (FileNotFoundException e) {
- onException(e);
- } catch (NoSuchAlgorithmException e) {
- onException(e);
- } catch (CertificateException e) {
- onException(e);
- } catch (IOException e) {
- onException(e);
- } finally {
- // in case we exit with an exception, we need to reset this
- mDisableOnChange = false;
- }
- }
- }
-
- @Override
- public IWizardPage getPreviousPage() {
- return mWizard.getKeystoreSelectionPage();
- }
-
- @Override
- public IWizardPage getNextPage() {
- if (mWizard.getKeyCreationMode()) {
- return mWizard.getKeyCreationPage();
- }
-
- return mWizard.getKeyCheckPage();
- }
-
- /**
- * Handles changes and update the error message and calls {@link #setPageComplete(boolean)}.
- */
- private void onChange() {
- if (mDisableOnChange) {
- return;
- }
-
- setErrorMessage(null);
- setMessage(null);
-
- if (mWizard.getKeyCreationMode() == false) {
- if (mKeyAliases.getSelectionIndex() == -1) {
- setErrorMessage("Select a key alias.");
- setPageComplete(false);
- return;
- }
-
- if (mKeyPassword.getText().trim().length() == 0) {
- setErrorMessage("Enter key password.");
- setPageComplete(false);
- return;
- }
- }
-
- setPageComplete(true);
- }
-
- private void enableWidgets() {
- boolean useKey = !mWizard.getKeyCreationMode();
- mKeyAliasesLabel.setEnabled(useKey);
- mKeyAliases.setEnabled(useKey);
- mKeyPassword.setEnabled(useKey);
- mKeyPasswordLabel.setEnabled(useKey);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/export/KeystoreSelectionPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/export/KeystoreSelectionPage.java
deleted file mode 100644
index eabee15a2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/export/KeystoreSelectionPage.java
+++ /dev/null
@@ -1,264 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.export;
-
-import com.android.ide.eclipse.adt.internal.project.ProjectHelper;
-import com.android.ide.eclipse.adt.internal.wizards.export.ExportWizard.ExportWizardPage;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-
-import java.io.File;
-
-/**
- * Keystore selection page. This page allows to choose to create a new keystore or use an
- * existing one.
- */
-final class KeystoreSelectionPage extends ExportWizardPage {
-
- private final ExportWizard mWizard;
- private Button mUseExistingKeystore;
- private Button mCreateKeystore;
- private Text mKeystore;
- private Text mKeystorePassword;
- private Label mConfirmLabel;
- private Text mKeystorePassword2;
- private boolean mDisableOnChange = false;
-
- protected KeystoreSelectionPage(ExportWizard wizard, String pageName) {
- super(pageName);
- mWizard = wizard;
-
- setTitle("Keystore selection");
- setDescription(""); //TODO
- }
-
- @Override
- public void createControl(Composite parent) {
- Composite composite = new Composite(parent, SWT.NULL);
- composite.setLayoutData(new GridData(GridData.FILL_BOTH));
- GridLayout gl = new GridLayout(3, false);
- composite.setLayout(gl);
-
- GridData gd;
-
- mUseExistingKeystore = new Button(composite, SWT.RADIO);
- mUseExistingKeystore.setText("Use existing keystore");
- mUseExistingKeystore.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
- gd.horizontalSpan = 3;
- mUseExistingKeystore.setSelection(true);
-
- mCreateKeystore = new Button(composite, SWT.RADIO);
- mCreateKeystore.setText("Create new keystore");
- mCreateKeystore.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
- gd.horizontalSpan = 3;
-
- new Label(composite, SWT.NONE).setText("Location:");
- mKeystore = new Text(composite, SWT.BORDER);
- mKeystore.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
- final Button browseButton = new Button(composite, SWT.PUSH);
- browseButton.setText("Browse...");
- browseButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- FileDialog fileDialog;
- if (mUseExistingKeystore.getSelection()) {
- fileDialog = new FileDialog(browseButton.getShell(),SWT.OPEN);
- fileDialog.setText("Load Keystore");
- } else {
- fileDialog = new FileDialog(browseButton.getShell(),SWT.SAVE);
- fileDialog.setText("Select Keystore Name");
- }
-
- String fileName = fileDialog.open();
- if (fileName != null) {
- mKeystore.setText(fileName);
- }
- }
- });
-
- new Label(composite, SWT.NONE).setText("Password:");
- mKeystorePassword = new Text(composite, SWT.BORDER | SWT.PASSWORD);
- mKeystorePassword.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
- mKeystorePassword.addVerifyListener(sPasswordVerifier);
- new Composite(composite, SWT.NONE).setLayoutData(gd = new GridData());
- gd.heightHint = gd.widthHint = 0;
-
- mConfirmLabel = new Label(composite, SWT.NONE);
- mConfirmLabel.setText("Confirm:");
- mKeystorePassword2 = new Text(composite, SWT.BORDER | SWT.PASSWORD);
- mKeystorePassword2.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
- mKeystorePassword2.addVerifyListener(sPasswordVerifier);
- new Composite(composite, SWT.NONE).setLayoutData(gd = new GridData());
- gd.heightHint = gd.widthHint = 0;
- mKeystorePassword2.setEnabled(false);
-
- // Show description the first time
- setErrorMessage(null);
- setMessage(null);
- setControl(composite);
-
- mUseExistingKeystore.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- boolean createStore = !mUseExistingKeystore.getSelection();
- mKeystorePassword2.setEnabled(createStore);
- mConfirmLabel.setEnabled(createStore);
- mWizard.setKeystoreCreationMode(createStore);
- onChange();
- }
- });
-
- mKeystore.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- mWizard.setKeystore(mKeystore.getText().trim());
- onChange();
- }
- });
-
- mKeystorePassword.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- mWizard.setKeystorePassword(mKeystorePassword.getText());
- onChange();
- }
- });
-
- mKeystorePassword2.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- onChange();
- }
- });
- }
-
- @Override
- public IWizardPage getNextPage() {
- if (mUseExistingKeystore.getSelection()) {
- return mWizard.getKeySelectionPage();
- }
-
- return mWizard.getKeyCreationPage();
- }
-
- @Override
- void onShow() {
- // fill the texts with information loaded from the project.
- if ((mProjectDataChanged & DATA_PROJECT) != 0) {
- // reset the keystore/alias from the content of the project
- IProject project = mWizard.getProject();
-
- // disable onChange for now. we'll call it once at the end.
- mDisableOnChange = true;
-
- String keystore = ProjectHelper.loadStringProperty(project,
- ExportWizard.PROPERTY_KEYSTORE);
- if (keystore != null) {
- mKeystore.setText(keystore);
- }
-
- // reset the passwords
- mKeystorePassword.setText(""); //$NON-NLS-1$
- mKeystorePassword2.setText(""); //$NON-NLS-1$
-
- // enable onChange, and call it to display errors and enable/disable pageCompleted.
- mDisableOnChange = false;
- onChange();
- }
- }
-
- /**
- * Handles changes and update the error message and calls {@link #setPageComplete(boolean)}.
- */
- private void onChange() {
- if (mDisableOnChange) {
- return;
- }
-
- setErrorMessage(null);
- setMessage(null);
-
- boolean createStore = !mUseExistingKeystore.getSelection();
-
- // checks the keystore path is non null.
- String keystore = mKeystore.getText().trim();
- if (keystore.length() == 0) {
- setErrorMessage("Enter path to keystore.");
- setPageComplete(false);
- return;
- } else {
- File f = new File(keystore);
- if (f.exists() == false) {
- if (createStore == false) {
- setErrorMessage("Keystore does not exist.");
- setPageComplete(false);
- return;
- }
- } else if (f.isDirectory()) {
- setErrorMessage("Keystore path is a directory.");
- setPageComplete(false);
- return;
- } else if (f.isFile()) {
- if (createStore) {
- setErrorMessage("File already exists.");
- setPageComplete(false);
- return;
- }
- }
- }
-
- String value = mKeystorePassword.getText();
- if (value.length() == 0) {
- setErrorMessage("Enter keystore password.");
- setPageComplete(false);
- return;
- } else if (createStore && value.length() < 6) {
- setErrorMessage("Keystore password is too short - must be at least 6 characters.");
- setPageComplete(false);
- return;
- }
-
- if (createStore) {
- if (mKeystorePassword2.getText().length() == 0) {
- setErrorMessage("Confirm keystore password.");
- setPageComplete(false);
- return;
- }
-
- if (mKeystorePassword.getText().equals(mKeystorePassword2.getText()) == false) {
- setErrorMessage("Keystore passwords do not match.");
- setPageComplete(false);
- return;
- }
- }
-
- setPageComplete(true);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/export/ProjectCheckPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/export/ProjectCheckPage.java
deleted file mode 100644
index b8a7043da..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/export/ProjectCheckPage.java
+++ /dev/null
@@ -1,291 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.export;
-
-import com.android.ide.common.xml.ManifestData;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.project.AndroidManifestHelper;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.project.ProjectChooserHelper;
-import com.android.ide.eclipse.adt.internal.project.ProjectChooserHelper.NonLibraryProjectOnlyFilter;
-import com.android.ide.eclipse.adt.internal.project.ProjectHelper;
-import com.android.ide.eclipse.adt.internal.wizards.export.ExportWizard.ExportWizardPage;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-
-/**
- * First Export Wizard Page. Display warning/errors.
- */
-final class ProjectCheckPage extends ExportWizardPage {
- private final static String IMG_ERROR = "error.png"; //$NON-NLS-1$
- private final static String IMG_WARNING = "warning.png"; //$NON-NLS-1$
-
- private final ExportWizard mWizard;
- private Image mError;
- private Image mWarning;
- private boolean mHasMessage = false;
- private Composite mTopComposite;
- private Composite mErrorComposite;
- private Text mProjectText;
- private ProjectChooserHelper mProjectChooserHelper;
- private boolean mFirstOnShow = true;
-
- protected ProjectCheckPage(ExportWizard wizard, String pageName) {
- super(pageName);
- mWizard = wizard;
-
- setTitle("Project Checks");
- setDescription("Performs a set of checks to make sure the application can be exported.");
- }
-
- @Override
- public void createControl(Composite parent) {
- mProjectChooserHelper = new ProjectChooserHelper(parent.getShell(),
- new NonLibraryProjectOnlyFilter());
-
- GridLayout gl = null;
- GridData gd = null;
-
- mTopComposite = new Composite(parent, SWT.NONE);
- mTopComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
- mTopComposite.setLayout(new GridLayout(1, false));
-
- // composite for the project selection.
- Composite projectComposite = new Composite(mTopComposite, SWT.NONE);
- projectComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- projectComposite.setLayout(gl = new GridLayout(3, false));
- gl.marginHeight = gl.marginWidth = 0;
-
- Label label = new Label(projectComposite, SWT.NONE);
- label.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
- gd.horizontalSpan = 3;
- label.setText("Select the project to export:");
-
- new Label(projectComposite, SWT.NONE).setText("Project:");
- mProjectText = new Text(projectComposite, SWT.BORDER);
- mProjectText.setLayoutData(gd = new GridData(GridData.FILL_HORIZONTAL));
- mProjectText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- handleProjectNameChange();
- }
- });
-
- Button browseButton = new Button(projectComposite, SWT.PUSH);
- browseButton.setText("Browse...");
- browseButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- IJavaProject javaProject = mProjectChooserHelper.chooseJavaProject(
- mProjectText.getText().trim(),
- "Please select a project to export");
-
- if (javaProject != null) {
- IProject project = javaProject.getProject();
-
- // set the new name in the text field. The modify listener will take
- // care of updating the status and the ExportWizard object.
- mProjectText.setText(project.getName());
- }
- }
- });
-
- setControl(mTopComposite);
- }
-
- @Override
- void onShow() {
- if (mFirstOnShow) {
- // get the project and init the ui
- IProject project = mWizard.getProject();
- if (project != null) {
- mProjectText.setText(project.getName());
- }
-
- mFirstOnShow = false;
- }
- }
-
- private void buildErrorUi(IProject project) {
- // Show description the first time
- setErrorMessage(null);
- setMessage(null);
- setPageComplete(true);
- mHasMessage = false;
-
- // composite parent for the warning/error
- GridLayout gl = null;
- mErrorComposite = new Composite(mTopComposite, SWT.NONE);
- mErrorComposite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- gl = new GridLayout(2, false);
- gl.marginHeight = gl.marginWidth = 0;
- gl.verticalSpacing *= 3; // more spacing than normal.
- mErrorComposite.setLayout(gl);
-
- if (project == null) {
- setErrorMessage("Select project to export.");
- mHasMessage = true;
- } else {
- try {
- if (project.hasNature(AdtConstants.NATURE_DEFAULT) == false) {
- addError(mErrorComposite, "Project is not an Android project.");
- } else {
- // check for errors
- if (ProjectHelper.hasError(project, true)) {
- addError(mErrorComposite, "Project has compilation error(s)");
- }
-
- // check the project output
- IFolder outputIFolder = BaseProjectHelper.getJavaOutputFolder(project);
- if (outputIFolder == null) {
- addError(mErrorComposite,
- "Unable to get the output folder of the project!");
- }
-
- // project is an android project, we check the debuggable attribute.
- ManifestData manifestData = AndroidManifestHelper.parseForData(project);
- Boolean debuggable = null;
- if (manifestData != null) {
- debuggable = manifestData.getDebuggable();
- }
-
- if (debuggable != null && debuggable == Boolean.TRUE) {
- addWarning(mErrorComposite,
- "The manifest 'debuggable' attribute is set to true.\n" +
- "You should set it to false for applications that you release to the public.\n\n" +
- "Applications with debuggable=true are compiled in debug mode always.");
- }
-
- // check for mapview stuff
- }
- } catch (CoreException e) {
- // unable to access nature
- addError(mErrorComposite, "Unable to get project nature");
- }
- }
-
- if (mHasMessage == false) {
- Label label = new Label(mErrorComposite, SWT.NONE);
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan = 2;
- label.setLayoutData(gd);
- label.setText("No errors found. Click Next.");
- }
-
- mTopComposite.layout();
- }
-
- /**
- * Adds an error label to a {@link Composite} object.
- * @param parent the Composite parent.
- * @param message the error message.
- */
- private void addError(Composite parent, String message) {
- if (mError == null) {
- mError = IconFactory.getInstance().getIcon(IMG_ERROR);
- }
-
- new Label(parent, SWT.NONE).setImage(mError);
- Label label = new Label(parent, SWT.NONE);
- label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- label.setText(message);
-
- setErrorMessage("Application cannot be exported due to the error(s) below.");
- setPageComplete(false);
- mHasMessage = true;
- }
-
- /**
- * Adds a warning label to a {@link Composite} object.
- * @param parent the Composite parent.
- * @param message the warning message.
- */
- private void addWarning(Composite parent, String message) {
- if (mWarning == null) {
- mWarning = IconFactory.getInstance().getIcon(IMG_WARNING);
- }
-
- new Label(parent, SWT.NONE).setImage(mWarning);
- Label label = new Label(parent, SWT.NONE);
- label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- label.setText(message);
-
- mHasMessage = true;
- }
-
- /**
- * Checks the parameters for correctness, and update the error message and buttons.
- */
- private void handleProjectNameChange() {
- setPageComplete(false);
-
- if (mErrorComposite != null) {
- mErrorComposite.dispose();
- mErrorComposite = null;
- }
-
- // update the wizard with the new project
- mWizard.setProject(null);
-
- //test the project name first!
- String text = mProjectText.getText().trim();
- if (text.length() == 0) {
- setErrorMessage("Select project to export.");
- } else if (text.matches("[a-zA-Z0-9_ \\.-]+") == false) {
- setErrorMessage("Project name contains unsupported characters!");
- } else {
- IJavaProject[] projects = mProjectChooserHelper.getAndroidProjects(null);
- IProject found = null;
- for (IJavaProject javaProject : projects) {
- if (javaProject.getProject().getName().equals(text)) {
- found = javaProject.getProject();
- break;
- }
-
- }
-
- if (found != null) {
- setErrorMessage(null);
-
- // update the wizard with the new project
- mWizard.setProject(found);
-
- // now rebuild the error ui.
- buildErrorUi(found);
- } else {
- setErrorMessage(String.format("There is no android project named '%1$s'",
- text));
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/BuildFileCreator.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/BuildFileCreator.java
deleted file mode 100644
index d3df0584f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/BuildFileCreator.java
+++ /dev/null
@@ -1,642 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.exportgradle;
-
-import static com.android.SdkConstants.GRADLE_LATEST_VERSION;
-import static com.android.SdkConstants.GRADLE_PLUGIN_LATEST_VERSION;
-import static com.android.SdkConstants.GRADLE_PLUGIN_NAME;
-import static com.android.tools.lint.checks.GradleDetector.APP_PLUGIN_ID;
-import static com.android.tools.lint.checks.GradleDetector.LIB_PLUGIN_ID;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.io.IFolderWrapper;
-import com.android.io.IAbstractFile;
-import com.android.sdklib.io.FileOp;
-import com.android.xml.AndroidManifest;
-import com.google.common.base.Charsets;
-import com.google.common.base.Joiner;
-import com.google.common.collect.Lists;
-import com.google.common.io.Closeables;
-import com.google.common.io.Files;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.SubMonitor;
-import org.eclipse.jdt.core.IClasspathEntry;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.osgi.util.NLS;
-import org.eclipse.swt.widgets.Shell;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Comparator;
-import java.util.List;
-import java.util.Properties;
-import java.util.Set;
-import java.util.TreeSet;
-
-/**
- * Creates build.gradle and settings.gradle files for a set of projects.
- * <p>
- * Based on {@link org.eclipse.ant.internal.ui.datatransfer.BuildFileCreator}
- */
-public class BuildFileCreator {
- static final String BUILD_FILE = "build.gradle"; //$NON-NLS-1$
- static final String SETTINGS_FILE = "settings.gradle"; //$NON-NLS-1$
- private static final String NEWLINE = System.getProperty("line.separator"); //$NON-NLS-1$
- private static final String GRADLE_WRAPPER_LOCATION =
- "tools/templates/gradle/wrapper"; //$NON-NLS-1$
- static final String PLUGIN_CLASSPATH =
- "classpath '" + GRADLE_PLUGIN_NAME + GRADLE_PLUGIN_LATEST_VERSION + "'"; //$NON-NLS-1$
- static final String MAVEN_REPOSITORY = "jcenter()"; //$NON-NLS-1$
-
- private static final String[] GRADLE_WRAPPER_FILES = new String[] {
- "gradlew", //$NON-NLS-1$
- "gradlew.bat", //$NON-NLS-1$
- "gradle/wrapper/gradle-wrapper.jar", //$NON-NLS-1$
- "gradle/wrapper/gradle-wrapper.properties" //$NON-NLS-1$
- };
-
- private static final Comparator<IFile> FILE_COMPARATOR = new Comparator<IFile>() {
- @Override
- public int compare(IFile o1, IFile o2) {
- return o1.toString().compareTo(o2.toString());
- }
- };
-
- private final GradleModule mModule;
- private final StringBuilder mBuildFile = new StringBuilder();
-
- /**
- * Create buildfile for the projects.
- *
- * @param shell parent instance for dialogs
- * @return project names for which buildfiles were created
- * @throws InterruptedException thrown when user cancels task
- */
- public static void createBuildFiles(
- @NonNull ProjectSetupBuilder builder,
- @NonNull Shell shell,
- @NonNull IProgressMonitor pm) {
-
- File gradleLocation = new File(Sdk.getCurrent().getSdkOsLocation(), GRADLE_WRAPPER_LOCATION);
- SubMonitor localmonitor = null;
-
- try {
- // See if we have a Gradle wrapper in the SDK templates directory. If so, we can copy
- // it over.
- boolean hasGradleWrapper = true;
- for (File wrapperFile : getGradleWrapperFiles(gradleLocation)) {
- if (!wrapperFile.exists()) {
- hasGradleWrapper = false;
- }
- }
-
- Collection<GradleModule> modules = builder.getModules();
- boolean multiModules = modules.size() > 1;
-
- // determine files to create/change
- List<IFile> files = new ArrayList<IFile>();
-
- // add the build.gradle file for all modules.
- for (GradleModule module : modules) {
- // build.gradle file
- IFile file = module.getProject().getFile(BuildFileCreator.BUILD_FILE);
- files.add(file);
- }
-
- // get the commonRoot for all modules. If only one module, this returns the path
- // of the project.
- IPath commonRoot = builder.getCommonRoot();
-
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
- IPath workspaceLocation = workspaceRoot.getLocation();
-
- IPath relativePath = commonRoot.makeRelativeTo(workspaceLocation);
- // if makeRelativePath to returns the same path, then commonRoot is not in the
- // workspace.
- boolean rootInWorkspace = !relativePath.equals(commonRoot);
- // we only care if the root is a workspace project. if it's the workspace folder itself,
- // then the files won't be handled by the workspace.
- rootInWorkspace = rootInWorkspace && relativePath.segmentCount() > 0;
-
- File settingsFile = new File(commonRoot.toFile(), SETTINGS_FILE);
-
- // more than one modules -> generate settings.gradle
- if (multiModules && rootInWorkspace) {
-
- // Locate the settings.gradle file and add it to the changed files list
- IPath settingsGradle = Path.fromOSString(settingsFile.getAbsolutePath());
-
- // different path, means commonRoot is inside the workspace, which means we have
- // to add settings.gradle and wrapper files to the list of files to add.
- IFile iFile = workspaceRoot.getFile(settingsGradle);
- if (iFile != null) {
- files.add(iFile);
- }
- }
-
- // Gradle wrapper files
- if (hasGradleWrapper && rootInWorkspace) {
- // See if there already wrapper files there and only mark nonexistent ones for
- // creation.
- for (File wrapperFile : getGradleWrapperFiles(commonRoot.toFile())) {
- if (!wrapperFile.exists()) {
- IPath path = Path.fromOSString(wrapperFile.getAbsolutePath());
- IFile file = workspaceRoot.getFile(path);
- files.add(file);
- }
- }
- }
-
- ExportStatus status = new ExportStatus();
- builder.setStatus(status);
-
- // Trigger checkout of changed files
- Set<IFile> confirmedFiles = validateEdit(files, status, shell);
-
- if (status.hasError()) {
- return;
- }
-
- // Now iterate over all the modules and generate the build files.
- localmonitor = SubMonitor.convert(pm, ExportMessages.PageTitle,
- confirmedFiles.size());
- List<String> projectSettingsPath = Lists.newArrayList();
- for (GradleModule currentModule : modules) {
- IProject moduleProject = currentModule.getProject();
-
- IFile file = moduleProject.getFile(BuildFileCreator.BUILD_FILE);
- if (!confirmedFiles.contains(file)) {
- continue;
- }
-
- localmonitor.setTaskName(NLS.bind(ExportMessages.FileStatusMessage,
- moduleProject.getName()));
-
- ProjectState projectState = Sdk.getProjectState(moduleProject);
- BuildFileCreator instance = new BuildFileCreator(currentModule, shell);
- if (projectState != null) {
- // This is an Android project
- if (!multiModules) {
- instance.appendBuildScript();
- }
- instance.appendHeader(projectState.isLibrary());
- instance.appendDependencies();
- instance.startAndroidTask(projectState);
- //instance.appendDefaultConfig();
- instance.createAndroidSourceSets();
- instance.finishAndroidTask();
- } else {
- // This is a plain Java project
- instance.appendJavaHeader();
- instance.createJavaSourceSets();
- }
-
- try {
- // Write the build file
- String buildfile = instance.mBuildFile.toString();
- InputStream is =
- new ByteArrayInputStream(buildfile.getBytes("UTF-8")); //$NON-NLS-1$
- if (file.exists()) {
- file.setContents(is, true, true, null);
- } else {
- file.create(is, true, null);
- }
- } catch (Exception e) {
- status.addFileStatus(ExportStatus.FileStatus.IO_FAILURE,
- file.getLocation().toFile());
- status.setErrorMessage(e.getMessage());
- return;
- }
-
- if (localmonitor.isCanceled()) {
- return;
- }
- localmonitor.worked(1);
-
- // get the project path to add it to the settings.gradle.
- projectSettingsPath.add(currentModule.getPath());
- }
-
- // write the settings file.
- if (multiModules) {
- try {
- writeGradleSettingsFile(settingsFile, projectSettingsPath);
- } catch (IOException e) {
- status.addFileStatus(ExportStatus.FileStatus.IO_FAILURE, settingsFile);
- status.setErrorMessage(e.getMessage());
- return;
- }
- File mainBuildFile = new File(commonRoot.toFile(), BUILD_FILE);
- try {
- writeRootBuildGradle(mainBuildFile);
- } catch (IOException e) {
- status.addFileStatus(ExportStatus.FileStatus.IO_FAILURE, mainBuildFile);
- status.setErrorMessage(e.getMessage());
- return;
- }
- }
-
- // finally write the wrapper
- // TODO check we can based on where it is
- if (hasGradleWrapper) {
- copyGradleWrapper(gradleLocation, commonRoot.toFile(), status);
- if (status.hasError()) {
- return;
- }
- }
-
- } finally {
- if (localmonitor != null && !localmonitor.isCanceled()) {
- localmonitor.done();
- }
- if (pm != null) {
- pm.done();
- }
- }
- }
-
- /**
- * @param GradleModule create buildfile for this project
- * @param shell parent instance for dialogs
- */
- private BuildFileCreator(GradleModule module, Shell shell) {
- mModule = module;
- }
-
- /**
- * Return the files that comprise the Gradle wrapper as a collection of {@link File} instances.
- * @param root
- * @return
- */
- private static List<File> getGradleWrapperFiles(File root) {
- List<File> files = new ArrayList<File>(GRADLE_WRAPPER_FILES.length);
- for (String file : GRADLE_WRAPPER_FILES) {
- files.add(new File(root, file));
- }
- return files;
- }
-
- /**
- * Copy the Gradle wrapper files from one directory to another.
- */
- private static void copyGradleWrapper(File from, File to, ExportStatus status) {
- for (String file : GRADLE_WRAPPER_FILES) {
- File dest = new File(to, file);
- try {
- File src = new File(from, file);
- dest.getParentFile().mkdirs();
- new FileOp().copyFile(src, dest);
-
- if (src.getName().equals(GRADLE_PROPERTIES)) {
- updateGradleDistributionUrl(GRADLE_LATEST_VERSION, dest);
- }
- dest.setExecutable(src.canExecute());
- status.addFileStatus(ExportStatus.FileStatus.OK, dest);
- } catch (IOException e) {
- status.addFileStatus(ExportStatus.FileStatus.IO_FAILURE, dest);
- return;
- }
- }
- }
-
- /**
- * Outputs boilerplate buildscript information common to all Gradle build files.
- */
- private void appendBuildScript() {
- appendBuildScript(mBuildFile);
- }
-
- /**
- * Outputs boilerplate header information common to all Gradle build files.
- */
- private static void appendBuildScript(StringBuilder builder) {
- builder.append("buildscript {\n"); //$NON-NLS-1$
- builder.append(" repositories {\n"); //$NON-NLS-1$
- builder.append(" " + MAVEN_REPOSITORY + "\n"); //$NON-NLS-1$
- builder.append(" }\n"); //$NON-NLS-1$
- builder.append(" dependencies {\n"); //$NON-NLS-1$
- builder.append(" " + PLUGIN_CLASSPATH + "\n"); //$NON-NLS-1$
- builder.append(" }\n"); //$NON-NLS-1$
- builder.append("}\n"); //$NON-NLS-1$
- }
-
- /**
- * Outputs boilerplate header information common to all Gradle build files.
- */
- private void appendHeader(boolean isLibrary) {
- if (isLibrary) {
- mBuildFile.append("apply plugin: '").append(LIB_PLUGIN_ID).append("'\n"); //$NON-NLS-1$ //$NON-NLS-2$
- } else {
- mBuildFile.append("apply plugin: '").append(APP_PLUGIN_ID).append("'\n"); //$NON-NLS-1$ //$NON-NLS-2$
- }
- mBuildFile.append("\n"); //$NON-NLS-1$
- }
-
- /**
- * Outputs a block which sets up library and project dependencies.
- */
- private void appendDependencies() {
- mBuildFile.append("dependencies {\n"); //$NON-NLS-1$
-
- // first the local jars.
- // TODO: Fix
- mBuildFile.append(" compile fileTree(dir: 'libs', include: '*.jar')\n"); //$NON-NLS-1$
-
- for (GradleModule dep : mModule.getDependencies()) {
- mBuildFile.append(" compile project('" + dep.getPath() + "')\n"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- mBuildFile.append("}\n"); //$NON-NLS-1$
- mBuildFile.append("\n"); //$NON-NLS-1$
- }
-
- /**
- * Outputs the beginning of an Android task in the build file.
- */
- private void startAndroidTask(ProjectState projectState) {
- int buildApi = projectState.getTarget().getVersion().getApiLevel();
- String toolsVersion = projectState.getTarget().getBuildToolInfo().getRevision().toString();
- mBuildFile.append("android {\n"); //$NON-NLS-1$
- mBuildFile.append(" compileSdkVersion " + buildApi + "\n"); //$NON-NLS-1$
- mBuildFile.append(" buildToolsVersion \"" + toolsVersion + "\"\n"); //$NON-NLS-1$
- mBuildFile.append("\n"); //$NON-NLS-1$
-
- try {
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(projectState.getProject());
- // otherwise we check source compatibility
- String source = javaProject.getOption(JavaCore.COMPILER_SOURCE, true);
- if (JavaCore.VERSION_1_7.equals(source)) {
- mBuildFile.append(
- " compileOptions {\n" + //$NON-NLS-1$
- " sourceCompatibility JavaVersion.VERSION_1_7\n" + //$NON-NLS-1$
- " targetCompatibility JavaVersion.VERSION_1_7\n" + //$NON-NLS-1$
- " }\n" + //$NON-NLS-1$
- "\n"); //$NON-NLS-1$
- }
- } catch (CoreException e) {
- // Ignore compliance level, go with default
- }
- }
-
- /**
- * Outputs a sourceSets block to the Android task that locates all of the various source
- * subdirectories in the project.
- */
- private void createAndroidSourceSets() {
- IFolderWrapper projectFolder = new IFolderWrapper(mModule.getProject());
- IAbstractFile mManifestFile = AndroidManifest.getManifest(projectFolder);
- if (mManifestFile == null) {
- return;
- }
- List<String> srcDirs = new ArrayList<String>();
- for (IClasspathEntry entry : mModule.getJavaProject().readRawClasspath()) {
- if (entry.getEntryKind() != IClasspathEntry.CPE_SOURCE ||
- SdkConstants.FD_GEN_SOURCES.equals(entry.getPath().lastSegment())) {
- continue;
- }
- IPath path = entry.getPath().removeFirstSegments(1);
- srcDirs.add("'" + path.toOSString() + "'"); //$NON-NLS-1$
- }
-
- String srcPaths = Joiner.on(",").join(srcDirs);
-
- mBuildFile.append(" sourceSets {\n"); //$NON-NLS-1$
- mBuildFile.append(" main {\n"); //$NON-NLS-1$
- mBuildFile.append(" manifest.srcFile '" + SdkConstants.FN_ANDROID_MANIFEST_XML + "'\n"); //$NON-NLS-1$
- mBuildFile.append(" java.srcDirs = [" + srcPaths + "]\n"); //$NON-NLS-1$
- mBuildFile.append(" resources.srcDirs = [" + srcPaths + "]\n"); //$NON-NLS-1$
- mBuildFile.append(" aidl.srcDirs = [" + srcPaths + "]\n"); //$NON-NLS-1$
- mBuildFile.append(" renderscript.srcDirs = [" + srcPaths + "]\n"); //$NON-NLS-1$
- mBuildFile.append(" res.srcDirs = ['res']\n"); //$NON-NLS-1$
- mBuildFile.append(" assets.srcDirs = ['assets']\n"); //$NON-NLS-1$
- mBuildFile.append(" }\n"); //$NON-NLS-1$
- mBuildFile.append("\n"); //$NON-NLS-1$
- mBuildFile.append(" // Move the tests to tests/java, tests/res, etc...\n"); //$NON-NLS-1$
- mBuildFile.append(" instrumentTest.setRoot('tests')\n"); //$NON-NLS-1$
- if (srcDirs.contains("'src'")) {
- mBuildFile.append("\n"); //$NON-NLS-1$
- mBuildFile.append(" // Move the build types to build-types/<type>\n"); //$NON-NLS-1$
- mBuildFile.append(" // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...\n"); //$NON-NLS-1$
- mBuildFile.append(" // This moves them out of them default location under src/<type>/... which would\n"); //$NON-NLS-1$
- mBuildFile.append(" // conflict with src/ being used by the main source set.\n"); //$NON-NLS-1$
- mBuildFile.append(" // Adding new build types or product flavors should be accompanied\n"); //$NON-NLS-1$
- mBuildFile.append(" // by a similar customization.\n"); //$NON-NLS-1$
- mBuildFile.append(" debug.setRoot('build-types/debug')\n"); //$NON-NLS-1$
- mBuildFile.append(" release.setRoot('build-types/release')\n"); //$NON-NLS-1$
- }
- mBuildFile.append(" }\n"); //$NON-NLS-1$
- }
-
- /**
- * Outputs the completion of the Android task in the build file.
- */
- private void finishAndroidTask() {
- mBuildFile.append("}\n"); //$NON-NLS-1$
- }
-
- /**
- * Outputs a boilerplate header for non-Android projects
- */
- private void appendJavaHeader() {
- mBuildFile.append("apply plugin: 'java'\n"); //$NON-NLS-1$
- }
-
- /**
- * Outputs a sourceSets block for non-Android projects to locate the source directories.
- */
- private void createJavaSourceSets() {
- List<String> dirs = new ArrayList<String>();
- for (IClasspathEntry entry : mModule.getJavaProject().readRawClasspath()) {
- if (entry.getEntryKind() != IClasspathEntry.CPE_SOURCE) {
- continue;
- }
- IPath path = entry.getPath().removeFirstSegments(1);
- dirs.add("'" + path.toOSString() + "'"); //$NON-NLS-1$
- }
-
- String srcPaths = Joiner.on(",").join(dirs);
-
- mBuildFile.append("sourceSets {\n"); //$NON-NLS-1$
- mBuildFile.append(" main.java.srcDirs = [" + srcPaths + "]\n"); //$NON-NLS-1$
- mBuildFile.append(" main.resources.srcDirs = [" + srcPaths + "]\n"); //$NON-NLS-1$
- mBuildFile.append(" test.java.srcDirs = ['tests/java']\n"); //$NON-NLS-1$
- mBuildFile.append(" test.resources.srcDirs = ['tests/resources']\n"); //$NON-NLS-1$
- mBuildFile.append("}\n"); //$NON-NLS-1$
- }
-
- /**
- * Merges the new subproject dependencies into the settings.gradle file if it already exists,
- * and creates one if it does not.
- * @throws IOException
- */
- private static void writeGradleSettingsFile(File settingsFile, List<String> projectPaths)
- throws IOException {
- StringBuilder contents = new StringBuilder();
- for (String path : projectPaths) {
- contents.append("include '").append(path).append("'\n"); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- Files.write(contents.toString(), settingsFile, Charsets.UTF_8);
- }
-
- private static void writeRootBuildGradle(File buildFile) throws IOException {
- StringBuilder sb = new StringBuilder(
- "// Top-level build file where you can add configuration options common to all sub-projects/modules.\n");
-
- appendBuildScript(sb);
-
- Files.write(sb.toString(), buildFile, Charsets.UTF_8);
- }
-
- /**
- * Request write access to given files. Depending on the version control
- * plug-in opens a confirm checkout dialog.
- *
- * @param shell
- * parent instance for dialogs
- * @return <code>IFile</code> objects for which user confirmed checkout
- * @throws CoreException
- * thrown if project is under version control, but not connected
- */
- static Set<IFile> validateEdit(
- @NonNull List<IFile> files,
- @NonNull ExportStatus exportStatus,
- @NonNull Shell shell) {
- Set<IFile> confirmedFiles = new TreeSet<IFile>(FILE_COMPARATOR);
- if (files.size() == 0) {
- return confirmedFiles;
- }
- IStatus status = (files.get(0)).getWorkspace().validateEdit(
- files.toArray(new IFile[files.size()]), shell);
- if (status.isMultiStatus() && status.getChildren().length > 0) {
- for (int i = 0; i < status.getChildren().length; i++) {
- IStatus statusChild = status.getChildren()[i];
- if (statusChild.isOK()) {
- confirmedFiles.add(files.get(i));
- } else {
- exportStatus.addFileStatus(
- ExportStatus.FileStatus.VCS_FAILURE,
- files.get(i).getLocation().toFile());
- }
- }
- } else if (status.isOK()) {
- confirmedFiles.addAll(files);
- }
- if (status.getSeverity() == IStatus.ERROR) {
- // not possible to checkout files: not connected to version
- // control plugin or hijacked files and made read-only, so
- // collect error messages provided by validator and re-throw
- StringBuffer message = new StringBuffer(status.getPlugin() + ": " //$NON-NLS-1$
- + status.getMessage() + NEWLINE);
- if (status.isMultiStatus()) {
- for (int i = 0; i < status.getChildren().length; i++) {
- IStatus statusChild = status.getChildren()[i];
- message.append(statusChild.getMessage() + NEWLINE);
- }
- }
- String s = message.toString();
- exportStatus.setErrorMessage(s);
- }
-
- return confirmedFiles;
- }
-
- // -------------------------------------------------------------------------------
- // Fix gradle wrapper version. This code is from GradleUtil in the Studio plugin:
- // -------------------------------------------------------------------------------
-
- private static final String GRADLE_PROPERTIES = "gradle-wrapper.properties";
- private static final String GRADLEW_PROPERTIES_PATH =
- "gradle" + File.separator + "wrapper" + File.separator + GRADLE_PROPERTIES;
- private static final String GRADLEW_DISTRIBUTION_URL_PROPERTY_NAME = "distributionUrl";
-
- @NonNull
- private static File getGradleWrapperPropertiesFilePath(@NonNull File projectRootDir) {
- return new File(projectRootDir, GRADLEW_PROPERTIES_PATH);
- }
-
- @Nullable
- public static File findWrapperPropertiesFile(@NonNull File projectRootDir) {
- File wrapperPropertiesFile = getGradleWrapperPropertiesFilePath(projectRootDir);
- return wrapperPropertiesFile.isFile() ? wrapperPropertiesFile : null;
- }
-
- private static boolean updateGradleDistributionUrl(
- @NonNull String gradleVersion,
- @NonNull File propertiesFile) throws IOException {
- Properties properties = loadGradleWrapperProperties(propertiesFile);
- String gradleDistributionUrl = getGradleDistributionUrl(gradleVersion, false);
- String property = properties.getProperty(GRADLEW_DISTRIBUTION_URL_PROPERTY_NAME);
- if (property != null
- && (property.equals(gradleDistributionUrl) || property
- .equals(getGradleDistributionUrl(gradleVersion, true)))) {
- return false;
- }
- properties.setProperty(GRADLEW_DISTRIBUTION_URL_PROPERTY_NAME, gradleDistributionUrl);
- FileOutputStream out = null;
- try {
- out = new FileOutputStream(propertiesFile);
- properties.store(out, null);
- return true;
- } finally {
- Closeables.close(out, true);
- }
- }
-
- @NonNull
- private static Properties loadGradleWrapperProperties(@NonNull File propertiesFile)
- throws IOException {
- Properties properties = new Properties();
- FileInputStream fileInputStream = null;
- try {
- fileInputStream = new FileInputStream(propertiesFile);
- properties.load(fileInputStream);
- return properties;
- } finally {
- Closeables.close(fileInputStream, true);
- }
- }
-
- @NonNull
- private static String getGradleDistributionUrl(@NonNull String gradleVersion,
- boolean binOnly) {
- String suffix = binOnly ? "bin" : "all";
- return String.format("https://services.gradle.org/distributions/gradle-%1$s-" + suffix
- + ".zip", gradleVersion);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ConfirmationPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ConfirmationPage.java
deleted file mode 100644
index 1f236fb2b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ConfirmationPage.java
+++ /dev/null
@@ -1,275 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.exportgradle;
-
-import com.google.common.collect.Lists;
-
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.SelectionChangedEvent;
-import org.eclipse.jface.viewers.TableLayout;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.ui.model.WorkbenchLabelProvider;
-
-import java.io.File;
-import java.util.Collection;
-import java.util.List;
-
-/**
- * Confirmation page to review the actual project export
- * list and see warning about existing files.
- *
- */
-public class ConfirmationPage extends WizardPage {
-
- private final ProjectSetupBuilder mBuilder;
- private TableViewer mTableViewer;
- private Label mModuleDescription1;
- private Label mModuleDescription2;
- private Label mModuleDescription3;
- private Label mProjectRootLabel;
- private Label mProjectRootWarning;
- private List<IJavaProject> mOverrideProjects;
- private boolean mOverrideWarning;
- private Button mForceOverride;
-
- public ConfirmationPage(ProjectSetupBuilder builder) {
- super("ConfirmationPage"); //$NON-NLS-1$
- mBuilder = builder;
- setPageComplete(false);
- setTitle(ExportMessages.PageTitle);
- setDescription(ExportMessages.PageDescription);
- }
-
- @Override
- public void createControl(Composite parent) {
- initializeDialogUnits(parent);
- GridData data;
-
- Composite workArea = new Composite(parent, SWT.NONE);
- setControl(workArea);
-
- workArea.setLayout(new GridLayout());
- workArea.setLayoutData(new GridData(GridData.FILL_BOTH
- | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));
-
- Label title = new Label(workArea, SWT.NONE);
- title.setText("Please review the export options.");
-
- Group group = new Group(workArea, SWT.NONE);
- group.setText("Project root");
- group.setLayout(new GridLayout());
- group.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false));
-
- mProjectRootLabel = new Label(group, SWT.NONE);
- mProjectRootLabel.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false));
-
- mProjectRootWarning = new Label(group, SWT.NONE);
- mProjectRootWarning.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false));
-
- Group group2 = new Group(workArea, SWT.NONE);
- group2.setText("Exported Modules");
- group2.setLayout(new GridLayout());
- group2.setLayoutData(data = new GridData(SWT.FILL, SWT.FILL, true, true));
- data.heightHint = 300;
-
- Table table = new Table(group2, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
- mTableViewer = new TableViewer(table);
- table.setLayout(new TableLayout());
- table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
- mTableViewer.setContentProvider(new IStructuredContentProvider() {
- @Override
- public Object[] getElements(Object inputElement) {
- if (inputElement instanceof ProjectSetupBuilder) {
- ProjectSetupBuilder builder = (ProjectSetupBuilder) inputElement;
- Collection<GradleModule> modules = builder.getModules();
- Object[] array = new Object[modules.size()];
- int i = 0;
- for (GradleModule module : modules) {
- array[i++] = module.getJavaProject();
- }
-
- return array;
- }
-
- return null;
- }
-
- @Override
- public void dispose() {
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- });
- mTableViewer.setLabelProvider(new WorkbenchLabelProvider() {
- @Override
- protected String decorateText(String input, Object element) {
- if (element instanceof IJavaProject) {
- IJavaProject javaProject = (IJavaProject) element;
- StringBuilder sb = new StringBuilder(input);
- if (!mBuilder.isOriginalProject(javaProject)) {
- sb.append('*');
- }
- // TODO: decorate icon instead?
- if (mOverrideProjects.contains(javaProject)) {
- sb.append(" (1 warning)");
- }
-
- return sb.toString();
- }
-
- return input;
- }
- });
- mTableViewer.addSelectionChangedListener(new ISelectionChangedListener() {
- @Override
- public void selectionChanged(SelectionChangedEvent event) {
- IStructuredSelection selection = (IStructuredSelection) event.getSelection();
- Object firstElement = selection.getFirstElement();
- if (firstElement instanceof IJavaProject) {
- GradleModule module = mBuilder.getModule((IJavaProject) firstElement);
- if (mBuilder.getOriginalModules().contains(module)) {
- mModuleDescription1.setText("Exported because selected in previous page.");
- } else {
- List<GradleModule> list = mBuilder.getShortestDependencyTo(module);
- StringBuilder sb = new StringBuilder();
- for (GradleModule m : list) {
- if (sb.length() > 0) {
- sb.append(" > ");
- }
- sb.append(m.getJavaProject().getProject().getName());
- }
- mModuleDescription1.setText("Dependency chain: " + sb);
- }
- mModuleDescription2.setText("Path: " + module.getPath());
-
- if (mOverrideProjects.contains(module.getJavaProject())) {
- mModuleDescription3.setText(
- "WARNING: build.gradle already exists for this project");
- } else {
- mModuleDescription3.setText("");
- }
- } else {
- mModuleDescription1.setText("");
- mModuleDescription2.setText("");
- mModuleDescription3.setText("");
- }
- }
- });
-
- mModuleDescription1 = new Label(group2, SWT.NONE);
- mModuleDescription1.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false));
- mModuleDescription2 = new Label(group2, SWT.NONE);
- mModuleDescription2.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false));
- mModuleDescription3 = new Label(group2, SWT.NONE);
- mModuleDescription3.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false));
-
- mForceOverride = new Button(workArea, SWT.CHECK);
- mForceOverride.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false));
- mForceOverride.setText("Force overriding of existing files");
- mForceOverride.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateEnablement();
- }
- });
-
- setControl(workArea);
- Dialog.applyDialogFont(parent);
- }
-
- /**
- * Get list of projects which have already a buildfile.
- *
- * @param javaProjects list of IJavaProject objects
- * @return set of project names
- */
- private void computeOverride(String commonRoot) {
- mOverrideProjects = Lists.newArrayList();
- for (GradleModule module : mBuilder.getModules()) {
- if (new File(module.getProject().getLocation().toFile(),
- BuildFileCreator.BUILD_FILE).exists()) {
- mOverrideProjects.add(module.getJavaProject());
- }
- }
-
- // also check on the root settings.gradle/build.gradle
- boolean settingsFile = new File(commonRoot, BuildFileCreator.SETTINGS_FILE).exists();
- boolean buildFile = new File(commonRoot, BuildFileCreator.BUILD_FILE).exists();
- if (settingsFile && buildFile) {
- mProjectRootWarning.setText(
- "WARNING: build.gradle/settings.gradle already exists at this location.");
- } else if (settingsFile) {
- mProjectRootWarning.setText(
- "WARNING: settings.gradle already exists at this location.");
- } else if (buildFile) {
- mProjectRootWarning.setText("WARNING: build.gradle already exists at this location.");
- }
-
- mOverrideWarning = mOverrideProjects.size() > 0 || settingsFile || buildFile;
- }
-
- /**
- * Enables/disables the finish button on the wizard and displays error messages as needed.
- */
- private void updateEnablement() {
- if (mOverrideWarning && !mForceOverride.getSelection()) {
- setErrorMessage("Enable overriding of existing files before clicking Finish");
- mBuilder.setCanGenerate(false);
- } else {
- setErrorMessage(null);
- mBuilder.setCanGenerate(true);
- }
- setPageComplete(false);
- getContainer().updateButtons();
- }
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- if (visible) {
- mProjectRootWarning.setText("");
-
- String commonRoot = mBuilder.getCommonRoot().toOSString();
- computeOverride(commonRoot);
- mProjectRootLabel.setText(commonRoot);
- mTableViewer.setInput(mBuilder);
- mTableViewer.getTable().setFocus();
- mBuilder.setCanFinish(false);
- mBuilder.setCanGenerate(true);
- updateEnablement();
- }
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ExportMessages.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ExportMessages.java
deleted file mode 100644
index c7d6c1748..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ExportMessages.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.exportgradle;
-
-import org.eclipse.osgi.util.NLS;
-
-public class ExportMessages extends NLS {
- private static final String BUNDLE_NAME =
- "com.android.ide.eclipse.adt.internal.wizards.exportgradle.ExportMessages";//$NON-NLS-1$
-
- public static String PageTitle;
- public static String PageDescription;
- public static String SelectProjects;
- public static String ConfirmOverwrite;
- public static String ConfirmOverwriteTitle;
- public static String CyclicProjectsError;
- public static String ExportFailedError;
- public static String SelectAll;
- public static String DeselectAll;
- public static String NoProjectsError;
- public static String StatusMessage;
- public static String FileStatusMessage;
- public static String WindowTitle;
-
- static {
- // load message values from bundle file
- NLS.initializeMessages(BUNDLE_NAME, ExportMessages.class);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ExportMessages.properties b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ExportMessages.properties
deleted file mode 100644
index 1a6dbb192..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ExportMessages.properties
+++ /dev/null
@@ -1,27 +0,0 @@
-# Copyright (C) 2013 The Android Open Source Project
-#
-# Licensed under the Eclipse Public License, Version 1.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.eclipse.org/org/documents/epl-v10.php
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-PageTitle=Generate Gradle Build files
-PageDescription=Generates Gradle build files based on the configuration of the Java projects
-SelectProjects=Select the projects to use to &generate the Gradle buildfiles:
-ConfirmOverwrite=Are you sure you want to overwrite the buildfiles for these projects?
-ConfirmOverwriteTitle=Overwrite Buildfiles?
-CyclicProjectsError=A cycle was detected in the build path of project: {0}
-ExportFailedError=Buildfile export failed: {0}. See the error log for more details.
-SelectAll=&Select All
-DeselectAll=&Deselect All
-NoProjectsError=Select one or more projects to export.
-StatusMessage=Creating Gradle build files...
-FileStatusMessage=Generating build file for {0}...
-WindowTitle=Export \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ExportStatus.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ExportStatus.java
deleted file mode 100644
index 6fbe14e42..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ExportStatus.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.exportgradle;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.Multimap;
-
-import java.io.File;
-
-public class ExportStatus {
-
- public static enum FileStatus { OK, VCS_FAILURE, IO_FAILURE; }
-
- private String mMainError = null;
- private final Multimap<FileStatus, File> mFileStatus = ArrayListMultimap.create();
-
- void addFileStatus(@NonNull FileStatus status, @NonNull File file) {
- mFileStatus.put(status, file);
- }
-
- boolean hasError() {
- return mMainError != null ||
- !mFileStatus.get(FileStatus.VCS_FAILURE).isEmpty() ||
- !mFileStatus.get(FileStatus.IO_FAILURE).isEmpty();
- }
-
- public void setErrorMessage(String error) {
- mMainError = error;
- }
-
- @Nullable
- public String getErrorMessage() {
- return mMainError;
- }
-
- @NonNull
- public Multimap<FileStatus, File> getFileStatus() {
- return mFileStatus;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/FinalPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/FinalPage.java
deleted file mode 100644
index bbfadf855..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/FinalPage.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.exportgradle;
-
-import com.android.ide.eclipse.adt.internal.wizards.exportgradle.ExportStatus.FileStatus;
-import com.google.common.collect.Multimap;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Text;
-
-import java.io.File;
-import java.util.Collection;
-
-/**
- * Final page to review the result of the export.
- */
-public class FinalPage extends WizardPage {
-
- private final ProjectSetupBuilder mBuilder;
- private ExportStatus mStatus;
-
- private Text mText;
-
- public FinalPage(ProjectSetupBuilder builder) {
- super("FinalPage"); //$NON-NLS-1$
- mBuilder = builder;
- setPageComplete(true);
- setTitle(ExportMessages.PageTitle);
- setDescription(ExportMessages.PageDescription);
- }
-
- @Override
- public void createControl(Composite parent) {
- initializeDialogUnits(parent);
-
- mText = new Text(parent, SWT.MULTI | SWT.READ_ONLY);
- mText.setLayoutData(new GridData(GridData.FILL_BOTH
- | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));
-
- setControl(mText);
- Dialog.applyDialogFont(parent);
- }
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- if (visible) {
- mStatus = mBuilder.getStatus();
- mBuilder.setCanFinish(!mStatus.hasError());
- mBuilder.setCanGenerate(false);
-
- StringBuilder sb = new StringBuilder();
- if (mStatus.hasError()) {
- sb.append("There was an error!").append("\n\n");
-
- String errorMsg = mStatus.getErrorMessage();
- if (errorMsg != null) {
- sb.append(errorMsg);
- }
-
- Multimap<FileStatus, File> fileStatusMap = mStatus.getFileStatus();
- Collection<File> files = fileStatusMap.values();
- if (files != null) {
- sb.append("\n\n").append("Error on files:").append('\n');
- for (File file : files) {
- sb.append("\n").append(file.getAbsolutePath());
- }
- }
- } else {
- sb.append("Export successful.\n\n");
-
- int count = mBuilder.getModuleCount();
- if (count > 1) {
- sb.append(String.format("Exported %s modules", count)).append('\n');
- sb.append(String.format(
- "Root folder: %s", mBuilder.getCommonRoot().toOSString()));
- } else {
- sb.append("Exported project: ").append(mBuilder.getCommonRoot().toOSString());
- }
-
- sb.append("\n\n").append("Choose 'Import Non-Android Studio project' in Android Studio").append('\n');
- sb.append("and select the following file:").append("\n\t");
-
- File bGradle = new File(
- mBuilder.getCommonRoot().toFile(), BuildFileCreator.BUILD_FILE);
- sb.append(bGradle.getAbsolutePath());
-
- sb.append("\n\n").append("Do NOT import the Eclipse project itself!");
- }
-
- mText.setText(sb.toString());
- }
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/GradleExportWizard.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/GradleExportWizard.java
deleted file mode 100644
index 8c74187ff..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/GradleExportWizard.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.exportgradle;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubMonitor;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.ui.IExportWizard;
-import org.eclipse.ui.IWorkbench;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.Collection;
-
-public class GradleExportWizard extends Wizard implements IExportWizard {
-
- private ProjectSetupBuilder mBuilder = new ProjectSetupBuilder();
-
- private ProjectSelectionPage mFirstPage;
- private ConfirmationPage mSecondPage;
- private FinalPage mFinalPage;
-
- /**
- * Creates buildfile.
- */
- @Override
- public boolean performFinish() {
- if (mBuilder.canGenerate()) {
- generateBuildfiles(mSecondPage);
- getContainer().showPage(mFinalPage);
- return false;
- }
-
- return true;
- }
-
- @Override
- public void addPages() {
- addPage(new ImportInsteadPage());
- mFirstPage = new ProjectSelectionPage(mBuilder);
- addPage(mFirstPage);
- mSecondPage = new ConfirmationPage(mBuilder);
- addPage(mSecondPage);
- mFinalPage = new FinalPage(mBuilder);
- addPage(mFinalPage);
- }
-
- @Override
- public void init(IWorkbench workbench, IStructuredSelection selection) {
- setWindowTitle(ExportMessages.WindowTitle);
- setNeedsProgressMonitor(true);
- }
-
- @Override
- public boolean canFinish() {
- return mBuilder.canFinish() || mBuilder.canGenerate();
- }
-
- /**
- * Converts Eclipse Java projects to Gradle build files. Displays error dialogs.
- */
- public boolean generateBuildfiles(final WizardPage page) {
- IRunnableWithProgress runnable = new IRunnableWithProgress() {
- @Override
- public void run(IProgressMonitor pm) throws InterruptedException {
- Collection<GradleModule> modules = mBuilder.getModules();
- final int count = modules.size();
-
- SubMonitor localmonitor = SubMonitor.convert(pm, ExportMessages.StatusMessage,
- count);
- BuildFileCreator.createBuildFiles(
- mBuilder,
- page.getShell(),
- localmonitor.newChild(count));
- }
- };
-
- try {
- getContainer().run(false, false, runnable);
- } catch (InvocationTargetException e) {
- AdtPlugin.log(e, null);
- return false;
- } catch (InterruptedException e) {
- AdtPlugin.log(e, null);
- return false;
- }
- if (page.getErrorMessage() != null) {
- return false;
- }
- return true;
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/GradleModule.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/GradleModule.java
deleted file mode 100644
index 684f03b9a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/GradleModule.java
+++ /dev/null
@@ -1,90 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.exportgradle;
-
-import com.android.annotations.NonNull;
-import com.google.common.collect.Lists;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jdt.core.IJavaProject;
-
-import java.util.List;
-
-/**
- * A configured Gradle module for export. This includes gradle path, dependency, type, etc...
- */
-public class GradleModule {
-
- @NonNull
- private final IJavaProject mJavaProject;
-
- private String mPath;
- private Type mType;
-
- private final List<GradleModule> mDependencies = Lists.newArrayList();
-
- public static enum Type { ANDROID, JAVA };
-
- GradleModule(@NonNull IJavaProject javaProject) {
- mJavaProject = javaProject;
- }
-
- @NonNull
- public IJavaProject getJavaProject() {
- return mJavaProject;
- }
-
- @NonNull
- public IProject getProject() {
- return mJavaProject.getProject();
- }
-
- boolean isConfigured() {
- return mType != null;
- }
-
- public void setType(Type type) {
- mType = type;
- }
-
- public Type getType() {
- return mType;
- }
-
- public void addDependency(GradleModule module) {
- mDependencies.add(module);
- }
-
- public List<GradleModule> getDependencies() {
- return mDependencies;
- }
-
- public void setPath(String path) {
- mPath = path;
- }
-
- public String getPath() {
- return mPath;
- }
-
- @Override
- public String toString() {
- return "GradleModule [mJavaProject=" + mJavaProject + ", mPath=" + mPath + ", mType="
- + mType + ", mDependencies=" + mDependencies + "]";
- }
-}
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ImportInsteadPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ImportInsteadPage.java
deleted file mode 100644
index cff9aca63..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ImportInsteadPage.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.exportgradle;
-
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.CLabel;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-
-class ImportInsteadPage extends WizardPage {
- public ImportInsteadPage() {
- super("importInstead");
- setTitle("Import Instead?");
- setDescription("Consider importing directly into Android Studio instead of exporting from Eclipse");
- }
-
- @Override
- public void createControl(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
- setControl(container);
- container.setLayout(new GridLayout(1, false));
-
- CLabel label = new CLabel(container, SWT.NONE);
- label.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, false, 1, 1));
- label.setText(
- "Recent versions of Android Studio now support direct import of ADT projects.\n" +
- "\n" +
- "There are advantages to importing from Studio instead of exporting from Eclipse:\n" +
- "- It can replace jars and library projects with Gradle dependencies instead\n" +
- "- On import, it creates a new copy of the project and changes the project structure\n" +
- " to the new Gradle directory layout which better supports multiple resource directories.\n" +
- "- It can merge instrumentation test projects into the same project\n" +
- "- Android Studio is released more frequently than the ADT plugin, so the import\n" +
- " mechanism more closely tracks the requirements of Studio Gradle projects.\n" +
- "\n" +
- "If you want to preserve your Eclipse directory structure, or if for some reason import\n" +
- "in Studio doesn't work (please let us know by filing a bug), continue to export from\n" +
- "Eclipse instead.");
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ProjectSelectionPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ProjectSelectionPage.java
deleted file mode 100644
index 81c7a7346..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ProjectSelectionPage.java
+++ /dev/null
@@ -1,275 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.exportgradle;
-
-import com.google.common.base.Joiner;
-import com.google.common.collect.Lists;
-import com.ibm.icu.text.MessageFormat;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jdt.core.IJavaModel;
-import org.eclipse.jdt.core.IJavaModelMarker;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.viewers.CheckStateChangedEvent;
-import org.eclipse.jface.viewers.CheckboxTableViewer;
-import org.eclipse.jface.viewers.ICheckStateListener;
-import org.eclipse.jface.viewers.TableLayout;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.ui.model.WorkbenchContentProvider;
-import org.eclipse.ui.model.WorkbenchLabelProvider;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Displays a wizard page that lets the user choose the projects for which to create Gradle build
- * files.
- * <p>
- * Based on {@link org.eclipse.ant.internal.ui.datatransfer.AntBuildfileExportPage}
- */
-public class ProjectSelectionPage extends WizardPage {
-
- private final ProjectSetupBuilder mBuilder;
- private CheckboxTableViewer mTableViewer;
- private List<IJavaProject> mSelectedJavaProjects = Lists.newArrayList();
-
- public ProjectSelectionPage(ProjectSetupBuilder builder) {
- super("GradleExportPage"); //$NON-NLS-1$
- mBuilder = builder;
- setPageComplete(false);
- setTitle(ExportMessages.PageTitle);
- setDescription(ExportMessages.PageDescription);
- }
-
- @Override
- public void createControl(Composite parent) {
- initializeDialogUnits(parent);
-
- Composite workArea = new Composite(parent, SWT.NONE);
- setControl(workArea);
-
- workArea.setLayout(new GridLayout());
- workArea.setLayoutData(new GridData(GridData.FILL_BOTH
- | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));
-
- Label title = new Label(workArea, SWT.NONE);
- title.setText(ExportMessages.SelectProjects);
-
- Composite listComposite = new Composite(workArea, SWT.NONE);
- GridLayout layout = new GridLayout();
- layout.numColumns = 2;
- layout.marginWidth = 0;
- layout.makeColumnsEqualWidth = false;
- listComposite.setLayout(layout);
-
- listComposite.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL
- | GridData.GRAB_VERTICAL | GridData.FILL_BOTH));
-
- Table table = new Table(listComposite,
- SWT.CHECK | SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
- mTableViewer = new CheckboxTableViewer(table);
- table.setLayout(new TableLayout());
- GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
- data.heightHint = 300;
- table.setLayoutData(data);
- mTableViewer.setContentProvider(new WorkbenchContentProvider() {
- @Override
- public Object[] getElements(Object element) {
- if (element instanceof IJavaProject[]) {
- return (IJavaProject[]) element;
- }
- return null;
- }
- });
- mTableViewer.setLabelProvider(new WorkbenchLabelProvider());
- mTableViewer.addCheckStateListener(new ICheckStateListener() {
- @Override
- public void checkStateChanged(CheckStateChangedEvent event) {
- if (event.getChecked()) {
- mSelectedJavaProjects.add((IJavaProject) event.getElement());
- } else {
- mSelectedJavaProjects.remove(event.getElement());
- }
- updateEnablement();
- }
- });
-
- initializeProjects();
- createSelectionButtons(listComposite);
- setControl(workArea);
- updateEnablement();
- Dialog.applyDialogFont(parent);
- }
-
- /**
- * Creates select all/deselect all buttons.
- */
- private void createSelectionButtons(Composite composite) {
- Composite buttonsComposite = new Composite(composite, SWT.NONE);
- GridLayout layout = new GridLayout();
- layout.marginWidth = 0;
- layout.marginHeight = 0;
- buttonsComposite.setLayout(layout);
-
- buttonsComposite.setLayoutData(new GridData(
- GridData.VERTICAL_ALIGN_BEGINNING));
-
- Button selectAll = new Button(buttonsComposite, SWT.PUSH);
- selectAll.setText(ExportMessages.SelectAll);
- selectAll.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- for (int i = 0; i < mTableViewer.getTable().getItemCount(); i++) {
- mSelectedJavaProjects.add((IJavaProject) mTableViewer.getElementAt(i));
- }
- mTableViewer.setAllChecked(true);
- updateEnablement();
- }
- });
- setButtonLayoutData(selectAll);
-
- Button deselectAll = new Button(buttonsComposite, SWT.PUSH);
- deselectAll.setText(ExportMessages.DeselectAll);
- deselectAll.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- mSelectedJavaProjects.clear();
- mTableViewer.setAllChecked(false);
- updateEnablement();
- }
- });
- setButtonLayoutData(deselectAll);
- }
-
- /**
- * Populates the list with all the eligible projects in the workspace.
- */
- private void initializeProjects() {
- IWorkspaceRoot rootWorkspace = ResourcesPlugin.getWorkspace().getRoot();
- IJavaModel javaModel = JavaCore.create(rootWorkspace);
- IJavaProject[] javaProjects;
- try {
- javaProjects = javaModel.getJavaProjects();
- } catch (JavaModelException e) {
- javaProjects = new IJavaProject[0];
- }
- mTableViewer.setInput(javaProjects);
- // Check any necessary projects
- if (mSelectedJavaProjects != null) {
- mTableViewer.setCheckedElements(mSelectedJavaProjects.toArray(
- new IJavaProject[mSelectedJavaProjects.size()]));
- }
- }
-
- /**
- * Enables/disables the finish button on the wizard and displays error messages as needed.
- */
- private void updateEnablement() {
- String error = null;
- try {
- if (mSelectedJavaProjects.size() == 0) {
- error = ExportMessages.NoProjectsError;
- return;
- }
-
- List<String> cyclicProjects;
- try {
- cyclicProjects = getCyclicProjects(mSelectedJavaProjects);
- if (cyclicProjects.size() > 0) {
- error = MessageFormat.format(ExportMessages.CyclicProjectsError,
- new Object[] { Joiner.on(", ").join(cyclicProjects) }); //$NON-NLS-1$
- return;
- }
-
- error = mBuilder.setProject(mSelectedJavaProjects);
- if (error != null) {
- return;
- }
-
- } catch (CoreException ignored) {
- // TODO: do something?
- }
- } finally {
- setErrorMessage(error);
- setPageComplete(error == null);
- getContainer().updateButtons();
- }
- }
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- if (visible) {
- mTableViewer.getTable().setFocus();
- mBuilder.setCanFinish(false);
- mBuilder.setCanGenerate(false);
- }
- }
-
- /**
- * Returns given projects that have cyclic dependencies.
- *
- * @param javaProjects list of IJavaProject objects
- * @return set of project names
- */
- private List<String> getCyclicProjects(List<IJavaProject> projects) throws CoreException {
-
- List<String> cyclicProjects = new ArrayList<String>();
- for (IJavaProject javaProject : projects) {
- if (hasCyclicDependency(javaProject)) {
- cyclicProjects.add(javaProject.getProject().getName());
- }
- }
- return cyclicProjects;
- }
-
- /**
- * Check if given project has a cyclic dependency.
- * <p>
- * See {@link org.eclipse.jdt.core.tests.model.ClasspathTests.numberOfCycleMarkers}
- */
- private static boolean hasCyclicDependency(IJavaProject javaProject)
- throws CoreException {
- IMarker[] markers = javaProject.getProject().findMarkers(
- IJavaModelMarker.BUILDPATH_PROBLEM_MARKER, false,
- IResource.DEPTH_ONE);
- for (IMarker marker : markers) {
- String cycleAttr = (String) marker
- .getAttribute(IJavaModelMarker.CYCLE_DETECTED);
- if (cycleAttr != null && cycleAttr.equals("true")) { //$NON-NLS-1$
- return true;
- }
- }
- return false;
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ProjectSetupBuilder.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ProjectSetupBuilder.java
deleted file mode 100644
index 1fd6b74f6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ProjectSetupBuilder.java
+++ /dev/null
@@ -1,425 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.exportgradle;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState.LibraryState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jdt.core.IClasspathEntry;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IPackageFragmentRoot;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.JavaModelException;
-
-import java.io.File;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.regex.Pattern;
-
-/**
- * Class to setup the project and its modules.
- */
-public class ProjectSetupBuilder {
-
- private final static class InternalException extends Exception {
- private static final long serialVersionUID = 1L;
-
- InternalException(String message) {
- super(message);
- }
- }
-
- private boolean mCanFinish = false;
- private boolean mCanGenerate = false;
- private final List<GradleModule> mOriginalModules = Lists.newArrayList();
- private final Map<IJavaProject, GradleModule> mModules = Maps.newHashMap();
- private IPath mCommonRoot;
- private ExportStatus mStatus;
-
- public ProjectSetupBuilder() {
-
- }
-
- public void setCanGenerate(boolean generate) {
- mCanGenerate = generate;
- }
-
- public void setCanFinish(boolean canFinish) {
- mCanFinish = canFinish;
- }
-
- public boolean canFinish() {
- return mCanFinish;
- }
-
- public boolean canGenerate() {
- return mCanGenerate;
- }
-
- public void setStatus(ExportStatus status) {
- mStatus = status;
- }
-
- public ExportStatus getStatus() {
- return mStatus;
- }
-
- @NonNull
- public String setProject(@NonNull List<IJavaProject> selectedProjects)
- throws CoreException {
- mModules.clear();
-
- // build a list of all projects that must be included. This is in case
- // some dependencies have not been included in the selected projects. We also include
- // parent projects so that the full multi-project setup is correct.
- // Note that if two projects are selected that are not related, both will be added
- // in the same multi-project anyway.
- try {
- for (IJavaProject javaProject : selectedProjects) {
- GradleModule module;
-
- if (javaProject.getProject().hasNature(AdtConstants.NATURE_DEFAULT)) {
- module = processAndroidProject(javaProject);
- } else {
- module = processJavaProject(javaProject);
- }
-
- mOriginalModules.add(module);
- }
-
- Collection<GradleModule> modules = mModules.values();
- computeRootAndPaths(modules);
-
- return null;
- } catch (InternalException e) {
- return e.getMessage();
- }
- }
-
- @NonNull
- public Collection<GradleModule> getModules() {
- return mModules.values();
- }
-
- public int getModuleCount() {
- return mModules.size();
- }
-
- @Nullable
- public IPath getCommonRoot() {
- return mCommonRoot;
- }
-
- @Nullable
- public GradleModule getModule(IJavaProject javaProject) {
- return mModules.get(javaProject);
- }
-
- public boolean isOriginalProject(@NonNull IJavaProject javaProject) {
- GradleModule module = mModules.get(javaProject);
- return mOriginalModules.contains(module);
- }
-
- @NonNull
- public List<GradleModule> getOriginalModules() {
- return mOriginalModules;
- }
-
- @Nullable
- public List<GradleModule> getShortestDependencyTo(GradleModule module) {
- return findModule(module, mOriginalModules);
- }
-
- @Nullable
- public List<GradleModule> findModule(GradleModule toFind, GradleModule rootModule) {
- if (toFind == rootModule) {
- List<GradleModule> list = Lists.newArrayList();
- list.add(toFind);
- return list;
- }
-
- List<GradleModule> shortestChain = findModule(toFind, rootModule.getDependencies());
-
- if (shortestChain != null) {
- shortestChain.add(0, rootModule);
- }
-
- return shortestChain;
- }
-
- @Nullable
- public List<GradleModule> findModule(GradleModule toFind, List<GradleModule> modules) {
- List<GradleModule> currentChain = null;
-
- for (GradleModule child : modules) {
- List<GradleModule> newChain = findModule(toFind, child);
- if (currentChain == null) {
- currentChain = newChain;
- } else if (newChain != null) {
- if (currentChain.size() > newChain.size()) {
- currentChain = newChain;
- }
- }
- }
-
- return currentChain;
- }
-
- @NonNull
- private GradleModule processAndroidProject(@NonNull IJavaProject javaProject)
- throws InternalException, CoreException {
-
- // get/create the module
- GradleModule module = createModuleOnDemand(javaProject);
- if (module.isConfigured()) {
- return module;
- }
-
- module.setType(GradleModule.Type.ANDROID);
-
- ProjectState projectState = Sdk.getProjectState(javaProject.getProject());
- assert projectState != null;
-
- // add library project dependencies
- List<LibraryState> libraryProjects = projectState.getLibraries();
- for (LibraryState libraryState : libraryProjects) {
- ProjectState libProjectState = libraryState.getProjectState();
- if (libProjectState != null) {
- IJavaProject javaLib = getJavaProject(libProjectState);
- if (javaLib != null) {
- GradleModule libModule = processAndroidProject(javaLib);
- module.addDependency(libModule);
- } else {
- throw new InternalException(String.format(
- "Project %1$s is missing. Needed by %2$s.\n" +
- "Make sure all dependencies are opened.",
- libraryState.getRelativePath(),
- javaProject.getProject().getName()));
- }
- } else {
- throw new InternalException(String.format(
- "Project %1$s is missing. Needed by %2$s.\n" +
- "Make sure all dependencies are opened.",
- libraryState.getRelativePath(),
- javaProject.getProject().getName()));
- }
- }
-
- // add java project dependencies
- List<IJavaProject> javaDepProjects = getReferencedProjects(javaProject);
- for (IJavaProject javaDep : javaDepProjects) {
- GradleModule libModule = processJavaProject(javaDep);
- module.addDependency(libModule);
- }
-
- return module;
- }
-
- @NonNull
- private GradleModule processJavaProject(@NonNull IJavaProject javaProject)
- throws InternalException, CoreException {
- // get/create the module
- GradleModule module = createModuleOnDemand(javaProject);
-
- if (module.isConfigured()) {
- return module;
- }
-
- module.setType(GradleModule.Type.JAVA);
-
- // add java project dependencies
- List<IJavaProject> javaDepProjects = getReferencedProjects(javaProject);
- for (IJavaProject javaDep : javaDepProjects) {
- // Java project should not reference Android project!
- if (javaDep.getProject().hasNature(AdtConstants.NATURE_DEFAULT)) {
- throw new InternalException(String.format(
- "Java project %1$s depends on Android project %2$s!\n" +
- "This is not a valid dependency",
- javaProject.getProject().getName(), javaDep.getProject().getName()));
- }
- GradleModule libModule = processJavaProject(javaDep);
- module.addDependency(libModule);
- }
-
- return module;
- }
-
- private void computeRootAndPaths(Collection<GradleModule> modules) throws InternalException {
- // compute the common root.
- mCommonRoot = determineCommonRoot(modules);
-
- // compute all the relative paths.
- for (GradleModule module : modules) {
- String path = getGradlePath(module.getJavaProject().getProject().getLocation(),
- mCommonRoot);
-
- module.setPath(path);
- }
- }
-
- /**
- * Finds the common parent directory shared by this project and all its dependencies.
- * If there's only one project, returns the single project's folder.
- * @throws InternalException
- */
- @NonNull
- private static IPath determineCommonRoot(Collection<GradleModule> modules)
- throws InternalException {
- IPath commonRoot = null;
- for (GradleModule module : modules) {
- if (commonRoot == null) {
- commonRoot = module.getJavaProject().getProject().getLocation();
- } else {
- commonRoot = findCommonRoot(commonRoot,
- module.getJavaProject().getProject().getLocation());
- }
- }
-
- return commonRoot;
- }
-
- /**
- * Converts the given path to be relative to the given root path, and converts it to
- * Gradle project notation, such as is used in the settings.gradle file.
- */
- @NonNull
- private static String getGradlePath(IPath path, IPath root) {
- IPath relativePath = path.makeRelativeTo(root);
- String relativeString = relativePath.toOSString();
- return ":" + relativeString.replaceAll(Pattern.quote(File.separator), ":"); //$NON-NLS-1$
- }
-
- /**
- * Given two IPaths, finds the parent directory of both of them.
- * @throws InternalException
- */
- @NonNull
- private static IPath findCommonRoot(@NonNull IPath path1, @NonNull IPath path2)
- throws InternalException {
- if (path1.getDevice() != null && !path1.getDevice().equals(path2.getDevice())) {
- throw new InternalException(
- "Different modules have been detected on different drives.\n" +
- "This prevents finding a common root to all modules.");
- }
-
- IPath result = path1.uptoSegment(0);
-
- final int count = Math.min(path1.segmentCount(), path2.segmentCount());
- for (int i = 0; i < count; i++) {
- if (path1.segment(i).equals(path2.segment(i))) {
- result = result.append(Path.SEPARATOR + path2.segment(i));
- }
- }
- return result;
- }
-
- @Nullable
- private IJavaProject getJavaProject(ProjectState projectState) {
- try {
- return BaseProjectHelper.getJavaProject(projectState.getProject());
- } catch (CoreException e) {
- return null;
- }
- }
-
- @NonNull
- private GradleModule createModuleOnDemand(@NonNull IJavaProject javaProject) {
- GradleModule module = mModules.get(javaProject);
- if (module == null) {
- module = new GradleModule(javaProject);
- mModules.put(javaProject, module);
- }
-
- return module;
- }
-
- @NonNull
- private static List<IJavaProject> getReferencedProjects(IJavaProject javaProject)
- throws JavaModelException, InternalException {
-
- List<IJavaProject> projects = Lists.newArrayList();
-
- IClasspathEntry entries[] = javaProject.getRawClasspath();
- for (IClasspathEntry classpathEntry : entries) {
- if (classpathEntry.getContentKind() == IPackageFragmentRoot.K_SOURCE
- && classpathEntry.getEntryKind() == IClasspathEntry.CPE_PROJECT) {
- // found required project on build path
- String subProjectRoot = classpathEntry.getPath().toString();
- IJavaProject subProject = getJavaProject(subProjectRoot);
- // is project available in workspace?
- if (subProject != null) {
- projects.add(subProject);
- } else {
- throw new InternalException(String.format(
- "Project '%s' is missing project dependency '%s' in Eclipse workspace.\n" +
- "Make sure all dependencies are opened.",
- javaProject.getProject().getName(),
- classpathEntry.getPath().toString()));
- }
- }
- }
-
- return projects;
- }
-
- /**
- * Get Java project for given root.
- */
- @Nullable
- private static IJavaProject getJavaProject(String root) {
- IPath path = new Path(root);
- if (path.segmentCount() == 1) {
- return getJavaProjectByName(root);
- }
- IResource resource = ResourcesPlugin.getWorkspace().getRoot()
- .findMember(path);
- if (resource != null && resource.getType() == IResource.PROJECT) {
- if (resource.exists()) {
- return (IJavaProject) JavaCore.create(resource);
- }
- }
- return null;
- }
-
- /**
- * Get Java project from resource.
- */
- private static IJavaProject getJavaProjectByName(String name) {
- try {
- IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(name);
- if (project.exists()) {
- return JavaCore.create(project);
- }
- } catch (IllegalArgumentException iae) {
- }
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/ApplicationInfoPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/ApplicationInfoPage.java
deleted file mode 100644
index c8325345a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/ApplicationInfoPage.java
+++ /dev/null
@@ -1,809 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.newproject;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk.ITargetChangeListener;
-import com.android.ide.eclipse.adt.internal.wizards.newproject.NewProjectWizardState.Mode;
-import com.android.sdklib.IAndroidTarget;
-
-import org.eclipse.core.filesystem.URIUtil;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jdt.core.JavaConventions;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-
-import java.io.File;
-import java.io.FileFilter;
-import java.net.URI;
-
-/** Page where you choose the application name, activity name, and optional test project info */
-public class ApplicationInfoPage extends WizardPage implements SelectionListener, ModifyListener,
- ITargetChangeListener {
- private static final String JDK_15 = "1.5"; //$NON-NLS-1$
- private final static String DUMMY_PACKAGE = "your.package.namespace";
-
- /** Suffix added by default to activity names */
- static final String ACTIVITY_NAME_SUFFIX = "Activity"; //$NON-NLS-1$
-
- private final NewProjectWizardState mValues;
-
- private Text mApplicationText;
- private Text mPackageText;
- private Text mActivityText;
- private Button mCreateActivityCheckbox;
- private Combo mSdkCombo;
-
- private boolean mIgnore;
- private Button mCreateTestCheckbox;
- private Text mTestProjectNameText;
- private Text mTestApplicationText;
- private Text mTestPackageText;
- private Label mTestProjectNameLabel;
- private Label mTestApplicationLabel;
- private Label mTestPackageLabel;
-
- /**
- * Create the wizard.
- */
- ApplicationInfoPage(NewProjectWizardState values) {
- super("appInfo"); //$NON-NLS-1$
- mValues = values;
-
- setTitle("Application Info");
- setDescription("Configure the new Android Project");
- AdtPlugin.getDefault().addTargetListener(this);
- }
-
- /**
- * Create contents of the wizard.
- */
- @Override
- @SuppressWarnings("unused") // Eclipse marks SWT constructors with side effects as unused
- public void createControl(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
- container.setLayout(new GridLayout(2, false));
-
- Label applicationLabel = new Label(container, SWT.NONE);
- applicationLabel.setText("Application Name:");
-
- mApplicationText = new Text(container, SWT.BORDER);
- mApplicationText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- mApplicationText.addModifyListener(this);
-
- Label packageLabel = new Label(container, SWT.NONE);
- packageLabel.setText("Package Name:");
-
- mPackageText = new Text(container, SWT.BORDER);
- mPackageText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- mPackageText.addModifyListener(this);
-
- if (mValues.mode != Mode.TEST) {
- mCreateActivityCheckbox = new Button(container, SWT.CHECK);
- mCreateActivityCheckbox.setText("Create Activity:");
- mCreateActivityCheckbox.addSelectionListener(this);
-
- mActivityText = new Text(container, SWT.BORDER);
- mActivityText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- mActivityText.addModifyListener(this);
- }
-
- Label minSdkLabel = new Label(container, SWT.NONE);
- minSdkLabel.setText("Minimum SDK:");
-
- mSdkCombo = new Combo(container, SWT.NONE);
- GridData gdSdkCombo = new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1);
- gdSdkCombo.widthHint = 200;
- mSdkCombo.setLayoutData(gdSdkCombo);
- mSdkCombo.addSelectionListener(this);
- mSdkCombo.addModifyListener(this);
-
- onSdkLoaded();
-
- setControl(container);
- new Label(container, SWT.NONE);
- new Label(container, SWT.NONE);
-
- mCreateTestCheckbox = new Button(container, SWT.CHECK);
- mCreateTestCheckbox.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
- mCreateTestCheckbox.setText("Create a Test Project");
- mCreateTestCheckbox.addSelectionListener(this);
-
- mTestProjectNameLabel = new Label(container, SWT.NONE);
- mTestProjectNameLabel.setText("Test Project Name:");
-
- mTestProjectNameText = new Text(container, SWT.BORDER);
- mTestProjectNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- mTestProjectNameText.addModifyListener(this);
-
- mTestApplicationLabel = new Label(container, SWT.NONE);
- mTestApplicationLabel.setText("Test Application:");
-
- mTestApplicationText = new Text(container, SWT.BORDER);
- mTestApplicationText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- mTestApplicationText.addModifyListener(this);
-
- mTestPackageLabel = new Label(container, SWT.NONE);
- mTestPackageLabel.setText("Test Package:");
-
- mTestPackageText = new Text(container, SWT.BORDER);
- mTestPackageText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- mTestPackageText.addModifyListener(this);
- }
-
- /** Controls whether the options for creating a paired test project should be shown */
- private void showTestOptions(boolean visible) {
- if (mValues.mode == Mode.SAMPLE) {
- visible = false;
- }
-
- mCreateTestCheckbox.setVisible(visible);
- mTestProjectNameLabel.setVisible(visible);
- mTestProjectNameText.setVisible(visible);
- mTestApplicationLabel.setVisible(visible);
- mTestApplicationText.setVisible(visible);
- mTestPackageLabel.setVisible(visible);
- mTestPackageText.setVisible(visible);
- }
-
- /** Controls whether the options for creating a paired test project should be enabled */
- private void enableTestOptions(boolean enabled) {
- mTestProjectNameLabel.setEnabled(enabled);
- mTestProjectNameText.setEnabled(enabled);
- mTestApplicationLabel.setEnabled(enabled);
- mTestApplicationText.setEnabled(enabled);
- mTestPackageLabel.setEnabled(enabled);
- mTestPackageText.setEnabled(enabled);
- }
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
-
- if (visible) {
- try {
- mIgnore = true;
- if (mValues.applicationName != null) {
- mApplicationText.setText(mValues.applicationName);
- }
- if (mValues.packageName != null) {
- mPackageText.setText(mValues.packageName);
- } else {
- mPackageText.setText(DUMMY_PACKAGE);
- }
-
- if (mValues.mode != Mode.TEST) {
- mCreateActivityCheckbox.setSelection(mValues.createActivity);
- mActivityText.setEnabled(mValues.createActivity);
- if (mValues.activityName != null) {
- mActivityText.setText(mValues.activityName);
- }
- }
- if (mValues.minSdk != null && mValues.minSdk.length() > 0) {
- mSdkCombo.setText(mValues.minSdk);
- }
-
- showTestOptions(mValues.mode == Mode.ANY);
- enableTestOptions(mCreateTestCheckbox.getSelection());
-
- if (mValues.testProjectName != null) {
- mTestProjectNameText.setText(mValues.testProjectName);
- }
- if (mValues.testApplicationName != null) {
- mTestApplicationText.setText(mValues.testApplicationName);
- }
- if (mValues.testProjectName != null) {
- mTestPackageText.setText(mValues.testProjectName);
- }
- } finally {
- mIgnore = false;
- }
- }
-
- // Start focus with the package name, since the other fields are typically assigned
- // reasonable defaults
- mPackageText.setFocus();
- mPackageText.selectAll();
-
- validatePage();
- }
-
- protected void setSdkTargets(IAndroidTarget[] targets, IAndroidTarget target) {
- if (targets == null) {
- targets = new IAndroidTarget[0];
- }
- int selectionIndex = -1;
- String[] items = new String[targets.length];
- for (int i = 0, n = targets.length; i < n; i++) {
- items[i] = targetLabel(targets[i]);
- if (targets[i] == target) {
- selectionIndex = i;
- }
- }
- try {
- mIgnore = true;
- mSdkCombo.setItems(items);
- mSdkCombo.setData(targets);
- if (selectionIndex != -1) {
- mSdkCombo.select(selectionIndex);
- }
- } finally {
- mIgnore = false;
- }
- }
-
- private String targetLabel(IAndroidTarget target) {
- // In the minimum SDK chooser, show the targets with api number and description,
- // such as "11 (Android 3.0)"
- return String.format("%1$s (%2$s)", target.getVersion().getApiString(),
- target.getFullName());
- }
-
- @Override
- public void dispose() {
- AdtPlugin.getDefault().removeTargetListener(this);
- super.dispose();
- }
-
- @Override
- public boolean isPageComplete() {
- // This page is only needed when creating new projects
- if (mValues.useExisting || mValues.mode != Mode.ANY) {
- return true;
- }
-
- // Ensure that we reach this page
- if (mValues.packageName == null) {
- return false;
- }
-
- return super.isPageComplete();
- }
-
- @Override
- public void modifyText(ModifyEvent e) {
- if (mIgnore) {
- return;
- }
-
- Object source = e.getSource();
- if (source == mSdkCombo) {
- mValues.minSdk = mSdkCombo.getText().trim();
- IAndroidTarget[] targets = (IAndroidTarget[]) mSdkCombo.getData();
- // An editable combo will treat item selection the same way as a user edit,
- // so we need to see if the string looks like a labeled version
- int index = mSdkCombo.getSelectionIndex();
- if (index != -1) {
- if (index >= 0 && index < targets.length) {
- IAndroidTarget target = targets[index];
- if (targetLabel(target).equals(mValues.minSdk)) {
- mValues.minSdk = target.getVersion().getApiString();
- }
- }
- }
-
- // Ensure that we never pick up the (Android x.y) suffix shown in combobox
- // for readability
- int separator = mValues.minSdk.indexOf(' ');
- if (separator != -1) {
- mValues.minSdk = mValues.minSdk.substring(0, separator);
- }
- mValues.minSdkModifiedByUser = true;
- mValues.updateSdkTargetToMatchMinSdkVersion();
- } else if (source == mApplicationText) {
- mValues.applicationName = mApplicationText.getText().trim();
- mValues.applicationNameModifiedByUser = true;
-
- if (!mValues.testApplicationNameModified) {
- mValues.testApplicationName = suggestTestApplicationName(mValues.applicationName);
- try {
- mIgnore = true;
- mTestApplicationText.setText(mValues.testApplicationName);
- } finally {
- mIgnore = false;
- }
- }
-
- } else if (source == mPackageText) {
- mValues.packageName = mPackageText.getText().trim();
- mValues.packageNameModifiedByUser = true;
-
- if (!mValues.testPackageModified) {
- mValues.testPackageName = suggestTestPackage(mValues.packageName);
- try {
- mIgnore = true;
- mTestPackageText.setText(mValues.testPackageName);
- } finally {
- mIgnore = false;
- }
- }
- } else if (source == mActivityText) {
- mValues.activityName = mActivityText.getText().trim();
- mValues.activityNameModifiedByUser = true;
- } else if (source == mTestApplicationText) {
- mValues.testApplicationName = mTestApplicationText.getText().trim();
- mValues.testApplicationNameModified = true;
- } else if (source == mTestPackageText) {
- mValues.testPackageName = mTestPackageText.getText().trim();
- mValues.testPackageModified = true;
- } else if (source == mTestProjectNameText) {
- mValues.testProjectName = mTestProjectNameText.getText().trim();
- mValues.testProjectModified = true;
- }
-
- validatePage();
- }
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (mIgnore) {
- return;
- }
-
- Object source = e.getSource();
-
- if (source == mCreateActivityCheckbox) {
- mValues.createActivity = mCreateActivityCheckbox.getSelection();
- mActivityText.setEnabled(mValues.createActivity);
- } else if (source == mSdkCombo) {
- int index = mSdkCombo.getSelectionIndex();
- IAndroidTarget[] targets = (IAndroidTarget[]) mSdkCombo.getData();
- if (index != -1) {
- if (index >= 0 && index < targets.length) {
- IAndroidTarget target = targets[index];
- // Even though we are showing the logical version name, we place the
- // actual api number as the minimum SDK
- mValues.minSdk = target.getVersion().getApiString();
- }
- } else {
- String text = mSdkCombo.getText();
- boolean found = false;
- for (IAndroidTarget target : targets) {
- if (targetLabel(target).equals(text)) {
- mValues.minSdk = target.getVersion().getApiString();
- found = true;
- break;
- }
- }
- if (!found) {
- mValues.minSdk = text;
- }
- }
- } else if (source == mCreateTestCheckbox) {
- mValues.createPairProject = mCreateTestCheckbox.getSelection();
- enableTestOptions(mValues.createPairProject);
- if (mValues.createPairProject) {
- if (mValues.testProjectName == null || mValues.testProjectName.length() == 0) {
- mValues.testProjectName = suggestTestProjectName(mValues.projectName);
- }
- if (mValues.testApplicationName == null ||
- mValues.testApplicationName.length() == 0) {
- mValues.testApplicationName =
- suggestTestApplicationName(mValues.applicationName);
- }
- if (mValues.testPackageName == null || mValues.testPackageName.length() == 0) {
- mValues.testPackageName = suggestTestPackage(mValues.packageName);
- }
-
- try {
- mIgnore = true;
- mTestProjectNameText.setText(mValues.testProjectName);
- mTestApplicationText.setText(mValues.testApplicationName);
- mTestPackageText.setText(mValues.testPackageName);
- } finally {
- mIgnore = false;
- }
- }
- }
-
- validatePage();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
-
- private void validatePage() {
- IStatus status = validatePackage(mValues.packageName);
- if (status == null || status.getSeverity() != IStatus.ERROR) {
- IStatus validActivity = validateActivity();
- if (validActivity != null) {
- status = validActivity;
- }
- }
- if (status == null || status.getSeverity() != IStatus.ERROR) {
- IStatus validMinSdk = validateMinSdk();
- if (validMinSdk != null) {
- status = validMinSdk;
- }
- }
-
- if (status == null || status.getSeverity() != IStatus.ERROR) {
- IStatus validSourceFolder = validateSourceFolder();
- if (validSourceFolder != null) {
- status = validSourceFolder;
- }
- }
-
- // If creating a test project to go along with the main project, also validate
- // the additional test project parameters
- if (status == null || status.getSeverity() != IStatus.ERROR) {
- if (mValues.createPairProject) {
- IStatus validTestProject = ProjectNamePage.validateProjectName(
- mValues.testProjectName);
- if (validTestProject != null) {
- status = validTestProject;
- }
-
- if (status == null || status.getSeverity() != IStatus.ERROR) {
- IStatus validTestLocation = validateTestProjectLocation();
- if (validTestLocation != null) {
- status = validTestLocation;
- }
- }
-
- if (status == null || status.getSeverity() != IStatus.ERROR) {
- IStatus validTestPackage = validatePackage(mValues.testPackageName);
- if (validTestPackage != null) {
- status = new Status(validTestPackage.getSeverity(),
- AdtPlugin.PLUGIN_ID,
- validTestPackage.getMessage() + " (in test package)");
- }
- }
-
- if (status == null || status.getSeverity() != IStatus.ERROR) {
- if (mValues.projectName.equals(mValues.testProjectName)) {
- status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "The main project name and the test project name must be different.");
- }
- }
- }
- }
-
- // -- update UI & enable finish if there's no error
- setPageComplete(status == null || status.getSeverity() != IStatus.ERROR);
- if (status != null) {
- setMessage(status.getMessage(),
- status.getSeverity() == IStatus.ERROR
- ? IMessageProvider.ERROR : IMessageProvider.WARNING);
- } else {
- setErrorMessage(null);
- setMessage(null);
- }
- }
-
- private IStatus validateTestProjectLocation() {
- assert mValues.createPairProject;
-
- // Validate location
- Path path = new Path(mValues.projectLocation.getPath());
- if (!mValues.useExisting) {
- if (!mValues.useDefaultLocation) {
- // If not using the default value validate the location.
- URI uri = URIUtil.toURI(path.toOSString());
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IProject handle = workspace.getRoot().getProject(mValues.testProjectName);
- IStatus locationStatus = workspace.validateProjectLocationURI(handle, uri);
- if (!locationStatus.isOK()) {
- return locationStatus;
- }
- // The location is valid as far as Eclipse is concerned (i.e. mostly not
- // an existing workspace project.) Check it either doesn't exist or is
- // a directory that is empty.
- File f = path.toFile();
- if (f.exists() && !f.isDirectory()) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "A directory name must be specified.");
- } else if (f.isDirectory()) {
- // However if the directory exists, we should put a
- // warning if it is not empty. We don't put an error
- // (we'll ask the user again for confirmation before
- // using the directory.)
- String[] l = f.list();
- if (l != null && l.length != 0) {
- return new Status(IStatus.WARNING, AdtPlugin.PLUGIN_ID,
- "The selected output directory is not empty.");
- }
- }
- } else {
- IPath destPath = path.removeLastSegments(1).append(mValues.testProjectName);
- File dest = destPath.toFile();
- if (dest.exists()) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- String.format(
- "There is already a file or directory named \"%1$s\" in the selected location.",
- mValues.testProjectName));
- }
- }
- }
-
- return null;
- }
-
- private IStatus validateSourceFolder() {
- // This check does nothing when creating a new project.
- // This check is also useless when no activity is present or created.
- mValues.sourceFolder = SdkConstants.FD_SOURCES;
- if (!mValues.useExisting || !mValues.createActivity) {
- return null;
- }
-
- String osTarget = mValues.activityName;
- if (osTarget.indexOf('.') == -1) {
- osTarget = mValues.packageName + File.separator + osTarget;
- } else if (osTarget.indexOf('.') == 0) {
- osTarget = mValues.packageName + osTarget;
- }
- osTarget = osTarget.replace('.', File.separatorChar) + SdkConstants.DOT_JAVA;
-
- File projectDir = mValues.projectLocation;
- File[] allDirs = projectDir.listFiles(new FileFilter() {
- @Override
- public boolean accept(File pathname) {
- return pathname.isDirectory();
- }
- });
- if (allDirs != null) {
- boolean found = false;
- for (File f : allDirs) {
- Path path = new Path(f.getAbsolutePath());
- File java_activity = path.append(osTarget).toFile();
- if (java_activity.isFile()) {
- mValues.sourceFolder = f.getName();
- found = true;
- break;
- }
- }
-
- if (!found) {
- String projectPath = projectDir.getPath();
- if (allDirs.length > 0) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- String.format("%1$s can not be found under %2$s.", osTarget,
- projectPath));
- } else {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- String.format("No source folders can be found in %1$s.",
- projectPath));
- }
- }
- }
-
- return null;
- }
-
- private IStatus validateMinSdk() {
- // Validate min SDK field
- // If the min sdk version is empty, it is always accepted.
- if (mValues.minSdk == null || mValues.minSdk.length() == 0) {
- return null;
- }
-
- IAndroidTarget target = mValues.target;
- if (target == null) {
- return null;
- }
-
- // If the current target is a preview, explicitly indicate minSdkVersion
- // must be set to this target name.
- if (target.getVersion().isPreview() && !target.getVersion().equals(mValues.minSdk)) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- String.format(
- "The SDK target is a preview. Min SDK Version must be set to '%s'.",
- target.getVersion().getCodename()));
- }
-
- if (!target.getVersion().equals(mValues.minSdk)) {
- return new Status(target.getVersion().isPreview() ? IStatus.ERROR : IStatus.WARNING,
- AdtPlugin.PLUGIN_ID,
- "The API level for the selected SDK target does not match the Min SDK Version."
- );
- }
-
- return null;
- }
-
- public static IStatus validatePackage(String packageFieldContents) {
- // Validate package
- if (packageFieldContents == null || packageFieldContents.length() == 0) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "Package name must be specified.");
- } else if (packageFieldContents.equals(DUMMY_PACKAGE)) {
- // The dummy package name is just a placeholder package (which isn't even valid
- // because it contains the reserved Java keyword "package") but we want to
- // make the error message say that a proper package should be entered rather than
- // what's wrong with this specific package. (And the reason we provide a dummy
- // package rather than a blank line is to make it more clear to beginners what
- // we're looking for.
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "Package name must be specified.");
- }
- // Check it's a valid package string
- IStatus status = JavaConventions.validatePackageName(packageFieldContents, JDK_15,
- JDK_15);
- if (!status.isOK()) {
- return status;
- }
-
- // The Android Activity Manager does not accept packages names with only one
- // identifier. Check the package name has at least one dot in them (the previous rule
- // validated that if such a dot exist, it's not the first nor last characters of the
- // string.)
- if (packageFieldContents.indexOf('.') == -1) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "Package name must have at least two identifiers.");
- }
-
- return null;
- }
-
- public static IStatus validateClass(String className) {
- if (className == null || className.length() == 0) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "Class name must be specified.");
- }
- if (className.indexOf('.') != -1) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "Enter just a class name, not a full package name");
- }
- return JavaConventions.validateJavaTypeName(className, JDK_15, JDK_15);
- }
-
- private IStatus validateActivity() {
- // Validate activity (if creating an activity)
- if (!mValues.createActivity) {
- return null;
- }
-
- return validateActivity(mValues.activityName);
- }
-
- /**
- * Validates the given activity name
- *
- * @param activityFieldContents the activity name to validate
- * @return a status for whether the activity name is valid
- */
- public static IStatus validateActivity(String activityFieldContents) {
- // Validate activity field
- if (activityFieldContents == null || activityFieldContents.length() == 0) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "Activity name must be specified.");
- } else if (ACTIVITY_NAME_SUFFIX.equals(activityFieldContents)) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, "Enter a valid activity name");
- } else if (activityFieldContents.contains("..")) { //$NON-NLS-1$
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "Package segments in activity name cannot be empty (..)");
- }
- // The activity field can actually contain part of a sub-package name
- // or it can start with a dot "." to indicates it comes from the parent package
- // name.
- String packageName = ""; //$NON-NLS-1$
- int pos = activityFieldContents.lastIndexOf('.');
- if (pos >= 0) {
- packageName = activityFieldContents.substring(0, pos);
- if (packageName.startsWith(".")) { //$NON-NLS-1$
- packageName = packageName.substring(1);
- }
-
- activityFieldContents = activityFieldContents.substring(pos + 1);
- }
-
- // the activity field can contain a simple java identifier, or a
- // package name or one that starts with a dot. So if it starts with a dot,
- // ignore this dot -- the rest must look like a package name.
- if (activityFieldContents.length() > 0 && activityFieldContents.charAt(0) == '.') {
- activityFieldContents = activityFieldContents.substring(1);
- }
-
- // Check it's a valid activity string
- IStatus status = JavaConventions.validateTypeVariableName(activityFieldContents, JDK_15,
- JDK_15);
- if (!status.isOK()) {
- return status;
- }
-
- // Check it's a valid package string
- if (packageName.length() > 0) {
- status = JavaConventions.validatePackageName(packageName, JDK_15, JDK_15);
- if (!status.isOK()) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- status.getMessage() + " (in the activity name)");
- }
- }
-
- return null;
- }
-
- // ---- Implement ITargetChangeListener ----
-
- @Override
- public void onSdkLoaded() {
- if (mSdkCombo == null) {
- return;
- }
-
- // Update the sdk target selector with the new targets
-
- // get the targets from the sdk
- IAndroidTarget[] targets = null;
- if (Sdk.getCurrent() != null) {
- targets = Sdk.getCurrent().getTargets();
- }
- setSdkTargets(targets, mValues.target);
- }
-
- @Override
- public void onProjectTargetChange(IProject changedProject) {
- // Ignore
- }
-
- @Override
- public void onTargetLoaded(IAndroidTarget target) {
- // Ignore
- }
-
- public static String suggestTestApplicationName(String applicationName) {
- if (applicationName == null) {
- applicationName = ""; //$NON-NLS-1$
- }
- if (applicationName.indexOf(' ') != -1) {
- return applicationName + " Test"; //$NON-NLS-1$
- } else {
- return applicationName + "Test"; //$NON-NLS-1$
- }
- }
-
- public static String suggestTestProjectName(String projectName) {
- if (projectName == null) {
- projectName = ""; //$NON-NLS-1$
- }
- if (projectName.length() > 0 && Character.isUpperCase(projectName.charAt(0))) {
- return projectName + "Test"; //$NON-NLS-1$
- } else {
- return projectName + "-test"; //$NON-NLS-1$
- }
- }
-
-
- public static String suggestTestPackage(String packagePath) {
- if (packagePath == null) {
- packagePath = ""; //$NON-NLS-1$
- }
- return packagePath + ".test"; //$NON-NLS-1$
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/FileStoreAdapter.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/FileStoreAdapter.java
deleted file mode 100755
index 0f4e87e9f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/FileStoreAdapter.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.newproject;
-
-import org.eclipse.core.filesystem.IFileInfo;
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.filesystem.IFileSystem;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-
-import java.io.File;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.URI;
-
-/**
- * IFileStore implementation that delegates to the give {@link IFileStore}.
- * This makes it easier to just override a single method from a store.
- */
-class FileStoreAdapter implements IFileStore {
-
- private final IFileStore mStore;
-
- public FileStoreAdapter(IFileStore store) {
- mStore = store;
- }
-
- @SuppressWarnings("rawtypes")
- @Override
- public Object getAdapter(Class adapter) {
- return mStore.getAdapter(adapter);
- }
-
- @Override
- public IFileInfo[] childInfos(int options, IProgressMonitor monitor) throws CoreException {
- return mStore.childInfos(options, monitor);
- }
-
- @Override
- public String[] childNames(int options, IProgressMonitor monitor)
- throws CoreException {
- return mStore.childNames(options, monitor);
- }
-
- @Override
- public IFileStore[] childStores(int options, IProgressMonitor monitor) throws CoreException {
- return mStore.childStores(options, monitor);
- }
-
- @Override
- public void copy(IFileStore destination, int options, IProgressMonitor monitor)
- throws CoreException {
- mStore.copy(destination, options, monitor);
- }
-
- @Override
- public void delete(int options, IProgressMonitor monitor) throws CoreException {
- mStore.delete(options, monitor);
- }
-
- @Override
- public IFileInfo fetchInfo() {
- return mStore.fetchInfo();
- }
-
- @Override
- public IFileInfo fetchInfo(int options, IProgressMonitor monitor) throws CoreException {
- return mStore.fetchInfo(options, monitor);
- }
-
- @Deprecated
- @Override
- public IFileStore getChild(IPath path) {
- return mStore.getChild(path);
- }
-
- @Override
- public IFileStore getFileStore(IPath path) {
- return mStore.getFileStore(path);
- }
-
- @Override
- public IFileStore getChild(String name) {
- return mStore.getChild(name);
- }
-
- @Override
- public IFileSystem getFileSystem() {
- return mStore.getFileSystem();
- }
-
- @Override
- public String getName() {
- return mStore.getName();
- }
-
- @Override
- public IFileStore getParent() {
- return mStore.getParent();
- }
-
- @Override
- public boolean isParentOf(IFileStore other) {
- return mStore.isParentOf(other);
- }
-
- @Override
- public IFileStore mkdir(int options, IProgressMonitor monitor) throws CoreException {
- return mStore.mkdir(options, monitor);
- }
-
- @Override
- public void move(IFileStore destination, int options, IProgressMonitor monitor)
- throws CoreException {
- mStore.move(destination, options, monitor);
- }
-
- @Override
- public InputStream openInputStream(int options, IProgressMonitor monitor)
- throws CoreException {
- return mStore.openInputStream(options, monitor);
- }
-
- @Override
- public OutputStream openOutputStream(int options, IProgressMonitor monitor)
- throws CoreException {
- return mStore.openOutputStream(options, monitor);
- }
-
- @Override
- public void putInfo(IFileInfo info, int options, IProgressMonitor monitor)
- throws CoreException {
- mStore.putInfo(info, options, monitor);
- }
-
- @Override
- public File toLocalFile(int options, IProgressMonitor monitor) throws CoreException {
- return mStore.toLocalFile(options, monitor);
- }
-
- @Override
- public URI toURI() {
- return mStore.toURI();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/ImportPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/ImportPage.java
deleted file mode 100644
index 1e02fedae..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/ImportPage.java
+++ /dev/null
@@ -1,512 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.newproject;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.tools.lint.detector.api.LintUtils;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.viewers.CellEditor;
-import org.eclipse.jface.viewers.CellLabelProvider;
-import org.eclipse.jface.viewers.CheckStateChangedEvent;
-import org.eclipse.jface.viewers.CheckboxTableViewer;
-import org.eclipse.jface.viewers.ColumnViewer;
-import org.eclipse.jface.viewers.EditingSupport;
-import org.eclipse.jface.viewers.ICheckStateListener;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.TextCellEditor;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerCell;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ControlEvent;
-import org.eclipse.swt.events.ControlListener;
-import org.eclipse.swt.events.KeyEvent;
-import org.eclipse.swt.events.KeyListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.events.TraverseEvent;
-import org.eclipse.swt.events.TraverseListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.DirectoryDialog;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkingSet;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-/** WizardPage for importing Android projects */
-class ImportPage extends WizardPage implements SelectionListener, IStructuredContentProvider,
- ICheckStateListener, KeyListener, TraverseListener, ControlListener {
- private static final int DIR_COLUMN = 0;
- private static final int NAME_COLUMN = 1;
-
- private final NewProjectWizardState mValues;
- private List<ImportedProject> mProjectPaths;
- private final IProject[] mExistingProjects;
-
- private Text mDir;
- private Button mBrowseButton;
- private Button mCopyCheckBox;
- private Button mRefreshButton;
- private Button mDeselectAllButton;
- private Button mSelectAllButton;
- private Table mTable;
- private CheckboxTableViewer mCheckboxTableViewer;
- private WorkingSetGroup mWorkingSetGroup;
-
- ImportPage(NewProjectWizardState values) {
- super("importPage"); //$NON-NLS-1$
- mValues = values;
- setTitle("Import Projects");
- setDescription("Select a directory to search for existing Android projects");
- mWorkingSetGroup = new WorkingSetGroup();
- setWorkingSets(new IWorkingSet[0]);
-
- // Record all projects such that we can ensure that the project names are unique
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
- mExistingProjects = workspaceRoot.getProjects();
- }
-
- public void init(IStructuredSelection selection, IWorkbenchPart activePart) {
- setWorkingSets(WorkingSetHelper.getSelectedWorkingSet(selection, activePart));
- }
-
- @SuppressWarnings("unused") // SWT constructors have side effects and aren't unused
- @Override
- public void createControl(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
- setControl(container);
- container.setLayout(new GridLayout(3, false));
-
- Label directoryLabel = new Label(container, SWT.NONE);
- directoryLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- directoryLabel.setText("Root Directory:");
-
- mDir = new Text(container, SWT.BORDER);
- mDir.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- mDir.addKeyListener(this);
- mDir.addTraverseListener(this);
-
- mBrowseButton = new Button(container, SWT.NONE);
- mBrowseButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
- mBrowseButton.setText("Browse...");
- mBrowseButton.addSelectionListener(this);
-
- Label projectsLabel = new Label(container, SWT.NONE);
- projectsLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 3, 1));
- projectsLabel.setText("Projects:");
-
- mTable = new Table(container, SWT.CHECK);
- mTable.setHeaderVisible(true);
- mCheckboxTableViewer = new CheckboxTableViewer(mTable);
-
- TableViewerColumn dirViewerColumn = new TableViewerColumn(mCheckboxTableViewer, SWT.NONE);
- TableColumn dirColumn = dirViewerColumn.getColumn();
- dirColumn.setWidth(200);
- dirColumn.setText("Project to Import");
- TableViewerColumn nameViewerColumn = new TableViewerColumn(mCheckboxTableViewer, SWT.NONE);
- TableColumn nameColumn = nameViewerColumn.getColumn();
- nameColumn.setWidth(200);
- nameColumn.setText("New Project Name");
- nameViewerColumn.setEditingSupport(new ProjectNameEditingSupport(mCheckboxTableViewer));
-
- mTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 4));
- mTable.setLinesVisible(true);
- mTable.setHeaderVisible(true);
- mTable.addSelectionListener(this);
- mTable.addControlListener(this);
- mCheckboxTableViewer.setContentProvider(this);
- mCheckboxTableViewer.setInput(this);
- mCheckboxTableViewer.addCheckStateListener(this);
- mCheckboxTableViewer.setLabelProvider(new ProjectCellLabelProvider());
-
- mSelectAllButton = new Button(container, SWT.NONE);
- mSelectAllButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
- mSelectAllButton.setText("Select All");
- mSelectAllButton.addSelectionListener(this);
-
- mDeselectAllButton = new Button(container, SWT.NONE);
- mDeselectAllButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
- mDeselectAllButton.setText("Deselect All");
- mDeselectAllButton.addSelectionListener(this);
-
- mRefreshButton = new Button(container, SWT.NONE);
- mRefreshButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
- mRefreshButton.setText("Refresh");
- mRefreshButton.addSelectionListener(this);
- new Label(container, SWT.NONE);
-
- mCopyCheckBox = new Button(container, SWT.CHECK);
- mCopyCheckBox.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 3, 1));
- mCopyCheckBox.setText("Copy projects into workspace");
- mCopyCheckBox.addSelectionListener(this);
-
- Composite group = mWorkingSetGroup.createControl(container);
- group.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 3, 1));
-
- updateColumnWidths();
- }
-
- private void updateColumnWidths() {
- Rectangle r = mTable.getClientArea();
- int availableWidth = r.width;
- // Add all available size to the first column
- for (int i = 1; i < mTable.getColumnCount(); i++) {
- TableColumn column = mTable.getColumn(i);
- availableWidth -= column.getWidth();
- }
- if (availableWidth > 100) {
- mTable.getColumn(0).setWidth(availableWidth);
- }
- }
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- validatePage();
- }
-
- private void refresh() {
- File root = new File(mDir.getText().trim());
- mProjectPaths = searchForProjects(root);
- mCheckboxTableViewer.refresh();
- mCheckboxTableViewer.setAllChecked(true);
-
- updateValidity();
- validatePage();
- }
-
- private void updateValidity(){
- List<ImportedProject> selected = new ArrayList<ImportedProject>();
- List<ImportedProject> disabled = new ArrayList<ImportedProject>();
- for (ImportedProject project : mProjectPaths) {
- String projectName = project.getProjectName();
- boolean invalid = false;
- for (IProject existingProject : mExistingProjects) {
- if (projectName.equals(existingProject.getName())) {
- invalid = true;
- break;
- }
- }
- if (invalid) {
- disabled.add(project);
- } else {
- selected.add(project);
- }
- }
-
- mValues.importProjects = selected;
-
- mCheckboxTableViewer.setGrayedElements(disabled.toArray());
- mCheckboxTableViewer.setCheckedElements(selected.toArray());
- mCheckboxTableViewer.refresh();
- mCheckboxTableViewer.getTable().setFocus();
- }
-
- private List<ImportedProject> searchForProjects(File dir) {
- List<ImportedProject> projects = new ArrayList<ImportedProject>();
- addProjects(dir, projects, dir.getPath().length() + 1);
- return projects;
- }
-
- /** Finds all project directories under the given directory */
- private void addProjects(File dir, List<ImportedProject> projects, int prefixLength) {
- if (dir.isDirectory()) {
- if (LintUtils.isManifestFolder(dir)) {
- String relative = dir.getPath();
- if (relative.length() > prefixLength) {
- relative = relative.substring(prefixLength);
- }
- projects.add(new ImportedProject(dir, relative));
- }
-
- File[] children = dir.listFiles();
- if (children != null) {
- for (File child : children) {
- addProjects(child, projects, prefixLength);
- }
- }
- }
- }
-
- private void validatePage() {
- IStatus status = null;
-
- // Validate project name -- unless we're creating a sample, in which case
- // the user will get a chance to pick the name on the Sample page
- if (mProjectPaths == null || mProjectPaths.isEmpty()) {
- status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "Select a directory to search for existing Android projects");
- } else if (mValues.importProjects == null || mValues.importProjects.isEmpty()) {
- status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "Select at least one project");
- } else {
- for (ImportedProject project : mValues.importProjects) {
- if (mCheckboxTableViewer.getGrayed(project)) {
- status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- String.format("Cannot import %1$s because the project name is in use",
- project.getProjectName()));
- break;
- } else {
- status = ProjectNamePage.validateProjectName(project.getProjectName());
- if (status != null && !status.isOK()) {
- // Need to insert project name to make it clear which project name
- // is in violation
- if (mValues.importProjects.size() > 1) {
- String message = String.format("%1$s: %2$s",
- project.getProjectName(), status.getMessage());
- status = new Status(status.getSeverity(), AdtPlugin.PLUGIN_ID,
- message);
- }
- break;
- } else {
- status = null; // Don't leave non null status with isOK() == true
- }
- }
- }
- }
-
- // -- update UI & enable finish if there's no error
- setPageComplete(status == null || status.getSeverity() != IStatus.ERROR);
- if (status != null) {
- setMessage(status.getMessage(),
- status.getSeverity() == IStatus.ERROR
- ? IMessageProvider.ERROR : IMessageProvider.WARNING);
- } else {
- setErrorMessage(null);
- setMessage(null);
- }
- }
-
- /**
- * Returns the working sets to which the new project should be added.
- *
- * @return the selected working sets to which the new project should be added
- */
- private IWorkingSet[] getWorkingSets() {
- return mWorkingSetGroup.getSelectedWorkingSets();
- }
-
- /**
- * Sets the working sets to which the new project should be added.
- *
- * @param workingSets the initial selected working sets
- */
- private void setWorkingSets(IWorkingSet[] workingSets) {
- assert workingSets != null;
- mWorkingSetGroup.setWorkingSets(workingSets);
- }
-
- @Override
- public IWizardPage getNextPage() {
- // Sync working set data to the value object, since the WorkingSetGroup
- // doesn't let us add listeners to do this lazily
- mValues.workingSets = getWorkingSets();
-
- return super.getNextPage();
- }
-
- // ---- Implements SelectionListener ----
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- Object source = e.getSource();
- if (source == mBrowseButton) {
- // Choose directory
- DirectoryDialog dialog = new DirectoryDialog(getShell(), SWT.OPEN);
- String path = mDir.getText().trim();
- if (path.length() > 0) {
- dialog.setFilterPath(path);
- }
- String file = dialog.open();
- if (file != null) {
- mDir.setText(file);
- refresh();
- }
- } else if (source == mSelectAllButton) {
- mCheckboxTableViewer.setAllChecked(true);
- mValues.importProjects = mProjectPaths;
- } else if (source == mDeselectAllButton) {
- mCheckboxTableViewer.setAllChecked(false);
- mValues.importProjects = Collections.emptyList();
- } else if (source == mRefreshButton || source == mDir) {
- refresh();
- } else if (source == mCopyCheckBox) {
- mValues.copyIntoWorkspace = mCopyCheckBox.getSelection();
- }
-
- validatePage();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
-
- // ---- KeyListener ----
-
- @Override
- public void keyPressed(KeyEvent e) {
- if (e.getSource() == mDir) {
- if (e.keyCode == SWT.CR) {
- refresh();
- }
- }
- }
-
- @Override
- public void keyReleased(KeyEvent e) {
- }
-
- // ---- TraverseListener ----
-
- @Override
- public void keyTraversed(TraverseEvent e) {
- // Prevent Return from running through the wizard; return is handled by
- // key listener to refresh project list instead
- if (SWT.TRAVERSE_RETURN == e.detail) {
- e.doit = false;
- }
- }
-
- // ---- Implements IStructuredContentProvider ----
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- @Override
- public Object[] getElements(Object inputElement) {
- return mProjectPaths != null ? mProjectPaths.toArray() : new Object[0];
- }
-
- // ---- Implements ICheckStateListener ----
-
- @Override
- public void checkStateChanged(CheckStateChangedEvent event) {
- // Try to disable other elements that conflict with this
- Object[] checked = mCheckboxTableViewer.getCheckedElements();
- List<ImportedProject> selected = new ArrayList<ImportedProject>(checked.length);
- for (Object o : checked) {
- if (!mCheckboxTableViewer.getGrayed(o)) {
- selected.add((ImportedProject) o);
- }
- }
- mValues.importProjects = selected;
- validatePage();
-
- mCheckboxTableViewer.update(event.getElement(), null);
- }
-
- // ---- Implements ControlListener ----
-
- @Override
- public void controlMoved(ControlEvent e) {
- }
-
- @Override
- public void controlResized(ControlEvent e) {
- updateColumnWidths();
- }
-
- private final class ProjectCellLabelProvider extends CellLabelProvider {
- @Override
- public void update(ViewerCell cell) {
- Object element = cell.getElement();
- int index = cell.getColumnIndex();
- ImportedProject project = (ImportedProject) element;
-
- Display display = mTable.getDisplay();
- Color fg;
- if (mCheckboxTableViewer.getGrayed(element)) {
- fg = display.getSystemColor(SWT.COLOR_DARK_GRAY);
- } else {
- fg = display.getSystemColor(SWT.COLOR_LIST_FOREGROUND);
- }
- cell.setForeground(fg);
- cell.setBackground(display.getSystemColor(SWT.COLOR_LIST_BACKGROUND));
-
- switch (index) {
- case DIR_COLUMN: {
- // Directory name
- cell.setText(project.getRelativePath());
- return;
- }
-
- case NAME_COLUMN: {
- // New name
- cell.setText(project.getProjectName());
- return;
- }
- default:
- assert false : index;
- }
- cell.setText("");
- }
- }
-
- /** Editing support for the project name column */
- private class ProjectNameEditingSupport extends EditingSupport {
- private ProjectNameEditingSupport(ColumnViewer viewer) {
- super(viewer);
- }
-
- @Override
- protected void setValue(Object element, Object value) {
- ImportedProject project = (ImportedProject) element;
- project.setProjectName(value.toString());
- mCheckboxTableViewer.update(element, null);
- updateValidity();
- validatePage();
- }
-
- @Override
- protected Object getValue(Object element) {
- ImportedProject project = (ImportedProject) element;
- return project.getProjectName();
- }
-
- @Override
- protected CellEditor getCellEditor(Object element) {
- return new TextCellEditor(mTable);
- }
-
- @Override
- protected boolean canEdit(Object element) {
- return true;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/ImportProjectWizard.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/ImportProjectWizard.java
deleted file mode 100644
index 1004fd692..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/ImportProjectWizard.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.newproject;
-
-import static com.android.SdkConstants.FN_PROJECT_PROGUARD_FILE;
-import static com.android.SdkConstants.OS_SDK_TOOLS_LIB_FOLDER;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.wizards.newproject.NewProjectWizardState.Mode;
-
-import org.eclipse.jdt.ui.actions.OpenJavaPerspectiveAction;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.ui.INewWizard;
-import org.eclipse.ui.IWorkbench;
-
-import java.io.File;
-
-
-/**
- * An "Import Android Project" wizard.
- */
-public class ImportProjectWizard extends Wizard implements INewWizard {
- private static final String PROJECT_LOGO_LARGE = "icons/android-64.png"; //$NON-NLS-1$
-
- private NewProjectWizardState mValues;
- private ImportPage mImportPage;
- private IStructuredSelection mSelection;
-
- /** Constructs a new wizard default project wizard */
- public ImportProjectWizard() {
- }
-
- @Override
- public void addPages() {
- mValues = new NewProjectWizardState(Mode.ANY);
- mImportPage = new ImportPage(mValues);
- if (mSelection != null) {
- mImportPage.init(mSelection, AdtUtils.getActivePart());
- }
- addPage(mImportPage);
- }
-
- @Override
- public void init(IWorkbench workbench, IStructuredSelection selection) {
- mSelection = selection;
-
- setHelpAvailable(false); // TODO have help
- ImageDescriptor desc = AdtPlugin.getImageDescriptor(PROJECT_LOGO_LARGE);
- setDefaultPageImageDescriptor(desc);
-
- // Trigger a check to see if the SDK needs to be reloaded (which will
- // invoke onSdkLoaded asynchronously as needed).
- AdtPlugin.getDefault().refreshSdk();
- }
-
- @Override
- public boolean performFinish() {
- File file = new File(AdtPlugin.getOsSdkFolder(), OS_SDK_TOOLS_LIB_FOLDER + File.separator
- + FN_PROJECT_PROGUARD_FILE);
- if (!file.exists()) {
- AdtPlugin.displayError("Tools Out of Date?",
- String.format("It looks like you do not have the latest version of the "
- + "SDK Tools installed. Make sure you update via the SDK Manager "
- + "first. (Could not find %1$s)", file.getPath()));
- return false;
- }
-
- NewProjectCreator creator = new NewProjectCreator(mValues, getContainer());
- if (!(creator.createAndroidProjects())) {
- return false;
- }
-
- // Open the default Java Perspective
- OpenJavaPerspectiveAction action = new OpenJavaPerspectiveAction();
- action.run();
- return true;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/ImportedProject.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/ImportedProject.java
deleted file mode 100644
index 74af651ca..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/ImportedProject.java
+++ /dev/null
@@ -1,256 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.newproject;
-
-import static com.android.SdkConstants.ATTR_NAME;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.xml.AndroidManifestParser;
-import com.android.ide.common.xml.ManifestData;
-import com.android.ide.common.xml.ManifestData.Activity;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.io.FolderWrapper;
-import com.android.sdklib.AndroidVersion;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.internal.project.ProjectProperties;
-import com.android.sdklib.internal.project.ProjectProperties.PropertyType;
-import com.google.common.base.Charsets;
-import com.google.common.io.Files;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.SAXException;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/** An Android project to be imported */
-class ImportedProject {
- private final File mLocation;
- private String mActivityName;
- private ManifestData mManifest;
- private String mProjectName;
- private String mRelativePath;
-
- ImportedProject(File location, String relativePath) {
- super();
- mLocation = location;
- mRelativePath = relativePath;
- }
-
- File getLocation() {
- return mLocation;
- }
-
- String getRelativePath() {
- return mRelativePath;
- }
-
- @Nullable
- ManifestData getManifest() {
- if (mManifest == null) {
- try {
- mManifest = AndroidManifestParser.parse(new FolderWrapper(mLocation));
- } catch (SAXException e) {
- // Some sort of error in the manifest file: report to the user in a better way?
- AdtPlugin.log(e, null);
- return null;
- } catch (Exception e) {
- AdtPlugin.log(e, null);
- return null;
- }
- }
-
- return mManifest;
- }
-
- @Nullable
- public String getActivityName() {
- if (mActivityName == null) {
- // Compute the project name and the package name from the manifest
- ManifestData manifest = getManifest();
- if (manifest != null) {
- if (manifest.getLauncherActivity() != null) {
- mActivityName = manifest.getLauncherActivity().getName();
- }
- if (mActivityName == null || mActivityName.isEmpty()) {
- Activity[] activities = manifest.getActivities();
- for (Activity activity : activities) {
- mActivityName = activity.getName();
- if (mActivityName != null && !mActivityName.isEmpty()) {
- break;
- }
- }
- }
- if (mActivityName != null) {
- int index = mActivityName.lastIndexOf('.');
- mActivityName = mActivityName.substring(index + 1);
- }
- }
- }
-
- return mActivityName;
- }
-
- @NonNull
- public String getProjectName() {
- if (mProjectName == null) {
- // Are we importing an Eclipse project? If so just use the existing project name
- mProjectName = findEclipseProjectName();
- if (mProjectName != null) {
- return mProjectName;
- }
-
- String activityName = getActivityName();
- if (activityName == null || activityName.isEmpty()) {
- // I could also look at the build files, say build.xml from ant, and
- // try to glean the project name from there
- mProjectName = mLocation.getName();
- } else {
- // Try to derive it from the activity name:
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IStatus nameStatus = workspace.validateName(activityName, IResource.PROJECT);
- if (nameStatus.isOK()) {
- mProjectName = activityName;
- } else {
- // Try to derive it by escaping characters
- StringBuilder sb = new StringBuilder();
- for (int i = 0, n = activityName.length(); i < n; i++) {
- char c = activityName.charAt(i);
- if (c != IPath.DEVICE_SEPARATOR && c != IPath.SEPARATOR && c != '\\') {
- sb.append(c);
- }
- }
- if (sb.length() == 0) {
- mProjectName = mLocation.getName();
- } else {
- mProjectName = sb.toString();
- }
- }
- }
- }
-
- return mProjectName;
- }
-
- @Nullable
- private String findEclipseProjectName() {
- File projectFile = new File(mLocation, ".project"); //$NON-NLS-1$
- if (projectFile.exists()) {
- String xml;
- try {
- xml = Files.toString(projectFile, Charsets.UTF_8);
- Document doc = DomUtilities.parseDocument(xml, false);
- if (doc != null) {
- NodeList names = doc.getElementsByTagName(ATTR_NAME);
- if (names.getLength() >= 1) {
- Node nameElement = names.item(0);
- String name = nameElement.getTextContent().trim();
- if (!name.isEmpty()) {
- return name;
- }
- }
- }
- } catch (IOException e) {
- // pass: don't attempt to read project name; must be some sort of unrelated
- // file with the same name, perhaps from a different editor or IDE
- }
- }
-
- return null;
- }
-
- public void setProjectName(@NonNull String newName) {
- mProjectName = newName;
- }
-
- public IAndroidTarget getTarget() {
- // Pick a target:
- // First try to find the one requested by project.properties
- IAndroidTarget[] targets = Sdk.getCurrent().getTargets();
- ProjectProperties properties = ProjectProperties.load(mLocation.getPath(),
- PropertyType.PROJECT);
- if (properties != null) {
- String targetProperty = properties.getProperty(ProjectProperties.PROPERTY_TARGET);
- if (targetProperty != null) {
- Matcher m = Pattern.compile("android-(.+)").matcher( //$NON-NLS-1$
- targetProperty.trim());
- if (m.matches()) {
- String targetName = m.group(1);
- int targetLevel;
- try {
- targetLevel = Integer.parseInt(targetName);
- } catch (NumberFormatException nufe) {
- // pass
- targetLevel = -1;
- }
- for (IAndroidTarget t : targets) {
- AndroidVersion version = t.getVersion();
- if (version.isPreview() && targetName.equals(version.getCodename())) {
- return t;
- } else if (targetLevel == version.getApiLevel()) {
- return t;
- }
- }
- if (targetLevel > 0) {
- // If not found, pick the closest one that is higher than the
- // api level
- IAndroidTarget target = targets[targets.length - 1];
- int targetDelta = target.getVersion().getApiLevel() - targetLevel;
- for (IAndroidTarget t : targets) {
- int newDelta = t.getVersion().getApiLevel() - targetLevel;
- if (newDelta >= 0 && newDelta < targetDelta) {
- targetDelta = newDelta;
- target = t;
- }
- }
-
- return target;
- }
- }
- }
- }
-
- // If not found, pick the closest one to the one requested by the
- // project (in project.properties) that is still >= the minSdk version
- IAndroidTarget target = targets[targets.length - 1];
- ManifestData manifest = getManifest();
- if (manifest != null) {
- int minSdkLevel = manifest.getMinSdkVersion();
- int targetDelta = target.getVersion().getApiLevel() - minSdkLevel;
- for (IAndroidTarget t : targets) {
- int newDelta = t.getVersion().getApiLevel() - minSdkLevel;
- if (newDelta >= 0 && newDelta < targetDelta) {
- targetDelta = newDelta;
- target = t;
- }
- }
- }
-
- return target;
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/NewProjectCreator.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/NewProjectCreator.java
deleted file mode 100644
index d168c7503..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/NewProjectCreator.java
+++ /dev/null
@@ -1,1520 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.newproject;
-
-import static com.android.SdkConstants.FN_PROJECT_PROPERTIES;
-import static com.android.sdklib.internal.project.ProjectProperties.PROPERTY_LIBRARY;
-
-import static org.eclipse.core.resources.IResource.DEPTH_ZERO;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.annotations.VisibleForTesting;
-import com.android.ide.common.res2.ValueXmlHelper;
-import com.android.ide.common.xml.ManifestData;
-import com.android.ide.common.xml.XmlFormatStyle;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.formatting.EclipseXmlFormatPreferences;
-import com.android.ide.eclipse.adt.internal.editors.formatting.EclipseXmlPrettyPrinter;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.project.AndroidNature;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.project.ProjectHelper;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.internal.wizards.newproject.NewProjectWizardState.Mode;
-import com.android.io.StreamException;
-import com.android.resources.Density;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.internal.project.ProjectPropertiesWorkingCopy;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileInfo;
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.filesystem.IFileSystem;
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IProjectDescription;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceStatus;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.jdt.core.IAccessRule;
-import org.eclipse.jdt.core.IClasspathAttribute;
-import org.eclipse.jdt.core.IClasspathEntry;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.WorkspaceModifyOperation;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.lang.reflect.InvocationTargetException;
-import java.net.MalformedURLException;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
-/**
- * The actual project creator invoked from the New Project Wizard
- * <p/>
- * Note: this class is public so that it can be accessed from unit tests.
- * It is however an internal class. Its API may change without notice.
- * It should semantically be considered as a private final class.
- */
-public class NewProjectCreator {
-
- private static final String PARAM_SDK_TOOLS_DIR = "ANDROID_SDK_TOOLS"; //$NON-NLS-1$
- private static final String PARAM_ACTIVITY = "ACTIVITY_NAME"; //$NON-NLS-1$
- private static final String PARAM_APPLICATION = "APPLICATION_NAME"; //$NON-NLS-1$
- private static final String PARAM_PACKAGE = "PACKAGE"; //$NON-NLS-1$
- private static final String PARAM_IMPORT_RESOURCE_CLASS = "IMPORT_RESOURCE_CLASS"; //$NON-NLS-1$
- private static final String PARAM_PROJECT = "PROJECT_NAME"; //$NON-NLS-1$
- private static final String PARAM_STRING_NAME = "STRING_NAME"; //$NON-NLS-1$
- private static final String PARAM_STRING_CONTENT = "STRING_CONTENT"; //$NON-NLS-1$
- private static final String PARAM_IS_NEW_PROJECT = "IS_NEW_PROJECT"; //$NON-NLS-1$
- private static final String PARAM_SAMPLE_LOCATION = "SAMPLE_LOCATION"; //$NON-NLS-1$
- private static final String PARAM_SOURCE = "SOURCE"; //$NON-NLS-1$
- private static final String PARAM_SRC_FOLDER = "SRC_FOLDER"; //$NON-NLS-1$
- private static final String PARAM_SDK_TARGET = "SDK_TARGET"; //$NON-NLS-1$
- private static final String PARAM_IS_LIBRARY = "IS_LIBRARY"; //$NON-NLS-1$
- private static final String PARAM_MIN_SDK_VERSION = "MIN_SDK_VERSION"; //$NON-NLS-1$
- // Warning: The expanded string PARAM_TEST_TARGET_PACKAGE must not contain the
- // string "PACKAGE" since it collides with the replacement of PARAM_PACKAGE.
- private static final String PARAM_TEST_TARGET_PACKAGE = "TEST_TARGET_PCKG"; //$NON-NLS-1$
- private static final String PARAM_TARGET_SELF = "TARGET_SELF"; //$NON-NLS-1$
- private static final String PARAM_TARGET_MAIN = "TARGET_MAIN"; //$NON-NLS-1$
- private static final String PARAM_TARGET_EXISTING = "TARGET_EXISTING"; //$NON-NLS-1$
- private static final String PARAM_REFERENCE_PROJECT = "REFERENCE_PROJECT"; //$NON-NLS-1$
-
- private static final String PH_ACTIVITIES = "ACTIVITIES"; //$NON-NLS-1$
- private static final String PH_USES_SDK = "USES-SDK"; //$NON-NLS-1$
- private static final String PH_INTENT_FILTERS = "INTENT_FILTERS"; //$NON-NLS-1$
- private static final String PH_STRINGS = "STRINGS"; //$NON-NLS-1$
- private static final String PH_TEST_USES_LIBRARY = "TEST-USES-LIBRARY"; //$NON-NLS-1$
- private static final String PH_TEST_INSTRUMENTATION = "TEST-INSTRUMENTATION"; //$NON-NLS-1$
-
- private static final String BIN_DIRECTORY =
- SdkConstants.FD_OUTPUT + AdtConstants.WS_SEP;
- private static final String BIN_CLASSES_DIRECTORY =
- SdkConstants.FD_OUTPUT + AdtConstants.WS_SEP +
- SdkConstants.FD_CLASSES_OUTPUT + AdtConstants.WS_SEP;
- private static final String RES_DIRECTORY =
- SdkConstants.FD_RESOURCES + AdtConstants.WS_SEP;
- private static final String ASSETS_DIRECTORY =
- SdkConstants.FD_ASSETS + AdtConstants.WS_SEP;
- private static final String DRAWABLE_DIRECTORY =
- SdkConstants.FD_RES_DRAWABLE + AdtConstants.WS_SEP;
- private static final String DRAWABLE_XHDPI_DIRECTORY =
- SdkConstants.FD_RES_DRAWABLE + '-' + Density.XHIGH.getResourceValue() +
- AdtConstants.WS_SEP;
- private static final String DRAWABLE_HDPI_DIRECTORY =
- SdkConstants.FD_RES_DRAWABLE + '-' + Density.HIGH.getResourceValue() +
- AdtConstants.WS_SEP;
- private static final String DRAWABLE_MDPI_DIRECTORY =
- SdkConstants.FD_RES_DRAWABLE + '-' + Density.MEDIUM.getResourceValue() +
- AdtConstants.WS_SEP;
- private static final String DRAWABLE_LDPI_DIRECTORY =
- SdkConstants.FD_RES_DRAWABLE + '-' + Density.LOW.getResourceValue() +
- AdtConstants.WS_SEP;
- private static final String LAYOUT_DIRECTORY =
- SdkConstants.FD_RES_LAYOUT + AdtConstants.WS_SEP;
- private static final String VALUES_DIRECTORY =
- SdkConstants.FD_RES_VALUES + AdtConstants.WS_SEP;
- private static final String GEN_SRC_DIRECTORY =
- SdkConstants.FD_GEN_SOURCES + AdtConstants.WS_SEP;
-
- private static final String TEMPLATES_DIRECTORY = "templates/"; //$NON-NLS-1$
- private static final String TEMPLATE_MANIFEST = TEMPLATES_DIRECTORY
- + "AndroidManifest.template"; //$NON-NLS-1$
- private static final String TEMPLATE_ACTIVITIES = TEMPLATES_DIRECTORY
- + "activity.template"; //$NON-NLS-1$
- private static final String TEMPLATE_USES_SDK = TEMPLATES_DIRECTORY
- + "uses-sdk.template"; //$NON-NLS-1$
- private static final String TEMPLATE_INTENT_LAUNCHER = TEMPLATES_DIRECTORY
- + "launcher_intent_filter.template"; //$NON-NLS-1$
- private static final String TEMPLATE_TEST_USES_LIBRARY = TEMPLATES_DIRECTORY
- + "test_uses-library.template"; //$NON-NLS-1$
- private static final String TEMPLATE_TEST_INSTRUMENTATION = TEMPLATES_DIRECTORY
- + "test_instrumentation.template"; //$NON-NLS-1$
-
-
-
- private static final String TEMPLATE_STRINGS = TEMPLATES_DIRECTORY
- + "strings.template"; //$NON-NLS-1$
- private static final String TEMPLATE_STRING = TEMPLATES_DIRECTORY
- + "string.template"; //$NON-NLS-1$
- private static final String PROJECT_ICON = "ic_launcher.png"; //$NON-NLS-1$
- private static final String ICON_XHDPI = "ic_launcher_xhdpi.png"; //$NON-NLS-1$
- private static final String ICON_HDPI = "ic_launcher_hdpi.png"; //$NON-NLS-1$
- private static final String ICON_MDPI = "ic_launcher_mdpi.png"; //$NON-NLS-1$
- private static final String ICON_LDPI = "ic_launcher_ldpi.png"; //$NON-NLS-1$
-
- private static final String STRINGS_FILE = "strings.xml"; //$NON-NLS-1$
-
- private static final String STRING_RSRC_PREFIX = SdkConstants.STRING_PREFIX;
- private static final String STRING_APP_NAME = "app_name"; //$NON-NLS-1$
- private static final String STRING_HELLO_WORLD = "hello"; //$NON-NLS-1$
-
- private static final String[] DEFAULT_DIRECTORIES = new String[] {
- BIN_DIRECTORY, BIN_CLASSES_DIRECTORY, RES_DIRECTORY, ASSETS_DIRECTORY };
- private static final String[] RES_DIRECTORIES = new String[] {
- DRAWABLE_DIRECTORY, LAYOUT_DIRECTORY, VALUES_DIRECTORY };
- private static final String[] RES_DENSITY_ENABLED_DIRECTORIES = new String[] {
- DRAWABLE_XHDPI_DIRECTORY,
- DRAWABLE_HDPI_DIRECTORY, DRAWABLE_MDPI_DIRECTORY, DRAWABLE_LDPI_DIRECTORY,
- LAYOUT_DIRECTORY, VALUES_DIRECTORY };
-
- private static final String JAVA_ACTIVITY_TEMPLATE = "java_file.template"; //$NON-NLS-1$
- private static final String LAYOUT_TEMPLATE = "layout.template"; //$NON-NLS-1$
- private static final String MAIN_LAYOUT_XML = "main.xml"; //$NON-NLS-1$
-
- private final NewProjectWizardState mValues;
- private final IRunnableContext mRunnableContext;
-
- /**
- * Creates a new {@linkplain NewProjectCreator}
- * @param values the wizard state with initial project parameters
- * @param runnableContext the context to run project creation in
- */
- public NewProjectCreator(NewProjectWizardState values, IRunnableContext runnableContext) {
- mValues = values;
- mRunnableContext = runnableContext;
- }
-
- /**
- * Before actually creating the project for a new project (as opposed to using an
- * existing project), we check if the target location is a directory that either does
- * not exist or is empty.
- *
- * If it's not empty, ask the user for confirmation.
- *
- * @param destination The destination folder where the new project is to be created.
- * @return True if the destination doesn't exist yet or is an empty directory or is
- * accepted by the user.
- */
- private boolean validateNewProjectLocationIsEmpty(IPath destination) {
- File f = new File(destination.toOSString());
- if (f.isDirectory() && f.list().length > 0) {
- return AdtPlugin.displayPrompt("New Android Project",
- "You are going to create a new Android Project in an existing, non-empty, directory. Are you sure you want to proceed?");
- }
- return true;
- }
-
- /**
- * Structure that describes all the information needed to create a project.
- * This is collected from the pages by {@link NewProjectCreator#createAndroidProjects()}
- * and then used by
- * {@link NewProjectCreator#createProjectAsync(IProgressMonitor, ProjectInfo, ProjectInfo)}.
- */
- private static class ProjectInfo {
- private final IProject mProject;
- private final IProjectDescription mDescription;
- private final Map<String, Object> mParameters;
- private final HashMap<String, String> mDictionary;
-
- public ProjectInfo(IProject project,
- IProjectDescription description,
- Map<String, Object> parameters,
- HashMap<String, String> dictionary) {
- mProject = project;
- mDescription = description;
- mParameters = parameters;
- mDictionary = dictionary;
- }
-
- public IProject getProject() {
- return mProject;
- }
-
- public IProjectDescription getDescription() {
- return mDescription;
- }
-
- public Map<String, Object> getParameters() {
- return mParameters;
- }
-
- public HashMap<String, String> getDictionary() {
- return mDictionary;
- }
- }
-
- /**
- * Creates the android project.
- * @return True if the project could be created.
- */
- public boolean createAndroidProjects() {
- if (mValues.importProjects != null && !mValues.importProjects.isEmpty()) {
- return importProjects();
- }
-
- final ProjectInfo mainData = collectMainPageInfo();
- final ProjectInfo testData = collectTestPageInfo();
-
- // Create a monitored operation to create the actual project
- WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
- @Override
- protected void execute(IProgressMonitor monitor) throws InvocationTargetException {
- createProjectAsync(monitor, mainData, testData, null, true);
- }
- };
-
- // Run the operation in a different thread
- runAsyncOperation(op);
- return true;
- }
-
- /**
- * Creates the a plain Java project without typical android directories or an Android Nature.
- * This is intended for use by unit tests and not as a general-purpose Java project creator.
- * @return True if the project could be created.
- */
- @VisibleForTesting
- public boolean createJavaProjects() {
- if (mValues.importProjects != null && !mValues.importProjects.isEmpty()) {
- return importProjects();
- }
-
- final ProjectInfo mainData = collectMainPageInfo();
- final ProjectInfo testData = collectTestPageInfo();
-
- // Create a monitored operation to create the actual project
- WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
- @Override
- protected void execute(IProgressMonitor monitor) throws InvocationTargetException {
- createProjectAsync(monitor, mainData, testData, null, false);
- }
- };
-
- // Run the operation in a different thread
- runAsyncOperation(op);
- return true;
- }
-
- /**
- * Imports a list of projects
- */
- private boolean importProjects() {
- assert mValues.importProjects != null && !mValues.importProjects.isEmpty();
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
-
- final List<ProjectInfo> projectData = new ArrayList<ProjectInfo>();
- for (ImportedProject p : mValues.importProjects) {
-
- // Compute the project name and the package name from the manifest
- ManifestData manifest = p.getManifest();
- if (manifest == null) {
- continue;
- }
- String packageName = manifest.getPackage();
- String projectName = p.getProjectName();
- String minSdk = manifest.getMinSdkVersionString();
-
- final IProject project = workspace.getRoot().getProject(projectName);
- final IProjectDescription description =
- workspace.newProjectDescription(project.getName());
-
- final Map<String, Object> parameters = new HashMap<String, Object>();
- parameters.put(PARAM_PROJECT, projectName);
- parameters.put(PARAM_PACKAGE, packageName);
- parameters.put(PARAM_SDK_TOOLS_DIR, AdtPlugin.getOsSdkToolsFolder());
- parameters.put(PARAM_IS_NEW_PROJECT, Boolean.FALSE);
- parameters.put(PARAM_SRC_FOLDER, SdkConstants.FD_SOURCES);
-
- parameters.put(PARAM_SDK_TARGET, p.getTarget());
-
- // TODO: Find out if these end up getting used in the import-path through the code!
- parameters.put(PARAM_MIN_SDK_VERSION, minSdk);
- parameters.put(PARAM_APPLICATION, STRING_RSRC_PREFIX + STRING_APP_NAME);
- final HashMap<String, String> dictionary = new HashMap<String, String>();
- dictionary.put(STRING_APP_NAME, mValues.applicationName);
-
- if (mValues.copyIntoWorkspace) {
- parameters.put(PARAM_SOURCE, p.getLocation());
-
- // TODO: Make sure it isn't *already* in the workspace!
- //IPath defaultLocation = Platform.getLocation();
- //if ((!mValues.useDefaultLocation || mValues.useExisting)
- // && !defaultLocation.isPrefixOf(path)) {
- //IPath workspaceLocation = Platform.getLocation().append(projectName);
- //description.setLocation(workspaceLocation);
- // DON'T SET THE LOCATION: It's IMPLIED and in fact it will generate
- // an error if you set it!
- } else {
- // Create in place
- description.setLocation(new Path(p.getLocation().getPath()));
- }
-
- projectData.add(new ProjectInfo(project, description, parameters, dictionary));
- }
-
- // Create a monitored operation to create the actual project
- WorkspaceModifyOperation op = new WorkspaceModifyOperation() {
- @Override
- protected void execute(IProgressMonitor monitor) throws InvocationTargetException {
- createProjectAsync(monitor, null, null, projectData, true);
- }
- };
-
- // Run the operation in a different thread
- runAsyncOperation(op);
- return true;
- }
-
- /**
- * Collects all the parameters needed to create the main project.
- * @return A new {@link ProjectInfo} on success. Returns null if the project cannot be
- * created because parameters are incorrect or should not be created because there
- * is no main page.
- */
- private ProjectInfo collectMainPageInfo() {
- if (mValues.mode == Mode.TEST) {
- return null;
- }
-
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- final IProject project = workspace.getRoot().getProject(mValues.projectName);
- final IProjectDescription description = workspace.newProjectDescription(project.getName());
-
- final Map<String, Object> parameters = new HashMap<String, Object>();
- parameters.put(PARAM_PROJECT, mValues.projectName);
- parameters.put(PARAM_PACKAGE, mValues.packageName);
- parameters.put(PARAM_APPLICATION, STRING_RSRC_PREFIX + STRING_APP_NAME);
- parameters.put(PARAM_SDK_TOOLS_DIR, AdtPlugin.getOsSdkToolsFolder());
- parameters.put(PARAM_IS_NEW_PROJECT, mValues.mode == Mode.ANY && !mValues.useExisting);
- parameters.put(PARAM_SAMPLE_LOCATION, mValues.chosenSample);
- parameters.put(PARAM_SRC_FOLDER, mValues.sourceFolder);
- parameters.put(PARAM_SDK_TARGET, mValues.target);
- parameters.put(PARAM_MIN_SDK_VERSION, mValues.minSdk);
-
- if (mValues.createActivity) {
- parameters.put(PARAM_ACTIVITY, mValues.activityName);
- }
-
- // create a dictionary of string that will contain name+content.
- // we'll put all the strings into values/strings.xml
- final HashMap<String, String> dictionary = new HashMap<String, String>();
- dictionary.put(STRING_APP_NAME, mValues.applicationName);
-
- IPath path = new Path(mValues.projectLocation.getPath());
- IPath defaultLocation = Platform.getLocation();
- if ((!mValues.useDefaultLocation || mValues.useExisting)
- && !defaultLocation.isPrefixOf(path)) {
- description.setLocation(path);
- }
-
- if (mValues.mode == Mode.ANY && !mValues.useExisting && !mValues.useDefaultLocation &&
- !validateNewProjectLocationIsEmpty(path)) {
- return null;
- }
-
- return new ProjectInfo(project, description, parameters, dictionary);
- }
-
- /**
- * Collects all the parameters needed to create the test project.
- *
- * @return A new {@link ProjectInfo} on success. Returns null if the project cannot be
- * created because parameters are incorrect or should not be created because there
- * is no test page.
- */
- private ProjectInfo collectTestPageInfo() {
- if (mValues.mode != Mode.TEST && !mValues.createPairProject) {
- return null;
- }
-
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- String projectName =
- mValues.mode == Mode.TEST ? mValues.projectName : mValues.testProjectName;
- final IProject project = workspace.getRoot().getProject(projectName);
- final IProjectDescription description = workspace.newProjectDescription(project.getName());
-
- final Map<String, Object> parameters = new HashMap<String, Object>();
-
- String pkg =
- mValues.mode == Mode.TEST ? mValues.packageName : mValues.testPackageName;
-
- parameters.put(PARAM_PACKAGE, pkg);
- parameters.put(PARAM_APPLICATION, STRING_RSRC_PREFIX + STRING_APP_NAME);
- parameters.put(PARAM_SDK_TOOLS_DIR, AdtPlugin.getOsSdkToolsFolder());
- parameters.put(PARAM_IS_NEW_PROJECT, !mValues.useExisting);
- parameters.put(PARAM_SRC_FOLDER, mValues.sourceFolder);
- parameters.put(PARAM_SDK_TARGET, mValues.target);
- parameters.put(PARAM_MIN_SDK_VERSION, mValues.minSdk);
-
- // Test-specific parameters
- String testedPkg = mValues.createPairProject
- ? mValues.packageName : mValues.testTargetPackageName;
- if (testedPkg == null) {
- assert mValues.testingSelf;
- testedPkg = pkg;
- }
-
- parameters.put(PARAM_TEST_TARGET_PACKAGE, testedPkg);
-
- if (mValues.testingSelf) {
- parameters.put(PARAM_TARGET_SELF, true);
- } else {
- parameters.put(PARAM_TARGET_EXISTING, true);
- parameters.put(PARAM_REFERENCE_PROJECT, mValues.testedProject);
- }
-
- if (mValues.createPairProject) {
- parameters.put(PARAM_TARGET_MAIN, true);
- }
-
- // create a dictionary of string that will contain name+content.
- // we'll put all the strings into values/strings.xml
- final HashMap<String, String> dictionary = new HashMap<String, String>();
- dictionary.put(STRING_APP_NAME, mValues.testApplicationName);
-
- // Use the same logic to determine test project location as in
- // ApplicationInfoPage#validateTestProjectLocation
- IPath path = new Path(mValues.projectLocation.getPath());
- path = path.removeLastSegments(1).append(mValues.testProjectName);
- IPath defaultLocation = Platform.getLocation();
- if ((!mValues.useDefaultLocation || mValues.useExisting)
- && !path.equals(defaultLocation)) {
- description.setLocation(path);
- }
-
- if (!mValues.useExisting && !mValues.useDefaultLocation &&
- !validateNewProjectLocationIsEmpty(path)) {
- return null;
- }
-
- return new ProjectInfo(project, description, parameters, dictionary);
- }
-
- /**
- * Runs the operation in a different thread and display generated
- * exceptions.
- *
- * @param op The asynchronous operation to run.
- */
- private void runAsyncOperation(WorkspaceModifyOperation op) {
- try {
- mRunnableContext.run(true /* fork */, true /* cancelable */, op);
- } catch (InvocationTargetException e) {
-
- AdtPlugin.log(e, "New Project Wizard failed");
-
- // The runnable threw an exception
- Throwable t = e.getTargetException();
- if (t instanceof CoreException) {
- CoreException core = (CoreException) t;
- if (core.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) {
- // The error indicates the file system is not case sensitive
- // and there's a resource with a similar name.
- MessageDialog.openError(AdtPlugin.getShell(),
- "Error", "Error: Case Variant Exists");
- } else {
- ErrorDialog.openError(AdtPlugin.getShell(),
- "Error", core.getMessage(), core.getStatus());
- }
- } else {
- // Some other kind of exception
- String msg = t.getMessage();
- Throwable t1 = t;
- while (msg == null && t1.getCause() != null) {
- msg = t1.getMessage();
- t1 = t1.getCause();
- }
- if (msg == null) {
- msg = t.toString();
- }
- MessageDialog.openError(AdtPlugin.getShell(), "Error", msg);
- }
- e.printStackTrace();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
-
- /**
- * Creates the actual project(s). This is run asynchronously in a different thread.
- *
- * @param monitor An existing monitor.
- * @param mainData Data for main project. Can be null.
- * @param isAndroidProject true if the project is to be set up as a full Android project; false
- * for a plain Java project.
- * @throws InvocationTargetException to wrap any unmanaged exception and
- * return it to the calling thread. The method can fail if it fails
- * to create or modify the project or if it is canceled by the user.
- */
- private void createProjectAsync(IProgressMonitor monitor,
- ProjectInfo mainData,
- ProjectInfo testData,
- List<ProjectInfo> importData,
- boolean isAndroidProject)
- throws InvocationTargetException {
- monitor.beginTask("Create Android Project", 100);
- try {
- IProject mainProject = null;
-
- if (mainData != null) {
- mainProject = createEclipseProject(
- new SubProgressMonitor(monitor, 50),
- mainData.getProject(),
- mainData.getDescription(),
- mainData.getParameters(),
- mainData.getDictionary(),
- null,
- isAndroidProject);
-
- if (mainProject != null) {
- final IJavaProject javaProject = JavaCore.create(mainProject);
- Display.getDefault().syncExec(new WorksetAdder(javaProject,
- mValues.workingSets));
- }
- }
-
- if (testData != null) {
- Map<String, Object> parameters = testData.getParameters();
- if (parameters.containsKey(PARAM_TARGET_MAIN) && mainProject != null) {
- parameters.put(PARAM_REFERENCE_PROJECT, mainProject);
- }
-
- IProject testProject = createEclipseProject(
- new SubProgressMonitor(monitor, 50),
- testData.getProject(),
- testData.getDescription(),
- parameters,
- testData.getDictionary(),
- null,
- isAndroidProject);
- if (testProject != null) {
- final IJavaProject javaProject = JavaCore.create(testProject);
- Display.getDefault().syncExec(new WorksetAdder(javaProject,
- mValues.workingSets));
- }
- }
-
- if (importData != null) {
- for (final ProjectInfo data : importData) {
- ProjectPopulator projectPopulator = null;
- if (mValues.copyIntoWorkspace) {
- projectPopulator = new ProjectPopulator() {
- @Override
- public void populate(IProject project) {
- // Copy
- IFileSystem fileSystem = EFS.getLocalFileSystem();
- File source = (File) data.getParameters().get(PARAM_SOURCE);
- IFileStore sourceDir = new ReadWriteFileStore(
- fileSystem.getStore(source.toURI()));
- IFileStore destDir = new ReadWriteFileStore(
- fileSystem.getStore(AdtUtils.getAbsolutePath(project)));
- try {
- sourceDir.copy(destDir, EFS.OVERWRITE, null);
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- }
- };
- }
- IProject project = createEclipseProject(
- new SubProgressMonitor(monitor, 50),
- data.getProject(),
- data.getDescription(),
- data.getParameters(),
- data.getDictionary(),
- projectPopulator,
- isAndroidProject);
- if (project != null) {
- final IJavaProject javaProject = JavaCore.create(project);
- Display.getDefault().syncExec(new WorksetAdder(javaProject,
- mValues.workingSets));
- ProjectHelper.enforcePreferredCompilerCompliance(javaProject);
- }
- }
- }
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- } catch (IOException e) {
- throw new InvocationTargetException(e);
- } catch (StreamException e) {
- throw new InvocationTargetException(e);
- } finally {
- monitor.done();
- }
- }
-
- /** Handler which can write contents into a project */
- public interface ProjectPopulator {
- /**
- * Add contents into the given project
- *
- * @param project the project to write into
- * @throws InvocationTargetException if anything goes wrong
- */
- public void populate(IProject project) throws InvocationTargetException;
- }
-
- /**
- * Creates the actual project, sets its nature and adds the required folders
- * and files to it. This is run asynchronously in a different thread.
- *
- * @param monitor An existing monitor.
- * @param project The project to create.
- * @param description A description of the project.
- * @param parameters Template parameters.
- * @param dictionary String definition.
- * @param isAndroidProject true if the project is to be set up as a full Android project; false
- * for a plain Java project.
- * @return The project newly created
- * @throws StreamException
- */
- private IProject createEclipseProject(
- @NonNull IProgressMonitor monitor,
- @NonNull IProject project,
- @NonNull IProjectDescription description,
- @NonNull Map<String, Object> parameters,
- @Nullable Map<String, String> dictionary,
- @Nullable ProjectPopulator projectPopulator,
- boolean isAndroidProject)
- throws CoreException, IOException, StreamException {
-
- // get the project target
- IAndroidTarget target = (IAndroidTarget) parameters.get(PARAM_SDK_TARGET);
- boolean legacy = isAndroidProject && target.getVersion().getApiLevel() < 4;
-
- // Create project and open it
- project.create(description, new SubProgressMonitor(monitor, 10));
- if (monitor.isCanceled()) throw new OperationCanceledException();
-
- project.open(IResource.BACKGROUND_REFRESH, new SubProgressMonitor(monitor, 10));
-
- // Add the Java and android nature to the project
- AndroidNature.setupProjectNatures(project, monitor, isAndroidProject);
-
- // Create folders in the project if they don't already exist
- addDefaultDirectories(project, AdtConstants.WS_ROOT, DEFAULT_DIRECTORIES, monitor);
- String[] sourceFolders;
- if (isAndroidProject) {
- sourceFolders = new String[] {
- (String) parameters.get(PARAM_SRC_FOLDER),
- GEN_SRC_DIRECTORY
- };
- } else {
- sourceFolders = new String[] {
- (String) parameters.get(PARAM_SRC_FOLDER)
- };
- }
- addDefaultDirectories(project, AdtConstants.WS_ROOT, sourceFolders, monitor);
-
- // Create the resource folders in the project if they don't already exist.
- if (legacy) {
- addDefaultDirectories(project, RES_DIRECTORY, RES_DIRECTORIES, monitor);
- } else {
- addDefaultDirectories(project, RES_DIRECTORY, RES_DENSITY_ENABLED_DIRECTORIES, monitor);
- }
-
- if (projectPopulator != null) {
- try {
- projectPopulator.populate(project);
- } catch (InvocationTargetException ite) {
- AdtPlugin.log(ite, null);
- }
- }
-
- // Setup class path: mark folders as source folders
- IJavaProject javaProject = JavaCore.create(project);
- setupSourceFolders(javaProject, sourceFolders, monitor);
-
- if (((Boolean) parameters.get(PARAM_IS_NEW_PROJECT)).booleanValue()) {
- // Create files in the project if they don't already exist
- addManifest(project, parameters, dictionary, monitor);
-
- // add the default app icon
- addIcon(project, legacy, monitor);
-
- // Create the default package components
- addSampleCode(project, sourceFolders[0], parameters, dictionary, monitor);
-
- // add the string definition file if needed
- if (dictionary != null && dictionary.size() > 0) {
- addStringDictionaryFile(project, dictionary, monitor);
- }
-
- // add the default proguard config
- File libFolder = new File((String) parameters.get(PARAM_SDK_TOOLS_DIR),
- SdkConstants.FD_LIB);
- addLocalFile(project,
- new File(libFolder, SdkConstants.FN_PROJECT_PROGUARD_FILE),
- // Write ProGuard config files with the extension .pro which
- // is what is used in the ProGuard documentation and samples
- SdkConstants.FN_PROJECT_PROGUARD_FILE,
- monitor);
-
- // Set output location
- javaProject.setOutputLocation(project.getFolder(BIN_CLASSES_DIRECTORY).getFullPath(),
- monitor);
- }
-
- File sampleDir = (File) parameters.get(PARAM_SAMPLE_LOCATION);
- if (sampleDir != null) {
- // Copy project
- copySampleCode(project, sampleDir, parameters, dictionary, monitor);
- }
-
- // Create the reference to the target project
- if (parameters.containsKey(PARAM_REFERENCE_PROJECT)) {
- IProject refProject = (IProject) parameters.get(PARAM_REFERENCE_PROJECT);
- if (refProject != null) {
- IProjectDescription desc = project.getDescription();
-
- // Add out reference to the existing project reference.
- // We just created a project with no references so we don't need to expand
- // the currently-empty current list.
- desc.setReferencedProjects(new IProject[] { refProject });
-
- project.setDescription(desc, IResource.KEEP_HISTORY,
- new SubProgressMonitor(monitor, 10));
-
- IClasspathEntry entry = JavaCore.newProjectEntry(
- refProject.getFullPath(), //path
- new IAccessRule[0], //accessRules
- false, //combineAccessRules
- new IClasspathAttribute[0], //extraAttributes
- false //isExported
-
- );
- ProjectHelper.addEntryToClasspath(javaProject, entry);
- }
- }
-
- if (isAndroidProject) {
- Sdk.getCurrent().initProject(project, target);
- }
-
- // Fix the project to make sure all properties are as expected.
- // Necessary for existing projects and good for new ones to.
- ProjectHelper.fixProject(project);
-
- Boolean isLibraryProject = (Boolean) parameters.get(PARAM_IS_LIBRARY);
- if (isLibraryProject != null && isLibraryProject.booleanValue()
- && Sdk.getCurrent() != null && project.isOpen()) {
- ProjectState state = Sdk.getProjectState(project);
- if (state != null) {
- // make a working copy of the properties
- ProjectPropertiesWorkingCopy properties =
- state.getProperties().makeWorkingCopy();
-
- properties.setProperty(PROPERTY_LIBRARY, Boolean.TRUE.toString());
- try {
- properties.save();
- IResource projectProp = project.findMember(FN_PROJECT_PROPERTIES);
- if (projectProp != null) {
- projectProp.refreshLocal(DEPTH_ZERO, new NullProgressMonitor());
- }
- } catch (Exception e) {
- String msg = String.format(
- "Failed to save %1$s for project %2$s",
- SdkConstants.FN_PROJECT_PROPERTIES, project.getName());
- AdtPlugin.log(e, msg);
- }
- }
- }
-
- return project;
- }
-
- /**
- * Creates a new project
- *
- * @param monitor An existing monitor.
- * @param project The project to create.
- * @param target the build target to associate with the project
- * @param projectPopulator a handler for writing the template contents
- * @param isLibrary whether this project should be marked as a library project
- * @param projectLocation the location to write the project into
- * @param workingSets Eclipse working sets, if any, to add the project to
- * @throws CoreException if anything goes wrong
- */
- public static void create(
- @NonNull IProgressMonitor monitor,
- @NonNull final IProject project,
- @NonNull IAndroidTarget target,
- @Nullable final ProjectPopulator projectPopulator,
- boolean isLibrary,
- @NonNull String projectLocation,
- @NonNull final IWorkingSet[] workingSets)
- throws CoreException {
- final NewProjectCreator creator = new NewProjectCreator(null, null);
-
- final Map<String, String> dictionary = null;
- final Map<String, Object> parameters = new HashMap<String, Object>();
- parameters.put(PARAM_SDK_TARGET, target);
- parameters.put(PARAM_SRC_FOLDER, SdkConstants.FD_SOURCES);
- parameters.put(PARAM_IS_NEW_PROJECT, false);
- parameters.put(PARAM_SAMPLE_LOCATION, null);
- parameters.put(PARAM_IS_LIBRARY, isLibrary);
-
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- final IProjectDescription description = workspace.newProjectDescription(project.getName());
-
- if (projectLocation != null) {
- IPath path = new Path(projectLocation);
- IPath parent = new Path(path.toFile().getParent());
- IPath workspaceLocation = Platform.getLocation();
- if (!workspaceLocation.equals(parent)) {
- description.setLocation(path);
- }
- }
-
- IWorkspaceRunnable workspaceRunnable = new IWorkspaceRunnable() {
- @Override
- public void run(IProgressMonitor submonitor) throws CoreException {
- try {
- creator.createEclipseProject(submonitor, project, description, parameters,
- dictionary, projectPopulator, true);
- } catch (IOException e) {
- throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "Unexpected error while creating project", e));
- } catch (StreamException e) {
- throw new CoreException(new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "Unexpected error while creating project", e));
- }
- if (workingSets != null && workingSets.length > 0) {
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
- if (javaProject != null) {
- Display.getDefault().syncExec(new WorksetAdder(javaProject,
- workingSets));
- }
- }
- }
- };
-
- ResourcesPlugin.getWorkspace().run(workspaceRunnable, monitor);
- }
-
- /**
- * Adds default directories to the project.
- *
- * @param project The Java Project to update.
- * @param parentFolder The path of the parent folder. Must end with a
- * separator.
- * @param folders Folders to be added.
- * @param monitor An existing monitor.
- * @throws CoreException if the method fails to create the directories in
- * the project.
- */
- private void addDefaultDirectories(IProject project, String parentFolder,
- String[] folders, IProgressMonitor monitor) throws CoreException {
- for (String name : folders) {
- if (name.length() > 0) {
- IFolder folder = project.getFolder(parentFolder + name);
- if (!folder.exists()) {
- folder.create(true /* force */, true /* local */,
- new SubProgressMonitor(monitor, 10));
- }
- }
- }
- }
-
- /**
- * Adds the manifest to the project.
- *
- * @param project The Java Project to update.
- * @param parameters Template Parameters.
- * @param dictionary String List to be added to a string definition
- * file. This map will be filled by this method.
- * @param monitor An existing monitor.
- * @throws CoreException if the method fails to update the project.
- * @throws IOException if the method fails to create the files in the
- * project.
- */
- private void addManifest(IProject project, Map<String, Object> parameters,
- Map<String, String> dictionary, IProgressMonitor monitor)
- throws CoreException, IOException {
-
- // get IFile to the manifest and check if it's not already there.
- IFile file = project.getFile(SdkConstants.FN_ANDROID_MANIFEST_XML);
- if (!file.exists()) {
-
- // Read manifest template
- String manifestTemplate = AdtPlugin.readEmbeddedTextFile(TEMPLATE_MANIFEST);
-
- // Replace all keyword parameters
- manifestTemplate = replaceParameters(manifestTemplate, parameters);
-
- if (manifestTemplate == null) {
- // Inform the user there will be not manifest.
- AdtPlugin.logAndPrintError(null, "Create Project" /*TAG*/,
- "Failed to generate the Android manifest. Missing template %s",
- TEMPLATE_MANIFEST);
- // Abort now, there's no need to continue
- return;
- }
-
- if (parameters.containsKey(PARAM_ACTIVITY)) {
- // now get the activity template
- String activityTemplate = AdtPlugin.readEmbeddedTextFile(TEMPLATE_ACTIVITIES);
-
- // If the activity name doesn't contain any dot, it's in the form
- // "ClassName" and we need to expand it to ".ClassName" in the XML.
- String name = (String) parameters.get(PARAM_ACTIVITY);
- if (name.indexOf('.') == -1) {
- // Duplicate the parameters map to avoid changing the caller
- parameters = new HashMap<String, Object>(parameters);
- parameters.put(PARAM_ACTIVITY, "." + name); //$NON-NLS-1$
- }
-
- // Replace all keyword parameters to make main activity.
- String activities = replaceParameters(activityTemplate, parameters);
-
- // set the intent.
- String intent = AdtPlugin.readEmbeddedTextFile(TEMPLATE_INTENT_LAUNCHER);
-
- if (activities != null) {
- if (intent != null) {
- // set the intent to the main activity
- activities = activities.replaceAll(PH_INTENT_FILTERS, intent);
- }
-
- // set the activity(ies) in the manifest
- manifestTemplate = manifestTemplate.replaceAll(PH_ACTIVITIES, activities);
- }
- } else {
- // remove the activity(ies) from the manifest
- manifestTemplate = manifestTemplate.replaceAll(PH_ACTIVITIES, ""); //$NON-NLS-1$
- }
-
- // Handle the case of the test projects
- if (parameters.containsKey(PARAM_TEST_TARGET_PACKAGE)) {
- // Set the uses-library needed by the test project
- String usesLibrary = AdtPlugin.readEmbeddedTextFile(TEMPLATE_TEST_USES_LIBRARY);
- if (usesLibrary != null) {
- manifestTemplate = manifestTemplate.replaceAll(
- PH_TEST_USES_LIBRARY, usesLibrary);
- }
-
- // Set the instrumentation element needed by the test project
- String instru = AdtPlugin.readEmbeddedTextFile(TEMPLATE_TEST_INSTRUMENTATION);
- if (instru != null) {
- manifestTemplate = manifestTemplate.replaceAll(
- PH_TEST_INSTRUMENTATION, instru);
- }
-
- // Replace PARAM_TEST_TARGET_PACKAGE itself now
- manifestTemplate = replaceParameters(manifestTemplate, parameters);
-
- } else {
- // remove the unused entries
- manifestTemplate = manifestTemplate.replaceAll(PH_TEST_USES_LIBRARY, ""); //$NON-NLS-1$
- manifestTemplate = manifestTemplate.replaceAll(PH_TEST_INSTRUMENTATION, ""); //$NON-NLS-1$
- }
-
- String minSdkVersion = (String) parameters.get(PARAM_MIN_SDK_VERSION);
- if (minSdkVersion != null && minSdkVersion.length() > 0) {
- String usesSdkTemplate = AdtPlugin.readEmbeddedTextFile(TEMPLATE_USES_SDK);
- if (usesSdkTemplate != null) {
- String usesSdk = replaceParameters(usesSdkTemplate, parameters);
- manifestTemplate = manifestTemplate.replaceAll(PH_USES_SDK, usesSdk);
- }
- } else {
- manifestTemplate = manifestTemplate.replaceAll(PH_USES_SDK, "");
- }
-
- // Reformat the file according to the user's formatting settings
- manifestTemplate = reformat(XmlFormatStyle.MANIFEST, manifestTemplate);
-
- // Save in the project as UTF-8
- InputStream stream = new ByteArrayInputStream(
- manifestTemplate.getBytes("UTF-8")); //$NON-NLS-1$
- file.create(stream, false /* force */, new SubProgressMonitor(monitor, 10));
- }
- }
-
- /**
- * Adds the string resource file.
- *
- * @param project The Java Project to update.
- * @param strings The list of strings to be added to the string file.
- * @param monitor An existing monitor.
- * @throws CoreException if the method fails to update the project.
- * @throws IOException if the method fails to create the files in the
- * project.
- */
- private void addStringDictionaryFile(IProject project,
- Map<String, String> strings, IProgressMonitor monitor)
- throws CoreException, IOException {
-
- // create the IFile object and check if the file doesn't already exist.
- IFile file = project.getFile(RES_DIRECTORY + AdtConstants.WS_SEP
- + VALUES_DIRECTORY + AdtConstants.WS_SEP + STRINGS_FILE);
- if (!file.exists()) {
- // get the Strings.xml template
- String stringDefinitionTemplate = AdtPlugin.readEmbeddedTextFile(TEMPLATE_STRINGS);
-
- // get the template for one string
- String stringTemplate = AdtPlugin.readEmbeddedTextFile(TEMPLATE_STRING);
-
- // get all the string names
- Set<String> stringNames = strings.keySet();
-
- // loop on it and create the string definitions
- StringBuilder stringNodes = new StringBuilder();
- for (String key : stringNames) {
- // get the value from the key
- String value = strings.get(key);
-
- // Escape values if necessary
- value = ValueXmlHelper.escapeResourceString(value);
-
- // place them in the template
- String stringDef = stringTemplate.replace(PARAM_STRING_NAME, key);
- stringDef = stringDef.replace(PARAM_STRING_CONTENT, value);
-
- // append to the other string
- if (stringNodes.length() > 0) {
- stringNodes.append('\n');
- }
- stringNodes.append(stringDef);
- }
-
- // put the string nodes in the Strings.xml template
- stringDefinitionTemplate = stringDefinitionTemplate.replace(PH_STRINGS,
- stringNodes.toString());
-
- // reformat the file according to the user's formatting settings
- stringDefinitionTemplate = reformat(XmlFormatStyle.RESOURCE, stringDefinitionTemplate);
-
- // write the file as UTF-8
- InputStream stream = new ByteArrayInputStream(
- stringDefinitionTemplate.getBytes("UTF-8")); //$NON-NLS-1$
- file.create(stream, false /* force */, new SubProgressMonitor(monitor, 10));
- }
- }
-
- /** Reformats the given contents with the current formatting settings */
- private String reformat(XmlFormatStyle style, String contents) {
- if (AdtPrefs.getPrefs().getUseCustomXmlFormatter()) {
- EclipseXmlFormatPreferences formatPrefs = EclipseXmlFormatPreferences.create();
- return EclipseXmlPrettyPrinter.prettyPrint(contents, formatPrefs, style,
- null /*lineSeparator*/);
- } else {
- return contents;
- }
- }
-
- /**
- * Adds default application icon to the project.
- *
- * @param project The Java Project to update.
- * @param legacy whether we're running in legacy mode (no density support)
- * @param monitor An existing monitor.
- * @throws CoreException if the method fails to update the project.
- */
- private void addIcon(IProject project, boolean legacy, IProgressMonitor monitor)
- throws CoreException {
- if (legacy) { // density support
- // do medium density icon only, in the default drawable folder.
- IFile file = project.getFile(RES_DIRECTORY + AdtConstants.WS_SEP
- + DRAWABLE_DIRECTORY + AdtConstants.WS_SEP + PROJECT_ICON);
- if (!file.exists()) {
- addFile(file, AdtPlugin.readEmbeddedFile(TEMPLATES_DIRECTORY + ICON_MDPI), monitor);
- }
- } else {
- // do all 4 icons.
- IFile file;
-
- // extra high density
- file = project.getFile(RES_DIRECTORY + AdtConstants.WS_SEP
- + DRAWABLE_XHDPI_DIRECTORY + AdtConstants.WS_SEP + PROJECT_ICON);
- if (!file.exists()) {
- addFile(file, AdtPlugin.readEmbeddedFile(TEMPLATES_DIRECTORY + ICON_XHDPI), monitor);
- }
-
- // high density
- file = project.getFile(RES_DIRECTORY + AdtConstants.WS_SEP
- + DRAWABLE_HDPI_DIRECTORY + AdtConstants.WS_SEP + PROJECT_ICON);
- if (!file.exists()) {
- addFile(file, AdtPlugin.readEmbeddedFile(TEMPLATES_DIRECTORY + ICON_HDPI), monitor);
- }
-
- // medium density
- file = project.getFile(RES_DIRECTORY + AdtConstants.WS_SEP
- + DRAWABLE_MDPI_DIRECTORY + AdtConstants.WS_SEP + PROJECT_ICON);
- if (!file.exists()) {
- addFile(file, AdtPlugin.readEmbeddedFile(TEMPLATES_DIRECTORY + ICON_MDPI), monitor);
- }
-
- // low density
- file = project.getFile(RES_DIRECTORY + AdtConstants.WS_SEP
- + DRAWABLE_LDPI_DIRECTORY + AdtConstants.WS_SEP + PROJECT_ICON);
- if (!file.exists()) {
- addFile(file, AdtPlugin.readEmbeddedFile(TEMPLATES_DIRECTORY + ICON_LDPI), monitor);
- }
- }
- }
-
- /**
- * Creates a file from a data source.
- * @param dest the file to write
- * @param source the content of the file.
- * @param monitor the progress monitor
- * @throws CoreException
- */
- private void addFile(IFile dest, byte[] source, IProgressMonitor monitor) throws CoreException {
- if (source != null) {
- // Save in the project
- InputStream stream = new ByteArrayInputStream(source);
- dest.create(stream, false /* force */, new SubProgressMonitor(monitor, 10));
- }
- }
-
- /**
- * Creates the package folder and copies the sample code in the project.
- *
- * @param project The Java Project to update.
- * @param parameters Template Parameters.
- * @param dictionary String List to be added to a string definition
- * file. This map will be filled by this method.
- * @param monitor An existing monitor.
- * @throws CoreException if the method fails to update the project.
- * @throws IOException if the method fails to create the files in the
- * project.
- */
- private void addSampleCode(IProject project, String sourceFolder,
- Map<String, Object> parameters, Map<String, String> dictionary,
- IProgressMonitor monitor) throws CoreException, IOException {
- // create the java package directories.
- IFolder pkgFolder = project.getFolder(sourceFolder);
- String packageName = (String) parameters.get(PARAM_PACKAGE);
-
- // The PARAM_ACTIVITY key will be absent if no activity should be created,
- // in which case activityName will be null.
- String activityName = (String) parameters.get(PARAM_ACTIVITY);
-
- Map<String, Object> java_activity_parameters = new HashMap<String, Object>(parameters);
- java_activity_parameters.put(PARAM_IMPORT_RESOURCE_CLASS, ""); //$NON-NLS-1$
-
- if (activityName != null) {
-
- String resourcePackageClass = null;
-
- // An activity name can be of the form ".package.Class", ".Class" or FQDN.
- // The initial dot is ignored, as it is always added later in the templates.
- int lastDotIndex = activityName.lastIndexOf('.');
-
- if (lastDotIndex != -1) {
-
- // Resource class
- if (lastDotIndex > 0) {
- resourcePackageClass = packageName + '.' + SdkConstants.FN_RESOURCE_BASE;
- }
-
- // Package name
- if (activityName.startsWith(".")) { //$NON-NLS-1$
- packageName += activityName.substring(0, lastDotIndex);
- } else {
- packageName = activityName.substring(0, lastDotIndex);
- }
-
- // Activity Class name
- activityName = activityName.substring(lastDotIndex + 1);
- }
-
- java_activity_parameters.put(PARAM_ACTIVITY, activityName);
- java_activity_parameters.put(PARAM_PACKAGE, packageName);
- if (resourcePackageClass != null) {
- String importResourceClass = "\nimport " + resourcePackageClass + ";"; //$NON-NLS-1$ // $NON-NLS-2$
- java_activity_parameters.put(PARAM_IMPORT_RESOURCE_CLASS, importResourceClass);
- }
- }
-
- String[] components = packageName.split(AdtConstants.RE_DOT);
- for (String component : components) {
- pkgFolder = pkgFolder.getFolder(component);
- if (!pkgFolder.exists()) {
- pkgFolder.create(true /* force */, true /* local */,
- new SubProgressMonitor(monitor, 10));
- }
- }
-
- if (activityName != null) {
- // create the main activity Java file
- String activityJava = activityName + SdkConstants.DOT_JAVA;
- IFile file = pkgFolder.getFile(activityJava);
- if (!file.exists()) {
- copyFile(JAVA_ACTIVITY_TEMPLATE, file, java_activity_parameters, monitor, false);
- }
-
- // create the layout file (if we're creating an
- IFolder layoutfolder = project.getFolder(RES_DIRECTORY).getFolder(LAYOUT_DIRECTORY);
- file = layoutfolder.getFile(MAIN_LAYOUT_XML);
- if (!file.exists()) {
- copyFile(LAYOUT_TEMPLATE, file, parameters, monitor, true);
- dictionary.put(STRING_HELLO_WORLD, String.format("Hello World, %1$s!",
- activityName));
- }
- }
- }
-
- private void copySampleCode(IProject project, File sampleDir,
- Map<String, Object> parameters, Map<String, String> dictionary,
- IProgressMonitor monitor) throws CoreException {
- // Copy the sampleDir into the project directory recursively
- IFileSystem fileSystem = EFS.getLocalFileSystem();
- IFileStore sourceDir = new ReadWriteFileStore(
- fileSystem.getStore(sampleDir.toURI()));
- IFileStore destDir = new ReadWriteFileStore(
- fileSystem.getStore(AdtUtils.getAbsolutePath(project)));
- sourceDir.copy(destDir, EFS.OVERWRITE, null);
- }
-
- /**
- * In a sample we never duplicate source files as read-only.
- * This creates a store that read files attributes and doesn't set the r-o flag.
- */
- private static class ReadWriteFileStore extends FileStoreAdapter {
-
- public ReadWriteFileStore(IFileStore store) {
- super(store);
- }
-
- // Override when reading attributes
- @Override
- public IFileInfo fetchInfo(int options, IProgressMonitor monitor) throws CoreException {
- IFileInfo info = super.fetchInfo(options, monitor);
- info.setAttribute(EFS.ATTRIBUTE_READ_ONLY, false);
- return info;
- }
-
- // Override when writing attributes
- @Override
- public void putInfo(IFileInfo info, int options, IProgressMonitor storeMonitor)
- throws CoreException {
- info.setAttribute(EFS.ATTRIBUTE_READ_ONLY, false);
- super.putInfo(info, options, storeMonitor);
- }
-
- @Deprecated
- @Override
- public IFileStore getChild(IPath path) {
- IFileStore child = super.getChild(path);
- if (!(child instanceof ReadWriteFileStore)) {
- child = new ReadWriteFileStore(child);
- }
- return child;
- }
-
- @Override
- public IFileStore getChild(String name) {
- return new ReadWriteFileStore(super.getChild(name));
- }
- }
-
- /**
- * Adds a file to the root of the project
- * @param project the project to add the file to.
- * @param destName the name to write the file as
- * @param source the file to add. It'll keep the same filename once copied into the project.
- * @param monitor the monitor to report progress to
- * @throws FileNotFoundException if the file to be added does not exist
- * @throws CoreException if writing the file does not work
- */
- public static void addLocalFile(IProject project, File source, String destName,
- IProgressMonitor monitor) throws FileNotFoundException, CoreException {
- IFile dest = project.getFile(destName);
- if (dest.exists() == false) {
- FileInputStream stream = new FileInputStream(source);
- dest.create(stream, false /* force */, new SubProgressMonitor(monitor, 10));
- }
- }
-
- /**
- * Adds the given folder to the project's class path.
- *
- * @param javaProject The Java Project to update.
- * @param sourceFolders Template Parameters.
- * @param monitor An existing monitor.
- * @throws JavaModelException if the classpath could not be set.
- */
- private void setupSourceFolders(IJavaProject javaProject, String[] sourceFolders,
- IProgressMonitor monitor) throws JavaModelException {
- IProject project = javaProject.getProject();
-
- // get the list of entries.
- IClasspathEntry[] entries = javaProject.getRawClasspath();
-
- // remove the project as a source folder (This is the default)
- entries = removeSourceClasspath(entries, project);
-
- // add the source folders.
- for (String sourceFolder : sourceFolders) {
- IFolder srcFolder = project.getFolder(sourceFolder);
-
- // remove it first in case.
- entries = removeSourceClasspath(entries, srcFolder);
- entries = ProjectHelper.addEntryToClasspath(entries,
- JavaCore.newSourceEntry(srcFolder.getFullPath()));
- }
-
- javaProject.setRawClasspath(entries, new SubProgressMonitor(monitor, 10));
- }
-
-
- /**
- * Removes the corresponding source folder from the class path entries if
- * found.
- *
- * @param entries The class path entries to read. A copy will be returned.
- * @param folder The parent source folder to remove.
- * @return A new class path entries array.
- */
- private IClasspathEntry[] removeSourceClasspath(IClasspathEntry[] entries, IContainer folder) {
- if (folder == null) {
- return entries;
- }
- IClasspathEntry source = JavaCore.newSourceEntry(folder.getFullPath());
- int n = entries.length;
- for (int i = n - 1; i >= 0; i--) {
- if (entries[i].equals(source)) {
- IClasspathEntry[] newEntries = new IClasspathEntry[n - 1];
- if (i > 0) System.arraycopy(entries, 0, newEntries, 0, i);
- if (i < n - 1) System.arraycopy(entries, i + 1, newEntries, i, n - i - 1);
- n--;
- entries = newEntries;
- }
- }
- return entries;
- }
-
-
- /**
- * Copies the given file from our resource folder to the new project.
- * Expects the file to the US-ASCII or UTF-8 encoded.
- *
- * @throws CoreException from IFile if failing to create the new file.
- * @throws MalformedURLException from URL if failing to interpret the URL.
- * @throws FileNotFoundException from RandomAccessFile.
- * @throws IOException from RandomAccessFile.length() if can't determine the
- * length.
- */
- private void copyFile(String resourceFilename, IFile destFile,
- Map<String, Object> parameters, IProgressMonitor monitor, boolean reformat)
- throws CoreException, IOException {
-
- // Read existing file.
- String template = AdtPlugin.readEmbeddedTextFile(
- TEMPLATES_DIRECTORY + resourceFilename);
-
- // Replace all keyword parameters
- template = replaceParameters(template, parameters);
-
- if (reformat) {
- // Guess the formatting style based on the file location
- XmlFormatStyle style = EclipseXmlPrettyPrinter
- .getForFile(destFile.getProjectRelativePath());
- if (style != null) {
- template = reformat(style, template);
- }
- }
-
- // Save in the project as UTF-8
- InputStream stream = new ByteArrayInputStream(template.getBytes("UTF-8")); //$NON-NLS-1$
- destFile.create(stream, false /* force */, new SubProgressMonitor(monitor, 10));
- }
-
- /**
- * Replaces placeholders found in a string with values.
- *
- * @param str the string to search for placeholders.
- * @param parameters a map of <placeholder, Value> to search for in the string
- * @return A new String object with the placeholder replaced by the values.
- */
- private String replaceParameters(String str, Map<String, Object> parameters) {
-
- if (parameters == null) {
- AdtPlugin.log(IStatus.ERROR,
- "NPW replace parameters: null parameter map. String: '%s'", str); //$NON-NLS-1$
- return str;
- } else if (str == null) {
- AdtPlugin.log(IStatus.ERROR,
- "NPW replace parameters: null template string"); //$NON-NLS-1$
- return str;
- }
-
- for (Entry<String, Object> entry : parameters.entrySet()) {
- if (entry != null && entry.getValue() instanceof String) {
- Object value = entry.getValue();
- if (value == null) {
- AdtPlugin.log(IStatus.ERROR,
- "NPW replace parameters: null value for key '%s' in template '%s'", //$NON-NLS-1$
- entry.getKey(),
- str);
- } else {
- str = str.replaceAll(entry.getKey(), (String) value);
- }
- }
- }
-
- return str;
- }
-
- private static class WorksetAdder implements Runnable {
- private final IJavaProject mProject;
- private final IWorkingSet[] mWorkingSets;
-
- private WorksetAdder(IJavaProject project, IWorkingSet[] workingSets) {
- mProject = project;
- mWorkingSets = workingSets;
- }
-
- @Override
- public void run() {
- if (mWorkingSets.length > 0 && mProject != null
- && mProject.exists()) {
- PlatformUI.getWorkbench().getWorkingSetManager()
- .addToWorkingSets(mProject, mWorkingSets);
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/NewProjectWizard.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/NewProjectWizard.java
deleted file mode 100644
index ff03b338f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/NewProjectWizard.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.newproject;
-
-import static com.android.SdkConstants.FN_PROJECT_PROGUARD_FILE;
-import static com.android.SdkConstants.OS_SDK_TOOLS_LIB_FOLDER;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.wizards.newproject.NewProjectWizardState.Mode;
-
-import org.eclipse.jdt.ui.actions.OpenJavaPerspectiveAction;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.ui.INewWizard;
-import org.eclipse.ui.IWorkbench;
-
-import java.io.File;
-
-
-/**
- * A "New Android Project" Wizard.
- * <p/>
- * Note: this class is public so that it can be accessed from unit tests.
- * It is however an internal class. Its API may change without notice.
- * It should semantically be considered as a private final class.
- * <p/>
- * Do not derive from this class.
- */
-public class NewProjectWizard extends Wizard implements INewWizard {
- private static final String PROJECT_LOGO_LARGE = "icons/android-64.png"; //$NON-NLS-1$
-
- private NewProjectWizardState mValues;
- private ProjectNamePage mNamePage;
- private SdkSelectionPage mSdkPage;
- private SampleSelectionPage mSamplePage;
- private ApplicationInfoPage mPropertiesPage;
- private final Mode mMode;
- private IStructuredSelection mSelection;
-
- /** Constructs a new wizard default project wizard */
- public NewProjectWizard() {
- this(Mode.ANY);
- }
-
- protected NewProjectWizard(Mode mode) {
- mMode = mode;
- switch (mMode) {
- case SAMPLE:
- setWindowTitle("New Android Sample Project");
- break;
- case TEST:
- setWindowTitle("New Android Test Project");
- break;
- default:
- setWindowTitle("New Android Project");
- break;
- }
- }
-
- @Override
- public void addPages() {
- mValues = new NewProjectWizardState(mMode);
-
- if (mMode != Mode.SAMPLE) {
- mNamePage = new ProjectNamePage(mValues);
-
- if (mSelection != null) {
- mNamePage.init(mSelection, AdtUtils.getActivePart());
- }
-
- addPage(mNamePage);
- }
-
- if (mMode == Mode.TEST) {
- addPage(new TestTargetPage(mValues));
- }
-
- mSdkPage = new SdkSelectionPage(mValues);
- addPage(mSdkPage);
-
- if (mMode != Mode.TEST) {
- // Sample projects can be created when entering the new/existing wizard, or
- // the sample wizard
- mSamplePage = new SampleSelectionPage(mValues);
- addPage(mSamplePage);
- }
-
- if (mMode != Mode.SAMPLE) {
- // Project properties are entered in all project types except sample projects
- mPropertiesPage = new ApplicationInfoPage(mValues);
- addPage(mPropertiesPage);
- }
- }
-
- @Override
- public void init(IWorkbench workbench, IStructuredSelection selection) {
- mSelection = selection;
-
- setHelpAvailable(false); // TODO have help
- ImageDescriptor desc = AdtPlugin.getImageDescriptor(PROJECT_LOGO_LARGE);
- setDefaultPageImageDescriptor(desc);
-
- // Trigger a check to see if the SDK needs to be reloaded (which will
- // invoke onSdkLoaded asynchronously as needed).
- AdtPlugin.getDefault().refreshSdk();
- }
-
- @Override
- public boolean performFinish() {
- File file = new File(AdtPlugin.getOsSdkFolder(), OS_SDK_TOOLS_LIB_FOLDER + File.separator
- + FN_PROJECT_PROGUARD_FILE);
- if (!file.exists()) {
- AdtPlugin.displayError("Tools Out of Date?",
- String.format("It looks like you do not have the latest version of the "
- + "SDK Tools installed. Make sure you update via the SDK Manager "
- + "first. (Could not find %1$s)", file.getPath()));
- return false;
- }
-
- NewProjectCreator creator = new NewProjectCreator(mValues, getContainer());
- if (!(creator.createAndroidProjects())) {
- return false;
- }
-
- // Open the default Java Perspective
- OpenJavaPerspectiveAction action = new OpenJavaPerspectiveAction();
- action.run();
- return true;
- }
-
- @Override
- public IWizardPage getNextPage(IWizardPage page) {
- if (page == mNamePage) {
- // Skip the test target selection page unless creating a test project
- if (mValues.mode != Mode.TEST) {
- return mSdkPage;
- }
- } else if (page == mSdkPage) {
- if (mValues.mode == Mode.SAMPLE) {
- return mSamplePage;
- } else if (mValues.mode != Mode.TEST) {
- return mPropertiesPage;
- } else {
- // Done with wizard when creating from existing or creating test projects
- return null;
- }
- } else if (page == mSamplePage) {
- // Nothing more to be entered for samples
- return null;
- }
-
- return super.getNextPage(page);
- }
-
- /**
- * Returns the package name currently set by the wizard
- *
- * @return the current package name, or null
- */
- public String getPackageName() {
- return mValues.packageName;
- }
-
- // TBD: Call setDialogSettings etc to store persistent state between wizard invocations.
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/NewProjectWizardState.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/NewProjectWizardState.java
deleted file mode 100644
index 06c0300b7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/NewProjectWizardState.java
+++ /dev/null
@@ -1,412 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.newproject;
-
-import com.android.SdkConstants;
-import com.android.annotations.Nullable;
-import com.android.ide.common.xml.ManifestData;
-import com.android.ide.common.xml.ManifestData.Activity;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.internal.project.AndroidManifestHelper;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.internal.project.ProjectProperties;
-import com.android.sdklib.internal.project.ProjectProperties.PropertyType;
-import com.android.utils.Pair;
-import com.android.xml.AndroidManifest;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.ui.IWorkingSet;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * The {@link NewProjectWizardState} holds the state used by the various pages
- * in the {@link NewProjectWizard} and its variations, and it can also be used
- * to pass project information to the {@link NewProjectCreator}.
- */
-public class NewProjectWizardState {
- /** The mode to run the wizard in: creating test, or sample, or plain project */
- public Mode mode;
-
- /**
- * If true, the project should be created from an existing codebase (pointed
- * to by the {@link #projectLocation} or in the case of sample projects, the
- * {@link #chosenSample}. Otherwise, create a brand new project from scratch.
- */
- public boolean useExisting;
-
- /**
- * Whether new projects should be created into the default project location
- * (e.g. in the Eclipse workspace) or not
- */
- public boolean useDefaultLocation = true;
-
- /** The build target SDK */
- public IAndroidTarget target;
- /** True if the user has manually modified the target */
- public boolean targetModifiedByUser;
-
- /** The location to store projects into */
- public File projectLocation = new File(Platform.getLocation().toOSString());
- /** True if the project location name has been manually edited by the user */
- public boolean projectLocationModifiedByUser;
-
- /** The name of the project */
- public String projectName = ""; //$NON-NLS-1$
- /** True if the project name has been manually edited by the user */
- public boolean projectNameModifiedByUser;
-
- /** The application name */
- public String applicationName;
- /** True if the application name has been manually edited by the user */
- public boolean applicationNameModifiedByUser;
-
- /** The package path */
- public String packageName;
- /** True if the package name has been manually edited by the user */
- public boolean packageNameModifiedByUser;
-
- /** True if a new activity should be created */
- public boolean createActivity;
-
- /** The name of the new activity to be created */
- public String activityName;
- /** True if the activity name has been manually edited by the user */
- public boolean activityNameModifiedByUser;
-
- /** The minimum SDK version to use with the project (may be null or blank) */
- public String minSdk;
- /** True if the minimum SDK version has been manually edited by the user */
- public boolean minSdkModifiedByUser;
- /**
- * A list of paths to each of the available samples for the current SDK.
- * The pair is (String: sample display name => File: sample directory).
- * Note we want a list, not a map since we might have duplicates.
- * */
- public List<Pair<String, File>> samples = new ArrayList<Pair<String, File>>();
- /** Path to the currently chosen sample */
- public File chosenSample;
-
- /** The name of the source folder, relative to the project root */
- public String sourceFolder = SdkConstants.FD_SOURCES;
- /** The set of chosen working sets to use when creating the project */
- public IWorkingSet[] workingSets = new IWorkingSet[0];
-
- /**
- * A reference to a different project that the current test project will be
- * testing.
- */
- public IProject testedProject;
- /**
- * If true, this test project should be testing itself, otherwise it will be
- * testing the project pointed to by {@link #testedProject}.
- */
- public boolean testingSelf;
-
- // NOTE: These apply only to creating paired projects; when isTest is true
- // we're using
- // the normal fields above
- /**
- * If true, create a test project along with this plain project which will
- * be testing the plain project. (This flag only applies when creating
- * normal projects.)
- */
- public boolean createPairProject;
- /**
- * The application name of the test application (only applies when
- * {@link #createPairProject} is true)
- */
- public String testApplicationName;
- /**
- * True if the testing application name has been modified by the user (only
- * applies when {@link #createPairProject} is true)
- */
- public boolean testApplicationNameModified;
- /**
- * The package name of the test application (only applies when
- * {@link #createPairProject} is true)
- */
- public String testPackageName;
- /**
- * True if the testing package name has been modified by the user (only
- * applies when {@link #createPairProject} is true)
- */
- public boolean testPackageModified;
- /**
- * The project name of the test project (only applies when
- * {@link #createPairProject} is true)
- */
- public String testProjectName;
- /**
- * True if the testing project name has been modified by the user (only
- * applies when {@link #createPairProject} is true)
- */
- public boolean testProjectModified;
- /** Package name of the tested app */
- public String testTargetPackageName;
-
- /**
- * Copy project into workspace? This flag only applies when importing
- * projects (creating projects from existing source)
- */
- public boolean copyIntoWorkspace;
-
- /**
- * List of projects to be imported. Null if not importing projects.
- */
- @Nullable
- public List<ImportedProject> importProjects;
-
- /**
- * Creates a new {@link NewProjectWizardState}
- *
- * @param mode the mode to run the wizard in
- */
- public NewProjectWizardState(Mode mode) {
- this.mode = mode;
- if (mode == Mode.SAMPLE) {
- useExisting = true;
- } else if (mode == Mode.TEST) {
- createActivity = false;
- }
- }
-
- /**
- * Extract information (package name, application name, minimum SDK etc) from
- * the given Android project.
- *
- * @param path the path to the project to extract information from
- */
- public void extractFromAndroidManifest(Path path) {
- String osPath = path.append(SdkConstants.FN_ANDROID_MANIFEST_XML).toOSString();
- if (!(new File(osPath).exists())) {
- return;
- }
-
- ManifestData manifestData = AndroidManifestHelper.parseForData(osPath);
- if (manifestData == null) {
- return;
- }
-
- String newPackageName = null;
- Activity activity = null;
- String newActivityName = null;
- String minSdkVersion = null;
- try {
- newPackageName = manifestData.getPackage();
- minSdkVersion = manifestData.getMinSdkVersionString();
-
- // try to get the first launcher activity. If none, just take the first activity.
- activity = manifestData.getLauncherActivity();
- if (activity == null) {
- Activity[] activities = manifestData.getActivities();
- if (activities != null && activities.length > 0) {
- activity = activities[0];
- }
- }
- } catch (Exception e) {
- // ignore exceptions
- }
-
- if (newPackageName != null && newPackageName.length() > 0) {
- packageName = newPackageName;
- }
-
- if (activity != null) {
- newActivityName = AndroidManifest.extractActivityName(activity.getName(),
- newPackageName);
- }
-
- if (newActivityName != null && newActivityName.length() > 0) {
- activityName = newActivityName;
- // we are "importing" an existing activity, not creating a new one
- createActivity = false;
-
- // If project name and application names are empty, use the activity
- // name as a default. If the activity name has dots, it's a part of a
- // package specification and only the last identifier must be used.
- if (newActivityName.indexOf('.') != -1) {
- String[] ids = newActivityName.split(AdtConstants.RE_DOT);
- newActivityName = ids[ids.length - 1];
- }
- if (projectName == null || projectName.length() == 0 ||
- !projectNameModifiedByUser) {
- projectName = newActivityName;
- projectNameModifiedByUser = false;
- }
- if (applicationName == null || applicationName.length() == 0 ||
- !applicationNameModifiedByUser) {
- applicationNameModifiedByUser = false;
- applicationName = newActivityName;
- }
- } else {
- activityName = ""; //$NON-NLS-1$
-
- // There is no activity name to use to fill in the project and application
- // name. However if there's a package name, we can use this as a base.
- if (newPackageName != null && newPackageName.length() > 0) {
- // Package name is a java identifier, so it's most suitable for
- // an application name.
-
- if (applicationName == null || applicationName.length() == 0 ||
- !applicationNameModifiedByUser) {
- applicationName = newPackageName;
- }
-
- // For the project name, remove any dots
- newPackageName = newPackageName.replace('.', '_');
- if (projectName == null || projectName.length() == 0 ||
- !projectNameModifiedByUser) {
- projectName = newPackageName;
- }
-
- }
- }
-
- if (mode == Mode.ANY && useExisting) {
- updateSdkTargetToMatchProject(path.toFile());
- }
-
- minSdk = minSdkVersion;
- minSdkModifiedByUser = false;
- }
-
- /**
- * Try to find an SDK Target that matches the current MinSdkVersion.
- *
- * There can be multiple targets with the same sdk api version, so don't change
- * it if it's already at the right version. Otherwise pick the first target
- * that matches.
- */
- public void updateSdkTargetToMatchMinSdkVersion() {
- IAndroidTarget currentTarget = target;
- if (currentTarget != null && currentTarget.getVersion().equals(minSdk)) {
- return;
- }
-
- Sdk sdk = Sdk.getCurrent();
- if (sdk != null) {
- IAndroidTarget[] targets = sdk.getTargets();
- for (IAndroidTarget t : targets) {
- if (t.getVersion().equals(minSdk)) {
- target = t;
- return;
- }
- }
- }
- }
-
- /**
- * Updates the SDK to reflect the SDK required by the project at the given
- * location
- *
- * @param location the location of the project
- */
- public void updateSdkTargetToMatchProject(File location) {
- // Select the target matching the manifest's sdk or build properties, if any
- IAndroidTarget foundTarget = null;
- // This is the target currently in the UI
- IAndroidTarget currentTarget = target;
- String projectPath = location.getPath();
-
- // If there's a current target defined, we do not allow to change it when
- // operating in the create-from-sample mode -- since the available sample list
- // is tied to the current target, so changing it would invalidate the project we're
- // trying to load in the first place.
- if (!targetModifiedByUser) {
- ProjectProperties p = ProjectProperties.load(projectPath,
- PropertyType.PROJECT);
- if (p != null) {
- String v = p.getProperty(ProjectProperties.PROPERTY_TARGET);
- IAndroidTarget desiredTarget = Sdk.getCurrent().getTargetFromHashString(v);
- // We can change the current target if:
- // - we found a new desired target
- // - there is no current target
- // - or the current target can't run the desired target
- if (desiredTarget != null &&
- (currentTarget == null || !desiredTarget.canRunOn(currentTarget))) {
- foundTarget = desiredTarget;
- }
- }
-
- Sdk sdk = Sdk.getCurrent();
- IAndroidTarget[] targets = null;
- if (sdk != null) {
- targets = sdk.getTargets();
- }
- if (targets == null) {
- targets = new IAndroidTarget[0];
- }
-
- if (foundTarget == null && minSdk != null) {
- // Otherwise try to match the requested min-sdk-version if we find an
- // exact match, regardless of the currently selected target.
- for (IAndroidTarget existingTarget : targets) {
- if (existingTarget != null &&
- existingTarget.getVersion().equals(minSdk)) {
- foundTarget = existingTarget;
- break;
- }
- }
- }
-
- if (foundTarget == null) {
- // Or last attempt, try to match a sample project location and use it
- // if we find an exact match, regardless of the currently selected target.
- for (IAndroidTarget existingTarget : targets) {
- if (existingTarget != null &&
- projectPath.startsWith(existingTarget.getLocation())) {
- foundTarget = existingTarget;
- break;
- }
- }
- }
- }
-
- if (foundTarget != null) {
- target = foundTarget;
- }
- }
-
- /**
- * Type of project being offered/created by the wizard
- */
- public enum Mode {
- /** Create a sample project. Testing options are not presented. */
- SAMPLE,
-
- /**
- * Create a test project, either testing itself or some other project.
- * Note that even if in the {@link #ANY} mode, a test project can be
- * created as a *paired* project with the main project, so this flag
- * only means that we are creating *just* a test project
- */
- TEST,
-
- /**
- * Create an Android project, which can be a plain project, optionally
- * with a paired test project, or a sample project (the first page
- * contains toggles for choosing which
- */
- ANY;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/NewSampleProjectWizard.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/NewSampleProjectWizard.java
deleted file mode 100644
index 6b6a4c29e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/NewSampleProjectWizard.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.newproject;
-
-import com.android.ide.eclipse.adt.internal.wizards.newproject.NewProjectWizardState.Mode;
-
-/**
- * A "New Sample Android Project" Wizard.
- * <p/>
- * This displays the new project wizard pre-configured for samples only.
- */
-public class NewSampleProjectWizard extends NewProjectWizard {
- /**
- * Creates a new wizard for creating a sample Android project
- */
- public NewSampleProjectWizard() {
- super(Mode.SAMPLE);
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/NewTestProjectWizard.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/NewTestProjectWizard.java
deleted file mode 100644
index e0959f4db..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/NewTestProjectWizard.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.newproject;
-
-import com.android.ide.eclipse.adt.internal.wizards.newproject.NewProjectWizardState.Mode;
-
-/**
- * A "New Test Android Project" Wizard.
- * <p/>
- * This is really the {@link NewProjectWizard} that only displays the "test project" pages.
- */
-public class NewTestProjectWizard extends NewProjectWizard {
- /**
- * Creates a new wizard for creating an Android Test Project
- */
- public NewTestProjectWizard() {
- super(Mode.TEST);
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/ProjectNamePage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/ProjectNamePage.java
deleted file mode 100644
index d04ea897f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/ProjectNamePage.java
+++ /dev/null
@@ -1,606 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.newproject;
-
-import static com.android.SdkConstants.FN_PROJECT_PROGUARD_FILE;
-import static com.android.SdkConstants.OS_SDK_TOOLS_LIB_FOLDER;
-import static com.android.ide.eclipse.adt.AdtUtils.capitalize;
-import static com.android.ide.eclipse.adt.internal.wizards.newproject.ApplicationInfoPage.ACTIVITY_NAME_SUFFIX;
-import static com.android.utils.SdkUtils.stripWhitespace;
-
-import com.android.SdkConstants;
-import com.android.ide.common.xml.ManifestData;
-import com.android.ide.common.xml.ManifestData.Activity;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.VersionCheck;
-import com.android.ide.eclipse.adt.internal.project.AndroidManifestHelper;
-import com.android.ide.eclipse.adt.internal.wizards.newproject.NewProjectWizardState.Mode;
-
-import org.eclipse.core.filesystem.URIUtil;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.osgi.util.TextProcessor;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.DirectoryDialog;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkingSet;
-
-import java.io.File;
-import java.net.URI;
-import java.util.Locale;
-
-/**
- * Initial page shown when creating projects which asks for the project name,
- * the the location of the project, working sets, etc.
- */
-public class ProjectNamePage extends WizardPage implements SelectionListener, ModifyListener {
- private final NewProjectWizardState mValues;
- /** Flag used when setting button/text state manually to ignore listener updates */
- private boolean mIgnore;
- /** Last user-browsed location, static so that it be remembered for the whole session */
- private static String sCustomLocationOsPath = ""; //$NON-NLS-1$
- private static boolean sAutoComputeCustomLocation = true;
-
- private Text mProjectNameText;
- private Text mLocationText;
- private Button mCreateSampleRadioButton;
- private Button mCreateNewButton;
- private Button mUseDefaultCheckBox;
- private Button mBrowseButton;
- private Label mLocationLabel;
- private WorkingSetGroup mWorkingSetGroup;
- /**
- * Whether we've made sure the Tools are up to date (enough that all the
- * resources required by the New Project wizard are present -- we don't
- * necessarily check for newer versions than that here; that's done by
- * {@link VersionCheck}, though that check doesn't <b>enforce</b> an update
- * since it needs to allow the user to proceed to access the SDK manager
- * etc.)
- */
- private boolean mCheckedSdkUptodate;
-
- /**
- * Create the wizard.
- * @param values current wizard state
- */
- ProjectNamePage(NewProjectWizardState values) {
- super("projectNamePage"); //$NON-NLS-1$
- mValues = values;
-
- setTitle("Create Android Project");
- setDescription("Select project name and type of project");
- mWorkingSetGroup = new WorkingSetGroup();
- setWorkingSets(new IWorkingSet[0]);
- }
-
- void init(IStructuredSelection selection, IWorkbenchPart activePart) {
- setWorkingSets(WorkingSetHelper.getSelectedWorkingSet(selection, activePart));
- }
-
- /**
- * Create contents of the wizard.
- * @param parent the parent to add the page to
- */
- @Override
- public void createControl(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
- container.setLayout(new GridLayout(3, false));
-
- Label nameLabel = new Label(container, SWT.NONE);
- nameLabel.setText("Project Name:");
-
- mProjectNameText = new Text(container, SWT.BORDER);
- mProjectNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
- mProjectNameText.addModifyListener(this);
-
- if (mValues.mode != Mode.TEST) {
- mCreateNewButton = new Button(container, SWT.RADIO);
- mCreateNewButton.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 3, 1));
- mCreateNewButton.setText("Create new project in workspace");
- mCreateNewButton.addSelectionListener(this);
-
- // TBD: Should we hide this completely, and make samples something you only invoke
- // from the "New Sample Project" wizard?
- mCreateSampleRadioButton = new Button(container, SWT.RADIO);
- mCreateSampleRadioButton.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false,
- 3, 1));
- mCreateSampleRadioButton.setText("Create project from existing sample");
- mCreateSampleRadioButton.addSelectionListener(this);
- }
-
- Label separator = new Label(container, SWT.SEPARATOR | SWT.HORIZONTAL);
- separator.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 3, 1));
-
- mUseDefaultCheckBox = new Button(container, SWT.CHECK);
- mUseDefaultCheckBox.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 3, 1));
- mUseDefaultCheckBox.setText("Use default location");
- mUseDefaultCheckBox.addSelectionListener(this);
-
- mLocationLabel = new Label(container, SWT.NONE);
- mLocationLabel.setText("Location:");
-
- mLocationText = new Text(container, SWT.BORDER);
- mLocationText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- mLocationText.addModifyListener(this);
-
- mBrowseButton = new Button(container, SWT.NONE);
- mBrowseButton.setText("Browse...");
- mBrowseButton.addSelectionListener(this);
-
- Composite group = mWorkingSetGroup.createControl(container);
- group.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 3, 1));
-
- setControl(container);
- }
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
-
- if (visible) {
- try {
- mIgnore = true;
- if (mValues.projectName != null) {
- mProjectNameText.setText(mValues.projectName);
- mProjectNameText.setFocus();
- }
- if (mValues.mode == Mode.ANY || mValues.mode == Mode.TEST) {
- if (mValues.useExisting) {
- assert false; // This is now handled by the separate import wizard
- } else if (mCreateNewButton != null) {
- mCreateNewButton.setSelection(true);
- }
- } else if (mValues.mode == Mode.SAMPLE) {
- mCreateSampleRadioButton.setSelection(true);
- }
- if (mValues.projectLocation != null) {
- mLocationText.setText(mValues.projectLocation.getPath());
- }
- mUseDefaultCheckBox.setSelection(mValues.useDefaultLocation);
- updateLocationState();
- } finally {
- mIgnore = false;
- }
- }
-
- validatePage();
- }
-
- @Override
- public void modifyText(ModifyEvent e) {
- if (mIgnore) {
- return;
- }
-
- Object source = e.getSource();
-
- if (source == mProjectNameText) {
- onProjectFieldModified();
- if (!mValues.useDefaultLocation && !mValues.projectLocationModifiedByUser) {
- updateLocationPathField(null);
- }
- } else if (source == mLocationText) {
- mValues.projectLocationModifiedByUser = true;
- if (!mValues.useDefaultLocation) {
- File f = new File(mLocationText.getText().trim());
- mValues.projectLocation = f;
- if (f.exists() && f.isDirectory() && !f.equals(mValues.projectLocation)) {
- updateLocationPathField(mValues.projectLocation.getPath());
- }
- }
- }
-
- validatePage();
- }
-
- private void onProjectFieldModified() {
- mValues.projectName = mProjectNameText.getText().trim();
- mValues.projectNameModifiedByUser = true;
-
- if (!mValues.applicationNameModifiedByUser) {
- mValues.applicationName = capitalize(mValues.projectName);
- if (!mValues.testApplicationNameModified) {
- mValues.testApplicationName =
- ApplicationInfoPage.suggestTestApplicationName(mValues.applicationName);
- }
- }
- if (!mValues.activityNameModifiedByUser) {
- String name = capitalize(mValues.projectName);
- mValues.activityName = stripWhitespace(name) + ACTIVITY_NAME_SUFFIX;
- }
- if (!mValues.testProjectModified) {
- mValues.testProjectName =
- ApplicationInfoPage.suggestTestProjectName(mValues.projectName);
- }
- if (!mValues.projectLocationModifiedByUser) {
- updateLocationPathField(null);
- }
- }
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (mIgnore) {
- return;
- }
-
- Object source = e.getSource();
-
- if (source == mCreateNewButton && mCreateNewButton != null
- && mCreateNewButton.getSelection()) {
- mValues.useExisting = false;
- if (mValues.mode == Mode.SAMPLE) {
- // Only reset the mode if we're toggling from sample back to create new
- // or create existing. We can only come to the sample state when we're in
- // ANY mode. (In particular, we don't want to switch to ANY if you're
- // in test mode.
- mValues.mode = Mode.ANY;
- }
- updateLocationState();
- } else if (source == mCreateSampleRadioButton && mCreateSampleRadioButton.getSelection()) {
- mValues.useExisting = true;
- mValues.useDefaultLocation = true;
- if (!mUseDefaultCheckBox.getSelection()) {
- try {
- mIgnore = true;
- mUseDefaultCheckBox.setSelection(true);
- } finally {
- mIgnore = false;
- }
- }
- mValues.mode = Mode.SAMPLE;
- updateLocationState();
- } else if (source == mUseDefaultCheckBox) {
- mValues.useDefaultLocation = mUseDefaultCheckBox.getSelection();
- updateLocationState();
- } else if (source == mBrowseButton) {
- onOpenDirectoryBrowser();
- }
-
- validatePage();
- }
-
- /**
- * Enables or disable the location widgets depending on the user selection:
- * the location path is enabled when using the "existing source" mode (i.e. not new project)
- * or in new project mode with the "use default location" turned off.
- */
- private void updateLocationState() {
- boolean isNewProject = !mValues.useExisting;
- boolean isCreateFromSample = mValues.mode == Mode.SAMPLE;
- boolean useDefault = mValues.useDefaultLocation && !isCreateFromSample;
- boolean locationEnabled = (!isNewProject || !useDefault) && !isCreateFromSample;
-
- mUseDefaultCheckBox.setEnabled(isNewProject);
- mLocationLabel.setEnabled(locationEnabled);
- mLocationText.setEnabled(locationEnabled);
- mBrowseButton.setEnabled(locationEnabled);
-
- updateLocationPathField(null);
- }
-
- /**
- * Display a directory browser and update the location path field with the selected path
- */
- private void onOpenDirectoryBrowser() {
-
- String existingDir = mLocationText.getText().trim();
-
- // Disable the path if it doesn't exist
- if (existingDir.length() == 0) {
- existingDir = null;
- } else {
- File f = new File(existingDir);
- if (!f.exists()) {
- existingDir = null;
- }
- }
-
- DirectoryDialog directoryDialog = new DirectoryDialog(mLocationText.getShell());
- directoryDialog.setMessage("Browse for folder");
- directoryDialog.setFilterPath(existingDir);
- String dir = directoryDialog.open();
-
- if (dir != null) {
- updateLocationPathField(dir);
- validatePage();
- }
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
-
- /**
- * Returns the working sets to which the new project should be added.
- *
- * @return the selected working sets to which the new project should be added
- */
- private IWorkingSet[] getWorkingSets() {
- return mWorkingSetGroup.getSelectedWorkingSets();
- }
-
- /**
- * Sets the working sets to which the new project should be added.
- *
- * @param workingSets the initial selected working sets
- */
- private void setWorkingSets(IWorkingSet[] workingSets) {
- assert workingSets != null;
- mWorkingSetGroup.setWorkingSets(workingSets);
- }
-
- /**
- * Updates the location directory path field.
- * <br/>
- * When custom user selection is enabled, use the absDir argument if not null and also
- * save it internally. If absDir is null, restore the last saved absDir. This allows the
- * user selection to be remembered when the user switches from default to custom.
- * <br/>
- * When custom user selection is disabled, use the workspace default location with the
- * current project name. This does not change the internally cached absDir.
- *
- * @param absDir A new absolute directory path or null to use the default.
- */
- private void updateLocationPathField(String absDir) {
- boolean isNewProject = !mValues.useExisting || mValues.mode == Mode.SAMPLE;
- boolean useDefault = mValues.useDefaultLocation;
- boolean customLocation = !isNewProject || !useDefault;
-
- if (!mIgnore) {
- try {
- mIgnore = true;
- if (customLocation) {
- if (absDir != null) {
- // We get here if the user selected a directory with the "Browse" button.
- // Disable auto-compute of the custom location unless the user selected
- // the exact same path.
- sAutoComputeCustomLocation = sAutoComputeCustomLocation &&
- absDir.equals(sCustomLocationOsPath);
- sCustomLocationOsPath = TextProcessor.process(absDir);
- } else if (sAutoComputeCustomLocation ||
- (!isNewProject && !new File(sCustomLocationOsPath).isDirectory())) {
- // As a default import location, just suggest the home directory; the user
- // needs to point to a project to import.
- // TODO: Open file chooser automatically?
- sCustomLocationOsPath = System.getProperty("user.home"); //$NON-NLS-1$
- }
- if (!mLocationText.getText().equals(sCustomLocationOsPath)) {
- mLocationText.setText(sCustomLocationOsPath);
- mValues.projectLocation = new File(sCustomLocationOsPath);
- }
- } else {
- String value = Platform.getLocation().append(mValues.projectName).toString();
- value = TextProcessor.process(value);
- if (!mLocationText.getText().equals(value)) {
- mLocationText.setText(value);
- mValues.projectLocation = new File(value);
- }
- }
- } finally {
- mIgnore = false;
- }
- }
-
- if (mValues.useExisting && mValues.projectLocation != null
- && mValues.projectLocation.exists() && mValues.mode != Mode.SAMPLE) {
- mValues.extractFromAndroidManifest(new Path(mValues.projectLocation.getPath()));
- if (!mValues.projectNameModifiedByUser && mValues.projectName != null) {
- try {
- mIgnore = true;
- mProjectNameText.setText(mValues.projectName);
- } finally {
- mIgnore = false;
- }
- }
- }
- }
-
- private void validatePage() {
- IStatus status = null;
-
- // Validate project name -- unless we're creating a sample, in which case
- // the user will get a chance to pick the name on the Sample page
- if (mValues.mode != Mode.SAMPLE) {
- status = validateProjectName(mValues.projectName);
- }
-
- if (status == null || status.getSeverity() != IStatus.ERROR) {
- IStatus validLocation = validateLocation();
- if (validLocation != null) {
- status = validLocation;
- }
- }
-
- if (!mCheckedSdkUptodate) {
- // Ensure that we have a recent enough version of the Tools that the right templates
- // are available
- File file = new File(AdtPlugin.getOsSdkFolder(), OS_SDK_TOOLS_LIB_FOLDER
- + File.separator + FN_PROJECT_PROGUARD_FILE);
- if (!file.exists()) {
- status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- String.format("You do not have the latest version of the "
- + "SDK Tools installed: Please update. (Missing %1$s)", file.getPath()));
- } else {
- mCheckedSdkUptodate = true;
- }
- }
-
- // -- update UI & enable finish if there's no error
- setPageComplete(status == null || status.getSeverity() != IStatus.ERROR);
- if (status != null) {
- setMessage(status.getMessage(),
- status.getSeverity() == IStatus.ERROR
- ? IMessageProvider.ERROR : IMessageProvider.WARNING);
- } else {
- setErrorMessage(null);
- setMessage(null);
- }
- }
-
- private IStatus validateLocation() {
- if (mValues.mode == Mode.SAMPLE) {
- // Samples are always created in the default directory
- return null;
- }
-
- // Validate location
- Path path = new Path(mValues.projectLocation.getPath());
- if (!mValues.useExisting) {
- if (!mValues.useDefaultLocation) {
- // If not using the default value validate the location.
- URI uri = URIUtil.toURI(path.toOSString());
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IProject handle = workspace.getRoot().getProject(mValues.projectName);
- IStatus locationStatus = workspace.validateProjectLocationURI(handle, uri);
- if (!locationStatus.isOK()) {
- return locationStatus;
- }
- // The location is valid as far as Eclipse is concerned (i.e. mostly not
- // an existing workspace project.) Check it either doesn't exist or is
- // a directory that is empty.
- File f = path.toFile();
- if (f.exists() && !f.isDirectory()) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "A directory name must be specified.");
- } else if (f.isDirectory()) {
- // However if the directory exists, we should put a
- // warning if it is not empty. We don't put an error
- // (we'll ask the user again for confirmation before
- // using the directory.)
- String[] l = f.list();
- if (l != null && l.length != 0) {
- return new Status(IStatus.WARNING, AdtPlugin.PLUGIN_ID,
- "The selected output directory is not empty.");
- }
- }
- } else {
- // Otherwise validate the path string is not empty
- if (mValues.projectLocation.getPath().length() == 0) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "A directory name must be specified.");
- }
- File dest = path.toFile();
- if (dest.exists()) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- String.format(
- "There is already a file or directory named \"%1$s\" in the selected location.",
- mValues.projectName));
- }
- }
- } else {
- // Must be an existing directory
- File f = path.toFile();
- if (!f.isDirectory()) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "An existing directory name must be specified.");
- }
-
- // Check there's an android manifest in the directory
- String osPath = path.append(SdkConstants.FN_ANDROID_MANIFEST_XML).toOSString();
- File manifestFile = new File(osPath);
- if (!manifestFile.isFile()) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- String.format(
- "Choose a valid Android code directory\n" +
- "(%1$s not found in %2$s.)",
- SdkConstants.FN_ANDROID_MANIFEST_XML, f.getName()));
- }
-
- // Parse it and check the important fields.
- ManifestData manifestData = AndroidManifestHelper.parseForData(osPath);
- if (manifestData == null) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- String.format("File %1$s could not be parsed.", osPath));
- }
- String packageName = manifestData.getPackage();
- if (packageName == null || packageName.length() == 0) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- String.format("No package name defined in %1$s.", osPath));
- }
- Activity[] activities = manifestData.getActivities();
- if (activities == null || activities.length == 0) {
- // This is acceptable now as long as no activity needs to be
- // created
- if (mValues.createActivity) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- String.format("No activity name defined in %1$s.", osPath));
- }
- }
-
- // If there's already a .project, tell the user to use import instead.
- if (path.append(".project").toFile().exists()) { //$NON-NLS-1$
- return new Status(IStatus.WARNING, AdtPlugin.PLUGIN_ID,
- "An Eclipse project already exists in this directory.\n" +
- "Consider using File > Import > Existing Project instead.");
- }
- }
-
- return null;
- }
-
- public static IStatus validateProjectName(String projectName) {
- if (projectName == null || projectName.length() == 0) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "Project name must be specified");
- } else {
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IStatus nameStatus = workspace.validateName(projectName, IResource.PROJECT);
- if (!nameStatus.isOK()) {
- return nameStatus;
- } else {
- // Note: the case-sensitiveness of the project name matters and can cause a
- // conflict *later* when creating the project resource, so let's check it now.
- for (IProject existingProj : workspace.getRoot().getProjects()) {
- if (projectName.equalsIgnoreCase(existingProj.getName())) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "A project with that name already exists in the workspace");
- }
- }
- }
- }
-
- return null;
- }
-
- @Override
- public IWizardPage getNextPage() {
- // Sync working set data to the value object, since the WorkingSetGroup
- // doesn't let us add listeners to do this lazily
- mValues.workingSets = getWorkingSets();
-
- return super.getNextPage();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/SampleSelectionPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/SampleSelectionPage.java
deleted file mode 100644
index 197247083..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/SampleSelectionPage.java
+++ /dev/null
@@ -1,271 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.newproject;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.wizards.newproject.NewProjectWizardState.Mode;
-import com.android.sdklib.IAndroidTarget;
-import com.android.utils.Pair;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.viewers.ArrayContentProvider;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.IBaseLabelProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.Text;
-
-import java.io.File;
-
-/** Page where the user can select a sample to "instantiate" */
-class SampleSelectionPage extends WizardPage implements SelectionListener, ModifyListener {
- private final NewProjectWizardState mValues;
- private boolean mIgnore;
-
- private Table mTable;
- private TableViewer mTableViewer;
- private IAndroidTarget mCurrentSamplesTarget;
- private Text mSampleProjectName;
-
- /**
- * Create the wizard.
- */
- SampleSelectionPage(NewProjectWizardState values) {
- super("samplePage"); //$NON-NLS-1$
- setTitle("Select Sample");
- setDescription("Select which sample to create");
- mValues = values;
- }
-
- /**
- * Create contents of the wizard.
- */
- @Override
- public void createControl(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
- container.setLayout(new GridLayout(2, false));
-
- mTableViewer = new TableViewer(container, SWT.BORDER | SWT.FULL_SELECTION);
- mTable = mTableViewer.getTable();
- GridData gridData = new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1);
- gridData.heightHint = 300;
- mTable.setLayoutData(gridData);
- mTable.addSelectionListener(this);
-
- setControl(container);
-
- Label projectLabel = new Label(container, SWT.NONE);
- projectLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- projectLabel.setText("Project Name:");
-
- mSampleProjectName = new Text(container, SWT.BORDER);
- mSampleProjectName.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- mSampleProjectName.addModifyListener(this);
- }
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
-
- if (visible) {
- if (mValues.projectName != null) {
- try {
- mIgnore = true;
- mSampleProjectName.setText(mValues.projectName);
- } finally {
- mIgnore = false;
- }
- }
-
- // Update samples list if the SDK target has changed (or if it hasn't yet
- // been populated)
- if (mCurrentSamplesTarget != mValues.target) {
- mCurrentSamplesTarget = mValues.target;
- updateSamples();
- }
-
- validatePage();
- }
- }
-
- private void updateSamples() {
- IBaseLabelProvider labelProvider = new ColumnLabelProvider() {
- @Override
- public Image getImage(Object element) {
- return AdtPlugin.getAndroidLogo();
- }
-
- @Override
- public String getText(Object element) {
- if (element instanceof Pair<?, ?>) {
- Object name = ((Pair<?, ?>) element).getFirst();
- return name.toString();
- }
- return element.toString(); // Fallback. Should not happen.
- }
- };
-
- mTableViewer.setContentProvider(new ArrayContentProvider());
- mTableViewer.setLabelProvider(labelProvider);
-
- if (mValues.samples != null && mValues.samples.size() > 0) {
- Object[] samples = mValues.samples.toArray();
- mTableViewer.setInput(samples);
-
- mTable.select(0);
- selectSample(mValues.samples.get(0).getSecond());
- extractNamesFromAndroidManifest();
- }
- }
-
- private void selectSample(File sample) {
- mValues.chosenSample = sample;
- if (sample != null && !mValues.projectNameModifiedByUser) {
- mValues.projectName = sample.getName();
- if (SdkConstants.FD_SAMPLE.equals(mValues.projectName) &&
- sample.getParentFile() != null) {
- mValues.projectName = sample.getParentFile().getName() + '_' + mValues.projectName;
- }
- try {
- mIgnore = true;
- mSampleProjectName.setText(mValues.projectName);
- } finally {
- mIgnore = false;
- }
- updatedProjectName();
- }
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (mIgnore) {
- return;
- }
-
- if (e.getSource() == mTable) {
- extractNamesFromAndroidManifest();
- int index = mTable.getSelectionIndex();
- if (index >= 0) {
- Object[] roots = (Object[]) mTableViewer.getInput();
- selectSample(((Pair<String, File>) roots[index]).getSecond());
- } else {
- selectSample(null);
- }
- } else {
- assert false : e.getSource();
- }
-
- validatePage();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
-
- @Override
- public void modifyText(ModifyEvent e) {
- if (mIgnore) {
- return;
- }
-
- if (e.getSource() == mSampleProjectName) {
- mValues.projectName = mSampleProjectName.getText().trim();
- mValues.projectNameModifiedByUser = true;
- updatedProjectName();
- }
-
- validatePage();
- }
-
- private void updatedProjectName() {
- if (mValues.useDefaultLocation) {
- mValues.projectLocation = Platform.getLocation().toFile();
- }
- }
-
- /**
- * A sample was selected. Update the location field, manifest and validate.
- * Extract names from an android manifest.
- * This is done only if the user selected the "use existing source" and a manifest xml file
- * can actually be found in the custom user directory.
- */
- private void extractNamesFromAndroidManifest() {
- if (mValues.chosenSample == null || !mValues.chosenSample.isDirectory()) {
- return;
- }
-
- Path path = new Path(mValues.chosenSample.getPath());
- mValues.extractFromAndroidManifest(path);
- }
-
- @Override
- public boolean isPageComplete() {
- if (mValues.mode != Mode.SAMPLE) {
- return true;
- }
-
- // Ensure that when creating samples, the Finish button isn't enabled until
- // the user has reached and completed this page
- if (mValues.chosenSample == null) {
- return false;
- }
-
- return super.isPageComplete();
- }
-
- private void validatePage() {
- IStatus status = null;
- if (mValues.samples == null || mValues.samples.size() == 0) {
- status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "The chosen SDK does not contain any samples");
- } else if (mValues.chosenSample == null) {
- status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, "Choose a sample");
- } else if (!mValues.chosenSample.exists()) {
- status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- String.format("Sample does not exist: %1$s", mValues.chosenSample.getPath()));
- } else {
- status = ProjectNamePage.validateProjectName(mValues.projectName);
- }
-
- // -- update UI & enable finish if there's no error
- setPageComplete(status == null || status.getSeverity() != IStatus.ERROR);
- if (status != null) {
- setMessage(status.getMessage(),
- status.getSeverity() == IStatus.ERROR
- ? IMessageProvider.ERROR : IMessageProvider.WARNING);
- } else {
- setErrorMessage(null);
- setMessage(null);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/SdkSelectionPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/SdkSelectionPage.java
deleted file mode 100644
index 6cafcf057..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/SdkSelectionPage.java
+++ /dev/null
@@ -1,487 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.newproject;
-
-import com.android.SdkConstants;
-import com.android.annotations.Nullable;
-import com.android.ide.common.sdk.LoadStatus;
-import com.android.ide.common.xml.AndroidManifestParser;
-import com.android.ide.common.xml.ManifestData;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk.ITargetChangeListener;
-import com.android.ide.eclipse.adt.internal.wizards.newproject.NewProjectWizardState.Mode;
-import com.android.io.FileWrapper;
-import com.android.sdklib.AndroidVersion;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.SdkManager;
-import com.android.sdkuilib.internal.widgets.SdkTargetSelector;
-import com.android.utils.NullLogger;
-import com.android.utils.Pair;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Group;
-
-import java.io.File;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.regex.Pattern;
-
-/** A page in the New Project wizard where you select the target SDK */
-class SdkSelectionPage extends WizardPage implements ITargetChangeListener {
- private final NewProjectWizardState mValues;
- private boolean mIgnore;
- private SdkTargetSelector mSdkTargetSelector;
-
- /**
- * Create the wizard.
- */
- SdkSelectionPage(NewProjectWizardState values) {
- super("sdkSelection"); //$NON-NLS-1$
- mValues = values;
-
- setTitle("Select Build Target");
- AdtPlugin.getDefault().addTargetListener(this);
- }
-
- @Override
- public void dispose() {
- AdtPlugin.getDefault().removeTargetListener(this);
- super.dispose();
- }
-
- /**
- * Create contents of the wizard.
- */
- @Override
- public void createControl(Composite parent) {
- Group group = new Group(parent, SWT.SHADOW_ETCHED_IN);
- // Layout has 1 column
- group.setLayout(new GridLayout());
- group.setLayoutData(new GridData(GridData.FILL_BOTH));
- group.setFont(parent.getFont());
- group.setText("Build Target");
-
- // The selector is created without targets. They are added below in the change listener.
- mSdkTargetSelector = new SdkTargetSelector(group, null);
-
- mSdkTargetSelector.setSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (mIgnore) {
- return;
- }
-
- mValues.target = mSdkTargetSelector.getSelected();
- mValues.targetModifiedByUser = true;
- onSdkTargetModified();
- validatePage();
- }
- });
-
- onSdkLoaded();
-
- setControl(group);
- }
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- if (mValues.mode == Mode.SAMPLE) {
- setDescription("Choose an SDK to select a sample from");
- } else {
- setDescription("Choose an SDK to target");
- }
- try {
- mIgnore = true;
- if (mValues.target != null) {
- mSdkTargetSelector.setSelection(mValues.target);
- }
- } finally {
- mIgnore = false;
- }
-
- validatePage();
- }
-
- @Override
- public boolean isPageComplete() {
- // Ensure that the Finish button isn't enabled until
- // the user has reached and completed this page
- if (mValues.target == null) {
- return false;
- }
-
- return super.isPageComplete();
- }
-
- /**
- * Called when an SDK target is modified.
- *
- * Also changes the minSdkVersion field to reflect the sdk api level that has
- * just been selected.
- */
- private void onSdkTargetModified() {
- if (mIgnore) {
- return;
- }
-
- IAndroidTarget target = mValues.target;
-
- // Update the minimum SDK text field?
- // We do if one of two conditions are met:
- if (target != null) {
- boolean setMinSdk = false;
- AndroidVersion version = target.getVersion();
- int apiLevel = version.getApiLevel();
- // 1. Has the user not manually edited the SDK field yet? If so, keep
- // updating it to the selected value.
- if (!mValues.minSdkModifiedByUser) {
- setMinSdk = true;
- } else {
- // 2. Is the API level set to a higher level than the newly selected
- // target SDK? If so, change it down to the new lower value.
- String s = mValues.minSdk;
- if (s.length() > 0) {
- try {
- int currentApi = Integer.parseInt(s);
- if (currentApi > apiLevel) {
- setMinSdk = true;
- }
- } catch (NumberFormatException nfe) {
- // User may have typed something invalid -- ignore
- }
- }
- }
- if (setMinSdk) {
- String minSdk;
- if (version.isPreview()) {
- minSdk = version.getCodename();
- } else {
- minSdk = Integer.toString(apiLevel);
- }
- mValues.minSdk = minSdk;
- }
- }
-
- loadSamplesForTarget(target);
- }
-
- /**
- * Updates the list of all samples for the given target SDK.
- * The list is stored in mSamplesPaths as absolute directory paths.
- * The combo is recreated to match this.
- */
- private void loadSamplesForTarget(IAndroidTarget target) {
- // Keep the name of the old selection (if there were any samples)
- File previouslyChosenSample = mValues.chosenSample;
-
- mValues.samples.clear();
- mValues.chosenSample = null;
-
- if (target != null) {
- // Get the sample root path and recompute the list of samples
- String samplesRootPath = target.getPath(IAndroidTarget.SAMPLES);
-
- File root = new File(samplesRootPath);
- findSamplesManifests(root, root, null, null, mValues.samples);
-
- Sdk sdk = Sdk.getCurrent();
- if (sdk != null) {
- // Parse the extras to see if we can find samples that are
- // compatible with the selected target API.
- // First we need an SdkManager that suppresses all output.
- SdkManager sdkman = sdk.getNewSdkManager(NullLogger.getLogger());
-
- Map<File, String> extras = sdkman.getExtraSamples();
- for (Entry<File, String> entry : extras.entrySet()) {
- File path = entry.getKey();
- String name = entry.getValue();
-
- // Case where the sample is at the root of the directory and not
- // in a per-sample sub-directory.
- if (path.getName().equals(SdkConstants.FD_SAMPLE)) {
- findSampleManifestInDir(
- path, path, name, target.getVersion(), mValues.samples);
- }
-
- // Scan sub-directories
- findSamplesManifests(
- path, path, name, target.getVersion(), mValues.samples);
- }
- }
-
- if (mValues.samples.isEmpty()) {
- return;
- } else {
- Collections.sort(mValues.samples, new Comparator<Pair<String, File>>() {
- @Override
- public int compare(Pair<String, File> o1, Pair<String, File> o2) {
- // Compare the display name of the sample
- return o1.getFirst().compareTo(o2.getFirst());
- }
- });
- }
-
- // Try to find the old selection.
- if (previouslyChosenSample != null) {
- String previouslyChosenName = previouslyChosenSample.getName();
- for (int i = 0, n = mValues.samples.size(); i < n; i++) {
- File file = mValues.samples.get(i).getSecond();
- if (file.getName().equals(previouslyChosenName)) {
- mValues.chosenSample = file;
- break;
- }
- }
- }
- }
- }
-
- /**
- * Recursively find potential sample directories under the given directory.
- * Actually lists any directory that contains an android manifest.
- * Paths found are added the samplesPaths list.
- *
- * @param rootDir The "samples" root directory. Doesn't change during recursion.
- * @param currDir The directory being scanned. Caller must initially set it to {@code rootDir}.
- * @param extraName Optional name appended to the samples display name. Typically used to
- * indicate a sample comes from a given extra package.
- * @param targetVersion Optional target version filter. If non null, only samples that are
- * compatible with the given target will be listed.
- * @param samplesPaths A non-null list filled by this method with all samples found. The
- * pair is (String: sample display name => File: sample directory).
- */
- private void findSamplesManifests(
- File rootDir,
- File currDir,
- @Nullable String extraName,
- @Nullable AndroidVersion targetVersion,
- List<Pair<String, File>> samplesPaths) {
- if (!currDir.isDirectory()) {
- return;
- }
-
- for (File f : currDir.listFiles()) {
- if (f.isDirectory()) {
- findSampleManifestInDir(f, rootDir, extraName, targetVersion, samplesPaths);
-
- // Recurse in the project, to find embedded tests sub-projects
- // We can however skip this recursion for known android sub-dirs that
- // can't have projects, namely for sources, assets and resources.
- String leaf = f.getName();
- if (!SdkConstants.FD_SOURCES.equals(leaf) &&
- !SdkConstants.FD_ASSETS.equals(leaf) &&
- !SdkConstants.FD_RES.equals(leaf)) {
- findSamplesManifests(rootDir, f, extraName, targetVersion, samplesPaths);
- }
- }
- }
- }
-
- private void findSampleManifestInDir(
- File sampleDir,
- File rootDir,
- String extraName,
- AndroidVersion targetVersion,
- List<Pair<String, File>> samplesPaths) {
- // Assume this is a sample if it contains an android manifest.
- File manifestFile = new File(sampleDir, SdkConstants.FN_ANDROID_MANIFEST_XML);
- if (manifestFile.isFile()) {
- try {
- ManifestData data =
- AndroidManifestParser.parse(new FileWrapper(manifestFile));
- if (data != null) {
- boolean accept = false;
- if (targetVersion == null) {
- accept = true;
- } else if (targetVersion != null) {
- int i = data.getMinSdkVersion();
- if (i != ManifestData.MIN_SDK_CODENAME) {
- accept = i <= targetVersion.getApiLevel();
- } else {
- String s = data.getMinSdkVersionString();
- if (s != null) {
- accept = s.equals(targetVersion.getCodename());
- }
- }
- }
-
- if (accept) {
- String name = getSampleDisplayName(extraName, rootDir, sampleDir);
- samplesPaths.add(Pair.of(name, sampleDir));
- }
- }
- } catch (Exception e) {
- // Ignore. Don't use a sample which manifest doesn't parse correctly.
- AdtPlugin.log(IStatus.INFO,
- "NPW ignoring malformed manifest %s", //$NON-NLS-1$
- manifestFile.getAbsolutePath());
- }
- }
- }
-
- /**
- * Compute the sample name compared to its root directory.
- */
- private String getSampleDisplayName(String extraName, File rootDir, File sampleDir) {
- String name = null;
- if (!rootDir.equals(sampleDir)) {
- String path = sampleDir.getPath();
- int n = rootDir.getPath().length();
- if (path.length() > n) {
- path = path.substring(n);
- if (path.charAt(0) == File.separatorChar) {
- path = path.substring(1);
- }
- if (path.endsWith(File.separator)) {
- path = path.substring(0, path.length() - 1);
- }
- name = path.replaceAll(Pattern.quote(File.separator), " > "); //$NON-NLS-1$
- }
- }
- if (name == null &&
- rootDir.equals(sampleDir) &&
- sampleDir.getName().equals(SdkConstants.FD_SAMPLE) &&
- extraName != null) {
- // This is an old-style extra with one single sample directory. Just use the
- // extra's name as the same name.
- return extraName;
- }
- if (name == null) {
- // Otherwise try to use the sample's directory name as the sample name.
- while (sampleDir != null &&
- (name == null ||
- SdkConstants.FD_SAMPLE.equals(name) ||
- SdkConstants.FD_SAMPLES.equals(name))) {
- name = sampleDir.getName();
- sampleDir = sampleDir.getParentFile();
- }
- }
- if (name == null) {
- if (extraName != null) {
- // In the unlikely case nothing worked and we have an extra name, use that.
- return extraName;
- } else {
- name = "Sample"; // fallback name... should not happen. //$NON-NLS-1$
- }
- }
- if (extraName != null) {
- name = name + " [" + extraName + ']'; //$NON-NLS-1$
- }
-
- return name;
- }
-
- private void validatePage() {
- String error = null;
-
- if (AdtPlugin.getDefault().getSdkLoadStatus() == LoadStatus.LOADING) {
- error = "The SDK is still loading; please wait.";
- }
-
- if (error == null && mValues.target == null) {
- error = "An SDK Target must be specified.";
- }
-
- if (error == null && mValues.mode == Mode.SAMPLE) {
- // Make sure this SDK target contains samples
- if (mValues.samples == null || mValues.samples.size() == 0) {
- error = "This target has no samples. Please select another target.";
- }
- }
-
- // -- update UI & enable finish if there's no error
- setPageComplete(error == null);
- if (error != null) {
- setMessage(error, IMessageProvider.ERROR);
- } else {
- setErrorMessage(null);
- setMessage(null);
- }
- }
-
- // ---- Implements ITargetChangeListener ----
- @Override
- public void onSdkLoaded() {
- if (mSdkTargetSelector == null) {
- return;
- }
-
- // Update the sdk target selector with the new targets
-
- // get the targets from the sdk
- IAndroidTarget[] targets = null;
- if (Sdk.getCurrent() != null) {
- targets = Sdk.getCurrent().getTargets();
- }
- mSdkTargetSelector.setTargets(targets);
-
- // If there's only one target, select it.
- // This will invoke the selection listener on the selector defined above.
- if (targets != null && targets.length == 1) {
- mValues.target = targets[0];
- mSdkTargetSelector.setSelection(mValues.target);
- onSdkTargetModified();
- } else if (targets != null) {
- // Pick the highest available platform by default (see issue #17505
- // for related discussion.)
- IAndroidTarget initialTarget = null;
- for (IAndroidTarget target : targets) {
- if (target.isPlatform()
- && !target.getVersion().isPreview()
- && (initialTarget == null ||
- target.getVersion().getApiLevel() >
- initialTarget.getVersion().getApiLevel())) {
- initialTarget = target;
- }
- }
- if (initialTarget != null) {
- mValues.target = initialTarget;
- try {
- mIgnore = true;
- mSdkTargetSelector.setSelection(mValues.target);
- } finally {
- mIgnore = false;
- }
- onSdkTargetModified();
- }
- }
-
- validatePage();
- }
-
- @Override
- public void onProjectTargetChange(IProject changedProject) {
- // Ignore
- }
-
- @Override
- public void onTargetLoaded(IAndroidTarget target) {
- // Ignore
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/TestTargetPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/TestTargetPage.java
deleted file mode 100644
index f1c188ae9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/TestTargetPage.java
+++ /dev/null
@@ -1,293 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.newproject;
-
-import com.android.ide.common.xml.ManifestData;
-import com.android.ide.eclipse.adt.internal.project.AndroidManifestHelper;
-import com.android.ide.eclipse.adt.internal.project.ProjectChooserHelper;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.sdklib.IAndroidTarget;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.jdt.core.IJavaModel;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.ui.JavaElementLabelProvider;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.viewers.ILabelProvider;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.dialogs.FilteredList;
-
-/**
- * Page shown when creating a test project which lets you choose between testing
- * yourself and testing a different project
- */
-class TestTargetPage extends WizardPage implements SelectionListener {
- private final NewProjectWizardState mValues;
- /** Flag used when setting button/text state manually to ignore listener updates */
- private boolean mIgnore;
- private String mLastExistingPackageName;
-
- private Button mCurrentRadioButton;
- private Button mExistingRadioButton;
- private FilteredList mProjectList;
- private boolean mPageShown;
-
- /**
- * Create the wizard.
- */
- TestTargetPage(NewProjectWizardState values) {
- super("testTargetPage"); //$NON-NLS-1$
- setTitle("Select Test Target");
- setDescription("Choose a project to test");
- mValues = values;
- }
-
- /**
- * Create contents of the wizard.
- */
- @Override
- public void createControl(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
-
- setControl(container);
- container.setLayout(new GridLayout(2, false));
-
- mCurrentRadioButton = new Button(container, SWT.RADIO);
- mCurrentRadioButton.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
- mCurrentRadioButton.setText("This project");
- mCurrentRadioButton.addSelectionListener(this);
-
- mExistingRadioButton = new Button(container, SWT.RADIO);
- mExistingRadioButton.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
- mExistingRadioButton.setText("An existing Android project:");
- mExistingRadioButton.addSelectionListener(this);
-
- ILabelProvider labelProvider = new JavaElementLabelProvider(
- JavaElementLabelProvider.SHOW_DEFAULT);
- mProjectList = new FilteredList(container,
- SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL | SWT.SINGLE, labelProvider,
- true /*ignoreCase*/, false /*allowDuplicates*/, true /* matchEmptyString*/);
- mProjectList.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
- mProjectList.addSelectionListener(this);
- }
-
- private void initializeList() {
- ProjectChooserHelper helper = new ProjectChooserHelper(getShell(), null /*filter*/);
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
- IJavaModel javaModel = JavaCore.create(workspaceRoot);
- IJavaProject[] androidProjects = helper.getAndroidProjects(javaModel);
- mProjectList.setElements(androidProjects);
- if (mValues.testedProject != null) {
- for (IJavaProject project : androidProjects) {
- if (project.getProject() == mValues.testedProject) {
- mProjectList.setSelection(new Object[] { project });
- break;
- }
- }
- } else {
- // No initial selection: force the user to choose
- mProjectList.setSelection(new int[0]);
- }
- }
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- mPageShown = true;
-
- if (visible) {
- try {
- mIgnore = true;
- mCurrentRadioButton.setSelection(mValues.testingSelf);
- mExistingRadioButton.setSelection(!mValues.testingSelf);
- mProjectList.setEnabled(!mValues.testingSelf);
-
- if (mProjectList.isEmpty()) {
- initializeList();
- }
- if (!mValues.testingSelf) {
- mProjectList.setFocus();
- IProject project = getSelectedProject();
- if (project != null) {
- // The FilteredList seems to -insist- on selecting the first item
- // in the list, even when the selection is explicitly set to an empty
- // array. This means the user is looking at a selection, so we need
- // to also go ahead and select this item in the model such that the
- // two agree, even if we would have preferred to have no initial
- // selection.
- mValues.testedProject = project;
- }
- }
- } finally {
- mIgnore = false;
- }
- }
-
- validatePage();
- }
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (mIgnore) {
- return;
- }
-
- Object source = e.getSource();
- if (source == mExistingRadioButton) {
- mProjectList.setEnabled(true);
- mValues.testingSelf = false;
- setExistingProject(getSelectedProject());
- mProjectList.setFocus();
- } else if (source == mCurrentRadioButton) {
- mProjectList.setEnabled(false);
- mValues.testingSelf = true;
- mValues.testedProject = null;
- } else {
- // The event must be from the project list, which unfortunately doesn't
- // pass itself as the selection event, it passes a reference to some internal
- // table widget that it uses, so we check for this case last
- IProject project = getSelectedProject();
- if (project != mValues.testedProject) {
- setExistingProject(project);
- }
- }
-
- validatePage();
- }
-
- private IProject getSelectedProject() {
- Object[] selection = mProjectList.getSelection();
- IProject project = selection != null && selection.length == 1
- ? ((IJavaProject) selection[0]).getProject() : null;
- return project;
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
-
- private void setExistingProject(IProject project) {
- mValues.testedProject = project;
-
- // Try to update the application, package, sdk target and minSdkVersion accordingly
- if (project != null &&
- (!mValues.applicationNameModifiedByUser ||
- !mValues.packageNameModifiedByUser ||
- !mValues.targetModifiedByUser ||
- !mValues.minSdkModifiedByUser)) {
- ManifestData manifestData = AndroidManifestHelper.parseForData(project);
- if (manifestData != null) {
- String appName = String.format("%1$sTest", project.getName());
- String packageName = manifestData.getPackage();
- String minSdkVersion = manifestData.getMinSdkVersionString();
- IAndroidTarget sdkTarget = null;
- if (Sdk.getCurrent() != null) {
- sdkTarget = Sdk.getCurrent().getTarget(project);
- }
-
- if (packageName == null) {
- packageName = ""; //$NON-NLS-1$
- }
- mLastExistingPackageName = packageName;
-
- if (!mValues.projectNameModifiedByUser) {
- mValues.projectName = appName;
- }
-
- if (!mValues.applicationNameModifiedByUser) {
- mValues.applicationName = appName;
- }
-
- if (!mValues.packageNameModifiedByUser) {
- packageName += ".test"; //$NON-NLS-1$
- mValues.packageName = packageName;
- }
-
- if (!mValues.targetModifiedByUser && sdkTarget != null) {
- mValues.target = sdkTarget;
- }
-
- if (!mValues.minSdkModifiedByUser) {
- if (minSdkVersion != null || sdkTarget != null) {
- mValues.minSdk = minSdkVersion;
- }
- if (sdkTarget == null) {
- mValues.updateSdkTargetToMatchMinSdkVersion();
- }
- }
- }
- }
-
- updateTestTargetPackageField(mLastExistingPackageName);
- }
-
- /**
- * Updates the test target package name
- *
- * When using the "self-test" option, the packageName argument is ignored and the
- * current value from the project package is used.
- *
- * Otherwise the packageName is used if it is not null.
- */
- private void updateTestTargetPackageField(String packageName) {
- if (mValues.testingSelf) {
- mValues.testTargetPackageName = mValues.packageName;
- } else if (packageName != null) {
- mValues.testTargetPackageName = packageName;
- }
- }
-
- @Override
- public boolean isPageComplete() {
- // Ensure that the user sees the page and makes a selection
- if (!mPageShown) {
- return false;
- }
-
- return super.isPageComplete();
- }
-
- private void validatePage() {
- String error = null;
-
- if (!mValues.testingSelf) {
- if (mValues.testedProject == null) {
- error = "Please select an existing Android project as a test target.";
- } else if (mValues.projectName.equals(mValues.testedProject.getName())) {
- error = "The main project name and the test project name must be different.";
- }
- }
-
- // -- update UI & enable finish if there's no error
- setPageComplete(error == null);
- if (error != null) {
- setMessage(error, IMessageProvider.ERROR);
- } else {
- setErrorMessage(null);
- setMessage(null);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/WorkingSetGroup.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/WorkingSetGroup.java
deleted file mode 100644
index fb33a08b4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/WorkingSetGroup.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package com.android.ide.eclipse.adt.internal.wizards.newproject;
-
-import org.eclipse.jdt.internal.ui.JavaPlugin;
-import org.eclipse.jdt.internal.ui.wizards.NewWizardMessages;
-import org.eclipse.jdt.internal.ui.workingsets.IWorkingSetIDs;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.ui.IWorkingSet;
-import org.eclipse.ui.dialogs.WorkingSetConfigurationBlock;
-
-/**
- * Copied from
- * org.eclipse.jdt.ui.wizards.NewJavaProjectWizardPageOne$WorkingSetGroup
- *
- * Creates the working set group with controls that allow
- * the selection of working sets
- */
-@SuppressWarnings("restriction")
-public class WorkingSetGroup {
-
- private WorkingSetConfigurationBlock fWorkingSetBlock;
- private Button mEnableButton;
-
- public WorkingSetGroup() {
- String[] workingSetIds = new String[] {
- IWorkingSetIDs.JAVA, IWorkingSetIDs.RESOURCE
- };
- fWorkingSetBlock = new WorkingSetConfigurationBlock(workingSetIds, JavaPlugin.getDefault()
- .getDialogSettings());
- }
-
- public Composite createControl(Composite composite) {
- Group workingSetGroup = new Group(composite, SWT.NONE);
- workingSetGroup.setFont(composite.getFont());
- workingSetGroup.setText(NewWizardMessages.NewJavaProjectWizardPageOne_WorkingSets_group);
- workingSetGroup.setLayout(new GridLayout(1, false));
-
- fWorkingSetBlock.createContent(workingSetGroup);
-
- // WorkingSetGroup is implemented in such a way that the checkbox it contains
- // can only be programmatically set if there's an existing working set associated
- // *before* we construct the control. However the control is created when the
- // wizard is opened, not when the page is first shown.
- //
- // One choice is to duplicate the class in our project.
- // Or find the checkbox we want and trigger it manually.
- mEnableButton = findCheckbox(workingSetGroup);
-
- return workingSetGroup;
- }
-
- public void setWorkingSets(IWorkingSet[] workingSets) {
- fWorkingSetBlock.setWorkingSets(workingSets);
- }
-
- public IWorkingSet[] getSelectedWorkingSets() {
- try {
- return fWorkingSetBlock.getSelectedWorkingSets();
- } catch (Throwable t) {
- // Test scenarios; no UI is created, which the fWorkingSetBlock assumes
- // (it dereferences the enabledButton)
- return new IWorkingSet[0];
- }
- }
-
- public boolean isChecked() {
- return mEnableButton == null ? false : mEnableButton.getSelection();
- }
-
- public void setChecked(boolean state) {
- if (mEnableButton != null) {
- mEnableButton.setSelection(state);
- }
- }
-
- /**
- * Finds the first button of style Checkbox in the given parent composite.
- * Returns null if not found.
- */
- private Button findCheckbox(Composite parent) {
- for (Control control : parent.getChildren()) {
- if (control instanceof Button && (control.getStyle() & SWT.CHECK) == SWT.CHECK) {
- return (Button) control;
- } else if (control instanceof Composite) {
- Button found = findCheckbox((Composite) control);
- if (found != null) {
- return found;
- }
- }
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/WorkingSetHelper.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/WorkingSetHelper.java
deleted file mode 100755
index 428bfd331..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newproject/WorkingSetHelper.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2000, 2009 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * IBM Corporation - initial API and implementation
- *******************************************************************************/
-
-package com.android.ide.eclipse.adt.internal.wizards.newproject;
-
-import org.eclipse.jdt.internal.ui.packageview.PackageExplorerPart;
-import org.eclipse.jdt.internal.ui.workingsets.IWorkingSetIDs;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.ITreeSelection;
-import org.eclipse.jface.viewers.TreePath;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkingSet;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-/**
- * This class contains a helper method to deal with working sets.
- * <p/>
- * Copied from org.eclipse.jdt.ui.wizards.NewJavaProjectWizardPageOne
- */
-@SuppressWarnings("restriction")
-public final class WorkingSetHelper {
-
- private static final IWorkingSet[] EMPTY_WORKING_SET_ARRAY = new IWorkingSet[0];
-
- /** This class is never instantiated. */
- private WorkingSetHelper() {
- }
-
- public static IWorkingSet[] getSelectedWorkingSet(IStructuredSelection selection,
- IWorkbenchPart activePart) {
- IWorkingSet[] selected= getSelectedWorkingSet(selection);
- if (selected != null && selected.length > 0) {
- for (int i= 0; i < selected.length; i++) {
- if (!isValidWorkingSet(selected[i]))
- return EMPTY_WORKING_SET_ARRAY;
- }
- return selected;
- }
-
- if (!(activePart instanceof PackageExplorerPart))
- return EMPTY_WORKING_SET_ARRAY;
-
- PackageExplorerPart explorerPart= (PackageExplorerPart) activePart;
- if (explorerPart.getRootMode() == PackageExplorerPart.PROJECTS_AS_ROOTS) {
- //Get active filter
- IWorkingSet filterWorkingSet= explorerPart.getFilterWorkingSet();
- if (filterWorkingSet == null)
- return EMPTY_WORKING_SET_ARRAY;
-
- if (!isValidWorkingSet(filterWorkingSet))
- return EMPTY_WORKING_SET_ARRAY;
-
- return new IWorkingSet[] {filterWorkingSet};
- } else {
- //If we have been gone into a working set return the working set
- Object input= explorerPart.getViewPartInput();
- if (!(input instanceof IWorkingSet))
- return EMPTY_WORKING_SET_ARRAY;
-
- IWorkingSet workingSet= (IWorkingSet)input;
- if (!isValidWorkingSet(workingSet))
- return EMPTY_WORKING_SET_ARRAY;
-
- return new IWorkingSet[] {workingSet};
- }
- }
-
- private static IWorkingSet[] getSelectedWorkingSet(IStructuredSelection selection) {
- if (!(selection instanceof ITreeSelection))
- return EMPTY_WORKING_SET_ARRAY;
-
- ITreeSelection treeSelection= (ITreeSelection) selection;
- if (treeSelection.isEmpty())
- return EMPTY_WORKING_SET_ARRAY;
-
- List<?> elements = treeSelection.toList();
- if (elements.size() == 1) {
- Object element= elements.get(0);
- TreePath[] paths= treeSelection.getPathsFor(element);
- if (paths.length != 1)
- return EMPTY_WORKING_SET_ARRAY;
-
- TreePath path= paths[0];
- if (path.getSegmentCount() == 0)
- return EMPTY_WORKING_SET_ARRAY;
-
- Object candidate= path.getSegment(0);
- if (!(candidate instanceof IWorkingSet))
- return EMPTY_WORKING_SET_ARRAY;
-
- IWorkingSet workingSetCandidate= (IWorkingSet) candidate;
- if (isValidWorkingSet(workingSetCandidate))
- return new IWorkingSet[] { workingSetCandidate };
-
- return EMPTY_WORKING_SET_ARRAY;
- }
-
- ArrayList<Object> result = new ArrayList<Object>();
- for (Iterator<?> iterator = elements.iterator(); iterator.hasNext();) {
- Object element= iterator.next();
- if (element instanceof IWorkingSet && isValidWorkingSet((IWorkingSet) element)) {
- result.add(element);
- }
- }
- return result.toArray(new IWorkingSet[result.size()]);
- }
-
-
- private static boolean isValidWorkingSet(IWorkingSet workingSet) {
- String id= workingSet.getId();
- if (!IWorkingSetIDs.JAVA.equals(id) && !IWorkingSetIDs.RESOURCE.equals(id))
- return false;
-
- if (workingSet.isAggregateWorkingSet())
- return false;
-
- return true;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newxmlfile/AddTranslationDialog.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newxmlfile/AddTranslationDialog.java
deleted file mode 100644
index 0301b80fe..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newxmlfile/AddTranslationDialog.java
+++ /dev/null
@@ -1,653 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.newxmlfile;
-
-import static com.android.SdkConstants.FD_RES;
-import static com.android.SdkConstants.FD_RES_VALUES;
-import static com.android.SdkConstants.RES_QUALIFIER_SEP;
-
-import com.android.ide.common.rendering.api.ResourceValue;
-import com.android.ide.common.res2.ValueXmlHelper;
-import com.android.ide.common.resources.LocaleManager;
-import com.android.ide.common.resources.ResourceItem;
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.configuration.FlagManager;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.ImageControl;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderPreviewManager;
-import com.android.ide.eclipse.adt.internal.resources.manager.ProjectResources;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.resources.ResourceType;
-import com.google.common.base.Charsets;
-import com.google.common.collect.Maps;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.viewers.ArrayContentProvider;
-import org.eclipse.jface.viewers.CellEditor;
-import org.eclipse.jface.viewers.CellLabelProvider;
-import org.eclipse.jface.viewers.ColumnViewer;
-import org.eclipse.jface.viewers.EditingSupport;
-import org.eclipse.jface.viewers.IBaseLabelProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.TextCellEditor;
-import org.eclipse.jface.viewers.ViewerCell;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ControlEvent;
-import org.eclipse.swt.events.ControlListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.events.TraverseEvent;
-import org.eclipse.swt.events.TraverseListener;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.PlatformUI;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.SortedSet;
-
-/**
- * Dialog which adds a new translation to the project
- */
-public class AddTranslationDialog extends Dialog implements ControlListener, SelectionListener,
- TraverseListener {
- private static final int KEY_COLUMN = 0;
- private static final int DEFAULT_TRANSLATION_COLUMN = 1;
- private static final int NEW_TRANSLATION_COLUMN = 2;
- private final FolderConfiguration mConfiguration = new FolderConfiguration();
- private final IProject mProject;
- private String mTarget;
- private boolean mIgnore;
- private Map<String, String> mTranslations;
- private Set<String> mExistingLanguages;
- private String mSelectedLanguage;
- private String mSelectedRegion;
-
- private Table mTable;
- private Combo mLanguageCombo;
- private Combo mRegionCombo;
- private ImageControl mFlag;
- private Label mFile;
- private Button mOkButton;
- private Composite mErrorPanel;
- private Label mErrorLabel;
- private MyTableViewer mTableViewer;
-
- /**
- * Creates the dialog.
- * @param parentShell the parent shell
- * @param project the project to add translations into
- */
- public AddTranslationDialog(Shell parentShell, IProject project) {
- super(parentShell);
- setShellStyle(SWT.CLOSE | SWT.RESIZE | SWT.TITLE);
- mProject = project;
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- Composite container = (Composite) super.createDialogArea(parent);
- GridLayout gl_container = new GridLayout(6, false);
- gl_container.horizontalSpacing = 0;
- container.setLayout(gl_container);
-
- Label languageLabel = new Label(container, SWT.NONE);
- languageLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- languageLabel.setText("Language:");
- mLanguageCombo = new Combo(container, SWT.READ_ONLY);
- GridData gd_mLanguageCombo = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
- gd_mLanguageCombo.widthHint = 150;
- mLanguageCombo.setLayoutData(gd_mLanguageCombo);
-
- Label regionLabel = new Label(container, SWT.NONE);
- GridData gd_regionLabel = new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1);
- gd_regionLabel.horizontalIndent = 10;
- regionLabel.setLayoutData(gd_regionLabel);
- regionLabel.setText("Region:");
- mRegionCombo = new Combo(container, SWT.READ_ONLY);
- GridData gd_mRegionCombo = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
- gd_mRegionCombo.widthHint = 150;
- mRegionCombo.setLayoutData(gd_mRegionCombo);
- mRegionCombo.setEnabled(false);
-
- mFlag = new ImageControl(container, SWT.NONE, null);
- mFlag.setDisposeImage(false);
- GridData gd_mFlag = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
- gd_mFlag.exclude = true;
- gd_mFlag.widthHint = 32;
- gd_mFlag.horizontalIndent = 3;
- mFlag.setLayoutData(gd_mFlag);
-
- mFile = new Label(container, SWT.NONE);
- mFile.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
-
- mTableViewer = new MyTableViewer(container, SWT.BORDER | SWT.FULL_SELECTION);
- mTable = mTableViewer.getTable();
- mTable.setEnabled(false);
- mTable.setLinesVisible(true);
- mTable.setHeaderVisible(true);
- mTable.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 6, 2));
- mTable.addControlListener(this);
- mTable.addTraverseListener(this);
- // If you have difficulty opening up this form in WindowBuilder and it complains about
- // the next line, change the type of the mTableViewer field and the above
- // constructor call from MyTableViewer to TableViewer
- TableViewerColumn keyViewerColumn = new TableViewerColumn(mTableViewer, SWT.NONE);
- TableColumn keyColumn = keyViewerColumn.getColumn();
- keyColumn.setWidth(100);
- keyColumn.setText("Key");
- TableViewerColumn defaultViewerColumn = new TableViewerColumn(mTableViewer, SWT.NONE);
- TableColumn defaultColumn = defaultViewerColumn.getColumn();
- defaultColumn.setWidth(200);
- defaultColumn.setText("Default");
- TableViewerColumn translationViewerColumn = new TableViewerColumn(mTableViewer, SWT.NONE);
- TableColumn translationColumn = translationViewerColumn.getColumn();
- translationColumn.setWidth(200);
- translationColumn.setText("New Translation");
-
- mErrorPanel = new Composite(container, SWT.NONE);
- GridData gd_mErrorLabel = new GridData(SWT.FILL, SWT.CENTER, false, false, 6, 1);
- gd_mErrorLabel.exclude = true;
- mErrorPanel.setLayoutData(gd_mErrorLabel);
-
- translationViewerColumn.setEditingSupport(new TranslationEditingSupport(mTableViewer));
-
- fillLanguages();
- fillRegions();
- fillStrings();
- updateColumnWidths();
- validatePage();
-
- mLanguageCombo.addSelectionListener(this);
- mRegionCombo.addSelectionListener(this);
-
- return container;
- }
-
- /** Populates the table with keys and default strings */
- private void fillStrings() {
- ResourceManager manager = ResourceManager.getInstance();
- ProjectResources resources = manager.getProjectResources(mProject);
- mExistingLanguages = resources.getLanguages();
-
- Collection<ResourceItem> items = resources.getResourceItemsOfType(ResourceType.STRING);
-
- ResourceItem[] array = items.toArray(new ResourceItem[items.size()]);
- Arrays.sort(array);
-
- // TODO: Read in the actual XML files providing the default keys here
- // (they can be obtained via ResourceItem.getSourceFileList())
- // such that we can read all the attributes associated with each
- // item, and if it defines translatable=false, or the filename is
- // donottranslate.xml, we can ignore it, and in other cases just
- // duplicate all the attributes (such as "formatted=true", or other
- // local conventions such as "product=tablet", or "msgid="123123123",
- // etc.)
-
- mTranslations = Maps.newHashMapWithExpectedSize(items.size());
- IBaseLabelProvider labelProvider = new CellLabelProvider() {
- @Override
- public void update(ViewerCell cell) {
- Object element = cell.getElement();
- int index = cell.getColumnIndex();
- ResourceItem item = (ResourceItem) element;
- switch (index) {
- case KEY_COLUMN: {
- // Key
- cell.setText(item.getName());
- return;
- }
- case DEFAULT_TRANSLATION_COLUMN: {
- // Default translation
- ResourceValue value = item.getResourceValue(ResourceType.STRING,
- mConfiguration, false);
-
- if (value != null) {
- cell.setText(value.getValue());
- return;
- }
- break;
- }
- case NEW_TRANSLATION_COLUMN: {
- // New translation
- String translation = mTranslations.get(item.getName());
- if (translation != null) {
- cell.setText(translation);
- return;
- }
- break;
- }
- default:
- assert false : index;
- }
- cell.setText("");
- }
- };
-
- mTableViewer.setLabelProvider(labelProvider);
- mTableViewer.setContentProvider(new ArrayContentProvider());
- mTableViewer.setInput(array);
- }
-
- /** Populate the languages dropdown */
- private void fillLanguages() {
- List<String> languageCodes = LocaleManager.getLanguageCodes();
- List<String> labels = new ArrayList<String>();
- for (String code : languageCodes) {
- labels.add(code + ": " + LocaleManager.getLanguageName(code)); //$NON-NLS-1$
- }
- Collections.sort(labels);
- labels.add(0, "(Select)");
- mLanguageCombo.setItems(labels.toArray(new String[labels.size()]));
- mLanguageCombo.select(0);
- }
-
- /** Populate the regions dropdown */
- private void fillRegions() {
- // TODO: When you switch languages, offer some "default" usable options. For example,
- // when you choose English, offer the countries that use English, and so on. Unfortunately
- // we don't have good data about this, we'd just need to hardcode a few common cases.
- List<String> regionCodes = LocaleManager.getRegionCodes();
- List<String> labels = new ArrayList<String>();
- for (String code : regionCodes) {
- labels.add(code + ": " + LocaleManager.getRegionName(code)); //$NON-NLS-1$
- }
- Collections.sort(labels);
- labels.add(0, "Any");
- mRegionCombo.setItems(labels.toArray(new String[labels.size()]));
- mRegionCombo.select(0);
- }
-
- /** React to resizing by distributing the space evenly between the last two columns */
- private void updateColumnWidths() {
- Rectangle r = mTable.getClientArea();
- int availableWidth = r.width;
- // Distribute all available space to the last two columns
- int columnCount = mTable.getColumnCount();
- for (int i = 0; i < columnCount; i++) {
- TableColumn column = mTable.getColumn(i);
- availableWidth -= column.getWidth();
- }
- if (availableWidth != 0) {
- TableColumn column = mTable.getColumn(DEFAULT_TRANSLATION_COLUMN);
- column.setWidth(column.getWidth() + availableWidth / 2);
- column = mTable.getColumn(NEW_TRANSLATION_COLUMN);
- column.setWidth(column.getWidth() + availableWidth / 2 + availableWidth % 2);
- }
- }
-
- @Override
- protected void createButtonsForButtonBar(Composite parent) {
- mOkButton = createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,
- // Don't make the OK button default as in most dialogs, since when you press
- // Return thinking you might edit a value it dismisses the dialog instead
- false);
- createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false);
- mOkButton.setEnabled(false);
-
- validatePage();
- }
-
- /**
- * Return the initial size of the dialog.
- */
- @Override
- protected Point getInitialSize() {
- return new Point(800, 600);
- }
-
- private void updateTarget() {
- if (mSelectedLanguage == null) {
- mTarget = null;
- mFile.setText("");
- } else {
- String folder = FD_RES + '/' + FD_RES_VALUES + RES_QUALIFIER_SEP + mSelectedLanguage;
- if (mSelectedRegion != null) {
- folder = folder + RES_QUALIFIER_SEP + 'r' + mSelectedRegion;
- }
- mTarget = folder + "/strings.xml"; //$NON-NLS-1$
- mFile.setText(String.format("Creating %1$s", mTarget));
- }
- }
-
- private void updateFlag() {
- if (mSelectedLanguage == null) {
- // Nothing selected
- ((GridData) mFlag.getLayoutData()).exclude = true;
- } else {
- FlagManager manager = FlagManager.get();
- Image flag = manager.getFlag(mSelectedLanguage, mSelectedRegion);
- if (flag != null) {
- ((GridData) mFlag.getLayoutData()).exclude = false;
- mFlag.setImage(flag);
- }
- }
-
- mFlag.getParent().layout(true);
- mFlag.getParent().redraw();
- }
-
- /** Actually create the new translation file and write it to disk */
- private void createTranslation() {
- List<String> keys = new ArrayList<String>(mTranslations.keySet());
- Collections.sort(keys);
-
- StringBuilder sb = new StringBuilder(keys.size() * 120);
- sb.append("<resources>\n\n"); //$NON-NLS-1$
- for (String key : keys) {
- String value = mTranslations.get(key);
- if (value == null || value.trim().isEmpty()) {
- continue;
- }
- sb.append(" <string name=\""); //$NON-NLS-1$
- sb.append(key);
- sb.append("\">"); //$NON-NLS-1$
- sb.append(ValueXmlHelper.escapeResourceString(value));
- sb.append("</string>\n"); //$NON-NLS-1$
- }
- sb.append("\n</resources>"); //$NON-NLS-1$
-
- IFile file = mProject.getFile(mTarget);
-
- try {
- IContainer parent = file.getParent();
- AdtUtils.ensureExists(parent);
- InputStream source = new ByteArrayInputStream(sb.toString().getBytes(Charsets.UTF_8));
- file.create(source, true, new NullProgressMonitor());
- AdtPlugin.openFile(file, null, true /*showEditorTab*/);
-
- // Ensure that the project resources updates itself to notice the new language.
- // In theory, this shouldn't be necessary.
- ResourceManager manager = ResourceManager.getInstance();
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- IFolder folder = root.getFolder(parent.getFullPath());
- manager.getResourceFolder(folder);
- RenderPreviewManager.bumpRevision();
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- }
-
- private void validatePage() {
- if (mOkButton == null) { // Early initialization
- return;
- }
-
- String message = null;
-
- if (mSelectedLanguage == null) {
- message = "Select a language";
- } else if (mExistingLanguages.contains(mSelectedLanguage)) {
- if (mSelectedRegion == null) {
- message = String.format("%1$s is already translated in this project",
- LocaleManager.getLanguageName(mSelectedLanguage));
- } else {
- ResourceManager manager = ResourceManager.getInstance();
- ProjectResources resources = manager.getProjectResources(mProject);
- SortedSet<String> regions = resources.getRegions(mSelectedLanguage);
- if (regions.contains(mSelectedRegion)) {
- message = String.format("%1$s (%2$s) is already translated in this project",
- LocaleManager.getLanguageName(mSelectedLanguage),
- LocaleManager.getRegionName(mSelectedRegion));
- }
- }
- } else {
- // Require all strings to be translated? No, some of these may not
- // be translatable (e.g. translatable=false, defined in donottranslate.xml, etc.)
- //int missing = mTable.getItemCount() - mTranslations.values().size();
- //if (missing > 0) {
- // message = String.format("Missing %1$d translations", missing);
- //}
- }
-
- boolean valid = message == null;
- mTable.setEnabled(message == null);
- mOkButton.setEnabled(valid);
- showError(message);
- }
-
- private void showError(String error) {
- GridData data = (GridData) mErrorPanel.getLayoutData();
-
- boolean show = error != null;
- if (show == data.exclude) {
- if (show) {
- if (mErrorLabel == null) {
- mErrorPanel.setLayout(new GridLayout(2, false));
- IWorkbench workbench = PlatformUI.getWorkbench();
- ISharedImages sharedImages = workbench.getSharedImages();
- String iconName = ISharedImages.IMG_OBJS_ERROR_TSK;
- Image image = sharedImages.getImage(iconName);
- @SuppressWarnings("unused")
- ImageControl icon = new ImageControl(mErrorPanel, SWT.NONE, image);
-
- mErrorLabel = new Label(mErrorPanel, SWT.NONE);
- mErrorLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
- 1, 1));
- }
- mErrorLabel.setText(error);
- }
- data.exclude = !show;
- mErrorPanel.getParent().layout(true);
- }
- }
-
- @Override
- protected void okPressed() {
- mTableViewer.applyEditorValue();
-
- super.okPressed();
- createTranslation();
- }
-
- // ---- Implements ControlListener ----
-
- @Override
- public void controlMoved(ControlEvent e) {
- }
-
- @Override
- public void controlResized(ControlEvent e) {
- if (mIgnore) {
- return;
- }
-
- updateColumnWidths();
- }
-
- // ---- Implements SelectionListener ----
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (mIgnore) {
- return;
- }
-
- Object source = e.getSource();
- if (source == mLanguageCombo) {
- try {
- mIgnore = true;
- mRegionCombo.select(0);
- mSelectedRegion = null;
- } finally {
- mIgnore = false;
- }
-
- int languageIndex = mLanguageCombo.getSelectionIndex();
- if (languageIndex == 0) {
- mSelectedLanguage = null;
- mRegionCombo.setEnabled(false);
- } else {
- // This depends on the label format
- mSelectedLanguage = mLanguageCombo.getItem(languageIndex).substring(0, 2);
- mRegionCombo.setEnabled(true);
- }
-
- updateTarget();
- updateFlag();
- } else if (source == mRegionCombo) {
- int regionIndex = mRegionCombo.getSelectionIndex();
- if (regionIndex == 0) {
- mSelectedRegion = null;
- } else {
- mSelectedRegion = mRegionCombo.getItem(regionIndex).substring(0, 2);
- }
-
- updateTarget();
- updateFlag();
- }
-
- try {
- mIgnore = true;
- validatePage();
- } finally {
- mIgnore = false;
- }
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
-
- // ---- TraverseListener ----
-
- @Override
- public void keyTraversed(TraverseEvent e) {
- // If you press Return and we're not cell editing, start editing the current row
- if (e.detail == SWT.TRAVERSE_RETURN && !mTableViewer.isCellEditorActive()) {
- int index = mTable.getSelectionIndex();
- if (index != -1) {
- Object next = mTable.getItem(index).getData();
- mTableViewer.editElement(next, NEW_TRANSLATION_COLUMN);
- }
- }
- }
-
- /** Editing support for the translation column */
- private class TranslationEditingSupport extends EditingSupport {
- /**
- * When true, setValue is being called as part of a default action
- * (e.g. Return), not due to focus loss
- */
- private boolean mDefaultAction;
-
- private TranslationEditingSupport(ColumnViewer viewer) {
- super(viewer);
- }
-
- @Override
- protected void setValue(Object element, Object value) {
- ResourceItem item = (ResourceItem) element;
- mTranslations.put(item.getName(), value.toString());
- mTableViewer.update(element, null);
- validatePage();
-
- // If the user is pressing Return to finish editing a value (which is
- // not the only way this method can get called - for example, if you click
- // outside the cell while editing, the focus loss will also result in
- // this method getting called), then mDefaultAction is true, and we automatically
- // start editing the next row.
- if (mDefaultAction) {
- mTable.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- if (!mTable.isDisposed() && !mTableViewer.isCellEditorActive()) {
- int index = mTable.getSelectionIndex();
- if (index != -1 && index < mTable.getItemCount() - 1) {
- Object next = mTable.getItem(index + 1).getData();
- mTableViewer.editElement(next, NEW_TRANSLATION_COLUMN);
- }
- }
- }
- });
- }
- }
-
- @Override
- protected Object getValue(Object element) {
- ResourceItem item = (ResourceItem) element;
- String value = mTranslations.get(item.getName());
- if (value == null) {
- return "";
- }
- return value;
- }
-
- @Override
- protected CellEditor getCellEditor(Object element) {
- return new TextCellEditor(mTable) {
- @Override
- protected void handleDefaultSelection(SelectionEvent event) {
- try {
- mDefaultAction = true;
- super.handleDefaultSelection(event);
- } finally {
- mDefaultAction = false;
- }
- }
- };
- }
-
- @Override
- protected boolean canEdit(Object element) {
- return true;
- }
- }
-
- private class MyTableViewer extends TableViewer {
- public MyTableViewer(Composite parent, int style) {
- super(parent, style);
- }
-
- // Make this public so we can call it to ensure values are applied before the dialog
- // is dismissed in {@link #okPressed}
- @Override
- public void applyEditorValue() {
- super.applyEditorValue();
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newxmlfile/ChooseConfigurationPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newxmlfile/ChooseConfigurationPage.java
deleted file mode 100644
index 1d6467e64..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newxmlfile/ChooseConfigurationPage.java
+++ /dev/null
@@ -1,282 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.newxmlfile;
-
-import com.android.SdkConstants;
-import com.android.ide.common.resources.configuration.ResourceQualifier;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.internal.ui.ConfigurationSelector;
-import com.android.ide.eclipse.adt.internal.ui.ConfigurationSelector.ConfigurationState;
-import com.android.ide.eclipse.adt.internal.ui.ConfigurationSelector.SelectorMode;
-import com.android.ide.eclipse.adt.internal.wizards.newxmlfile.NewXmlFileCreationPage.TypeInfo;
-import com.android.ide.eclipse.adt.internal.wizards.newxmlfile.NewXmlFileWizard.Values;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-
-/**
- * Second page of the {@link NewXmlFileWizard}.
- * <p>
- * This page is used for choosing the current configuration or specific resource
- * folder.
- */
-public class ChooseConfigurationPage extends WizardPage {
- private Values mValues;
- private Text mWsFolderPathTextField;
- private ConfigurationSelector mConfigSelector;
- private boolean mInternalWsFolderPathUpdate;
- private boolean mInternalConfigSelectorUpdate;
-
- /** Absolute destination folder root, e.g. "/res/" */
- static final String RES_FOLDER_ABS = AdtConstants.WS_RESOURCES + AdtConstants.WS_SEP;
- /** Relative destination folder root, e.g. "res/" */
- static final String RES_FOLDER_REL = SdkConstants.FD_RESOURCES + AdtConstants.WS_SEP;
-
- /**
- * Create the wizard.
- *
- * @param values value object holding current wizard state
- */
- public ChooseConfigurationPage(NewXmlFileWizard.Values values) {
- super("chooseConfig");
- mValues = values;
- setTitle("Choose Configuration Folder");
- }
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- if (visible) {
- if (mValues.folderPath != null) {
- mWsFolderPathTextField.setText(mValues.folderPath);
- }
- }
- }
-
- @Override
- public void createControl(Composite parent) {
- // This UI is maintained with WindowBuilder.
-
- Composite composite = new Composite(parent, SWT.NULL);
- composite.setLayout(new GridLayout(2, false /* makeColumnsEqualWidth */));
- composite.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- // label before configuration selector
- Label label = new Label(composite, SWT.NONE);
- label.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
- label.setText("Optional: Choose a specific configuration to limit the XML to:");
-
- // configuration selector
- mConfigSelector = new ConfigurationSelector(composite, SelectorMode.DEFAULT);
- GridData gd = new GridData(GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL);
- gd.verticalAlignment = SWT.FILL;
- gd.horizontalAlignment = SWT.FILL;
- gd.horizontalSpan = 2;
- gd.heightHint = ConfigurationSelector.HEIGHT_HINT;
- mConfigSelector.setLayoutData(gd);
- mConfigSelector.setOnChangeListener(new ConfigurationChangeListener());
-
- // Folder name: [text]
- String tooltip = "The folder where the file will be generated, relative to the project.";
-
- Label separator = new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL);
- GridData gdSeparator = new GridData(SWT.FILL, SWT.CENTER, false, false, 2, 1);
- gdSeparator.heightHint = 10;
- separator.setLayoutData(gdSeparator);
- Label folderLabel = new Label(composite, SWT.NONE);
- folderLabel.setText("Folder:");
- folderLabel.setToolTipText(tooltip);
-
- mWsFolderPathTextField = new Text(composite, SWT.BORDER);
- mWsFolderPathTextField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mWsFolderPathTextField.setToolTipText(tooltip);
- mWsFolderPathTextField.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- onWsFolderPathUpdated();
- }
- });
-
- setControl(composite);
-
- mConfigSelector.setConfiguration(mValues.configuration);
- }
-
- /**
- * Callback called when the Folder text field is changed, either programmatically
- * or by the user.
- */
- private void onWsFolderPathUpdated() {
- if (mInternalWsFolderPathUpdate) {
- return;
- }
-
- String wsFolderPath = mWsFolderPathTextField.getText();
-
- // This is a custom path, we need to sanitize it.
- // First it should start with "/res/". Then we need to make sure there are no
- // relative paths, things like "../" or "./" or even "//".
- wsFolderPath = wsFolderPath.replaceAll("/+\\.\\./+|/+\\./+|//+|\\\\+|^/+", "/"); //$NON-NLS-1$ //$NON-NLS-2$
- wsFolderPath = wsFolderPath.replaceAll("^\\.\\./+|^\\./+", ""); //$NON-NLS-1$ //$NON-NLS-2$
- wsFolderPath = wsFolderPath.replaceAll("/+\\.\\.$|/+\\.$|/+$", ""); //$NON-NLS-1$ //$NON-NLS-2$
-
- // We get "res/foo" from selections relative to the project when we want a "/res/foo" path.
- if (wsFolderPath.startsWith(RES_FOLDER_REL)) {
- wsFolderPath = RES_FOLDER_ABS + wsFolderPath.substring(RES_FOLDER_REL.length());
-
- mInternalWsFolderPathUpdate = true;
- mWsFolderPathTextField.setText(wsFolderPath);
- mInternalWsFolderPathUpdate = false;
- }
-
- mValues.folderPath = wsFolderPath;
-
- if (wsFolderPath.startsWith(RES_FOLDER_ABS)) {
- wsFolderPath = wsFolderPath.substring(RES_FOLDER_ABS.length());
-
- int pos = wsFolderPath.indexOf(AdtConstants.WS_SEP_CHAR);
- if (pos >= 0) {
- wsFolderPath = wsFolderPath.substring(0, pos);
- }
-
- String[] folderSegments = wsFolderPath.split(SdkConstants.RES_QUALIFIER_SEP);
-
- if (folderSegments.length > 0) {
- String folderName = folderSegments[0];
-
- // update config selector
- mInternalConfigSelectorUpdate = true;
- mConfigSelector.setConfiguration(folderSegments);
- mInternalConfigSelectorUpdate = false;
-
- IWizardPage previous = ((NewXmlFileWizard) getWizard()).getPreviousPage(this);
- if (previous instanceof NewXmlFileCreationPage) {
- NewXmlFileCreationPage p = (NewXmlFileCreationPage) previous;
- p.selectTypeFromFolder(folderName);
- }
- }
- }
-
- validatePage();
- }
-
- /**
- * Callback called when the configuration has changed in the {@link ConfigurationSelector}.
- */
- private class ConfigurationChangeListener implements Runnable {
- @Override
- public void run() {
- if (mInternalConfigSelectorUpdate) {
- return;
- }
-
- resetFolderPath(true /*validate*/);
- }
- }
-
- /**
- * Reset the current Folder path based on the UI selection
- * @param validate if true, force a call to {@link #validatePage()}.
- */
- private void resetFolderPath(boolean validate) {
- TypeInfo type = mValues.type;
- if (type != null) {
- mConfigSelector.getConfiguration(mValues.configuration);
- StringBuilder sb = new StringBuilder(RES_FOLDER_ABS);
- sb.append(mValues.configuration.getFolderName(type.getResFolderType()));
-
- mInternalWsFolderPathUpdate = true;
- String newPath = sb.toString();
- mValues.folderPath = newPath;
- mWsFolderPathTextField.setText(newPath);
- mInternalWsFolderPathUpdate = false;
-
- if (validate) {
- validatePage();
- }
- }
- }
-
- /**
- * Returns the destination folder path relative to the project or an empty string.
- *
- * @return the currently edited folder
- */
- public String getWsFolderPath() {
- return mWsFolderPathTextField == null ? "" : mWsFolderPathTextField.getText(); //$NON-NLS-1$
- }
-
- /**
- * Validates the fields, displays errors and warnings.
- * Enables the finish button if there are no errors.
- */
- private void validatePage() {
- String error = null;
- String warning = null;
-
- // -- validate folder configuration
- if (error == null) {
- ConfigurationState state = mConfigSelector.getState();
- if (state == ConfigurationState.INVALID_CONFIG) {
- ResourceQualifier qual = mConfigSelector.getInvalidQualifier();
- if (qual != null) {
- error =
- String.format("The qualifier '%1$s' is invalid in the folder configuration.",
- qual.getName());
- }
- } else if (state == ConfigurationState.REGION_WITHOUT_LANGUAGE) {
- error = "The Region qualifier requires the Language qualifier.";
- }
- }
-
- // -- validate generated path
- if (error == null) {
- String wsFolderPath = getWsFolderPath();
- if (!wsFolderPath.startsWith(RES_FOLDER_ABS)) {
- error = String.format("Target folder must start with %1$s.", RES_FOLDER_ABS);
- }
- }
-
- // -- validate destination file doesn't exist
- if (error == null) {
- IFile file = mValues.getDestinationFile();
- if (file != null && file.exists()) {
- warning = "The destination file already exists";
- }
- }
-
- // -- update UI & enable finish if there's no error
- setPageComplete(error == null);
- if (error != null) {
- setMessage(error, IMessageProvider.ERROR);
- } else if (warning != null) {
- setMessage(warning, IMessageProvider.WARNING);
- } else {
- setErrorMessage(null);
- setMessage(null);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newxmlfile/NewXmlFileCreationPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newxmlfile/NewXmlFileCreationPage.java
deleted file mode 100644
index 28fb8c032..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newxmlfile/NewXmlFileCreationPage.java
+++ /dev/null
@@ -1,1163 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.newxmlfile;
-
-import static com.android.SdkConstants.DOT_XML;
-import static com.android.SdkConstants.HORIZONTAL_SCROLL_VIEW;
-import static com.android.SdkConstants.LINEAR_LAYOUT;
-import static com.android.SdkConstants.RES_QUALIFIER_SEP;
-import static com.android.SdkConstants.SCROLL_VIEW;
-import static com.android.SdkConstants.VALUE_FILL_PARENT;
-import static com.android.SdkConstants.VALUE_MATCH_PARENT;
-import static com.android.ide.eclipse.adt.AdtConstants.WS_SEP_CHAR;
-import static com.android.ide.eclipse.adt.internal.wizards.newxmlfile.ChooseConfigurationPage.RES_FOLDER_ABS;
-
-import com.android.SdkConstants;
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.common.resources.configuration.ResourceQualifier;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.DocumentDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.IDescriptorProvider;
-import com.android.ide.eclipse.adt.internal.project.ProjectChooserHelper;
-import com.android.ide.eclipse.adt.internal.project.ProjectChooserHelper.ProjectCombo;
-import com.android.ide.eclipse.adt.internal.resources.ResourceNameValidator;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk.TargetChangeListener;
-import com.android.resources.ResourceFolderType;
-import com.android.sdklib.IAndroidTarget;
-import com.android.utils.Pair;
-import com.android.utils.SdkUtils;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.viewers.ArrayContentProvider;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.IBaseLabelProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.part.FileEditorInput;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-
-/**
- * This is the first page of the {@link NewXmlFileWizard} which provides the ability to create
- * skeleton XML resources files for Android projects.
- * <p/>
- * This page is used to select the project, resource type and file name.
- */
-class NewXmlFileCreationPage extends WizardPage {
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- // Ensure the initial focus is in the Name field; you usually don't need
- // to edit the default text field (the project name)
- if (visible && mFileNameTextField != null) {
- mFileNameTextField.setFocus();
- }
-
- validatePage();
- }
-
- /**
- * Information on one type of resource that can be created (e.g. menu, pref, layout, etc.)
- */
- static class TypeInfo {
- private final String mUiName;
- private final ResourceFolderType mResFolderType;
- private final String mTooltip;
- private final Object mRootSeed;
- private ArrayList<String> mRoots = new ArrayList<String>();
- private final String mXmlns;
- private final String mDefaultAttrs;
- private final String mDefaultRoot;
- private final int mTargetApiLevel;
-
- public TypeInfo(String uiName,
- String tooltip,
- ResourceFolderType resFolderType,
- Object rootSeed,
- String defaultRoot,
- String xmlns,
- String defaultAttrs,
- int targetApiLevel) {
- mUiName = uiName;
- mResFolderType = resFolderType;
- mTooltip = tooltip;
- mRootSeed = rootSeed;
- mDefaultRoot = defaultRoot;
- mXmlns = xmlns;
- mDefaultAttrs = defaultAttrs;
- mTargetApiLevel = targetApiLevel;
- }
-
- /** Returns the UI name for the resource type. Unique. Never null. */
- String getUiName() {
- return mUiName;
- }
-
- /** Returns the tooltip for the resource type. Can be null. */
- String getTooltip() {
- return mTooltip;
- }
-
- /**
- * Returns the name of the {@link ResourceFolderType}.
- * Never null but not necessarily unique,
- * e.g. two types use {@link ResourceFolderType#XML}.
- */
- String getResFolderName() {
- return mResFolderType.getName();
- }
-
- /**
- * Returns the matching {@link ResourceFolderType}.
- * Never null but not necessarily unique,
- * e.g. two types use {@link ResourceFolderType#XML}.
- */
- ResourceFolderType getResFolderType() {
- return mResFolderType;
- }
-
- /**
- * Returns the seed used to fill the root element values.
- * The seed might be either a String, a String array, an {@link ElementDescriptor},
- * a {@link DocumentDescriptor} or null.
- */
- Object getRootSeed() {
- return mRootSeed;
- }
-
- /**
- * Returns the default root element that should be selected by default. Can be
- * null.
- *
- * @param project the associated project, or null if not known
- */
- String getDefaultRoot(IProject project) {
- return mDefaultRoot;
- }
-
- /**
- * Returns the list of all possible root elements for the resource type.
- * This can be an empty ArrayList but not null.
- * <p/>
- * TODO: the root list SHOULD depend on the currently selected project, to include
- * custom classes.
- */
- ArrayList<String> getRoots() {
- return mRoots;
- }
-
- /**
- * If the generated resource XML file requires an "android" XMLNS, this should be set
- * to {@link SdkConstants#NS_RESOURCES}. When it is null, no XMLNS is generated.
- */
- String getXmlns() {
- return mXmlns;
- }
-
- /**
- * When not null, this represent extra attributes that must be specified in the
- * root element of the generated XML file. When null, no extra attributes are inserted.
- *
- * @param project the project to get the attributes for
- * @param root the selected root element string, never null
- */
- String getDefaultAttrs(IProject project, String root) {
- return mDefaultAttrs;
- }
-
- /**
- * When not null, represents an extra string that should be written inside
- * the element when constructed
- *
- * @param project the project to get the child content for
- * @param root the chosen root element
- * @return a string to be written inside the root element, or null if nothing
- */
- String getChild(IProject project, String root) {
- return null;
- }
-
- /**
- * The minimum API level required by the current SDK target to support this feature.
- *
- * @return the minimum API level
- */
- public int getTargetApiLevel() {
- return mTargetApiLevel;
- }
- }
-
- /**
- * TypeInfo, information for each "type" of file that can be created.
- */
- private static final TypeInfo[] sTypes = {
- new TypeInfo(
- "Layout", // UI name
- "An XML file that describes a screen layout.", // tooltip
- ResourceFolderType.LAYOUT, // folder type
- AndroidTargetData.DESCRIPTOR_LAYOUT, // root seed
- LINEAR_LAYOUT, // default root
- SdkConstants.NS_RESOURCES, // xmlns
- "", // not used, see below
- 1 // target API level
- ) {
-
- @Override
- String getDefaultRoot(IProject project) {
- // TODO: Use GridLayout by default for new SDKs
- // (when we've ironed out all the usability issues)
- //Sdk currentSdk = Sdk.getCurrent();
- //if (project != null && currentSdk != null) {
- // IAndroidTarget target = currentSdk.getTarget(project);
- // // fill_parent was renamed match_parent in API level 8
- // if (target != null && target.getVersion().getApiLevel() >= 13) {
- // return GRID_LAYOUT;
- // }
- //}
-
- return LINEAR_LAYOUT;
- };
-
- // The default attributes must be determined dynamically since whether
- // we use match_parent or fill_parent depends on the API level of the
- // project
- @Override
- String getDefaultAttrs(IProject project, String root) {
- Sdk currentSdk = Sdk.getCurrent();
- String fill = VALUE_FILL_PARENT;
- if (currentSdk != null) {
- IAndroidTarget target = currentSdk.getTarget(project);
- // fill_parent was renamed match_parent in API level 8
- if (target != null && target.getVersion().getApiLevel() >= 8) {
- fill = VALUE_MATCH_PARENT;
- }
- }
-
- // Only set "vertical" orientation of LinearLayouts by default;
- // for GridLayouts for example we want to rely on the real default
- // of the layout
- String size = String.format(
- "android:layout_width=\"%1$s\"\n" //$NON-NLS-1$
- + "android:layout_height=\"%2$s\"", //$NON-NLS-1$
- fill, fill);
- if (LINEAR_LAYOUT.equals(root)) {
- return "android:orientation=\"vertical\"\n" + size; //$NON-NLS-1$
- } else {
- return size;
- }
- }
-
- @Override
- String getChild(IProject project, String root) {
- // Create vertical linear layouts inside new scroll views
- if (SCROLL_VIEW.equals(root) || HORIZONTAL_SCROLL_VIEW.equals(root)) {
- return " <LinearLayout " //$NON-NLS-1$
- + getDefaultAttrs(project, root).replace('\n', ' ')
- + " android:orientation=\"vertical\"" //$NON-NLS-1$
- + "></LinearLayout>\n"; //$NON-NLS-1$
- }
- return null;
- }
- },
- new TypeInfo("Values", // UI name
- "An XML file with simple values: colors, strings, dimensions, etc.", // tooltip
- ResourceFolderType.VALUES, // folder type
- SdkConstants.TAG_RESOURCES, // root seed
- null, // default root
- null, // xmlns
- null, // default attributes
- 1 // target API level
- ),
- new TypeInfo("Drawable", // UI name
- "An XML file that describes a drawable.", // tooltip
- ResourceFolderType.DRAWABLE, // folder type
- AndroidTargetData.DESCRIPTOR_DRAWABLE, // root seed
- null, // default root
- SdkConstants.NS_RESOURCES, // xmlns
- null, // default attributes
- 1 // target API level
- ),
- new TypeInfo("Menu", // UI name
- "An XML file that describes an menu.", // tooltip
- ResourceFolderType.MENU, // folder type
- SdkConstants.TAG_MENU, // root seed
- null, // default root
- SdkConstants.NS_RESOURCES, // xmlns
- null, // default attributes
- 1 // target API level
- ),
- new TypeInfo("Color List", // UI name
- "An XML file that describes a color state list.", // tooltip
- ResourceFolderType.COLOR, // folder type
- AndroidTargetData.DESCRIPTOR_COLOR, // root seed
- "selector", //$NON-NLS-1$ // default root
- SdkConstants.NS_RESOURCES, // xmlns
- null, // default attributes
- 1 // target API level
- ),
- new TypeInfo("Property Animation", // UI name
- "An XML file that describes a property animation", // tooltip
- ResourceFolderType.ANIMATOR, // folder type
- AndroidTargetData.DESCRIPTOR_ANIMATOR, // root seed
- "set", //$NON-NLS-1$ // default root
- SdkConstants.NS_RESOURCES, // xmlns
- null, // default attributes
- 11 // target API level
- ),
- new TypeInfo("Tween Animation", // UI name
- "An XML file that describes a tween animation.", // tooltip
- ResourceFolderType.ANIM, // folder type
- AndroidTargetData.DESCRIPTOR_ANIM, // root seed
- "set", //$NON-NLS-1$ // default root
- null, // xmlns
- null, // default attributes
- 1 // target API level
- ),
- new TypeInfo("AppWidget Provider", // UI name
- "An XML file that describes a widget provider.", // tooltip
- ResourceFolderType.XML, // folder type
- AndroidTargetData.DESCRIPTOR_APPWIDGET_PROVIDER, // root seed
- null, // default root
- SdkConstants.NS_RESOURCES, // xmlns
- null, // default attributes
- 3 // target API level
- ),
- new TypeInfo("Preference", // UI name
- "An XML file that describes preferences.", // tooltip
- ResourceFolderType.XML, // folder type
- AndroidTargetData.DESCRIPTOR_PREFERENCES, // root seed
- SdkConstants.CLASS_NAME_PREFERENCE_SCREEN, // default root
- SdkConstants.NS_RESOURCES, // xmlns
- null, // default attributes
- 1 // target API level
- ),
- new TypeInfo("Searchable", // UI name
- "An XML file that describes a searchable.", // tooltip
- ResourceFolderType.XML, // folder type
- AndroidTargetData.DESCRIPTOR_SEARCHABLE, // root seed
- null, // default root
- SdkConstants.NS_RESOURCES, // xmlns
- null, // default attributes
- 1 // target API level
- ),
- // Still missing: Interpolator, Raw and Mipmap. Raw should probably never be in
- // this menu since it's not often used for creating XML files.
- };
-
- private NewXmlFileWizard.Values mValues;
- private ProjectCombo mProjectButton;
- private Text mFileNameTextField;
- private Combo mTypeCombo;
- private IStructuredSelection mInitialSelection;
- private ResourceFolderType mInitialFolderType;
- private boolean mInternalTypeUpdate;
- private TargetChangeListener mSdkTargetChangeListener;
- private Table mRootTable;
- private TableViewer mRootTableViewer;
-
- // --- UI creation ---
-
- /**
- * Constructs a new {@link NewXmlFileCreationPage}.
- * <p/>
- * Called by {@link NewXmlFileWizard#createMainPage}.
- */
- protected NewXmlFileCreationPage(String pageName, NewXmlFileWizard.Values values) {
- super(pageName);
- mValues = values;
- setPageComplete(false);
- }
-
- public void setInitialSelection(IStructuredSelection initialSelection) {
- mInitialSelection = initialSelection;
- }
-
- public void setInitialFolderType(ResourceFolderType initialType) {
- mInitialFolderType = initialType;
- }
-
- /**
- * Called by the parent Wizard to create the UI for this Wizard Page.
- *
- * {@inheritDoc}
- *
- * @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
- */
- @Override
- @SuppressWarnings("unused") // SWT constructors have side effects, they aren't unused
- public void createControl(Composite parent) {
- // This UI is maintained with WindowBuilder.
-
- Composite composite = new Composite(parent, SWT.NULL);
- composite.setLayout(new GridLayout(2, false /*makeColumnsEqualWidth*/));
- composite.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- // label before type radios
- Label typeLabel = new Label(composite, SWT.NONE);
- typeLabel.setText("Resource Type:");
-
- mTypeCombo = new Combo(composite, SWT.DROP_DOWN | SWT.READ_ONLY);
- mTypeCombo.setToolTipText("What type of resource would you like to create?");
- mTypeCombo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- if (mInitialFolderType != null) {
- mTypeCombo.setEnabled(false);
- }
- mTypeCombo.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- TypeInfo type = getSelectedType();
- if (type != null) {
- onSelectType(type);
- }
- }
- });
-
- // separator
- Label separator = new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL);
- GridData gd2 = new GridData(GridData.GRAB_HORIZONTAL);
- gd2.horizontalAlignment = SWT.FILL;
- gd2.horizontalSpan = 2;
- separator.setLayoutData(gd2);
-
- // Project: [button]
- String tooltip = "The Android Project where the new resource file will be created.";
- Label projectLabel = new Label(composite, SWT.NONE);
- projectLabel.setText("Project:");
- projectLabel.setToolTipText(tooltip);
-
- ProjectChooserHelper helper =
- new ProjectChooserHelper(getShell(), null /* filter */);
-
- mProjectButton = new ProjectCombo(helper, composite, mValues.project);
- mProjectButton.setToolTipText(tooltip);
- mProjectButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mProjectButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- IProject project = mProjectButton.getSelectedProject();
- if (project != mValues.project) {
- changeProject(project);
- }
- };
- });
-
- // Filename: [text]
- Label fileLabel = new Label(composite, SWT.NONE);
- fileLabel.setText("File:");
- fileLabel.setToolTipText("The name of the resource file to create.");
-
- mFileNameTextField = new Text(composite, SWT.BORDER);
- mFileNameTextField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mFileNameTextField.setToolTipText(tooltip);
- mFileNameTextField.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- mValues.name = mFileNameTextField.getText();
- validatePage();
- }
- });
-
- // separator
- Label rootSeparator = new Label(composite, SWT.SEPARATOR | SWT.HORIZONTAL);
- GridData gd = new GridData(GridData.GRAB_HORIZONTAL);
- gd.horizontalAlignment = SWT.FILL;
- gd.horizontalSpan = 2;
- rootSeparator.setLayoutData(gd);
-
- // Root Element:
- // [TableViewer]
- Label rootLabel = new Label(composite, SWT.NONE);
- rootLabel.setText("Root Element:");
- new Label(composite, SWT.NONE);
-
- mRootTableViewer = new TableViewer(composite, SWT.BORDER | SWT.FULL_SELECTION);
- mRootTable = mRootTableViewer.getTable();
- GridData tableGridData = new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1);
- tableGridData.heightHint = 200;
- mRootTable.setLayoutData(tableGridData);
-
- setControl(composite);
-
- // Update state the first time
- setErrorMessage(null);
- setMessage(null);
-
- initializeFromSelection(mInitialSelection);
- updateAvailableTypes();
- initializeFromFixedType();
- initializeRootValues();
- installTargetChangeListener();
-
- initialSelectType();
- validatePage();
- }
-
- private void initialSelectType() {
- TypeInfo[] types = (TypeInfo[]) mTypeCombo.getData();
- int typeIndex = getTypeComboIndex(mValues.type);
- if (typeIndex == -1) {
- typeIndex = 0;
- } else {
- assert mValues.type == types[typeIndex];
- }
- mTypeCombo.select(typeIndex);
- onSelectType(types[typeIndex]);
- updateRootCombo(types[typeIndex]);
- }
-
- private void installTargetChangeListener() {
- mSdkTargetChangeListener = new TargetChangeListener() {
- @Override
- public IProject getProject() {
- return mValues.project;
- }
-
- @Override
- public void reload() {
- if (mValues.project != null) {
- changeProject(mValues.project);
- }
- }
- };
-
- AdtPlugin.getDefault().addTargetListener(mSdkTargetChangeListener);
- }
-
- @Override
- public void dispose() {
-
- if (mSdkTargetChangeListener != null) {
- AdtPlugin.getDefault().removeTargetListener(mSdkTargetChangeListener);
- mSdkTargetChangeListener = null;
- }
-
- super.dispose();
- }
-
- /**
- * Returns the selected root element string, if any.
- *
- * @return The selected root element string or null.
- */
- public String getRootElement() {
- int index = mRootTable.getSelectionIndex();
- if (index >= 0) {
- Object[] roots = (Object[]) mRootTableViewer.getInput();
- return roots[index].toString();
- }
- return null;
- }
-
- /**
- * Called by {@link NewXmlFileWizard} to initialize the page with the selection
- * received by the wizard -- typically the current user workbench selection.
- * <p/>
- * Things we expect to find out from the selection:
- * <ul>
- * <li>The project name, valid if it's an android nature.</li>
- * <li>The current folder, valid if it's a folder under /res</li>
- * <li>An existing filename, in which case the user will be asked whether to override it.</li>
- * </ul>
- * <p/>
- * The selection can also be set to a {@link Pair} of {@link IProject} and a workspace
- * resource path (where the resource path does not have to exist yet, such as res/anim/).
- *
- * @param selection The selection when the wizard was initiated.
- */
- private boolean initializeFromSelection(IStructuredSelection selection) {
- if (selection == null) {
- return false;
- }
-
- // Find the best match in the element list. In case there are multiple selected elements
- // select the one that provides the most information and assign them a score,
- // e.g. project=1 + folder=2 + file=4.
- IProject targetProject = null;
- String targetWsFolderPath = null;
- String targetFileName = null;
- int targetScore = 0;
- for (Object element : selection.toList()) {
- if (element instanceof IAdaptable) {
- IResource res = (IResource) ((IAdaptable) element).getAdapter(IResource.class);
- IProject project = res != null ? res.getProject() : null;
-
- // Is this an Android project?
- try {
- if (project == null || !project.hasNature(AdtConstants.NATURE_DEFAULT)) {
- continue;
- }
- } catch (CoreException e) {
- // checking the nature failed, ignore this resource
- continue;
- }
-
- int score = 1; // we have a valid project at least
-
- IPath wsFolderPath = null;
- String fileName = null;
- assert res != null; // Eclipse incorrectly thinks res could be null, so tell it no
- if (res.getType() == IResource.FOLDER) {
- wsFolderPath = res.getProjectRelativePath();
- } else if (res.getType() == IResource.FILE) {
- if (SdkUtils.endsWithIgnoreCase(res.getName(), DOT_XML)) {
- fileName = res.getName();
- }
- wsFolderPath = res.getParent().getProjectRelativePath();
- }
-
- // Disregard this folder selection if it doesn't point to /res/something
- if (wsFolderPath != null &&
- wsFolderPath.segmentCount() > 1 &&
- SdkConstants.FD_RESOURCES.equals(wsFolderPath.segment(0))) {
- score += 2;
- } else {
- wsFolderPath = null;
- fileName = null;
- }
-
- score += fileName != null ? 4 : 0;
-
- if (score > targetScore) {
- targetScore = score;
- targetProject = project;
- targetWsFolderPath = wsFolderPath != null ? wsFolderPath.toString() : null;
- targetFileName = fileName;
- }
- } else if (element instanceof Pair<?,?>) {
- // Pair of Project/String
- @SuppressWarnings("unchecked")
- Pair<IProject,String> pair = (Pair<IProject,String>)element;
- targetScore = 1;
- targetProject = pair.getFirst();
- targetWsFolderPath = pair.getSecond();
- targetFileName = "";
- }
- }
-
- if (targetProject == null) {
- // Try to figure out the project from the active editor
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- if (window != null) {
- IWorkbenchPage page = window.getActivePage();
- if (page != null) {
- IEditorPart activeEditor = page.getActiveEditor();
- if (activeEditor instanceof AndroidXmlEditor) {
- Object input = ((AndroidXmlEditor) activeEditor).getEditorInput();
- if (input instanceof FileEditorInput) {
- FileEditorInput fileInput = (FileEditorInput) input;
- targetScore = 1;
- IFile file = fileInput.getFile();
- targetProject = file.getProject();
- IPath path = file.getParent().getProjectRelativePath();
- targetWsFolderPath = path != null ? path.toString() : null;
- }
- }
- }
- }
- }
-
- if (targetProject == null) {
- // If we didn't find a default project based on the selection, check how many
- // open Android projects we can find in the current workspace. If there's only
- // one, we'll just select it by default.
- IJavaProject[] projects = AdtUtils.getOpenAndroidProjects();
- if (projects != null && projects.length == 1) {
- targetScore = 1;
- targetProject = projects[0].getProject();
- }
- }
-
- // Now set the UI accordingly
- if (targetScore > 0) {
- mValues.project = targetProject;
- mValues.folderPath = targetWsFolderPath;
- mProjectButton.setSelectedProject(targetProject);
- mFileNameTextField.setText(targetFileName != null ? targetFileName : ""); //$NON-NLS-1$
-
- // If the current selection context corresponds to a specific file type,
- // select it.
- if (targetWsFolderPath != null) {
- int pos = targetWsFolderPath.lastIndexOf(WS_SEP_CHAR);
- if (pos >= 0) {
- targetWsFolderPath = targetWsFolderPath.substring(pos + 1);
- }
- String[] folderSegments = targetWsFolderPath.split(RES_QUALIFIER_SEP);
- if (folderSegments.length > 0) {
- mValues.configuration = FolderConfiguration.getConfig(folderSegments);
- String folderName = folderSegments[0];
- selectTypeFromFolder(folderName);
- }
- }
- }
-
- return true;
- }
-
- private void initializeFromFixedType() {
- if (mInitialFolderType != null) {
- for (TypeInfo type : sTypes) {
- if (type.getResFolderType() == mInitialFolderType) {
- mValues.type = type;
- updateFolderPath(type);
- break;
- }
- }
- }
- }
-
- /**
- * Given a folder name, such as "drawable", select the corresponding type in
- * the dropdown.
- */
- void selectTypeFromFolder(String folderName) {
- List<TypeInfo> matches = new ArrayList<TypeInfo>();
- boolean selected = false;
-
- TypeInfo selectedType = getSelectedType();
- for (TypeInfo type : sTypes) {
- if (type.getResFolderName().equals(folderName)) {
- matches.add(type);
- selected |= type == selectedType;
- }
- }
-
- if (matches.size() == 1) {
- // If there's only one match, select it if it's not already selected
- if (!selected) {
- selectType(matches.get(0));
- }
- } else if (matches.size() > 1) {
- // There are multiple type candidates for this folder. This can happen
- // for /res/xml for example. Check to see if one of them is currently
- // selected. If yes, leave the selection unchanged. If not, deselect all type.
- if (!selected) {
- selectType(null);
- }
- } else {
- // Nothing valid was selected.
- selectType(null);
- }
- }
-
- /**
- * Initialize the root values of the type infos based on the current framework values.
- */
- private void initializeRootValues() {
- IProject project = mValues.project;
- for (TypeInfo type : sTypes) {
- // Clear all the roots for this type
- ArrayList<String> roots = type.getRoots();
- if (roots.size() > 0) {
- roots.clear();
- }
-
- // depending of the type of the seed, initialize the root in different ways
- Object rootSeed = type.getRootSeed();
-
- if (rootSeed instanceof String) {
- // The seed is a single string, Add it as-is.
- roots.add((String) rootSeed);
- } else if (rootSeed instanceof String[]) {
- // The seed is an array of strings. Add them as-is.
- for (String value : (String[]) rootSeed) {
- roots.add(value);
- }
- } else if (rootSeed instanceof Integer && project != null) {
- // The seed is a descriptor reference defined in AndroidTargetData.DESCRIPTOR_*
- // In this case add all the children element descriptors defined, recursively,
- // and avoid infinite recursion by keeping track of what has already been added.
-
- // Note: if project is null, the root list will be empty since it has been
- // cleared above.
-
- // get the AndroidTargetData from the project
- IAndroidTarget target = null;
- AndroidTargetData data = null;
-
- target = Sdk.getCurrent().getTarget(project);
- if (target == null) {
- // A project should have a target. The target can be missing if the project
- // is an old project for which a target hasn't been affected or if the
- // target no longer exists in this SDK. Simply log the error and dismiss.
-
- AdtPlugin.log(IStatus.INFO,
- "NewXmlFile wizard: no platform target for project %s", //$NON-NLS-1$
- project.getName());
- continue;
- } else {
- data = Sdk.getCurrent().getTargetData(target);
-
- if (data == null) {
- // We should have both a target and its data.
- // However if the wizard is invoked whilst the platform is still being
- // loaded we can end up in a weird case where we have a target but it
- // doesn't have any data yet.
- // Lets log a warning and silently ignore this root.
-
- AdtPlugin.log(IStatus.INFO,
- "NewXmlFile wizard: no data for target %s, project %s", //$NON-NLS-1$
- target.getName(), project.getName());
- continue;
- }
- }
-
- IDescriptorProvider provider = data.getDescriptorProvider((Integer)rootSeed);
- ElementDescriptor descriptor = provider.getDescriptor();
- if (descriptor != null) {
- HashSet<ElementDescriptor> visited = new HashSet<ElementDescriptor>();
- initRootElementDescriptor(roots, descriptor, visited);
- }
-
- // Sort alphabetically.
- Collections.sort(roots);
- }
- }
- }
-
- /**
- * Helper method to recursively insert all XML names for the given {@link ElementDescriptor}
- * into the roots array list. Keeps track of visited nodes to avoid infinite recursion.
- * Also avoids inserting the top {@link DocumentDescriptor} which is generally synthetic
- * and not a valid root element.
- */
- private void initRootElementDescriptor(ArrayList<String> roots,
- ElementDescriptor desc, HashSet<ElementDescriptor> visited) {
- if (!(desc instanceof DocumentDescriptor)) {
- String xmlName = desc.getXmlName();
- if (xmlName != null && xmlName.length() > 0) {
- roots.add(xmlName);
- }
- }
-
- visited.add(desc);
-
- for (ElementDescriptor child : desc.getChildren()) {
- if (!visited.contains(child)) {
- initRootElementDescriptor(roots, child, visited);
- }
- }
- }
-
- /**
- * Changes mProject to the given new project and update the UI accordingly.
- * <p/>
- * Note that this does not check if the new project is the same as the current one
- * on purpose, which allows a project to be updated when its target has changed or
- * when targets are loaded in the background.
- */
- private void changeProject(IProject newProject) {
- mValues.project = newProject;
-
- // enable types based on new API level
- updateAvailableTypes();
- initialSelectType();
-
- // update the folder name based on API level
- updateFolderPath(mValues.type);
-
- // update the Type with the new descriptors.
- initializeRootValues();
-
- // update the combo
- updateRootCombo(mValues.type);
-
- validatePage();
- }
-
- private void onSelectType(TypeInfo type) {
- // Do nothing if this is an internal modification or if the widget has been
- // deselected.
- if (mInternalTypeUpdate) {
- return;
- }
-
- mValues.type = type;
-
- if (type == null) {
- return;
- }
-
- // update the combo
- updateRootCombo(type);
-
- // update the folder path
- updateFolderPath(type);
-
- validatePage();
- }
-
- /** Updates the selected type in the type dropdown control */
- private void setSelectedType(TypeInfo type) {
- TypeInfo[] types = (TypeInfo[]) mTypeCombo.getData();
- if (types != null) {
- for (int i = 0, n = types.length; i < n; i++) {
- if (types[i] == type) {
- mTypeCombo.select(i);
- break;
- }
- }
- }
- }
-
- /** Returns the selected type in the type dropdown control */
- private TypeInfo getSelectedType() {
- int index = mTypeCombo.getSelectionIndex();
- if (index != -1) {
- TypeInfo[] types = (TypeInfo[]) mTypeCombo.getData();
- return types[index];
- }
-
- return null;
- }
-
- /** Returns the selected index in the type dropdown control */
- private int getTypeComboIndex(TypeInfo type) {
- TypeInfo[] types = (TypeInfo[]) mTypeCombo.getData();
- for (int i = 0, n = types.length; i < n; i++) {
- if (type == types[i]) {
- return i;
- }
- }
-
- return -1;
- }
-
- /** Updates the folder path to reflect the given type */
- private void updateFolderPath(TypeInfo type) {
- String wsFolderPath = mValues.folderPath;
- String newPath = null;
- FolderConfiguration config = mValues.configuration;
- ResourceQualifier qual = config.getInvalidQualifier();
- if (qual == null) {
- // The configuration is valid. Reformat the folder path using the canonical
- // value from the configuration.
- newPath = RES_FOLDER_ABS + config.getFolderName(type.getResFolderType());
- } else {
- // The configuration is invalid. We still update the path but this time
- // do it manually on the string.
- if (wsFolderPath.startsWith(RES_FOLDER_ABS)) {
- wsFolderPath = wsFolderPath.replaceFirst(
- "^(" + RES_FOLDER_ABS +")[^-]*(.*)", //$NON-NLS-1$ //$NON-NLS-2$
- "\\1" + type.getResFolderName() + "\\2"); //$NON-NLS-1$ //$NON-NLS-2$
- } else {
- newPath = RES_FOLDER_ABS + config.getFolderName(type.getResFolderType());
- }
- }
-
- if (newPath != null && !newPath.equals(wsFolderPath)) {
- mValues.folderPath = newPath;
- }
- }
-
- /**
- * Helper method that fills the values of the "root element" combo box based
- * on the currently selected type radio button. Also disables the combo is there's
- * only one choice. Always select the first root element for the given type.
- *
- * @param type The currently selected {@link TypeInfo}, or null
- */
- private void updateRootCombo(TypeInfo type) {
- IBaseLabelProvider labelProvider = new ColumnLabelProvider() {
- @Override
- public Image getImage(Object element) {
- return IconFactory.getInstance().getIcon(element.toString());
- }
- };
- mRootTableViewer.setContentProvider(new ArrayContentProvider());
- mRootTableViewer.setLabelProvider(labelProvider);
-
- if (type != null) {
- // get the list of roots. The list can be empty but not null.
- ArrayList<String> roots = type.getRoots();
- mRootTableViewer.setInput(roots.toArray());
-
- int index = 0; // default is to select the first one
- String defaultRoot = type.getDefaultRoot(mValues.project);
- if (defaultRoot != null) {
- index = roots.indexOf(defaultRoot);
- }
- mRootTable.select(index < 0 ? 0 : index);
- mRootTable.showSelection();
- }
- }
-
- /**
- * Helper method to select the current type in the type dropdown
- *
- * @param type The TypeInfo matching the radio button to selected or null to deselect them all.
- */
- private void selectType(TypeInfo type) {
- mInternalTypeUpdate = true;
- mValues.type = type;
- if (type == null) {
- if (mTypeCombo.getSelectionIndex() != -1) {
- mTypeCombo.deselect(mTypeCombo.getSelectionIndex());
- }
- } else {
- setSelectedType(type);
- }
- updateRootCombo(type);
- mInternalTypeUpdate = false;
- }
-
- /**
- * Add the available types in the type combobox, based on whether they are available
- * for the current SDK.
- * <p/>
- * A type is available either if:
- * - if mProject is null, API level 1 is considered valid
- * - if mProject is !null, the project->target->API must be >= to the type's API level.
- */
- private void updateAvailableTypes() {
- IProject project = mValues.project;
- IAndroidTarget target = project != null ? Sdk.getCurrent().getTarget(project) : null;
- int currentApiLevel = 1;
- if (target != null) {
- currentApiLevel = target.getVersion().getApiLevel();
- }
-
- List<String> items = new ArrayList<String>(sTypes.length);
- List<TypeInfo> types = new ArrayList<TypeInfo>(sTypes.length);
- for (int i = 0, n = sTypes.length; i < n; i++) {
- TypeInfo type = sTypes[i];
- if (type.getTargetApiLevel() <= currentApiLevel) {
- items.add(type.getUiName());
- types.add(type);
- }
- }
- mTypeCombo.setItems(items.toArray(new String[items.size()]));
- mTypeCombo.setData(types.toArray(new TypeInfo[types.size()]));
- }
-
- /**
- * Validates the fields, displays errors and warnings.
- * Enables the finish button if there are no errors.
- */
- private void validatePage() {
- String error = null;
- String warning = null;
-
- // -- validate type
- TypeInfo type = mValues.type;
- if (error == null) {
- if (type == null) {
- error = "One of the types must be selected (e.g. layout, values, etc.)";
- }
- }
-
- // -- validate project
- if (mValues.project == null) {
- error = "Please select an Android project.";
- }
-
- // -- validate type API level
- if (error == null) {
- IAndroidTarget target = Sdk.getCurrent().getTarget(mValues.project);
- int currentApiLevel = 1;
- if (target != null) {
- currentApiLevel = target.getVersion().getApiLevel();
- }
-
- assert type != null;
- if (type.getTargetApiLevel() > currentApiLevel) {
- error = "The API level of the selected type (e.g. AppWidget, etc.) is not " +
- "compatible with the API level of the project.";
- }
- }
-
- // -- validate filename
- if (error == null) {
- String fileName = mValues.getFileName();
- assert type != null;
- ResourceFolderType folderType = type.getResFolderType();
- error = ResourceNameValidator.create(true, folderType).isValid(fileName);
- }
-
- // -- validate destination file doesn't exist
- if (error == null) {
- IFile file = mValues.getDestinationFile();
- if (file != null && file.exists()) {
- warning = "The destination file already exists";
- }
- }
-
- // -- update UI & enable finish if there's no error
- setPageComplete(error == null);
- if (error != null) {
- setMessage(error, IMessageProvider.ERROR);
- } else if (warning != null) {
- setMessage(warning, IMessageProvider.WARNING);
- } else {
- setErrorMessage(null);
- setMessage(null);
- }
- }
-
- /**
- * Returns the {@link TypeInfo} for the given {@link ResourceFolderType}, or null if
- * not found
- *
- * @param folderType the {@link ResourceFolderType} to look for
- * @return the corresponding {@link TypeInfo}
- */
- static TypeInfo getTypeInfo(ResourceFolderType folderType) {
- for (TypeInfo typeInfo : sTypes) {
- if (typeInfo.getResFolderType() == folderType) {
- return typeInfo;
- }
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newxmlfile/NewXmlFileWizard.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newxmlfile/NewXmlFileWizard.java
deleted file mode 100644
index 16cd7b355..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/newxmlfile/NewXmlFileWizard.java
+++ /dev/null
@@ -1,431 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.newxmlfile;
-
-import static com.android.SdkConstants.FQCN_GRID_LAYOUT;
-import static com.android.SdkConstants.GRID_LAYOUT;
-
-import com.android.SdkConstants;
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.common.xml.XmlFormatStyle;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.formatting.EclipseXmlFormatPreferences;
-import com.android.ide.eclipse.adt.internal.editors.formatting.EclipseXmlPrettyPrinter;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderPreviewManager;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.project.SupportLibraryHelper;
-import com.android.ide.eclipse.adt.internal.wizards.newxmlfile.NewXmlFileCreationPage.TypeInfo;
-import com.android.resources.ResourceFolderType;
-import com.android.utils.Pair;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.INewWizard;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.PartInitException;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.io.UnsupportedEncodingException;
-
-/**
- * The "New Android XML File Wizard" provides the ability to create skeleton XML
- * resources files for Android projects.
- * <p/>
- * The wizard has one page, {@link NewXmlFileCreationPage}, used to select the project,
- * the resource folder, resource type and file name. It then creates the XML file.
- */
-public class NewXmlFileWizard extends Wizard implements INewWizard {
- /** The XML header to write at the top of the XML file */
- public static final String XML_HEADER_LINE = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"; //$NON-NLS-1$
-
- private static final String PROJECT_LOGO_LARGE = "android-64"; //$NON-NLS-1$
-
- protected static final String MAIN_PAGE_NAME = "newAndroidXmlFilePage"; //$NON-NLS-1$
-
- private NewXmlFileCreationPage mMainPage;
- private ChooseConfigurationPage mConfigPage;
- private Values mValues;
-
- @Override
- public void init(IWorkbench workbench, IStructuredSelection selection) {
- setHelpAvailable(false); // TODO have help
- setWindowTitle("New Android XML File");
- setImageDescriptor();
-
- mValues = new Values();
- mMainPage = createMainPage(mValues);
- mMainPage.setTitle("New Android XML File");
- mMainPage.setDescription("Creates a new Android XML file.");
- mMainPage.setInitialSelection(selection);
-
- mConfigPage = new ChooseConfigurationPage(mValues);
-
- // Trigger a check to see if the SDK needs to be reloaded (which will
- // invoke onSdkLoaded asynchronously as needed).
- AdtPlugin.getDefault().refreshSdk();
- }
-
- /**
- * Creates the wizard page.
- * <p/>
- * Please do NOT override this method.
- * <p/>
- * This is protected so that it can be overridden by unit tests.
- * However the contract of this class is private and NO ATTEMPT will be made
- * to maintain compatibility between different versions of the plugin.
- */
- protected NewXmlFileCreationPage createMainPage(NewXmlFileWizard.Values values) {
- return new NewXmlFileCreationPage(MAIN_PAGE_NAME, values);
- }
-
- // -- Methods inherited from org.eclipse.jface.wizard.Wizard --
- //
- // The Wizard class implements most defaults and boilerplate code needed by
- // IWizard
-
- /**
- * Adds pages to this wizard.
- */
- @Override
- public void addPages() {
- addPage(mMainPage);
- addPage(mConfigPage);
-
- }
-
- /**
- * Performs any actions appropriate in response to the user having pressed
- * the Finish button, or refuse if finishing now is not permitted: here, it
- * actually creates the workspace project and then switch to the Java
- * perspective.
- *
- * @return True
- */
- @Override
- public boolean performFinish() {
- final Pair<IFile, IRegion> created = createXmlFile();
- if (created == null) {
- return false;
- } else {
- // Open the file
- // This has to be delayed in order for focus handling to work correctly
- AdtPlugin.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- IFile file = created.getFirst();
- IRegion region = created.getSecond();
- try {
- IEditorPart editor = AdtPlugin.openFile(file, null,
- false /*showEditorTab*/);
- if (editor instanceof AndroidXmlEditor) {
- final AndroidXmlEditor xmlEditor = (AndroidXmlEditor)editor;
- if (!xmlEditor.hasMultiplePages()) {
- xmlEditor.show(region.getOffset(), region.getLength(),
- true /* showEditorTab */);
- }
- }
- } catch (PartInitException e) {
- AdtPlugin.log(e, "Failed to create %1$s: missing type", //$NON-NLS-1$
- file.getFullPath().toString());
- }
- }});
-
- return true;
- }
- }
-
- // -- Custom Methods --
-
- private Pair<IFile, IRegion> createXmlFile() {
- IFile file = mValues.getDestinationFile();
- TypeInfo type = mValues.type;
- if (type == null) {
- // this is not expected to happen
- String name = file.getFullPath().toString();
- AdtPlugin.log(IStatus.ERROR, "Failed to create %1$s: missing type", name); //$NON-NLS-1$
- return null;
- }
- String xmlns = type.getXmlns();
- String root = mMainPage.getRootElement();
- if (root == null) {
- // this is not expected to happen
- AdtPlugin.log(IStatus.ERROR, "Failed to create %1$s: missing root element", //$NON-NLS-1$
- file.toString());
- return null;
- }
-
- String attrs = type.getDefaultAttrs(mValues.project, root);
- String child = type.getChild(mValues.project, root);
- return createXmlFile(file, xmlns, root, attrs, child, type.getResFolderType());
- }
-
- /** Creates a new file using the given root element, namespace and root attributes */
- private static Pair<IFile, IRegion> createXmlFile(IFile file, String xmlns,
- String root, String rootAttributes, String child, ResourceFolderType folderType) {
- String name = file.getFullPath().toString();
- boolean need_delete = false;
-
- if (file.exists()) {
- if (!AdtPlugin.displayPrompt("New Android XML File",
- String.format("Do you want to overwrite the file %1$s ?", name))) {
- // abort if user selects cancel.
- return null;
- }
- need_delete = true;
- } else {
- AdtUtils.createWsParentDirectory(file.getParent());
- }
-
- StringBuilder sb = new StringBuilder(XML_HEADER_LINE);
-
- if (folderType == ResourceFolderType.LAYOUT && root.equals(GRID_LAYOUT)) {
- IProject project = file.getParent().getProject();
- int minSdk = ManifestInfo.get(project).getMinSdkVersion();
- if (minSdk < 14) {
- root = SupportLibraryHelper.getTagFor(project, FQCN_GRID_LAYOUT);
- if (root.equals(FQCN_GRID_LAYOUT)) {
- root = GRID_LAYOUT;
- }
- }
- }
-
- sb.append('<').append(root);
- if (xmlns != null) {
- sb.append('\n').append(" xmlns:android=\"").append(xmlns).append('"'); //$NON-NLS-1$
- }
-
- if (rootAttributes != null) {
- sb.append("\n "); //$NON-NLS-1$
- sb.append(rootAttributes.replace("\n", "\n ")); //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- sb.append(">\n"); //$NON-NLS-1$
-
- if (child != null) {
- sb.append(child);
- }
-
- boolean autoFormat = AdtPrefs.getPrefs().getUseCustomXmlFormatter();
-
- // Insert an indented caret. Since the markup here will be reformatted, we need to
- // insert text tokens that the formatter will preserve, which we can then turn back
- // into indentation and a caret offset:
- final String indentToken = "${indent}"; //$NON-NLS-1$
- final String caretToken = "${caret}"; //$NON-NLS-1$
- sb.append(indentToken);
- sb.append(caretToken);
- if (!autoFormat) {
- sb.append('\n');
- }
-
- sb.append("</").append(root).append(">\n"); //$NON-NLS-1$ //$NON-NLS-2$
-
- EclipseXmlFormatPreferences formatPrefs = EclipseXmlFormatPreferences.create();
- String fileContents;
- if (!autoFormat) {
- fileContents = sb.toString();
- } else {
- XmlFormatStyle style = EclipseXmlPrettyPrinter.getForFolderType(folderType);
- fileContents = EclipseXmlPrettyPrinter.prettyPrint(sb.toString(), formatPrefs,
- style, null /*lineSeparator*/);
- }
-
- // Remove marker tokens and replace them with whitespace
- fileContents = fileContents.replace(indentToken, formatPrefs.getOneIndentUnit());
- int caretOffset = fileContents.indexOf(caretToken);
- if (caretOffset != -1) {
- fileContents = fileContents.replace(caretToken, ""); //$NON-NLS-1$
- }
-
- String error = null;
- try {
- byte[] buf = fileContents.getBytes("UTF8"); //$NON-NLS-1$
- InputStream stream = new ByteArrayInputStream(buf);
- if (need_delete) {
- file.delete(IResource.KEEP_HISTORY | IResource.FORCE, null /*monitor*/);
- }
- file.create(stream, true /*force*/, null /*progress*/);
- IRegion region = caretOffset != -1 ? new Region(caretOffset, 0) : null;
-
- // If you introduced a new locale, or new screen variations etc, ensure that
- // the list of render previews is updated if necessary
- if (file.getParent().getName().indexOf('-') != -1
- && (folderType == ResourceFolderType.LAYOUT
- || folderType == ResourceFolderType.VALUES)) {
- RenderPreviewManager.bumpRevision();
- }
-
- return Pair.of(file, region);
- } catch (UnsupportedEncodingException e) {
- error = e.getMessage();
- } catch (CoreException e) {
- error = e.getMessage();
- }
-
- error = String.format("Failed to generate %1$s: %2$s", name, error);
- AdtPlugin.displayError("New Android XML File", error);
- return null;
- }
-
- /**
- * Returns true if the New XML Wizard can create new files of the given
- * {@link ResourceFolderType}
- *
- * @param folderType the folder type to create a file for
- * @return true if this wizard can create new files for the given folder type
- */
- public static boolean canCreateXmlFile(ResourceFolderType folderType) {
- TypeInfo typeInfo = NewXmlFileCreationPage.getTypeInfo(folderType);
- return typeInfo != null && (typeInfo.getDefaultRoot(null /*project*/) != null ||
- typeInfo.getRootSeed() instanceof String);
- }
-
- /**
- * Creates a new XML file using the template according to the given folder type
- *
- * @param project the project to create the file in
- * @param file the file to be created
- * @param folderType the type of folder to look up a template for
- * @return the created file
- */
- public static Pair<IFile, IRegion> createXmlFile(IProject project, IFile file,
- ResourceFolderType folderType) {
- TypeInfo type = NewXmlFileCreationPage.getTypeInfo(folderType);
- String xmlns = type.getXmlns();
- String root = type.getDefaultRoot(project);
- if (root == null) {
- root = type.getRootSeed().toString();
- }
- String attrs = type.getDefaultAttrs(project, root);
- return createXmlFile(file, xmlns, root, attrs, null, folderType);
- }
-
- /**
- * Returns an image descriptor for the wizard logo.
- */
- private void setImageDescriptor() {
- ImageDescriptor desc = IconFactory.getInstance().getImageDescriptor(PROJECT_LOGO_LARGE);
- setDefaultPageImageDescriptor(desc);
- }
-
- /**
- * Specific New XML File wizard tied to the {@link ResourceFolderType#LAYOUT} type
- */
- public static class NewLayoutWizard extends NewXmlFileWizard {
- /** Creates a new {@link NewLayoutWizard} */
- public NewLayoutWizard() {
- }
-
- @Override
- public void init(IWorkbench workbench, IStructuredSelection selection) {
- super.init(workbench, selection);
- setWindowTitle("New Android Layout XML File");
- super.mMainPage.setTitle("New Android Layout XML File");
- super.mMainPage.setDescription("Creates a new Android Layout XML file.");
- super.mMainPage.setInitialFolderType(ResourceFolderType.LAYOUT);
- }
- }
-
- /**
- * Specific New XML File wizard tied to the {@link ResourceFolderType#VALUES} type
- */
- public static class NewValuesWizard extends NewXmlFileWizard {
- /** Creates a new {@link NewValuesWizard} */
- public NewValuesWizard() {
- }
-
- @Override
- public void init(IWorkbench workbench, IStructuredSelection selection) {
- super.init(workbench, selection);
- setWindowTitle("New Android Values XML File");
- super.mMainPage.setTitle("New Android Values XML File");
- super.mMainPage.setDescription("Creates a new Android Values XML file.");
- super.mMainPage.setInitialFolderType(ResourceFolderType.VALUES);
- }
- }
-
- /** Value object which holds the current state of the wizard pages */
- public static class Values {
- /** The currently selected project, or null */
- public IProject project;
- /** The root name of the XML file to create, or null */
- public String name;
- /** The type of XML file to create */
- public TypeInfo type;
- /** The path within the project to create the new file in */
- public String folderPath;
- /** The currently chosen configuration */
- public FolderConfiguration configuration = new FolderConfiguration();
-
- /**
- * Returns the destination filename or an empty string.
- *
- * @return the filename, never null.
- */
- public String getFileName() {
- String fileName;
- if (name == null) {
- fileName = ""; //$NON-NLS-1$
- } else {
- fileName = name.trim();
- if (fileName.length() > 0 && fileName.indexOf('.') == -1) {
- fileName = fileName + SdkConstants.DOT_XML;
- }
- }
-
- return fileName;
- }
-
- /**
- * Returns a {@link IFile} for the destination file.
- * <p/>
- * Returns null if the project, filename or folder are invalid and the
- * destination file cannot be determined.
- * <p/>
- * The {@link IFile} is a resource. There might or might not be an
- * actual real file.
- *
- * @return an {@link IFile} for the destination file
- */
- public IFile getDestinationFile() {
- String fileName = getFileName();
- if (project != null && folderPath != null && folderPath.length() > 0
- && fileName.length() > 0) {
- IPath dest = new Path(folderPath).append(fileName);
- IFile file = project.getFile(dest);
- return file;
- }
- return null;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/ActivityPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/ActivityPage.java
deleted file mode 100644
index ba4aedc8a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/ActivityPage.java
+++ /dev/null
@@ -1,326 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.CATEGORY_ACTIVITIES;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.CATEGORY_OTHER;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.IS_LAUNCHER;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.PREVIEW_PADDING;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.PREVIEW_WIDTH;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.ImageControl;
-import com.google.common.collect.Lists;
-import com.google.common.io.Files;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.resource.JFaceResources;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.List;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-
-class ActivityPage extends WizardPage implements SelectionListener {
- private final NewProjectWizardState mValues;
- private List mList;
- private Button mCreateToggle;
- private java.util.List<File> mTemplates;
-
- private boolean mIgnore;
- private boolean mShown;
- private ImageControl mPreview;
- private Image mPreviewImage;
- private boolean mDisposePreviewImage;
- private Label mHeading;
- private Label mDescription;
- private boolean mOnlyActivities;
- private boolean mAskCreate;
- private boolean mLauncherActivitiesOnly;
-
- /**
- * Create the wizard.
- */
- ActivityPage(NewProjectWizardState values, boolean onlyActivities, boolean askCreate) {
- super("activityPage"); //$NON-NLS-1$
- mValues = values;
- mOnlyActivities = onlyActivities;
- mAskCreate = askCreate;
-
- if (onlyActivities) {
- setTitle("Create Activity");
- } else {
- setTitle("Create Android Object");
- }
- if (onlyActivities && askCreate) {
- setDescription(
- "Select whether to create an activity, and if so, what kind of activity.");
- } else {
- setDescription("Select which template to use");
- }
- }
-
- /** Sets whether the activity page should only offer launcher activities */
- void setLauncherActivitiesOnly(boolean launcherActivitiesOnly) {
- mLauncherActivitiesOnly = launcherActivitiesOnly;
- }
-
- @Override
- public void createControl(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
- setControl(container);
- }
-
- @SuppressWarnings("unused") // SWT constructors have side effects and aren't unused
- private void onEnter() {
- Composite container = (Composite) getControl();
- container.setLayout(new GridLayout(3, false));
-
- if (mAskCreate) {
- mCreateToggle = new Button(container, SWT.CHECK);
- mCreateToggle.setSelection(true);
- mCreateToggle.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 3, 1));
- mCreateToggle.setText("Create Activity");
- mCreateToggle.addSelectionListener(this);
- }
-
- mList = new List(container, SWT.BORDER | SWT.V_SCROLL);
- mList.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
-
-
- TemplateManager manager = mValues.template.getManager();
- java.util.List<File> templates = manager.getTemplates(CATEGORY_ACTIVITIES);
-
- if (!mOnlyActivities) {
- templates.addAll(manager.getTemplates(CATEGORY_OTHER));
- }
- java.util.List<String> names = new ArrayList<String>(templates.size());
- File current = mValues.activityValues.getTemplateLocation();
- mTemplates = Lists.newArrayListWithExpectedSize(templates.size());
- int index = -1;
- for (int i = 0, n = templates.size(); i < n; i++) {
- File template = templates.get(i);
- TemplateMetadata metadata = manager.getTemplate(template);
- if (metadata == null) {
- continue;
- }
- if (mLauncherActivitiesOnly) {
- Parameter parameter = metadata.getParameter(IS_LAUNCHER);
- if (parameter == null) {
- continue;
- }
- }
- mTemplates.add(template);
- names.add(metadata.getTitle());
- if (template.equals(current)) {
- index = names.size();
- }
- }
- String[] items = names.toArray(new String[names.size()]);
- mList.setItems(items);
- if (index == -1 && !mTemplates.isEmpty()) {
- mValues.activityValues.setTemplateLocation(mTemplates.get(0));
- index = 0;
- }
- if (index >= 0) {
- mList.setSelection(index);
- mList.addSelectionListener(this);
- }
-
- // Preview
- mPreview = new ImageControl(container, SWT.NONE, null);
- mPreview.setDisposeImage(false); // Handled manually in this class
- GridData gd_mImage = new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1);
- gd_mImage.widthHint = PREVIEW_WIDTH + 2 * PREVIEW_PADDING;
- mPreview.setLayoutData(gd_mImage);
- new Label(container, SWT.NONE);
-
- mHeading = new Label(container, SWT.NONE);
- mHeading.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
- new Label(container, SWT.NONE);
-
- mDescription = new Label(container, SWT.WRAP);
- mDescription.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 2, 1));
-
- Font font = JFaceResources.getFontRegistry().getBold(JFaceResources.BANNER_FONT);
- if (font != null) {
- mHeading.setFont(font);
- }
-
- updatePreview();
- }
-
- private void updatePreview() {
- Image oldImage = mPreviewImage;
- boolean dispose = mDisposePreviewImage;
- mPreviewImage = null;
-
- String title = "";
- String description = "";
- TemplateHandler handler = mValues.activityValues.getTemplateHandler();
- TemplateMetadata template = handler.getTemplate();
- if (template != null) {
- String thumb = template.getThumbnailPath();
- if (thumb != null && !thumb.isEmpty()) {
- File file = new File(mValues.activityValues.getTemplateLocation(),
- thumb.replace('/', File.separatorChar));
- if (file != null) {
- try {
- byte[] bytes = Files.toByteArray(file);
- ByteArrayInputStream input = new ByteArrayInputStream(bytes);
- mPreviewImage = new Image(getControl().getDisplay(), input);
- mDisposePreviewImage = true;
- input.close();
- } catch (IOException e) {
- AdtPlugin.log(e, null);
- }
- }
- } else {
- // Fallback icon
- mDisposePreviewImage = false;
- mPreviewImage = TemplateMetadata.getDefaultTemplateIcon();
- }
- title = template.getTitle();
- description = template.getDescription();
- }
-
- mHeading.setText(title);
- mDescription.setText(description);
- mPreview.setImage(mPreviewImage);
- mPreview.fitToWidth(PREVIEW_WIDTH);
-
- if (oldImage != null && dispose) {
- oldImage.dispose();
- }
-
- Composite parent = (Composite) getControl();
- parent.layout(true, true);
- parent.redraw();
- }
-
- @Override
- public void dispose() {
- super.dispose();
-
- if (mPreviewImage != null && mDisposePreviewImage) {
- mDisposePreviewImage = false;
- mPreviewImage.dispose();
- mPreviewImage = null;
- }
- }
-
- @Override
- public void setVisible(boolean visible) {
- if (visible && !mShown) {
- onEnter();
- }
-
- super.setVisible(visible);
-
- if (visible) {
- mShown = true;
- if (mAskCreate) {
- try {
- mIgnore = true;
- mCreateToggle.setSelection(mValues.createActivity);
- } finally {
- mIgnore = false;
- }
- }
- }
-
- validatePage();
- }
-
-
- private void validatePage() {
- IStatus status = null;
-
- if (mValues.createActivity) {
- if (mList.getSelectionCount() < 1) {
- status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "Select an activity type");
- } else {
- TemplateHandler templateHandler = mValues.activityValues.getTemplateHandler();
- status = templateHandler.validateTemplate(mValues.minSdkLevel,
- mValues.getBuildApi());
- }
- }
-
- setPageComplete(status == null || status.getSeverity() != IStatus.ERROR);
- if (status != null) {
- setMessage(status.getMessage(),
- status.getSeverity() == IStatus.ERROR
- ? IMessageProvider.ERROR : IMessageProvider.WARNING);
- } else {
- setErrorMessage(null);
- setMessage(null);
- }
- }
-
- @Override
- public boolean isPageComplete() {
- // Ensure that the Finish button isn't enabled until
- // the user has reached and completed this page
- if (!mShown && mValues.createActivity) {
- return false;
- }
-
- return super.isPageComplete();
- }
-
- // ---- Implements SelectionListener ----
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (mIgnore) {
- return;
- }
-
- Object source = e.getSource();
- if (source == mCreateToggle) {
- mValues.createActivity = mCreateToggle.getSelection();
- mList.setEnabled(mValues.createActivity);
- } else if (source == mList) {
- int index = mList.getSelectionIndex();
- if (index >= 0 && index < mTemplates.size()) {
- File template = mTemplates.get(index);
- mValues.activityValues.setTemplateLocation(template);
- updatePreview();
- }
- }
-
- validatePage();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/CreateFileChange.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/CreateFileChange.java
deleted file mode 100644
index 3b41c36c2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/CreateFileChange.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import com.android.annotations.NonNull;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.google.common.io.Closeables;
-import com.google.common.io.Files;
-import com.google.common.io.InputSupplier;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.core.runtime.SubProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.resource.ResourceChange;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.InputStream;
-import java.net.URI;
-
-/** Change which lazily copies a file */
-public class CreateFileChange extends ResourceChange {
- private String mName;
- private final IPath mPath;
- private final File mSource;
-
- CreateFileChange(@NonNull String name, @NonNull IPath workspacePath, File source) {
- mName = name;
- mPath = workspacePath;
- mSource = source;
- }
-
- @Override
- protected IResource getModifiedResource() {
- return ResourcesPlugin.getWorkspace().getRoot().getFile(mPath);
- }
-
- @Override
- public String getName() {
- return mName;
- }
-
- @Override
- public RefactoringStatus isValid(IProgressMonitor pm)
- throws CoreException, OperationCanceledException {
- RefactoringStatus result = new RefactoringStatus();
- IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(mPath);
- URI location = file.getLocationURI();
- if (location == null) {
- result.addFatalError("Unknown location " + file.getFullPath().toString());
- return result;
- }
- return result;
- }
-
- @SuppressWarnings("resource") // Eclipse doesn't know about Guava's Closeables.closeQuietly
- @Override
- public Change perform(IProgressMonitor pm) throws CoreException {
- InputSupplier<FileInputStream> supplier = Files.newInputStreamSupplier(mSource);
- InputStream is = null;
- try {
- pm.beginTask("Creating file", 3);
- IFile file = (IFile) getModifiedResource();
-
- IContainer parent = file.getParent();
- if (parent != null && !parent.exists()) {
- IFolder folder = ResourcesPlugin.getWorkspace().getRoot().getFolder(
- parent.getFullPath());
- AdtUtils.ensureExists(folder);
- }
-
- is = supplier.getInput();
- file.create(is, false, new SubProgressMonitor(pm, 1));
- pm.worked(1);
- } catch (Exception ioe) {
- AdtPlugin.log(ioe, null);
- } finally {
- Closeables.closeQuietly(is);
- pm.done();
- }
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmActivityToLayoutMethod.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmActivityToLayoutMethod.java
deleted file mode 100644
index fbd50e986..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmActivityToLayoutMethod.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectPage.ACTIVITY_NAME_SUFFIX;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectPage.LAYOUT_NAME_PREFIX;
-
-import com.android.ide.eclipse.adt.AdtUtils;
-
-import freemarker.template.SimpleScalar;
-import freemarker.template.TemplateMethodModel;
-import freemarker.template.TemplateModel;
-import freemarker.template.TemplateModelException;
-
-import java.util.List;
-
-/**
- * Method invoked by FreeMarker to convert an Activity class name into
- * a suitable layout name.
- */
-public class FmActivityToLayoutMethod implements TemplateMethodModel {
- @Override
- public TemplateModel exec(List args) throws TemplateModelException {
- if (args.size() != 1) {
- throw new TemplateModelException("Wrong arguments");
- }
-
- String activityName = args.get(0).toString();
-
- if (activityName.isEmpty()) {
- return new SimpleScalar("");
- }
-
- // Strip off the end portion of the activity name. The user might be typing
- // the activity name such that only a portion has been entered so far (e.g.
- // "MainActivi") and we want to chop off that portion too such that we don't
- // offer a layout name partially containing the activity suffix (e.g. "main_activi").
- int suffixStart = activityName.lastIndexOf(ACTIVITY_NAME_SUFFIX.charAt(0));
- if (suffixStart != -1 && activityName.regionMatches(suffixStart, ACTIVITY_NAME_SUFFIX, 0,
- activityName.length() - suffixStart)) {
- activityName = activityName.substring(0, suffixStart);
- }
- assert !activityName.endsWith(ACTIVITY_NAME_SUFFIX) : activityName;
-
- // Convert CamelCase convention used in activity class names to underlined convention
- // used in layout name:
- String name = LAYOUT_NAME_PREFIX + AdtUtils.camelCaseToUnderlines(activityName);
-
- return new SimpleScalar(name);
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmCamelCaseToUnderscoreMethod.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmCamelCaseToUnderscoreMethod.java
deleted file mode 100644
index b85576577..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmCamelCaseToUnderscoreMethod.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import com.android.ide.eclipse.adt.AdtUtils;
-
-import freemarker.template.SimpleScalar;
-import freemarker.template.TemplateMethodModel;
-import freemarker.template.TemplateModel;
-import freemarker.template.TemplateModelException;
-
-import java.util.List;
-
-/**
- * Method invoked by FreeMarker to convert an underscore name into a CamelCase name.
- */
-public class FmCamelCaseToUnderscoreMethod implements TemplateMethodModel {
- @Override
- public TemplateModel exec(List args) throws TemplateModelException {
- if (args.size() != 1) {
- throw new TemplateModelException("Wrong arguments");
- }
- return new SimpleScalar(AdtUtils.camelCaseToUnderlines(args.get(0).toString()));
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmClassNameToResourceMethod.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmClassNameToResourceMethod.java
deleted file mode 100644
index 366de9afa..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmClassNameToResourceMethod.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectPage.ACTIVITY_NAME_SUFFIX;
-
-import com.android.ide.eclipse.adt.AdtUtils;
-
-import freemarker.template.SimpleScalar;
-import freemarker.template.TemplateMethodModel;
-import freemarker.template.TemplateModel;
-import freemarker.template.TemplateModelException;
-
-import java.util.List;
-
-/**
- * Similar to {@link FmCamelCaseToUnderscoreMethod}, but strips off common class
- * suffixes such as "Activity", "Fragment", etc.
- */
-public class FmClassNameToResourceMethod implements TemplateMethodModel {
- @Override
- public TemplateModel exec(List args) throws TemplateModelException {
- if (args.size() != 1) {
- throw new TemplateModelException("Wrong arguments");
- }
-
- String name = args.get(0).toString();
-
- if (name.isEmpty()) {
- return new SimpleScalar("");
- }
-
- name = stripSuffix(name, ACTIVITY_NAME_SUFFIX);
- name = stripSuffix(name, "Fragment"); //$NON-NLS-1$
- name = stripSuffix(name, "Service"); //$NON-NLS-1$
- name = stripSuffix(name, "Provider"); //$NON-NLS-1$
-
- return new SimpleScalar(AdtUtils.camelCaseToUnderlines(name));
- }
-
- // Strip off the end portion of the activity name. The user might be typing
- // the activity name such that only a portion has been entered so far (e.g.
- // "MainActivi") and we want to chop off that portion too such that we don't
- private static String stripSuffix(String name, String suffix) {
- int suffixStart = name.lastIndexOf(suffix.charAt(0));
- if (suffixStart != -1 && name.regionMatches(suffixStart, suffix, 0,
- name.length() - suffixStart)) {
- name = name.substring(0, suffixStart);
- }
- assert !name.endsWith(suffix) : name;
-
- return name;
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmEscapeXmlAttributeMethod.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmEscapeXmlAttributeMethod.java
deleted file mode 100644
index 21f33b8d7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmEscapeXmlAttributeMethod.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import com.android.utils.XmlUtils;
-
-import freemarker.template.SimpleScalar;
-import freemarker.template.TemplateMethodModel;
-import freemarker.template.TemplateModel;
-import freemarker.template.TemplateModelException;
-
-import java.util.List;
-
-/**
- * Method invoked by FreeMarker to escape a string such that it can be used
- * as an XML attribute (escaping ', ", & and <).
- */
-public class FmEscapeXmlAttributeMethod implements TemplateMethodModel {
- @Override
- public TemplateModel exec(List args) throws TemplateModelException {
- if (args.size() != 1) {
- throw new TemplateModelException("Wrong arguments");
- }
- String string = args.get(0).toString();
- return new SimpleScalar(XmlUtils.toXmlAttributeValue(string));
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmEscapeXmlStringMethod.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmEscapeXmlStringMethod.java
deleted file mode 100644
index 2255653a7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmEscapeXmlStringMethod.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import com.android.ide.common.res2.ValueXmlHelper;
-
-import freemarker.template.SimpleScalar;
-import freemarker.template.TemplateMethodModel;
-import freemarker.template.TemplateModel;
-import freemarker.template.TemplateModelException;
-
-import java.util.List;
-
-/**
- * Method invoked by FreeMarker to escape a string such that it can be placed
- * as text in a string resource file.
- * This is similar to {@link FmEscapeXmlTextMethod}, but in addition to escaping
- * &lt; and &amp; it also escapes characters such as quotes necessary for Android
- *{@code <string>} elements.
- */
-public class FmEscapeXmlStringMethod implements TemplateMethodModel {
- @Override
- public TemplateModel exec(List args) throws TemplateModelException {
- if (args.size() != 1) {
- throw new TemplateModelException("Wrong arguments");
- }
- String string = args.get(0).toString();
- return new SimpleScalar(ValueXmlHelper.escapeResourceString(string));
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmEscapeXmlTextMethod.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmEscapeXmlTextMethod.java
deleted file mode 100644
index 55a4bc8ab..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmEscapeXmlTextMethod.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import com.android.utils.XmlUtils;
-
-import freemarker.template.SimpleScalar;
-import freemarker.template.TemplateMethodModel;
-import freemarker.template.TemplateModel;
-import freemarker.template.TemplateModelException;
-
-import java.util.List;
-
-/**
- * Method invoked by FreeMarker to escape a string such that it can be used
- * as XML text (escaping < and &, but not ' and " etc).
- */
-public class FmEscapeXmlTextMethod implements TemplateMethodModel {
- @Override
- public TemplateModel exec(List args) throws TemplateModelException {
- if (args.size() != 1) {
- throw new TemplateModelException("Wrong arguments");
- }
- String string = args.get(0).toString();
- return new SimpleScalar(XmlUtils.toXmlTextValue(string));
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmExtractLettersMethod.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmExtractLettersMethod.java
deleted file mode 100644
index 09fa81c57..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmExtractLettersMethod.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import freemarker.template.SimpleScalar;
-import freemarker.template.TemplateMethodModel;
-import freemarker.template.TemplateModel;
-import freemarker.template.TemplateModelException;
-
-import java.util.List;
-
-/**
- * Method invoked by FreeMarker to extract letters from a string; this will remove
- * any whitespace, punctuation and digits.
- */
-public class FmExtractLettersMethod implements TemplateMethodModel {
- @Override
- public TemplateModel exec(List args) throws TemplateModelException {
- if (args.size() != 1) {
- throw new TemplateModelException("Wrong arguments");
- }
- String string = args.get(0).toString();
- StringBuilder sb = new StringBuilder(string.length());
- for (int i = 0, n = string.length(); i < n; i++) {
- char c = string.charAt(i);
- if (Character.isLetter(c)) {
- sb.append(c);
- }
- }
- return new SimpleScalar(sb.toString());
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmLayoutToActivityMethod.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmLayoutToActivityMethod.java
deleted file mode 100644
index 6514959f7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmLayoutToActivityMethod.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import static com.android.ide.eclipse.adt.AdtUtils.extractClassName;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectPage.ACTIVITY_NAME_SUFFIX;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectPage.LAYOUT_NAME_PREFIX;
-
-import com.android.ide.eclipse.adt.AdtUtils;
-
-import freemarker.template.SimpleScalar;
-import freemarker.template.TemplateMethodModel;
-import freemarker.template.TemplateModel;
-import freemarker.template.TemplateModelException;
-
-import java.util.List;
-
-/**
- * Method invoked by FreeMarker to convert a layout name into an appropriate
- * Activity class.
- */
-public class FmLayoutToActivityMethod implements TemplateMethodModel {
- @Override
- public TemplateModel exec(List args) throws TemplateModelException {
- if (args.size() != 1) {
- throw new TemplateModelException("Wrong arguments");
- }
-
- String name = args.get(0).toString();
-
- // Strip off the beginning portion of the layout name. The user might be typing
- // the activity name such that only a portion has been entered so far (e.g.
- // "MainActivi") and we want to chop off that portion too such that we don't
- // offer a layout name partially containing the activity suffix (e.g. "main_activi").
- if (name.startsWith(LAYOUT_NAME_PREFIX)) {
- name = name.substring(LAYOUT_NAME_PREFIX.length());
- }
-
- name = AdtUtils.underlinesToCamelCase(name);
- String className = extractClassName(name);
- if (className == null) {
- className = "My";
- }
- String activityName = className + ACTIVITY_NAME_SUFFIX;
-
- return new SimpleScalar(activityName);
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmSlashedPackageNameMethod.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmSlashedPackageNameMethod.java
deleted file mode 100644
index 60a6531e6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmSlashedPackageNameMethod.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import freemarker.template.SimpleScalar;
-import freemarker.template.TemplateMethodModel;
-import freemarker.template.TemplateModel;
-import freemarker.template.TemplateModelException;
-
-import java.util.List;
-
-/**
- * Method invoked by FreeMarker to convert a package name (foo.bar) into
- * a slashed path (foo/bar)
- */
-public class FmSlashedPackageNameMethod implements TemplateMethodModel {
-
- @Override
- public TemplateModel exec(List args) throws TemplateModelException {
- if (args.size() != 1) {
- throw new TemplateModelException("Wrong arguments");
- }
-
- return new SimpleScalar(args.get(0).toString().replace('.', '/'));
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmUnderscoreToCamelCaseMethod.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmUnderscoreToCamelCaseMethod.java
deleted file mode 100644
index 26d4fadb4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/FmUnderscoreToCamelCaseMethod.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import com.android.ide.eclipse.adt.AdtUtils;
-
-import freemarker.template.SimpleScalar;
-import freemarker.template.TemplateMethodModel;
-import freemarker.template.TemplateModel;
-import freemarker.template.TemplateModelException;
-
-import java.util.List;
-
-/**
- * Method invoked by FreeMarker to convert a CamelCase word into
- * underscore_names.
- */
-public class FmUnderscoreToCamelCaseMethod implements TemplateMethodModel {
- @Override
- public TemplateModel exec(List args) throws TemplateModelException {
- if (args.size() != 1) {
- throw new TemplateModelException("Wrong arguments");
- }
- return new SimpleScalar(AdtUtils.underlinesToCamelCase(args.get(0).toString()));
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/InstallDependencyPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/InstallDependencyPage.java
deleted file mode 100644
index d806e7970..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/InstallDependencyPage.java
+++ /dev/null
@@ -1,298 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.actions.AddSupportJarAction;
-import com.android.utils.Pair;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.wizard.IWizard;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.browser.IWebBrowser;
-
-import java.io.File;
-import java.net.URL;
-import java.util.List;
-
-class InstallDependencyPage extends WizardPage implements SelectionListener {
- /**
- * The compatibility library. This is the only library the templates
- * currently support. The appearance of any other dependency in this
- * template will be flagged as a validation error (and the user encouraged
- * to upgrade to a newer ADT
- */
- static final String SUPPORT_LIBRARY_NAME = "android-support-v4"; //$NON-NLS-1$
-
- /** URL containing more info */
- private static final String URL =
- "http://developer.android.com/tools/extras/support-library.html"; //$NON-NLS-1$
-
- private Button mCheckButton;
- private Button mInstallButton;
- private Link mLink;
- private TemplateMetadata mTemplate;
-
- InstallDependencyPage() {
- super("dependency"); //$NON-NLS-1$
- setTitle("Install Dependencies");
- }
-
- void setTemplate(TemplateMetadata template) {
- if (template != mTemplate) {
- mTemplate = template;
- if (getControl() != null) {
- validatePage();
- }
- }
- }
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- if (visible) {
- updateVersionLabels();
- validatePage();
- }
- }
-
- @Override
- public void createControl(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
- setControl(container);
- container.setLayout(new GridLayout(2, false));
- // Remaining contents are created lazily, since this page is always added to
- // the page list, but typically not shown
-
- Label dependLabel = new Label(container, SWT.WRAP);
- GridData gd_dependLabel = new GridData(SWT.LEFT, SWT.TOP, true, false, 2, 1);
- gd_dependLabel.widthHint = NewTemplatePage.WIZARD_PAGE_WIDTH - 50;
- dependLabel.setLayoutData(gd_dependLabel);
- dependLabel.setText("This template depends on the Android Support library, which is " +
- "either not installed, or the template depends on a more recent version than " +
- "the one you have installed.");
-
- mLink = new Link(container, SWT.NONE);
- mLink.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 2, 1));
- mLink.setText("<a href=\"" + URL + "\">" + URL + "</a>"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- mLink.addSelectionListener(this);
-
- Label lblNewLabel_1 = new Label(container, SWT.NONE);
- lblNewLabel_1.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
-
- requiredLabel = new Label(container, SWT.NONE);
- requiredLabel.setText("Required version:");
-
- mRequiredVersion = new Label(container, SWT.NONE);
- mRequiredVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
-
- installedLabel = new Label(container, SWT.NONE);
- installedLabel.setText("Installed version:");
-
- mInstalledVersion = new Label(container, SWT.NONE);
- mInstalledVersion.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1));
-
- Label lblNewLabel = new Label(container, SWT.NONE);
- lblNewLabel.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
-
- Label descLabel = new Label(container, SWT.WRAP);
- GridData gd_descLabel = new GridData(SWT.LEFT, SWT.TOP, true, false, 2, 1);
- gd_descLabel.widthHint = 550;
- descLabel.setLayoutData(gd_descLabel);
- descLabel.setText(
- "You can install or upgrade it by clicking the Install button below, or " +
- "alternatively, you can install it outside of Eclipse with the SDK Manager, " +
- "then click on \"Check Again\" to proceed.");
-
- mInstallButton = new Button(container, SWT.NONE);
- mInstallButton.setText("Install/Upgrade");
- mInstallButton.addSelectionListener(this);
-
- mCheckButton = new Button(container, SWT.NONE);
- mCheckButton.setText("Check Again");
- mCheckButton.addSelectionListener(this);
-
- mInstallButton.setFocus();
- }
-
- private void showNextPage() {
- validatePage();
- if (isPageComplete()) {
- // Finish button will be enabled now
- mInstallButton.setEnabled(false);
- mCheckButton.setEnabled(false);
-
- IWizard wizard = getWizard();
- IWizardPage next = wizard.getNextPage(this);
- if (next != null) {
- wizard.getContainer().showPage(next);
- }
- }
- }
-
- @Override
- public boolean isPageComplete() {
- if (mTemplate == null) {
- return true;
- }
-
- return super.isPageComplete() && isInstalled();
- }
-
- private boolean isInstalled() {
- return isInstalled(mTemplate.getDependencies());
- }
-
- static String sCachedName;
- static int sCachedVersion;
- private Label requiredLabel;
- private Label installedLabel;
- private Label mRequiredVersion;
- private Label mInstalledVersion;
-
- public static boolean isInstalled(List<Pair<String, Integer>> dependencies) {
- for (Pair<String, Integer> dependency : dependencies) {
- String name = dependency.getFirst();
- int required = dependency.getSecond();
-
- int installed = -1;
- if (SUPPORT_LIBRARY_NAME.equals(name)) {
- installed = getInstalledSupportLibVersion();
- }
-
- if (installed == -1) {
- return false;
- }
- if (required > installed) {
- return false;
- }
- }
-
- return true;
- }
-
- private static int getInstalledSupportLibVersion() {
- if (SUPPORT_LIBRARY_NAME.equals(sCachedName)) {
- return sCachedVersion;
- } else {
- int version = AddSupportJarAction.getInstalledRevision();
- sCachedName = SUPPORT_LIBRARY_NAME;
- sCachedVersion = version;
- return version;
- }
- }
-
- private void updateVersionLabels() {
- int version = getInstalledSupportLibVersion();
- if (version == -1) {
- mInstalledVersion.setText("Not installed");
- } else {
- mInstalledVersion.setText(Integer.toString(version));
- }
-
- if (mTemplate != null) {
- for (Pair<String, Integer> dependency : mTemplate.getDependencies()) {
- String name = dependency.getFirst();
- if (name.equals(SUPPORT_LIBRARY_NAME)) {
- int required = dependency.getSecond();
- mRequiredVersion.setText(Integer.toString(required));
- break;
- }
- }
- }
- }
-
- private void validatePage() {
- if (mTemplate == null) {
- return;
- }
-
- IStatus status = null;
-
- List<Pair<String, Integer>> dependencies = mTemplate.getDependencies();
- if (dependencies.size() > 1 || dependencies.size() == 1
- && !dependencies.get(0).getFirst().equals(SUPPORT_LIBRARY_NAME)) {
- status = new Status(IStatus.WARNING, AdtPlugin.PLUGIN_ID,
- "Unsupported template dependency: Upgrade your Android Eclipse plugin");
- }
-
- setPageComplete(status == null || status.getSeverity() != IStatus.ERROR);
- if (status != null) {
- setMessage(status.getMessage(),
- status.getSeverity() == IStatus.ERROR
- ? IMessageProvider.ERROR : IMessageProvider.WARNING);
- } else {
- setErrorMessage(null);
- setMessage(null);
- }
- }
-
- // ---- Implements SelectionListener ----
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- Object source = e.getSource();
- if (source == mCheckButton) {
- sCachedName = null;
- if (isInstalled()) {
- showNextPage();
- }
- updateVersionLabels();
- } else if (source == mInstallButton) {
- sCachedName = null;
- for (Pair<String, Integer> dependency : mTemplate.getDependencies()) {
- String name = dependency.getFirst();
- if (SUPPORT_LIBRARY_NAME.equals(name)) {
- int version = dependency.getSecond();
- File installed = AddSupportJarAction.installSupport(version);
- if (installed != null) {
- showNextPage();
- }
- updateVersionLabels();
- }
- }
- } else if (source == mLink) {
- try {
- IWorkbench workbench = PlatformUI.getWorkbench();
- IWebBrowser browser = workbench.getBrowserSupport().getExternalBrowser();
- browser.openURL(new URL(URL));
- } catch (Exception ex) {
- String message = String.format("Could not open browser. Vist\n%1$s\ninstead.",
- URL);
- MessageDialog.openError(getShell(), "Browser Error", message);
- }
- }
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewActivityWizard.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewActivityWizard.java
deleted file mode 100644
index b33d65bb7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewActivityWizard.java
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.ATTR_BUILD_API;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.ATTR_MIN_API;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.ATTR_MIN_API_LEVEL;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.ATTR_PACKAGE_NAME;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.ATTR_TARGET_API;
-import static org.eclipse.core.resources.IResource.DEPTH_INFINITE;
-
-import com.android.annotations.NonNull;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.ui.IWorkbench;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.List;
-import java.util.Set;
-
-/**
- * Wizard for creating new activities. This is a hybrid between a New Project
- * Wizard and a New Template Wizard: it has the "Activity selector" page from
- * the New Project Wizard, which is used to dynamically select a wizard for the
- * second page, but beyond that it runs the normal template wizard when it comes
- * time to create the template.
- */
-public class NewActivityWizard extends TemplateWizard {
- private NewTemplatePage mTemplatePage;
- private ActivityPage mActivityPage;
- private NewProjectWizardState mValues;
- private NewTemplateWizardState mActivityValues;
- protected boolean mOnlyActivities;
-
- /** Creates a new {@link NewActivityWizard} */
- public NewActivityWizard() {
- mOnlyActivities = true;
- }
-
- @Override
- protected boolean shouldAddIconPage() {
- return mActivityValues.getIconState() != null;
- }
-
- @Override
- public void init(IWorkbench workbench, IStructuredSelection selection) {
- super.init(workbench, selection);
-
- setWindowTitle(mOnlyActivities ? "New Activity" : "New Android Object");
-
- mValues = new NewProjectWizardState();
- mActivityPage = new ActivityPage(mValues, mOnlyActivities, false);
-
- mActivityValues = mValues.activityValues;
- List<IProject> projects = AdtUtils.getSelectedProjects(selection);
- if (projects.size() == 1) {
- mActivityValues.project = projects.get(0);
- }
- }
-
- @Override
- public void addPages() {
- super.addPages();
- addPage(mActivityPage);
- }
-
- @Override
- public IWizardPage getNextPage(IWizardPage page) {
- if (page == mActivityPage) {
- if (mTemplatePage == null) {
- Set<String> hidden = mActivityValues.hidden;
- hidden.add(ATTR_PACKAGE_NAME);
- hidden.add(ATTR_MIN_API);
- hidden.add(ATTR_MIN_API_LEVEL);
- hidden.add(ATTR_TARGET_API);
- hidden.add(ATTR_BUILD_API);
-
- mTemplatePage = new NewTemplatePage(mActivityValues, true);
- addPage(mTemplatePage);
- }
- return mTemplatePage;
- } else if (page == mTemplatePage && shouldAddIconPage()) {
- WizardPage iconPage = getIconPage(mActivityValues.getIconState());
- mActivityValues.updateIconState(mTemplatePage.getEvaluator());
- return iconPage;
- } else if (page == mTemplatePage
- || shouldAddIconPage() && page == getIconPage(mActivityValues.getIconState())) {
- TemplateMetadata template = mActivityValues.getTemplateHandler().getTemplate();
- if (template != null) {
- if (InstallDependencyPage.isInstalled(template.getDependencies())) {
- return getPreviewPage(mActivityValues);
- } else {
- return getDependencyPage(template, true);
- }
- }
- } else {
- TemplateMetadata template = mActivityValues.getTemplateHandler().getTemplate();
- if (template != null && page == getDependencyPage(template, false)) {
- return getPreviewPage(mActivityValues);
- }
- }
-
- return super.getNextPage(page);
- }
-
- @Override
- public boolean canFinish() {
- // Deal with lazy creation of some pages: these may not be in the page-list yet
- // since they are constructed lazily, so consider that option here.
- if (mTemplatePage == null || !mTemplatePage.isPageComplete()) {
- return false;
- }
-
- return super.canFinish();
- }
-
- @Override
- public boolean performFinish(IProgressMonitor monitor) throws InvocationTargetException {
- boolean success = super.performFinish(monitor);
-
- if (success) {
- List<Runnable> finalizingTasks = getFinalizingActions();
- for (Runnable r : finalizingTasks) {
- r.run();
- }
- return true;
- }
- return false;
- }
-
- @Override
- @NonNull
- protected IProject getProject() {
- return mActivityValues.project;
- }
-
- @Override
- @NonNull
- protected List<String> getFilesToOpen() {
- TemplateHandler activityTemplate = mActivityValues.getTemplateHandler();
- return activityTemplate.getFilesToOpen();
- }
-
- @Override
- @NonNull
- protected List<Runnable> getFinalizingActions() {
- TemplateHandler activityTemplate = mActivityValues.getTemplateHandler();
- return activityTemplate.getFinalizingActions();
- }
-
- @Override
- protected List<Change> computeChanges() {
- return mActivityValues.computeChanges();
- }
-
- /** Wizard for creating other Android components */
- public static class OtherWizard extends NewActivityWizard {
- /** Create new {@link OtherWizard} */
- public OtherWizard() {
- mOnlyActivities = false;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewProjectPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewProjectPage.java
deleted file mode 100644
index 14f59c00d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewProjectPage.java
+++ /dev/null
@@ -1,931 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.ide.eclipse.adt.AdtUtils.extractClassName;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewTemplatePage.WIZARD_PAGE_WIDTH;
-
-import com.android.annotations.Nullable;
-import com.android.sdklib.SdkVersionInfo;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.internal.wizards.newproject.ApplicationInfoPage;
-import com.android.ide.eclipse.adt.internal.wizards.newproject.ProjectNamePage;
-import com.android.sdklib.AndroidVersion;
-import com.android.sdklib.IAndroidTarget;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.fieldassist.ControlDecoration;
-import org.eclipse.jface.fieldassist.FieldDecoration;
-import org.eclipse.jface.fieldassist.FieldDecorationRegistry;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.FocusEvent;
-import org.eclipse.swt.events.FocusListener;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-/**
- * First wizard page in the "New Project From Template" wizard
- */
-public class NewProjectPage extends WizardPage
- implements ModifyListener, SelectionListener, FocusListener {
- private static final int FIELD_WIDTH = 300;
- private static final String SAMPLE_PACKAGE_PREFIX = "com.example."; //$NON-NLS-1$
- /** Suffix added by default to activity names */
- static final String ACTIVITY_NAME_SUFFIX = "Activity"; //$NON-NLS-1$
- /** Prefix added to default layout names */
- static final String LAYOUT_NAME_PREFIX = "activity_"; //$NON-NLS-1$
- private static final int INITIAL_MIN_SDK = 8;
-
- private final NewProjectWizardState mValues;
- private Map<String, Integer> mMinNameToApi;
- private Parameter mThemeParameter;
- private Combo mThemeCombo;
-
- private Text mProjectText;
- private Text mPackageText;
- private Text mApplicationText;
- private Combo mMinSdkCombo;
- private Combo mTargetSdkCombo;
- private Combo mBuildSdkCombo;
- private Label mHelpIcon;
- private Label mTipLabel;
-
- private boolean mIgnore;
- private ControlDecoration mApplicationDec;
- private ControlDecoration mProjectDec;
- private ControlDecoration mPackageDec;
- private ControlDecoration mBuildTargetDec;
- private ControlDecoration mMinSdkDec;
- private ControlDecoration mTargetSdkDec;
- private ControlDecoration mThemeDec;
-
- NewProjectPage(NewProjectWizardState values) {
- super("newAndroidApp"); //$NON-NLS-1$
- mValues = values;
- setTitle("New Android Application");
- setDescription("Creates a new Android Application");
- }
-
- @SuppressWarnings("unused") // SWT constructors have side effects and aren't unused
- @Override
- public void createControl(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
- setControl(container);
- GridLayout gl_container = new GridLayout(4, false);
- gl_container.horizontalSpacing = 10;
- container.setLayout(gl_container);
-
- Label applicationLabel = new Label(container, SWT.NONE);
- applicationLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 2, 1));
- applicationLabel.setText("Application Name:");
-
- mApplicationText = new Text(container, SWT.BORDER);
- GridData gdApplicationText = new GridData(SWT.LEFT, SWT.CENTER, true, false, 2, 1);
- gdApplicationText.widthHint = FIELD_WIDTH;
- mApplicationText.setLayoutData(gdApplicationText);
- mApplicationText.addModifyListener(this);
- mApplicationText.addFocusListener(this);
- mApplicationDec = createFieldDecoration(mApplicationText,
- "The application name is shown in the Play Store, as well as in the " +
- "Manage Application list in Settings.");
-
- Label projectLabel = new Label(container, SWT.NONE);
- projectLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 2, 1));
- projectLabel.setText("Project Name:");
- mProjectText = new Text(container, SWT.BORDER);
- GridData gdProjectText = new GridData(SWT.LEFT, SWT.CENTER, true, false, 2, 1);
- gdProjectText.widthHint = FIELD_WIDTH;
- mProjectText.setLayoutData(gdProjectText);
- mProjectText.addModifyListener(this);
- mProjectText.addFocusListener(this);
- mProjectDec = createFieldDecoration(mProjectText,
- "The project name is only used by Eclipse, but must be unique within the " +
- "workspace. This can typically be the same as the application name.");
-
- Label packageLabel = new Label(container, SWT.NONE);
- packageLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 2, 1));
- packageLabel.setText("Package Name:");
-
- mPackageText = new Text(container, SWT.BORDER);
- GridData gdPackageText = new GridData(SWT.LEFT, SWT.CENTER, true, false, 2, 1);
- gdPackageText.widthHint = FIELD_WIDTH;
- mPackageText.setLayoutData(gdPackageText);
- mPackageText.addModifyListener(this);
- mPackageText.addFocusListener(this);
- mPackageDec = createFieldDecoration(mPackageText,
- "The package name must be a unique identifier for your application.\n" +
- "It is typically not shown to users, but it *must* stay the same " +
- "for the lifetime of your application; it is how multiple versions " +
- "of the same application are considered the \"same app\".\nThis is " +
- "typically the reverse domain name of your organization plus one or " +
- "more application identifiers, and it must be a valid Java package " +
- "name.");
- new Label(container, SWT.NONE);
-
- new Label(container, SWT.NONE);
- new Label(container, SWT.NONE);
- new Label(container, SWT.NONE);
-
- // Min SDK
-
- Label minSdkLabel = new Label(container, SWT.NONE);
- minSdkLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 2, 1));
- minSdkLabel.setText("Minimum Required SDK:");
-
- mMinSdkCombo = new Combo(container, SWT.READ_ONLY);
- GridData gdMinSdkCombo = new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1);
- gdMinSdkCombo.widthHint = FIELD_WIDTH;
- mMinSdkCombo.setLayoutData(gdMinSdkCombo);
-
- // Pick most recent platform
- IAndroidTarget[] targets = getCompilationTargets();
- mMinNameToApi = Maps.newHashMap();
- List<String> targetLabels = new ArrayList<String>(targets.length);
- for (IAndroidTarget target : targets) {
- String targetLabel;
- if (target.isPlatform()
- && target.getVersion().getApiLevel() <= AdtUtils.getHighestKnownApiLevel()) {
- targetLabel = AdtUtils.getAndroidName(target.getVersion().getApiLevel());
- } else {
- targetLabel = AdtUtils.getTargetLabel(target);
- }
- targetLabels.add(targetLabel);
- mMinNameToApi.put(targetLabel, target.getVersion().getApiLevel());
- }
-
- List<String> codeNames = Lists.newArrayList();
- int buildTargetIndex = -1;
- for (int i = 0, n = targets.length; i < n; i++) {
- IAndroidTarget target = targets[i];
- AndroidVersion version = target.getVersion();
- int apiLevel = version.getApiLevel();
- if (version.isPreview()) {
- String codeName = version.getCodename();
- String targetLabel = codeName + " Preview";
- codeNames.add(targetLabel);
- mMinNameToApi.put(targetLabel, apiLevel);
- } else if (target.isPlatform()
- && (mValues.target == null ||
- apiLevel > mValues.target.getVersion().getApiLevel())) {
- mValues.target = target;
- buildTargetIndex = i;
- }
- }
- List<String> labels = new ArrayList<String>(24);
- for (String label : AdtUtils.getKnownVersions()) {
- labels.add(label);
- }
- assert labels.size() >= 15; // *Known* versions to ADT, not installed/available versions
- for (String codeName : codeNames) {
- labels.add(codeName);
- }
- String[] versions = labels.toArray(new String[labels.size()]);
- mMinSdkCombo.setItems(versions);
- if (mValues.target != null && mValues.target.getVersion().isPreview()) {
- mValues.minSdk = mValues.target.getVersion().getCodename();
- mMinSdkCombo.setText(mValues.minSdk);
- mValues.iconState.minSdk = mValues.target.getVersion().getApiLevel();
- mValues.minSdkLevel = mValues.iconState.minSdk;
- } else {
- mMinSdkCombo.select(INITIAL_MIN_SDK - 1);
- mValues.minSdk = Integer.toString(INITIAL_MIN_SDK);
- mValues.minSdkLevel = INITIAL_MIN_SDK;
- mValues.iconState.minSdk = INITIAL_MIN_SDK;
- }
- mMinSdkCombo.addSelectionListener(this);
- mMinSdkCombo.addFocusListener(this);
- mMinSdkDec = createFieldDecoration(mMinSdkCombo,
- "Choose the lowest version of Android that your application will support. Lower " +
- "API levels target more devices, but means fewer features are available. By " +
- "targeting API 8 and later, you reach approximately 95% of the market.");
- new Label(container, SWT.NONE);
-
- // Target SDK
- Label targetSdkLabel = new Label(container, SWT.NONE);
- targetSdkLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 2, 1));
- targetSdkLabel.setText("Target SDK:");
-
- mTargetSdkCombo = new Combo(container, SWT.READ_ONLY);
- GridData gdTargetSdkCombo = new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1);
- gdTargetSdkCombo.widthHint = FIELD_WIDTH;
- mTargetSdkCombo.setLayoutData(gdTargetSdkCombo);
-
- mTargetSdkCombo.setItems(versions);
- mTargetSdkCombo.select(mValues.targetSdkLevel - 1);
-
- mTargetSdkCombo.addSelectionListener(this);
- mTargetSdkCombo.addFocusListener(this);
- mTargetSdkDec = createFieldDecoration(mTargetSdkCombo,
- "Choose the highest API level that the application is known to work with. " +
- "This attribute informs the system that you have tested against the target " +
- "version and the system should not enable any compatibility behaviors to " +
- "maintain your app's forward-compatibility with the target version. " +
- "The application is still able to run on older versions " +
- "(down to minSdkVersion). Your application may look dated if you are not " +
- "targeting the current version.");
- new Label(container, SWT.NONE);
-
- // Build Version
-
- Label buildSdkLabel = new Label(container, SWT.NONE);
- buildSdkLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 2, 1));
- buildSdkLabel.setText("Compile With:");
-
- mBuildSdkCombo = new Combo(container, SWT.READ_ONLY);
- GridData gdBuildSdkCombo = new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1);
- gdBuildSdkCombo.widthHint = FIELD_WIDTH;
- mBuildSdkCombo.setLayoutData(gdBuildSdkCombo);
- mBuildSdkCombo.setData(targets);
- mBuildSdkCombo.setItems(targetLabels.toArray(new String[targetLabels.size()]));
- if (buildTargetIndex != -1) {
- mBuildSdkCombo.select(buildTargetIndex);
- }
-
- mBuildSdkCombo.addSelectionListener(this);
- mBuildSdkCombo.addFocusListener(this);
- mBuildTargetDec = createFieldDecoration(mBuildSdkCombo,
- "Choose a target API to compile your code against, from your installed SDKs. " +
- "This is typically the most recent version, or the first version that supports " +
- "all the APIs you want to directly access without reflection.");
- new Label(container, SWT.NONE);
-
- TemplateMetadata metadata = mValues.template.getTemplate();
- if (metadata != null) {
- mThemeParameter = metadata.getParameter("baseTheme"); //$NON-NLS-1$
- if (mThemeParameter != null && mThemeParameter.element != null) {
- Label themeLabel = new Label(container, SWT.NONE);
- themeLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 2, 1));
- themeLabel.setText("Theme:");
-
- mThemeCombo = NewTemplatePage.createOptionCombo(mThemeParameter, container,
- mValues.parameters, this, this);
- GridData gdThemeCombo = new GridData(SWT.LEFT, SWT.CENTER, true, false, 1, 1);
- gdThemeCombo.widthHint = FIELD_WIDTH;
- mThemeCombo.setLayoutData(gdThemeCombo);
- new Label(container, SWT.NONE);
-
- mThemeDec = createFieldDecoration(mThemeCombo,
- "Choose the base theme to use for the application");
- }
- }
-
- new Label(container, SWT.NONE);
- new Label(container, SWT.NONE);
- new Label(container, SWT.NONE);
- new Label(container, SWT.NONE);
-
- Label label = new Label(container, SWT.SEPARATOR | SWT.HORIZONTAL);
- label.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 4, 1));
-
- mHelpIcon = new Label(container, SWT.NONE);
- mHelpIcon.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false, 1, 1));
- Image icon = IconFactory.getInstance().getIcon("quickfix");
- mHelpIcon.setImage(icon);
- mHelpIcon.setVisible(false);
-
- mTipLabel = new Label(container, SWT.WRAP);
- mTipLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1));
-
- // Reserve space for 4 lines
- mTipLabel.setText("\n\n\n\n"); //$NON-NLS-1$
-
- // Reserve enough width to accommodate the various wizard pages up front
- // (since they are created lazily, and we don't want the wizard to dynamically
- // resize itself for small size adjustments as each successive page is slightly
- // larger)
- Label dummy = new Label(container, SWT.NONE);
- GridData data = new GridData();
- data.horizontalSpan = 4;
- data.widthHint = WIZARD_PAGE_WIDTH;
- dummy.setLayoutData(data);
- }
-
- /**
- * Updates the theme selection such that it's valid for the current build
- * and min sdk targets. Also runs {@link #validatePage} in case no valid entry was found.
- * Does nothing if called on a template that does not supply a theme.
- */
- void updateTheme() {
- if (mThemeParameter != null) {
- // Pick the highest theme version that works for the current SDK level
- Parameter parameter = NewTemplatePage.getParameter(mThemeCombo);
- assert parameter == mThemeParameter;
- if (parameter != null) {
- String[] optionIds = (String[]) mThemeCombo.getData(ATTR_ID);
- for (int index = optionIds.length - 1; index >= 0; index--) {
- IStatus status = NewTemplatePage.validateCombo(null, mThemeParameter,
- index, mValues.minSdkLevel, mValues.getBuildApi());
- if (status == null || status.isOK()) {
- String optionId = optionIds[index];
- parameter.value = optionId;
- parameter.edited = optionId != null && !optionId.toString().isEmpty();
- mValues.parameters.put(parameter.id, optionId);
- try {
- mIgnore = true;
- mThemeCombo.select(index);
- } finally {
- mIgnore = false;
- }
- break;
- }
- }
- }
-
- validatePage();
- }
- }
-
- private IAndroidTarget[] getCompilationTargets() {
- Sdk current = Sdk.getCurrent();
- if (current == null) {
- return new IAndroidTarget[0];
- }
- IAndroidTarget[] targets = current.getTargets();
- List<IAndroidTarget> list = new ArrayList<IAndroidTarget>();
-
- for (IAndroidTarget target : targets) {
- if (target.isPlatform() == false &&
- (target.getOptionalLibraries() == null ||
- target.getOptionalLibraries().length == 0)) {
- continue;
- }
- list.add(target);
- }
-
- return list.toArray(new IAndroidTarget[list.size()]);
- }
-
- private ControlDecoration createFieldDecoration(Control control, String description) {
- ControlDecoration dec = new ControlDecoration(control, SWT.LEFT);
- dec.setMarginWidth(2);
- FieldDecoration errorFieldIndicator = FieldDecorationRegistry.getDefault().
- getFieldDecoration(FieldDecorationRegistry.DEC_INFORMATION);
- dec.setImage(errorFieldIndicator.getImage());
- dec.setDescriptionText(description);
- control.setToolTipText(description);
-
- return dec;
- }
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
-
- // DURING DEVELOPMENT ONLY
- //if (assertionsEnabled()) {
- // String uniqueProjectName = AdtUtils.getUniqueProjectName("Test", "");
- // mProjectText.setText(uniqueProjectName);
- // mPackageText.setText("test.pkg");
- //}
-
- validatePage();
- }
-
- // ---- Implements ModifyListener ----
-
- @Override
- public void modifyText(ModifyEvent e) {
- if (mIgnore) {
- return;
- }
-
- Object source = e.getSource();
- if (source == mProjectText) {
- mValues.projectName = mProjectText.getText();
- updateProjectLocation(mValues.projectName);
- mValues.projectModified = true;
-
- try {
- mIgnore = true;
- if (!mValues.applicationModified) {
- mValues.applicationName = mValues.projectName;
- mApplicationText.setText(mValues.projectName);
- }
- updateActivityNames(mValues.projectName);
- } finally {
- mIgnore = false;
- }
- suggestPackage(mValues.projectName);
- } else if (source == mPackageText) {
- mValues.packageName = mPackageText.getText();
- mValues.packageModified = true;
- } else if (source == mApplicationText) {
- mValues.applicationName = mApplicationText.getText();
- mValues.applicationModified = true;
-
- try {
- mIgnore = true;
- if (!mValues.projectModified) {
- mValues.projectName = appNameToProjectName(mValues.applicationName);
- mProjectText.setText(mValues.projectName);
- updateProjectLocation(mValues.projectName);
- }
- updateActivityNames(mValues.applicationName);
- } finally {
- mIgnore = false;
- }
- suggestPackage(mValues.applicationName);
- }
-
- validatePage();
- }
-
- private String appNameToProjectName(String appName) {
- // Strip out whitespace (and capitalize subsequent words where spaces were removed
- boolean upcaseNext = false;
- StringBuilder sb = new StringBuilder(appName.length());
- for (int i = 0, n = appName.length(); i < n; i++) {
- char c = appName.charAt(i);
- if (c == ' ') {
- upcaseNext = true;
- } else if (upcaseNext) {
- sb.append(Character.toUpperCase(c));
- upcaseNext = false;
- } else {
- sb.append(c);
- }
- }
-
- appName = sb.toString().trim();
-
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IStatus nameStatus = workspace.validateName(appName, IResource.PROJECT);
- if (nameStatus.isOK()) {
- return appName;
- }
-
- sb = new StringBuilder(appName.length());
- for (int i = 0, n = appName.length(); i < n; i++) {
- char c = appName.charAt(i);
- if (Character.isLetterOrDigit(c) || c == '.' || c == '-') {
- sb.append(c);
- }
- }
-
- return sb.toString().trim();
- }
-
- /** If the project should be created in the workspace, then update the project location
- * based on the project name. */
- private void updateProjectLocation(String projectName) {
- if (projectName == null) {
- projectName = "";
- }
-
- if (mValues.useDefaultLocation) {
- IPath workspace = Platform.getLocation();
- String projectLocation = workspace.append(projectName).toOSString();
- mValues.projectLocation = projectLocation;
- }
- }
-
- private void updateActivityNames(String name) {
- try {
- mIgnore = true;
- if (!mValues.activityNameModified) {
- mValues.activityName = extractClassName(name) + ACTIVITY_NAME_SUFFIX;
- }
- if (!mValues.activityTitleModified) {
- mValues.activityTitle = name;
- }
- } finally {
- mIgnore = false;
- }
- }
-
- // ---- Implements SelectionListener ----
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (mIgnore) {
- return;
- }
-
- Object source = e.getSource();
- if (source == mMinSdkCombo) {
- mValues.minSdk = getSelectedMinSdk();
- Integer minSdk = mMinNameToApi.get(mValues.minSdk);
- if (minSdk == null) {
- try {
- minSdk = Integer.parseInt(mValues.minSdk);
- } catch (NumberFormatException nufe) {
- // If not a number, then the string is a codename, so treat it
- // as a preview version.
- minSdk = SdkVersionInfo.HIGHEST_KNOWN_API + 1;
- }
- }
- mValues.iconState.minSdk = minSdk.intValue();
- mValues.minSdkLevel = minSdk.intValue();
-
- // If higher than build target, adjust build target
- if (mValues.minSdkLevel > mValues.getBuildApi()) {
- // Try to find a build target with an adequate build API
- IAndroidTarget[] targets = (IAndroidTarget[]) mBuildSdkCombo.getData();
- IAndroidTarget best = null;
- int bestApi = Integer.MAX_VALUE;
- int bestTargetIndex = -1;
- for (int i = 0; i < targets.length; i++) {
- IAndroidTarget target = targets[i];
- if (!target.isPlatform()) {
- continue;
- }
- int api = target.getVersion().getApiLevel();
- if (api >= mValues.minSdkLevel && api < bestApi) {
- best = target;
- bestApi = api;
- bestTargetIndex = i;
- }
- }
-
- if (best != null) {
- assert bestTargetIndex != -1;
- mValues.target = best;
- try {
- mIgnore = true;
- mBuildSdkCombo.select(bestTargetIndex);
- } finally {
- mIgnore = false;
- }
- }
- }
-
- // If higher than targetSdkVersion, adjust targetSdkVersion
- if (mValues.minSdkLevel > mValues.targetSdkLevel) {
- mValues.targetSdkLevel = mValues.minSdkLevel;
- try {
- mIgnore = true;
- setSelectedTargetSdk(mValues.targetSdkLevel);
- } finally {
- mIgnore = false;
- }
- }
- } else if (source == mBuildSdkCombo) {
- mValues.target = getSelectedBuildTarget();
-
- // If lower than min sdk target, adjust min sdk target
- if (mValues.target.getVersion().isPreview()) {
- mValues.minSdk = mValues.target.getVersion().getCodename();
- try {
- mIgnore = true;
- mMinSdkCombo.setText(mValues.minSdk);
- } finally {
- mIgnore = false;
- }
- } else {
- String minSdk = mValues.minSdk;
- int buildApiLevel = mValues.target.getVersion().getApiLevel();
- if (minSdk != null && !minSdk.isEmpty()
- && Character.isDigit(minSdk.charAt(0))
- && buildApiLevel < Integer.parseInt(minSdk)) {
- mValues.minSdk = Integer.toString(buildApiLevel);
- try {
- mIgnore = true;
- setSelectedMinSdk(buildApiLevel);
- } finally {
- mIgnore = false;
- }
- }
- }
- } else if (source == mTargetSdkCombo) {
- mValues.targetSdkLevel = getSelectedTargetSdk();
- }
-
- validatePage();
- }
-
- private String getSelectedMinSdk() {
- // If you're using a preview build, such as android-JellyBean, you have
- // to use the codename, e.g. JellyBean, as the minimum SDK as well.
- IAndroidTarget buildTarget = getSelectedBuildTarget();
- if (buildTarget != null && buildTarget.getVersion().isPreview()) {
- return buildTarget.getVersion().getCodename();
- }
-
- // +1: First API level (at index 0) is 1
- return Integer.toString(mMinSdkCombo.getSelectionIndex() + 1);
- }
-
- private int getSelectedTargetSdk() {
- // +1: First API level (at index 0) is 1
- return mTargetSdkCombo.getSelectionIndex() + 1;
- }
-
- private void setSelectedMinSdk(int api) {
- mMinSdkCombo.select(api - 1); // -1: First API level (at index 0) is 1
- }
-
- private void setSelectedTargetSdk(int api) {
- mTargetSdkCombo.select(api - 1); // -1: First API level (at index 0) is 1
- }
-
- @Nullable
- private IAndroidTarget getSelectedBuildTarget() {
- IAndroidTarget[] targets = (IAndroidTarget[]) mBuildSdkCombo.getData();
- int index = mBuildSdkCombo.getSelectionIndex();
- if (index >= 0 && index < targets.length) {
- return targets[index];
- } else {
- return null;
- }
- }
-
- private void suggestPackage(String original) {
- if (!mValues.packageModified) {
- // Create default package name
- StringBuilder sb = new StringBuilder();
- sb.append(SAMPLE_PACKAGE_PREFIX);
- appendPackage(sb, original);
-
- String pkg = sb.toString();
- if (pkg.endsWith(".")) { //$NON-NLS-1$
- pkg = pkg.substring(0, pkg.length() - 1);
- }
- mValues.packageName = pkg;
- try {
- mIgnore = true;
- mPackageText.setText(mValues.packageName);
- } finally {
- mIgnore = false;
- }
- }
- }
-
- private static void appendPackage(StringBuilder sb, String string) {
- for (int i = 0, n = string.length(); i < n; i++) {
- char c = string.charAt(i);
- if (i == 0 && Character.isJavaIdentifierStart(c)
- || i != 0 && Character.isJavaIdentifierPart(c)) {
- sb.append(Character.toLowerCase(c));
- } else if ((c == '.')
- && (sb.length() > 0 && sb.charAt(sb.length() - 1) != '.')) {
- sb.append('.');
- } else if (c == '-') {
- sb.append('_');
- }
- }
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
-
- // ---- Implements FocusListener ----
-
- @Override
- public void focusGained(FocusEvent e) {
- Object source = e.getSource();
- String tip = "";
- if (source == mApplicationText) {
- tip = mApplicationDec.getDescriptionText();
- } else if (source == mProjectText) {
- tip = mProjectDec.getDescriptionText();
- } else if (source == mBuildSdkCombo) {
- tip = mBuildTargetDec.getDescriptionText();
- } else if (source == mMinSdkCombo) {
- tip = mMinSdkDec.getDescriptionText();
- } else if (source == mPackageText) {
- tip = mPackageDec.getDescriptionText();
- if (mPackageText.getText().startsWith(SAMPLE_PACKAGE_PREFIX)) {
- int length = SAMPLE_PACKAGE_PREFIX.length();
- if (mPackageText.getText().length() > length
- && SAMPLE_PACKAGE_PREFIX.endsWith(".")) { //$NON-NLS-1$
- length--;
- }
- mPackageText.setSelection(0, length);
- }
- } else if (source == mTargetSdkCombo) {
- tip = mTargetSdkDec.getDescriptionText();
- } else if (source == mThemeCombo) {
- tip = mThemeDec.getDescriptionText();
- }
- mTipLabel.setText(tip);
- mHelpIcon.setVisible(tip.length() > 0);
- }
-
- @Override
- public void focusLost(FocusEvent e) {
- mTipLabel.setText("");
- mHelpIcon.setVisible(false);
- }
-
- // Validation
-
- private void validatePage() {
- IStatus status = mValues.template.validateTemplate(mValues.minSdkLevel,
- mValues.getBuildApi());
- if (status != null && !status.isOK()) {
- updateDecorator(mApplicationDec, null, true);
- updateDecorator(mPackageDec, null, true);
- updateDecorator(mProjectDec, null, true);
- updateDecorator(mThemeDec, null, true);
- /* These never get marked with errors:
- updateDecorator(mBuildTargetDec, null, true);
- updateDecorator(mMinSdkDec, null, true);
- updateDecorator(mTargetSdkDec, null, true);
- */
- } else {
- IStatus appStatus = validateAppName();
- if (appStatus != null && (status == null
- || appStatus.getSeverity() > status.getSeverity())) {
- status = appStatus;
- }
-
- IStatus projectStatus = validateProjectName();
- if (projectStatus != null && (status == null
- || projectStatus.getSeverity() > status.getSeverity())) {
- status = projectStatus;
- }
-
- IStatus packageStatus = validatePackageName();
- if (packageStatus != null && (status == null
- || packageStatus.getSeverity() > status.getSeverity())) {
- status = packageStatus;
- }
-
- IStatus locationStatus = ProjectContentsPage.validateLocationInWorkspace(mValues);
- if (locationStatus != null && (status == null
- || locationStatus.getSeverity() > status.getSeverity())) {
- status = locationStatus;
- }
-
- if (status == null || status.getSeverity() != IStatus.ERROR) {
- if (mValues.target == null) {
- status = new Status(IStatus.WARNING, AdtPlugin.PLUGIN_ID,
- "Select an Android build target version");
- }
- }
-
- if (status == null || status.getSeverity() != IStatus.ERROR) {
- if (mValues.minSdk == null || mValues.minSdk.isEmpty()) {
- status = new Status(IStatus.WARNING, AdtPlugin.PLUGIN_ID,
- "Select a minimum SDK version");
- } else {
- AndroidVersion version = mValues.target.getVersion();
- if (version.isPreview()) {
- if (version.getCodename().equals(mValues.minSdk) == false) {
- status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "Preview platforms require the min SDK version to match their codenames.");
- }
- } else if (mValues.target.getVersion().compareTo(
- mValues.minSdkLevel,
- version.isPreview() ? mValues.minSdk : null) < 0) {
- status = new Status(IStatus.WARNING, AdtPlugin.PLUGIN_ID,
- "The minimum SDK version is higher than the build target version");
- }
- if (status == null || status.getSeverity() != IStatus.ERROR) {
- if (mValues.targetSdkLevel < mValues.minSdkLevel) {
- status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "The target SDK version should be at least as high as the minimum SDK version");
- }
- }
- }
- }
-
- IStatus themeStatus = validateTheme();
- if (themeStatus != null && (status == null
- || themeStatus.getSeverity() > status.getSeverity())) {
- status = themeStatus;
- }
- }
-
- setPageComplete(status == null || status.getSeverity() != IStatus.ERROR);
- if (status != null) {
- setMessage(status.getMessage(),
- status.getSeverity() == IStatus.ERROR
- ? IMessageProvider.ERROR : IMessageProvider.WARNING);
- } else {
- setErrorMessage(null);
- setMessage(null);
- }
- }
-
- private IStatus validateAppName() {
- String appName = mValues.applicationName;
- IStatus status = null;
- if (appName == null || appName.isEmpty()) {
- status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "Enter an application name (shown in launcher)");
- } else if (Character.isLowerCase(mValues.applicationName.charAt(0))) {
- status = new Status(IStatus.WARNING, AdtPlugin.PLUGIN_ID,
- "The application name for most apps begins with an uppercase letter");
- }
-
- updateDecorator(mApplicationDec, status, true);
-
- return status;
- }
-
- private IStatus validateProjectName() {
- IStatus status = ProjectNamePage.validateProjectName(mValues.projectName);
- updateDecorator(mProjectDec, status, true);
-
- return status;
- }
-
- private IStatus validatePackageName() {
- IStatus status;
- if (mValues.packageName == null || mValues.packageName.startsWith(SAMPLE_PACKAGE_PREFIX)) {
- if (mValues.packageName != null
- && !mValues.packageName.equals(SAMPLE_PACKAGE_PREFIX)) {
- status = ApplicationInfoPage.validatePackage(mValues.packageName);
- if (status == null || status.isOK()) {
- status = new Status(IStatus.WARNING, AdtPlugin.PLUGIN_ID,
- String.format("The prefix '%1$s' is meant as a placeholder and should " +
- "not be used", SAMPLE_PACKAGE_PREFIX));
- }
- } else {
- status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "Package name must be specified.");
- }
- } else {
- status = ApplicationInfoPage.validatePackage(mValues.packageName);
- }
-
- updateDecorator(mPackageDec, status, true);
-
- return status;
- }
-
- private IStatus validateTheme() {
- IStatus status = null;
-
- if (mThemeParameter != null) {
- status = NewTemplatePage.validateCombo(null, mThemeParameter,
- mThemeCombo.getSelectionIndex(), mValues.minSdkLevel,
- mValues.getBuildApi());
-
- updateDecorator(mThemeDec, status, true);
- }
-
- return status;
- }
-
- private void updateDecorator(ControlDecoration decorator, IStatus status, boolean hasInfo) {
- if (hasInfo) {
- int severity = status != null ? status.getSeverity() : IStatus.OK;
- setDecoratorType(decorator, severity);
- } else {
- if (status == null || status.isOK()) {
- decorator.hide();
- } else {
- decorator.show();
- }
- }
- }
-
- private void setDecoratorType(ControlDecoration decorator, int severity) {
- String id;
- if (severity == IStatus.ERROR) {
- id = FieldDecorationRegistry.DEC_ERROR;
- } else if (severity == IStatus.WARNING) {
- id = FieldDecorationRegistry.DEC_WARNING;
- } else {
- id = FieldDecorationRegistry.DEC_INFORMATION;
- }
- FieldDecoration errorFieldIndicator = FieldDecorationRegistry.getDefault().
- getFieldDecoration(id);
- decorator.setImage(errorFieldIndicator.getImage());
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewProjectWizard.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewProjectWizard.java
deleted file mode 100644
index d350a00dd..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewProjectWizard.java
+++ /dev/null
@@ -1,456 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import static org.eclipse.core.resources.IResource.DEPTH_INFINITE;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.VisibleForTesting;
-import com.android.assetstudiolib.GraphicGenerator;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.actions.AddSupportJarAction;
-import com.android.ide.eclipse.adt.internal.assetstudio.AssetType;
-import com.android.ide.eclipse.adt.internal.assetstudio.ConfigureAssetSetPage;
-import com.android.ide.eclipse.adt.internal.assetstudio.CreateAssetSetWizardState;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.project.ProjectHelper;
-import com.android.ide.eclipse.adt.internal.wizards.newproject.NewProjectCreator;
-import com.android.ide.eclipse.adt.internal.wizards.newproject.NewProjectCreator.ProjectPopulator;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.ui.IWorkbench;
-
-import java.io.File;
-import java.lang.reflect.InvocationTargetException;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Wizard for creating new projects
- */
-public class NewProjectWizard extends TemplateWizard {
- private static final String PARENT_ACTIVITY_CLASS = "parentActivityClass"; //$NON-NLS-1$
- private static final String ACTIVITY_TITLE = "activityTitle"; //$NON-NLS-1$
- static final String IS_LAUNCHER = "isLauncher"; //$NON-NLS-1$
- static final String IS_NEW_PROJECT = "isNewProject"; //$NON-NLS-1$
- static final String IS_LIBRARY_PROJECT = "isLibraryProject"; //$NON-NLS-1$
- static final String ATTR_COPY_ICONS = "copyIcons"; //$NON-NLS-1$
- static final String ATTR_TARGET_API = "targetApi"; //$NON-NLS-1$
- static final String ATTR_MIN_API = "minApi"; //$NON-NLS-1$
- static final String ATTR_MIN_BUILD_API = "minBuildApi"; //$NON-NLS-1$
- static final String ATTR_BUILD_API = "buildApi"; //$NON-NLS-1$
- static final String ATTR_REVISION = "revision"; //$NON-NLS-1$
- static final String ATTR_MIN_API_LEVEL = "minApiLevel"; //$NON-NLS-1$
- static final String ATTR_PACKAGE_NAME = "packageName"; //$NON-NLS-1$
- static final String ATTR_APP_TITLE = "appTitle"; //$NON-NLS-1$
- static final String CATEGORY_PROJECTS = "projects"; //$NON-NLS-1$
- static final String CATEGORY_ACTIVITIES = "activities"; //$NON-NLS-1$
- static final String CATEGORY_OTHER = "other"; //$NON-NLS-1$
- static final String ATTR_APP_COMPAT = "appCompat"; //$NON-NLS-1$
- /**
- * Reserved file name for the launcher icon, resolves to the xhdpi version
- *
- * @see CreateAssetSetWizardState#getImage
- */
- public static final String DEFAULT_LAUNCHER_ICON = "launcher_icon"; //$NON-NLS-1$
-
- private NewProjectPage mMainPage;
- private ProjectContentsPage mContentsPage;
- private ActivityPage mActivityPage;
- private NewTemplatePage mTemplatePage;
- private NewProjectWizardState mValues;
- /** The project being created */
- private IProject mProject;
-
- @Override
- public void init(IWorkbench workbench, IStructuredSelection selection) {
- super.init(workbench, selection);
-
- setWindowTitle("New Android Application");
-
- mValues = new NewProjectWizardState();
- mMainPage = new NewProjectPage(mValues);
- mContentsPage = new ProjectContentsPage(mValues);
- mContentsPage.init(selection, AdtUtils.getActivePart());
- mActivityPage = new ActivityPage(mValues, true, true);
- mActivityPage.setLauncherActivitiesOnly(true);
- }
-
- @Override
- public void addPages() {
- super.addPages();
- addPage(mMainPage);
- addPage(mContentsPage);
- addPage(mActivityPage);
- }
-
- @Override
- public IWizardPage getNextPage(IWizardPage page) {
- if (page == mMainPage) {
- return mContentsPage;
- }
-
- if (page == mContentsPage) {
- if (mValues.createIcon) {
- // Bundle asset studio wizard to create the launcher icon
- CreateAssetSetWizardState iconState = mValues.iconState;
- iconState.type = AssetType.LAUNCHER;
- iconState.outputName = "ic_launcher"; //$NON-NLS-1$
- iconState.background = new RGB(0xff, 0xff, 0xff);
- iconState.foreground = new RGB(0x33, 0xb6, 0xea);
- iconState.trim = true;
-
- // ADT 20: White icon with blue shape
- //iconState.shape = GraphicGenerator.Shape.CIRCLE;
- //iconState.sourceType = CreateAssetSetWizardState.SourceType.CLIPART;
- //iconState.clipartName = "user.png"; //$NON-NLS-1$
- //iconState.padding = 10;
-
- // ADT 21: Use the platform packaging icon, but allow user to customize it
- iconState.sourceType = CreateAssetSetWizardState.SourceType.IMAGE;
- iconState.imagePath = new File(DEFAULT_LAUNCHER_ICON);
- iconState.shape = GraphicGenerator.Shape.NONE;
- iconState.padding = 0;
-
- WizardPage p = getIconPage(mValues.iconState);
- p.setTitle("Configure Launcher Icon");
- return p;
- } else {
- if (mValues.createActivity) {
- return mActivityPage;
- } else {
- return null;
- }
- }
- }
-
- if (page == mIconPage) {
- return mActivityPage;
- }
-
- if (page == mActivityPage && mValues.createActivity) {
- if (mTemplatePage == null) {
- NewTemplateWizardState activityValues = mValues.activityValues;
-
- // Initialize the *default* activity name based on what we've derived
- // from the project name
- activityValues.defaults.put("activityName", mValues.activityName);
-
- // Hide those parameters that the template requires but that we don't want to
- // ask the users about, since we will supply these values from the rest
- // of the new project wizard.
- Set<String> hidden = activityValues.hidden;
- hidden.add(ATTR_PACKAGE_NAME);
- hidden.add(ATTR_APP_TITLE);
- hidden.add(ATTR_MIN_API);
- hidden.add(ATTR_MIN_API_LEVEL);
- hidden.add(ATTR_TARGET_API);
- hidden.add(ATTR_BUILD_API);
- hidden.add(IS_LAUNCHER);
- // Don't ask about hierarchical parent activities in new projects where there
- // can't possibly be any
- hidden.add(PARENT_ACTIVITY_CLASS);
- hidden.add(ACTIVITY_TITLE); // Not used for the first activity in the project
-
- mTemplatePage = new NewTemplatePage(activityValues, false);
- addPage(mTemplatePage);
- }
- mTemplatePage.setCustomMinSdk(mValues.minSdkLevel, mValues.getBuildApi());
- return mTemplatePage;
- }
-
- if (page == mTemplatePage) {
- TemplateMetadata template = mValues.activityValues.getTemplateHandler().getTemplate();
- if (template != null
- && !InstallDependencyPage.isInstalled(template.getDependencies())) {
- return getDependencyPage(template, true);
- }
- }
-
- if (page == mTemplatePage || !mValues.createActivity && page == mActivityPage
- || page == getDependencyPage(null, false)) {
- return null;
- }
-
- return super.getNextPage(page);
- }
-
- @Override
- public boolean canFinish() {
- // Deal with lazy creation of some pages: these may not be in the page-list yet
- // since they are constructed lazily, so consider that option here.
- if (mValues.createIcon && (mIconPage == null || !mIconPage.isPageComplete())) {
- return false;
- }
- if (mValues.createActivity && (mTemplatePage == null || !mTemplatePage.isPageComplete())) {
- return false;
- }
-
- // Override super behavior (which just calls isPageComplete() on each of the pages)
- // to special case the template and icon pages since we want to skip them if
- // the appropriate flags are not set.
- for (IWizardPage page : getPages()) {
- if (page == mTemplatePage && !mValues.createActivity) {
- continue;
- }
- if (page == mIconPage && !mValues.createIcon) {
- continue;
- }
- if (!page.isPageComplete()) {
- return false;
- }
- }
-
- return true;
- }
-
- @Override
- @NonNull
- protected IProject getProject() {
- return mProject;
- }
-
- @Override
- @NonNull
- protected List<String> getFilesToOpen() {
- return mValues.template.getFilesToOpen();
- }
-
- @VisibleForTesting
- NewProjectWizardState getValues() {
- return mValues;
- }
-
- @VisibleForTesting
- void setValues(NewProjectWizardState values) {
- mValues = values;
- }
-
- @Override
- protected List<Change> computeChanges() {
- final TemplateHandler template = mValues.template;
- // We'll be merging in an activity template, but don't create *~ backup files
- // of the merged files (such as the manifest file) in that case.
- // (NOTE: After the change from direct file manipulation to creating a list of Change
- // objects, this no longer applies - but the code is kept around a little while longer
- // in case we want to generate change objects that makes backups of merged files)
- template.setBackupMergedFiles(false);
-
- // Generate basic output skeleton
- Map<String, Object> paramMap = new HashMap<String, Object>();
- addProjectInfo(paramMap);
- TemplateHandler.addDirectoryParameters(paramMap, getProject());
- // We don't know at this point whether the activity is going to need
- // AppCompat so we just assume that it will.
- if (mValues.createActivity && mValues.minSdkLevel < 14) {
- paramMap.put(ATTR_APP_COMPAT, true);
- getFinalizingActions().add(new Runnable() {
- @Override
- public void run() {
- AddSupportJarAction.installAppCompatLibrary(mProject, true);
- }
- });
- }
-
- return template.render(mProject, paramMap);
- }
-
- @Override
- protected boolean performFinish(final IProgressMonitor monitor)
- throws InvocationTargetException {
- try {
- IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
- String name = mValues.projectName;
- mProject = root.getProject(name);
-
- final TemplateHandler template = mValues.template;
- // We'll be merging in an activity template, but don't create *~ backup files
- // of the merged files (such as the manifest file) in that case.
- template.setBackupMergedFiles(false);
-
- ProjectPopulator projectPopulator = new ProjectPopulator() {
- @Override
- public void populate(IProject project) throws InvocationTargetException {
- // Copy in the proguard file; templates don't provide this one.
- // add the default proguard config
- File libFolder = new File(AdtPlugin.getOsSdkToolsFolder(),
- SdkConstants.FD_LIB);
- try {
- assert project == mProject;
- NewProjectCreator.addLocalFile(project,
- new File(libFolder, SdkConstants.FN_PROJECT_PROGUARD_FILE),
- // Write ProGuard config files with the extension .pro which
- // is what is used in the ProGuard documentation and samples
- SdkConstants.FN_PROJECT_PROGUARD_FILE,
- new NullProgressMonitor());
- } catch (Exception e) {
- AdtPlugin.log(e, null);
- }
-
- try {
- mProject.refreshLocal(DEPTH_INFINITE, new NullProgressMonitor());
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
-
- // Render the project template
- List<Change> changes = computeChanges();
- if (!changes.isEmpty()) {
- monitor.beginTask("Creating project...", changes.size());
- try {
- CompositeChange composite = new CompositeChange("",
- changes.toArray(new Change[changes.size()]));
- composite.perform(monitor);
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- throw new InvocationTargetException(e);
- } finally {
- monitor.done();
- }
- }
-
- if (mValues.createIcon) { // TODO: Set progress
- generateIcons(mProject);
- }
-
- // Render the embedded activity template template
- if (mValues.createActivity) {
- final TemplateHandler activityTemplate =
- mValues.activityValues.getTemplateHandler();
- // We'll be merging in an activity template, but don't create
- // *~ backup files of the merged files (such as the manifest file)
- // in that case.
- activityTemplate.setBackupMergedFiles(false);
- generateActivity(template, project, monitor);
- }
- }
- };
-
- NewProjectCreator.create(monitor, mProject, mValues.target, projectPopulator,
- mValues.isLibrary, mValues.projectLocation, mValues.workingSets);
-
- // For new projects, ensure that we're actually using the preferred compliance,
- // not just the default one
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(mProject);
- if (javaProject != null) {
- ProjectHelper.enforcePreferredCompilerCompliance(javaProject);
- }
-
- try {
- mProject.refreshLocal(DEPTH_INFINITE, new NullProgressMonitor());
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
-
- List<Runnable> finalizingTasks = getFinalizingActions();
- for (Runnable r : finalizingTasks) {
- r.run();
- }
-
- return true;
- } catch (Exception ioe) {
- AdtPlugin.log(ioe, null);
- return false;
- }
- }
-
- /**
- * Generate custom icons into the project based on the asset studio wizard state
- */
- private void generateIcons(final IProject newProject) {
- // Generate the custom icons
- assert mValues.createIcon;
- ConfigureAssetSetPage.generateIcons(newProject, mValues.iconState, false, mIconPage);
- }
-
- /**
- * Generate the activity: Pre-populate information about the project the
- * activity needs but that we don't need to ask about when creating a new
- * project
- */
- private void generateActivity(TemplateHandler projectTemplate, IProject project,
- IProgressMonitor monitor) throws InvocationTargetException {
- assert mValues.createActivity;
- NewTemplateWizardState activityValues = mValues.activityValues;
- Map<String, Object> parameters = activityValues.parameters;
-
- addProjectInfo(parameters);
-
- parameters.put(IS_NEW_PROJECT, true);
- parameters.put(IS_LIBRARY_PROJECT, mValues.isLibrary);
- // Ensure that activities created as part of a new project are marked as
- // launcher activities
- parameters.put(IS_LAUNCHER, true);
- TemplateHandler.addDirectoryParameters(parameters, project);
-
- TemplateHandler activityTemplate = activityValues.getTemplateHandler();
- activityTemplate.setBackupMergedFiles(false);
- List<Change> changes = activityTemplate.render(project, parameters);
- if (!changes.isEmpty()) {
- monitor.beginTask("Creating template...", changes.size());
- try {
- CompositeChange composite = new CompositeChange("",
- changes.toArray(new Change[changes.size()]));
- composite.perform(monitor);
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- throw new InvocationTargetException(e);
- } finally {
- monitor.done();
- }
- }
-
- List<String> filesToOpen = activityTemplate.getFilesToOpen();
- projectTemplate.getFilesToOpen().addAll(filesToOpen);
-
- List<Runnable> finalizingActions = activityTemplate.getFinalizingActions();
- projectTemplate.getFinalizingActions().addAll(finalizingActions);
- }
-
- private void addProjectInfo(Map<String, Object> parameters) {
- parameters.put(ATTR_PACKAGE_NAME, mValues.packageName);
- parameters.put(ATTR_APP_TITLE, mValues.applicationName);
- parameters.put(ATTR_MIN_API, mValues.minSdk);
- parameters.put(ATTR_MIN_API_LEVEL, mValues.minSdkLevel);
- parameters.put(ATTR_TARGET_API, mValues.targetSdkLevel);
- parameters.put(ATTR_BUILD_API, mValues.target.getVersion().getApiLevel());
- parameters.put(ATTR_COPY_ICONS, !mValues.createIcon);
- parameters.putAll(mValues.parameters);
- }
-
- @Override
- @NonNull
- protected List<Runnable> getFinalizingActions() {
- return mValues.template.getFinalizingActions();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewProjectWizardState.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewProjectWizardState.java
deleted file mode 100644
index 9cd3a6dcf..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewProjectWizardState.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.CATEGORY_PROJECTS;
-
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.assetstudio.CreateAssetSetWizardState;
-import com.android.sdklib.IAndroidTarget;
-
-import org.eclipse.ui.IWorkingSet;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Value object which holds the current state of the wizard pages for the
- * {@link NewProjectWizard}
- */
-public class NewProjectWizardState {
- /** Creates a new {@link NewProjectWizardState} */
- public NewProjectWizardState() {
- template = TemplateHandler.createFromName(CATEGORY_PROJECTS,
- "NewAndroidApplication"); //$NON-NLS-1$
- }
-
- /** The template handler instantiating the project */
- public final TemplateHandler template;
-
- /** The name of the project */
- public String projectName;
-
- /** The derived name of the activity, if any */
- public String activityName;
-
- /** The derived title of the activity, if any */
- public String activityTitle;
-
- /** The application name */
- public String applicationName;
-
- /** The package name */
- public String packageName;
-
- /** Whether the project name has been edited by the user */
- public boolean projectModified;
-
- /** Whether the package name has been edited by the user */
- public boolean packageModified;
-
- /** Whether the activity name has been edited by the user */
- public boolean activityNameModified;
-
- /** Whether the activity title has been edited by the user */
- public boolean activityTitleModified;
-
- /** Whether the application name has been edited by the user */
- public boolean applicationModified;
-
- /** The compilation target to use for this project */
- public IAndroidTarget target;
-
- /** The minimum SDK API level, as a string (if the API is a preview release with a codename) */
- public String minSdk;
-
- /** The minimum SDK API level to use */
- public int minSdkLevel;
-
- /** The target SDK level */
- public int targetSdkLevel = AdtUtils.getHighestKnownApiLevel();
-
- /** Whether this project should be marked as a library project */
- public boolean isLibrary;
-
- /** Whether to create an activity (if so, the activity state is stored in
- * {@link #activityValues}) */
- public boolean createActivity = true;
-
- /** Whether a custom icon should be created instead of just reusing the default (if so,
- * the icon wizard state is stored in {@link #iconState}) */
- public boolean createIcon = true;
-
- // Delegated wizards
-
- /** State for the asset studio wizard, used to create custom icons */
- public CreateAssetSetWizardState iconState = new CreateAssetSetWizardState();
-
- /** State for the template wizard, used to embed an activity template */
- public NewTemplateWizardState activityValues = new NewTemplateWizardState();
-
- /** Whether a custom location should be used */
- public boolean useDefaultLocation = true;
-
- /** Folder where the project should be created. */
- public String projectLocation;
-
- /** Configured parameters, by id */
- public final Map<String, Object> parameters = new HashMap<String, Object>();
-
- /** The set of chosen working sets to use when creating the project */
- public IWorkingSet[] workingSets = new IWorkingSet[0];
-
- /**
- * Returns the build target API level
- *
- * @return the build target API level
- */
- public int getBuildApi() {
- return target != null ? target.getVersion().getApiLevel() : minSdkLevel;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewTemplatePage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewTemplatePage.java
deleted file mode 100644
index 57cf5c824..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewTemplatePage.java
+++ /dev/null
@@ -1,946 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import static com.android.SdkConstants.CLASS_ACTIVITY;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.ATTR_MIN_API;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.ATTR_MIN_BUILD_API;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.ATTR_DEFAULT;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.ATTR_ID;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.ATTR_NAME;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.PREVIEW_PADDING;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.PREVIEW_WIDTH;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.ImageControl;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.project.ProjectChooserHelper;
-import com.android.ide.eclipse.adt.internal.project.ProjectChooserHelper.ProjectCombo;
-import com.android.ide.eclipse.adt.internal.wizards.templates.Parameter.Constraint;
-import com.android.ide.eclipse.adt.internal.wizards.templates.Parameter.Type;
-import com.android.tools.lint.detector.api.LintUtils;
-import com.google.common.collect.Lists;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jdt.core.Flags;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.core.ITypeHierarchy;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.core.search.IJavaSearchScope;
-import org.eclipse.jdt.core.search.SearchEngine;
-import org.eclipse.jdt.ui.IJavaElementSearchConstants;
-import org.eclipse.jdt.ui.JavaUI;
-import org.eclipse.jdt.ui.dialogs.ITypeInfoFilterExtension;
-import org.eclipse.jdt.ui.dialogs.ITypeInfoRequestor;
-import org.eclipse.jdt.ui.dialogs.TypeSelectionExtension;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.IInputValidator;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.dialogs.ProgressMonitorDialog;
-import org.eclipse.jface.fieldassist.ControlDecoration;
-import org.eclipse.jface.fieldassist.FieldDecoration;
-import org.eclipse.jface.fieldassist.FieldDecorationRegistry;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.FocusEvent;
-import org.eclipse.swt.events.FocusListener;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.dialogs.SelectionDialog;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import java.io.ByteArrayInputStream;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * First wizard page in the "New Project From Template" wizard (which is parameterized
- * via template.xml files)
- */
-public class NewTemplatePage extends WizardPage
- implements ModifyListener, SelectionListener, FocusListener {
- /** The default width to use for the wizard page */
- static final int WIZARD_PAGE_WIDTH = 600;
-
- private final NewTemplateWizardState mValues;
- private final boolean mChooseProject;
- private int mCustomMinSdk = -1;
- private int mCustomBuildApi = -1;
- private boolean mIgnore;
- private boolean mShown;
- private Control mFirst;
- // TODO: Move decorators to the Parameter objects?
- private Map<String, ControlDecoration> mDecorations = new HashMap<String, ControlDecoration>();
- private Label mHelpIcon;
- private Label mTipLabel;
- private ImageControl mPreview;
- private Image mPreviewImage;
- private boolean mDisposePreviewImage;
- private ProjectCombo mProjectButton;
- private StringEvaluator mEvaluator;
-
- private TemplateMetadata mShowingTemplate;
-
- /**
- * Creates a new {@link NewTemplatePage}
- *
- * @param values the wizard state
- * @param chooseProject whether the wizard should present a project chooser,
- * and update {@code values}' project field
- */
- NewTemplatePage(NewTemplateWizardState values, boolean chooseProject) {
- super("newTemplatePage"); //$NON-NLS-1$
- mValues = values;
- mChooseProject = chooseProject;
- }
-
- /**
- * @param minSdk a minimum SDK to use, provided chooseProject is false. If
- * it is true, then the minimum SDK used for validation will be
- * the one of the project
- * @param buildApi the build API to use
- */
- void setCustomMinSdk(int minSdk, int buildApi) {
- assert !mChooseProject;
- //assert buildApi >= minSdk;
- mCustomMinSdk = minSdk;
- mCustomBuildApi = buildApi;
- }
-
- @Override
- public void createControl(Composite parent2) {
- Composite parent = new Composite(parent2, SWT.NULL);
- setControl(parent);
- GridLayout parentLayout = new GridLayout(3, false);
- parentLayout.verticalSpacing = 0;
- parentLayout.marginWidth = 0;
- parentLayout.marginHeight = 0;
- parentLayout.horizontalSpacing = 0;
- parent.setLayout(parentLayout);
-
- // Reserve enough width (since the panel is created lazily later)
- Label label = new Label(parent, SWT.NONE);
- GridData data = new GridData();
- data.widthHint = WIZARD_PAGE_WIDTH;
- label.setLayoutData(data);
- }
-
- @SuppressWarnings("unused") // SWT constructors have side effects and aren't unused
- private void onEnter() {
- TemplateMetadata template = mValues.getTemplateHandler().getTemplate();
- if (template == mShowingTemplate) {
- return;
- }
- mShowingTemplate = template;
-
- Composite parent = (Composite) getControl();
-
- Control[] children = parent.getChildren();
- if (children.length > 0) {
- for (Control c : parent.getChildren()) {
- c.dispose();
- }
- for (ControlDecoration decoration : mDecorations.values()) {
- decoration.dispose();
- }
- mDecorations.clear();
- }
-
- Composite container = new Composite(parent, SWT.NULL);
- container.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
- GridLayout gl_container = new GridLayout(3, false);
- gl_container.horizontalSpacing = 10;
- container.setLayout(gl_container);
-
- if (mChooseProject) {
- // Project: [button]
- String tooltip = "The Android Project where the new resource will be created.";
- Label projectLabel = new Label(container, SWT.NONE);
- projectLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- projectLabel.setText("Project:");
- projectLabel.setToolTipText(tooltip);
-
- ProjectChooserHelper helper =
- new ProjectChooserHelper(getShell(), null /* filter */);
- mProjectButton = new ProjectCombo(helper, container, mValues.project);
- mProjectButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
- mProjectButton.setToolTipText(tooltip);
- mProjectButton.addSelectionListener(this);
-
- //Label projectSeparator = new Label(container, SWT.SEPARATOR | SWT.HORIZONTAL);
- //projectSeparator.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 3, 1));
- }
-
- // Add parameters
- mFirst = null;
- String thumb = null;
- if (template != null) {
- thumb = template.getThumbnailPath();
- String title = template.getTitle();
- if (title != null && !title.isEmpty()) {
- setTitle(title);
- }
- String description = template.getDescription();
- if (description != null && !description.isEmpty()) {
- setDescription(description);
- }
-
- Map<String, String> defaults = mValues.defaults;
- Set<String> seen = null;
- if (LintUtils.assertionsEnabled()) {
- seen = new HashSet<String>();
- }
-
- List<Parameter> parameters = template.getParameters();
- for (Parameter parameter : parameters) {
- Parameter.Type type = parameter.type;
-
- if (type == Parameter.Type.SEPARATOR) {
- Label separator = new Label(container, SWT.SEPARATOR | SWT.HORIZONTAL);
- separator.setLayoutData(new GridData(SWT.FILL, SWT.TOP, true, false, 3, 1));
- continue;
- }
-
- String id = parameter.id;
- assert id != null && !id.isEmpty() : ATTR_ID;
- Object value = defaults.get(id);
- if (value == null) {
- value = parameter.value;
- }
-
- String name = parameter.name;
- String help = parameter.help;
-
- // Required
- assert name != null && !name.isEmpty() : ATTR_NAME;
- // Ensure id's are unique:
- assert seen != null && seen.add(id) : id;
-
- // Skip attributes that were already provided by the surrounding
- // context. For example, when adding into an existing project,
- // provide the minimum SDK automatically from the project.
- if (mValues.hidden != null && mValues.hidden.contains(id)) {
- continue;
- }
-
- switch (type) {
- case STRING: {
- // TODO: Look at the constraints to add validators here
- // TODO: If I type.equals("layout") add resource validator for layout
- // names
- // TODO: If I type.equals("class") make class validator
-
- // TODO: Handle package and id better later
- Label label = new Label(container, SWT.NONE);
- label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false,
- 1, 1));
- label.setText(name);
-
- Text text = new Text(container, SWT.BORDER);
- text.setData(parameter);
- parameter.control = text;
-
- if (parameter.constraints.contains(Constraint.EXISTS)) {
- text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
- 1, 1));
-
- Button button = new Button(container, SWT.FLAT);
- button.setData(parameter);
- button.setText("...");
- button.addSelectionListener(this);
- } else {
- text.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
- 2, 1));
- }
-
- boolean hasValue = false;
- if (value instanceof String) {
- String stringValue = (String) value;
- hasValue = !stringValue.isEmpty();
- text.setText(stringValue);
- mValues.parameters.put(id, value);
- }
-
- if (!hasValue) {
- if (parameter.constraints.contains(Constraint.EMPTY)) {
- text.setMessage("Optional");
- } else if (parameter.constraints.contains(Constraint.NONEMPTY)) {
- text.setMessage("Required");
- }
- }
-
- text.addModifyListener(this);
- text.addFocusListener(this);
-
- if (mFirst == null) {
- mFirst = text;
- }
-
- if (help != null && !help.isEmpty()) {
- text.setToolTipText(help);
- ControlDecoration decoration = createFieldDecoration(id, text, help);
- }
- break;
- }
- case BOOLEAN: {
- Label label = new Label(container, SWT.NONE);
- label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false,
- 1, 1));
-
- Button checkBox = new Button(container, SWT.CHECK);
- checkBox.setText(name);
- checkBox.setData(parameter);
- parameter.control = checkBox;
- checkBox.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
- 2, 1));
-
- if (value instanceof Boolean) {
- Boolean selected = (Boolean) value;
- checkBox.setSelection(selected);
- mValues.parameters.put(id, value);
- }
-
- checkBox.addSelectionListener(this);
- checkBox.addFocusListener(this);
-
- if (mFirst == null) {
- mFirst = checkBox;
- }
-
- if (help != null && !help.isEmpty()) {
- checkBox.setToolTipText(help);
- ControlDecoration decoration = createFieldDecoration(id, checkBox,
- help);
- }
- break;
- }
- case ENUM: {
- Label label = new Label(container, SWT.NONE);
- label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false,
- 1, 1));
- label.setText(name);
-
- Combo combo = createOptionCombo(parameter, container, mValues.parameters,
- this, this);
- combo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
- 2, 1));
-
- if (mFirst == null) {
- mFirst = combo;
- }
-
- if (help != null && !help.isEmpty()) {
- ControlDecoration decoration = createFieldDecoration(id, combo, help);
- }
- break;
- }
- case SEPARATOR:
- // Already handled above
- assert false : type;
- break;
- default:
- assert false : type;
- }
- }
- }
-
- // Preview
- mPreview = new ImageControl(parent, SWT.NONE, null);
- mPreview.setDisposeImage(false); // Handled manually in this class
- GridData gd_mImage = new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 1);
- gd_mImage.widthHint = PREVIEW_WIDTH + 2 * PREVIEW_PADDING;
- mPreview.setLayoutData(gd_mImage);
-
- Label separator = new Label(parent, SWT.SEPARATOR | SWT.HORIZONTAL);
- GridData separatorData = new GridData(SWT.FILL, SWT.TOP, true, false, 3, 1);
- separatorData.heightHint = 16;
- separator.setLayoutData(separatorData);
-
- // Generic help
- mHelpIcon = new Label(parent, SWT.NONE);
- mHelpIcon.setLayoutData(new GridData(SWT.RIGHT, SWT.TOP, false, false, 1, 1));
- Image icon = IconFactory.getInstance().getIcon("quickfix");
- mHelpIcon.setImage(icon);
- mHelpIcon.setVisible(false);
- mTipLabel = new Label(parent, SWT.WRAP);
- mTipLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1));
-
- setPreview(thumb);
-
- parent.layout(true, true);
- // TODO: This is a workaround for the fact that (at least on OSX) you end up
- // with some visual artifacts from the control decorations in the upper left corner
- // (outside the parent widget itself) from the initial control decoration placement
- // prior to layout. Therefore, perform a redraw. A better solution would be to
- // delay creation of the control decorations until layout has been performed.
- // Let's do that soon.
- parent.getParent().redraw();
- }
-
- @NonNull
- static Combo createOptionCombo(
- @NonNull Parameter parameter,
- @NonNull Composite container,
- @NonNull Map<String, Object> valueMap,
- @NonNull SelectionListener selectionListener,
- @NonNull FocusListener focusListener) {
- Combo combo = new Combo(container, SWT.READ_ONLY);
-
- List<Element> options = parameter.getOptions();
- assert options.size() > 0;
- int selected = 0;
- List<String> ids = Lists.newArrayList();
- List<Integer> minSdks = Lists.newArrayList();
- List<Integer> minBuildApis = Lists.newArrayList();
- List<String> labels = Lists.newArrayList();
- for (int i = 0, n = options.size(); i < n; i++) {
- Element option = options.get(i);
- String optionId = option.getAttribute(ATTR_ID);
- assert optionId != null && !optionId.isEmpty() : ATTR_ID;
- String isDefault = option.getAttribute(ATTR_DEFAULT);
- if (isDefault != null && !isDefault.isEmpty() &&
- Boolean.valueOf(isDefault)) {
- selected = i;
- }
- NodeList childNodes = option.getChildNodes();
- assert childNodes.getLength() == 1 &&
- childNodes.item(0).getNodeType() == Node.TEXT_NODE;
- String optionLabel = childNodes.item(0).getNodeValue().trim();
-
- String minApiString = option.getAttribute(ATTR_MIN_API);
- int minSdk = 1;
- if (minApiString != null && !minApiString.isEmpty()) {
- try {
- minSdk = Integer.parseInt(minApiString);
- } catch (NumberFormatException nufe) {
- // Templates aren't allowed to contain codenames, should
- // always be an integer
- AdtPlugin.log(nufe, null);
- minSdk = 1;
- }
- }
- String minBuildApiString = option.getAttribute(ATTR_MIN_BUILD_API);
- int minBuildApi = 1;
- if (minBuildApiString != null && !minBuildApiString.isEmpty()) {
- try {
- minBuildApi = Integer.parseInt(minBuildApiString);
- } catch (NumberFormatException nufe) {
- // Templates aren't allowed to contain codenames, should
- // always be an integer
- AdtPlugin.log(nufe, null);
- minBuildApi = 1;
- }
- }
- minSdks.add(minSdk);
- minBuildApis.add(minBuildApi);
- ids.add(optionId);
- labels.add(optionLabel);
- }
- combo.setData(parameter);
- parameter.control = combo;
- combo.setData(ATTR_ID, ids.toArray(new String[ids.size()]));
- combo.setData(ATTR_MIN_API, minSdks.toArray(new Integer[minSdks.size()]));
- combo.setData(ATTR_MIN_BUILD_API, minBuildApis.toArray(
- new Integer[minBuildApis.size()]));
- assert labels.size() > 0;
- combo.setItems(labels.toArray(new String[labels.size()]));
- combo.select(selected);
-
- combo.addSelectionListener(selectionListener);
- combo.addFocusListener(focusListener);
-
- valueMap.put(parameter.id, ids.get(selected));
-
- if (parameter.help != null && !parameter.help.isEmpty()) {
- combo.setToolTipText(parameter.help);
- }
-
- return combo;
- }
-
- private void setPreview(String thumb) {
- Image oldImage = mPreviewImage;
- boolean dispose = mDisposePreviewImage;
- mPreviewImage = null;
-
- if (thumb == null || thumb.isEmpty()) {
- mPreviewImage = TemplateMetadata.getDefaultTemplateIcon();
- mDisposePreviewImage = false;
- } else {
- byte[] data = mValues.getTemplateHandler().readTemplateResource(thumb);
- if (data != null) {
- try {
- mPreviewImage = new Image(getControl().getDisplay(),
- new ByteArrayInputStream(data));
- mDisposePreviewImage = true;
- } catch (Exception e) {
- AdtPlugin.log(e, null);
- }
- }
- if (mPreviewImage == null) {
- return;
- }
- }
-
- mPreview.setImage(mPreviewImage);
- mPreview.fitToWidth(PREVIEW_WIDTH);
-
- if (oldImage != null && dispose) {
- oldImage.dispose();
- }
- }
-
- @Override
- public void dispose() {
- super.dispose();
-
- if (mPreviewImage != null && mDisposePreviewImage) {
- mDisposePreviewImage = false;
- mPreviewImage.dispose();
- mPreviewImage = null;
- }
- }
-
- private ControlDecoration createFieldDecoration(String id, Control control,
- String description) {
- ControlDecoration decoration = new ControlDecoration(control, SWT.LEFT);
- decoration.setMarginWidth(2);
- FieldDecoration errorFieldIndicator = FieldDecorationRegistry.getDefault().
- getFieldDecoration(FieldDecorationRegistry.DEC_INFORMATION);
- decoration.setImage(errorFieldIndicator.getImage());
- decoration.setDescriptionText(description);
- control.setToolTipText(description);
- mDecorations.put(id, decoration);
-
- return decoration;
- }
-
- @Override
- public boolean isPageComplete() {
- // Force user to reach this page before hitting Finish
- return mShown && super.isPageComplete();
- }
-
- @Override
- public void setVisible(boolean visible) {
- if (visible) {
- onEnter();
- }
-
- super.setVisible(visible);
-
- if (mFirst != null) {
- mFirst.setFocus();
- }
-
- if (visible) {
- mShown = true;
- }
-
- validatePage();
- }
-
- /** Returns the parameter associated with the given control */
- @Nullable
- static Parameter getParameter(Control control) {
- return (Parameter) control.getData();
- }
-
- /**
- * Returns the current string evaluator, if any
- *
- * @return the evaluator or null
- */
- @Nullable
- public StringEvaluator getEvaluator() {
- return mEvaluator;
- }
-
- // ---- Validation ----
-
- private void validatePage() {
- int minSdk = getMinSdk();
- int buildApi = getBuildApi();
- IStatus status = mValues.getTemplateHandler().validateTemplate(minSdk, buildApi);
-
- if (status == null || status.isOK()) {
- if (mChooseProject && mValues.project == null) {
- status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "Please select an Android project.");
- }
- }
-
- for (Parameter parameter : mShowingTemplate.getParameters()) {
- if (parameter.type == Parameter.Type.SEPARATOR) {
- continue;
- }
- IInputValidator validator = parameter.getValidator(mValues.project);
- if (validator != null) {
- ControlDecoration decoration = mDecorations.get(parameter.id);
- String value = parameter.value == null ? "" : parameter.value.toString();
- String error = validator.isValid(value);
- if (error != null) {
- IStatus s = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, error);
- if (decoration != null) {
- updateDecorator(decoration, s, parameter.help);
- }
- if (status == null || status.isOK()) {
- status = s;
- }
- } else if (decoration != null) {
- updateDecorator(decoration, null, parameter.help);
- }
- }
-
- if (status == null || status.isOK()) {
- if (parameter.control instanceof Combo) {
- status = validateCombo(status, parameter, minSdk, buildApi);
- }
- }
- }
-
- setPageComplete(status == null || status.getSeverity() != IStatus.ERROR);
- if (status != null) {
- setMessage(status.getMessage(),
- status.getSeverity() == IStatus.ERROR
- ? IMessageProvider.ERROR : IMessageProvider.WARNING);
- } else {
- setErrorMessage(null);
- setMessage(null);
- }
- }
-
- /** Validates the given combo */
- static IStatus validateCombo(IStatus status, Parameter parameter, int minSdk, int buildApi) {
- Combo combo = (Combo) parameter.control;
- int index = combo.getSelectionIndex();
- return validateCombo(status, parameter, index, minSdk, buildApi);
- }
-
- /** Validates the given combo assuming the value at the given index is chosen */
- static IStatus validateCombo(IStatus status, Parameter parameter, int index,
- int minSdk, int buildApi) {
- Combo combo = (Combo) parameter.control;
- Integer[] optionIds = (Integer[]) combo.getData(ATTR_MIN_API);
- // Check minSdk
- if (index != -1 && index < optionIds.length) {
- Integer requiredMinSdk = optionIds[index];
- if (requiredMinSdk > minSdk) {
- status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- String.format(
- "%1$s \"%2$s\" requires a minimum SDK version of at " +
- "least %3$d, and the current min version is %4$d",
- parameter.name, combo.getItems()[index], requiredMinSdk, minSdk));
- }
- }
-
- // Check minimum build target
- optionIds = (Integer[]) combo.getData(ATTR_MIN_BUILD_API);
- if (index != -1 && index < optionIds.length) {
- Integer requiredBuildApi = optionIds[index];
- if (requiredBuildApi > buildApi) {
- status = new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- String.format(
- "%1$s \"%2$s\" requires a build target API version of at " +
- "least %3$d, and the current version is %4$d",
- parameter.name, combo.getItems()[index], requiredBuildApi, buildApi));
- }
- }
- return status;
- }
-
- private int getMinSdk() {
- return mChooseProject ? mValues.getMinSdk() : mCustomMinSdk;
- }
-
- private int getBuildApi() {
- return mChooseProject ? mValues.getBuildApi() : mCustomBuildApi;
- }
-
- private void updateDecorator(ControlDecoration decorator, IStatus status, String help) {
- if (help != null && !help.isEmpty()) {
- decorator.setDescriptionText(status != null ? status.getMessage() : help);
-
- int severity = status != null ? status.getSeverity() : IStatus.OK;
- String id;
- if (severity == IStatus.ERROR) {
- id = FieldDecorationRegistry.DEC_ERROR;
- } else if (severity == IStatus.WARNING) {
- id = FieldDecorationRegistry.DEC_WARNING;
- } else {
- id = FieldDecorationRegistry.DEC_INFORMATION;
- }
- FieldDecoration errorFieldIndicator = FieldDecorationRegistry.getDefault().
- getFieldDecoration(id);
- decorator.setImage(errorFieldIndicator.getImage());
- } else {
- if (status == null || status.isOK()) {
- decorator.hide();
- } else {
- decorator.show();
- }
- }
- }
-
- // ---- Implements ModifyListener ----
-
- @Override
- public void modifyText(ModifyEvent e) {
- if (mIgnore) {
- return;
- }
-
- Object source = e.getSource();
- if (source instanceof Text) {
- Text text = (Text) source;
- editParameter(text, text.getText().trim());
- }
-
- validatePage();
- }
-
- // ---- Implements SelectionListener ----
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (mIgnore) {
- return;
- }
-
- Object source = e.getSource();
- if (source == mProjectButton) {
- mValues.project = mProjectButton.getSelectedProject();
- } else if (source instanceof Combo) {
- Combo combo = (Combo) source;
- String[] optionIds = (String[]) combo.getData(ATTR_ID);
- int index = combo.getSelectionIndex();
- if (index != -1 && index < optionIds.length) {
- String optionId = optionIds[index];
- editParameter(combo, optionId);
- TemplateMetadata template = mValues.getTemplateHandler().getTemplate();
- if (template != null) {
- setPreview(template.getThumbnailPath());
- }
- }
- } else if (source instanceof Button) {
- Button button = (Button) source;
- Parameter parameter = (Parameter) button.getData();
- if (parameter.type == Type.BOOLEAN) {
- // Checkbox parameter
- editParameter(button, button.getSelection());
-
- TemplateMetadata template = mValues.getTemplateHandler().getTemplate();
- if (template != null) {
- setPreview(template.getThumbnailPath());
- }
- } else {
- // Choose button for some other parameter, usually a text
- String activity = chooseActivity();
- if (activity != null) {
- setValue(parameter, activity);
- }
- }
- }
-
- validatePage();
- }
-
- private String chooseActivity() {
- try {
- // Compute a search scope: We need to merge all the subclasses
- // android.app.Fragment and android.support.v4.app.Fragment
- IJavaSearchScope scope = SearchEngine.createWorkspaceScope();
- IProject project = mValues.project;
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
- IType activityType = null;
-
- if (javaProject != null) {
- activityType = javaProject.findType(CLASS_ACTIVITY);
- }
- if (activityType == null) {
- IJavaProject[] projects = BaseProjectHelper.getAndroidProjects(null);
- for (IJavaProject p : projects) {
- activityType = p.findType(CLASS_ACTIVITY);
- if (activityType != null) {
- break;
- }
- }
- }
- if (activityType != null) {
- NullProgressMonitor monitor = new NullProgressMonitor();
- ITypeHierarchy hierarchy = activityType.newTypeHierarchy(monitor);
- IType[] classes = hierarchy.getAllSubtypes(activityType);
- scope = SearchEngine.createJavaSearchScope(classes, IJavaSearchScope.SOURCES);
- }
-
- Shell parent = AdtPlugin.getShell();
- final SelectionDialog dialog = JavaUI.createTypeDialog(
- parent,
- new ProgressMonitorDialog(parent),
- scope,
- IJavaElementSearchConstants.CONSIDER_CLASSES, false,
- // Use ? as a default filter to fill dialog with matches
- "?", //$NON-NLS-1$
- new TypeSelectionExtension() {
- @Override
- public ITypeInfoFilterExtension getFilterExtension() {
- return new ITypeInfoFilterExtension() {
- @Override
- public boolean select(ITypeInfoRequestor typeInfoRequestor) {
- int modifiers = typeInfoRequestor.getModifiers();
- if (!Flags.isPublic(modifiers)
- || Flags.isInterface(modifiers)
- || Flags.isEnum(modifiers)) {
- return false;
- }
- return true;
- }
- };
- }
- });
-
- dialog.setTitle("Choose Activity Class");
- dialog.setMessage("Select an Activity class (? = any character, * = any string):");
- if (dialog.open() == IDialogConstants.CANCEL_ID) {
- return null;
- }
-
- Object[] types = dialog.getResult();
- if (types != null && types.length > 0) {
- return ((IType) types[0]).getFullyQualifiedName();
- }
- } catch (JavaModelException e) {
- AdtPlugin.log(e, null);
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- return null;
- }
-
- private void editParameter(Control control, Object value) {
- Parameter parameter = getParameter(control);
- if (parameter != null) {
- String id = parameter.id;
- parameter.value = value;
- parameter.edited = value != null && !value.toString().isEmpty();
- mValues.parameters.put(id, value);
-
- // Update dependent variables, if any
- List<Parameter> parameters = mShowingTemplate.getParameters();
- for (Parameter p : parameters) {
- if (p == parameter || p.suggest == null || p.edited ||
- p.type == Parameter.Type.SEPARATOR) {
- continue;
- }
- if (!p.suggest.contains(id)) {
- continue;
- }
-
- try {
- if (mEvaluator == null) {
- mEvaluator = new StringEvaluator();
- }
- String updated = mEvaluator.evaluate(p.suggest, parameters);
- if (updated != null && !updated.equals(p.value)) {
- setValue(p, updated);
- }
- } catch (Throwable t) {
- // Pass: Ignore updating if something wrong happens
- t.printStackTrace(); // during development only
- }
- }
- }
- }
-
- private void setValue(Parameter p, String value) {
- p.value = value;
- mValues.parameters.put(p.id, value);
-
- // Update form widgets
- boolean prevIgnore = mIgnore;
- try {
- mIgnore = true;
- if (p.control instanceof Text) {
- ((Text) p.control).setText(value);
- } else if (p.control instanceof Button) {
- // TODO: Handle
- } else if (p.control instanceof Combo) {
- // TODO: Handle
- } else if (p.control != null) {
- assert false : p.control;
- }
- } finally {
- mIgnore = prevIgnore;
- }
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
-
- // ---- Implements FocusListener ----
-
- @Override
- public void focusGained(FocusEvent e) {
- Object source = e.getSource();
- String tip = "";
-
- if (source instanceof Control) {
- Control control = (Control) source;
- Parameter parameter = getParameter(control);
- if (parameter != null) {
- ControlDecoration decoration = mDecorations.get(parameter.id);
- if (decoration != null) {
- tip = decoration.getDescriptionText();
- }
- }
- }
-
- mTipLabel.setText(tip);
- mHelpIcon.setVisible(tip.length() > 0);
- }
-
- @Override
- public void focusLost(FocusEvent e) {
- mTipLabel.setText("");
- mHelpIcon.setVisible(false);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewTemplateWizard.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewTemplateWizard.java
deleted file mode 100644
index 99814f731..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewTemplateWizard.java
+++ /dev/null
@@ -1,212 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.ATTR_BUILD_API;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.ATTR_MIN_API;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.ATTR_MIN_API_LEVEL;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.ATTR_PACKAGE_NAME;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.ATTR_TARGET_API;
-
-import com.android.annotations.NonNull;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard;
-
-import java.io.File;
-import java.util.List;
-import java.util.Set;
-
-/**
- * Template wizard which creates parameterized templates
- */
-public class NewTemplateWizard extends TemplateWizard {
- /** Template name and location under $sdk/templates for the default activity */
- static final String BLANK_ACTIVITY = "activities/BlankActivity"; //$NON-NLS-1$
- /** Template name and location under $sdk/templates for the custom view template */
- static final String CUSTOM_VIEW = "other/CustomView"; //$NON-NLS-1$
-
- protected NewTemplatePage mMainPage;
- protected NewTemplateWizardState mValues;
- private final String mTemplateName;
-
- NewTemplateWizard(String templateName) {
- mTemplateName = templateName;
- }
-
- @Override
- public void init(IWorkbench workbench, IStructuredSelection selection) {
- super.init(workbench, selection);
-
- mValues = new NewTemplateWizardState();
-
- File template = TemplateManager.getTemplateLocation(mTemplateName);
- if (template != null) {
- mValues.setTemplateLocation(template);
- }
- hideBuiltinParameters();
-
- List<IProject> projects = AdtUtils.getSelectedProjects(selection);
- if (projects.size() == 1) {
- mValues.project = projects.get(0);
- }
-
- mMainPage = new NewTemplatePage(mValues, true);
- }
-
- @Override
- protected boolean shouldAddIconPage() {
- return mValues.getIconState() != null;
- }
-
- /**
- * Hide those parameters that the template requires but that we don't want
- * to ask the users about, since we can derive it from the target project
- * the template is written into.
- */
- protected void hideBuiltinParameters() {
- Set<String> hidden = mValues.hidden;
- hidden.add(ATTR_PACKAGE_NAME);
- hidden.add(ATTR_MIN_API);
- hidden.add(ATTR_MIN_API_LEVEL);
- hidden.add(ATTR_TARGET_API);
- hidden.add(ATTR_BUILD_API);
- }
-
- @Override
- public void addPages() {
- super.addPages();
- addPage(mMainPage);
- }
-
- @Override
- public IWizardPage getNextPage(IWizardPage page) {
- TemplateMetadata template = mValues.getTemplateHandler().getTemplate();
-
- if (page == mMainPage && shouldAddIconPage()) {
- WizardPage iconPage = getIconPage(mValues.getIconState());
- mValues.updateIconState(mMainPage.getEvaluator());
- return iconPage;
- } else if (page == mMainPage
- || shouldAddIconPage() && page == getIconPage(mValues.getIconState())) {
- if (template != null) {
- if (InstallDependencyPage.isInstalled(template.getDependencies())) {
- return getPreviewPage(mValues);
- } else {
- return getDependencyPage(template, true);
- }
- }
- } else if (page == getDependencyPage(template, false)) {
- return getPreviewPage(mValues);
- }
-
- return super.getNextPage(page);
- }
-
- @Override
- @NonNull
- protected IProject getProject() {
- return mValues.project;
- }
-
- @Override
- @NonNull
- protected List<String> getFilesToOpen() {
- TemplateHandler activityTemplate = mValues.getTemplateHandler();
- return activityTemplate.getFilesToOpen();
- }
-
- @Override
- @NonNull
- protected List<Runnable> getFinalizingActions() {
- TemplateHandler activityTemplate = mValues.getTemplateHandler();
- return activityTemplate.getFinalizingActions();
- }
-
- @Override
- protected List<Change> computeChanges() {
- return mValues.computeChanges();
- }
-
- /**
- * Opens the given set of files (as relative paths within a given project
- *
- * @param project the project containing the paths
- * @param relativePaths the paths to files to open
- * @param mWorkbench the workbench to open the files in
- */
- public static void openFiles(
- @NonNull final IProject project,
- @NonNull final List<String> relativePaths,
- @NonNull final IWorkbench mWorkbench) {
- if (!relativePaths.isEmpty()) {
- // This has to be delayed in order for focus handling to work correctly
- AdtPlugin.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- for (String path : relativePaths) {
- IResource resource = project.findMember(path);
- if (resource != null) {
- if (resource instanceof IFile) {
- try {
- AdtPlugin.openFile((IFile) resource, null, false);
- } catch (PartInitException e) {
- AdtPlugin.log(e, "Failed to open %1$s", //$NON-NLS-1$
- resource.getFullPath().toString());
- }
- }
- boolean isLast = relativePaths.size() == 1 ||
- path.equals(relativePaths.get(relativePaths.size() - 1));
- if (isLast) {
- BasicNewResourceWizard.selectAndReveal(resource,
- mWorkbench.getActiveWorkbenchWindow());
- }
- }
- }
- }
- });
- }
- }
-
- /**
- * Specific New Custom View wizard
- */
- public static class NewCustomViewWizard extends NewTemplateWizard {
- /** Creates a new {@link NewCustomViewWizard} */
- public NewCustomViewWizard() {
- super(CUSTOM_VIEW);
- }
-
- @Override
- public void init(IWorkbench workbench, IStructuredSelection selection) {
- super.init(workbench, selection);
- setWindowTitle("New Custom View");
- super.mMainPage.setTitle("New Custom View");
- super.mMainPage.setDescription("Creates a new custom view");
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewTemplateWizardState.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewTemplateWizardState.java
deleted file mode 100644
index 2c97003f2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/NewTemplateWizardState.java
+++ /dev/null
@@ -1,215 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.ATTR_BUILD_API;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.ATTR_COPY_ICONS;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.ATTR_MIN_API;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.ATTR_MIN_API_LEVEL;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.ATTR_PACKAGE_NAME;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.ATTR_TARGET_API;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.IS_LIBRARY_PROJECT;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.IS_NEW_PROJECT;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewTemplateWizard.BLANK_ACTIVITY;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.internal.assetstudio.ConfigureAssetSetPage;
-import com.android.ide.eclipse.adt.internal.assetstudio.CreateAssetSetWizardState;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.sdklib.IAndroidTarget;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.NullChange;
-
-import java.io.File;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Value object which holds the current state of the wizard pages for the
- * {@link NewTemplateWizard}
- */
-public class NewTemplateWizardState {
- /** Template handler responsible for instantiating templates and reading resources */
- private TemplateHandler mTemplateHandler;
-
- /** Configured parameters, by id */
- public final Map<String, Object> parameters = new HashMap<String, Object>();
-
- /** Configured defaults for the parameters, by id */
- public final Map<String, String> defaults = new HashMap<String, String>();
-
- /** Ids for parameters which should be hidden (because the client wizard already
- * has information for these parameters) */
- public final Set<String> hidden = new HashSet<String>();
-
- /**
- * The chosen project (which may be null if the wizard page is being
- * embedded in the new project wizard)
- */
- public IProject project;
-
- /** The minimum API level to use for this template */
- public int minSdkLevel;
-
- /** Location of the template being created */
- private File mTemplateLocation;
-
- /**
- * State for the asset studio wizard, used to create custom icons provided
- * the icon requests it with an {@code <icons>} element
- */
- private CreateAssetSetWizardState mIconState;
-
- /**
- * Create a new state object for use by the {@link NewTemplatePage}
- */
- public NewTemplateWizardState() {
- parameters.put(IS_NEW_PROJECT, false);
- }
-
- @NonNull
- TemplateHandler getTemplateHandler() {
- if (mTemplateHandler == null) {
- File inputPath;
- if (mTemplateLocation != null) {
- inputPath = mTemplateLocation;
- } else {
- // Default
- inputPath = TemplateManager.getTemplateLocation(BLANK_ACTIVITY);
- }
- mTemplateHandler = TemplateHandler.createFromPath(inputPath);
- }
-
- return mTemplateHandler;
- }
-
- /** Sets the current template */
- void setTemplateLocation(File file) {
- if (!file.equals(mTemplateLocation)) {
- mTemplateLocation = file;
- mTemplateHandler = null;
- }
- }
-
- /** Returns the current template */
- File getTemplateLocation() {
- return mTemplateLocation;
- }
-
- /** Returns the min SDK version to use */
- int getMinSdk() {
- if (project == null) {
- return -1;
- }
- ManifestInfo manifest = ManifestInfo.get(project);
- return manifest.getMinSdkVersion();
- }
-
- /** Returns the build API version to use */
- int getBuildApi() {
- if (project == null) {
- return -1;
- }
- IAndroidTarget target = Sdk.getCurrent().getTarget(project);
- if (target != null) {
- return target.getVersion().getApiLevel();
- }
-
- return getMinSdk();
- }
-
- /** Computes the changes this wizard will make */
- @NonNull
- List<Change> computeChanges() {
- if (project == null) {
- return Collections.emptyList();
- }
-
- ManifestInfo manifest = ManifestInfo.get(project);
- parameters.put(ATTR_PACKAGE_NAME, manifest.getPackage());
- parameters.put(ATTR_MIN_API, manifest.getMinSdkName());
- parameters.put(ATTR_MIN_API_LEVEL, manifest.getMinSdkVersion());
- parameters.put(ATTR_TARGET_API, manifest.getTargetSdkVersion());
- parameters.put(ATTR_BUILD_API, getBuildApi());
- parameters.put(ATTR_COPY_ICONS, mIconState == null);
- ProjectState projectState = Sdk.getProjectState(project);
- parameters.put(IS_LIBRARY_PROJECT,
- projectState != null ? projectState.isLibrary() : false);
-
- TemplateHandler.addDirectoryParameters(parameters, project);
-
- List<Change> changes = getTemplateHandler().render(project, parameters);
-
- if (mIconState != null) {
- String title = String.format("Generate icons (res/drawable-<density>/%1$s.png)",
- mIconState.outputName);
- changes.add(new NullChange(title) {
- @Override
- public Change perform(IProgressMonitor pm) throws CoreException {
- ConfigureAssetSetPage.generateIcons(mIconState.project,
- mIconState, false, null);
-
- // Not undoable: just return null instead of an undo-change.
- return null;
- }
- });
-
- }
-
- return changes;
- }
-
- @NonNull
- CreateAssetSetWizardState getIconState() {
- if (mIconState == null) {
- TemplateHandler handler = getTemplateHandler();
- if (handler != null) {
- TemplateMetadata template = handler.getTemplate();
- if (template != null) {
- mIconState = template.getIconState(project);
- }
- }
- }
-
- return mIconState;
- }
-
- /**
- * Updates the icon state, such as the output name, based on other parameter settings
- * @param evaluator the string evaluator, or null if none exists
- */
- public void updateIconState(@Nullable StringEvaluator evaluator) {
- TemplateMetadata template = getTemplateHandler().getTemplate();
- if (template != null) {
- if (evaluator == null) {
- evaluator = new StringEvaluator();
- }
- template.updateIconName(template.getParameters(), evaluator);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/Parameter.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/Parameter.java
deleted file mode 100644
index 3139451c7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/Parameter.java
+++ /dev/null
@@ -1,417 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.ATTR_PACKAGE_NAME;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.ATTR_CONSTRAINTS;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.ATTR_DEFAULT;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.ATTR_HELP;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.ATTR_ID;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.ATTR_NAME;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.ATTR_SUGGEST;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.resources.ResourceNameValidator;
-import com.android.ide.eclipse.adt.internal.wizards.newproject.ApplicationInfoPage;
-import com.android.resources.ResourceFolderType;
-import com.android.resources.ResourceType;
-import com.google.common.base.Splitter;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jface.dialogs.IInputValidator;
-import org.eclipse.jface.fieldassist.ControlDecoration;
-import org.eclipse.swt.widgets.Control;
-import org.w3c.dom.Element;
-
-import java.util.Collections;
-import java.util.EnumSet;
-import java.util.List;
-import java.util.Locale;
-
-/**
- * A template parameter editable and edited by the user.
- * <p>
- * Note that this class encapsulates not just the metadata provided by the
- * template, but the actual editing operation of that template in the wizard: it
- * also captures current values, a reference to the editing widget (such that
- * related widgets can be updated when one value depends on another etc)
- */
-class Parameter {
- enum Type {
- STRING,
- BOOLEAN,
- ENUM,
- SEPARATOR;
- // TODO: Numbers?
-
- public static Type get(String name) {
- try {
- return Type.valueOf(name.toUpperCase(Locale.US));
- } catch (IllegalArgumentException e) {
- AdtPlugin.printErrorToConsole("Unexpected template type '" + name + "'");
- AdtPlugin.printErrorToConsole("Expected one of :");
- for (Type s : Type.values()) {
- AdtPlugin.printErrorToConsole(" " + s.name().toLowerCase(Locale.US));
- }
- }
-
- return STRING;
- }
- }
-
- /**
- * Constraints that can be applied to a parameter which helps the UI add a
- * validator etc for user input. These are typically combined into a set
- * of constraints via an EnumSet.
- */
- enum Constraint {
- /**
- * This value must be unique. This constraint usually only makes sense
- * when other constraints are specified, such as {@link #LAYOUT}, which
- * means that the parameter should designate a name that does not
- * represent an existing layout resource name
- */
- UNIQUE,
-
- /**
- * This value must already exist. This constraint usually only makes sense
- * when other constraints are specified, such as {@link #LAYOUT}, which
- * means that the parameter should designate a name that already exists as
- * a resource name.
- */
- EXISTS,
-
- /** The associated value must not be empty */
- NONEMPTY,
-
- /** The associated value is allowed to be empty */
- EMPTY,
-
- /** The associated value should represent a fully qualified activity class name */
- ACTIVITY,
-
- /** The associated value should represent an API level */
- APILEVEL,
-
- /** The associated value should represent a valid class name */
- CLASS,
-
- /** The associated value should represent a valid package name */
- PACKAGE,
-
- /** The associated value should represent a valid layout resource name */
- LAYOUT,
-
- /** The associated value should represent a valid drawable resource name */
- DRAWABLE,
-
- /** The associated value should represent a valid id resource name */
- ID,
-
- /** The associated value should represent a valid string resource name */
- STRING;
-
- public static Constraint get(String name) {
- try {
- return Constraint.valueOf(name.toUpperCase(Locale.US));
- } catch (IllegalArgumentException e) {
- AdtPlugin.printErrorToConsole("Unexpected template constraint '" + name + "'");
- if (name.indexOf(',') != -1) {
- AdtPlugin.printErrorToConsole("Use | to separate constraints");
- } else {
- AdtPlugin.printErrorToConsole("Expected one of :");
- for (Constraint s : Constraint.values()) {
- AdtPlugin.printErrorToConsole(" " + s.name().toLowerCase(Locale.US));
- }
- }
- }
-
- return NONEMPTY;
- }
- }
-
- /** The template defining the parameter */
- public final TemplateMetadata template;
-
- /** The type of parameter */
- @NonNull
- public final Type type;
-
- /** The unique id of the parameter (not displayed to the user) */
- @Nullable
- public final String id;
-
- /** The display name for this parameter */
- @Nullable
- public final String name;
-
- /**
- * The initial value for this parameter (see also {@link #suggest} for more
- * dynamic defaults
- */
- @Nullable
- public final String initial;
-
- /**
- * A template expression using other template parameters for producing a
- * default value based on other edited parameters, if possible.
- */
- @Nullable
- public final String suggest;
-
- /** Help for the parameter, if any */
- @Nullable
- public final String help;
-
- /** The currently edited value */
- @Nullable
- public Object value;
-
- /** The control showing this value */
- @Nullable
- public Control control;
-
- /** The decoration associated with the control */
- @Nullable
- public ControlDecoration decoration;
-
- /** Whether the parameter has been edited */
- public boolean edited;
-
- /** The element defining this parameter */
- @NonNull
- public final Element element;
-
- /** The constraints applicable for this parameter */
- @NonNull
- public final EnumSet<Constraint> constraints;
-
- /** The validator, if any, for this field */
- private IInputValidator mValidator;
-
- /** True if this field has no validator */
- private boolean mNoValidator;
-
- /** Project associated with this validator */
- private IProject mValidatorProject;
-
- Parameter(@NonNull TemplateMetadata template, @NonNull Element parameter) {
- this.template = template;
- element = parameter;
-
- String typeName = parameter.getAttribute(TemplateHandler.ATTR_TYPE);
- assert typeName != null && !typeName.isEmpty() : TemplateHandler.ATTR_TYPE;
- type = Type.get(typeName);
-
- id = parameter.getAttribute(ATTR_ID);
- initial = parameter.getAttribute(ATTR_DEFAULT);
- suggest = parameter.getAttribute(ATTR_SUGGEST);
- name = parameter.getAttribute(ATTR_NAME);
- help = parameter.getAttribute(ATTR_HELP);
- String constraintString = parameter.getAttribute(ATTR_CONSTRAINTS);
- if (constraintString != null && !constraintString.isEmpty()) {
- EnumSet<Constraint> constraintSet = null;
- for (String s : Splitter.on('|').omitEmptyStrings().split(constraintString)) {
- Constraint constraint = Constraint.get(s);
- if (constraintSet == null) {
- constraintSet = EnumSet.of(constraint);
- } else {
- constraintSet = EnumSet.copyOf(constraintSet);
- constraintSet.add(constraint);
- }
- }
- constraints = constraintSet;
- } else {
- constraints = EnumSet.noneOf(Constraint.class);
- }
-
- if (initial != null && !initial.isEmpty() && type == Type.BOOLEAN) {
- value = Boolean.valueOf(initial);
- } else {
- value = initial;
- }
- }
-
- Parameter(
- @NonNull TemplateMetadata template,
- @NonNull Type type,
- @NonNull String id,
- @NonNull String initialValue) {
- this.template = template;
- this.type = type;
- this.id = id;
- this.value = initialValue;
- element = null;
- initial = null;
- suggest = null;
- name = id;
- help = null;
- constraints = EnumSet.noneOf(Constraint.class);
- }
-
- List<Element> getOptions() {
- if (element != null) {
- return DomUtilities.getChildren(element);
- } else {
- return Collections.emptyList();
- }
- }
-
- @Nullable
- public IInputValidator getValidator(@Nullable final IProject project) {
- if (mNoValidator) {
- return null;
- }
-
- if (project != mValidatorProject) {
- // Force update of validators if the project changes, since the validators
- // are often tied to project metadata (for example, the resource name validators
- // which look for name conflicts)
- mValidator = null;
- mValidatorProject = project;
- }
-
- if (mValidator == null) {
- if (constraints.contains(Constraint.LAYOUT)) {
- if (project != null && constraints.contains(Constraint.UNIQUE)) {
- mValidator = ResourceNameValidator.create(false, project, ResourceType.LAYOUT);
- } else {
- mValidator = ResourceNameValidator.create(false, ResourceFolderType.LAYOUT);
- }
- return mValidator;
- } else if (constraints.contains(Constraint.STRING)) {
- if (project != null && constraints.contains(Constraint.UNIQUE)) {
- mValidator = ResourceNameValidator.create(false, project, ResourceType.STRING);
- } else {
- mValidator = ResourceNameValidator.create(false, ResourceFolderType.VALUES);
- }
- return mValidator;
- } else if (constraints.contains(Constraint.ID)) {
- if (project != null && constraints.contains(Constraint.UNIQUE)) {
- mValidator = ResourceNameValidator.create(false, project, ResourceType.ID);
- } else {
- mValidator = ResourceNameValidator.create(false, ResourceFolderType.VALUES);
- }
- return mValidator;
- } else if (constraints.contains(Constraint.DRAWABLE)) {
- if (project != null && constraints.contains(Constraint.UNIQUE)) {
- mValidator = ResourceNameValidator.create(false, project,
- ResourceType.DRAWABLE);
- } else {
- mValidator = ResourceNameValidator.create(false, ResourceFolderType.DRAWABLE);
- }
- return mValidator;
- } else if (constraints.contains(Constraint.PACKAGE)
- || constraints.contains(Constraint.CLASS)
- || constraints.contains(Constraint.ACTIVITY)) {
- mValidator = new IInputValidator() {
- @Override
- public String isValid(String newText) {
- newText = newText.trim();
- if (newText.isEmpty()) {
- if (constraints.contains(Constraint.EMPTY)) {
- return null;
- } else if (constraints.contains(Constraint.NONEMPTY)) {
- return String.format("Enter a value for %1$s", name);
- } else {
- // Compatibility mode: older templates might not specify;
- // in that case, accept empty
- if (!"activityClass".equals(id)) { //$NON-NLS-1$
- return null;
- }
- }
- }
- IStatus status;
- if (constraints.contains(Constraint.ACTIVITY)) {
- status = ApplicationInfoPage.validateActivity(newText);
- } else if (constraints.contains(Constraint.PACKAGE)) {
- status = ApplicationInfoPage.validatePackage(newText);
- } else {
- assert constraints.contains(Constraint.CLASS);
- status = ApplicationInfoPage.validateClass(newText);
- }
- if (status != null && !status.isOK()) {
- return status.getMessage();
- }
-
- // Uniqueness
- if (project != null && constraints.contains(Constraint.UNIQUE)) {
- try {
- // Determine the package.
- // If there is a package info
-
- IJavaProject p = BaseProjectHelper.getJavaProject(project);
- if (p != null) {
- String fqcn = newText;
- if (fqcn.indexOf('.') == -1) {
- String pkg = null;
- Parameter parameter = template.getParameter(
- ATTR_PACKAGE_NAME);
- if (parameter != null && parameter.value != null) {
- pkg = parameter.value.toString();
- } else {
- pkg = ManifestInfo.get(project).getPackage();
- }
- fqcn = pkg.isEmpty() ? newText : pkg + '.' + newText;
- }
-
- IType t = p.findType(fqcn);
- if (t != null && t.exists()) {
- return String.format("%1$s already exists", newText);
- }
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- }
-
- return null;
- }
- };
- return mValidator;
- } else if (constraints.contains(Constraint.NONEMPTY)) {
- mValidator = new IInputValidator() {
- @Override
- public String isValid(String newText) {
- if (newText.trim().isEmpty()) {
- return String.format("Enter a value for %1$s", name);
- }
-
- return null;
- }
- };
- return mValidator;
- }
-
- // TODO: Handle EXISTS, APILEVEL (which is currently handled manually in the
- // new project wizard, and never actually input by the user in a templated
- // wizard)
-
- mNoValidator = true;
- }
-
- return mValidator;
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/ProjectContentsPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/ProjectContentsPage.java
deleted file mode 100644
index 7d7881fcf..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/ProjectContentsPage.java
+++ /dev/null
@@ -1,380 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.wizards.newproject.WorkingSetGroup;
-import com.android.ide.eclipse.adt.internal.wizards.newproject.WorkingSetHelper;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.FocusEvent;
-import org.eclipse.swt.events.FocusListener;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.DirectoryDialog;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkingSet;
-
-import java.io.File;
-
-/**
- * Second wizard page in the "New Project From Template" wizard
- */
-public class ProjectContentsPage extends WizardPage
- implements ModifyListener, SelectionListener, FocusListener {
-
- private final NewProjectWizardState mValues;
-
- private boolean mIgnore;
- private Button mCustomIconToggle;
- private Button mLibraryToggle;
-
- private Button mUseDefaultLocationToggle;
- private Label mLocationLabel;
- private Text mLocationText;
- private Button mChooseLocationButton;
- private static String sLastProjectLocation = System.getProperty("user.home"); //$NON-NLS-1$
- private Button mCreateActivityToggle;
- private WorkingSetGroup mWorkingSetGroup;
-
- ProjectContentsPage(NewProjectWizardState values) {
- super("newAndroidApp"); //$NON-NLS-1$
- mValues = values;
- setTitle("New Android Application");
- setDescription("Configure Project");
-
- mWorkingSetGroup = new WorkingSetGroup();
- setWorkingSets(new IWorkingSet[0]);
- }
-
- @Override
- public void createControl(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
- setControl(container);
- GridLayout gl_container = new GridLayout(4, false);
- gl_container.horizontalSpacing = 10;
- container.setLayout(gl_container);
-
- mCustomIconToggle = new Button(container, SWT.CHECK);
- mCustomIconToggle.setSelection(true);
- mCustomIconToggle.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 4, 1));
- mCustomIconToggle.setText("Create custom launcher icon");
- mCustomIconToggle.setSelection(mValues.createIcon);
- mCustomIconToggle.addSelectionListener(this);
-
- mCreateActivityToggle = new Button(container, SWT.CHECK);
- mCreateActivityToggle.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false,
- 4, 1));
- mCreateActivityToggle.setText("Create activity");
- mCreateActivityToggle.setSelection(mValues.createActivity);
- mCreateActivityToggle.addSelectionListener(this);
-
- new Label(container, SWT.NONE).setLayoutData(
- new GridData(SWT.LEFT, SWT.CENTER, false, false, 4, 1));
-
- mLibraryToggle = new Button(container, SWT.CHECK);
- mLibraryToggle.setSelection(true);
- mLibraryToggle.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 4, 1));
- mLibraryToggle.setText("Mark this project as a library");
- mLibraryToggle.setSelection(mValues.isLibrary);
- mLibraryToggle.addSelectionListener(this);
-
- // Blank line
- new Label(container, SWT.NONE).setLayoutData(
- new GridData(SWT.LEFT, SWT.CENTER, false, false, 4, 1));
-
- mUseDefaultLocationToggle = new Button(container, SWT.CHECK);
- mUseDefaultLocationToggle.setLayoutData(
- new GridData(SWT.LEFT, SWT.CENTER, false, false, 4, 1));
- mUseDefaultLocationToggle.setText("Create Project in Workspace");
- mUseDefaultLocationToggle.addSelectionListener(this);
-
- mLocationLabel = new Label(container, SWT.NONE);
- mLocationLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- mLocationLabel.setText("Location:");
-
- mLocationText = new Text(container, SWT.BORDER);
- mLocationText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
- mLocationText.addModifyListener(this);
-
- mChooseLocationButton = new Button(container, SWT.NONE);
- mChooseLocationButton.setText("Browse...");
- mChooseLocationButton.addSelectionListener(this);
- mChooseLocationButton.setEnabled(false);
- setUseCustomLocation(!mValues.useDefaultLocation);
-
- new Label(container, SWT.NONE).setLayoutData(
- new GridData(SWT.LEFT, SWT.CENTER, false, false, 4, 1));
-
- Composite group = mWorkingSetGroup.createControl(container);
- group.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, false, 4, 1));
- }
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
-
- if (visible) {
- try {
- mIgnore = true;
- mUseDefaultLocationToggle.setSelection(mValues.useDefaultLocation);
- mLocationText.setText(mValues.projectLocation);
- } finally {
- mIgnore = false;
- }
- }
-
- validatePage();
- }
-
- private void setUseCustomLocation(boolean en) {
- mValues.useDefaultLocation = !en;
- mUseDefaultLocationToggle.setSelection(!en);
- if (!en) {
- updateProjectLocation(mValues.projectName);
- }
-
- mLocationLabel.setEnabled(en);
- mLocationText.setEnabled(en);
- mChooseLocationButton.setEnabled(en);
- }
-
- void init(IStructuredSelection selection, IWorkbenchPart activePart) {
- setWorkingSets(WorkingSetHelper.getSelectedWorkingSet(selection, activePart));
- }
-
- /**
- * Returns the working sets to which the new project should be added.
- *
- * @return the selected working sets to which the new project should be added
- */
- private IWorkingSet[] getWorkingSets() {
- return mWorkingSetGroup.getSelectedWorkingSets();
- }
-
- /**
- * Sets the working sets to which the new project should be added.
- *
- * @param workingSets the initial selected working sets
- */
- private void setWorkingSets(IWorkingSet[] workingSets) {
- assert workingSets != null;
- mWorkingSetGroup.setWorkingSets(workingSets);
- }
-
- @Override
- public IWizardPage getNextPage() {
- // Sync working set data to the value object, since the WorkingSetGroup
- // doesn't let us add listeners to do this lazily
- mValues.workingSets = getWorkingSets();
-
- return super.getNextPage();
- }
-
- // ---- Implements ModifyListener ----
-
- @Override
- public void modifyText(ModifyEvent e) {
- if (mIgnore) {
- return;
- }
-
- Object source = e.getSource();
- if (source == mLocationText) {
- mValues.projectLocation = mLocationText.getText().trim();
- }
-
- validatePage();
- }
-
-
- /** If the project should be created in the workspace, then update the project location
- * based on the project name. */
- private void updateProjectLocation(String projectName) {
- if (projectName == null) {
- projectName = "";
- }
-
- boolean useDefaultLocation = mUseDefaultLocationToggle.getSelection();
-
- if (useDefaultLocation) {
- IPath workspace = Platform.getLocation();
- String projectLocation = workspace.append(projectName).toOSString();
- mLocationText.setText(projectLocation);
- mValues.projectLocation = projectLocation;
- }
- }
-
- // ---- Implements SelectionListener ----
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (mIgnore) {
- return;
- }
-
- Object source = e.getSource();
- if (source == mCustomIconToggle) {
- mValues.createIcon = mCustomIconToggle.getSelection();
- } else if (source == mLibraryToggle) {
- mValues.isLibrary = mLibraryToggle.getSelection();
- } else if (source == mCreateActivityToggle) {
- mValues.createActivity = mCreateActivityToggle.getSelection();
- } else if (source == mUseDefaultLocationToggle) {
- boolean useDefault = mUseDefaultLocationToggle.getSelection();
- setUseCustomLocation(!useDefault);
- } else if (source == mChooseLocationButton) {
- String dir = promptUserForLocation(getShell());
- if (dir != null) {
- mLocationText.setText(dir);
- mValues.projectLocation = dir;
- }
- }
-
- validatePage();
- }
-
- private String promptUserForLocation(Shell shell) {
- DirectoryDialog dd = new DirectoryDialog(getShell());
- dd.setMessage("Select folder where project should be created");
-
- String curLocation = mLocationText.getText().trim();
- if (!curLocation.isEmpty()) {
- dd.setFilterPath(curLocation);
- } else if (sLastProjectLocation != null) {
- dd.setFilterPath(sLastProjectLocation);
- }
-
- String dir = dd.open();
- if (dir != null) {
- sLastProjectLocation = dir;
- }
-
- return dir;
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
-
- // ---- Implements FocusListener ----
-
- @Override
- public void focusGained(FocusEvent e) {
- }
-
- @Override
- public void focusLost(FocusEvent e) {
- }
-
- // Validation
-
- void validatePage() {
- IStatus status = validateProjectLocation();
-
- setPageComplete(status == null || status.getSeverity() != IStatus.ERROR);
- if (status != null) {
- setMessage(status.getMessage(),
- status.getSeverity() == IStatus.ERROR
- ? IMessageProvider.ERROR : IMessageProvider.WARNING);
- } else {
- setErrorMessage(null);
- setMessage(null);
- }
- }
-
- static IStatus validateLocationInWorkspace(NewProjectWizardState values) {
- if (values.useDefaultLocation) {
- return null;
- }
-
- // Validate location
- if (values.projectName != null) {
- File dest = Platform.getLocation().append(values.projectName).toFile();
- if (dest.exists()) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID, String.format(
- "There is already a file or directory named \"%1$s\" in the selected location.",
- values.projectName));
- }
- }
-
- return null;
- }
-
- private IStatus validateProjectLocation() {
- if (mValues.useDefaultLocation) {
- return validateLocationInWorkspace(mValues);
- }
-
- String location = mLocationText.getText();
- if (location.trim().isEmpty()) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- "Provide a valid file system location where the project should be created.");
- }
-
- File f = new File(location);
- if (f.exists()) {
- if (!f.isDirectory()) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- String.format("'%s' is not a valid folder.", location));
- }
-
- File[] children = f.listFiles();
- if (children != null && children.length > 0) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- String.format("Folder '%s' is not empty.", location));
- }
- }
-
- // if the folder doesn't exist, then make sure that the parent
- // exists and is a writable folder
- File parent = f.getParentFile();
- if (!parent.exists()) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- String.format("Folder '%s' does not exist.", parent.getName()));
- }
-
- if (!parent.isDirectory()) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- String.format("'%s' is not a folder.", parent.getName()));
- }
-
- if (!parent.canWrite()) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- String.format("'%s' is not writeable.", parent.getName()));
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/StringEvaluator.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/StringEvaluator.java
deleted file mode 100644
index c1c8073c0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/StringEvaluator.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import static com.android.tools.lint.detector.api.LintUtils.assertionsEnabled;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import freemarker.cache.TemplateLoader;
-import freemarker.template.Configuration;
-import freemarker.template.DefaultObjectWrapper;
-import freemarker.template.Template;
-
-import java.io.IOException;
-import java.io.Reader;
-import java.io.StringReader;
-import java.io.StringWriter;
-import java.util.List;
-import java.util.Map;
-
-/**
- * A template handler which can evaluate simple strings. Used to evaluate
- * parameter constraints during UI wizard value editing.
- * <p>
- * Unlike the more general {@link TemplateHandler} which is used to instantiate
- * full template files (from resources, merging into existing files etc) this
- * evaluator supports only simple strings, referencing only values from the
- * provided map (and builtin functions).
- */
-class StringEvaluator implements TemplateLoader {
- private Map<String, Object> mParameters;
- private Configuration mFreemarker;
- private String mCurrentExpression;
-
- StringEvaluator() {
- mParameters = TemplateHandler.createBuiltinMap();
-
- mFreemarker = new Configuration();
- mFreemarker.setObjectWrapper(new DefaultObjectWrapper());
- mFreemarker.setTemplateLoader(this);
- }
-
- /** Evaluates the given expression, with the given set of parameters */
- @Nullable
- String evaluate(@NonNull String expression, @NonNull List<Parameter> parameters) {
- // Render the instruction list template.
- for (Parameter parameter : parameters) {
- mParameters.put(parameter.id, parameter.value);
- }
- try {
- mCurrentExpression = expression;
- Template inputsTemplate = mFreemarker.getTemplate(expression);
- StringWriter out = new StringWriter();
- inputsTemplate.process(mParameters, out);
- out.flush();
- return out.toString();
- } catch (Exception e) {
- if (assertionsEnabled()) {
- AdtPlugin.log(e, null);
- }
- return null;
- }
- }
-
- // ---- Implements TemplateLoader ----
-
- @Override
- public Object findTemplateSource(String name) throws IOException {
- return mCurrentExpression;
- }
-
- @Override
- public long getLastModified(Object templateSource) {
- return 0;
- }
-
- @Override
- public Reader getReader(Object templateSource, String encoding) throws IOException {
- return new StringReader(mCurrentExpression);
- }
-
- @Override
- public void closeTemplateSource(Object templateSource) throws IOException {
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateHandler.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateHandler.java
deleted file mode 100644
index 8e11841b4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateHandler.java
+++ /dev/null
@@ -1,1239 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import static com.android.SdkConstants.ATTR_PACKAGE;
-import static com.android.SdkConstants.DOT_AIDL;
-import static com.android.SdkConstants.DOT_FTL;
-import static com.android.SdkConstants.DOT_JAVA;
-import static com.android.SdkConstants.DOT_RS;
-import static com.android.SdkConstants.DOT_SVG;
-import static com.android.SdkConstants.DOT_TXT;
-import static com.android.SdkConstants.DOT_XML;
-import static com.android.SdkConstants.EXT_XML;
-import static com.android.SdkConstants.FD_NATIVE_LIBS;
-import static com.android.SdkConstants.XMLNS_PREFIX;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.InstallDependencyPage.SUPPORT_LIBRARY_NAME;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateManager.getTemplateRootFolder;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.annotations.VisibleForTesting;
-import com.android.ide.common.xml.XmlFormatStyle;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.actions.AddSupportJarAction;
-import com.android.ide.eclipse.adt.internal.editors.formatting.EclipseXmlFormatPreferences;
-import com.android.ide.eclipse.adt.internal.editors.formatting.EclipseXmlPrettyPrinter;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.sdk.AdtManifestMergeCallback;
-import com.android.manifmerger.ManifestMerger;
-import com.android.manifmerger.MergerLog;
-import com.android.resources.ResourceFolderType;
-import com.android.utils.SdkUtils;
-import com.google.common.base.Charsets;
-import com.google.common.collect.Lists;
-import com.google.common.io.Files;
-
-import freemarker.cache.TemplateLoader;
-import freemarker.template.Configuration;
-import freemarker.template.DefaultObjectWrapper;
-import freemarker.template.Template;
-import freemarker.template.TemplateException;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.ToolFactory;
-import org.eclipse.jdt.core.formatter.CodeFormatter;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.NullChange;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.swt.SWT;
-import org.eclipse.text.edits.InsertEdit;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.ReplaceEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.osgi.framework.Constants;
-import org.osgi.framework.Version;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.xml.sax.Attributes;
-import org.xml.sax.SAXException;
-import org.xml.sax.helpers.DefaultHandler;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.Reader;
-import java.io.StringWriter;
-import java.io.Writer;
-import java.lang.reflect.InvocationTargetException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
-
-/**
- * Handler which manages instantiating FreeMarker templates, copying resources
- * and merging into existing files
- */
-class TemplateHandler {
- /** Highest supported format; templates with a higher number will be skipped
- * <p>
- * <ul>
- * <li> 1: Initial format, supported by ADT 20 and up.
- * <li> 2: ADT 21 and up. Boolean variables that have a default value and are not
- * edited by the user would end up as strings in ADT 20; now they are always
- * proper Booleans. Templates which rely on this should specify format >= 2.
- * <li> 3: The wizard infrastructure passes the {@code isNewProject} boolean variable
- * to indicate whether a wizard is created as part of a new blank project
- * <li> 4: The templates now specify dependencies in the recipe file.
- * </ul>
- */
- static final int CURRENT_FORMAT = 4;
-
- /**
- * Special marker indicating that this path refers to the special shared
- * resource directory rather than being somewhere inside the root/ directory
- * where all template specific resources are found
- */
- private static final String VALUE_TEMPLATE_DIR = "$TEMPLATEDIR"; //$NON-NLS-1$
-
- /**
- * Directory within the template which contains the resources referenced
- * from the template.xml file
- */
- private static final String DATA_ROOT = "root"; //$NON-NLS-1$
-
- /**
- * Shared resource directory containing common resources shared among
- * multiple templates
- */
- private static final String RESOURCE_ROOT = "resources"; //$NON-NLS-1$
-
- /** Reserved filename which describes each template */
- static final String TEMPLATE_XML = "template.xml"; //$NON-NLS-1$
-
- // Various tags and attributes used in the template metadata files - template.xml,
- // globals.xml.ftl, recipe.xml.ftl, etc.
-
- static final String TAG_MERGE = "merge"; //$NON-NLS-1$
- static final String TAG_EXECUTE = "execute"; //$NON-NLS-1$
- static final String TAG_GLOBALS = "globals"; //$NON-NLS-1$
- static final String TAG_GLOBAL = "global"; //$NON-NLS-1$
- static final String TAG_PARAMETER = "parameter"; //$NON-NLS-1$
- static final String TAG_COPY = "copy"; //$NON-NLS-1$
- static final String TAG_INSTANTIATE = "instantiate"; //$NON-NLS-1$
- static final String TAG_OPEN = "open"; //$NON-NLS-1$
- static final String TAG_THUMB = "thumb"; //$NON-NLS-1$
- static final String TAG_THUMBS = "thumbs"; //$NON-NLS-1$
- static final String TAG_DEPENDENCY = "dependency"; //$NON-NLS-1$
- static final String TAG_ICONS = "icons"; //$NON-NLS-1$
- static final String TAG_FORMFACTOR = "formfactor"; //$NON-NLS-1$
- static final String TAG_CATEGORY = "category"; //$NON-NLS-1$
- static final String ATTR_FORMAT = "format"; //$NON-NLS-1$
- static final String ATTR_REVISION = "revision"; //$NON-NLS-1$
- static final String ATTR_VALUE = "value"; //$NON-NLS-1$
- static final String ATTR_DEFAULT = "default"; //$NON-NLS-1$
- static final String ATTR_SUGGEST = "suggest"; //$NON-NLS-1$
- static final String ATTR_ID = "id"; //$NON-NLS-1$
- static final String ATTR_NAME = "name"; //$NON-NLS-1$
- static final String ATTR_DESCRIPTION = "description";//$NON-NLS-1$
- static final String ATTR_TYPE = "type"; //$NON-NLS-1$
- static final String ATTR_HELP = "help"; //$NON-NLS-1$
- static final String ATTR_FILE = "file"; //$NON-NLS-1$
- static final String ATTR_TO = "to"; //$NON-NLS-1$
- static final String ATTR_FROM = "from"; //$NON-NLS-1$
- static final String ATTR_CONSTRAINTS = "constraints";//$NON-NLS-1$
- static final String ATTR_BACKGROUND = "background"; //$NON-NLS-1$
- static final String ATTR_FOREGROUND = "foreground"; //$NON-NLS-1$
- static final String ATTR_SHAPE = "shape"; //$NON-NLS-1$
- static final String ATTR_TRIM = "trim"; //$NON-NLS-1$
- static final String ATTR_PADDING = "padding"; //$NON-NLS-1$
- static final String ATTR_SOURCE_TYPE = "source"; //$NON-NLS-1$
- static final String ATTR_CLIPART_NAME = "clipartName";//$NON-NLS-1$
- static final String ATTR_TEXT = "text"; //$NON-NLS-1$
- static final String ATTR_SRC_DIR = "srcDir"; //$NON-NLS-1$
- static final String ATTR_SRC_OUT = "srcOut"; //$NON-NLS-1$
- static final String ATTR_RES_DIR = "resDir"; //$NON-NLS-1$
- static final String ATTR_RES_OUT = "resOut"; //$NON-NLS-1$
- static final String ATTR_MANIFEST_DIR = "manifestDir";//$NON-NLS-1$
- static final String ATTR_MANIFEST_OUT = "manifestOut";//$NON-NLS-1$
- static final String ATTR_PROJECT_DIR = "projectDir"; //$NON-NLS-1$
- static final String ATTR_PROJECT_OUT = "projectOut"; //$NON-NLS-1$
- static final String ATTR_MAVEN_URL = "mavenUrl"; //$NON-NLS-1$
- static final String ATTR_DEBUG_KEYSTORE_SHA1 =
- "debugKeystoreSha1"; //$NON-NLS-1$
-
- static final String CATEGORY_ACTIVITIES = "activities";//$NON-NLS-1$
- static final String CATEGORY_PROJECTS = "projects"; //$NON-NLS-1$
- static final String CATEGORY_OTHER = "other"; //$NON-NLS-1$
-
- static final String MAVEN_SUPPORT_V4 = "support-v4"; //$NON-NLS-1$
- static final String MAVEN_SUPPORT_V13 = "support-v13"; //$NON-NLS-1$
- static final String MAVEN_APPCOMPAT = "appcompat-v7"; //$NON-NLS-1$
-
- /** Default padding to apply in wizards around the thumbnail preview images */
- static final int PREVIEW_PADDING = 10;
-
- /** Default width to scale thumbnail preview images in wizards to */
- static final int PREVIEW_WIDTH = 200;
-
- /**
- * List of files to open after the wizard has been created (these are
- * identified by {@link #TAG_OPEN} elements in the recipe file
- */
- private final List<String> mOpen = Lists.newArrayList();
-
- /**
- * List of actions to perform after the wizard has finished.
- */
- protected List<Runnable> mFinalizingActions = Lists.newArrayList();
-
- /** Path to the directory containing the templates */
- @NonNull
- private final File mRootPath;
-
- /** The changes being processed by the template handler */
- private List<Change> mMergeChanges;
- private List<Change> mTextChanges;
- private List<Change> mOtherChanges;
-
- /** The project to write the template into */
- private IProject mProject;
-
- /** The template loader which is responsible for finding (and sharing) template files */
- private final MyTemplateLoader mLoader;
-
- /** Agree to all file-overwrites from now on? */
- private boolean mYesToAll = false;
-
- /** Is writing the template cancelled? */
- private boolean mNoToAll = false;
-
- /**
- * Should files that we merge contents into be backed up? If yes, will
- * create emacs-style tilde-file backups (filename.xml~)
- */
- private boolean mBackupMergedFiles = true;
-
- /**
- * Template metadata
- */
- private TemplateMetadata mTemplate;
-
- private final TemplateManager mManager;
-
- /** Creates a new {@link TemplateHandler} for the given root path */
- static TemplateHandler createFromPath(File rootPath) {
- return new TemplateHandler(rootPath, new TemplateManager());
- }
-
- /** Creates a new {@link TemplateHandler} for the template name, which should
- * be relative to the templates directory */
- static TemplateHandler createFromName(String category, String name) {
- TemplateManager manager = new TemplateManager();
-
- // Use the TemplateManager iteration which should merge contents between the
- // extras/templates/ and tools/templates folders and pick the most recent version
- List<File> templates = manager.getTemplates(category);
- for (File file : templates) {
- if (file.getName().equals(name) && category.equals(file.getParentFile().getName())) {
- return new TemplateHandler(file, manager);
- }
- }
-
- return new TemplateHandler(new File(getTemplateRootFolder(),
- category + File.separator + name), manager);
- }
-
- private TemplateHandler(File rootPath, TemplateManager manager) {
- mRootPath = rootPath;
- mManager = manager;
- mLoader = new MyTemplateLoader();
- mLoader.setPrefix(mRootPath.getPath());
- }
-
- public TemplateManager getManager() {
- return mManager;
- }
-
- public void setBackupMergedFiles(boolean backupMergedFiles) {
- mBackupMergedFiles = backupMergedFiles;
- }
-
- @NonNull
- public List<Change> render(IProject project, Map<String, Object> args) {
- mOpen.clear();
-
- mProject = project;
- mMergeChanges = new ArrayList<Change>();
- mTextChanges = new ArrayList<Change>();
- mOtherChanges = new ArrayList<Change>();
-
- // Render the instruction list template.
- Map<String, Object> paramMap = createParameterMap(args);
- Configuration freemarker = new Configuration();
- freemarker.setObjectWrapper(new DefaultObjectWrapper());
- freemarker.setTemplateLoader(mLoader);
-
- processVariables(freemarker, TEMPLATE_XML, paramMap);
-
- // Add the changes in the order where merges are shown first, then text files,
- // and finally other files (like jars and icons which don't have previews).
- List<Change> changes = new ArrayList<Change>();
- changes.addAll(mMergeChanges);
- changes.addAll(mTextChanges);
- changes.addAll(mOtherChanges);
- return changes;
- }
-
- Map<String, Object> createParameterMap(Map<String, Object> args) {
- final Map<String, Object> paramMap = createBuiltinMap();
-
- // Wizard parameters supplied by user, specific to this template
- paramMap.putAll(args);
-
- return paramMap;
- }
-
- /** Data model for the templates */
- static Map<String, Object> createBuiltinMap() {
- // Create the data model.
- final Map<String, Object> paramMap = new HashMap<String, Object>();
-
- // Builtin conversion methods
- paramMap.put("slashedPackageName", new FmSlashedPackageNameMethod()); //$NON-NLS-1$
- paramMap.put("camelCaseToUnderscore", new FmCamelCaseToUnderscoreMethod()); //$NON-NLS-1$
- paramMap.put("underscoreToCamelCase", new FmUnderscoreToCamelCaseMethod()); //$NON-NLS-1$
- paramMap.put("activityToLayout", new FmActivityToLayoutMethod()); //$NON-NLS-1$
- paramMap.put("layoutToActivity", new FmLayoutToActivityMethod()); //$NON-NLS-1$
- paramMap.put("classToResource", new FmClassNameToResourceMethod()); //$NON-NLS-1$
- paramMap.put("escapeXmlAttribute", new FmEscapeXmlStringMethod()); //$NON-NLS-1$
- paramMap.put("escapeXmlText", new FmEscapeXmlStringMethod()); //$NON-NLS-1$
- paramMap.put("escapeXmlString", new FmEscapeXmlStringMethod()); //$NON-NLS-1$
- paramMap.put("extractLetters", new FmExtractLettersMethod()); //$NON-NLS-1$
-
- // This should be handled better: perhaps declared "required packages" as part of the
- // inputs? (It would be better if we could conditionally disable template based
- // on availability)
- Map<String, String> builtin = new HashMap<String, String>();
- builtin.put("templatesRes", VALUE_TEMPLATE_DIR); //$NON-NLS-1$
- paramMap.put("android", builtin); //$NON-NLS-1$
-
- return paramMap;
- }
-
- static void addDirectoryParameters(Map<String, Object> parameters, IProject project) {
- IPath srcDir = project.getFile(SdkConstants.SRC_FOLDER).getProjectRelativePath();
- parameters.put(ATTR_SRC_DIR, srcDir.toString());
-
- IPath resDir = project.getFile(SdkConstants.RES_FOLDER).getProjectRelativePath();
- parameters.put(ATTR_RES_DIR, resDir.toString());
-
- IPath manifestDir = project.getProjectRelativePath();
- parameters.put(ATTR_MANIFEST_DIR, manifestDir.toString());
- parameters.put(ATTR_MANIFEST_OUT, manifestDir.toString());
-
- parameters.put(ATTR_PROJECT_DIR, manifestDir.toString());
- parameters.put(ATTR_PROJECT_OUT, manifestDir.toString());
-
- parameters.put(ATTR_DEBUG_KEYSTORE_SHA1, "");
- }
-
- @Nullable
- public TemplateMetadata getTemplate() {
- if (mTemplate == null) {
- mTemplate = mManager.getTemplate(mRootPath);
- }
-
- return mTemplate;
- }
-
- @NonNull
- public String getResourcePath(String templateName) {
- return new File(mRootPath.getPath(), templateName).getPath();
- }
-
- /**
- * Load a text resource for the given relative path within the template
- *
- * @param relativePath relative path within the template
- * @return the string contents of the template text file
- */
- @Nullable
- public String readTemplateTextResource(@NonNull String relativePath) {
- try {
- return Files.toString(new File(mRootPath,
- relativePath.replace('/', File.separatorChar)), Charsets.UTF_8);
- } catch (IOException e) {
- AdtPlugin.log(e, null);
- return null;
- }
- }
-
- @Nullable
- public String readTemplateTextResource(@NonNull File file) {
- assert file.isAbsolute();
- try {
- return Files.toString(file, Charsets.UTF_8);
- } catch (IOException e) {
- AdtPlugin.log(e, null);
- return null;
- }
- }
-
- /**
- * Reads the contents of a resource
- *
- * @param relativePath the path relative to the template directory
- * @return the binary data read from the file
- */
- @Nullable
- public byte[] readTemplateResource(@NonNull String relativePath) {
- try {
- return Files.toByteArray(new File(mRootPath, relativePath));
- } catch (IOException e) {
- AdtPlugin.log(e, null);
- return null;
- }
- }
-
- /**
- * Most recent thrown exception during template instantiation. This should
- * basically always be null. Used by unit tests to see if any template
- * instantiation recorded a failure.
- */
- @VisibleForTesting
- public static Exception sMostRecentException;
-
- /** Read the given FreeMarker file and process the variable definitions */
- private void processVariables(final Configuration freemarker,
- String file, final Map<String, Object> paramMap) {
- try {
- String xml;
- if (file.endsWith(DOT_XML)) {
- // Just read the file
- xml = readTemplateTextResource(file);
- if (xml == null) {
- return;
- }
- } else {
- mLoader.setTemplateFile(new File(mRootPath, file));
- Template inputsTemplate = freemarker.getTemplate(file);
- StringWriter out = new StringWriter();
- inputsTemplate.process(paramMap, out);
- out.flush();
- xml = out.toString();
- }
-
- SAXParserFactory factory = SAXParserFactory.newInstance();
- SAXParser saxParser = factory.newSAXParser();
- saxParser.parse(new ByteArrayInputStream(xml.getBytes()), new DefaultHandler() {
- @Override
- public void startElement(String uri, String localName, String name,
- Attributes attributes)
- throws SAXException {
- if (TAG_PARAMETER.equals(name)) {
- String id = attributes.getValue(ATTR_ID);
- if (!paramMap.containsKey(id)) {
- String value = attributes.getValue(ATTR_DEFAULT);
- Object mapValue = value;
- if (value != null && !value.isEmpty()) {
- String type = attributes.getValue(ATTR_TYPE);
- if ("boolean".equals(type)) { //$NON-NLS-1$
- mapValue = Boolean.valueOf(value);
- }
- }
- paramMap.put(id, mapValue);
- }
- } else if (TAG_GLOBAL.equals(name)) {
- String id = attributes.getValue(ATTR_ID);
- if (!paramMap.containsKey(id)) {
- paramMap.put(id, TypedVariable.parseGlobal(attributes));
- }
- } else if (TAG_GLOBALS.equals(name)) {
- // Handle evaluation of variables
- String path = attributes.getValue(ATTR_FILE);
- if (path != null) {
- processVariables(freemarker, path, paramMap);
- } // else: <globals> root element
- } else if (TAG_EXECUTE.equals(name)) {
- String path = attributes.getValue(ATTR_FILE);
- if (path != null) {
- execute(freemarker, path, paramMap);
- }
- } else if (TAG_DEPENDENCY.equals(name)) {
- String dependencyName = attributes.getValue(ATTR_NAME);
- if (dependencyName.equals(SUPPORT_LIBRARY_NAME)) {
- // We assume the revision requirement has been satisfied
- // by the wizard
- File path = AddSupportJarAction.getSupportJarFile();
- if (path != null) {
- IPath to = getTargetPath(FD_NATIVE_LIBS +'/' + path.getName());
- try {
- copy(path, to);
- } catch (IOException ioe) {
- AdtPlugin.log(ioe, null);
- }
- }
- }
- } else if (!name.equals("template") && !name.equals(TAG_CATEGORY) &&
- !name.equals(TAG_FORMFACTOR) && !name.equals("option") &&
- !name.equals(TAG_THUMBS) && !name.equals(TAG_THUMB) &&
- !name.equals(TAG_ICONS)) {
- System.err.println("WARNING: Unknown template directive " + name);
- }
- }
- });
- } catch (Exception e) {
- sMostRecentException = e;
- AdtPlugin.log(e, null);
- }
- }
-
- @SuppressWarnings("unused")
- private boolean canOverwrite(File file) {
- if (file.exists()) {
- // Warn that the file already exists and ask the user what to do
- if (!mYesToAll) {
- MessageDialog dialog = new MessageDialog(null, "File Already Exists", null,
- String.format(
- "%1$s already exists.\nWould you like to replace it?",
- file.getPath()),
- MessageDialog.QUESTION, new String[] {
- // Yes will be moved to the end because it's the default
- "Yes", "No", "Cancel", "Yes to All"
- }, 0);
- int result = dialog.open();
- switch (result) {
- case 0:
- // Yes
- break;
- case 3:
- // Yes to all
- mYesToAll = true;
- break;
- case 1:
- // No
- return false;
- case SWT.DEFAULT:
- case 2:
- // Cancel
- mNoToAll = true;
- return false;
- }
- }
-
- if (mBackupMergedFiles) {
- return makeBackup(file);
- } else {
- return file.delete();
- }
- }
-
- return true;
- }
-
- /** Executes the given recipe file: copying, merging, instantiating, opening files etc */
- private void execute(
- final Configuration freemarker,
- String file,
- final Map<String, Object> paramMap) {
- try {
- mLoader.setTemplateFile(new File(mRootPath, file));
- Template freemarkerTemplate = freemarker.getTemplate(file);
-
- StringWriter out = new StringWriter();
- freemarkerTemplate.process(paramMap, out);
- out.flush();
- String xml = out.toString();
-
- // Parse and execute the resulting instruction list.
- SAXParserFactory factory = SAXParserFactory.newInstance();
- SAXParser saxParser = factory.newSAXParser();
-
- saxParser.parse(new ByteArrayInputStream(xml.getBytes()),
- new DefaultHandler() {
- @Override
- public void startElement(String uri, String localName, String name,
- Attributes attributes)
- throws SAXException {
- if (mNoToAll) {
- return;
- }
-
- try {
- boolean instantiate = TAG_INSTANTIATE.equals(name);
- if (TAG_COPY.equals(name) || instantiate) {
- String fromPath = attributes.getValue(ATTR_FROM);
- String toPath = attributes.getValue(ATTR_TO);
- if (toPath == null || toPath.isEmpty()) {
- toPath = attributes.getValue(ATTR_FROM);
- toPath = AdtUtils.stripSuffix(toPath, DOT_FTL);
- }
- IPath to = getTargetPath(toPath);
- if (instantiate) {
- instantiate(freemarker, paramMap, fromPath, to);
- } else {
- copyTemplateResource(fromPath, to);
- }
- } else if (TAG_MERGE.equals(name)) {
- String fromPath = attributes.getValue(ATTR_FROM);
- String toPath = attributes.getValue(ATTR_TO);
- if (toPath == null || toPath.isEmpty()) {
- toPath = attributes.getValue(ATTR_FROM);
- toPath = AdtUtils.stripSuffix(toPath, DOT_FTL);
- }
- // Resources in template.xml are located within root/
- IPath to = getTargetPath(toPath);
- merge(freemarker, paramMap, fromPath, to);
- } else if (name.equals(TAG_OPEN)) {
- // The relative path here is within the output directory:
- String relativePath = attributes.getValue(ATTR_FILE);
- if (relativePath != null && !relativePath.isEmpty()) {
- mOpen.add(relativePath);
- }
- } else if (TAG_DEPENDENCY.equals(name)) {
- String dependencyUrl = attributes.getValue(ATTR_MAVEN_URL);
- File path;
- if (dependencyUrl.contains(MAVEN_SUPPORT_V4)) {
- // We assume the revision requirement has been satisfied
- // by the wizard
- path = AddSupportJarAction.getSupportJarFile();
- } else if (dependencyUrl.contains(MAVEN_SUPPORT_V13)) {
- path = AddSupportJarAction.getSupport13JarFile();
- } else if (dependencyUrl.contains(MAVEN_APPCOMPAT)) {
- path = null;
- mFinalizingActions.add(new Runnable() {
- @Override
- public void run() {
- AddSupportJarAction.installAppCompatLibrary(mProject, true);
- }
- });
- } else {
- path = null;
- System.err.println("WARNING: Unknown dependency type");
- }
-
- if (path != null) {
- IPath to = getTargetPath(FD_NATIVE_LIBS +'/' + path.getName());
- try {
- copy(path, to);
- } catch (IOException ioe) {
- AdtPlugin.log(ioe, null);
- }
- }
- } else if (!name.equals("recipe") && !name.equals(TAG_DEPENDENCY)) { //$NON-NLS-1$
- System.err.println("WARNING: Unknown template directive " + name);
- }
- } catch (Exception e) {
- sMostRecentException = e;
- AdtPlugin.log(e, null);
- }
- }
- });
-
- } catch (Exception e) {
- sMostRecentException = e;
- AdtPlugin.log(e, null);
- }
- }
-
- @NonNull
- private File getFullPath(@NonNull String fromPath) {
- if (fromPath.startsWith(VALUE_TEMPLATE_DIR)) {
- return new File(getTemplateRootFolder(), RESOURCE_ROOT + File.separator
- + fromPath.substring(VALUE_TEMPLATE_DIR.length() + 1).replace('/',
- File.separatorChar));
- }
- return new File(mRootPath, DATA_ROOT + File.separator + fromPath);
- }
-
- @NonNull
- private IPath getTargetPath(@NonNull String relative) {
- if (relative.indexOf('\\') != -1) {
- relative = relative.replace('\\', '/');
- }
- return new Path(relative);
- }
-
- @NonNull
- private IFile getTargetFile(@NonNull IPath path) {
- return mProject.getFile(path);
- }
-
- private void merge(
- @NonNull final Configuration freemarker,
- @NonNull final Map<String, Object> paramMap,
- @NonNull String relativeFrom,
- @NonNull IPath toPath) throws IOException, TemplateException {
-
- String currentXml = null;
-
- IFile to = getTargetFile(toPath);
- if (to.exists()) {
- currentXml = AdtPlugin.readFile(to);
- }
-
- if (currentXml == null) {
- // The target file doesn't exist: don't merge, just copy
- boolean instantiate = relativeFrom.endsWith(DOT_FTL);
- if (instantiate) {
- instantiate(freemarker, paramMap, relativeFrom, toPath);
- } else {
- copyTemplateResource(relativeFrom, toPath);
- }
- return;
- }
-
- if (!to.getFileExtension().equals(EXT_XML)) {
- throw new RuntimeException("Only XML files can be merged at this point: " + to);
- }
-
- String xml = null;
- File from = getFullPath(relativeFrom);
- if (relativeFrom.endsWith(DOT_FTL)) {
- // Perform template substitution of the template prior to merging
- mLoader.setTemplateFile(from);
- Template template = freemarker.getTemplate(from.getName());
- Writer out = new StringWriter();
- template.process(paramMap, out);
- out.flush();
- xml = out.toString();
- } else {
- xml = readTemplateTextResource(from);
- if (xml == null) {
- return;
- }
- }
-
- Document currentDocument = DomUtilities.parseStructuredDocument(currentXml);
- assert currentDocument != null : currentXml;
- Document fragment = DomUtilities.parseStructuredDocument(xml);
- assert fragment != null : xml;
-
- XmlFormatStyle formatStyle = XmlFormatStyle.MANIFEST;
- boolean modified;
- boolean ok;
- String fileName = to.getName();
- if (fileName.equals(SdkConstants.FN_ANDROID_MANIFEST_XML)) {
- modified = ok = mergeManifest(currentDocument, fragment);
- } else {
- // Merge plain XML files
- String parentFolderName = to.getParent().getName();
- ResourceFolderType folderType = ResourceFolderType.getFolderType(parentFolderName);
- if (folderType != null) {
- formatStyle = EclipseXmlPrettyPrinter.getForFile(toPath);
- } else {
- formatStyle = XmlFormatStyle.FILE;
- }
-
- modified = mergeResourceFile(currentDocument, fragment, folderType, paramMap);
- ok = true;
- }
-
- // Finally write out the merged file (formatting etc)
- String contents = null;
- if (ok) {
- if (modified) {
- contents = EclipseXmlPrettyPrinter.prettyPrint(currentDocument,
- EclipseXmlFormatPreferences.create(), formatStyle, null,
- currentXml.endsWith("\n")); //$NON-NLS-1$
- }
- } else {
- // Just insert into file along with comment, using the "standard" conflict
- // syntax that many tools and editors recognize.
- String sep = SdkUtils.getLineSeparator();
- contents =
- "<<<<<<< Original" + sep
- + currentXml + sep
- + "=======" + sep
- + xml
- + ">>>>>>> Added" + sep;
- }
-
- if (contents != null) {
- TextFileChange change = new TextFileChange("Merge " + fileName, to);
- MultiTextEdit rootEdit = new MultiTextEdit();
- rootEdit.addChild(new ReplaceEdit(0, currentXml.length(), contents));
- change.setEdit(rootEdit);
- change.setTextType(SdkConstants.EXT_XML);
- mMergeChanges.add(change);
- }
- }
-
- /** Merges the given resource file contents into the given resource file
- * @param paramMap */
- private static boolean mergeResourceFile(Document currentDocument, Document fragment,
- ResourceFolderType folderType, Map<String, Object> paramMap) {
- boolean modified = false;
-
- // Copy namespace declarations
- NamedNodeMap attributes = fragment.getDocumentElement().getAttributes();
- if (attributes != null) {
- for (int i = 0, n = attributes.getLength(); i < n; i++) {
- Attr attribute = (Attr) attributes.item(i);
- if (attribute.getName().startsWith(XMLNS_PREFIX)) {
- currentDocument.getDocumentElement().setAttribute(attribute.getName(),
- attribute.getValue());
- }
- }
- }
-
- // For layouts for example, I want to *append* inside the root all the
- // contents of the new file.
- // But for resources for example, I want to combine elements which specify
- // the same name or id attribute.
- // For elements like manifest files we need to insert stuff at the right
- // location in a nested way (activities in the application element etc)
- // but that doesn't happen for the other file types.
- Element root = fragment.getDocumentElement();
- NodeList children = root.getChildNodes();
- List<Node> nodes = new ArrayList<Node>(children.getLength());
- for (int i = children.getLength() - 1; i >= 0; i--) {
- Node child = children.item(i);
- nodes.add(child);
- root.removeChild(child);
- }
- Collections.reverse(nodes);
-
- root = currentDocument.getDocumentElement();
-
- if (folderType == ResourceFolderType.VALUES) {
- // Try to merge items of the same name
- Map<String, Node> old = new HashMap<String, Node>();
- NodeList newSiblings = root.getChildNodes();
- for (int i = newSiblings.getLength() - 1; i >= 0; i--) {
- Node child = newSiblings.item(i);
- if (child.getNodeType() == Node.ELEMENT_NODE) {
- Element element = (Element) child;
- String name = getResourceId(element);
- if (name != null) {
- old.put(name, element);
- }
- }
- }
-
- for (Node node : nodes) {
- if (node.getNodeType() == Node.ELEMENT_NODE) {
- Element element = (Element) node;
- String name = getResourceId(element);
- Node replace = name != null ? old.get(name) : null;
- if (replace != null) {
- // There is an existing item with the same id: just replace it
- // ACTUALLY -- let's NOT change it.
- // Let's say you've used the activity wizard once, and it
- // emits some configuration parameter as a resource that
- // it depends on, say "padding". Then the user goes and
- // tweaks the padding to some other number.
- // Now running the wizard a *second* time for some new activity,
- // we should NOT go and set the value back to the template's
- // default!
- //root.replaceChild(node, replace);
-
- // ... ON THE OTHER HAND... What if it's a parameter class
- // (where the template rewrites a common attribute). Here it's
- // really confusing if the new parameter is not set. This is
- // really an error in the template, since we shouldn't have conflicts
- // like that, but we need to do something to help track this down.
- AdtPlugin.log(null,
- "Warning: Ignoring name conflict in resource file for name %1$s",
- name);
- } else {
- root.appendChild(node);
- modified = true;
- }
- }
- }
- } else {
- // In other file types, such as layouts, just append all the new content
- // at the end.
- for (Node node : nodes) {
- root.appendChild(node);
- modified = true;
- }
- }
- return modified;
- }
-
- /** Merges the given manifest fragment into the given manifest file */
- private static boolean mergeManifest(Document currentManifest, Document fragment) {
- // TODO change MergerLog.wrapSdkLog by a custom IMergerLog that will create
- // and maintain error markers.
-
- // Transfer package element from manifest to merged in root; required by
- // manifest merger
- Element fragmentRoot = fragment.getDocumentElement();
- Element manifestRoot = currentManifest.getDocumentElement();
- if (fragmentRoot == null || manifestRoot == null) {
- return false;
- }
- String pkg = fragmentRoot.getAttribute(ATTR_PACKAGE);
- if (pkg == null || pkg.isEmpty()) {
- pkg = manifestRoot.getAttribute(ATTR_PACKAGE);
- if (pkg != null && !pkg.isEmpty()) {
- fragmentRoot.setAttribute(ATTR_PACKAGE, pkg);
- }
- }
-
- ManifestMerger merger = new ManifestMerger(
- MergerLog.wrapSdkLog(AdtPlugin.getDefault()),
- new AdtManifestMergeCallback()).setExtractPackagePrefix(true);
- return currentManifest != null &&
- fragment != null &&
- merger.process(currentManifest, fragment);
- }
-
- /**
- * Makes a backup of the given file, if it exists, by renaming it to name~
- * (and removing an old name~ file if it exists)
- */
- private static boolean makeBackup(File file) {
- if (!file.exists()) {
- return true;
- }
- if (file.isDirectory()) {
- return false;
- }
-
- File backupFile = new File(file.getParentFile(), file.getName() + '~');
- if (backupFile.exists()) {
- backupFile.delete();
- }
- return file.renameTo(backupFile);
- }
-
- private static String getResourceId(Element element) {
- String name = element.getAttribute(ATTR_NAME);
- if (name == null) {
- name = element.getAttribute(ATTR_ID);
- }
-
- return name;
- }
-
- /** Instantiates the given template file into the given output file */
- private void instantiate(
- @NonNull final Configuration freemarker,
- @NonNull final Map<String, Object> paramMap,
- @NonNull String relativeFrom,
- @NonNull IPath to) throws IOException, TemplateException {
- // For now, treat extension-less files as directories... this isn't quite right
- // so I should refine this! Maybe with a unique attribute in the template file?
- boolean isDirectory = relativeFrom.indexOf('.') == -1;
- if (isDirectory) {
- // It's a directory
- copyTemplateResource(relativeFrom, to);
- } else {
- File from = getFullPath(relativeFrom);
- mLoader.setTemplateFile(from);
- Template template = freemarker.getTemplate(from.getName());
- Writer out = new StringWriter(1024);
- template.process(paramMap, out);
- out.flush();
- String contents = out.toString();
-
- contents = format(mProject, contents, to);
- IFile targetFile = getTargetFile(to);
- TextFileChange change = createNewFileChange(targetFile);
- MultiTextEdit rootEdit = new MultiTextEdit();
- rootEdit.addChild(new InsertEdit(0, contents));
- change.setEdit(rootEdit);
- mTextChanges.add(change);
- }
- }
-
- private static String format(IProject project, String contents, IPath to) {
- String name = to.lastSegment();
- if (name.endsWith(DOT_XML)) {
- XmlFormatStyle formatStyle = EclipseXmlPrettyPrinter.getForFile(to);
- EclipseXmlFormatPreferences prefs = EclipseXmlFormatPreferences.create();
- return EclipseXmlPrettyPrinter.prettyPrint(contents, prefs, formatStyle, null);
- } else if (name.endsWith(DOT_JAVA)) {
- Map<?, ?> options = null;
- if (project != null && project.isAccessible()) {
- try {
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
- if (javaProject != null) {
- options = javaProject.getOptions(true);
- }
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- }
- if (options == null) {
- options = JavaCore.getOptions();
- }
-
- CodeFormatter formatter = ToolFactory.createCodeFormatter(options);
-
- try {
- IDocument doc = new org.eclipse.jface.text.Document();
- // format the file (the meat and potatoes)
- doc.set(contents);
- TextEdit edit = formatter.format(
- CodeFormatter.K_COMPILATION_UNIT | CodeFormatter.F_INCLUDE_COMMENTS,
- contents, 0, contents.length(), 0, null);
- if (edit != null) {
- edit.apply(doc);
- }
-
- return doc.get();
- } catch (Exception e) {
- AdtPlugin.log(e, null);
- }
- }
-
- return contents;
- }
-
- private static TextFileChange createNewFileChange(IFile targetFile) {
- String fileName = targetFile.getName();
- String message;
- if (targetFile.exists()) {
- message = String.format("Replace %1$s", fileName);
- } else {
- message = String.format("Create %1$s", fileName);
- }
-
- TextFileChange change = new TextFileChange(message, targetFile) {
- @Override
- protected IDocument acquireDocument(IProgressMonitor pm) throws CoreException {
- IDocument document = super.acquireDocument(pm);
-
- // In our case, we know we *always* use this TextFileChange
- // to *create* files, we're not appending to existing files.
- // However, due to the following bug we can end up with cached
- // contents of previously deleted files that happened to have the
- // same file name:
- // https://bugs.eclipse.org/bugs/show_bug.cgi?id=390402
- // Therefore, as a workaround, wipe out the cached contents here
- if (document.getLength() > 0) {
- try {
- document.replace(0, document.getLength(), "");
- } catch (BadLocationException e) {
- // pass
- }
- }
-
- return document;
- }
- };
- change.setTextType(fileName.substring(fileName.lastIndexOf('.') + 1));
- return change;
- }
-
- /**
- * Returns the list of files to open when the template has been created
- *
- * @return the list of files to open
- */
- @NonNull
- public List<String> getFilesToOpen() {
- return mOpen;
- }
-
- /**
- * Returns the list of actions to perform when the template has been created
- *
- * @return the list of actions to perform
- */
- @NonNull
- public List<Runnable> getFinalizingActions() {
- return mFinalizingActions;
- }
-
- /** Copy a template resource */
- private final void copyTemplateResource(
- @NonNull String relativeFrom,
- @NonNull IPath output) throws IOException {
- File from = getFullPath(relativeFrom);
- copy(from, output);
- }
-
- /** Returns true if the given file contains the given bytes */
- private static boolean isIdentical(@Nullable byte[] data, @NonNull IFile dest) {
- assert dest.exists();
- byte[] existing = AdtUtils.readData(dest);
- return Arrays.equals(existing, data);
- }
-
- /**
- * Copies the given source file into the given destination file (where the
- * source is allowed to be a directory, in which case the whole directory is
- * copied recursively)
- */
- private void copy(File src, IPath path) throws IOException {
- if (src.isDirectory()) {
- File[] children = src.listFiles();
- if (children != null) {
- for (File child : children) {
- copy(child, path.append(child.getName()));
- }
- }
- } else {
- IResource dest = mProject.getFile(path);
- if (dest.exists() && !(dest instanceof IFile)) {// Don't attempt to overwrite a folder
- assert false : dest.getClass().getName();
- return;
- }
- IFile file = (IFile) dest;
- String targetName = path.lastSegment();
- if (dest instanceof IFile) {
- if (dest.exists() && isIdentical(Files.toByteArray(src), file)) {
- String label = String.format(
- "Not overwriting %1$s because the files are identical", targetName);
- NullChange change = new NullChange(label);
- change.setEnabled(false);
- mOtherChanges.add(change);
- return;
- }
- }
-
- if (targetName.endsWith(DOT_XML)
- || targetName.endsWith(DOT_JAVA)
- || targetName.endsWith(DOT_TXT)
- || targetName.endsWith(DOT_RS)
- || targetName.endsWith(DOT_AIDL)
- || targetName.endsWith(DOT_SVG)) {
-
- String newFile = Files.toString(src, Charsets.UTF_8);
- newFile = format(mProject, newFile, path);
-
- TextFileChange addFile = createNewFileChange(file);
- addFile.setEdit(new InsertEdit(0, newFile));
- mTextChanges.add(addFile);
- } else {
- // Write binary file: Need custom change for that
- IPath workspacePath = mProject.getFullPath().append(path);
- mOtherChanges.add(new CreateFileChange(targetName, workspacePath, src));
- }
- }
- }
-
- /**
- * A custom {@link TemplateLoader} which locates and provides templates
- * within the plugin .jar file
- */
- private static final class MyTemplateLoader implements TemplateLoader {
- private String mPrefix;
-
- public void setPrefix(String prefix) {
- mPrefix = prefix;
- }
-
- public void setTemplateFile(File file) {
- setTemplateParent(file.getParentFile());
- }
-
- public void setTemplateParent(File parent) {
- mPrefix = parent.getPath();
- }
-
- @Override
- public Reader getReader(Object templateSource, String encoding) throws IOException {
- URL url = (URL) templateSource;
- return new InputStreamReader(url.openStream(), encoding);
- }
-
- @Override
- public long getLastModified(Object templateSource) {
- return 0;
- }
-
- @Override
- public Object findTemplateSource(String name) throws IOException {
- String path = mPrefix != null ? mPrefix + '/' + name : name;
- File file = new File(path);
- if (file.exists()) {
- return file.toURI().toURL();
- }
- return null;
- }
-
- @Override
- public void closeTemplateSource(Object templateSource) throws IOException {
- }
- }
-
- /**
- * Validates this template to make sure it's supported
- * @param currentMinSdk the minimum SDK in the project, or -1 or 0 if unknown (e.g. codename)
- * @param buildApi the build API, or -1 or 0 if unknown (e.g. codename)
- *
- * @return a status object with the error, or null if there is no problem
- */
- @SuppressWarnings("cast") // In Eclipse 3.6.2 cast below is needed
- @Nullable
- public IStatus validateTemplate(int currentMinSdk, int buildApi) {
- TemplateMetadata template = getTemplate();
- if (template == null) {
- return null;
- }
- if (!template.isSupported()) {
- String versionString = (String) AdtPlugin.getDefault().getBundle().getHeaders().get(
- Constants.BUNDLE_VERSION);
- Version version = new Version(versionString);
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- String.format("This template requires a more recent version of the " +
- "Android Eclipse plugin. Please update from version %1$d.%2$d.%3$d.",
- version.getMajor(), version.getMinor(), version.getMicro()));
- }
- int templateMinSdk = template.getMinSdk();
- if (templateMinSdk > currentMinSdk && currentMinSdk >= 1) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- String.format("This template requires a minimum SDK version of at " +
- "least %1$d, and the current min version is %2$d",
- templateMinSdk, currentMinSdk));
- }
- int templateMinBuildApi = template.getMinBuildApi();
- if (templateMinBuildApi > buildApi && buildApi >= 1) {
- return new Status(IStatus.ERROR, AdtPlugin.PLUGIN_ID,
- String.format("This template requires a build target API version of at " +
- "least %1$d, and the current version is %2$d",
- templateMinBuildApi, buildApi));
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateManager.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateManager.java
deleted file mode 100644
index 30dd09e31..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateManager.java
+++ /dev/null
@@ -1,261 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import static com.android.SdkConstants.FD_EXTRAS;
-import static com.android.SdkConstants.FD_TEMPLATES;
-import static com.android.SdkConstants.FD_TOOLS;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.TEMPLATE_XML;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.google.common.base.Charsets;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-import com.google.common.io.Files;
-
-import org.w3c.dom.Document;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/** Handles locating templates and providing template metadata */
-public class TemplateManager {
- private static final Set<String> EXCLUDED_CATEGORIES = Sets.newHashSet("Folder", "Google");
- private static final Set<String> EXCLUDED_FORMFACTORS = Sets.newHashSet("Wear", "TV");
-
- TemplateManager() {
- }
-
- /** @return the root folder containing templates */
- @Nullable
- public static File getTemplateRootFolder() {
- String location = AdtPrefs.getPrefs().getOsSdkFolder();
- if (location != null) {
- File folder = new File(location, FD_TOOLS + File.separator + FD_TEMPLATES);
- if (folder.isDirectory()) {
- return folder;
- }
- }
-
- return null;
- }
-
- /** @return the root folder containing extra templates */
- @NonNull
- public static List<File> getExtraTemplateRootFolders() {
- List<File> folders = new ArrayList<File>();
- String location = AdtPrefs.getPrefs().getOsSdkFolder();
- if (location != null) {
- File extras = new File(location, FD_EXTRAS);
- if (extras.isDirectory()) {
- for (File vendor : AdtUtils.listFiles(extras)) {
- if (!vendor.isDirectory()) {
- continue;
- }
- for (File pkg : AdtUtils.listFiles(vendor)) {
- if (pkg.isDirectory()) {
- File folder = new File(pkg, FD_TEMPLATES);
- if (folder.isDirectory()) {
- folders.add(folder);
- }
- }
- }
- }
-
- // Legacy
- File folder = new File(extras, FD_TEMPLATES);
- if (folder.isDirectory()) {
- folders.add(folder);
- }
- }
- }
-
- return folders;
- }
-
- /**
- * Returns a template file under the given root, if it exists
- *
- * @param root the root folder
- * @param relativePath the relative path
- * @return a template file under the given root, if it exists
- */
- @Nullable
- public static File getTemplateLocation(@NonNull File root, @NonNull String relativePath) {
- File templateRoot = getTemplateRootFolder();
- if (templateRoot != null) {
- String rootPath = root.getPath();
- File templateFile = new File(templateRoot,
- rootPath.replace('/', File.separatorChar) + File.separator
- + relativePath.replace('/', File.separatorChar));
- if (templateFile.exists()) {
- return templateFile;
- }
- }
-
- return null;
- }
-
- /**
- * Returns a template file under one of the available roots, if it exists
- *
- * @param relativePath the relative path
- * @return a template file under one of the available roots, if it exists
- */
- @Nullable
- public static File getTemplateLocation(@NonNull String relativePath) {
- File templateRoot = getTemplateRootFolder();
- if (templateRoot != null) {
- File templateFile = new File(templateRoot,
- relativePath.replace('/', File.separatorChar));
- if (templateFile.exists()) {
- return templateFile;
- }
- }
-
- return null;
-
- }
-
- /**
- * Returns all the templates with the given prefix
- *
- * @param folder the folder prefix
- * @return the available templates
- */
- @NonNull
- List<File> getTemplates(@NonNull String folder) {
- List<File> templates = new ArrayList<File>();
- Map<String, File> templateNames = Maps.newHashMap();
- File root = getTemplateRootFolder();
- if (root != null) {
- File[] files = new File(root, folder).listFiles();
- if (files != null) {
- for (File file : files) {
- if (file.isDirectory()) { // Avoid .DS_Store etc
- templates.add(file);
- templateNames.put(file.getName(), file);
- }
- }
- }
- }
-
- // Add in templates from extras/ as well.
- for (File extra : getExtraTemplateRootFolders()) {
- File[] files = new File(extra, folder).listFiles();
- if (files != null) {
- for (File file : files) {
- if (file.isDirectory()) {
- File replaces = templateNames.get(file.getName());
- if (replaces != null) {
- int compare = compareTemplates(replaces, file);
- if (compare > 0) {
- int index = templates.indexOf(replaces);
- if (index != -1) {
- templates.set(index, file);
- } else {
- templates.add(file);
- }
- }
- } else {
- templates.add(file);
- }
- }
- }
- }
- }
-
- // Sort by file name (not path as is File's default)
- if (templates.size() > 1) {
- Collections.sort(templates, new Comparator<File>() {
- @Override
- public int compare(File file1, File file2) {
- return file1.getName().compareTo(file2.getName());
- }
- });
- }
-
- return templates;
- }
-
- /**
- * Compare two files, and return the one with the HIGHEST revision, and if
- * the same, most recently modified
- */
- private int compareTemplates(File file1, File file2) {
- TemplateMetadata template1 = getTemplate(file1);
- TemplateMetadata template2 = getTemplate(file2);
-
- if (template1 == null) {
- return 1;
- } else if (template2 == null) {
- return -1;
- } else {
- int delta = template2.getRevision() - template1.getRevision();
- if (delta == 0) {
- delta = (int) (file2.lastModified() - file1.lastModified());
- }
- return delta;
- }
- }
-
- /** Cache for {@link #getTemplate()} */
- private Map<File, TemplateMetadata> mTemplateMap;
-
- @Nullable
- TemplateMetadata getTemplate(File templateDir) {
- if (mTemplateMap != null) {
- TemplateMetadata metadata = mTemplateMap.get(templateDir);
- if (metadata != null) {
- return metadata;
- }
- } else {
- mTemplateMap = Maps.newHashMap();
- }
-
- try {
- File templateFile = new File(templateDir, TEMPLATE_XML);
- if (templateFile.isFile()) {
- String xml = Files.toString(templateFile, Charsets.UTF_8);
- Document doc = DomUtilities.parseDocument(xml, true);
- if (doc != null && doc.getDocumentElement() != null) {
- TemplateMetadata metadata = new TemplateMetadata(doc);
- if (EXCLUDED_CATEGORIES.contains(metadata.getCategory()) ||
- EXCLUDED_FORMFACTORS.contains(metadata.getFormFactor())) {
- return null;
- }
- mTemplateMap.put(templateDir, metadata);
- return metadata;
- }
- }
- } catch (IOException e) {
- AdtPlugin.log(e, null);
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateMetadata.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateMetadata.java
deleted file mode 100644
index 4ce7d74c2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateMetadata.java
+++ /dev/null
@@ -1,468 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.ATTR_MIN_API;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.ATTR_MIN_BUILD_API;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.ATTR_REVISION;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.ATTR_BACKGROUND;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.ATTR_CLIPART_NAME;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.ATTR_DESCRIPTION;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.ATTR_FOREGROUND;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.ATTR_FORMAT;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.ATTR_NAME;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.ATTR_PADDING;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.ATTR_SHAPE;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.ATTR_SOURCE_TYPE;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.ATTR_TEXT;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.ATTR_TRIM;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.ATTR_TYPE;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.ATTR_VALUE;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.CURRENT_FORMAT;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.TAG_DEPENDENCY;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.TAG_ICONS;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.TAG_PARAMETER;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.TAG_THUMB;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.TAG_FORMFACTOR;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.TAG_CATEGORY;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.assetstudiolib.GraphicGenerator;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.assetstudio.AssetType;
-import com.android.ide.eclipse.adt.internal.assetstudio.CreateAssetSetWizardState;
-import com.android.ide.eclipse.adt.internal.assetstudio.CreateAssetSetWizardState.SourceType;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.ImageUtils;
-import com.android.utils.Pair;
-import com.google.common.collect.Lists;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.RGB;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-
-/** An ADT template along with metadata */
-class TemplateMetadata {
- private final Document mDocument;
- private final List<Parameter> mParameters;
- private final Map<String, Parameter> mParameterMap;
- private List<Pair<String, Integer>> mDependencies;
- private Integer mMinApi;
- private Integer mMinBuildApi;
- private Integer mRevision;
- private boolean mNoIcons;
- private CreateAssetSetWizardState mIconState;
- private String mFormFactor;
- private String mCategory;
-
- TemplateMetadata(@NonNull Document document) {
- mDocument = document;
-
- NodeList parameters = mDocument.getElementsByTagName(TAG_PARAMETER);
- mParameters = new ArrayList<Parameter>(parameters.getLength());
- mParameterMap = new HashMap<String, Parameter>(parameters.getLength());
- for (int index = 0, max = parameters.getLength(); index < max; index++) {
- Element element = (Element) parameters.item(index);
- Parameter parameter = new Parameter(this, element);
- mParameters.add(parameter);
- if (parameter.id != null) {
- mParameterMap.put(parameter.id, parameter);
- }
- }
- }
-
- boolean isSupported() {
- String versionString = mDocument.getDocumentElement().getAttribute(ATTR_FORMAT);
- if (versionString != null && !versionString.isEmpty()) {
- try {
- int version = Integer.parseInt(versionString);
- return version <= CURRENT_FORMAT;
- } catch (NumberFormatException nufe) {
- return false;
- }
- }
-
- // Older templates without version specified: supported
- return true;
- }
-
- @Nullable
- String getTitle() {
- String name = mDocument.getDocumentElement().getAttribute(ATTR_NAME);
- if (name != null && !name.isEmpty()) {
- return name;
- }
-
- return null;
- }
-
- @Nullable
- String getDescription() {
- String description = mDocument.getDocumentElement().getAttribute(ATTR_DESCRIPTION);
- if (description != null && !description.isEmpty()) {
- return description;
- }
-
- return null;
- }
-
- int getMinSdk() {
- if (mMinApi == null) {
- mMinApi = 1;
- String api = mDocument.getDocumentElement().getAttribute(ATTR_MIN_API);
- if (api != null && !api.isEmpty()) {
- try {
- mMinApi = Integer.parseInt(api);
- } catch (NumberFormatException nufe) {
- // Templates aren't allowed to contain codenames, should always be an integer
- AdtPlugin.log(nufe, null);
- mMinApi = 1;
- }
- }
- }
-
- return mMinApi.intValue();
- }
-
- int getMinBuildApi() {
- if (mMinBuildApi == null) {
- mMinBuildApi = 1;
- String api = mDocument.getDocumentElement().getAttribute(ATTR_MIN_BUILD_API);
- if (api != null && !api.isEmpty()) {
- try {
- mMinBuildApi = Integer.parseInt(api);
- } catch (NumberFormatException nufe) {
- // Templates aren't allowed to contain codenames, should always be an integer
- AdtPlugin.log(nufe, null);
- mMinBuildApi = 1;
- }
- }
- }
-
- return mMinBuildApi.intValue();
- }
-
- public int getRevision() {
- if (mRevision == null) {
- mRevision = 1;
- String revision = mDocument.getDocumentElement().getAttribute(ATTR_REVISION);
- if (revision != null && !revision.isEmpty()) {
- try {
- mRevision = Integer.parseInt(revision);
- } catch (NumberFormatException nufe) {
- AdtPlugin.log(nufe, null);
- mRevision = 1;
- }
- }
- }
-
- return mRevision.intValue();
- }
-
- public String getFormFactor() {
- if (mFormFactor == null) {
- mFormFactor = "Mobile";
-
- NodeList formfactorDeclarations = mDocument.getElementsByTagName(TAG_FORMFACTOR);
- if (formfactorDeclarations.getLength() > 0) {
- Element element = (Element) formfactorDeclarations.item(0);
- String formFactor = element.getAttribute(ATTR_VALUE);
- if (formFactor != null && !formFactor.isEmpty()) {
- mFormFactor = formFactor;
- }
- }
- }
- return mFormFactor;
- }
-
- public String getCategory() {
- if (mCategory == null) {
- mCategory = "";
- NodeList categories = mDocument.getElementsByTagName(TAG_CATEGORY);
- if (categories.getLength() > 0) {
- Element element = (Element) categories.item(0);
- String category = element.getAttribute(ATTR_VALUE);
- if (category != null && !category.isEmpty()) {
- mCategory = category;
- }
- }
- }
- return mCategory;
- }
-
- /**
- * Returns a suitable icon wizard state instance if this wizard requests
- * icons to be created, and null otherwise
- *
- * @return icon wizard state or null
- */
- @Nullable
- public CreateAssetSetWizardState getIconState(IProject project) {
- if (mIconState == null && !mNoIcons) {
- NodeList icons = mDocument.getElementsByTagName(TAG_ICONS);
- if (icons.getLength() < 1) {
- mNoIcons = true;
- return null;
- }
- Element icon = (Element) icons.item(0);
-
- mIconState = new CreateAssetSetWizardState();
- mIconState.project = project;
-
- String typeString = getAttributeOrNull(icon, ATTR_TYPE);
- if (typeString != null) {
- typeString = typeString.toUpperCase(Locale.US);
- boolean found = false;
- for (AssetType type : AssetType.values()) {
- if (typeString.equals(type.name())) {
- mIconState.type = type;
- found = true;
- break;
- }
- }
- if (!found) {
- AdtPlugin.log(null, "Unknown asset type %1$s", typeString);
- }
- }
-
- mIconState.outputName = getAttributeOrNull(icon, ATTR_NAME);
- if (mIconState.outputName != null) {
- // Register parameter such that if it is referencing other values, it gets
- // updated when other values are edited
- Parameter outputParameter = new Parameter(this,
- Parameter.Type.STRING, "_iconname", mIconState.outputName); //$NON-NLS-1$
- getParameters().add(outputParameter);
- }
-
- RGB background = getRgb(icon, ATTR_BACKGROUND);
- if (background != null) {
- mIconState.background = background;
- }
- RGB foreground = getRgb(icon, ATTR_FOREGROUND);
- if (foreground != null) {
- mIconState.foreground = foreground;
- }
- String shapeString = getAttributeOrNull(icon, ATTR_SHAPE);
- if (shapeString != null) {
- shapeString = shapeString.toUpperCase(Locale.US);
- boolean found = false;
- for (GraphicGenerator.Shape shape : GraphicGenerator.Shape.values()) {
- if (shapeString.equals(shape.name())) {
- mIconState.shape = shape;
- found = true;
- break;
- }
- }
- if (!found) {
- AdtPlugin.log(null, "Unknown shape %1$s", shapeString);
- }
- }
- String trimString = getAttributeOrNull(icon, ATTR_TRIM);
- if (trimString != null) {
- mIconState.trim = Boolean.valueOf(trimString);
- }
- String paddingString = getAttributeOrNull(icon, ATTR_PADDING);
- if (paddingString != null) {
- mIconState.padding = Integer.parseInt(paddingString);
- }
- String sourceTypeString = getAttributeOrNull(icon, ATTR_SOURCE_TYPE);
- if (sourceTypeString != null) {
- sourceTypeString = sourceTypeString.toUpperCase(Locale.US);
- boolean found = false;
- for (SourceType type : SourceType.values()) {
- if (sourceTypeString.equals(type.name())) {
- mIconState.sourceType = type;
- found = true;
- break;
- }
- }
- if (!found) {
- AdtPlugin.log(null, "Unknown source type %1$s", sourceTypeString);
- }
- }
- mIconState.clipartName = getAttributeOrNull(icon, ATTR_CLIPART_NAME);
-
- String textString = getAttributeOrNull(icon, ATTR_TEXT);
- if (textString != null) {
- mIconState.text = textString;
- }
- }
-
- return mIconState;
- }
-
- void updateIconName(List<Parameter> parameters, StringEvaluator evaluator) {
- if (mIconState != null) {
- NodeList icons = mDocument.getElementsByTagName(TAG_ICONS);
- if (icons.getLength() < 1) {
- return;
- }
- Element icon = (Element) icons.item(0);
- String name = getAttributeOrNull(icon, ATTR_NAME);
- if (name != null) {
- mIconState.outputName = evaluator.evaluate(name, parameters);
- }
- }
- }
-
- private static RGB getRgb(@NonNull Element element, @NonNull String name) {
- String colorString = getAttributeOrNull(element, name);
- if (colorString != null) {
- int rgb = ImageUtils.getColor(colorString.trim());
- return ImageUtils.intToRgb(rgb);
- }
-
- return null;
- }
-
- @Nullable
- private static String getAttributeOrNull(@NonNull Element element, @NonNull String name) {
- String value = element.getAttribute(name);
- if (value != null && value.isEmpty()) {
- return null;
- }
- return value;
- }
-
- @Nullable
- String getThumbnailPath() {
- // Apply selector logic. Pick the thumb first thumb that satisfies the largest number
- // of conditions.
- NodeList thumbs = mDocument.getElementsByTagName(TAG_THUMB);
- if (thumbs.getLength() == 0) {
- return null;
- }
-
-
- int bestMatchCount = 0;
- Element bestMatch = null;
-
- for (int i = 0, n = thumbs.getLength(); i < n; i++) {
- Element thumb = (Element) thumbs.item(i);
-
- NamedNodeMap attributes = thumb.getAttributes();
- if (bestMatch == null && attributes.getLength() == 0) {
- bestMatch = thumb;
- } else if (attributes.getLength() <= bestMatchCount) {
- // Already have a match with this number of attributes, no point checking
- continue;
- } else {
- boolean match = true;
- for (int j = 0, max = attributes.getLength(); j < max; j++) {
- Attr attribute = (Attr) attributes.item(j);
- Parameter parameter = mParameterMap.get(attribute.getName());
- if (parameter == null) {
- AdtPlugin.log(null, "Unexpected parameter in template thumbnail: %1$s",
- attribute.getName());
- continue;
- }
- String thumbNailValue = attribute.getValue();
- String editedValue = parameter.value != null ? parameter.value.toString() : "";
- if (!thumbNailValue.equals(editedValue)) {
- match = false;
- break;
- }
- }
- if (match) {
- bestMatch = thumb;
- bestMatchCount = attributes.getLength();
- }
- }
- }
-
- if (bestMatch != null) {
- NodeList children = bestMatch.getChildNodes();
- for (int i = 0, n = children.getLength(); i < n; i++) {
- Node child = children.item(i);
- if (child.getNodeType() == Node.TEXT_NODE) {
- return child.getNodeValue().trim();
- }
- }
- }
-
- return null;
- }
-
- /**
- * Returns the dependencies (as a list of pairs of names and revisions)
- * required by this template
- */
- List<Pair<String, Integer>> getDependencies() {
- if (mDependencies == null) {
- NodeList elements = mDocument.getElementsByTagName(TAG_DEPENDENCY);
- if (elements.getLength() == 0) {
- return Collections.emptyList();
- }
-
- List<Pair<String, Integer>> dependencies = Lists.newArrayList();
- for (int i = 0, n = elements.getLength(); i < n; i++) {
- Element element = (Element) elements.item(i);
- String name = element.getAttribute(ATTR_NAME);
- int revision = -1;
- String revisionString = element.getAttribute(ATTR_REVISION);
- if (!revisionString.isEmpty()) {
- revision = Integer.parseInt(revisionString);
- }
- dependencies.add(Pair.of(name, revision));
- }
- mDependencies = dependencies;
- }
-
- return mDependencies;
- }
-
- /** Returns the list of available parameters */
- @NonNull
- List<Parameter> getParameters() {
- return mParameters;
- }
-
- /**
- * Returns the parameter of the given id, or null if not found
- *
- * @param id the id of the target parameter
- * @return the corresponding parameter, or null if not found
- */
- @Nullable
- public Parameter getParameter(@NonNull String id) {
- for (Parameter parameter : mParameters) {
- if (id.equals(parameter.id)) {
- return parameter;
- }
- }
-
- return null;
- }
-
- /** Returns a default icon for templates */
- static Image getDefaultTemplateIcon() {
- return IconFactory.getInstance().getIcon("default_template"); //$NON-NLS-1$
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplatePreviewPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplatePreviewPage.java
deleted file mode 100644
index c3d28fcf2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplatePreviewPage.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.ltk.internal.ui.refactoring.PreviewWizardPage;
-
-import java.util.List;
-
-@SuppressWarnings("restriction") // Refactoring UI
-class TemplatePreviewPage extends PreviewWizardPage {
- private final NewTemplateWizardState mValues;
-
- TemplatePreviewPage(NewTemplateWizardState values) {
- super(true);
- mValues = values;
- setTitle("Preview");
- setDescription("Optionally review pending changes");
- }
-
- @Override
- public void setVisible(boolean visible) {
- if (visible) {
- List<Change> changes = mValues.computeChanges();
- CompositeChange root = new CompositeChange("Create template",
- changes.toArray(new Change[changes.size()]));
- setChange(root);
- }
-
- super.setVisible(visible);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateTestPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateTestPage.java
deleted file mode 100644
index e461d5597..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateTestPage.java
+++ /dev/null
@@ -1,161 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.DirectoryDialog;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-
-import java.io.File;
-
-/** For template developers: Test local template directory */
-public class TemplateTestPage extends WizardPage
- implements SelectionListener, ModifyListener {
- private Text mLocation;
- private Button mButton;
- private static String sLocation; // Persist between repeated invocations
- private Button mProjectToggle;
- private File mTemplate;
-
- TemplateTestPage() {
- super("testWizardPage"); //$NON-NLS-1$
- setTitle("Wizard Tester");
- setDescription("Test a new template");
- }
-
- @SuppressWarnings("unused") // SWT constructors have side effects and aren't unused
- @Override
- public void createControl(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
- setControl(container);
- container.setLayout(new GridLayout(3, false));
-
- Label label = new Label(container, SWT.NONE);
- label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- label.setText("Template Location:");
-
- mLocation = new Text(container, SWT.BORDER);
- GridData gd_mLocation = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
- gd_mLocation.widthHint = 400;
- mLocation.setLayoutData(gd_mLocation);
- if (sLocation != null) {
- mLocation.setText(sLocation);
- }
- mLocation.addModifyListener(this);
-
- mButton = new Button(container, SWT.FLAT);
- mButton.setText("...");
-
- mProjectToggle = new Button(container, SWT.CHECK);
- mProjectToggle.setEnabled(false);
- mProjectToggle.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
- mProjectToggle.setText("Full project template");
- new Label(container, SWT.NONE);
- mButton.addSelectionListener(this);
- }
-
- @Override
- public void setVisible(boolean visible) {
- super.setVisible(visible);
- validatePage();
- }
-
- private boolean validatePage() {
- String error = null;
-
- String path = mLocation.getText().trim();
- if (path == null || path.length() == 0) {
- error = "Select a template directory";
- mTemplate = null;
- } else {
- mTemplate = new File(path);
- if (!mTemplate.exists()) {
- error = String.format("%1$s does not exist", path);
- } else {
- // Preserve across wizard sessions
- sLocation = path;
-
- if (mTemplate.isDirectory()) {
- if (!new File(mTemplate, TemplateHandler.TEMPLATE_XML).exists()) {
- error = String.format("Not a template: missing template.xml file in %1$s ",
- path);
- }
- } else {
- if (mTemplate.getName().equals(TemplateHandler.TEMPLATE_XML)) {
- mTemplate = mTemplate.getParentFile();
- } else {
- error = String.format("Select a directory containing a template");
- }
- }
- }
- }
-
- setPageComplete(error == null);
- if (error != null) {
- setMessage(error, IMessageProvider.ERROR);
- } else {
- setErrorMessage(null);
- setMessage(null);
- }
-
- return error == null;
- }
-
- @Override
- public void modifyText(ModifyEvent e) {
- validatePage();
- }
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (e.getSource() == mButton) {
- DirectoryDialog dialog = new DirectoryDialog(mButton.getShell(), SWT.OPEN);
- String path = mLocation.getText().trim();
- if (path.length() > 0) {
- dialog.setFilterPath(path);
- }
- String file = dialog.open();
- if (file != null) {
- mLocation.setText(file);
- }
- }
-
- validatePage();
- }
-
- File getLocation() {
- return mTemplate;
- }
-
- boolean isProjectTemplate() {
- return mProjectToggle.getSelection();
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateTestWizard.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateTestWizard.java
deleted file mode 100644
index b3b1ef2f4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateTestWizard.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.ui.IWorkbench;
-
-import java.io.File;
-
-/**
- * Template wizard which creates parameterized templates
- */
-public class TemplateTestWizard extends NewTemplateWizard {
- private TemplateTestPage mSelectionPage;
- private IProject mProject;
-
- /** Creates a new wizard for testing template definitions in a local directory */
- public TemplateTestWizard() {
- super("");
- }
-
- @Override
- public void init(IWorkbench workbench, IStructuredSelection selection) {
- super.init(workbench, selection);
- if (mValues != null) {
- mProject = mValues.project;
- }
-
- mMainPage = null;
- mValues = null;
-
- mSelectionPage = new TemplateTestPage();
- }
-
- @Override
- public void addPages() {
- addPage(mSelectionPage);
- }
-
- @Override
- public IWizardPage getNextPage(IWizardPage page) {
- if (page == mSelectionPage) {
- File file = mSelectionPage.getLocation();
- if (file != null && file.exists()) {
- if (mValues == null) {
- mValues = new NewTemplateWizardState();
- mValues.setTemplateLocation(file);
- mValues.project = mProject;
- hideBuiltinParameters();
-
- mMainPage = new NewTemplatePage(mValues, true);
- addPage(mMainPage);
- } else {
- mValues.setTemplateLocation(file);
- }
-
- return mMainPage;
- }
- }
-
- return super.getNextPage(page);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateWizard.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateWizard.java
deleted file mode 100644
index 7ca32f91f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateWizard.java
+++ /dev/null
@@ -1,222 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import static org.eclipse.core.resources.IResource.DEPTH_INFINITE;
-
-import com.android.annotations.NonNull;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.assetstudio.ConfigureAssetSetPage;
-import com.android.ide.eclipse.adt.internal.assetstudio.CreateAssetSetWizardState;
-import com.android.ide.eclipse.adt.internal.editors.IconFactory;
-import com.google.common.collect.Lists;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.wizard.IWizardPage;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.INewWizard;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.actions.WorkspaceModifyOperation;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import javax.swing.SwingUtilities;
-
-abstract class TemplateWizard extends Wizard implements INewWizard {
- private static final String PROJECT_LOGO_LARGE = "android-64"; //$NON-NLS-1$
- protected IWorkbench mWorkbench;
- private UpdateToolsPage mUpdatePage;
- private InstallDependencyPage mDependencyPage;
- private TemplatePreviewPage mPreviewPage;
- protected ConfigureAssetSetPage mIconPage;
-
- protected TemplateWizard() {
- }
-
- /** Should this wizard add an icon page? */
- protected boolean shouldAddIconPage() {
- return false;
- }
-
- @Override
- public void init(IWorkbench workbench, IStructuredSelection selection) {
- mWorkbench = workbench;
-
- setHelpAvailable(false);
- ImageDescriptor desc = IconFactory.getInstance().getImageDescriptor(PROJECT_LOGO_LARGE);
- setDefaultPageImageDescriptor(desc);
-
- if (!UpdateToolsPage.isUpToDate()) {
- mUpdatePage = new UpdateToolsPage();
- }
-
- setNeedsProgressMonitor(true);
-
- // Trigger a check to see if the SDK needs to be reloaded (which will
- // invoke onSdkLoaded asynchronously as needed).
- AdtPlugin.getDefault().refreshSdk();
- }
-
- @Override
- public void addPages() {
- super.addPages();
- if (mUpdatePage != null) {
- addPage(mUpdatePage);
- }
- }
-
- @Override
- public IWizardPage getStartingPage() {
- if (mUpdatePage != null && mUpdatePage.isPageComplete()) {
- return getNextPage(mUpdatePage);
- }
-
- return super.getStartingPage();
- }
-
- protected WizardPage getPreviewPage(NewTemplateWizardState values) {
- if (mPreviewPage == null) {
- mPreviewPage = new TemplatePreviewPage(values);
- addPage(mPreviewPage);
- }
-
- return mPreviewPage;
- }
-
- protected WizardPage getIconPage(CreateAssetSetWizardState iconState) {
- if (mIconPage == null) {
- mIconPage = new ConfigureAssetSetPage(iconState);
- mIconPage.setTitle("Configure Icon");
- addPage(mIconPage);
- }
-
- return mIconPage;
- }
-
- protected WizardPage getDependencyPage(TemplateMetadata template, boolean create) {
- if (!create) {
- return mDependencyPage;
- }
-
- if (mDependencyPage == null) {
- mDependencyPage = new InstallDependencyPage();
- addPage(mDependencyPage);
- }
- mDependencyPage.setTemplate(template);
- return mDependencyPage;
- }
-
- /**
- * Returns the project where the template is being inserted
- *
- * @return the project to insert the template into
- */
- @NonNull
- protected abstract IProject getProject();
-
- /**
- * Returns the list of files to open, which might be empty. This method will
- * only be called <b>after</b> {@link #computeChanges()} has been called.
- *
- * @return a list of files to open
- */
- @NonNull
- protected abstract List<String> getFilesToOpen();
-
- /**
- * Returns the list of files to open, which might be empty. This method will
- * only be called <b>after</b> {@link #computeChanges()} has been called.
- *
- * @return a list of files to open
- */
- @NonNull
- protected abstract List<Runnable> getFinalizingActions();
-
- /**
- * Computes the changes to the {@link #getProject()} this template should
- * perform
- *
- * @return the changes to perform
- */
- protected abstract List<Change> computeChanges();
-
- protected boolean performFinish(IProgressMonitor monitor) throws InvocationTargetException {
- List<Change> changes = computeChanges();
- if (!changes.isEmpty()) {
- monitor.beginTask("Creating template...", changes.size());
- try {
- CompositeChange composite = new CompositeChange("",
- changes.toArray(new Change[changes.size()]));
- composite.perform(monitor);
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- throw new InvocationTargetException(e);
- } finally {
- monitor.done();
- }
- }
-
- // TBD: Is this necessary now that we're using IFile objects?
- try {
- getProject().refreshLocal(DEPTH_INFINITE, new NullProgressMonitor());
- } catch (CoreException e) {
- AdtPlugin.log(e, null);
- }
- return true;
- }
-
- @Override
- public boolean performFinish() {
- final AtomicBoolean success = new AtomicBoolean();
- try {
- getContainer().run(true, false, new IRunnableWithProgress() {
- @Override
- public void run(IProgressMonitor monitor) throws InvocationTargetException,
- InterruptedException {
- boolean ok = performFinish(monitor);
- success.set(ok);
- }
- });
-
- } catch (InvocationTargetException e) {
- AdtPlugin.log(e, null);
- return false;
- } catch (InterruptedException e) {
- AdtPlugin.log(e, null);
- return false;
- }
-
- if (success.get()) {
- // Open the primary file/files
- NewTemplateWizard.openFiles(getProject(), getFilesToOpen(), mWorkbench);
- return true;
- } else {
- return false;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TypedVariable.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TypedVariable.java
deleted file mode 100644
index 468a10c77..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TypedVariable.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import java.util.Locale;
-
-import org.xml.sax.Attributes;
-
-public class TypedVariable {
- public enum Type {
- STRING,
- BOOLEAN,
- INTEGER;
-
- public static Type get(String name) {
- if (name == null) {
- return STRING;
- }
- try {
- return valueOf(name.toUpperCase(Locale.US));
- } catch (IllegalArgumentException e) {
- System.err.println("Unexpected global type '" + name + "'");
- System.err.println("Expected one of :");
- for (Type s : Type.values()) {
- System.err.println(" " + s.name().toLowerCase(Locale.US));
- }
- }
-
- return STRING;
- }
- }
-
- public static Object parseGlobal(Attributes attributes) {
- String value = attributes.getValue(TemplateHandler.ATTR_VALUE);
- Type type = Type.get(attributes.getValue(TemplateHandler.ATTR_TYPE));
-
- switch (type) {
- case STRING:
- return value;
- case BOOLEAN:
- return Boolean.parseBoolean(value);
- case INTEGER:
- try {
- return Integer.parseInt(value);
- } catch (NumberFormatException e) {
- return value;
- }
- }
-
- return value;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/UpdateToolsPage.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/UpdateToolsPage.java
deleted file mode 100644
index 5bbf449d4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/UpdateToolsPage.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-
-class UpdateToolsPage extends WizardPage implements SelectionListener {
- private Button mInstallButton;
- UpdateToolsPage() {
- super("update");
- setTitle("Update Tools");
- validatePage();
- }
-
- @Override
- public void createControl(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
- setControl(container);
- container.setLayout(new GridLayout(1, false));
-
- Label label = new Label(container, SWT.WRAP);
- GridData layoutData = new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1);
- layoutData.widthHint = NewTemplatePage.WIZARD_PAGE_WIDTH - 50;
- label.setLayoutData(layoutData);
- label.setText(
- "Your tools installation appears to be out of date (or not yet installed).\n" +
- "\n" +
- "This wizard depends on templates distributed with the Android SDK Tools.\n" +
- "\n" +
- "Please update the tools first (via Window > Android SDK Manager, or by " +
- "using the \"android\" command in a terminal window). Note that on Windows " +
- "you may need to restart the IDE, since there are some known problems where " +
- "Windows locks the files held open by the running IDE, so the updater is " +
- "unable to delete them in order to upgrade them.");
-
- mInstallButton = new Button(container, SWT.NONE);
- mInstallButton.setText("Check Again");
- mInstallButton.addSelectionListener(this);
- }
-
- @Override
- public boolean isPageComplete() {
- return isUpToDate();
- }
-
- static boolean isUpToDate() {
- return TemplateManager.getTemplateRootFolder() != null;
- }
-
- private void validatePage() {
- boolean ok = isUpToDate();
- setPageComplete(ok);
- if (ok) {
- setErrorMessage(null);
- setMessage(null);
- } else {
- setErrorMessage("The tools need to be updated via the SDK Manager");
- }
- }
-
- // ---- Implements SelectionListener ----
-
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (e.getSource() == mInstallButton) {
- validatePage();
- }
- }
-
- @Override
- public void widgetDefaultSelected(SelectionEvent e) {
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/io/IFileWrapper.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/io/IFileWrapper.java
deleted file mode 100644
index b030f0718..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/io/IFileWrapper.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.io;
-
-import com.android.io.IAbstractFile;
-import com.android.io.IAbstractFolder;
-import com.android.io.StreamException;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.NullProgressMonitor;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-/**
- * An implementation of {@link IAbstractFile} on top of an {@link IFile} object.
- */
-public class IFileWrapper implements IAbstractFile {
-
- private final IFile mFile;
-
- public IFileWrapper(IFile file) {
- mFile = file;
- }
-
- @Override
- public InputStream getContents() throws StreamException {
- try {
- return mFile.getContents();
- } catch (CoreException e) {
- StreamException.Error error = StreamException.Error.DEFAULT;
- if (mFile.isSynchronized(IResource.DEPTH_ZERO) == false) {
- error = StreamException.Error.OUTOFSYNC;
- }
- throw new StreamException(e, this, error);
- }
- }
-
- @Override
- public void setContents(InputStream source) throws StreamException {
- try {
- mFile.setContents(source, IResource.FORCE, null);
- } catch (CoreException e) {
- throw new StreamException(e, this);
- }
- }
-
- @Override
- public OutputStream getOutputStream() throws StreamException {
- return new ByteArrayOutputStream() {
- @Override
- public void close() throws IOException {
- super.close();
-
- byte[] data = toByteArray();
- try {
- setContents(new ByteArrayInputStream(data));
- } catch (StreamException e) {
- throw new IOException();
- }
- }
- };
- }
-
- @Override
- public PreferredWriteMode getPreferredWriteMode() {
- return PreferredWriteMode.INPUTSTREAM;
- }
-
- @Override
- public String getOsLocation() {
- return mFile.getLocation().toOSString();
- }
-
- @Override
- public String getName() {
- return mFile.getName();
- }
-
- @Override
- public boolean exists() {
- return mFile.exists();
- }
-
- @Override
- public boolean delete() {
- try {
- mFile.delete(true /*force*/, new NullProgressMonitor());
- return true;
- } catch (CoreException e) {
- return false;
- }
- }
-
- /**
- * Returns the {@link IFile} object that the receiver could represent. Can be <code>null</code>
- */
- public IFile getIFile() {
- return mFile;
- }
-
- @Override
- public long getModificationStamp() {
- return mFile.getModificationStamp();
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj instanceof IFileWrapper) {
- return mFile.equals(((IFileWrapper)obj).mFile);
- }
-
- if (obj instanceof IFile) {
- return mFile.equals(obj);
- }
-
- return super.equals(obj);
- }
-
- @Override
- public int hashCode() {
- return mFile.hashCode();
- }
-
- @Override
- public IAbstractFolder getParentFolder() {
- IContainer p = mFile.getParent();
- if (p != null) {
- return new IFolderWrapper(p);
- }
-
- return null;
- }
-
- @Override
- public String toString() {
- return mFile.toString();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/io/IFolderWrapper.java b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/io/IFolderWrapper.java
deleted file mode 100644
index c659711a5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/io/IFolderWrapper.java
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.io;
-
-import com.android.io.IAbstractFile;
-import com.android.io.IAbstractFolder;
-import com.android.io.IAbstractResource;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Path;
-
-import java.util.ArrayList;
-
-/**
- * An implementation of {@link IAbstractFolder} on top of either an {@link IFolder} or an
- * {@link IContainer} object.
- */
-public class IFolderWrapper implements IAbstractFolder {
-
- private final IFolder mFolder; // could be null.
- private final IContainer mContainer; // never null.
-
- public IFolderWrapper(IFolder folder) {
- mContainer = mFolder = folder;
- }
-
- public IFolderWrapper(IContainer container) {
- mFolder = container instanceof IFolder ? (IFolder)container : null;
- mContainer = container;
- }
-
- @Override
- public String getName() {
- return mContainer.getName();
- }
-
- @Override
- public boolean exists() {
- return mContainer.exists();
- }
-
- @Override
- public boolean delete() {
- try {
- mContainer.delete(true /*force*/, new NullProgressMonitor());
- return true;
- } catch (CoreException e) {
- return false;
- }
- }
-
-
- @Override
- public IAbstractResource[] listMembers() {
- try {
- IResource[] members = mContainer.members();
- final int count = members.length;
- IAbstractResource[] afiles = new IAbstractResource[count];
-
- for (int i = 0 ; i < count ; i++) {
- IResource f = members[i];
- if (f instanceof IFile) {
- afiles[i] = new IFileWrapper((IFile) f);
- } else {
- afiles[i] = new IFolderWrapper((IContainer) f);
- }
- }
-
- return afiles;
- } catch (CoreException e) {
- // return empty array below
- }
-
- return new IAbstractResource[0];
- }
-
- @Override
- public boolean hasFile(String name) {
- try {
- IResource[] files = mContainer.members();
- for (IResource file : files) {
- if (name.equals(file.getName())) {
- return true;
- }
- }
- } catch (CoreException e) {
- // we'll return false below.
- }
-
- return false;
- }
-
- @Override
- public IAbstractFile getFile(String name) {
- if (mFolder != null) {
- IFile file = mFolder.getFile(name);
- return new IFileWrapper(file);
- }
-
- IFile file = mContainer.getFile(new Path(name));
- return new IFileWrapper(file);
- }
-
- /**
- * Returns the {@link IFolder} object that the receiver could represent.
- * Can be <code>null</code>
- */
- public IFolder getIFolder() {
- return mFolder;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (obj instanceof IFolderWrapper) {
- return mFolder.equals(((IFolderWrapper)obj).mFolder);
- }
-
- if (obj instanceof IFolder) {
- return mFolder.equals(obj);
- }
-
- return super.equals(obj);
- }
-
- @Override
- public int hashCode() {
- return mContainer.hashCode();
- }
-
- @Override
- public IAbstractFolder getFolder(String name) {
- if (mFolder != null) {
- IFolder folder = mFolder.getFolder(name);
- return new IFolderWrapper(folder);
- }
-
- IFolder folder = mContainer.getFolder(new Path(name));
- return new IFolderWrapper(folder);
- }
-
- @Override
- public String getOsLocation() {
- return mContainer.getLocation().toOSString();
- }
-
- @Override
- public String[] list(FilenameFilter filter) {
- try {
- IResource[] members = mContainer.members();
- if (members.length > 0) {
- ArrayList<String> list = new ArrayList<String>();
- for (IResource res : members) {
- if (filter.accept(this, res.getName())) {
- list.add(res.getName());
- }
- }
-
- return list.toArray(new String[list.size()]);
- }
- } catch (CoreException e) {
- // can't read the members? return empty list below.
- }
-
- return new String[0];
- }
-
- @Override
- public IAbstractFolder getParentFolder() {
- IContainer p = mContainer.getParent();
- if (p != null) {
- return new IFolderWrapper(p);
- }
-
- return null;
- }
-
- @Override
- public String toString() {
- return mFolder.toString();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/messages.properties b/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/messages.properties
deleted file mode 100644
index 3a85856d3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/messages.properties
+++ /dev/null
@@ -1,14 +0,0 @@
-Could_Not_Find_Folder=Could not find SDK folder '%1$s'.
-Could_Not_Find_Folder_In_SDK=Could not find folder '%1$s' inside SDK '%2$s'.
-Could_Not_Find=Could not find %1$s\!
-VersionCheck_Tools_Too_Old=This version of ADT requires Android SDK Tools revision %1$s or above.\n\nCurrent revision is %2$s.\n\nPlease update your SDK Tools to the latest version.
-VersionCheck_Plugin_Version_Failed=Failed to get the required ADT version number from the SDK.\n\nThe Android Developer Toolkit may not work properly.
-VersionCheck_Build_Tool_Missing=The Android SDK requires the new Build Tools component to be installed.\n\nPlease open the SDK Manager and install \"Android SDK Build-tools".
-VersionCheck_Unable_To_Parse_Version_s=Unable to parse sdk build version: %1$s
-VersionCheck_Plugin_Too_Old=This Android SDK requires Android Developer Toolkit version %1$d.%2$d.%3$d or above.\n\nCurrent version is %4$s.\n\nPlease update ADT to the latest version.
-AdtPlugin_Failed_To_Start_s=Failed to start %1$s
-AdtPlugin_Android_SDK_Content_Loader=Android SDK Content Loader
-AdtPlugin_Android_SDK_Resource_Parser=Android SDK Resource Parser
-AdtPlugin_Failed_To_Parse_s=Failed to parse:
-Console_Date_Tag=[%1$tF %1$tT]
-Console_Data_Project_Tag=[%1$tF %1$tT - %2$s]
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/templates/AndroidManifest.template b/eclipse/plugins/com.android.ide.eclipse.adt/templates/AndroidManifest.template
deleted file mode 100644
index e8975a06c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/templates/AndroidManifest.template
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="PACKAGE"
- android:versionCode="1"
- android:versionName="1.0">
-USES-SDK
-TEST-INSTRUMENTATION
- <application android:icon="@drawable/ic_launcher" android:label="APPLICATION_NAME">
-ACTIVITIES
-TEST-USES-LIBRARY
- </application>
-</manifest>
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/templates/activity.template b/eclipse/plugins/com.android.ide.eclipse.adt/templates/activity.template
deleted file mode 100644
index ee17fb82a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/templates/activity.template
+++ /dev/null
@@ -1,7 +0,0 @@
- <activity android:name="ACTIVITY_NAME"
- android:label="APPLICATION_NAME">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
-INTENT_FILTERS
- </intent-filter>
- </activity>
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/templates/ic_launcher_hdpi.png b/eclipse/plugins/com.android.ide.eclipse.adt/templates/ic_launcher_hdpi.png
deleted file mode 100644
index 96a442e5b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/templates/ic_launcher_hdpi.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/templates/ic_launcher_ldpi.png b/eclipse/plugins/com.android.ide.eclipse.adt/templates/ic_launcher_ldpi.png
deleted file mode 100644
index 99238729d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/templates/ic_launcher_ldpi.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/templates/ic_launcher_mdpi.png b/eclipse/plugins/com.android.ide.eclipse.adt/templates/ic_launcher_mdpi.png
deleted file mode 100644
index 359047dfa..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/templates/ic_launcher_mdpi.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/templates/ic_launcher_xhdpi.png b/eclipse/plugins/com.android.ide.eclipse.adt/templates/ic_launcher_xhdpi.png
deleted file mode 100644
index 71c6d760f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/templates/ic_launcher_xhdpi.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/templates/java_file.template b/eclipse/plugins/com.android.ide.eclipse.adt/templates/java_file.template
deleted file mode 100644
index e40e77ef5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/templates/java_file.template
+++ /dev/null
@@ -1,13 +0,0 @@
-package PACKAGE;
-IMPORT_RESOURCE_CLASS
-import android.app.Activity;
-import android.os.Bundle;
-
-public class ACTIVITY_NAME extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/templates/launcher_intent_filter.template b/eclipse/plugins/com.android.ide.eclipse.adt/templates/launcher_intent_filter.template
deleted file mode 100644
index f5681be1e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/templates/launcher_intent_filter.template
+++ /dev/null
@@ -1 +0,0 @@
- <category android:name="android.intent.category.LAUNCHER" /> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/templates/layout.template b/eclipse/plugins/com.android.ide.eclipse.adt/templates/layout.template
deleted file mode 100644
index 398b79a97..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/templates/layout.template
+++ /dev/null
@@ -1,15 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- tools:context=".ACTIVITY_NAME"
- >
-<TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello"
- />
-</LinearLayout>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/templates/preference_intent_filter.template b/eclipse/plugins/com.android.ide.eclipse.adt/templates/preference_intent_filter.template
deleted file mode 100644
index 609bb2cf0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/templates/preference_intent_filter.template
+++ /dev/null
@@ -1 +0,0 @@
- <category android:name="android.intent.category.PREFERENCE" /> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/templates/string.template b/eclipse/plugins/com.android.ide.eclipse.adt/templates/string.template
deleted file mode 100644
index 3a6e4b2b5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/templates/string.template
+++ /dev/null
@@ -1 +0,0 @@
- <string name="STRING_NAME">STRING_CONTENT</string> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/templates/strings.template b/eclipse/plugins/com.android.ide.eclipse.adt/templates/strings.template
deleted file mode 100644
index b980acea4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/templates/strings.template
+++ /dev/null
@@ -1,5 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
-STRINGS
-</resources>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/templates/test_instrumentation.template b/eclipse/plugins/com.android.ide.eclipse.adt/templates/test_instrumentation.template
deleted file mode 100755
index c282fbcfe..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/templates/test_instrumentation.template
+++ /dev/null
@@ -1 +0,0 @@
- <instrumentation android:targetPackage="TEST_TARGET_PCKG" android:name="android.test.InstrumentationTestRunner" />
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/templates/test_uses-library.template b/eclipse/plugins/com.android.ide.eclipse.adt/templates/test_uses-library.template
deleted file mode 100755
index 28ae7a431..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/templates/test_uses-library.template
+++ /dev/null
@@ -1 +0,0 @@
- <uses-library android:name="android.test.runner" />
diff --git a/eclipse/plugins/com.android.ide.eclipse.adt/templates/uses-sdk.template b/eclipse/plugins/com.android.ide.eclipse.adt/templates/uses-sdk.template
deleted file mode 100644
index 8adae717a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.adt/templates/uses-sdk.template
+++ /dev/null
@@ -1 +0,0 @@
- <uses-sdk android:minSdkVersion="MIN_SDK_VERSION" />
diff --git a/eclipse/plugins/com.android.ide.eclipse.base/.classpath b/eclipse/plugins/com.android.ide.eclipse.base/.classpath
deleted file mode 100644
index 0281bd964..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.base/.classpath
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry exported="true" kind="lib" path="libs/dvlib.jar" sourcepath="/dvlib"/>
- <classpathentry exported="true" kind="lib" path="libs/common.jar" sourcepath="/common"/>
- <classpathentry exported="true" kind="lib" path="libs/commons-codec-1.4.jar"/>
- <classpathentry exported="true" kind="lib" path="libs/commons-compress-1.0.jar"/>
- <classpathentry exported="true" kind="lib" path="libs/commons-logging-1.1.1.jar"/>
- <classpathentry exported="true" kind="lib" path="libs/guava-17.0.jar"/>
- <classpathentry exported="true" kind="lib" path="libs/httpclient-4.1.1.jar"/>
- <classpathentry exported="true" kind="lib" path="libs/httpcore-4.1.jar"/>
- <classpathentry exported="true" kind="lib" path="libs/kxml2-2.3.0.jar"/>
- <classpathentry exported="true" kind="lib" path="libs/layoutlib-api.jar" sourcepath="/layoutlib-api"/>
- <classpathentry exported="true" kind="lib" path="libs/sdklib.jar" sourcepath="/sdklib"/>
- <classpathentry exported="true" kind="lib" path="libs/sdkstats.jar" sourcepath="/sdkstats"/>
- <classpathentry exported="true" kind="lib" path="libs/sdk-common.jar" sourcepath="/sdk-common"/>
- <classpathentry exported="true" kind="lib" path="libs/httpmime-4.1.jar"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry kind="src" path="src"/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
diff --git a/eclipse/plugins/com.android.ide.eclipse.base/.gitignore b/eclipse/plugins/com.android.ide.eclipse.base/.gitignore
deleted file mode 100644
index 5e56e040e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.base/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-/bin
diff --git a/eclipse/plugins/com.android.ide.eclipse.base/.project b/eclipse/plugins/com.android.ide.eclipse.base/.project
deleted file mode 100644
index 34e7eda5c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.base/.project
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>plugin-base</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
diff --git a/eclipse/plugins/com.android.ide.eclipse.base/.settings/org.eclipse.jdt.core.prefs b/eclipse/plugins/com.android.ide.eclipse.base/.settings/org.eclipse.jdt.core.prefs
deleted file mode 100644
index ea661960a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.base/.settings/org.eclipse.jdt.core.prefs
+++ /dev/null
@@ -1,98 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore
-org.eclipse.jdt.core.compiler.annotation.nonnull=com.android.annotations.NonNull
-org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=com.android.annotations.NonNullByDefault
-org.eclipse.jdt.core.compiler.annotation.nonnullisdefault=disabled
-org.eclipse.jdt.core.compiler.annotation.nullable=com.android.annotations.Nullable
-org.eclipse.jdt.core.compiler.annotation.nullanalysis=enabled
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
-org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
-org.eclipse.jdt.core.compiler.compliance=1.6
-org.eclipse.jdt.core.compiler.debug.lineNumber=generate
-org.eclipse.jdt.core.compiler.debug.localVariable=generate
-org.eclipse.jdt.core.compiler.debug.sourceFile=generate
-org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
-org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
-org.eclipse.jdt.core.compiler.problem.deadCode=warning
-org.eclipse.jdt.core.compiler.problem.deprecation=warning
-org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
-org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
-org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
-org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore
-org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning
-org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled
-org.eclipse.jdt.core.compiler.problem.fieldHiding=warning
-org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
-org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
-org.eclipse.jdt.core.compiler.problem.forbiddenReference=error
-org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
-org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=enabled
-org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
-org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning
-org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
-org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning
-org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
-org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore
-org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled
-org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=warning
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=error
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
-org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
-org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
-org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
-org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
-org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
-org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=warning
-org.eclipse.jdt.core.compiler.problem.nullReference=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecInsufficientInfo=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecViolation=warning
-org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=ignore
-org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
-org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
-org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullSpecViolation=error
-org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=warning
-org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=warning
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
-org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
-org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
-org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=enabled
-org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
-org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
-org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning
-org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=disabled
-org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
-org.eclipse.jdt.core.compiler.problem.unclosedCloseable=error
-org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
-org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
-org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning
-org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
-org.eclipse.jdt.core.compiler.problem.unusedImport=warning
-org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
-org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
-org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=warning
-org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
-org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
-org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
-org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
-org.eclipse.jdt.core.compiler.source=1.6
diff --git a/eclipse/plugins/com.android.ide.eclipse.base/META-INF/MANIFEST.MF b/eclipse/plugins/com.android.ide.eclipse.base/META-INF/MANIFEST.MF
deleted file mode 100644
index f6cb3dede..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.base/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,157 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: Common Android Utilities
-Bundle-SymbolicName: com.android.ide.eclipse.base;singleton:=true
-Bundle-Version: 24.3.3.qualifier
-Require-Bundle: org.eclipse.ui,
- org.eclipse.core.runtime
-Bundle-ActivationPolicy: lazy
-Bundle-Vendor: The Android Open Source Project
-Bundle-ClassPath: .,
- libs/annotations.jar,
- libs/common.jar,
- libs/commons-codec-1.4.jar,
- libs/commons-compress-1.0.jar,
- libs/commons-logging-1.1.1.jar,
- libs/guava-17.0.jar,
- libs/httpclient-4.1.1.jar,
- libs/httpcore-4.1.jar,
- libs/httpmime-4.1.jar,
- libs/kxml2-2.3.0.jar,
- libs/layoutlib-api.jar,
- libs/sdklib.jar,
- libs/sdkstats.jar,
- libs/dvlib.jar,
- libs/sdk-common.jar
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
-Export-Package: com.android,
- com.android.annotations,
- com.android.annotations.concurrency,
- com.android.build,
- com.android.dvlib,
- com.android.ide.common.build,
- com.android.ide.common.internal,
- com.android.ide.common.packaging,
- com.android.ide.common.rendering,
- com.android.ide.common.rendering.api,
- com.android.ide.common.rendering.legacy,
- com.android.ide.common.repository,
- com.android.ide.common.res2,
- com.android.ide.common.resources,
- com.android.ide.common.resources.configuration,
- com.android.ide.common.sdk,
- com.android.ide.common.signing,
- com.android.ide.common.xml,
- com.android.ide.eclipse.base,
- com.android.ide.eclipse.base.internal.preferences,
- com.android.io,
- com.android.layoutlib.api,
- com.android.prefs,
- com.android.resources,
- com.android.sdklib,
- com.android.sdklib.build,
- com.android.sdklib.devices,
- com.android.sdklib.internal.androidTarget,
- com.android.sdklib.internal.avd,
- com.android.sdklib.internal.build,
- com.android.sdklib.internal.project,
- com.android.sdklib.internal.repository,
- com.android.sdklib.internal.repository.archives,
- com.android.sdklib.internal.repository.packages,
- com.android.sdklib.internal.repository.sources,
- com.android.sdklib.internal.repository.updater,
- com.android.sdklib.io,
- com.android.sdklib.repository,
- com.android.sdklib.repository.descriptors,
- com.android.sdklib.repository.local,
- com.android.sdklib.repository.remote,
- com.android.sdklib.util,
- com.android.sdkstats,
- com.android.util,
- com.android.utils,
- com.android.xml,
- com.google.common.annotations,
- com.google.common.base,
- com.google.common.base.internal,
- com.google.common.cache,
- com.google.common.collect,
- com.google.common.escape,
- com.google.common.eventbus,
- com.google.common.hash,
- com.google.common.html,
- com.google.common.io,
- com.google.common.math,
- com.google.common.net,
- com.google.common.primitives,
- com.google.common.reflect,
- com.google.common.util.concurrent,
- com.google.common.xml,
- com.google.thirdparty.publicsuffix,
- org.apache.commons.codec,
- org.apache.commons.codec.binary,
- org.apache.commons.codec.digest,
- org.apache.commons.codec.language,
- org.apache.commons.codec.net,
- org.apache.commons.compress.archivers,
- org.apache.commons.compress.archivers.ar,
- org.apache.commons.compress.archivers.arj,
- org.apache.commons.compress.archivers.cpio,
- org.apache.commons.compress.archivers.dump,
- org.apache.commons.compress.archivers.jar,
- org.apache.commons.compress.archivers.sevenz,
- org.apache.commons.compress.archivers.tar,
- org.apache.commons.compress.archivers.zip,
- org.apache.commons.compress.changes,
- org.apache.commons.compress.compressors,
- org.apache.commons.compress.compressors.bzip2,
- org.apache.commons.compress.compressors.gzip,
- org.apache.commons.compress.compressors.lzma,
- org.apache.commons.compress.compressors.pack200,
- org.apache.commons.compress.compressors.snappy,
- org.apache.commons.compress.compressors.xz,
- org.apache.commons.compress.compressors.z,
- org.apache.commons.compress.compressors.z._internal_,
- org.apache.commons.compress.utils,
- org.apache.commons.logging,
- org.apache.commons.logging.impl,
- org.apache.http,
- org.apache.http.annotation,
- org.apache.http.auth,
- org.apache.http.auth.params,
- org.apache.http.client,
- org.apache.http.client.entity,
- org.apache.http.client.methods,
- org.apache.http.client.params,
- org.apache.http.client.protocol,
- org.apache.http.client.utils,
- org.apache.http.conn,
- org.apache.http.conn.params,
- org.apache.http.conn.routing,
- org.apache.http.conn.scheme,
- org.apache.http.conn.ssl,
- org.apache.http.conn.util,
- org.apache.http.cookie,
- org.apache.http.cookie.params,
- org.apache.http.entity,
- org.apache.http.entity.mime,
- org.apache.http.entity.mime.content,
- org.apache.http.impl,
- org.apache.http.impl.auth,
- org.apache.http.impl.client,
- org.apache.http.impl.conn,
- org.apache.http.impl.conn.tsccm,
- org.apache.http.impl.cookie,
- org.apache.http.impl.entity,
- org.apache.http.impl.io,
- org.apache.http.io,
- org.apache.http.message,
- org.apache.http.params,
- org.apache.http.protocol,
- org.apache.http.util,
- org.kxml2.io,
- org.kxml2.kdom,
- org.kxml2.wap,
- org.kxml2.wap.syncml,
- org.kxml2.wap.wml,
- org.kxml2.wap.wv,
- org.xmlpull.v1
diff --git a/eclipse/plugins/com.android.ide.eclipse.base/build.properties b/eclipse/plugins/com.android.ide.eclipse.base/build.properties
deleted file mode 100644
index d30490239..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.base/build.properties
+++ /dev/null
@@ -1,7 +0,0 @@
-output.. = bin/
-bin.includes = .,\
- libs/,\
- META-INF/,\
- plugin.xml
-jars.compile.order = .
-source.. = src/
diff --git a/eclipse/plugins/com.android.ide.eclipse.base/plugin.xml b/eclipse/plugins/com.android.ide.eclipse.base/plugin.xml
deleted file mode 100644
index 6e298b769..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.base/plugin.xml
+++ /dev/null
@@ -1,14 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<?eclipse version="3.4"?>
-<plugin>
- <extension
- point="org.eclipse.ui.preferencePages">
- <page
- category="com.android.ide.eclipse.preferences.main"
- class="com.android.ide.eclipse.base.internal.preferences.UsagePreferencePage"
- id="com.android.ide.eclipse.common.preferences.UsagePreferencePage"
- name="Usage Stats">
- </page>
- </extension>
-
-</plugin>
diff --git a/eclipse/plugins/com.android.ide.eclipse.base/pom.xml b/eclipse/plugins/com.android.ide.eclipse.base/pom.xml
deleted file mode 100644
index b3f7ed1e9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.base/pom.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <version>24.3.3-SNAPSHOT</version>
- <artifactId>com.android.ide.eclipse.base</artifactId>
- <packaging>eclipse-plugin</packaging>
- <name>base</name>
-
- <parent>
- <relativePath>../../pom.xml</relativePath>
- <groupId>adt.group</groupId>
- <artifactId>parent</artifactId>
- <version>1.0.0-SNAPSHOT</version>
- </parent>
-</project>
diff --git a/eclipse/plugins/com.android.ide.eclipse.base/src/com/android/ide/eclipse/base/InstallDetails.java b/eclipse/plugins/com.android.ide.eclipse.base/src/com/android/ide/eclipse/base/InstallDetails.java
deleted file mode 100644
index 8c4a4a71e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.base/src/com/android/ide/eclipse/base/InstallDetails.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.base;
-
-import org.eclipse.core.runtime.Platform;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.Version;
-
-public class InstallDetails {
- private static final String ADT_PLUGIN_ID = "com.android.ide.eclipse.adt"; //$NON-NLS-1$
- private static final String ECLIPSE_PLATFORM_PLUGIN_ID = "org.eclipse.platform"; //$NON-NLS-1$
-
- /**
- * Returns true if the ADT plugin is available in the current platform. This is useful
- * for distinguishing between specific RCP applications vs. ADT + Eclipse.
- */
- public static boolean isAdtInstalled() {
- Bundle b = Platform.getBundle(ADT_PLUGIN_ID);
- return b != null;
- }
-
- /** Returns the version of current eclipse platform. */
- public static Version getPlatformVersion() {
- Bundle b = Platform.getBundle(ECLIPSE_PLATFORM_PLUGIN_ID);
- return b == null ? Version.emptyVersion : b.getVersion();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.base/src/com/android/ide/eclipse/base/internal/preferences/UsagePreferencePage.java b/eclipse/plugins/com.android.ide.eclipse.base/src/com/android/ide/eclipse/base/internal/preferences/UsagePreferencePage.java
deleted file mode 100644
index c8b70e1a3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.base/src/com/android/ide/eclipse/base/internal/preferences/UsagePreferencePage.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.base.internal.preferences;
-
-import com.android.sdkstats.DdmsPreferenceStore;
-import com.android.sdkstats.SdkStatsPermissionDialog;
-
-import org.eclipse.jface.preference.BooleanFieldEditor;
-import org.eclipse.jface.preference.PreferencePage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Link;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-
-public class UsagePreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
- private static final int WRAP_WIDTH_PX = 200;
-
- private BooleanFieldEditor mOptInCheckBox;
- private DdmsPreferenceStore mStore = new DdmsPreferenceStore();
-
- public UsagePreferencePage() {
- }
-
- @Override
- public void init(IWorkbench workbench) {
- // pass
- }
-
- @Override
- protected Control createContents(Composite parent) {
- Composite top = new Composite(parent, SWT.NONE);
- top.setLayout(new GridLayout(1, false));
- top.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- Label l = new Label(top, SWT.WRAP);
- l.setText(SdkStatsPermissionDialog.BODY_TEXT);
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.widthHint = WRAP_WIDTH_PX;
- l.setLayoutData(gd);
-
- Link privacyPolicyLink = new Link(top, SWT.WRAP);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.widthHint = WRAP_WIDTH_PX;
- privacyPolicyLink.setLayoutData(gd);
- privacyPolicyLink.setText(SdkStatsPermissionDialog.PRIVACY_POLICY_LINK_TEXT);
-
- privacyPolicyLink.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent event) {
- SdkStatsPermissionDialog.openUrl(event.text);
- }
- });
-
- mOptInCheckBox = new BooleanFieldEditor(DdmsPreferenceStore.PING_OPT_IN,
- SdkStatsPermissionDialog.CHECKBOX_TEXT, top);
- mOptInCheckBox.setPage(this);
- mOptInCheckBox.setPreferenceStore(mStore.getPreferenceStore());
- mOptInCheckBox.load();
-
- return top;
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.preference.PreferencePage#performCancel()
- */
- @Override
- public boolean performCancel() {
- mOptInCheckBox.load();
- return super.performCancel();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.preference.PreferencePage#performDefaults()
- */
- @Override
- protected void performDefaults() {
- mOptInCheckBox.loadDefault();
- super.performDefaults();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.preference.PreferencePage#performOk()
- */
- @Override
- public boolean performOk() {
- save();
- return super.performOk();
- }
-
- /* (non-Javadoc)
- * @see org.eclipse.jface.preference.PreferencePage#performApply()
- */
- @Override
- protected void performApply() {
- save();
- super.performApply();
- }
-
- private void save() {
- mStore.setPingOptIn(mOptInCheckBox.getBooleanValue());
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/.classpath b/eclipse/plugins/com.android.ide.eclipse.ddms/.classpath
deleted file mode 100644
index 97afc7968..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/.classpath
+++ /dev/null
@@ -1,13 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="src" path="src"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry kind="lib" path="libs/jfreechart-1.0.9.jar"/>
- <classpathentry kind="lib" path="libs/jcommon-1.0.12.jar"/>
- <classpathentry kind="lib" path="libs/jfreechart-swt-1.0.9.jar"/>
- <classpathentry exported="true" kind="lib" path="libs/ddmlib.jar" sourcepath="/ddmlib"/>
- <classpathentry exported="true" kind="lib" path="libs/ddmuilib.jar" sourcepath="/ddmuilib"/>
- <classpathentry exported="true" kind="lib" path="libs/uiautomatorviewer.jar" sourcepath="/uiautomatorviewer/src"/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/.gitignore b/eclipse/plugins/com.android.ide.eclipse.ddms/.gitignore
deleted file mode 100644
index 5e56e040e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-/bin
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/.project b/eclipse/plugins/com.android.ide.eclipse.ddms/.project
deleted file mode 100644
index f4150a27f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/.project
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>plugin-ddms</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/.settings/org.eclipse.jdt.core.prefs b/eclipse/plugins/com.android.ide.eclipse.ddms/.settings/org.eclipse.jdt.core.prefs
deleted file mode 100644
index ea661960a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/.settings/org.eclipse.jdt.core.prefs
+++ /dev/null
@@ -1,98 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore
-org.eclipse.jdt.core.compiler.annotation.nonnull=com.android.annotations.NonNull
-org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=com.android.annotations.NonNullByDefault
-org.eclipse.jdt.core.compiler.annotation.nonnullisdefault=disabled
-org.eclipse.jdt.core.compiler.annotation.nullable=com.android.annotations.Nullable
-org.eclipse.jdt.core.compiler.annotation.nullanalysis=enabled
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
-org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
-org.eclipse.jdt.core.compiler.compliance=1.6
-org.eclipse.jdt.core.compiler.debug.lineNumber=generate
-org.eclipse.jdt.core.compiler.debug.localVariable=generate
-org.eclipse.jdt.core.compiler.debug.sourceFile=generate
-org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
-org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
-org.eclipse.jdt.core.compiler.problem.deadCode=warning
-org.eclipse.jdt.core.compiler.problem.deprecation=warning
-org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
-org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
-org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
-org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore
-org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning
-org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled
-org.eclipse.jdt.core.compiler.problem.fieldHiding=warning
-org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
-org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
-org.eclipse.jdt.core.compiler.problem.forbiddenReference=error
-org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
-org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=enabled
-org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
-org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning
-org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
-org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning
-org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
-org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore
-org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled
-org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=warning
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=error
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
-org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
-org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
-org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
-org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
-org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
-org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=warning
-org.eclipse.jdt.core.compiler.problem.nullReference=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecInsufficientInfo=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecViolation=warning
-org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=ignore
-org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
-org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
-org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullSpecViolation=error
-org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=warning
-org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=warning
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
-org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
-org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
-org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=enabled
-org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
-org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
-org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning
-org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=disabled
-org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
-org.eclipse.jdt.core.compiler.problem.unclosedCloseable=error
-org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
-org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
-org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning
-org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
-org.eclipse.jdt.core.compiler.problem.unusedImport=warning
-org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
-org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
-org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=warning
-org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
-org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
-org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
-org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
-org.eclipse.jdt.core.compiler.source=1.6
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/META-INF/MANIFEST.MF b/eclipse/plugins/com.android.ide.eclipse.ddms/META-INF/MANIFEST.MF
deleted file mode 100644
index 92868ce77..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,43 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: %Bundle-Name
-Bundle-SymbolicName: com.android.ide.eclipse.ddms;singleton:=true
-Bundle-Version: 24.3.3.qualifier
-Bundle-Activator: com.android.ide.eclipse.ddms.DdmsPlugin
-Bundle-Vendor: %Bundle-Vendor
-Bundle-Localization: plugin
-Require-Bundle: org.eclipse.ui,
- org.eclipse.core.runtime,
- org.eclipse.ui.console,
- org.eclipse.core.resources,
- org.eclipse.ui.ide,
- org.eclipse.core.filesystem,
- com.android.ide.eclipse.base
-Bundle-ActivationPolicy: lazy
-Export-Package: com.android.ddmlib,
- com.android.ddmlib.log,
- com.android.ddmlib.testrunner,
- com.android.ddmlib.utils,
- com.android.ddmuilib,
- com.android.ddmuilib.actions,
- com.android.ddmuilib.annotation,
- com.android.ddmuilib.console,
- com.android.ddmuilib.explorer,
- com.android.ddmuilib.handler,
- com.android.ddmuilib.heap,
- com.android.ddmuilib.location,
- com.android.ddmuilib.log.event,
- com.android.ddmuilib.logcat,
- com.android.ddmuilib.net,
- com.android.ide.eclipse.ddms,
- com.android.ide.eclipse.ddms.i18n,
- com.android.ide.eclipse.ddms.preferences,
- com.android.ide.eclipse.ddms.views
-Bundle-ClassPath: .,
- libs/ddmlib.jar,
- libs/ddmuilib.jar,
- libs/jcommon-1.0.12.jar,
- libs/jfreechart-1.0.9.jar,
- libs/jfreechart-swt-1.0.9.jar,
- libs/uiautomatorviewer.jar
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/MODULE_LICENSE_APACHE2 b/eclipse/plugins/com.android.ide.eclipse.ddms/MODULE_LICENSE_APACHE2
deleted file mode 100644
index e69de29bb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/MODULE_LICENSE_APACHE2
+++ /dev/null
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/about.html b/eclipse/plugins/com.android.ide.eclipse.ddms/about.html
deleted file mode 100644
index 2858811f0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/about.html
+++ /dev/null
@@ -1,226 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
-<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
-<title>About</title>
-</head>
-<body lang="EN-US">
-<h2>About This Content</h2>
-
-<p>September 19, 2010</p>
-<h3>License</h3>
-
-<pre>
-
-Note: jcommon-1.0.12.jar is under the BSD license rather than the APL. You can find a copy of the BSD License at http://www.opensource.org/licenses/bsd-license.php
-
- jfreechart-1.0.9.jar and jfreechart-1.0.9-swt.jar are under the LGPL rather than the APL. You can find a copy of the LGPL at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt. You can get the source code for these two components at http://android.git.kernel.org/pub/jfreechart-1.0.9.zip
-
-
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- &quot;License&quot; shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- &quot;Licensor&quot; shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- &quot;Legal Entity&quot; shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- &quot;control&quot; means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- &quot;You&quot; (or &quot;Your&quot;) shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- &quot;Source&quot; form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- &quot;Object&quot; form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- &quot;Work&quot; shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- &quot;Derivative Works&quot; shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- &quot;Contribution&quot; shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, &quot;submitted&quot;
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as &quot;Not a Contribution.&quot;
-
- &quot;Contributor&quot; shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a &quot;NOTICE&quot; text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an &quot;AS IS&quot; BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets &quot;[]&quot;
- replaced with your own identifying information. (Don&apos;t include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same &quot;printed page&quot; as the copyright notice for easier
- identification within third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-
-</pre>
-
-</body>
-</html> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/about.ini b/eclipse/plugins/com.android.ide.eclipse.ddms/about.ini
deleted file mode 100644
index 339537950..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/about.ini
+++ /dev/null
@@ -1,2 +0,0 @@
-aboutText=%blurb
-featureImage=icons/ddms-32.png \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/about.properties b/eclipse/plugins/com.android.ide.eclipse.ddms/about.properties
deleted file mode 100755
index 7b7aaa213..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/about.properties
+++ /dev/null
@@ -1,7 +0,0 @@
-blurb=Dalvik Debug Monitor Service\n\
-\n\
-Version\: {featureVersion}\n\
-\n\
-(c) Copyright 2007-2011 The Android Open Source Project. All rights reserved.\n\
-Visit http://developer.android.com/sdk/eclipse-adt.html
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/build.properties b/eclipse/plugins/com.android.ide.eclipse.ddms/build.properties
deleted file mode 100644
index 3c02154cc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/build.properties
+++ /dev/null
@@ -1,13 +0,0 @@
-source.. = src/
-output.. = bin/
-bin.includes = META-INF/,\
- icons/,\
- plugin.xml,\
- .,\
- libs/,\
- schema/,\
- about.html,\
- about.ini,\
- about.properties,\
- plugin.properties
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/icons/android.png b/eclipse/plugins/com.android.ide.eclipse.ddms/icons/android.png
deleted file mode 100644
index a8dc35ec4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/icons/android.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/icons/ddms-16.png b/eclipse/plugins/com.android.ide.eclipse.ddms/icons/ddms-16.png
deleted file mode 100644
index f40e7207d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/icons/ddms-16.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/icons/ddms-32.png b/eclipse/plugins/com.android.ide.eclipse.ddms/icons/ddms-32.png
deleted file mode 100644
index d54ab7f0b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/icons/ddms-32.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/icons/device.png b/eclipse/plugins/com.android.ide.eclipse.ddms/icons/device.png
deleted file mode 100644
index 7dbbbb6a4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/icons/device.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/icons/emulator-16.png b/eclipse/plugins/com.android.ide.eclipse.ddms/icons/emulator-16.png
deleted file mode 100644
index 7554b240e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/icons/emulator-16.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/icons/heap.png b/eclipse/plugins/com.android.ide.eclipse.ddms/icons/heap.png
deleted file mode 100644
index e3aa3f06d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/icons/heap.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/icons/logcat.png b/eclipse/plugins/com.android.ide.eclipse.ddms/icons/logcat.png
deleted file mode 100644
index 0843eb734..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/icons/logcat.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/icons/networkstats.png b/eclipse/plugins/com.android.ide.eclipse.ddms/icons/networkstats.png
deleted file mode 100644
index 7018705f2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/icons/networkstats.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/icons/systrace.png b/eclipse/plugins/com.android.ide.eclipse.ddms/icons/systrace.png
deleted file mode 100644
index f6639149a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/icons/systrace.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/icons/thread.png b/eclipse/plugins/com.android.ide.eclipse.ddms/icons/thread.png
deleted file mode 100644
index ac839e89d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/icons/thread.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/icons/uiautomator.png b/eclipse/plugins/com.android.ide.eclipse.ddms/icons/uiautomator.png
deleted file mode 100644
index 423f78174..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/icons/uiautomator.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/plugin.properties b/eclipse/plugins/com.android.ide.eclipse.ddms/plugin.properties
deleted file mode 100644
index 05936797e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/plugin.properties
+++ /dev/null
@@ -1,21 +0,0 @@
-#Properties file for com.android.ide.eclipse.ddms
-Bundle-Vendor = The Android Open Source Project
-Bundle-Name = Dalvik Debug Monitor Service
-category.name = Android
-view.name.Devices = Devices
-view.name.LogCat = LogCat
-view.name.Threads = Threads
-view.name.Heap = Heap
-view.name.File_Explorer = File Explorer
-view.name.Emulator_Control = Emulator Control
-view.name.Allocation_Tracker = Allocation Tracker
-view.name.Network_Stats = Network Statistics
-view.name.SysInfo = System Information
-perspective.name.DDMS = DDMS
-page.name.DDMS = DDMS
-page.name.LogCat = LogCat
-extension-point.name.Tools_Locator = Tools Locator
-extension-point.name.Debugger_Connector = Debugger Connector
-extension-point.name.Source_Revealer = Source Revealer
-extension-point.name.TreeView_Laucher = TraceView Launcher
-extension-point.name.ClientAction = Client Specific Actions \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/plugin.xml b/eclipse/plugins/com.android.ide.eclipse.ddms/plugin.xml
deleted file mode 100644
index 43d10cf77..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/plugin.xml
+++ /dev/null
@@ -1,156 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<?eclipse version="3.2"?>
-<plugin>
- <extension-point id="toolsLocator" name="%extension-point.name.Tools_Locator" schema="schema/toolsLocator.exsd"/>
- <extension-point id="debuggerConnector" name="%extension-point.name.Debugger_Connector" schema="schema/debuggerConnector.exsd"/>
- <extension-point id="sourceRevealer" name="%extension-point.name.Source_Revealer" schema="schema/sourceRevealer.exsd"/>
- <extension-point id="traceviewLauncher" name="%extension-point.name.TreeView_Laucher" schema="schema/traceviewLauncher.exsd"/>
- <extension-point id="clientAction" name="%extension-point.name.ClientAction" schema="schema/clientAction.exsd"/>
-
- <extension
- point="org.eclipse.ui.views">
- <category
- name="%category.name"
- id="com.android.ide.eclipse.ddms.views.category">
- </category>
- <view
- allowMultiple="false"
- category="com.android.ide.eclipse.ddms.views.category"
- class="com.android.ide.eclipse.ddms.views.DeviceView"
- icon="icons/device.png"
- id="com.android.ide.eclipse.ddms.views.DeviceView"
- name="%view.name.Devices">
- </view>
- <!-- Deprecate the old logcat view. It should be removed entirely
- after the preview release -->
- <view
- allowMultiple="false"
- category="com.android.ide.eclipse.ddms.views.category"
- class="com.android.ide.eclipse.ddms.views.OldLogCatView"
- icon="icons/android.png"
- id="com.android.ide.eclipse.ddms.views.OldLogCatView"
- name="LogCat (deprecated)"/>
- <view
- allowMultiple="false"
- category="com.android.ide.eclipse.ddms.views.category"
- class="com.android.ide.eclipse.ddms.views.LogCatView"
- icon="icons/logcat.png"
- id="com.android.ide.eclipse.ddms.views.LogCatView"
- name="%view.name.LogCat"/>
- <!-- Disabled for now due to AWT/SWT bridge issue on Leopard.
- <view
- allowMultiple="false"
- category="com.android.ide.eclipse.ddms.views.category"
- class="com.android.ide.eclipse.ddms.views.EventLogView"
- icon="icons/android.png"
- id="com.android.ide.eclipse.ddms.views.EventLogView"
- name="Event Log"/> -->
- <view
- allowMultiple="false"
- category="com.android.ide.eclipse.ddms.views.category"
- class="com.android.ide.eclipse.ddms.views.ThreadView"
- icon="icons/thread.png"
- id="com.android.ide.eclipse.ddms.views.ThreadView"
- name="%view.name.Threads"/>
- <view
- allowMultiple="false"
- category="com.android.ide.eclipse.ddms.views.category"
- class="com.android.ide.eclipse.ddms.views.HeapView"
- icon="icons/heap.png"
- id="com.android.ide.eclipse.ddms.views.HeapView"
- name="%view.name.Heap"/>
- <view
- allowMultiple="false"
- category="com.android.ide.eclipse.ddms.views.category"
- class="com.android.ide.eclipse.ddms.views.FileExplorerView"
- icon="icons/android.png"
- id="com.android.ide.eclipse.ddms.views.FileExplorerView"
- name="%view.name.File_Explorer"/>
- <view
- allowMultiple="false"
- category="com.android.ide.eclipse.ddms.views.category"
- class="com.android.ide.eclipse.ddms.views.EmulatorControlView"
- icon="icons/emulator-16.png"
- id="com.android.ide.eclipse.ddms.views.EmulatorControlView"
- name="%view.name.Emulator_Control"/>
- <view
- allowMultiple="false"
- category="com.android.ide.eclipse.ddms.views.category"
- class="com.android.ide.eclipse.ddms.views.AllocTrackerView"
- icon="icons/heap.png"
- id="com.android.ide.eclipse.ddms.views.AllocTrackerView"
- name="%view.name.Allocation_Tracker"/>
- <view
- category="com.android.ide.eclipse.ddms.views.category"
- class="com.android.ide.eclipse.ddms.views.NetworkStatisticsView"
- icon="icons/networkstats.png"
- id="com.android.ide.eclipse.ddms.views.NetworkStatsView"
- name="%view.name.Network_Stats"
- restorable="true">
- </view>
- <view
- category="com.android.ide.eclipse.ddms.views.category"
- class="com.android.ide.eclipse.ddms.views.SysInfoView"
- id="com.android.ide.eclipse.ddms.views.SysInfoView"
- name="%view.name.SysInfo"
- restorable="true">
- </view>
- </extension>
- <extension
- point="org.eclipse.ui.editors">
- <editor
- class="com.android.ide.eclipse.ddms.editors.UiAutomatorViewer"
- default="true"
- extensions="uix"
- icon="icons/uiautomator.png"
- id="com.android.ide.eclipse.ddms.editors.UiAutomatorViewer"
- name="UI Automator Hierarchy Viewer">
- </editor>
- </extension>
- <extension
- point="org.eclipse.ui.perspectives">
- <perspective
- class="com.android.ide.eclipse.ddms.Perspective"
- icon="icons/ddms-16.png"
- id="com.android.ide.eclipse.ddms.Perspective"
- name="%perspective.name.DDMS"/>
- </extension>
- <extension
- point="org.eclipse.core.runtime.preferences">
- <initializer class="com.android.ide.eclipse.ddms.preferences.PreferenceInitializer"/>
- </extension>
- <extension
- point="org.eclipse.ui.perspectiveExtensions">
- <perspectiveExtension targetID="org.eclipse.jdt.ui.JavaPerspective">
- <perspectiveShortcut id="com.android.ide.eclipse.ddms.Perspective"/>
- </perspectiveExtension>
- <perspectiveExtension targetID="org.eclipse.ui.resourcePerspective">
- <perspectiveShortcut id="com.android.ide.eclipse.ddms.Perspective"/>
- </perspectiveExtension>
- <perspectiveExtension targetID="org.eclipse.debug.ui.DebugPerspective">
- <perspectiveShortcut id="com.android.ide.eclipse.ddms.Perspective"/>
- <view id="com.android.ide.eclipse.ddms.views.LogCatView"
- relative="org.eclipse.ui.views.ProblemView"
- relationship="stack" />
- </perspectiveExtension>
- </extension>
- <extension
- point="org.eclipse.ui.preferencePages">
- <page
- category="com.android.ide.eclipse.preferences.main"
- class="com.android.ide.eclipse.ddms.preferences.PreferencePage"
- id="com.android.ide.eclipse.ddms.preferences.PreferencePage"
- name="%page.name.DDMS"/>
- <page
- category="com.android.ide.eclipse.preferences.main"
- class="com.android.ide.eclipse.ddms.preferences.LogCatPreferencePage"
- id="com.android.ide.eclipse.ddms.preferences.LogCatPreferencePage"
- name="%page.name.LogCat"/>
- <page
- category="com.android.ide.eclipse.ddms.preferences.LogCatPreferencePage"
- class="com.android.ide.eclipse.ddms.preferences.LogCatColorsPage"
- id="com.android.ide.eclipse.ddms.preferences.LogCatColorsPage"
- name="Colors">
- </page>
- </extension>
-</plugin>
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/pom.xml b/eclipse/plugins/com.android.ide.eclipse.ddms/pom.xml
deleted file mode 100644
index 5f4393623..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/pom.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <version>24.3.3-SNAPSHOT</version>
- <artifactId>com.android.ide.eclipse.ddms</artifactId>
- <packaging>eclipse-plugin</packaging>
- <name>ddms</name>
-
- <parent>
- <relativePath>../../pom.xml</relativePath>
- <groupId>adt.group</groupId>
- <artifactId>parent</artifactId>
- <version>1.0.0-SNAPSHOT</version>
- </parent>
-</project>
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/schema/clientAction.exsd b/eclipse/plugins/com.android.ide.eclipse.ddms/schema/clientAction.exsd
deleted file mode 100644
index f277bb043..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/schema/clientAction.exsd
+++ /dev/null
@@ -1,94 +0,0 @@
-<?xml version='1.0' encoding='UTF-8'?>
-<!-- Schema file written by PDE -->
-<schema targetNamespace="com.android.ide.eclipse.ddms" xmlns="http://www.w3.org/2001/XMLSchema">
-<annotation>
- <appInfo>
- <meta.schema plugin="com.android.ide.eclipse.ddms" id="clientAction" name="%extension-point.name.ClientAction"/>
- </appInfo>
- <documentation>
- Extension point that allows adding custom actions to the DDMS Device Panel to act on the currently selected client (Dalvik VM).
- </documentation>
- </annotation>
-
- <element name="clientAction">
- <complexType>
- <attribute name="class" type="string" use="required">
- <annotation>
- <documentation>
-
- </documentation>
- <appInfo>
- <meta.attribute kind="java" basedOn=":com.android.ide.eclipse.ddms.IClientAction"/>
- </appInfo>
- </annotation>
- </attribute>
- </complexType>
- </element>
-
- <element name="extension">
- <annotation>
- <appInfo>
- <meta.element />
- </appInfo>
- </annotation>
- <complexType>
- <sequence>
- <element ref="clientAction"/>
- </sequence>
- <attribute name="point" type="string" use="required">
- <annotation>
- <documentation>
-
- </documentation>
- </annotation>
- </attribute>
- <attribute name="id" type="string">
- <annotation>
- <documentation>
-
- </documentation>
- </annotation>
- </attribute>
- <attribute name="name" type="string">
- <annotation>
- <documentation>
-
- </documentation>
- <appInfo>
- <meta.attribute translatable="true"/>
- </appInfo>
- </annotation>
- </attribute>
- </complexType>
- </element>
-
- <annotation>
- <appInfo>
- <meta.section type="since"/>
- </appInfo>
- <documentation>
- 21.1.0
- </documentation>
- </annotation>
-
-
- <annotation>
- <appInfo>
- <meta.section type="apiinfo"/>
- </appInfo>
- <documentation>
- Extensions must implement com.android.ide.ddms.IClientAction
- </documentation>
- </annotation>
-
-
- <annotation>
- <appInfo>
- <meta.section type="copyright"/>
- </appInfo>
- <documentation>
- Copyright (C) 2012 The Android Open Source Project
- </documentation>
- </annotation>
-
-</schema>
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/schema/debuggerConnector.exsd b/eclipse/plugins/com.android.ide.eclipse.ddms/schema/debuggerConnector.exsd
deleted file mode 100644
index 515713a23..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/schema/debuggerConnector.exsd
+++ /dev/null
@@ -1,104 +0,0 @@
-<?xml version='1.0' encoding='UTF-8'?>
-<!-- Schema file written by PDE -->
-<schema targetNamespace="com.android.ide.eclipse.ddms" xmlns="http://www.w3.org/2001/XMLSchema">
-<annotation>
- <appInfo>
- <meta.schema plugin="com.android.ide.eclipse.ddms" id="debuggerConnector" name="Debugger Connector"/>
- </appInfo>
- <documentation>
- Extension Point to provide a way to connect a debugger to a VM running on a connected device.
-
-The goal of the extension is to identify which project in the workspace matches the running application to properly setup a launch configuration.
- </documentation>
- </annotation>
-
- <element name="connector">
- <complexType>
- <attribute name="class" type="string" use="required">
- <annotation>
- <documentation>
-
- </documentation>
- <appInfo>
- <meta.attribute kind="java" basedOn=":com.android.ide.eclipse.ddms.IDebuggerConnector"/>
- </appInfo>
- </annotation>
- </attribute>
- </complexType>
- </element>
-
- <element name="extension">
- <annotation>
- <appInfo>
- <meta.element />
- </appInfo>
- </annotation>
- <complexType>
- <sequence>
- <element ref="connector"/>
- </sequence>
- <attribute name="point" type="string" use="required">
- <annotation>
- <documentation>
-
- </documentation>
- </annotation>
- </attribute>
- <attribute name="id" type="string">
- <annotation>
- <documentation>
-
- </documentation>
- </annotation>
- </attribute>
- <attribute name="name" type="string">
- <annotation>
- <documentation>
-
- </documentation>
- <appInfo>
- <meta.attribute translatable="true"/>
- </appInfo>
- </annotation>
- </attribute>
- </complexType>
- </element>
-
- <annotation>
- <appInfo>
- <meta.section type="since"/>
- </appInfo>
- <documentation>
- 8.0.0
- </documentation>
- </annotation>
-
- <annotation>
- <appInfo>
- <meta.section type="examples"/>
- </appInfo>
- <documentation>
- [Enter extension point usage example here.]
- </documentation>
- </annotation>
-
- <annotation>
- <appInfo>
- <meta.section type="apiinfo"/>
- </appInfo>
- <documentation>
- The class must implement com.android.ide.ddms.IDebuggerConnector.
- </documentation>
- </annotation>
-
-
- <annotation>
- <appInfo>
- <meta.section type="copyright"/>
- </appInfo>
- <documentation>
- Copyright (C) 2010 The Android Open Source Project
- </documentation>
- </annotation>
-
-</schema>
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/schema/sourceRevealer.exsd b/eclipse/plugins/com.android.ide.eclipse.ddms/schema/sourceRevealer.exsd
deleted file mode 100644
index 9f2cf9c5a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/schema/sourceRevealer.exsd
+++ /dev/null
@@ -1,96 +0,0 @@
-<?xml version='1.0' encoding='UTF-8'?>
-<!-- Schema file written by PDE -->
-<schema targetNamespace="com.android.ide.eclipse.ddms" xmlns="http://www.w3.org/2001/XMLSchema">
-<annotation>
- <appInfo>
- <meta.schema plugin="com.android.ide.eclipse.ddms" id="sourceRevealer" name="Source Revealer"/>
- </appInfo>
- <documentation>
- Extension Point to provide a way to display the source code of a VM running on a connected device.
-
-The goal of the extension is to identify which project in the workspace matches the running application to properly identify the source file to open.
- </documentation>
- </annotation>
-
- <element name="revealer">
- <complexType>
- <attribute name="class" type="string" use="required">
- <annotation>
- <documentation>
-
- </documentation>
- <appInfo>
- <meta.attribute kind="java" basedOn=":com.android.ide.eclipse.ddms.ISourceRevealer"/>
- </appInfo>
- </annotation>
- </attribute>
- </complexType>
- </element>
-
- <element name="extension">
- <annotation>
- <appInfo>
- <meta.element />
- </appInfo>
- </annotation>
- <complexType>
- <sequence>
- <element ref="revealer"/>
- </sequence>
- <attribute name="point" type="string" use="required">
- <annotation>
- <documentation>
-
- </documentation>
- </annotation>
- </attribute>
- <attribute name="id" type="string">
- <annotation>
- <documentation>
-
- </documentation>
- </annotation>
- </attribute>
- <attribute name="name" type="string">
- <annotation>
- <documentation>
-
- </documentation>
- <appInfo>
- <meta.attribute translatable="true"/>
- </appInfo>
- </annotation>
- </attribute>
- </complexType>
- </element>
-
- <annotation>
- <appInfo>
- <meta.section type="since"/>
- </appInfo>
- <documentation>
- 8.0.0
- </documentation>
- </annotation>
-
-
- <annotation>
- <appInfo>
- <meta.section type="apiinfo"/>
- </appInfo>
- <documentation>
- The class must implement com.android.ide.ddms.ISourceRevealer.
- </documentation>
- </annotation>
-
-
- <annotation>
- <appInfo>
- <meta.section type="copyright"/>
- </appInfo>
- <documentation>
- Copyright (C) 2010 The Android Open Source Project
- </documentation>
- </annotation>
-
-</schema>
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/schema/toolsLocator.exsd b/eclipse/plugins/com.android.ide.eclipse.ddms/schema/toolsLocator.exsd
deleted file mode 100644
index da5192172..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/schema/toolsLocator.exsd
+++ /dev/null
@@ -1,104 +0,0 @@
-<?xml version='1.0' encoding='UTF-8'?>
-<!-- Schema file written by PDE -->
-<schema targetNamespace="com.android.ide.eclipse.ddms" xmlns="http://www.w3.org/2001/XMLSchema">
-<annotation>
- <appInfo>
- <meta.schema plugin="com.android.ide.eclipse.ddms" id="toolsLocator" name="Tools Locator"/>
- </appInfo>
- <documentation>
- Extension Point to provide the location of SDK Tools to DDMS.
- </documentation>
- </annotation>
-
- <element name="locator">
- <complexType>
- <attribute name="class" type="string" use="required">
- <annotation>
- <documentation>
-
- </documentation>
- <appInfo>
- <meta.attribute kind="java" basedOn=":com.android.ide.eclipse.ddms.IToolsLocator"/>
- </appInfo>
- </annotation>
- </attribute>
- </complexType>
- </element>
-
- <element name="extension">
- <annotation>
- <appInfo>
- <meta.element />
- </appInfo>
- </annotation>
- <complexType>
- <sequence>
- <element ref="locator"/>
- </sequence>
- <attribute name="point" type="string" use="required">
- <annotation>
- <documentation>
-
- </documentation>
- </annotation>
- </attribute>
- <attribute name="id" type="string">
- <annotation>
- <documentation>
-
- </documentation>
- </annotation>
- </attribute>
- <attribute name="name" type="string">
- <annotation>
- <documentation>
-
- </documentation>
- <appInfo>
- <meta.attribute translatable="true"/>
- </appInfo>
- </annotation>
- </attribute>
- </complexType>
- </element>
-
- <annotation>
- <appInfo>
- <meta.section type="since"/>
- </appInfo>
- <documentation>
- 8.0.0
- </documentation>
- </annotation>
-
- <annotation>
- <appInfo>
- <meta.section type="examples"/>
- </appInfo>
- <documentation>
- &lt;extension point=&quot;com.android.ide.eclipse.ddms.toolsLocator&quot;&gt;
- &lt;locator class=&quot;com.android.ide.eclipse.adt.ToolsLocator&quot;/&gt;
-&lt;/extension&gt;
- </documentation>
- </annotation>
-
- <annotation>
- <appInfo>
- <meta.section type="apiinfo"/>
- </appInfo>
- <documentation>
- The class must implement com.android.ide.ddms.IToolsLocator.
- </documentation>
- </annotation>
-
-
- <annotation>
- <appInfo>
- <meta.section type="copyright"/>
- </appInfo>
- <documentation>
- Copyright (C) 2010 The Android Open Source Project
- </documentation>
- </annotation>
-
-</schema>
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/schema/traceviewLauncher.exsd b/eclipse/plugins/com.android.ide.eclipse.ddms/schema/traceviewLauncher.exsd
deleted file mode 100644
index daca83a08..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/schema/traceviewLauncher.exsd
+++ /dev/null
@@ -1,100 +0,0 @@
-<?xml version='1.0' encoding='UTF-8'?>
-<!-- Schema file written by PDE -->
-<schema targetNamespace="com.android.ide.eclipse.ddms" xmlns="http://www.w3.org/2001/XMLSchema">
-<annotation>
- <appInfo>
- <meta.schema plugin="com.android.ide.eclipse.ddms" id="traceviewLauncher" name="Traceview Launcher"/>
- </appInfo>
- <documentation>
- Extension Point to launch Traceview.
- </documentation>
- </annotation>
-
- <element name="launcher">
- <complexType>
- <attribute name="class" type="string" use="required">
- <annotation>
- <documentation>
- </documentation>
- <appInfo>
- <meta.attribute kind="java" basedOn=":com.android.ide.eclipse.ddms.ITraceviewLauncher"/>
- </appInfo>
- </annotation>
- </attribute>
- </complexType>
- </element>
-
- <element name="extension">
- <annotation>
- <appInfo>
- <meta.element />
- </appInfo>
- </annotation>
- <complexType>
- <sequence>
- <element ref="launcher"/>
- </sequence>
- <attribute name="point" type="string" use="required">
- <annotation>
- <documentation>
- </documentation>
- </annotation>
- </attribute>
- <attribute name="id" type="string">
- <annotation>
- <documentation>
- </documentation>
- </annotation>
- </attribute>
- <attribute name="name" type="string">
- <annotation>
- <documentation>
- </documentation>
- <appInfo>
- <meta.attribute translatable="true"/>
- </appInfo>
- </annotation>
- </attribute>
- </complexType>
- </element>
-
- <annotation>
- <appInfo>
- <meta.section type="since"/>
- </appInfo>
- <documentation>
- 10.0.0
- </documentation>
- </annotation>
-
- <annotation>
- <appInfo>
- <meta.section type="examples"/>
- </appInfo>
- <documentation>
- &lt;extension point=&quot;com.android.ide.eclipse.ddms.traceviewLauncher&quot;&gt;
- &lt;launcher class=&quot;com.android.ide.eclipse.adt.Launcher&quot;/&gt;
-&lt;/extension&gt;
- </documentation>
- </annotation>
-
- <annotation>
- <appInfo>
- <meta.section type="apiinfo"/>
- </appInfo>
- <documentation>
- The class must implement com.android.ide.ddms.ITraceviewLauncher.
- </documentation>
- </annotation>
-
-
- <annotation>
- <appInfo>
- <meta.section type="copyright"/>
- </appInfo>
- <documentation>
- Copyright (C) 2011 The Android Open Source Project
- </documentation>
- </annotation>
-
-</schema>
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/CommonAction.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/CommonAction.java
deleted file mode 100644
index ae13037f8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/CommonAction.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.ddms;
-
-import com.android.ddmuilib.actions.ICommonAction;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.resource.ImageDescriptor;
-
-/**
- * Basic action extending the jFace Action class in order to implement
- * ICommonAction.
- */
-public class CommonAction extends Action implements ICommonAction {
-
- private Runnable mRunnable;
-
- public CommonAction() {
- super();
- }
-
- public CommonAction(String text) {
- super(text);
- }
-
- /**
- * @param text
- * @param image
- */
- public CommonAction(String text, ImageDescriptor image) {
- super(text, image);
- }
-
- /**
- * @param text
- * @param style
- */
- public CommonAction(String text, int style) {
- super(text, style);
- }
-
- @Override
- public void run() {
- if (mRunnable != null) {
- mRunnable.run();
- }
- }
-
- /**
- * Sets the {@link Runnable}.
- * @see ICommonAction#setRunnable(Runnable)
- */
- @Override
- public void setRunnable(Runnable runnable) {
- mRunnable = runnable;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/DdmsPlugin.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/DdmsPlugin.java
deleted file mode 100644
index e08080bf0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/DdmsPlugin.java
+++ /dev/null
@@ -1,876 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms;
-
-import com.android.annotations.NonNull;
-import com.android.ddmlib.AndroidDebugBridge;
-import com.android.ddmlib.AndroidDebugBridge.IDeviceChangeListener;
-import com.android.ddmlib.Client;
-import com.android.ddmlib.DdmPreferences;
-import com.android.ddmlib.IDevice;
-import com.android.ddmlib.Log;
-import com.android.ddmlib.Log.ILogOutput;
-import com.android.ddmlib.Log.LogLevel;
-import com.android.ddmuilib.DdmUiPreferences;
-import com.android.ddmuilib.DevicePanel.IUiSelectionListener;
-import com.android.ddmuilib.StackTracePanel;
-import com.android.ddmuilib.console.DdmConsole;
-import com.android.ddmuilib.console.IDdmConsole;
-import com.android.ide.eclipse.ddms.i18n.Messages;
-import com.android.ide.eclipse.ddms.preferences.PreferenceInitializer;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-import org.eclipse.core.runtime.IExtensionPoint;
-import org.eclipse.core.runtime.IExtensionRegistry;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.SWTException;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.console.ConsolePlugin;
-import org.eclipse.ui.console.IConsole;
-import org.eclipse.ui.console.MessageConsole;
-import org.eclipse.ui.console.MessageConsoleStream;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.osgi.framework.BundleContext;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Collections;
-import java.util.List;
-
-/**
- * The activator class controls the plug-in life cycle
- */
-public final class DdmsPlugin extends AbstractUIPlugin implements IDeviceChangeListener,
- IUiSelectionListener, com.android.ddmuilib.StackTracePanel.ISourceRevealer {
-
-
- // The plug-in ID
- public static final String PLUGIN_ID = "com.android.ide.eclipse.ddms"; //$NON-NLS-1$
-
- /** The singleton instance */
- private static DdmsPlugin sPlugin;
-
- /** Location of the adb command line executable */
- private static String sAdbLocation;
- private static String sToolsFolder;
- private static String sHprofConverter;
-
- private boolean mHasDebuggerConnectors;
- /** debugger connectors for already running apps.
- * Initialized from an extension point.
- */
- private IDebuggerConnector[] mDebuggerConnectors;
- private ITraceviewLauncher[] mTraceviewLaunchers;
- private List<IClientAction> mClientSpecificActions = null;
-
- /** Console for DDMS log message */
- private MessageConsole mDdmsConsole;
-
- private IDevice mCurrentDevice;
- private Client mCurrentClient;
- private boolean mListeningToUiSelection = false;
-
- private final ArrayList<ISelectionListener> mListeners = new ArrayList<ISelectionListener>();
-
- private Color mRed;
-
-
- /**
- * Classes which implement this interface provide methods that deals
- * with {@link IDevice} and {@link Client} selectionchanges.
- */
- public interface ISelectionListener {
-
- /**
- * Sent when a new {@link Client} is selected.
- * @param selectedClient The selected client. If null, no clients are selected.
- */
- public void selectionChanged(Client selectedClient);
-
- /**
- * Sent when a new {@link IDevice} is selected.
- * @param selectedDevice the selected device. If null, no devices are selected.
- */
- public void selectionChanged(IDevice selectedDevice);
- }
-
- /**
- * The constructor
- */
- public DdmsPlugin() {
- sPlugin = this;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
-
- final Display display = getDisplay();
-
- // get the eclipse store
- final IPreferenceStore eclipseStore = getPreferenceStore();
-
- AndroidDebugBridge.addDeviceChangeListener(this);
-
- DdmUiPreferences.setStore(eclipseStore);
-
- //DdmUiPreferences.displayCharts();
-
- // set the consoles.
- mDdmsConsole = new MessageConsole("DDMS", null); //$NON-NLS-1$
- ConsolePlugin.getDefault().getConsoleManager().addConsoles(
- new IConsole[] {
- mDdmsConsole
- });
-
- final MessageConsoleStream consoleStream = mDdmsConsole.newMessageStream();
- final MessageConsoleStream errorConsoleStream = mDdmsConsole.newMessageStream();
- mRed = new Color(display, 0xFF, 0x00, 0x00);
-
- // because this can be run, in some cases, by a non UI thread, and because
- // changing the console properties update the UI, we need to make this change
- // in the UI thread.
- display.asyncExec(new Runnable() {
- @Override
- public void run() {
- errorConsoleStream.setColor(mRed);
- }
- });
-
- // set up the ddms log to use the ddms console.
- Log.setLogOutput(new ILogOutput() {
- @Override
- public void printLog(LogLevel logLevel, String tag, String message) {
- if (logLevel.getPriority() >= LogLevel.ERROR.getPriority()) {
- printToStream(errorConsoleStream, tag, message);
- showConsoleView(mDdmsConsole);
- } else {
- printToStream(consoleStream, tag, message);
- }
- }
-
- @Override
- public void printAndPromptLog(final LogLevel logLevel, final String tag,
- final String message) {
- printLog(logLevel, tag, message);
- // dialog box only run in UI thread..
- display.asyncExec(new Runnable() {
- @Override
- public void run() {
- Shell shell = display.getActiveShell();
- if (logLevel == LogLevel.ERROR) {
- MessageDialog.openError(shell, tag, message);
- } else {
- MessageDialog.openWarning(shell, tag, message);
- }
- }
- });
- }
-
- });
-
- // set up the ddms console to use this objects
- DdmConsole.setConsole(new IDdmConsole() {
- @Override
- public void printErrorToConsole(String message) {
- printToStream(errorConsoleStream, null, message);
- showConsoleView(mDdmsConsole);
- }
- @Override
- public void printErrorToConsole(String[] messages) {
- for (String m : messages) {
- printToStream(errorConsoleStream, null, m);
- }
- showConsoleView(mDdmsConsole);
- }
- @Override
- public void printToConsole(String message) {
- printToStream(consoleStream, null, message);
- }
- @Override
- public void printToConsole(String[] messages) {
- for (String m : messages) {
- printToStream(consoleStream, null, m);
- }
- }
- });
-
- // set the listener for the preference change
- eclipseStore.addPropertyChangeListener(new IPropertyChangeListener() {
- @Override
- public void propertyChange(PropertyChangeEvent event) {
- // get the name of the property that changed.
- String property = event.getProperty();
-
- if (PreferenceInitializer.ATTR_DEBUG_PORT_BASE.equals(property)) {
- DdmPreferences.setDebugPortBase(
- eclipseStore.getInt(PreferenceInitializer.ATTR_DEBUG_PORT_BASE));
- } else if (PreferenceInitializer.ATTR_SELECTED_DEBUG_PORT.equals(property)) {
- DdmPreferences.setSelectedDebugPort(
- eclipseStore.getInt(PreferenceInitializer.ATTR_SELECTED_DEBUG_PORT));
- } else if (PreferenceInitializer.ATTR_THREAD_INTERVAL.equals(property)) {
- DdmUiPreferences.setThreadRefreshInterval(
- eclipseStore.getInt(PreferenceInitializer.ATTR_THREAD_INTERVAL));
- } else if (PreferenceInitializer.ATTR_LOG_LEVEL.equals(property)) {
- DdmPreferences.setLogLevel(
- eclipseStore.getString(PreferenceInitializer.ATTR_LOG_LEVEL));
- } else if (PreferenceInitializer.ATTR_TIME_OUT.equals(property)) {
- DdmPreferences.setTimeOut(
- eclipseStore.getInt(PreferenceInitializer.ATTR_TIME_OUT));
- } else if (PreferenceInitializer.ATTR_USE_ADBHOST.equals(property)) {
- DdmPreferences.setUseAdbHost(
- eclipseStore.getBoolean(PreferenceInitializer.ATTR_USE_ADBHOST));
- } else if (PreferenceInitializer.ATTR_ADBHOST_VALUE.equals(property)) {
- DdmPreferences.setAdbHostValue(
- eclipseStore.getString(PreferenceInitializer.ATTR_ADBHOST_VALUE));
- }
- }
- });
-
- // do some last initializations
-
- // set the preferences.
- PreferenceInitializer.setupPreferences();
-
- // this class is set as the main source revealer and will look at all the implementations
- // of the extension point. see #reveal(String, String, int)
- StackTracePanel.setSourceRevealer(this);
-
- /*
- * Load the extension point implementations.
- * The first step is to load the IConfigurationElement representing the implementations.
- * The 2nd step is to use these objects to instantiate the implementation classes.
- *
- * Because the 2nd step will trigger loading the plug-ins providing the implementations,
- * and those plug-ins could access DDMS classes (like ADT), this 2nd step should be done
- * in a Job to ensure that DDMS is loaded, so that the other plug-ins can load.
- *
- * Both steps could be done in the 2nd step but some of DDMS UI rely on knowing if there
- * is an implementation or not (DeviceView), so we do the first steps in start() and, in
- * some case, record it.
- *
- */
-
- // get the IConfigurationElement for the debuggerConnector right away.
- final IConfigurationElement[] dcce = findConfigElements(
- "com.android.ide.eclipse.ddms.debuggerConnector"); //$NON-NLS-1$
- mHasDebuggerConnectors = dcce.length > 0;
-
- // get the other configElements and instantiante them in a Job.
- new Job(Messages.DdmsPlugin_DDMS_Post_Create_Init) {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- // init the lib
- AndroidDebugBridge.init(true /* debugger support */);
-
- // get the available adb locators
- IConfigurationElement[] elements = findConfigElements(
- "com.android.ide.eclipse.ddms.toolsLocator"); //$NON-NLS-1$
-
- IToolsLocator[] locators = instantiateToolsLocators(elements);
-
- for (IToolsLocator locator : locators) {
- try {
- String adbLocation = locator.getAdbLocation();
- String traceviewLocation = locator.getTraceViewLocation();
- String hprofConvLocation = locator.getHprofConvLocation();
- if (adbLocation != null && traceviewLocation != null &&
- hprofConvLocation != null) {
- // checks if the location is valid.
- if (setToolsLocation(adbLocation, hprofConvLocation,
- traceviewLocation)) {
-
- AndroidDebugBridge.createBridge(sAdbLocation,
- true /* forceNewBridge */);
-
- // no need to look at the other locators.
- break;
- }
- }
- } catch (Throwable t) {
- // ignore, we'll just not use this implementation.
- }
- }
-
- // get the available debugger connectors
- mDebuggerConnectors = instantiateDebuggerConnectors(dcce);
-
- // get the available Traceview Launchers.
- elements = findConfigElements("com.android.ide.eclipse.ddms.traceviewLauncher"); //$NON-NLS-1$
- mTraceviewLaunchers = instantiateTraceviewLauncher(elements);
-
- return Status.OK_STATUS;
- } catch (CoreException e) {
- return e.getStatus();
- }
- }
- }.schedule();
- }
-
- private void showConsoleView(MessageConsole console) {
- ConsolePlugin.getDefault().getConsoleManager().showConsoleView(console);
- }
-
-
- /** Obtain a list of configuration elements that extend the given extension point. */
- IConfigurationElement[] findConfigElements(String extensionPointId) {
- // get the adb location from an implementation of the ADB Locator extension point.
- IExtensionRegistry extensionRegistry = Platform.getExtensionRegistry();
- IExtensionPoint extensionPoint = extensionRegistry.getExtensionPoint(extensionPointId);
- if (extensionPoint != null) {
- return extensionPoint.getConfigurationElements();
- }
-
- // shouldn't happen or it means the plug-in is broken.
- return new IConfigurationElement[0];
- }
-
- /**
- * Finds if any other plug-in is extending the exposed Extension Point called adbLocator.
- *
- * @return an array of all locators found, or an empty array if none were found.
- */
- private IToolsLocator[] instantiateToolsLocators(IConfigurationElement[] configElements)
- throws CoreException {
- ArrayList<IToolsLocator> list = new ArrayList<IToolsLocator>();
-
- if (configElements.length > 0) {
- // only use the first one, ignore the others.
- IConfigurationElement configElement = configElements[0];
-
- // instantiate the class
- Object obj = configElement.createExecutableExtension("class"); //$NON-NLS-1$
- if (obj instanceof IToolsLocator) {
- list.add((IToolsLocator) obj);
- }
- }
-
- return list.toArray(new IToolsLocator[list.size()]);
- }
-
- /**
- * Finds if any other plug-in is extending the exposed Extension Point called debuggerConnector.
- *
- * @return an array of all locators found, or an empty array if none were found.
- */
- private IDebuggerConnector[] instantiateDebuggerConnectors(
- IConfigurationElement[] configElements) throws CoreException {
- ArrayList<IDebuggerConnector> list = new ArrayList<IDebuggerConnector>();
-
- if (configElements.length > 0) {
- // only use the first one, ignore the others.
- IConfigurationElement configElement = configElements[0];
-
- // instantiate the class
- Object obj = configElement.createExecutableExtension("class"); //$NON-NLS-1$
- if (obj instanceof IDebuggerConnector) {
- list.add((IDebuggerConnector) obj);
- }
- }
-
- return list.toArray(new IDebuggerConnector[list.size()]);
- }
-
- /**
- * Finds if any other plug-in is extending the exposed Extension Point called traceviewLauncher.
- *
- * @return an array of all locators found, or an empty array if none were found.
- */
- private ITraceviewLauncher[] instantiateTraceviewLauncher(
- IConfigurationElement[] configElements)
- throws CoreException {
- ArrayList<ITraceviewLauncher> list = new ArrayList<ITraceviewLauncher>();
-
- if (configElements.length > 0) {
- // only use the first one, ignore the others.
- IConfigurationElement configElement = configElements[0];
-
- // instantiate the class
- Object obj = configElement.createExecutableExtension("class"); //$NON-NLS-1$
- if (obj instanceof ITraceviewLauncher) {
- list.add((ITraceviewLauncher) obj);
- }
- }
-
- return list.toArray(new ITraceviewLauncher[list.size()]);
- }
-
- /**
- * Returns the classes that implement {@link IClientAction} in each of the extensions that
- * extend clientAction extension point.
- * @throws CoreException
- */
- private List<IClientAction> instantiateClientSpecificActions(IConfigurationElement[] elements)
- throws CoreException {
- if (elements == null || elements.length == 0) {
- return Collections.emptyList();
- }
-
- List<IClientAction> extensions = new ArrayList<IClientAction>(1);
-
- for (IConfigurationElement e : elements) {
- Object o = e.createExecutableExtension("class"); //$NON-NLS-1$
- if (o instanceof IClientAction) {
- extensions.add((IClientAction) o);
- }
- }
-
- return extensions;
- }
-
- public static Display getDisplay() {
- IWorkbench bench = sPlugin.getWorkbench();
- if (bench != null) {
- return bench.getDisplay();
- }
- return null;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- @Override
- public void stop(BundleContext context) throws Exception {
- AndroidDebugBridge.removeDeviceChangeListener(this);
-
- AndroidDebugBridge.terminate();
-
- mRed.dispose();
-
- sPlugin = null;
- super.stop(context);
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static DdmsPlugin getDefault() {
- return sPlugin;
- }
-
- public static String getAdb() {
- return sAdbLocation;
- }
-
- public static File getPlatformToolsFolder() {
- return new File(sAdbLocation).getParentFile();
- }
-
- public static String getToolsFolder() {
- return sToolsFolder;
- }
-
- public static String getHprofConverter() {
- return sHprofConverter;
- }
-
- /**
- * Stores the adb location. This returns true if the location is an existing file.
- */
- private static boolean setToolsLocation(String adbLocation, String hprofConvLocation,
- String traceViewLocation) {
-
- File adb = new File(adbLocation);
- File hprofConverter = new File(hprofConvLocation);
- File traceview = new File(traceViewLocation);
-
- String missing = "";
- if (adb.isFile() == false) {
- missing += adb.getAbsolutePath() + " ";
- }
- if (hprofConverter.isFile() == false) {
- missing += hprofConverter.getAbsolutePath() + " ";
- }
- if (traceview.isFile() == false) {
- missing += traceview.getAbsolutePath() + " ";
- }
-
- if (missing.length() > 0) {
- String msg = String.format("DDMS files not found: %1$s", missing);
- Log.e("DDMS", msg);
- Status status = new Status(IStatus.ERROR, PLUGIN_ID, msg, null /*exception*/);
- getDefault().getLog().log(status);
- return false;
- }
-
- sAdbLocation = adbLocation;
- sHprofConverter = hprofConverter.getAbsolutePath();
- DdmUiPreferences.setTraceviewLocation(traceview.getAbsolutePath());
-
- sToolsFolder = traceview.getParent();
-
- return true;
- }
-
- /**
- * Set the location of the adb executable and optionally starts adb
- * @param adb location of adb
- * @param startAdb flag to start adb
- */
- public static void setToolsLocation(String adbLocation, boolean startAdb,
- String hprofConvLocation, String traceViewLocation) {
-
- if (setToolsLocation(adbLocation, hprofConvLocation, traceViewLocation)) {
- // starts the server in a thread in case this is blocking.
- if (startAdb) {
- new Thread() {
- @Override
- public void run() {
- // create and start the bridge
- try {
- AndroidDebugBridge.createBridge(sAdbLocation,
- false /* forceNewBridge */);
- } catch (Throwable t) {
- Status status = new Status(IStatus.ERROR, PLUGIN_ID,
- "Failed to create AndroidDebugBridge", t);
- getDefault().getLog().log(status);
- }
- }
- }.start();
- }
- }
- }
-
- /**
- * Returns whether there are implementations of the debuggerConnectors extension point.
- * <p/>
- * This is guaranteed to return the correct value as soon as the plug-in is loaded.
- */
- public boolean hasDebuggerConnectors() {
- return mHasDebuggerConnectors;
- }
-
- /**
- * Returns the implementations of {@link IDebuggerConnector}.
- * <p/>
- * There may be a small amount of time right after the plug-in load where this can return
- * null even if there are implementation.
- * <p/>
- * Since the use of the implementation likely require user input, the UI can use
- * {@link #hasDebuggerConnectors()} to know if there are implementations before they are loaded.
- */
- public IDebuggerConnector[] getDebuggerConnectors() {
- return mDebuggerConnectors;
- }
-
- public synchronized void addSelectionListener(ISelectionListener listener) {
- mListeners.add(listener);
-
- // notify the new listener of the current selection
- listener.selectionChanged(mCurrentDevice);
- listener.selectionChanged(mCurrentClient);
- }
-
- public synchronized void removeSelectionListener(ISelectionListener listener) {
- mListeners.remove(listener);
- }
-
- public synchronized void setListeningState(boolean state) {
- mListeningToUiSelection = state;
- }
-
- /**
- * Sent when the a device is connected to the {@link AndroidDebugBridge}.
- * <p/>
- * This is sent from a non UI thread.
- * @param device the new device.
- *
- * @see IDeviceChangeListener#deviceConnected(IDevice)
- */
- @Override
- public void deviceConnected(IDevice device) {
- // if we are listening to selection coming from the ui, then we do nothing, as
- // any change in the devices/clients, will be handled by the UI, and we'll receive
- // selection notification through our implementation of IUiSelectionListener.
- if (mListeningToUiSelection == false) {
- if (mCurrentDevice == null) {
- handleDefaultSelection(device);
- }
- }
- }
-
- /**
- * Sent when the a device is disconnected to the {@link AndroidDebugBridge}.
- * <p/>
- * This is sent from a non UI thread.
- * @param device the new device.
- *
- * @see IDeviceChangeListener#deviceDisconnected(IDevice)
- */
- @Override
- public void deviceDisconnected(IDevice device) {
- // if we are listening to selection coming from the ui, then we do nothing, as
- // any change in the devices/clients, will be handled by the UI, and we'll receive
- // selection notification through our implementation of IUiSelectionListener.
- if (mListeningToUiSelection == false) {
- // test if the disconnected device was the default selection.
- if (mCurrentDevice == device) {
- // try to find a new device
- AndroidDebugBridge bridge = AndroidDebugBridge.getBridge();
- if (bridge != null) {
- // get the device list
- IDevice[] devices = bridge.getDevices();
-
- // check if we still have devices
- if (devices.length == 0) {
- handleDefaultSelection((IDevice)null);
- } else {
- handleDefaultSelection(devices[0]);
- }
- } else {
- handleDefaultSelection((IDevice)null);
- }
- }
- }
- }
-
- /**
- * Sent when a device data changed, or when clients are started/terminated on the device.
- * <p/>
- * This is sent from a non UI thread.
- * @param device the device that was updated.
- * @param changeMask the mask indicating what changed.
- *
- * @see IDeviceChangeListener#deviceChanged(IDevice)
- */
- @Override
- public void deviceChanged(IDevice device, int changeMask) {
- // if we are listening to selection coming from the ui, then we do nothing, as
- // any change in the devices/clients, will be handled by the UI, and we'll receive
- // selection notification through our implementation of IUiSelectionListener.
- if (mListeningToUiSelection == false) {
-
- // check if this is our device
- if (device == mCurrentDevice) {
- if (mCurrentClient == null) {
- handleDefaultSelection(device);
- } else {
- // get the clients and make sure ours is still in there.
- Client[] clients = device.getClients();
- boolean foundClient = false;
- for (Client client : clients) {
- if (client == mCurrentClient) {
- foundClient = true;
- break;
- }
- }
-
- // if we haven't found our client, lets look for a new one
- if (foundClient == false) {
- mCurrentClient = null;
- handleDefaultSelection(device);
- }
- }
- }
- }
- }
-
- /**
- * Sent when a new {@link IDevice} and {@link Client} are selected.
- * @param selectedDevice the selected device. If null, no devices are selected.
- * @param selectedClient The selected client. If null, no clients are selected.
- */
- @Override
- public synchronized void selectionChanged(IDevice selectedDevice, Client selectedClient) {
- if (mCurrentDevice != selectedDevice) {
- mCurrentDevice = selectedDevice;
-
- // notify of the new default device
- for (ISelectionListener listener : mListeners) {
- listener.selectionChanged(mCurrentDevice);
- }
- }
-
- if (mCurrentClient != selectedClient) {
- mCurrentClient = selectedClient;
-
- // notify of the new default client
- for (ISelectionListener listener : mListeners) {
- listener.selectionChanged(mCurrentClient);
- }
- }
- }
-
- /**
- * Handles a default selection of a {@link IDevice} and {@link Client}.
- * @param device the selected device
- */
- private void handleDefaultSelection(final IDevice device) {
- // because the listener expect to receive this from the UI thread, and this is called
- // from the AndroidDebugBridge notifications, we need to run this in the UI thread.
- try {
- Display display = getDisplay();
-
- display.asyncExec(new Runnable() {
- @Override
- public void run() {
- // set the new device if different.
- boolean newDevice = false;
- if (mCurrentDevice != device) {
- mCurrentDevice = device;
- newDevice = true;
-
- // notify of the new default device
- for (ISelectionListener listener : mListeners) {
- listener.selectionChanged(mCurrentDevice);
- }
- }
-
- if (device != null) {
- // if this is a device switch or the same device but we didn't find a valid
- // client the last time, we go look for a client to use again.
- if (newDevice || mCurrentClient == null) {
- // now get the new client
- Client[] clients = device.getClients();
- if (clients.length > 0) {
- handleDefaultSelection(clients[0]);
- } else {
- handleDefaultSelection((Client)null);
- }
- }
- } else {
- handleDefaultSelection((Client)null);
- }
- }
- });
- } catch (SWTException e) {
- // display is disposed. Do nothing since we're quitting anyway.
- }
- }
-
- private void handleDefaultSelection(Client client) {
- mCurrentClient = client;
-
- // notify of the new default client
- for (ISelectionListener listener : mListeners) {
- listener.selectionChanged(mCurrentClient);
- }
- }
-
- /**
- * Prints a message, associated with a project to the specified stream
- * @param stream The stream to write to
- * @param tag The tag associated to the message. Can be null
- * @param message The message to print.
- */
- private static synchronized void printToStream(MessageConsoleStream stream, String tag,
- String message) {
- String dateTag = getMessageTag(tag);
-
- stream.print(dateTag);
- if (!dateTag.endsWith(" ")) {
- stream.print(" "); //$NON-NLS-1$
- }
- stream.println(message);
- }
-
- /**
- * Creates a string containing the current date/time, and the tag
- * @param tag The tag associated to the message. Can be null
- * @return The dateTag
- */
- private static String getMessageTag(String tag) {
- Calendar c = Calendar.getInstance();
-
- if (tag == null) {
- return String.format(Messages.DdmsPlugin_Message_Tag_Mask_1, c);
- }
-
- return String.format(Messages.DdmsPlugin_Message_Tag_Mask_2, c, tag);
- }
-
- /**
- * Implementation of com.android.ddmuilib.StackTracePanel.ISourceRevealer.
- */
- @Override
- public void reveal(String applicationName, String className, int line) {
- JavaSourceRevealer.reveal(applicationName, className, line);
- }
-
- public boolean launchTraceview(String osPath) {
- if (mTraceviewLaunchers != null) {
- for (ITraceviewLauncher launcher : mTraceviewLaunchers) {
- try {
- if (launcher.openFile(osPath)) {
- return true;
- }
- } catch (Throwable t) {
- // ignore, we'll just not use this implementation.
- }
- }
- }
-
- return false;
- }
-
- /**
- * Returns the list of clients that extend the clientAction extension point.
- */
- @NonNull
- public synchronized List<IClientAction> getClientSpecificActions() {
- if (mClientSpecificActions == null) {
- // get available client specific action extensions
- IConfigurationElement[] elements =
- findConfigElements("com.android.ide.eclipse.ddms.clientAction"); //$NON-NLS-1$
- try {
- mClientSpecificActions = instantiateClientSpecificActions(elements);
- } catch (CoreException e) {
- mClientSpecificActions = Collections.emptyList();
- }
- }
-
- return mClientSpecificActions;
- }
-
- private LogCatMonitor mLogCatMonitor;
- public void startLogCatMonitor(IDevice device) {
- if (mLogCatMonitor == null) {
- mLogCatMonitor = new LogCatMonitor(getDebuggerConnectors(), getPreferenceStore());
- }
-
- mLogCatMonitor.monitorDevice(device);
- }
-
- /** Returns an image descriptor for the image file at the given plug-in relative path */
- public static ImageDescriptor getImageDescriptor(String path) {
- return imageDescriptorFromPlugin(PLUGIN_ID, path);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/IClientAction.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/IClientAction.java
deleted file mode 100644
index c23197599..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/IClientAction.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms;
-
-import com.android.ddmlib.Client;
-
-import org.eclipse.jface.action.Action;
-
-public interface IClientAction {
- Action getAction();
- void selectedClientChanged(Client c);
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/IDebuggerConnector.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/IDebuggerConnector.java
deleted file mode 100644
index c22dfd231..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/IDebuggerConnector.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms;
-
-/**
- * Classes which implement this interface provides a way to connect a debugger to a VM running
- * on a connected device.
- */
-public interface IDebuggerConnector {
- /**
- * Is this application from a project present in the workspace?
- * @param appName name of the application. This is typically the application's package, but
- * can be different if the component was setup to run in its own process.
- * @return true if there is a project in the workspace containing the given app.
- */
- boolean isWorkspaceApp(String appName);
-
- /**
- * Connects a debugger to a VM identified by its appName.
- * <p/>
- * The given port is tied to the application and should be used if possible. However the
- * "selected" port can also be used if needed.
- * @param appName the name of the application. Usually the application's package but this
- * can be different if the component was setup to run in it's own process.
- * @param appPort the preferred connection port.
- * @param selectedPort the port value for the selected application
- * @return true if success.
- */
- boolean connectDebugger(String appName, int appPort, int selectedPort);
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/ISourceRevealer.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/ISourceRevealer.java
deleted file mode 100644
index 078203f52..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/ISourceRevealer.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms;
-
-/**
- * Classes which implement this interface are able to open a source file based on the provided
- * constraints.
- */
-public interface ISourceRevealer {
- /**
- * Reveal a particular line in the given application.
- * @param applicationName the name of the application running the source.
- * @param className the fully qualified class name
- * @param line the line to reveal
- * @return true if the source was revealed.
- */
- boolean reveal(String applicationName, String className, int line);
-
- /**
- * Reveal a particular Java method.
- * @param fqmn fully qualified method name
- * @param fileName file name that contains the method, null if not known
- * @param lineNumber line number in the file, -1 if not known
- * @param perspective If not null, switch to this perspective before
- * revealing the source
- * @return true if the source was revealed.
- */
- boolean revealMethod(String fqmn, String fileName, int lineNumber, String perspective);
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/IToolsLocator.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/IToolsLocator.java
deleted file mode 100644
index 5b53db3fb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/IToolsLocator.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms;
-
-/**
- * Classes which implement this interface provides the location of various SDK tools.
- */
-public interface IToolsLocator {
-
- /**
- * Queries the location of ADB
- * @return A full OS path to the location of adb.
- */
- String getAdbLocation();
-
- /**
- * Queries the location of Traceview
- * @return A full OS path to the location of traceview
- */
- String getTraceViewLocation();
-
- /**
- * Queries the location of hprof-conv
- * @return A full OS path to the location of hprof-conv.
- */
- String getHprofConvLocation();
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/ITraceviewLauncher.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/ITraceviewLauncher.java
deleted file mode 100644
index 7542b8838..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/ITraceviewLauncher.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms;
-
-/**
- * Classes which implement this interface provides a way to open a traceview file.
- */
-public interface ITraceviewLauncher {
-
- boolean openFile(String osPath);
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/JavaSourceRevealer.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/JavaSourceRevealer.java
deleted file mode 100644
index 6f9086a52..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/JavaSourceRevealer.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms;
-
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IConfigurationElement;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class JavaSourceRevealer {
- private static final String SOURCE_REVEALER_EXTENSION_ID =
- "com.android.ide.eclipse.ddms.sourceRevealer"; //$NON-NLS-1$
-
- private static List<ISourceRevealer> sSourceRevealers = instantiateSourceRevealers();
-
- /** Instantiate all providers of the {@link #SOURCE_REVEALER_EXTENSION_ID} extension. */
- private static List<ISourceRevealer> instantiateSourceRevealers() {
- IConfigurationElement[] configElements =
- DdmsPlugin.getDefault().findConfigElements(SOURCE_REVEALER_EXTENSION_ID);
-
- List<ISourceRevealer> providers = new ArrayList<ISourceRevealer>();
-
- for (IConfigurationElement configElement : configElements) {
- // instantiate the class
- Object obj = null;
- try {
- obj = configElement.createExecutableExtension("class"); //$NON-NLS-1$
- } catch (CoreException e) {
- // ignore exception while instantiating this class.
- }
-
- if (obj instanceof ISourceRevealer) {
- providers.add((ISourceRevealer) obj);
- }
- }
-
- return providers;
- }
-
- public static boolean reveal(String applicationName, String className, int line) {
- for (ISourceRevealer revealer : sSourceRevealers) {
- try {
- if (revealer.reveal(applicationName, className, line)) {
- return true;
- }
- } catch (Throwable t) {
- // ignore, we'll just not use this implementation.
- }
- }
-
- return false;
- }
-
- public static boolean revealMethod(String fqmn, String fileName, int linenumber,
- String perspective) {
- for (ISourceRevealer revealer : sSourceRevealers) {
- try {
- if (revealer.revealMethod(fqmn, fileName, linenumber, perspective)) {
- return true;
- }
- } catch (Throwable t) {
- // ignore, we'll just not use this implementation.
- }
- }
-
- return false;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/LogCatMonitor.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/LogCatMonitor.java
deleted file mode 100644
index e99a637be..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/LogCatMonitor.java
+++ /dev/null
@@ -1,277 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.ddms;
-
-import com.android.ddmlib.AndroidDebugBridge;
-import com.android.ddmlib.AndroidDebugBridge.IDeviceChangeListener;
-import com.android.ddmlib.IDevice;
-import com.android.ddmlib.Log.LogLevel;
-import com.android.ddmlib.logcat.LogCatMessage;
-import com.android.ddmuilib.logcat.ILogCatBufferChangeListener;
-import com.android.ddmuilib.logcat.LogCatReceiver;
-import com.android.ddmuilib.logcat.LogCatReceiverFactory;
-import com.android.ide.eclipse.ddms.views.LogCatView;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IViewPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * LogCatMonitor helps in monitoring the logcat output from a set of devices.
- * It scans through the received logcat messages, and activates the logcat view
- * if any message is deemed important.
- */
-public class LogCatMonitor {
- public static final String AUTO_MONITOR_PREFKEY = "ddms.logcat.automonitor"; //$NON-NLS-1$
- public static final String AUTO_MONITOR_LOGLEVEL = "ddms.logcat.auotmonitor.level"; //$NON-NLS-1$
- private static final String AUTO_MONITOR_PROMPT_SHOWN = "ddms.logcat.automonitor.userprompt"; //$NON-NLS-1$
-
- private IPreferenceStore mPrefStore;
- private Map<String, DeviceData> mMonitoredDevices;
- private IDebuggerConnector[] mConnectors;
-
- private int mMinMessagePriority;
-
- /**
- * Flag that controls when the logcat stream is checked. This flag is set when the user
- * performs a launch, and is reset as soon as the logcat view is displayed.
- */
- final AtomicBoolean mMonitorEnabled = new AtomicBoolean(false);
-
- public LogCatMonitor(IDebuggerConnector[] debuggerConnectors, IPreferenceStore prefStore) {
- mConnectors = debuggerConnectors;
- mPrefStore = prefStore;
- mMinMessagePriority =
- LogLevel.getByString(mPrefStore.getString(AUTO_MONITOR_LOGLEVEL)).getPriority();
-
- mMonitoredDevices = new HashMap<String, DeviceData>();
-
- AndroidDebugBridge.addDeviceChangeListener(new IDeviceChangeListener() {
- @Override
- public void deviceDisconnected(IDevice device) {
- unmonitorDevice(device.getSerialNumber());
- mMonitoredDevices.remove(device.getSerialNumber());
- }
-
- @Override
- public void deviceConnected(IDevice device) {
- }
-
- @Override
- public void deviceChanged(IDevice device, int changeMask) {
- }
- });
-
- mPrefStore.addPropertyChangeListener(new IPropertyChangeListener() {
- @Override
- public void propertyChange(PropertyChangeEvent event) {
- if (AUTO_MONITOR_PREFKEY.equals(event.getProperty())
- && event.getNewValue().equals(false)) {
- unmonitorAllDevices();
- } else if (AUTO_MONITOR_LOGLEVEL.equals(event.getProperty())) {
- mMinMessagePriority =
- LogLevel.getByString((String) event.getNewValue()).getPriority();
- }
- }
- });
- }
-
- private void unmonitorAllDevices() {
- for (String device : mMonitoredDevices.keySet()) {
- unmonitorDevice(device);
- }
-
- mMonitoredDevices.clear();
- }
-
- private void unmonitorDevice(String deviceSerial) {
- DeviceData data = mMonitoredDevices.get(deviceSerial);
- if (data == null) {
- return;
- }
-
- data.receiver.removeMessageReceivedEventListener(data.bufferChangeListener);
- }
-
- public void monitorDevice(final IDevice device) {
- if (!mPrefStore.getBoolean(AUTO_MONITOR_PREFKEY)) {
- // do not monitor device if auto monitoring is off
- return;
- }
-
- mMonitorEnabled.set(true);
-
- if (mMonitoredDevices.keySet().contains(device.getSerialNumber())) {
- // the device is already monitored
- return;
- }
-
- LogCatReceiver r = LogCatReceiverFactory.INSTANCE.newReceiver(device, mPrefStore);
- ILogCatBufferChangeListener l = new ILogCatBufferChangeListener() {
- @Override
- public void bufferChanged(List<LogCatMessage> addedMessages,
- List<LogCatMessage> deletedMessages) {
- checkMessages(addedMessages, device);
- }
- };
- r.addMessageReceivedEventListener(l);
-
- mMonitoredDevices.put(device.getSerialNumber(), new DeviceData(r, l));
- }
-
- private void checkMessages(List<LogCatMessage> receivedMessages, IDevice device) {
- if (!mMonitorEnabled.get()) {
- return;
- }
-
- // check the received list of messages to see if any of them are
- // significant enough to be seen by the user. If so, activate the logcat view
- // to display those messages
- for (LogCatMessage m : receivedMessages) {
- if (isImportantMessage(m)) {
- focusLogCatView(device, m.getAppName());
-
- // now that logcat view is active, no need to check messages until the next
- // time user launches an application.
- mMonitorEnabled.set(false);
- break;
- }
- }
- }
-
- /**
- * Check whether a message is "important". Currently, we assume that a message is important if
- * it is of severity level error or higher, and it belongs to an app currently in the workspace.
- */
- private boolean isImportantMessage(LogCatMessage m) {
- if (m.getLogLevel().getPriority() < mMinMessagePriority) {
- return false;
- }
-
- String app = m.getAppName();
- for (IDebuggerConnector c : mConnectors) {
- if (c.isWorkspaceApp(app)) {
- return true;
- }
- }
-
- return false;
- }
-
- private void focusLogCatView(final IDevice device, final String appName) {
- Display.getDefault().asyncExec(new Runnable() {
- @Override
- public void run() {
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- if (window == null) {
- return;
- }
-
- IWorkbenchPage page = window.getActivePage();
- if (page == null) {
- return;
- }
-
- // if the logcat view is not visible, then prompt the user once to set
- // logcat monitoring preferences
- if (!isLogCatViewVisible(page)) {
- boolean showLogCatView = promptUserOnce(page.getWorkbenchWindow().getShell());
- if (!showLogCatView) {
- return;
- }
- }
-
- // display view
- final LogCatView v = displayLogCatView(page);
- if (v == null) {
- return;
- }
-
- // select correct device
- v.selectionChanged(device);
-
- // select appropriate filter
- v.selectTransientAppFilter(appName);
- }
-
- private boolean isLogCatViewVisible(IWorkbenchPage page) {
- IViewPart view = page.findView(LogCatView.ID);
- return view != null && page.isPartVisible(view);
- }
-
- private LogCatView displayLogCatView(IWorkbenchPage page) {
- // if the view is already in the page, just bring it to the front
- // without giving it focus.
- IViewPart view = page.findView(LogCatView.ID);
- if (view != null) {
- page.bringToTop(view);
- if (view instanceof LogCatView) {
- return (LogCatView)view;
- }
- }
-
- // if the view is not in the page, then create and show it.
- try {
- return (LogCatView) page.showView(LogCatView.ID);
- } catch (PartInitException e) {
- return null;
- }
- }
-
- private boolean promptUserOnce(Shell shell) {
- // see if this prompt was already displayed
- boolean promptShown = mPrefStore.getBoolean(AUTO_MONITOR_PROMPT_SHOWN);
- if (promptShown) {
- return mPrefStore.getBoolean(AUTO_MONITOR_PREFKEY);
- }
-
- LogCatMonitorDialog dlg = new LogCatMonitorDialog(shell);
- int r = dlg.open();
-
- // save preference indicating that this dialog has been displayed once
- mPrefStore.setValue(AUTO_MONITOR_PROMPT_SHOWN, true);
- mPrefStore.setValue(AUTO_MONITOR_PREFKEY, dlg.shouldMonitor());
- mPrefStore.setValue(AUTO_MONITOR_LOGLEVEL, dlg.getMinimumPriority());
-
- return r == Window.OK && dlg.shouldMonitor();
- }
-
- });
- }
-
- private static class DeviceData {
- public final LogCatReceiver receiver;
- public final ILogCatBufferChangeListener bufferChangeListener;
-
- public DeviceData(LogCatReceiver r, ILogCatBufferChangeListener l) {
- receiver = r;
- bufferChangeListener = l;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/LogCatMonitorDialog.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/LogCatMonitorDialog.java
deleted file mode 100644
index 6194a0d9c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/LogCatMonitorDialog.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms;
-
-import com.android.ddmlib.Log.LogLevel;
-
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.TitleAreaDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Shell;
-
-public class LogCatMonitorDialog extends TitleAreaDialog {
- private static final String TITLE = "Auto Monitor Logcat";
- private static final String DEFAULT_MESSAGE =
- "Would you like ADT to automatically monitor logcat \n" +
- "output for messages from applications in the workspace?";
-
- private boolean mShouldMonitor = true;
-
- private static final String[] LOG_PRIORITIES = new String[] {
- LogLevel.VERBOSE.getStringValue(),
- LogLevel.DEBUG.getStringValue(),
- LogLevel.INFO.getStringValue(),
- LogLevel.WARN.getStringValue(),
- LogLevel.ERROR.getStringValue(),
- LogLevel.ASSERT.getStringValue(),
- };
- private static final int ERROR_PRIORITY_INDEX = 4;
-
- private String mMinimumLogPriority = LOG_PRIORITIES[ERROR_PRIORITY_INDEX];
-
- public LogCatMonitorDialog(Shell parentShell) {
- super(parentShell);
- setHelpAvailable(false);
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- setTitle(TITLE);
- setMessage(DEFAULT_MESSAGE);
-
- parent = (Composite) super.createDialogArea(parent);
- Composite c = new Composite(parent, SWT.BORDER);
- c.setLayout(new GridLayout(2, false));
- GridData gd_c = new GridData(GridData.FILL_BOTH);
- gd_c.grabExcessVerticalSpace = false;
- gd_c.grabExcessHorizontalSpace = false;
- c.setLayoutData(gd_c);
-
- final Button disableButton = new Button(c, SWT.RADIO);
- disableButton.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, false, false, 2, 1));
- disableButton.setText("No, do not monitor logcat output.");
-
- final Button enableButton = new Button(c, SWT.RADIO);
- enableButton.setText("Yes, monitor logcat and display logcat view if there are\n" +
- "messages with priority higher than:");
- enableButton.setSelection(true);
-
- final Combo levelCombo = new Combo(c, SWT.READ_ONLY | SWT.DROP_DOWN);
- levelCombo.setItems(LOG_PRIORITIES);
- levelCombo.select(ERROR_PRIORITY_INDEX);
-
- SelectionListener s = new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (e.getSource() == enableButton) {
- mShouldMonitor = enableButton.getSelection();
- levelCombo.setEnabled(mShouldMonitor);
- } else if (e.getSource() == levelCombo) {
- mMinimumLogPriority = LOG_PRIORITIES[levelCombo.getSelectionIndex()];
- }
- }
- };
-
- levelCombo.addSelectionListener(s);
- enableButton.addSelectionListener(s);
-
- return parent;
- }
-
- @Override
- protected void createButtonsForButtonBar(Composite parent) {
- // Only need OK button
- createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,
- true);
- }
-
- public boolean shouldMonitor() {
- return mShouldMonitor;
- }
-
- public String getMinimumPriority() {
- return mMinimumLogPriority;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/Perspective.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/Perspective.java
deleted file mode 100644
index c98e9ca7f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/Perspective.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms;
-
-import com.android.ide.eclipse.ddms.views.AllocTrackerView;
-import com.android.ide.eclipse.ddms.views.DeviceView;
-import com.android.ide.eclipse.ddms.views.EmulatorControlView;
-import com.android.ide.eclipse.ddms.views.FileExplorerView;
-import com.android.ide.eclipse.ddms.views.HeapView;
-import com.android.ide.eclipse.ddms.views.LogCatView;
-import com.android.ide.eclipse.ddms.views.NetworkStatisticsView;
-import com.android.ide.eclipse.ddms.views.SysInfoView;
-import com.android.ide.eclipse.ddms.views.ThreadView;
-
-import org.eclipse.ui.IFolderLayout;
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IPerspectiveFactory;
-
-public class Perspective implements IPerspectiveFactory {
-
- public static String ID = "com.android.ide.eclipse.ddms.Perspective"; //$NON-NLS-1$
-
- @Override
- public void createInitialLayout(IPageLayout layout) {
- // create a default layout that looks like the stand alone DDMS.
-
- // no editor window
- layout.setEditorAreaVisible(false);
-
- String editorArea = layout.getEditorArea();
- IFolderLayout folder;
-
- folder = layout.createFolder("logcat", IPageLayout.BOTTOM, 0.8f, //$NON-NLS-1$
- editorArea);
- folder.addPlaceholder(LogCatView.ID + ":*"); //$NON-NLS-1$
- folder.addView(LogCatView.ID);
-
- folder = layout.createFolder("devices", IPageLayout.LEFT, 0.3f, //$NON-NLS-1$
- editorArea);
- folder.addPlaceholder(DeviceView.ID + ":*"); //$NON-NLS-1$
- folder.addView(DeviceView.ID);
-
- folder = layout.createFolder("ddms-detail", IPageLayout.RIGHT, 0.5f, //$NON-NLS-1$
- editorArea);
- folder.addPlaceholder(ThreadView.ID + ":*"); //$NON-NLS-1$
- folder.addView(ThreadView.ID);
- folder.addView(HeapView.ID);
- folder.addView(AllocTrackerView.ID);
- folder.addView(NetworkStatisticsView.ID);
- folder.addView(FileExplorerView.ID);
- folder.addView(EmulatorControlView.ID);
- folder.addView(SysInfoView.ID);
-
- layout.addPerspectiveShortcut("org.eclipse.ui.resourcePerspective"); //$NON-NLS-1$
- layout.addPerspectiveShortcut("org.eclipse.debug.ui.DebugPerspective"); //$NON-NLS-1$
- layout.addPerspectiveShortcut("org.eclipse.jdt.ui.JavaPerspective"); //$NON-NLS-1$
-
- layout.addShowViewShortcut(DeviceView.ID);
- layout.addShowViewShortcut(FileExplorerView.ID);
- layout.addShowViewShortcut(HeapView.ID);
- layout.addShowViewShortcut(AllocTrackerView.ID);
- layout.addShowViewShortcut(LogCatView.ID);
- layout.addShowViewShortcut(ThreadView.ID);
- layout.addShowViewShortcut(NetworkStatisticsView.ID);
- layout.addShowViewShortcut(SysInfoView.ID);
-
- layout.addShowViewShortcut(IPageLayout.ID_RES_NAV);
- layout.addShowViewShortcut(IPageLayout.ID_BOOKMARKS);
- layout.addShowViewShortcut(IPageLayout.ID_OUTLINE);
- layout.addShowViewShortcut(IPageLayout.ID_PROP_SHEET);
- layout.addShowViewShortcut(IPageLayout.ID_PROBLEM_VIEW);
- layout.addShowViewShortcut(IPageLayout.ID_PROGRESS_VIEW);
- layout.addShowViewShortcut(IPageLayout.ID_TASK_LIST);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/editors/UiAutomatorViewer.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/editors/UiAutomatorViewer.java
deleted file mode 100644
index 0843018aa..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/editors/UiAutomatorViewer.java
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.editors;
-
-import com.android.ide.eclipse.base.InstallDetails;
-import com.android.uiautomator.UiAutomatorHelper.UiAutomatorResult;
-import com.android.uiautomator.UiAutomatorModel;
-import com.android.uiautomator.UiAutomatorView;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.IURIEditorInput;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.WorkbenchException;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.ui.part.EditorPart;
-
-import java.io.File;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-public class UiAutomatorViewer extends EditorPart {
- private String mFilePath;
- private UiAutomatorView mView;
-
- @Override
- public void doSave(IProgressMonitor arg0) {
- }
-
- @Override
- public void doSaveAs() {
- }
-
- @Override
- public boolean isSaveAsAllowed() {
- return false;
- }
-
- @Override
- public boolean isDirty() {
- return false;
- }
-
- @Override
- public void init(IEditorSite site, IEditorInput input) throws PartInitException {
- // we use a IURIEditorInput to allow opening files not within the workspace
- if (!(input instanceof IURIEditorInput)) {
- throw new PartInitException("UI Automator Hierarchy View: unsupported input type.");
- }
-
- setSite(site);
- setInput(input);
- mFilePath = ((IURIEditorInput) input).getURI().getPath();
-
- // set the editor part name to be the name of the file.
- File f = new File(mFilePath);
- setPartName(f.getName());
- }
-
- @Override
- public void createPartControl(Composite parent) {
- Composite c = new Composite(parent, SWT.NONE);
- c.setLayout(new GridLayout(1, false));
- GridData gd = new GridData(GridData.FILL_BOTH);
- c.setLayoutData(gd);
-
- mView = new UiAutomatorView(c, SWT.BORDER);
- mView.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- if (mFilePath == null) {
- return;
- }
-
- UiAutomatorModel model = null;
- File modelFile = new File(mFilePath);
- try {
- model = new UiAutomatorModel(modelFile);
- } catch (Exception e) {
- MessageDialog.openError(parent.getShell(), "Error opening " + mFilePath,
- "Unexpected error while parsing input: " + e.getMessage());
- return;
- }
-
- mView.setModel(model, modelFile, null);
- }
-
- @Override
- public void setFocus() {
- }
-
- public static boolean openEditor(final UiAutomatorResult r) {
- final IFileStore fileStore = EFS.getLocalFileSystem().getStore(
- new Path(r.uiHierarchy.getAbsolutePath()));
- if (!fileStore.fetchInfo().exists()) {
- return false;
- }
-
- final AtomicBoolean status = new AtomicBoolean(false);
-
- final IWorkbench workbench = PlatformUI.getWorkbench();
- workbench.getDisplay().syncExec(new Runnable() {
- @Override
- public void run() {
- IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
- if (window == null) {
- return;
- }
-
- IWorkbenchPage page = window.getActivePage();
- if (page == null) {
- return;
- }
-
- // try to switch perspectives if possible
- if (page.isEditorAreaVisible() == false && InstallDetails.isAdtInstalled()) {
- try {
- workbench.showPerspective("org.eclipse.jdt.ui.JavaPerspective", window); //$NON-NLS-1$
- } catch (WorkbenchException e) {
- }
- }
-
- IEditorPart editor = null;
- try {
- editor = IDE.openEditorOnFileStore(page, fileStore);
- } catch (PartInitException e) {
- return;
- }
-
- if (!(editor instanceof UiAutomatorViewer)) {
- return;
- }
-
- ((UiAutomatorViewer) editor).setModel(r.model, r.uiHierarchy, r.screenshot);
- status.set(true);
- }
- });
-
- return status.get();
- }
-
- protected void setModel(UiAutomatorModel model, File modelFile, Image screenshot) {
- mView.setModel(model, modelFile, screenshot);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/i18n/Messages.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/i18n/Messages.java
deleted file mode 100644
index 576b59873..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/i18n/Messages.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.i18n;
-
-import org.eclipse.osgi.util.NLS;
-
-public class Messages extends NLS {
- private static final String BUNDLE_NAME = "com.android.ide.eclipse.ddms.i18n.messages"; //$NON-NLS-1$
- public static String DdmsPlugin_Message_Tag_Mask_1;
- public static String DdmsPlugin_Message_Tag_Mask_2;
- public static String DdmsPlugin_DDMS_Post_Create_Init;
- public static String DeviceView_ADB_Error;
- public static String DeviceView_ADB_Failed_Restart;
- public static String DeviceView_Cause_GC;
- public static String DeviceView_Cause_GC_Tooltip;
- public static String DeviceView_Debug_Process;
- public static String DeviceView_Debug_Process_Title;
- public static String DeviceView_Debug_Process_Tooltip;
- public static String DeviceView_Debug_Session_Failed;
- public static String DeviceView_Dump_HPROF_File;
- public static String DeviceView_Dump_HPROF_File_Not_Supported_By_VM;
- public static String DeviceView_Dump_HPROF_File_Tooltip;
- public static String DeviceView_Failed_To_Save_HPROF_Data;
- public static String DeviceView_HPROF_Error;
- public static String DeviceView_Process_Already_Being_Debugged;
- public static String DeviceView_Process_Debug_Already_In_Use;
- public static String DeviceView_Pulling_From_Device;
- public static String DeviceView_Reset_ADB;
- public static String DeviceView_Reset_ADB_Host_Deamon;
- public static String DeviceView_Save_HPROF_File;
- public static String DeviceView_Screen_Capture;
- public static String DeviceView_Screen_Capture_Tooltip;
- public static String DeviceView_Start_Method_Profiling;
- public static String DeviceView_Start_Method_Profiling_Not_Suported_By_Vm;
- public static String DeviceView_Start_Method_Profiling_Tooltip;
- public static String DeviceView_Stop_Method_Profiling;
- public static String DeviceView_Stop_Method_Profiling_Tooltip;
- public static String DeviceView_Stop_Process;
- public static String DeviceView_Stop_Process_Tooltip;
- public static String DeviceView_Threads;
- public static String DeviceView_Threads_Tooltip;
- public static String DeviceView_Unable_Create_HPROF_For_Application;
- public static String DeviceView_Unable_Download_HPROF_From_Device_One_Param_First_Message;
- public static String DeviceView_Unable_Download_HPROF_From_Device_One_Param_Second_Message;
- public static String DeviceView_Unable_Download_HPROF_From_Device_Two_Param;
- public static String DeviceView_Update_Heap;
- public static String DeviceView_Update_Heap_Tooltip;
- public static String EventLogView_Clear_Log;
- public static String EventLogView_Clears_Event_Log;
- public static String EventLogView_Import_Bug_Report_Log;
- public static String EventLogView_Imports_Bug_Report;
- public static String EventLogView_Load_Log;
- public static String EventLogView_Loads_Event_Log;
- public static String EventLogView_Opens_Options_Panel;
- public static String EventLogView_Options;
- public static String EventLogView_Save_Log;
- public static String EventLogView_Saves_Event_Log;
- public static String FileExplorerView_Delete;
- public static String FileExplorerView_Delete_The_Selection;
- public static String FileExplorerView_Pull_File;
- public static String FileExplorerView_Pull_File_From_File;
- public static String FileExplorerView_Push_File;
- public static String FileExplorerView_Push_File_Onto_Device;
- public static String LogCatPreferencePage_Display_Font;
- public static String LogCatPreferencePage_MaxMessages;
- public static String LogCatPreferencePage_Switch_Perspective;
- public static String LogCatPreferencePage_Switch_To;
- public static String LogCatPreferencePage_AutoMonitorLogcat;
- public static String LogCatPreferencePage_SessionFilterLogLevel;
- public static String LogCatView_Clear_Log;
- public static String LogCatView_Copy;
- public static String LogCatView_Create_Filter;
- public static String LogCatView_Create_Filter_Tooltip;
- public static String LogCatView_Delete_Filter;
- public static String LogCatView_Delete_Filter_Tooltip;
- public static String LogCatView_Edit_Filter;
- public static String LogCatView_Edit_Filter_Tooltip;
- public static String LogCatView_Export_Selection_As_Text;
- public static String LogCatView_Export_Selection_As_Text_Tooltip;
- public static String LogCatView_Select_All;
- public static String PreferencePage_ADB_Connection_Time_Out;
- public static String PreferencePage_Adbhost_value;
- public static String PreferencePage_Assert;
- public static String PreferencePage_Base_Local_Debugger_Port;
- public static String PreferencePage_Debug;
- public static String PreferencePage_Error;
- public static String PreferencePage_Heap_Updates_Enabled_Default;
- public static String PreferencePage_HPROF_Action;
- public static String PreferencePage_Info;
- public static String PreferencePage_Logging_Level;
- public static String PreferencePage_Open_Eclipse;
- public static String PreferencePage_Save_Disk;
- public static String PreferencePage_Thread_Status_Refresh_Interval;
- public static String PreferencePage_Thread_Updates_Enabled_By_Default;
- public static String PreferencePage_Use_Adbhost;
- public static String PreferencePage_Verbose;
- public static String PreferencePage_Warning;
- public static String TableView_Copy;
- public static String TableView_Select_All;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
-
- private Messages() {
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/i18n/messages.properties b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/i18n/messages.properties
deleted file mode 100644
index 3698ebce7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/i18n/messages.properties
+++ /dev/null
@@ -1,107 +0,0 @@
-#
-# Copyright (C) 2011 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-
-DdmsPlugin_Message_Tag_Mask_1=[%1$tF %1$tT]
-DdmsPlugin_Message_Tag_Mask_2=[%1$tF %1$tT - %2$s]
-DdmsPlugin_DDMS_Post_Create_Init=DDMS post-create init
-DeviceView_ADB_Error=Adb Error
-DeviceView_ADB_Failed_Restart=Adb failed to restart\!\n\nMake sure the plugin is properly configured.
-DeviceView_Cause_GC=Cause GC
-DeviceView_Cause_GC_Tooltip=Cause GC
-DeviceView_Debug_Process=Debug Process
-DeviceView_Debug_Process_Title=Process Debug
-DeviceView_Debug_Process_Tooltip=Debug the selected process, provided its source project is present and opened in the workspace.
-DeviceView_Debug_Session_Failed=No opened project found for %1$s. Debug session failed\!
-DeviceView_Dump_HPROF_File=Dump HPROF file
-DeviceView_Dump_HPROF_File_Not_Supported_By_VM=Dump HPROF file (not supported by this VM)
-DeviceView_Dump_HPROF_File_Tooltip=Dump HPROF file
-DeviceView_Failed_To_Save_HPROF_Data=Failed to save hprof data into temp file%1$s
-DeviceView_HPROF_Error=HPROF Error
-DeviceView_Process_Already_Being_Debugged=The process is already being debugged\!
-DeviceView_Process_Debug_Already_In_Use=The process debug port is already in use\!
-DeviceView_Pulling_From_Device=Pulling %1$s from the device
-DeviceView_Reset_ADB=Reset adb
-DeviceView_Reset_ADB_Host_Deamon=Reset the adb host daemon
-DeviceView_Save_HPROF_File=Save HPROF file
-DeviceView_Screen_Capture=Screen Capture
-DeviceView_Screen_Capture_Tooltip=Screen Capture
-DeviceView_Start_Method_Profiling=Start Method Profiling
-DeviceView_Start_Method_Profiling_Not_Suported_By_Vm=Start Method Profiling (not supported by this VM)
-DeviceView_Start_Method_Profiling_Tooltip=Start Method Profiling
-DeviceView_Stop_Method_Profiling=Stop Method Profiling
-DeviceView_Stop_Method_Profiling_Tooltip=Stop Method Profiling
-DeviceView_Stop_Process=Stop Process
-DeviceView_Stop_Process_Tooltip=Stop Process
-DeviceView_Threads=Update Threads
-DeviceView_Threads_Tooltip=Update Threads
-DeviceView_Unable_Create_HPROF_For_Application=Unable to create HPROF file for application '%1$s'.\n\n%2$s Check logcat for more information.
-DeviceView_Unable_Download_HPROF_From_Device_One_Param_First_Message=Unable to download HPROF file from device '%1$s'.
-DeviceView_Unable_Download_HPROF_From_Device_One_Param_Second_Message=Unable to download HPROF file from device '%1$s'.
-DeviceView_Unable_Download_HPROF_From_Device_Two_Param=Unable to download HPROF file from device '%1$s'.\n\n%2$s
-DeviceView_Update_Heap=Update Heap
-DeviceView_Update_Heap_Tooltip=Update Heap
-EventLogView_Clear_Log=Clear Log
-EventLogView_Clears_Event_Log=Clears the event log
-EventLogView_Import_Bug_Report_Log=Import Bug Report Log
-EventLogView_Imports_Bug_Report=Imports a bug report.
-EventLogView_Load_Log=Load Log
-EventLogView_Loads_Event_Log=Loads an event log
-EventLogView_Opens_Options_Panel=Opens the options panel
-EventLogView_Options=Options...
-EventLogView_Save_Log=Save Log
-EventLogView_Saves_Event_Log=Saves the event log
-FileExplorerView_Delete=Delete
-FileExplorerView_Delete_The_Selection=Delete the selection
-FileExplorerView_Pull_File=Pull File...
-FileExplorerView_Pull_File_From_File=Pull a file from the device
-FileExplorerView_Push_File=Push File...
-FileExplorerView_Push_File_Onto_Device=Push a file onto the device
-LogCatPreferencePage_Display_Font=Display Font:
-LogCatPreferencePage_MaxMessages=Maximum number of logcat messages to buffer:
-LogCatPreferencePage_Switch_Perspective=Switch Perspective
-LogCatPreferencePage_Switch_To=Switch to:
-LogCatPreferencePage_AutoMonitorLogcat=Monitor logcat for messages from applications in workspace
-LogCatPreferencePage_SessionFilterLogLevel=Show logcat view if message priority is atleast:
-LogCatView_Clear_Log=Clear Log
-LogCatView_Copy=Copy
-LogCatView_Create_Filter=Create Filter
-LogCatView_Create_Filter_Tooltip=Create Filter
-LogCatView_Delete_Filter=Delete Filter
-LogCatView_Delete_Filter_Tooltip=Delete Filter
-LogCatView_Edit_Filter=Edit Filter
-LogCatView_Edit_Filter_Tooltip=Edit Filter
-LogCatView_Export_Selection_As_Text=Export Selection As Text...
-LogCatView_Export_Selection_As_Text_Tooltip=Export Selection As Text...
-LogCatView_Select_All=Select All
-PreferencePage_ADB_Connection_Time_Out=ADB connection time out (ms):
-PreferencePage_Adbhost_value=ADBHOST value:
-PreferencePage_Assert=Assert
-PreferencePage_Base_Local_Debugger_Port=Base local debugger port:
-PreferencePage_Debug=Debug
-PreferencePage_Error=Error
-PreferencePage_Heap_Updates_Enabled_Default=Heap updates enabled by default
-PreferencePage_HPROF_Action=HPROF Action:
-PreferencePage_Info=Info
-PreferencePage_Logging_Level=Logging Level
-PreferencePage_Open_Eclipse=Open in Eclipse
-PreferencePage_Save_Disk=Save to disk
-PreferencePage_Thread_Status_Refresh_Interval=Thread status refresh interval (seconds):
-PreferencePage_Thread_Updates_Enabled_By_Default=Thread updates enabled by default
-PreferencePage_Use_Adbhost=Use ADBHOST
-PreferencePage_Verbose=Verbose
-PreferencePage_Warning=Warning
-TableView_Copy=Copy
-TableView_Select_All=Select All
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/preferences/LogCatColorsPage.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/preferences/LogCatColorsPage.java
deleted file mode 100644
index 675a51c24..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/preferences/LogCatColorsPage.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.preferences;
-
-import com.android.ddmuilib.logcat.LogCatPanel;
-import com.android.ide.eclipse.ddms.DdmsPlugin;
-
-import org.eclipse.jface.preference.ColorFieldEditor;
-import org.eclipse.jface.preference.FieldEditorPreferencePage;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-
-public class LogCatColorsPage extends FieldEditorPreferencePage
- implements IWorkbenchPreferencePage {
- public LogCatColorsPage() {
- super(GRID);
- setPreferenceStore(DdmsPlugin.getDefault().getPreferenceStore());
- }
-
- @Override
- public void init(IWorkbench workbench) {
- }
-
- @Override
- protected void createFieldEditors() {
- // colors preference for different log levels
- ColorFieldEditor cfe = new ColorFieldEditor(LogCatPanel.VERBOSE_COLOR_PREFKEY,
- "Verbose Log Message Color", getFieldEditorParent());
- addField(cfe);
-
- cfe = new ColorFieldEditor(LogCatPanel.DEBUG_COLOR_PREFKEY, "Debug Log Message Color",
- getFieldEditorParent());
- addField(cfe);
-
- cfe = new ColorFieldEditor(LogCatPanel.INFO_COLOR_PREFKEY, "Info Log Message Color",
- getFieldEditorParent());
- addField(cfe);
-
- cfe = new ColorFieldEditor(LogCatPanel.WARN_COLOR_PREFKEY, "Warning Log Message Color",
- getFieldEditorParent());
- addField(cfe);
-
- cfe = new ColorFieldEditor(LogCatPanel.ERROR_COLOR_PREFKEY, "Error Log Message Color",
- getFieldEditorParent());
- addField(cfe);
-
- cfe = new ColorFieldEditor(LogCatPanel.ASSERT_COLOR_PREFKEY, "Assert Log Message Color",
- getFieldEditorParent());
- addField(cfe);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/preferences/LogCatPreferencePage.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/preferences/LogCatPreferencePage.java
deleted file mode 100644
index aa88eecb7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/preferences/LogCatPreferencePage.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.preferences;
-
-import com.android.ddmlib.Log.LogLevel;
-import com.android.ddmuilib.logcat.LogCatMessageList;
-import com.android.ddmuilib.logcat.LogCatPanel;
-import com.android.ide.eclipse.base.InstallDetails;
-import com.android.ide.eclipse.ddms.DdmsPlugin;
-import com.android.ide.eclipse.ddms.LogCatMonitor;
-import com.android.ide.eclipse.ddms.i18n.Messages;
-
-import org.eclipse.jface.preference.BooleanFieldEditor;
-import org.eclipse.jface.preference.ComboFieldEditor;
-import org.eclipse.jface.preference.FieldEditorPreferencePage;
-import org.eclipse.jface.preference.FontFieldEditor;
-import org.eclipse.jface.preference.IntegerFieldEditor;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.ui.IPerspectiveDescriptor;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-import org.eclipse.ui.PlatformUI;
-
-/**
- * Preference Pane for LogCat.
- */
-public class LogCatPreferencePage extends FieldEditorPreferencePage implements
- IWorkbenchPreferencePage {
- private BooleanFieldEditor mSwitchPerspective;
- private ComboFieldEditor mWhichPerspective;
- private IntegerFieldEditor mMaxMessages;
- private BooleanFieldEditor mAutoMonitorLogcat;
- private ComboFieldEditor mAutoMonitorLogcatLevel;
- private BooleanFieldEditor mAutoScrollLock;
-
- public LogCatPreferencePage() {
- super(GRID);
- setPreferenceStore(DdmsPlugin.getDefault().getPreferenceStore());
- }
-
- @Override
- protected void createFieldEditors() {
- FontFieldEditor ffe = new FontFieldEditor(LogCatPanel.LOGCAT_VIEW_FONT_PREFKEY,
- Messages.LogCatPreferencePage_Display_Font, getFieldEditorParent());
- addField(ffe);
-
- mMaxMessages = new IntegerFieldEditor(
- LogCatMessageList.MAX_MESSAGES_PREFKEY,
- Messages.LogCatPreferencePage_MaxMessages, getFieldEditorParent());
- addField(mMaxMessages);
-
- mAutoScrollLock = new BooleanFieldEditor(LogCatPanel.AUTO_SCROLL_LOCK_PREFKEY,
- "Automatically enable/disable scroll lock based on the scrollbar position",
- getFieldEditorParent());
- addField(mAutoScrollLock);
-
- createHorizontalSeparator();
-
- if (InstallDetails.isAdtInstalled()) {
- createAdtSpecificFieldEditors();
- }
- }
-
- private void createHorizontalSeparator() {
- Label l = new Label(getFieldEditorParent(), SWT.SEPARATOR | SWT.HORIZONTAL);
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan = 3;
- l.setLayoutData(gd);
- }
-
- private void createAdtSpecificFieldEditors() {
- mSwitchPerspective = new BooleanFieldEditor(PreferenceInitializer.ATTR_SWITCH_PERSPECTIVE,
- Messages.LogCatPreferencePage_Switch_Perspective, getFieldEditorParent());
- addField(mSwitchPerspective);
- IPerspectiveDescriptor[] perspectiveDescriptors =
- PlatformUI.getWorkbench().getPerspectiveRegistry().getPerspectives();
- String[][] perspectives = new String[0][0];
- if (perspectiveDescriptors.length > 0) {
- perspectives = new String[perspectiveDescriptors.length][2];
- for (int i = 0; i < perspectiveDescriptors.length; i++) {
- IPerspectiveDescriptor perspective = perspectiveDescriptors[i];
- perspectives[i][0] = perspective.getLabel();
- perspectives[i][1] = perspective.getId();
- }
- }
- mWhichPerspective = new ComboFieldEditor(PreferenceInitializer.ATTR_PERSPECTIVE_ID,
- Messages.LogCatPreferencePage_Switch_To, perspectives, getFieldEditorParent());
- mWhichPerspective.setEnabled(getPreferenceStore()
- .getBoolean(PreferenceInitializer.ATTR_SWITCH_PERSPECTIVE), getFieldEditorParent());
- addField(mWhichPerspective);
-
- createHorizontalSeparator();
-
- mAutoMonitorLogcat = new BooleanFieldEditor(LogCatMonitor.AUTO_MONITOR_PREFKEY,
- Messages.LogCatPreferencePage_AutoMonitorLogcat,
- getFieldEditorParent());
- addField(mAutoMonitorLogcat);
-
- mAutoMonitorLogcatLevel = new ComboFieldEditor(LogCatMonitor.AUTO_MONITOR_LOGLEVEL,
- Messages.LogCatPreferencePage_SessionFilterLogLevel,
- new String[][] {
- { LogLevel.VERBOSE.toString(), LogLevel.VERBOSE.getStringValue() },
- { LogLevel.DEBUG.toString(), LogLevel.DEBUG.getStringValue() },
- { LogLevel.INFO.toString(), LogLevel.INFO.getStringValue() },
- { LogLevel.WARN.toString(), LogLevel.WARN.getStringValue() },
- { LogLevel.ERROR.toString(), LogLevel.ERROR.getStringValue() },
- { LogLevel.ASSERT.toString(), LogLevel.ASSERT.getStringValue() },
- },
- getFieldEditorParent());
- mAutoMonitorLogcatLevel.setEnabled(
- getPreferenceStore().getBoolean(LogCatMonitor.AUTO_MONITOR_PREFKEY),
- getFieldEditorParent());
- addField(mAutoMonitorLogcatLevel);
- }
-
- @Override
- public void init(IWorkbench workbench) {
- }
-
- @Override
- public void propertyChange(PropertyChangeEvent event) {
- if (event.getSource().equals(mSwitchPerspective)) {
- mWhichPerspective.setEnabled(mSwitchPerspective.getBooleanValue(),
- getFieldEditorParent());
- } else if (event.getSource().equals(mAutoMonitorLogcat)) {
- mAutoMonitorLogcatLevel.setEnabled(mAutoMonitorLogcat.getBooleanValue(),
- getFieldEditorParent());
- }
- }
-
- @Override
- protected void performDefaults() {
- super.performDefaults();
- mWhichPerspective.setEnabled(mSwitchPerspective.getBooleanValue(), getFieldEditorParent());
-
- mMaxMessages.setStringValue(
- Integer.toString(LogCatMessageList.MAX_MESSAGES_DEFAULT));
-
- mAutoMonitorLogcatLevel.setEnabled(mAutoMonitorLogcat.getBooleanValue(),
- getFieldEditorParent());
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/preferences/PreferenceInitializer.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/preferences/PreferenceInitializer.java
deleted file mode 100644
index 254b2c58a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/preferences/PreferenceInitializer.java
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.preferences;
-
-import com.android.ddmlib.DdmPreferences;
-import com.android.ddmlib.Log.LogLevel;
-import com.android.ddmuilib.DdmUiPreferences;
-import com.android.ide.eclipse.ddms.DdmsPlugin;
-import com.android.ide.eclipse.ddms.LogCatMonitor;
-import com.android.ide.eclipse.ddms.views.DeviceView.HProfHandler;
-import com.android.ide.eclipse.ddms.views.LogCatView;
-
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.content.IContentType;
-import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.FontData;
-
-/**
- * Class used to initialize default preference values.
- */
-public class PreferenceInitializer extends AbstractPreferenceInitializer {
-
- public final static String ATTR_LOG_LEVEL =
- DdmsPlugin.PLUGIN_ID + ".logLevel"; //$NON-NLS-1$
-
- public final static String ATTR_DEBUG_PORT_BASE =
- DdmsPlugin.PLUGIN_ID + ".adbDebugBasePort"; //$NON-NLS-1$
-
- public final static String ATTR_SELECTED_DEBUG_PORT =
- DdmsPlugin.PLUGIN_ID + ".debugSelectedPort"; //$NON-NLS-1$
-
- public final static String ATTR_DEFAULT_THREAD_UPDATE =
- DdmsPlugin.PLUGIN_ID + ".defaultThreadUpdateEnabled"; //$NON-NLS-1$
-
- public final static String ATTR_DEFAULT_HEAP_UPDATE =
- DdmsPlugin.PLUGIN_ID + ".defaultHeapUpdateEnabled"; //$NON-NLS-1$
-
- public final static String ATTR_THREAD_INTERVAL =
- DdmsPlugin.PLUGIN_ID + ".threadStatusInterval"; //$NON-NLS-1$
-
- public final static String ATTR_IMAGE_SAVE_DIR =
- DdmsPlugin.PLUGIN_ID + ".imageSaveDir"; //$NON-NLS-1$
-
- public final static String ATTR_LAST_IMAGE_SAVE_DIR =
- DdmsPlugin.PLUGIN_ID + ".lastImageSaveDir"; //$NON-NLS-1$
-
- public final static String ATTR_LOGCAT_FONT =
- DdmsPlugin.PLUGIN_ID + ".logcatFont"; //$NON-NLS-1$
-
- public final static String ATTR_HPROF_ACTION =
- DdmsPlugin.PLUGIN_ID + ".hprofAction"; //$NON-NLS-1$
-
- public final static String ATTR_TIME_OUT =
- DdmsPlugin.PLUGIN_ID + ".timeOut"; //$NON-NLS-1$
-
- public final static String ATTR_USE_ADBHOST =
- DdmsPlugin.PLUGIN_ID + ".useAdbHost"; //$NON-NLS-1$
-
- public final static String ATTR_ADBHOST_VALUE =
- DdmsPlugin.PLUGIN_ID + ".adbHostValue"; //$NON-NLS-1$
-
- public final static String ATTR_SWITCH_PERSPECTIVE =
- DdmsPlugin.PLUGIN_ID + ".switchPerspective"; //$NON-NLS-1$
-
- public final static String ATTR_PERSPECTIVE_ID =
- DdmsPlugin.PLUGIN_ID + ".perspectiveId"; //$NON-NLS-1$
-
- public static final String ATTR_PROFILER_BUFSIZE_MB =
- DdmsPlugin.PLUGIN_ID + ".profilerBufferSizeMb"; //$NON-NLS-1$
-
- /*
- * (non-Javadoc)
- *
- * @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer
- * #initializeDefaultPreferences()
- */
- @Override
- public void initializeDefaultPreferences() {
- IPreferenceStore store = DdmsPlugin.getDefault().getPreferenceStore();
-
- store.setDefault(ATTR_DEBUG_PORT_BASE, DdmPreferences.DEFAULT_DEBUG_PORT_BASE);
-
- store.setDefault(ATTR_SELECTED_DEBUG_PORT, DdmPreferences.DEFAULT_SELECTED_DEBUG_PORT);
-
- store.setDefault(ATTR_DEFAULT_THREAD_UPDATE, DdmPreferences.DEFAULT_INITIAL_THREAD_UPDATE);
- store.setDefault(ATTR_DEFAULT_HEAP_UPDATE,
- DdmPreferences.DEFAULT_INITIAL_HEAP_UPDATE);
-
- store.setDefault(ATTR_PROFILER_BUFSIZE_MB, DdmPreferences.DEFAULT_PROFILER_BUFFER_SIZE_MB);
-
- store.setDefault(ATTR_THREAD_INTERVAL, DdmUiPreferences.DEFAULT_THREAD_REFRESH_INTERVAL);
-
- String homeDir = System.getProperty("user.home"); //$NON-NLS-1$
- store.setDefault(ATTR_IMAGE_SAVE_DIR, homeDir);
-
- store.setDefault(ATTR_LOG_LEVEL, DdmPreferences.DEFAULT_LOG_LEVEL.getStringValue());
-
- store.setDefault(ATTR_LOGCAT_FONT,
- new FontData("Courier", 10, SWT.NORMAL).toString()); //$NON-NLS-1$
-
- // When obtaining hprof files from the device, default to opening the file
- // only if there is a registered content type for the hprof extension.
- store.setDefault(ATTR_HPROF_ACTION, HProfHandler.ACTION_SAVE);
- for (IContentType contentType: Platform.getContentTypeManager().getAllContentTypes()) {
- if (contentType.isAssociatedWith(HProfHandler.DOT_HPROF)) {
- store.setDefault(ATTR_HPROF_ACTION, HProfHandler.ACTION_OPEN);
- break;
- }
- }
-
- store.setDefault(ATTR_TIME_OUT, DdmPreferences.DEFAULT_TIMEOUT);
-
- store.setDefault(ATTR_USE_ADBHOST, DdmPreferences.DEFAULT_USE_ADBHOST);
- store.setDefault(ATTR_ADBHOST_VALUE, DdmPreferences.DEFAULT_ADBHOST_VALUE);
- store.setDefault(ATTR_SWITCH_PERSPECTIVE, LogCatView.DEFAULT_SWITCH_PERSPECTIVE);
- store.setDefault(ATTR_PERSPECTIVE_ID, LogCatView.DEFAULT_PERSPECTIVE_ID);
-
- store.setDefault(LogCatMonitor.AUTO_MONITOR_PREFKEY, true);
- store.setDefault(LogCatMonitor.AUTO_MONITOR_LOGLEVEL, LogLevel.VERBOSE.getStringValue());
- }
-
- /**
- * Initializes the preferences of ddmlib and ddmuilib with values from the eclipse store.
- */
- public synchronized static void setupPreferences() {
- IPreferenceStore store = DdmsPlugin.getDefault().getPreferenceStore();
-
- DdmPreferences.setDebugPortBase(store.getInt(ATTR_DEBUG_PORT_BASE));
- DdmPreferences.setSelectedDebugPort(store.getInt(ATTR_SELECTED_DEBUG_PORT));
- DdmPreferences.setLogLevel(store.getString(ATTR_LOG_LEVEL));
- DdmPreferences.setInitialThreadUpdate(store.getBoolean(ATTR_DEFAULT_THREAD_UPDATE));
- DdmPreferences.setInitialHeapUpdate(store.getBoolean(ATTR_DEFAULT_HEAP_UPDATE));
- DdmPreferences.setProfilerBufferSizeMb(store.getInt(ATTR_PROFILER_BUFSIZE_MB));
- DdmUiPreferences.setThreadRefreshInterval(store.getInt(ATTR_THREAD_INTERVAL));
- DdmPreferences.setTimeOut(store.getInt(ATTR_TIME_OUT));
- DdmPreferences.setUseAdbHost(store.getBoolean(ATTR_USE_ADBHOST));
- DdmPreferences.setAdbHostValue(store.getString(ATTR_ADBHOST_VALUE));
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/preferences/PreferencePage.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/preferences/PreferencePage.java
deleted file mode 100644
index 56af601e5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/preferences/PreferencePage.java
+++ /dev/null
@@ -1,152 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.preferences;
-
-import com.android.ddmlib.DdmPreferences;
-import com.android.ddmlib.Log.LogLevel;
-import com.android.ide.eclipse.base.InstallDetails;
-import com.android.ide.eclipse.ddms.DdmsPlugin;
-import com.android.ide.eclipse.ddms.i18n.Messages;
-import com.android.ide.eclipse.ddms.views.DeviceView.HProfHandler;
-
-import org.eclipse.jface.preference.BooleanFieldEditor;
-import org.eclipse.jface.preference.ComboFieldEditor;
-import org.eclipse.jface.preference.FieldEditorPreferencePage;
-import org.eclipse.jface.preference.IntegerFieldEditor;
-import org.eclipse.jface.preference.RadioGroupFieldEditor;
-import org.eclipse.jface.preference.StringFieldEditor;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-
-public class PreferencePage extends FieldEditorPreferencePage implements
- IWorkbenchPreferencePage {
-
- private BooleanFieldEditor mUseAdbHost;
- private StringFieldEditor mAdbHostValue;
- private IntegerFieldEditor mProfilerBufsize;
-
- public PreferencePage() {
- super(GRID);
- setPreferenceStore(DdmsPlugin.getDefault().getPreferenceStore());
- }
-
- /**
- * Creates the field editors. Field editors are abstractions of the common
- * GUI blocks needed to manipulate various types of preferences. Each field
- * editor knows how to save and restore itself.
- */
- @Override
- public void createFieldEditors() {
- IntegerFieldEditor ife;
-
- ife = new IntegerFieldEditor(PreferenceInitializer.ATTR_DEBUG_PORT_BASE,
- Messages.PreferencePage_Base_Local_Debugger_Port, getFieldEditorParent());
- ife.setValidRange(1024, 32767);
- addField(ife);
-
- BooleanFieldEditor bfe;
-
- bfe = new BooleanFieldEditor(PreferenceInitializer.ATTR_DEFAULT_THREAD_UPDATE,
- Messages.PreferencePage_Thread_Updates_Enabled_By_Default, getFieldEditorParent());
- addField(bfe);
-
- bfe = new BooleanFieldEditor(PreferenceInitializer.ATTR_DEFAULT_HEAP_UPDATE,
- Messages.PreferencePage_Heap_Updates_Enabled_Default, getFieldEditorParent());
- addField(bfe);
-
- ife = new IntegerFieldEditor(PreferenceInitializer.ATTR_THREAD_INTERVAL,
- Messages.PreferencePage_Thread_Status_Refresh_Interval, getFieldEditorParent());
- ife.setValidRange(1, 60);
- addField(ife);
-
- if (InstallDetails.isAdtInstalled()) {
- ComboFieldEditor cfe = new ComboFieldEditor(PreferenceInitializer.ATTR_HPROF_ACTION,
- Messages.PreferencePage_HPROF_Action, new String[][] {
- {
- Messages.PreferencePage_Save_Disk, HProfHandler.ACTION_SAVE
- },
- {
- Messages.PreferencePage_Open_Eclipse, HProfHandler.ACTION_OPEN
- },
- }, getFieldEditorParent());
- addField(cfe);
- }
-
- mProfilerBufsize = new IntegerFieldEditor(PreferenceInitializer.ATTR_PROFILER_BUFSIZE_MB,
- "Method Profiler buffer size (MB):",
- getFieldEditorParent());
- addField(mProfilerBufsize);
-
- ife = new IntegerFieldEditor(PreferenceInitializer.ATTR_TIME_OUT,
- Messages.PreferencePage_ADB_Connection_Time_Out, getFieldEditorParent());
- addField(ife);
-
- RadioGroupFieldEditor rgfe = new RadioGroupFieldEditor(
- PreferenceInitializer.ATTR_LOG_LEVEL,
- Messages.PreferencePage_Logging_Level, 1, new String[][] {
- {
- Messages.PreferencePage_Verbose, LogLevel.VERBOSE.getStringValue()
- },
- {
- Messages.PreferencePage_Debug, LogLevel.DEBUG.getStringValue()
- },
- {
- Messages.PreferencePage_Info, LogLevel.INFO.getStringValue()
- },
- {
- Messages.PreferencePage_Warning, LogLevel.WARN.getStringValue()
- },
- {
- Messages.PreferencePage_Error, LogLevel.ERROR.getStringValue()
- },
- {
- Messages.PreferencePage_Assert, LogLevel.ASSERT.getStringValue()
- }
- },
- getFieldEditorParent(), true);
- addField(rgfe);
- mUseAdbHost = new BooleanFieldEditor(PreferenceInitializer.ATTR_USE_ADBHOST,
- Messages.PreferencePage_Use_Adbhost, getFieldEditorParent());
- addField(mUseAdbHost);
- mAdbHostValue = new StringFieldEditor(PreferenceInitializer.ATTR_ADBHOST_VALUE,
- Messages.PreferencePage_Adbhost_value, getFieldEditorParent());
- mAdbHostValue.setEnabled(getPreferenceStore()
- .getBoolean(PreferenceInitializer.ATTR_USE_ADBHOST), getFieldEditorParent());
- addField(mAdbHostValue);
- }
-
- @Override
- public void init(IWorkbench workbench) {
- }
-
- @Override
- public void propertyChange(PropertyChangeEvent event) {
- if (event.getSource().equals(mUseAdbHost)) {
- mAdbHostValue.setEnabled(mUseAdbHost.getBooleanValue(), getFieldEditorParent());
- } else if (event.getSource().equals(mProfilerBufsize)) {
- DdmPreferences.setProfilerBufferSizeMb(mProfilerBufsize.getIntValue());
- }
- super.propertyChange(event);
- }
-
- @Override
- protected void performDefaults() {
- super.performDefaults();
- mAdbHostValue.setEnabled(mUseAdbHost.getBooleanValue(), getFieldEditorParent());
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/ISystraceOptions.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/ISystraceOptions.java
deleted file mode 100644
index f0e080421..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/ISystraceOptions.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.systrace;
-
-public interface ISystraceOptions {
- /** Get tags to enable, returns null if no tags need to be enabled. */
- String getTags();
-
- /** Get the command line options to atrace. */
- String getOptions();
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/ISystraceOptionsDialog.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/ISystraceOptionsDialog.java
deleted file mode 100644
index 4cc0faa59..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/ISystraceOptionsDialog.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.systrace;
-
-public interface ISystraceOptionsDialog {
- ISystraceOptions getSystraceOptions();
- String getTraceFilePath();
- int open();
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/SystraceOptionsDialogV1.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/SystraceOptionsDialogV1.java
deleted file mode 100644
index b462ada29..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/SystraceOptionsDialogV1.java
+++ /dev/null
@@ -1,445 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.systrace;
-
-import org.eclipse.jface.dialogs.TitleAreaDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-
-import java.io.File;
-
-public class SystraceOptionsDialogV1 extends TitleAreaDialog implements ISystraceOptionsDialog {
- private static final String TITLE = "Android System Trace";
- private static final String DEFAULT_MESSAGE =
- "Settings to use while capturing system level trace";
- private static final String DEFAULT_TRACE_FNAME = "trace.html"; //$NON-NLS-1$
-
- private Text mDestinationText;
- private String mDestinationPath;
- private Text mTraceDurationText;
- private Text mTraceBufferSizeText;
-
- private static String sSaveToFolder = System.getProperty("user.home"); //$NON-NLS-1$
- private static String sTraceDuration = "";
- private static String sTraceBufferSize = "";
-
- private Button mTraceCpuFreqBtn;
- private Button mTraceCpuIdleBtn;
- private Button mTraceCpuLoadBtn;
- private Button mTraceDiskIoBtn;
- private Button mTraceKernelWorkqueuesBtn;
- private Button mTraceCpuSchedulerBtn;
-
- private static boolean sTraceCpuFreq;
- private static boolean sTraceCpuIdle;
- private static boolean sTraceCpuLoad;
- private static boolean sTraceDiskIo;
- private static boolean sTraceKernelWorkqueues;
- private static boolean sTraceCpuScheduler;
-
- private Button mGfxTagBtn;
- private Button mInputTagBtn;
- private Button mViewTagBtn;
- private Button mWebViewTagBtn;
- private Button mWmTagBtn;
- private Button mAmTagBtn;
- private Button mSyncTagBtn;
- private Button mAudioTagBtn;
- private Button mVideoTagBtn;
- private Button mCameraTagBtn;
-
- private static boolean sGfxTag;
- private static boolean sInputTag;
- private static boolean sViewTag;
- private static boolean sWebViewTag;
- private static boolean sWmTag;
- private static boolean sAmTag;
- private static boolean sSyncTag;
- private static boolean sAudioTag;
- private static boolean sVideoTag;
- private static boolean sCameraTag;
-
- private final SystraceOptions mOptions = new SystraceOptions();
-
- public SystraceOptionsDialogV1(Shell parentShell) {
- super(parentShell);
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- setTitle(TITLE);
- setMessage(DEFAULT_MESSAGE);
-
- Composite c = new Composite(parent, SWT.BORDER);
- c.setLayout(new GridLayout(3, false));
- c.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- Label l = new Label(c, SWT.NONE);
- l.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- l.setText("Destination File: ");
-
- mDestinationText = new Text(c, SWT.BORDER);
- mDestinationText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- mDestinationText.setText(sSaveToFolder + File.separator + DEFAULT_TRACE_FNAME);
-
- final Button browse = new Button(c, SWT.NONE);
- browse.setText("Browse...");
- browse.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- String path = openBrowseDialog(browse.getShell());
- if (path != null) mDestinationText.setText(path);
- }
- });
-
- Label lblTraceDurationseconds = new Label(c, SWT.NONE);
- lblTraceDurationseconds.setLayoutData(
- new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- lblTraceDurationseconds.setText("Trace duration (seconds): ");
-
- mTraceDurationText = new Text(c, SWT.BORDER);
- mTraceDurationText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
- mTraceDurationText.setText(sTraceDuration);
-
- Label lblTraceBufferSize = new Label(c, SWT.NONE);
- lblTraceBufferSize.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- lblTraceBufferSize.setText("Trace Buffer Size (kb): ");
-
- mTraceBufferSizeText = new Text(c, SWT.BORDER);
- mTraceBufferSizeText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
- mTraceBufferSizeText.setText(sTraceBufferSize);
-
- Label separator = new Label(c, SWT.SEPARATOR | SWT.HORIZONTAL);
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan = 3;
- separator.setLayoutData(gd);
-
- Group grpTraceEvents = new Group(c, SWT.BORDER);
- grpTraceEvents.setLayout(new GridLayout(3, false));
- grpTraceEvents.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 2, 1));
- grpTraceEvents.setText("Trace Events");
-
- mTraceCpuFreqBtn = new Button(grpTraceEvents, SWT.CHECK);
- mTraceCpuFreqBtn.setText("CPU Frequency Changes");
- mTraceCpuFreqBtn.setSelection(sTraceCpuFreq);
-
- mTraceCpuIdleBtn = new Button(grpTraceEvents, SWT.CHECK);
- mTraceCpuIdleBtn.setText("CPU Idle Events");
- mTraceCpuIdleBtn.setSelection(sTraceCpuIdle);
-
- mTraceCpuLoadBtn = new Button(grpTraceEvents, SWT.CHECK);
- mTraceCpuLoadBtn.setText("CPU Load");
- mTraceCpuLoadBtn.setSelection(sTraceCpuLoad);
-
- mTraceCpuSchedulerBtn = new Button(grpTraceEvents, SWT.CHECK);
- mTraceCpuSchedulerBtn.setText("CPU Scheduler");
- mTraceCpuSchedulerBtn.setSelection(sTraceCpuScheduler);
-
- Group grpTraceRootEvents = new Group(c, SWT.BORDER);
- grpTraceRootEvents.setLayout(new GridLayout(2, false));
- grpTraceRootEvents.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 2, 1));
- grpTraceRootEvents.setText("Trace Events that require root privileges on device");
-
- mTraceDiskIoBtn = new Button(grpTraceRootEvents, SWT.CHECK);
- mTraceDiskIoBtn.setText("Disk I/O");
- mTraceDiskIoBtn.setSelection(sTraceDiskIo);
-
- mTraceKernelWorkqueuesBtn = new Button(grpTraceRootEvents, SWT.CHECK);
- mTraceKernelWorkqueuesBtn.setText("Kernel Workqueues (requires root)");
- mTraceKernelWorkqueuesBtn.setSelection(sTraceKernelWorkqueues);
-
- Group grpTraceTags = new Group(c, SWT.BORDER);
- grpTraceTags.setLayout(new GridLayout(5, false));
- grpTraceTags.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 3, 1));
- grpTraceTags.setText("Trace Tags");
-
- mGfxTagBtn = new Button(grpTraceTags, SWT.CHECK);
- mGfxTagBtn.setText("gfx");
- mGfxTagBtn.setSelection(sGfxTag);
-
- mInputTagBtn = new Button(grpTraceTags, SWT.CHECK);
- mInputTagBtn.setText("input");
- mInputTagBtn.setSelection(sInputTag);
-
- mViewTagBtn = new Button(grpTraceTags, SWT.CHECK);
- mViewTagBtn.setText("view");
- mViewTagBtn.setSelection(sViewTag);
-
- mWebViewTagBtn = new Button(grpTraceTags, SWT.CHECK);
- mWebViewTagBtn.setText("webview");
- mWebViewTagBtn.setSelection(sWebViewTag);
-
- mWmTagBtn = new Button(grpTraceTags, SWT.CHECK);
- mWmTagBtn.setText("wm");
- mWmTagBtn.setSelection(sWmTag);
-
- mAmTagBtn = new Button(grpTraceTags, SWT.CHECK);
- mAmTagBtn.setText("am");
- mAmTagBtn.setSelection(sAmTag);
-
- mSyncTagBtn = new Button(grpTraceTags, SWT.CHECK);
- mSyncTagBtn.setText("sync");
- mSyncTagBtn.setSelection(sSyncTag);
-
- mAudioTagBtn = new Button(grpTraceTags, SWT.CHECK);
- mAudioTagBtn.setText("audio");
- mAudioTagBtn.setSelection(sAudioTag);
-
- mVideoTagBtn = new Button(grpTraceTags, SWT.CHECK);
- mVideoTagBtn.setText("video");
- mVideoTagBtn.setSelection(sVideoTag);
-
- mCameraTagBtn = new Button(grpTraceTags, SWT.CHECK);
- mCameraTagBtn.setText("camera");
- mCameraTagBtn.setSelection(sCameraTag);
-
- Label lblTraceTagsWarning = new Label(grpTraceTags, SWT.NONE);
- lblTraceTagsWarning.setText(
- "Changes to trace tags will likely need a restart of the Android framework to take effect:\n"
- + " $ adb shell stop\n"
- + " $ adb shell start");
- lblTraceTagsWarning.setLayoutData(new GridData(SWT.LEFT, SWT.CENTER, true, false, 5, 1));
-
- ModifyListener m = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- validateFields();
- }
- };
-
- mDestinationText.addModifyListener(m);
- mTraceBufferSizeText.addModifyListener(m);
- mTraceDurationText.addModifyListener(m);
-
- return c;
- }
-
- private void validateFields() {
- // validate trace destination path
- String msg = validatePath(mDestinationText.getText());
- if (msg != null) {
- setErrorMessage(msg);
- getButton(OK).setEnabled(false);
- return;
- }
-
- // validate the trace duration
- if (!validateInteger(mTraceDurationText.getText())) {
- setErrorMessage("Trace Duration should be a valid integer (seconds)");
- getButton(OK).setEnabled(false);
- return;
- }
-
- // validate the trace buffer size
- if (!validateInteger(mTraceBufferSizeText.getText())) {
- setErrorMessage("Trace Buffer Size should be a valid integer (kilobytes)");
- getButton(OK).setEnabled(false);
- return;
- }
-
- getButton(OK).setEnabled(true);
- setErrorMessage(null);
- }
-
- private boolean validateInteger(String text) {
- if (text == null || text.isEmpty()) {
- return true;
- }
-
- try {
- Integer.parseInt(text);
- return true;
- } catch (NumberFormatException e) {
- return false;
- }
- }
-
- private String validatePath(String path) {
- if (path == null || path.isEmpty()) {
- return null;
- }
-
- File f = new File(path);
- if (f.isDirectory()) {
- return String.format("The path '%s' points to a folder", path);
- }
-
- if (!f.exists()) { // if such a file doesn't exist, make sure the parent folder is valid
- if (!f.getParentFile().isDirectory()) {
- return String.format("That path '%s' is not a valid folder.", f.getParent());
- }
- }
-
- return null;
- }
-
- private String openBrowseDialog(Shell parentShell) {
- FileDialog fd = new FileDialog(parentShell, SWT.SAVE);
-
- fd.setText("Save To");
- fd.setFileName(DEFAULT_TRACE_FNAME);
-
- fd.setFilterPath(sSaveToFolder);
- fd.setFilterExtensions(new String[] { "*.html" }); //$NON-NLS-1$
-
- String fname = fd.open();
- if (fname == null || fname.trim().length() == 0) {
- return null;
- }
-
- sSaveToFolder = fd.getFilterPath();
- return fname;
- }
-
- @Override
- protected void okPressed() {
- mDestinationPath = mDestinationText.getText().trim();
-
- sTraceDuration = mTraceDurationText.getText();
- if (!sTraceDuration.isEmpty()) {
- mOptions.mTraceDuration = Integer.parseInt(sTraceDuration);
- }
-
- sTraceBufferSize = mTraceBufferSizeText.getText();
- if (!sTraceBufferSize.isEmpty()) {
- mOptions.mTraceBufferSize = Integer.parseInt(sTraceBufferSize);
- }
-
- mOptions.mTraceCpuFreq = mTraceCpuFreqBtn.getSelection();
- mOptions.mTraceCpuIdle = mTraceCpuIdleBtn.getSelection();
- mOptions.mTraceCpuLoad = mTraceCpuLoadBtn.getSelection();
- mOptions.mTraceDiskIo = mTraceDiskIoBtn.getSelection();
- mOptions.mTraceKernelWorkqueues = mTraceKernelWorkqueuesBtn.getSelection();
- mOptions.mTraceCpuScheduler = mTraceCpuSchedulerBtn.getSelection();
-
- if (mGfxTagBtn.getSelection()) mOptions.enableTag(SystraceOptions.TAG_GFX);
- if (mInputTagBtn.getSelection()) mOptions.enableTag(SystraceOptions.TAG_INPUT);
- if (mViewTagBtn.getSelection()) mOptions.enableTag(SystraceOptions.TAG_VIEW);
- if (mWebViewTagBtn.getSelection()) mOptions.enableTag(SystraceOptions.TAG_WEBVIEW);
- if (mWmTagBtn.getSelection()) mOptions.enableTag(SystraceOptions.TAG_WM);
- if (mAmTagBtn.getSelection()) mOptions.enableTag(SystraceOptions.TAG_AM);
- if (mSyncTagBtn.getSelection()) mOptions.enableTag(SystraceOptions.TAG_SYNC);
- if (mAudioTagBtn.getSelection()) mOptions.enableTag(SystraceOptions.TAG_AUDIO);
- if (mVideoTagBtn.getSelection()) mOptions.enableTag(SystraceOptions.TAG_VIDEO);
- if (mCameraTagBtn.getSelection()) mOptions.enableTag(SystraceOptions.TAG_CAMERA);
-
- // save current selections to be restored if the dialog is invoked again
- sTraceCpuFreq = mTraceCpuFreqBtn.getSelection();
- sTraceCpuIdle = mTraceCpuIdleBtn.getSelection();
- sTraceCpuLoad = mTraceCpuLoadBtn.getSelection();
- sTraceDiskIo = mTraceDiskIoBtn.getSelection();
- sTraceKernelWorkqueues = mTraceKernelWorkqueuesBtn.getSelection();
- sTraceCpuScheduler = mTraceCpuSchedulerBtn.getSelection();
-
- sGfxTag = mGfxTagBtn.getSelection();
- sInputTag = mInputTagBtn.getSelection();
- sViewTag = mViewTagBtn.getSelection();
- sWebViewTag = mWebViewTagBtn.getSelection();
- sWmTag = mWmTagBtn.getSelection();
- sAmTag = mAmTagBtn.getSelection();
- sSyncTag = mSyncTagBtn.getSelection();
- sAudioTag = mAudioTagBtn.getSelection();
- sVideoTag = mVideoTagBtn.getSelection();
- sCameraTag = mCameraTagBtn.getSelection();
-
- super.okPressed();
- }
-
- @Override
- public SystraceOptions getSystraceOptions() {
- return mOptions;
- }
-
- @Override
- public String getTraceFilePath() {
- return mDestinationPath;
- }
-
- private class SystraceOptions implements ISystraceOptions {
- // This list is based on the tags in frameworks/native/include/utils/Trace.h
- private static final int TAG_GFX = 1 << 1;
- private static final int TAG_INPUT = 1 << 2;
- private static final int TAG_VIEW = 1 << 3;
- private static final int TAG_WEBVIEW = 1 << 4;
- private static final int TAG_WM = 1 << 5;
- private static final int TAG_AM = 1 << 6;
- private static final int TAG_SYNC = 1 << 7;
- private static final int TAG_AUDIO = 1 << 8;
- private static final int TAG_VIDEO = 1 << 9;
- private static final int TAG_CAMERA = 1 << 10;
-
- private int mTraceBufferSize;
- private int mTraceDuration;
-
- private boolean mTraceCpuFreq;
- private boolean mTraceCpuIdle;
- private boolean mTraceCpuLoad;
- private boolean mTraceDiskIo;
- private boolean mTraceKernelWorkqueues;
- private boolean mTraceCpuScheduler;
-
- private int mTag;
-
- private void enableTag(int tag) {
- mTag |= tag;
- }
-
- @Override
- public String getTags() {
- return mTag == 0 ? null : "0x" + Integer.toHexString(mTag);
- }
-
- @Override
- public String getOptions() {
- StringBuilder sb = new StringBuilder(20);
-
- if (mTraceCpuFreq) sb.append("-f "); //$NON-NLS-1$
- if (mTraceCpuIdle) sb.append("-i "); //$NON-NLS-1$
- if (mTraceCpuLoad) sb.append("-l "); //$NON-NLS-1$
- if (mTraceDiskIo) sb.append("-d "); //$NON-NLS-1$
- if (mTraceKernelWorkqueues) sb.append("-w "); //$NON-NLS-1$
- if (mTraceCpuScheduler) sb.append("-s "); //$NON-NLS-1$
-
- if (mTraceDuration > 0) {
- sb.append("-t"); //$NON-NLS-1$
- sb.append(mTraceDuration);
- sb.append(' ');
- }
-
- if (mTraceBufferSize > 0) {
- sb.append("-b "); //$NON-NLS-1$
- sb.append(mTraceBufferSize);
- sb.append(' ');
- }
-
- return sb.toString().trim();
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/SystraceOptionsDialogV2.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/SystraceOptionsDialogV2.java
deleted file mode 100644
index e28edd389..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/SystraceOptionsDialogV2.java
+++ /dev/null
@@ -1,369 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.systrace;
-
-import com.android.ddmuilib.TableHelper;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-
-import org.eclipse.jface.dialogs.TitleAreaDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableItem;
-import org.eclipse.swt.widgets.Text;
-
-import java.io.File;
-import java.util.List;
-import java.util.Set;
-
-public class SystraceOptionsDialogV2 extends TitleAreaDialog implements ISystraceOptionsDialog {
- private static final String TITLE = "Systrace (Android System Trace)";
- private static final String DEFAULT_MESSAGE =
- "Settings to use while capturing system level trace";
- private static final String DEFAULT_TRACE_FNAME = "trace.html"; //$NON-NLS-1$
- private static final Set<String> sCommonTags = ImmutableSet.of(
- "am", "app", "dalvik", "disk", "gfx", "input", "res", "sched", "view", "webview", "wm");
-
- private Text mDestinationText;
- private String mDestinationPath;
- private Text mTraceDurationText;
- private Text mTraceBufferSizeText;
- private Combo mTraceAppCombo;
-
- private static String sSaveToFolder = System.getProperty("user.home"); //$NON-NLS-1$
- private static String sTraceDuration = "5";
- private static String sTraceBufferSize = "2048";
- private static Set<String> sEnabledTags = Sets.newHashSet(sCommonTags);
- private static String sLastSelectedApp = null;
-
- private final List<SystraceTag> mCommonSupportedTags;
- private final List<SystraceTag> mAdvancedSupportedTags;
-
- private final List<String> mCurrentApps;
-
- private final SystraceOptions mOptions = new SystraceOptions();
- private Table mCommonTagsTable;
- private Table mAdvancedTagsTable;
-
- public SystraceOptionsDialogV2(Shell parentShell, List<SystraceTag> tags, List<String> apps) {
- super(parentShell);
- mCurrentApps = apps;
-
- mCommonSupportedTags = Lists.newArrayListWithExpectedSize(tags.size());
- mAdvancedSupportedTags = Lists.newArrayListWithExpectedSize(tags.size());
-
- for (SystraceTag supportedTag : tags) {
- if (sCommonTags.contains(supportedTag.tag)) {
- mCommonSupportedTags.add(supportedTag);
- } else {
- mAdvancedSupportedTags.add(supportedTag);
- }
- }
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- setTitle(TITLE);
- setMessage(DEFAULT_MESSAGE);
-
- Composite c = new Composite(parent, SWT.BORDER);
- c.setLayout(new GridLayout(3, false));
- c.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- Label l = new Label(c, SWT.NONE);
- l.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- l.setText("Destination File: ");
-
- mDestinationText = new Text(c, SWT.BORDER);
- mDestinationText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- mDestinationText.setText(sSaveToFolder + File.separator + DEFAULT_TRACE_FNAME);
-
- final Button browse = new Button(c, SWT.NONE);
- browse.setText("Browse...");
- browse.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- String path = openBrowseDialog(browse.getShell());
- if (path != null) mDestinationText.setText(path);
- }
- });
-
- Label lblTraceDurationseconds = new Label(c, SWT.NONE);
- lblTraceDurationseconds.setLayoutData(
- new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- lblTraceDurationseconds.setText("Trace duration (seconds): ");
-
- mTraceDurationText = new Text(c, SWT.BORDER);
- mTraceDurationText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
- mTraceDurationText.setText(sTraceDuration);
-
- Label lblTraceBufferSize = new Label(c, SWT.NONE);
- lblTraceBufferSize.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- lblTraceBufferSize.setText("Trace Buffer Size (kb): ");
-
- mTraceBufferSizeText = new Text(c, SWT.BORDER);
- mTraceBufferSizeText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
- mTraceBufferSizeText.setText(sTraceBufferSize);
-
- Label lblTraceAppName = new Label(c, SWT.NONE);
- lblTraceAppName.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- lblTraceAppName.setText("Enable Application Traces from: ");
-
- mTraceAppCombo = new Combo(c, SWT.DROP_DOWN | SWT.READ_ONLY);
- mTraceAppCombo.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1));
- String[] items = new String[mCurrentApps.size() + 1];
- items[0] = "None";
- for (int i = 0; i < mCurrentApps.size(); i++) {
- items[i+1] = mCurrentApps.get(i);
- }
- mTraceAppCombo.setItems(items);
- if (sLastSelectedApp != null) {
- mTraceAppCombo.setText(sLastSelectedApp);
- } else {
- mTraceAppCombo.select(0);
- }
-
- Label separator = new Label(c, SWT.SEPARATOR | SWT.HORIZONTAL);
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan = 3;
- separator.setLayoutData(gd);
-
- ModifyListener m = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- validateFields();
- }
- };
-
- mDestinationText.addModifyListener(m);
- mTraceBufferSizeText.addModifyListener(m);
- mTraceDurationText.addModifyListener(m);
-
- mCommonTagsTable = createTable(c, "Commonly Used Tags: ", mCommonSupportedTags);
- mAdvancedTagsTable = createTable(c, "Advanced Options: ", mAdvancedSupportedTags);
-
- return c;
- }
-
- private Table createTable(Composite c, String label, List<SystraceTag> supportedTags) {
- Label l = new Label(c, SWT.NONE);
- l.setText(label);
- l.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
-
- Table table = new Table(c, SWT.CHECK | SWT.BORDER);
- GridData gd = new GridData(GridData.FILL_BOTH);
- gd.horizontalSpan = 2;
- table.setLayoutData(gd);
- table.setHeaderVisible(false);
- table.setLinesVisible(false);
-
- for (SystraceTag tag : supportedTags) {
- TableItem item = new TableItem(table, SWT.NONE);
- item.setText(tag.info);
- item.setChecked(sEnabledTags.contains(tag.tag));
- }
-
- TableHelper.createTableColumn(table,
- "TagHeaderNotDisplayed", //$NON-NLS-1$
- SWT.LEFT,
- "SampleTagForColumnLengthCalculation", //$NON-NLS-1$
- null,
- null);
-
- return table;
- }
-
- private void validateFields() {
- // validate trace destination path
- String msg = validatePath(mDestinationText.getText());
- if (msg != null) {
- setErrorMessage(msg);
- getButton(OK).setEnabled(false);
- return;
- }
-
- // validate the trace duration
- if (!validateInteger(mTraceDurationText.getText())) {
- setErrorMessage("Trace Duration should be a valid integer (seconds)");
- getButton(OK).setEnabled(false);
- return;
- }
-
- // validate the trace buffer size
- if (!validateInteger(mTraceBufferSizeText.getText())) {
- setErrorMessage("Trace Buffer Size should be a valid integer (kilobytes)");
- getButton(OK).setEnabled(false);
- return;
- }
-
- getButton(OK).setEnabled(true);
- setErrorMessage(null);
- }
-
- private boolean validateInteger(String text) {
- if (text == null || text.isEmpty()) {
- return true;
- }
-
- try {
- Integer.parseInt(text);
- return true;
- } catch (NumberFormatException e) {
- return false;
- }
- }
-
- private String validatePath(String path) {
- if (path == null || path.isEmpty()) {
- return null;
- }
-
- File f = new File(path);
- if (f.isDirectory()) {
- return String.format("The path '%s' points to a folder", path);
- }
-
- if (!f.exists()) { // if such a file doesn't exist, make sure the parent folder is valid
- if (!f.getParentFile().isDirectory()) {
- return String.format("That path '%s' is not a valid folder.", f.getParent());
- }
- }
-
- return null;
- }
-
- private String openBrowseDialog(Shell parentShell) {
- FileDialog fd = new FileDialog(parentShell, SWT.SAVE);
-
- fd.setText("Save To");
- fd.setFileName(DEFAULT_TRACE_FNAME);
-
- fd.setFilterPath(sSaveToFolder);
- fd.setFilterExtensions(new String[] { "*.html" }); //$NON-NLS-1$
-
- String fname = fd.open();
- if (fname == null || fname.trim().length() == 0) {
- return null;
- }
-
- sSaveToFolder = fd.getFilterPath();
- return fname;
- }
-
- @Override
- protected void okPressed() {
- mDestinationPath = mDestinationText.getText().trim();
-
- sTraceDuration = mTraceDurationText.getText();
- if (!sTraceDuration.isEmpty()) {
- mOptions.mTraceDuration = Integer.parseInt(sTraceDuration);
- }
-
- sTraceBufferSize = mTraceBufferSizeText.getText();
- if (!sTraceBufferSize.isEmpty()) {
- mOptions.mTraceBufferSize = Integer.parseInt(sTraceBufferSize);
- }
-
- if (mTraceAppCombo.getSelectionIndex() != 0) {
- mOptions.mTraceApp = sLastSelectedApp = mTraceAppCombo.getText();
- }
-
- sEnabledTags.clear();
- sEnabledTags.addAll(getEnabledTags(mCommonTagsTable, mCommonSupportedTags));
- sEnabledTags.addAll(getEnabledTags(mAdvancedTagsTable, mAdvancedSupportedTags));
-
- super.okPressed();
- }
-
- private static Set<String> getEnabledTags(Table table, List<SystraceTag> tags) {
- Set<String> enabledTags = Sets.newHashSetWithExpectedSize(tags.size());
-
- for (int i = 0; i < table.getItemCount(); i++) {
- TableItem it = table.getItem(i);
- if (it.getChecked()) {
- enabledTags.add(tags.get(i).tag);
- }
- }
-
- return enabledTags;
- }
-
- @Override
- public ISystraceOptions getSystraceOptions() {
- return mOptions;
- }
-
- @Override
- public String getTraceFilePath() {
- return mDestinationPath;
- }
-
- private class SystraceOptions implements ISystraceOptions {
- private int mTraceBufferSize;
- private int mTraceDuration;
- private String mTraceApp;
-
- @Override
- public String getTags() {
- return null;
- }
-
- @Override
- public String getOptions() {
- StringBuilder sb = new StringBuilder(5 * mCommonSupportedTags.size());
-
- if (mTraceApp != null) {
- sb.append("-a "); //$NON-NLS-1$
- sb.append(mTraceApp);
- sb.append(' ');
- }
-
- if (mTraceDuration > 0) {
- sb.append("-t"); //$NON-NLS-1$
- sb.append(mTraceDuration);
- sb.append(' ');
- }
-
- if (mTraceBufferSize > 0) {
- sb.append("-b "); //$NON-NLS-1$
- sb.append(mTraceBufferSize);
- sb.append(' ');
- }
-
- for (String s : sEnabledTags) {
- sb.append(s);
- sb.append(' ');
- }
-
- return sb.toString().trim();
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/SystraceOutputParser.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/SystraceOutputParser.java
deleted file mode 100644
index 2548edc23..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/SystraceOutputParser.java
+++ /dev/null
@@ -1,169 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.systrace;
-
-import com.google.common.base.Charsets;
-import com.google.common.io.Files;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.zip.DataFormatException;
-import java.util.zip.Inflater;
-
-/** {@link SystraceOutputParser} receives the output of atrace command run on the device,
- * parses it and generates html based on the trace */
-public class SystraceOutputParser {
- private static final String TRACE_START = "TRACE:\n"; //$NON-NLS-1$
-
- private final boolean mUncompress;
- private final String mJs;
- private final String mCss;
- private final String mHtmlPrefix;
- private final String mHtmlSuffix;
-
- private byte[] mAtraceOutput;
- private int mAtraceLength;
- private int mSystraceIndex = -1;
-
- /**
- * Constructs a atrace output parser.
- * @param compressedStream Is the input stream compressed using zlib?
- * @param systraceJs systrace javascript content
- * @param systraceCss systrace css content
- */
- public SystraceOutputParser(boolean compressedStream, String systraceJs, String systraceCss,
- String htmlPrefix, String htmlSuffix) {
- mUncompress = compressedStream;
- mJs = systraceJs;
- mCss = systraceCss;
- mHtmlPrefix = htmlPrefix;
- mHtmlSuffix = htmlSuffix;
- }
-
- /**
- * Parses the atrace output for systrace content.
- * @param atraceOutput output bytes from atrace
- */
- public void parse(byte[] atraceOutput) {
- mAtraceOutput = atraceOutput;
- mAtraceLength = atraceOutput.length;
-
- removeCrLf();
-
- // locate the trace start marker within the first hundred bytes
- String header = new String(mAtraceOutput, 0, Math.min(100, mAtraceLength));
- mSystraceIndex = locateSystraceData(header);
-
- if (mSystraceIndex < 0) {
- throw new RuntimeException("Unable to find trace start marker 'TRACE:':\n" + header);
- }
- }
-
- /** Replaces \r\n with \n in {@link #mAtraceOutput}. */
- private void removeCrLf() {
- int dst = 0;
- for (int src = 0; src < mAtraceLength - 1; src++, dst++) {
- byte copy;
- if (mAtraceOutput[src] == '\r' && mAtraceOutput[src + 1] == '\n') {
- copy = '\n';
- src++;
- } else {
- copy = mAtraceOutput[src];
- }
- mAtraceOutput[dst] = copy;
- }
-
- mAtraceLength = dst;
- }
-
- private int locateSystraceData(String header) {
- int index = header.indexOf(TRACE_START);
- if (index < 0) {
- return -1;
- } else {
- return index + TRACE_START.length();
- }
- }
-
- public String getSystraceHtml() {
- if (mSystraceIndex < 0) {
- return "";
- }
-
- String trace = "";
- if (mUncompress) {
- Inflater decompressor = new Inflater();
- decompressor.setInput(mAtraceOutput, mSystraceIndex, mAtraceLength - mSystraceIndex);
-
- byte[] buf = new byte[4096];
- int n;
- StringBuilder sb = new StringBuilder(1000);
- try {
- while ((n = decompressor.inflate(buf)) > 0) {
- sb.append(new String(buf, 0, n));
- }
- } catch (DataFormatException e) {
- throw new RuntimeException(e);
- }
- decompressor.end();
-
- trace = sb.toString();
- } else {
- trace = new String(mAtraceOutput, mSystraceIndex, mAtraceLength - mSystraceIndex);
- }
-
- // each line should end with the characters \n\ followed by a newline
- String html_out = trace.replaceAll("\n", "\\\\n\\\\\n");
- String header = String.format(mHtmlPrefix, mCss, mJs, "");
- String footer = mHtmlSuffix;
- return header + html_out + footer;
- }
-
- public static String getJs(File assetsFolder) {
- try {
- return String.format("<script language=\"javascript\">%s</script>",
- Files.toString(new File(assetsFolder, "script.js"), Charsets.UTF_8));
- } catch (IOException e) {
- return "";
- }
- }
-
- public static String getCss(File assetsFolder) {
- try {
- return String.format("<style type=\"text/css\">%s</style>",
- Files.toString(new File(assetsFolder, "style.css"), Charsets.UTF_8));
- } catch (IOException e) {
- return "";
- }
- }
-
- public static String getHtmlPrefix(File assetsFolder) {
- return getHtmlTemplate(assetsFolder, "prefix.html");
- }
-
- public static String getHtmlSuffix(File assetsFolder) {
- return getHtmlTemplate(assetsFolder, "suffix.html");
- }
-
- private static String getHtmlTemplate(File assetsFolder, String htmlFileName) {
- try {
- return Files.toString(new File(assetsFolder, htmlFileName), Charsets.UTF_8);
- } catch (IOException e) {
- return "";
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/SystraceTag.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/SystraceTag.java
deleted file mode 100644
index 0fc03efa3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/SystraceTag.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.systrace;
-
-public class SystraceTag {
- public final String tag;
- public final String info;
-
- public SystraceTag(String tagName, String details) {
- tag = tagName;
- info = details;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/SystraceTask.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/SystraceTask.java
deleted file mode 100644
index 726296468..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/SystraceTask.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.systrace;
-
-import com.android.ddmlib.IDevice;
-import com.android.ddmlib.IShellOutputReceiver;
-import com.google.common.primitives.Bytes;
-
-public class SystraceTask implements Runnable {
- private final IDevice mDevice;
- private final String mOptions;
-
- private volatile boolean mCancel;
-
- private final Object mLock = new Object();
- private String errorMessage;
- private boolean mTraceComplete;
- private byte[] mBuffer = new byte[1024];
- private int mDataLength = 0;
-
- public SystraceTask(IDevice device, String options) {
- mDevice = device;
- mOptions = options;
- }
-
- @Override
- public void run() {
- try {
- mDevice.executeShellCommand("atrace " + mOptions, new Receiver(), 0);
- } catch (Exception e) {
- synchronized (mLock) {
- errorMessage = "Unexpected error while running atrace on device: " + e;
- }
- }
- }
-
- public void cancel() {
- mCancel = true;
- }
-
- public String getError() {
- synchronized (mLock) {
- return errorMessage;
- }
- }
-
- public byte[] getAtraceOutput() {
- synchronized (mLock) {
- return mTraceComplete ? mBuffer : null;
- }
- }
-
- private class Receiver implements IShellOutputReceiver {
- @Override
- public void addOutput(byte[] data, int offset, int length) {
- synchronized (mLock) {
- if (mDataLength + length > mBuffer.length) {
- mBuffer = Bytes.ensureCapacity(mBuffer, mDataLength + length + 1, 1024);
- }
-
- for (int i = 0; i < length; i++) {
- mBuffer[mDataLength + i] = data[offset + i];
- }
- mDataLength += length;
- }
- }
-
- @Override
- public void flush() {
- synchronized (mLock) {
- // trim mBuffer to its final size
- byte[] copy = new byte[mDataLength];
- for (int i = 0; i < mDataLength; i++) {
- copy[i] = mBuffer[i];
- }
- mBuffer = copy;
-
- mTraceComplete = true;
- }
- }
-
- @Override
- public boolean isCancelled() {
- return mCancel;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/SystraceVersionDetector.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/SystraceVersionDetector.java
deleted file mode 100644
index 646a45412..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/systrace/SystraceVersionDetector.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.systrace;
-
-import com.android.ddmlib.CollectingOutputReceiver;
-import com.android.ddmlib.IDevice;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public class SystraceVersionDetector implements IRunnableWithProgress {
- public static final int SYSTRACE_V1 = 1;
- public static final int SYSTRACE_V2 = 2;
-
- private final IDevice mDevice;
- private List<SystraceTag> mTags;
-
- public SystraceVersionDetector(IDevice device) {
- mDevice = device;
- }
-
- @Override
- public void run(IProgressMonitor monitor) throws InvocationTargetException,
- InterruptedException {
- monitor.beginTask("Checking systrace version on device..",
- IProgressMonitor.UNKNOWN);
-
- CountDownLatch setTagLatch = new CountDownLatch(1);
- CollectingOutputReceiver receiver = new CollectingOutputReceiver(setTagLatch);
- try {
- String cmd = "atrace --list_categories";
- mDevice.executeShellCommand(cmd, receiver);
- setTagLatch.await(5, TimeUnit.SECONDS);
- } catch (Exception e) {
- throw new InvocationTargetException(e);
- }
-
- String shellOutput = receiver.getOutput();
- mTags = parseSupportedTags(shellOutput);
-
- monitor.done();
- }
-
- public int getVersion() {
- if (mTags == null) {
- return SYSTRACE_V1;
- } else {
- return SYSTRACE_V2;
- }
- }
-
- public List<SystraceTag> getTags() {
- return mTags;
- }
-
- private List<SystraceTag> parseSupportedTags(String listCategoriesOutput) {
- if (listCategoriesOutput == null) {
- return null;
- }
-
- if (listCategoriesOutput.contains("unknown option")) {
- return null;
- }
-
- String[] categories = listCategoriesOutput.split("\n");
- List<SystraceTag> tags = new ArrayList<SystraceTag>(categories.length);
-
- Pattern p = Pattern.compile("([^-]+) - (.*)"); //$NON-NLS-1$
- for (String category : categories) {
- Matcher m = p.matcher(category);
- if (m.find()) {
- tags.add(new SystraceTag(m.group(1).trim(), m.group(2).trim()));
- }
- }
-
- return tags;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/AllocTrackerView.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/AllocTrackerView.java
deleted file mode 100644
index e8b73ff51..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/AllocTrackerView.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.views;
-
-import com.android.ddmuilib.AllocationPanel;
-
-import org.eclipse.swt.widgets.Composite;
-
-public class AllocTrackerView extends TableView {
-
- public static final String ID = "com.android.ide.eclipse.ddms.views.AllocTrackerView"; //$NON-NLS-1$
- private AllocationPanel mPanel;
-
- public AllocTrackerView() {
- }
-
- @Override
- public void createPartControl(Composite parent) {
- mPanel = new AllocationPanel();
- mPanel.createPanel(parent);
-
- setSelectionDependentPanel(mPanel);
-
- // listen to focus changes for table(s) of the panel.
- setupTableFocusListener(mPanel, parent);
- }
-
- @Override
- public void setFocus() {
- mPanel.setFocus();
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/DeviceView.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/DeviceView.java
deleted file mode 100644
index c70c38803..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/DeviceView.java
+++ /dev/null
@@ -1,877 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.views;
-
-import com.android.ddmlib.AndroidDebugBridge;
-import com.android.ddmlib.AndroidDebugBridge.IClientChangeListener;
-import com.android.ddmlib.Client;
-import com.android.ddmlib.ClientData;
-import com.android.ddmlib.ClientData.IHprofDumpHandler;
-import com.android.ddmlib.ClientData.MethodProfilingStatus;
-import com.android.ddmlib.CollectingOutputReceiver;
-import com.android.ddmlib.DdmPreferences;
-import com.android.ddmlib.IDevice;
-import com.android.ddmlib.SyncException;
-import com.android.ddmlib.SyncService;
-import com.android.ddmlib.SyncService.ISyncProgressMonitor;
-import com.android.ddmlib.TimeoutException;
-import com.android.ddmuilib.DevicePanel;
-import com.android.ddmuilib.DevicePanel.IUiSelectionListener;
-import com.android.ddmuilib.ImageLoader;
-import com.android.ddmuilib.ScreenShotDialog;
-import com.android.ddmuilib.SyncProgressHelper;
-import com.android.ddmuilib.SyncProgressHelper.SyncRunnable;
-import com.android.ddmuilib.handler.BaseFileHandler;
-import com.android.ddmuilib.handler.MethodProfilingHandler;
-import com.android.ide.eclipse.ddms.DdmsPlugin;
-import com.android.ide.eclipse.ddms.IClientAction;
-import com.android.ide.eclipse.ddms.IDebuggerConnector;
-import com.android.ide.eclipse.ddms.editors.UiAutomatorViewer;
-import com.android.ide.eclipse.ddms.i18n.Messages;
-import com.android.ide.eclipse.ddms.preferences.PreferenceInitializer;
-import com.android.ide.eclipse.ddms.systrace.ISystraceOptions;
-import com.android.ide.eclipse.ddms.systrace.ISystraceOptionsDialog;
-import com.android.ide.eclipse.ddms.systrace.SystraceOptionsDialogV1;
-import com.android.ide.eclipse.ddms.systrace.SystraceOptionsDialogV2;
-import com.android.ide.eclipse.ddms.systrace.SystraceOutputParser;
-import com.android.ide.eclipse.ddms.systrace.SystraceTask;
-import com.android.ide.eclipse.ddms.systrace.SystraceVersionDetector;
-import com.android.uiautomator.UiAutomatorHelper;
-import com.android.uiautomator.UiAutomatorHelper.UiAutomatorException;
-import com.android.uiautomator.UiAutomatorHelper.UiAutomatorResult;
-import com.google.common.io.Files;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.dialogs.ProgressMonitorDialog;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.WorkbenchException;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.ui.part.ViewPart;
-
-import java.io.File;
-import java.io.IOException;
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-public class DeviceView extends ViewPart implements IUiSelectionListener, IClientChangeListener {
-
- private final static boolean USE_SELECTED_DEBUG_PORT = true;
-
- public static final String ID = "com.android.ide.eclipse.ddms.views.DeviceView"; //$NON-NLS-1$
-
- private static DeviceView sThis;
-
- private Shell mParentShell;
- private DevicePanel mDeviceList;
-
- private Action mResetAdbAction;
- private Action mCaptureAction;
- private Action mViewUiAutomatorHierarchyAction;
- private Action mSystraceAction;
- private Action mUpdateThreadAction;
- private Action mUpdateHeapAction;
- private Action mGcAction;
- private Action mKillAppAction;
- private Action mDebugAction;
- private Action mHprofAction;
- private Action mTracingAction;
-
- private ImageDescriptor mTracingStartImage;
- private ImageDescriptor mTracingStopImage;
-
- public class HProfHandler extends BaseFileHandler implements IHprofDumpHandler {
- public final static String ACTION_SAVE = "hprof.save"; //$NON-NLS-1$
- public final static String ACTION_OPEN = "hprof.open"; //$NON-NLS-1$
-
- public final static String DOT_HPROF = ".hprof"; //$NON-NLS-1$
-
- HProfHandler(Shell parentShell) {
- super(parentShell);
- }
-
- @Override
- protected String getDialogTitle() {
- return Messages.DeviceView_HPROF_Error;
- }
-
- @Override
- public void onEndFailure(final Client client, final String message) {
- mParentShell.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- try {
- displayErrorFromUiThread(
- Messages.DeviceView_Unable_Create_HPROF_For_Application,
- client.getClientData().getClientDescription(),
- message != null ? message + "\n\n" : ""); //$NON-NLS-1$ //$NON-NLS-2$
- } finally {
- // this will make sure the dump hprof button is
- // re-enabled for the
- // current selection. as the client is finished dumping
- // an hprof file
- doSelectionChanged(mDeviceList.getSelectedClient());
- }
- }
- });
- }
-
- @Override
- public void onSuccess(final String remoteFilePath, final Client client) {
- mParentShell.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- final IDevice device = client.getDevice();
- try {
- // get the sync service to pull the HPROF file
- final SyncService sync = client.getDevice().getSyncService();
- if (sync != null) {
- // get from the preference what action to take
- IPreferenceStore store = DdmsPlugin.getDefault().getPreferenceStore();
- String value = store.getString(PreferenceInitializer.ATTR_HPROF_ACTION);
-
- if (ACTION_OPEN.equals(value)) {
- File temp = File.createTempFile("android", DOT_HPROF); //$NON-NLS-1$
- final String tempPath = temp.getAbsolutePath();
- SyncProgressHelper.run(new SyncRunnable() {
-
- @Override
- public void run(ISyncProgressMonitor monitor)
- throws SyncException, IOException,
- TimeoutException {
- sync.pullFile(remoteFilePath, tempPath, monitor);
- }
-
- @Override
- public void close() {
- sync.close();
- }
- },
- String.format(Messages.DeviceView_Pulling_From_Device,
- remoteFilePath),
- mParentShell);
-
- open(tempPath);
- } else {
- // default action is ACTION_SAVE
- promptAndPull(sync,
- client.getClientData().getClientDescription() + DOT_HPROF,
- remoteFilePath, Messages.DeviceView_Save_HPROF_File);
-
- }
- } else {
- displayErrorFromUiThread(
- Messages.DeviceView_Unable_Download_HPROF_From_Device_One_Param_First_Message,
- device.getSerialNumber());
- }
- } catch (SyncException e) {
- if (e.wasCanceled() == false) {
- displayErrorFromUiThread(
- Messages.DeviceView_Unable_Download_HPROF_From_Device_Two_Param,
- device.getSerialNumber(), e.getMessage());
- }
- } catch (Exception e) {
- displayErrorFromUiThread(
- Messages.DeviceView_Unable_Download_HPROF_From_Device_One_Param_Second_Message,
- device.getSerialNumber());
-
- } finally {
- // this will make sure the dump hprof button is
- // re-enabled for the
- // current selection. as the client is finished dumping
- // an hprof file
- doSelectionChanged(mDeviceList.getSelectedClient());
- }
- }
- });
- }
-
- @Override
- public void onSuccess(final byte[] data, final Client client) {
- mParentShell.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- // get from the preference what action to take
- IPreferenceStore store = DdmsPlugin.getDefault().getPreferenceStore();
- String value = store.getString(PreferenceInitializer.ATTR_HPROF_ACTION);
-
- if (ACTION_OPEN.equals(value)) {
- try {
- // no need to give an extension since we're going to
- // convert the
- // file anyway after.
- File tempFile = saveTempFile(data, null /* extension */);
- open(tempFile.getAbsolutePath());
- } catch (Exception e) {
- String errorMsg = e.getMessage();
- displayErrorFromUiThread(
- Messages.DeviceView_Failed_To_Save_HPROF_Data,
- errorMsg != null ? ":\n" + errorMsg : "."); //$NON-NLS-1$ //$NON-NLS-2$
- }
- } else {
- // default action is ACTION_SAVE
- promptAndSave(client.getClientData().getClientDescription() + DOT_HPROF,
- data, Messages.DeviceView_Save_HPROF_File);
- }
- }
- });
- }
-
- private void open(String path) throws IOException, InterruptedException, PartInitException {
- // make a temp file to convert the hprof into something
- // readable by normal tools
- File temp = File.createTempFile("android", DOT_HPROF); //$NON-NLS-1$
- String tempPath = temp.getAbsolutePath();
-
- String[] command = new String[3];
- command[0] = DdmsPlugin.getHprofConverter();
- command[1] = path;
- command[2] = tempPath;
-
- Process p = Runtime.getRuntime().exec(command);
- p.waitFor();
-
- IFileStore fileStore = EFS.getLocalFileSystem().getStore(new Path(tempPath));
- if (!fileStore.fetchInfo().isDirectory() && fileStore.fetchInfo().exists()) {
- // before we open the file in an editor window, we make sure the
- // current
- // workbench page has an editor area (typically the ddms
- // perspective doesn't).
- IWorkbench workbench = PlatformUI.getWorkbench();
- IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
- IWorkbenchPage page = window.getActivePage();
- if (page == null) {
- return;
- }
-
- if (page.isEditorAreaVisible() == false) {
- IAdaptable input;
- input = page.getInput();
- try {
- workbench.showPerspective("org.eclipse.debug.ui.DebugPerspective", //$NON-NLS-1$
- window, input);
- } catch (WorkbenchException e) {
- }
- }
-
- IDE.openEditorOnFileStore(page, fileStore);
- }
- }
- }
-
- public DeviceView() {
- // the view is declared with allowMultiple="false" so we
- // can safely do this.
- sThis = this;
- }
-
- public static DeviceView getInstance() {
- return sThis;
- }
-
- @Override
- public void createPartControl(Composite parent) {
- mParentShell = parent.getShell();
-
- ImageLoader loader = ImageLoader.getDdmUiLibLoader();
-
- mDeviceList = new DevicePanel(USE_SELECTED_DEBUG_PORT);
- mDeviceList.createPanel(parent);
- mDeviceList.addSelectionListener(this);
-
- DdmsPlugin plugin = DdmsPlugin.getDefault();
- mDeviceList.addSelectionListener(plugin);
- plugin.setListeningState(true);
-
- mCaptureAction = new Action(Messages.DeviceView_Screen_Capture) {
- @Override
- public void run() {
- ScreenShotDialog dlg = new ScreenShotDialog(
- DdmsPlugin.getDisplay().getActiveShell());
- dlg.open(mDeviceList.getSelectedDevice());
- }
- };
- mCaptureAction.setToolTipText(Messages.DeviceView_Screen_Capture_Tooltip);
- mCaptureAction.setImageDescriptor(loader.loadDescriptor("capture.png")); //$NON-NLS-1$
-
- mViewUiAutomatorHierarchyAction = new Action("Dump View Hierarchy for UI Automator") {
- @Override
- public void run() {
- takeUiAutomatorSnapshot(mDeviceList.getSelectedDevice(),
- DdmsPlugin.getDisplay().getActiveShell());
- }
- };
- mViewUiAutomatorHierarchyAction.setToolTipText("Dump View Hierarchy for UI Automator");
- mViewUiAutomatorHierarchyAction.setImageDescriptor(
- DdmsPlugin.getImageDescriptor("icons/uiautomator.png")); //$NON-NLS-1$
-
- mSystraceAction = new Action("Capture System Wide Trace") {
- @Override
- public void run() {
- launchSystrace(mDeviceList.getSelectedDevice(),
- DdmsPlugin.getDisplay().getActiveShell());
- }
- };
- mSystraceAction.setToolTipText("Capture system wide trace using Android systrace");
- mSystraceAction.setImageDescriptor(
- DdmsPlugin.getImageDescriptor("icons/systrace.png")); //$NON-NLS-1$
- mSystraceAction.setEnabled(true);
-
- mResetAdbAction = new Action(Messages.DeviceView_Reset_ADB) {
- @Override
- public void run() {
- AndroidDebugBridge bridge = AndroidDebugBridge.getBridge();
- if (bridge != null) {
- if (bridge.restart() == false) {
- // get the current Display
- final Display display = DdmsPlugin.getDisplay();
-
- // dialog box only run in ui thread..
- display.asyncExec(new Runnable() {
- @Override
- public void run() {
- Shell shell = display.getActiveShell();
- MessageDialog.openError(shell, Messages.DeviceView_ADB_Error,
- Messages.DeviceView_ADB_Failed_Restart);
- }
- });
- }
- }
- }
- };
- mResetAdbAction.setToolTipText(Messages.DeviceView_Reset_ADB_Host_Deamon);
- mResetAdbAction.setImageDescriptor(PlatformUI.getWorkbench()
- .getSharedImages().getImageDescriptor(
- ISharedImages.IMG_OBJS_WARN_TSK));
-
- mKillAppAction = new Action() {
- @Override
- public void run() {
- mDeviceList.killSelectedClient();
- }
- };
-
- mKillAppAction.setText(Messages.DeviceView_Stop_Process);
- mKillAppAction.setToolTipText(Messages.DeviceView_Stop_Process_Tooltip);
- mKillAppAction.setImageDescriptor(loader.loadDescriptor(DevicePanel.ICON_HALT));
-
- mGcAction = new Action() {
- @Override
- public void run() {
- mDeviceList.forceGcOnSelectedClient();
- }
- };
-
- mGcAction.setText(Messages.DeviceView_Cause_GC);
- mGcAction.setToolTipText(Messages.DeviceView_Cause_GC_Tooltip);
- mGcAction.setImageDescriptor(loader.loadDescriptor(DevicePanel.ICON_GC));
-
- mHprofAction = new Action() {
- @Override
- public void run() {
- mDeviceList.dumpHprof();
- doSelectionChanged(mDeviceList.getSelectedClient());
- }
- };
- mHprofAction.setText(Messages.DeviceView_Dump_HPROF_File);
- mHprofAction.setToolTipText(Messages.DeviceView_Dump_HPROF_File_Tooltip);
- mHprofAction.setImageDescriptor(loader.loadDescriptor(DevicePanel.ICON_HPROF));
-
- mUpdateHeapAction = new Action(Messages.DeviceView_Update_Heap, IAction.AS_CHECK_BOX) {
- @Override
- public void run() {
- boolean enable = mUpdateHeapAction.isChecked();
- mDeviceList.setEnabledHeapOnSelectedClient(enable);
- }
- };
- mUpdateHeapAction.setToolTipText(Messages.DeviceView_Update_Heap_Tooltip);
- mUpdateHeapAction.setImageDescriptor(loader.loadDescriptor(DevicePanel.ICON_HEAP));
-
- mUpdateThreadAction = new Action(Messages.DeviceView_Threads, IAction.AS_CHECK_BOX) {
- @Override
- public void run() {
- boolean enable = mUpdateThreadAction.isChecked();
- mDeviceList.setEnabledThreadOnSelectedClient(enable);
- }
- };
- mUpdateThreadAction.setToolTipText(Messages.DeviceView_Threads_Tooltip);
- mUpdateThreadAction.setImageDescriptor(loader.loadDescriptor(DevicePanel.ICON_THREAD));
-
- mTracingAction = new Action() {
- @Override
- public void run() {
- mDeviceList.toggleMethodProfiling();
- }
- };
- mTracingAction.setText(Messages.DeviceView_Start_Method_Profiling);
- mTracingAction.setToolTipText(Messages.DeviceView_Start_Method_Profiling_Tooltip);
- mTracingStartImage = loader.loadDescriptor(DevicePanel.ICON_TRACING_START);
- mTracingStopImage = loader.loadDescriptor(DevicePanel.ICON_TRACING_STOP);
- mTracingAction.setImageDescriptor(mTracingStartImage);
-
- mDebugAction = new Action(Messages.DeviceView_Debug_Process) {
- @Override
- public void run() {
- if (DdmsPlugin.getDefault().hasDebuggerConnectors()) {
- Client currentClient = mDeviceList.getSelectedClient();
- if (currentClient != null) {
- ClientData clientData = currentClient.getClientData();
-
- // make sure the client can be debugged
- switch (clientData.getDebuggerConnectionStatus()) {
- case ERROR: {
- Display display = DdmsPlugin.getDisplay();
- Shell shell = display.getActiveShell();
- MessageDialog.openError(shell,
- Messages.DeviceView_Debug_Process_Title,
- Messages.DeviceView_Process_Debug_Already_In_Use);
- return;
- }
- case ATTACHED: {
- Display display = DdmsPlugin.getDisplay();
- Shell shell = display.getActiveShell();
- MessageDialog.openError(shell,
- Messages.DeviceView_Debug_Process_Title,
- Messages.DeviceView_Process_Already_Being_Debugged);
- return;
- }
- }
-
- // get the name of the client
- String packageName = clientData.getClientDescription();
- if (packageName != null) {
-
- // try all connectors till one returns true.
- IDebuggerConnector[] connectors =
- DdmsPlugin.getDefault().getDebuggerConnectors();
-
- if (connectors != null) {
- for (IDebuggerConnector connector : connectors) {
- try {
- if (connector.connectDebugger(packageName,
- currentClient.getDebuggerListenPort(),
- DdmPreferences.getSelectedDebugPort())) {
- return;
- }
- } catch (Throwable t) {
- // ignore, we'll just not use this
- // implementation
- }
- }
- }
-
- // if we get to this point, then we failed to find a
- // project
- // that matched the application to debug
- Display display = DdmsPlugin.getDisplay();
- Shell shell = display.getActiveShell();
- MessageDialog.openError(shell, Messages.DeviceView_Debug_Process_Title,
- String.format(
- Messages.DeviceView_Debug_Session_Failed,
- packageName));
- }
- }
- }
- }
- };
- mDebugAction.setToolTipText(Messages.DeviceView_Debug_Process_Tooltip);
- mDebugAction.setImageDescriptor(loader.loadDescriptor("debug-attach.png")); //$NON-NLS-1$
- mDebugAction.setEnabled(DdmsPlugin.getDefault().hasDebuggerConnectors());
-
- placeActions();
-
- // disabling all action buttons
- selectionChanged(null, null);
-
- ClientData.setHprofDumpHandler(new HProfHandler(mParentShell));
- AndroidDebugBridge.addClientChangeListener(this);
- ClientData.setMethodProfilingHandler(new MethodProfilingHandler(mParentShell) {
- @Override
- protected void open(String tempPath) {
- if (DdmsPlugin.getDefault().launchTraceview(tempPath) == false) {
- super.open(tempPath);
- }
- }
- });
- }
-
- private void takeUiAutomatorSnapshot(final IDevice device, final Shell shell) {
- ProgressMonitorDialog dialog = new ProgressMonitorDialog(shell);
- try {
- dialog.run(true, false, new IRunnableWithProgress() {
- @Override
- public void run(IProgressMonitor monitor) throws InvocationTargetException,
- InterruptedException {
- UiAutomatorResult result = null;
- try {
- result = UiAutomatorHelper.takeSnapshot(device, monitor);
- } catch (UiAutomatorException e) {
- throw new InvocationTargetException(e);
- } finally {
- monitor.done();
- }
-
- UiAutomatorViewer.openEditor(result);
- }
- });
- } catch (Exception e) {
- Throwable t = e;
- if (e instanceof InvocationTargetException) {
- t = ((InvocationTargetException) e).getTargetException();
- }
- Status s = new Status(IStatus.ERROR, DdmsPlugin.PLUGIN_ID,
- "Error obtaining UI hierarchy", t);
- ErrorDialog.openError(shell, "UI Automator",
- "Unexpected error while obtaining UI hierarchy", s);
- }
- };
-
- private void launchSystrace(final IDevice device, final Shell parentShell) {
- final File systraceAssets = new File(DdmsPlugin.getPlatformToolsFolder(), "systrace"); //$NON-NLS-1$
- if (!systraceAssets.isDirectory()) {
- MessageDialog.openError(parentShell, "Systrace",
- "Updated version of platform-tools (18.0.1 or greater) is required.\n"
- + "Please update your platform-tools using SDK Manager.");
- return;
- }
-
- SystraceVersionDetector detector = new SystraceVersionDetector(device);
- try {
- new ProgressMonitorDialog(parentShell).run(true, false, detector);
- } catch (InvocationTargetException e) {
- MessageDialog.openError(parentShell,
- "Systrace",
- "Unexpected error while detecting atrace version: " + e);
- return;
- } catch (InterruptedException e) {
- return;
- }
-
- final ISystraceOptionsDialog dlg;
- if (detector.getVersion() == SystraceVersionDetector.SYSTRACE_V1) {
- dlg = new SystraceOptionsDialogV1(parentShell);
- } else {
- Client[] clients = device.getClients();
- List<String> apps = new ArrayList<String>(clients.length);
- for (int i = 0; i < clients.length; i++) {
- String name = clients[i].getClientData().getClientDescription();
- if (name != null && !name.isEmpty()) {
- apps.add(name);
- }
- }
- dlg = new SystraceOptionsDialogV2(parentShell, detector.getTags(), apps);
- }
-
- if (dlg.open() != SystraceOptionsDialogV1.OK) {
- return;
- }
-
- final ISystraceOptions options = dlg.getSystraceOptions();
-
- // set trace tag if necessary:
- // adb shell setprop debug.atrace.tags.enableflags <tag>
- String tag = options.getTags();
- if (tag != null) {
- CountDownLatch setTagLatch = new CountDownLatch(1);
- CollectingOutputReceiver receiver = new CollectingOutputReceiver(setTagLatch);
- try {
- String cmd = "setprop debug.atrace.tags.enableflags " + tag;
- device.executeShellCommand(cmd, receiver);
- setTagLatch.await(5, TimeUnit.SECONDS);
- } catch (Exception e) {
- MessageDialog.openError(parentShell,
- "Systrace",
- "Unexpected error while setting trace tags: " + e);
- return;
- }
-
- String shellOutput = receiver.getOutput();
- if (shellOutput.contains("Error type")) { //$NON-NLS-1$
- throw new RuntimeException(receiver.getOutput());
- }
- }
-
- // obtain the output of "adb shell atrace <trace-options>" and generate the html file
- ProgressMonitorDialog d = new ProgressMonitorDialog(parentShell);
- try {
- d.run(true, true, new IRunnableWithProgress() {
- @Override
- public void run(IProgressMonitor monitor) throws InvocationTargetException,
- InterruptedException {
- boolean COMPRESS_DATA = true;
-
- monitor.setTaskName("Collecting Trace Information");
- final String atraceOptions = options.getOptions()
- + (COMPRESS_DATA ? " -z" : "");
- SystraceTask task = new SystraceTask(device, atraceOptions);
- Thread t = new Thread(task, "Systrace Output Receiver");
- t.start();
-
- // check if the user has cancelled tracing every so often
- while (true) {
- t.join(1000);
-
- if (t.isAlive()) {
- if (monitor.isCanceled()) {
- task.cancel();
- return;
- }
- } else {
- break;
- }
- }
-
- if (task.getError() != null) {
- throw new RuntimeException(task.getError());
- }
-
- monitor.setTaskName("Saving trace information");
- SystraceOutputParser parser = new SystraceOutputParser(
- COMPRESS_DATA,
- SystraceOutputParser.getJs(systraceAssets),
- SystraceOutputParser.getCss(systraceAssets),
- SystraceOutputParser.getHtmlPrefix(systraceAssets),
- SystraceOutputParser.getHtmlSuffix(systraceAssets));
-
- parser.parse(task.getAtraceOutput());
-
- String html = parser.getSystraceHtml();
- try {
- Files.write(html.getBytes(), new File(dlg.getTraceFilePath()));
- } catch (IOException e) {
- throw new InvocationTargetException(e);
- }
- }
- });
- } catch (InvocationTargetException e) {
- ErrorDialog.openError(parentShell, "Systrace",
- "Unable to collect system trace.",
- new Status(Status.ERROR,
- DdmsPlugin.PLUGIN_ID,
- "Unexpected error while collecting system trace.",
- e.getCause()));
- } catch (InterruptedException ignore) {
- }
- }
-
- @Override
- public void setFocus() {
- mDeviceList.setFocus();
- }
-
- /**
- * Sent when a new {@link IDevice} and {@link Client} are selected.
- *
- * @param selectedDevice the selected device. If null, no devices are
- * selected.
- * @param selectedClient The selected client. If null, no clients are
- * selected.
- */
- @Override
- public void selectionChanged(IDevice selectedDevice, Client selectedClient) {
- // update the buttons
- doSelectionChanged(selectedClient);
- doSelectionChanged(selectedDevice);
- }
-
- private void doSelectionChanged(Client selectedClient) {
- // update the buttons
- if (selectedClient != null) {
- if (USE_SELECTED_DEBUG_PORT) {
- // set the client as the debug client
- selectedClient.setAsSelectedClient();
- }
-
- mDebugAction.setEnabled(DdmsPlugin.getDefault().hasDebuggerConnectors());
- mKillAppAction.setEnabled(true);
- mGcAction.setEnabled(true);
-
- mUpdateHeapAction.setEnabled(true);
- mUpdateHeapAction.setChecked(selectedClient.isHeapUpdateEnabled());
-
- mUpdateThreadAction.setEnabled(true);
- mUpdateThreadAction.setChecked(selectedClient.isThreadUpdateEnabled());
-
- ClientData data = selectedClient.getClientData();
-
- if (data.hasFeature(ClientData.FEATURE_HPROF)) {
- mHprofAction.setEnabled(data.hasPendingHprofDump() == false);
- mHprofAction.setToolTipText(Messages.DeviceView_Dump_HPROF_File);
- } else {
- mHprofAction.setEnabled(false);
- mHprofAction
- .setToolTipText(Messages.DeviceView_Dump_HPROF_File_Not_Supported_By_VM);
- }
-
- if (data.hasFeature(ClientData.FEATURE_PROFILING)) {
- mTracingAction.setEnabled(true);
- if (data.getMethodProfilingStatus() == MethodProfilingStatus.TRACER_ON
- || data.getMethodProfilingStatus() == MethodProfilingStatus.SAMPLER_ON) {
- mTracingAction
- .setToolTipText(Messages.DeviceView_Stop_Method_Profiling_Tooltip);
- mTracingAction.setText(Messages.DeviceView_Stop_Method_Profiling);
- mTracingAction.setImageDescriptor(mTracingStopImage);
- } else {
- mTracingAction
- .setToolTipText(Messages.DeviceView_Start_Method_Profiling_Tooltip);
- mTracingAction.setImageDescriptor(mTracingStartImage);
- mTracingAction.setText(Messages.DeviceView_Start_Method_Profiling);
- }
- } else {
- mTracingAction.setEnabled(false);
- mTracingAction.setImageDescriptor(mTracingStartImage);
- mTracingAction
- .setToolTipText(Messages.DeviceView_Start_Method_Profiling_Not_Suported_By_Vm);
- mTracingAction.setText(Messages.DeviceView_Start_Method_Profiling);
- }
- } else {
- if (USE_SELECTED_DEBUG_PORT) {
- // set the client as the debug client
- AndroidDebugBridge bridge = AndroidDebugBridge.getBridge();
- if (bridge != null) {
- bridge.setSelectedClient(null);
- }
- }
-
- mDebugAction.setEnabled(false);
- mKillAppAction.setEnabled(false);
- mGcAction.setEnabled(false);
- mUpdateHeapAction.setChecked(false);
- mUpdateHeapAction.setEnabled(false);
- mUpdateThreadAction.setEnabled(false);
- mUpdateThreadAction.setChecked(false);
- mHprofAction.setEnabled(false);
-
- mHprofAction.setEnabled(false);
- mHprofAction.setToolTipText(Messages.DeviceView_Dump_HPROF_File);
-
- mTracingAction.setEnabled(false);
- mTracingAction.setImageDescriptor(mTracingStartImage);
- mTracingAction.setToolTipText(Messages.DeviceView_Start_Method_Profiling_Tooltip);
- mTracingAction.setText(Messages.DeviceView_Start_Method_Profiling);
- }
-
- for (IClientAction a : DdmsPlugin.getDefault().getClientSpecificActions()) {
- a.selectedClientChanged(selectedClient);
- }
- }
-
- private void doSelectionChanged(IDevice selectedDevice) {
- boolean validDevice = selectedDevice != null;
-
- mCaptureAction.setEnabled(validDevice);
- mViewUiAutomatorHierarchyAction.setEnabled(validDevice);
- mSystraceAction.setEnabled(validDevice);
- }
-
- /**
- * Place the actions in the ui.
- */
- private final void placeActions() {
- IActionBars actionBars = getViewSite().getActionBars();
-
- // first in the menu
- IMenuManager menuManager = actionBars.getMenuManager();
- menuManager.removeAll();
- menuManager.add(mDebugAction);
- menuManager.add(new Separator());
- menuManager.add(mUpdateHeapAction);
- menuManager.add(mHprofAction);
- menuManager.add(mGcAction);
- menuManager.add(new Separator());
- menuManager.add(mUpdateThreadAction);
- menuManager.add(mTracingAction);
- menuManager.add(new Separator());
- menuManager.add(mKillAppAction);
- menuManager.add(new Separator());
- menuManager.add(mCaptureAction);
- menuManager.add(new Separator());
- menuManager.add(mViewUiAutomatorHierarchyAction);
- menuManager.add(new Separator());
- menuManager.add(mSystraceAction);
- menuManager.add(new Separator());
- menuManager.add(mResetAdbAction);
- for (IClientAction a : DdmsPlugin.getDefault().getClientSpecificActions()) {
- menuManager.add(a.getAction());
- }
-
- // and then in the toolbar
- IToolBarManager toolBarManager = actionBars.getToolBarManager();
- toolBarManager.removeAll();
- toolBarManager.add(mDebugAction);
- toolBarManager.add(new Separator());
- toolBarManager.add(mUpdateHeapAction);
- toolBarManager.add(mHprofAction);
- toolBarManager.add(mGcAction);
- toolBarManager.add(new Separator());
- toolBarManager.add(mUpdateThreadAction);
- toolBarManager.add(mTracingAction);
- toolBarManager.add(new Separator());
- toolBarManager.add(mKillAppAction);
- toolBarManager.add(new Separator());
- toolBarManager.add(mCaptureAction);
- toolBarManager.add(new Separator());
- toolBarManager.add(mViewUiAutomatorHierarchyAction);
- toolBarManager.add(new Separator());
- toolBarManager.add(mSystraceAction);
- for (IClientAction a : DdmsPlugin.getDefault().getClientSpecificActions()) {
- toolBarManager.add(a.getAction());
- }
- }
-
- @Override
- public void clientChanged(final Client client, int changeMask) {
- if ((changeMask & Client.CHANGE_METHOD_PROFILING_STATUS) == Client.CHANGE_METHOD_PROFILING_STATUS) {
- if (mDeviceList.getSelectedClient() == client) {
- mParentShell.getDisplay().asyncExec(new Runnable() {
- @Override
- public void run() {
- // force refresh of the button enabled state.
- doSelectionChanged(client);
- }
- });
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/EmulatorControlView.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/EmulatorControlView.java
deleted file mode 100644
index 0dda7ef61..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/EmulatorControlView.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.views;
-
-import com.android.ddmuilib.EmulatorControlPanel;
-
-import org.eclipse.swt.widgets.Composite;
-
-public class EmulatorControlView extends SelectionDependentViewPart {
-
- public static final String ID =
- "com.android.ide.eclipse.ddms.views.EmulatorControlView"; //$NON-NLS-1$
-
- private EmulatorControlPanel mPanel;
-
- @Override
- public void createPartControl(Composite parent) {
- mPanel = new EmulatorControlPanel();
- mPanel.createPanel(parent);
- setSelectionDependentPanel(mPanel);
- }
-
- @Override
- public void setFocus() {
- mPanel.setFocus();
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/EventLogView.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/EventLogView.java
deleted file mode 100644
index 653f17f43..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/EventLogView.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.views;
-
-import com.android.ddmuilib.ImageLoader;
-import com.android.ddmuilib.log.event.EventLogPanel;
-import com.android.ide.eclipse.ddms.CommonAction;
-import com.android.ide.eclipse.ddms.i18n.Messages;
-
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.IActionBars;
-
-public class EventLogView extends SelectionDependentViewPart {
-
- private EventLogPanel mLogPanel;
-
- @Override
- public void createPartControl(Composite parent) {
- ImageLoader loader = ImageLoader.getDdmUiLibLoader();
-
- // create the external actions
- CommonAction optionsAction = new CommonAction(Messages.EventLogView_Options);
- optionsAction.setToolTipText(Messages.EventLogView_Opens_Options_Panel);
- optionsAction.setImageDescriptor(loader.loadDescriptor("edit.png")); //$NON-NLS-1$
-
- CommonAction clearLogAction = new CommonAction(Messages.EventLogView_Clear_Log);
- clearLogAction.setToolTipText(Messages.EventLogView_Clears_Event_Log);
- clearLogAction.setImageDescriptor(loader.loadDescriptor("clear.png")); //$NON-NLS-1$
-
- CommonAction saveAction = new CommonAction(Messages.EventLogView_Save_Log);
- saveAction.setToolTipText(Messages.EventLogView_Saves_Event_Log);
- saveAction.setImageDescriptor(loader.loadDescriptor("save.png")); //$NON-NLS-1$
-
- CommonAction loadAction = new CommonAction(Messages.EventLogView_Load_Log);
- loadAction.setToolTipText(Messages.EventLogView_Loads_Event_Log);
- loadAction.setImageDescriptor(loader.loadDescriptor("load.png")); //$NON-NLS-1$
-
- CommonAction importBugAction = new CommonAction(Messages.EventLogView_Import_Bug_Report_Log);
- importBugAction.setToolTipText(Messages.EventLogView_Imports_Bug_Report);
- importBugAction.setImageDescriptor(loader.loadDescriptor("importBug.png")); //$NON-NLS-1$
-
- placeActions(optionsAction, clearLogAction, saveAction, loadAction, importBugAction);
-
- mLogPanel = new EventLogPanel();
- mLogPanel
- .setActions(optionsAction, clearLogAction, saveAction, loadAction, importBugAction);
- mLogPanel.createPanel(parent);
- setSelectionDependentPanel(mLogPanel);
- }
-
- @Override
- public void setFocus() {
- mLogPanel.setFocus();
- }
-
- @Override
- public void dispose() {
- if (mLogPanel != null) {
- mLogPanel.stopEventLog(true);
- }
- }
-
- /**
- * Places the actions in the toolbar and in the menu.
- *
- * @param importBugAction
- */
- private void placeActions(IAction optionAction, IAction clearAction, IAction saveAction,
- IAction loadAction, CommonAction importBugAction) {
- IActionBars actionBars = getViewSite().getActionBars();
-
- // first in the menu
- IMenuManager menuManager = actionBars.getMenuManager();
- menuManager.add(clearAction);
- menuManager.add(new Separator());
- menuManager.add(saveAction);
- menuManager.add(loadAction);
- menuManager.add(importBugAction);
- menuManager.add(new Separator());
- menuManager.add(optionAction);
-
- // and then in the toolbar
- IToolBarManager toolBarManager = actionBars.getToolBarManager();
- toolBarManager.add(clearAction);
- toolBarManager.add(new Separator());
- toolBarManager.add(saveAction);
- toolBarManager.add(loadAction);
- toolBarManager.add(importBugAction);
- toolBarManager.add(new Separator());
- toolBarManager.add(optionAction);
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/FileExplorerView.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/FileExplorerView.java
deleted file mode 100644
index 41796dcfd..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/FileExplorerView.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.views;
-
-import com.android.ddmlib.Client;
-import com.android.ddmlib.IDevice;
-import com.android.ddmuilib.ImageLoader;
-import com.android.ddmuilib.explorer.DeviceExplorer;
-import com.android.ide.eclipse.ddms.CommonAction;
-import com.android.ide.eclipse.ddms.DdmsPlugin;
-import com.android.ide.eclipse.ddms.DdmsPlugin.ISelectionListener;
-import com.android.ide.eclipse.ddms.i18n.Messages;
-
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.swt.graphics.Device;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.part.ViewPart;
-
-public class FileExplorerView extends ViewPart implements ISelectionListener {
-
- public static final String ID = "com.android.ide.eclipse.ddms.views.FileExplorerView"; //$NON-NLS-1$
-
- private final static String COLUMN_NAME =
- DdmsPlugin.PLUGIN_ID + ".explorer.name"; //$NON-NLS-1S
- private final static String COLUMN_SIZE =
- DdmsPlugin.PLUGIN_ID + ".explorer.size"; //$NON-NLS-1S
- private final static String COLUMN_DATE =
- DdmsPlugin.PLUGIN_ID + ".explorer.data"; //$NON-NLS-1S
- private final static String COLUMN_TIME =
- DdmsPlugin.PLUGIN_ID + ".explorer.time"; //$NON-NLS-1S
- private final static String COLUMN_PERMISSIONS =
- DdmsPlugin.PLUGIN_ID + ".explorer.permissions"; //$NON-NLS-1S
- private final static String COLUMN_INFO =
- DdmsPlugin.PLUGIN_ID + ".explorer.info"; //$NON-NLS-1$
-
- private DeviceExplorer mExplorer;
-
- public FileExplorerView() {
- }
-
- @Override
- public void createPartControl(Composite parent) {
- ImageLoader loader = ImageLoader.getDdmUiLibLoader();
-
- DeviceExplorer.COLUMN_NAME = COLUMN_NAME;
- DeviceExplorer.COLUMN_SIZE = COLUMN_SIZE;
- DeviceExplorer.COLUMN_DATE = COLUMN_DATE;
- DeviceExplorer.COLUMN_TIME = COLUMN_TIME;
- DeviceExplorer.COLUMN_PERMISSIONS = COLUMN_PERMISSIONS;
- DeviceExplorer.COLUMN_INFO = COLUMN_INFO;
-
- // device explorer
- mExplorer = new DeviceExplorer();
-
- mExplorer.setCustomImages(
- PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FILE),
- PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_FOLDER),
- null /* apk image */,
- PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT)
- );
-
- // creates the actions
- CommonAction pushAction = new CommonAction(Messages.FileExplorerView_Push_File) {
- @Override
- public void run() {
- mExplorer.pushIntoSelection();
- }
- };
- pushAction.setToolTipText(Messages.FileExplorerView_Push_File_Onto_Device);
- pushAction.setImageDescriptor(loader.loadDescriptor("push.png")); //$NON-NLS-1$
- pushAction.setEnabled(false);
-
- CommonAction pullAction = new CommonAction(Messages.FileExplorerView_Pull_File) {
- @Override
- public void run() {
- mExplorer.pullSelection();
- }
- };
- pullAction.setToolTipText(Messages.FileExplorerView_Pull_File_From_File);
- pullAction.setImageDescriptor(loader.loadDescriptor("pull.png")); //$NON-NLS-1$
- pullAction.setEnabled(false);
-
- CommonAction deleteAction = new CommonAction(Messages.FileExplorerView_Delete) {
- @Override
- public void run() {
- mExplorer.deleteSelection();
- }
- };
- deleteAction.setToolTipText(Messages.FileExplorerView_Delete_The_Selection);
- deleteAction.setImageDescriptor(loader.loadDescriptor("delete.png")); //$NON-NLS-1$
- deleteAction.setEnabled(false);
-
- CommonAction createNewFolderAction = new CommonAction("New Folder") {
- @Override
- public void run() {
- mExplorer.createNewFolderInSelection();
- }
- };
- createNewFolderAction.setToolTipText("New Folder");
- createNewFolderAction.setImageDescriptor(loader.loadDescriptor("add.png")); //$NON-NLS-1$
- createNewFolderAction.setEnabled(false);
-
- // set up the actions in the explorer
- mExplorer.setActions(pushAction, pullAction, deleteAction, createNewFolderAction);
-
- // and in the ui
- IActionBars actionBars = getViewSite().getActionBars();
- IMenuManager menuManager = actionBars.getMenuManager();
- IToolBarManager toolBarManager = actionBars.getToolBarManager();
-
- menuManager.add(pullAction);
- menuManager.add(pushAction);
- menuManager.add(new Separator());
- menuManager.add(deleteAction);
- menuManager.add(new Separator());
- menuManager.add(createNewFolderAction);
-
- toolBarManager.add(pullAction);
- toolBarManager.add(pushAction);
- toolBarManager.add(new Separator());
- toolBarManager.add(deleteAction);
- toolBarManager.add(new Separator());
- toolBarManager.add(createNewFolderAction);
-
- mExplorer.createPanel(parent);
-
- DdmsPlugin.getDefault().addSelectionListener(this);
- }
-
- @Override
- public void setFocus() {
- mExplorer.setFocus();
- }
-
- /**
- * Sent when a new {@link Client} is selected.
- *
- * @param selectedClient The selected client.
- */
- @Override
- public void selectionChanged(Client selectedClient) {
- // pass
- }
-
- /**
- * Sent when a new {@link Device} is selected.
- *
- * @param selectedDevice the selected device.
- */
- @Override
- public void selectionChanged(IDevice selectedDevice) {
- mExplorer.switchDevice(selectedDevice);
- }
-
- /**
- * Sent when there is no current selection.
- */
- public void selectionRemoved() {
-
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/HeapView.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/HeapView.java
deleted file mode 100644
index 5745e8efc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/HeapView.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.views;
-
-import com.android.ddmuilib.HeapPanel;
-
-import org.eclipse.swt.widgets.Composite;
-
-public class HeapView extends TableView {
-
- public static final String ID = "com.android.ide.eclipse.ddms.views.HeapView"; //$NON-NLS-1$
- private HeapPanel mPanel;
-
- public HeapView() {
- }
-
- @Override
- public void createPartControl(Composite parent) {
- mPanel = new HeapPanel();
- mPanel.createPanel(parent);
-
- setSelectionDependentPanel(mPanel);
-
- // listen to focus changes for table(s) of the panel.
- setupTableFocusListener(mPanel, parent);
- }
-
- @Override
- public void setFocus() {
- mPanel.setFocus();
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/LogCatView.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/LogCatView.java
deleted file mode 100644
index 9f78c4aa1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/LogCatView.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.ddms.views;
-
-import com.android.ddmlib.logcat.LogCatMessage;
-import com.android.ddmuilib.logcat.ILogCatMessageSelectionListener;
-import com.android.ddmuilib.logcat.LogCatPanel;
-import com.android.ddmuilib.logcat.LogCatStackTraceParser;
-import com.android.ide.eclipse.ddms.DdmsPlugin;
-import com.android.ide.eclipse.ddms.JavaSourceRevealer;
-import com.android.ide.eclipse.ddms.i18n.Messages;
-import com.android.ide.eclipse.ddms.preferences.PreferenceInitializer;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.actions.ActionFactory;
-
-public class LogCatView extends SelectionDependentViewPart {
- /** LogCatView ID as defined in plugin.xml. */
- public static final String ID = "com.android.ide.eclipse.ddms.views.LogCatView"; //$NON-NLS-1$
-
- /** Switch perspective when a Java file is opened from logcat view. */
- public static final boolean DEFAULT_SWITCH_PERSPECTIVE = true;
-
- /** Target perspective to open when a Java file is opened from logcat view. */
- public static final String DEFAULT_PERSPECTIVE_ID =
- "org.eclipse.jdt.ui.JavaPerspective"; //$NON-NLS-1$
-
- private LogCatPanel mLogCatPanel;
- private LogCatStackTraceParser mStackTraceParser = new LogCatStackTraceParser();
-
- private Clipboard mClipboard;
-
- @Override
- public void createPartControl(Composite parent) {
- parent.setLayout(new FillLayout());
-
- IPreferenceStore prefStore = DdmsPlugin.getDefault().getPreferenceStore();
- mLogCatPanel = new LogCatPanel(prefStore);
- mLogCatPanel.createPanel(parent);
- setSelectionDependentPanel(mLogCatPanel);
-
- mLogCatPanel.addLogCatMessageSelectionListener(new ILogCatMessageSelectionListener() {
- @Override
- public void messageDoubleClicked(LogCatMessage m) {
- onDoubleClick(m);
- }
- });
-
- mClipboard = new Clipboard(parent.getDisplay());
- IActionBars actionBars = getViewSite().getActionBars();
- actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(),
- new Action(Messages.LogCatView_Copy) {
- @Override
- public void run() {
- mLogCatPanel.copySelectionToClipboard(mClipboard);
- }
- });
-
- actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(),
- new Action(Messages.LogCatView_Select_All) {
- @Override
- public void run() {
- mLogCatPanel.selectAll();
- }
- });
-
- actionBars.setGlobalActionHandler(ActionFactory.FIND.getId(),
- new Action("Find") {
- @Override
- public void run() {
- mLogCatPanel.showFindDialog();
- }
- });
- }
-
- @Override
- public void setFocus() {
- }
-
- private void onDoubleClick(LogCatMessage m) {
- String msg = m.getMessage();
- if (!mStackTraceParser.isValidExceptionTrace(msg)) {
- return;
- }
-
- IPreferenceStore store = DdmsPlugin.getDefault().getPreferenceStore();
- String perspectiveId = null;
- if (store.getBoolean(PreferenceInitializer.ATTR_SWITCH_PERSPECTIVE)) {
- perspectiveId = store.getString(PreferenceInitializer.ATTR_PERSPECTIVE_ID);
- }
-
-
- String fileName = mStackTraceParser.getFileName(msg);
- int lineNumber = mStackTraceParser.getLineNumber(msg);
- String methodName = mStackTraceParser.getMethodName(msg);
- JavaSourceRevealer.revealMethod(methodName, fileName, lineNumber, perspectiveId);
- }
-
- public void selectTransientAppFilter(String appName) {
- mLogCatPanel.selectTransientAppFilter(appName);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/NativeHeapView.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/NativeHeapView.java
deleted file mode 100644
index 91c8022b7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/NativeHeapView.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.views;
-
-import com.android.ddmuilib.NativeHeapPanel;
-
-import org.eclipse.swt.widgets.Composite;
-
-public class NativeHeapView extends TableView {
-
- public static final String ID =
- "com.android.ide.eclipse.ddms.views.NativeHeapView"; //$NON-NLS-1$
- private NativeHeapPanel mPanel;
-
- public NativeHeapView() {
- }
-
- @Override
- public void createPartControl(Composite parent) {
- mPanel = new NativeHeapPanel();
- mPanel.createPanel(parent);
-
- setSelectionDependentPanel(mPanel);
-
- // listen to focus changes for table(s) of the panel.
- setupTableFocusListener(mPanel, parent);
- }
-
- @Override
- public void setFocus() {
- mPanel.setFocus();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/NetworkStatisticsView.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/NetworkStatisticsView.java
deleted file mode 100644
index f90189c6d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/NetworkStatisticsView.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.views;
-
-import com.android.ddmuilib.net.NetworkPanel;
-
-import org.eclipse.swt.widgets.Composite;
-
-public class NetworkStatisticsView extends TableView {
- public static final String ID = "com.android.ide.eclipse.ddms.views.NetworkStatsView";
-
- private NetworkPanel mPanel;
-
- public NetworkStatisticsView() {
- }
-
- @Override
- public void createPartControl(Composite parent) {
- mPanel = new NetworkPanel();
- mPanel.createPanel(parent);
-
- setSelectionDependentPanel(mPanel);
-
- // listen to focus changes for table(s) of the panel.
- setupTableFocusListener(mPanel, parent);
- }
-
- @Override
- public void setFocus() {
- mPanel.setFocus();
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/OldLogCatView.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/OldLogCatView.java
deleted file mode 100644
index d0b1fb442..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/OldLogCatView.java
+++ /dev/null
@@ -1,385 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.views;
-
-import com.android.ddmlib.Log.LogLevel;
-import com.android.ddmuilib.ImageLoader;
-import com.android.ddmuilib.logcat.LogColors;
-import com.android.ddmuilib.logcat.LogFilter;
-import com.android.ddmuilib.logcat.LogPanel;
-import com.android.ddmuilib.logcat.LogPanel.ILogFilterStorageManager;
-import com.android.ddmuilib.logcat.LogPanel.LogCatViewInterface;
-import com.android.ide.eclipse.ddms.CommonAction;
-import com.android.ide.eclipse.ddms.DdmsPlugin;
-import com.android.ide.eclipse.ddms.i18n.Messages;
-import com.android.ide.eclipse.ddms.preferences.PreferenceInitializer;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Font;
-import org.eclipse.swt.graphics.FontData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IPerspectiveRegistry;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.WorkbenchException;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.ide.IDE;
-
-import java.util.ArrayList;
-
-/**
- * The log cat view displays log output from the current device selection.
- */
-public final class OldLogCatView extends SelectionDependentViewPart implements LogCatViewInterface {
-
- public static final String ID = "com.android.ide.eclipse.ddms.views.OldLogCatView"; //$NON-NLS-1$
-
- private static final String PREFS_COL_TIME =
- DdmsPlugin.PLUGIN_ID + ".logcat.time"; //$NON-NLS-1$
- private static final String PREFS_COL_LEVEL =
- DdmsPlugin.PLUGIN_ID + ".logcat.level"; //$NON-NLS-1$
- private static final String PREFS_COL_PID =
- DdmsPlugin.PLUGIN_ID + ".logcat.pid"; //$NON-NLS-1$
- private static final String PREFS_COL_TAG =
- DdmsPlugin.PLUGIN_ID + ".logcat.tag"; //$NON-NLS-1$
- private static final String PREFS_COL_MESSAGE =
- DdmsPlugin.PLUGIN_ID + ".logcat.message"; //$NON-NLS-1$
-
- private static final String PREFS_FILTERS =
- DdmsPlugin.PLUGIN_ID + ".logcat.filters"; //$NON-NLS-1$
-
- public static final String CHOICE_METHOD_DECLARATION =
- DdmsPlugin.PLUGIN_ID + ".logcat.MethodDeclaration"; //$NON-NLS-1$
- public static final String CHOICE_ERROR_LINE =
- DdmsPlugin.PLUGIN_ID + ".logcat.ErrorLine"; //$NON-NLS-1$
-
- /* Default values for the switch of perspective. */
- public static final boolean DEFAULT_SWITCH_PERSPECTIVE = true;
- public static final String DEFAULT_PERSPECTIVE_ID = "org.eclipse.jdt.ui.JavaPerspective"; //$NON-NLS-1$
- private static OldLogCatView sThis;
- private LogPanel mLogPanel;
-
- private CommonAction mCreateFilterAction;
- private CommonAction mDeleteFilterAction;
- private CommonAction mEditFilterAction;
- private CommonAction mExportAction;
-
- private CommonAction[] mLogLevelActions;
- private String[] mLogLevelIcons = {
- "v.png", //$NON-NLS-1S
- "d.png", //$NON-NLS-1S
- "i.png", //$NON-NLS-1S
- "w.png", //$NON-NLS-1S
- "e.png", //$NON-NLS-1S
- };
-
- private Action mClearAction;
-
- private Clipboard mClipboard;
-
- /**
- * An implementation of {@link ILogFilterStorageManager} to bridge to the
- * eclipse preference store, and saves the log filters.
- */
- private final class FilterStorage implements ILogFilterStorageManager {
-
- @Override
- public LogFilter[] getFilterFromStore() {
- String filterPrefs = DdmsPlugin.getDefault().getPreferenceStore().getString(
- PREFS_FILTERS);
-
- // split in a string per filter
- String[] filters = filterPrefs.split("\\|"); //$NON-NLS-1$
-
- ArrayList<LogFilter> list =
- new ArrayList<LogFilter>(filters.length);
-
- for (String f : filters) {
- if (f.length() > 0) {
- LogFilter logFilter = new LogFilter();
- if (logFilter.loadFromString(f)) {
- list.add(logFilter);
- }
- }
- }
-
- return list.toArray(new LogFilter[list.size()]);
- }
-
- @Override
- public void saveFilters(LogFilter[] filters) {
- StringBuilder sb = new StringBuilder();
- for (LogFilter f : filters) {
- String filterString = f.toString();
- sb.append(filterString);
- sb.append('|');
- }
-
- DdmsPlugin.getDefault().getPreferenceStore().setValue(PREFS_FILTERS, sb.toString());
- }
-
- @Override
- public boolean requiresDefaultFilter() {
- return true;
- }
- }
-
- public OldLogCatView() {
- sThis = this;
- LogPanel.PREFS_TIME = PREFS_COL_TIME;
- LogPanel.PREFS_LEVEL = PREFS_COL_LEVEL;
- LogPanel.PREFS_PID = PREFS_COL_PID;
- LogPanel.PREFS_TAG = PREFS_COL_TAG;
- LogPanel.PREFS_MESSAGE = PREFS_COL_MESSAGE;
- }
-
- /**
- * Returns the singleton instance.
- */
- public static OldLogCatView getInstance() {
- return sThis;
- }
-
- /**
- * Sets the display font.
- *
- * @param font The font.
- */
- public static void setFont(Font font) {
- if (sThis != null && sThis.mLogPanel != null) {
- sThis.mLogPanel.setFont(font);
- }
- }
-
- @Override
- public void createPartControl(Composite parent) {
- Display d = parent.getDisplay();
- LogColors colors = new LogColors();
-
- ImageLoader loader = ImageLoader.getDdmUiLibLoader();
-
- colors.infoColor = new Color(d, 0, 127, 0);
- colors.debugColor = new Color(d, 0, 0, 127);
- colors.errorColor = new Color(d, 255, 0, 0);
- colors.warningColor = new Color(d, 255, 127, 0);
- colors.verboseColor = new Color(d, 0, 0, 0);
-
- mCreateFilterAction = new CommonAction(Messages.LogCatView_Create_Filter) {
- @Override
- public void run() {
- mLogPanel.addFilter();
- }
- };
- mCreateFilterAction.setToolTipText(Messages.LogCatView_Create_Filter_Tooltip);
- mCreateFilterAction.setImageDescriptor(loader.loadDescriptor("add.png")); //$NON-NLS-1$
-
- mEditFilterAction = new CommonAction(Messages.LogCatView_Edit_Filter) {
- @Override
- public void run() {
- mLogPanel.editFilter();
- }
- };
- mEditFilterAction.setToolTipText(Messages.LogCatView_Edit_Filter_Tooltip);
- mEditFilterAction.setImageDescriptor(loader.loadDescriptor("edit.png")); //$NON-NLS-1$
-
- mDeleteFilterAction = new CommonAction(Messages.LogCatView_Delete_Filter) {
- @Override
- public void run() {
- mLogPanel.deleteFilter();
- }
- };
- mDeleteFilterAction.setToolTipText(Messages.LogCatView_Delete_Filter_Tooltip);
- mDeleteFilterAction.setImageDescriptor(loader.loadDescriptor("delete.png")); //$NON-NLS-1$
-
- mExportAction = new CommonAction(Messages.LogCatView_Export_Selection_As_Text) {
- @Override
- public void run() {
- mLogPanel.save();
- }
- };
- mExportAction.setToolTipText(Messages.LogCatView_Export_Selection_As_Text_Tooltip);
- mExportAction.setImageDescriptor(loader.loadDescriptor("save.png")); //$NON-NLS-1$
-
- LogLevel[] levels = LogLevel.values();
- mLogLevelActions = new CommonAction[mLogLevelIcons.length];
- for (int i = 0; i < mLogLevelActions.length; i++) {
- String name = levels[i].getStringValue();
- mLogLevelActions[i] = new CommonAction(name, IAction.AS_CHECK_BOX) {
- @Override
- public void run() {
- // disable the other actions and record current index
- for (int j = 0; j < mLogLevelActions.length; j++) {
- Action a = mLogLevelActions[j];
- if (a == this) {
- a.setChecked(true);
-
- // set the log level
- mLogPanel.setCurrentFilterLogLevel(j + 2);
- } else {
- a.setChecked(false);
- }
- }
- }
- };
-
- mLogLevelActions[i].setToolTipText(name);
- mLogLevelActions[i].setImageDescriptor(loader.loadDescriptor(mLogLevelIcons[i]));
- }
-
- mClearAction = new Action(Messages.LogCatView_Clear_Log) {
- @Override
- public void run() {
- mLogPanel.clear();
- }
- };
- mClearAction.setImageDescriptor(loader.loadDescriptor("clear.png")); //$NON-NLS-1$
-
- // now create the log view
- mLogPanel = new LogPanel(colors, new FilterStorage(), LogPanel.FILTER_MANUAL);
- mLogPanel.setLogCatViewInterface(this);
- mLogPanel.setActions(mDeleteFilterAction, mEditFilterAction, mLogLevelActions);
-
- // get the font
- String fontStr = DdmsPlugin.getDefault().getPreferenceStore().getString(
- PreferenceInitializer.ATTR_LOGCAT_FONT);
- if (fontStr != null) {
- FontData data = new FontData(fontStr);
-
- if (fontStr != null) {
- mLogPanel.setFont(new Font(parent.getDisplay(), data));
- }
- }
-
- mLogPanel.createPanel(parent);
- setSelectionDependentPanel(mLogPanel);
-
- // place the actions.
- placeActions();
-
- // setup the copy action
- mClipboard = new Clipboard(d);
- IActionBars actionBars = getViewSite().getActionBars();
- actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(), new Action(
- Messages.LogCatView_Copy) {
- @Override
- public void run() {
- mLogPanel.copy(mClipboard);
- }
- });
-
- // setup the select all action
- actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(),
- new Action(Messages.LogCatView_Select_All) {
- @Override
- public void run() {
- mLogPanel.selectAll();
- }
- });
- }
-
- @Override
- public void dispose() {
- mLogPanel.stopLogCat(true);
- mClipboard.dispose();
- }
-
- @Override
- public void setFocus() {
- mLogPanel.setFocus();
- }
-
- /**
- * Place the actions in the ui.
- */
- private void placeActions() {
- IActionBars actionBars = getViewSite().getActionBars();
-
- // first in the menu
- IMenuManager menuManager = actionBars.getMenuManager();
- menuManager.add(mCreateFilterAction);
- menuManager.add(mEditFilterAction);
- menuManager.add(mDeleteFilterAction);
- menuManager.add(new Separator());
- menuManager.add(mClearAction);
- menuManager.add(new Separator());
- menuManager.add(mExportAction);
-
- // and then in the toolbar
- IToolBarManager toolBarManager = actionBars.getToolBarManager();
- for (CommonAction a : mLogLevelActions) {
- toolBarManager.add(a);
- }
- toolBarManager.add(new Separator());
- toolBarManager.add(mCreateFilterAction);
- toolBarManager.add(mEditFilterAction);
- toolBarManager.add(mDeleteFilterAction);
- toolBarManager.add(new Separator());
- toolBarManager.add(mClearAction);
- }
-
- void openFile(IFile file, IMarker marker) {
- try {
- IWorkbenchPage page = getViewSite().getWorkbenchWindow()
- .getActivePage();
- if (page != null) {
- IDE.openEditor(page, marker);
- marker.delete();
- }
- } catch (CoreException e) {
- Status s = new Status(Status.ERROR, DdmsPlugin.PLUGIN_ID, e.getMessage(), e);
- DdmsPlugin.getDefault().getLog().log(s);
- }
- }
-
- void switchPerspective() {
- IPreferenceStore store = DdmsPlugin.getDefault().getPreferenceStore();
- if (store.getBoolean(PreferenceInitializer.ATTR_SWITCH_PERSPECTIVE)) {
- IWorkbench workbench = PlatformUI.getWorkbench();
- IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
- IPerspectiveRegistry perspectiveRegistry = workbench.getPerspectiveRegistry();
- String perspectiveId = store.getString(PreferenceInitializer.ATTR_PERSPECTIVE_ID);
- if (perspectiveId != null
- && perspectiveId.length() > 0
- && perspectiveRegistry.findPerspectiveWithId(perspectiveId) != null) {
- try {
- workbench.showPerspective(perspectiveId, window);
- } catch (WorkbenchException e) {
- e.printStackTrace();
- }
- }
- }
- }
-
- @Override
- public void onDoubleClick() {
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/SelectionDependentViewPart.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/SelectionDependentViewPart.java
deleted file mode 100644
index 3326d0138..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/SelectionDependentViewPart.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.views;
-
-import com.android.ddmlib.Client;
-import com.android.ddmlib.IDevice;
-import com.android.ddmuilib.SelectionDependentPanel;
-import com.android.ide.eclipse.ddms.DdmsPlugin;
-import com.android.ide.eclipse.ddms.DdmsPlugin.ISelectionListener;
-
-import org.eclipse.swt.graphics.Device;
-import org.eclipse.ui.part.ViewPart;
-
-/**
- * A Workbench {@link ViewPart} that requires {@link Device}/{@link Client} selection notifications
- * from {@link DdmsPlugin} through the {@link ISelectionListener} interface.
- */
-public abstract class SelectionDependentViewPart extends ViewPart implements ISelectionListener {
-
- private SelectionDependentPanel mPanel;
-
- protected final void setSelectionDependentPanel(SelectionDependentPanel panel) {
- // remember the panel
- mPanel = panel;
-
- // and add ourself as listener of selection events.
- DdmsPlugin.getDefault().addSelectionListener(this);
- }
-
- @Override
- public void dispose() {
- DdmsPlugin.getDefault().removeSelectionListener(this);
- super.dispose();
- }
-
- /**
- * Sent when a new {@link Client} is selected.
- * @param selectedClient The selected client.
- *
- * @see ISelectionListener
- */
- @Override
- public final void selectionChanged(Client selectedClient) {
- mPanel.clientSelected(selectedClient);
- }
-
- /**
- * Sent when a new {@link Device} is selected.
- * @param selectedDevice the selected device.
- *
- * @see ISelectionListener
- */
- @Override
- public final void selectionChanged(IDevice selectedDevice) {
- mPanel.deviceSelected(selectedDevice);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/SysInfoView.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/SysInfoView.java
deleted file mode 100644
index e4939250e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/SysInfoView.java
+++ /dev/null
@@ -1,29 +0,0 @@
-package com.android.ide.eclipse.ddms.views;
-
-import com.android.ddmuilib.SysinfoPanel;
-
-import org.eclipse.swt.widgets.Composite;
-
-public class SysInfoView extends SelectionDependentViewPart {
- public static final String ID = "com.android.ide.eclipse.ddms.views.SysInfoView"; //$NON-NLS-1$
-
- private SysinfoPanel mSysInfoPanel;
-
- @Override
- public void createPartControl(Composite parent) {
- mSysInfoPanel = new SysinfoPanel();
- mSysInfoPanel.createPanel(parent);
- setSelectionDependentPanel(mSysInfoPanel);
- }
-
- @Override
- public void setFocus() {
- mSysInfoPanel.setFocus();
- }
-
- @Override
- public void dispose() {
- mSysInfoPanel.dispose();
- super.dispose();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/TableView.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/TableView.java
deleted file mode 100644
index 1f9f0db53..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/TableView.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.views;
-
-import com.android.ddmuilib.ITableFocusListener;
-import com.android.ddmuilib.ITableFocusListener.IFocusedTableActivator;
-import com.android.ddmuilib.TablePanel;
-import com.android.ide.eclipse.ddms.i18n.Messages;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.actions.ActionFactory;
-
-/**
- * Base class for view containing Table that needs to support copy, and select
- * all.
- */
-public abstract class TableView extends SelectionDependentViewPart {
-
- /** Activator for the current Table that has the focus */
- IFocusedTableActivator mActivator = null;
-
- private Clipboard mClipboard;
-
- private Action mCopyAction;
- private Action mSelectAllAction;
-
- /**
- * Setup the listener for the Table objects of <code>Panel</code>, and setup
- * the copy and select all actions.
- *
- * @param panel The panel to setup
- * @param parent The parent composite of the Panel's content.
- */
- void setupTableFocusListener(TablePanel panel, Composite parent) {
- panel.setTableFocusListener(new ITableFocusListener() {
- @Override
- public void focusGained(IFocusedTableActivator activator) {
- mActivator = activator;
- mCopyAction.setEnabled(true);
- mSelectAllAction.setEnabled(true);
- }
-
- @Override
- public void focusLost(IFocusedTableActivator activator) {
- if (activator == mActivator) {
- mActivator = null;
- mCopyAction.setEnabled(false);
- mSelectAllAction.setEnabled(false);
- }
- }
- });
-
- // setup the copy action
- mClipboard = new Clipboard(parent.getDisplay());
- IActionBars actionBars = getViewSite().getActionBars();
- actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(),
- mCopyAction = new Action(Messages.TableView_Copy) {
- @Override
- public void run() {
- if (mActivator != null) {
- mActivator.copy(mClipboard);
- }
- }
- });
-
- // setup the select all action
- actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(),
- mSelectAllAction = new Action(Messages.TableView_Select_All) {
- @Override
- public void run() {
- if (mActivator != null) {
- mActivator.selectAll();
- }
- }
- });
-
- }
-
- @Override
- public void dispose() {
- super.dispose();
- mClipboard.dispose();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/ThreadView.java b/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/ThreadView.java
deleted file mode 100644
index 9d4eeb74a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ddms/src/com/android/ide/eclipse/ddms/views/ThreadView.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ddms.views;
-
-import com.android.ddmuilib.ThreadPanel;
-
-import org.eclipse.swt.widgets.Composite;
-
-public class ThreadView extends TableView {
-
- public static final String ID =
- "com.android.ide.eclipse.ddms.views.ThreadView"; //$NON-NLS-1$
- private ThreadPanel mPanel;
-
- public ThreadView() {
- }
-
- @Override
- public void createPartControl(Composite parent) {
- mPanel = new ThreadPanel();
- mPanel.createPanel(parent);
-
- setSelectionDependentPanel(mPanel);
-
- // listen to focus changes for table(s) of the panel.
- setupTableFocusListener(mPanel, parent);
- }
-
- @Override
- public void setFocus() {
- mPanel.setFocus();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/.classpath b/eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/.classpath
deleted file mode 100644
index 2abf48333..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/.classpath
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry kind="src" path="src"/>
- <classpathentry kind="lib" path="/plugin-gldebugger/libs/host-libprotobuf-java-2.3.0-lite.jar"/>
- <classpathentry kind="lib" path="/plugin-gldebugger/libs/liblzf-1.0.jar"/>
- <classpathentry combineaccessrules="false" kind="src" path="/ddmlib"/>
- <classpathentry combineaccessrules="false" kind="src" path="/ddmuilib"/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/.project b/eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/.project
deleted file mode 100644
index ef19c361d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/.project
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>plugin-gldebugger-tests</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/META-INF/MANIFEST.MF b/eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/META-INF/MANIFEST.MF
deleted file mode 100644
index 240874b8b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,10 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: gldebugger-tests
-Bundle-SymbolicName: com.android.ide.eclipse.gldebugger.tests
-Bundle-Version: 24.3.3.qualifier
-Bundle-RequiredExecutionEnvironment: J2SE-1.5
-Require-Bundle: org.junit4;bundle-version="4.5.0";resolution:=optional,
- com.android.ide.eclipse.gldebugger,
- org.eclipse.swt,
- org.junit;bundle-version="4.11.0";resolution:=optional
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/build.properties b/eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/build.properties
deleted file mode 100644
index 34d2e4d2d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/build.properties
+++ /dev/null
@@ -1,4 +0,0 @@
-source.. = src/
-output.. = bin/
-bin.includes = META-INF/,\
- .
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/pom.xml b/eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/pom.xml
deleted file mode 100644
index f87e88afe..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/pom.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <version>24.3.3-SNAPSHOT</version>
- <artifactId>com.android.ide.eclipse.gldebugger.tests</artifactId>
- <packaging>eclipse-test-plugin</packaging>
- <name>gldebugger.tests</name>
-
- <parent>
- <relativePath>../../pom.xml</relativePath>
- <groupId>adt.group</groupId>
- <artifactId>parent</artifactId>
- <version>1.0.0-SNAPSHOT</version>
- </parent>
-</project>
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/src/com/android/ide/eclipse/gltrace/format/GLAPISpecTest.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/src/com/android/ide/eclipse/gltrace/format/GLAPISpecTest.java
deleted file mode 100644
index 4a4d0706c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/src/com/android/ide/eclipse/gltrace/format/GLAPISpecTest.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.format;
-
-import static org.junit.Assert.*;
-
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.Type;
-
-import org.junit.Test;
-
-import java.util.Arrays;
-import java.util.List;
-
-public class GLAPISpecTest {
- @Test
- public void testParser() {
- String returnType = "void";
- String funcName = "glDiscardFramebufferEXT";
- List<String> args = Arrays.asList(
- "GLenum target",
- "GLsizei numAttachments",
- "const GLenum* attachments");
-
- GLAPISpec spec = GLAPISpec.parseLine(createSpec(returnType, funcName, args));
-
- assertEquals(Type.VOID, spec.getReturnValue().getDataType());
- assertEquals(returnType, spec.getReturnValue().getCType());
- assertEquals(funcName, spec.getFunction());
-
- List<GLDataTypeSpec> argSpecs = spec.getArgs();
- assertEquals(argSpecs.size(), args.size());
-
- GLDataTypeSpec argSpec = argSpecs.get(0);
- assertEquals(argSpec.getArgName(), "target");
- assertEquals(argSpec.getDataType(), Type.ENUM);
- assertEquals(argSpec.isPointer(), false);
-
- argSpec = argSpecs.get(2);
- assertEquals(argSpec.getArgName(), "attachments");
- assertEquals(argSpec.getDataType(), Type.ENUM);
- assertEquals(argSpec.isPointer(), true);
- }
-
- private String createSpec(String returnType, String funcName, List<String> args) {
- StringBuffer sb = new StringBuffer();
- sb.append(String.format("%s, %s", returnType, funcName));
-
- if (args != null) {
- sb.append(", ");
- for (int i = 0; i < args.size(); i++) {
- sb.append(args.get(i));
- if (i != args.size() - 1) {
- sb.append(", ");
- }
- }
- }
-
- return sb.toString();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/src/com/android/ide/eclipse/gltrace/format/GLMessageFormatterTest.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/src/com/android/ide/eclipse/gltrace/format/GLMessageFormatterTest.java
deleted file mode 100644
index 5d1804102..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger.tests/src/com/android/ide/eclipse/gltrace/format/GLMessageFormatterTest.java
+++ /dev/null
@@ -1,195 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.format;
-
-import static org.junit.Assert.*;
-
-import com.android.ide.eclipse.gltrace.GLEnum;
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage;
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.Builder;
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType;
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.Type;
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.Function;
-import com.google.protobuf.ByteString;
-
-import org.junit.Test;
-
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-public class GLMessageFormatterTest {
- private static final List<String> API_SPECS = Arrays.asList(
- "void, glBindBuffer, GLenum target, GLuint buffer",
- "const GLchar*, glGetString, GLenum name",
- "void, glMultMatrixf, const GLfloat* m",
- "GLenum, eglBindAPI, GLEnum arg",
- "void, glGetActiveAttrib, GLenum* type",
- "void, glTexImage2D, GLint level, GLsizei width, const GLvoid* pixels");
- private static GLMessageFormatter sGLMessageFormatter;
-
- static {
- Map<String, GLAPISpec> specs = new HashMap<String, GLAPISpec>(API_SPECS.size());
-
- for (String specString: API_SPECS) {
- GLAPISpec spec = GLAPISpec.parseLine(specString);
- specs.put(spec.getFunction(), spec);
- }
-
- sGLMessageFormatter = new GLMessageFormatter(specs);
- }
-
- @Test
- public void testBindBuffer() {
- GLEnum arg1 = GLEnum.GL_ELEMENT_ARRAY_BUFFER;
- int arg2 = 10;
-
- GLMessage msg = constructGLMessage(null, Function.glBindBuffer,
- createEnumDataType((int)arg1.value),
- createIntegerDataType(arg2));
-
- String expected = String.format("glBindBuffer(target = %s, buffer = %s)",
- arg1.toString(),
- Integer.toString(arg2));
- String actual = sGLMessageFormatter.formatGLMessage(msg);
-
- assertEquals(expected, actual);
- }
-
- @Test
- public void testGlGetString() {
- String retValue = "testString";
- GLEnum arg1 = GLEnum.GL_RENDERER;
-
- GLMessage msg = constructGLMessage(
- createStringDataType(retValue),
- Function.glGetString,
- createEnumDataType((int)arg1.value));
- String expected = String.format("%s(name = %s) = (const GLchar*) %s", Function.glGetString,
- arg1.toString(), retValue);
- String actual = sGLMessageFormatter.formatGLMessage(msg);
-
- assertEquals(expected, actual);
- }
-
- @Test
- public void testGLEnum0() {
- // an enum of value 0 should equal GL_POINTS if it is an argument,
- // and GL_NO_ERROR if it is a return value
- GLMessage msg = constructGLMessage(
- createEnumDataType(0),
- Function.eglBindAPI,
- createEnumDataType(0));
- String expected = "eglBindAPI(arg = GL_POINTS) = (GLenum) GL_NO_ERROR";
- String actual = sGLMessageFormatter.formatGLMessage(msg);
-
- assertEquals(expected, actual);
- }
-
- @Test
- public void testMessageWithPointer() {
- GLMessage msg = constructGLMessage(null,
- Function.glTexImage2D,
- createIntegerDataType(1),
- createIntegerDataType(2),
- createIntegerPointerDataType(0xbadc0ffe));
- String expected = "glTexImage2D(level = 1, width = 2, pixels = 0xbadc0ffe)";
- String actual = sGLMessageFormatter.formatGLMessage(msg);
-
- assertEquals(expected, actual);
- }
-
- @Test
- public void testMessageWithMismatchedPointer() {
- // "void, glMultMatrixf, const GLfloat* m",
- GLMessage msg = constructGLMessage(null,
- Function.glMultMatrixf,
- createIntegerDataType(0xbadc0ffe));
-
- String expected = "glMultMatrixf(m = 0xbadc0ffe)";
- String actual = sGLMessageFormatter.formatGLMessage(msg);
-
- assertEquals(expected, actual);
- }
-
- @Test
- public void testMessageWithEnumPointer() {
- //void, glGetActiveAttrib, GLenum* type
- GLMessage msg = constructGLMessage(null,
- Function.glGetActiveAttrib,
- createIntegerPointerDataType((int)GLEnum.GL_FLOAT_MAT4.value));
-
- String expected = "glGetActiveAttrib(type = [GL_FLOAT_MAT4])";
- String actual = sGLMessageFormatter.formatGLMessage(msg);
-
- assertEquals(expected, actual);
- }
-
- private DataType createStringDataType(String retValue) {
- return DataType.newBuilder()
- .addCharValue(ByteString.copyFromUtf8(retValue))
- .setIsArray(true)
- .setType(Type.CHAR)
- .build();
- }
-
- private DataType createIntegerDataType(int val) {
- return DataType.newBuilder()
- .addIntValue(val)
- .setIsArray(false)
- .setType(Type.INT)
- .build();
- }
-
- private DataType createIntegerPointerDataType(int val) {
- return DataType.newBuilder()
- .addIntValue(val)
- .setIsArray(true)
- .setType(Type.INT)
- .build();
- }
-
- private DataType createEnumDataType(int val) {
- return DataType.newBuilder()
- .addIntValue(val)
- .setIsArray(false)
- .setType(Type.ENUM)
- .build();
- }
-
- private GLMessage constructGLMessage(DataType retValue, Function func, DataType...args) {
- Builder builder = GLMessage.newBuilder();
- builder.setFunction(func);
-
- // set required fields we don't care about in these tests
- builder.setContextId(0);
- builder.setStartTime(0);
- builder.setDuration(0);
-
- // set return value if any
- if (retValue != null) {
- builder.setReturnValue(retValue);
- }
-
- for (DataType arg: args) {
- builder.addArgs(arg);
- }
-
- return builder.build();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/.classpath b/eclipse/plugins/com.android.ide.eclipse.gldebugger/.classpath
deleted file mode 100755
index aaeec62f7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/.classpath
+++ /dev/null
@@ -1,9 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry kind="src" path="src"/>
- <classpathentry kind="lib" path="libs/host-libprotobuf-java-2.3.0-lite.jar"/>
- <classpathentry kind="lib" path="libs/liblzf-1.0.jar" />
- <classpathentry kind="output" path="bin"/>
-</classpath>
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/.project b/eclipse/plugins/com.android.ide.eclipse.gldebugger/.project
deleted file mode 100755
index 0327756af..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/.project
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>plugin-gldebugger</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/.settings/org.eclipse.jdt.core.prefs b/eclipse/plugins/com.android.ide.eclipse.gldebugger/.settings/org.eclipse.jdt.core.prefs
deleted file mode 100644
index ea661960a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/.settings/org.eclipse.jdt.core.prefs
+++ /dev/null
@@ -1,98 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore
-org.eclipse.jdt.core.compiler.annotation.nonnull=com.android.annotations.NonNull
-org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=com.android.annotations.NonNullByDefault
-org.eclipse.jdt.core.compiler.annotation.nonnullisdefault=disabled
-org.eclipse.jdt.core.compiler.annotation.nullable=com.android.annotations.Nullable
-org.eclipse.jdt.core.compiler.annotation.nullanalysis=enabled
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
-org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
-org.eclipse.jdt.core.compiler.compliance=1.6
-org.eclipse.jdt.core.compiler.debug.lineNumber=generate
-org.eclipse.jdt.core.compiler.debug.localVariable=generate
-org.eclipse.jdt.core.compiler.debug.sourceFile=generate
-org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
-org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
-org.eclipse.jdt.core.compiler.problem.deadCode=warning
-org.eclipse.jdt.core.compiler.problem.deprecation=warning
-org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
-org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
-org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
-org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore
-org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning
-org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled
-org.eclipse.jdt.core.compiler.problem.fieldHiding=warning
-org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
-org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
-org.eclipse.jdt.core.compiler.problem.forbiddenReference=error
-org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
-org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=enabled
-org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
-org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning
-org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
-org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning
-org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
-org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore
-org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled
-org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=warning
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=error
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
-org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
-org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
-org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
-org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
-org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
-org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=warning
-org.eclipse.jdt.core.compiler.problem.nullReference=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecInsufficientInfo=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecViolation=warning
-org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=ignore
-org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
-org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
-org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullSpecViolation=error
-org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=warning
-org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=warning
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
-org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
-org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
-org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=enabled
-org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
-org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
-org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning
-org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=disabled
-org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
-org.eclipse.jdt.core.compiler.problem.unclosedCloseable=error
-org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
-org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
-org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning
-org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
-org.eclipse.jdt.core.compiler.problem.unusedImport=warning
-org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
-org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
-org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=warning
-org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
-org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
-org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
-org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
-org.eclipse.jdt.core.compiler.source=1.6
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/META-INF/MANIFEST.MF b/eclipse/plugins/com.android.ide.eclipse.gldebugger/META-INF/MANIFEST.MF
deleted file mode 100644
index 96177db76..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,23 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: Tracer for OpenGL ES
-Bundle-SymbolicName: com.android.ide.eclipse.gldebugger;singleton:=true
-Bundle-Version: 24.3.3.qualifier
-Bundle-Activator: com.android.ide.eclipse.gltrace.GlTracePlugin
-Require-Bundle: org.eclipse.ui,
- org.eclipse.core.runtime,
- org.eclipse.ui.ide,
- org.eclipse.core.resources,
- org.eclipse.core.filesystem,
- org.eclipse.ui.console,
- com.android.ide.eclipse.ddms,
- com.android.ide.eclipse.base
-Bundle-ActivationPolicy: lazy
-Bundle-ClassPath: libs/host-libprotobuf-java-2.3.0-lite.jar,
- libs/liblzf-1.0.jar,
- .
-Bundle-Vendor: The Android Open Source Project
-Export-Package: com.android.ide.eclipse.gltrace;x-friends:="com.android.ide.eclipse.gldebugger.tests",
- com.android.ide.eclipse.gltrace.format;x-friends:="com.android.ide.eclipse.gldebugger.tests",
- com.android.ide.eclipse.gltrace.model;x-friends:="com.android.ide.eclipse.gldebugger.tests"
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/build.properties b/eclipse/plugins/com.android.ide.eclipse.gldebugger/build.properties
deleted file mode 100644
index 4f3d57a4b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/build.properties
+++ /dev/null
@@ -1,8 +0,0 @@
-source.. = src/
-output.. = bin/
-bin.includes = plugin.xml,\
- META-INF/,\
- .,\
- libs/,\
- icons/,\
- entries.in,
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/entries.in b/eclipse/plugins/com.android.ide.eclipse.gldebugger/entries.in
deleted file mode 100644
index 46f27974b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/entries.in
+++ /dev/null
@@ -1,549 +0,0 @@
-# com.android.ide.eclipse.gltrace.glentries, v1
-# This file is a slightly processed version of $ANDROID_SRC/frameworks/base/opengl/libs/entries.in
-# The only differences are that the GL_ENTRY() text is removed, and all pointers are associated
-# with the data type as opposed to the variable name. e.g. "void *data" will is converted to
-# "void* data".
-void, eglCreateContext, int version, int context
-void, eglMakeCurrent, int context
-void, glActiveShaderProgramEXT, GLuint pipeline, GLuint program
-void, glActiveTexture, GLenum texture
-void, glAlphaFunc, GLenum func, GLclampf ref
-void, glAlphaFuncQCOM, GLenum func, GLclampf ref
-void, glAlphaFuncx, GLenum func, GLclampx ref
-void, glAlphaFuncxOES, GLenum func, GLclampx ref
-void, glAttachShader, GLuint program, GLuint shader
-void, glBeginPerfMonitorAMD, GLuint monitor
-void, glBeginQuery, GLenum target, GLuint id
-void, glBeginQueryEXT, GLenum target, GLuint id
-void, glBeginTransformFeedback, GLenum primitiveMode
-void, glBindAttribLocation, GLuint program, GLuint index, const GLchar* name
-void, glBindBuffer, GLenum target, GLuint buffer
-void, glBindBufferBase, GLenum target, GLuint index, GLuint buffer
-void, glBindBufferRange, GLenum target, GLuint index, GLuint buffer, GLintptr offset, GLsizeiptr size
-void, glBindFramebuffer, GLenum target, GLuint framebuffer
-void, glBindFramebufferOES, GLenum target, GLuint framebuffer
-void, glBindProgramPipelineEXT, GLuint pipeline
-void, glBindRenderbuffer, GLenum target, GLuint renderbuffer
-void, glBindRenderbufferOES, GLenum target, GLuint renderbuffer
-void, glBindSampler, GLuint unit, GLuint sampler
-void, glBindTexture, GLenum target, GLuint texture
-void, glBindTransformFeedback, GLenum target, GLuint id
-void, glBindVertexArray, GLuint array
-void, glBindVertexArrayOES, GLuint array
-void, glBlendColor, GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha
-void, glBlendEquation, GLenum mode
-void, glBlendEquationOES, GLenum mode
-void, glBlendEquationSeparate, GLenum modeRGB, GLenum modeAlpha
-void, glBlendEquationSeparateOES, GLenum modeRGB, GLenum modeAlpha
-void, glBlendFunc, GLenum sfactor, GLenum dfactor
-void, glBlendFuncSeparate, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha
-void, glBlendFuncSeparateOES, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha
-void, glBlitFramebuffer, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter
-void, glBlitFramebufferANGLE, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter
-void, glBufferData, GLenum target, GLsizeiptr size, const GLvoid* data, GLenum usage
-void, glBufferSubData, GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid* data
-GLenum, glCheckFramebufferStatus, GLenum target
-GLenum, glCheckFramebufferStatusOES, GLenum target
-void, glClear, GLbitfield mask
-void, glClearBufferfi, GLenum buffer, GLint drawbuffer, GLfloat depth, GLint stencil
-void, glClearBufferfv, GLenum buffer, GLint drawbuffer, const GLfloat* value
-void, glClearBufferiv, GLenum buffer, GLint drawbuffer, const GLint* value
-void, glClearBufferuiv, GLenum buffer, GLint drawbuffer, const GLuint* value
-void, glClearColor, GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha
-void, glClearColorx, GLclampx red, GLclampx green, GLclampx blue, GLclampx alpha
-void, glClearColorxOES, GLclampx red, GLclampx green, GLclampx blue, GLclampx alpha
-void, glClearDepthf, GLclampf depth
-void, glClearDepthfOES, GLclampf depth
-void, glClearDepthx, GLclampx depth
-void, glClearDepthxOES, GLclampx depth
-void, glClearStencil, GLint s
-void, glClientActiveTexture, GLenum texture
-GLenum, glClientWaitSync, GLsync sync, GLbitfield flags, GLuint64 timeout
-void, glClipPlanef, GLenum plane, const GLfloat* equation
-void, glClipPlanefIMG, GLenum p, const GLfloat* eqn
-void, glClipPlanefOES, GLenum plane, const GLfloat* equation
-void, glClipPlanex, GLenum plane, const GLfixed* equation
-void, glClipPlanexIMG, GLenum p, const GLfixed* eqn
-void, glClipPlanexOES, GLenum plane, const GLfixed* equation
-void, glColor4f, GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha
-void, glColor4ub, GLubyte red, GLubyte green, GLubyte blue, GLubyte alpha
-void, glColor4x, GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha
-void, glColor4xOES, GLfixed red, GLfixed green, GLfixed blue, GLfixed alpha
-void, glColorMask, GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha
-void, glColorPointer, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer
-void, glCompileShader, GLuint shader
-void, glCompressedTexImage2D, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid* data
-void, glCompressedTexImage3D, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid* data
-void, glCompressedTexImage3DOES, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLsizei imageSize, const GLvoid* data
-void, glCompressedTexSubImage2D, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid* data
-void, glCompressedTexSubImage3D, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid* data
-void, glCompressedTexSubImage3DOES, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLsizei imageSize, const GLvoid* data
-void, glCopyBufferSubData, GLenum readTarget, GLenum writeTarget, GLintptr readOffset, GLintptr writeOffset, GLsizeiptr size
-void, glCopyTexImage2D, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border
-void, glCopyTexSubImage2D, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height
-void, glCopyTexSubImage3D, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height
-void, glCopyTexSubImage3DOES, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLint x, GLint y, GLsizei width, GLsizei height
-void, glCoverageMaskNV, GLboolean mask
-void, glCoverageOperationNV, GLenum operation
-GLuint, glCreateProgram, void
-GLuint, glCreateShader, GLenum type
-GLuint, glCreateShaderProgramvEXT, GLenum type, GLsizei count, const GLchar** strings
-void, glCullFace, GLenum mode
-void, glCurrentPaletteMatrixOES, GLuint matrixpaletteindex
-void, glDeleteBuffers, GLsizei n, const GLuint* buffers
-void, glDeleteFencesNV, GLsizei n, const GLuint* fences
-void, glDeleteFramebuffers, GLsizei n, const GLuint* framebuffers
-void, glDeleteFramebuffersOES, GLsizei n, const GLuint* framebuffers
-void, glDeletePerfMonitorsAMD, GLsizei n, GLuint* monitors
-void, glDeleteProgram, GLuint program
-void, glDeleteProgramPipelinesEXT, GLsizei n, const GLuint* pipelines
-void, glDeleteQueries, GLsizei n, const GLuint* ids
-void, glDeleteQueriesEXT, GLsizei n, const GLuint* ids
-void, glDeleteRenderbuffers, GLsizei n, const GLuint* renderbuffers
-void, glDeleteRenderbuffersOES, GLsizei n, const GLuint* renderbuffers
-void, glDeleteSamplers, GLsizei count, const GLuint* samplers
-void, glDeleteShader, GLuint shader
-void, glDeleteSync, GLsync sync
-void, glDeleteTextures, GLsizei n, const GLuint* textures
-void, glDeleteTransformFeedbacks, GLsizei n, const GLuint* ids
-void, glDeleteVertexArrays, GLsizei n, const GLuint* arrays
-void, glDeleteVertexArraysOES, GLsizei n, const GLuint* arrays
-void, glDepthFunc, GLenum func
-void, glDepthMask, GLboolean flag
-void, glDepthRangef, GLclampf zNear, GLclampf zFar
-void, glDepthRangefOES, GLclampf zNear, GLclampf zFar
-void, glDepthRangex, GLclampx zNear, GLclampx zFar
-void, glDepthRangexOES, GLclampx zNear, GLclampx zFar
-void, glDetachShader, GLuint program, GLuint shader
-void, glDisable, GLenum cap
-void, glDisableClientState, GLenum array
-void, glDisableDriverControlQCOM, GLuint driverControl
-void, glDisableVertexAttribArray, GLuint index
-void, glDiscardFramebufferEXT, GLenum target, GLsizei numAttachments, const GLenum* attachments
-void, glDrawArrays, GLenum mode, GLint first, GLsizei count
-void, glDrawArraysInstanced, GLenum mode, GLint first, GLsizei count, GLsizei instanceCount
-void, glDrawBuffers, GLsizei n, const GLenum* bufs
-void, glDrawBuffersNV, GLsizei n, const GLenum* bufs
-void, glDrawElements, GLenum mode, GLsizei count, GLenum type, const GLvoid* indices
-void, glDrawElementsInstanced, GLenum mode, GLsizei count, GLenum type, const GLvoid* indices, GLsizei instanceCount
-void, glDrawRangeElements, GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const GLvoid* indices
-void, glDrawTexfOES, GLfloat x, GLfloat y, GLfloat z, GLfloat width, GLfloat height
-void, glDrawTexfvOES, const GLfloat* coords
-void, glDrawTexiOES, GLint x, GLint y, GLint z, GLint width, GLint height
-void, glDrawTexivOES, const GLint* coords
-void, glDrawTexsOES, GLshort x, GLshort y, GLshort z, GLshort width, GLshort height
-void, glDrawTexsvOES, const GLshort* coords
-void, glDrawTexxOES, GLfixed x, GLfixed y, GLfixed z, GLfixed width, GLfixed height
-void, glDrawTexxvOES, const GLfixed* coords
-void, glEGLImageTargetRenderbufferStorageOES, GLenum target, GLeglImageOES image
-void, glEGLImageTargetTexture2DOES, GLenum target, GLeglImageOES image
-void, glEnable, GLenum cap
-void, glEnableClientState, GLenum array
-void, glEnableDriverControlQCOM, GLuint driverControl
-void, glEnableVertexAttribArray, GLuint index
-void, glEndPerfMonitorAMD, GLuint monitor
-void, glEndQuery, GLenum target
-void, glEndQueryEXT, GLenum target
-void, glEndTilingQCOM, GLbitfield preserveMask
-void, glEndTransformFeedback, void
-void, glExtGetBufferPointervQCOM, GLenum target, GLvoid** params
-void, glExtGetBuffersQCOM, GLuint* buffers, GLint maxBuffers, GLint* numBuffers
-void, glExtGetFramebuffersQCOM, GLuint* framebuffers, GLint maxFramebuffers, GLint* numFramebuffers
-void, glExtGetProgramBinarySourceQCOM, GLuint program, GLenum shadertype, GLchar* source, GLint* length
-void, glExtGetProgramsQCOM, GLuint* programs, GLint maxPrograms, GLint* numPrograms
-void, glExtGetRenderbuffersQCOM, GLuint* renderbuffers, GLint maxRenderbuffers, GLint* numRenderbuffers
-void, glExtGetShadersQCOM, GLuint* shaders, GLint maxShaders, GLint* numShaders
-void, glExtGetTexLevelParameterivQCOM, GLuint texture, GLenum face, GLint level, GLenum pname, GLint* params
-void, glExtGetTexSubImageQCOM, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, GLvoid* texels
-void, glExtGetTexturesQCOM, GLuint* textures, GLint maxTextures, GLint* numTextures
-GLboolean, glExtIsProgramBinaryQCOM, GLuint program
-void, glExtTexObjectStateOverrideiQCOM, GLenum target, GLenum pname, GLint param
-GLsync, glFenceSync, GLenum condition, GLbitfield flags
-void, glFinish, void
-void, glFinishFenceNV, GLuint fence
-void, glFlush, void
-void, glFlushMappedBufferRange, GLenum target, GLintptr offset, GLsizeiptr length
-void, glFogf, GLenum pname, GLfloat param
-void, glFogfv, GLenum pname, const GLfloat* params
-void, glFogx, GLenum pname, GLfixed param
-void, glFogxOES, GLenum pname, GLfixed param
-void, glFogxv, GLenum pname, const GLfixed* params
-void, glFogxvOES, GLenum pname, const GLfixed* params
-void, glFramebufferRenderbuffer, GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer
-void, glFramebufferRenderbufferOES, GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer
-void, glFramebufferTexture2D, GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level
-void, glFramebufferTexture2DMultisampleEXT, GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLsizei samples
-void, glFramebufferTexture2DMultisampleIMG, GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLsizei samples
-void, glFramebufferTexture2DOES, GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level
-void, glFramebufferTexture3DOES, GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset
-void, glFramebufferTextureLayer, GLenum target, GLenum attachment, GLuint texture, GLint level, GLint layer
-void, glFrontFace, GLenum mode
-void, glFrustumf, GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar
-void, glFrustumfOES, GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar
-void, glFrustumx, GLfixed left, GLfixed right, GLfixed bottom, GLfixed top, GLfixed zNear, GLfixed zFar
-void, glFrustumxOES, GLfixed left, GLfixed right, GLfixed bottom, GLfixed top, GLfixed zNear, GLfixed zFar
-void, glGenBuffers, GLsizei n, GLuint* buffers
-void, glGenFencesNV, GLsizei n, GLuint* fences
-void, glGenFramebuffers, GLsizei n, GLuint* framebuffers
-void, glGenFramebuffersOES, GLsizei n, GLuint* framebuffers
-void, glGenPerfMonitorsAMD, GLsizei n, GLuint* monitors
-void, glGenProgramPipelinesEXT, GLsizei n, GLuint* pipelines
-void, glGenQueries, GLsizei n, GLuint* ids
-void, glGenQueriesEXT, GLsizei n, GLuint* ids
-void, glGenRenderbuffers, GLsizei n, GLuint* renderbuffers
-void, glGenRenderbuffersOES, GLsizei n, GLuint* renderbuffers
-void, glGenSamplers, GLsizei count, GLuint* samplers
-void, glGenTextures, GLsizei n, GLuint* textures
-void, glGenTransformFeedbacks, GLsizei n, GLuint* ids
-void, glGenVertexArrays, GLsizei n, GLuint* arrays
-void, glGenVertexArraysOES, GLsizei n, GLuint* arrays
-void, glGenerateMipmap, GLenum target
-void, glGenerateMipmapOES, GLenum target
-void, glGetActiveAttrib, GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, GLchar* name
-void, glGetActiveUniform, GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, GLchar* name
-void, glGetActiveUniformBlockName, GLuint program, GLuint uniformBlockIndex, GLsizei bufSize, GLsizei* length, GLchar* uniformBlockName
-void, glGetActiveUniformBlockiv, GLuint program, GLuint uniformBlockIndex, GLenum pname, GLint* params
-void, glGetActiveUniformsiv, GLuint program, GLsizei uniformCount, const GLuint* uniformIndices, GLenum pname, GLint* params
-void, glGetAttachedShaders, GLuint program, GLsizei maxcount, GLsizei* count, GLuint* shaders
-GLint, glGetAttribLocation, GLuint program, const GLchar* name
-void, glGetBooleanv, GLenum pname, GLboolean* params
-void, glGetBufferParameteri64v, GLenum target, GLenum pname, GLint64* params
-void, glGetBufferParameteriv, GLenum target, GLenum pname, GLint* params
-void, glGetBufferPointerv, GLenum target, GLenum pname, GLvoid** params
-void, glGetBufferPointervOES, GLenum target, GLenum pname, GLvoid** params
-void, glGetClipPlanef, GLenum pname, GLfloat eqn[4]
-void, glGetClipPlanefOES, GLenum pname, GLfloat eqn[4]
-void, glGetClipPlanex, GLenum pname, GLfixed eqn[4]
-void, glGetClipPlanexOES, GLenum pname, GLfixed eqn[4]
-void, glGetDriverControlStringQCOM, GLuint driverControl, GLsizei bufSize, GLsizei* length, GLchar* driverControlString
-void, glGetDriverControlsQCOM, GLint* num, GLsizei size, GLuint* driverControls
-GLenum, glGetError, void
-void, glGetFenceivNV, GLuint fence, GLenum pname, GLint* params
-void, glGetFixedv, GLenum pname, GLfixed* params
-void, glGetFixedvOES, GLenum pname, GLfixed* params
-void, glGetFloatv, GLenum pname, GLfloat* params
-GLint, glGetFragDataLocation, GLuint program, const GLchar* name
-void, glGetFramebufferAttachmentParameteriv, GLenum target, GLenum attachment, GLenum pname, GLint* params
-void, glGetFramebufferAttachmentParameterivOES, GLenum target, GLenum attachment, GLenum pname, GLint* params
-GLenum, glGetGraphicsResetStatusEXT, void
-void, glGetInteger64i_v, GLenum target, GLuint index, GLint64* data
-void, glGetInteger64v, GLenum pname, GLint64* params
-void, glGetIntegeri_v, GLenum target, GLuint index, GLint* data
-void, glGetIntegerv, GLenum pname, GLint* params
-void, glGetInternalformativ, GLenum target, GLenum internalformat, GLenum pname, GLsizei bufSize, GLint* params
-void, glGetLightfv, GLenum light, GLenum pname, GLfloat* params
-void, glGetLightxv, GLenum light, GLenum pname, GLfixed* params
-void, glGetLightxvOES, GLenum light, GLenum pname, GLfixed* params
-void, glGetMaterialfv, GLenum face, GLenum pname, GLfloat* params
-void, glGetMaterialxv, GLenum face, GLenum pname, GLfixed* params
-void, glGetMaterialxvOES, GLenum face, GLenum pname, GLfixed* params
-void, glGetObjectLabelEXT, GLenum type, GLuint object, GLsizei bufSize, GLsizei* length, GLchar* label
-void, glGetPerfMonitorCounterDataAMD, GLuint monitor, GLenum pname, GLsizei dataSize, GLuint* data, GLint* bytesWritten
-void, glGetPerfMonitorCounterInfoAMD, GLuint group, GLuint counter, GLenum pname, GLvoid* data
-void, glGetPerfMonitorCounterStringAMD, GLuint group, GLuint counter, GLsizei bufSize, GLsizei* length, GLchar* counterString
-void, glGetPerfMonitorCountersAMD, GLuint group, GLint* numCounters, GLint* maxActiveCounters, GLsizei counterSize, GLuint* counters
-void, glGetPerfMonitorGroupStringAMD, GLuint group, GLsizei bufSize, GLsizei* length, GLchar* groupString
-void, glGetPerfMonitorGroupsAMD, GLint* numGroups, GLsizei groupsSize, GLuint* groups
-void, glGetPointerv, GLenum pname, GLvoid** params
-void, glGetProgramBinary, GLuint program, GLsizei bufSize, GLsizei* length, GLenum* binaryFormat, GLvoid* binary
-void, glGetProgramBinaryOES, GLuint program, GLsizei bufSize, GLsizei* length, GLenum* binaryFormat, GLvoid* binary
-void, glGetProgramInfoLog, GLuint program, GLsizei bufsize, GLsizei* length, GLchar* infolog
-void, glGetProgramPipelineInfoLogEXT, GLuint pipeline, GLsizei bufSize, GLsizei* length, GLchar* infoLog
-void, glGetProgramPipelineivEXT, GLuint pipeline, GLenum pname, GLint* params
-void, glGetProgramiv, GLuint program, GLenum pname, GLint* params
-void, glGetQueryObjectuiv, GLuint id, GLenum pname, GLuint* params
-void, glGetQueryObjectuivEXT, GLuint id, GLenum pname, GLuint* params
-void, glGetQueryiv, GLenum target, GLenum pname, GLint* params
-void, glGetQueryivEXT, GLenum target, GLenum pname, GLint* params
-void, glGetRenderbufferParameteriv, GLenum target, GLenum pname, GLint* params
-void, glGetRenderbufferParameterivOES, GLenum target, GLenum pname, GLint* params
-void, glGetSamplerParameterfv, GLuint sampler, GLenum pname, GLfloat* params
-void, glGetSamplerParameteriv, GLuint sampler, GLenum pname, GLint* params
-void, glGetShaderInfoLog, GLuint shader, GLsizei bufsize, GLsizei* length, GLchar* infolog
-void, glGetShaderPrecisionFormat, GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision
-void, glGetShaderSource, GLuint shader, GLsizei bufsize, GLsizei* length, GLchar* source
-void, glGetShaderiv, GLuint shader, GLenum pname, GLint* params
-const GLchar* , glGetString, GLenum name
-const GLubyte*, glGetStringi, GLenum name, GLuint index
-void, glGetSynciv, GLsync sync, GLenum pname, GLsizei bufSize, GLsizei* length, GLint* values
-void, glGetTexEnvfv, GLenum env, GLenum pname, GLfloat* params
-void, glGetTexEnviv, GLenum env, GLenum pname, GLint* params
-void, glGetTexEnvxv, GLenum env, GLenum pname, GLfixed* params
-void, glGetTexEnvxvOES, GLenum env, GLenum pname, GLfixed* params
-void, glGetTexGenfvOES, GLenum coord, GLenum pname, GLfloat* params
-void, glGetTexGenivOES, GLenum coord, GLenum pname, GLint* params
-void, glGetTexGenxvOES, GLenum coord, GLenum pname, GLfixed* params
-void, glGetTexParameterfv, GLenum target, GLenum pname, GLfloat* params
-void, glGetTexParameteriv, GLenum target, GLenum pname, GLint* params
-void, glGetTexParameterxv, GLenum target, GLenum pname, GLfixed* params
-void, glGetTexParameterxvOES, GLenum target, GLenum pname, GLfixed* params
-void, glGetTransformFeedbackVarying, GLuint program, GLuint index, GLsizei bufSize, GLsizei* length, GLsizei* size, GLenum* type, GLchar* name
-GLuint, glGetUniformBlockIndex, GLuint program, const GLchar* uniformBlockName
-void, glGetUniformIndices, GLuint program, GLsizei uniformCount, const GLchar* const* uniformNames, GLuint* uniformIndices
-GLint, glGetUniformLocation, GLuint program, const GLchar* name
-void, glGetUniformfv, GLuint program, GLint location, GLfloat* params
-void, glGetUniformiv, GLuint program, GLint location, GLint* params
-void, glGetUniformuiv, GLuint program, GLint location, GLuint* params
-void, glGetVertexAttribIiv, GLuint index, GLenum pname, GLint* params
-void, glGetVertexAttribIuiv, GLuint index, GLenum pname, GLuint* params
-void, glGetVertexAttribPointerv, GLuint index, GLenum pname, GLvoid** pointer
-void, glGetVertexAttribfv, GLuint index, GLenum pname, GLfloat* params
-void, glGetVertexAttribiv, GLuint index, GLenum pname, GLint* params
-void, glGetnUniformfvEXT, GLuint program, GLint location, GLsizei bufSize, float* params
-void, glGetnUniformivEXT, GLuint program, GLint location, GLsizei bufSize, GLint* params
-void, glHint, GLenum target, GLenum mode
-void, glInsertEventMarkerEXT, GLsizei length, const GLchar* marker
-void, glInvalidateFramebuffer, GLenum target, GLsizei numAttachments, const GLenum* attachments
-void, glInvalidateSubFramebuffer, GLenum target, GLsizei numAttachments, const GLenum* attachments, GLint x, GLint y, GLsizei width, GLsizei height
-GLboolean, glIsBuffer, GLuint buffer
-GLboolean, glIsEnabled, GLenum cap
-GLboolean, glIsFenceNV, GLuint fence
-GLboolean, glIsFramebuffer, GLuint framebuffer
-GLboolean, glIsFramebufferOES, GLuint framebuffer
-GLboolean, glIsProgram, GLuint program
-GLboolean, glIsProgramPipelineEXT, GLuint pipeline
-GLboolean, glIsQuery, GLuint id
-GLboolean, glIsQueryEXT, GLuint id
-GLboolean, glIsRenderbuffer, GLuint renderbuffer
-GLboolean, glIsRenderbufferOES, GLuint renderbuffer
-GLboolean, glIsSampler, GLuint sampler
-GLboolean, glIsShader, GLuint shader
-GLboolean, glIsSync, GLsync sync
-GLboolean, glIsTexture, GLuint texture
-GLboolean, glIsTransformFeedback, GLuint id
-GLboolean, glIsVertexArray, GLuint array
-GLboolean, glIsVertexArrayOES, GLuint array
-void, glLabelObjectEXT, GLenum type, GLuint object, GLsizei length, const GLchar* label
-void, glLightModelf, GLenum pname, GLfloat param
-void, glLightModelfv, GLenum pname, const GLfloat* params
-void, glLightModelx, GLenum pname, GLfixed param
-void, glLightModelxOES, GLenum pname, GLfixed param
-void, glLightModelxv, GLenum pname, const GLfixed* params
-void, glLightModelxvOES, GLenum pname, const GLfixed* params
-void, glLightf, GLenum light, GLenum pname, GLfloat param
-void, glLightfv, GLenum light, GLenum pname, const GLfloat* params
-void, glLightx, GLenum light, GLenum pname, GLfixed param
-void, glLightxOES, GLenum light, GLenum pname, GLfixed param
-void, glLightxv, GLenum light, GLenum pname, const GLfixed* params
-void, glLightxvOES, GLenum light, GLenum pname, const GLfixed* params
-void, glLineWidth, GLfloat width
-void, glLineWidthx, GLfixed width
-void, glLineWidthxOES, GLfixed width
-void, glLinkProgram, GLuint program
-void, glLoadIdentity, void
-void, glLoadMatrixf, const GLfloat* m
-void, glLoadMatrixx, const GLfixed* m
-void, glLoadMatrixxOES, const GLfixed* m
-void, glLoadPaletteFromModelViewMatrixOES, void
-void, glLogicOp, GLenum opcode
-void*, glMapBufferOES, GLenum target, GLenum access
-GLvoid*, glMapBufferRange, GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access
-void, glMaterialf, GLenum face, GLenum pname, GLfloat param
-void, glMaterialfv, GLenum face, GLenum pname, const GLfloat* params
-void, glMaterialx, GLenum face, GLenum pname, GLfixed param
-void, glMaterialxOES, GLenum face, GLenum pname, GLfixed param
-void, glMaterialxv, GLenum face, GLenum pname, const GLfixed* params
-void, glMaterialxvOES, GLenum face, GLenum pname, const GLfixed* params
-void, glMatrixIndexPointerOES, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer
-void, glMatrixMode, GLenum mode
-void, glMultMatrixf, const GLfloat* m
-void, glMultMatrixx, const GLfixed* m
-void, glMultMatrixxOES, const GLfixed* m
-void, glMultiDrawArraysEXT, GLenum mode, GLint* first, GLsizei* count, GLsizei primcount
-void, glMultiDrawElementsEXT, GLenum mode, const GLsizei* count, GLenum type, const GLvoid** indices, GLsizei primcount
-void, glMultiTexCoord4f, GLenum target, GLfloat s, GLfloat t, GLfloat r, GLfloat q
-void, glMultiTexCoord4x, GLenum target, GLfixed s, GLfixed t, GLfixed r, GLfixed q
-void, glMultiTexCoord4xOES, GLenum target, GLfixed s, GLfixed t, GLfixed r, GLfixed q
-void, glNormal3f, GLfloat nx, GLfloat ny, GLfloat nz
-void, glNormal3x, GLfixed nx, GLfixed ny, GLfixed nz
-void, glNormal3xOES, GLfixed nx, GLfixed ny, GLfixed nz
-void, glNormalPointer, GLenum type, GLsizei stride, const GLvoid* pointer
-void, glOrthof, GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar
-void, glOrthofOES, GLfloat left, GLfloat right, GLfloat bottom, GLfloat top, GLfloat zNear, GLfloat zFar
-void, glOrthox, GLfixed left, GLfixed right, GLfixed bottom, GLfixed top, GLfixed zNear, GLfixed zFar
-void, glOrthoxOES, GLfixed left, GLfixed right, GLfixed bottom, GLfixed top, GLfixed zNear, GLfixed zFar
-void, glPauseTransformFeedback, void
-void, glPixelStorei, GLenum pname, GLint param
-void, glPointParameterf, GLenum pname, GLfloat param
-void, glPointParameterfv, GLenum pname, const GLfloat* params
-void, glPointParameterx, GLenum pname, GLfixed param
-void, glPointParameterxOES, GLenum pname, GLfixed param
-void, glPointParameterxv, GLenum pname, const GLfixed* params
-void, glPointParameterxvOES, GLenum pname, const GLfixed* params
-void, glPointSize, GLfloat size
-void, glPointSizePointerOES, GLenum type, GLsizei stride, const GLvoid* pointer
-void, glPointSizex, GLfixed size
-void, glPointSizexOES, GLfixed size
-void, glPolygonOffset, GLfloat factor, GLfloat units
-void, glPolygonOffsetx, GLfixed factor, GLfixed units
-void, glPolygonOffsetxOES, GLfixed factor, GLfixed units
-void, glPopGroupMarkerEXT, void
-void, glPopMatrix, void
-void, glProgramBinary, GLuint program, GLenum binaryFormat, const GLvoid* binary, GLsizei length
-void, glProgramBinaryOES, GLuint program, GLenum binaryFormat, const GLvoid* binary, GLint length
-void, glProgramParameteri, GLuint program, GLenum pname, GLint value
-void, glProgramParameteriEXT, GLuint program, GLenum pname, GLint value
-void, glProgramUniform1fEXT, GLuint program, GLint location, GLfloat x
-void, glProgramUniform1fvEXT, GLuint program, GLint location, GLsizei count, const GLfloat* value
-void, glProgramUniform1iEXT, GLuint program, GLint location, GLint x
-void, glProgramUniform1ivEXT, GLuint program, GLint location, GLsizei count, const GLint* value
-void, glProgramUniform2fEXT, GLuint program, GLint location, GLfloat x, GLfloat y
-void, glProgramUniform2fvEXT, GLuint program, GLint location, GLsizei count, const GLfloat* value
-void, glProgramUniform2iEXT, GLuint program, GLint location, GLint x, GLint y
-void, glProgramUniform2ivEXT, GLuint program, GLint location, GLsizei count, const GLint* value
-void, glProgramUniform3fEXT, GLuint program, GLint location, GLfloat x, GLfloat y, GLfloat z
-void, glProgramUniform3fvEXT, GLuint program, GLint location, GLsizei count, const GLfloat* value
-void, glProgramUniform3iEXT, GLuint program, GLint location, GLint x, GLint y, GLint z
-void, glProgramUniform3ivEXT, GLuint program, GLint location, GLsizei count, const GLint* value
-void, glProgramUniform4fEXT, GLuint program, GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w
-void, glProgramUniform4fvEXT, GLuint program, GLint location, GLsizei count, const GLfloat* value
-void, glProgramUniform4iEXT, GLuint program, GLint location, GLint x, GLint y, GLint z, GLint w
-void, glProgramUniform4ivEXT, GLuint program, GLint location, GLsizei count, const GLint* value
-void, glProgramUniformMatrix2fvEXT, GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value
-void, glProgramUniformMatrix3fvEXT, GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value
-void, glProgramUniformMatrix4fvEXT, GLuint program, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value
-void, glPushGroupMarkerEXT, GLsizei length, const GLchar* marker
-void, glPushMatrix, void
-GLbitfield, glQueryMatrixxOES, GLfixed mantissa[16], GLint exponent[16]
-void, glReadBuffer, GLenum mode
-void, glReadBufferNV, GLenum mode
-void, glReadPixels, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid* pixels
-void, glReadnPixelsEXT, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, void* data
-void, glReleaseShaderCompiler, void
-void, glRenderbufferStorage, GLenum target, GLenum internalformat, GLsizei width, GLsizei height
-void, glRenderbufferStorageMultisample, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height
-void, glRenderbufferStorageMultisampleANGLE, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height
-void, glRenderbufferStorageMultisampleAPPLE, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height
-void, glRenderbufferStorageMultisampleEXT, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height
-void, glRenderbufferStorageMultisampleIMG, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height
-void, glRenderbufferStorageOES, GLenum target, GLenum internalformat, GLsizei width, GLsizei height
-void, glResolveMultisampleFramebufferAPPLE, void
-void, glResumeTransformFeedback, void
-void, glRotatef, GLfloat angle, GLfloat x, GLfloat y, GLfloat z
-void, glRotatex, GLfixed angle, GLfixed x, GLfixed y, GLfixed z
-void, glRotatexOES, GLfixed angle, GLfixed x, GLfixed y, GLfixed z
-void, glSampleCoverage, GLclampf value, GLboolean invert
-void, glSampleCoveragex, GLclampx value, GLboolean invert
-void, glSampleCoveragexOES, GLclampx value, GLboolean invert
-void, glSamplerParameterf, GLuint sampler, GLenum pname, GLfloat param
-void, glSamplerParameterfv, GLuint sampler, GLenum pname, const GLfloat* param
-void, glSamplerParameteri, GLuint sampler, GLenum pname, GLint param
-void, glSamplerParameteriv, GLuint sampler, GLenum pname, const GLint* param
-void, glScalef, GLfloat x, GLfloat y, GLfloat z
-void, glScalex, GLfixed x, GLfixed y, GLfixed z
-void, glScalexOES, GLfixed x, GLfixed y, GLfixed z
-void, glScissor, GLint x, GLint y, GLsizei width, GLsizei height
-void, glSelectPerfMonitorCountersAMD, GLuint monitor, GLboolean enable, GLuint group, GLint numCounters, GLuint* countersList
-void, glSetFenceNV, GLuint fence, GLenum condition
-void, glShadeModel, GLenum mode
-void, glShaderBinary, GLsizei n, const GLuint* shaders, GLenum binaryformat, const GLvoid* binary, GLsizei length
-void, glShaderSource, GLuint shader, GLsizei count, const GLchar** string, const GLint* length
-void, glStartTilingQCOM, GLuint x, GLuint y, GLuint width, GLuint height, GLbitfield preserveMask
-void, glStencilFunc, GLenum func, GLint ref, GLuint mask
-void, glStencilFuncSeparate, GLenum face, GLenum func, GLint ref, GLuint mask
-void, glStencilMask, GLuint mask
-void, glStencilMaskSeparate, GLenum face, GLuint mask
-void, glStencilOp, GLenum fail, GLenum zfail, GLenum zpass
-void, glStencilOpSeparate, GLenum face, GLenum fail, GLenum zfail, GLenum zpass
-GLboolean, glTestFenceNV, GLuint fence
-void, glTexCoordPointer, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer
-void, glTexEnvf, GLenum target, GLenum pname, GLfloat param
-void, glTexEnvfv, GLenum target, GLenum pname, const GLfloat* params
-void, glTexEnvi, GLenum target, GLenum pname, GLint param
-void, glTexEnviv, GLenum target, GLenum pname, const GLint* params
-void, glTexEnvx, GLenum target, GLenum pname, GLfixed param
-void, glTexEnvxOES, GLenum target, GLenum pname, GLfixed param
-void, glTexEnvxv, GLenum target, GLenum pname, const GLfixed* params
-void, glTexEnvxvOES, GLenum target, GLenum pname, const GLfixed* params
-void, glTexGenfOES, GLenum coord, GLenum pname, GLfloat param
-void, glTexGenfvOES, GLenum coord, GLenum pname, const GLfloat* params
-void, glTexGeniOES, GLenum coord, GLenum pname, GLint param
-void, glTexGenivOES, GLenum coord, GLenum pname, const GLint* params
-void, glTexGenxOES, GLenum coord, GLenum pname, GLfixed param
-void, glTexGenxvOES, GLenum coord, GLenum pname, const GLfixed* params
-void, glTexImage2D, GLenum target, GLint level, GLEnum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid* pixels
-void, glTexImage3D, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid* pixels
-void, glTexImage3DOES, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth, GLint border, GLenum format, GLenum type, const GLvoid* pixels
-void, glTexParameterf, GLenum target, GLenum pname, GLfloat param
-void, glTexParameterfv, GLenum target, GLenum pname, const GLfloat* params
-void, glTexParameteri, GLenum target, GLenum pname, GLint param
-void, glTexParameteriv, GLenum target, GLenum pname, const GLint* params
-void, glTexParameterx, GLenum target, GLenum pname, GLfixed param
-void, glTexParameterxOES, GLenum target, GLenum pname, GLfixed param
-void, glTexParameterxv, GLenum target, GLenum pname, const GLfixed* params
-void, glTexParameterxvOES, GLenum target, GLenum pname, const GLfixed* params
-void, glTexStorage1DEXT, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width
-void, glTexStorage2D, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height
-void, glTexStorage2DEXT, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height
-void, glTexStorage3D, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth
-void, glTexStorage3DEXT, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth
-void, glTexSubImage2D, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid* pixels
-void, glTexSubImage3D, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid* pixels
-void, glTexSubImage3DOES, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const GLvoid* pixels
-void, glTextureStorage1DEXT, GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width
-void, glTextureStorage2DEXT, GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height
-void, glTextureStorage3DEXT, GLuint texture, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height, GLsizei depth
-void, glTransformFeedbackVaryings, GLuint program, GLsizei count, const GLchar* const* varyings, GLenum bufferMode
-void, glTranslatef, GLfloat x, GLfloat y, GLfloat z
-void, glTranslatex, GLfixed x, GLfixed y, GLfixed z
-void, glTranslatexOES, GLfixed x, GLfixed y, GLfixed z
-void, glUniform1f, GLint location, GLfloat x
-void, glUniform1fv, GLint location, GLsizei count, const GLfloat* v
-void, glUniform1i, GLint location, GLint x
-void, glUniform1iv, GLint location, GLsizei count, const GLint* v
-void, glUniform1ui, GLint location, GLuint v0
-void, glUniform1uiv, GLint location, GLsizei count, const GLuint* value
-void, glUniform2f, GLint location, GLfloat x, GLfloat y
-void, glUniform2fv, GLint location, GLsizei count, const GLfloat* v
-void, glUniform2i, GLint location, GLint x, GLint y
-void, glUniform2iv, GLint location, GLsizei count, const GLint* v
-void, glUniform2ui, GLint location, GLuint v0, GLuint v1
-void, glUniform2uiv, GLint location, GLsizei count, const GLuint* value
-void, glUniform3f, GLint location, GLfloat x, GLfloat y, GLfloat z
-void, glUniform3fv, GLint location, GLsizei count, const GLfloat* v
-void, glUniform3i, GLint location, GLint x, GLint y, GLint z
-void, glUniform3iv, GLint location, GLsizei count, const GLint* v
-void, glUniform3ui, GLint location, GLuint v0, GLuint v1, GLuint v2
-void, glUniform3uiv, GLint location, GLsizei count, const GLuint* value
-void, glUniform4f, GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w
-void, glUniform4fv, GLint location, GLsizei count, const GLfloat* v
-void, glUniform4i, GLint location, GLint x, GLint y, GLint z, GLint w
-void, glUniform4iv, GLint location, GLsizei count, const GLint* v
-void, glUniform4ui, GLint location, GLuint v0, GLuint v1, GLuint v2, GLuint v3
-void, glUniform4uiv, GLint location, GLsizei count, const GLuint* value
-void, glUniformBlockBinding, GLuint program, GLuint uniformBlockIndex, GLuint uniformBlockBinding
-void, glUniformMatrix2fv, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value
-void, glUniformMatrix2x3fv, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value
-void, glUniformMatrix2x4fv, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value
-void, glUniformMatrix3fv, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value
-void, glUniformMatrix3x2fv, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value
-void, glUniformMatrix3x4fv, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value
-void, glUniformMatrix4fv, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value
-void, glUniformMatrix4x2fv, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value
-void, glUniformMatrix4x3fv, GLint location, GLsizei count, GLboolean transpose, const GLfloat* value
-GLboolean, glUnmapBuffer, GLenum target
-GLboolean, glUnmapBufferOES, GLenum target
-void, glUseProgram, GLuint program
-void, glUseProgramStagesEXT, GLuint pipeline, GLbitfield stages, GLuint program
-void, glValidateProgram, GLuint program
-void, glValidateProgramPipelineEXT, GLuint pipeline
-void, glVertexAttrib1f, GLuint indx, GLfloat x
-void, glVertexAttrib1fv, GLuint indx, const GLfloat* values
-void, glVertexAttrib2f, GLuint indx, GLfloat x, GLfloat y
-void, glVertexAttrib2fv, GLuint indx, const GLfloat* values
-void, glVertexAttrib3f, GLuint indx, GLfloat x, GLfloat y, GLfloat z
-void, glVertexAttrib3fv, GLuint indx, const GLfloat* values
-void, glVertexAttrib4f, GLuint indx, GLfloat x, GLfloat y, GLfloat z, GLfloat w
-void, glVertexAttrib4fv, GLuint indx, const GLfloat* values
-void, glVertexAttribDivisor, GLuint index, GLuint divisor
-void, glVertexAttribI4i, GLuint index, GLint x, GLint y, GLint z, GLint w
-void, glVertexAttribI4iv, GLuint index, const GLint* v
-void, glVertexAttribI4ui, GLuint index, GLuint x, GLuint y, GLuint z, GLuint w
-void, glVertexAttribI4uiv, GLuint index, const GLuint* v
-void, glVertexAttribIPointer, GLuint index, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer
-void, glVertexAttribPointer, GLuint indx, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid* ptr
-void, glVertexAttribPointerData, GLuint indx, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid* ptr, GLuint minIndex, GLuint maxIndex
-void, glVertexPointer, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer
-void, glViewport, GLint x, GLint y, GLsizei width, GLsizei height
-void, glWaitSync, GLsync sync, GLbitfield flags, GLuint64 timeout
-void, glWeightPointerOES, GLint size, GLenum type, GLsizei stride, const GLvoid* pointer
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/icons/connect.png b/eclipse/plugins/com.android.ide.eclipse.gldebugger/icons/connect.png
deleted file mode 100644
index 14ef52212..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/icons/connect.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/icons/expandall.png b/eclipse/plugins/com.android.ide.eclipse.gldebugger/icons/expandall.png
deleted file mode 100644
index 7bdf83d32..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/icons/expandall.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/icons/opengl.png b/eclipse/plugins/com.android.ide.eclipse.gldebugger/icons/opengl.png
deleted file mode 100644
index ae9d032d3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/icons/opengl.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/icons/sample.gif b/eclipse/plugins/com.android.ide.eclipse.gldebugger/icons/sample.gif
deleted file mode 100644
index 34fb3c9d8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/icons/sample.gif
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/icons/zoomfit.png b/eclipse/plugins/com.android.ide.eclipse.gldebugger/icons/zoomfit.png
deleted file mode 100644
index 9c53ac8bf..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/icons/zoomfit.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/plugin.xml b/eclipse/plugins/com.android.ide.eclipse.gldebugger/plugin.xml
deleted file mode 100644
index 5806b3cd5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/plugin.xml
+++ /dev/null
@@ -1,99 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<?eclipse version="3.4"?>
-<plugin>
-
- <extension
- point="org.eclipse.ui.views">
- <category
- id="com.android.ide.eclipse.gltrace"
- name="Tracer for OpenGL ES">
- </category>
- <view
- category="com.android.ide.eclipse.gltrace"
- class="com.android.ide.eclipse.gltrace.views.FrameSummaryView"
- icon="icons/opengl.png"
- id="com.android.ide.eclipse.gltrace.views.FrameBuffer"
- name="Frame Summary"
- restorable="true">
- </view>
- <view
- category="com.android.ide.eclipse.gltrace"
- class="com.android.ide.eclipse.gltrace.views.StateView"
- icon="icons/opengl.png"
- id="com.android.ide.eclipse.gltrace.views.State"
- name="GL State"
- restorable="true">
- </view>
- <view
- category="com.android.ide.eclipse.gltrace"
- class="com.android.ide.eclipse.gltrace.views.detail.DetailsView"
- icon="icons/opengl.png"
- id="com.android.ide.eclipse.gltrace.views.Details"
- name="Details"
- restorable="true">
- </view>
- </extension>
- <extension
- point="org.eclipse.ui.editors">
- <editor
- class="com.android.ide.eclipse.gltrace.editors.GLFunctionTraceViewer"
- default="true"
- extensions="gltrace"
- icon="icons/opengl.png"
- id="com.android.ide.eclipse.gltrace.GLFunctionTrace"
- name="GL Function Trace">
- </editor>
- </extension>
- <extension
- point="org.eclipse.ui.actionSets">
- <actionSet
- description="OpenGL Trace Actions"
- id="com.android.ide.eclipse.gltrace.actionset"
- label="OpenGL Trace Actions"
- visible="false">
- <action
- class="com.android.ide.eclipse.gltrace.CollectTraceAction"
- icon="icons/connect.png"
- id="gltrace.action.connect"
- label="Collects OpenGL trace from device"
- style="push"
- toolbarPath="Normal/additions"
- tooltip="Connects to the device and collects OpenGL trace information">
- </action>
- <action
- class="com.android.ide.eclipse.gltrace.OpenGLTraceAction"
- icon="icons/opengl.png"
- id="gltrace.action.open"
- label="Open GL Trace File"
- style="push"
- toolbarPath="Normal/additions"
- tooltip="Open a saved OpenGL Trace File">
- </action>
- </actionSet>
- </extension>
- <extension
- point="org.eclipse.ui.perspectives">
- <perspective
- class="com.android.ide.eclipse.gltrace.GLTracePerspective"
- icon="icons/opengl.png"
- id="com.android.ide.eclipse.gltrace.perspective"
- name="Tracer for OpenGL ES">
- </perspective>
- </extension>
- <extension
- point="org.eclipse.ui.perspectiveExtensions">
- <perspectiveExtension
- targetID="com.android.ide.eclipse.gltrace.perspective">
- <actionSet
- id="com.android.ide.eclipse.gltrace.actionset">
- </actionSet>
- </perspectiveExtension>
- </extension>
- <extension
- point="com.android.ide.eclipse.ddms.clientAction">
- <clientAction
- class="com.android.ide.eclipse.gltrace.DeviceViewAction">
- </clientAction>
- </extension>
-
-</plugin>
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/pom.xml b/eclipse/plugins/com.android.ide.eclipse.gldebugger/pom.xml
deleted file mode 100644
index a2a8cefe7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/pom.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <version>24.3.3-SNAPSHOT</version>
- <artifactId>com.android.ide.eclipse.gldebugger</artifactId>
- <packaging>eclipse-plugin</packaging>
- <name>gldebugger</name>
-
- <parent>
- <relativePath>../../pom.xml</relativePath>
- <groupId>adt.group</groupId>
- <artifactId>parent</artifactId>
- <version>1.0.0-SNAPSHOT</version>
- </parent>
-</project>
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/CollectTraceAction.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/CollectTraceAction.java
deleted file mode 100644
index c13ab461b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/CollectTraceAction.java
+++ /dev/null
@@ -1,428 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace;
-
-import com.android.ddmlib.AdbCommandRejectedException;
-import com.android.ddmlib.AndroidDebugBridge;
-import com.android.ddmlib.Client;
-import com.android.ddmlib.IDevice;
-import com.android.ddmlib.IDevice.DeviceUnixSocketNamespace;
-import com.android.ddmlib.IShellOutputReceiver;
-import com.android.ddmlib.ShellCommandUnresponsiveException;
-import com.android.ddmlib.TimeoutException;
-import com.android.ide.eclipse.gltrace.editors.GLFunctionTraceViewer;
-import com.google.common.io.Closeables;
-import com.google.common.util.concurrent.SimpleTimeLimiter;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorReference;
-import org.eclipse.ui.IURIEditorInput;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.WorkbenchException;
-import org.eclipse.ui.ide.IDE;
-
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.net.Socket;
-import java.util.concurrent.Callable;
-import java.util.concurrent.Semaphore;
-import java.util.concurrent.TimeUnit;
-
-public class CollectTraceAction implements IWorkbenchWindowActionDelegate {
- /** Abstract Unix Domain Socket Name used by the gltrace device code. */
- private static final String GLTRACE_UDS = "gltrace"; //$NON-NLS-1$
-
- /** Local port that is forwarded to the device's {@link #GLTRACE_UDS} socket. */
- private static final int LOCAL_FORWARDED_PORT = 6039;
-
- /** Activity name to use for a system activity that has already been launched. */
- private static final String SYSTEM_APP = "system"; //$NON-NLS-1$
-
- /** Time to wait for the application to launch (seconds) */
- private static final int LAUNCH_TIMEOUT = 15;
-
- /** Time to wait for the application to die (seconds) */
- private static final int KILL_TIMEOUT = 5;
-
- private static final int MIN_API_LEVEL = 16;
-
- @Override
- public void run(IAction action) {
- connectToDevice();
- }
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
- }
-
- @Override
- public void dispose() {
- }
-
- @Override
- public void init(IWorkbenchWindow window) {
- }
-
- private void connectToDevice() {
- Shell shell = Display.getDefault().getActiveShell();
- GLTraceOptionsDialog dlg = new GLTraceOptionsDialog(shell);
- if (dlg.open() != Window.OK) {
- return;
- }
-
- TraceOptions traceOptions = dlg.getTraceOptions();
-
- IDevice device = getDevice(traceOptions.device);
- String apiLevelString = device.getProperty(IDevice.PROP_BUILD_API_LEVEL);
- int apiLevel;
- try {
- apiLevel = Integer.parseInt(apiLevelString);
- } catch (NumberFormatException e) {
- apiLevel = MIN_API_LEVEL;
- }
- if (apiLevel < MIN_API_LEVEL) {
- MessageDialog.openError(shell, "GL Trace",
- String.format("OpenGL Tracing is only supported on devices at API Level %1$d."
- + "The selected device '%2$s' provides API level %3$s.",
- MIN_API_LEVEL, traceOptions.device, apiLevelString));
- return;
- }
-
- try {
- setupForwarding(device, LOCAL_FORWARDED_PORT);
- } catch (Exception e) {
- MessageDialog.openError(shell, "Setup GL Trace",
- "Error while setting up port forwarding: " + e.getMessage());
- return;
- }
-
- try {
- if (!SYSTEM_APP.equals(traceOptions.appToTrace)) {
- startActivity(device, traceOptions.appToTrace, traceOptions.activityToTrace,
- traceOptions.isActivityNameFullyQualified);
- }
- } catch (Exception e) {
- MessageDialog.openError(shell, "Setup GL Trace",
- "Error while launching application: " + e.getMessage());
- return;
- }
-
- // if everything went well, the app should now be waiting for the gl debugger
- // to connect
- startTracing(shell, traceOptions, LOCAL_FORWARDED_PORT);
-
- // once tracing is complete, remove port forwarding
- disablePortForwarding(device, LOCAL_FORWARDED_PORT);
-
- // and finally open the editor to view the file
- openInEditor(shell, traceOptions.traceDestination);
- }
-
- public static void openInEditor(Shell shell, String traceFilePath) {
- final IFileStore fileStore = EFS.getLocalFileSystem().getStore(new Path(traceFilePath));
- if (!fileStore.fetchInfo().exists()) {
- return;
- }
-
- final IWorkbench workbench = PlatformUI.getWorkbench();
- IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
- if (window == null) {
- return;
- }
-
- IWorkbenchPage page = window.getActivePage();
- if (page == null) {
- return;
- }
-
- try {
- workbench.showPerspective("com.android.ide.eclipse.gltrace.perspective", window);
- } catch (WorkbenchException e) {
- }
-
- // if there is a editor already open, then refresh its model
- GLFunctionTraceViewer viewer = getOpenTraceViewer(page, traceFilePath);
- if (viewer != null) {
- viewer.setInput(shell, traceFilePath);
- }
-
- // open the editor (if not open), or bring it to foreground if it is already open
- try {
- IDE.openEditorOnFileStore(page, fileStore);
- } catch (PartInitException e) {
- GlTracePlugin.getDefault().logMessage(
- "Unexpected error while opening gltrace file in editor: " + e);
- return;
- }
- }
-
- /**
- * Returns the editor part that has the provided file path open.
- * @param page page containing editors
- * @param traceFilePath file that should be open in an editor
- * @return if given trace file is already open, then a reference to that editor part,
- * null otherwise
- */
- private static GLFunctionTraceViewer getOpenTraceViewer(IWorkbenchPage page,
- String traceFilePath) {
- IEditorReference[] editorRefs = page.getEditorReferences();
- for (IEditorReference ref : editorRefs) {
- String id = ref.getId();
- if (!GLFunctionTraceViewer.ID.equals(id)) {
- continue;
- }
-
- IEditorInput input = null;
- try {
- input = ref.getEditorInput();
- } catch (PartInitException e) {
- continue;
- }
-
- if (!(input instanceof IURIEditorInput)) {
- continue;
- }
-
- if (traceFilePath.equals(((IURIEditorInput) input).getURI().getPath())) {
- return (GLFunctionTraceViewer) ref.getEditor(true);
- }
- }
-
- return null;
- }
-
- @SuppressWarnings("resource") // Closeables.closeQuietly
- public static void startTracing(Shell shell, TraceOptions traceOptions, int port) {
- Socket socket = new Socket();
- DataInputStream traceDataStream = null;
- DataOutputStream traceCommandsStream = null;
- try {
- socket.connect(new java.net.InetSocketAddress("127.0.0.1", port)); //$NON-NLS-1$
- socket.setTcpNoDelay(true);
- traceDataStream = new DataInputStream(socket.getInputStream());
- traceCommandsStream = new DataOutputStream(socket.getOutputStream());
- } catch (IOException e) {
- MessageDialog.openError(shell,
- "OpenGL Trace",
- "Unable to connect to remote GL Trace Server: " + e.getMessage());
- return;
- }
-
- // create channel to send trace commands to device
- TraceCommandWriter traceCommandWriter = new TraceCommandWriter(traceCommandsStream);
- try {
- traceCommandWriter.setTraceOptions(traceOptions.collectFbOnEglSwap,
- traceOptions.collectFbOnGlDraw,
- traceOptions.collectTextureData);
- } catch (IOException e) {
- MessageDialog.openError(shell,
- "OpenGL Trace",
- "Unexpected error while setting trace options: " + e.getMessage());
- closeSocket(socket);
- return;
- }
-
- FileOutputStream fos = null;
- try {
- fos = new FileOutputStream(traceOptions.traceDestination, false);
- } catch (FileNotFoundException e) {
- // input path is valid, so this cannot occur
- }
-
- // create trace writer that writes to a trace file
- TraceFileWriter traceFileWriter = new TraceFileWriter(fos, traceDataStream);
- traceFileWriter.start();
-
- GLTraceCollectorDialog dlg = new GLTraceCollectorDialog(shell,
- traceFileWriter,
- traceCommandWriter,
- traceOptions);
- dlg.open();
-
- traceFileWriter.stopTracing();
- traceCommandWriter.close();
- closeSocket(socket);
- }
-
- private static void closeSocket(Socket socket) {
- try {
- socket.close();
- } catch (IOException e) {
- // ignore error while closing socket
- }
- }
-
- private void startActivity(IDevice device, String appPackage, String activity,
- boolean isActivityNameFullyQualified)
- throws TimeoutException, AdbCommandRejectedException,
- ShellCommandUnresponsiveException, IOException, InterruptedException {
- killApp(device, appPackage); // kill app if it is already running
- waitUntilAppKilled(device, appPackage, KILL_TIMEOUT);
-
- StringBuilder activityPath = new StringBuilder(appPackage);
- if (!activity.isEmpty()) {
- activityPath.append('/');
- if (!isActivityNameFullyQualified) {
- activityPath.append('.');
- }
- activityPath.append(activity);
- }
- String startAppCmd = String.format(
- "am start --opengl-trace %s -a android.intent.action.MAIN -c android.intent.category.LAUNCHER", //$NON-NLS-1$
- activityPath.toString());
-
- Semaphore launchCompletionSempahore = new Semaphore(0);
- StartActivityOutputReceiver receiver = new StartActivityOutputReceiver(
- launchCompletionSempahore);
- device.executeShellCommand(startAppCmd, receiver);
-
- // wait until shell finishes launch command
- launchCompletionSempahore.acquire();
-
- // throw exception if there was an error during launch
- String output = receiver.getOutput();
- if (output.contains("Error")) { //$NON-NLS-1$
- throw new RuntimeException(output);
- }
-
- // wait until the app itself has been launched
- waitUntilAppLaunched(device, appPackage, LAUNCH_TIMEOUT);
- }
-
- private void killApp(IDevice device, String appName) {
- Client client = device.getClient(appName);
- if (client != null) {
- client.kill();
- }
- }
-
- private void waitUntilAppLaunched(final IDevice device, final String appName, int timeout) {
- Callable<Boolean> c = new Callable<Boolean>() {
- @Override
- public Boolean call() throws Exception {
- Client client;
- do {
- client = device.getClient(appName);
- } while (client == null);
-
- return Boolean.TRUE;
- }
- };
- try {
- new SimpleTimeLimiter().callWithTimeout(c, timeout, TimeUnit.SECONDS, true);
- } catch (Exception e) {
- throw new RuntimeException("Timed out waiting for application to launch.");
- }
-
- // once the app has launched, wait an additional couple of seconds
- // for it to start up
- try {
- Thread.sleep(2000);
- } catch (InterruptedException e) {
- // ignore
- }
- }
-
- private void waitUntilAppKilled(final IDevice device, final String appName, int timeout) {
- Callable<Boolean> c = new Callable<Boolean>() {
- @Override
- public Boolean call() throws Exception {
- Client client;
- while ((client = device.getClient(appName)) != null) {
- client.kill();
- }
- return Boolean.TRUE;
- }
- };
- try {
- new SimpleTimeLimiter().callWithTimeout(c, timeout, TimeUnit.SECONDS, true);
- } catch (Exception e) {
- throw new RuntimeException("Timed out waiting for running application to die.");
- }
- }
-
- public static void setupForwarding(IDevice device, int i)
- throws TimeoutException, AdbCommandRejectedException, IOException {
- device.createForward(i, GLTRACE_UDS, DeviceUnixSocketNamespace.ABSTRACT);
- }
-
- public static void disablePortForwarding(IDevice device, int port) {
- try {
- device.removeForward(port, GLTRACE_UDS, DeviceUnixSocketNamespace.ABSTRACT);
- } catch (Exception e) {
- // ignore exceptions;
- }
- }
-
- private IDevice getDevice(String deviceName) {
- IDevice[] devices = AndroidDebugBridge.getBridge().getDevices();
-
- for (IDevice device : devices) {
- if (device.getName().equals(deviceName)) {
- return device;
- }
- }
-
- return null;
- }
-
- private static class StartActivityOutputReceiver implements IShellOutputReceiver {
- private Semaphore mSemaphore;
- private StringBuffer sb = new StringBuffer(300);
-
- public StartActivityOutputReceiver(Semaphore s) {
- mSemaphore = s;
- }
-
- @Override
- public void addOutput(byte[] data, int offset, int length) {
- String d = new String(data, offset, length);
- sb.append(d);
- }
-
- @Override
- public void flush() {
- mSemaphore.release();
- }
-
- @Override
- public boolean isCancelled() {
- return false;
- }
-
- public String getOutput() {
- return sb.toString();
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/DeviceViewAction.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/DeviceViewAction.java
deleted file mode 100644
index 7d912bafe..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/DeviceViewAction.java
+++ /dev/null
@@ -1,113 +0,0 @@
-package com.android.ide.eclipse.gltrace;
-
-import com.android.ddmlib.Client;
-import com.android.ddmlib.ClientData;
-import com.android.ide.eclipse.ddms.IClientAction;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.dialogs.ProgressMonitorDialog;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-
-import java.lang.reflect.InvocationTargetException;
-
-public class DeviceViewAction implements IClientAction {
- private static final class StartTraceAction extends Action {
- private static final int LOCAL_FORWARDED_PORT = 6049;
-
- private Client mClient;
-
- public StartTraceAction() {
- super("Start OpenGL Trace");
- setImageDescriptor(GlTracePlugin.getImageDescriptor("/icons/connect.png")); //$NON-NLS-1$
- setClient(null);
- }
-
- public void setClient(Client c) {
- mClient = c;
- clientChanged();
- }
-
- private void clientChanged() {
- if (mClient == null) {
- setEnabled(false);
- return;
- }
-
- ClientData cd = mClient.getClientData();
- if (cd.hasFeature(ClientData.FEATURE_OPENGL_TRACING)) {
- setEnabled(true);
- setToolTipText("Trace OpenGL calls");
- } else {
- setEnabled(false);
- setToolTipText("Selected VM does not support tracing OpenGL calls");
- }
- }
-
- @Override
- public void run() {
- if (mClient == null) {
- return;
- }
-
- Shell shell = Display.getDefault().getActiveShell();
- GLTraceOptionsDialog dlg = new GLTraceOptionsDialog(shell, false,
- mClient.getClientData().getClientDescription());
- if (dlg.open() != Window.OK) {
- return;
- }
-
- // start tracing on the client
- mClient.startOpenGlTracing();
-
- try {
- CollectTraceAction.setupForwarding(mClient.getDevice(), LOCAL_FORWARDED_PORT);
- } catch (Exception e) {
- MessageDialog.openError(shell, "Setup GL Trace",
- "Error while setting up port forwarding: " + e.getMessage());
- return;
- }
-
- // wait for a few seconds for the client to start the trace server
- try {
- new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress() {
- @Override
- public void run(IProgressMonitor monitor)
- throws InvocationTargetException, InterruptedException {
- Thread.sleep(3000);
- }
- });
- } catch (Exception e) {
- }
-
- // retrieve the trace from the device
- TraceOptions traceOptions = dlg.getTraceOptions();
- CollectTraceAction.startTracing(shell, traceOptions, LOCAL_FORWARDED_PORT);
-
- // inform the client that it doesn't need to be traced anymore
- mClient.stopOpenGlTracing();
-
- // remove port forwarding
- CollectTraceAction.disablePortForwarding(mClient.getDevice(), LOCAL_FORWARDED_PORT);
-
- // and finally open the editor to view the file
- CollectTraceAction.openInEditor(shell, traceOptions.traceDestination);
- }
- }
-
- private static final StartTraceAction sAction = new StartTraceAction();
-
- @Override
- public Action getAction() {
- return sAction;
- }
-
- @Override
- public void selectedClientChanged(Client c) {
- sAction.setClient(c);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/FileUtils.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/FileUtils.java
deleted file mode 100644
index ab06f6757..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/FileUtils.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace;
-
-import com.google.common.io.Files;
-
-import java.io.File;
-import java.io.IOException;
-
-public class FileUtils {
- private static final File sCacheDir;
-
- static {
- sCacheDir = Files.createTempDir();
- sCacheDir.deleteOnExit();
- }
-
- public static File createTempFile(String prefix, String suffix) {
- File f;
- try {
- f = File.createTempFile(prefix, suffix, sCacheDir);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- f.deleteOnExit();
- return f;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GLEnum.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GLEnum.java
deleted file mode 100644
index ceb9f1a51..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GLEnum.java
+++ /dev/null
@@ -1,1017 +0,0 @@
-/*
- ** Copyright 2011, The Android Open Source Project
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- ** http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ** See the License for the specific language governing permissions and
- ** limitations under the License.
- */
-
-// auto generated by generate_GLEnum_java.py"
-
-package com.android.ide.eclipse.gltrace;
-
-public enum GLEnum {
- GL_NONE(0x0000),
- GL_LINES(0x0001),
- GL_LINE_LOOP(0x0002),
- GL_LINE_STRIP(0x0003),
- GL_TRIANGLES(0x0004),
- GL_TRIANGLE_STRIP(0x0005),
- GL_TRIANGLE_FAN(0x0006),
- GL_ADD(0x0104),
- GL_NEVER(0x0200),
- GL_LESS(0x0201),
- GL_EQUAL(0x0202),
- GL_LEQUAL(0x0203),
- GL_GREATER(0x0204),
- GL_NOTEQUAL(0x0205),
- GL_GEQUAL(0x0206),
- GL_ALWAYS(0x0207),
- GL_SRC_COLOR(0x0300),
- GL_ONE_MINUS_SRC_COLOR(0x0301),
- GL_SRC_ALPHA(0x0302),
- GL_ONE_MINUS_SRC_ALPHA(0x0303),
- GL_DST_ALPHA(0x0304),
- GL_ONE_MINUS_DST_ALPHA(0x0305),
- GL_DST_COLOR(0x0306),
- GL_ONE_MINUS_DST_COLOR(0x0307),
- GL_SRC_ALPHA_SATURATE(0x0308),
- GL_FRONT(0x0404),
- GL_BACK(0x0405),
- GL_FRONT_AND_BACK(0x0408),
- GL_INVALID_ENUM(0x0500),
- GL_INVALID_VALUE(0x0501),
- GL_INVALID_OPERATION(0x0502),
- GL_STACK_OVERFLOW(0x0503),
- GL_STACK_UNDERFLOW(0x0504),
- GL_OUT_OF_MEMORY(0x0505),
- GL_INVALID_FRAMEBUFFER_OPERATION(0x0506),
- GL_EXP(0x0800),
- GL_EXP2(0x0801),
- GL_CW(0x0900),
- GL_CCW(0x0901),
- GL_CURRENT_COLOR(0x0B00),
- GL_CURRENT_NORMAL(0x0B02),
- GL_CURRENT_TEXTURE_COORDS(0x0B03),
- GL_POINT_SMOOTH(0x0B10),
- GL_POINT_SIZE(0x0B11),
- GL_SMOOTH_POINT_SIZE_RANGE(0x0B12),
- GL_LINE_SMOOTH(0x0B20),
- GL_LINE_WIDTH(0x0B21),
- GL_SMOOTH_LINE_WIDTH_RANGE(0x0B22),
- GL_CULL_FACE(0x0B44),
- GL_CULL_FACE_MODE(0x0B45),
- GL_FRONT_FACE(0x0B46),
- GL_LIGHTING(0x0B50),
- GL_LIGHT_MODEL_TWO_SIDE(0x0B52),
- GL_LIGHT_MODEL_AMBIENT(0x0B53),
- GL_SHADE_MODEL(0x0B54),
- GL_COLOR_MATERIAL(0x0B57),
- GL_FOG(0x0B60),
- GL_FOG_DENSITY(0x0B62),
- GL_FOG_START(0x0B63),
- GL_FOG_END(0x0B64),
- GL_FOG_MODE(0x0B65),
- GL_FOG_COLOR(0x0B66),
- GL_DEPTH_RANGE(0x0B70),
- GL_DEPTH_TEST(0x0B71),
- GL_DEPTH_WRITEMASK(0x0B72),
- GL_DEPTH_CLEAR_VALUE(0x0B73),
- GL_DEPTH_FUNC(0x0B74),
- GL_STENCIL_TEST(0x0B90),
- GL_STENCIL_CLEAR_VALUE(0x0B91),
- GL_STENCIL_FUNC(0x0B92),
- GL_STENCIL_VALUE_MASK(0x0B93),
- GL_STENCIL_FAIL(0x0B94),
- GL_STENCIL_PASS_DEPTH_FAIL(0x0B95),
- GL_STENCIL_PASS_DEPTH_PASS(0x0B96),
- GL_STENCIL_REF(0x0B97),
- GL_STENCIL_WRITEMASK(0x0B98),
- GL_MATRIX_MODE(0x0BA0),
- GL_NORMALIZE(0x0BA1),
- GL_VIEWPORT(0x0BA2),
- GL_MODELVIEW_STACK_DEPTH(0x0BA3),
- GL_PROJECTION_STACK_DEPTH(0x0BA4),
- GL_TEXTURE_STACK_DEPTH(0x0BA5),
- GL_MODELVIEW_MATRIX(0x0BA6),
- GL_PROJECTION_MATRIX(0x0BA7),
- GL_TEXTURE_MATRIX(0x0BA8),
- GL_ALPHA_TEST(0x0BC0),
- GL_ALPHA_TEST_FUNC(0x0BC1),
- GL_ALPHA_TEST_REF(0x0BC2),
- GL_DITHER(0x0BD0),
- GL_BLEND_DST(0x0BE0),
- GL_BLEND_SRC(0x0BE1),
- GL_BLEND(0x0BE2),
- GL_LOGIC_OP_MODE(0x0BF0),
- GL_COLOR_LOGIC_OP(0x0BF2),
- GL_READ_BUFFER_NV(0x0C02),
- GL_SCISSOR_BOX(0x0C10),
- GL_SCISSOR_TEST(0x0C11),
- GL_COLOR_CLEAR_VALUE(0x0C22),
- GL_COLOR_WRITEMASK(0x0C23),
- GL_PERSPECTIVE_CORRECTION_HINT(0x0C50),
- GL_POINT_SMOOTH_HINT(0x0C51),
- GL_LINE_SMOOTH_HINT(0x0C52),
- GL_FOG_HINT(0x0C54),
- GL_UNPACK_ROW_LENGTH(0x0CF2),
- GL_UNPACK_SKIP_ROWS(0x0CF3),
- GL_UNPACK_SKIP_PIXELS(0x0CF4),
- GL_UNPACK_ALIGNMENT(0x0CF5),
- GL_PACK_ALIGNMENT(0x0D05),
- GL_ALPHA_SCALE(0x0D1C),
- GL_MAX_LIGHTS(0x0D31),
- GL_MAX_CLIP_PLANES(0x0D32),
- GL_MAX_TEXTURE_SIZE(0x0D33),
- GL_MAX_MODELVIEW_STACK_DEPTH(0x0D36),
- GL_MAX_PROJECTION_STACK_DEPTH(0x0D38),
- GL_MAX_TEXTURE_STACK_DEPTH(0x0D39),
- GL_MAX_VIEWPORT_DIMS(0x0D3A),
- GL_SUBPIXEL_BITS(0x0D50),
- GL_RED_BITS(0x0D52),
- GL_GREEN_BITS(0x0D53),
- GL_BLUE_BITS(0x0D54),
- GL_ALPHA_BITS(0x0D55),
- GL_DEPTH_BITS(0x0D56),
- GL_STENCIL_BITS(0x0D57),
- GL_TEXTURE_2D(0x0DE1),
- GL_DONT_CARE(0x1100),
- GL_FASTEST(0x1101),
- GL_NICEST(0x1102),
- GL_AMBIENT(0x1200),
- GL_DIFFUSE(0x1201),
- GL_SPECULAR(0x1202),
- GL_POSITION(0x1203),
- GL_SPOT_DIRECTION(0x1204),
- GL_SPOT_EXPONENT(0x1205),
- GL_SPOT_CUTOFF(0x1206),
- GL_CONSTANT_ATTENUATION(0x1207),
- GL_LINEAR_ATTENUATION(0x1208),
- GL_QUADRATIC_ATTENUATION(0x1209),
- GL_BYTE(0x1400),
- GL_UNSIGNED_BYTE(0x1401),
- GL_SHORT(0x1402),
- GL_UNSIGNED_SHORT(0x1403),
- GL_INT(0x1404),
- GL_UNSIGNED_INT(0x1405),
- GL_FLOAT(0x1406),
- GL_FIXED(0x140C),
- GL_CLEAR(0x1500),
- GL_AND(0x1501),
- GL_AND_REVERSE(0x1502),
- GL_COPY(0x1503),
- GL_AND_INVERTED(0x1504),
- GL_NOOP(0x1505),
- GL_XOR(0x1506),
- GL_OR(0x1507),
- GL_NOR(0x1508),
- GL_EQUIV(0x1509),
- GL_INVERT(0x150A),
- GL_OR_REVERSE(0x150B),
- GL_COPY_INVERTED(0x150C),
- GL_OR_INVERTED(0x150D),
- GL_NAND(0x150E),
- GL_SET(0x150F),
- GL_EMISSION(0x1600),
- GL_SHININESS(0x1601),
- GL_AMBIENT_AND_DIFFUSE(0x1602),
- GL_MODELVIEW(0x1700),
- GL_PROJECTION(0x1701),
- GL_TEXTURE(0x1702),
- GL_COLOR_EXT(0x1800),
- GL_DEPTH_EXT(0x1801),
- GL_STENCIL_EXT(0x1802),
- GL_STENCIL_INDEX(0x1901),
- GL_DEPTH_COMPONENT(0x1902),
- GL_RED_EXT(0x1903),
- GL_ALPHA(0x1906),
- GL_RGB(0x1907),
- GL_RGBA(0x1908),
- GL_LUMINANCE(0x1909),
- GL_LUMINANCE_ALPHA(0x190A),
- GL_FLAT(0x1D00),
- GL_SMOOTH(0x1D01),
- GL_KEEP(0x1E00),
- GL_REPLACE(0x1E01),
- GL_INCR(0x1E02),
- GL_DECR(0x1E03),
- GL_VENDOR(0x1F00),
- GL_RENDERER(0x1F01),
- GL_VERSION(0x1F02),
- GL_EXTENSIONS(0x1F03),
- GL_MODULATE(0x2100),
- GL_DECAL(0x2101),
- GL_TEXTURE_ENV_MODE(0x2200),
- GL_TEXTURE_ENV_COLOR(0x2201),
- GL_TEXTURE_ENV(0x2300),
- GL_TEXTURE_GEN_MODE(0x2500),
- GL_NEAREST(0x2600),
- GL_LINEAR(0x2601),
- GL_NEAREST_MIPMAP_NEAREST(0x2700),
- GL_LINEAR_MIPMAP_NEAREST(0x2701),
- GL_NEAREST_MIPMAP_LINEAR(0x2702),
- GL_LINEAR_MIPMAP_LINEAR(0x2703),
- GL_TEXTURE_MAG_FILTER(0x2800),
- GL_TEXTURE_MIN_FILTER(0x2801),
- GL_TEXTURE_WRAP_S(0x2802),
- GL_TEXTURE_WRAP_T(0x2803),
- GL_REPEAT(0x2901),
- GL_POLYGON_OFFSET_UNITS(0x2A00),
- GL_CLIP_PLANE0(0x3000),
- GL_CLIP_PLANE1(0x3001),
- GL_CLIP_PLANE2(0x3002),
- GL_CLIP_PLANE3(0x3003),
- GL_CLIP_PLANE4(0x3004),
- GL_CLIP_PLANE5(0x3005),
- GL_LIGHT0(0x4000),
- GL_LIGHT1(0x4001),
- GL_LIGHT2(0x4002),
- GL_LIGHT3(0x4003),
- GL_LIGHT4(0x4004),
- GL_LIGHT5(0x4005),
- GL_LIGHT6(0x4006),
- GL_LIGHT7(0x4007),
- GL_COVERAGE_BUFFER_BIT_NV(0x8000),
- GL_CONSTANT_COLOR(0x8001),
- GL_ONE_MINUS_CONSTANT_COLOR(0x8002),
- GL_CONSTANT_ALPHA(0x8003),
- GL_ONE_MINUS_CONSTANT_ALPHA(0x8004),
- GL_BLEND_COLOR(0x8005),
- GL_FUNC_ADD(0x8006),
- GL_MIN_EXT(0x8007),
- GL_MAX_EXT(0x8008),
- GL_BLEND_EQUATION_RGB(0x8009),
- GL_FUNC_SUBTRACT(0x800A),
- GL_FUNC_REVERSE_SUBTRACT(0x800B),
- GL_UNSIGNED_SHORT_4_4_4_4(0x8033),
- GL_UNSIGNED_SHORT_5_5_5_1(0x8034),
- GL_POLYGON_OFFSET_FILL(0x8037),
- GL_POLYGON_OFFSET_FACTOR(0x8038),
- GL_RESCALE_NORMAL(0x803A),
- GL_ALPHA8_EXT(0x803C),
- GL_LUMINANCE8_EXT(0x8040),
- GL_LUMINANCE8_ALPHA8_EXT(0x8045),
- GL_RGB8(0x8051),
- GL_RGB10_EXT(0x8052),
- GL_RGBA4(0x8056),
- GL_RGB5_A1(0x8057),
- GL_RGBA8(0x8058),
- GL_RGB10_A2_EXT(0x8059),
- GL_TEXTURE_BINDING_2D(0x8069),
- GL_TEXTURE_BINDING_3D(0x806A),
- GL_TEXTURE_3D(0x806F),
- GL_TEXTURE_WRAP_R(0x8072),
- GL_MAX_3D_TEXTURE_SIZE(0x8073),
- GL_VERTEX_ARRAY(0x8074),
- GL_NORMAL_ARRAY(0x8075),
- GL_COLOR_ARRAY(0x8076),
- GL_TEXTURE_COORD_ARRAY(0x8078),
- GL_VERTEX_ARRAY_SIZE(0x807A),
- GL_VERTEX_ARRAY_TYPE(0x807B),
- GL_VERTEX_ARRAY_STRIDE(0x807C),
- GL_NORMAL_ARRAY_TYPE(0x807E),
- GL_NORMAL_ARRAY_STRIDE(0x807F),
- GL_COLOR_ARRAY_SIZE(0x8081),
- GL_COLOR_ARRAY_TYPE(0x8082),
- GL_COLOR_ARRAY_STRIDE(0x8083),
- GL_TEXTURE_COORD_ARRAY_SIZE(0x8088),
- GL_TEXTURE_COORD_ARRAY_TYPE(0x8089),
- GL_TEXTURE_COORD_ARRAY_STRIDE(0x808A),
- GL_VERTEX_ARRAY_POINTER(0x808E),
- GL_NORMAL_ARRAY_POINTER(0x808F),
- GL_COLOR_ARRAY_POINTER(0x8090),
- GL_TEXTURE_COORD_ARRAY_POINTER(0x8092),
- GL_MULTISAMPLE(0x809D),
- GL_SAMPLE_ALPHA_TO_COVERAGE(0x809E),
- GL_SAMPLE_ALPHA_TO_ONE(0x809F),
- GL_SAMPLE_COVERAGE(0x80A0),
- GL_SAMPLE_BUFFERS(0x80A8),
- GL_SAMPLES(0x80A9),
- GL_SAMPLE_COVERAGE_VALUE(0x80AA),
- GL_SAMPLE_COVERAGE_INVERT(0x80AB),
- GL_BLEND_DST_RGB(0x80C8),
- GL_BLEND_SRC_RGB(0x80C9),
- GL_BLEND_DST_ALPHA(0x80CA),
- GL_BLEND_SRC_ALPHA(0x80CB),
- GL_BGRA_EXT(0x80E1),
- GL_POINT_SIZE_MIN(0x8126),
- GL_POINT_SIZE_MAX(0x8127),
- GL_POINT_FADE_THRESHOLD_SIZE(0x8128),
- GL_POINT_DISTANCE_ATTENUATION(0x8129),
- GL_CLAMP_TO_EDGE(0x812F),
- GL_GENERATE_MIPMAP(0x8191),
- GL_GENERATE_MIPMAP_HINT(0x8192),
- GL_DEPTH_COMPONENT16(0x81A5),
- GL_DEPTH_COMPONENT24(0x81A6),
- GL_DEPTH_COMPONENT32(0x81A7),
- GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT(0x8210),
- GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT(0x8211),
- GL_RG_EXT(0x8227),
- GL_R8_EXT(0x8229),
- GL_RG8_EXT(0x822B),
- GL_R16F_EXT(0x822D),
- GL_RG16F_EXT(0x822F),
- GL_LOSE_CONTEXT_ON_RESET_EXT(0x8252),
- GL_GUILTY_CONTEXT_RESET_EXT(0x8253),
- GL_INNOCENT_CONTEXT_RESET_EXT(0x8254),
- GL_UNKNOWN_CONTEXT_RESET_EXT(0x8255),
- GL_RESET_NOTIFICATION_STRATEGY_EXT(0x8256),
- GL_PROGRAM_SEPARABLE_EXT(0x8258),
- GL_ACTIVE_PROGRAM_EXT(0x8259),
- GL_PROGRAM_PIPELINE_BINDING_EXT(0x825A),
- GL_NO_RESET_NOTIFICATION_EXT(0x8261),
- GL_UNSIGNED_SHORT_5_6_5(0x8363),
- GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT(0x8365),
- GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT(0x8366),
- GL_UNSIGNED_INT_2_10_10_10_REV_EXT(0x8368),
- GL_MIRRORED_REPEAT(0x8370),
- GL_COMPRESSED_RGB_S3TC_DXT1_EXT(0x83F0),
- GL_COMPRESSED_RGBA_S3TC_DXT1_EXT(0x83F1),
- GL_ALIASED_POINT_SIZE_RANGE(0x846D),
- GL_ALIASED_LINE_WIDTH_RANGE(0x846E),
- GL_TEXTURE0(0x84C0),
- GL_TEXTURE1(0x84C1),
- GL_TEXTURE2(0x84C2),
- GL_TEXTURE3(0x84C3),
- GL_TEXTURE4(0x84C4),
- GL_TEXTURE5(0x84C5),
- GL_TEXTURE6(0x84C6),
- GL_TEXTURE7(0x84C7),
- GL_TEXTURE8(0x84C8),
- GL_TEXTURE9(0x84C9),
- GL_TEXTURE10(0x84CA),
- GL_TEXTURE11(0x84CB),
- GL_TEXTURE12(0x84CC),
- GL_TEXTURE13(0x84CD),
- GL_TEXTURE14(0x84CE),
- GL_TEXTURE15(0x84CF),
- GL_TEXTURE16(0x84D0),
- GL_TEXTURE17(0x84D1),
- GL_TEXTURE18(0x84D2),
- GL_TEXTURE19(0x84D3),
- GL_TEXTURE20(0x84D4),
- GL_TEXTURE21(0x84D5),
- GL_TEXTURE22(0x84D6),
- GL_TEXTURE23(0x84D7),
- GL_TEXTURE24(0x84D8),
- GL_TEXTURE25(0x84D9),
- GL_TEXTURE26(0x84DA),
- GL_TEXTURE27(0x84DB),
- GL_TEXTURE28(0x84DC),
- GL_TEXTURE29(0x84DD),
- GL_TEXTURE30(0x84DE),
- GL_TEXTURE31(0x84DF),
- GL_ACTIVE_TEXTURE(0x84E0),
- GL_CLIENT_ACTIVE_TEXTURE(0x84E1),
- GL_MAX_TEXTURE_UNITS(0x84E2),
- GL_SUBTRACT(0x84E7),
- GL_MAX_RENDERBUFFER_SIZE(0x84E8),
- GL_ALL_COMPLETED_NV(0x84F2),
- GL_FENCE_STATUS_NV(0x84F3),
- GL_FENCE_CONDITION_NV(0x84F4),
- GL_DEPTH_STENCIL(0x84F9),
- GL_UNSIGNED_INT_24_8(0x84FA),
- GL_MAX_TEXTURE_LOD_BIAS_EXT(0x84FD),
- GL_TEXTURE_MAX_ANISOTROPY_EXT(0x84FE),
- GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT(0x84FF),
- GL_TEXTURE_FILTER_CONTROL_EXT(0x8500),
- GL_TEXTURE_LOD_BIAS_EXT(0x8501),
- GL_INCR_WRAP(0x8507),
- GL_DECR_WRAP(0x8508),
- GL_NORMAL_MAP(0x8511),
- GL_REFLECTION_MAP(0x8512),
- GL_TEXTURE_CUBE_MAP(0x8513),
- GL_TEXTURE_BINDING_CUBE_MAP(0x8514),
- GL_TEXTURE_CUBE_MAP_POSITIVE_X(0x8515),
- GL_TEXTURE_CUBE_MAP_NEGATIVE_X(0x8516),
- GL_TEXTURE_CUBE_MAP_POSITIVE_Y(0x8517),
- GL_TEXTURE_CUBE_MAP_NEGATIVE_Y(0x8518),
- GL_TEXTURE_CUBE_MAP_POSITIVE_Z(0x8519),
- GL_TEXTURE_CUBE_MAP_NEGATIVE_Z(0x851A),
- GL_MAX_CUBE_MAP_TEXTURE_SIZE(0x851C),
- GL_COMBINE(0x8570),
- GL_COMBINE_RGB(0x8571),
- GL_COMBINE_ALPHA(0x8572),
- GL_RGB_SCALE(0x8573),
- GL_ADD_SIGNED(0x8574),
- GL_INTERPOLATE(0x8575),
- GL_CONSTANT(0x8576),
- GL_PRIMARY_COLOR(0x8577),
- GL_PREVIOUS(0x8578),
- GL_SRC0_RGB(0x8580),
- GL_SRC1_RGB(0x8581),
- GL_SRC2_RGB(0x8582),
- GL_SRC0_ALPHA(0x8588),
- GL_SRC1_ALPHA(0x8589),
- GL_SRC2_ALPHA(0x858A),
- GL_OPERAND0_RGB(0x8590),
- GL_OPERAND1_RGB(0x8591),
- GL_OPERAND2_RGB(0x8592),
- GL_OPERAND0_ALPHA(0x8598),
- GL_OPERAND1_ALPHA(0x8599),
- GL_OPERAND2_ALPHA(0x859A),
- GL_VERTEX_ARRAY_BINDING(0x85B5),
- GL_UNSIGNED_SHORT_8_8_APPLE(0x85BA),
- GL_UNSIGNED_SHORT_8_8_REV_APPLE(0x85BB),
- GL_VERTEX_ATTRIB_ARRAY_ENABLED(0x8622),
- GL_VERTEX_ATTRIB_ARRAY_SIZE(0x8623),
- GL_VERTEX_ATTRIB_ARRAY_STRIDE(0x8624),
- GL_VERTEX_ATTRIB_ARRAY_TYPE(0x8625),
- GL_CURRENT_VERTEX_ATTRIB(0x8626),
- GL_VERTEX_ATTRIB_ARRAY_POINTER(0x8645),
- GL_NUM_COMPRESSED_TEXTURE_FORMATS(0x86A2),
- GL_COMPRESSED_TEXTURE_FORMATS(0x86A3),
- GL_MAX_VERTEX_UNITS(0x86A4),
- GL_WEIGHT_ARRAY_TYPE(0x86A9),
- GL_WEIGHT_ARRAY_STRIDE(0x86AA),
- GL_WEIGHT_ARRAY_SIZE(0x86AB),
- GL_WEIGHT_ARRAY_POINTER(0x86AC),
- GL_WEIGHT_ARRAY(0x86AD),
- GL_DOT3_RGB(0x86AE),
- GL_DOT3_RGBA(0x86AF),
- GL_Z400_BINARY_AMD(0x8740),
- GL_PROGRAM_BINARY_LENGTH(0x8741),
- GL_BUFFER_SIZE(0x8764),
- GL_BUFFER_USAGE(0x8765),
- GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD(0x87EE),
- GL_3DC_X_AMD(0x87F9),
- GL_3DC_XY_AMD(0x87FA),
- GL_NUM_PROGRAM_BINARY_FORMATS(0x87FE),
- GL_PROGRAM_BINARY_FORMATS(0x87FF),
- GL_STENCIL_BACK_FUNC(0x8800),
- GL_STENCIL_BACK_FAIL(0x8801),
- GL_STENCIL_BACK_PASS_DEPTH_FAIL(0x8802),
- GL_STENCIL_BACK_PASS_DEPTH_PASS(0x8803),
- GL_RGBA32F_EXT(0x8814),
- GL_RGB32F_EXT(0x8815),
- GL_ALPHA32F_EXT(0x8816),
- GL_LUMINANCE32F_EXT(0x8818),
- GL_LUMINANCE_ALPHA32F_EXT(0x8819),
- GL_RGBA16F_EXT(0x881A),
- GL_RGB16F_EXT(0x881B),
- GL_ALPHA16F_EXT(0x881C),
- GL_LUMINANCE16F_EXT(0x881E),
- GL_LUMINANCE_ALPHA16F_EXT(0x881F),
- GL_WRITEONLY_RENDERING_QCOM(0x8823),
- GL_MAX_DRAW_BUFFERS_NV(0x8824),
- GL_DRAW_BUFFER0_NV(0x8825),
- GL_DRAW_BUFFER1_NV(0x8826),
- GL_DRAW_BUFFER2_NV(0x8827),
- GL_DRAW_BUFFER3_NV(0x8828),
- GL_DRAW_BUFFER4_NV(0x8829),
- GL_DRAW_BUFFER5_NV(0x882A),
- GL_DRAW_BUFFER6_NV(0x882B),
- GL_DRAW_BUFFER7_NV(0x882C),
- GL_DRAW_BUFFER8_NV(0x882D),
- GL_DRAW_BUFFER9_NV(0x882E),
- GL_DRAW_BUFFER10_NV(0x882F),
- GL_DRAW_BUFFER11_NV(0x8830),
- GL_DRAW_BUFFER12_NV(0x8831),
- GL_DRAW_BUFFER13_NV(0x8832),
- GL_DRAW_BUFFER14_NV(0x8833),
- GL_DRAW_BUFFER15_NV(0x8834),
- GL_BLEND_EQUATION_ALPHA(0x883D),
- GL_MATRIX_PALETTE(0x8840),
- GL_MAX_PALETTE_MATRICES(0x8842),
- GL_CURRENT_PALETTE_MATRIX(0x8843),
- GL_MATRIX_INDEX_ARRAY(0x8844),
- GL_MATRIX_INDEX_ARRAY_SIZE(0x8846),
- GL_MATRIX_INDEX_ARRAY_TYPE(0x8847),
- GL_MATRIX_INDEX_ARRAY_STRIDE(0x8848),
- GL_MATRIX_INDEX_ARRAY_POINTER(0x8849),
- GL_COMPARE_REF_TO_TEXTURE_EXT(0x884E),
- GL_CURRENT_QUERY_EXT(0x8865),
- GL_QUERY_RESULT_EXT(0x8866),
- GL_QUERY_RESULT_AVAILABLE_EXT(0x8867),
- GL_POINT_SPRITE(0x8861),
- GL_COORD_REPLACE(0x8862),
- GL_MAX_VERTEX_ATTRIBS(0x8869),
- GL_VERTEX_ATTRIB_ARRAY_NORMALIZED(0x886A),
- GL_MAX_TEXTURE_IMAGE_UNITS(0x8872),
- GL_ARRAY_BUFFER(0x8892),
- GL_ELEMENT_ARRAY_BUFFER(0x8893),
- GL_ARRAY_BUFFER_BINDING(0x8894),
- GL_ELEMENT_ARRAY_BUFFER_BINDING(0x8895),
- GL_VERTEX_ARRAY_BUFFER_BINDING(0x8896),
- GL_NORMAL_ARRAY_BUFFER_BINDING(0x8897),
- GL_COLOR_ARRAY_BUFFER_BINDING(0x8898),
- GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING(0x889A),
- GL_WEIGHT_ARRAY_BUFFER_BINDING(0x889E),
- GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING(0x889F),
- GL_WRITE_ONLY(0x88B9),
- GL_BUFFER_ACCESS(0x88BB),
- GL_BUFFER_MAPPED(0x88BC),
- GL_BUFFER_MAP_POINTER(0x88BD),
- GL_STREAM_DRAW(0x88E0),
- GL_STATIC_DRAW(0x88E4),
- GL_DYNAMIC_DRAW(0x88E8),
- GL_DEPTH24_STENCIL8(0x88F0),
- GL_POINT_SIZE_ARRAY_TYPE(0x898A),
- GL_POINT_SIZE_ARRAY_STRIDE(0x898B),
- GL_POINT_SIZE_ARRAY_POINTER(0x898C),
- GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS(0x898D),
- GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS(0x898E),
- GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS(0x898F),
- GL_RGB_422_APPLE(0x8A1F),
- GL_PROGRAM_PIPELINE_OBJECT_EXT(0x8A4F),
- GL_FRAGMENT_SHADER(0x8B30),
- GL_VERTEX_SHADER(0x8B31),
- GL_PROGRAM_OBJECT_EXT(0x8B40),
- GL_SHADER_OBJECT_EXT(0x8B48),
- GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS(0x8B4C),
- GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS(0x8B4D),
- GL_SHADER_TYPE(0x8B4F),
- GL_FLOAT_VEC2(0x8B50),
- GL_FLOAT_VEC3(0x8B51),
- GL_FLOAT_VEC4(0x8B52),
- GL_INT_VEC2(0x8B53),
- GL_INT_VEC3(0x8B54),
- GL_INT_VEC4(0x8B55),
- GL_BOOL(0x8B56),
- GL_BOOL_VEC2(0x8B57),
- GL_BOOL_VEC3(0x8B58),
- GL_BOOL_VEC4(0x8B59),
- GL_FLOAT_MAT2(0x8B5A),
- GL_FLOAT_MAT3(0x8B5B),
- GL_FLOAT_MAT4(0x8B5C),
- GL_SAMPLER_2D(0x8B5E),
- GL_SAMPLER_3D(0x8B5F),
- GL_SAMPLER_CUBE(0x8B60),
- GL_SAMPLER_2D_SHADOW_EXT(0x8B62),
- GL_DELETE_STATUS(0x8B80),
- GL_COMPILE_STATUS(0x8B81),
- GL_LINK_STATUS(0x8B82),
- GL_VALIDATE_STATUS(0x8B83),
- GL_INFO_LOG_LENGTH(0x8B84),
- GL_ATTACHED_SHADERS(0x8B85),
- GL_ACTIVE_UNIFORMS(0x8B86),
- GL_ACTIVE_UNIFORM_MAX_LENGTH(0x8B87),
- GL_SHADER_SOURCE_LENGTH(0x8B88),
- GL_ACTIVE_ATTRIBUTES(0x8B89),
- GL_ACTIVE_ATTRIBUTE_MAX_LENGTH(0x8B8A),
- GL_FRAGMENT_SHADER_DERIVATIVE_HINT(0x8B8B),
- GL_SHADING_LANGUAGE_VERSION(0x8B8C),
- GL_CURRENT_PROGRAM(0x8B8D),
- GL_PALETTE4_RGB8(0x8B90),
- GL_PALETTE4_RGBA8(0x8B91),
- GL_PALETTE4_R5_G6_B5(0x8B92),
- GL_PALETTE4_RGBA4(0x8B93),
- GL_PALETTE4_RGB5_A1(0x8B94),
- GL_PALETTE8_RGB8(0x8B95),
- GL_PALETTE8_RGBA8(0x8B96),
- GL_PALETTE8_R5_G6_B5(0x8B97),
- GL_PALETTE8_RGBA4(0x8B98),
- GL_PALETTE8_RGB5_A1(0x8B99),
- GL_IMPLEMENTATION_COLOR_READ_TYPE(0x8B9A),
- GL_IMPLEMENTATION_COLOR_READ_FORMAT(0x8B9B),
- GL_POINT_SIZE_ARRAY(0x8B9C),
- GL_TEXTURE_CROP_RECT(0x8B9D),
- GL_MATRIX_INDEX_ARRAY_BUFFER_BINDING(0x8B9E),
- GL_POINT_SIZE_ARRAY_BUFFER_BINDING(0x8B9F),
- GL_COUNTER_TYPE_AMD(0x8BC0),
- GL_COUNTER_RANGE_AMD(0x8BC1),
- GL_UNSIGNED_INT64_AMD(0x8BC2),
- GL_PERCENTAGE_AMD(0x8BC3),
- GL_PERFMON_RESULT_AVAILABLE_AMD(0x8BC4),
- GL_PERFMON_RESULT_SIZE_AMD(0x8BC5),
- GL_PERFMON_RESULT_AMD(0x8BC6),
- GL_TEXTURE_WIDTH_QCOM(0x8BD2),
- GL_TEXTURE_HEIGHT_QCOM(0x8BD3),
- GL_TEXTURE_DEPTH_QCOM(0x8BD4),
- GL_TEXTURE_INTERNAL_FORMAT_QCOM(0x8BD5),
- GL_TEXTURE_FORMAT_QCOM(0x8BD6),
- GL_TEXTURE_TYPE_QCOM(0x8BD7),
- GL_TEXTURE_IMAGE_VALID_QCOM(0x8BD8),
- GL_TEXTURE_NUM_LEVELS_QCOM(0x8BD9),
- GL_TEXTURE_TARGET_QCOM(0x8BDA),
- GL_TEXTURE_OBJECT_VALID_QCOM(0x8BDB),
- GL_STATE_RESTORE(0x8BDC),
- GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG(0x8C00),
- GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG(0x8C01),
- GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG(0x8C02),
- GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG(0x8C03),
- GL_MODULATE_COLOR_IMG(0x8C04),
- GL_RECIP_ADD_SIGNED_ALPHA_IMG(0x8C05),
- GL_TEXTURE_ALPHA_MODULATE_IMG(0x8C06),
- GL_FACTOR_ALPHA_MODULATE_IMG(0x8C07),
- GL_FRAGMENT_ALPHA_MODULATE_IMG(0x8C08),
- GL_ADD_BLEND_IMG(0x8C09),
- GL_SGX_BINARY_IMG(0x8C0A),
- GL_UNSIGNED_NORMALIZED_EXT(0x8C17),
- GL_ANY_SAMPLES_PASSED_EXT(0x8C2F),
- GL_SRGB_EXT(0x8C40),
- GL_SRGB_ALPHA_EXT(0x8C42),
- GL_SRGB8_ALPHA8_EXT(0x8C43),
- GL_ATC_RGB_AMD(0x8C92),
- GL_ATC_RGBA_EXPLICIT_ALPHA_AMD(0x8C93),
- GL_STENCIL_BACK_REF(0x8CA3),
- GL_STENCIL_BACK_VALUE_MASK(0x8CA4),
- GL_STENCIL_BACK_WRITEMASK(0x8CA5),
- GL_FRAMEBUFFER_BINDING(0x8CA6),
- GL_RENDERBUFFER_BINDING(0x8CA7),
- GL_READ_FRAMEBUFFER_APPLE(0x8CA8),
- GL_DRAW_FRAMEBUFFER_APPLE(0x8CA9),
- GL_READ_FRAMEBUFFER_BINDING_APPLE(0x8CAA),
- GL_RENDERBUFFER_SAMPLES_APPLE(0x8CAB),
- GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE(0x8CD0),
- GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME(0x8CD1),
- GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL(0x8CD2),
- GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE(0x8CD3),
- GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET(0x8CD4),
- GL_FRAMEBUFFER_COMPLETE(0x8CD5),
- GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT(0x8CD6),
- GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT(0x8CD7),
- GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS(0x8CD9),
- GL_FRAMEBUFFER_INCOMPLETE_FORMATS(0x8CDA),
- GL_FRAMEBUFFER_UNSUPPORTED(0x8CDD),
- GL_MAX_COLOR_ATTACHMENTS_NV(0x8CDF),
- GL_COLOR_ATTACHMENT0(0x8CE0),
- GL_COLOR_ATTACHMENT1_NV(0x8CE1),
- GL_COLOR_ATTACHMENT2_NV(0x8CE2),
- GL_COLOR_ATTACHMENT3_NV(0x8CE3),
- GL_COLOR_ATTACHMENT4_NV(0x8CE4),
- GL_COLOR_ATTACHMENT5_NV(0x8CE5),
- GL_COLOR_ATTACHMENT6_NV(0x8CE6),
- GL_COLOR_ATTACHMENT7_NV(0x8CE7),
- GL_COLOR_ATTACHMENT8_NV(0x8CE8),
- GL_COLOR_ATTACHMENT9_NV(0x8CE9),
- GL_COLOR_ATTACHMENT10_NV(0x8CEA),
- GL_COLOR_ATTACHMENT11_NV(0x8CEB),
- GL_COLOR_ATTACHMENT12_NV(0x8CEC),
- GL_COLOR_ATTACHMENT13_NV(0x8CED),
- GL_COLOR_ATTACHMENT14_NV(0x8CEE),
- GL_COLOR_ATTACHMENT15_NV(0x8CEF),
- GL_DEPTH_ATTACHMENT(0x8D00),
- GL_STENCIL_ATTACHMENT(0x8D20),
- GL_FRAMEBUFFER(0x8D40),
- GL_RENDERBUFFER(0x8D41),
- GL_RENDERBUFFER_WIDTH(0x8D42),
- GL_RENDERBUFFER_HEIGHT(0x8D43),
- GL_RENDERBUFFER_INTERNAL_FORMAT(0x8D44),
- GL_STENCIL_INDEX1(0x8D46),
- GL_STENCIL_INDEX4(0x8D47),
- GL_STENCIL_INDEX8(0x8D48),
- GL_RENDERBUFFER_RED_SIZE(0x8D50),
- GL_RENDERBUFFER_GREEN_SIZE(0x8D51),
- GL_RENDERBUFFER_BLUE_SIZE(0x8D52),
- GL_RENDERBUFFER_ALPHA_SIZE(0x8D53),
- GL_RENDERBUFFER_DEPTH_SIZE(0x8D54),
- GL_RENDERBUFFER_STENCIL_SIZE(0x8D55),
- GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_APPLE(0x8D56),
- GL_MAX_SAMPLES_APPLE(0x8D57),
- GL_TEXTURE_GEN_STR(0x8D60),
- GL_HALF_FLOAT(0x8D61),
- GL_RGB565(0x8D62),
- GL_ETC1_RGB8(0x8D64),
- GL_TEXTURE_EXTERNAL(0x8D65),
- GL_SAMPLER_EXTERNAL(0x8D66),
- GL_TEXTURE_BINDING_EXTERNAL(0x8D67),
- GL_REQUIRED_TEXTURE_IMAGE_UNITS(0x8D68),
- GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT(0x8D6A),
- GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_SAMPLES_EXT(0x8D6C),
- GL_LOW_FLOAT(0x8DF0),
- GL_MEDIUM_FLOAT(0x8DF1),
- GL_HIGH_FLOAT(0x8DF2),
- GL_LOW_INT(0x8DF3),
- GL_MEDIUM_INT(0x8DF4),
- GL_HIGH_INT(0x8DF5),
- GL_UNSIGNED_INT_10_10_10_2(0x8DF6),
- GL_INT_10_10_10_2(0x8DF7),
- GL_SHADER_BINARY_FORMATS(0x8DF8),
- GL_NUM_SHADER_BINARY_FORMATS(0x8DF9),
- GL_SHADER_COMPILER(0x8DFA),
- GL_MAX_VERTEX_UNIFORM_VECTORS(0x8DFB),
- GL_MAX_VARYING_VECTORS(0x8DFC),
- GL_MAX_FRAGMENT_UNIFORM_VECTORS(0x8DFD),
- GL_DEPTH_COMPONENT16_NONLINEAR_NV(0x8E2C),
- GL_COVERAGE_COMPONENT_NV(0x8ED0),
- GL_COVERAGE_COMPONENT4_NV(0x8ED1),
- GL_COVERAGE_ATTACHMENT_NV(0x8ED2),
- GL_COVERAGE_BUFFERS_NV(0x8ED3),
- GL_COVERAGE_SAMPLES_NV(0x8ED4),
- GL_COVERAGE_ALL_FRAGMENTS_NV(0x8ED5),
- GL_COVERAGE_EDGE_FRAGMENTS_NV(0x8ED6),
- GL_COVERAGE_AUTOMATIC_NV(0x8ED7),
- GL_MALI_SHADER_BINARY_ARM(0x8F60),
- GL_PERFMON_GLOBAL_MODE_QCOM(0x8FA0),
- GL_SHADER_BINARY_VIV(0x8FC4),
- GL_CONTEXT_ROBUST_ACCESS_EXT(0x90F3),
- GL_TEXTURE_IMMUTABLE_FORMAT_EXT(0x912F),
- GL_SGX_PROGRAM_BINARY_IMG(0x9130),
- GL_RENDERBUFFER_SAMPLES_EXT(0x9133),
- GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT(0x9134),
- GL_MAX_SAMPLES_EXT(0x9135),
- GL_TEXTURE_SAMPLES_IMG(0x9136),
- GL_BUFFER_OBJECT_EXT(0x9151),
- GL_QUERY_OBJECT_EXT(0x9153),
- GL_VERTEX_ARRAY_OBJECT_EXT(0x9154),
- GL_SHADER_BINARY_DMP(0x9250),
- GL_BGRA8_EXT(0x93A1),
-
- // Constants defined by ES3
- GL_READ_BUFFER(0x0C02),
- GL_PACK_ROW_LENGTH(0x0D02),
- GL_PACK_SKIP_ROWS(0x0D03),
- GL_PACK_SKIP_PIXELS(0x0D04),
- GL_COLOR(0x1800),
- GL_DEPTH(0x1801),
- GL_STENCIL(0x1802),
- GL_RED(0x1903),
- GL_RGB10_A2(0x8059),
- GL_UNPACK_SKIP_IMAGES(0x806D),
- GL_UNPACK_IMAGE_HEIGHT(0x806E),
- GL_UNSIGNED_INT_2_10_10_10_REV(0x8368),
- GL_MAX_ELEMENTS_VERTICES(0x80E8),
- GL_MAX_ELEMENTS_INDICES(0x80E9),
- GL_TEXTURE_MIN_LOD(0x813A),
- GL_TEXTURE_MAX_LOD(0x813B),
- GL_TEXTURE_BASE_LEVEL(0x813C),
- GL_TEXTURE_MAX_LEVEL(0x813D),
- GL_MIN(0x8007),
- GL_MAX(0x8008),
- GL_MAX_TEXTURE_LOD_BIAS(0x84FD),
- GL_TEXTURE_COMPARE_MODE(0x884C),
- GL_TEXTURE_COMPARE_FUNC(0x884D),
- GL_CURRENT_QUERY(0x8865),
- GL_QUERY_RESULT(0x8866),
- GL_QUERY_RESULT_AVAILABLE(0x8867),
- GL_STREAM_READ(0x88E1),
- GL_STREAM_COPY(0x88E2),
- GL_STATIC_READ(0x88E5),
- GL_STATIC_COPY(0x88E6),
- GL_DYNAMIC_READ(0x88E9),
- GL_DYNAMIC_COPY(0x88EA),
- GL_MAX_DRAW_BUFFERS(0x8824),
- GL_DRAW_BUFFER0(0x8825),
- GL_DRAW_BUFFER1(0x8826),
- GL_DRAW_BUFFER2(0x8827),
- GL_DRAW_BUFFER3(0x8828),
- GL_DRAW_BUFFER4(0x8829),
- GL_DRAW_BUFFER5(0x882A),
- GL_DRAW_BUFFER6(0x882B),
- GL_DRAW_BUFFER7(0x882C),
- GL_DRAW_BUFFER8(0x882D),
- GL_DRAW_BUFFER9(0x882E),
- GL_DRAW_BUFFER10(0x882F),
- GL_DRAW_BUFFER11(0x8830),
- GL_DRAW_BUFFER12(0x8831),
- GL_DRAW_BUFFER13(0x8832),
- GL_DRAW_BUFFER14(0x8833),
- GL_DRAW_BUFFER15(0x8834),
- GL_MAX_FRAGMENT_UNIFORM_COMPONENTS(0x8B49),
- GL_MAX_VERTEX_UNIFORM_COMPONENTS(0x8B4A),
- GL_SAMPLER_2D_SHADOW(0x8B62),
- GL_PIXEL_PACK_BUFFER(0x88EB),
- GL_PIXEL_UNPACK_BUFFER(0x88EC),
- GL_PIXEL_PACK_BUFFER_BINDING(0x88ED),
- GL_PIXEL_UNPACK_BUFFER_BINDING(0x88EF),
- GL_FLOAT_MAT2x3(0x8B65),
- GL_FLOAT_MAT2x4(0x8B66),
- GL_FLOAT_MAT3x2(0x8B67),
- GL_FLOAT_MAT3x4(0x8B68),
- GL_FLOAT_MAT4x2(0x8B69),
- GL_FLOAT_MAT4x3(0x8B6A),
- GL_SRGB(0x8C40),
- GL_SRGB8(0x8C41),
- GL_SRGB8_ALPHA8(0x8C43),
- GL_COMPARE_REF_TO_TEXTURE(0x884E),
- GL_MAJOR_VERSION(0x821B),
- GL_MINOR_VERSION(0x821C),
- GL_NUM_EXTENSIONS(0x821D),
- GL_RGBA32F(0x8814),
- GL_RGB32F(0x8815),
- GL_RGBA16F(0x881A),
- GL_RGB16F(0x881B),
- GL_VERTEX_ATTRIB_ARRAY_INTEGER(0x88FD),
- GL_MAX_ARRAY_TEXTURE_LAYERS(0x88FF),
- GL_MIN_PROGRAM_TEXEL_OFFSET(0x8904),
- GL_MAX_PROGRAM_TEXEL_OFFSET(0x8905),
- GL_MAX_VARYING_COMPONENTS(0x8B4B),
- GL_TEXTURE_2D_ARRAY(0x8C1A),
- GL_TEXTURE_BINDING_2D_ARRAY(0x8C1D),
- GL_R11F_G11F_B10F(0x8C3A),
- GL_UNSIGNED_INT_10F_11F_11F_REV(0x8C3B),
- GL_RGB9_E5(0x8C3D),
- GL_UNSIGNED_INT_5_9_9_9_REV(0x8C3E),
- GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH(0x8C76),
- GL_TRANSFORM_FEEDBACK_BUFFER_MODE(0x8C7F),
- GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS(0x8C80),
- GL_TRANSFORM_FEEDBACK_VARYINGS(0x8C83),
- GL_TRANSFORM_FEEDBACK_BUFFER_START(0x8C84),
- GL_TRANSFORM_FEEDBACK_BUFFER_SIZE(0x8C85),
- GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN(0x8C88),
- GL_RASTERIZER_DISCARD(0x8C89),
- GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS(0x8C8A),
- GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS(0x8C8B),
- GL_INTERLEAVED_ATTRIBS(0x8C8C),
- GL_SEPARATE_ATTRIBS(0x8C8D),
- GL_TRANSFORM_FEEDBACK_BUFFER(0x8C8E),
- GL_TRANSFORM_FEEDBACK_BUFFER_BINDING(0x8C8F),
- GL_RGBA32UI(0x8D70),
- GL_RGB32UI(0x8D71),
- GL_RGBA16UI(0x8D76),
- GL_RGB16UI(0x8D77),
- GL_RGBA8UI(0x8D7C),
- GL_RGB8UI(0x8D7D),
- GL_RGBA32I(0x8D82),
- GL_RGB32I(0x8D83),
- GL_RGBA16I(0x8D88),
- GL_RGB16I(0x8D89),
- GL_RGBA8I(0x8D8E),
- GL_RGB8I(0x8D8F),
- GL_RED_INTEGER(0x8D94),
- GL_RGB_INTEGER(0x8D98),
- GL_RGBA_INTEGER(0x8D99),
- GL_SAMPLER_2D_ARRAY(0x8DC1),
- GL_SAMPLER_2D_ARRAY_SHADOW(0x8DC4),
- GL_SAMPLER_CUBE_SHADOW(0x8DC5),
- GL_UNSIGNED_INT_VEC2(0x8DC6),
- GL_UNSIGNED_INT_VEC3(0x8DC7),
- GL_UNSIGNED_INT_VEC4(0x8DC8),
- GL_INT_SAMPLER_2D(0x8DCA),
- GL_INT_SAMPLER_3D(0x8DCB),
- GL_INT_SAMPLER_CUBE(0x8DCC),
- GL_INT_SAMPLER_2D_ARRAY(0x8DCF),
- GL_UNSIGNED_INT_SAMPLER_2D(0x8DD2),
- GL_UNSIGNED_INT_SAMPLER_3D(0x8DD3),
- GL_UNSIGNED_INT_SAMPLER_CUBE(0x8DD4),
- GL_UNSIGNED_INT_SAMPLER_2D_ARRAY(0x8DD7),
- GL_BUFFER_ACCESS_FLAGS(0x911F),
- GL_BUFFER_MAP_LENGTH(0x9120),
- GL_BUFFER_MAP_OFFSET(0x9121),
- GL_DEPTH_COMPONENT32F(0x8CAC),
- GL_DEPTH32F_STENCIL8(0x8CAD),
- GL_FLOAT_32_UNSIGNED_INT_24_8_REV(0x8DAD),
- GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING(0x8210),
- GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE(0x8211),
- GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE(0x8212),
- GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE(0x8213),
- GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE(0x8214),
- GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE(0x8215),
- GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE(0x8216),
- GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE(0x8217),
- GL_FRAMEBUFFER_DEFAULT(0x8218),
- GL_FRAMEBUFFER_UNDEFINED(0x8219),
- GL_DEPTH_STENCIL_ATTACHMENT(0x821A),
- GL_UNSIGNED_NORMALIZED(0x8C17),
- GL_READ_FRAMEBUFFER(0x8CA8),
- GL_DRAW_FRAMEBUFFER(0x8CA9),
- GL_READ_FRAMEBUFFER_BINDING(0x8CAA),
- GL_RENDERBUFFER_SAMPLES(0x8CAB),
- GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER(0x8CD4),
- GL_MAX_COLOR_ATTACHMENTS(0x8CDF),
- GL_COLOR_ATTACHMENT1(0x8CE1),
- GL_COLOR_ATTACHMENT2(0x8CE2),
- GL_COLOR_ATTACHMENT3(0x8CE3),
- GL_COLOR_ATTACHMENT4(0x8CE4),
- GL_COLOR_ATTACHMENT5(0x8CE5),
- GL_COLOR_ATTACHMENT6(0x8CE6),
- GL_COLOR_ATTACHMENT7(0x8CE7),
- GL_COLOR_ATTACHMENT8(0x8CE8),
- GL_COLOR_ATTACHMENT9(0x8CE9),
- GL_COLOR_ATTACHMENT10(0x8CEA),
- GL_COLOR_ATTACHMENT11(0x8CEB),
- GL_COLOR_ATTACHMENT12(0x8CEC),
- GL_COLOR_ATTACHMENT13(0x8CED),
- GL_COLOR_ATTACHMENT14(0x8CEE),
- GL_COLOR_ATTACHMENT15(0x8CEF),
- GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE(0x8D56),
- GL_MAX_SAMPLES(0x8D57),
- GL_MAP_READ_BIT(0x0001),
- GL_MAP_WRITE_BIT(0x0002),
- GL_MAP_INVALIDATE_RANGE_BIT(0x0004),
- GL_MAP_INVALIDATE_BUFFER_BIT(0x0008),
- GL_MAP_FLUSH_EXPLICIT_BIT(0x0010),
- GL_MAP_UNSYNCHRONIZED_BIT(0x0020),
- GL_RG(0x8227),
- GL_RG_INTEGER(0x8228),
- GL_R8(0x8229),
- GL_RG8(0x822B),
- GL_R16F(0x822D),
- GL_R32F(0x822E),
- GL_RG16F(0x822F),
- GL_RG32F(0x8230),
- GL_R8I(0x8231),
- GL_R8UI(0x8232),
- GL_R16I(0x8233),
- GL_R16UI(0x8234),
- GL_R32I(0x8235),
- GL_R32UI(0x8236),
- GL_RG8I(0x8237),
- GL_RG8UI(0x8238),
- GL_RG16I(0x8239),
- GL_RG16UI(0x823A),
- GL_RG32I(0x823B),
- GL_RG32UI(0x823C),
- GL_R8_SNORM(0x8F94),
- GL_RG8_SNORM(0x8F95),
- GL_RGB8_SNORM(0x8F96),
- GL_RGBA8_SNORM(0x8F97),
- GL_SIGNED_NORMALIZED(0x8F9C),
- GL_PRIMITIVE_RESTART_FIXED_INDEX(0x8D69),
- GL_COPY_READ_BUFFER(0x8F36),
- GL_COPY_WRITE_BUFFER(0x8F37),
- GL_UNIFORM_BUFFER(0x8A11),
- GL_UNIFORM_BUFFER_BINDING(0x8A28),
- GL_UNIFORM_BUFFER_START(0x8A29),
- GL_UNIFORM_BUFFER_SIZE(0x8A2A),
- GL_MAX_VERTEX_UNIFORM_BLOCKS(0x8A2B),
- GL_MAX_FRAGMENT_UNIFORM_BLOCKS(0x8A2D),
- GL_MAX_COMBINED_UNIFORM_BLOCKS(0x8A2E),
- GL_MAX_UNIFORM_BUFFER_BINDINGS(0x8A2F),
- GL_MAX_UNIFORM_BLOCK_SIZE(0x8A30),
- GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS(0x8A31),
- GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS(0x8A33),
- GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT(0x8A34),
- GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH(0x8A35),
- GL_ACTIVE_UNIFORM_BLOCKS(0x8A36),
- GL_UNIFORM_TYPE(0x8A37),
- GL_UNIFORM_SIZE(0x8A38),
- GL_UNIFORM_NAME_LENGTH(0x8A39),
- GL_UNIFORM_BLOCK_INDEX(0x8A3A),
- GL_UNIFORM_OFFSET(0x8A3B),
- GL_UNIFORM_ARRAY_STRIDE(0x8A3C),
- GL_UNIFORM_MATRIX_STRIDE(0x8A3D),
- GL_UNIFORM_IS_ROW_MAJOR(0x8A3E),
- GL_UNIFORM_BLOCK_BINDING(0x8A3F),
- GL_UNIFORM_BLOCK_DATA_SIZE(0x8A40),
- GL_UNIFORM_BLOCK_NAME_LENGTH(0x8A41),
- GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS(0x8A42),
- GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES(0x8A43),
- GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER(0x8A44),
- GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER(0x8A46),
- GL_MAX_VERTEX_OUTPUT_COMPONENTS(0x9122),
- GL_MAX_FRAGMENT_INPUT_COMPONENTS(0x9125),
- GL_MAX_SERVER_WAIT_TIMEOUT(0x9111),
- GL_OBJECT_TYPE(0x9112),
- GL_SYNC_CONDITION(0x9113),
- GL_SYNC_STATUS(0x9114),
- GL_SYNC_FLAGS(0x9115),
- GL_SYNC_FENCE(0x9116),
- GL_SYNC_GPU_COMMANDS_COMPLETE(0x9117),
- GL_UNSIGNALED(0x9118),
- GL_SIGNALED(0x9119),
- GL_ALREADY_SIGNALED(0x911A),
- GL_TIMEOUT_EXPIRED(0x911B),
- GL_CONDITION_SATISFIED(0x911C),
- GL_WAIT_FAILED(0x911D),
- GL_SYNC_FLUSH_COMMANDS_BIT(0x00000001),
- GL_TIMEOUT_IGNORED(0xFFFFFFFFFFFFFFFFl),
- GL_VERTEX_ATTRIB_ARRAY_DIVISOR(0x88FE),
- GL_ANY_SAMPLES_PASSED(0x8C2F),
- GL_ANY_SAMPLES_PASSED_CONSERVATIVE(0x8D6A),
- GL_SAMPLER_BINDING(0x8919),
- GL_RGB10_A2UI(0x906F),
- GL_TEXTURE_SWIZZLE_R(0x8E42),
- GL_TEXTURE_SWIZZLE_G(0x8E43),
- GL_TEXTURE_SWIZZLE_B(0x8E44),
- GL_TEXTURE_SWIZZLE_A(0x8E45),
- GL_GREEN(0x1904),
- GL_BLUE(0x1905),
- GL_INT_2_10_10_10_REV(0x8D9F),
- GL_TRANSFORM_FEEDBACK(0x8E22),
- GL_TRANSFORM_FEEDBACK_PAUSED(0x8E23),
- GL_TRANSFORM_FEEDBACK_ACTIVE(0x8E24),
- GL_TRANSFORM_FEEDBACK_BINDING(0x8E25),
- GL_PROGRAM_BINARY_RETRIEVABLE_HINT(0x8257),
- GL_COMPRESSED_R11_EAC(0x9270),
- GL_COMPRESSED_SIGNED_R11_EAC(0x9271),
- GL_COMPRESSED_RG11_EAC(0x9272),
- GL_COMPRESSED_SIGNED_RG11_EAC(0x9273),
- GL_COMPRESSED_RGB8_ETC2(0x9274),
- GL_COMPRESSED_SRGB8_ETC2(0x9275),
- GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2(0x9276),
- GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2(0x9277),
- GL_COMPRESSED_RGBA8_ETC2_EAC(0x9278),
- GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC(0x9279),
- GL_TEXTURE_IMMUTABLE_FORMAT(0x912F),
- GL_MAX_ELEMENT_INDEX(0x8D6B),
- GL_NUM_SAMPLE_COUNTS(0x9380),
- GL_TEXTURE_IMMUTABLE_LEVELS(0x82DF),
-
- GL_ALL_SHADER_BITS_EXT(0xFFFFFFFF),
- ;
-
- public final long value;
- GLEnum(final long value) {
- this.value = value;
- }
-
- private static final java.util.HashMap<Long, GLEnum> reverseMap = new java.util.HashMap<Long, GLEnum>();
- static {
- for (GLEnum e : GLEnum.values())
- reverseMap.put(e.value, e);
- }
-
- public static GLEnum valueOf(final long value) {
- return reverseMap.get(value);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GLProtoBuf.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GLProtoBuf.java
deleted file mode 100644
index 3c0fbd49e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GLProtoBuf.java
+++ /dev/null
@@ -1,3119 +0,0 @@
-// Generated by the protocol buffer compiler. DO NOT EDIT!
-// source: gltrace.proto
-
-package com.android.ide.eclipse.gltrace;
-
-public final class GLProtoBuf {
- private GLProtoBuf() {}
- public static void registerAllExtensions(
- com.google.protobuf.ExtensionRegistryLite registry) {
- }
- public static final class GLMessage extends
- com.google.protobuf.GeneratedMessageLite {
- // Use GLMessage.newBuilder() to construct.
- private GLMessage() {
- initFields();
- }
- private GLMessage(boolean noInit) {}
-
- private static final GLMessage defaultInstance;
- public static GLMessage getDefaultInstance() {
- return defaultInstance;
- }
-
- @Override
- public GLMessage getDefaultInstanceForType() {
- return defaultInstance;
- }
-
- public enum Function
- implements com.google.protobuf.Internal.EnumLite {
- glActiveTexture(0, 0),
- glAlphaFunc(1, 1),
- glAlphaFuncx(2, 2),
- glAlphaFuncxOES(3, 3),
- glAttachShader(4, 4),
- glBeginPerfMonitorAMD(5, 5),
- glBindAttribLocation(6, 6),
- glBindBuffer(7, 7),
- glBindFramebuffer(8, 8),
- glBindFramebufferOES(9, 9),
- glBindRenderbuffer(10, 10),
- glBindRenderbufferOES(11, 11),
- glBindTexture(12, 12),
- glBindVertexArrayOES(13, 13),
- glBlendColor(14, 14),
- glBlendEquation(15, 15),
- glBlendEquationOES(16, 16),
- glBlendEquationSeparate(17, 17),
- glBlendEquationSeparateOES(18, 18),
- glBlendFunc(19, 19),
- glBlendFuncSeparate(20, 20),
- glBlendFuncSeparateOES(21, 21),
- glBufferData(22, 22),
- glBufferSubData(23, 23),
- glCheckFramebufferStatus(24, 24),
- glCheckFramebufferStatusOES(25, 25),
- glClearColor(26, 26),
- glClearColorx(27, 27),
- glClearColorxOES(28, 28),
- glClearDepthf(29, 29),
- glClearDepthfOES(30, 30),
- glClearDepthx(31, 31),
- glClearDepthxOES(32, 32),
- glClear(33, 33),
- glClearStencil(34, 34),
- glClientActiveTexture(35, 35),
- glClipPlanef(36, 36),
- glClipPlanefIMG(37, 37),
- glClipPlanefOES(38, 38),
- glClipPlanex(39, 39),
- glClipPlanexIMG(40, 40),
- glClipPlanexOES(41, 41),
- glColor4f(42, 42),
- glColor4ub(43, 43),
- glColor4x(44, 44),
- glColor4xOES(45, 45),
- glColorMask(46, 46),
- glColorPointer(47, 47),
- glCompileShader(48, 48),
- glCompressedTexImage2D(49, 49),
- glCompressedTexImage3DOES(50, 50),
- glCompressedTexSubImage2D(51, 51),
- glCompressedTexSubImage3DOES(52, 52),
- glCopyTexImage2D(53, 53),
- glCopyTexSubImage2D(54, 54),
- glCopyTexSubImage3DOES(55, 55),
- glCoverageMaskNV(56, 56),
- glCoverageOperationNV(57, 57),
- glCreateProgram(58, 58),
- glCreateShader(59, 59),
- glCullFace(60, 60),
- glCurrentPaletteMatrixOES(61, 61),
- glDeleteBuffers(62, 62),
- glDeleteFencesNV(63, 63),
- glDeleteFramebuffers(64, 64),
- glDeleteFramebuffersOES(65, 65),
- glDeletePerfMonitorsAMD(66, 66),
- glDeleteProgram(67, 67),
- glDeleteRenderbuffers(68, 68),
- glDeleteRenderbuffersOES(69, 69),
- glDeleteShader(70, 70),
- glDeleteTextures(71, 71),
- glDeleteVertexArraysOES(72, 72),
- glDepthFunc(73, 73),
- glDepthMask(74, 74),
- glDepthRangef(75, 75),
- glDepthRangefOES(76, 76),
- glDepthRangex(77, 77),
- glDepthRangexOES(78, 78),
- glDetachShader(79, 79),
- glDisableClientState(80, 80),
- glDisableDriverControlQCOM(81, 81),
- glDisable(82, 82),
- glDisableVertexAttribArray(83, 83),
- glDiscardFramebufferEXT(84, 84),
- glDrawArrays(85, 85),
- glDrawElements(86, 86),
- glDrawTexfOES(87, 87),
- glDrawTexfvOES(88, 88),
- glDrawTexiOES(89, 89),
- glDrawTexivOES(90, 90),
- glDrawTexsOES(91, 91),
- glDrawTexsvOES(92, 92),
- glDrawTexxOES(93, 93),
- glDrawTexxvOES(94, 94),
- glEGLImageTargetRenderbufferStorageOES(95, 95),
- glEGLImageTargetTexture2DOES(96, 96),
- glEnableClientState(97, 97),
- glEnableDriverControlQCOM(98, 98),
- glEnable(99, 99),
- glEnableVertexAttribArray(100, 100),
- glEndPerfMonitorAMD(101, 101),
- glEndTilingQCOM(102, 102),
- glExtGetBufferPointervQCOM(103, 103),
- glExtGetBuffersQCOM(104, 104),
- glExtGetFramebuffersQCOM(105, 105),
- glExtGetProgramBinarySourceQCOM(106, 106),
- glExtGetProgramsQCOM(107, 107),
- glExtGetRenderbuffersQCOM(108, 108),
- glExtGetShadersQCOM(109, 109),
- glExtGetTexLevelParameterivQCOM(110, 110),
- glExtGetTexSubImageQCOM(111, 111),
- glExtGetTexturesQCOM(112, 112),
- glExtIsProgramBinaryQCOM(113, 113),
- glExtTexObjectStateOverrideiQCOM(114, 114),
- glFinishFenceNV(115, 115),
- glFinish(116, 116),
- glFlush(117, 117),
- glFogf(118, 118),
- glFogfv(119, 119),
- glFogx(120, 120),
- glFogxOES(121, 121),
- glFogxv(122, 122),
- glFogxvOES(123, 123),
- glFramebufferRenderbuffer(124, 124),
- glFramebufferRenderbufferOES(125, 125),
- glFramebufferTexture2D(126, 126),
- glFramebufferTexture2DMultisampleIMG(127, 127),
- glFramebufferTexture2DOES(128, 128),
- glFramebufferTexture3DOES(129, 129),
- glFrontFace(130, 130),
- glFrustumf(131, 131),
- glFrustumfOES(132, 132),
- glFrustumx(133, 133),
- glFrustumxOES(134, 134),
- glGenBuffers(135, 135),
- glGenerateMipmap(136, 136),
- glGenerateMipmapOES(137, 137),
- glGenFencesNV(138, 138),
- glGenFramebuffers(139, 139),
- glGenFramebuffersOES(140, 140),
- glGenPerfMonitorsAMD(141, 141),
- glGenRenderbuffers(142, 142),
- glGenRenderbuffersOES(143, 143),
- glGenTextures(144, 144),
- glGenVertexArraysOES(145, 145),
- glGetActiveAttrib(146, 146),
- glGetActiveUniform(147, 147),
- glGetAttachedShaders(148, 148),
- glGetAttribLocation(149, 149),
- glGetBooleanv(150, 150),
- glGetBufferParameteriv(151, 151),
- glGetBufferPointervOES(152, 152),
- glGetClipPlanef(153, 153),
- glGetClipPlanefOES(154, 154),
- glGetClipPlanex(155, 155),
- glGetClipPlanexOES(156, 156),
- glGetDriverControlsQCOM(157, 157),
- glGetDriverControlStringQCOM(158, 158),
- glGetError(159, 159),
- glGetFenceivNV(160, 160),
- glGetFixedv(161, 161),
- glGetFixedvOES(162, 162),
- glGetFloatv(163, 163),
- glGetFramebufferAttachmentParameteriv(164, 164),
- glGetFramebufferAttachmentParameterivOES(165, 165),
- glGetIntegerv(166, 166),
- glGetLightfv(167, 167),
- glGetLightxv(168, 168),
- glGetLightxvOES(169, 169),
- glGetMaterialfv(170, 170),
- glGetMaterialxv(171, 171),
- glGetMaterialxvOES(172, 172),
- glGetPerfMonitorCounterDataAMD(173, 173),
- glGetPerfMonitorCounterInfoAMD(174, 174),
- glGetPerfMonitorCountersAMD(175, 175),
- glGetPerfMonitorCounterStringAMD(176, 176),
- glGetPerfMonitorGroupsAMD(177, 177),
- glGetPerfMonitorGroupStringAMD(178, 178),
- glGetPointerv(179, 179),
- glGetProgramBinaryOES(180, 180),
- glGetProgramInfoLog(181, 181),
- glGetProgramiv(182, 182),
- glGetRenderbufferParameteriv(183, 183),
- glGetRenderbufferParameterivOES(184, 184),
- glGetShaderInfoLog(185, 185),
- glGetShaderiv(186, 186),
- glGetShaderPrecisionFormat(187, 187),
- glGetShaderSource(188, 188),
- glGetString(189, 189),
- glGetTexEnvfv(190, 190),
- glGetTexEnviv(191, 191),
- glGetTexEnvxv(192, 192),
- glGetTexEnvxvOES(193, 193),
- glGetTexGenfvOES(194, 194),
- glGetTexGenivOES(195, 195),
- glGetTexGenxvOES(196, 196),
- glGetTexParameterfv(197, 197),
- glGetTexParameteriv(198, 198),
- glGetTexParameterxv(199, 199),
- glGetTexParameterxvOES(200, 200),
- glGetUniformfv(201, 201),
- glGetUniformiv(202, 202),
- glGetUniformLocation(203, 203),
- glGetVertexAttribfv(204, 204),
- glGetVertexAttribiv(205, 205),
- glGetVertexAttribPointerv(206, 206),
- glHint(207, 207),
- glIsBuffer(208, 208),
- glIsEnabled(209, 209),
- glIsFenceNV(210, 210),
- glIsFramebuffer(211, 211),
- glIsFramebufferOES(212, 212),
- glIsProgram(213, 213),
- glIsRenderbuffer(214, 214),
- glIsRenderbufferOES(215, 215),
- glIsShader(216, 216),
- glIsTexture(217, 217),
- glIsVertexArrayOES(218, 218),
- glLightf(219, 219),
- glLightfv(220, 220),
- glLightModelf(221, 221),
- glLightModelfv(222, 222),
- glLightModelx(223, 223),
- glLightModelxOES(224, 224),
- glLightModelxv(225, 225),
- glLightModelxvOES(226, 226),
- glLightx(227, 227),
- glLightxOES(228, 228),
- glLightxv(229, 229),
- glLightxvOES(230, 230),
- glLineWidth(231, 231),
- glLineWidthx(232, 232),
- glLineWidthxOES(233, 233),
- glLinkProgram(234, 234),
- glLoadIdentity(235, 235),
- glLoadMatrixf(236, 236),
- glLoadMatrixx(237, 237),
- glLoadMatrixxOES(238, 238),
- glLoadPaletteFromModelViewMatrixOES(239, 239),
- glLogicOp(240, 240),
- glMapBufferOES(241, 241),
- glMaterialf(242, 242),
- glMaterialfv(243, 243),
- glMaterialx(244, 244),
- glMaterialxOES(245, 245),
- glMaterialxv(246, 246),
- glMaterialxvOES(247, 247),
- glMatrixIndexPointerOES(248, 248),
- glMatrixMode(249, 249),
- glMultiDrawArraysEXT(250, 250),
- glMultiDrawElementsEXT(251, 251),
- glMultiTexCoord4f(252, 252),
- glMultiTexCoord4x(253, 253),
- glMultiTexCoord4xOES(254, 254),
- glMultMatrixf(255, 255),
- glMultMatrixx(256, 256),
- glMultMatrixxOES(257, 257),
- glNormal3f(258, 258),
- glNormal3x(259, 259),
- glNormal3xOES(260, 260),
- glNormalPointer(261, 261),
- glOrthof(262, 262),
- glOrthofOES(263, 263),
- glOrthox(264, 264),
- glOrthoxOES(265, 265),
- glPixelStorei(266, 266),
- glPointParameterf(267, 267),
- glPointParameterfv(268, 268),
- glPointParameterx(269, 269),
- glPointParameterxOES(270, 270),
- glPointParameterxv(271, 271),
- glPointParameterxvOES(272, 272),
- glPointSize(273, 273),
- glPointSizePointerOES(274, 274),
- glPointSizex(275, 275),
- glPointSizexOES(276, 276),
- glPolygonOffset(277, 277),
- glPolygonOffsetx(278, 278),
- glPolygonOffsetxOES(279, 279),
- glPopMatrix(280, 280),
- glProgramBinaryOES(281, 281),
- glPushMatrix(282, 282),
- glQueryMatrixxOES(283, 283),
- glReadPixels(284, 284),
- glReleaseShaderCompiler(285, 285),
- glRenderbufferStorage(286, 286),
- glRenderbufferStorageMultisampleIMG(287, 287),
- glRenderbufferStorageOES(288, 288),
- glRotatef(289, 289),
- glRotatex(290, 290),
- glRotatexOES(291, 291),
- glSampleCoverage(292, 292),
- glSampleCoveragex(293, 293),
- glSampleCoveragexOES(294, 294),
- glScalef(295, 295),
- glScalex(296, 296),
- glScalexOES(297, 297),
- glScissor(298, 298),
- glSelectPerfMonitorCountersAMD(299, 299),
- glSetFenceNV(300, 300),
- glShadeModel(301, 301),
- glShaderBinary(302, 302),
- glShaderSource(303, 303),
- glStartTilingQCOM(304, 304),
- glStencilFunc(305, 305),
- glStencilFuncSeparate(306, 306),
- glStencilMask(307, 307),
- glStencilMaskSeparate(308, 308),
- glStencilOp(309, 309),
- glStencilOpSeparate(310, 310),
- glTestFenceNV(311, 311),
- glTexCoordPointer(312, 312),
- glTexEnvf(313, 313),
- glTexEnvfv(314, 314),
- glTexEnvi(315, 315),
- glTexEnviv(316, 316),
- glTexEnvx(317, 317),
- glTexEnvxOES(318, 318),
- glTexEnvxv(319, 319),
- glTexEnvxvOES(320, 320),
- glTexGenfOES(321, 321),
- glTexGenfvOES(322, 322),
- glTexGeniOES(323, 323),
- glTexGenivOES(324, 324),
- glTexGenxOES(325, 325),
- glTexGenxvOES(326, 326),
- glTexImage2D(327, 327),
- glTexImage3DOES(328, 328),
- glTexParameterf(329, 329),
- glTexParameterfv(330, 330),
- glTexParameteri(331, 331),
- glTexParameteriv(332, 332),
- glTexParameterx(333, 333),
- glTexParameterxOES(334, 334),
- glTexParameterxv(335, 335),
- glTexParameterxvOES(336, 336),
- glTexSubImage2D(337, 337),
- glTexSubImage3DOES(338, 338),
- glTranslatef(339, 339),
- glTranslatex(340, 340),
- glTranslatexOES(341, 341),
- glUniform1f(342, 342),
- glUniform1fv(343, 343),
- glUniform1i(344, 344),
- glUniform1iv(345, 345),
- glUniform2f(346, 346),
- glUniform2fv(347, 347),
- glUniform2i(348, 348),
- glUniform2iv(349, 349),
- glUniform3f(350, 350),
- glUniform3fv(351, 351),
- glUniform3i(352, 352),
- glUniform3iv(353, 353),
- glUniform4f(354, 354),
- glUniform4fv(355, 355),
- glUniform4i(356, 356),
- glUniform4iv(357, 357),
- glUniformMatrix2fv(358, 358),
- glUniformMatrix3fv(359, 359),
- glUniformMatrix4fv(360, 360),
- glUnmapBufferOES(361, 361),
- glUseProgram(362, 362),
- glValidateProgram(363, 363),
- glVertexAttrib1f(364, 364),
- glVertexAttrib1fv(365, 365),
- glVertexAttrib2f(366, 366),
- glVertexAttrib2fv(367, 367),
- glVertexAttrib3f(368, 368),
- glVertexAttrib3fv(369, 369),
- glVertexAttrib4f(370, 370),
- glVertexAttrib4fv(371, 371),
- glVertexAttribPointer(372, 372),
- glVertexPointer(373, 373),
- glViewport(374, 374),
- glWeightPointerOES(375, 375),
- glReadBuffer(376, 376),
- glDrawRangeElements(377, 377),
- glTexImage3D(378, 378),
- glTexSubImage3D(379, 379),
- glCopyTexSubImage3D(380, 380),
- glCompressedTexImage3D(381, 381),
- glCompressedTexSubImage3D(382, 382),
- glGenQueries(383, 383),
- glDeleteQueries(384, 384),
- glIsQuery(385, 385),
- glBeginQuery(386, 386),
- glEndQuery(387, 387),
- glGetQueryiv(388, 388),
- glGetQueryObjectuiv(389, 389),
- glUnmapBuffer(390, 390),
- glGetBufferPointerv(391, 391),
- glDrawBuffers(392, 392),
- glUniformMatrix2x3fv(393, 393),
- glUniformMatrix3x2fv(394, 394),
- glUniformMatrix2x4fv(395, 395),
- glUniformMatrix4x2fv(396, 396),
- glUniformMatrix3x4fv(397, 397),
- glUniformMatrix4x3fv(398, 398),
- glBlitFramebuffer(399, 399),
- glRenderbufferStorageMultisample(400, 400),
- glFramebufferTextureLayer(401, 401),
- glMapBufferRange(402, 402),
- glFlushMappedBufferRange(403, 403),
- glBindVertexArray(404, 404),
- glDeleteVertexArrays(405, 405),
- glGenVertexArrays(406, 406),
- glIsVertexArray(407, 407),
- glGetIntegeri_v(408, 408),
- glBeginTransformFeedback(409, 409),
- glEndTransformFeedback(410, 410),
- glBindBufferRange(411, 411),
- glBindBufferBase(412, 412),
- glTransformFeedbackVaryings(413, 413),
- glGetTransformFeedbackVarying(414, 414),
- glVertexAttribIPointer(415, 415),
- glGetVertexAttribIiv(416, 416),
- glGetVertexAttribIuiv(417, 417),
- glVertexAttribI4i(418, 418),
- glVertexAttribI4ui(419, 419),
- glVertexAttribI4iv(420, 420),
- glVertexAttribI4uiv(421, 421),
- glGetUniformuiv(422, 422),
- glGetFragDataLocation(423, 423),
- glUniform1ui(424, 424),
- glUniform2ui(425, 425),
- glUniform3ui(426, 426),
- glUniform4ui(427, 427),
- glUniform1uiv(428, 428),
- glUniform2uiv(429, 429),
- glUniform3uiv(430, 430),
- glUniform4uiv(431, 431),
- glClearBufferiv(432, 432),
- glClearBufferuiv(433, 433),
- glClearBufferfv(434, 434),
- glClearBufferfi(435, 435),
- glGetStringi(436, 436),
- glCopyBufferSubData(437, 437),
- glGetUniformIndices(438, 438),
- glGetActiveUniformsiv(439, 439),
- glGetUniformBlockIndex(440, 440),
- glGetActiveUniformBlockiv(441, 441),
- glGetActiveUniformBlockName(442, 442),
- glUniformBlockBinding(443, 443),
- glDrawArraysInstanced(444, 444),
- glDrawElementsInstanced(445, 445),
- glFenceSync(446, 446),
- glIsSync(447, 447),
- glDeleteSync(448, 448),
- glClientWaitSync(449, 449),
- glWaitSync(450, 450),
- glGetInteger64v(451, 451),
- glGetSynciv(452, 452),
- glGetInteger64i_v(453, 453),
- glGetBufferParameteri64v(454, 454),
- glGenSamplers(455, 455),
- glDeleteSamplers(456, 456),
- glIsSampler(457, 457),
- glBindSampler(458, 458),
- glSamplerParameteri(459, 459),
- glSamplerParameteriv(460, 460),
- glSamplerParameterf(461, 461),
- glSamplerParameterfv(462, 462),
- glGetSamplerParameteriv(463, 463),
- glGetSamplerParameterfv(464, 464),
- glVertexAttribDivisor(465, 465),
- glBindTransformFeedback(466, 466),
- glDeleteTransformFeedbacks(467, 467),
- glGenTransformFeedbacks(468, 468),
- glIsTransformFeedback(469, 469),
- glPauseTransformFeedback(470, 470),
- glResumeTransformFeedback(471, 471),
- glGetProgramBinary(472, 472),
- glProgramBinary(473, 473),
- glProgramParameteri(474, 474),
- glInvalidateFramebuffer(475, 475),
- glInvalidateSubFramebuffer(476, 476),
- glTexStorage2D(477, 477),
- glTexStorage3D(478, 478),
- glGetInternalformativ(479, 479),
- glActiveShaderProgramEXT(480, 502),
- glAlphaFuncQCOM(481, 503),
- glBeginQueryEXT(482, 504),
- glBindProgramPipelineEXT(483, 505),
- glBlitFramebufferANGLE(484, 506),
- glCreateShaderProgramvEXT(485, 507),
- glDeleteProgramPipelinesEXT(486, 508),
- glDeleteQueriesEXT(487, 509),
- glDrawBuffersNV(488, 510),
- glEndQueryEXT(489, 511),
- glFramebufferTexture2DMultisampleEXT(490, 512),
- glGenProgramPipelinesEXT(491, 513),
- glGenQueriesEXT(492, 514),
- glGetGraphicsResetStatusEXT(493, 515),
- glGetObjectLabelEXT(494, 516),
- glGetProgramPipelineInfoLogEXT(495, 517),
- glGetProgramPipelineivEXT(496, 518),
- glGetQueryObjectuivEXT(497, 519),
- glGetQueryivEXT(498, 520),
- glGetnUniformfvEXT(499, 521),
- glInsertEventMarkerEXT(501, 522),
- glIsProgramPipelineEXT(502, 523),
- glIsQueryEXT(503, 524),
- glLabelObjectEXT(504, 525),
- glPopGroupMarkerEXT(505, 526),
- glProgramParameteriEXT(506, 527),
- glProgramUniform1fEXT(507, 528),
- glProgramUniform1fvEXT(508, 529),
- glProgramUniform1iEXT(509, 530),
- glProgramUniform1ivEXT(510, 531),
- glProgramUniform2fEXT(511, 532),
- glProgramUniform2fvEXT(512, 533),
- glProgramUniform2iEXT(513, 534),
- glProgramUniform2ivEXT(514, 535),
- glProgramUniform3fEXT(515, 536),
- glProgramUniform3fvEXT(516, 537),
- glProgramUniform3iEXT(517, 538),
- glProgramUniform3ivEXT(518, 539),
- glProgramUniform4fEXT(519, 540),
- glProgramUniform4fvEXT(520, 541),
- glProgramUniform4iEXT(521, 542),
- glProgramUniform4ivEXT(522, 543),
- glProgramUniformMatrix2fvEXT(523, 544),
- glProgramUniformMatrix3fvEXT(524, 545),
- glProgramUniformMatrix4fvEXT(525, 546),
- glPushGroupMarkerEXT(526, 547),
- glReadBufferNV(527, 548),
- glReadnPixelsEXT(528, 549),
- glRenderbufferStorageMultisampleANGLE(529, 550),
- glRenderbufferStorageMultisampleAPPLE(530, 551),
- glRenderbufferStorageMultisampleEXT(531, 552),
- glResolveMultisampleFramebufferAPPLE(532, 553),
- glTexStorage1DEXT(533, 554),
- glTexStorage2DEXT(534, 555),
- glTexStorage3DEXT(535, 556),
- glTextureStorage1DEXT(536, 557),
- glTextureStorage2DEXT(537, 558),
- glTextureStorage3DEXT(538, 559),
- glUseProgramStagesEXT(539, 560),
- glValidateProgramPipelineEXT(540, 561),
- eglGetDisplay(541, 2000),
- eglInitialize(542, 2001),
- eglTerminate(543, 2002),
- eglGetConfigs(544, 2003),
- eglChooseConfig(545, 2004),
- eglGetConfigAttrib(546, 2005),
- eglCreateWindowSurface(547, 2006),
- eglCreatePixmapSurface(548, 2007),
- eglCreatePbufferSurface(549, 2008),
- eglDestroySurface(550, 2009),
- eglQuerySurface(551, 2010),
- eglCreateContext(552, 2011),
- eglDestroyContext(553, 2012),
- eglMakeCurrent(554, 2013),
- eglGetCurrentContext(555, 2014),
- eglGetCurrentSurface(556, 2015),
- eglGetCurrentDisplay(557, 2016),
- eglQueryContext(558, 2017),
- eglWaitGL(559, 2018),
- eglWaitNative(560, 2019),
- eglSwapBuffers(561, 2020),
- eglCopyBuffers(562, 2021),
- eglGetError(563, 2022),
- eglQueryString(564, 2023),
- eglGetProcAddress(565, 2024),
- eglSurfaceAttrib(566, 2025),
- eglBindTexImage(567, 2026),
- eglReleaseTexImage(568, 2027),
- eglSwapInterval(569, 2028),
- eglBindAPI(570, 2029),
- eglQueryAPI(571, 2030),
- eglWaitClient(572, 2031),
- eglReleaseThread(573, 2032),
- eglCreatePbufferFromClientBuffer(574, 2033),
- eglLockSurfaceKHR(575, 2034),
- eglUnlockSurfaceKHR(576, 2035),
- eglCreateImageKHR(577, 2036),
- eglDestroyImageKHR(578, 2037),
- eglCreateSyncKHR(579, 2038),
- eglDestroySyncKHR(580, 2039),
- eglClientWaitSyncKHR(581, 2040),
- eglGetSyncAttribKHR(582, 2041),
- eglSetSwapRectangleANDROID(583, 2042),
- eglGetRenderBufferANDROID(584, 2043),
- eglGetSystemTimeFrequencyNV(585, 2044),
- eglGetSystemTimeNV(586, 2045),
- invalid(587, 3000),
- glVertexAttribPointerData(588, 3001),
- ;
-
- public static final Function glGetnUniformivEXT = glGetnUniformfvEXT;
-
- @Override
- public final int getNumber() { return value; }
-
- public static Function valueOf(int value) {
- switch (value) {
- case 0: return glActiveTexture;
- case 1: return glAlphaFunc;
- case 2: return glAlphaFuncx;
- case 3: return glAlphaFuncxOES;
- case 4: return glAttachShader;
- case 5: return glBeginPerfMonitorAMD;
- case 6: return glBindAttribLocation;
- case 7: return glBindBuffer;
- case 8: return glBindFramebuffer;
- case 9: return glBindFramebufferOES;
- case 10: return glBindRenderbuffer;
- case 11: return glBindRenderbufferOES;
- case 12: return glBindTexture;
- case 13: return glBindVertexArrayOES;
- case 14: return glBlendColor;
- case 15: return glBlendEquation;
- case 16: return glBlendEquationOES;
- case 17: return glBlendEquationSeparate;
- case 18: return glBlendEquationSeparateOES;
- case 19: return glBlendFunc;
- case 20: return glBlendFuncSeparate;
- case 21: return glBlendFuncSeparateOES;
- case 22: return glBufferData;
- case 23: return glBufferSubData;
- case 24: return glCheckFramebufferStatus;
- case 25: return glCheckFramebufferStatusOES;
- case 26: return glClearColor;
- case 27: return glClearColorx;
- case 28: return glClearColorxOES;
- case 29: return glClearDepthf;
- case 30: return glClearDepthfOES;
- case 31: return glClearDepthx;
- case 32: return glClearDepthxOES;
- case 33: return glClear;
- case 34: return glClearStencil;
- case 35: return glClientActiveTexture;
- case 36: return glClipPlanef;
- case 37: return glClipPlanefIMG;
- case 38: return glClipPlanefOES;
- case 39: return glClipPlanex;
- case 40: return glClipPlanexIMG;
- case 41: return glClipPlanexOES;
- case 42: return glColor4f;
- case 43: return glColor4ub;
- case 44: return glColor4x;
- case 45: return glColor4xOES;
- case 46: return glColorMask;
- case 47: return glColorPointer;
- case 48: return glCompileShader;
- case 49: return glCompressedTexImage2D;
- case 50: return glCompressedTexImage3DOES;
- case 51: return glCompressedTexSubImage2D;
- case 52: return glCompressedTexSubImage3DOES;
- case 53: return glCopyTexImage2D;
- case 54: return glCopyTexSubImage2D;
- case 55: return glCopyTexSubImage3DOES;
- case 56: return glCoverageMaskNV;
- case 57: return glCoverageOperationNV;
- case 58: return glCreateProgram;
- case 59: return glCreateShader;
- case 60: return glCullFace;
- case 61: return glCurrentPaletteMatrixOES;
- case 62: return glDeleteBuffers;
- case 63: return glDeleteFencesNV;
- case 64: return glDeleteFramebuffers;
- case 65: return glDeleteFramebuffersOES;
- case 66: return glDeletePerfMonitorsAMD;
- case 67: return glDeleteProgram;
- case 68: return glDeleteRenderbuffers;
- case 69: return glDeleteRenderbuffersOES;
- case 70: return glDeleteShader;
- case 71: return glDeleteTextures;
- case 72: return glDeleteVertexArraysOES;
- case 73: return glDepthFunc;
- case 74: return glDepthMask;
- case 75: return glDepthRangef;
- case 76: return glDepthRangefOES;
- case 77: return glDepthRangex;
- case 78: return glDepthRangexOES;
- case 79: return glDetachShader;
- case 80: return glDisableClientState;
- case 81: return glDisableDriverControlQCOM;
- case 82: return glDisable;
- case 83: return glDisableVertexAttribArray;
- case 84: return glDiscardFramebufferEXT;
- case 85: return glDrawArrays;
- case 86: return glDrawElements;
- case 87: return glDrawTexfOES;
- case 88: return glDrawTexfvOES;
- case 89: return glDrawTexiOES;
- case 90: return glDrawTexivOES;
- case 91: return glDrawTexsOES;
- case 92: return glDrawTexsvOES;
- case 93: return glDrawTexxOES;
- case 94: return glDrawTexxvOES;
- case 95: return glEGLImageTargetRenderbufferStorageOES;
- case 96: return glEGLImageTargetTexture2DOES;
- case 97: return glEnableClientState;
- case 98: return glEnableDriverControlQCOM;
- case 99: return glEnable;
- case 100: return glEnableVertexAttribArray;
- case 101: return glEndPerfMonitorAMD;
- case 102: return glEndTilingQCOM;
- case 103: return glExtGetBufferPointervQCOM;
- case 104: return glExtGetBuffersQCOM;
- case 105: return glExtGetFramebuffersQCOM;
- case 106: return glExtGetProgramBinarySourceQCOM;
- case 107: return glExtGetProgramsQCOM;
- case 108: return glExtGetRenderbuffersQCOM;
- case 109: return glExtGetShadersQCOM;
- case 110: return glExtGetTexLevelParameterivQCOM;
- case 111: return glExtGetTexSubImageQCOM;
- case 112: return glExtGetTexturesQCOM;
- case 113: return glExtIsProgramBinaryQCOM;
- case 114: return glExtTexObjectStateOverrideiQCOM;
- case 115: return glFinishFenceNV;
- case 116: return glFinish;
- case 117: return glFlush;
- case 118: return glFogf;
- case 119: return glFogfv;
- case 120: return glFogx;
- case 121: return glFogxOES;
- case 122: return glFogxv;
- case 123: return glFogxvOES;
- case 124: return glFramebufferRenderbuffer;
- case 125: return glFramebufferRenderbufferOES;
- case 126: return glFramebufferTexture2D;
- case 127: return glFramebufferTexture2DMultisampleIMG;
- case 128: return glFramebufferTexture2DOES;
- case 129: return glFramebufferTexture3DOES;
- case 130: return glFrontFace;
- case 131: return glFrustumf;
- case 132: return glFrustumfOES;
- case 133: return glFrustumx;
- case 134: return glFrustumxOES;
- case 135: return glGenBuffers;
- case 136: return glGenerateMipmap;
- case 137: return glGenerateMipmapOES;
- case 138: return glGenFencesNV;
- case 139: return glGenFramebuffers;
- case 140: return glGenFramebuffersOES;
- case 141: return glGenPerfMonitorsAMD;
- case 142: return glGenRenderbuffers;
- case 143: return glGenRenderbuffersOES;
- case 144: return glGenTextures;
- case 145: return glGenVertexArraysOES;
- case 146: return glGetActiveAttrib;
- case 147: return glGetActiveUniform;
- case 148: return glGetAttachedShaders;
- case 149: return glGetAttribLocation;
- case 150: return glGetBooleanv;
- case 151: return glGetBufferParameteriv;
- case 152: return glGetBufferPointervOES;
- case 153: return glGetClipPlanef;
- case 154: return glGetClipPlanefOES;
- case 155: return glGetClipPlanex;
- case 156: return glGetClipPlanexOES;
- case 157: return glGetDriverControlsQCOM;
- case 158: return glGetDriverControlStringQCOM;
- case 159: return glGetError;
- case 160: return glGetFenceivNV;
- case 161: return glGetFixedv;
- case 162: return glGetFixedvOES;
- case 163: return glGetFloatv;
- case 164: return glGetFramebufferAttachmentParameteriv;
- case 165: return glGetFramebufferAttachmentParameterivOES;
- case 166: return glGetIntegerv;
- case 167: return glGetLightfv;
- case 168: return glGetLightxv;
- case 169: return glGetLightxvOES;
- case 170: return glGetMaterialfv;
- case 171: return glGetMaterialxv;
- case 172: return glGetMaterialxvOES;
- case 173: return glGetPerfMonitorCounterDataAMD;
- case 174: return glGetPerfMonitorCounterInfoAMD;
- case 175: return glGetPerfMonitorCountersAMD;
- case 176: return glGetPerfMonitorCounterStringAMD;
- case 177: return glGetPerfMonitorGroupsAMD;
- case 178: return glGetPerfMonitorGroupStringAMD;
- case 179: return glGetPointerv;
- case 180: return glGetProgramBinaryOES;
- case 181: return glGetProgramInfoLog;
- case 182: return glGetProgramiv;
- case 183: return glGetRenderbufferParameteriv;
- case 184: return glGetRenderbufferParameterivOES;
- case 185: return glGetShaderInfoLog;
- case 186: return glGetShaderiv;
- case 187: return glGetShaderPrecisionFormat;
- case 188: return glGetShaderSource;
- case 189: return glGetString;
- case 190: return glGetTexEnvfv;
- case 191: return glGetTexEnviv;
- case 192: return glGetTexEnvxv;
- case 193: return glGetTexEnvxvOES;
- case 194: return glGetTexGenfvOES;
- case 195: return glGetTexGenivOES;
- case 196: return glGetTexGenxvOES;
- case 197: return glGetTexParameterfv;
- case 198: return glGetTexParameteriv;
- case 199: return glGetTexParameterxv;
- case 200: return glGetTexParameterxvOES;
- case 201: return glGetUniformfv;
- case 202: return glGetUniformiv;
- case 203: return glGetUniformLocation;
- case 204: return glGetVertexAttribfv;
- case 205: return glGetVertexAttribiv;
- case 206: return glGetVertexAttribPointerv;
- case 207: return glHint;
- case 208: return glIsBuffer;
- case 209: return glIsEnabled;
- case 210: return glIsFenceNV;
- case 211: return glIsFramebuffer;
- case 212: return glIsFramebufferOES;
- case 213: return glIsProgram;
- case 214: return glIsRenderbuffer;
- case 215: return glIsRenderbufferOES;
- case 216: return glIsShader;
- case 217: return glIsTexture;
- case 218: return glIsVertexArrayOES;
- case 219: return glLightf;
- case 220: return glLightfv;
- case 221: return glLightModelf;
- case 222: return glLightModelfv;
- case 223: return glLightModelx;
- case 224: return glLightModelxOES;
- case 225: return glLightModelxv;
- case 226: return glLightModelxvOES;
- case 227: return glLightx;
- case 228: return glLightxOES;
- case 229: return glLightxv;
- case 230: return glLightxvOES;
- case 231: return glLineWidth;
- case 232: return glLineWidthx;
- case 233: return glLineWidthxOES;
- case 234: return glLinkProgram;
- case 235: return glLoadIdentity;
- case 236: return glLoadMatrixf;
- case 237: return glLoadMatrixx;
- case 238: return glLoadMatrixxOES;
- case 239: return glLoadPaletteFromModelViewMatrixOES;
- case 240: return glLogicOp;
- case 241: return glMapBufferOES;
- case 242: return glMaterialf;
- case 243: return glMaterialfv;
- case 244: return glMaterialx;
- case 245: return glMaterialxOES;
- case 246: return glMaterialxv;
- case 247: return glMaterialxvOES;
- case 248: return glMatrixIndexPointerOES;
- case 249: return glMatrixMode;
- case 250: return glMultiDrawArraysEXT;
- case 251: return glMultiDrawElementsEXT;
- case 252: return glMultiTexCoord4f;
- case 253: return glMultiTexCoord4x;
- case 254: return glMultiTexCoord4xOES;
- case 255: return glMultMatrixf;
- case 256: return glMultMatrixx;
- case 257: return glMultMatrixxOES;
- case 258: return glNormal3f;
- case 259: return glNormal3x;
- case 260: return glNormal3xOES;
- case 261: return glNormalPointer;
- case 262: return glOrthof;
- case 263: return glOrthofOES;
- case 264: return glOrthox;
- case 265: return glOrthoxOES;
- case 266: return glPixelStorei;
- case 267: return glPointParameterf;
- case 268: return glPointParameterfv;
- case 269: return glPointParameterx;
- case 270: return glPointParameterxOES;
- case 271: return glPointParameterxv;
- case 272: return glPointParameterxvOES;
- case 273: return glPointSize;
- case 274: return glPointSizePointerOES;
- case 275: return glPointSizex;
- case 276: return glPointSizexOES;
- case 277: return glPolygonOffset;
- case 278: return glPolygonOffsetx;
- case 279: return glPolygonOffsetxOES;
- case 280: return glPopMatrix;
- case 281: return glProgramBinaryOES;
- case 282: return glPushMatrix;
- case 283: return glQueryMatrixxOES;
- case 284: return glReadPixels;
- case 285: return glReleaseShaderCompiler;
- case 286: return glRenderbufferStorage;
- case 287: return glRenderbufferStorageMultisampleIMG;
- case 288: return glRenderbufferStorageOES;
- case 289: return glRotatef;
- case 290: return glRotatex;
- case 291: return glRotatexOES;
- case 292: return glSampleCoverage;
- case 293: return glSampleCoveragex;
- case 294: return glSampleCoveragexOES;
- case 295: return glScalef;
- case 296: return glScalex;
- case 297: return glScalexOES;
- case 298: return glScissor;
- case 299: return glSelectPerfMonitorCountersAMD;
- case 300: return glSetFenceNV;
- case 301: return glShadeModel;
- case 302: return glShaderBinary;
- case 303: return glShaderSource;
- case 304: return glStartTilingQCOM;
- case 305: return glStencilFunc;
- case 306: return glStencilFuncSeparate;
- case 307: return glStencilMask;
- case 308: return glStencilMaskSeparate;
- case 309: return glStencilOp;
- case 310: return glStencilOpSeparate;
- case 311: return glTestFenceNV;
- case 312: return glTexCoordPointer;
- case 313: return glTexEnvf;
- case 314: return glTexEnvfv;
- case 315: return glTexEnvi;
- case 316: return glTexEnviv;
- case 317: return glTexEnvx;
- case 318: return glTexEnvxOES;
- case 319: return glTexEnvxv;
- case 320: return glTexEnvxvOES;
- case 321: return glTexGenfOES;
- case 322: return glTexGenfvOES;
- case 323: return glTexGeniOES;
- case 324: return glTexGenivOES;
- case 325: return glTexGenxOES;
- case 326: return glTexGenxvOES;
- case 327: return glTexImage2D;
- case 328: return glTexImage3DOES;
- case 329: return glTexParameterf;
- case 330: return glTexParameterfv;
- case 331: return glTexParameteri;
- case 332: return glTexParameteriv;
- case 333: return glTexParameterx;
- case 334: return glTexParameterxOES;
- case 335: return glTexParameterxv;
- case 336: return glTexParameterxvOES;
- case 337: return glTexSubImage2D;
- case 338: return glTexSubImage3DOES;
- case 339: return glTranslatef;
- case 340: return glTranslatex;
- case 341: return glTranslatexOES;
- case 342: return glUniform1f;
- case 343: return glUniform1fv;
- case 344: return glUniform1i;
- case 345: return glUniform1iv;
- case 346: return glUniform2f;
- case 347: return glUniform2fv;
- case 348: return glUniform2i;
- case 349: return glUniform2iv;
- case 350: return glUniform3f;
- case 351: return glUniform3fv;
- case 352: return glUniform3i;
- case 353: return glUniform3iv;
- case 354: return glUniform4f;
- case 355: return glUniform4fv;
- case 356: return glUniform4i;
- case 357: return glUniform4iv;
- case 358: return glUniformMatrix2fv;
- case 359: return glUniformMatrix3fv;
- case 360: return glUniformMatrix4fv;
- case 361: return glUnmapBufferOES;
- case 362: return glUseProgram;
- case 363: return glValidateProgram;
- case 364: return glVertexAttrib1f;
- case 365: return glVertexAttrib1fv;
- case 366: return glVertexAttrib2f;
- case 367: return glVertexAttrib2fv;
- case 368: return glVertexAttrib3f;
- case 369: return glVertexAttrib3fv;
- case 370: return glVertexAttrib4f;
- case 371: return glVertexAttrib4fv;
- case 372: return glVertexAttribPointer;
- case 373: return glVertexPointer;
- case 374: return glViewport;
- case 375: return glWeightPointerOES;
- case 376: return glReadBuffer;
- case 377: return glDrawRangeElements;
- case 378: return glTexImage3D;
- case 379: return glTexSubImage3D;
- case 380: return glCopyTexSubImage3D;
- case 381: return glCompressedTexImage3D;
- case 382: return glCompressedTexSubImage3D;
- case 383: return glGenQueries;
- case 384: return glDeleteQueries;
- case 385: return glIsQuery;
- case 386: return glBeginQuery;
- case 387: return glEndQuery;
- case 388: return glGetQueryiv;
- case 389: return glGetQueryObjectuiv;
- case 390: return glUnmapBuffer;
- case 391: return glGetBufferPointerv;
- case 392: return glDrawBuffers;
- case 393: return glUniformMatrix2x3fv;
- case 394: return glUniformMatrix3x2fv;
- case 395: return glUniformMatrix2x4fv;
- case 396: return glUniformMatrix4x2fv;
- case 397: return glUniformMatrix3x4fv;
- case 398: return glUniformMatrix4x3fv;
- case 399: return glBlitFramebuffer;
- case 400: return glRenderbufferStorageMultisample;
- case 401: return glFramebufferTextureLayer;
- case 402: return glMapBufferRange;
- case 403: return glFlushMappedBufferRange;
- case 404: return glBindVertexArray;
- case 405: return glDeleteVertexArrays;
- case 406: return glGenVertexArrays;
- case 407: return glIsVertexArray;
- case 408: return glGetIntegeri_v;
- case 409: return glBeginTransformFeedback;
- case 410: return glEndTransformFeedback;
- case 411: return glBindBufferRange;
- case 412: return glBindBufferBase;
- case 413: return glTransformFeedbackVaryings;
- case 414: return glGetTransformFeedbackVarying;
- case 415: return glVertexAttribIPointer;
- case 416: return glGetVertexAttribIiv;
- case 417: return glGetVertexAttribIuiv;
- case 418: return glVertexAttribI4i;
- case 419: return glVertexAttribI4ui;
- case 420: return glVertexAttribI4iv;
- case 421: return glVertexAttribI4uiv;
- case 422: return glGetUniformuiv;
- case 423: return glGetFragDataLocation;
- case 424: return glUniform1ui;
- case 425: return glUniform2ui;
- case 426: return glUniform3ui;
- case 427: return glUniform4ui;
- case 428: return glUniform1uiv;
- case 429: return glUniform2uiv;
- case 430: return glUniform3uiv;
- case 431: return glUniform4uiv;
- case 432: return glClearBufferiv;
- case 433: return glClearBufferuiv;
- case 434: return glClearBufferfv;
- case 435: return glClearBufferfi;
- case 436: return glGetStringi;
- case 437: return glCopyBufferSubData;
- case 438: return glGetUniformIndices;
- case 439: return glGetActiveUniformsiv;
- case 440: return glGetUniformBlockIndex;
- case 441: return glGetActiveUniformBlockiv;
- case 442: return glGetActiveUniformBlockName;
- case 443: return glUniformBlockBinding;
- case 444: return glDrawArraysInstanced;
- case 445: return glDrawElementsInstanced;
- case 446: return glFenceSync;
- case 447: return glIsSync;
- case 448: return glDeleteSync;
- case 449: return glClientWaitSync;
- case 450: return glWaitSync;
- case 451: return glGetInteger64v;
- case 452: return glGetSynciv;
- case 453: return glGetInteger64i_v;
- case 454: return glGetBufferParameteri64v;
- case 455: return glGenSamplers;
- case 456: return glDeleteSamplers;
- case 457: return glIsSampler;
- case 458: return glBindSampler;
- case 459: return glSamplerParameteri;
- case 460: return glSamplerParameteriv;
- case 461: return glSamplerParameterf;
- case 462: return glSamplerParameterfv;
- case 463: return glGetSamplerParameteriv;
- case 464: return glGetSamplerParameterfv;
- case 465: return glVertexAttribDivisor;
- case 466: return glBindTransformFeedback;
- case 467: return glDeleteTransformFeedbacks;
- case 468: return glGenTransformFeedbacks;
- case 469: return glIsTransformFeedback;
- case 470: return glPauseTransformFeedback;
- case 471: return glResumeTransformFeedback;
- case 472: return glGetProgramBinary;
- case 473: return glProgramBinary;
- case 474: return glProgramParameteri;
- case 475: return glInvalidateFramebuffer;
- case 476: return glInvalidateSubFramebuffer;
- case 477: return glTexStorage2D;
- case 478: return glTexStorage3D;
- case 479: return glGetInternalformativ;
- case 502: return glActiveShaderProgramEXT;
- case 503: return glAlphaFuncQCOM;
- case 504: return glBeginQueryEXT;
- case 505: return glBindProgramPipelineEXT;
- case 506: return glBlitFramebufferANGLE;
- case 507: return glCreateShaderProgramvEXT;
- case 508: return glDeleteProgramPipelinesEXT;
- case 509: return glDeleteQueriesEXT;
- case 510: return glDrawBuffersNV;
- case 511: return glEndQueryEXT;
- case 512: return glFramebufferTexture2DMultisampleEXT;
- case 513: return glGenProgramPipelinesEXT;
- case 514: return glGenQueriesEXT;
- case 515: return glGetGraphicsResetStatusEXT;
- case 516: return glGetObjectLabelEXT;
- case 517: return glGetProgramPipelineInfoLogEXT;
- case 518: return glGetProgramPipelineivEXT;
- case 519: return glGetQueryObjectuivEXT;
- case 520: return glGetQueryivEXT;
- case 521: return glGetnUniformfvEXT;
- case 522: return glInsertEventMarkerEXT;
- case 523: return glIsProgramPipelineEXT;
- case 524: return glIsQueryEXT;
- case 525: return glLabelObjectEXT;
- case 526: return glPopGroupMarkerEXT;
- case 527: return glProgramParameteriEXT;
- case 528: return glProgramUniform1fEXT;
- case 529: return glProgramUniform1fvEXT;
- case 530: return glProgramUniform1iEXT;
- case 531: return glProgramUniform1ivEXT;
- case 532: return glProgramUniform2fEXT;
- case 533: return glProgramUniform2fvEXT;
- case 534: return glProgramUniform2iEXT;
- case 535: return glProgramUniform2ivEXT;
- case 536: return glProgramUniform3fEXT;
- case 537: return glProgramUniform3fvEXT;
- case 538: return glProgramUniform3iEXT;
- case 539: return glProgramUniform3ivEXT;
- case 540: return glProgramUniform4fEXT;
- case 541: return glProgramUniform4fvEXT;
- case 542: return glProgramUniform4iEXT;
- case 543: return glProgramUniform4ivEXT;
- case 544: return glProgramUniformMatrix2fvEXT;
- case 545: return glProgramUniformMatrix3fvEXT;
- case 546: return glProgramUniformMatrix4fvEXT;
- case 547: return glPushGroupMarkerEXT;
- case 548: return glReadBufferNV;
- case 549: return glReadnPixelsEXT;
- case 550: return glRenderbufferStorageMultisampleANGLE;
- case 551: return glRenderbufferStorageMultisampleAPPLE;
- case 552: return glRenderbufferStorageMultisampleEXT;
- case 553: return glResolveMultisampleFramebufferAPPLE;
- case 554: return glTexStorage1DEXT;
- case 555: return glTexStorage2DEXT;
- case 556: return glTexStorage3DEXT;
- case 557: return glTextureStorage1DEXT;
- case 558: return glTextureStorage2DEXT;
- case 559: return glTextureStorage3DEXT;
- case 560: return glUseProgramStagesEXT;
- case 561: return glValidateProgramPipelineEXT;
- case 2000: return eglGetDisplay;
- case 2001: return eglInitialize;
- case 2002: return eglTerminate;
- case 2003: return eglGetConfigs;
- case 2004: return eglChooseConfig;
- case 2005: return eglGetConfigAttrib;
- case 2006: return eglCreateWindowSurface;
- case 2007: return eglCreatePixmapSurface;
- case 2008: return eglCreatePbufferSurface;
- case 2009: return eglDestroySurface;
- case 2010: return eglQuerySurface;
- case 2011: return eglCreateContext;
- case 2012: return eglDestroyContext;
- case 2013: return eglMakeCurrent;
- case 2014: return eglGetCurrentContext;
- case 2015: return eglGetCurrentSurface;
- case 2016: return eglGetCurrentDisplay;
- case 2017: return eglQueryContext;
- case 2018: return eglWaitGL;
- case 2019: return eglWaitNative;
- case 2020: return eglSwapBuffers;
- case 2021: return eglCopyBuffers;
- case 2022: return eglGetError;
- case 2023: return eglQueryString;
- case 2024: return eglGetProcAddress;
- case 2025: return eglSurfaceAttrib;
- case 2026: return eglBindTexImage;
- case 2027: return eglReleaseTexImage;
- case 2028: return eglSwapInterval;
- case 2029: return eglBindAPI;
- case 2030: return eglQueryAPI;
- case 2031: return eglWaitClient;
- case 2032: return eglReleaseThread;
- case 2033: return eglCreatePbufferFromClientBuffer;
- case 2034: return eglLockSurfaceKHR;
- case 2035: return eglUnlockSurfaceKHR;
- case 2036: return eglCreateImageKHR;
- case 2037: return eglDestroyImageKHR;
- case 2038: return eglCreateSyncKHR;
- case 2039: return eglDestroySyncKHR;
- case 2040: return eglClientWaitSyncKHR;
- case 2041: return eglGetSyncAttribKHR;
- case 2042: return eglSetSwapRectangleANDROID;
- case 2043: return eglGetRenderBufferANDROID;
- case 2044: return eglGetSystemTimeFrequencyNV;
- case 2045: return eglGetSystemTimeNV;
- case 3000: return invalid;
- case 3001: return glVertexAttribPointerData;
- default: return null;
- }
- }
-
- public static com.google.protobuf.Internal.EnumLiteMap<Function>
- internalGetValueMap() {
- return internalValueMap;
- }
- private static com.google.protobuf.Internal.EnumLiteMap<Function>
- internalValueMap =
- new com.google.protobuf.Internal.EnumLiteMap<Function>() {
- @Override
- public Function findValueByNumber(int number) {
- return Function.valueOf(number)
- ; }
- };
-
- private final int index;
- private final int value;
- private Function(int index, int value) {
- this.index = index;
- this.value = value;
- }
-
- // @@protoc_insertion_point(enum_scope:android.gltrace.GLMessage.Function)
- }
-
- public static final class DataType extends
- com.google.protobuf.GeneratedMessageLite {
- // Use DataType.newBuilder() to construct.
- private DataType() {
- initFields();
- }
- private DataType(boolean noInit) {}
-
- private static final DataType defaultInstance;
- public static DataType getDefaultInstance() {
- return defaultInstance;
- }
-
- @Override
- public DataType getDefaultInstanceForType() {
- return defaultInstance;
- }
-
- public enum Type
- implements com.google.protobuf.Internal.EnumLite {
- VOID(0, 1),
- CHAR(1, 2),
- BYTE(2, 3),
- INT(3, 4),
- FLOAT(4, 5),
- BOOL(5, 6),
- ENUM(6, 7),
- INT64(7, 8),
- ;
-
-
- @Override
- public final int getNumber() { return value; }
-
- public static Type valueOf(int value) {
- switch (value) {
- case 1: return VOID;
- case 2: return CHAR;
- case 3: return BYTE;
- case 4: return INT;
- case 5: return FLOAT;
- case 6: return BOOL;
- case 7: return ENUM;
- case 8: return INT64;
- default: return null;
- }
- }
-
- public static com.google.protobuf.Internal.EnumLiteMap<Type>
- internalGetValueMap() {
- return internalValueMap;
- }
- private static com.google.protobuf.Internal.EnumLiteMap<Type>
- internalValueMap =
- new com.google.protobuf.Internal.EnumLiteMap<Type>() {
- @Override
- public Type findValueByNumber(int number) {
- return Type.valueOf(number)
- ; }
- };
-
- private final int index;
- private final int value;
- private Type(int index, int value) {
- this.index = index;
- this.value = value;
- }
-
- // @@protoc_insertion_point(enum_scope:android.gltrace.GLMessage.DataType.Type)
- }
-
- // required .android.gltrace.GLMessage.DataType.Type type = 1 [default = VOID];
- public static final int TYPE_FIELD_NUMBER = 1;
- private boolean hasType;
- private com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.Type type_;
- public boolean hasType() { return hasType; }
- public com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.Type getType() { return type_; }
-
- // required bool isArray = 2 [default = false];
- public static final int ISARRAY_FIELD_NUMBER = 2;
- private boolean hasIsArray;
- private boolean isArray_ = false;
- public boolean hasIsArray() { return hasIsArray; }
- public boolean getIsArray() { return isArray_; }
-
- // repeated int32 intValue = 3;
- public static final int INTVALUE_FIELD_NUMBER = 3;
- private java.util.List<java.lang.Integer> intValue_ =
- java.util.Collections.emptyList();
- public java.util.List<java.lang.Integer> getIntValueList() {
- return intValue_;
- }
- public int getIntValueCount() { return intValue_.size(); }
- public int getIntValue(int index) {
- return intValue_.get(index);
- }
-
- // repeated float floatValue = 4;
- public static final int FLOATVALUE_FIELD_NUMBER = 4;
- private java.util.List<java.lang.Float> floatValue_ =
- java.util.Collections.emptyList();
- public java.util.List<java.lang.Float> getFloatValueList() {
- return floatValue_;
- }
- public int getFloatValueCount() { return floatValue_.size(); }
- public float getFloatValue(int index) {
- return floatValue_.get(index);
- }
-
- // repeated bytes charValue = 5;
- public static final int CHARVALUE_FIELD_NUMBER = 5;
- private java.util.List<com.google.protobuf.ByteString> charValue_ =
- java.util.Collections.emptyList();
- public java.util.List<com.google.protobuf.ByteString> getCharValueList() {
- return charValue_;
- }
- public int getCharValueCount() { return charValue_.size(); }
- public com.google.protobuf.ByteString getCharValue(int index) {
- return charValue_.get(index);
- }
-
- // repeated bytes rawBytes = 6;
- public static final int RAWBYTES_FIELD_NUMBER = 6;
- private java.util.List<com.google.protobuf.ByteString> rawBytes_ =
- java.util.Collections.emptyList();
- public java.util.List<com.google.protobuf.ByteString> getRawBytesList() {
- return rawBytes_;
- }
- public int getRawBytesCount() { return rawBytes_.size(); }
- public com.google.protobuf.ByteString getRawBytes(int index) {
- return rawBytes_.get(index);
- }
-
- // repeated bool boolValue = 7;
- public static final int BOOLVALUE_FIELD_NUMBER = 7;
- private java.util.List<java.lang.Boolean> boolValue_ =
- java.util.Collections.emptyList();
- public java.util.List<java.lang.Boolean> getBoolValueList() {
- return boolValue_;
- }
- public int getBoolValueCount() { return boolValue_.size(); }
- public boolean getBoolValue(int index) {
- return boolValue_.get(index);
- }
-
- // repeated int64 int64Value = 8;
- public static final int INT64VALUE_FIELD_NUMBER = 8;
- private java.util.List<java.lang.Long> int64Value_ =
- java.util.Collections.emptyList();
- public java.util.List<java.lang.Long> getInt64ValueList() {
- return int64Value_;
- }
- public int getInt64ValueCount() { return int64Value_.size(); }
- public long getInt64Value(int index) {
- return int64Value_.get(index);
- }
-
- private void initFields() {
- type_ = com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.Type.VOID;
- }
- @Override
- public final boolean isInitialized() {
- if (!hasType) return false;
- if (!hasIsArray) return false;
- return true;
- }
-
- @Override
- public void writeTo(com.google.protobuf.CodedOutputStream output)
- throws java.io.IOException {
- getSerializedSize();
- if (hasType()) {
- output.writeEnum(1, getType().getNumber());
- }
- if (hasIsArray()) {
- output.writeBool(2, getIsArray());
- }
- for (int element : getIntValueList()) {
- output.writeInt32(3, element);
- }
- for (float element : getFloatValueList()) {
- output.writeFloat(4, element);
- }
- for (com.google.protobuf.ByteString element : getCharValueList()) {
- output.writeBytes(5, element);
- }
- for (com.google.protobuf.ByteString element : getRawBytesList()) {
- output.writeBytes(6, element);
- }
- for (boolean element : getBoolValueList()) {
- output.writeBool(7, element);
- }
- for (long element : getInt64ValueList()) {
- output.writeInt64(8, element);
- }
- }
-
- private int memoizedSerializedSize = -1;
- @Override
- public int getSerializedSize() {
- int size = memoizedSerializedSize;
- if (size != -1) return size;
-
- size = 0;
- if (hasType()) {
- size += com.google.protobuf.CodedOutputStream
- .computeEnumSize(1, getType().getNumber());
- }
- if (hasIsArray()) {
- size += com.google.protobuf.CodedOutputStream
- .computeBoolSize(2, getIsArray());
- }
- {
- int dataSize = 0;
- for (int element : getIntValueList()) {
- dataSize += com.google.protobuf.CodedOutputStream
- .computeInt32SizeNoTag(element);
- }
- size += dataSize;
- size += 1 * getIntValueList().size();
- }
- {
- int dataSize = 0;
- dataSize = 4 * getFloatValueList().size();
- size += dataSize;
- size += 1 * getFloatValueList().size();
- }
- {
- int dataSize = 0;
- for (com.google.protobuf.ByteString element : getCharValueList()) {
- dataSize += com.google.protobuf.CodedOutputStream
- .computeBytesSizeNoTag(element);
- }
- size += dataSize;
- size += 1 * getCharValueList().size();
- }
- {
- int dataSize = 0;
- for (com.google.protobuf.ByteString element : getRawBytesList()) {
- dataSize += com.google.protobuf.CodedOutputStream
- .computeBytesSizeNoTag(element);
- }
- size += dataSize;
- size += 1 * getRawBytesList().size();
- }
- {
- int dataSize = 0;
- dataSize = 1 * getBoolValueList().size();
- size += dataSize;
- size += 1 * getBoolValueList().size();
- }
- {
- int dataSize = 0;
- for (long element : getInt64ValueList()) {
- dataSize += com.google.protobuf.CodedOutputStream
- .computeInt64SizeNoTag(element);
- }
- size += dataSize;
- size += 1 * getInt64ValueList().size();
- }
- memoizedSerializedSize = size;
- return size;
- }
-
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType parseFrom(
- com.google.protobuf.ByteString data)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return newBuilder().mergeFrom(data).buildParsed();
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType parseFrom(
- com.google.protobuf.ByteString data,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return newBuilder().mergeFrom(data, extensionRegistry)
- .buildParsed();
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType parseFrom(byte[] data)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return newBuilder().mergeFrom(data).buildParsed();
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType parseFrom(
- byte[] data,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return newBuilder().mergeFrom(data, extensionRegistry)
- .buildParsed();
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType parseFrom(java.io.InputStream input)
- throws java.io.IOException {
- return newBuilder().mergeFrom(input).buildParsed();
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType parseFrom(
- java.io.InputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws java.io.IOException {
- return newBuilder().mergeFrom(input, extensionRegistry)
- .buildParsed();
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType parseDelimitedFrom(java.io.InputStream input)
- throws java.io.IOException {
- Builder builder = newBuilder();
- if (builder.mergeDelimitedFrom(input)) {
- return builder.buildParsed();
- } else {
- return null;
- }
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType parseDelimitedFrom(
- java.io.InputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws java.io.IOException {
- Builder builder = newBuilder();
- if (builder.mergeDelimitedFrom(input, extensionRegistry)) {
- return builder.buildParsed();
- } else {
- return null;
- }
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType parseFrom(
- com.google.protobuf.CodedInputStream input)
- throws java.io.IOException {
- return newBuilder().mergeFrom(input).buildParsed();
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType parseFrom(
- com.google.protobuf.CodedInputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws java.io.IOException {
- return newBuilder().mergeFrom(input, extensionRegistry)
- .buildParsed();
- }
-
- public static Builder newBuilder() { return Builder.create(); }
- @Override
- public Builder newBuilderForType() { return newBuilder(); }
- public static Builder newBuilder(com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType prototype) {
- return newBuilder().mergeFrom(prototype);
- }
- @Override
- public Builder toBuilder() { return newBuilder(this); }
-
- public static final class Builder extends
- com.google.protobuf.GeneratedMessageLite.Builder<
- com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType, Builder> {
- private com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType result;
-
- // Construct using com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.newBuilder()
- private Builder() {}
-
- private static Builder create() {
- Builder builder = new Builder();
- builder.result = new com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType();
- return builder;
- }
-
- @Override
- protected com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType internalGetResult() {
- return result;
- }
-
- @Override
- public Builder clear() {
- if (result == null) {
- throw new IllegalStateException(
- "Cannot call clear() after build().");
- }
- result = new com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType();
- return this;
- }
-
- @Override
- public Builder clone() {
- return create().mergeFrom(result);
- }
-
- @Override
- public com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType getDefaultInstanceForType() {
- return com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.getDefaultInstance();
- }
-
- @Override
- public boolean isInitialized() {
- return result.isInitialized();
- }
- @Override
- public com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType build() {
- if (result != null && !isInitialized()) {
- throw newUninitializedMessageException(result);
- }
- return buildPartial();
- }
-
- private com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType buildParsed()
- throws com.google.protobuf.InvalidProtocolBufferException {
- if (!isInitialized()) {
- throw newUninitializedMessageException(
- result).asInvalidProtocolBufferException();
- }
- return buildPartial();
- }
-
- @Override
- public com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType buildPartial() {
- if (result == null) {
- throw new IllegalStateException(
- "build() has already been called on this Builder.");
- }
- if (result.intValue_ != java.util.Collections.EMPTY_LIST) {
- result.intValue_ =
- java.util.Collections.unmodifiableList(result.intValue_);
- }
- if (result.floatValue_ != java.util.Collections.EMPTY_LIST) {
- result.floatValue_ =
- java.util.Collections.unmodifiableList(result.floatValue_);
- }
- if (result.charValue_ != java.util.Collections.EMPTY_LIST) {
- result.charValue_ =
- java.util.Collections.unmodifiableList(result.charValue_);
- }
- if (result.rawBytes_ != java.util.Collections.EMPTY_LIST) {
- result.rawBytes_ =
- java.util.Collections.unmodifiableList(result.rawBytes_);
- }
- if (result.boolValue_ != java.util.Collections.EMPTY_LIST) {
- result.boolValue_ =
- java.util.Collections.unmodifiableList(result.boolValue_);
- }
- if (result.int64Value_ != java.util.Collections.EMPTY_LIST) {
- result.int64Value_ =
- java.util.Collections.unmodifiableList(result.int64Value_);
- }
- com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType returnMe = result;
- result = null;
- return returnMe;
- }
-
- @Override
- public Builder mergeFrom(com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType other) {
- if (other == com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.getDefaultInstance()) return this;
- if (other.hasType()) {
- setType(other.getType());
- }
- if (other.hasIsArray()) {
- setIsArray(other.getIsArray());
- }
- if (!other.intValue_.isEmpty()) {
- if (result.intValue_.isEmpty()) {
- result.intValue_ = new java.util.ArrayList<java.lang.Integer>();
- }
- result.intValue_.addAll(other.intValue_);
- }
- if (!other.floatValue_.isEmpty()) {
- if (result.floatValue_.isEmpty()) {
- result.floatValue_ = new java.util.ArrayList<java.lang.Float>();
- }
- result.floatValue_.addAll(other.floatValue_);
- }
- if (!other.charValue_.isEmpty()) {
- if (result.charValue_.isEmpty()) {
- result.charValue_ = new java.util.ArrayList<com.google.protobuf.ByteString>();
- }
- result.charValue_.addAll(other.charValue_);
- }
- if (!other.rawBytes_.isEmpty()) {
- if (result.rawBytes_.isEmpty()) {
- result.rawBytes_ = new java.util.ArrayList<com.google.protobuf.ByteString>();
- }
- result.rawBytes_.addAll(other.rawBytes_);
- }
- if (!other.boolValue_.isEmpty()) {
- if (result.boolValue_.isEmpty()) {
- result.boolValue_ = new java.util.ArrayList<java.lang.Boolean>();
- }
- result.boolValue_.addAll(other.boolValue_);
- }
- if (!other.int64Value_.isEmpty()) {
- if (result.int64Value_.isEmpty()) {
- result.int64Value_ = new java.util.ArrayList<java.lang.Long>();
- }
- result.int64Value_.addAll(other.int64Value_);
- }
- return this;
- }
-
- @Override
- public Builder mergeFrom(
- com.google.protobuf.CodedInputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws java.io.IOException {
- while (true) {
- int tag = input.readTag();
- switch (tag) {
- case 0:
- return this;
- default: {
- if (!parseUnknownField(input, extensionRegistry, tag)) {
- return this;
- }
- break;
- }
- case 8: {
- int rawValue = input.readEnum();
- com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.Type value = com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.Type.valueOf(rawValue);
- if (value != null) {
- setType(value);
- }
- break;
- }
- case 16: {
- setIsArray(input.readBool());
- break;
- }
- case 24: {
- addIntValue(input.readInt32());
- break;
- }
- case 26: {
- int length = input.readRawVarint32();
- int limit = input.pushLimit(length);
- while (input.getBytesUntilLimit() > 0) {
- addIntValue(input.readInt32());
- }
- input.popLimit(limit);
- break;
- }
- case 37: {
- addFloatValue(input.readFloat());
- break;
- }
- case 34: {
- int length = input.readRawVarint32();
- int limit = input.pushLimit(length);
- while (input.getBytesUntilLimit() > 0) {
- addFloatValue(input.readFloat());
- }
- input.popLimit(limit);
- break;
- }
- case 42: {
- addCharValue(input.readBytes());
- break;
- }
- case 50: {
- addRawBytes(input.readBytes());
- break;
- }
- case 56: {
- addBoolValue(input.readBool());
- break;
- }
- case 58: {
- int length = input.readRawVarint32();
- int limit = input.pushLimit(length);
- while (input.getBytesUntilLimit() > 0) {
- addBoolValue(input.readBool());
- }
- input.popLimit(limit);
- break;
- }
- case 64: {
- addInt64Value(input.readInt64());
- break;
- }
- case 66: {
- int length = input.readRawVarint32();
- int limit = input.pushLimit(length);
- while (input.getBytesUntilLimit() > 0) {
- addInt64Value(input.readInt64());
- }
- input.popLimit(limit);
- break;
- }
- }
- }
- }
-
-
- // required .android.gltrace.GLMessage.DataType.Type type = 1 [default = VOID];
- public boolean hasType() {
- return result.hasType();
- }
- public com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.Type getType() {
- return result.getType();
- }
- public Builder setType(com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.Type value) {
- if (value == null) {
- throw new NullPointerException();
- }
- result.hasType = true;
- result.type_ = value;
- return this;
- }
- public Builder clearType() {
- result.hasType = false;
- result.type_ = com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.Type.VOID;
- return this;
- }
-
- // required bool isArray = 2 [default = false];
- public boolean hasIsArray() {
- return result.hasIsArray();
- }
- public boolean getIsArray() {
- return result.getIsArray();
- }
- public Builder setIsArray(boolean value) {
- result.hasIsArray = true;
- result.isArray_ = value;
- return this;
- }
- public Builder clearIsArray() {
- result.hasIsArray = false;
- result.isArray_ = false;
- return this;
- }
-
- // repeated int32 intValue = 3;
- public java.util.List<java.lang.Integer> getIntValueList() {
- return java.util.Collections.unmodifiableList(result.intValue_);
- }
- public int getIntValueCount() {
- return result.getIntValueCount();
- }
- public int getIntValue(int index) {
- return result.getIntValue(index);
- }
- public Builder setIntValue(int index, int value) {
- result.intValue_.set(index, value);
- return this;
- }
- public Builder addIntValue(int value) {
- if (result.intValue_.isEmpty()) {
- result.intValue_ = new java.util.ArrayList<java.lang.Integer>();
- }
- result.intValue_.add(value);
- return this;
- }
- public Builder addAllIntValue(
- java.lang.Iterable<? extends java.lang.Integer> values) {
- if (result.intValue_.isEmpty()) {
- result.intValue_ = new java.util.ArrayList<java.lang.Integer>();
- }
- super.addAll(values, result.intValue_);
- return this;
- }
- public Builder clearIntValue() {
- result.intValue_ = java.util.Collections.emptyList();
- return this;
- }
-
- // repeated float floatValue = 4;
- public java.util.List<java.lang.Float> getFloatValueList() {
- return java.util.Collections.unmodifiableList(result.floatValue_);
- }
- public int getFloatValueCount() {
- return result.getFloatValueCount();
- }
- public float getFloatValue(int index) {
- return result.getFloatValue(index);
- }
- public Builder setFloatValue(int index, float value) {
- result.floatValue_.set(index, value);
- return this;
- }
- public Builder addFloatValue(float value) {
- if (result.floatValue_.isEmpty()) {
- result.floatValue_ = new java.util.ArrayList<java.lang.Float>();
- }
- result.floatValue_.add(value);
- return this;
- }
- public Builder addAllFloatValue(
- java.lang.Iterable<? extends java.lang.Float> values) {
- if (result.floatValue_.isEmpty()) {
- result.floatValue_ = new java.util.ArrayList<java.lang.Float>();
- }
- super.addAll(values, result.floatValue_);
- return this;
- }
- public Builder clearFloatValue() {
- result.floatValue_ = java.util.Collections.emptyList();
- return this;
- }
-
- // repeated bytes charValue = 5;
- public java.util.List<com.google.protobuf.ByteString> getCharValueList() {
- return java.util.Collections.unmodifiableList(result.charValue_);
- }
- public int getCharValueCount() {
- return result.getCharValueCount();
- }
- public com.google.protobuf.ByteString getCharValue(int index) {
- return result.getCharValue(index);
- }
- public Builder setCharValue(int index, com.google.protobuf.ByteString value) {
- if (value == null) {
- throw new NullPointerException();
- }
- result.charValue_.set(index, value);
- return this;
- }
- public Builder addCharValue(com.google.protobuf.ByteString value) {
- if (value == null) {
- throw new NullPointerException();
- }
- if (result.charValue_.isEmpty()) {
- result.charValue_ = new java.util.ArrayList<com.google.protobuf.ByteString>();
- }
- result.charValue_.add(value);
- return this;
- }
- public Builder addAllCharValue(
- java.lang.Iterable<? extends com.google.protobuf.ByteString> values) {
- if (result.charValue_.isEmpty()) {
- result.charValue_ = new java.util.ArrayList<com.google.protobuf.ByteString>();
- }
- super.addAll(values, result.charValue_);
- return this;
- }
- public Builder clearCharValue() {
- result.charValue_ = java.util.Collections.emptyList();
- return this;
- }
-
- // repeated bytes rawBytes = 6;
- public java.util.List<com.google.protobuf.ByteString> getRawBytesList() {
- return java.util.Collections.unmodifiableList(result.rawBytes_);
- }
- public int getRawBytesCount() {
- return result.getRawBytesCount();
- }
- public com.google.protobuf.ByteString getRawBytes(int index) {
- return result.getRawBytes(index);
- }
- public Builder setRawBytes(int index, com.google.protobuf.ByteString value) {
- if (value == null) {
- throw new NullPointerException();
- }
- result.rawBytes_.set(index, value);
- return this;
- }
- public Builder addRawBytes(com.google.protobuf.ByteString value) {
- if (value == null) {
- throw new NullPointerException();
- }
- if (result.rawBytes_.isEmpty()) {
- result.rawBytes_ = new java.util.ArrayList<com.google.protobuf.ByteString>();
- }
- result.rawBytes_.add(value);
- return this;
- }
- public Builder addAllRawBytes(
- java.lang.Iterable<? extends com.google.protobuf.ByteString> values) {
- if (result.rawBytes_.isEmpty()) {
- result.rawBytes_ = new java.util.ArrayList<com.google.protobuf.ByteString>();
- }
- super.addAll(values, result.rawBytes_);
- return this;
- }
- public Builder clearRawBytes() {
- result.rawBytes_ = java.util.Collections.emptyList();
- return this;
- }
-
- // repeated bool boolValue = 7;
- public java.util.List<java.lang.Boolean> getBoolValueList() {
- return java.util.Collections.unmodifiableList(result.boolValue_);
- }
- public int getBoolValueCount() {
- return result.getBoolValueCount();
- }
- public boolean getBoolValue(int index) {
- return result.getBoolValue(index);
- }
- public Builder setBoolValue(int index, boolean value) {
- result.boolValue_.set(index, value);
- return this;
- }
- public Builder addBoolValue(boolean value) {
- if (result.boolValue_.isEmpty()) {
- result.boolValue_ = new java.util.ArrayList<java.lang.Boolean>();
- }
- result.boolValue_.add(value);
- return this;
- }
- public Builder addAllBoolValue(
- java.lang.Iterable<? extends java.lang.Boolean> values) {
- if (result.boolValue_.isEmpty()) {
- result.boolValue_ = new java.util.ArrayList<java.lang.Boolean>();
- }
- super.addAll(values, result.boolValue_);
- return this;
- }
- public Builder clearBoolValue() {
- result.boolValue_ = java.util.Collections.emptyList();
- return this;
- }
-
- // repeated int64 int64Value = 8;
- public java.util.List<java.lang.Long> getInt64ValueList() {
- return java.util.Collections.unmodifiableList(result.int64Value_);
- }
- public int getInt64ValueCount() {
- return result.getInt64ValueCount();
- }
- public long getInt64Value(int index) {
- return result.getInt64Value(index);
- }
- public Builder setInt64Value(int index, long value) {
- result.int64Value_.set(index, value);
- return this;
- }
- public Builder addInt64Value(long value) {
- if (result.int64Value_.isEmpty()) {
- result.int64Value_ = new java.util.ArrayList<java.lang.Long>();
- }
- result.int64Value_.add(value);
- return this;
- }
- public Builder addAllInt64Value(
- java.lang.Iterable<? extends java.lang.Long> values) {
- if (result.int64Value_.isEmpty()) {
- result.int64Value_ = new java.util.ArrayList<java.lang.Long>();
- }
- super.addAll(values, result.int64Value_);
- return this;
- }
- public Builder clearInt64Value() {
- result.int64Value_ = java.util.Collections.emptyList();
- return this;
- }
-
- // @@protoc_insertion_point(builder_scope:android.gltrace.GLMessage.DataType)
- }
-
- static {
- defaultInstance = new DataType(true);
- com.android.ide.eclipse.gltrace.GLProtoBuf.internalForceInit();
- defaultInstance.initFields();
- }
-
- // @@protoc_insertion_point(class_scope:android.gltrace.GLMessage.DataType)
- }
-
- public static final class FrameBuffer extends
- com.google.protobuf.GeneratedMessageLite {
- // Use FrameBuffer.newBuilder() to construct.
- private FrameBuffer() {
- initFields();
- }
- private FrameBuffer(boolean noInit) {}
-
- private static final FrameBuffer defaultInstance;
- public static FrameBuffer getDefaultInstance() {
- return defaultInstance;
- }
-
- @Override
- public FrameBuffer getDefaultInstanceForType() {
- return defaultInstance;
- }
-
- // required int32 width = 1;
- public static final int WIDTH_FIELD_NUMBER = 1;
- private boolean hasWidth;
- private int width_ = 0;
- public boolean hasWidth() { return hasWidth; }
- public int getWidth() { return width_; }
-
- // required int32 height = 2;
- public static final int HEIGHT_FIELD_NUMBER = 2;
- private boolean hasHeight;
- private int height_ = 0;
- public boolean hasHeight() { return hasHeight; }
- public int getHeight() { return height_; }
-
- // repeated bytes contents = 3;
- public static final int CONTENTS_FIELD_NUMBER = 3;
- private java.util.List<com.google.protobuf.ByteString> contents_ =
- java.util.Collections.emptyList();
- public java.util.List<com.google.protobuf.ByteString> getContentsList() {
- return contents_;
- }
- public int getContentsCount() { return contents_.size(); }
- public com.google.protobuf.ByteString getContents(int index) {
- return contents_.get(index);
- }
-
- private void initFields() {
- }
- @Override
- public final boolean isInitialized() {
- if (!hasWidth) return false;
- if (!hasHeight) return false;
- return true;
- }
-
- @Override
- public void writeTo(com.google.protobuf.CodedOutputStream output)
- throws java.io.IOException {
- getSerializedSize();
- if (hasWidth()) {
- output.writeInt32(1, getWidth());
- }
- if (hasHeight()) {
- output.writeInt32(2, getHeight());
- }
- for (com.google.protobuf.ByteString element : getContentsList()) {
- output.writeBytes(3, element);
- }
- }
-
- private int memoizedSerializedSize = -1;
- @Override
- public int getSerializedSize() {
- int size = memoizedSerializedSize;
- if (size != -1) return size;
-
- size = 0;
- if (hasWidth()) {
- size += com.google.protobuf.CodedOutputStream
- .computeInt32Size(1, getWidth());
- }
- if (hasHeight()) {
- size += com.google.protobuf.CodedOutputStream
- .computeInt32Size(2, getHeight());
- }
- {
- int dataSize = 0;
- for (com.google.protobuf.ByteString element : getContentsList()) {
- dataSize += com.google.protobuf.CodedOutputStream
- .computeBytesSizeNoTag(element);
- }
- size += dataSize;
- size += 1 * getContentsList().size();
- }
- memoizedSerializedSize = size;
- return size;
- }
-
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer parseFrom(
- com.google.protobuf.ByteString data)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return newBuilder().mergeFrom(data).buildParsed();
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer parseFrom(
- com.google.protobuf.ByteString data,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return newBuilder().mergeFrom(data, extensionRegistry)
- .buildParsed();
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer parseFrom(byte[] data)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return newBuilder().mergeFrom(data).buildParsed();
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer parseFrom(
- byte[] data,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return newBuilder().mergeFrom(data, extensionRegistry)
- .buildParsed();
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer parseFrom(java.io.InputStream input)
- throws java.io.IOException {
- return newBuilder().mergeFrom(input).buildParsed();
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer parseFrom(
- java.io.InputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws java.io.IOException {
- return newBuilder().mergeFrom(input, extensionRegistry)
- .buildParsed();
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer parseDelimitedFrom(java.io.InputStream input)
- throws java.io.IOException {
- Builder builder = newBuilder();
- if (builder.mergeDelimitedFrom(input)) {
- return builder.buildParsed();
- } else {
- return null;
- }
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer parseDelimitedFrom(
- java.io.InputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws java.io.IOException {
- Builder builder = newBuilder();
- if (builder.mergeDelimitedFrom(input, extensionRegistry)) {
- return builder.buildParsed();
- } else {
- return null;
- }
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer parseFrom(
- com.google.protobuf.CodedInputStream input)
- throws java.io.IOException {
- return newBuilder().mergeFrom(input).buildParsed();
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer parseFrom(
- com.google.protobuf.CodedInputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws java.io.IOException {
- return newBuilder().mergeFrom(input, extensionRegistry)
- .buildParsed();
- }
-
- public static Builder newBuilder() { return Builder.create(); }
- @Override
- public Builder newBuilderForType() { return newBuilder(); }
- public static Builder newBuilder(com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer prototype) {
- return newBuilder().mergeFrom(prototype);
- }
- @Override
- public Builder toBuilder() { return newBuilder(this); }
-
- public static final class Builder extends
- com.google.protobuf.GeneratedMessageLite.Builder<
- com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer, Builder> {
- private com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer result;
-
- // Construct using com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer.newBuilder()
- private Builder() {}
-
- private static Builder create() {
- Builder builder = new Builder();
- builder.result = new com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer();
- return builder;
- }
-
- @Override
- protected com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer internalGetResult() {
- return result;
- }
-
- @Override
- public Builder clear() {
- if (result == null) {
- throw new IllegalStateException(
- "Cannot call clear() after build().");
- }
- result = new com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer();
- return this;
- }
-
- @Override
- public Builder clone() {
- return create().mergeFrom(result);
- }
-
- @Override
- public com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer getDefaultInstanceForType() {
- return com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer.getDefaultInstance();
- }
-
- @Override
- public boolean isInitialized() {
- return result.isInitialized();
- }
- @Override
- public com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer build() {
- if (result != null && !isInitialized()) {
- throw newUninitializedMessageException(result);
- }
- return buildPartial();
- }
-
- private com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer buildParsed()
- throws com.google.protobuf.InvalidProtocolBufferException {
- if (!isInitialized()) {
- throw newUninitializedMessageException(
- result).asInvalidProtocolBufferException();
- }
- return buildPartial();
- }
-
- @Override
- public com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer buildPartial() {
- if (result == null) {
- throw new IllegalStateException(
- "build() has already been called on this Builder.");
- }
- if (result.contents_ != java.util.Collections.EMPTY_LIST) {
- result.contents_ =
- java.util.Collections.unmodifiableList(result.contents_);
- }
- com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer returnMe = result;
- result = null;
- return returnMe;
- }
-
- @Override
- public Builder mergeFrom(com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer other) {
- if (other == com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer.getDefaultInstance()) return this;
- if (other.hasWidth()) {
- setWidth(other.getWidth());
- }
- if (other.hasHeight()) {
- setHeight(other.getHeight());
- }
- if (!other.contents_.isEmpty()) {
- if (result.contents_.isEmpty()) {
- result.contents_ = new java.util.ArrayList<com.google.protobuf.ByteString>();
- }
- result.contents_.addAll(other.contents_);
- }
- return this;
- }
-
- @Override
- public Builder mergeFrom(
- com.google.protobuf.CodedInputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws java.io.IOException {
- while (true) {
- int tag = input.readTag();
- switch (tag) {
- case 0:
- return this;
- default: {
- if (!parseUnknownField(input, extensionRegistry, tag)) {
- return this;
- }
- break;
- }
- case 8: {
- setWidth(input.readInt32());
- break;
- }
- case 16: {
- setHeight(input.readInt32());
- break;
- }
- case 26: {
- addContents(input.readBytes());
- break;
- }
- }
- }
- }
-
-
- // required int32 width = 1;
- public boolean hasWidth() {
- return result.hasWidth();
- }
- public int getWidth() {
- return result.getWidth();
- }
- public Builder setWidth(int value) {
- result.hasWidth = true;
- result.width_ = value;
- return this;
- }
- public Builder clearWidth() {
- result.hasWidth = false;
- result.width_ = 0;
- return this;
- }
-
- // required int32 height = 2;
- public boolean hasHeight() {
- return result.hasHeight();
- }
- public int getHeight() {
- return result.getHeight();
- }
- public Builder setHeight(int value) {
- result.hasHeight = true;
- result.height_ = value;
- return this;
- }
- public Builder clearHeight() {
- result.hasHeight = false;
- result.height_ = 0;
- return this;
- }
-
- // repeated bytes contents = 3;
- public java.util.List<com.google.protobuf.ByteString> getContentsList() {
- return java.util.Collections.unmodifiableList(result.contents_);
- }
- public int getContentsCount() {
- return result.getContentsCount();
- }
- public com.google.protobuf.ByteString getContents(int index) {
- return result.getContents(index);
- }
- public Builder setContents(int index, com.google.protobuf.ByteString value) {
- if (value == null) {
- throw new NullPointerException();
- }
- result.contents_.set(index, value);
- return this;
- }
- public Builder addContents(com.google.protobuf.ByteString value) {
- if (value == null) {
- throw new NullPointerException();
- }
- if (result.contents_.isEmpty()) {
- result.contents_ = new java.util.ArrayList<com.google.protobuf.ByteString>();
- }
- result.contents_.add(value);
- return this;
- }
- public Builder addAllContents(
- java.lang.Iterable<? extends com.google.protobuf.ByteString> values) {
- if (result.contents_.isEmpty()) {
- result.contents_ = new java.util.ArrayList<com.google.protobuf.ByteString>();
- }
- super.addAll(values, result.contents_);
- return this;
- }
- public Builder clearContents() {
- result.contents_ = java.util.Collections.emptyList();
- return this;
- }
-
- // @@protoc_insertion_point(builder_scope:android.gltrace.GLMessage.FrameBuffer)
- }
-
- static {
- defaultInstance = new FrameBuffer(true);
- com.android.ide.eclipse.gltrace.GLProtoBuf.internalForceInit();
- defaultInstance.initFields();
- }
-
- // @@protoc_insertion_point(class_scope:android.gltrace.GLMessage.FrameBuffer)
- }
-
- // required int32 context_id = 1;
- public static final int CONTEXT_ID_FIELD_NUMBER = 1;
- private boolean hasContextId;
- private int contextId_ = 0;
- public boolean hasContextId() { return hasContextId; }
- public int getContextId() { return contextId_; }
-
- // required int64 start_time = 2;
- public static final int START_TIME_FIELD_NUMBER = 2;
- private boolean hasStartTime;
- private long startTime_ = 0L;
- public boolean hasStartTime() { return hasStartTime; }
- public long getStartTime() { return startTime_; }
-
- // required int32 duration = 3;
- public static final int DURATION_FIELD_NUMBER = 3;
- private boolean hasDuration;
- private int duration_ = 0;
- public boolean hasDuration() { return hasDuration; }
- public int getDuration() { return duration_; }
-
- // required .android.gltrace.GLMessage.Function function = 4 [default = invalid];
- public static final int FUNCTION_FIELD_NUMBER = 4;
- private boolean hasFunction;
- private com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.Function function_;
- public boolean hasFunction() { return hasFunction; }
- public com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.Function getFunction() { return function_; }
-
- // repeated .android.gltrace.GLMessage.DataType args = 5;
- public static final int ARGS_FIELD_NUMBER = 5;
- private java.util.List<com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType> args_ =
- java.util.Collections.emptyList();
- public java.util.List<com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType> getArgsList() {
- return args_;
- }
- public int getArgsCount() { return args_.size(); }
- public com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType getArgs(int index) {
- return args_.get(index);
- }
-
- // optional .android.gltrace.GLMessage.DataType returnValue = 6;
- public static final int RETURNVALUE_FIELD_NUMBER = 6;
- private boolean hasReturnValue;
- private com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType returnValue_;
- public boolean hasReturnValue() { return hasReturnValue; }
- public com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType getReturnValue() { return returnValue_; }
-
- // optional .android.gltrace.GLMessage.FrameBuffer fb = 7;
- public static final int FB_FIELD_NUMBER = 7;
- private boolean hasFb;
- private com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer fb_;
- public boolean hasFb() { return hasFb; }
- public com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer getFb() { return fb_; }
-
- // optional int32 threadtime = 8;
- public static final int THREADTIME_FIELD_NUMBER = 8;
- private boolean hasThreadtime;
- private int threadtime_ = 0;
- public boolean hasThreadtime() { return hasThreadtime; }
- public int getThreadtime() { return threadtime_; }
-
- private void initFields() {
- function_ = com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.Function.invalid;
- returnValue_ = com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.getDefaultInstance();
- fb_ = com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer.getDefaultInstance();
- }
- @Override
- public final boolean isInitialized() {
- if (!hasContextId) return false;
- if (!hasStartTime) return false;
- if (!hasDuration) return false;
- if (!hasFunction) return false;
- for (com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType element : getArgsList()) {
- if (!element.isInitialized()) return false;
- }
- if (hasReturnValue()) {
- if (!getReturnValue().isInitialized()) return false;
- }
- if (hasFb()) {
- if (!getFb().isInitialized()) return false;
- }
- return true;
- }
-
- @Override
- public void writeTo(com.google.protobuf.CodedOutputStream output)
- throws java.io.IOException {
- getSerializedSize();
- if (hasContextId()) {
- output.writeInt32(1, getContextId());
- }
- if (hasStartTime()) {
- output.writeInt64(2, getStartTime());
- }
- if (hasDuration()) {
- output.writeInt32(3, getDuration());
- }
- if (hasFunction()) {
- output.writeEnum(4, getFunction().getNumber());
- }
- for (com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType element : getArgsList()) {
- output.writeMessage(5, element);
- }
- if (hasReturnValue()) {
- output.writeMessage(6, getReturnValue());
- }
- if (hasFb()) {
- output.writeMessage(7, getFb());
- }
- if (hasThreadtime()) {
- output.writeInt32(8, getThreadtime());
- }
- }
-
- private int memoizedSerializedSize = -1;
- @Override
- public int getSerializedSize() {
- int size = memoizedSerializedSize;
- if (size != -1) return size;
-
- size = 0;
- if (hasContextId()) {
- size += com.google.protobuf.CodedOutputStream
- .computeInt32Size(1, getContextId());
- }
- if (hasStartTime()) {
- size += com.google.protobuf.CodedOutputStream
- .computeInt64Size(2, getStartTime());
- }
- if (hasDuration()) {
- size += com.google.protobuf.CodedOutputStream
- .computeInt32Size(3, getDuration());
- }
- if (hasFunction()) {
- size += com.google.protobuf.CodedOutputStream
- .computeEnumSize(4, getFunction().getNumber());
- }
- for (com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType element : getArgsList()) {
- size += com.google.protobuf.CodedOutputStream
- .computeMessageSize(5, element);
- }
- if (hasReturnValue()) {
- size += com.google.protobuf.CodedOutputStream
- .computeMessageSize(6, getReturnValue());
- }
- if (hasFb()) {
- size += com.google.protobuf.CodedOutputStream
- .computeMessageSize(7, getFb());
- }
- if (hasThreadtime()) {
- size += com.google.protobuf.CodedOutputStream
- .computeInt32Size(8, getThreadtime());
- }
- memoizedSerializedSize = size;
- return size;
- }
-
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage parseFrom(
- com.google.protobuf.ByteString data)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return newBuilder().mergeFrom(data).buildParsed();
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage parseFrom(
- com.google.protobuf.ByteString data,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return newBuilder().mergeFrom(data, extensionRegistry)
- .buildParsed();
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage parseFrom(byte[] data)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return newBuilder().mergeFrom(data).buildParsed();
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage parseFrom(
- byte[] data,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws com.google.protobuf.InvalidProtocolBufferException {
- return newBuilder().mergeFrom(data, extensionRegistry)
- .buildParsed();
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage parseFrom(java.io.InputStream input)
- throws java.io.IOException {
- return newBuilder().mergeFrom(input).buildParsed();
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage parseFrom(
- java.io.InputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws java.io.IOException {
- return newBuilder().mergeFrom(input, extensionRegistry)
- .buildParsed();
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage parseDelimitedFrom(java.io.InputStream input)
- throws java.io.IOException {
- Builder builder = newBuilder();
- if (builder.mergeDelimitedFrom(input)) {
- return builder.buildParsed();
- } else {
- return null;
- }
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage parseDelimitedFrom(
- java.io.InputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws java.io.IOException {
- Builder builder = newBuilder();
- if (builder.mergeDelimitedFrom(input, extensionRegistry)) {
- return builder.buildParsed();
- } else {
- return null;
- }
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage parseFrom(
- com.google.protobuf.CodedInputStream input)
- throws java.io.IOException {
- return newBuilder().mergeFrom(input).buildParsed();
- }
- public static com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage parseFrom(
- com.google.protobuf.CodedInputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws java.io.IOException {
- return newBuilder().mergeFrom(input, extensionRegistry)
- .buildParsed();
- }
-
- public static Builder newBuilder() { return Builder.create(); }
- @Override
- public Builder newBuilderForType() { return newBuilder(); }
- public static Builder newBuilder(com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage prototype) {
- return newBuilder().mergeFrom(prototype);
- }
- @Override
- public Builder toBuilder() { return newBuilder(this); }
-
- public static final class Builder extends
- com.google.protobuf.GeneratedMessageLite.Builder<
- com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage, Builder> {
- private com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage result;
-
- // Construct using com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.newBuilder()
- private Builder() {}
-
- private static Builder create() {
- Builder builder = new Builder();
- builder.result = new com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage();
- return builder;
- }
-
- @Override
- protected com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage internalGetResult() {
- return result;
- }
-
- @Override
- public Builder clear() {
- if (result == null) {
- throw new IllegalStateException(
- "Cannot call clear() after build().");
- }
- result = new com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage();
- return this;
- }
-
- @Override
- public Builder clone() {
- return create().mergeFrom(result);
- }
-
- @Override
- public com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage getDefaultInstanceForType() {
- return com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.getDefaultInstance();
- }
-
- @Override
- public boolean isInitialized() {
- return result.isInitialized();
- }
- @Override
- public com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage build() {
- if (result != null && !isInitialized()) {
- throw newUninitializedMessageException(result);
- }
- return buildPartial();
- }
-
- private com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage buildParsed()
- throws com.google.protobuf.InvalidProtocolBufferException {
- if (!isInitialized()) {
- throw newUninitializedMessageException(
- result).asInvalidProtocolBufferException();
- }
- return buildPartial();
- }
-
- @Override
- public com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage buildPartial() {
- if (result == null) {
- throw new IllegalStateException(
- "build() has already been called on this Builder.");
- }
- if (result.args_ != java.util.Collections.EMPTY_LIST) {
- result.args_ =
- java.util.Collections.unmodifiableList(result.args_);
- }
- com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage returnMe = result;
- result = null;
- return returnMe;
- }
-
- @Override
- public Builder mergeFrom(com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage other) {
- if (other == com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.getDefaultInstance()) return this;
- if (other.hasContextId()) {
- setContextId(other.getContextId());
- }
- if (other.hasStartTime()) {
- setStartTime(other.getStartTime());
- }
- if (other.hasDuration()) {
- setDuration(other.getDuration());
- }
- if (other.hasFunction()) {
- setFunction(other.getFunction());
- }
- if (!other.args_.isEmpty()) {
- if (result.args_.isEmpty()) {
- result.args_ = new java.util.ArrayList<com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType>();
- }
- result.args_.addAll(other.args_);
- }
- if (other.hasReturnValue()) {
- mergeReturnValue(other.getReturnValue());
- }
- if (other.hasFb()) {
- mergeFb(other.getFb());
- }
- if (other.hasThreadtime()) {
- setThreadtime(other.getThreadtime());
- }
- return this;
- }
-
- @Override
- public Builder mergeFrom(
- com.google.protobuf.CodedInputStream input,
- com.google.protobuf.ExtensionRegistryLite extensionRegistry)
- throws java.io.IOException {
- while (true) {
- int tag = input.readTag();
- switch (tag) {
- case 0:
- return this;
- default: {
- if (!parseUnknownField(input, extensionRegistry, tag)) {
- return this;
- }
- break;
- }
- case 8: {
- setContextId(input.readInt32());
- break;
- }
- case 16: {
- setStartTime(input.readInt64());
- break;
- }
- case 24: {
- setDuration(input.readInt32());
- break;
- }
- case 32: {
- int rawValue = input.readEnum();
- com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.Function value = com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.Function.valueOf(rawValue);
- if (value != null) {
- setFunction(value);
- }
- break;
- }
- case 42: {
- com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.Builder subBuilder = com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.newBuilder();
- input.readMessage(subBuilder, extensionRegistry);
- addArgs(subBuilder.buildPartial());
- break;
- }
- case 50: {
- com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.Builder subBuilder = com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.newBuilder();
- if (hasReturnValue()) {
- subBuilder.mergeFrom(getReturnValue());
- }
- input.readMessage(subBuilder, extensionRegistry);
- setReturnValue(subBuilder.buildPartial());
- break;
- }
- case 58: {
- com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer.Builder subBuilder = com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer.newBuilder();
- if (hasFb()) {
- subBuilder.mergeFrom(getFb());
- }
- input.readMessage(subBuilder, extensionRegistry);
- setFb(subBuilder.buildPartial());
- break;
- }
- case 64: {
- setThreadtime(input.readInt32());
- break;
- }
- }
- }
- }
-
-
- // required int32 context_id = 1;
- public boolean hasContextId() {
- return result.hasContextId();
- }
- public int getContextId() {
- return result.getContextId();
- }
- public Builder setContextId(int value) {
- result.hasContextId = true;
- result.contextId_ = value;
- return this;
- }
- public Builder clearContextId() {
- result.hasContextId = false;
- result.contextId_ = 0;
- return this;
- }
-
- // required int64 start_time = 2;
- public boolean hasStartTime() {
- return result.hasStartTime();
- }
- public long getStartTime() {
- return result.getStartTime();
- }
- public Builder setStartTime(long value) {
- result.hasStartTime = true;
- result.startTime_ = value;
- return this;
- }
- public Builder clearStartTime() {
- result.hasStartTime = false;
- result.startTime_ = 0L;
- return this;
- }
-
- // required int32 duration = 3;
- public boolean hasDuration() {
- return result.hasDuration();
- }
- public int getDuration() {
- return result.getDuration();
- }
- public Builder setDuration(int value) {
- result.hasDuration = true;
- result.duration_ = value;
- return this;
- }
- public Builder clearDuration() {
- result.hasDuration = false;
- result.duration_ = 0;
- return this;
- }
-
- // required .android.gltrace.GLMessage.Function function = 4 [default = invalid];
- public boolean hasFunction() {
- return result.hasFunction();
- }
- public com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.Function getFunction() {
- return result.getFunction();
- }
- public Builder setFunction(com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.Function value) {
- if (value == null) {
- throw new NullPointerException();
- }
- result.hasFunction = true;
- result.function_ = value;
- return this;
- }
- public Builder clearFunction() {
- result.hasFunction = false;
- result.function_ = com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.Function.invalid;
- return this;
- }
-
- // repeated .android.gltrace.GLMessage.DataType args = 5;
- public java.util.List<com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType> getArgsList() {
- return java.util.Collections.unmodifiableList(result.args_);
- }
- public int getArgsCount() {
- return result.getArgsCount();
- }
- public com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType getArgs(int index) {
- return result.getArgs(index);
- }
- public Builder setArgs(int index, com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType value) {
- if (value == null) {
- throw new NullPointerException();
- }
- result.args_.set(index, value);
- return this;
- }
- public Builder setArgs(int index, com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.Builder builderForValue) {
- result.args_.set(index, builderForValue.build());
- return this;
- }
- public Builder addArgs(com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType value) {
- if (value == null) {
- throw new NullPointerException();
- }
- if (result.args_.isEmpty()) {
- result.args_ = new java.util.ArrayList<com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType>();
- }
- result.args_.add(value);
- return this;
- }
- public Builder addArgs(com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.Builder builderForValue) {
- if (result.args_.isEmpty()) {
- result.args_ = new java.util.ArrayList<com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType>();
- }
- result.args_.add(builderForValue.build());
- return this;
- }
- public Builder addAllArgs(
- java.lang.Iterable<? extends com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType> values) {
- if (result.args_.isEmpty()) {
- result.args_ = new java.util.ArrayList<com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType>();
- }
- super.addAll(values, result.args_);
- return this;
- }
- public Builder clearArgs() {
- result.args_ = java.util.Collections.emptyList();
- return this;
- }
-
- // optional .android.gltrace.GLMessage.DataType returnValue = 6;
- public boolean hasReturnValue() {
- return result.hasReturnValue();
- }
- public com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType getReturnValue() {
- return result.getReturnValue();
- }
- public Builder setReturnValue(com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType value) {
- if (value == null) {
- throw new NullPointerException();
- }
- result.hasReturnValue = true;
- result.returnValue_ = value;
- return this;
- }
- public Builder setReturnValue(com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.Builder builderForValue) {
- result.hasReturnValue = true;
- result.returnValue_ = builderForValue.build();
- return this;
- }
- public Builder mergeReturnValue(com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType value) {
- if (result.hasReturnValue() &&
- result.returnValue_ != com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.getDefaultInstance()) {
- result.returnValue_ =
- com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.newBuilder(result.returnValue_).mergeFrom(value).buildPartial();
- } else {
- result.returnValue_ = value;
- }
- result.hasReturnValue = true;
- return this;
- }
- public Builder clearReturnValue() {
- result.hasReturnValue = false;
- result.returnValue_ = com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.getDefaultInstance();
- return this;
- }
-
- // optional .android.gltrace.GLMessage.FrameBuffer fb = 7;
- public boolean hasFb() {
- return result.hasFb();
- }
- public com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer getFb() {
- return result.getFb();
- }
- public Builder setFb(com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer value) {
- if (value == null) {
- throw new NullPointerException();
- }
- result.hasFb = true;
- result.fb_ = value;
- return this;
- }
- public Builder setFb(com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer.Builder builderForValue) {
- result.hasFb = true;
- result.fb_ = builderForValue.build();
- return this;
- }
- public Builder mergeFb(com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer value) {
- if (result.hasFb() &&
- result.fb_ != com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer.getDefaultInstance()) {
- result.fb_ =
- com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer.newBuilder(result.fb_).mergeFrom(value).buildPartial();
- } else {
- result.fb_ = value;
- }
- result.hasFb = true;
- return this;
- }
- public Builder clearFb() {
- result.hasFb = false;
- result.fb_ = com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.FrameBuffer.getDefaultInstance();
- return this;
- }
-
- // optional int32 threadtime = 8;
- public boolean hasThreadtime() {
- return result.hasThreadtime();
- }
- public int getThreadtime() {
- return result.getThreadtime();
- }
- public Builder setThreadtime(int value) {
- result.hasThreadtime = true;
- result.threadtime_ = value;
- return this;
- }
- public Builder clearThreadtime() {
- result.hasThreadtime = false;
- result.threadtime_ = 0;
- return this;
- }
-
- // @@protoc_insertion_point(builder_scope:android.gltrace.GLMessage)
- }
-
- static {
- defaultInstance = new GLMessage(true);
- com.android.ide.eclipse.gltrace.GLProtoBuf.internalForceInit();
- defaultInstance.initFields();
- }
-
- // @@protoc_insertion_point(class_scope:android.gltrace.GLMessage)
- }
-
-
- static {
- }
-
- public static void internalForceInit() {}
-
- // @@protoc_insertion_point(outer_class_scope)
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GLTraceCollectorDialog.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GLTraceCollectorDialog.java
deleted file mode 100644
index 56dc8e9ac..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GLTraceCollectorDialog.java
+++ /dev/null
@@ -1,228 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace;
-
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.dialogs.TitleAreaDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.ProgressBar;
-import org.eclipse.swt.widgets.Shell;
-
-import java.io.IOException;
-import java.text.DecimalFormat;
-
-/** Dialog displayed while the trace is being streamed from device to host. */
-public class GLTraceCollectorDialog extends TitleAreaDialog {
- private static final String TITLE = "OpenGL ES Trace";
- private static final String DEFAULT_MESSAGE = "Trace collection in progress.";
- private static final DecimalFormat SIZE_FORMATTER = new DecimalFormat("#.##"); //$NON-NLS-1$
-
- private TraceOptions mTraceOptions;
- private final TraceFileWriter mTraceFileWriter;
- private final TraceCommandWriter mTraceCommandWriter;
-
- private Label mFramesCollectedLabel;
- private Label mTraceFileSizeLabel;
- private StatusRefreshTask mRefreshTask;
-
- protected GLTraceCollectorDialog(Shell parentShell, TraceFileWriter traceFileWriter,
- TraceCommandWriter traceCommandWriter, TraceOptions traceOptions) {
- super(parentShell);
- mTraceFileWriter = traceFileWriter;
- mTraceCommandWriter = traceCommandWriter;
- mTraceOptions = traceOptions;
- }
-
- @Override
- protected Control createButtonBar(Composite parent) {
- Composite c = new Composite(parent, SWT.NONE);
- c.setLayout(new GridLayout(0, false));
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalAlignment = GridData.CENTER;
- c.setLayoutData(gd);
-
- createButton(c, IDialogConstants.OK_ID, "Stop Tracing", true);
- return c;
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- parent.setLayout(new GridLayout());
-
- setTitle(TITLE);
- setMessage(DEFAULT_MESSAGE);
-
- Group controlGroup = new Group(parent, SWT.BORDER);
- controlGroup.setLayout(new GridLayout(2, false));
- controlGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- controlGroup.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_BLUE));
- controlGroup.setText("Trace Options");
-
- createLabel(controlGroup, "Collect Framebuffer contents on eglSwapBuffers()");
- final Button eglSwapCheckBox = createButton(controlGroup,
- mTraceOptions.collectFbOnEglSwap);
-
- createLabel(controlGroup, "Collect Framebuffer contents on glDraw*()");
- final Button glDrawCheckBox = createButton(controlGroup, mTraceOptions.collectFbOnGlDraw);
-
- createLabel(controlGroup, "Collect texture data for glTexImage*()");
- final Button glTexImageCheckBox = createButton(controlGroup,
- mTraceOptions.collectTextureData);
-
- SelectionListener l = new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent event) {
- boolean eglSwap = eglSwapCheckBox.getSelection();
- boolean glDraw = glDrawCheckBox.getSelection();
- boolean glTexImage = glTexImageCheckBox.getSelection();
-
- try {
- mTraceCommandWriter.setTraceOptions(eglSwap, glDraw, glTexImage);
- } catch (IOException e) {
- eglSwapCheckBox.setEnabled(false);
- glDrawCheckBox.setEnabled(false);
- glTexImageCheckBox.setEnabled(false);
-
- MessageDialog.openError(Display.getDefault().getActiveShell(),
- "OpenGL ES Trace",
- "Error while setting trace options: " + e.getMessage());
- }
-
- // update the text on the button
- if (!(event.getSource() instanceof Button)) {
- return;
- }
- Button sourceButton = (Button) event.getSource();
- sourceButton.setText(getToggleActionText(sourceButton.getSelection()));
- sourceButton.pack();
- }
- };
-
- eglSwapCheckBox.addSelectionListener(l);
- glDrawCheckBox.addSelectionListener(l);
- glTexImageCheckBox.addSelectionListener(l);
-
- Group statusGroup = new Group(parent, SWT.NONE);
- statusGroup.setLayout(new GridLayout(2, false));
- statusGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- statusGroup.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_BLUE));
- statusGroup.setText("Trace Status");
-
- createLabel(statusGroup, "Frames Collected:");
- mFramesCollectedLabel = createLabel(statusGroup, "");
-
- createLabel(statusGroup, "Trace File Size:");
- mTraceFileSizeLabel = createLabel(statusGroup, "");
-
- ProgressBar pb = new ProgressBar(statusGroup, SWT.INDETERMINATE);
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan = 2;
- pb.setLayoutData(gd);
-
- mRefreshTask = new StatusRefreshTask();
- new Thread(mRefreshTask, "Trace Status Refresh Thread").start();
-
- return super.createDialogArea(parent);
- }
-
- private Button createButton(Composite controlComposite, boolean selection) {
- Button b = new Button(controlComposite, SWT.TOGGLE);
- b.setText(getToggleActionText(selection));
- b.setSelection(selection);
- return b;
- }
-
- /** Get text to show on toggle box given its current selection. */
- private String getToggleActionText(boolean en) {
- return en ? "Disable" : "Enable";
- }
-
- private Label createLabel(Composite parent, String text) {
- Label l = new Label(parent, SWT.NONE);
- l.setText(text);
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalAlignment = SWT.LEFT;
- gd.verticalAlignment = SWT.CENTER;
- l.setLayoutData(gd);
-
- return l;
- }
-
- @Override
- protected void okPressed() {
- mRefreshTask.cancel();
- super.okPressed();
- }
-
- /** Periodically refresh the trace status. */
- private class StatusRefreshTask implements Runnable {
- private static final int REFRESH_INTERVAL = 1000;
- private volatile boolean mIsCancelled = false;
-
- @Override
- public void run() {
- if (mTraceFileWriter == null) {
- return;
- }
-
- while (!mIsCancelled) {
- final String frameCount = Integer.toString(mTraceFileWriter.getCurrentFrameCount());
-
- double fileSize = mTraceFileWriter.getCurrentFileSize();
- fileSize /= (1024 * 1024); // convert to size in MB
- final String frameSize = SIZE_FORMATTER.format(fileSize) + " MB";
-
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- if (mFramesCollectedLabel.isDisposed()) {
- return;
- }
-
- mFramesCollectedLabel.setText(frameCount);
- mTraceFileSizeLabel.setText(frameSize);
-
- mFramesCollectedLabel.pack();
- mTraceFileSizeLabel.pack();
- }
- });
-
- try {
- Thread.sleep(REFRESH_INTERVAL);
- } catch (InterruptedException e) {
- return;
- }
- }
- }
-
- public void cancel() {
- mIsCancelled = true;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GLTraceOptionsDialog.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GLTraceOptionsDialog.java
deleted file mode 100644
index b4de3d151..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GLTraceOptionsDialog.java
+++ /dev/null
@@ -1,403 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace;
-
-import com.android.ddmlib.AndroidDebugBridge;
-import com.android.ddmlib.IDevice;
-
-import org.eclipse.core.runtime.preferences.IEclipsePreferences;
-import org.eclipse.core.runtime.preferences.InstanceScope;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.TitleAreaDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-import org.osgi.service.prefs.BackingStoreException;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
-
-/** Dialog displaying all the trace options before the user initiates tracing. */
-public class GLTraceOptionsDialog extends TitleAreaDialog {
- private static final String TITLE = "OpenGL ES Trace Options";
- private static final String DEFAULT_MESSAGE = "Provide the application and activity to be traced.";
-
- private static final String PREF_APP_PACKAGE = "gl.trace.apppackage"; //$NON-NLS-1$
- private static final String PREF_ACTIVITY = "gl.trace.activity"; //$NON-NLS-1$
- private static final String PREF_TRACEFILE = "gl.trace.destfile"; //$NON-NLS-1$
- private static final String PREF_DEVICE = "gl.trace.device"; //$NON-NLS-1$
- private String mLastUsedDevice;
-
- private static String sSaveToFolder = System.getProperty("user.home"); //$NON-NLS-1$
-
- private Button mOkButton;
-
- private Combo mDeviceCombo;
- private Text mAppPackageToTraceText;
- private Text mActivityToTraceText;
- private Button mIsActivityFullyQualifiedButton;
- private Text mTraceFilePathText;
-
- private String mSelectedDevice = "";
- private String mAppPackageToTrace = "";
- private String mActivityToTrace = "";
- private String mTraceFilePath = "";
- private boolean mAllowAppSelection;
-
- private static boolean sCollectFbOnEglSwap = true;
- private static boolean sCollectFbOnGlDraw = false;
- private static boolean sCollectTextureData = false;
- private static boolean sIsActivityFullyQualified = false;
- private IDevice[] mDevices;
-
- public GLTraceOptionsDialog(Shell parentShell) {
- this(parentShell, true, null);
- }
-
- /**
- * Constructs a dialog displaying options for the tracer.
- * @param allowAppSelection true if user can change the application to trace
- * @param appToTrace default application package to trace
- */
- public GLTraceOptionsDialog(Shell parentShell, boolean allowAppSelection,
- String appToTrace) {
- super(parentShell);
- loadPreferences();
-
- mAllowAppSelection = allowAppSelection;
- if (appToTrace != null) {
- mAppPackageToTrace = appToTrace;
- }
- }
-
- @Override
- protected Control createDialogArea(Composite shell) {
- setTitle(TITLE);
- setMessage(DEFAULT_MESSAGE);
-
- Composite parent = (Composite) super.createDialogArea(shell);
- Composite c = new Composite(parent, SWT.BORDER);
- c.setLayout(new GridLayout(2, false));
- c.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- createLabel(c, "Device:");
- mDevices = AndroidDebugBridge.getBridge().getDevices();
- createDeviceDropdown(c, mDevices);
-
- createSeparator(c);
-
- createLabel(c, "Application Package:");
- createAppToTraceText(c, "e.g. com.example.package");
-
- createLabel(c, "Activity to launch:");
- createActivityToTraceText(c, "Leave blank to launch default activity");
-
- createLabel(c, "");
- createIsFullyQualifedActivityButton(c,
- "Activity name is fully qualified, do not prefix with package name");
-
- if (!mAllowAppSelection) {
- mAppPackageToTraceText.setEnabled(false);
- mActivityToTraceText.setEnabled(false);
- mIsActivityFullyQualifiedButton.setEnabled(false);
- }
-
- createSeparator(c);
-
- createLabel(c, "Data Collection Options:");
- createCaptureImageOptions(c);
-
- createSeparator(c);
-
- createLabel(c, "Destination File: ");
- createSaveToField(c);
-
- return c;
- }
-
- @Override
- protected void createButtonsForButtonBar(Composite parent) {
- super.createButtonsForButtonBar(parent);
-
- mOkButton = getButton(IDialogConstants.OK_ID);
- mOkButton.setText("Trace");
-
- DialogStatus status = validateDialog();
- mOkButton.setEnabled(status.valid);
- }
-
- private void createSeparator(Composite c) {
- Label l = new Label(c, SWT.SEPARATOR | SWT.HORIZONTAL);
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- gd.horizontalSpan = 2;
- l.setLayoutData(gd);
- }
-
- private void createSaveToField(Composite parent) {
- Composite c = new Composite(parent, SWT.NONE);
- c.setLayout(new GridLayout(2, false));
- c.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- mTraceFilePathText = new Text(c, SWT.BORDER);
- mTraceFilePathText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mTraceFilePathText.setText(mTraceFilePath);
- mTraceFilePathText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- validateAndSetMessage();
- }
- });
-
- Button browse = new Button(c, SWT.PUSH);
- browse.setText("Browse...");
- browse.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- String fName = openBrowseDialog();
- if (fName == null) {
- return;
- }
-
- mTraceFilePathText.setText(fName);
- validateAndSetMessage();
- }
- });
- }
-
- private String openBrowseDialog() {
- FileDialog fd = new FileDialog(Display.getDefault().getActiveShell(), SWT.SAVE);
-
- fd.setText("Save To");
- fd.setFileName("trace1.gltrace");
-
- fd.setFilterPath(sSaveToFolder);
- fd.setFilterExtensions(new String[] { "*.gltrace" });
-
- String fname = fd.open();
- if (fname == null || fname.trim().length() == 0) {
- return null;
- }
-
- sSaveToFolder = fd.getFilterPath();
- return fname;
- }
-
- /** Options controlling when the FB should be captured. */
- private void createCaptureImageOptions(Composite parent) {
- Composite c = new Composite(parent, SWT.NONE);
- c.setLayout(new GridLayout(1, false));
- c.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- final Button readFbOnEglSwapCheckBox = new Button(c, SWT.CHECK);
- readFbOnEglSwapCheckBox.setText("Read back framebuffer 0 on eglSwapBuffers()");
- readFbOnEglSwapCheckBox.setSelection(sCollectFbOnEglSwap);
-
- final Button readFbOnGlDrawCheckBox = new Button(c, SWT.CHECK);
- readFbOnGlDrawCheckBox.setText("Read back currently bound framebuffer On glDraw*()");
- readFbOnGlDrawCheckBox.setSelection(sCollectFbOnGlDraw);
-
- final Button readTextureDataCheckBox = new Button(c, SWT.CHECK);
- readTextureDataCheckBox.setText("Collect texture data submitted using glTexImage*()");
- readTextureDataCheckBox.setSelection(sCollectTextureData);
-
- SelectionListener l = new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- sCollectFbOnEglSwap = readFbOnEglSwapCheckBox.getSelection();
- sCollectFbOnGlDraw = readFbOnGlDrawCheckBox.getSelection();
- sCollectTextureData = readTextureDataCheckBox.getSelection();
- }
- };
-
- readFbOnEglSwapCheckBox.addSelectionListener(l);
- readFbOnGlDrawCheckBox.addSelectionListener(l);
- readTextureDataCheckBox.addSelectionListener(l);
- }
-
- private Text createAppToTraceText(Composite parent, String defaultMessage) {
- mAppPackageToTraceText = new Text(parent, SWT.BORDER);
- mAppPackageToTraceText.setMessage(defaultMessage);
- mAppPackageToTraceText.setText(mAppPackageToTrace);
-
- mAppPackageToTraceText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- mAppPackageToTraceText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- validateAndSetMessage();
- }
- });
-
- return mActivityToTraceText;
- }
-
- private Text createActivityToTraceText(Composite parent, String defaultMessage) {
- mActivityToTraceText = new Text(parent, SWT.BORDER);
- mActivityToTraceText.setMessage(defaultMessage);
- mActivityToTraceText.setText(mActivityToTrace);
-
- mActivityToTraceText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- mActivityToTraceText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- validateAndSetMessage();
- }
- });
-
- return mActivityToTraceText;
- }
-
- private Button createIsFullyQualifedActivityButton(Composite parent, String message) {
- mIsActivityFullyQualifiedButton = new Button(parent, SWT.CHECK);
- mIsActivityFullyQualifiedButton.setText(message);
- mIsActivityFullyQualifiedButton.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mIsActivityFullyQualifiedButton.setSelection(sIsActivityFullyQualified);
-
- return mIsActivityFullyQualifiedButton;
- }
-
- private void validateAndSetMessage() {
- DialogStatus status = validateDialog();
- mOkButton.setEnabled(status.valid);
- setErrorMessage(status.message);
- }
-
- private Combo createDeviceDropdown(Composite parent, IDevice[] devices) {
- mDeviceCombo = new Combo(parent, SWT.READ_ONLY | SWT.BORDER);
-
- List<String> items = new ArrayList<String>(devices.length);
- for (IDevice d : devices) {
- items.add(d.getName());
- }
- mDeviceCombo.setItems(items.toArray(new String[items.size()]));
-
- int index = 0;
- if (items.contains(mLastUsedDevice)) {
- index = items.indexOf(mLastUsedDevice);
- }
- if (index >= 0 && index < items.size()) {
- mDeviceCombo.select(index);
- }
- return mDeviceCombo;
- }
-
- private void createLabel(Composite parent, String text) {
- Label l = new Label(parent, SWT.NONE);
- l.setText(text);
- GridData gd = new GridData();
- gd.horizontalAlignment = SWT.RIGHT;
- gd.verticalAlignment = SWT.CENTER;
- l.setLayoutData(gd);
- }
-
- /**
- * A tuple that specifies whether the current state of the inputs
- * on the dialog is valid or not. If it is not valid, the message
- * field stores the reason why it isn't.
- */
- private final class DialogStatus {
- final boolean valid;
- final String message;
-
- private DialogStatus(boolean isValid, String errMessage) {
- valid = isValid;
- message = errMessage;
- }
- }
-
- private DialogStatus validateDialog() {
- if (mDevices.length == 0) {
- return new DialogStatus(false, "No connected devices.");
- }
-
- if (mAppPackageToTraceText.getText().trim().isEmpty()) {
- return new DialogStatus(false, "Provide an application name");
- }
-
- String traceFile = mTraceFilePathText.getText().trim();
- if (traceFile.isEmpty()) {
- return new DialogStatus(false, "Specify the location where the trace will be saved.");
- }
-
- File f = new File(traceFile).getParentFile();
- if (f != null && !f.exists()) {
- return new DialogStatus(false,
- String.format("Folder %s does not exist", f.getAbsolutePath()));
- }
-
- return new DialogStatus(true, null);
- }
-
- @Override
- protected void okPressed() {
- mAppPackageToTrace = mAppPackageToTraceText.getText().trim();
- mActivityToTrace = mActivityToTraceText.getText().trim();
- if (mActivityToTrace.startsWith(".")) { //$NON-NLS-1$
- mActivityToTrace = mActivityToTrace.substring(1);
- }
- sIsActivityFullyQualified = mIsActivityFullyQualifiedButton.getSelection();
- mTraceFilePath = mTraceFilePathText.getText().trim();
- mSelectedDevice = mDeviceCombo.getText();
-
- savePreferences();
-
- super.okPressed();
- }
-
- private void savePreferences() {
- IEclipsePreferences prefs = new InstanceScope().getNode(GlTracePlugin.PLUGIN_ID);
- prefs.put(PREF_APP_PACKAGE, mAppPackageToTrace);
- prefs.put(PREF_ACTIVITY, mActivityToTrace);
- prefs.put(PREF_TRACEFILE, mTraceFilePath);
- prefs.put(PREF_DEVICE, mSelectedDevice);
- try {
- prefs.flush();
- } catch (BackingStoreException e) {
- // ignore issues while persisting preferences
- }
- }
-
- private void loadPreferences() {
- IEclipsePreferences prefs = new InstanceScope().getNode(GlTracePlugin.PLUGIN_ID);
- mAppPackageToTrace = prefs.get(PREF_APP_PACKAGE, "");
- mActivityToTrace = prefs.get(PREF_ACTIVITY, "");
- mTraceFilePath = prefs.get(PREF_TRACEFILE, "");
- mLastUsedDevice = prefs.get(PREF_DEVICE, "");
- }
-
- public TraceOptions getTraceOptions() {
- return new TraceOptions(mSelectedDevice, mAppPackageToTrace, mActivityToTrace,
- sIsActivityFullyQualified, mTraceFilePath, sCollectFbOnEglSwap,
- sCollectFbOnGlDraw, sCollectTextureData);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GLTracePerspective.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GLTracePerspective.java
deleted file mode 100644
index 30bb1d532..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GLTracePerspective.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace;
-
-import com.android.ide.eclipse.gltrace.views.FrameSummaryView;
-import com.android.ide.eclipse.gltrace.views.StateView;
-import com.android.ide.eclipse.gltrace.views.detail.DetailsView;
-
-import org.eclipse.ui.IFolderLayout;
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IPerspectiveFactory;
-
-public class GLTracePerspective implements IPerspectiveFactory {
- private static final String STATE_FOLDER_ID = "stateFolder"; //$NON-NLS-1$
- private static final String FB_FOLDER_ID = "fbFolder"; //$NON-NLS-1$
- private static final String TEXTURE_VIEW_FOLDER_ID = "textureViewFolder"; //$NON-NLS-1$
-
- @Override
- public void createInitialLayout(IPageLayout layout) {
- // Create a 3 column layout
- // The first column contains the function trace in an editor.
- // The second column contains the GL State View.
- // The third column contains the texture view and the top and the framebuffer at the bottom.
-
- // Add the OpenGL state view to the right of the editor
- IFolderLayout column2 = layout.createFolder(STATE_FOLDER_ID, IPageLayout.RIGHT, 0.65f,
- layout.getEditorArea());
- column2.addView(StateView.ID);
-
- // Add the Texture View in the 3rd column
- IFolderLayout column3 = layout.createFolder(FB_FOLDER_ID, IPageLayout.RIGHT, 0.6f,
- STATE_FOLDER_ID);
- column3.addView(DetailsView.ID);
-
- // Add the OpenGL Framebuffer view below the texture view (bottom of 3rd column)
- IFolderLayout column3bottom = layout.createFolder(TEXTURE_VIEW_FOLDER_ID,
- IPageLayout.BOTTOM,
- 0.5f,
- FB_FOLDER_ID);
- column3bottom.addView(FrameSummaryView.ID);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GLUtils.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GLUtils.java
deleted file mode 100644
index 9e82768d5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GLUtils.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace;
-
-
-import java.nio.ByteBuffer;
-import java.nio.ByteOrder;
-import java.nio.FloatBuffer;
-import java.nio.IntBuffer;
-import java.nio.ShortBuffer;
-
-public class GLUtils {
- public static String formatData(byte[] data, GLEnum format) {
- switch (format) {
- case GL_BYTE:
- return formatBytes(data, false);
- case GL_UNSIGNED_BYTE:
- return formatBytes(data, true);
- case GL_SHORT:
- return formatShorts(data, false);
- case GL_UNSIGNED_SHORT:
- return formatShorts(data, true);
- case GL_FIXED:
- return formatInts(data);
- case GL_FLOAT:
- return formatFloats(data);
- default:
- return ""; //$NON-NLS-1$
- }
- }
-
- private static String formatFloats(byte[] data) {
- FloatBuffer bb = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).asFloatBuffer();
-
- StringBuilder sb = new StringBuilder(bb.capacity() * 3);
-
- while (bb.remaining() > 0) {
- sb.append(String.format("%.4f", bb.get()));
- sb.append(',');
- sb.append('\n');
- }
-
- return sb.toString();
- }
-
- private static String formatInts(byte[] data) {
- IntBuffer bb = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).asIntBuffer();
-
- StringBuilder sb = new StringBuilder(bb.capacity() * 3);
-
- while (bb.remaining() > 0) {
- sb.append(bb.get());
- sb.append(',');
- sb.append('\n');
- }
-
- return sb.toString();
- }
-
- private static String formatShorts(byte[] data, boolean unsigned) {
- ShortBuffer bb = ByteBuffer.wrap(data).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer();
-
- StringBuilder sb = new StringBuilder(bb.capacity() * 3);
-
- while (bb.remaining() > 0) {
- if (unsigned) {
- sb.append(bb.get() & 0xffff);
- } else {
- sb.append(bb.get());
- }
- sb.append(',');
- sb.append('\n');
- }
-
- return sb.toString();
- }
-
- private static String formatBytes(byte[] data, boolean unsigned) {
- ByteBuffer bb = ByteBuffer.wrap(data);
-
- StringBuilder sb = new StringBuilder(bb.capacity() * 3);
-
- while (bb.remaining() > 0) {
- if (unsigned) {
- sb.append(bb.get() & 0xff);
- } else {
- sb.append(bb.get());
- }
-
- sb.append(',');
- sb.append('\n');
- }
-
- return sb.toString();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GlTracePlugin.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GlTracePlugin.java
deleted file mode 100644
index a73b7f18f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/GlTracePlugin.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- ** Copyright 2011, The Android Open Source Project
- **
- ** Licensed under the Apache License, Version 2.0 (the "License");
- ** you may not use this file except in compliance with the License.
- ** You may obtain a copy of the License at
- **
- ** http://www.apache.org/licenses/LICENSE-2.0
- **
- ** Unless required by applicable law or agreed to in writing, software
- ** distributed under the License is distributed on an "AS IS" BASIS,
- ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ** See the License for the specific language governing permissions and
- ** limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.console.ConsolePlugin;
-import org.eclipse.ui.console.IConsole;
-import org.eclipse.ui.console.IConsoleConstants;
-import org.eclipse.ui.console.MessageConsole;
-import org.eclipse.ui.console.MessageConsoleStream;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.osgi.framework.BundleContext;
-
-/**
- * The activator class controls the plug-in life cycle
- */
-public class GlTracePlugin extends AbstractUIPlugin {
-
- // The plug-in ID
- public static final String PLUGIN_ID = "com.android.ide.eclipse.gldebugger"; //$NON-NLS-1$
-
- // The shared instance
- private static GlTracePlugin plugin;
-
- private MessageConsole mConsole;
- private MessageConsoleStream mConsoleStream;
-
- /**
- * The constructor
- */
- public GlTracePlugin() {
- }
-
- /*
- * (non-Javadoc)
- * @see
- * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
- * )
- */
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
- plugin = this;
-
- mConsole = new MessageConsole("OpenGL Trace View", null);
- ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[] {
- mConsole });
-
- mConsoleStream = mConsole.newMessageStream();
- }
-
- /*
- * (non-Javadoc)
- * @see
- * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
- * )
- */
- @Override
- public void stop(BundleContext context) throws Exception {
- plugin = null;
- super.stop(context);
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static GlTracePlugin getDefault() {
- return plugin;
- }
-
- /**
- * Returns an image descriptor for the image file at the given plug-in
- * relative path
- *
- * @param path the path
- * @return the image descriptor
- */
- public static ImageDescriptor getImageDescriptor(String path) {
- return imageDescriptorFromPlugin(PLUGIN_ID, path);
- }
-
- public void logMessage(String message) {
- mConsoleStream.println(message);
-
- Display.getDefault().asyncExec(sShowConsoleRunnable);
- }
-
- private static Runnable sShowConsoleRunnable = new Runnable() {
- @Override
- public void run() {
- showConsoleView();
- };
- };
-
- private static void showConsoleView() {
- IWorkbenchWindow w = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- if (w != null) {
- IWorkbenchPage page = w.getActivePage();
- if (page != null) {
- try {
- page.showView(IConsoleConstants.ID_CONSOLE_VIEW, null,
- IWorkbenchPage.VIEW_VISIBLE);
- } catch (PartInitException e) {
- // ignore
- }
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/OpenGLTraceAction.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/OpenGLTraceAction.java
deleted file mode 100644
index 6e232bb6c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/OpenGLTraceAction.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.ide.IDE;
-
-import java.io.File;
-
-public class OpenGLTraceAction implements IWorkbenchWindowActionDelegate {
- private static String sLoadFromFolder = System.getProperty("user.home");
-
- @Override
- public void run(IAction action) {
- openTrace();
- }
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
- }
-
- @Override
- public void dispose() {
- }
-
- @Override
- public void init(IWorkbenchWindow window) {
- }
-
- private void openTrace() {
- Shell shell = Display.getDefault().getActiveShell();
- FileDialog fd = new FileDialog(shell, SWT.OPEN);
-
- fd.setText("Open Trace File");
- fd.setFilterPath(sLoadFromFolder);
- fd.setFilterExtensions(new String[] { "*.gltrace" });
-
- String fname = fd.open();
- if (fname == null || fname.trim().length() == 0) {
- return;
- }
-
- sLoadFromFolder = new File(fname).getParent().toString();
-
- openEditorFor(fname);
- }
-
- private void openEditorFor(String fname) {
- IFileStore fileStore = EFS.getLocalFileSystem().getStore(new Path(fname));
- IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
-
- try {
- IDE.openEditorOnFileStore( page, fileStore );
- } catch (PartInitException e) {
- MessageDialog.openError(Display.getDefault().getActiveShell(),
- "Error opening GL Trace File",
- "Unexpected error while opening GL Trace file: " + e.getMessage());
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/ProtoBufUtils.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/ProtoBufUtils.java
deleted file mode 100644
index 074e4409e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/ProtoBufUtils.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace;
-
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage;
-
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.ImageData;
-import org.eclipse.swt.graphics.PaletteData;
-import org.eclipse.swt.widgets.Display;
-import org.liblzf.CLZF;
-
-/** Utilities to deal with protobuf encoded {@link GLMessage}. */
-public class ProtoBufUtils {
- private static ImageData getImageData(GLMessage glMsg) {
- int width = glMsg.getFb().getWidth();
- int height = glMsg.getFb().getHeight();
-
- if (width * height == 0) {
- return null;
- }
-
- byte[] compressed = glMsg.getFb().getContents(0).toByteArray();
- byte[] uncompressed = new byte[width * height * 4];
-
- int size = CLZF.lzf_decompress(compressed, compressed.length,
- uncompressed, uncompressed.length);
- assert size == width * height * 4 : "Unexpected image size after decompression.";
-
- int redMask = 0xff000000;
- int greenMask = 0x00ff0000;
- int blueMask = 0x0000ff00;
- PaletteData palette = new PaletteData(redMask, greenMask, blueMask);
- ImageData imageData = new ImageData(
- width,
- height,
- 32, // depth
- palette,
- 1, // scan line padding
- uncompressed);
- byte[] alpha = new byte[width*height];
- for (int i = 0; i < width * height; i++) {
- alpha[i] = uncompressed[i * 4 + 3];
- }
- imageData.alphaData = alpha;
-
- imageData = imageData.scaledTo(imageData.width, -imageData.height);
- return imageData;
- }
-
- /** Obtains the image stored in provided protocol buffer message. */
- public static Image getImage(Display display, GLMessage glMsg) {
- if (!glMsg.hasFb()) {
- return null;
- }
-
- ImageData imageData = null;
- try {
- imageData = getImageData(glMsg);
- } catch (Exception e) {
- GlTracePlugin.getDefault().logMessage(
- "Unexpected error while retrieving framebuffer image: " + e);
- return null;
- }
-
- if (imageData == null) {
- return null;
- }
-
- return new Image(display, imageData);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/SwtUtils.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/SwtUtils.java
deleted file mode 100644
index a7c960dfc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/SwtUtils.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace;
-
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.widgets.Control;
-
-public class SwtUtils {
- /** Minimum Character width in pixels. */
- private static final int MIN_CHAR_WIDTH = 10;
-
- /** Returns the font width if it is greater than {@link #MIN_CHAR_WIDTH}. */
- public static int getApproximateFontWidth(Control c) {
- GC gc = new GC(c);
- int avgCharWidth = gc.getFontMetrics().getAverageCharWidth();
- gc.dispose();
- return Math.max(avgCharWidth, MIN_CHAR_WIDTH);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/TraceCommandWriter.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/TraceCommandWriter.java
deleted file mode 100644
index dd5cd3c1e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/TraceCommandWriter.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace;
-
-import java.io.DataOutputStream;
-import java.io.IOException;
-
-/**
- * Write trace control options to the trace backend.
- * Currently, the number of options is limited, so all the options are packed into a
- * single integer. Any changes to this protocol have to be updated on the device as well.
- */
-public class TraceCommandWriter {
- private static final int CMD_SIZE = 4;
-
- private static final int READ_FB_ON_EGLSWAP_BIT = 0;
- private static final int READ_FB_ON_GLDRAW_BIT = 1;
- private static final int READ_TEXTURE_DATA_ON_GLTEXIMAGE_BIT = 2;
-
- private final DataOutputStream mStream;;
-
- public TraceCommandWriter(DataOutputStream traceCommandStream) {
- mStream = traceCommandStream;
- }
-
- public void setTraceOptions(boolean readFbOnEglSwap, boolean readFbOnGlDraw,
- boolean readTextureOnGlTexImage) throws IOException {
- int eglSwap = readFbOnEglSwap ? (1 << READ_FB_ON_EGLSWAP_BIT) : 0;
- int glDraw = readFbOnGlDraw ? (1 << READ_FB_ON_GLDRAW_BIT) : 0;
- int tex = readTextureOnGlTexImage ? ( 1 << READ_TEXTURE_DATA_ON_GLTEXIMAGE_BIT) : 0;
-
- int cmd = eglSwap | glDraw | tex;
-
- mStream.writeInt(CMD_SIZE);
- mStream.writeInt(cmd);
- mStream.flush();
- }
-
- public void close() {
- try {
- mStream.close();
- } catch (IOException e) {
- // ignore exception while closing stream
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/TraceFileInfo.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/TraceFileInfo.java
deleted file mode 100644
index 80933b02e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/TraceFileInfo.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace;
-
-public class TraceFileInfo {
- private final String mPath;
- private final long mSize;
- private final long mLastModified;
-
- public TraceFileInfo(String path, long size, long lastModified) {
- mPath = path;
- mSize = size;
- mLastModified = lastModified;
- }
-
- public String getPath() {
- return mPath;
- }
-
- public long getSize() {
- return mSize;
- }
-
- public long getLastModificationTime() {
- return mLastModified;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/TraceFileParserTask.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/TraceFileParserTask.java
deleted file mode 100644
index b90c004b0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/TraceFileParserTask.java
+++ /dev/null
@@ -1,254 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace;
-
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage;
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.Function;
-import com.android.ide.eclipse.gltrace.format.GLAPISpec;
-import com.android.ide.eclipse.gltrace.format.GLMessageFormatter;
-import com.android.ide.eclipse.gltrace.model.GLCall;
-import com.android.ide.eclipse.gltrace.model.GLFrame;
-import com.android.ide.eclipse.gltrace.model.GLTrace;
-import com.android.ide.eclipse.gltrace.state.transforms.StateTransformFactory;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.RandomAccessFile;
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
-import java.util.Set;
-import java.util.TreeSet;
-
-public class TraceFileParserTask implements IRunnableWithProgress {
- private static final TraceFileReader sReader = new TraceFileReader();
-
- private static final GLMessageFormatter sGLMessageFormatter =
- new GLMessageFormatter(GLAPISpec.getSpecs());
-
- private String mTraceFilePath;
- private RandomAccessFile mFile;
-
- private List<GLCall> mGLCalls;
- private Set<Integer> mGLContextIds;
-
- private GLTrace mTrace;
-
- /**
- * Construct a GL Trace file parser.
- * @param path path to trace file
- */
- public TraceFileParserTask(String path) {
- try {
- mFile = new RandomAccessFile(path, "r"); //$NON-NLS-1$
- } catch (FileNotFoundException e) {
- throw new IllegalArgumentException(e);
- }
-
- mTraceFilePath = path;
- mGLCalls = new ArrayList<GLCall>();
- mGLContextIds = new TreeSet<Integer>();
- }
-
- private void addMessage(int index, long traceFileOffset, GLMessage msg, long startTime) {
- String formattedMsg;
- try {
- formattedMsg = sGLMessageFormatter.formatGLMessage(msg);
- } catch (Exception e) {
- formattedMsg = String.format("%s()", msg.getFunction().toString()); //$NON-NLS-1$
- }
-
- GLCall c = new GLCall(index,
- startTime,
- traceFileOffset,
- formattedMsg,
- msg.getFunction(),
- msg.hasFb(),
- msg.getContextId(),
- msg.getDuration(),
- msg.getThreadtime());
-
- addProperties(c, msg);
-
- try {
- c.setStateTransformations(StateTransformFactory.getTransformsFor(msg));
- } catch (Exception e) {
- c.setStateTransformationCreationError(e.getMessage());
- GlTracePlugin.getDefault().logMessage("Error while creating transformations for "
- + c.toString() + ":");
- GlTracePlugin.getDefault().logMessage(e.getMessage());
- }
-
- mGLCalls.add(c);
- mGLContextIds.add(Integer.valueOf(c.getContextId()));
- }
-
- /** Save important values from the {@link GLMessage} in the {@link GLCall} as properties. */
- private void addProperties(GLCall c, GLMessage msg) {
- switch (msg.getFunction()) {
- case glPushGroupMarkerEXT:
- // void PushGroupMarkerEXT(sizei length, const char *marker);
- // save the marker name
- c.addProperty(GLCall.PROPERTY_MARKERNAME,
- msg.getArgs(1).getCharValue(0).toStringUtf8());
- break;
- case glVertexAttribPointerData:
- // void glVertexAttribPointerData(GLuint indx, GLint size, GLenum type,
- // GLboolean normalized, GLsizei stride, const GLvoid* ptr,
- // int minIndex, int maxIndex)
- c.addProperty(GLCall.PROPERTY_VERTEX_ATTRIB_POINTER_SIZE,
- Integer.valueOf(msg.getArgs(1).getIntValue(0)));
- c.addProperty(GLCall.PROPERTY_VERTEX_ATTRIB_POINTER_TYPE,
- GLEnum.valueOf(msg.getArgs(2).getIntValue(0)));
- c.addProperty(GLCall.PROPERTY_VERTEX_ATTRIB_POINTER_DATA,
- msg.getArgs(5).getRawBytes(0).toByteArray());
- break;
- default:
- break;
- }
- }
-
- /**
- * Parse the entire file and create a {@link GLTrace} object that can be retrieved
- * using {@link #getTrace()}.
- */
- @Override
- public void run(IProgressMonitor monitor) throws InvocationTargetException,
- InterruptedException {
- long fileLength;
- try {
- fileLength = mFile.length();
- } catch (IOException e1) {
- fileLength = 0;
- }
-
- monitor.beginTask("Parsing OpenGL Trace File",
- fileLength > 0 ? 100 : IProgressMonitor.UNKNOWN);
-
- List<GLFrame> glFrames = null;
-
- try {
- GLMessage msg = null;
- int msgCount = 0;
- long filePointer = mFile.getFilePointer();
- int percentParsed = 0;
-
- // counters that maintain some statistics about the trace messages
- long minTraceStartTime = Long.MAX_VALUE;
-
- while ((msg = sReader.getMessageAtOffset(mFile, -1)) != null) {
- if (minTraceStartTime > msg.getStartTime()) {
- minTraceStartTime = msg.getStartTime();
- }
-
- addMessage(msgCount, filePointer, msg, msg.getStartTime() - minTraceStartTime);
-
- filePointer = mFile.getFilePointer();
- msgCount++;
-
- if (monitor.isCanceled()) {
- throw new InterruptedException();
- }
-
- if (fileLength > 0) {
- int percentParsedNow = (int)((filePointer * 100) / fileLength);
- monitor.worked(percentParsedNow - percentParsed);
- percentParsed = percentParsedNow;
- }
- }
-
- if (mGLContextIds.size() > 1) {
- // if there are multiple contexts, then the calls may arrive at the
- // host out of order. So we perform a sort based on the invocation time.
- Collections.sort(mGLCalls, new Comparator<GLCall>() {
- @Override
- public int compare(GLCall c1, GLCall c2) {
- long diff = (c1.getStartTime() - c2.getStartTime());
-
- // We could return diff casted to an int. But in Java, casting
- // from a long to an int truncates the bits and will not preserve
- // the sign. So we resort to comparing the diff to 0 and returning
- // the sign.
- if (diff == 0) {
- return 0;
- } else if (diff > 0) {
- return 1;
- } else {
- return -1;
- }
- }
- });
-
- // reassign indices after sorting
- for (int i = 0; i < mGLCalls.size(); i++) {
- mGLCalls.get(i).setIndex(i);
- }
- }
-
- glFrames = createFrames(mGLCalls);
- } catch (Exception e) {
- throw new InvocationTargetException(e);
- } finally {
- try {
- mFile.close();
- } catch (IOException e) {
- // ignore exception while closing file
- }
- monitor.done();
- }
-
- File f = new File(mTraceFilePath);
- TraceFileInfo fileInfo = new TraceFileInfo(mTraceFilePath, f.length(), f.lastModified());
- mTrace = new GLTrace(fileInfo, glFrames, mGLCalls, new ArrayList<Integer>(mGLContextIds));
- }
-
- /** Assign GL calls to GL Frames. */
- private List<GLFrame> createFrames(List<GLCall> calls) {
- List<GLFrame> glFrames = new ArrayList<GLFrame>();
- int startCallIndex = 0;
- int frameIndex = 0;
-
- for (int i = 0; i < calls.size(); i++) {
- GLCall c = calls.get(i);
- if (c.getFunction() == Function.eglSwapBuffers) {
- glFrames.add(new GLFrame(frameIndex, startCallIndex, i + 1));
- startCallIndex = i + 1;
- frameIndex++;
- }
- }
-
- // assign left over calls at the end to the last frame
- if (startCallIndex != mGLCalls.size()) {
- glFrames.add(new GLFrame(frameIndex, startCallIndex, mGLCalls.size()));
- }
-
- return glFrames;
- }
-
- /**
- * Retrieve the trace object constructed from messages in the trace file.
- */
- public GLTrace getTrace() {
- return mTrace;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/TraceFileReader.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/TraceFileReader.java
deleted file mode 100644
index 76b32b099..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/TraceFileReader.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace;
-
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage;
-import com.google.protobuf.InvalidProtocolBufferException;
-
-import java.io.EOFException;
-import java.io.IOException;
-import java.io.RandomAccessFile;
-
-public class TraceFileReader {
- /** Maximum size for a protocol buffer message.
- * The message size is dominated by the size of the compressed framebuffer.
- * Currently, we assume that the maximum is for a 1080p display. Since the buffers compress
- * well, we should probably never get close to this.
- */
- private static final int MAX_PROTOBUF_SIZE = 1920 * 1080 * 100;
-
- /**
- * Obtain the next protobuf message in this file.
- * @param file file to read from
- * @param offset offset to start reading from
- * @return protobuf message at given offset
- * @throws IOException in case of file I/O errors
- * @throws InvalidProtocolBufferException if protobuf is not well formed
- */
- public GLMessage getMessageAtOffset(RandomAccessFile file, long offset) throws IOException {
- int len;
- byte[] b;
- try {
- if (offset != -1) {
- file.seek(offset);
- }
-
- len = file.readInt();
- if (len > MAX_PROTOBUF_SIZE) {
- String msg = String.format(
- "Unexpectedly large (%d bytes) protocol buffer message encountered.",
- len);
- throw new InvalidProtocolBufferException(msg);
- }
-
- b = new byte[len];
- file.readFully(b);
- } catch (EOFException e) {
- return null;
- }
-
- return GLMessage.parseFrom(b);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/TraceFileWriter.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/TraceFileWriter.java
deleted file mode 100644
index 0be05aee2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/TraceFileWriter.java
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace;
-
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage;
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.Function;
-import com.google.protobuf.InvalidProtocolBufferException;
-
-import java.io.DataInputStream;
-import java.io.DataOutputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-
-/** A class that streams data received from a socket into the trace file. */
-public class TraceFileWriter {
- private DataInputStream mInputStream;
- private DataOutputStream mOutputStream;
- private Thread mReceiverThread;
-
- private int mFileSize = 0;
- private int mFrameCount = 0;
-
- /**
- * Construct a trace file writer.
- * @param fos output stream to write trace data to
- * @param is input stream from which trace data is read
- */
- public TraceFileWriter(FileOutputStream fos, DataInputStream is) {
- mOutputStream = new DataOutputStream(fos);
- mInputStream = is;
- }
-
- public void start() {
- // launch thread
- mReceiverThread = new Thread(new GLTraceReceiverTask());
- mReceiverThread.setName("GL Trace Receiver");
- mReceiverThread.start();
- }
-
- public void stopTracing() {
- // close socket to stop the receiver thread
- try {
- mInputStream.close();
- } catch (IOException e) {
- // ignore exception while closing socket
- }
-
- // wait for receiver to complete
- try {
- mReceiverThread.join();
- } catch (InterruptedException e1) {
- // ignore, this cannot be interrupted
- }
-
- // close stream
- try {
- mOutputStream.close();
- } catch (IOException e) {
- // ignore error while closing stream
- }
- }
-
- /**
- * The GLTraceReceiverTask collects trace data from the device and writes it
- * into a file while collecting some stats on the way.
- */
- private class GLTraceReceiverTask implements Runnable {
- @Override
- public void run() {
- while (true) {
- byte[] buffer = readTraceData(mInputStream);
- if (buffer == null) {
- break;
- }
-
- try {
- writeTraceData(buffer, mOutputStream);
- } catch (IOException e) {
- break;
- }
-
- updateTraceStats(buffer);
- }
- }
- }
-
- private byte[] readTraceData(DataInputStream dis) {
- int len;
- try {
- len = dis.readInt();
- } catch (IOException e1) {
- return null;
- }
- len = Integer.reverseBytes(len); // readInt is big endian, we want little endian
-
- byte[] buffer = new byte[len];
- int readLen = 0;
- while (readLen < len) {
- try {
- int read = dis.read(buffer, readLen, len - readLen);
- if (read < 0) {
- return null;
- } else {
- readLen += read;
- }
- } catch (IOException e) {
- return null;
- }
- }
-
- return buffer;
- }
-
-
- private void writeTraceData(byte[] buffer, DataOutputStream stream) throws IOException {
- stream.writeInt(buffer.length);
- stream.write(buffer);
- }
-
- private void updateTraceStats(byte[] buffer) {
- GLMessage msg = null;
- try {
- msg = GLMessage.parseFrom(buffer);
- } catch (InvalidProtocolBufferException e) {
- return;
- }
-
- mFileSize += buffer.length;
-
- if (msg.getFunction() == Function.eglSwapBuffers) {
- mFrameCount++;
- }
- }
-
- public int getCurrentFileSize() {
- return mFileSize;
- }
-
- public int getCurrentFrameCount() {
- return mFrameCount;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/TraceOptions.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/TraceOptions.java
deleted file mode 100644
index ac9fb6b5c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/TraceOptions.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace;
-
-public class TraceOptions {
- /** Device on which the application should be run. */
- public final String device;
-
- /** Application to trace. */
- public final String appToTrace;
-
- /** Activity to trace. */
- public final String activityToTrace;
-
- public final boolean isActivityNameFullyQualified;
-
- /** Path where the trace file should be saved. */
- public final String traceDestination;
-
- /** Flag indicating whether Framebuffer should be captured on eglSwap() */
- public final boolean collectFbOnEglSwap;
-
- /** Flag indicating whether Framebuffer should be captured on glDraw*() */
- public final boolean collectFbOnGlDraw;
-
- /** Flag indicating whether texture data should be captured on glTexImage*() */
- public final boolean collectTextureData;
-
- public TraceOptions(String device, String appPackage, String activity,
- boolean isActivityNameFullyQualified, String destinationPath,
- boolean collectFbOnEglSwap, boolean collectFbOnGlDraw, boolean collectTextureData) {
- this.device = device;
- this.appToTrace = appPackage;
- this.activityToTrace = activity;
- this.isActivityNameFullyQualified = isActivityNameFullyQualified;
- this.traceDestination = destinationPath;
- this.collectFbOnEglSwap = collectFbOnEglSwap;
- this.collectFbOnGlDraw = collectFbOnGlDraw;
- this.collectTextureData = collectTextureData;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/editors/DurationMinimap.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/editors/DurationMinimap.java
deleted file mode 100644
index 9b4c57cad..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/editors/DurationMinimap.java
+++ /dev/null
@@ -1,541 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.editors;
-
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.Function;
-import com.android.ide.eclipse.gltrace.model.GLCall;
-import com.android.ide.eclipse.gltrace.model.GLTrace;
-
-import org.eclipse.jface.resource.FontRegistry;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.MouseAdapter;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.events.MouseMoveListener;
-import org.eclipse.swt.events.MouseTrackListener;
-import org.eclipse.swt.events.PaintEvent;
-import org.eclipse.swt.events.PaintListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.FontData;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Canvas;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Listener;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class DurationMinimap extends Canvas {
- /** Default alpha value. */
- private static final int DEFAULT_ALPHA = 255;
-
- /** Alpha value for highlighting visible calls. */
- private static final int VISIBLE_CALLS_HIGHLIGHT_ALPHA = 50;
-
- /** Clamp call durations at this value. */
- private static final long CALL_DURATION_CLAMP = 20000;
-
- private static final String FONT_KEY = "default.font"; //$NON-NLS-1$
-
- /** Scale font size by this amount to get the max display length of call duration. */
- private static final int MAX_DURATION_LENGTH_SCALE = 6;
-
- /** List of GL Calls in the trace. */
- private List<GLCall> mCalls;
-
- /** Number of GL contexts in the trace. */
- private int mContextCount;
-
- /** Starting call index of currently displayed frame. */
- private int mStartCallIndex;
-
- /** Ending call index of currently displayed frame. */
- private int mEndCallIndex;
-
- /** The top index that is currently visible in the table. */
- private int mVisibleCallTopIndex;
-
- /** The bottom index that is currently visible in the table. */
- private int mVisibleCallBottomIndex;
-
- private Color mBackgroundColor;
- private Color mDurationLineColor;
- private Color mGlDrawColor;
- private Color mGlErrorColor;
- private Color mContextHeaderColor;
- private Color mVisibleCallsHighlightColor;
- private Color mMouseMarkerColor;
-
- private FontRegistry mFontRegistry;
- private int mFontWidth;
- private int mFontHeight;
-
- // back buffers used for double buffering
- private Image mBackBufferImage;
- private GC mBackBufferGC;
-
- // mouse state
- private boolean mMouseInSelf;
- private int mMouseY;
-
- // helper object used to position various items on screen
- private final PositionHelper mPositionHelper;
-
- public DurationMinimap(Composite parent, GLTrace trace) {
- super(parent, SWT.NO_BACKGROUND);
-
- setInput(trace);
-
- initializeColors();
- initializeFonts();
-
- mPositionHelper = new PositionHelper(
- mFontHeight,
- mContextCount,
- mFontWidth * MAX_DURATION_LENGTH_SCALE, /* max display length for call. */
- CALL_DURATION_CLAMP /* max duration */);
-
- addPaintListener(new PaintListener() {
- @Override
- public void paintControl(PaintEvent e) {
- draw(e.display, e.gc);
- }
- });
-
- addListener(SWT.Resize, new Listener() {
- @Override
- public void handleEvent(Event event) {
- controlResized();
- }
- });
-
- addMouseMoveListener(new MouseMoveListener() {
- @Override
- public void mouseMove(MouseEvent e) {
- mouseMoved(e);
- }
- });
-
- addMouseListener(new MouseAdapter() {
- @Override
- public void mouseUp(MouseEvent e) {
- mouseClicked(e);
- }
- });
-
- addMouseTrackListener(new MouseTrackListener() {
- @Override
- public void mouseHover(MouseEvent e) {
- }
-
- @Override
- public void mouseExit(MouseEvent e) {
- mMouseInSelf = false;
- redraw();
- }
-
- @Override
- public void mouseEnter(MouseEvent e) {
- mMouseInSelf = true;
- redraw();
- }
- });
- }
-
- public void setInput(GLTrace trace) {
- if (trace != null) {
- mCalls = trace.getGLCalls();
- mContextCount = trace.getContexts().size();
- } else {
- mCalls = null;
- mContextCount = 1;
- }
- }
-
- @Override
- public void dispose() {
- disposeColors();
- disposeBackBuffer();
- super.dispose();
- }
-
- private void initializeColors() {
- mBackgroundColor = new Color(getDisplay(), 0x33, 0x33, 0x33);
- mDurationLineColor = new Color(getDisplay(), 0x08, 0x51, 0x9c);
- mGlDrawColor = new Color(getDisplay(), 0x6b, 0xae, 0xd6);
- mContextHeaderColor = new Color(getDisplay(), 0xd1, 0xe5, 0xf0);
- mVisibleCallsHighlightColor = new Color(getDisplay(), 0xcc, 0xcc, 0xcc);
- mMouseMarkerColor = new Color(getDisplay(), 0xaa, 0xaa, 0xaa);
-
- mGlErrorColor = getDisplay().getSystemColor(SWT.COLOR_RED);
- }
-
- private void disposeColors() {
- mBackgroundColor.dispose();
- mDurationLineColor.dispose();
- mGlDrawColor.dispose();
- mContextHeaderColor.dispose();
- mVisibleCallsHighlightColor.dispose();
- mMouseMarkerColor.dispose();
- }
-
- private void initializeFonts() {
- mFontRegistry = new FontRegistry(getDisplay());
- mFontRegistry.put(FONT_KEY,
- new FontData[] { new FontData("Arial", 8, SWT.NORMAL) }); //$NON-NLS-1$
-
- GC gc = new GC(getDisplay());
- gc.setFont(mFontRegistry.get(FONT_KEY));
- mFontWidth = gc.getFontMetrics().getAverageCharWidth();
- mFontHeight = gc.getFontMetrics().getHeight();
- gc.dispose();
- }
-
- private void initializeBackBuffer() {
- Rectangle clientArea = getClientArea();
-
- if (clientArea.width == 0 || clientArea.height == 0) {
- mBackBufferImage = null;
- mBackBufferGC = null;
- return;
- }
-
- mBackBufferImage = new Image(getDisplay(),
- clientArea.width,
- clientArea.height);
- mBackBufferGC = new GC(mBackBufferImage);
- }
-
- private void disposeBackBuffer() {
- if (mBackBufferImage != null) {
- mBackBufferImage.dispose();
- mBackBufferImage = null;
- }
-
- if (mBackBufferGC != null) {
- mBackBufferGC.dispose();
- mBackBufferGC = null;
- }
- }
-
- private void mouseMoved(MouseEvent e) {
- mMouseY = e.y;
- redraw();
- }
-
- private void mouseClicked(MouseEvent e) {
- if (mMouseInSelf) {
- int selIndex = mPositionHelper.getCallAt(mMouseY);
- sendCallSelectedEvent(selIndex);
- redraw();
- }
- }
-
- private void draw(Display display, GC gc) {
- if (mBackBufferImage == null) {
- initializeBackBuffer();
- }
-
- if (mBackBufferImage == null) {
- return;
- }
-
- // draw contents onto the back buffer
- drawBackground(mBackBufferGC, mBackBufferImage.getBounds());
- drawContextHeaders(mBackBufferGC);
- drawCallDurations(mBackBufferGC);
- drawVisibleCallHighlights(mBackBufferGC);
- drawMouseMarkers(mBackBufferGC);
-
- // finally copy over the rendered back buffer onto screen
- int width = getClientArea().width;
- int height = getClientArea().height;
- gc.drawImage(mBackBufferImage,
- 0, 0, width, height,
- 0, 0, width, height);
- }
-
- private void drawBackground(GC gc, Rectangle bounds) {
- gc.setBackground(mBackgroundColor);
- gc.fillRectangle(bounds);
- }
-
- private void drawContextHeaders(GC gc) {
- if (mContextCount <= 1) {
- return;
- }
-
- gc.setForeground(mContextHeaderColor);
- gc.setFont(mFontRegistry.get(FONT_KEY));
- for (int i = 0; i < mContextCount; i++) {
- Point p = mPositionHelper.getHeaderLocation(i);
- gc.drawText("CTX" + Integer.toString(i), p.x, p.y);
- }
- }
-
- /** Draw the call durations as a sequence of lines.
- *
- * Calls are arranged on the y-axis based on the sequence in which they were originally
- * called by the application. If the display height is lesser than the number of calls, then
- * not every call is shown - the calls are underscanned based the height of the display.
- *
- * The x-axis shows two pieces of information: the duration of the call, and the context
- * in which the call was made. The duration controls how long the displayed line is, and
- * the context controls the starting offset of the line.
- */
- private void drawCallDurations(GC gc) {
- if (mCalls == null || mCalls.size() < mEndCallIndex) {
- return;
- }
-
- gc.setBackground(mDurationLineColor);
-
- int callUnderScan = mPositionHelper.getCallUnderScanValue();
- for (int i = mStartCallIndex; i < mEndCallIndex; i += callUnderScan) {
- boolean resetColor = false;
- GLCall c = mCalls.get(i);
-
- long duration = c.getWallDuration();
-
- if (c.hasErrors()) {
- gc.setBackground(mGlErrorColor);
- resetColor = true;
-
- // If the call has any errors, we want it to be visible in the minimap
- // regardless of how long it took.
- duration = mPositionHelper.getMaxDuration();
- } else if (c.getFunction() == Function.glDrawArrays
- || c.getFunction() == Function.glDrawElements
- || c.getFunction() == Function.eglSwapBuffers) {
- gc.setBackground(mGlDrawColor);
- resetColor = true;
-
- // render all draw calls & swap buffer at max length
- duration = mPositionHelper.getMaxDuration();
- }
-
- Rectangle bounds = mPositionHelper.getDurationBounds(
- i - mStartCallIndex,
- c.getContextId(),
- duration);
- gc.fillRectangle(bounds);
-
- if (resetColor) {
- gc.setBackground(mDurationLineColor);
- }
- }
- }
-
- /**
- * Draw a bounding box that highlights the currently visible range of calls in the
- * {@link GLFunctionTraceViewer} table.
- */
- private void drawVisibleCallHighlights(GC gc) {
- gc.setAlpha(VISIBLE_CALLS_HIGHLIGHT_ALPHA);
- gc.setBackground(mVisibleCallsHighlightColor);
- gc.fillRectangle(mPositionHelper.getBoundsFramingCalls(
- mVisibleCallTopIndex - mStartCallIndex,
- mVisibleCallBottomIndex - mStartCallIndex));
- gc.setAlpha(DEFAULT_ALPHA);
- }
-
- private void drawMouseMarkers(GC gc) {
- if (!mMouseInSelf) {
- return;
- }
-
- if (mPositionHelper.getCallAt(mMouseY) < 0) {
- return;
- }
-
- gc.setForeground(mMouseMarkerColor);
- gc.drawLine(0, mMouseY, getClientArea().width, mMouseY);
- }
-
- private void controlResized() {
- // regenerate back buffer on size changes
- disposeBackBuffer();
- initializeBackBuffer();
-
- redraw();
- }
-
- public int getMinimumWidth() {
- return mPositionHelper.getMinimumWidth();
- }
-
- /** Set the GL Call start and end indices for currently displayed frame. */
- public void setCallRangeForCurrentFrame(int startCallIndex, int endCallIndex) {
- mStartCallIndex = startCallIndex;
- mEndCallIndex = endCallIndex;
- mPositionHelper.updateCallDensity(mEndCallIndex - mStartCallIndex, getClientArea().height);
- redraw();
- }
-
- /**
- * Set the call range that is currently visible in the {@link GLFunctionTraceViewer} table.
- * @param visibleTopIndex index of call currently visible at the top of the table.
- * @param visibleBottomIndex index of call currently visible at the bottom of the table.
- */
- public void setVisibleCallRange(int visibleTopIndex, int visibleBottomIndex) {
- mVisibleCallTopIndex = visibleTopIndex;
- mVisibleCallBottomIndex = visibleBottomIndex;
- redraw();
- }
-
- public interface ICallSelectionListener {
- void callSelected(int selectedCallIndex);
- }
-
- private List<ICallSelectionListener> mListeners = new ArrayList<ICallSelectionListener>();
-
- public void addCallSelectionListener(ICallSelectionListener l) {
- mListeners.add(l);
- }
-
- private void sendCallSelectedEvent(int selectedCall) {
- for (ICallSelectionListener l : mListeners) {
- l.callSelected(selectedCall);
- }
- }
-
- /** Utility class to help with the positioning and sizes of elements in the canvas. */
- private static class PositionHelper {
- /** Left Margin after which duration lines are drawn. */
- private static final int LEFT_MARGIN = 5;
-
- /** Top margin after which header is drawn. */
- private static final int TOP_MARGIN = 5;
-
- /** # of pixels of padding between duration markers for different contexts. */
- private static final int CONTEXT_PADDING = 10;
-
- private final int mHeaderMargin;
- private final int mContextCount;
- private final int mMaxDurationLength;
- private final long mMaxDuration;
- private final double mScale;
-
- private int mCallCount;
- private int mNumCallsPerPixel = 1;
-
- public PositionHelper(int fontHeight, int contextCount,
- int maxDurationLength, long maxDuration) {
- mContextCount = contextCount;
- mMaxDurationLength = maxDurationLength;
- mMaxDuration = maxDuration;
- mScale = (double) maxDurationLength / maxDuration;
-
- // header region is present only there are multiple contexts
- if (mContextCount > 1) {
- mHeaderMargin = fontHeight * 3;
- } else {
- mHeaderMargin = 0;
- }
- }
-
- /** Get the minimum width of the canvas. */
- public int getMinimumWidth() {
- return LEFT_MARGIN + (mMaxDurationLength + CONTEXT_PADDING) * mContextCount;
- }
-
- /** Get the bounds for a call duration line. */
- public Rectangle getDurationBounds(int callIndex, int context, long duration) {
- if (duration <= 0) {
- duration = 1;
- } else if (duration > mMaxDuration) {
- duration = mMaxDuration;
- }
-
- int x = LEFT_MARGIN + ((mMaxDurationLength + CONTEXT_PADDING) * context);
- int y = (callIndex/mNumCallsPerPixel) + TOP_MARGIN + mHeaderMargin;
- int w = (int) (duration * mScale);
- int h = 1;
-
- return new Rectangle(x, y, w, h);
- }
-
- public long getMaxDuration() {
- return mMaxDuration;
- }
-
- /** Get the bounds for calls spanning given range. */
- public Rectangle getBoundsFramingCalls(int startCallIndex, int endCallIndex) {
- if (startCallIndex >= 0 && endCallIndex >= startCallIndex
- && endCallIndex <= mCallCount) {
- int x = LEFT_MARGIN;
- int y = (startCallIndex/mNumCallsPerPixel) + TOP_MARGIN + mHeaderMargin;
- int w = ((mMaxDurationLength + CONTEXT_PADDING) * mContextCount);
- int h = (endCallIndex - startCallIndex)/mNumCallsPerPixel;
- return new Rectangle(x, y, w, h);
- } else {
- return new Rectangle(0, 0, 0, 0);
- }
- }
-
- public Point getHeaderLocation(int context) {
- int x = LEFT_MARGIN + ((mMaxDurationLength + CONTEXT_PADDING) * context);
- return new Point(x, TOP_MARGIN);
- }
-
- /** Update the call density based on the number of calls to be displayed and
- * the available height to display them in. */
- public void updateCallDensity(int callCount, int displayHeight) {
- mCallCount = callCount;
-
- if (displayHeight <= 0) {
- displayHeight = callCount + 1;
- }
-
- mNumCallsPerPixel = (callCount / displayHeight) + 1;
- }
-
- /** Get the underscan value. In cases where there are more calls to be displayed
- * than there are availble pixels, we only display 1 out of every underscan calls. */
- public int getCallUnderScanValue() {
- return mNumCallsPerPixel;
- }
-
- /** Get the index of the call at given y offset. */
- public int getCallAt(int y) {
- if (!isWithinBounds(y)) {
- return -1;
- }
-
- Rectangle displayBounds = getBoundsFramingCalls(0, mCallCount);
- return (y - displayBounds.y) * mNumCallsPerPixel;
- }
-
- /** Does the provided y offset map to a valid call? */
- private boolean isWithinBounds(int y) {
- Rectangle displayBounds = getBoundsFramingCalls(0, mCallCount);
- if (y < displayBounds.y) {
- return false;
- }
-
- if (y > (displayBounds.y + displayBounds.height)) {
- return false;
- }
-
- return true;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/editors/GLCallGroups.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/editors/GLCallGroups.java
deleted file mode 100644
index 226d4831a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/editors/GLCallGroups.java
+++ /dev/null
@@ -1,202 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.editors;
-
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.Function;
-import com.android.ide.eclipse.gltrace.model.GLCall;
-import com.android.ide.eclipse.gltrace.model.GLTrace;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Stack;
-
-public class GLCallGroups {
- /**
- * A {@link GLCallNode} is a simple wrapper around a {@link GLCall} that
- * adds the notion of hierarchy.
- */
- public interface GLCallNode {
- /** Does this call have child nodes? */
- boolean hasChildren();
-
- /** Returns a list of child nodes of this call. */
- List<GLCallNode> getChildren();
-
- /** Returns the {@link GLCall} that is wrapped by this node. */
- GLCall getCall();
-
- /** Returns the parent of this node, the parent is null if this is a top level node */
- GLCallNode getParent();
-
- /** Set the parent node. */
- void setParent(GLCallNode parent);
- }
-
- private static class GLTreeNode implements GLCallNode {
- private final GLCall mCall;
- private GLCallNode mParent;
- private List<GLCallNode> mGLCallNodes;
-
- public GLTreeNode(GLCall call) {
- mCall = call;
- mGLCallNodes = new ArrayList<GLCallNode>();
- }
-
- @Override
- public boolean hasChildren() {
- return true;
- }
-
- @Override
- public GLCallNode getParent() {
- return mParent;
- }
-
- @Override
- public void setParent(GLCallNode parent) {
- mParent = parent;
- }
-
- @Override
- public List<GLCallNode> getChildren() {
- return mGLCallNodes;
- }
-
- public void addChild(GLCallNode n) {
- mGLCallNodes.add(n);
- n.setParent(this);
- }
-
- @Override
- public GLCall getCall() {
- return mCall;
- }
- }
-
- private static class GLLeafNode implements GLCallNode {
- private final GLCall mCall;
- private GLCallNode mParent;
-
- public GLLeafNode(GLCall call) {
- mCall = call;
- }
-
- @Override
- public boolean hasChildren() {
- return false;
- }
-
- @Override
- public List<GLCallNode> getChildren() {
- return null;
- }
-
- @Override
- public GLCallNode getParent() {
- return mParent;
- }
-
- @Override
- public void setParent(GLCallNode parent) {
- mParent = parent;
- }
-
- @Override
- public GLCall getCall() {
- return mCall;
- }
- }
-
- /**
- * Impose a hierarchy on a list of {@link GLCall}'s based on the presence of
- * {@link Function#glPushGroupMarkerEXT} and {@link Function#glPopGroupMarkerEXT} calls.
- * Such a hierarchy is possible only if calls from a single context are considered.
- * @param trace trace to look at
- * @param start starting call index
- * @param end ending call index
- * @param contextToGroup context from which calls should be grouped. If no such context
- * is present, then all calls in the given range will be returned back as a flat
- * list.
- * @return a tree structured list of {@link GLCallNode} objects
- */
- public static List<GLCallNode> constructCallHierarchy(GLTrace trace, int start, int end,
- int contextToGroup) {
- if (trace == null) {
- return Collections.emptyList();
- }
-
- if (contextToGroup < 0 || contextToGroup > trace.getContexts().size()) {
- return flatHierarchy(trace, start, end);
- }
-
- List<GLCall> calls = trace.getGLCalls();
-
- Stack<GLTreeNode> hierarchyStack = new Stack<GLTreeNode>();
- List<GLCallNode> items = new ArrayList<GLCallNode>();
-
- for (int i = start; i < end; i++) {
- GLCall c = calls.get(i);
- if (c.getContextId() != contextToGroup) {
- // skip this call if it is not part of the context we need to display
- continue;
- }
-
- if (c.getFunction() == Function.glPushGroupMarkerEXT) {
- GLTreeNode group = new GLTreeNode(c);
- if (hierarchyStack.size() > 0) {
- hierarchyStack.peek().addChild(group);
- } else {
- items.add(group);
- }
- hierarchyStack.push(group);
- } else if (c.getFunction() == Function.glPopGroupMarkerEXT) {
- if (hierarchyStack.size() > 0) {
- hierarchyStack.pop();
- } else {
- // FIXME: If we are attempting to pop from an empty stack,
- // that implies that a push marker was seen in a prior frame
- // (in a call before @start). In such a case, we simply continue
- // adding further calls to the root of the hierarchy rather than
- // searching backwards in the call list for the corresponding
- // push markers.
- items.add(new GLLeafNode(c));
- }
- } else {
- GLLeafNode leaf = new GLLeafNode(c);
- if (hierarchyStack.size() > 0) {
- hierarchyStack.peek().addChild(leaf);
- } else {
- items.add(leaf);
- }
- }
- }
-
- return items;
- }
-
- private static List<GLCallNode> flatHierarchy(GLTrace trace, int start, int end) {
- List<GLCallNode> items = new ArrayList<GLCallNode>();
-
- List<GLCall> calls = trace.getGLCalls();
- for (int i = start; i < end; i++) {
- items.add(new GLLeafNode(calls.get(i)));
- }
-
- return items;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/editors/GLFunctionTraceViewer.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/editors/GLFunctionTraceViewer.java
deleted file mode 100644
index b809ddddf..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/editors/GLFunctionTraceViewer.java
+++ /dev/null
@@ -1,984 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.editors;
-
-import com.android.ddmuilib.AbstractBufferFindTarget;
-import com.android.ddmuilib.FindDialog;
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.Function;
-import com.android.ide.eclipse.gltrace.GlTracePlugin;
-import com.android.ide.eclipse.gltrace.SwtUtils;
-import com.android.ide.eclipse.gltrace.TraceFileParserTask;
-import com.android.ide.eclipse.gltrace.editors.DurationMinimap.ICallSelectionListener;
-import com.android.ide.eclipse.gltrace.editors.GLCallGroups.GLCallNode;
-import com.android.ide.eclipse.gltrace.model.GLCall;
-import com.android.ide.eclipse.gltrace.model.GLFrame;
-import com.android.ide.eclipse.gltrace.model.GLTrace;
-import com.android.ide.eclipse.gltrace.views.FrameSummaryViewPage;
-import com.android.ide.eclipse.gltrace.views.detail.DetailsPage;
-import com.google.common.base.Charsets;
-import com.google.common.io.Files;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.dialogs.ProgressMonitorDialog;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.jface.viewers.CellLabelProvider;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.jface.viewers.TreeViewerColumn;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerCell;
-import org.eclipse.jface.viewers.ViewerFilter;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.dnd.Clipboard;
-import org.eclipse.swt.dnd.TextTransfer;
-import org.eclipse.swt.dnd.Transfer;
-import org.eclipse.swt.events.ControlAdapter;
-import org.eclipse.swt.events.ControlEvent;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Scale;
-import org.eclipse.swt.widgets.ScrollBar;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Spinner;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.swt.widgets.ToolBar;
-import org.eclipse.swt.widgets.ToolItem;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeColumn;
-import org.eclipse.swt.widgets.TreeItem;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.IURIEditorInput;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.part.EditorPart;
-
-import java.io.File;
-import java.io.IOException;
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/** Display OpenGL function trace in a tabular view. */
-public class GLFunctionTraceViewer extends EditorPart implements ISelectionProvider {
- public static final String ID = "com.android.ide.eclipse.gltrace.GLFunctionTrace"; //$NON-NLS-1$
-
- private static final String DEFAULT_FILTER_MESSAGE = "Filter list of OpenGL calls. Accepts Java regexes.";
- private static final String NEWLINE = System.getProperty("line.separator"); //$NON-NLS-1$
-
- private static Image sExpandAllIcon;
-
- private static String sLastExportedToFolder;
-
- private String mFilePath;
- private Scale mFrameSelectionScale;
- private Spinner mFrameSelectionSpinner;
-
- private GLTrace mTrace;
-
- private TreeViewer mFrameTreeViewer;
- private List<GLCallNode> mTreeViewerNodes;
-
- private Text mFilterText;
- private GLCallFilter mGLCallFilter;
-
- private Color mGldrawTextColor;
- private Color mGlCallErrorColor;
-
- /**
- * Job to refresh the tree view & frame summary view.
- *
- * When the currently displayed frame is changed, either via the {@link #mFrameSelectionScale}
- * or via {@link #mFrameSelectionSpinner}, we need to update the displayed tree of calls for
- * that frame, and the frame summary view. Both these operations need to happen on the UI
- * thread, but are time consuming. This works out ok if the frame selection is not changing
- * rapidly (i.e., when the spinner or scale is moved to the target frame in a single action).
- * However, if the spinner is constantly pressed, then the user is scrolling through a sequence
- * of frames, and rather than refreshing the details for each of the intermediate frames,
- * we create a job to refresh the details and schedule the job after a short interval
- * {@link #TREE_REFRESH_INTERVAL}. This allows us to stay responsive to the spinner/scale,
- * and not do the costly refresh for each of the intermediate frames.
- */
- private Job mTreeRefresherJob;
- private final Object mTreeRefresherLock = new Object();
- private static final int TREE_REFRESH_INTERVAL_MS = 250;
-
- private int mCurrentFrame;
-
- // Currently displayed frame's start and end call indices.
- private int mCallStartIndex;
- private int mCallEndIndex;
-
- private DurationMinimap mDurationMinimap;
- private ScrollBar mVerticalScrollBar;
-
- private Combo mContextSwitchCombo;
- private boolean mShowContextSwitcher;
- private int mCurrentlyDisplayedContext = -1;
-
- private StateViewPage mStateViewPage;
- private FrameSummaryViewPage mFrameSummaryViewPage;
- private DetailsPage mDetailsPage;
-
- private ToolItem mExpandAllToolItem;
- private ToolItem mCollapseAllToolItem;
- private ToolItem mSaveAsToolItem;
-
- public GLFunctionTraceViewer() {
- mGldrawTextColor = Display.getDefault().getSystemColor(SWT.COLOR_BLUE);
- mGlCallErrorColor = Display.getDefault().getSystemColor(SWT.COLOR_RED);
- }
-
- @Override
- public void doSave(IProgressMonitor monitor) {
- }
-
- @Override
- public void doSaveAs() {
- }
-
- @Override
- public void init(IEditorSite site, IEditorInput input) throws PartInitException {
- // we use a IURIEditorInput to allow opening files not within the workspace
- if (!(input instanceof IURIEditorInput)) {
- throw new PartInitException("GL Function Trace View: unsupported input type.");
- }
-
- setSite(site);
- setInput(input);
- mFilePath = ((IURIEditorInput) input).getURI().getPath();
-
- // set the editor part name to be the name of the file.
- File f = new File(mFilePath);
- setPartName(f.getName());
- }
-
- @Override
- public boolean isDirty() {
- return false;
- }
-
- @Override
- public boolean isSaveAsAllowed() {
- return false;
- }
-
- @Override
- public void createPartControl(Composite parent) {
- Composite c = new Composite(parent, SWT.NONE);
- c.setLayout(new GridLayout(1, false));
- GridData gd = new GridData(GridData.FILL_BOTH);
- c.setLayoutData(gd);
-
- setInput(parent.getShell(), mFilePath);
-
- createFrameSelectionControls(c);
- createOptionsBar(c);
- createFrameTraceView(c);
-
- getSite().setSelectionProvider(mFrameTreeViewer);
-
- IActionBars actionBars = getEditorSite().getActionBars();
- actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(),
- new Action("Copy") {
- @Override
- public void run() {
- copySelectionToClipboard();
- }
- });
-
- actionBars.setGlobalActionHandler(ActionFactory.SELECT_ALL.getId(),
- new Action("Select All") {
- @Override
- public void run() {
- selectAll();
- }
- });
-
- actionBars.setGlobalActionHandler(ActionFactory.FIND.getId(),
- new Action("Find") {
- @Override
- public void run() {
- showFindDialog();
- }
- });
- }
-
- public void setInput(Shell shell, String tracePath) {
- ProgressMonitorDialog dlg = new ProgressMonitorDialog(shell);
- TraceFileParserTask parser = new TraceFileParserTask(mFilePath);
- try {
- dlg.run(true, true, parser);
- } catch (InvocationTargetException e) {
- // exception while parsing, display error to user
- MessageDialog.openError(shell,
- "Error parsing OpenGL Trace File",
- e.getCause().getMessage());
- return;
- } catch (InterruptedException e) {
- // operation canceled by user, just return
- return;
- }
-
- mTrace = parser.getTrace();
- mShowContextSwitcher = (mTrace == null) ? false : mTrace.getContexts().size() > 1;
- if (mStateViewPage != null) {
- mStateViewPage.setInput(mTrace);
- }
- if (mFrameSummaryViewPage != null) {
- mFrameSummaryViewPage.setInput(mTrace);
- }
- if (mDetailsPage != null) {
- mDetailsPage.setInput(mTrace);
- }
- if (mDurationMinimap != null) {
- mDurationMinimap.setInput(mTrace);
- }
-
- Display.getDefault().asyncExec(new Runnable() {
- @Override
- public void run() {
- refreshUI();
- }
- });
- }
-
- private void refreshUI() {
- if (mTrace == null || mTrace.getGLCalls().size() == 0) {
- setFrameCount(0);
- return;
- }
-
- setFrameCount(mTrace.getFrames().size());
- selectFrame(1);
- }
-
- private void createFrameSelectionControls(Composite parent) {
- Composite c = new Composite(parent, SWT.NONE);
- c.setLayout(new GridLayout(3, false));
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- c.setLayoutData(gd);
-
- Label l = new Label(c, SWT.NONE);
- l.setText("Select Frame:");
-
- mFrameSelectionScale = new Scale(c, SWT.HORIZONTAL);
- mFrameSelectionScale.setMinimum(1);
- mFrameSelectionScale.setMaximum(1);
- mFrameSelectionScale.setSelection(0);
- gd = new GridData(GridData.FILL_HORIZONTAL);
- mFrameSelectionScale.setLayoutData(gd);
-
- mFrameSelectionScale.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- int selectedFrame = mFrameSelectionScale.getSelection();
- mFrameSelectionSpinner.setSelection(selectedFrame);
- selectFrame(selectedFrame);
- }
- });
-
- mFrameSelectionSpinner = new Spinner(c, SWT.BORDER);
- gd = new GridData();
- // width to hold atleast 6 digits
- gd.widthHint = SwtUtils.getApproximateFontWidth(mFrameSelectionSpinner) * 6;
- mFrameSelectionSpinner.setLayoutData(gd);
-
- mFrameSelectionSpinner.setMinimum(1);
- mFrameSelectionSpinner.setMaximum(1);
- mFrameSelectionSpinner.setSelection(0);
- mFrameSelectionSpinner.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- int selectedFrame = mFrameSelectionSpinner.getSelection();
- mFrameSelectionScale.setSelection(selectedFrame);
- selectFrame(selectedFrame);
- }
- });
- }
-
- private void setFrameCount(int nFrames) {
- boolean en = nFrames > 0;
- mFrameSelectionScale.setEnabled(en);
- mFrameSelectionSpinner.setEnabled(en);
-
- mFrameSelectionScale.setMaximum(nFrames);
- mFrameSelectionSpinner.setMaximum(nFrames);
- }
-
- private void selectFrame(int selectedFrame) {
- mFrameSelectionScale.setSelection(selectedFrame);
- mFrameSelectionSpinner.setSelection(selectedFrame);
-
- synchronized (mTreeRefresherLock) {
- if (mTrace != null) {
- GLFrame f = mTrace.getFrame(selectedFrame - 1);
- mCallStartIndex = f.getStartIndex();
- mCallEndIndex = f.getEndIndex();
- } else {
- mCallStartIndex = mCallEndIndex = 0;
- }
-
- mCurrentFrame = selectedFrame - 1;
-
- scheduleNewRefreshJob();
- }
-
- // update minimap view
- mDurationMinimap.setCallRangeForCurrentFrame(mCallStartIndex, mCallEndIndex);
- }
-
- /**
- * Show only calls from the given context
- * @param context context id whose calls should be displayed. Illegal values will result in
- * calls from all contexts being displayed.
- */
- private void selectContext(int context) {
- if (mCurrentlyDisplayedContext == context) {
- return;
- }
-
- synchronized (mTreeRefresherLock) {
- mCurrentlyDisplayedContext = context;
- scheduleNewRefreshJob();
- }
- }
-
- private void scheduleNewRefreshJob() {
- if (mTreeRefresherJob != null) {
- return;
- }
-
- mTreeRefresherJob = new Job("Refresh GL Trace View Tree") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- final int start, end, context;
-
- synchronized (mTreeRefresherLock) {
- start = mCallStartIndex;
- end = mCallEndIndex;
- context = mCurrentlyDisplayedContext;
-
- mTreeRefresherJob = null;
- }
-
- // update tree view in the editor
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- refreshTree(start, end, context);
-
- // update the frame summary view
- if (mFrameSummaryViewPage != null) {
- mFrameSummaryViewPage.setSelectedFrame(mCurrentFrame);
- }
- }
- });
- return Status.OK_STATUS;
- }
- };
- mTreeRefresherJob.setPriority(Job.SHORT);
- mTreeRefresherJob.schedule(TREE_REFRESH_INTERVAL_MS);
- }
-
- private void refreshTree(int startCallIndex, int endCallIndex, int contextToDisplay) {
- mTreeViewerNodes = GLCallGroups.constructCallHierarchy(mTrace,
- startCallIndex, endCallIndex,
- contextToDisplay);
- mFrameTreeViewer.setInput(mTreeViewerNodes);
- mFrameTreeViewer.refresh();
- mFrameTreeViewer.expandAll();
- }
-
- private void createOptionsBar(Composite parent) {
- int numColumns = mShowContextSwitcher ? 4 : 3;
-
- Composite c = new Composite(parent, SWT.NONE);
- c.setLayout(new GridLayout(numColumns, false));
- GridData gd = new GridData(GridData.FILL_HORIZONTAL);
- c.setLayoutData(gd);
-
- Label l = new Label(c, SWT.NONE);
- l.setText("Filter:");
-
- mFilterText = new Text(c, SWT.BORDER | SWT.ICON_SEARCH | SWT.SEARCH | SWT.ICON_CANCEL);
- mFilterText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- mFilterText.setMessage(DEFAULT_FILTER_MESSAGE);
- mFilterText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- updateAppliedFilters();
- }
- });
-
- if (mShowContextSwitcher) {
- mContextSwitchCombo = new Combo(c, SWT.BORDER | SWT.READ_ONLY);
-
- // Setup the combo such that "All Contexts" is the first item,
- // and then we have an item for each context.
- mContextSwitchCombo.add("All Contexts");
- mContextSwitchCombo.select(0);
- mCurrentlyDisplayedContext = -1; // showing all contexts
- for (int i = 0; i < mTrace.getContexts().size(); i++) {
- mContextSwitchCombo.add("Context " + i);
- }
-
- mContextSwitchCombo.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- selectContext(mContextSwitchCombo.getSelectionIndex() - 1);
- }
- });
- } else {
- mCurrentlyDisplayedContext = 0;
- }
-
- ToolBar toolBar = new ToolBar(c, SWT.FLAT | SWT.BORDER);
-
- mExpandAllToolItem = new ToolItem(toolBar, SWT.PUSH);
- mExpandAllToolItem.setToolTipText("Expand All");
- if (sExpandAllIcon == null) {
- ImageDescriptor id = GlTracePlugin.getImageDescriptor("/icons/expandall.png");
- sExpandAllIcon = id.createImage();
- }
- if (sExpandAllIcon != null) {
- mExpandAllToolItem.setImage(sExpandAllIcon);
- }
-
- mCollapseAllToolItem = new ToolItem(toolBar, SWT.PUSH);
- mCollapseAllToolItem.setToolTipText("Collapse All");
- mCollapseAllToolItem.setImage(
- PlatformUI.getWorkbench().getSharedImages().getImage(
- ISharedImages.IMG_ELCL_COLLAPSEALL));
-
- mSaveAsToolItem = new ToolItem(toolBar, SWT.PUSH);
- mSaveAsToolItem.setToolTipText("Export Trace");
- mSaveAsToolItem.setImage(
- PlatformUI.getWorkbench().getSharedImages().getImage(
- ISharedImages.IMG_ETOOL_SAVEAS_EDIT));
-
- SelectionListener toolbarSelectionListener = new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (e.getSource() == mCollapseAllToolItem) {
- setTreeItemsExpanded(false);
- } else if (e.getSource() == mExpandAllToolItem) {
- setTreeItemsExpanded(true);
- } else if (e.getSource() == mSaveAsToolItem) {
- exportTrace();
- }
- }
- };
- mExpandAllToolItem.addSelectionListener(toolbarSelectionListener);
- mCollapseAllToolItem.addSelectionListener(toolbarSelectionListener);
- mSaveAsToolItem.addSelectionListener(toolbarSelectionListener);
- }
-
- private void updateAppliedFilters() {
- mGLCallFilter.setFilters(mFilterText.getText().trim());
- mFrameTreeViewer.refresh();
- }
-
- private void createFrameTraceView(Composite parent) {
- Composite c = new Composite(parent, SWT.NONE);
- c.setLayout(new GridLayout(2, false));
- GridData gd = new GridData(GridData.FILL_BOTH);
- c.setLayoutData(gd);
-
- final Tree tree = new Tree(c, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI);
- gd = new GridData(GridData.FILL_BOTH);
- tree.setLayoutData(gd);
- tree.setLinesVisible(true);
- tree.setHeaderVisible(true);
-
- mFrameTreeViewer = new TreeViewer(tree);
- CellLabelProvider labelProvider = new GLFrameLabelProvider();
-
- // column showing the GL context id
- TreeViewerColumn tvc = new TreeViewerColumn(mFrameTreeViewer, SWT.NONE);
- tvc.setLabelProvider(labelProvider);
- TreeColumn column = tvc.getColumn();
- column.setText("Function");
- column.setWidth(500);
-
- // column showing the GL function duration (wall clock time)
- tvc = new TreeViewerColumn(mFrameTreeViewer, SWT.NONE);
- tvc.setLabelProvider(labelProvider);
- column = tvc.getColumn();
- column.setText("Wall Time (ns)");
- column.setWidth(150);
- column.setAlignment(SWT.RIGHT);
-
- // column showing the GL function duration (thread time)
- tvc = new TreeViewerColumn(mFrameTreeViewer, SWT.NONE);
- tvc.setLabelProvider(labelProvider);
- column = tvc.getColumn();
- column.setText("Thread Time (ns)");
- column.setWidth(150);
- column.setAlignment(SWT.RIGHT);
-
- mFrameTreeViewer.setContentProvider(new GLFrameContentProvider());
-
- mGLCallFilter = new GLCallFilter();
- mFrameTreeViewer.addFilter(mGLCallFilter);
-
- // when the control is resized, give all the additional space
- // to the function name column.
- tree.addControlListener(new ControlAdapter() {
- @Override
- public void controlResized(ControlEvent e) {
- int w = mFrameTreeViewer.getTree().getClientArea().width;
- if (w > 200) {
- mFrameTreeViewer.getTree().getColumn(2).setWidth(100);
- mFrameTreeViewer.getTree().getColumn(1).setWidth(100);
- mFrameTreeViewer.getTree().getColumn(0).setWidth(w - 200);
- }
- }
- });
-
- mDurationMinimap = new DurationMinimap(c, mTrace);
- gd = new GridData(GridData.FILL_VERTICAL);
- gd.widthHint = gd.minimumWidth = mDurationMinimap.getMinimumWidth();
- mDurationMinimap.setLayoutData(gd);
- mDurationMinimap.addCallSelectionListener(new ICallSelectionListener() {
- @Override
- public void callSelected(int selectedCallIndex) {
- if (selectedCallIndex > 0 && selectedCallIndex < mTreeViewerNodes.size()) {
- TreeItem item = tree.getItem(selectedCallIndex);
- tree.select(item);
- tree.setTopItem(item);
- }
- }
- });
-
- mVerticalScrollBar = tree.getVerticalBar();
- mVerticalScrollBar.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateVisibleRange();
- }
- });
- }
-
- private void updateVisibleRange() {
- int visibleCallTopIndex = mCallStartIndex;
- int visibleCallBottomIndex = mCallEndIndex;
-
- if (mVerticalScrollBar.isEnabled()) {
- int selection = mVerticalScrollBar.getSelection();
- int thumb = mVerticalScrollBar.getThumb();
- int max = mVerticalScrollBar.getMaximum();
-
- // from the scrollbar values, compute the visible fraction
- double top = (double) selection / max;
- double bottom = (double) (selection + thumb) / max;
-
- // map the fraction to the call indices
- int range = mCallEndIndex - mCallStartIndex;
- visibleCallTopIndex = mCallStartIndex + (int) Math.floor(range * top);
- visibleCallBottomIndex = mCallStartIndex + (int) Math.ceil(range * bottom);
- }
-
- mDurationMinimap.setVisibleCallRange(visibleCallTopIndex, visibleCallBottomIndex);
- }
-
- @Override
- public void setFocus() {
- mFrameTreeViewer.getTree().setFocus();
- }
-
- private static class GLFrameContentProvider implements ITreeContentProvider {
- @Override
- public void dispose() {
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- @Override
- public Object[] getElements(Object inputElement) {
- return getChildren(inputElement);
- }
-
- @Override
- public Object[] getChildren(Object parentElement) {
- if (parentElement instanceof List<?>) {
- return ((List<?>) parentElement).toArray();
- }
-
- if (!(parentElement instanceof GLCallNode)) {
- return null;
- }
-
- GLCallNode parent = (GLCallNode) parentElement;
- if (parent.hasChildren()) {
- return parent.getChildren().toArray();
- } else {
- return new Object[0];
- }
- }
-
- @Override
- public Object getParent(Object element) {
- if (!(element instanceof GLCallNode)) {
- return null;
- }
-
- return ((GLCallNode) element).getParent();
- }
-
- @Override
- public boolean hasChildren(Object element) {
- if (!(element instanceof GLCallNode)) {
- return false;
- }
-
- return ((GLCallNode) element).hasChildren();
- }
- }
-
- private class GLFrameLabelProvider extends ColumnLabelProvider {
- @Override
- public void update(ViewerCell cell) {
- Object element = cell.getElement();
- if (!(element instanceof GLCallNode)) {
- return;
- }
-
- GLCall c = ((GLCallNode) element).getCall();
-
- if (c.getFunction() == Function.glDrawArrays
- || c.getFunction() == Function.glDrawElements) {
- cell.setForeground(mGldrawTextColor);
- }
-
- if (c.hasErrors()) {
- cell.setForeground(mGlCallErrorColor);
- }
-
- cell.setText(getColumnText(c, cell.getColumnIndex()));
- }
-
- private String getColumnText(GLCall c, int columnIndex) {
- switch (columnIndex) {
- case 0:
- if (c.getFunction() == Function.glPushGroupMarkerEXT) {
- Object marker = c.getProperty(GLCall.PROPERTY_MARKERNAME);
- if (marker instanceof String) {
- return ((String) marker);
- }
- }
- return c.toString();
- case 1:
- return formatDuration(c.getWallDuration());
- case 2:
- return formatDuration(c.getThreadDuration());
- default:
- return Integer.toString(c.getContextId());
- }
- }
-
- private String formatDuration(int time) {
- // Max duration is in the 10s of milliseconds, so xx,xxx,xxx ns
- // So we require a format specifier that is 10 characters wide
- return String.format("%,10d", time); //$NON-NLS-1$
- }
- }
-
- private static class GLCallFilter extends ViewerFilter {
- private final List<Pattern> mPatterns = new ArrayList<Pattern>();
-
- public void setFilters(String filter) {
- mPatterns.clear();
-
- // split the user input into multiple regexes
- // we assume that the regexes are OR'ed together i.e., all text that matches
- // any one of the regexes will be displayed
- for (String regex : filter.split(" ")) {
- mPatterns.add(Pattern.compile(regex, Pattern.CASE_INSENSITIVE));
- }
- }
-
- @Override
- public boolean select(Viewer viewer, Object parentElement, Object element) {
- if (!(element instanceof GLCallNode)) {
- return true;
- }
-
- String text = getTextUnderNode((GLCallNode) element);
-
- if (mPatterns.size() == 0) {
- // match if there are no regex filters
- return true;
- }
-
- for (Pattern p : mPatterns) {
- Matcher matcher = p.matcher(text);
- if (matcher.find()) {
- // match if atleast one of the regexes matches this text
- return true;
- }
- }
-
- return false;
- }
-
- /** Obtain a string representation of all functions under a given tree node. */
- private String getTextUnderNode(GLCallNode element) {
- String func = element.getCall().getFunction().toString();
- if (!element.hasChildren()) {
- return func;
- }
-
- StringBuilder sb = new StringBuilder(100);
- sb.append(func);
-
- for (GLCallNode child : element.getChildren()) {
- sb.append(getTextUnderNode(child));
- }
-
- return sb.toString();
- }
- }
-
- @Override
- public void addSelectionChangedListener(ISelectionChangedListener listener) {
- if (mFrameTreeViewer != null) {
- mFrameTreeViewer.addSelectionChangedListener(listener);
- }
- }
-
- @Override
- public ISelection getSelection() {
- if (mFrameTreeViewer != null) {
- return mFrameTreeViewer.getSelection();
- } else {
- return null;
- }
- }
-
- @Override
- public void removeSelectionChangedListener(ISelectionChangedListener listener) {
- if (mFrameTreeViewer != null) {
- mFrameTreeViewer.removeSelectionChangedListener(listener);
- }
- }
-
- @Override
- public void setSelection(ISelection selection) {
- if (mFrameTreeViewer != null) {
- mFrameTreeViewer.setSelection(selection);
- }
- }
-
- public GLTrace getTrace() {
- return mTrace;
- }
-
- public StateViewPage getStateViewPage() {
- if (mStateViewPage == null) {
- mStateViewPage = new StateViewPage(mTrace);
- }
-
- return mStateViewPage;
- }
-
- public FrameSummaryViewPage getFrameSummaryViewPage() {
- if (mFrameSummaryViewPage == null) {
- mFrameSummaryViewPage = new FrameSummaryViewPage(mTrace);
- }
-
- return mFrameSummaryViewPage;
- }
-
- public DetailsPage getDetailsPage() {
- if (mDetailsPage == null) {
- mDetailsPage = new DetailsPage(mTrace);
- }
-
- return mDetailsPage;
- }
-
- private void copySelectionToClipboard() {
- if (mFrameTreeViewer == null || mFrameTreeViewer.getTree().isDisposed()) {
- return;
- }
-
- StringBuilder sb = new StringBuilder();
-
- for (TreeItem it: mFrameTreeViewer.getTree().getSelection()) {
- Object data = it.getData();
- if (data instanceof GLCallNode) {
- sb.append(((GLCallNode) data).getCall());
- sb.append(NEWLINE);
- }
- }
-
- if (sb.length() > 0) {
- Clipboard cb = new Clipboard(Display.getDefault());
- cb.setContents(
- new Object[] { sb.toString() },
- new Transfer[] { TextTransfer.getInstance() });
- cb.dispose();
- }
- }
-
- private void selectAll() {
- if (mFrameTreeViewer == null || mFrameTreeViewer.getTree().isDisposed()) {
- return;
- }
-
- mFrameTreeViewer.getTree().selectAll();
- }
-
- private void exportTrace() {
- if (mFrameTreeViewer == null || mFrameTreeViewer.getTree().isDisposed()) {
- return;
- }
-
- if (mCallEndIndex == 0) {
- return;
- }
-
- FileDialog fd = new FileDialog(mFrameTreeViewer.getTree().getShell(), SWT.SAVE);
- fd.setFilterExtensions(new String[] { "*.txt" });
- if (sLastExportedToFolder != null) {
- fd.setFilterPath(sLastExportedToFolder);
- }
-
- String path = fd.open();
- if (path == null) {
- return;
- }
-
- File f = new File(path);
- sLastExportedToFolder = f.getParent();
- try {
- exportFrameTo(f);
- } catch (IOException e) {
- ErrorDialog.openError(mFrameTreeViewer.getTree().getShell(),
- "Export trace file.",
- "Unexpected error exporting trace file.",
- new Status(Status.ERROR, GlTracePlugin.PLUGIN_ID, e.toString()));
- }
- }
-
- private void exportFrameTo(File f) throws IOException {
- String glCalls = serializeGlCalls(mTrace.getGLCalls(), mCallStartIndex, mCallEndIndex);
- Files.write(glCalls, f, Charsets.UTF_8);
- }
-
- private String serializeGlCalls(List<GLCall> glCalls, int start, int end) {
- StringBuilder sb = new StringBuilder();
- while (start < end) {
- sb.append(glCalls.get(start).toString());
- sb.append("\n"); //$NON-NLS-1$
- start++;
- }
-
- return sb.toString();
- }
-
- private void setTreeItemsExpanded(boolean expand) {
- if (mFrameTreeViewer == null || mFrameTreeViewer.getTree().isDisposed()) {
- return;
- }
-
- if (expand) {
- mFrameTreeViewer.expandAll();
- } else {
- mFrameTreeViewer.collapseAll();
- }
- }
-
- private class TraceViewerFindTarget extends AbstractBufferFindTarget {
- @Override
- public int getItemCount() {
- return mFrameTreeViewer.getTree().getItemCount();
- }
-
- @Override
- public String getItem(int index) {
- Object data = mFrameTreeViewer.getTree().getItem(index).getData();
- if (data instanceof GLCallNode) {
- return ((GLCallNode) data).getCall().toString();
- }
- return null;
- }
-
- @Override
- public void selectAndReveal(int index) {
- Tree t = mFrameTreeViewer.getTree();
- t.deselectAll();
- t.select(t.getItem(index));
- t.showSelection();
- }
-
- @Override
- public int getStartingIndex() {
- return 0;
- }
- };
-
- private FindDialog mFindDialog;
- private TraceViewerFindTarget mFindTarget = new TraceViewerFindTarget();
-
- private void showFindDialog() {
- if (mFindDialog != null) {
- // the dialog is already displayed
- return;
- }
-
- mFindDialog = new FindDialog(Display.getDefault().getActiveShell(),
- mFindTarget,
- FindDialog.FIND_NEXT_ID);
- mFindDialog.open(); // blocks until find dialog is closed
- mFindDialog = null;
- }
-
- public String getInputPath() {
- return mFilePath;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/editors/StateContentProvider.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/editors/StateContentProvider.java
deleted file mode 100644
index 7bff168fc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/editors/StateContentProvider.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.editors;
-
-import com.android.ide.eclipse.gltrace.state.GLCompositeProperty;
-import com.android.ide.eclipse.gltrace.state.GLListProperty;
-import com.android.ide.eclipse.gltrace.state.GLSparseArrayProperty;
-import com.android.ide.eclipse.gltrace.state.IGLProperty;
-
-import org.eclipse.jface.viewers.ITreeContentProvider;
-import org.eclipse.jface.viewers.Viewer;
-
-public class StateContentProvider implements ITreeContentProvider {
- @Override
- public void dispose() {
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- @Override
- public Object[] getElements(Object inputElement) {
- return getChildren(inputElement);
- }
-
- @Override
- public Object[] getChildren(Object parentElement) {
- if (parentElement instanceof GLListProperty) {
- return ((GLListProperty) parentElement).getList().toArray();
- }
-
- if (parentElement instanceof GLCompositeProperty) {
- return ((GLCompositeProperty) parentElement).getProperties().toArray();
- }
-
- if (parentElement instanceof GLSparseArrayProperty) {
- return ((GLSparseArrayProperty) parentElement).getValues().toArray();
- }
-
- return null;
- }
-
- @Override
- public Object getParent(Object element) {
- if (element instanceof IGLProperty) {
- return ((IGLProperty) element).getParent();
- }
-
- return null;
- }
-
- @Override
- public boolean hasChildren(Object element) {
- if (element instanceof IGLProperty) {
- return ((IGLProperty) element).isComposite();
- }
-
- return false;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/editors/StateLabelProvider.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/editors/StateLabelProvider.java
deleted file mode 100644
index e37ea77fd..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/editors/StateLabelProvider.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.editors;
-
-import com.android.ide.eclipse.gltrace.state.GLListProperty;
-import com.android.ide.eclipse.gltrace.state.GLSparseArrayProperty;
-import com.android.ide.eclipse.gltrace.state.GLStateType;
-import com.android.ide.eclipse.gltrace.state.IGLProperty;
-
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.ViewerCell;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.widgets.Display;
-
-import java.util.Set;
-
-public class StateLabelProvider extends ColumnLabelProvider {
- private Set<IGLProperty> mChangedProperties;
-
- private Color mHighlightForegroundColor;
- private Color mNormalForegroundColor;
-
- public StateLabelProvider() {
- mHighlightForegroundColor = Display.getDefault().getSystemColor(SWT.COLOR_BLUE);
- mNormalForegroundColor = Display.getDefault().getSystemColor(SWT.COLOR_BLACK);
- }
-
- public String getColumnText(IGLProperty property, int columnIndex) {
- switch (columnIndex) {
- case 0:
- return getName(property);
- case 1:
- return getValue(property);
- default:
- return "";
- }
- }
-
- private String getValue(IGLProperty element) {
- return element.getStringValue();
- }
-
- private String getName(IGLProperty element) {
- IGLProperty parent = element.getParent();
- if (parent instanceof GLListProperty) {
- // For members of list, use the index in the list as the name as opposed to
- // the property type
- int index = ((GLListProperty) parent).indexOf(element);
- if (element.getType() == GLStateType.GL_STATE_ES1) {
- return String.format("Context %d (ES1)", index);
- } else if (element.getType() == GLStateType.GL_STATE_ES2) {
- return String.format("Context %d (ES2)", index);
- } else {
- return Integer.toString(index);
- }
- } else if (parent instanceof GLSparseArrayProperty) {
- // For members of sparse array, use the key as the name as opposed to
- // the property type
- int index = ((GLSparseArrayProperty) parent).keyFor(element);
- return Integer.toString(index);
- }
-
- return element.getType().getDescription();
- }
-
- @Override
- public void update(ViewerCell cell) {
- Object element = cell.getElement();
- if (!(element instanceof IGLProperty)) {
- return;
- }
-
- IGLProperty prop = (IGLProperty) element;
-
- String text = getColumnText(prop, cell.getColumnIndex());
- cell.setText(text);
-
- if (mChangedProperties != null && mChangedProperties.contains(prop)) {
- cell.setForeground(mHighlightForegroundColor);
- } else {
- cell.setForeground(mNormalForegroundColor);
- }
- }
-
- public void setChangedProperties(Set<IGLProperty> changedProperties) {
- mChangedProperties = changedProperties;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/editors/StateViewPage.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/editors/StateViewPage.java
deleted file mode 100644
index faa9561cb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/editors/StateViewPage.java
+++ /dev/null
@@ -1,372 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.editors;
-
-import com.android.ide.eclipse.gltrace.GlTracePlugin;
-import com.android.ide.eclipse.gltrace.editors.GLCallGroups.GLCallNode;
-import com.android.ide.eclipse.gltrace.model.GLCall;
-import com.android.ide.eclipse.gltrace.model.GLTrace;
-import com.android.ide.eclipse.gltrace.state.GLState;
-import com.android.ide.eclipse.gltrace.state.IGLProperty;
-import com.android.ide.eclipse.gltrace.state.StatePrettyPrinter;
-import com.android.ide.eclipse.gltrace.state.transforms.IStateTransform;
-import com.google.common.base.Charsets;
-import com.google.common.io.Files;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.ILock;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.layout.GridDataFactory;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.ISelectionChangedListener;
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.jface.viewers.TreeSelection;
-import org.eclipse.jface.viewers.TreeViewer;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Tree;
-import org.eclipse.swt.widgets.TreeColumn;
-import org.eclipse.ui.ISelectionListener;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.part.IPageSite;
-import org.eclipse.ui.part.Page;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * A tree view of the OpenGL state. It listens to the current GLCall that is selected
- * in the Function Trace view, and updates its view to reflect the state as of the selected call.
- */
-public class StateViewPage extends Page implements ISelectionListener, ISelectionProvider {
- public static final String ID = "com.android.ide.eclipse.gltrace.views.GLState"; //$NON-NLS-1$
- private static String sLastUsedPath;
- private static final ILock sGlStateLock = Job.getJobManager().newLock();
-
- private GLTrace mTrace;
- private List<GLCall> mGLCalls;
-
- /** OpenGL State as of call {@link #mCurrentStateIndex}. */
- private IGLProperty mState;
- private int mCurrentStateIndex;
-
- private String[] TREE_PROPERTIES = { "Name", "Value" };
- private TreeViewer mTreeViewer;
- private StateLabelProvider mLabelProvider;
-
- public StateViewPage(GLTrace trace) {
- setInput(trace);
- }
-
- public void setInput(GLTrace trace) {
- mTrace = trace;
- if (trace != null) {
- mGLCalls = trace.getGLCalls();
- } else {
- mGLCalls = null;
- }
-
- mState = GLState.createDefaultState();
- mCurrentStateIndex = -1;
-
- if (mTreeViewer != null) {
- mTreeViewer.setInput(mState);
- mTreeViewer.refresh();
- }
- }
-
- @Override
- public void createControl(Composite parent) {
- final Tree tree = new Tree(parent, SWT.VIRTUAL | SWT.H_SCROLL | SWT.V_SCROLL);
- GridDataFactory.fillDefaults().grab(true, true).applyTo(tree);
-
- tree.setHeaderVisible(true);
- tree.setLinesVisible(true);
- tree.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- TreeColumn col1 = new TreeColumn(tree, SWT.LEFT);
- col1.setText(TREE_PROPERTIES[0]);
- col1.setWidth(200);
-
- TreeColumn col2 = new TreeColumn(tree, SWT.LEFT);
- col2.setText(TREE_PROPERTIES[1]);
- col2.setWidth(200);
-
- mTreeViewer = new TreeViewer(tree);
- mTreeViewer.setContentProvider(new StateContentProvider());
- mLabelProvider = new StateLabelProvider();
- mTreeViewer.setLabelProvider(mLabelProvider);
- mTreeViewer.setInput(mState);
- mTreeViewer.refresh();
-
- final IToolBarManager manager = getSite().getActionBars().getToolBarManager();
- manager.add(new Action("Save to File",
- PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(
- ISharedImages.IMG_ETOOL_SAVEAS_EDIT)) {
- @Override
- public void run() {
- saveCurrentState();
- }
- });
- }
-
- private void saveCurrentState() {
- final Shell shell = mTreeViewer.getTree().getShell();
- FileDialog fd = new FileDialog(shell, SWT.SAVE);
- fd.setFilterExtensions(new String[] { "*.txt" });
- if (sLastUsedPath != null) {
- fd.setFilterPath(sLastUsedPath);
- }
-
- String path = fd.open();
- if (path == null) {
- return;
- }
-
- File f = new File(path);
- sLastUsedPath = f.getParent();
-
- // export state to f
- StatePrettyPrinter pp = new StatePrettyPrinter();
- synchronized (sGlStateLock) {
- mState.prettyPrint(pp);
- }
-
- try {
- Files.write(pp.toString(), f, Charsets.UTF_8);
- } catch (IOException e) {
- ErrorDialog.openError(shell,
- "Export GL State",
- "Unexpected error while writing GL state to file.",
- new Status(Status.ERROR, GlTracePlugin.PLUGIN_ID, e.toString()));
- }
- }
-
- @Override
- public void init(IPageSite pageSite) {
- super.init(pageSite);
- pageSite.getPage().addSelectionListener(this);
- }
-
- @Override
- public void dispose() {
- getSite().getPage().removeSelectionListener(this);
- super.dispose();
- }
-
- @Override
- public void selectionChanged(IWorkbenchPart part, ISelection selection) {
- if (!(part instanceof GLFunctionTraceViewer)) {
- return;
- }
-
- if (((GLFunctionTraceViewer) part).getTrace() != mTrace) {
- return;
- }
-
- if (!(selection instanceof TreeSelection)) {
- return;
- }
-
- GLCall selectedCall = null;
-
- Object data = ((TreeSelection) selection).getFirstElement();
- if (data instanceof GLCallNode) {
- selectedCall = ((GLCallNode) data).getCall();
- }
-
- if (selectedCall == null) {
- return;
- }
-
- final int selectedCallIndex = selectedCall.getIndex();
-
- // Creation of texture images takes a few seconds on the first run. So run
- // the update task as an Eclipse job.
- Job job = new Job("Updating GL State") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- Set<IGLProperty> changedProperties = null;
-
- try {
- sGlStateLock.acquire();
- changedProperties = updateState(mCurrentStateIndex,
- selectedCallIndex);
- mCurrentStateIndex = selectedCallIndex;
- } catch (Exception e) {
- GlTracePlugin.getDefault().logMessage(
- "Unexpected error while updating GL State.");
- GlTracePlugin.getDefault().logMessage(e.getMessage());
- return new Status(Status.ERROR,
- GlTracePlugin.PLUGIN_ID,
- "Unexpected error while updating GL State.",
- e);
- } finally {
- sGlStateLock.release();
- }
-
- mLabelProvider.setChangedProperties(changedProperties);
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- if (!mTreeViewer.getTree().isDisposed()) {
- mTreeViewer.refresh();
- }
- }
- });
-
- return Status.OK_STATUS;
- }
- };
- job.setPriority(Job.SHORT);
- job.schedule();
- }
-
- @Override
- public Control getControl() {
- if (mTreeViewer == null) {
- return null;
- }
-
- return mTreeViewer.getControl();
- }
-
- @Override
- public void setFocus() {
- }
-
- /**
- * Update GL state from GL call at fromIndex to the call at toIndex.
- * If fromIndex < toIndex, the GL state will be updated by applying all the transformations
- * corresponding to calls from (fromIndex + 1) to toIndex (inclusive).
- * If fromIndex > toIndex, the GL state will be updated by reverting all the calls from
- * fromIndex (inclusive) to (toIndex + 1).
- * @return GL state properties that changed as a result of this update.
- */
- private Set<IGLProperty> updateState(int fromIndex, int toIndex) {
- assert fromIndex >= -1 && fromIndex < mGLCalls.size();
- assert toIndex >= 0 && toIndex < mGLCalls.size();
-
- if (fromIndex < toIndex) {
- return applyTransformations(fromIndex, toIndex);
- } else if (fromIndex > toIndex) {
- return revertTransformations(fromIndex, toIndex);
- } else {
- return Collections.emptySet();
- }
- }
-
- private Set<IGLProperty> applyTransformations(int fromIndex, int toIndex) {
- int setSizeHint = 3 * (toIndex - fromIndex) + 10;
- Set<IGLProperty> changedProperties = new HashSet<IGLProperty>(setSizeHint);
-
- for (int i = fromIndex + 1; i <= toIndex; i++) {
- GLCall call = mGLCalls.get(i);
- for (IStateTransform f : call.getStateTransformations()) {
- try {
- f.apply(mState);
- IGLProperty changedProperty = f.getChangedProperty(mState);
- if (changedProperty != null) {
- changedProperties.addAll(getHierarchy(changedProperty));
- }
- } catch (Exception e) {
- GlTracePlugin.getDefault().logMessage("Error applying transformations for "
- + call);
- GlTracePlugin.getDefault().logMessage(e.toString());
- }
- }
- }
-
- return changedProperties;
- }
-
- private Set<IGLProperty> revertTransformations(int fromIndex, int toIndex) {
- int setSizeHint = 3 * (fromIndex - toIndex) + 10;
- Set<IGLProperty> changedProperties = new HashSet<IGLProperty>(setSizeHint);
-
- for (int i = fromIndex; i > toIndex; i--) {
- List<IStateTransform> transforms = mGLCalls.get(i).getStateTransformations();
- // When reverting transformations, iterate from the last to first so that the reversals
- // are performed in the correct sequence.
- for (int j = transforms.size() - 1; j >= 0; j--) {
- IStateTransform f = transforms.get(j);
- f.revert(mState);
-
- IGLProperty changedProperty = f.getChangedProperty(mState);
- if (changedProperty != null) {
- changedProperties.addAll(getHierarchy(changedProperty));
- }
- }
- }
-
- return changedProperties;
- }
-
- /**
- * Obtain the list of properties starting from the provided property up to
- * the root of GL state.
- */
- private List<IGLProperty> getHierarchy(IGLProperty changedProperty) {
- List<IGLProperty> changedProperties = new ArrayList<IGLProperty>(5);
- changedProperties.add(changedProperty);
-
- // add the entire parent chain until we reach the root
- IGLProperty prop = changedProperty;
- while ((prop = prop.getParent()) != null) {
- changedProperties.add(prop);
- }
-
- return changedProperties;
- }
-
- @Override
- public void addSelectionChangedListener(ISelectionChangedListener listener) {
- mTreeViewer.addSelectionChangedListener(listener);
- }
-
- @Override
- public ISelection getSelection() {
- return mTreeViewer.getSelection();
- }
-
- @Override
- public void removeSelectionChangedListener(ISelectionChangedListener listener) {
- mTreeViewer.removeSelectionChangedListener(listener);
- }
-
- @Override
- public void setSelection(ISelection selection) {
- mTreeViewer.setSelection(selection);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/format/GLAPISpec.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/format/GLAPISpec.java
deleted file mode 100644
index 57b587cb3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/format/GLAPISpec.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.format;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Model a single GL API function call's specification.
- */
-public class GLAPISpec {
- private static final String GL_SPECS_FILE = "/entries.in"; //$NON-NLS-1$
- private static final String GLES2_ENTRIES_HEADER_V1 =
- "# com.android.ide.eclipse.gltrace.glentries, v1"; //$NON-NLS-1$
- private static Map<String, GLAPISpec> sApiSpecs;
-
- private final String mGLFunction;
- private final GLDataTypeSpec mReturnType;
- private final List<GLDataTypeSpec> mArgs;
-
- private GLAPISpec(String glFunction, GLDataTypeSpec returnType, List<GLDataTypeSpec> args) {
- mGLFunction = glFunction;
- mReturnType = returnType;
- mArgs = args;
- }
-
- public String getFunction() {
- return mGLFunction;
- }
-
- public GLDataTypeSpec getReturnValue() {
- return mReturnType;
- }
-
- public List<GLDataTypeSpec> getArgs() {
- return mArgs;
- }
-
- public static Map<String, GLAPISpec> getSpecs() {
- if (sApiSpecs == null) {
- sApiSpecs = parseApiSpecs(GLAPISpec.class.getResourceAsStream(GL_SPECS_FILE));
- }
-
- return sApiSpecs;
- }
-
- private static Map<String, GLAPISpec> parseApiSpecs(InputStream specFile) {
- BufferedReader reader = new BufferedReader(new InputStreamReader(specFile));
- Map<String, GLAPISpec> specs = new HashMap<String, GLAPISpec>(400);
-
- try{
- String header = reader.readLine().trim();
- assert header.equals(GLES2_ENTRIES_HEADER_V1);
-
- String line;
- while ((line = reader.readLine()) != null) {
- // strip away the comments
- int commentPos = line.indexOf('#');
- if (commentPos != -1) {
- line = line.substring(0, commentPos);
- }
- line = line.trim();
-
- // parse non empty lines
- if (line.length() > 0) {
- GLAPISpec spec = parseLine(line);
- specs.put(spec.getFunction(), spec);
- }
- }
-
- specFile.close();
- } catch (IOException e) {
- // this is unlikely to happen as the file is present within this .jar file.
- // Even if it does happen, we just return whatever we've read till now. The net
- // impact will be that the function calls will not be parsed fully and will just
- // display the function name.
- }
-
- return specs;
- }
-
- /**
- * Parse a GL API Specification entry from "/entries.in". Each line is of the format:
- * {@code returnType, funcName, arg*}. This method is package private for testing.
- */
- static GLAPISpec parseLine(String line) {
- List<String> words = Arrays.asList(line.split(","));
-
- String retType = words.get(0).trim();
- String func = words.get(1).trim();
- List<String> argDefinitions = words.subList(2, words.size());
-
- List<GLDataTypeSpec> glArgs = new ArrayList<GLDataTypeSpec>(argDefinitions.size()/2);
- for (String argDefn: argDefinitions) {
- // an argDefn is something like: "const GLvoid* data"
- argDefn = argDefn.trim();
- int lastSeparator = argDefn.lastIndexOf(' ');
- if (lastSeparator == -1) {
- // no space => a void type with no argument name
- glArgs.add(new GLDataTypeSpec(argDefn, null));
- } else {
- // everything upto the last space is the type
- String type = argDefn.substring(0, lastSeparator);
-
- // and the last word is the variable name
- String name = argDefn.substring(lastSeparator + 1);
- glArgs.add(new GLDataTypeSpec(type, name));
- }
- }
-
- return new GLAPISpec(func, new GLDataTypeSpec(retType, null), glArgs);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/format/GLDataTypeSpec.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/format/GLDataTypeSpec.java
deleted file mode 100644
index de9c9b686..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/format/GLDataTypeSpec.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.format;
-
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.Type;
-
-public class GLDataTypeSpec {
- private final String mCType;
- private final Type mType;
- private final String mName;
- private final boolean mIsPointer;
-
- public GLDataTypeSpec(String type, String name) {
- mCType = type;
- mName = name;
-
- mType = getDataType(type);
- mIsPointer = type.contains("*"); //$NON-NLS-1$
- }
-
- private Type getDataType(String type) {
- type = type.toLowerCase();
-
- // We use type.contains() rather than type.equals since we are matching against
- // the type name along with qualifiers. e.g. "void", "GLvoid" and "void*" should
- // all be assigned the same type.
- if (type.contains("boolean")) { //$NON-NLS-1$
- return Type.BOOL;
- } else if (type.contains("enum")) { //$NON-NLS-1$
- return Type.ENUM;
- } else if (type.contains("float") || type.contains("clampf")) { //$NON-NLS-1$ //$NON-NLS-2$
- return Type.FLOAT;
- } else if (type.contains("void")) { //$NON-NLS-1$
- return Type.VOID;
- } else if (type.contains("char")) { //$NON-NLS-1$
- return Type.CHAR;
- } else {
- // Matches all of the following types:
- // glclampx, gluint, glint, glshort, glsizei, glfixed,
- // glsizeiptr, glintptr, glbitfield, glfixed, glubyte.
- // We might do custom formatting for these types in the future.
- return Type.INT;
- }
- }
-
- public Type getDataType() {
- return mType;
- }
-
- public String getCType() {
- return mCType;
- }
-
- public String getArgName() {
- return mName;
- }
-
- public boolean isPointer() {
- return mIsPointer;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/format/GLMessageFormatter.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/format/GLMessageFormatter.java
deleted file mode 100644
index 6c34005ac..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/format/GLMessageFormatter.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.format;
-
-import com.android.ide.eclipse.gltrace.GLEnum;
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage;
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType;
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.DataType.Type;
-
-import java.util.List;
-import java.util.Map;
-
-/**
- * GLMessageFormatter is used to format and create a string representation for a {@link GLMessage}.
- * It is provided with a specification for all GL Functions. Using this information, each
- * GLMessage is parsed and formatted appropriately for display.
- */
-public class GLMessageFormatter {
- private static final String GL_NO_ERROR = "GL_NO_ERROR";
- private Map<String, GLAPISpec> mAPISpecs;
- private enum DataTypeContext { CONTEXT_ARGUMENT, CONTEXT_RETURNVALUE };
-
- public GLMessageFormatter(Map<String, GLAPISpec> specs) {
- mAPISpecs = specs;
- }
-
- public String formatGLMessage(GLMessage glMessage) {
- GLAPISpec apiSpec = mAPISpecs.get(glMessage.getFunction().toString());
- if (apiSpec == null) {
- return glMessage.getFunction().toString();
- }
-
- return formatCall(apiSpec, glMessage) + formatReturnValue(apiSpec, glMessage);
- }
-
- private String formatReturnValue(GLAPISpec apiSpec, GLMessage glMessage) {
- if (apiSpec.getReturnValue().getDataType() == Type.VOID) {
- return "";
- }
-
- GLDataTypeSpec returnSpec = apiSpec.getReturnValue();
- return String.format(" = (%s) %s", returnSpec.getCType(), //$NON-NLS-1$
- formatDataValue(glMessage.getReturnValue(),
- returnSpec,
- DataTypeContext.CONTEXT_RETURNVALUE));
- }
-
- private String formatCall(GLAPISpec apiSpec, GLMessage glMessage) {
- return String.format("%s(%s)", apiSpec.getFunction(), //$NON-NLS-1$
- formatArgs(glMessage, apiSpec.getArgs()));
- }
-
- private String formatArgs(GLMessage glMessage, List<GLDataTypeSpec> argSpecs) {
- int sizeEstimate = 10 + argSpecs.size() * 5;
- StringBuilder sb = new StringBuilder(sizeEstimate);
-
- for (int i = 0; i < argSpecs.size(); i++) {
- GLDataTypeSpec argSpec = argSpecs.get(i);
-
- if (argSpec.getDataType() == Type.VOID && !argSpec.isPointer()) {
- sb.append("void"); //$NON-NLS-1$
- } else {
- sb.append(argSpec.getArgName());
- sb.append(" = "); //$NON-NLS-1$
- sb.append(formatDataValue(glMessage.getArgs(i),
- argSpec,
- DataTypeContext.CONTEXT_ARGUMENT));
- }
-
- if (i < argSpecs.size() - 1) {
- sb.append(", "); //$NON-NLS-1$
- }
- }
-
- return sb.toString();
- }
-
- private String formatDataValue(DataType var, GLDataTypeSpec typeSpec, DataTypeContext context) {
- if (typeSpec.isPointer()) {
- return formatPointer(var, typeSpec.getDataType());
- }
-
- switch (typeSpec.getDataType()) {
- case VOID:
- return "";
- case BOOL:
- return Boolean.toString(var.getBoolValue(0));
- case FLOAT:
- return String.format("%f", var.getFloatValue(0)); //$NON-NLS-1$
- case INT:
- return Integer.toString(var.getIntValue(0));
- case ENUM:
- if (var.getIntValue(0) == 0 && context == DataTypeContext.CONTEXT_RETURNVALUE) {
- return GL_NO_ERROR;
- } else {
- return GLEnum.valueOf(var.getIntValue(0)).toString();
- }
- default:
- return "(unknown type)"; //$NON-NLS-1$
- }
- }
-
- private String formatPointer(DataType var, Type typeSpec) {
- if (var.getType() != typeSpec && !isEnumTypeWithIntData(var, typeSpec)) {
- // the type of the data in the message does not match expected specification.
- // in such a case, just print the data as a pointer and don't try to interpret it.
- if (var.getIntValueCount() > 0) {
- return String.format("0x%x", var.getIntValue(0)); //$NON-NLS-1$
- } else {
- return "0x??"; //$NON-NLS-1$
- }
- }
-
- // Display as array if possible
- switch (typeSpec) {
- case BOOL:
- return var.getBoolValueList().toString();
- case FLOAT:
- return var.getFloatValueList().toString();
- case INT:
- return var.getIntValueList().toString();
- case CHAR:
- return var.getCharValueList().get(0).toStringUtf8();
- case ENUM:
- List<Integer> vals = var.getIntValueList();
- StringBuilder sb = new StringBuilder(vals.size() * 5);
- sb.append('[');
- for (Integer v: vals) {
- sb.append(GLEnum.valueOf(v.intValue()));
- }
- sb.append(']');
- return sb.toString();
- case VOID:
- if (var.getRawBytesList().size() > 0) {
- return String.format("[ %d bytes ]", var.getRawBytesList().get(0).size()); //$NON-NLS-1$
- }
- return "[]"; //$NON-NLS-1$
- }
-
- // We have a pointer, but we don't have the data pointed to.
- // Just format and return the pointer (points to device memory)
- if (var.getIntValue(0) == 0) {
- return "NULL"; //$NON-NLS-1$
- } else {
- return String.format("0x%x", var.getIntValue(0)); //$NON-NLS-1$
- }
- }
-
- private boolean isEnumTypeWithIntData(DataType var, Type typeSpec) {
- return var.getType() == Type.INT && typeSpec == Type.ENUM;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/model/GLCall.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/model/GLCall.java
deleted file mode 100644
index 0f6a11646..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/model/GLCall.java
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.model;
-
-import com.android.ide.eclipse.gltrace.GLProtoBuf;
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.Function;
-import com.android.ide.eclipse.gltrace.state.transforms.IStateTransform;
-import com.android.utils.SparseArray;
-
-import java.util.Collections;
-import java.util.List;
-
-/**
- * A GLCall is the in memory representation of a single {@link GLProtoBuf.GLMessage}.
- *
- * Some protocol buffer messages have a large amount of image data packed in them. Rather
- * than storing all of that in memory, the GLCall stores a thumbnail image, and an offset
- * into the trace file corresponding to original protocol buffer message. If full image data
- * is required, the protocol buffer message can be recreated by reading the trace at the
- * specified offset.
- */
-public class GLCall {
- /** Marker name provided by a {@link Function#glPushGroupMarkerEXT} call. */
- public static final int PROPERTY_MARKERNAME = 0;
-
- /** Size argument in a {@link Function#glVertexAttribPointerData} call. */
- public static final int PROPERTY_VERTEX_ATTRIB_POINTER_SIZE = 1;
-
- /** Type argument in a {@link Function#glVertexAttribPointerData} call. */
- public static final int PROPERTY_VERTEX_ATTRIB_POINTER_TYPE = 2;
-
- /** Data argument in a {@link Function#glVertexAttribPointerData} call. */
- public static final int PROPERTY_VERTEX_ATTRIB_POINTER_DATA = 3;
-
- /** Index of this call in the trace. */
- private int mIndex;
-
- /** Time on device when this call was invoked. */
- private final long mStartTime;
-
- /** Offset of the protobuf message corresponding to this call in the trace file. */
- private final long mTraceFileOffset;
-
- /** Flag indicating whether the original protobuf message included FB data. */
- private final boolean mHasFb;
-
- /** Full string representation of this call. */
- private final String mDisplayString;
-
- /** The actual GL Function called. */
- private final Function mFunction;
-
- /** GL Context identifier corresponding to the context of this call. */
- private final int mContextId;
-
- /** Duration of this call (MONOTONIC/wall clock time). */
- private final int mWallDuration;
-
- /** Duration of this call (THREAD time). */
- private final int mThreadDuration;
-
- /** List of state transformations performed by this call. */
- private List<IStateTransform> mStateTransforms = Collections.emptyList();
-
- /** Error conditions while creating state transforms for this call. */
- private String mStateTransformationCreationErrorMessage;
-
- /** List of properties associated to this call. */
- private SparseArray<Object> mProperties;
-
- public GLCall(int index, long startTime, long traceFileOffset, String displayString,
- Function function, boolean hasFb, int contextId,
- int wallTime, int threadTime) {
- mIndex = index;
- mStartTime = startTime;
- mTraceFileOffset = traceFileOffset;
- mDisplayString = displayString;
- mFunction = function;
- mHasFb = hasFb;
- mContextId = contextId;
- mWallDuration = wallTime;
- mThreadDuration = threadTime;
- }
-
- public int getIndex() {
- return mIndex;
- }
-
- public void setIndex(int i) {
- mIndex = i;
- }
-
- public long getOffsetInTraceFile() {
- return mTraceFileOffset;
- }
-
- public Function getFunction() {
- return mFunction;
- }
-
- public int getContextId() {
- return mContextId;
- }
-
- public boolean hasFb() {
- return mHasFb;
- }
-
- public long getStartTime() {
- return mStartTime;
- }
-
- public int getWallDuration() {
- return mWallDuration;
- }
-
- public int getThreadDuration() {
- return mThreadDuration;
- }
-
- public void setStateTransformations(List<IStateTransform> transforms) {
- mStateTransforms = transforms;
- }
-
- public void setStateTransformationCreationError(String errorMessage) {
- mStateTransformationCreationErrorMessage = errorMessage;
- }
-
- public boolean hasErrors() {
- return mStateTransformationCreationErrorMessage != null;
- }
-
- public String getError() {
- return mStateTransformationCreationErrorMessage;
- }
-
- public List<IStateTransform> getStateTransformations() {
- return mStateTransforms;
- }
-
- @Override
- public String toString() {
- return mDisplayString;
- }
-
- /**
- * Associate a certain value to the property name. Property names are defined
- * as constants in {@link GLCall}.
- */
- public void addProperty(int propertyName, Object value) {
- if (mProperties == null) {
- mProperties = new SparseArray<Object>(1);
- }
-
- mProperties.put(propertyName, value);
- }
-
- /**
- * Obtain the value for the given property. Returns null if no such property
- * is associated with this {@link GLCall}.
- */
- public Object getProperty(int propertyName) {
- if (mProperties == null) {
- return null;
- }
-
- return mProperties.get(propertyName);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/model/GLFrame.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/model/GLFrame.java
deleted file mode 100644
index 5ff07a4f9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/model/GLFrame.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.model;
-
-/**
- * A GLFrame is used to keep track of the start and end {@link GLCall} indices
- * for each OpenGL frame.
- */
-public class GLFrame {
- private final int mIndex;
- private final int mStartCallIndex;
- private final int mEndCallIndex;
-
- /**
- * Construct a {@link GLFrame} given the range of {@link GLCall}s spanning this frame.
- * @param frameIndex index of this frame in the trace.
- * @param startCallIndex index of the first call in this frame (inclusive).
- * @param endCallIndex index of the last call in this frame (exclusive).
- */
- public GLFrame(int frameIndex, int startCallIndex, int endCallIndex) {
- mIndex = frameIndex;
- mStartCallIndex = startCallIndex;
- mEndCallIndex = endCallIndex;
- }
-
- public int getIndex() {
- return mIndex;
- }
-
- public int getStartIndex() {
- return mStartCallIndex;
- }
-
- public int getEndIndex() {
- return mEndCallIndex;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/model/GLTrace.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/model/GLTrace.java
deleted file mode 100644
index 766764466..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/model/GLTrace.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.model;
-
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage;
-import com.android.ide.eclipse.gltrace.ProtoBufUtils;
-import com.android.ide.eclipse.gltrace.TraceFileInfo;
-import com.android.ide.eclipse.gltrace.TraceFileReader;
-
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Display;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.RandomAccessFile;
-import java.util.Collections;
-import java.util.List;
-
-/** GLTrace is the in memory model of a OpenGL trace file. */
-public class GLTrace {
- private static final TraceFileReader sTraceFileReader = new TraceFileReader();
-
- /** Information regarding the trace file. */
- private final TraceFileInfo mTraceFileInfo;
-
- /** List of frames in the trace. */
- private final List<GLFrame> mGLFrames;
-
- /** List of GL Calls comprising the trace. */
- private final List<GLCall> mGLCalls;
-
- /** List of context ids used by the application. */
- private List<Integer> mContextIds;
-
- public GLTrace(TraceFileInfo traceFileInfo, List<GLFrame> glFrames, List<GLCall> glCalls,
- List<Integer> contextIds) {
- mTraceFileInfo = traceFileInfo;
- mGLFrames = glFrames;
- mGLCalls = glCalls;
- mContextIds = contextIds;
- }
-
- public List<GLFrame> getFrames() {
- return mGLFrames;
- }
-
- public GLFrame getFrame(int i) {
- return mGLFrames.get(i);
- }
-
- public List<GLCall> getGLCalls() {
- return mGLCalls;
- }
-
- public List<GLCall> getGLCallsForFrame(int frameIndex) {
- if (frameIndex >= mGLFrames.size()) {
- return Collections.emptyList();
- }
-
- GLFrame frame = mGLFrames.get(frameIndex);
- return mGLCalls.subList(frame.getStartIndex(), frame.getEndIndex());
- }
-
- public Image getImage(GLCall c) {
- if (!c.hasFb()) {
- return null;
- }
-
- if (isTraceFileModified()) {
- return null;
- }
-
- RandomAccessFile file;
- try {
- file = new RandomAccessFile(mTraceFileInfo.getPath(), "r"); //$NON-NLS-1$
- } catch (FileNotFoundException e1) {
- return null;
- }
-
- GLMessage m = null;
- try {
- m = sTraceFileReader.getMessageAtOffset(file, c.getOffsetInTraceFile());
- } catch (Exception e) {
- return null;
- } finally {
- try {
- file.close();
- } catch (IOException e) {
- // ignore exception while closing file
- }
- }
-
- return ProtoBufUtils.getImage(Display.getCurrent(), m);
- }
-
- private boolean isTraceFileModified() {
- File f = new File(mTraceFileInfo.getPath());
- return f.length() != mTraceFileInfo.getSize()
- || f.lastModified() != mTraceFileInfo.getLastModificationTime();
- }
-
- public List<Integer> getContexts() {
- return mContextIds;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/DisplayRadix.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/DisplayRadix.java
deleted file mode 100644
index 935f4d79c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/DisplayRadix.java
+++ /dev/null
@@ -1,21 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state;
-
-public enum DisplayRadix {
- DECIMAL, HEX
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLAbstractAtomicProperty.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLAbstractAtomicProperty.java
deleted file mode 100644
index cb96312b8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLAbstractAtomicProperty.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state;
-
-
-/**
- * Abstract implementation of {@link IGLProperty}. This provides the basics that can be
- * used by leaf level properties.
- */
-public abstract class GLAbstractAtomicProperty implements IGLProperty {
- private final GLStateType mType;
- private IGLProperty mParent;
-
- public GLAbstractAtomicProperty(GLStateType type) {
- mType = type;
- }
-
- @Override
- public GLStateType getType() {
- return mType;
- }
-
- @Override
- public IGLProperty getParent() {
- return mParent;
- }
-
- @Override
- public void setParent(IGLProperty parent) {
- mParent = parent;
- }
-
- @Override
- public boolean isComposite() {
- return false;
- }
-
- @Override
- public IGLProperty clone() {
- try {
- return (IGLProperty) super.clone();
- } catch (CloneNotSupportedException e) {
- return null;
- }
- }
-
- @Override
- public void prettyPrint(StatePrettyPrinter pp) {
- pp.prettyPrint(mType, getStringValue());
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLBooleanProperty.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLBooleanProperty.java
deleted file mode 100644
index 8332b0a65..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLBooleanProperty.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state;
-
-
-/** Properties that hold boolean values. */
-public final class GLBooleanProperty extends GLAbstractAtomicProperty {
- private final Boolean mDefaultValue;
- private Boolean mCurrentValue;
-
- public GLBooleanProperty(GLStateType name, Boolean defaultValue) {
- super(name);
-
- mDefaultValue = mCurrentValue = defaultValue;
- }
-
- @Override
- public boolean isDefault() {
- return mDefaultValue != null & mDefaultValue.equals(mCurrentValue);
- }
-
- public void setValue(Boolean newValue) {
- mCurrentValue = newValue;
- }
-
- @Override
- public String getStringValue() {
- return mCurrentValue.toString();
- }
-
- @Override
- public String toString() {
- return getType() + "=" + getStringValue(); //$NON-NLS-1$
- }
-
- @Override
- public void setValue(Object value) {
- if (value instanceof Boolean) {
- mCurrentValue = (Boolean) value;
- } else {
- throw new IllegalArgumentException("Attempt to set non-boolean value for " //$NON-NLS-1$
- + getType());
- }
- }
-
- @Override
- public Object getValue() {
- return mCurrentValue;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLCompositeProperty.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLCompositeProperty.java
deleted file mode 100644
index ff8b83a86..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLCompositeProperty.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state;
-
-import java.util.Collection;
-import java.util.EnumMap;
-import java.util.Map;
-
-/**
- * A composite property is a container for multiple named properties, kind of like a dictionary.
- */
-public class GLCompositeProperty implements IGLProperty {
- private final GLStateType mType;
- private final Map<GLStateType, IGLProperty> mPropertiesMap;
- private IGLProperty mParent;
-
- /** Construct a composite property given a list of {@link IGLProperty} objects. */
- public GLCompositeProperty(GLStateType type, IGLProperty... iglProperties) {
- mType = type;
- mPropertiesMap = new EnumMap<GLStateType, IGLProperty>(GLStateType.class);
-
- for (IGLProperty p : iglProperties) {
- mPropertiesMap.put(p.getType(), p);
- p.setParent(this);
- }
- }
-
- public Collection<IGLProperty> getProperties() {
- return mPropertiesMap.values();
- }
-
- public IGLProperty getProperty(GLStateType name) {
- return mPropertiesMap.get(name);
- }
-
- @Override
- public GLCompositeProperty clone() {
- IGLProperty []props = new IGLProperty[mPropertiesMap.size()];
-
- int i = 0;
- for (IGLProperty p : mPropertiesMap.values()) {
- props[i++] = p.clone();
- }
-
- return new GLCompositeProperty(getType(), props);
- }
-
- @Override
- public String toString() {
- StringBuffer sb = new StringBuffer();
- sb.append("GLCompositeProperty {"); //$NON-NLS-1$
-
- for (IGLProperty p : mPropertiesMap.values()) {
- sb.append(p.toString());
- sb.append(", "); //$NON-NLS-1$
- }
-
- sb.append("}");
- return sb.toString();
- }
-
- @Override
- public String getStringValue() {
- // This method is called for displaying objects in the UI.
- // We do not display any values for composites in the UI as they are only intermediate
- // nodes in the tree.
- return "";
- }
-
- @Override
- public GLStateType getType() {
- return mType;
- }
-
- @Override
- public boolean isComposite() {
- return true;
- }
-
- @Override
- public boolean isDefault() {
- for (IGLProperty p : mPropertiesMap.values()) {
- if (!p.isDefault()) {
- return false;
- }
- }
-
- return true;
- }
-
- @Override
- public IGLProperty getParent() {
- return mParent;
- }
-
- @Override
- public void setParent(IGLProperty parent) {
- mParent = parent;
- }
-
- @Override
- public void setValue(Object value) {
- throw new UnsupportedOperationException(
- "Values cannot be set for composite properties."); //$NON-NLS-1$
- }
-
- @Override
- public Object getValue() {
- throw new UnsupportedOperationException(
- "Values cannot be obtained for composite properties."); //$NON-NLS-1$
- }
-
- @Override
- public void prettyPrint(StatePrettyPrinter pp) {
- pp.prettyPrint(mType, null);
- pp.incrementIndentLevel();
- for (IGLProperty p : mPropertiesMap.values()) {
- p.prettyPrint(pp);
- }
- pp.decrementIndentLevel();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLEnumProperty.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLEnumProperty.java
deleted file mode 100644
index a3acbd4c8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLEnumProperty.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state;
-
-import com.android.ide.eclipse.gltrace.GLEnum;
-
-/** Properties that hold a {@link GLEnum}. */
-public final class GLEnumProperty extends GLAbstractAtomicProperty {
- private GLEnum mCurrentValue;
- private final GLEnum mDefaultValue;
-
- public GLEnumProperty(GLStateType name, GLEnum defaultValue) {
- super(name);
-
- mCurrentValue = mDefaultValue = defaultValue;
- }
-
- @Override
- public boolean isDefault() {
- return mDefaultValue == mCurrentValue;
- }
-
- public void setValue(GLEnum newValue) {
- mCurrentValue = newValue;
- }
-
- @Override
- public String getStringValue() {
- return mCurrentValue.toString();
- }
-
- @Override
- public String toString() {
- return getType() + "=" + getStringValue(); //$NON-NLS-1$
- }
-
- @Override
- public void setValue(Object value) {
- if (value instanceof GLEnum) {
- mCurrentValue = (GLEnum) value;
- } else {
- throw new IllegalArgumentException("Attempt to set invalid value for " + getType()); //$NON-NLS-1$
- }
- }
-
- @Override
- public Object getValue() {
- return mCurrentValue;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLFloatProperty.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLFloatProperty.java
deleted file mode 100644
index 387a88c6d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLFloatProperty.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state;
-
-/** Properties that hold float values. */
-public class GLFloatProperty extends GLAbstractAtomicProperty {
- private final Float mDefaultValue;
- private Float mCurrentValue;
-
- public GLFloatProperty(GLStateType name, Float defaultValue) {
- super(name);
-
- mDefaultValue = mCurrentValue = defaultValue;
- }
-
- @Override
- public boolean isDefault() {
- return Math.abs(mCurrentValue - mDefaultValue) < 0.000000001;
- }
-
- public void setValue(Float newValue) {
- mCurrentValue = newValue;
- }
-
- @Override
- public void setValue(Object value) {
- if (value instanceof Float) {
- mCurrentValue = (Float) value;
- } else {
- throw new IllegalArgumentException("Attempt to set non float value for "
- + getType());
- }
- }
-
- @Override
- public Object getValue() {
- return mCurrentValue;
- }
-
- @Override
- public String getStringValue() {
- return mCurrentValue.toString();
- }
-
- @Override
- public String toString() {
- return getType() + "=" + getStringValue(); //$NON-NLS-1$
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLIntegerProperty.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLIntegerProperty.java
deleted file mode 100644
index 7374ff087..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLIntegerProperty.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state;
-
-/** Properties that hold an integer value. */
-public class GLIntegerProperty extends GLAbstractAtomicProperty {
- private final Integer mDefaultValue;
- private Integer mCurrentValue;
- private final DisplayRadix mRadix;
-
- public GLIntegerProperty(GLStateType name, Integer defaultValue, DisplayRadix radix) {
- super(name);
-
- mDefaultValue = mCurrentValue = defaultValue;
- mRadix = radix;
- }
-
- public GLIntegerProperty(GLStateType name, Integer defaultValue) {
- this(name, defaultValue, DisplayRadix.DECIMAL);
- }
-
- @Override
- public boolean isDefault() {
- return mDefaultValue != null & mDefaultValue.equals(mCurrentValue);
- }
-
- public void setValue(Integer newValue) {
- mCurrentValue = newValue;
- }
-
- @Override
- public String getStringValue() {
- if (mRadix == DisplayRadix.HEX) {
- return String.format("0x%08x", Integer.valueOf(mCurrentValue));
- }
-
- return mCurrentValue.toString();
- }
-
- @Override
- public String toString() {
- return getType() + "=" + getStringValue(); //$NON-NLS-1$
- }
-
- @Override
- public void setValue(Object value) {
- if (value instanceof Integer) {
- mCurrentValue = (Integer) value;
- } else {
- throw new IllegalArgumentException("Attempt to set non-integer value for " //$NON-NLS-1$
- + getType());
- }
- }
-
- @Override
- public Object getValue() {
- return mCurrentValue;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLListProperty.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLListProperty.java
deleted file mode 100644
index 6840abff4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLListProperty.java
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-
-/**
- * A list property is a container for a list of properties, addressed by index.
- */
-public class GLListProperty implements IGLProperty {
- private final List<IGLProperty> mList;
- private final GLStateType mType;
- private IGLProperty mParent;
- private IGLProperty mTemplate;
-
- /**
- * Construct a list of properties of given size from the provided template.
- * @param template property that will be cloned and used as members of the list
- * @param size size of the list
- */
- public GLListProperty(GLStateType type, IGLProperty template, int size) {
- mType = type;
- mTemplate = template;
-
- mList = new ArrayList<IGLProperty>(size);
- for (int i = 0; i < size; i++) {
- IGLProperty p = template.clone();
- mList.add(p);
-
- p.setParent(this);
- }
- }
-
- private GLListProperty(GLStateType type, List<IGLProperty> props) {
- mList = props;
- mType = type;
-
- for (IGLProperty p : mList) {
- p.setParent(this);
- }
- }
-
- public List<IGLProperty> getList() {
- return mList;
- }
-
- public IGLProperty get(int index) {
- return mList.get(index);
- }
-
- public boolean add(IGLProperty property) {
- property.setParent(this);
- return mList.add(property);
- }
-
- public boolean remove(IGLProperty property) {
- return mList.remove(property);
- }
-
- public void set(int index, IGLProperty property) {
- ensureCapacity(index + 1);
- mList.set(index, property);
- property.setParent(this);
- }
-
- private void ensureCapacity(int capactiy) {
- for (int i = mList.size(); i < capactiy; i++) {
- mList.add(mTemplate);
- }
- }
-
- @Override
- public GLListProperty clone() {
- List<IGLProperty> props = new ArrayList<IGLProperty>(
- mList.size());
-
- for (IGLProperty p : mList) {
- props.add(p.clone());
- }
-
- return new GLListProperty(getType(), props);
- }
-
- @Override
- public String toString() {
- StringBuffer sb = new StringBuffer();
- sb.append("GLListProperty ["); //$NON-NLS-1$
-
- int i = 0;
- for (IGLProperty p : mList) {
- sb.append(i);
- sb.append(':');
- sb.append(p.toString());
- sb.append(", "); //$NON-NLS-1$
- i++;
- }
-
- sb.append("]");
- return sb.toString();
- }
-
- @Override
- public String getStringValue() {
- // This method is called for displaying objects in the UI.
- // We do not display any values for composites in the UI as they are only intermediate
- // nodes in the tree.
- return "";
- }
-
- @Override
- public GLStateType getType() {
- return mType;
- }
-
- @Override
- public boolean isComposite() {
- return true;
- }
-
- @Override
- public boolean isDefault() {
- return false;
- }
-
- @Override
- public IGLProperty getParent() {
- return mParent;
- }
-
- @Override
- public void setParent(IGLProperty parent) {
- mParent = parent;
- }
-
- public int indexOf(IGLProperty property) {
- return mList.indexOf(property);
- }
-
- @Override
- public void setValue(Object value) {
- throw new UnsupportedOperationException(
- "Values cannot be set for composite properties."); //$NON-NLS-1$
- }
-
- @Override
- public Object getValue() {
- throw new UnsupportedOperationException(
- "Values cannot be obtained for composite properties."); //$NON-NLS-1$
- }
-
- public int size() {
- return mList.size();
- }
-
- @Override
- public void prettyPrint(StatePrettyPrinter pp) {
- pp.prettyPrint(mType, null);
- pp.incrementIndentLevel();
- for (int i = 0; i < mList.size(); i++) {
- pp.prettyPrint(String.format(Locale.US, "Index %d:", i));
- IGLProperty p = mList.get(i);
- p.prettyPrint(pp);
- }
- pp.decrementIndentLevel();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLLongProperty.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLLongProperty.java
deleted file mode 100644
index 44c04ec57..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLLongProperty.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2014 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state;
-
-/** Properties that hold a long value. */
-public class GLLongProperty extends GLAbstractAtomicProperty {
- private final Long mDefaultValue;
- private Long mCurrentValue;
- private final DisplayRadix mRadix;
-
- public GLLongProperty(GLStateType name, Long defaultValue, DisplayRadix radix) {
- super(name);
-
- mDefaultValue = mCurrentValue = defaultValue;
- mRadix = radix;
- }
-
- public GLLongProperty(GLStateType name, Long defaultValue) {
- this(name, defaultValue, DisplayRadix.DECIMAL);
- }
-
- @Override
- public boolean isDefault() {
- return mDefaultValue != null & mDefaultValue.equals(mCurrentValue);
- }
-
- public void setValue(Long newValue) {
- mCurrentValue = newValue;
- }
-
- @Override
- public String getStringValue() {
- if (mRadix == DisplayRadix.HEX) {
- return String.format("0x%08x", Long.valueOf(mCurrentValue));
- }
-
- return mCurrentValue.toString();
- }
-
- @Override
- public String toString() {
- return getType() + "=" + getStringValue(); //$NON-NLS-1$
- }
-
- @Override
- public void setValue(Object value) {
- if (value instanceof Long) {
- mCurrentValue = (Long) value;
- } else {
- throw new IllegalArgumentException("Attempt to set non-integer value for " //$NON-NLS-1$
- + getType());
- }
- }
-
- @Override
- public Object getValue() {
- return mCurrentValue;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLObjectProperty.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLObjectProperty.java
deleted file mode 100644
index 703d4da6b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLObjectProperty.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state;
-
-import com.google.common.base.Joiner;
-
-import java.util.List;
-
-public class GLObjectProperty extends GLAbstractAtomicProperty {
- private final Object mDefaultValue;
- private Object mCurrentValue;
-
- private static final Joiner JOINER = Joiner.on(", "); //$NON-NLS-1$
-
- public GLObjectProperty(GLStateType type, Object defaultValue) {
- super(type);
-
- mDefaultValue = mCurrentValue = defaultValue;
- }
-
- @Override
- public boolean isDefault() {
- return mDefaultValue != null & mDefaultValue.equals(mCurrentValue);
- }
-
- @Override
- public void setValue(Object newValue) {
- mCurrentValue = newValue;
- }
-
- @Override
- public String getStringValue() {
- if (mCurrentValue == null) {
- return "null";
- } else {
- if (mCurrentValue instanceof List<?>) {
- return "[" + JOINER.join((List<?>) mCurrentValue) + "]"; //$NON-NLS-1$ //$NON-NLS-2$
- }
- return mCurrentValue.toString();
- }
- }
-
- @Override
- public String toString() {
- return getType() + "=" + getStringValue(); //$NON-NLS-1$
- }
-
- @Override
- public Object getValue() {
- return mCurrentValue;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLSparseArrayProperty.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLSparseArrayProperty.java
deleted file mode 100644
index c45002857..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLSparseArrayProperty.java
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Locale;
-
-import com.android.utils.SparseArray;
-
-public class GLSparseArrayProperty implements IGLProperty {
- private final GLStateType mType;
- private final IGLProperty mDefaultValue;
- private final boolean mCreateOnAccess;
- private final SparseArray<IGLProperty> mSparseArray;
- private IGLProperty mParent;
-
- public GLSparseArrayProperty(GLStateType type, IGLProperty defaultValue) {
- this(type, defaultValue, false);
- }
-
- /**
- * Constructs a sparse array property.
- * @param type GL state corresponding to this property
- * @param defaultValue default value of each item
- * @param createOnAccess create an item on access if it is not present
- */
- public GLSparseArrayProperty(GLStateType type, IGLProperty defaultValue,
- boolean createOnAccess) {
- mType = type;
- mDefaultValue = defaultValue;
- mCreateOnAccess = createOnAccess;
- mSparseArray = new SparseArray<IGLProperty>(20);
- }
-
- private GLSparseArrayProperty(GLStateType type, IGLProperty defaultValue,
- boolean createOnAccess, SparseArray<IGLProperty> contents) {
- mType = type;
- mDefaultValue = defaultValue;
- mCreateOnAccess = createOnAccess;
- mSparseArray = contents;
- }
-
- public List<IGLProperty> getValues() {
- List<IGLProperty> values = new ArrayList<IGLProperty>(mSparseArray.size());
-
- for (int i = 0; i < mSparseArray.size(); i++) {
- values.add(mSparseArray.valueAt(i));
- }
-
- return values;
- }
-
- public IGLProperty getProperty(int key) {
- IGLProperty p = mSparseArray.get(key);
- if (p == null && mCreateOnAccess) {
- add(key);
- p = mSparseArray.get(key);
- }
- return p;
- }
-
- public int keyFor(IGLProperty element) {
- int index = mSparseArray.indexOfValue(element);
- return mSparseArray.keyAt(index);
- }
-
- public void put(int key, IGLProperty element) {
- element.setParent(this);
- mSparseArray.put(key, element);
- }
-
- public void add(int key) {
- IGLProperty prop = mDefaultValue.clone();
- prop.setParent(this);
- mSparseArray.put(key, prop);
- }
-
- public void delete(int key) {
- mSparseArray.delete(key);
- }
-
- @Override
- public GLStateType getType() {
- return mType;
- }
-
- @Override
- public boolean isComposite() {
- return true;
- }
-
- @Override
- public boolean isDefault() {
- return false;
- }
-
- @Override
- public IGLProperty getParent() {
- return mParent;
- }
-
- @Override
- public void setParent(IGLProperty parent) {
- mParent = parent;
- }
-
- @Override
- public GLSparseArrayProperty clone() {
- SparseArray<IGLProperty> copy = new SparseArray<IGLProperty>(mSparseArray.size());
- for (int i = 0; i < mSparseArray.size(); i++) {
- int key = mSparseArray.keyAt(i);
- IGLProperty value = mSparseArray.get(key);
- copy.put(key, value);
- }
-
- return new GLSparseArrayProperty(mType, mDefaultValue, mCreateOnAccess, copy);
- }
-
- @Override
- public String getStringValue() {
- // This method is called for displaying objects in the UI.
- // We do not display any values for composites in the UI as they are only intermediate
- // nodes in the tree.
- return "";
- }
-
- @Override
- public void setValue(Object value) {
- throw new UnsupportedOperationException(
- "Values cannot be set for composite properties."); //$NON-NLS-1$
- }
-
- @Override
- public Object getValue() {
- throw new UnsupportedOperationException(
- "Values cannot be obtained for composite properties."); //$NON-NLS-1$
- }
-
- @Override
- public void prettyPrint(StatePrettyPrinter pp) {
- pp.prettyPrint(mType, null);
- pp.incrementIndentLevel();
- for (int i = 0; i < mSparseArray.size(); i++) {
- int key = mSparseArray.keyAt(i);
- pp.prettyPrint(String.format(Locale.US, "Index %d:", key));
- IGLProperty prop = mSparseArray.get(key);
-
- assert prop != null;
- if (prop != null) {
- prop.prettyPrint(pp);
- }
- }
- pp.decrementIndentLevel();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLState.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLState.java
deleted file mode 100644
index 04ce676c2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLState.java
+++ /dev/null
@@ -1,402 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state;
-
-import com.android.ide.eclipse.gltrace.GLEnum;
-import com.android.ide.eclipse.gltrace.state.DisplayRadix;
-
-import java.util.Collections;
-
-public class GLState {
- /** # of texture units modeled in the GL State. */
- public static final int TEXTURE_UNIT_COUNT = 32;
-
- /** # of vertex attributes */
- private static final int MAX_VERTEX_ATTRIBS = 16;
-
- private static GLState sGLState = new GLState();
-
- private IGLProperty createBufferBindings() {
- IGLProperty array, eArray, vArray;
-
- array = new GLIntegerProperty(GLStateType.ARRAY_BUFFER_BINDING, 0);
- eArray = new GLIntegerProperty(GLStateType.ELEMENT_ARRAY_BUFFER_BINDING, 0);
-
- vArray = new GLIntegerProperty(
- GLStateType.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_PER_INDEX, 0);
- IGLProperty vArray8 = new GLListProperty(GLStateType.VERTEX_ATTRIB_ARRAY_BUFFER_BINDINGS,
- vArray, MAX_VERTEX_ATTRIBS);
-
- return new GLCompositeProperty(
- GLStateType.BUFFER_BINDINGS,
- array,
- eArray,
- vArray8);
- }
-
- private IGLProperty createVertexAttribArrays() {
- IGLProperty enabled, size, stride, type, normalized, pointer;
-
- enabled = new GLBooleanProperty(GLStateType.VERTEX_ATTRIB_ARRAY_ENABLED, false);
- size = new GLIntegerProperty(GLStateType.VERTEX_ATTRIB_ARRAY_SIZE, 4);
- stride = new GLIntegerProperty(GLStateType.VERTEX_ATTRIB_ARRAY_STRIDE, 0);
- type = new GLEnumProperty(GLStateType.VERTEX_ATTRIB_ARRAY_TYPE, GLEnum.GL_FLOAT);
- normalized = new GLBooleanProperty(GLStateType.VERTEX_ATTRIB_ARRAY_NORMALIZED, false);
- pointer = new GLLongProperty(GLStateType.VERTEX_ATTRIB_ARRAY_POINTER, 0L,
- DisplayRadix.HEX);
-
- IGLProperty perVertexAttribArrayState = new GLCompositeProperty(
- GLStateType.VERTEX_ATTRIB_ARRAY_COMPOSITE,
- enabled,
- size,
- stride,
- type,
- normalized,
- pointer);
-
- return new GLListProperty(
- GLStateType.VERTEX_ATTRIB_ARRAY,
- perVertexAttribArrayState,
- MAX_VERTEX_ATTRIBS);
- }
-
- private IGLProperty createGenericVertexAttributeState() {
- IGLProperty v0 = new GLFloatProperty(GLStateType.GENERIC_VERTEX_ATTRIB_V0,
- Float.valueOf(0));
- IGLProperty v1 = new GLFloatProperty(GLStateType.GENERIC_VERTEX_ATTRIB_V1,
- Float.valueOf(0));
- IGLProperty v2 = new GLFloatProperty(GLStateType.GENERIC_VERTEX_ATTRIB_V2,
- Float.valueOf(0));
- IGLProperty v3 = new GLFloatProperty(GLStateType.GENERIC_VERTEX_ATTRIB_V3,
- Float.valueOf(0));
-
- IGLProperty perGenericVertexAttribState = new GLCompositeProperty(
- GLStateType.GENERIC_VERTEX_ATTRIBUTE_DATA_COMPOSITE,
- v0, v1, v2, v3);
-
- return new GLListProperty(
- GLStateType.GENERIC_VERTEX_ATTRIBUTES,
- perGenericVertexAttribState,
- MAX_VERTEX_ATTRIBS);
- }
-
- private IGLProperty createVboState() {
- IGLProperty size = new GLIntegerProperty(GLStateType.BUFFER_SIZE, Integer.valueOf(0));
- IGLProperty usage = new GLEnumProperty(GLStateType.BUFFER_USAGE, GLEnum.GL_STATIC_DRAW);
- IGLProperty data = new GLObjectProperty(GLStateType.BUFFER_DATA, new byte[0]);
- IGLProperty type = new GLEnumProperty(GLStateType.BUFFER_TYPE, GLEnum.GL_ARRAY_BUFFER);
-
- IGLProperty perVboState = new GLCompositeProperty(GLStateType.VBO_COMPOSITE,
- size, usage, data, type);
-
- return new GLSparseArrayProperty(GLStateType.VBO, perVboState);
- }
-
- private IGLProperty createVertexArrayData() {
- IGLProperty vertexAttribArrays = createVertexAttribArrays();
- IGLProperty bufferBindings = createBufferBindings();
- IGLProperty genericAttribs = createGenericVertexAttributeState();
- IGLProperty vboState = createVboState();
-
- return new GLCompositeProperty(GLStateType.VERTEX_ARRAY_DATA,
- genericAttribs,
- vertexAttribArrays,
- bufferBindings,
- vboState);
- }
-
- private IGLProperty createTransformationState() {
- IGLProperty viewPortX = new GLIntegerProperty(GLStateType.VIEWPORT_X, 0);
- IGLProperty viewPortY = new GLIntegerProperty(GLStateType.VIEWPORT_Y, 0);
- IGLProperty viewPortW = new GLIntegerProperty(GLStateType.VIEWPORT_WIDTH, 0);
- IGLProperty viewPortH = new GLIntegerProperty(GLStateType.VIEWPORT_HEIGHT, 0);
- IGLProperty viewPort = new GLCompositeProperty(GLStateType.VIEWPORT,
- viewPortX, viewPortY, viewPortW, viewPortH);
-
- IGLProperty clampNear = new GLFloatProperty(GLStateType.DEPTH_RANGE_NEAR,
- Float.valueOf(0.0f));
- IGLProperty clampFar = new GLFloatProperty(GLStateType.DEPTH_RANGE_FAR,
- Float.valueOf(1.0f));
- IGLProperty depthRange = new GLCompositeProperty(GLStateType.DEPTH_RANGE,
- clampNear,
- clampFar);
-
- IGLProperty transformationState = new GLCompositeProperty(GLStateType.TRANSFORMATION_STATE,
- viewPort,
- depthRange);
- return transformationState;
- }
-
- private IGLProperty createRasterizationState() {
- IGLProperty lineWidth = new GLFloatProperty(GLStateType.LINE_WIDTH, Float.valueOf(1.0f));
- IGLProperty cullFace = new GLBooleanProperty(GLStateType.CULL_FACE, Boolean.FALSE);
- IGLProperty cullFaceMode = new GLEnumProperty(GLStateType.CULL_FACE_MODE, GLEnum.GL_BACK);
- IGLProperty frontFace = new GLEnumProperty(GLStateType.FRONT_FACE, GLEnum.GL_CCW);
- IGLProperty polyOffsetFactor = new GLFloatProperty(GLStateType.POLYGON_OFFSET_FACTOR,
- Float.valueOf(0f));
- IGLProperty polyOffsetUnits = new GLFloatProperty(GLStateType.POLYGON_OFFSET_UNITS,
- Float.valueOf(0f));
- IGLProperty polyOffsetFill = new GLBooleanProperty(GLStateType.POLYGON_OFFSET_FILL,
- Boolean.FALSE);
-
- return new GLCompositeProperty(GLStateType.RASTERIZATION_STATE,
- lineWidth,
- cullFace,
- cullFaceMode,
- frontFace,
- polyOffsetFactor,
- polyOffsetUnits,
- polyOffsetFill);
- }
-
- private IGLProperty createPixelOperationsState() {
- IGLProperty scissorTest = new GLBooleanProperty(GLStateType.SCISSOR_TEST, Boolean.FALSE);
- IGLProperty scissorBoxX = new GLIntegerProperty(GLStateType.SCISSOR_BOX_X, 0);
- IGLProperty scissorBoxY = new GLIntegerProperty(GLStateType.SCISSOR_BOX_Y, 0);
- IGLProperty scissorBoxW = new GLIntegerProperty(GLStateType.SCISSOR_BOX_WIDTH, 0);
- IGLProperty scissorBoxH = new GLIntegerProperty(GLStateType.SCISSOR_BOX_HEIGHT, 0);
- IGLProperty scissorBox = new GLCompositeProperty(GLStateType.SCISSOR_BOX,
- scissorBoxX, scissorBoxY, scissorBoxW, scissorBoxH);
-
- IGLProperty stencilTest = new GLBooleanProperty(GLStateType.STENCIL_TEST, Boolean.FALSE);
- IGLProperty stencilFunc = new GLEnumProperty(GLStateType.STENCIL_FUNC, GLEnum.GL_ALWAYS);
- IGLProperty stencilMask = new GLIntegerProperty(GLStateType.STENCIL_VALUE_MASK,
- Integer.valueOf(0xffffffff), DisplayRadix.HEX);
- IGLProperty stencilRef = new GLIntegerProperty(GLStateType.STENCIL_REF,
- Integer.valueOf(0));
- IGLProperty stencilFail = new GLEnumProperty(GLStateType.STENCIL_FAIL, GLEnum.GL_KEEP);
- IGLProperty stencilPassDepthFail = new GLEnumProperty(GLStateType.STENCIL_PASS_DEPTH_FAIL,
- GLEnum.GL_KEEP);
- IGLProperty stencilPassDepthPass = new GLEnumProperty(GLStateType.STENCIL_PASS_DEPTH_PASS,
- GLEnum.GL_KEEP);
- IGLProperty stencilBackFunc = new GLEnumProperty(GLStateType.STENCIL_BACK_FUNC,
- GLEnum.GL_ALWAYS);
- IGLProperty stencilBackValueMask = new GLIntegerProperty(
- GLStateType.STENCIL_BACK_VALUE_MASK, Integer.valueOf(0xffffffff), DisplayRadix.HEX);
- IGLProperty stencilBackRef = new GLIntegerProperty(GLStateType.STENCIL_BACK_REF, 0);
- IGLProperty stencilBackFail = new GLEnumProperty(GLStateType.STENCIL_BACK_FAIL,
- GLEnum.GL_KEEP);
- IGLProperty stencilBackPassDepthFail = new GLEnumProperty(
- GLStateType.STENCIL_BACK_PASS_DEPTH_FAIL, GLEnum.GL_KEEP);
- IGLProperty stencilBackPassDepthPass = new GLEnumProperty(
- GLStateType.STENCIL_BACK_PASS_DEPTH_PASS, GLEnum.GL_KEEP);
- IGLProperty stencil = new GLCompositeProperty(GLStateType.STENCIL,
- stencilTest, stencilFunc,
- stencilMask, stencilRef, stencilFail,
- stencilPassDepthFail, stencilPassDepthPass,
- stencilBackFunc, stencilBackValueMask,
- stencilBackRef, stencilBackFail,
- stencilBackPassDepthFail, stencilBackPassDepthPass);
-
- IGLProperty depthTest = new GLBooleanProperty(GLStateType.DEPTH_TEST, Boolean.FALSE);
- IGLProperty depthFunc = new GLEnumProperty(GLStateType.DEPTH_FUNC, GLEnum.GL_LESS);
-
- IGLProperty blendEnabled = new GLBooleanProperty(GLStateType.BLEND_ENABLED, Boolean.FALSE);
- // FIXME: BLEND_SRC_RGB should be set to GL_ONE, but GL_LINES is already 0x1.
- IGLProperty blendSrcRgb = new GLEnumProperty(GLStateType.BLEND_SRC_RGB, GLEnum.GL_LINES);
- IGLProperty blendSrcAlpha = new GLEnumProperty(GLStateType.BLEND_SRC_ALPHA,
- GLEnum.GL_LINES);
- IGLProperty blendDstRgb = new GLEnumProperty(GLStateType.BLEND_DST_RGB, GLEnum.GL_NONE);
- IGLProperty blendDstAlpha = new GLEnumProperty(GLStateType.BLEND_DST_ALPHA,
- GLEnum.GL_NONE);
- IGLProperty blendEquationRgb = new GLEnumProperty(GLStateType.BLEND_EQUATION_RGB,
- GLEnum.GL_FUNC_ADD);
- IGLProperty blendEquationAlpha = new GLEnumProperty(GLStateType.BLEND_EQUATION_ALPHA,
- GLEnum.GL_FUNC_ADD);
- IGLProperty blend = new GLCompositeProperty(GLStateType.BLEND,
- blendEnabled, blendSrcRgb, blendSrcAlpha, blendDstRgb, blendDstAlpha,
- blendEquationRgb, blendEquationAlpha);
-
- IGLProperty dither = new GLBooleanProperty(GLStateType.DITHER, Boolean.TRUE);
-
- return new GLCompositeProperty(GLStateType.PIXEL_OPERATIONS,
- scissorTest, scissorBox, stencil,
- depthTest, depthFunc, blend, dither);
- }
-
- private IGLProperty createPixelPackState() {
- IGLProperty packAlignment = new GLIntegerProperty(GLStateType.PACK_ALIGNMENT,
- Integer.valueOf(4));
- IGLProperty unpackAlignment = new GLIntegerProperty(GLStateType.UNPACK_ALIGNMENT,
- Integer.valueOf(4));
- IGLProperty pixelPack = new GLCompositeProperty(GLStateType.PIXEL_PACKING,
- packAlignment, unpackAlignment);
- return pixelPack;
- }
-
- private IGLProperty createFramebufferState() {
- IGLProperty binding = new GLIntegerProperty(GLStateType.FRAMEBUFFER_BINDING, 0);
- GLCompositeProperty framebufferState = new GLCompositeProperty(
- GLStateType.FRAMEBUFFER_STATE,
- binding);
- return framebufferState;
- }
-
- private IGLProperty createTextureState() {
- IGLProperty activeTexture = new GLIntegerProperty(GLStateType.ACTIVE_TEXTURE_UNIT,
- Integer.valueOf(0));
-
- IGLProperty binding2D = new GLIntegerProperty(GLStateType.TEXTURE_BINDING_2D,
- Integer.valueOf(0));
- IGLProperty bindingCubeMap = new GLIntegerProperty(GLStateType.TEXTURE_BINDING_CUBE_MAP,
- Integer.valueOf(0));
- IGLProperty bindingExternal = new GLIntegerProperty(GLStateType.TEXTURE_BINDING_EXTERNAL,
- Integer.valueOf(0));
- IGLProperty perTextureUnitState = new GLCompositeProperty(
- GLStateType.PER_TEXTURE_UNIT_STATE, binding2D, bindingCubeMap, bindingExternal);
- IGLProperty textureUnitState = new GLListProperty(GLStateType.TEXTURE_UNITS,
- perTextureUnitState, TEXTURE_UNIT_COUNT);
-
- IGLProperty swizzleR = new GLEnumProperty(GLStateType.TEXTURE_SWIZZLE_R, GLEnum.GL_RED);
- IGLProperty swizzleG = new GLEnumProperty(GLStateType.TEXTURE_SWIZZLE_G, GLEnum.GL_GREEN);
- IGLProperty swizzleB = new GLEnumProperty(GLStateType.TEXTURE_SWIZZLE_B, GLEnum.GL_BLUE);
- IGLProperty swizzleA = new GLEnumProperty(GLStateType.TEXTURE_SWIZZLE_A, GLEnum.GL_ALPHA);
- IGLProperty minFilter = new GLEnumProperty(GLStateType.TEXTURE_MIN_FILTER,
- GLEnum.GL_NEAREST);
- IGLProperty magFilter = new GLEnumProperty(GLStateType.TEXTURE_MAG_FILTER,
- GLEnum.GL_NEAREST);
- IGLProperty wrapS = new GLEnumProperty(GLStateType.TEXTURE_WRAP_S, GLEnum.GL_REPEAT);
- IGLProperty wrapT = new GLEnumProperty(GLStateType.TEXTURE_WRAP_T, GLEnum.GL_REPEAT);
- IGLProperty wrapR = new GLEnumProperty(GLStateType.TEXTURE_WRAP_R, GLEnum.GL_REPEAT);
- IGLProperty minLod = new GLFloatProperty(GLStateType.TEXTURE_MIN_LOD, Float.valueOf(-1000));
- IGLProperty maxLod = new GLFloatProperty(GLStateType.TEXTURE_MAX_LOD, Float.valueOf(1000));
- IGLProperty baseLevel = new GLIntegerProperty(GLStateType.TEXTURE_BASE_LEVEL, 0);
- IGLProperty maxLevel = new GLIntegerProperty(GLStateType.TEXTURE_MAX_LEVEL, 1000);
- IGLProperty cmpMode = new GLEnumProperty(GLStateType.TEXTURE_COMPARE_MODE, GLEnum.GL_NONE);
- IGLProperty cmpFunc = new GLEnumProperty(GLStateType.TEXTURE_COMPARE_FUNC,
- GLEnum.GL_LEQUAL);
- IGLProperty immutableFormat = new GLBooleanProperty(GLStateType.TEXTURE_IMMUTABLE_FORMAT,
- Boolean.FALSE);
- IGLProperty immutableLevels = new GLIntegerProperty(GLStateType.TEXTURE_IMMUTABLE_LEVELS,
- 0);
-
- IGLProperty width = new GLIntegerProperty(GLStateType.TEXTURE_WIDTH, Integer.valueOf(-1));
- IGLProperty height = new GLIntegerProperty(GLStateType.TEXTURE_HEIGHT,
- Integer.valueOf(-1));
- IGLProperty format = new GLEnumProperty(GLStateType.TEXTURE_FORMAT,
- GLEnum.GL_INVALID_VALUE);
- IGLProperty imageType = new GLEnumProperty(GLStateType.TEXTURE_IMAGE_TYPE,
- GLEnum.GL_UNSIGNED_BYTE);
- IGLProperty image = new GLStringProperty(GLStateType.TEXTURE_IMAGE, null);
-
- IGLProperty perTextureLevelState = new GLCompositeProperty(
- GLStateType.PER_TEXTURE_LEVEL_STATE,
- width, height, format, imageType, image);
- IGLProperty mipmapState = new GLSparseArrayProperty(GLStateType.TEXTURE_MIPMAPS,
- perTextureLevelState, true);
-
- IGLProperty textureDefaultState = new GLCompositeProperty(GLStateType.PER_TEXTURE_STATE,
- swizzleR, swizzleG, swizzleB, swizzleA,
- minFilter, magFilter,
- wrapS, wrapT, wrapR,
- minLod, maxLod,
- baseLevel, maxLevel,
- cmpMode, cmpFunc,
- immutableFormat, immutableLevels,
- mipmapState);
- GLSparseArrayProperty textures = new GLSparseArrayProperty(GLStateType.TEXTURES,
- textureDefaultState);
- textures.add(0);
-
- return new GLCompositeProperty(GLStateType.TEXTURE_STATE,
- activeTexture,
- textureUnitState,
- textures);
- }
-
- private IGLProperty createProgramState() {
- IGLProperty currentProgram = new GLIntegerProperty(GLStateType.CURRENT_PROGRAM,
- Integer.valueOf(0));
-
- IGLProperty attachedShaderId = new GLIntegerProperty(GLStateType.ATTACHED_SHADER_ID,
- Integer.valueOf(0));
- IGLProperty attachedShaders = new GLSparseArrayProperty(GLStateType.ATTACHED_SHADERS,
- attachedShaderId);
-
- IGLProperty attributeName = new GLStringProperty(GLStateType.ATTRIBUTE_NAME, "");
- IGLProperty attributeType = new GLEnumProperty(GLStateType.ATTRIBUTE_TYPE,
- GLEnum.GL_FLOAT_MAT4);
- IGLProperty attributeSize = new GLIntegerProperty(GLStateType.ATTRIBUTE_SIZE,
- Integer.valueOf(1));
- IGLProperty attributeValue = new GLObjectProperty(GLStateType.ATTRIBUTE_VALUE,
- Collections.emptyList());
- IGLProperty perAttributeProperty = new GLCompositeProperty(GLStateType.PER_ATTRIBUTE_STATE,
- attributeName, attributeType, attributeSize, attributeValue);
- IGLProperty attributes = new GLSparseArrayProperty(GLStateType.ACTIVE_ATTRIBUTES,
- perAttributeProperty);
-
- IGLProperty uniformName = new GLStringProperty(GLStateType.UNIFORM_NAME, "");
- IGLProperty uniformType = new GLEnumProperty(GLStateType.UNIFORM_TYPE,
- GLEnum.GL_FLOAT_MAT4);
- IGLProperty uniformSize = new GLIntegerProperty(GLStateType.UNIFORM_SIZE,
- Integer.valueOf(1));
- IGLProperty uniformValue = new GLObjectProperty(GLStateType.UNIFORM_VALUE,
- Collections.emptyList());
- IGLProperty perUniformProperty = new GLCompositeProperty(GLStateType.PER_UNIFORM_STATE,
- uniformName, uniformType, uniformSize, uniformValue);
- IGLProperty uniforms = new GLSparseArrayProperty(GLStateType.ACTIVE_UNIFORMS,
- perUniformProperty);
-
- IGLProperty perProgramState = new GLCompositeProperty(GLStateType.PER_PROGRAM_STATE,
- attachedShaders, attributes, uniforms);
-
- IGLProperty programs = new GLSparseArrayProperty(GLStateType.PROGRAMS, perProgramState);
-
- return new GLCompositeProperty(GLStateType.PROGRAM_STATE,
- currentProgram, programs);
- }
-
- private IGLProperty createShaderState() {
- IGLProperty shaderType = new GLEnumProperty(GLStateType.SHADER_TYPE,
- GLEnum.GL_VERTEX_SHADER);
- IGLProperty shaderSource = new GLStringProperty(GLStateType.SHADER_SOURCE,
- ""); //$NON-NLS-1$
- IGLProperty perShaderState = new GLCompositeProperty(GLStateType.PER_SHADER_STATE,
- shaderType, shaderSource);
- return new GLSparseArrayProperty(GLStateType.SHADERS, perShaderState);
- }
-
- public static IGLProperty createDefaultES2State() {
- GLCompositeProperty glState = new GLCompositeProperty(GLStateType.GL_STATE_ES2,
- sGLState.createVertexArrayData(),
- sGLState.createFramebufferState(),
- sGLState.createTransformationState(),
- sGLState.createRasterizationState(),
- sGLState.createPixelOperationsState(),
- sGLState.createPixelPackState(),
- sGLState.createTextureState(),
- sGLState.createProgramState(),
- sGLState.createShaderState());
- return glState;
- }
-
- public static IGLProperty createDefaultES1State() {
- GLCompositeProperty glState = new GLCompositeProperty(GLStateType.GL_STATE_ES1,
- sGLState.createVertexArrayData(),
- sGLState.createFramebufferState(),
- sGLState.createTransformationState(),
- sGLState.createRasterizationState(),
- sGLState.createPixelOperationsState(),
- sGLState.createPixelPackState(),
- sGLState.createTextureState());
- return glState;
- }
-
- public static IGLProperty createDefaultState() {
- return new GLListProperty(GLStateType.GL_STATE, null, 0);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLStateType.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLStateType.java
deleted file mode 100644
index a0a7ce470..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLStateType.java
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state;
-
-/** The type for each OpenGL State Property {@link IGLProperty}. */
-public enum GLStateType {
- // Note: the indentation reflects the state hierarchy.
-
- GL_STATE("OpenGL State Variables"),
- GL_STATE_ES1("OpenGL ES 1.1 State"),
- GL_STATE_ES2("OpenGL ES 2.0 State"),
-
- VERTEX_ARRAY_DATA("Vertex Array Data"),
- GENERIC_VERTEX_ATTRIBUTES("Generic Vertex Attributes"),
- GENERIC_VERTEX_ATTRIBUTE_DATA_COMPOSITE("Generic Vertex Attribute Data"),
- GENERIC_VERTEX_ATTRIB_V0("x"),
- GENERIC_VERTEX_ATTRIB_V1("y"),
- GENERIC_VERTEX_ATTRIB_V2("z"),
- GENERIC_VERTEX_ATTRIB_V3("w"),
-
- VERTEX_ATTRIB_ARRAY("Vertex Attrib Array Properties"),
- VERTEX_ATTRIB_ARRAY_COMPOSITE("Vertex Attrib Array #n Properties"),
- VERTEX_ATTRIB_ARRAY_ENABLED("Vertex Attrib Array Enable"),
- VERTEX_ATTRIB_ARRAY_SIZE("Vertex Attrib Array Size"),
- VERTEX_ATTRIB_ARRAY_STRIDE("Vertex Attrib Array Stride"),
- VERTEX_ATTRIB_ARRAY_TYPE("Vertex Attrib Array Type"),
- VERTEX_ATTRIB_ARRAY_NORMALIZED("Vertex Attrib Array Normalized"),
- VERTEX_ATTRIB_ARRAY_POINTER("Vertex Attrib Array Pointer"),
-
- BUFFER_BINDINGS("Buffer Bindings"),
- ARRAY_BUFFER_BINDING("Current Buffer Binding"),
- ELEMENT_ARRAY_BUFFER_BINDING("Element Array Buffer Binding"),
- VERTEX_ATTRIB_ARRAY_BUFFER_BINDINGS("Attribute Array Buffer Bindings"),
- VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_PER_INDEX("Attribute Array Buffer Binding"),
-
- VBO("Vertex Buffer Objects"),
- VBO_COMPOSITE("Per VBO State"),
- BUFFER_SIZE("Size"),
- BUFFER_USAGE("Usage"),
- BUFFER_DATA("Data"),
- BUFFER_TYPE("Type"),
-
- TRANSFORMATION_STATE("Transformation State"),
- VIEWPORT("Viewport"),
- VIEWPORT_X("Lower Left X"),
- VIEWPORT_Y("Lower Left Y"),
- VIEWPORT_WIDTH("Width"),
- VIEWPORT_HEIGHT("Height"),
- DEPTH_RANGE("Depth Range"),
- DEPTH_RANGE_NEAR("Near Clipping Plane"),
- DEPTH_RANGE_FAR("Far Clipping Plane"),
-
- RASTERIZATION_STATE("Rasterization State"),
- LINE_WIDTH("Line Width"),
- CULL_FACE("Polygon Culling Enabled"),
- CULL_FACE_MODE("Cull front/back facing polygons"),
- FRONT_FACE("Polygon frontface CW/CCW indicator"),
- POLYGON_OFFSET_FACTOR("Polygon Offset Factor"),
- POLYGON_OFFSET_UNITS("Polygon Offset Units"),
- POLYGON_OFFSET_FILL("Polygon Offset Enable"),
-
- PIXEL_OPERATIONS("Pixel Operations"),
- SCISSOR_TEST("Scissoring enabled"),
- SCISSOR_BOX("Scissor Box"),
- SCISSOR_BOX_X("Lower Left X"),
- SCISSOR_BOX_Y("Lower Left Y"),
- SCISSOR_BOX_WIDTH("Width"),
- SCISSOR_BOX_HEIGHT("Height"),
- STENCIL("Stencil"),
- STENCIL_TEST("Stenciling enabled"),
- STENCIL_FUNC("Front Stencil Function"),
- STENCIL_VALUE_MASK("Front Stencil Mask"),
- STENCIL_REF("Front Stencil Reference Value"),
- STENCIL_FAIL("Front Stencil Fail Action"),
- STENCIL_PASS_DEPTH_FAIL("Front stencil depth buffer fail action"),
- STENCIL_PASS_DEPTH_PASS("Front stencil depth buffer pass action"),
- STENCIL_BACK_FUNC("Back stencil function"),
- STENCIL_BACK_VALUE_MASK("Back stencil mask"),
- STENCIL_BACK_REF("Back stencil reference value"),
- STENCIL_BACK_FAIL("Back stencil fail action"),
- STENCIL_BACK_PASS_DEPTH_FAIL("Back stencil depth buffer fail action"),
- STENCIL_BACK_PASS_DEPTH_PASS("Back stencil depth buffer pass action"),
- DEPTH_TEST("Depth buffer enabled"),
- DEPTH_FUNC("Depth buffer test function"),
- BLEND("Blending"),
- BLEND_ENABLED("Enabled"),
- BLEND_SRC_RGB("Source RGB function"),
- BLEND_SRC_ALPHA("Source A function"),
- BLEND_DST_RGB("Dest. RGB function"),
- BLEND_DST_ALPHA("Dest. A function"),
- BLEND_EQUATION_RGB("RGB Equation"),
- BLEND_EQUATION_ALPHA("Alpha Equation"),
- DITHER("Dithering enabled"),
-
- PIXEL_PACKING("Pixel Packing"),
- PACK_ALIGNMENT("Pack Alignment"),
- UNPACK_ALIGNMENT("Unpack Alignment"),
-
- TEXTURE_STATE("Texture State"),
- ACTIVE_TEXTURE_UNIT("Active Texture Unit"),
- TEXTURE_UNITS("Texture Units"),
- PER_TEXTURE_UNIT_STATE("Texture Unit Properties"),
- TEXTURE_BINDING_2D("TEXTURE_2D Binding"),
- TEXTURE_BINDING_CUBE_MAP("TEXTURE_CUBE_MAP Binding"),
- TEXTURE_BINDING_EXTERNAL("TEXTURE_EXTERNAL Binding"),
- TEXTURES("Textures"),
- PER_TEXTURE_STATE("Per Texture State"),
- TEXTURE_SWIZZLE_R("Red Component Swizzle"),
- TEXTURE_SWIZZLE_G("Green Component Swizzle"),
- TEXTURE_SWIZZLE_B("Blue Component Swizzle"),
- TEXTURE_SWIZZLE_A("Alpha Component Swizzle"),
- TEXTURE_MIN_FILTER("Minification Function"),
- TEXTURE_MAG_FILTER("Magnification Function"),
- TEXTURE_WRAP_S("Texcoord s Wrap Mode"),
- TEXTURE_WRAP_T("Texcoord t Wrap Mode"),
- TEXTURE_WRAP_R("Texcoord r Wrap Mode"),
- TEXTURE_MIN_LOD("Min Level of Detail"),
- TEXTURE_MAX_LOD("Max Level of Detail"),
- TEXTURE_BASE_LEVEL("Base Texture Array"),
- TEXTURE_MAX_LEVEL("Max Texture Array Level"),
- TEXTURE_COMPARE_MODE("Comparison Mode"),
- TEXTURE_COMPARE_FUNC("Comparison Function"),
- TEXTURE_IMMUTABLE_FORMAT("Size and format immutable?"),
- TEXTURE_IMMUTABLE_LEVELS("# of levels in immutable textures"),
- TEXTURE_MIPMAPS("Texture Mipmap State"),
- PER_TEXTURE_LEVEL_STATE("Per Texture Level State"),
- TEXTURE_FORMAT("Format"),
- TEXTURE_WIDTH("Width"),
- TEXTURE_HEIGHT("Height"),
- TEXTURE_IMAGE_TYPE("Image Type"),
- TEXTURE_IMAGE("Image"),
-
- PROGRAM_STATE("Program Object State"),
- CURRENT_PROGRAM("Current Program"),
- PROGRAMS("Programs"),
- PER_PROGRAM_STATE("Per Program State"),
- ATTACHED_SHADERS("Attached Shaders"),
- ATTACHED_SHADER_ID("Attached Shader ID"),
- ACTIVE_ATTRIBUTES("Attributes"),
- PER_ATTRIBUTE_STATE("Per Attribute State"),
- ATTRIBUTE_NAME("Name"),
- ATTRIBUTE_TYPE("Type"),
- ATTRIBUTE_SIZE("Size"),
- ATTRIBUTE_VALUE("Value"),
- ACTIVE_UNIFORMS("Uniforms"),
- PER_UNIFORM_STATE("Per Uniform State"),
- UNIFORM_NAME("Name"),
- UNIFORM_TYPE("Type"),
- UNIFORM_SIZE("Size"),
- UNIFORM_VALUE("Value"),
-
- SHADERS("Shader Objects"),
- PER_SHADER_STATE("Per Shader State"),
- SHADER_TYPE("Shader Type"),
- SHADER_SOURCE("Source"),
-
- FRAMEBUFFER_STATE("Framebuffer State"),
- FRAMEBUFFER_BINDING("Framebuffer Binding"),
- FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE("Framebuffer object type"),
- FRAMEBUFFER_ATTACHMENT_OBJECT_NAME("Framebuffer object name"),
- FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL("Framebuffer texture level"),
- FRAMEBUFFER_ATTACHEMENT_TEXTURE_CUBE_MAP_FACE("Framebuffer texture cubemap face");
-
- private final String mDescription;
-
- GLStateType(String description) {
- mDescription = description;
- }
-
- public String getDescription() {
- return mDescription;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLStringProperty.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLStringProperty.java
deleted file mode 100644
index d95651fe3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/GLStringProperty.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state;
-
-public class GLStringProperty extends GLAbstractAtomicProperty {
- private final String mDefaultValue;
- private String mCurrentValue;
-
- public GLStringProperty(GLStateType type, String defaultValue) {
- super(type);
-
- mDefaultValue = mCurrentValue = defaultValue;
- }
-
- @Override
- public boolean isDefault() {
- return mDefaultValue.equalsIgnoreCase(mCurrentValue);
- }
-
- @Override
- public void setValue(Object value) {
- if (value instanceof String) {
- mCurrentValue = (String) value;
- } else {
- throw new IllegalArgumentException("Attempt to set non-string value for " //$NON-NLS-1$
- + getType());
- }
- }
-
- public void setValue(String value) {
- mCurrentValue = value;
- }
-
- @Override
- public Object getValue() {
- return mCurrentValue;
- }
-
- @Override
- public String getStringValue() {
- return mCurrentValue;
- }
-
- @Override
- public String toString() {
- return getType() + "=" + getStringValue(); //$NON-NLS-1$
- };
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/IGLProperty.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/IGLProperty.java
deleted file mode 100644
index ed87fd231..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/IGLProperty.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state;
-
-
-/**
- * The GL state is modeled as a hierarchical set of properties, all of which implement
- * this interface.
- */
-public interface IGLProperty extends Cloneable {
- /** Obtain the type of the property. */
- GLStateType getType();
-
- /** Is this a composite property?
- * @return true if it is a list or structure of properties,
- * false if it is a leaf level atomic property
- * */
- boolean isComposite();
-
- /**
- * Is the currently set value the default?
- * @return true if current value matches the default (initial) value
- */
- boolean isDefault();
-
- /** Set the current value for this property. */
- void setValue(Object value);
-
- /** Get the current value for this property. */
- Object getValue();
-
- /** Get the string representation for this property. */
- String getStringValue();
-
- /**
- * Get the parent property that holds this property.
- * @return null if this property is at the top level, parent otherwise
- */
- IGLProperty getParent();
-
- /** Set the parent property that holds this property. */
- void setParent(IGLProperty parent);
-
- /** Deep clone this property. */
- IGLProperty clone();
-
- /** Pretty print current property value to the given writer. */
- void prettyPrint(StatePrettyPrinter pp);
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/StatePrettyPrinter.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/StatePrettyPrinter.java
deleted file mode 100644
index 0ad9aa4d7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/StatePrettyPrinter.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.utils.SdkUtils;
-
-public class StatePrettyPrinter {
- private static final int SPACES_PER_INDENT = 4;
- private final String mLineSeparator = SdkUtils.getLineSeparator();
-
- private StringBuilder mSb = new StringBuilder(1000);
- private int mIndentLevel = 0;
-
- public void prettyPrint(@NonNull GLStateType name, @Nullable String value) {
- indentLine(mIndentLevel * SPACES_PER_INDENT);
-
- mSb.append(name.toString());
-
- if (value != null) {
- mSb.append(':');
- mSb.append(value);
- }
- mSb.append(mLineSeparator);
- }
-
- public void prettyPrint(@NonNull String s) {
- indentLine(mIndentLevel * SPACES_PER_INDENT);
-
- mSb.append(s);
- mSb.append(mLineSeparator);
- }
-
- private void indentLine(int spaces) {
- for (int i = 0; i < spaces; i++) {
- mSb.append(' ');
- }
- }
-
- public void incrementIndentLevel() {
- mIndentLevel++;
- }
-
- public void decrementIndentLevel() {
- mIndentLevel--;
- }
-
- @Override
- public String toString() {
- return mSb.toString();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/BufferSubDataTransform.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/BufferSubDataTransform.java
deleted file mode 100644
index 393f1b9b7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/BufferSubDataTransform.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state.transforms;
-
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.Function;
-import com.android.ide.eclipse.gltrace.state.IGLProperty;
-
-import java.nio.ByteBuffer;
-
-/**
- * A {@link BufferSubDataTransform} updates a portion of the buffer data as specified by
- * the {@link Function#glBufferSubData} function.
- */
-public class BufferSubDataTransform implements IStateTransform {
- private final IGLPropertyAccessor mAccessor;
- private final int mOffset;
-
- private final byte[] mSubData;
- private byte[] mOldData;
- private byte[] mNewData;
-
- public BufferSubDataTransform(IGLPropertyAccessor accessor, int offset, byte[] data) {
- mAccessor = accessor;
- mOffset = offset;
- mSubData = data;
- }
-
- @Override
- public void apply(IGLProperty state) {
- IGLProperty property = mAccessor.getProperty(state);
- mOldData = (byte[]) property.getValue();
-
- if (mOldData != null) {
- mNewData = new byte[mOldData.length];
- ByteBuffer bb = ByteBuffer.wrap(mNewData);
-
- // copy all of the old buffer
- bb.put(mOldData);
- bb.rewind();
-
- // update with the sub buffer data at specified offset
- bb.position(mOffset);
- bb.put(mSubData);
- }
-
- property.setValue(mNewData);
- }
-
- @Override
- public void revert(IGLProperty state) {
- if (mOldData != null) {
- IGLProperty property = mAccessor.getProperty(state);
- property.setValue(mOldData);
- mOldData = null;
- }
- }
-
- @Override
- public IGLProperty getChangedProperty(IGLProperty state) {
- return mAccessor.getProperty(state);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/CurrentProgramPropertyAccessor.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/CurrentProgramPropertyAccessor.java
deleted file mode 100644
index 9cc3cb885..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/CurrentProgramPropertyAccessor.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state.transforms;
-
-import com.android.ide.eclipse.gltrace.state.GLIntegerProperty;
-import com.android.ide.eclipse.gltrace.state.GLStateType;
-import com.android.ide.eclipse.gltrace.state.IGLProperty;
-
-public class CurrentProgramPropertyAccessor implements IGLPropertyAccessor {
- private final int mContextId;
- private final GLStateType mStateCategory;
- private final int mLocation;
- private final GLStateType mStateType;
- private final IGLPropertyAccessor mCurrentProgramAccessor;
-
- public CurrentProgramPropertyAccessor(int contextid, GLStateType stateCategory,
- int location, GLStateType stateType) {
- mContextId = contextid;
- mStateCategory = stateCategory;
- mLocation = location;
- mStateType = stateType;
-
- mCurrentProgramAccessor = GLPropertyAccessor.makeAccessor(contextid,
- GLStateType.PROGRAM_STATE,
- GLStateType.CURRENT_PROGRAM);
- }
-
- @Override
- public IGLProperty getProperty(IGLProperty state) {
- // obtain the current program
- IGLProperty currentProgramProperty = mCurrentProgramAccessor.getProperty(state);
- if (!(currentProgramProperty instanceof GLIntegerProperty)) {
- return null;
- }
-
- Integer program = (Integer) currentProgramProperty.getValue();
-
- // now access the required program property
- return GLPropertyAccessor.makeAccessor(mContextId,
- GLStateType.PROGRAM_STATE,
- GLStateType.PROGRAMS,
- program,
- mStateCategory,
- Integer.valueOf(mLocation),
- mStateType).getProperty(state);
- }
-
- @Override
- public String getPath() {
- return String.format("PROGRAM_STATE/PROGRAMS/${program}/%s/%d/%s",
- mStateCategory, mLocation, mStateType);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/CurrentVboPropertyAccessor.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/CurrentVboPropertyAccessor.java
deleted file mode 100644
index bd1286d5b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/CurrentVboPropertyAccessor.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state.transforms;
-
-import com.android.ide.eclipse.gltrace.GLEnum;
-import com.android.ide.eclipse.gltrace.state.GLIntegerProperty;
-import com.android.ide.eclipse.gltrace.state.GLStateType;
-import com.android.ide.eclipse.gltrace.state.IGLProperty;
-
-/**
- * An {@link IGLPropertyAccessor} that retrieves the requested property in the
- * currently bound {@link GLEnum#GL_ARRAY_BUFFER} or {@link GLEnum#GL_ELEMENT_ARRAY_BUFFER}.
- */
-public class CurrentVboPropertyAccessor implements IGLPropertyAccessor {
- private final int mContextId;
- private final IGLPropertyAccessor mVboBindingAccessor;
- private final GLStateType mVboProperty;
-
- public CurrentVboPropertyAccessor(int contextId, GLEnum target, GLStateType vboProperty) {
- mContextId = contextId;
- mVboProperty = vboProperty;
-
- GLStateType vboType;
- if (target == GLEnum.GL_ARRAY_BUFFER) {
- vboType = GLStateType.ARRAY_BUFFER_BINDING;
- } else {
- vboType = GLStateType.ELEMENT_ARRAY_BUFFER_BINDING;
- }
-
- mVboBindingAccessor = GLPropertyAccessor.makeAccessor(contextId,
- GLStateType.VERTEX_ARRAY_DATA,
- GLStateType.BUFFER_BINDINGS,
- vboType);
- }
-
- @Override
- public IGLProperty getProperty(IGLProperty state) {
- // obtain the current bound buffer
- IGLProperty currentBinding = mVboBindingAccessor.getProperty(state);
- if (!(currentBinding instanceof GLIntegerProperty)) {
- return null;
- }
-
- Integer buffer = (Integer) currentBinding.getValue();
-
- return GLPropertyAccessor.makeAccessor(mContextId,
- GLStateType.VERTEX_ARRAY_DATA,
- GLStateType.VBO,
- buffer,
- mVboProperty).getProperty(state);
- }
-
- @Override
- public String getPath() {
- return String.format("VERTEX_ARRAY_DATA/VBO/${currentBuffer}/%s", mVboProperty);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/GLPropertyAccessor.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/GLPropertyAccessor.java
deleted file mode 100644
index be338be19..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/GLPropertyAccessor.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state.transforms;
-
-import com.android.ide.eclipse.gltrace.state.GLCompositeProperty;
-import com.android.ide.eclipse.gltrace.state.GLListProperty;
-import com.android.ide.eclipse.gltrace.state.GLSparseArrayProperty;
-import com.android.ide.eclipse.gltrace.state.GLStateType;
-import com.android.ide.eclipse.gltrace.state.IGLProperty;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * GLPropertyAccessor's can be used to extract a certain property from the provided
- * OpenGL State hierarchy.
- */
-public class GLPropertyAccessor implements IGLPropertyAccessor {
- private final int mContextId;
- private final List<GLPropertyExtractor> mExtractors;
-
- private GLPropertyAccessor(int contextId, List<GLPropertyExtractor> extractors) {
- mContextId = contextId;
- mExtractors = extractors;
- }
-
- @Override
- public IGLProperty getProperty(IGLProperty state) {
- IGLProperty root = ((GLListProperty) state).get(mContextId);
-
- for (GLPropertyExtractor e : mExtractors) {
- IGLProperty successor = e.getProperty(root);
- if (successor == null) {
- root = null;
- break;
- }
- root = successor;
- }
-
- return root;
- }
-
- /**
- * Factory method used to construct a {@link GLPropertyAccessor}.
- * @param contextId id of affected context
- * @param accessors list of accessor's to be used to navigate the property hierarchy. The
- * accessors are either Integers or {@link GLStateType} objects. Integers
- * are assumed to be indexes in a {@link GLListProperty} or
- * {@link GLSparseArrayProperty}, and the GLStateType enum objects are
- * used to query {@link GLCompositeProperty}'s.
- */
- public static IGLPropertyAccessor makeAccessor(int contextId, Object...accessors) {
- List<GLPropertyExtractor> extractors = new ArrayList<GLPropertyExtractor>();
-
- for (Object accessor : accessors) {
- if (accessor instanceof GLStateType) {
- extractors.add(new GLNamePropertyExtractor((GLStateType) accessor));
- } else if (accessor instanceof Integer) {
- extractors.add(new GLIndexPropertyExtractor((Integer) accessor));
- } else {
- throw new IllegalArgumentException("Unknown property (" + accessor
- + ") used to access members of IGLProperty");
- }
- }
-
- return new GLPropertyAccessor(contextId, extractors);
- }
-
- private interface GLPropertyExtractor {
- IGLProperty getProperty(IGLProperty p);
- }
-
- /** Extract properties by name. */
- private static class GLNamePropertyExtractor implements GLPropertyExtractor {
- private final GLStateType mType;
-
- public GLNamePropertyExtractor(GLStateType type) {
- mType = type;
- }
-
- @Override
- public IGLProperty getProperty(IGLProperty p) {
- if (p instanceof GLCompositeProperty) {
- return ((GLCompositeProperty) p).getProperty(mType);
- }
-
- return null;
- }
- }
-
- /** Extract properties by index. */
- private static class GLIndexPropertyExtractor implements GLPropertyExtractor {
- private final int mIndex;
-
- public GLIndexPropertyExtractor(int index) {
- mIndex = index;
- }
-
- @Override
- public IGLProperty getProperty(IGLProperty p) {
- if (p instanceof GLListProperty && mIndex >= 0) {
- return ((GLListProperty) p).get(mIndex);
- }
- if (p instanceof GLSparseArrayProperty) {
- return ((GLSparseArrayProperty) p).getProperty(mIndex);
- }
- return null;
- }
- }
-
- @Override
- public String getPath() {
- StringBuilder sb = new StringBuilder(mExtractors.size() * 10);
- for (GLPropertyExtractor e: mExtractors) {
- if (e instanceof GLNamePropertyExtractor) {
- sb.append(((GLNamePropertyExtractor) e).mType);
- } else {
- sb.append(((GLIndexPropertyExtractor) e).mIndex);
- }
- sb.append('/');
- }
-
- return sb.toString();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/IGLPropertyAccessor.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/IGLPropertyAccessor.java
deleted file mode 100644
index 5df21b950..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/IGLPropertyAccessor.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state.transforms;
-
-import com.android.ide.eclipse.gltrace.state.IGLProperty;
-
-/**
- * An {@link IGLPropertyAccessor} provides an interface to extract
- * a specific property from a composite property.
- */
-public interface IGLPropertyAccessor {
- /** Obtain a specific property from the given state. */
- IGLProperty getProperty(IGLProperty state);
-
- /** Returns the string representation of this property accessor. */
- String getPath();
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/IPredicate.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/IPredicate.java
deleted file mode 100644
index e31226ffb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/IPredicate.java
+++ /dev/null
@@ -1,21 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state.transforms;
-
-public interface IPredicate {
- boolean apply(Object value);
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/IStateTransform.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/IStateTransform.java
deleted file mode 100644
index de33a08f0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/IStateTransform.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state.transforms;
-
-import com.android.ide.eclipse.gltrace.state.IGLProperty;
-
-/**
- * This interface encapsulates a single change to the GL state. GL Calls that affect
- * multiple state variables would use a list of these state transformations.
- */
-public interface IStateTransform {
- /** Apply this transformation on the given state. */
- void apply(IGLProperty currentState);
-
- /** Revert this transformation from the given state. */
- void revert(IGLProperty currentState);
-
- /** Obtain the property that will be affected by this transformation. */
- IGLProperty getChangedProperty(IGLProperty currentState);
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/ListElementAddTransform.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/ListElementAddTransform.java
deleted file mode 100644
index dcf50d7e8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/ListElementAddTransform.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state.transforms;
-
-import com.android.ide.eclipse.gltrace.state.GLListProperty;
-import com.android.ide.eclipse.gltrace.state.IGLProperty;
-
-/**
- * A {@link ListElementAddTransform} provides the ability to add a new property to a list of
- * properties in the GL State.
- */
-public class ListElementAddTransform implements IStateTransform {
- private final IGLPropertyAccessor mAccessor;
- private final IGLProperty mElement;
-
- public ListElementAddTransform(IGLPropertyAccessor accessor, IGLProperty element) {
- mAccessor = accessor;
- mElement = element;
- }
-
- @Override
- public void apply(IGLProperty currentState) {
- GLListProperty list = getList(currentState);
- if (list != null) {
- list.add(mElement);
- }
- }
-
- @Override
- public void revert(IGLProperty currentState) {
- GLListProperty list = getList(currentState);
- if (list != null) {
- list.remove(mElement);
- }
- }
-
- @Override
- public IGLProperty getChangedProperty(IGLProperty currentState) {
- return getList(currentState);
- }
-
- private GLListProperty getList(IGLProperty state) {
- IGLProperty p = state;
-
- if (mAccessor != null) {
- p = mAccessor.getProperty(p);
- }
-
- if (p instanceof GLListProperty) {
- return (GLListProperty) p;
- } else {
- return null;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/Predicates.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/Predicates.java
deleted file mode 100644
index 0de8358c8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/Predicates.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state.transforms;
-
-public class Predicates {
- private static class IntegerPropertyEqualsPredicate implements IPredicate {
- private int mExpected;
-
- public IntegerPropertyEqualsPredicate(Integer expected) {
- mExpected = expected.intValue();
- }
-
- @Override
- public boolean apply(Object value) {
- return value instanceof Integer && ((Integer) value).intValue() == mExpected;
- }
- }
-
- public static IPredicate matchesInteger(int expected) {
- return new IntegerPropertyEqualsPredicate(expected);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/PropertyChangeTransform.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/PropertyChangeTransform.java
deleted file mode 100644
index 276f6f49b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/PropertyChangeTransform.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state.transforms;
-
-import com.android.ide.eclipse.gltrace.state.IGLProperty;
-
-/**
- * A PropertyChangeTransform object provides the ability to alter the value of a
- * single GL State variable. An optional predicate provides the ability to perform
- * the change only if the predicate succeeds.
- */
-public class PropertyChangeTransform implements IStateTransform {
- private final IGLPropertyAccessor mAccessor;
- private final Object mNewValue;
- private final IPredicate mPredicate;
- private Object mOldValue;
-
- /**
- * Construct a state transform that will extract the property using the accessor,
- * and modify its value to the provided value.
- */
- PropertyChangeTransform(IGLPropertyAccessor accessor, Object newValue) {
- this(accessor, newValue, null);
- }
-
- /**
- * Construct a state transform that will extract the property using the accessor,
- * check if the predicate function accepts the current value, and if so modify its
- * value to the provided value.
- */
- public PropertyChangeTransform(IGLPropertyAccessor accessor, Object newValue,
- IPredicate predicate) {
- mAccessor = accessor;
- mNewValue = newValue;
- mPredicate = predicate;
- mOldValue = null;
- }
-
- /** Apply the state transformation on the given OpenGL state. */
- @Override
- public void apply(IGLProperty state) {
- IGLProperty property = mAccessor.getProperty(state);
-
- assert mOldValue == null : "Transform cannot be applied multiple times";
- if (mPredicate != null) {
- // if predicate is not null, then first check if the current value
- // passes the predicate function.
- if (!mPredicate.apply(property.getValue())) {
- return;
- }
- }
-
- if (property != null) {
- mOldValue = property.getValue();
- property.setValue(mNewValue);
- } else {
- throw new RuntimeException("No such property: " + mAccessor.getPath());
- }
- }
-
- /**
- * Reverses the effect of this state transform. It restores the property's value to the same
- * state as it was before this transformation was applied. If this transform was never
- * {@link #apply(IGLProperty)}'ed, then performing a revert has no effect.
- */
- @Override
- public void revert(IGLProperty state) {
- if (mOldValue != null) {
- IGLProperty property = mAccessor.getProperty(state);
- property.setValue(mOldValue);
- mOldValue = null;
- }
- }
-
- /** Gets the property that will be affected by applying this transformation. */
- @Override
- public IGLProperty getChangedProperty(IGLProperty state) {
- if (mPredicate != null) {
- Object value = mOldValue == null ? mNewValue : mOldValue;
- if (!mPredicate.apply(value)) {
- // if the value doesn't match the predicate, then this property
- // is not altered.
- return null;
- }
- }
-
- return mAccessor.getProperty(state);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/SparseArrayElementAddTransform.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/SparseArrayElementAddTransform.java
deleted file mode 100644
index b7547bc9a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/SparseArrayElementAddTransform.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state.transforms;
-
-import com.android.ide.eclipse.gltrace.state.GLSparseArrayProperty;
-import com.android.ide.eclipse.gltrace.state.IGLProperty;
-
-/**
- * A {@link SparseArrayElementAddTransform} changes given state by adding an
- * element to a sparse array, if there is no item with the same key already.
- */
-public class SparseArrayElementAddTransform implements IStateTransform {
- private IGLPropertyAccessor mAccessor;
- private int mKey;
- private IGLProperty mOldValue;
-
- public SparseArrayElementAddTransform(IGLPropertyAccessor accessor, int key) {
- mAccessor = accessor;
- mKey = key;
- }
-
- @Override
- public void apply(IGLProperty currentState) {
- GLSparseArrayProperty propertyArray = getArray(currentState);
- if (propertyArray != null) {
- mOldValue = propertyArray.getProperty(mKey);
- if (mOldValue == null) {
- // add only if there is no item with this key already present
- propertyArray.add(mKey);
- }
- }
- }
-
- @Override
- public void revert(IGLProperty currentState) {
- GLSparseArrayProperty propertyArray = getArray(currentState);
- if (propertyArray != null) {
- if (mOldValue == null) {
- // delete only if we actually added this key
- propertyArray.delete(mKey);
- }
- }
- }
-
- @Override
- public IGLProperty getChangedProperty(IGLProperty currentState) {
- return getArray(currentState);
- }
-
- private GLSparseArrayProperty getArray(IGLProperty state) {
- IGLProperty p = state;
-
- if (mAccessor != null) {
- p = mAccessor.getProperty(p);
- }
-
- if (p instanceof GLSparseArrayProperty) {
- return (GLSparseArrayProperty) p;
- } else {
- return null;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/SparseArrayElementRemoveTransform.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/SparseArrayElementRemoveTransform.java
deleted file mode 100644
index c1ff211bd..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/SparseArrayElementRemoveTransform.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state.transforms;
-
-import com.android.ide.eclipse.gltrace.state.IGLProperty;
-
-/**
- * A {@link SparseArrayElementRemoveTransform} changes given state by removing an
- * element from a sparse array.
- */
-public class SparseArrayElementRemoveTransform implements IStateTransform {
- private final SparseArrayElementAddTransform mAddTransform;
-
- public SparseArrayElementRemoveTransform(IGLPropertyAccessor accessor, int key) {
- mAddTransform = new SparseArrayElementAddTransform(accessor, key);
- }
-
- @Override
- public void apply(IGLProperty currentState) {
- // applying a RemoveTransform is the same as reverting an AddTransform.
- mAddTransform.revert(currentState);
- }
-
- @Override
- public void revert(IGLProperty currentState) {
- // reverting a RemoveTransform is the same as applying an AddTransform.
- mAddTransform.apply(currentState);
- }
-
- @Override
- public IGLProperty getChangedProperty(IGLProperty currentState) {
- return mAddTransform.getChangedProperty(currentState);
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/StateTransformFactory.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/StateTransformFactory.java
deleted file mode 100644
index 023f84b6a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/StateTransformFactory.java
+++ /dev/null
@@ -1,1384 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state.transforms;
-
-import com.android.ide.eclipse.gltrace.FileUtils;
-import com.android.ide.eclipse.gltrace.GLEnum;
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage;
-import com.android.ide.eclipse.gltrace.state.GLState;
-import com.android.ide.eclipse.gltrace.state.GLStateType;
-import com.android.ide.eclipse.gltrace.state.IGLProperty;
-import com.google.common.io.Files;
-import com.google.protobuf.ByteString;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.EnumSet;
-import java.util.List;
-
-public class StateTransformFactory {
- private static final String TEXTURE_DATA_FILE_PREFIX = "tex"; //$NON-NLS-1$
- private static final String TEXTURE_DATA_FILE_SUFFIX = ".dat"; //$NON-NLS-1$
- private static EnumSet<GLEnum> sTexParameterPnameValues;
-
- /** Construct a list of transformations to be applied for the provided OpenGL call. */
- public static List<IStateTransform> getTransformsFor(GLMessage msg) {
- switch (msg.getFunction()) {
- case eglCreateContext:
- return transformsForEglCreateContext(msg);
- case glBindFramebuffer:
- return transformsForGlBindFramebuffer(msg);
-
- // vertex data
- case glVertexAttribPointer:
- return transformsForGlVertexAttribPointer(msg);
- case glVertexAttrib1f:
- case glVertexAttrib2f:
- case glVertexAttrib3f:
- case glVertexAttrib4f:
- return transformsForGlVertexAttribxf(msg);
- case glVertexAttrib1fv:
- case glVertexAttrib2fv:
- case glVertexAttrib3fv:
- case glVertexAttrib4fv:
- return transformsForGlVertexAttribxfv(msg);
- case glEnableVertexAttribArray:
- return transformsForGlEnableVertexAttribArray(msg);
- case glDisableVertexAttribArray:
- return transformsForGlDisableVertexAttribArray(msg);
-
- // VBO's
- case glBindBuffer:
- return transformsForGlBindBuffer(msg);
- case glGenBuffers:
- return transformsForGlGenBuffers(msg);
- case glDeleteBuffers:
- return transformsForGlDeleteBuffers(msg);
- case glBufferData:
- return transformsForGlBufferData(msg);
- case glBufferSubData:
- return transformsForGlBufferSubData(msg);
-
- // transformation state
- case glViewport:
- return transformsForGlViewport(msg);
- case glDepthRangef:
- return transformsForGlDepthRangef(msg);
-
- // rasterization
- case glLineWidth:
- return transformsForGlLineWidth(msg);
- case glCullFace:
- return transformsForGlCullFace(msg);
- case glFrontFace:
- return transformsForGlFrontFace(msg);
- case glPolygonOffset:
- return transformsForGlPolygonOffset(msg);
-
- // pixel operations
- case glScissor:
- return transformsForGlScissor(msg);
- case glStencilFunc:
- return transformsForGlStencilFunc(msg);
- case glStencilFuncSeparate:
- return transformsForGlStencilFuncSeparate(msg);
- case glStencilOp:
- return transformsForGlStencilOp(msg);
- case glStencilOpSeparate:
- return transformsForGlStencilOpSeparate(msg);
- case glDepthFunc:
- return transformsForGlDepthFunc(msg);
- case glBlendEquation:
- return transformsForGlBlendEquation(msg);
- case glBlendEquationSeparate:
- return transformsForGlBlendEquationSeparate(msg);
- case glBlendFunc:
- return transformsForGlBlendFunc(msg);
- case glBlendFuncSeparate:
- return transformsForGlBlendFuncSeparate(msg);
- case glPixelStorei:
- return transformsForGlPixelStorei(msg);
-
- // Texture State Transformations
- case glGenTextures:
- return transformsForGlGenTextures(msg);
- case glDeleteTextures:
- return transformsForGlDeleteTextures(msg);
- case glActiveTexture:
- return transformsForGlActiveTexture(msg);
- case glBindTexture:
- return transformsForGlBindTexture(msg);
- case glTexImage2D:
- return transformsForGlTexImage2D(msg);
- case glTexSubImage2D:
- return transformsForGlTexSubImage2D(msg);
- case glTexParameteri:
- return transformsForGlTexParameter(msg);
-
- // Program State Transformations
- case glCreateProgram:
- return transformsForGlCreateProgram(msg);
- case glUseProgram:
- return transformsForGlUseProgram(msg);
- case glAttachShader:
- return transformsForGlAttachShader(msg);
- case glDetachShader:
- return transformsForGlDetachShader(msg);
- case glGetActiveAttrib:
- return transformsForGlGetActiveAttrib(msg);
- case glGetActiveUniform:
- return transformsForGlGetActiveUniform(msg);
- case glUniform1i:
- case glUniform2i:
- case glUniform3i:
- case glUniform4i:
- return transformsForGlUniform(msg, false);
- case glUniform1f:
- case glUniform2f:
- case glUniform3f:
- case glUniform4f:
- return transformsForGlUniform(msg, true);
- case glUniform1iv:
- case glUniform2iv:
- case glUniform3iv:
- case glUniform4iv:
- return transformsForGlUniformv(msg, false);
- case glUniform1fv:
- case glUniform2fv:
- case glUniform3fv:
- case glUniform4fv:
- return transformsForGlUniformv(msg, true);
- case glUniformMatrix2fv:
- case glUniformMatrix3fv:
- case glUniformMatrix4fv:
- return transformsForGlUniformMatrix(msg);
-
- // Shader State Transformations
- case glCreateShader:
- return transformsForGlCreateShader(msg);
- case glDeleteShader:
- return transformsForGlDeleteShader(msg);
- case glShaderSource:
- return transformsForGlShaderSource(msg);
- default:
- return Collections.emptyList();
- }
- }
-
- private static List<IStateTransform> transformsForGlVertexAttribPointer(GLMessage msg) {
- int index = msg.getArgs(0).getIntValue(0);
-
- int size = msg.getArgs(1).getIntValue(0);
- int type = msg.getArgs(2).getIntValue(0);
- boolean normalized = msg.getArgs(3).getBoolValue(0);
- int stride = msg.getArgs(4).getIntValue(0);
-
- long pointer;
- if (msg.getArgs(5).getIntValueCount() > 0) {
- pointer = msg.getArgs(5).getIntValue(0);
- } else {
- pointer = msg.getArgs(5).getInt64Value(0);
- }
-
- List<IStateTransform> transforms = new ArrayList<IStateTransform>();
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.VERTEX_ARRAY_DATA,
- GLStateType.VERTEX_ATTRIB_ARRAY,
- Integer.valueOf(index),
- GLStateType.VERTEX_ATTRIB_ARRAY_SIZE),
- Integer.valueOf(size)));
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.VERTEX_ARRAY_DATA,
- GLStateType.VERTEX_ATTRIB_ARRAY,
- Integer.valueOf(index),
- GLStateType.VERTEX_ATTRIB_ARRAY_TYPE),
- GLEnum.valueOf(type)));
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.VERTEX_ARRAY_DATA,
- GLStateType.VERTEX_ATTRIB_ARRAY,
- Integer.valueOf(index),
- GLStateType.VERTEX_ATTRIB_ARRAY_NORMALIZED),
- Boolean.valueOf(normalized)));
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.VERTEX_ARRAY_DATA,
- GLStateType.VERTEX_ATTRIB_ARRAY,
- Integer.valueOf(index),
- GLStateType.VERTEX_ATTRIB_ARRAY_STRIDE),
- Integer.valueOf(stride)));
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.VERTEX_ARRAY_DATA,
- GLStateType.VERTEX_ATTRIB_ARRAY,
- Integer.valueOf(index),
- GLStateType.VERTEX_ATTRIB_ARRAY_POINTER),
- Long.valueOf(pointer)));
- return transforms;
- }
-
- private static List<IStateTransform> transformsForGlVertexAttrib(int context,
- int index, float v0, float v1, float v2, float v3) {
- List<IStateTransform> transforms = new ArrayList<IStateTransform>(4);
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(context,
- GLStateType.VERTEX_ARRAY_DATA,
- GLStateType.GENERIC_VERTEX_ATTRIBUTES,
- Integer.valueOf(index),
- GLStateType.GENERIC_VERTEX_ATTRIB_V0),
- Float.valueOf(v0)));
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(context,
- GLStateType.VERTEX_ARRAY_DATA,
- GLStateType.GENERIC_VERTEX_ATTRIBUTES,
- Integer.valueOf(index),
- GLStateType.GENERIC_VERTEX_ATTRIB_V1),
- Float.valueOf(v1)));
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(context,
- GLStateType.VERTEX_ARRAY_DATA,
- GLStateType.GENERIC_VERTEX_ATTRIBUTES,
- Integer.valueOf(index),
- GLStateType.GENERIC_VERTEX_ATTRIB_V2),
- Float.valueOf(v2)));
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(context,
- GLStateType.VERTEX_ARRAY_DATA,
- GLStateType.GENERIC_VERTEX_ATTRIBUTES,
- Integer.valueOf(index),
- GLStateType.GENERIC_VERTEX_ATTRIB_V3),
- Float.valueOf(v3)));
- return transforms;
- }
-
- private static List<IStateTransform> transformsForGlVertexAttribxf(GLMessage msg) {
- // void glVertexAttrib1f(GLuint index, GLfloat v0);
- // void glVertexAttrib2f(GLuint index, GLfloat v0, GLfloat v1);
- // void glVertexAttrib3f(GLuint index, GLfloat v0, GLfloat v1, GLfloat v2);
- // void glVertexAttrib4f(GLuint index, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
-
- int index = msg.getArgs(0).getIntValue(0);
- float v0 = msg.getArgs(1).getFloatValue(0);
- float v1 = msg.getArgsCount() > 2 ? msg.getArgs(2).getFloatValue(0) : 0;
- float v2 = msg.getArgsCount() > 3 ? msg.getArgs(3).getFloatValue(0) : 0;
- float v3 = msg.getArgsCount() > 4 ? msg.getArgs(4).getFloatValue(0) : 0;
-
- return transformsForGlVertexAttrib(msg.getContextId(), index, v0, v1, v2, v3);
- }
-
- private static List<IStateTransform> transformsForGlVertexAttribxfv(GLMessage msg) {
- // void glVertexAttrib1fv(GLuint index, const GLfloat *v);
- // void glVertexAttrib2fv(GLuint index, const GLfloat *v);
- // void glVertexAttrib3fv(GLuint index, const GLfloat *v);
- // void glVertexAttrib4fv(GLuint index, const GLfloat *v);
-
- int index = msg.getArgs(0).getIntValue(0);
- float v[] = new float[4];
-
- for (int i = 0; i < msg.getArgs(1).getFloatValueList().size(); i++) {
- v[i] = msg.getArgs(1).getFloatValue(i);
- }
-
- return transformsForGlVertexAttrib(msg.getContextId(), index, v[0], v[1], v[2], v[3]);
- }
-
- private static List<IStateTransform> transformsForGlEnableVertexAttribArray(GLMessage msg) {
- // void glEnableVertexAttribArray(GLuint index);
- // void glDisableVertexAttribArray(GLuint index);
-
- int index = msg.getArgs(0).getIntValue(0);
- IStateTransform transform = new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.VERTEX_ARRAY_DATA,
- GLStateType.VERTEX_ATTRIB_ARRAY,
- Integer.valueOf(index),
- GLStateType.VERTEX_ATTRIB_ARRAY_ENABLED),
- Boolean.TRUE);
- return Collections.singletonList(transform);
- }
-
- private static List<IStateTransform> transformsForGlDisableVertexAttribArray(GLMessage msg) {
- // void glEnableVertexAttribArray(GLuint index);
- // void glDisableVertexAttribArray(GLuint index);
-
- int index = msg.getArgs(0).getIntValue(0);
- IStateTransform transform = new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.VERTEX_ARRAY_DATA,
- GLStateType.VERTEX_ATTRIB_ARRAY,
- Integer.valueOf(index),
- GLStateType.VERTEX_ATTRIB_ARRAY_ENABLED),
- Boolean.FALSE);
- return Collections.singletonList(transform);
- }
-
- private static List<IStateTransform> transformsForGlBindBuffer(GLMessage msg) {
- // void glBindBuffer(GLenum target, GLuint buffer);
- // target is one of GL_ARRAY_BUFFER or GL_ELEMENT_ARRAY_BUFFER.
-
- GLEnum target = GLEnum.valueOf(msg.getArgs(0).getIntValue(0));
- int buffer = msg.getArgs(1).getIntValue(0);
- GLStateType bufferType;
-
- if (target == GLEnum.GL_ARRAY_BUFFER) {
- bufferType = GLStateType.ARRAY_BUFFER_BINDING;
- } else {
- bufferType = GLStateType.ELEMENT_ARRAY_BUFFER_BINDING;
- }
-
- IStateTransform transform = new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.VERTEX_ARRAY_DATA,
- GLStateType.BUFFER_BINDINGS,
- bufferType),
- Integer.valueOf(buffer));
- return Collections.singletonList(transform);
- }
-
- private static List<IStateTransform> transformsForGlGenBuffers(GLMessage msg) {
- // void glGenBuffers(GLsizei n, GLuint * buffers);
- int n = msg.getArgs(0).getIntValue(0);
- List<IStateTransform> transforms = new ArrayList<IStateTransform>();
-
- for (int i = 0; i < n; i++) {
- transforms.add(new SparseArrayElementAddTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.VERTEX_ARRAY_DATA,
- GLStateType.VBO),
- msg.getArgs(1).getIntValue(i)));
- }
-
- return transforms;
- }
-
- private static List<IStateTransform> transformsForGlDeleteBuffers(GLMessage msg) {
- // void glDeleteBuffers(GLsizei n, const GLuint * buffers);
- int n = msg.getArgs(0).getIntValue(0);
- List<IStateTransform> transforms = new ArrayList<IStateTransform>();
-
- for (int i = 0; i < n; i++) {
- transforms.add(new SparseArrayElementRemoveTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.VERTEX_ARRAY_DATA,
- GLStateType.VBO),
- msg.getArgs(1).getIntValue(i)));
- }
-
- return transforms;
- }
-
- private static List<IStateTransform> transformsForGlBufferData(GLMessage msg) {
- // void glBufferData(GLenum target, GLsizeiptr size, const GLvoid * data, GLenum usage);
- GLEnum target = GLEnum.valueOf(msg.getArgs(0).getIntValue(0));
- int size = msg.getArgs(1).getIntValue(0);
- byte[] data = null;
- GLEnum usage = GLEnum.valueOf(msg.getArgs(3).getIntValue(0));
-
- if (msg.getArgs(2).getRawBytesList().size() > 0) {
- data = msg.getArgs(2).getRawBytesList().get(0).toByteArray();
- } else {
- data = new byte[size];
- }
-
- List<IStateTransform> transforms = new ArrayList<IStateTransform>();
-
- transforms.add(new PropertyChangeTransform(
- new CurrentVboPropertyAccessor(msg.getContextId(),
- target,
- GLStateType.BUFFER_SIZE),
- Integer.valueOf(size)));
- transforms.add(new PropertyChangeTransform(
- new CurrentVboPropertyAccessor(msg.getContextId(),
- target,
- GLStateType.BUFFER_DATA),
- data));
- transforms.add(new PropertyChangeTransform(
- new CurrentVboPropertyAccessor(msg.getContextId(),
- target,
- GLStateType.BUFFER_USAGE),
- usage));
- transforms.add(new PropertyChangeTransform(
- new CurrentVboPropertyAccessor(msg.getContextId(),
- target,
- GLStateType.BUFFER_TYPE),
- target));
- return transforms;
- }
-
- private static List<IStateTransform> transformsForGlBufferSubData(GLMessage msg) {
- // void glBufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid * data);
- GLEnum target = GLEnum.valueOf(msg.getArgs(0).getIntValue(0));
- int offset = msg.getArgs(1).getIntValue(0);
- byte[] data = msg.getArgs(3).getRawBytesList().get(0).toByteArray();
-
- IStateTransform transform = new BufferSubDataTransform(
- new CurrentVboPropertyAccessor(msg.getContextId(),
- target,
- GLStateType.BUFFER_DATA),
- offset, data);
-
- return Collections.singletonList(transform);
- }
-
- private static List<IStateTransform> transformsForGlBindFramebuffer(GLMessage msg) {
- // void glBindFramebuffer(GLenum target, GLuint framebuffer);
- int fb = msg.getArgs(1).getIntValue(0);
- IStateTransform transform = new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.FRAMEBUFFER_STATE,
- GLStateType.FRAMEBUFFER_BINDING),
- fb);
- return Collections.singletonList(transform);
- }
-
- private static List<IStateTransform> transformsForGlLineWidth(GLMessage msg) {
- // void glLineWidth(GLfloat width);
- float width = msg.getArgs(0).getFloatValue(0);
- IStateTransform transform = new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.RASTERIZATION_STATE,
- GLStateType.LINE_WIDTH),
- width);
- return Collections.singletonList(transform);
- }
-
- private static List<IStateTransform> transformsForGlCullFace(GLMessage msg) {
- // void glCullFace(GLenum mode);
- int mode = msg.getArgs(0).getIntValue(0);
- IStateTransform transform = new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.RASTERIZATION_STATE,
- GLStateType.CULL_FACE_MODE),
- GLEnum.valueOf(mode));
- return Collections.singletonList(transform);
- }
-
- private static List<IStateTransform> transformsForGlFrontFace(GLMessage msg) {
- // void glFrontFace(GLenum mode);
- int mode = msg.getArgs(0).getIntValue(0);
- IStateTransform transform = new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.RASTERIZATION_STATE,
- GLStateType.FRONT_FACE),
- GLEnum.valueOf(mode));
- return Collections.singletonList(transform);
- }
-
- private static List<IStateTransform> transformsForGlPolygonOffset(GLMessage msg) {
- // void glPolygonOffset(GLfloat factor, GLfloat units)
- float factor = msg.getArgs(0).getFloatValue(0);
- float units = msg.getArgs(1).getFloatValue(0);
-
- List<IStateTransform> transforms = new ArrayList<IStateTransform>();
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.RASTERIZATION_STATE,
- GLStateType.POLYGON_OFFSET_FACTOR),
- Float.valueOf(factor)));
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.RASTERIZATION_STATE,
- GLStateType.POLYGON_OFFSET_UNITS),
- Float.valueOf(units)));
- return transforms;
- }
-
- private static List<IStateTransform> transformsForGlScissor(GLMessage msg) {
- // void glScissor(GLint x, GLint y, GLsizei width, GLsizei height);
- int x = msg.getArgs(0).getIntValue(0);
- int y = msg.getArgs(1).getIntValue(0);
- int w = msg.getArgs(2).getIntValue(0);
- int h = msg.getArgs(3).getIntValue(0);
-
- List<IStateTransform> transforms = new ArrayList<IStateTransform>();
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.PIXEL_OPERATIONS,
- GLStateType.SCISSOR_BOX,
- GLStateType.SCISSOR_BOX_X),
- Integer.valueOf(x)));
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.PIXEL_OPERATIONS,
- GLStateType.SCISSOR_BOX,
- GLStateType.SCISSOR_BOX_Y),
- Integer.valueOf(y)));
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.PIXEL_OPERATIONS,
- GLStateType.SCISSOR_BOX,
- GLStateType.SCISSOR_BOX_WIDTH),
- Integer.valueOf(w)));
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.PIXEL_OPERATIONS,
- GLStateType.SCISSOR_BOX,
- GLStateType.SCISSOR_BOX_HEIGHT),
- Integer.valueOf(h)));
- return transforms;
- }
-
- private static List<IStateTransform> transformsForGlStencilFuncFront(int contextId,
- GLEnum func, int ref, int mask) {
- List<IStateTransform> transforms = new ArrayList<IStateTransform>();
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(contextId,
- GLStateType.PIXEL_OPERATIONS,
- GLStateType.STENCIL,
- GLStateType.STENCIL_FUNC),
- func));
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(contextId,
- GLStateType.PIXEL_OPERATIONS,
- GLStateType.STENCIL,
- GLStateType.STENCIL_REF),
- Integer.valueOf(ref)));
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(contextId,
- GLStateType.PIXEL_OPERATIONS,
- GLStateType.STENCIL,
- GLStateType.STENCIL_VALUE_MASK),
- Integer.valueOf(mask)));
- return transforms;
- }
-
- private static List<IStateTransform> transformsForGlStencilFuncBack(int contextId,
- GLEnum func, int ref, int mask) {
- List<IStateTransform> transforms = new ArrayList<IStateTransform>();
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(contextId,
- GLStateType.PIXEL_OPERATIONS,
- GLStateType.STENCIL,
- GLStateType.STENCIL_BACK_FUNC),
- func));
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(contextId,
- GLStateType.PIXEL_OPERATIONS,
- GLStateType.STENCIL,
- GLStateType.STENCIL_BACK_REF),
- Integer.valueOf(ref)));
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(contextId,
- GLStateType.PIXEL_OPERATIONS,
- GLStateType.STENCIL,
- GLStateType.STENCIL_BACK_VALUE_MASK),
- Integer.valueOf(mask)));
- return transforms;
- }
-
- private static List<IStateTransform> transformsForGlStencilFunc(GLMessage msg) {
- // void glStencilFunc(GLenum func, GLint ref, GLuint mask);
- GLEnum func = GLEnum.valueOf(msg.getArgs(0).getIntValue(0));
- int ref = msg.getArgs(1).getIntValue(0);
- int mask = msg.getArgs(2).getIntValue(0);
-
- List<IStateTransform> transforms = new ArrayList<IStateTransform>();
- transforms.addAll(transformsForGlStencilFuncFront(msg.getContextId(), func, ref, mask));
- transforms.addAll(transformsForGlStencilFuncBack(msg.getContextId(), func, ref, mask));
- return transforms;
- }
-
- private static List<IStateTransform> transformsForGlStencilFuncSeparate(GLMessage msg) {
- // void glStencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask);
- GLEnum face = GLEnum.valueOf(msg.getArgs(0).getIntValue(0));
- GLEnum func = GLEnum.valueOf(msg.getArgs(1).getIntValue(0));
- int ref = msg.getArgs(2).getIntValue(0);
- int mask = msg.getArgs(3).getIntValue(0);
-
- List<IStateTransform> transforms = new ArrayList<IStateTransform>();
- if (face == GLEnum.GL_FRONT || face == GLEnum.GL_FRONT_AND_BACK) {
- transforms.addAll(
- transformsForGlStencilFuncFront(msg.getContextId(), func, ref, mask));
- }
- if (face == GLEnum.GL_BACK || face == GLEnum.GL_FRONT_AND_BACK) {
- transforms.addAll(
- transformsForGlStencilFuncBack(msg.getContextId(), func, ref, mask));
- }
-
- return transforms;
- }
-
- private static List<IStateTransform> transformsForGlStencilOpFront(int contextId,
- GLEnum sfail, GLEnum dpfail, GLEnum dppass) {
- List<IStateTransform> transforms = new ArrayList<IStateTransform>();
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(contextId,
- GLStateType.PIXEL_OPERATIONS,
- GLStateType.STENCIL,
- GLStateType.STENCIL_FAIL),
- sfail));
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(contextId,
- GLStateType.PIXEL_OPERATIONS,
- GLStateType.STENCIL,
- GLStateType.STENCIL_PASS_DEPTH_FAIL),
- dpfail));
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(contextId,
- GLStateType.PIXEL_OPERATIONS,
- GLStateType.STENCIL,
- GLStateType.STENCIL_PASS_DEPTH_PASS),
- dppass));
- return transforms;
- }
-
- private static List<IStateTransform> transformsForGlStencilOpBack(int contextId,
- GLEnum sfail, GLEnum dpfail, GLEnum dppass) {
- List<IStateTransform> transforms = new ArrayList<IStateTransform>();
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(contextId,
- GLStateType.PIXEL_OPERATIONS,
- GLStateType.STENCIL,
- GLStateType.STENCIL_BACK_FAIL),
- sfail));
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(contextId,
- GLStateType.PIXEL_OPERATIONS,
- GLStateType.STENCIL,
- GLStateType.STENCIL_BACK_PASS_DEPTH_FAIL),
- dpfail));
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(contextId,
- GLStateType.PIXEL_OPERATIONS,
- GLStateType.STENCIL,
- GLStateType.STENCIL_BACK_PASS_DEPTH_PASS),
- dppass));
- return transforms;
- }
-
- private static List<IStateTransform> transformsForGlStencilOp(GLMessage msg) {
- // void glStencilOp(GLenum sfail, GLenum dpfail, GLenum dppass);
- GLEnum sfail = GLEnum.valueOf(msg.getArgs(0).getIntValue(0));
- GLEnum dpfail = GLEnum.valueOf(msg.getArgs(1).getIntValue(0));
- GLEnum dppass = GLEnum.valueOf(msg.getArgs(2).getIntValue(0));
- List<IStateTransform> transforms = new ArrayList<IStateTransform>();
- transforms.addAll(
- transformsForGlStencilOpFront(msg.getContextId(), sfail, dpfail, dppass));
- transforms.addAll(
- transformsForGlStencilOpBack(msg.getContextId(), sfail, dpfail, dppass));
- return transforms;
- }
-
- private static List<IStateTransform> transformsForGlStencilOpSeparate(GLMessage msg) {
- // void glStencilOp(GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass);
- GLEnum face = GLEnum.valueOf(msg.getArgs(0).getIntValue(0));
- GLEnum sfail = GLEnum.valueOf(msg.getArgs(1).getIntValue(0));
- GLEnum dpfail = GLEnum.valueOf(msg.getArgs(2).getIntValue(0));
- GLEnum dppass = GLEnum.valueOf(msg.getArgs(3).getIntValue(0));
- List<IStateTransform> transforms = new ArrayList<IStateTransform>();
-
- if (face == GLEnum.GL_FRONT || face == GLEnum.GL_FRONT_AND_BACK) {
- transforms.addAll(
- transformsForGlStencilOpFront(msg.getContextId(), sfail, dpfail, dppass));
- }
-
- if (face == GLEnum.GL_BACK || face == GLEnum.GL_FRONT_AND_BACK) {
- transforms.addAll(
- transformsForGlStencilOpBack(msg.getContextId(), sfail, dpfail, dppass));
- }
-
- return transforms;
- }
-
- private static List<IStateTransform> transformsForGlDepthFunc(GLMessage msg) {
- // void glDepthFunc(GLenum func);
- GLEnum func = GLEnum.valueOf(msg.getArgs(0).getIntValue(0));
-
- IStateTransform transform = new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.PIXEL_OPERATIONS,
- GLStateType.DEPTH_FUNC),
- func);
- return Collections.singletonList(transform);
- }
-
- private static IStateTransform transformForGlEquationRGB(int contextId, GLEnum mode) {
- return new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(contextId,
- GLStateType.PIXEL_OPERATIONS,
- GLStateType.BLEND,
- GLStateType.BLEND_EQUATION_RGB),
- mode);
- }
-
- private static IStateTransform transformForGlEquationAlpha(int contextId, GLEnum mode) {
- return new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(contextId,
- GLStateType.PIXEL_OPERATIONS,
- GLStateType.BLEND,
- GLStateType.BLEND_EQUATION_ALPHA),
- mode);
- }
-
- private static List<IStateTransform> transformsForGlBlendEquationSeparate(GLMessage msg) {
- // void glBlendEquationSeparate(GLenum modeRGB, GLenum modeAlpha);
- GLEnum rgb = GLEnum.valueOf(msg.getArgs(0).getIntValue(0));
- GLEnum alpha = GLEnum.valueOf(msg.getArgs(1).getIntValue(0));
-
- List<IStateTransform> transforms = new ArrayList<IStateTransform>();
- transforms.add(transformForGlEquationRGB(msg.getContextId(), rgb));
- transforms.add(transformForGlEquationAlpha(msg.getContextId(), alpha));
- return transforms;
- }
-
- private static List<IStateTransform> transformsForGlBlendEquation(GLMessage msg) {
- // void glBlendEquation(GLenum mode);
- GLEnum mode = GLEnum.valueOf(msg.getArgs(0).getIntValue(0));
-
- List<IStateTransform> transforms = new ArrayList<IStateTransform>();
- transforms.add(transformForGlEquationRGB(msg.getContextId(), mode));
- transforms.add(transformForGlEquationAlpha(msg.getContextId(), mode));
- return transforms;
- }
-
- private static List<IStateTransform> transformsForGlBlendFuncSrcDst(boolean src,
- int contextId, GLEnum rgb, GLEnum alpha) {
- List<IStateTransform> transforms = new ArrayList<IStateTransform>();
-
- GLStateType rgbAccessor = GLStateType.BLEND_DST_RGB;
- GLStateType alphaAccessor = GLStateType.BLEND_DST_ALPHA;
- if (src) {
- rgbAccessor = GLStateType.BLEND_SRC_RGB;
- alphaAccessor = GLStateType.BLEND_SRC_ALPHA;
- }
-
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(contextId,
- GLStateType.PIXEL_OPERATIONS,
- GLStateType.BLEND,
- rgbAccessor),
- rgb));
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(contextId,
- GLStateType.PIXEL_OPERATIONS,
- GLStateType.BLEND,
- alphaAccessor),
- alpha));
- return transforms;
- }
-
- private static List<IStateTransform> transformsForGlBlendFuncSeparate(GLMessage msg) {
- // void glBlendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha)
- GLEnum srcRgb = GLEnum.valueOf(msg.getArgs(0).getIntValue(0));
- GLEnum dstRgb = GLEnum.valueOf(msg.getArgs(1).getIntValue(0));
- GLEnum srcAlpha = GLEnum.valueOf(msg.getArgs(2).getIntValue(0));
- GLEnum dstAlpha = GLEnum.valueOf(msg.getArgs(3).getIntValue(0));
-
- List<IStateTransform> transforms = new ArrayList<IStateTransform>();
- transforms.addAll(transformsForGlBlendFuncSrcDst(true,
- msg.getContextId(), srcRgb, srcAlpha));
- transforms.addAll(transformsForGlBlendFuncSrcDst(false,
- msg.getContextId(), dstRgb, dstAlpha));
- return transforms;
- }
-
- private static List<IStateTransform> transformsForGlBlendFunc(GLMessage msg) {
- // void glBlendFunc(GLenum sfactor, GLenum dfactor);
- GLEnum sfactor = GLEnum.valueOf(msg.getArgs(0).getIntValue(0));
- GLEnum dfactor = GLEnum.valueOf(msg.getArgs(1).getIntValue(0));
-
- List<IStateTransform> transforms = new ArrayList<IStateTransform>();
- transforms.addAll(transformsForGlBlendFuncSrcDst(true,
- msg.getContextId(), sfactor, sfactor));
- transforms.addAll(transformsForGlBlendFuncSrcDst(false,
- msg.getContextId(), dfactor, dfactor));
- return transforms;
- }
-
- private static List<IStateTransform> transformsForGlPixelStorei(GLMessage msg) {
- // void glPixelStorei(GLenum pname, GLint param);
- GLEnum pname = GLEnum.valueOf(msg.getArgs(0).getIntValue(0));
- Integer param = Integer.valueOf(msg.getArgs(1).getIntValue(0));
-
- IStateTransform transform;
- if (pname == GLEnum.GL_PACK_ALIGNMENT) {
- transform = new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.PIXEL_PACKING,
- GLStateType.PACK_ALIGNMENT),
- param);
- } else {
- transform = new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.PIXEL_PACKING,
- GLStateType.UNPACK_ALIGNMENT),
- param);
- }
-
- return Collections.singletonList(transform);
- }
-
- private static List<IStateTransform> transformsForGlViewport(GLMessage msg) {
- // void glViewport( GLint x, GLint y, GLsizei width, GLsizei height);
- int x = msg.getArgs(0).getIntValue(0);
- int y = msg.getArgs(1).getIntValue(0);
- int w = msg.getArgs(2).getIntValue(0);
- int h = msg.getArgs(3).getIntValue(0);
-
- List<IStateTransform> transforms = new ArrayList<IStateTransform>();
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.TRANSFORMATION_STATE,
- GLStateType.VIEWPORT,
- GLStateType.VIEWPORT_X),
- Integer.valueOf(x)));
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.TRANSFORMATION_STATE,
- GLStateType.VIEWPORT,
- GLStateType.VIEWPORT_Y),
- Integer.valueOf(y)));
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.TRANSFORMATION_STATE,
- GLStateType.VIEWPORT,
- GLStateType.VIEWPORT_WIDTH),
- Integer.valueOf(w)));
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.TRANSFORMATION_STATE,
- GLStateType.VIEWPORT,
- GLStateType.VIEWPORT_HEIGHT),
- Integer.valueOf(h)));
- return transforms;
- }
-
- private static List<IStateTransform> transformsForGlDepthRangef(GLMessage msg) {
- // void glDepthRangef(GLclampf nearVal, GLclampf farVal);
- float near = msg.getArgs(0).getFloatValue(0);
- float far = msg.getArgs(1).getFloatValue(0);
-
- List<IStateTransform> transforms = new ArrayList<IStateTransform>();
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.TRANSFORMATION_STATE,
- GLStateType.DEPTH_RANGE,
- GLStateType.DEPTH_RANGE_NEAR),
- Float.valueOf(near)));
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.TRANSFORMATION_STATE,
- GLStateType.DEPTH_RANGE,
- GLStateType.DEPTH_RANGE_FAR),
- Float.valueOf(far)));
- return transforms;
- }
-
- private static List<IStateTransform> transformsForGlGenTextures(GLMessage msg) {
- // void glGenTextures(GLsizei n, GLuint *textures);
- int n = msg.getArgs(0).getIntValue(0);
-
- List<IStateTransform> transforms = new ArrayList<IStateTransform>();
- for (int i = 0; i < n; i++) {
- int texture = msg.getArgs(1).getIntValue(i);
- transforms.add(new SparseArrayElementAddTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.TEXTURE_STATE,
- GLStateType.TEXTURES),
- texture));
- }
-
- return transforms;
- }
-
- /**
- * Obtain a list of transforms that will reset any existing texture units
- * that are bound to provided texture.
- * @param contextId context to operate on
- * @param texture texture that should be unbound
- */
- private static List<IStateTransform> transformsToResetBoundTextureUnits(int contextId,
- int texture) {
- List<IStateTransform> transforms = new ArrayList<IStateTransform>(
- GLState.TEXTURE_UNIT_COUNT);
-
- for (int i = 0; i < GLState.TEXTURE_UNIT_COUNT; i++) {
- transforms.add(new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(contextId,
- GLStateType.TEXTURE_STATE,
- GLStateType.TEXTURE_UNITS,
- Integer.valueOf(i),
- GLStateType.TEXTURE_BINDING_2D),
- Integer.valueOf(0), /* reset binding to texture 0 */
- Predicates.matchesInteger(texture) /* only if currently bound to @texture */ ));
- }
- return transforms;
- }
-
- private static List<IStateTransform> transformsForGlDeleteTextures(GLMessage msg) {
- // void glDeleteTextures(GLsizei n, const GLuint * textures);
- int n = msg.getArgs(0).getIntValue(0);
-
- List<IStateTransform> transforms = new ArrayList<IStateTransform>(n);
- for (int i = 0; i < n; i++) {
- int texture = msg.getArgs(1).getIntValue(i);
- transforms.add(new SparseArrayElementRemoveTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.TEXTURE_STATE,
- GLStateType.TEXTURES),
- texture));
- transforms.addAll(transformsToResetBoundTextureUnits(msg.getContextId(), texture));
- }
-
- return transforms;
- }
-
- private static List<IStateTransform> transformsForGlActiveTexture(GLMessage msg) {
- // void glActiveTexture(GLenum texture);
- GLEnum texture = GLEnum.valueOf(msg.getArgs(0).getIntValue(0));
- Integer textureIndex = Integer.valueOf((int)(texture.value - GLEnum.GL_TEXTURE0.value));
- IStateTransform transform = new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.TEXTURE_STATE,
- GLStateType.ACTIVE_TEXTURE_UNIT),
- textureIndex);
- return Collections.singletonList(transform);
- }
-
- private static GLStateType getTextureUnitTargetName(GLEnum target) {
- if (target == GLEnum.GL_TEXTURE_CUBE_MAP) {
- return GLStateType.TEXTURE_BINDING_CUBE_MAP;
- } else if (target == GLEnum.GL_TEXTURE_EXTERNAL) {
- // added by OES_EGL_image_external
- return GLStateType.TEXTURE_BINDING_EXTERNAL;
- } else {
- return GLStateType.TEXTURE_BINDING_2D;
- }
- }
-
- private static GLStateType getTextureTargetName(GLEnum pname) {
- switch (pname) {
- case GL_TEXTURE_MIN_FILTER:
- return GLStateType.TEXTURE_MIN_FILTER;
- case GL_TEXTURE_MAG_FILTER:
- return GLStateType.TEXTURE_MAG_FILTER;
- case GL_TEXTURE_WRAP_S:
- return GLStateType.TEXTURE_WRAP_S;
- case GL_TEXTURE_WRAP_T:
- return GLStateType.TEXTURE_WRAP_T;
- }
-
- assert false : "glTexParameter's pname argument does not support provided value.";
- return GLStateType.TEXTURE_MIN_FILTER;
- }
-
- private static List<IStateTransform> transformsForGlBindTexture(GLMessage msg) {
- // void glBindTexture(GLenum target, GLuint texture);
- GLEnum target = GLEnum.valueOf(msg.getArgs(0).getIntValue(0));
- Integer texture = Integer.valueOf(msg.getArgs(1).getIntValue(0));
-
- IStateTransform transform = new PropertyChangeTransform(
- new TextureUnitPropertyAccessor(msg.getContextId(),
- getTextureUnitTargetName(target)),
- texture);
- return Collections.singletonList(transform);
- }
-
- /**
- * Utility function used by both {@link #transformsForGlTexImage2D(GLMessage) and
- * {@link #transformsForGlTexSubImage2D(GLMessage)}.
- */
- private static List<IStateTransform> transformsForGlTexImage(GLMessage msg, int widthArgIndex,
- int heightArgIndex, int xOffsetIndex, int yOffsetIndex) {
- GLEnum target = GLEnum.valueOf(msg.getArgs(0).getIntValue(0));
- int level = msg.getArgs(1).getIntValue(0);
- Integer width = Integer.valueOf(msg.getArgs(widthArgIndex).getIntValue(0));
- Integer height = Integer.valueOf(msg.getArgs(heightArgIndex).getIntValue(0));
- GLEnum format = GLEnum.valueOf(msg.getArgs(6).getIntValue(0));
- GLEnum type = GLEnum.valueOf(msg.getArgs(7).getIntValue(0));
-
- List<IStateTransform> transforms = new ArrayList<IStateTransform>();
- transforms.add(new PropertyChangeTransform(
- new TexturePropertyAccessor(msg.getContextId(),
- getTextureUnitTargetName(target),
- level,
- GLStateType.TEXTURE_WIDTH),
- width));
- transforms.add(new PropertyChangeTransform(
- new TexturePropertyAccessor(msg.getContextId(),
- getTextureUnitTargetName(target),
- level,
- GLStateType.TEXTURE_HEIGHT),
- height));
- transforms.add(new PropertyChangeTransform(
- new TexturePropertyAccessor(msg.getContextId(),
- getTextureUnitTargetName(target),
- level,
- GLStateType.TEXTURE_FORMAT),
- format));
- transforms.add(new PropertyChangeTransform(
- new TexturePropertyAccessor(msg.getContextId(),
- getTextureUnitTargetName(target),
- level,
- GLStateType.TEXTURE_IMAGE_TYPE),
- type));
-
- // if texture data is available, extract and store it in the cache folder
- File f = null;
- if (msg.getArgs(8).getIsArray()) {
- ByteString data = msg.getArgs(8).getRawBytes(0);
- f = FileUtils.createTempFile(TEXTURE_DATA_FILE_PREFIX, TEXTURE_DATA_FILE_SUFFIX);
- try {
- Files.write(data.toByteArray(), f);
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- int xOffset = 0;
- int yOffset = 0;
-
- if (xOffsetIndex >= 0) {
- xOffset = msg.getArgs(xOffsetIndex).getIntValue(0);
- }
-
- if (yOffsetIndex >= 0) {
- yOffset = msg.getArgs(yOffsetIndex).getIntValue(0);
- }
-
- transforms.add(new TexImageTransform(
- new TexturePropertyAccessor(msg.getContextId(),
- getTextureUnitTargetName(target),
- level,
- GLStateType.TEXTURE_IMAGE),
- f, format, type, xOffset, yOffset, width, height));
-
- return transforms;
- }
-
- private static List<IStateTransform> transformsForGlTexImage2D(GLMessage msg) {
- // void glTexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width,
- // GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid *data);
- return transformsForGlTexImage(msg, 3, 4, -1, -1);
- }
-
- private static List<IStateTransform> transformsForGlTexSubImage2D(GLMessage msg) {
- // void glTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset,
- // GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid *data);
- return transformsForGlTexImage(msg, 4, 5, 2, 3);
- }
-
- private static List<IStateTransform> transformsForGlTexParameter(GLMessage msg) {
- // void glTexParameteri(GLenum target, GLenum pname, GLint param);
- GLEnum target = GLEnum.valueOf(msg.getArgs(0).getIntValue(0));
- GLEnum pname = GLEnum.valueOf(msg.getArgs(1).getIntValue(0));
- GLEnum pvalue = GLEnum.valueOf(msg.getArgs(2).getIntValue(0));
-
- if (sTexParameterPnameValues == null) {
- GLEnum[] pnameValues = new GLEnum[] {
- GLEnum.GL_TEXTURE_BASE_LEVEL,
- GLEnum.GL_TEXTURE_COMPARE_FUNC,
- GLEnum.GL_TEXTURE_COMPARE_MODE,
- GLEnum.GL_TEXTURE_MIN_FILTER,
- GLEnum.GL_TEXTURE_MAG_FILTER,
- GLEnum.GL_TEXTURE_MIN_LOD,
- GLEnum.GL_TEXTURE_MAX_LOD,
- GLEnum.GL_TEXTURE_MAX_LEVEL,
- GLEnum.GL_TEXTURE_SWIZZLE_R,
- GLEnum.GL_TEXTURE_SWIZZLE_G,
- GLEnum.GL_TEXTURE_SWIZZLE_B,
- GLEnum.GL_TEXTURE_SWIZZLE_A,
- GLEnum.GL_TEXTURE_WRAP_S,
- GLEnum.GL_TEXTURE_WRAP_T,
- GLEnum.GL_TEXTURE_WRAP_R
- };
- sTexParameterPnameValues = EnumSet.copyOf(Arrays.asList(pnameValues));
- }
-
- if (!sTexParameterPnameValues.contains(pname)) {
- throw new IllegalArgumentException(
- String.format("Unsupported parameter (%s) for glTexParameter()", pname));
- }
-
- IStateTransform transform = new PropertyChangeTransform(
- new TexturePropertyAccessor(msg.getContextId(),
- getTextureUnitTargetName(target),
- getTextureTargetName(pname)),
- pvalue);
- return Collections.singletonList(transform);
- }
-
- private static List<IStateTransform> transformsForGlCreateProgram(GLMessage msg) {
- // GLuint glCreateProgram(void);
- int program = msg.getReturnValue().getIntValue(0);
-
- IStateTransform transform = new SparseArrayElementAddTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.PROGRAM_STATE,
- GLStateType.PROGRAMS),
- program);
- return Collections.singletonList(transform);
- }
-
- private static List<IStateTransform> transformsForGlUseProgram(GLMessage msg) {
- // void glUseProgram(GLuint program);
- Integer program = Integer.valueOf(msg.getArgs(0).getIntValue(0));
-
- IStateTransform transform = new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.PROGRAM_STATE,
- GLStateType.CURRENT_PROGRAM),
- program);
- return Collections.singletonList(transform);
- }
-
- private static List<IStateTransform> transformsForGlAttachShader(GLMessage msg) {
- // void glAttachShader(GLuint program, GLuint shader);
- int program = msg.getArgs(0).getIntValue(0);
- int shader = msg.getArgs(1).getIntValue(0);
-
- IStateTransform transform = new SparseArrayElementAddTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.PROGRAM_STATE,
- GLStateType.PROGRAMS,
- Integer.valueOf(program),
- GLStateType.ATTACHED_SHADERS),
- Integer.valueOf(shader));
- return Collections.singletonList(transform);
- }
-
- private static List<IStateTransform> transformsForGlDetachShader(GLMessage msg) {
- // void glDetachShader(GLuint program, GLuint shader);
- int program = msg.getArgs(0).getIntValue(0);
- int shader = msg.getArgs(1).getIntValue(0);
-
- IStateTransform transform = new SparseArrayElementRemoveTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.PROGRAM_STATE,
- GLStateType.PROGRAMS,
- Integer.valueOf(program),
- GLStateType.ATTACHED_SHADERS),
- Integer.valueOf(shader));
- return Collections.singletonList(transform);
- }
-
- private static List<IStateTransform> transformsForGlGetActiveAttribOrUniform(
- GLMessage msg, boolean isAttrib) {
- // void glGetActive[Attrib|Uniform](GLuint program, GLuint index, GLsizei bufsize,
- // GLsizei* length, GLint* size, GLenum* type, GLchar* name);
- int program = msg.getArgs(0).getIntValue(0);
- int size = msg.getArgs(4).getIntValue(0);
- GLEnum type = GLEnum.valueOf(msg.getArgs(5).getIntValue(0));
- String name = msg.getArgs(6).getCharValue(0).toStringUtf8();
-
- // The 2nd argument (index) does not give the correct location of the
- // attribute/uniform in device. The actual location is obtained from
- // the getAttribLocation or getUniformLocation calls. The trace library
- // appends this value as an additional last argument to this call.
- int location = msg.getArgs(7).getIntValue(0);
-
- GLStateType activeInput;
- GLStateType inputName;
- GLStateType inputType;
- GLStateType inputSize;
-
- if (isAttrib) {
- activeInput = GLStateType.ACTIVE_ATTRIBUTES;
- inputName = GLStateType.ATTRIBUTE_NAME;
- inputType = GLStateType.ATTRIBUTE_TYPE;
- inputSize = GLStateType.ATTRIBUTE_SIZE;
- } else {
- activeInput = GLStateType.ACTIVE_UNIFORMS;
- inputName = GLStateType.UNIFORM_NAME;
- inputType = GLStateType.UNIFORM_TYPE;
- inputSize = GLStateType.UNIFORM_SIZE;
- }
-
- IStateTransform addAttribute = new SparseArrayElementAddTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.PROGRAM_STATE,
- GLStateType.PROGRAMS,
- Integer.valueOf(program),
- activeInput),
- Integer.valueOf(location));
- IStateTransform setAttributeName = new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.PROGRAM_STATE,
- GLStateType.PROGRAMS,
- Integer.valueOf(program),
- activeInput,
- Integer.valueOf(location),
- inputName),
- name);
- IStateTransform setAttributeType = new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.PROGRAM_STATE,
- GLStateType.PROGRAMS,
- Integer.valueOf(program),
- activeInput,
- Integer.valueOf(location),
- inputType),
- type);
- IStateTransform setAttributeSize = new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.PROGRAM_STATE,
- GLStateType.PROGRAMS,
- Integer.valueOf(program),
- activeInput,
- Integer.valueOf(location),
- inputSize),
- Integer.valueOf(size));
- return Arrays.asList(addAttribute, setAttributeName, setAttributeType, setAttributeSize);
- }
-
- private static List<IStateTransform> transformsForGlGetActiveAttrib(GLMessage msg) {
- return transformsForGlGetActiveAttribOrUniform(msg, true);
- }
-
- private static List<IStateTransform> transformsForGlGetActiveUniform(GLMessage msg) {
- return transformsForGlGetActiveAttribOrUniform(msg, false);
- }
-
- private static List<IStateTransform> transformsForGlUniformMatrix(GLMessage msg) {
- // void glUniformMatrix[2|3|4]fv(GLint location, GLsizei count, GLboolean transpose,
- // const GLfloat *value);
- int location = msg.getArgs(0).getIntValue(0);
- List<Float> uniforms = msg.getArgs(3).getFloatValueList();
-
- IStateTransform setValues = new PropertyChangeTransform(
- new CurrentProgramPropertyAccessor(msg.getContextId(),
- GLStateType.ACTIVE_UNIFORMS,
- location,
- GLStateType.UNIFORM_VALUE),
- uniforms);
-
- return Collections.singletonList(setValues);
- }
-
- private static List<IStateTransform> transformsForGlUniformv(GLMessage msg, boolean isFloats) {
- // void glUniform1fv(GLint location, GLsizei count, const GLfloat *value);
- int location = msg.getArgs(0).getIntValue(0);
- List<?> uniforms;
- if (isFloats) {
- uniforms = msg.getArgs(2).getFloatValueList();
- } else {
- uniforms = msg.getArgs(2).getIntValueList();
- }
-
- IStateTransform setValues = new PropertyChangeTransform(
- new CurrentProgramPropertyAccessor(msg.getContextId(),
- GLStateType.ACTIVE_UNIFORMS,
- location,
- GLStateType.UNIFORM_VALUE),
- uniforms);
-
- return Collections.singletonList(setValues);
- }
-
- private static List<IStateTransform> transformsForGlUniform(GLMessage msg, boolean isFloats) {
- // void glUniform1f(GLint location, GLfloat v0);
- // void glUniform2f(GLint location, GLfloat v0, GLfloat v1);
- // .. 3f
- // .. 4f
- // void glUniform1i(GLint location, GLfloat v0);
- // void glUniform2i(GLint location, GLfloat v0, GLfloat v1);
- // .. 3i
- // .. 4i
-
- int location = msg.getArgs(0).getIntValue(0);
- if (location < 0) {
- throw new IllegalArgumentException("Argument location cannot be less than 0.");
- }
- List<?> uniforms;
- if (isFloats) {
- List<Float> args = new ArrayList<Float>(msg.getArgsCount() - 1);
- for (int i = 1; i < msg.getArgsCount(); i++) {
- args.add(Float.valueOf(msg.getArgs(1).getFloatValue(0)));
- }
- uniforms = args;
- } else {
- List<Integer> args = new ArrayList<Integer>(msg.getArgsCount() - 1);
- for (int i = 1; i < msg.getArgsCount(); i++) {
- args.add(Integer.valueOf(msg.getArgs(1).getIntValue(0)));
- }
- uniforms = args;
- }
-
- IStateTransform setValues = new PropertyChangeTransform(
- new CurrentProgramPropertyAccessor(msg.getContextId(),
- GLStateType.ACTIVE_UNIFORMS,
- location,
- GLStateType.UNIFORM_VALUE),
- uniforms);
-
- return Collections.singletonList(setValues);
- }
-
- private static List<IStateTransform> transformsForGlCreateShader(GLMessage msg) {
- // GLuint glCreateShader(GLenum shaderType);
- GLEnum shaderType = GLEnum.valueOf(msg.getArgs(0).getIntValue(0));
- int shader = msg.getReturnValue().getIntValue(0);
-
- IStateTransform addShader = new SparseArrayElementAddTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.SHADERS),
- shader);
- IStateTransform setShaderType = new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.SHADERS,
- Integer.valueOf(shader),
- GLStateType.SHADER_TYPE),
- shaderType);
- return Arrays.asList(addShader, setShaderType);
- }
-
- private static List<IStateTransform> transformsForGlDeleteShader(GLMessage msg) {
- // void glDeleteShader(GLuint shader);
- int shader = msg.getArgs(0).getIntValue(0);
-
- IStateTransform transform = new SparseArrayElementRemoveTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.SHADERS),
- shader);
- return Collections.singletonList(transform);
- }
-
- private static List<IStateTransform> transformsForGlShaderSource(GLMessage msg) {
- // void glShaderSource(GLuint shader, GLsizei count, const GLchar **string,
- // const GLint *length);
- // This message is patched up on the device to return a single string as opposed to a
- // list of strings
- int shader = msg.getArgs(0).getIntValue(0);
- String src = msg.getArgs(2).getCharValue(0).toStringUtf8();
-
- IStateTransform transform = new PropertyChangeTransform(
- GLPropertyAccessor.makeAccessor(msg.getContextId(),
- GLStateType.SHADERS,
- Integer.valueOf(shader),
- GLStateType.SHADER_SOURCE),
- src);
- return Collections.singletonList(transform);
- }
-
- private static List<IStateTransform> transformsForEglCreateContext(GLMessage msg) {
- // void eglCreateContext(int version, int context);
- int version = msg.getArgs(0).getIntValue(0);
- IGLProperty glState = null;
- if (version == 0) {
- glState = GLState.createDefaultES1State();
- } else {
- glState = GLState.createDefaultES2State();
- }
- IStateTransform transform = new ListElementAddTransform(null, glState);
- return Collections.singletonList(transform);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/TexImageTransform.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/TexImageTransform.java
deleted file mode 100644
index dde89eae6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/TexImageTransform.java
+++ /dev/null
@@ -1,342 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state.transforms;
-
-import com.android.ide.eclipse.gltrace.FileUtils;
-import com.android.ide.eclipse.gltrace.GLEnum;
-import com.android.ide.eclipse.gltrace.state.GLStringProperty;
-import com.android.ide.eclipse.gltrace.state.IGLProperty;
-import com.google.common.io.Files;
-import com.google.common.primitives.UnsignedBytes;
-
-import java.awt.image.BufferedImage;
-import java.io.File;
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.nio.FloatBuffer;
-
-import javax.imageio.ImageIO;
-
-/**
- * {@link TexImageTransform} transforms the state to reflect the effect of a
- * glTexImage2D or glTexSubImage2D GL call.
- */
-public class TexImageTransform implements IStateTransform {
- private static final String PNG_IMAGE_FORMAT = "PNG";
- private static final String TEXTURE_FILE_PREFIX = "tex";
- private static final String TEXTURE_FILE_SUFFIX = ".png";
-
- private final IGLPropertyAccessor mAccessor;
- private final File mTextureDataFile;
-
- private final int mxOffset;
- private final int myOffset;
- private final int mWidth;
- private final int mHeight;
-
- private String mOldValue;
- private String mNewValue;
- private GLEnum mFormat;
- private GLEnum mType;
-
- /**
- * Construct a texture image transformation.
- * @param accessor accessor to obtain the GL state variable to modify
- * @param textureData texture data passed in by the call. Could be null.
- * @param format format of the source texture data
- * @param xOffset x offset for the source data (used only in glTexSubImage2D)
- * @param yOffset y offset for the source data (used only in glTexSubImage2D)
- * @param width width of the texture
- * @param height height of the texture
- */
- public TexImageTransform(IGLPropertyAccessor accessor, File textureData, GLEnum format,
- GLEnum type, int xOffset, int yOffset, int width, int height) {
- mAccessor = accessor;
- mTextureDataFile = textureData;
- mFormat = format;
- mType = type;
-
- mxOffset = xOffset;
- myOffset = yOffset;
- mWidth = width;
- mHeight = height;
- }
-
- @Override
- public void apply(IGLProperty currentState) {
- assert mOldValue == null : "Transform cannot be applied multiple times"; //$NON-NLS-1$
-
- IGLProperty property = mAccessor.getProperty(currentState);
- if (!(property instanceof GLStringProperty)) {
- return;
- }
-
- GLStringProperty prop = (GLStringProperty) property;
- mOldValue = prop.getStringValue();
-
- // Applying texture transformations is a heavy weight process. So we perform
- // it only once and save the result in a temporary file. The property is actually
- // the path to the file.
- if (mNewValue == null) {
- try {
- if (mOldValue == null) {
- mNewValue = createTexture(mTextureDataFile, mWidth, mHeight);
- } else {
- mNewValue = updateTextureData(mOldValue, mTextureDataFile, mxOffset, myOffset,
- mWidth, mHeight);
- }
- } catch (IOException e) {
- throw new RuntimeException(e);
- } catch (RuntimeException e) {
- throw e;
- }
- }
-
- prop.setValue(mNewValue);
- }
-
- @Override
- public void revert(IGLProperty state) {
- if (mOldValue != null) {
- IGLProperty property = mAccessor.getProperty(state);
- property.setValue(mOldValue);
- mOldValue = null;
- }
- }
-
- @Override
- public IGLProperty getChangedProperty(IGLProperty state) {
- return mAccessor.getProperty(state);
- }
-
- /**
- * Creates a texture of provided width and height. If the texture data file is provided,
- * then the texture is initialized with the contents of that file, otherwise an empty
- * image is created.
- * @param textureDataFile path to texture data, could be null.
- * @param width width of texture
- * @param height height of texture
- * @return path to cached texture
- */
- private String createTexture(File textureDataFile, int width, int height) throws IOException {
- File f = FileUtils.createTempFile(TEXTURE_FILE_PREFIX, TEXTURE_FILE_SUFFIX);
-
- BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
-
- if (textureDataFile != null) {
- byte[] initialData = Files.toByteArray(textureDataFile);
- img.getRaster().setDataElements(0, 0, width, height,
- formatSourceData(initialData, width, height));
- }
-
- ImageIO.write(img, PNG_IMAGE_FORMAT, f);
-
- return f.getAbsolutePath();
- }
-
- /**
- * Update part of an existing texture.
- * @param currentImagePath current texture image.
- * @param textureDataFile new data to update the current texture with
- * @param xOffset x offset for the update region
- * @param yOffset y offset for the update region
- * @param width width of the update region
- * @param height height of the update region
- * @return path to the updated texture
- */
- private String updateTextureData(String currentImagePath, File textureDataFile,
- int xOffset, int yOffset, int width, int height) throws IOException {
- assert currentImagePath != null : "Attempt to update a null texture";
-
- if (textureDataFile == null) {
- // Do not perform any updates if we don't have the actual data.
- return currentImagePath;
- }
-
- File f = FileUtils.createTempFile(TEXTURE_FILE_PREFIX, TEXTURE_FILE_SUFFIX);
- BufferedImage image = null;
- image = ImageIO.read(new File(currentImagePath));
-
- byte[] subImageData = Files.toByteArray(textureDataFile);
- image.getRaster().setDataElements(xOffset, yOffset, width, height,
- formatSourceData(subImageData, width, height));
- ImageIO.write(image, PNG_IMAGE_FORMAT, f);
-
- return f.getAbsolutePath();
- }
-
- private byte[] formatSourceData(byte[] subImageData, int width, int height) {
- if (mType != GLEnum.GL_UNSIGNED_BYTE) {
- subImageData = unpackData(subImageData, mType);
- }
-
- switch (mFormat) {
- case GL_RGBA:
- // no conversions necessary
- return subImageData;
- case GL_RGB:
- return addAlphaChannel(subImageData, width, height);
- case GL_RED:
- case GL_GREEN:
- case GL_BLUE:
- // GL_RED, GL_GREEN and GL_BLUE are all supposed to fill those respective
- // channels, but we assume that the programmers intent was to use GL_ALPHA in order
- // to overcome the issue that GL_ALPHA cannot be used with float data.
- if (mType != GLEnum.GL_FLOAT) {
- throw new RuntimeException();
- } else {
- // fall through - assume that it is GL_ALPHA
- }
- //$FALL-THROUGH$
- case GL_ALPHA:
- return addRGBChannels(subImageData, width, height);
- case GL_LUMINANCE:
- return createRGBAFromLuminance(subImageData, width, height);
- case GL_LUMINANCE_ALPHA:
- return createRGBAFromLuminanceAlpha(subImageData, width, height);
- default:
- throw new RuntimeException();
- }
- }
-
- private byte[] unpackData(byte[] data, GLEnum type) {
- switch (type) {
- case GL_UNSIGNED_BYTE:
- return data;
- case GL_UNSIGNED_SHORT_4_4_4_4:
- return convertShortToUnsigned(data, 0xf000, 12, 0x0f00, 8, 0x00f0, 4, 0x000f, 0,
- true);
- case GL_UNSIGNED_SHORT_5_6_5:
- return convertShortToUnsigned(data, 0xf800, 11, 0x07e0, 5, 0x001f, 0, 0, 0,
- false);
- case GL_UNSIGNED_SHORT_5_5_5_1:
- return convertShortToUnsigned(data, 0xf800, 11, 0x07c0, 6, 0x003e, 1, 0x1, 0,
- true);
- case GL_FLOAT:
- return convertFloatToUnsigned(data);
- default:
- return data;
- }
- }
-
- private byte[] convertFloatToUnsigned(byte[] data) {
- byte[] unsignedData = new byte[data.length];
- ByteBuffer floatBuffer = ByteBuffer.wrap(data);
- for (int i = 0; i < data.length / 4; i++) {
- float v = floatBuffer.getFloat(i);
- byte alpha = (byte)(v * 255);
- unsignedData[i*4 + 3] = alpha;
- }
- return unsignedData;
- }
-
- private byte[] convertShortToUnsigned(byte[] shortData,
- int rmask, int rshift,
- int gmask, int gshift,
- int bmask, int bshift,
- int amask, int ashift,
- boolean includeAlpha) {
- int numChannels = includeAlpha ? 4 : 3;
- byte[] unsignedData = new byte[(shortData.length/2) * numChannels];
-
- for (int i = 0; i < (shortData.length / 2); i++) {
- int hi = UnsignedBytes.toInt(shortData[i*2 + 0]);
- int lo = UnsignedBytes.toInt(shortData[i*2 + 1]);
-
- int x = hi << 8 | lo;
-
- int r = (x & rmask) >>> rshift;
- int g = (x & gmask) >>> gshift;
- int b = (x & bmask) >>> bshift;
- int a = (x & amask) >>> ashift;
-
- unsignedData[i * numChannels + 0] = UnsignedBytes.checkedCast(r);
- unsignedData[i * numChannels + 1] = UnsignedBytes.checkedCast(g);
- unsignedData[i * numChannels + 2] = UnsignedBytes.checkedCast(b);
-
- if (includeAlpha) {
- unsignedData[i * numChannels + 3] = UnsignedBytes.checkedCast(a);
- }
- }
-
- return unsignedData;
- }
-
- private byte[] addAlphaChannel(byte[] sourceData, int width, int height) {
- assert sourceData.length == 3 * width * height; // should have R, G & B channels
-
- byte[] data = new byte[4 * width * height];
-
- for (int src = 0, dst = 0; src < sourceData.length; src += 3, dst += 4) {
- data[dst + 0] = sourceData[src + 0]; // copy R byte
- data[dst + 1] = sourceData[src + 1]; // copy G byte
- data[dst + 2] = sourceData[src + 2]; // copy B byte
- data[dst + 3] = 1; // add alpha = 1
- }
-
- return data;
- }
-
- private byte[] addRGBChannels(byte[] sourceData, int width, int height) {
- assert sourceData.length == width * height; // should have a single alpha channel
-
- byte[] data = new byte[4 * width * height];
-
- for (int src = 0, dst = 0; src < sourceData.length; src++, dst += 4) {
- data[dst + 0] = data[dst + 1] = data[dst + 2] = 0; // set R = G = B = 0
- data[dst + 3] = sourceData[src]; // copy over alpha
- }
-
- return data;
- }
-
- private byte[] createRGBAFromLuminance(byte[] sourceData, int width, int height) {
- assert sourceData.length == width * height; // should have a single luminance channel
-
- byte[] data = new byte[4 * width * height];
-
- for (int src = 0, dst = 0; src < sourceData.length; src++, dst += 4) {
- int l = sourceData[src] * 3;
- if (l > 255) { // clamp to 255
- l = 255;
- }
-
- data[dst + 0] = data[dst + 1] = data[dst + 2] = (byte) l; // set R = G = B = L * 3
- data[dst + 3] = 1; // set alpha = 1
- }
-
- return data;
- }
-
- private byte[] createRGBAFromLuminanceAlpha(byte[] sourceData, int width, int height) {
- assert sourceData.length == 2 * width * height; // should have luminance & alpha channels
-
- byte[] data = new byte[4 * width * height];
-
- for (int src = 0, dst = 0; src < sourceData.length; src += 2, dst += 4) {
- int l = sourceData[src] * 3;
- if (l > 255) { // clamp to 255
- l = 255;
- }
-
- data[dst + 0] = data[dst + 1] = data[dst + 2] = (byte) l; // set R = G = B = L * 3
- data[dst + 3] = sourceData[src + 1]; // copy over alpha
- }
-
- return data;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/TexturePropertyAccessor.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/TexturePropertyAccessor.java
deleted file mode 100644
index 10758d819..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/TexturePropertyAccessor.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state.transforms;
-
-import com.android.ide.eclipse.gltrace.state.GLIntegerProperty;
-import com.android.ide.eclipse.gltrace.state.GLStateType;
-import com.android.ide.eclipse.gltrace.state.IGLProperty;
-
-/**
- * The {@link TexturePropertyAccessor} provides the ability to access a
- * texture property. Texture properties are accessed by first identifying the active
- * texture unit ({@link GLStateType#ACTIVE_TEXTURE_UNIT}), and then identifying the texture
- * that is bound to that unit.
- */
-public class TexturePropertyAccessor implements IGLPropertyAccessor {
- private final int mContextId;
- private final GLStateType mTargetUnitType;
- private final int mMipmapLevel;
- private final GLStateType mTextureType;
- private TextureUnitPropertyAccessor mTextureUnitPropertyAccessor;
-
- public TexturePropertyAccessor(int contextId, GLStateType textureUnitTarget, int level,
- GLStateType textureTargetName) {
- mContextId = contextId;
- mTargetUnitType = textureUnitTarget;
- mMipmapLevel = level;
- mTextureType = textureTargetName;
- mTextureUnitPropertyAccessor = new TextureUnitPropertyAccessor(mContextId,
- mTargetUnitType);
- }
-
- public TexturePropertyAccessor(int contextId, GLStateType textureUnitTarget,
- GLStateType textureTargetName) {
- this(contextId, textureUnitTarget, -1, textureTargetName);
- }
-
- @Override
- public IGLProperty getProperty(IGLProperty state) {
- // identify the texture that is bound in the current active texture unit
- IGLProperty targetTexture = mTextureUnitPropertyAccessor.getProperty(state);
- if (!(targetTexture instanceof GLIntegerProperty)) {
- return null;
- }
- Integer textureId = (Integer) targetTexture.getValue();
-
- // now extract the required property from the selected texture
- IGLPropertyAccessor textureAccessor;
- if (mMipmapLevel >= 0) {
- textureAccessor = GLPropertyAccessor.makeAccessor(mContextId,
- GLStateType.TEXTURE_STATE,
- GLStateType.TEXTURES,
- textureId,
- GLStateType.TEXTURE_MIPMAPS,
- Integer.valueOf(mMipmapLevel),
- mTextureType);
- } else {
- textureAccessor = GLPropertyAccessor.makeAccessor(mContextId,
- GLStateType.TEXTURE_STATE,
- GLStateType.TEXTURES,
- textureId,
- mTextureType);
- }
-
- return textureAccessor.getProperty(state);
- }
-
- @Override
- public String getPath() {
- return String.format("TEXTURE_STATE/TEXTURES/${activeTexture}/%s", mTextureType);
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/TextureUnitPropertyAccessor.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/TextureUnitPropertyAccessor.java
deleted file mode 100644
index 2489e14db..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/state/transforms/TextureUnitPropertyAccessor.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.state.transforms;
-
-import com.android.ide.eclipse.gltrace.state.GLIntegerProperty;
-import com.android.ide.eclipse.gltrace.state.GLStateType;
-import com.android.ide.eclipse.gltrace.state.IGLProperty;
-
-/**
- * The {@link TextureUnitPropertyAccessor} provides the ability to access a
- * texture unit property that is indexed based on the run time value of the
- * {@link GLStateType#ACTIVE_TEXTURE_UNIT} property.
- */
-public class TextureUnitPropertyAccessor implements IGLPropertyAccessor {
- private final int mContextId;
- private final IGLPropertyAccessor mActiveTextureAccessor;
- private final GLStateType mTargetType;
-
- public TextureUnitPropertyAccessor(int contextId, GLStateType targetPropertyType) {
- mContextId = contextId;
- mTargetType = targetPropertyType;
-
- mActiveTextureAccessor = GLPropertyAccessor.makeAccessor(mContextId,
- GLStateType.TEXTURE_STATE,
- GLStateType.ACTIVE_TEXTURE_UNIT);
- }
-
- @Override
- public IGLProperty getProperty(IGLProperty state) {
- // first extract the current active texture unit
- IGLProperty activeTextureProperty = mActiveTextureAccessor.getProperty(state);
- if (!(activeTextureProperty instanceof GLIntegerProperty)) {
- return null;
- }
- Integer activeTexture = (Integer) activeTextureProperty.getValue();
-
- // extract the required property for the current texture unit
- IGLPropertyAccessor targetAccessor = GLPropertyAccessor.makeAccessor(mContextId,
- GLStateType.TEXTURE_STATE,
- GLStateType.TEXTURE_UNITS,
- activeTexture,
- mTargetType);
- return targetAccessor.getProperty(state);
- }
-
- @Override
- public String getPath() {
- return String.format("TEXTURE_STATE/TEXTURE_UNITS/${activeTextureUnit}/%s", mTargetType);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/FitToCanvasAction.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/FitToCanvasAction.java
deleted file mode 100644
index 1ee0fa0c2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/FitToCanvasAction.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.views;
-
-import com.android.ide.eclipse.gltrace.GlTracePlugin;
-import com.android.ide.eclipse.gltrace.widgets.ImageCanvas;
-
-import org.eclipse.jface.action.Action;
-
-public class FitToCanvasAction extends Action {
- private ImageCanvas mImageCanvas;
-
- public FitToCanvasAction(boolean fitByDefault, ImageCanvas canvas) {
- super("Fit to Canvas", GlTracePlugin.getImageDescriptor("/icons/zoomfit.png")); //$NON-NLS-2$
- setToolTipText("Fit Image to Canvas");
- mImageCanvas = canvas;
-
- setChecked(fitByDefault);
- mImageCanvas.setFitToCanvas(fitByDefault);
- }
-
- @Override
- public void run() {
- mImageCanvas.setFitToCanvas(isChecked());
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/FrameSummaryView.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/FrameSummaryView.java
deleted file mode 100644
index 42eb98c8f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/FrameSummaryView.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.views;
-
-import com.android.ide.eclipse.gltrace.editors.GLFunctionTraceViewer;
-
-import org.eclipse.ui.IWorkbenchPart;
-
-/**
- * The {@link FrameSummaryView} is a page book view with pages of type {@link FrameSummaryViewPage}.
- */
-public class FrameSummaryView extends GLPageBookView {
- public static final String ID = "com.android.ide.eclipse.gltrace.views.FrameBuffer"; //$NON-NLS-1$
-
- public FrameSummaryView() {
- super("Open a GL Trace file to view the framebuffer contents.");
- }
-
- @Override
- protected PageRec doCreatePage(IWorkbenchPart part) {
- if (!(part instanceof GLFunctionTraceViewer)) {
- return null;
- }
-
- GLFunctionTraceViewer viewer = (GLFunctionTraceViewer) part;
- FrameSummaryViewPage page = viewer.getFrameSummaryViewPage();
- initPage(page);
- page.createControl(getPageBook());
-
- return new PageRec(part, page);
- }
-
- @Override
- protected void doDestroyPage(IWorkbenchPart part, PageRec pageRecord) {
- FrameSummaryViewPage page = (FrameSummaryViewPage) pageRecord.page;
- page.dispose();
- pageRecord.dispose();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/FrameSummaryViewPage.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/FrameSummaryViewPage.java
deleted file mode 100644
index 25de48f20..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/FrameSummaryViewPage.java
+++ /dev/null
@@ -1,442 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.views;
-
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.Function;
-import com.android.ide.eclipse.gltrace.model.GLCall;
-import com.android.ide.eclipse.gltrace.model.GLTrace;
-import com.android.ide.eclipse.gltrace.widgets.ImageCanvas;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.layout.GridDataFactory;
-import org.eclipse.jface.viewers.ColumnLabelProvider;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.TableViewer;
-import org.eclipse.jface.viewers.TableViewerColumn;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.viewers.ViewerCell;
-import org.eclipse.jface.viewers.ViewerComparator;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.SashForm;
-import org.eclipse.swt.events.ControlAdapter;
-import org.eclipse.swt.events.ControlEvent;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableColumn;
-import org.eclipse.ui.part.Page;
-
-import java.util.EnumMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * A {@link FrameSummaryViewPage} displays summary information regarding a frame. This includes
- * the contents of the frame buffer at the end of the frame, and statistics regarding the
- * OpenGL Calls present in the frame.
- */
-public class FrameSummaryViewPage extends Page {
- private GLTrace mTrace;
-
- private final Object mLock = new Object();
- private Job mRefresherJob;
- private int mCurrentFrame;
-
- private SashForm mSash;
- private ImageCanvas mImageCanvas;
-
- private Label mWallClockTimeLabel;
- private Label mThreadTimeLabel;
-
- private TableViewer mStatsTableViewer;
- private StatsLabelProvider mStatsLabelProvider;
- private StatsTableComparator mStatsTableComparator;
-
- private FitToCanvasAction mFitToCanvasAction;
- private SaveImageAction mSaveImageAction;
-
- private static final String[] STATS_TABLE_PROPERTIES = {
- "Function",
- "Count",
- "Wall Time (ns)",
- "Thread Time (ns)",
- };
- private static final float[] STATS_TABLE_COLWIDTH_RATIOS = {
- 0.4f, 0.1f, 0.25f, 0.25f,
- };
- private static final int[] STATS_TABLE_COL_ALIGNMENT = {
- SWT.LEFT, SWT.LEFT, SWT.RIGHT, SWT.RIGHT,
- };
-
- public FrameSummaryViewPage(GLTrace trace) {
- mTrace = trace;
- }
-
- public void setInput(GLTrace trace) {
- mTrace = trace;
- }
-
- @Override
- public void createControl(Composite parent) {
- mSash = new SashForm(parent, SWT.VERTICAL);
-
- // create image canvas where the framebuffer is displayed
- mImageCanvas = new ImageCanvas(mSash);
-
- // create a composite where the frame statistics are displayed
- createFrameStatisticsPart(mSash);
-
- mSash.setWeights(new int[] {70, 30});
-
- mFitToCanvasAction = new FitToCanvasAction(true, mImageCanvas);
- mSaveImageAction = new SaveImageAction(mImageCanvas);
-
- IToolBarManager toolbarManager = getSite().getActionBars().getToolBarManager();
- toolbarManager.add(mFitToCanvasAction);
- toolbarManager.add(mSaveImageAction);
- }
-
- private void createFrameStatisticsPart(Composite parent) {
- Composite c = new Composite(parent, SWT.NONE);
- c.setLayout(new GridLayout(2, false));
- GridDataFactory.fillDefaults().grab(true, true).applyTo(c);
-
- Label l = new Label(c, SWT.NONE);
- l.setText("Cumulative call duration of all OpenGL Calls in this frame:");
- l.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_DARK_GRAY));
- GridDataFactory.fillDefaults().span(2, 1).applyTo(l);
-
- l = new Label(c, SWT.NONE);
- l.setText("Wall Clock Time: ");
- GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(l);
-
- mWallClockTimeLabel = new Label(c, SWT.NONE);
- GridDataFactory.defaultsFor(mWallClockTimeLabel)
- .grab(true, false)
- .applyTo(mWallClockTimeLabel);
-
- l = new Label(c, SWT.NONE);
- l.setText("Thread Time: ");
- GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(l);
-
- mThreadTimeLabel = new Label(c, SWT.NONE);
- GridDataFactory.defaultsFor(mThreadTimeLabel)
- .grab(true, false)
- .applyTo(mThreadTimeLabel);
-
- l = new Label(c, SWT.HORIZONTAL | SWT.SEPARATOR);
- GridDataFactory.fillDefaults().span(2, 1).applyTo(l);
-
- l = new Label(c, SWT.NONE);
- l.setText("Per OpenGL Function Statistics:");
- l.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_DARK_GRAY));
- GridDataFactory.fillDefaults().span(2, 1).applyTo(l);
-
- final Table table = new Table(c, SWT.BORDER | SWT.FULL_SELECTION);
- GridDataFactory.fillDefaults().grab(true, true).span(2, 1).applyTo(table);
-
- table.setLinesVisible(true);
- table.setHeaderVisible(true);
-
- mStatsTableViewer = new TableViewer(table);
- mStatsLabelProvider = new StatsLabelProvider();
- mStatsTableComparator = new StatsTableComparator(1);
-
- // when a column is selected, sort the table based on that column
- SelectionListener columnSelectionListener = new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- TableColumn tc = (TableColumn) e.widget;
- String colText = tc.getText();
- for (int i = 0; i < STATS_TABLE_PROPERTIES.length; i++) {
- if (STATS_TABLE_PROPERTIES[i].equals(colText)) {
- mStatsTableComparator.setSortColumn(i);
- table.setSortColumn(tc);
- table.setSortDirection(mStatsTableComparator.getDirection());
- mStatsTableViewer.refresh();
- break;
- }
- }
- }
- };
-
- for (int i = 0; i < STATS_TABLE_PROPERTIES.length; i++) {
- TableViewerColumn tvc = new TableViewerColumn(mStatsTableViewer, SWT.NONE);
- tvc.getColumn().setText(STATS_TABLE_PROPERTIES[i]);
- tvc.setLabelProvider(mStatsLabelProvider);
- tvc.getColumn().setAlignment(STATS_TABLE_COL_ALIGNMENT[i]);
- tvc.getColumn().addSelectionListener(columnSelectionListener);
- }
- mStatsTableViewer.setContentProvider(new StatsContentProvider());
- mStatsTableViewer.setInput(null);
- mStatsTableViewer.setComparator(mStatsTableComparator);
-
- // resize columns appropriately when the size of the widget changes
- table.addControlListener(new ControlAdapter() {
- @Override
- public void controlResized(ControlEvent e) {
- int w = table.getClientArea().width;
-
- for (int i = 0; i < STATS_TABLE_COLWIDTH_RATIOS.length; i++) {
- table.getColumn(i).setWidth((int) (w * STATS_TABLE_COLWIDTH_RATIOS[i]));
- }
- }
- });
- }
-
- @Override
- public Control getControl() {
- return mSash;
- }
-
- @Override
- public void setFocus() {
- }
-
- public void setSelectedFrame(int frame) {
- if (mTrace == null) {
- return;
- }
-
- synchronized (mLock) {
- mCurrentFrame = frame;
-
- if (mRefresherJob != null) {
- return;
- }
-
- mRefresherJob = new Job("Update Frame Summary Task") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- final int currentFrame;
- synchronized (mLock) {
- currentFrame = mCurrentFrame;
- mRefresherJob = null;
- };
-
- updateImageCanvas(currentFrame);
- updateFrameStats(currentFrame);
-
- return Status.OK_STATUS;
- }
- };
- mRefresherJob.setPriority(Job.SHORT);
- mRefresherJob.schedule(500);
- };
- }
-
- private void updateFrameStats(int frame) {
- final List<GLCall> calls = mTrace.getGLCallsForFrame(frame);
-
- Job job = new Job("Update Frame Statistics") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- long wallClockDuration = 0;
- long threadDuration = 0;
-
- final Map<Function, PerCallStats> cumulativeStats =
- new EnumMap<Function, PerCallStats>(Function.class);
-
- for (GLCall c: calls) {
- wallClockDuration += c.getWallDuration();
- threadDuration += c.getThreadDuration();
-
- PerCallStats stats = cumulativeStats.get(c.getFunction());
- if (stats == null) {
- stats = new PerCallStats();
- }
-
- stats.count++;
- stats.threadDuration += c.getThreadDuration();
- stats.wallDuration += c.getWallDuration();
-
- cumulativeStats.put(c.getFunction(), stats);
- }
-
- final String wallTime = formatMilliSeconds(wallClockDuration);
- final String threadTime = formatMilliSeconds(threadDuration);
-
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- mWallClockTimeLabel.setText(wallTime);
- mThreadTimeLabel.setText(threadTime);
- mStatsTableViewer.setInput(cumulativeStats);
- }
- });
-
- return Status.OK_STATUS;
- }
- };
- job.setUser(true);
- job.schedule();
- }
-
- private String formatMilliSeconds(long nanoSeconds) {
- double milliSeconds = (double) nanoSeconds / 1000000;
- return String.format("%.2f ms", milliSeconds); //$NON-NLS-1$
- }
-
- private void updateImageCanvas(int frame) {
- int lastCallIndex = mTrace.getFrame(frame).getEndIndex() - 1;
- if (lastCallIndex >= 0 && lastCallIndex < mTrace.getGLCalls().size()) {
- GLCall call = mTrace.getGLCalls().get(lastCallIndex);
- final Image image = mTrace.getImage(call);
- Display.getDefault().asyncExec(new Runnable() {
- @Override
- public void run() {
- mImageCanvas.setImage(image);
-
- mFitToCanvasAction.setEnabled(image != null);
- mSaveImageAction.setEnabled(image != null);
- }
- });
- }
- }
-
- /** Cumulative stats maintained for each type of OpenGL Function in a particular frame. */
- private static class PerCallStats {
- public int count;
- public long wallDuration;
- public long threadDuration;
- }
-
- private static class StatsContentProvider implements IStructuredContentProvider {
- @Override
- public void dispose() {
- }
-
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- @Override
- public Object[] getElements(Object inputElement) {
- if (inputElement instanceof Map<?, ?>) {
- return ((Map<?, ?>) inputElement).entrySet().toArray();
- }
-
- return null;
- }
- }
-
- private static class StatsLabelProvider extends ColumnLabelProvider {
- @Override
- public void update(ViewerCell cell) {
- Object element = cell.getElement();
- if (!(element instanceof Map.Entry<?, ?>)) {
- return;
- }
-
- Function f = (Function) ((Map.Entry<?, ?>) element).getKey();
- PerCallStats stats = (PerCallStats) ((Map.Entry<?, ?>) element).getValue();
-
- switch (cell.getColumnIndex()) {
- case 0:
- cell.setText(f.toString());
- break;
- case 1:
- cell.setText(Integer.toString(stats.count));
- break;
- case 2:
- cell.setText(formatDuration(stats.wallDuration));
- break;
- case 3:
- cell.setText(formatDuration(stats.threadDuration));
- break;
- default:
- // should not happen
- cell.setText("??"); //$NON-NLS-1$
- break;
- }
- }
-
- private String formatDuration(long time) {
- // Max duration is in the 10s of milliseconds = xx,xxx,xxx ns
- // So we require a format specifier that is 10 characters wide
- return String.format("%,10d", time); //$NON-NLS-1$
- }
- }
-
- private static class StatsTableComparator extends ViewerComparator {
- private int mSortColumn;
- private boolean mDescending = true;
-
- private StatsTableComparator(int defaultSortColIndex) {
- mSortColumn = defaultSortColIndex;
- }
-
- public void setSortColumn(int index) {
- if (index == mSortColumn) {
- // if same column as what we are currently sorting on,
- // then toggle the direction
- mDescending = !mDescending;
- } else {
- mSortColumn = index;
- mDescending = true;
- }
- }
-
- public int getDirection() {
- return mDescending ? SWT.UP : SWT.DOWN;
- }
-
- @Override
- public int compare(Viewer viewer, Object e1, Object e2) {
- Map.Entry<?, ?> entry1;
- Map.Entry<?, ?> entry2;
-
- if (mDescending) {
- entry1 = (Map.Entry<?, ?>) e1;
- entry2 = (Map.Entry<?, ?>) e2;
- } else {
- entry1 = (Map.Entry<?, ?>) e2;
- entry2 = (Map.Entry<?, ?>) e1;
- }
-
- String k1 = entry1.getKey().toString();
- String k2 = entry2.getKey().toString();
-
- PerCallStats stats1 = (PerCallStats) entry1.getValue();
- PerCallStats stats2 = (PerCallStats) entry2.getValue();
-
- switch (mSortColumn) {
- case 0: // function name
- return String.CASE_INSENSITIVE_ORDER.compare(k1, k2);
- case 1:
- return stats1.count - stats2.count;
- case 2:
- return (int) (stats1.wallDuration - stats2.wallDuration);
- case 3:
- return (int) (stats1.threadDuration - stats2.threadDuration);
- default:
- return super.compare(viewer, e1, e2);
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/GLPageBookView.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/GLPageBookView.java
deleted file mode 100644
index 12405539b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/GLPageBookView.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.views;
-
-import com.android.ide.eclipse.gltrace.editors.GLFunctionTraceViewer;
-
-import org.eclipse.jface.viewers.ISelectionProvider;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.part.IPage;
-import org.eclipse.ui.part.IPageSite;
-import org.eclipse.ui.part.MessagePage;
-import org.eclipse.ui.part.PageBook;
-import org.eclipse.ui.part.PageBookView;
-
-/**
- * {@link GLPageBookView} is an abstract {@link PageBookView} that can be used
- * to provide page book view's whose main part is a {@link GLFunctionTraceViewer}.
- */
-public abstract class GLPageBookView extends PageBookView {
- private final String mDefaultMessage;
-
- public GLPageBookView(String defaultMessage) {
- super();
-
- mDefaultMessage = defaultMessage;
- }
-
- @Override
- protected IPage createDefaultPage(PageBook book) {
- MessagePage page = new MessagePage();
- initPage(page);
- page.createControl(book);
- page.setMessage(mDefaultMessage);
- return page;
- }
-
- @Override
- protected IWorkbenchPart getBootstrapPart() {
- IWorkbenchPage page = getSite().getPage();
- if (page != null) {
- return page.getActiveEditor();
- }
-
- return null;
- }
-
- @Override
- protected boolean isImportant(IWorkbenchPart part) {
- return part instanceof GLFunctionTraceViewer;
- }
-
- @Override
- public void partBroughtToTop(IWorkbenchPart part) {
- partActivated(part);
- }
-
- @Override
- protected void showPageRec(PageRec pageRec) {
- IPageSite pageSite = getPageSite(pageRec.page);
- if (pageRec.page instanceof ISelectionProvider) {
- pageSite.setSelectionProvider((ISelectionProvider) pageRec.page);
- } else {
- pageSite.setSelectionProvider(null); // clear selection provider
- }
-
- super.showPageRec(pageRec);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/SaveImageAction.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/SaveImageAction.java
deleted file mode 100644
index 6cc8b699c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/SaveImageAction.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.views;
-
-import com.android.ide.eclipse.gltrace.widgets.ImageCanvas;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.ui.ISharedImages;
-import org.eclipse.ui.PlatformUI;
-
-import java.io.File;
-
-public class SaveImageAction extends Action {
- private static String sLastUsedPath;
-
- private ImageCanvas mImageCanvas;
-
- public SaveImageAction(ImageCanvas canvas) {
- super("Save Image",
- PlatformUI.getWorkbench().getSharedImages().getImageDescriptor(
- ISharedImages.IMG_ETOOL_SAVEAS_EDIT));
- setToolTipText("Save Image");
- mImageCanvas = canvas;
- }
-
- @Override
- public void run() {
- FileDialog fd = new FileDialog(mImageCanvas.getShell(), SWT.SAVE);
- fd.setFilterExtensions(new String[] { "*.png" });
- if (sLastUsedPath != null) {
- fd.setFilterPath(sLastUsedPath);
- }
-
- String path = fd.open();
- if (path == null) {
- return;
- }
-
- File f = new File(path);
- sLastUsedPath = f.getParent();
- mImageCanvas.exportImageTo(f);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/StateView.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/StateView.java
deleted file mode 100644
index eff2fefaf..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/StateView.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.views;
-
-import com.android.ide.eclipse.gltrace.editors.GLFunctionTraceViewer;
-import com.android.ide.eclipse.gltrace.editors.StateViewPage;
-
-import org.eclipse.ui.IWorkbenchPart;
-
-/**
- * The StateView shows the GL state for the current active {@link GLFunctionTraceViewer}.
- * It behaves like the Eclipse Outline View: Each active editor provides the GL state content
- * to show via a {@link StateViewPage}. This class simply acts as a stack view showing the
- * state corresponding to whichever editor is active.
- */
-public class StateView extends GLPageBookView {
- public static final String ID = "com.android.ide.eclipse.gltrace.views.State"; //$NON-NLS-1$
-
- public StateView() {
- super("Open (or select) a GL Trace file to view the GL State.");
- }
-
- @Override
- protected PageRec doCreatePage(IWorkbenchPart part) {
- if (!(part instanceof GLFunctionTraceViewer)) {
- return null;
- }
-
- GLFunctionTraceViewer viewer = (GLFunctionTraceViewer) part;
- StateViewPage page = viewer.getStateViewPage();
- initPage(page);
- page.createControl(getPageBook());
-
- return new PageRec(part, page);
- }
-
- @Override
- protected void doDestroyPage(IWorkbenchPart part, PageRec pageRecord) {
- StateViewPage v = (StateViewPage) pageRecord.page;
- v.dispose();
- pageRecord.dispose();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/DetailsPage.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/DetailsPage.java
deleted file mode 100644
index 510898df9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/DetailsPage.java
+++ /dev/null
@@ -1,232 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.views.detail;
-
-import com.android.ide.eclipse.gltrace.editors.GLCallGroups.GLCallNode;
-import com.android.ide.eclipse.gltrace.editors.GLFunctionTraceViewer;
-import com.android.ide.eclipse.gltrace.model.GLCall;
-import com.android.ide.eclipse.gltrace.model.GLTrace;
-import com.android.ide.eclipse.gltrace.state.IGLProperty;
-import com.android.ide.eclipse.gltrace.views.StateView;
-
-import org.eclipse.jface.action.IContributionItem;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.viewers.TreeSelection;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.StackLayout;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.ISelectionListener;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.part.IPageSite;
-import org.eclipse.ui.part.Page;
-
-import java.util.Arrays;
-import java.util.List;
-
-public class DetailsPage extends Page implements ISelectionListener {
- private GLTrace mTrace;
-
- private IToolBarManager mToolBarManager;
- private Composite mTopComposite;
- private StackLayout mStackLayout;
- private Composite mBlankComposite;
-
- private List<IDetailProvider> mDetailProviders = Arrays.asList(
- new ShaderSourceDetailsProvider(),
- new ShaderUniformDetailsProvider(),
- new TextureImageDetailsProvider(),
- new VboDetailProvider(),
- new GlDrawCallDetailProvider(),
- new VertexAttribPointerDataDetailProvider());
-
- public DetailsPage(GLTrace trace) {
- mTrace = trace;
- }
-
- public void setInput(GLTrace trace) {
- mTrace = trace;
- }
-
- @Override
- public void createControl(Composite parent) {
- mTopComposite = new Composite(parent, SWT.NONE);
- mStackLayout = new StackLayout();
- mTopComposite.setLayout(mStackLayout);
- mTopComposite.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- mBlankComposite = new Composite(mTopComposite, SWT.NONE);
-
- mToolBarManager = getSite().getActionBars().getToolBarManager();
-
- for (IDetailProvider provider : mDetailProviders) {
- provider.createControl(mTopComposite);
-
- for (IContributionItem item: provider.getToolBarItems()) {
- mToolBarManager.add(item);
- }
- }
-
- setDetailsProvider(null);
- }
-
- private void setDetailsProvider(IDetailProvider provider) {
- for (IContributionItem item: mToolBarManager.getItems()) {
- item.setVisible(false);
- }
-
- if (provider == null) {
- setTopControl(mBlankComposite);
- } else {
- setTopControl(provider.getControl());
-
- for (IContributionItem item: provider.getToolBarItems()) {
- item.setVisible(true);
- }
- }
-
- mToolBarManager.update(true);
- }
-
- private void setTopControl(Control c) {
- mStackLayout.topControl = c;
- mTopComposite.layout();
- }
-
- @Override
- public Control getControl() {
- return mTopComposite;
- }
-
- @Override
- public void init(IPageSite pageSite) {
- super.init(pageSite);
- pageSite.getPage().addSelectionListener(this);
- }
-
- @Override
- public void dispose() {
- getSite().getPage().removeSelectionListener(this);
-
- for (IDetailProvider provider : mDetailProviders) {
- provider.disposeControl();
- }
-
- super.dispose();
- }
-
- @Override
- public void setFocus() {
- }
-
- @Override
- public void selectionChanged(IWorkbenchPart part, ISelection selection) {
- if (part instanceof GLFunctionTraceViewer) {
- GLCall selectedCall = getSelectedCall((GLFunctionTraceViewer) part, selection);
- if (selectedCall == null) {
- return;
- }
-
- callSelected(selectedCall);
- return;
- } else if (part instanceof StateView) {
- IGLProperty selectedProperty = getSelectedProperty((StateView) part, selection);
- if (selectedProperty == null) {
- return;
- }
-
- stateVariableSelected(selectedProperty);
- return;
- }
-
- return;
- }
-
- private void stateVariableSelected(IGLProperty property) {
- for (IDetailProvider p : mDetailProviders) {
- if (!(p instanceof IStateDetailProvider)) {
- continue;
- }
-
- IStateDetailProvider sp = (IStateDetailProvider) p;
- if (sp.isApplicable(property)) {
- sp.updateControl(property);
- setDetailsProvider(sp);
- return;
- }
- }
-
- setDetailsProvider(null);
- return;
- }
-
- private void callSelected(GLCall selectedCall) {
- for (IDetailProvider p : mDetailProviders) {
- if (!(p instanceof ICallDetailProvider)) {
- continue;
- }
-
- ICallDetailProvider cp = (ICallDetailProvider) p;
- if (cp.isApplicable(selectedCall)) {
- cp.updateControl(mTrace, selectedCall);
- setDetailsProvider(cp);
- return;
- }
- }
-
- setDetailsProvider(null);
- return;
- }
-
- private GLCall getSelectedCall(GLFunctionTraceViewer part, ISelection selection) {
- if (part.getTrace() != mTrace) {
- return null;
- }
-
- if (!(selection instanceof TreeSelection)) {
- return null;
- }
-
- Object data = ((TreeSelection) selection).getFirstElement();
- if (data instanceof GLCallNode) {
- return ((GLCallNode) data).getCall();
- } else {
- return null;
- }
- }
-
- private IGLProperty getSelectedProperty(StateView view, ISelection selection) {
- if (!(selection instanceof IStructuredSelection)) {
- return null;
- }
-
- IStructuredSelection ssel = (IStructuredSelection) selection;
- @SuppressWarnings("rawtypes")
- List objects = ssel.toList();
- if (objects.size() > 0) {
- Object data = objects.get(0);
- if (data instanceof IGLProperty) {
- return (IGLProperty) data;
- }
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/DetailsView.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/DetailsView.java
deleted file mode 100644
index 0a2d88e52..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/DetailsView.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.views.detail;
-
-import com.android.ide.eclipse.gltrace.editors.GLFunctionTraceViewer;
-import com.android.ide.eclipse.gltrace.views.GLPageBookView;
-
-import org.eclipse.ui.IWorkbenchPart;
-
-public class DetailsView extends GLPageBookView {
- public static final String ID = "com.android.ide.eclipse.gltrace.views.Details"; //$NON-NLS-1$
-
- public DetailsView() {
- super(""); //$NON-NLS-1$
- }
-
- @Override
- protected PageRec doCreatePage(IWorkbenchPart part) {
- if (!(part instanceof GLFunctionTraceViewer)) {
- return null;
- }
-
- GLFunctionTraceViewer viewer = (GLFunctionTraceViewer) part;
- DetailsPage page = viewer.getDetailsPage();
-
- initPage(page);
- page.createControl(getPageBook());
-
- return new PageRec(part, page);
- }
-
- @Override
- protected void doDestroyPage(IWorkbenchPart part, PageRec pageRecord) {
- DetailsPage page = (DetailsPage) pageRecord.page;
- page.dispose();
- pageRecord.dispose();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/GlDrawCallDetailProvider.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/GlDrawCallDetailProvider.java
deleted file mode 100644
index 44a05ffc9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/GlDrawCallDetailProvider.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.views.detail;
-
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.Function;
-import com.android.ide.eclipse.gltrace.model.GLCall;
-import com.android.ide.eclipse.gltrace.model.GLTrace;
-import com.android.ide.eclipse.gltrace.views.FitToCanvasAction;
-import com.android.ide.eclipse.gltrace.views.SaveImageAction;
-import com.android.ide.eclipse.gltrace.widgets.ImageCanvas;
-
-import org.eclipse.jface.action.ActionContributionItem;
-import org.eclipse.jface.action.IContributionItem;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-
-import java.util.Arrays;
-import java.util.List;
-
-public class GlDrawCallDetailProvider implements ICallDetailProvider {
- private ImageCanvas mImageCanvas;
- private FitToCanvasAction mFitToCanvasAction;
- private SaveImageAction mSaveImageAction;
- private List<IContributionItem> mToolBarItems;
-
- @Override
- public boolean isApplicable(GLCall call) {
- return (call.getFunction() == Function.glDrawArrays
- || call.getFunction() == Function.glDrawElements) && call.hasFb();
- }
-
- @Override
- public void createControl(Composite parent) {
- mImageCanvas = new ImageCanvas(parent);
- mImageCanvas.setFitToCanvas(false);
-
- mFitToCanvasAction = new FitToCanvasAction(false, mImageCanvas);
- mSaveImageAction = new SaveImageAction(mImageCanvas);
-
- mToolBarItems = Arrays.asList(
- (IContributionItem) new ActionContributionItem(mFitToCanvasAction),
- (IContributionItem) new ActionContributionItem(mSaveImageAction));
- }
-
- @Override
- public void disposeControl() {
- if (mImageCanvas != null) {
- mImageCanvas.dispose();
- mImageCanvas = null;
- }
- }
-
- @Override
- public Control getControl() {
- return mImageCanvas;
- }
-
- @Override
- public void updateControl(GLTrace trace, GLCall call) {
- mImageCanvas.setImage(trace.getImage(call));
- mImageCanvas.setFitToCanvas(true);
- }
-
- @Override
- public List<IContributionItem> getToolBarItems() {
- return mToolBarItems;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/ICallDetailProvider.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/ICallDetailProvider.java
deleted file mode 100644
index 51770f35b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/ICallDetailProvider.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.views.detail;
-
-import com.android.ide.eclipse.gltrace.model.GLCall;
-import com.android.ide.eclipse.gltrace.model.GLTrace;
-
-public interface ICallDetailProvider extends IDetailProvider {
- /** Is this provider applicable for given {@link GLCall}? */
- boolean isApplicable(GLCall call);
-
- /**
- * Update the detail view for given {@link GLCall} that is part of the given
- * {@link GLTrace}.
- */
- void updateControl(GLTrace trace, GLCall call);
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/IDetailProvider.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/IDetailProvider.java
deleted file mode 100644
index 1fc5174d3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/IDetailProvider.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.views.detail;
-
-import org.eclipse.jface.action.IContributionItem;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-
-import java.util.List;
-
-public interface IDetailProvider {
- /** Create the controls to display the details. */
- void createControl(Composite parent);
-
- /** Dispose off any created controls. */
- void disposeControl();
-
- /** Obtain the top level control used by this detail provider. */
- Control getControl();
-
-
- /** Obtain a list of tool bar items to be displayed when this provider is active. */
- List<IContributionItem> getToolBarItems();
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/IStateDetailProvider.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/IStateDetailProvider.java
deleted file mode 100644
index 4ad06beba..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/IStateDetailProvider.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.views.detail;
-
-import com.android.ide.eclipse.gltrace.state.IGLProperty;
-
-public interface IStateDetailProvider extends IDetailProvider {
- /** Is this provider applicable for given GL state property? */
- boolean isApplicable(IGLProperty state);
-
- /** Update the detail view for given GL state property. */
- void updateControl(IGLProperty state);
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/ShaderSourceDetailsProvider.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/ShaderSourceDetailsProvider.java
deleted file mode 100644
index ca986c355..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/ShaderSourceDetailsProvider.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.views.detail;
-
-import com.android.ide.eclipse.gltrace.state.GLCompositeProperty;
-import com.android.ide.eclipse.gltrace.state.GLStateType;
-import com.android.ide.eclipse.gltrace.state.GLStringProperty;
-import com.android.ide.eclipse.gltrace.state.IGLProperty;
-
-import org.eclipse.jface.action.IContributionItem;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Text;
-
-import java.util.Collections;
-import java.util.List;
-
-public class ShaderSourceDetailsProvider implements IStateDetailProvider {
- private Text mTextControl;
-
- @Override
- public boolean isApplicable(IGLProperty state) {
- return getShaderSourceProperty(state) != null;
- }
-
- @Override
- public void createControl(Composite parent) {
- mTextControl = new Text(parent, SWT.BORDER| SWT.READ_ONLY
- | SWT.MULTI | SWT.WRAP | SWT.V_SCROLL | SWT.H_SCROLL);
- mTextControl.setEditable(false);
- }
-
- @Override
- public void disposeControl() {
- }
-
- @Override
- public Control getControl() {
- return mTextControl;
- }
-
- @Override
- public void updateControl(IGLProperty state) {
- IGLProperty shaderSrcProperty = getShaderSourceProperty(state);
- if (shaderSrcProperty instanceof GLStringProperty) {
- String shaderSrc = ((GLStringProperty) shaderSrcProperty).getStringValue();
- mTextControl.setText(shaderSrc);
- mTextControl.setEnabled(true);
- } else {
- mTextControl.setText(""); //$NON-NLS-1$
- mTextControl.setEnabled(false);
- }
- }
-
- /**
- * Get the {@link GLStateType#SHADER_SOURCE} property given a node in
- * the state hierarchy.
- * @param state any node in the GL state hierarchy
- * @return The {@link GLStateType#SHADER_SOURCE} property if a unique instance
- * of it can be accessed from the given node, null otherwise.
- * A unique instance can be accessed if the given node is
- * either the requested node itself, or its parent or sibling.
- */
- private IGLProperty getShaderSourceProperty(IGLProperty state) {
- if (state.getType() == GLStateType.SHADER_SOURCE) {
- // given node is the requested node
- return state;
- }
-
- if (state.getType() != GLStateType.PER_SHADER_STATE) {
- // if it is not the parent, then it could be a sibling, in which case
- // we go up a level to its parent
- state = state.getParent();
- }
-
- if (state != null && state.getType() == GLStateType.PER_SHADER_STATE) {
- // if it is the parent, we can access the required property
- return ((GLCompositeProperty) state).getProperty(GLStateType.SHADER_SOURCE);
- }
-
- return null;
- }
-
- @Override
- public List<IContributionItem> getToolBarItems() {
- return Collections.emptyList();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/ShaderUniformDetailsProvider.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/ShaderUniformDetailsProvider.java
deleted file mode 100644
index 2e3f7254b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/ShaderUniformDetailsProvider.java
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.views.detail;
-
-import com.android.ide.eclipse.gltrace.GLEnum;
-import com.android.ide.eclipse.gltrace.state.GLCompositeProperty;
-import com.android.ide.eclipse.gltrace.state.GLStateType;
-import com.android.ide.eclipse.gltrace.state.IGLProperty;
-import com.google.common.base.Joiner;
-
-import org.eclipse.jface.action.IContributionItem;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Text;
-
-import java.util.Collections;
-import java.util.List;
-
-public class ShaderUniformDetailsProvider implements IStateDetailProvider {
- private Text mTextControl;
- private static final Joiner JOINER = Joiner.on(", ");
-
- @Override
- public boolean isApplicable(IGLProperty state) {
- return getShaderUniformProperty(state) != null;
- }
-
- @Override
- public void createControl(Composite parent) {
- mTextControl = new Text(parent, SWT.BORDER | SWT.READ_ONLY | SWT.MULTI | SWT.WRAP);
- mTextControl.setEditable(false);
- }
-
- @Override
- public void disposeControl() {
- }
-
- @Override
- public Control getControl() {
- return mTextControl;
- }
-
- @Override
- public void updateControl(IGLProperty state) {
- IGLProperty uniform = getShaderUniformProperty(state);
- if (uniform instanceof GLCompositeProperty) {
- GLCompositeProperty uniformProperty = (GLCompositeProperty) uniform;
- IGLProperty nameProperty = uniformProperty.getProperty(GLStateType.UNIFORM_NAME);
- IGLProperty typeProperty = uniformProperty.getProperty(GLStateType.UNIFORM_TYPE);
- IGLProperty valueProperty = uniformProperty.getProperty(GLStateType.UNIFORM_VALUE);
-
- String name = (String) nameProperty.getValue();
- GLEnum type = (GLEnum) typeProperty.getValue();
- Object value = valueProperty.getValue();
- mTextControl.setText(formatUniform(name, type, value));
- mTextControl.setEnabled(true);
- } else {
- mTextControl.setText(""); //$NON-NLS-1$
- mTextControl.setEnabled(false);
- }
- }
-
- private String formatUniform(String name, GLEnum type, Object value) {
- String valueText;
-
- switch (type) {
- case GL_FLOAT:
- case GL_FLOAT_VEC2:
- case GL_FLOAT_VEC3:
- case GL_FLOAT_VEC4:
- case GL_INT:
- case GL_INT_VEC2:
- case GL_INT_VEC3:
- case GL_INT_VEC4:
- case GL_BOOL:
- case GL_BOOL_VEC2:
- case GL_BOOL_VEC3:
- case GL_BOOL_VEC4:
- valueText = formatVector(value);
- break;
- case GL_FLOAT_MAT2:
- valueText = formatMatrix(2, value);
- break;
- case GL_FLOAT_MAT3:
- valueText = formatMatrix(3, value);
- break;
- case GL_FLOAT_MAT4:
- valueText = formatMatrix(4, value);
- break;
- case GL_SAMPLER_2D:
- case GL_SAMPLER_CUBE:
- default:
- valueText = value.toString();
- break;
- }
-
- return String.format("%s %s = %s", type, name, valueText); //$NON-NLS-1$
- }
-
- private String formatVector(Object value) {
- if (value instanceof List<?>) {
- List<?> list = (List<?>) value;
- StringBuilder sb = new StringBuilder(list.size() * 4);
- sb.append('[');
- JOINER.appendTo(sb, list);
- sb.append(']');
- return sb.toString();
- }
-
- return value.toString();
- }
-
- private String formatMatrix(int dimension, Object value) {
- if (value instanceof List<?>) {
- List<?> list = (List<?>) value;
- if (list.size() != dimension * dimension) {
- // Uniforms can only be square matrices, so this scenario should
- // not occur.
- return formatVector(value);
- }
-
- StringBuilder sb = new StringBuilder(list.size() * 4);
- sb.append('[');
- sb.append('\n');
- for (int i = 0; i < dimension; i++) {
- sb.append(" "); //$NON-NLS-1$
- JOINER.appendTo(sb, list.subList(i * dimension, (i + 1) * dimension));
- sb.append('\n');
- }
- sb.append(']');
- return sb.toString();
- }
-
- return value.toString();
- }
-
- /**
- * Get the {@link GLStateType#PER_UNIFORM_STATE} property given a node in
- * the state hierarchy.
- */
- private IGLProperty getShaderUniformProperty(IGLProperty state) {
- if (state.getType() == GLStateType.PER_UNIFORM_STATE) {
- return state;
- }
-
- state = state.getParent();
- if (state != null && state.getType() == GLStateType.PER_UNIFORM_STATE) {
- return state;
- }
-
- return null;
- }
-
- @Override
- public List<IContributionItem> getToolBarItems() {
- return Collections.emptyList();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/TextureImageDetailsProvider.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/TextureImageDetailsProvider.java
deleted file mode 100644
index 4dcbb10c4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/TextureImageDetailsProvider.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.views.detail;
-
-import com.android.ide.eclipse.gltrace.state.GLCompositeProperty;
-import com.android.ide.eclipse.gltrace.state.GLSparseArrayProperty;
-import com.android.ide.eclipse.gltrace.state.GLStateType;
-import com.android.ide.eclipse.gltrace.state.GLStringProperty;
-import com.android.ide.eclipse.gltrace.state.IGLProperty;
-import com.android.ide.eclipse.gltrace.views.FitToCanvasAction;
-import com.android.ide.eclipse.gltrace.views.SaveImageAction;
-import com.android.ide.eclipse.gltrace.widgets.ImageCanvas;
-
-import org.eclipse.jface.action.ActionContributionItem;
-import org.eclipse.jface.action.IContributionItem;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Display;
-
-import java.util.Arrays;
-import java.util.List;
-
-public class TextureImageDetailsProvider implements IStateDetailProvider {
- private ImageCanvas mImageCanvas;
- private FitToCanvasAction mFitToCanvasAction;
- private SaveImageAction mSaveImageAction;
- private List<IContributionItem> mToolBarItems;
-
- @Override
- public boolean isApplicable(IGLProperty state) {
- return getTextureImageProperty(state) != null;
- }
-
- @Override
- public void createControl(Composite parent) {
- mImageCanvas = new ImageCanvas(parent);
- mImageCanvas.setFitToCanvas(false);
-
- mFitToCanvasAction = new FitToCanvasAction(false, mImageCanvas);
- mSaveImageAction = new SaveImageAction(mImageCanvas);
-
- mToolBarItems = Arrays.asList(
- (IContributionItem) new ActionContributionItem(mFitToCanvasAction),
- (IContributionItem) new ActionContributionItem(mSaveImageAction));
- }
-
- @Override
- public void disposeControl() {
- mImageCanvas.dispose();
- mImageCanvas = null;
- }
-
- @Override
- public Control getControl() {
- return mImageCanvas;
- }
-
- @Override
- public void updateControl(IGLProperty state) {
- IGLProperty imageProperty = getTextureImageProperty(state);
- if (imageProperty == null) {
- return;
- }
-
- String texturePath = ((GLStringProperty) imageProperty).getStringValue();
- if (texturePath != null) {
- mImageCanvas.setImage(new Image(Display.getDefault(), texturePath));
- mImageCanvas.setFitToCanvas(false);
- return;
- }
- }
-
- /**
- * Get the {@link GLStateType#TEXTURE_IMAGE} property given a node in
- * the state hierarchy.
- * @param state any node in the GL state hierarchy
- * @return The {@link GLStateType#TEXTURE_IMAGE} property if a unique instance
- * of it can be accessed from the given node. A unique instance can be
- * accessed if the given node is either the requested node itself, or
- * its parent or sibling. In cases where a unique instance cannot be
- * accessed, but one of the texture mipmap levels can be accessed, then
- * return the first texture mipmap level. This happens if the selected
- * state is a child of {@link GLStateType#PER_TEXTURE_STATE}. Returns
- * null otherwise.
- */
- private IGLProperty getTextureImageProperty(IGLProperty state) {
- if (state.getType() == GLStateType.TEXTURE_IMAGE) {
- // given node is the requested node
- return state;
- }
-
- IGLProperty img = getImageFromPerTextureLevelState(state);
- if (img != null) {
- return img;
- }
-
- return getFirstMipmapImage(state);
- }
-
- /**
- * Returns the {@link GLStateType#TEXTURE_IMAGE} if the provided state is either
- * {@link GLStateType#PER_TEXTURE_LEVEL_STATE} or one of its children. Returns null otherwise.
- */
- private IGLProperty getImageFromPerTextureLevelState(IGLProperty state) {
- if (state != null && state.getType() != GLStateType.PER_TEXTURE_LEVEL_STATE) {
- state = state.getParent();
- }
-
- if (state == null || state.getType() != GLStateType.PER_TEXTURE_LEVEL_STATE) {
- return null;
- }
-
- return ((GLCompositeProperty) state).getProperty(GLStateType.TEXTURE_IMAGE);
- }
-
- /**
- * Returns the first mipmap level's image entry if the provided state is either
- * {@link GLStateType#PER_TEXTURE_STATE} or one of its immediate children, null otherwise.
- */
- private IGLProperty getFirstMipmapImage(IGLProperty state) {
- if (state != null && state.getType() != GLStateType.PER_TEXTURE_STATE) {
- state = state.getParent();
- }
-
- if (state == null || state.getType() != GLStateType.PER_TEXTURE_STATE) {
- return null;
- }
-
- IGLProperty mipmaps =
- ((GLCompositeProperty) state).getProperty(GLStateType.TEXTURE_MIPMAPS);
- if (!(mipmaps instanceof GLSparseArrayProperty)) {
- return null;
- }
-
- IGLProperty perTextureLevelState = ((GLSparseArrayProperty) mipmaps).getProperty(0);
- return getImageFromPerTextureLevelState(perTextureLevelState);
- }
-
- @Override
- public List<IContributionItem> getToolBarItems() {
- return mToolBarItems;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/VboDetailProvider.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/VboDetailProvider.java
deleted file mode 100644
index e0ba947c5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/VboDetailProvider.java
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.views.detail;
-
-import com.android.ide.eclipse.gltrace.GLEnum;
-import com.android.ide.eclipse.gltrace.GLUtils;
-import com.android.ide.eclipse.gltrace.state.GLCompositeProperty;
-import com.android.ide.eclipse.gltrace.state.GLStateType;
-import com.android.ide.eclipse.gltrace.state.IGLProperty;
-
-import org.eclipse.jface.action.IContributionItem;
-import org.eclipse.jface.layout.GridDataFactory;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Combo;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-public class VboDetailProvider implements IStateDetailProvider {
- private static enum DisplayFormat {
- GL_FLOAT,
- GL_BYTE,
- GL_UNSIGNED_BYTE,
- GL_SHORT,
- GL_UNSIGNED_SHORT,
- GL_FIXED,
- }
-
- private Composite mComposite;
-
- private Label mSizeLabel;
- private Label mUsageLabel;
- private Label mTypeLabel;
- private Combo mDisplayFormatCombo;
- private Text mTextControl;
-
- private byte[] mBufferData;
-
- @Override
- public boolean isApplicable(IGLProperty state) {
- return getVboProperty(state) != null;
- }
-
- @Override
- public void createControl(Composite parent) {
- mComposite = new Composite(parent, SWT.NONE);
- GridLayout layout = new GridLayout(2, false);
- layout.marginWidth = layout.marginHeight = 0;
- mComposite.setLayout(layout);
- GridDataFactory.fillDefaults().grab(true, true).applyTo(mComposite);
-
- Label l = new Label(mComposite, SWT.NONE);
- l.setText("Size: ");
- GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(l);
-
- mSizeLabel = new Label(mComposite, SWT.NONE);
- GridDataFactory.fillDefaults().grab(true, false).applyTo(mSizeLabel);
-
- l = new Label(mComposite, SWT.NONE);
- l.setText("Usage: ");
- GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(l);
-
- mUsageLabel = new Label(mComposite, SWT.NONE);
- GridDataFactory.fillDefaults().grab(true, false).applyTo(mUsageLabel);
-
- l = new Label(mComposite, SWT.NONE);
- l.setText("Type: ");
- GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(l);
-
- mTypeLabel = new Label(mComposite, SWT.NONE);
- GridDataFactory.fillDefaults().grab(true, false).applyTo(mTypeLabel);
-
- l = new Label(mComposite, SWT.NONE);
- l.setText("Format Data As: ");
- GridDataFactory.fillDefaults().align(SWT.RIGHT, SWT.CENTER).applyTo(l);
-
- DisplayFormat[] values = DisplayFormat.values();
- List<String> formats = new ArrayList<String>(values.length);
- for (DisplayFormat format: values) {
- formats.add(format.name());
- }
-
- mDisplayFormatCombo = new Combo(mComposite, SWT.DROP_DOWN | SWT.READ_ONLY);
- mDisplayFormatCombo.setItems(formats.toArray(new String[formats.size()]));
- mDisplayFormatCombo.select(0);
- mDisplayFormatCombo.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateContents();
- }
- });
- GridDataFactory.fillDefaults().grab(true, false).applyTo(mDisplayFormatCombo);
-
- mTextControl = new Text(mComposite, SWT.BORDER | SWT.READ_ONLY | SWT.MULTI
- | SWT.WRAP | SWT.V_SCROLL | SWT.H_SCROLL);
- GridDataFactory.fillDefaults().span(2, 1).grab(true, true).applyTo(mTextControl);
- mTextControl.setEditable(false);
- }
-
- @Override
- public void disposeControl() {
- }
-
- @Override
- public Control getControl() {
- return mComposite;
- }
-
- @Override
- public void updateControl(IGLProperty state) {
- IGLProperty vbo = getVboProperty(state);
- if (vbo instanceof GLCompositeProperty) {
- GLCompositeProperty vboProperty = (GLCompositeProperty) vbo;
-
- IGLProperty sizeProperty = vboProperty.getProperty(GLStateType.BUFFER_SIZE);
- mSizeLabel.setText(sizeProperty.getStringValue() + " bytes"); //$NON-NLS-1$
-
- IGLProperty usageProperty = vboProperty.getProperty(GLStateType.BUFFER_USAGE);
- mUsageLabel.setText(usageProperty.getStringValue());
-
- IGLProperty typeProperty = vboProperty.getProperty(GLStateType.BUFFER_TYPE);
- mTypeLabel.setText(typeProperty.getStringValue());
-
- IGLProperty dataProperty = vboProperty.getProperty(GLStateType.BUFFER_DATA);
- mBufferData = (byte[]) dataProperty.getValue();
- } else {
- mBufferData = null;
- }
-
- updateContents();
- }
-
- private void updateContents() {
- if (mBufferData != null) {
- mTextControl.setText(GLUtils.formatData(mBufferData,
- GLEnum.valueOf(mDisplayFormatCombo.getText())));
- mTextControl.setEnabled(true);
- mDisplayFormatCombo.setEnabled(true);
- } else {
- mTextControl.setText("");
- mTextControl.setEnabled(false);
- mDisplayFormatCombo.setEnabled(false);
- }
- }
-
- @Override
- public List<IContributionItem> getToolBarItems() {
- return Collections.emptyList();
- }
-
- /**
- * Get the {@link GLStateType#VBO_COMPOSITE} property given a node in
- * the state hierarchy.
- */
- private IGLProperty getVboProperty(IGLProperty state) {
- if (state.getType() == GLStateType.VBO_COMPOSITE) {
- return state;
- }
-
- state = state.getParent();
- if (state != null && state.getType() == GLStateType.VBO_COMPOSITE) {
- return state;
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/VertexAttribPointerDataDetailProvider.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/VertexAttribPointerDataDetailProvider.java
deleted file mode 100644
index 55f8d841c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/views/detail/VertexAttribPointerDataDetailProvider.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.views.detail;
-
-import com.android.ide.eclipse.gltrace.GLEnum;
-import com.android.ide.eclipse.gltrace.GLUtils;
-import com.android.ide.eclipse.gltrace.GLProtoBuf.GLMessage.Function;
-import com.android.ide.eclipse.gltrace.model.GLCall;
-import com.android.ide.eclipse.gltrace.model.GLTrace;
-import com.google.protobuf.ByteString;
-
-import org.eclipse.jface.action.IContributionItem;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.Text;
-
-import java.util.Collections;
-import java.util.List;
-
-public class VertexAttribPointerDataDetailProvider implements ICallDetailProvider {
- private Text mText;
-
- @Override
- public boolean isApplicable(GLCall call) {
- return call.getFunction() == Function.glVertexAttribPointerData;
- }
-
- @Override
- public void createControl(Composite parent) {
- mText = new Text(parent, SWT.BORDER | SWT.READ_ONLY | SWT.MULTI
- | SWT.WRAP | SWT.V_SCROLL | SWT.H_SCROLL);
- }
-
- @Override
- public void disposeControl() {
- }
-
- @Override
- public Control getControl() {
- return mText;
- }
-
- @Override
- public void updateControl(GLTrace trace, GLCall call) {
- // void glVertexAttribPointerData(GLuint indx, GLint size, GLenum type, GLboolean norm,
- // GLsizei stride, const GLvoid* ptr, int minIndex, int maxIndex)
- GLEnum type = (GLEnum) call.getProperty(GLCall.PROPERTY_VERTEX_ATTRIB_POINTER_TYPE);
- byte[] data = (byte[]) call.getProperty(GLCall.PROPERTY_VERTEX_ATTRIB_POINTER_DATA);
-
- mText.setText(GLUtils.formatData(data, type));
- }
-
- @Override
- public List<IContributionItem> getToolBarItems() {
- return Collections.emptyList();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/widgets/ImageCanvas.java b/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/widgets/ImageCanvas.java
deleted file mode 100644
index 23baf1739..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.gldebugger/src/com/android/ide/eclipse/gltrace/widgets/ImageCanvas.java
+++ /dev/null
@@ -1,250 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.gltrace.widgets;
-
-import com.android.ide.eclipse.gltrace.GlTracePlugin;
-
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.ImageData;
-import org.eclipse.swt.graphics.ImageLoader;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Canvas;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.ScrollBar;
-
-import java.io.File;
-
-public class ImageCanvas extends Canvas {
- private static final int SCROLLBAR_INCREMENT = 20;
-
- private Point mOrigin;
-
- private ScrollBar mHorizontalScrollBar;
- private ScrollBar mVerticalScrollBar;
-
- private Image mImage;
- private boolean mFitToCanvas;
-
- public ImageCanvas(Composite parent) {
- super(parent, SWT.NO_BACKGROUND | SWT.V_SCROLL | SWT.H_SCROLL);
- mOrigin = new Point(0, 0);
-
- mHorizontalScrollBar = getHorizontalBar();
- mVerticalScrollBar = getVerticalBar();
-
- mFitToCanvas = true;
-
- setScrollBarIncrements();
- setScrollBarPageIncrements(getClientArea());
-
- updateScrollBars();
-
- SelectionListener scrollBarSelectionListener = new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- if (e.getSource() == mHorizontalScrollBar) {
- scrollHorizontally();
- } else {
- scrollVertically();
- }
- }
- };
-
- mHorizontalScrollBar.addSelectionListener(scrollBarSelectionListener);
- mVerticalScrollBar.addSelectionListener(scrollBarSelectionListener);
-
- addListener(SWT.Resize, new Listener() {
- @Override
- public void handleEvent(Event e) {
- setScrollBarPageIncrements(getClientArea());
- updateScrollBars();
- }
- });
-
- addListener(SWT.Paint, new Listener() {
- @Override
- public void handleEvent(Event e) {
- paintCanvas(e.gc);
- }
- });
- }
-
- public void setFitToCanvas(boolean en) {
- mFitToCanvas = en;
- updateScrollBars();
- redraw();
- }
-
- public void setImage(Image image) {
- if (mImage != null) {
- mImage.dispose();
- }
-
- mImage = image;
- mOrigin = new Point(0, 0);
- updateScrollBars();
- redraw();
- }
-
- private void updateScrollBars() {
- Rectangle client = getClientArea();
-
- int imageWidth, imageHeight;
- if (mImage != null & !mFitToCanvas) {
- imageWidth = mImage.getBounds().width;
- imageHeight = mImage.getBounds().height;
- } else {
- imageWidth = client.width;
- imageHeight = client.height;
- }
-
- mHorizontalScrollBar.setMaximum(imageWidth);
- mVerticalScrollBar.setMaximum(imageHeight);
- mHorizontalScrollBar.setThumb(Math.min(imageWidth, client.width));
- mVerticalScrollBar.setThumb(Math.min(imageHeight, client.height));
-
- int hPage = imageWidth - client.width;
- int vPage = imageHeight - client.height;
- int hSelection = mHorizontalScrollBar.getSelection();
- int vSelection = mVerticalScrollBar.getSelection();
- if (hSelection >= hPage) {
- if (hPage <= 0) {
- hSelection = 0;
- }
- mOrigin.x = -hSelection;
- }
-
- if (vSelection >= vPage) {
- if (vPage <= 0) {
- vSelection = 0;
- }
- mOrigin.y = -vSelection;
- }
-
- redraw();
- }
-
- private void setScrollBarPageIncrements(Rectangle clientArea) {
- mHorizontalScrollBar.setPageIncrement(clientArea.width);
- mVerticalScrollBar.setPageIncrement(clientArea.height);
- }
-
- private void setScrollBarIncrements() {
- // The default increment is 1 pixel. Assign a saner default.
- mHorizontalScrollBar.setIncrement(SCROLLBAR_INCREMENT);
- mVerticalScrollBar.setIncrement(SCROLLBAR_INCREMENT);
- }
-
- private void scrollHorizontally() {
- if (mImage == null) {
- return;
- }
-
- int selection = mHorizontalScrollBar.getSelection();
- int destX = -selection - mOrigin.x;
- Rectangle imageBounds = mImage.getBounds();
- scroll(destX, 0, 0, 0, imageBounds.width, imageBounds.height, false);
- mOrigin.x = -selection;
- }
-
- private void scrollVertically() {
- if (mImage == null) {
- return;
- }
-
- int selection = mVerticalScrollBar.getSelection();
- int destY = -selection - mOrigin.y;
- Rectangle imageBounds = mImage.getBounds();
- scroll(0, destY, 0, 0, imageBounds.width, imageBounds.height, false);
- mOrigin.y = -selection;
- }
-
- private void paintCanvas(GC gc) {
- gc.fillRectangle(getClientArea()); // clear entire client area
- if (mImage == null) {
- return;
- }
-
- Rectangle rect = mImage.getBounds();
- Rectangle client = getClientArea();
-
- if (mFitToCanvas && rect.width > 0 && rect.height > 0) {
- double sx = (double) client.width / (double) rect.width;
- double sy = (double) client.height / (double) rect.height;
-
- if (sx < sy) {
- // if we need to scale more horizontally, then reduce the client height
- // appropriately so that aspect ratios are maintained
- gc.drawImage(mImage,
- 0, 0, rect.width, rect.height,
- 0, 0, client.width, (int)(rect.height * sx));
- drawBorder(gc, 0, 0, client.width, (int)(rect.height * sx));
- } else {
- // scale client width to maintain aspect ratio
- gc.drawImage(mImage,
- 0, 0, rect.width, rect.height,
- 0, 0, (int)(rect.width * sy), client.height);
- drawBorder(gc, 0, 0, (int)(rect.width * sy), client.height);
- }
- } else {
- gc.drawImage(mImage, mOrigin.x, mOrigin.y);
- drawBorder(gc, mOrigin.x, mOrigin.y, rect.width, rect.height);
- }
- }
-
- private void drawBorder(GC gc, int x, int y, int width, int height) {
- Color origFg = gc.getForeground();
- gc.setForeground(Display.getDefault().getSystemColor(SWT.COLOR_WIDGET_NORMAL_SHADOW));
- gc.drawRectangle(x, y, width, height);
- gc.setForeground(origFg);
- }
-
- @Override
- public void dispose() {
- if (mImage != null && !mImage.isDisposed()) {
- mImage.dispose();
- }
- }
-
- public void exportImageTo(File file) {
- if (mImage == null || file == null) {
- return;
- }
-
- ImageLoader imageLoader = new ImageLoader();
- imageLoader.data = new ImageData[] { mImage.getImageData() };
-
- try {
- imageLoader.save(file.getAbsolutePath(), SWT.IMAGE_PNG);
- } catch (Exception e) {
- ErrorDialog.openError(getShell(), "Save Image", "Error saving image",
- new Status(Status.ERROR, GlTracePlugin.PLUGIN_ID, e.toString()));
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/.classpath b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/.classpath
deleted file mode 100644
index 7073f2091..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/.classpath
+++ /dev/null
@@ -1,10 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry kind="src" path="src"/>
- <classpathentry kind="lib" path="libs/hierarchyviewer2lib.jar" sourcepath="/hierarchyviewer2lib"/>
- <classpathentry combineaccessrules="false" kind="src" path="/ddmlib"/>
- <classpathentry combineaccessrules="false" kind="src" path="/ddmuilib"/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/.project b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/.project
deleted file mode 100644
index c9e969694..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/.project
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>plugin-hierarchyviewer</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/.settings/org.eclipse.jdt.core.prefs b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/.settings/org.eclipse.jdt.core.prefs
deleted file mode 100644
index ea661960a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/.settings/org.eclipse.jdt.core.prefs
+++ /dev/null
@@ -1,98 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore
-org.eclipse.jdt.core.compiler.annotation.nonnull=com.android.annotations.NonNull
-org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=com.android.annotations.NonNullByDefault
-org.eclipse.jdt.core.compiler.annotation.nonnullisdefault=disabled
-org.eclipse.jdt.core.compiler.annotation.nullable=com.android.annotations.Nullable
-org.eclipse.jdt.core.compiler.annotation.nullanalysis=enabled
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
-org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
-org.eclipse.jdt.core.compiler.compliance=1.6
-org.eclipse.jdt.core.compiler.debug.lineNumber=generate
-org.eclipse.jdt.core.compiler.debug.localVariable=generate
-org.eclipse.jdt.core.compiler.debug.sourceFile=generate
-org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
-org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
-org.eclipse.jdt.core.compiler.problem.deadCode=warning
-org.eclipse.jdt.core.compiler.problem.deprecation=warning
-org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
-org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
-org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
-org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore
-org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning
-org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled
-org.eclipse.jdt.core.compiler.problem.fieldHiding=warning
-org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
-org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
-org.eclipse.jdt.core.compiler.problem.forbiddenReference=error
-org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
-org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=enabled
-org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
-org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning
-org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
-org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning
-org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
-org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore
-org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled
-org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=warning
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=error
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
-org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
-org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
-org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
-org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
-org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
-org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=warning
-org.eclipse.jdt.core.compiler.problem.nullReference=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecInsufficientInfo=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecViolation=warning
-org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=ignore
-org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
-org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
-org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullSpecViolation=error
-org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=warning
-org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=warning
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
-org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
-org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
-org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=enabled
-org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
-org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
-org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning
-org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=disabled
-org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
-org.eclipse.jdt.core.compiler.problem.unclosedCloseable=error
-org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
-org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
-org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning
-org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
-org.eclipse.jdt.core.compiler.problem.unusedImport=warning
-org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
-org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
-org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=warning
-org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
-org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
-org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
-org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
-org.eclipse.jdt.core.compiler.source=1.6
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/META-INF/MANIFEST.MF b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/META-INF/MANIFEST.MF
deleted file mode 100644
index b57d20ca4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,18 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: Hierarchy Viewer
-Bundle-SymbolicName: com.android.ide.eclipse.hierarchyviewer;singleton:=true
-Bundle-Version: 24.3.3.qualifier
-Bundle-Activator: com.android.ide.eclipse.hierarchyviewer.HierarchyViewerPlugin
-Bundle-Vendor: The Android Open Source Project
-Bundle-Localization: plugin
-Bundle-ActivationPolicy: lazy
-Require-Bundle: org.eclipse.ui,
- org.eclipse.core.runtime,
- org.eclipse.ui.console,
- com.android.ide.eclipse.ddms,
- com.android.ide.eclipse.base
-Bundle-ClassPath: .,
- libs/hierarchyviewer2lib.jar
-Export-Package: com.android.ide.eclipse.hierarchyviewer
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/MODULE_LICENSE_APACHE2 b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/MODULE_LICENSE_APACHE2
deleted file mode 100644
index e69de29bb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/MODULE_LICENSE_APACHE2
+++ /dev/null
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/about.html b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/about.html
deleted file mode 100644
index 380248c07..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/about.html
+++ /dev/null
@@ -1,218 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
-<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
-<title>About</title>
-</head>
-<body lang="EN-US">
-<h2>About This Content</h2>
-
-<p>September 19, 2010</p>
-<h3>License</h3>
-
-<pre>Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- &quot;License&quot; shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- &quot;Licensor&quot; shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- &quot;Legal Entity&quot; shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- &quot;control&quot; means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- &quot;You&quot; (or &quot;Your&quot;) shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- &quot;Source&quot; form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- &quot;Object&quot; form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- &quot;Work&quot; shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- &quot;Derivative Works&quot; shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- &quot;Contribution&quot; shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, &quot;submitted&quot;
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as &quot;Not a Contribution.&quot;
-
- &quot;Contributor&quot; shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a &quot;NOTICE&quot; text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an &quot;AS IS&quot; BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets &quot;[]&quot;
- replaced with your own identifying information. (Don&apos;t include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same &quot;printed page&quot; as the copyright notice for easier
- identification within third-party archives.
-
- Copyright [yyyy] [name of copyright owner]
-
- Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an &quot;AS IS&quot; BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- </pre>
-
-</body>
-</html> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/about.ini b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/about.ini
deleted file mode 100644
index 18f6ab010..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/about.ini
+++ /dev/null
@@ -1,2 +0,0 @@
-aboutText=%blurb
-featureImage=icons/hierarchyviewer-32.png \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/about.properties b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/about.properties
deleted file mode 100755
index 207cbbec1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/about.properties
+++ /dev/null
@@ -1,7 +0,0 @@
-blurb=Hierarchy Viewer\n\
-\n\
-Version\: {featureVersion}\n\
-\n\
-(c) Copyright 2010-2011 The Android Open Source Project. All rights reserved.\n\
-Visit http://developer.android.com/sdk/eclipse-adt.html
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/build.properties b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/build.properties
deleted file mode 100644
index f7e5d3fa9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/build.properties
+++ /dev/null
@@ -1,10 +0,0 @@
-source.. = src/
-output.. = bin/
-bin.includes = META-INF/,\
- icons/,\
- plugin.xml,\
- .,\
- libs/,\
- about.html,\
- about.ini,\
- about.properties
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/icons/device.png b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/icons/device.png
deleted file mode 100644
index 7dbbbb6a4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/icons/device.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/icons/hierarchyviewer-16.png b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/icons/hierarchyviewer-16.png
deleted file mode 100644
index 02073d421..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/icons/hierarchyviewer-16.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/icons/hierarchyviewer-32.png b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/icons/hierarchyviewer-32.png
deleted file mode 100644
index fa21c24dd..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/icons/hierarchyviewer-32.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/icons/pixel-perfect.png b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/icons/pixel-perfect.png
deleted file mode 100644
index 6e517012b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/icons/pixel-perfect.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/icons/tree-view.png b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/icons/tree-view.png
deleted file mode 100644
index 8f01dda41..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/icons/tree-view.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/plugin.xml b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/plugin.xml
deleted file mode 100644
index a4c299471..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/plugin.xml
+++ /dev/null
@@ -1,91 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<?eclipse version="3.4"?>
-<plugin>
- <extension
- point="org.eclipse.ui.views">
- <view
- allowMultiple="false"
- category="com.android.ide.eclipse.ddms.views.category"
- class="com.android.ide.eclipse.hierarchyviewer.views.DeviceSelectorView"
- icon="icons/device.png"
- id="com.android.ide.eclipse.hierarchyviewer.views.DeviceSelectorView"
- name="Windows">
- </view>
- <view
- allowMultiple="false"
- category="com.android.ide.eclipse.ddms.views.category"
- class="com.android.ide.eclipse.hierarchyviewer.views.PixelPerfectView"
- icon="icons/pixel-perfect.png"
- id="com.android.ide.eclipse.hierarchyviewer.views.PixelPerfectView"
- name="Pixel Perfect">
- </view>
- <view
- allowMultiple="false"
- category="com.android.ide.eclipse.ddms.views.category"
- class="com.android.ide.eclipse.hierarchyviewer.views.PixelPerfectLoupeView"
- icon="icons/pixel-perfect.png"
- id="com.android.ide.eclipse.hierarchyviewer.views.PixelPerfectLoupeView"
- name="Pixel Perfect Loupe">
- </view>
- <view
- allowMultiple="false"
- category="com.android.ide.eclipse.ddms.views.category"
- class="com.android.ide.eclipse.hierarchyviewer.views.PixelPerfectTreeView"
- icon="icons/pixel-perfect.png"
- id="com.android.ide.eclipse.hierarchyviewer.views.PixelPerfectTreeView"
- name="Pixel Perfect Tree">
- </view>
- <view
- allowMultiple="false"
- category="com.android.ide.eclipse.ddms.views.category"
- class="com.android.ide.eclipse.hierarchyviewer.views.TreeViewView"
- icon="icons/tree-view.png"
- id="com.android.ide.eclipse.hierarchyviewer.views.TreeViewView"
- name="Tree View">
- </view>
- <view
- allowMultiple="false"
- category="com.android.ide.eclipse.ddms.views.category"
- class="com.android.ide.eclipse.hierarchyviewer.views.PropertyView"
- icon="icons/tree-view.png"
- id="com.android.ide.eclipse.hierarchyviewer.views.PropertyView"
- name="View Properties">
- </view>
- <view
- allowMultiple="false"
- category="com.android.ide.eclipse.ddms.views.category"
- class="com.android.ide.eclipse.hierarchyviewer.views.TreeOverviewView"
- icon="icons/tree-view.png"
- id="com.android.ide.eclipse.hierarchyviewer.views.TreeOverviewView"
- name="Tree Overview">
- </view>
- <view
- allowMultiple="false"
- category="com.android.ide.eclipse.ddms.views.category"
- class="com.android.ide.eclipse.hierarchyviewer.views.LayoutView"
- icon="icons/tree-view.png"
- id="com.android.ide.eclipse.hierarchyviewer.views.LayoutView"
- name="Layout View">
- </view>
- </extension>
- <extension
- point="org.eclipse.ui.perspectives">
- <perspective
- class="com.android.ide.eclipse.hierarchyviewer.PixelPerfectPespective"
- icon="icons/pixel-perfect.png"
- id="com.android.ide.eclipse.hierarchyviewer.PixelPerfectPespective"
- name="Pixel Perfect"/>
- <perspective
- class="com.android.ide.eclipse.hierarchyviewer.TreeViewPerspective"
- icon="icons/hierarchyviewer-16.png"
- id="com.android.ide.eclipse.hierarchyviewer.TreeViewPerspective"
- name="Hierarchy View"/>
- </extension>
- <extension
- point="org.eclipse.ui.perspectiveExtensions">
- <perspectiveExtension targetID="org.eclipse.jdt.ui.JavaPerspective">
- <perspectiveShortcut id="com.android.ide.eclipse.hierarchyviewer.PixelPerfectPespective"/>
- <perspectiveShortcut id="com.android.ide.eclipse.hierarchyviewer.TreeViewPerspective"/>
- </perspectiveExtension>
- </extension>
-</plugin>
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/pom.xml b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/pom.xml
deleted file mode 100644
index 133fe09ae..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/pom.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <version>24.3.3-SNAPSHOT</version>
- <artifactId>com.android.ide.eclipse.hierarchyviewer</artifactId>
- <packaging>eclipse-plugin</packaging>
- <name>hierarchyviewer</name>
-
- <parent>
- <relativePath>../../pom.xml</relativePath>
- <groupId>adt.group</groupId>
- <artifactId>parent</artifactId>
- <version>1.0.0-SNAPSHOT</version>
- </parent>
-</project>
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/HierarchyViewerPlugin.java b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/HierarchyViewerPlugin.java
deleted file mode 100644
index d4a64d008..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/HierarchyViewerPlugin.java
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.hierarchyviewer;
-
-import com.android.ddmlib.AndroidDebugBridge;
-import com.android.ddmlib.AndroidDebugBridge.IDebugBridgeChangeListener;
-import com.android.ddmlib.Log;
-import com.android.ddmlib.Log.ILogOutput;
-import com.android.ddmlib.Log.LogLevel;
-import com.android.hierarchyviewerlib.HierarchyViewerDirector;
-
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.console.ConsolePlugin;
-import org.eclipse.ui.console.IConsole;
-import org.eclipse.ui.console.MessageConsole;
-import org.eclipse.ui.console.MessageConsoleStream;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.osgi.framework.BundleContext;
-
-import java.util.Calendar;
-
-/**
- * The activator class controls the plug-in life cycle
- */
-public class HierarchyViewerPlugin extends AbstractUIPlugin {
-
- public static final String PLUGIN_ID = "com.android.ide.eclipse.hierarchyviewer"; //$NON-NLS-1$
-
- public static final String ADB_LOCATION = PLUGIN_ID + ".adb"; //$NON-NLS-1$
-
- // The shared instance
- private static HierarchyViewerPlugin sPlugin;
-
- private Color mRedColor;
-
- /**
- * The constructor
- */
- public HierarchyViewerPlugin() {
- }
-
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
- sPlugin = this;
-
-
- // set the consoles.
- final MessageConsole messageConsole = new MessageConsole("Hierarchy Viewer", null); //$NON-NLS-1$
- ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[] {
- messageConsole
- });
-
- final MessageConsoleStream consoleStream = messageConsole.newMessageStream();
- final MessageConsoleStream errorConsoleStream = messageConsole.newMessageStream();
- mRedColor = new Color(Display.getDefault(), 0xFF, 0x00, 0x00);
-
- // because this can be run, in some cases, by a non UI thread, and
- // because
- // changing the console properties update the UI, we need to make this
- // change
- // in the UI thread.
- Display.getDefault().asyncExec(new Runnable() {
- @Override
- public void run() {
- errorConsoleStream.setColor(mRedColor);
- }
- });
-
- // set up the ddms log to use the ddms console.
- Log.setLogOutput(new ILogOutput() {
- @Override
- public void printLog(LogLevel logLevel, String tag, String message) {
- if (logLevel.getPriority() >= LogLevel.ERROR.getPriority()) {
- printToStream(errorConsoleStream, tag, message);
- ConsolePlugin.getDefault().getConsoleManager().showConsoleView(messageConsole);
- } else {
- printToStream(consoleStream, tag, message);
- }
- }
-
- @Override
- public void printAndPromptLog(final LogLevel logLevel, final String tag,
- final String message) {
- printLog(logLevel, tag, message);
- // dialog box only run in UI thread..
- Display.getDefault().asyncExec(new Runnable() {
- @Override
- public void run() {
- Shell shell = Display.getDefault().getActiveShell();
- if (logLevel == LogLevel.ERROR) {
- MessageDialog.openError(shell, tag, message);
- } else {
- MessageDialog.openWarning(shell, tag, message);
- }
- }
- });
- }
-
- });
-
- final HierarchyViewerDirector director = HierarchyViewerPluginDirector.createDirector();
- director.startListenForDevices();
-
- // make the director receive change in ADB.
- AndroidDebugBridge.addDebugBridgeChangeListener(new IDebugBridgeChangeListener() {
- @Override
- public void bridgeChanged(AndroidDebugBridge bridge) {
- director.acquireBridge(bridge);
- }
- });
-
- // get the current ADB if any
- director.acquireBridge(AndroidDebugBridge.getBridge());
-
- // populate the UI with current devices (if any) in a thread
- new Thread() {
- @Override
- public void run() {
- director.populateDeviceSelectionModel();
- }
- }.start();
- }
-
- /*
- * (non-Javadoc)
- * @see
- * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
- * )
- */
- @Override
- public void stop(BundleContext context) throws Exception {
- sPlugin = null;
- super.stop(context);
-
- mRedColor.dispose();
-
- HierarchyViewerDirector director = HierarchyViewerDirector.getDirector();
- director.stopListenForDevices();
- director.stopDebugBridge();
- director.terminate();
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static HierarchyViewerPlugin getPlugin() {
- return sPlugin;
- }
-
- /**
- * Prints a message, associated with a project to the specified stream
- *
- * @param stream The stream to write to
- * @param tag The tag associated to the message. Can be null
- * @param message The message to print.
- */
- private static synchronized void printToStream(MessageConsoleStream stream, String tag,
- String message) {
- String dateTag = getMessageTag(tag);
-
- stream.print(dateTag);
- stream.println(message);
- }
-
- /**
- * Creates a string containing the current date/time, and the tag
- *
- * @param tag The tag associated to the message. Can be null
- * @return The dateTag
- */
- private static String getMessageTag(String tag) {
- Calendar c = Calendar.getInstance();
-
- if (tag == null) {
- return String.format("[%1$tF %1$tT]", c); //$NON-NLS-1$
- }
-
- return String.format("[%1$tF %1$tT - %2$s]", c, tag); //$NON-NLS-1$
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/HierarchyViewerPluginDirector.java b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/HierarchyViewerPluginDirector.java
deleted file mode 100644
index 597f7a489..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/HierarchyViewerPluginDirector.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.hierarchyviewer;
-
-import com.android.hierarchyviewerlib.HierarchyViewerDirector;
-import com.android.hierarchyviewerlib.device.IHvDevice;
-import com.android.hierarchyviewerlib.models.Window;
-import com.android.ide.eclipse.hierarchyviewer.views.PixelPerfectTreeView;
-import com.android.ide.eclipse.hierarchyviewer.views.PropertyView;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.ISchedulingRule;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchPart;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-
-public class HierarchyViewerPluginDirector extends HierarchyViewerDirector {
-
- public static HierarchyViewerDirector createDirector() {
- return sDirector = new HierarchyViewerPluginDirector();
- }
-
- @Override
- public void executeInBackground(final String taskName, final Runnable task) {
- Job job = new Job(taskName) {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- task.run();
- return Status.OK_STATUS;
- }
- };
- job.setPriority(Job.SHORT);
- job.setRule(mSchedulingRule);
- job.schedule();
- }
-
- private ISchedulingRule mSchedulingRule = new ISchedulingRule() {
- @Override
- public boolean contains(ISchedulingRule rule) {
- return rule == this;
- }
-
- @Override
- public boolean isConflicting(ISchedulingRule rule) {
- return rule == this;
- }
-
- };
-
- @Override
- public String getAdbLocation() {
- return HierarchyViewerPlugin.getPlugin().getPreferenceStore().getString(
- HierarchyViewerPlugin.ADB_LOCATION);
- }
-
- @Override
- public void loadViewTreeData(Window window) {
- super.loadViewTreeData(window);
-
- // The windows tab hides the property tab, so let's bring the property
- // tab
- // forward.
-
- IWorkbenchWindow[] windows =
- HierarchyViewerPlugin.getPlugin().getWorkbench().getWorkbenchWindows();
- for (IWorkbenchWindow currentWindow : windows) {
- IWorkbenchPage page = currentWindow.getActivePage();
- if (page.getPerspective().getId().equals(TreeViewPerspective.ID)) {
- try {
- IWorkbenchPart part = page.findView(PropertyView.ID);
- if (part != null) {
- page.showView(PropertyView.ID);
- }
- } catch (PartInitException e) {
-
- }
- }
- }
- }
-
- @Override
- public void loadPixelPerfectData(IHvDevice device) {
- super.loadPixelPerfectData(device);
-
- // The windows tab hides the tree tab, so let's bring the tree tab
- // forward.
-
- IWorkbenchWindow[] windows =
- HierarchyViewerPlugin.getPlugin().getWorkbench().getWorkbenchWindows();
- for (IWorkbenchWindow window : windows) {
- IWorkbenchPage page = window.getActivePage();
- if (page.getPerspective().getId().equals(PixelPerfectPespective.ID)) {
- try {
- IWorkbenchPart part = page.findView(PixelPerfectTreeView.ID);
- if (part != null) {
- page.showView(PixelPerfectTreeView.ID);
- }
- } catch (PartInitException e) {
-
- }
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/PixelPerfectPespective.java b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/PixelPerfectPespective.java
deleted file mode 100644
index 973b30e8e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/PixelPerfectPespective.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.hierarchyviewer;
-
-import com.android.ide.eclipse.ddms.Perspective;
-import com.android.ide.eclipse.hierarchyviewer.views.DeviceSelectorView;
-import com.android.ide.eclipse.hierarchyviewer.views.PixelPerfectLoupeView;
-import com.android.ide.eclipse.hierarchyviewer.views.PixelPerfectTreeView;
-import com.android.ide.eclipse.hierarchyviewer.views.PixelPerfectView;
-
-import org.eclipse.ui.IFolderLayout;
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IPerspectiveFactory;
-
-public class PixelPerfectPespective implements IPerspectiveFactory {
-
- public static final String ID =
- "com.android.ide.eclipse.hierarchyviewer.PixelPerfectPespective"; //$NON-NLS-1$
-
- @Override
- public void createInitialLayout(IPageLayout layout) {
- layout.setEditorAreaVisible(false);
-
- String editorArea = layout.getEditorArea();
- IFolderLayout folder;
-
- folder = layout.createFolder("tree", IPageLayout.LEFT, 0.25f, editorArea); //$NON-NLS-1$
- folder.addView(DeviceSelectorView.ID);
- folder.addView(PixelPerfectTreeView.ID);
-
- folder = layout.createFolder("overview", IPageLayout.RIGHT, 0.4f, editorArea); //$NON-NLS-1$
- folder.addView(PixelPerfectView.ID);
-
- folder = layout.createFolder("main", IPageLayout.RIGHT, 0.35f, editorArea); //$NON-NLS-1$
- folder.addView(PixelPerfectLoupeView.ID);
-
-
- layout.addShowViewShortcut(DeviceSelectorView.ID);
- layout.addShowViewShortcut(PixelPerfectTreeView.ID);
- layout.addShowViewShortcut(PixelPerfectLoupeView.ID);
- layout.addShowViewShortcut(PixelPerfectView.ID);
-
- layout.addPerspectiveShortcut("org.eclipse.jdt.ui.JavaPerspective"); //$NON-NLS-1$
- layout.addPerspectiveShortcut(TreeViewPerspective.ID);
- layout.addPerspectiveShortcut(Perspective.ID);
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/TreeViewPerspective.java b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/TreeViewPerspective.java
deleted file mode 100644
index b6198d8f8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/TreeViewPerspective.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.hierarchyviewer;
-
-import com.android.ide.eclipse.ddms.Perspective;
-import com.android.ide.eclipse.hierarchyviewer.views.DeviceSelectorView;
-import com.android.ide.eclipse.hierarchyviewer.views.LayoutView;
-import com.android.ide.eclipse.hierarchyviewer.views.PropertyView;
-import com.android.ide.eclipse.hierarchyviewer.views.TreeOverviewView;
-import com.android.ide.eclipse.hierarchyviewer.views.TreeViewView;
-
-import org.eclipse.ui.IFolderLayout;
-import org.eclipse.ui.IPageLayout;
-import org.eclipse.ui.IPerspectiveFactory;
-
-public class TreeViewPerspective implements IPerspectiveFactory {
-
- public static final String ID = "com.android.ide.eclipse.hierarchyviewer.TreeViewPerspective"; //$NON-NLS-1$
-
- @Override
- public void createInitialLayout(IPageLayout layout) {
- layout.setEditorAreaVisible(false);
-
- String editorArea = layout.getEditorArea();
- IFolderLayout folder;
-
- folder = layout.createFolder("properties", IPageLayout.LEFT, 0.10f, editorArea); //$NON-NLS-1$
- folder.addView(DeviceSelectorView.ID);
- folder.addView(PropertyView.ID);
-
- folder = layout.createFolder("main", IPageLayout.RIGHT, 0.24f, "properties"); //$NON-NLS-1$ //$NON-NLS-2$
- folder.addView(TreeViewView.ID);
-
- folder = layout.createFolder("panel-top", IPageLayout.RIGHT, 0.7f, "main"); //$NON-NLS-1$ //$NON-NLS-2$
- folder.addView(TreeOverviewView.ID);
-
-
- folder = layout.createFolder("panel-bottom", IPageLayout.BOTTOM, 0.5f, "panel-top"); //$NON-NLS-1$ //$NON-NLS-2$
- folder.addView(LayoutView.ID);
-
- layout.addShowViewShortcut(DeviceSelectorView.ID);
- layout.addShowViewShortcut(PropertyView.ID);
- layout.addShowViewShortcut(TreeOverviewView.ID);
- layout.addShowViewShortcut(LayoutView.ID);
- layout.addShowViewShortcut(TreeViewView.ID);
-
- layout.addPerspectiveShortcut("org.eclipse.jdt.ui.JavaPerspective"); //$NON-NLS-1$
- layout.addPerspectiveShortcut(PixelPerfectPespective.ID);
- layout.addPerspectiveShortcut(Perspective.ID);
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/DeviceSelectorView.java b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/DeviceSelectorView.java
deleted file mode 100644
index 1905cde1a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/DeviceSelectorView.java
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.hierarchyviewer.views;
-
-import com.android.hierarchyviewerlib.actions.InspectScreenshotAction;
-import com.android.hierarchyviewerlib.actions.LoadViewHierarchyAction;
-import com.android.hierarchyviewerlib.actions.RefreshWindowsAction;
-import com.android.hierarchyviewerlib.ui.DeviceSelector;
-import com.android.ide.eclipse.hierarchyviewer.PixelPerfectPespective;
-import com.android.ide.eclipse.hierarchyviewer.TreeViewPerspective;
-
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.IPerspectiveDescriptor;
-import org.eclipse.ui.IPerspectiveListener;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.part.ViewPart;
-
-public class DeviceSelectorView extends ViewPart implements IPerspectiveListener {
-
- public static final String ID =
- "com.android.ide.eclipse.hierarchyviewer.views.DeviceSelectorView"; //$NON-NLS-1$
-
- private DeviceSelector mDeviceSelector;
-
- @Override
- public void createPartControl(Composite parent) {
- parent.setLayout(new FillLayout());
-
-
- IPerspectiveDescriptor perspective = getViewSite().getPage().getPerspective();
- boolean doTreeViewStuff = true;
- boolean doPixelPerfectStuff = true;
- if (perspective.getId().equals(PixelPerfectPespective.ID)) {
- doTreeViewStuff = false;
- } else if (perspective.getId().equals(TreeViewPerspective.ID)) {
- doPixelPerfectStuff = false;
- }
- mDeviceSelector = new DeviceSelector(parent, doTreeViewStuff, doPixelPerfectStuff);
-
- placeActions(doTreeViewStuff, doPixelPerfectStuff);
-
- getViewSite().getWorkbenchWindow().addPerspectiveListener(this);
- }
-
- @Override
- public void dispose() {
- super.dispose();
- getViewSite().getWorkbenchWindow().removePerspectiveListener(this);
- }
-
- private void placeActions(boolean doTreeViewStuff, boolean doPixelPerfectStuff) {
- IActionBars actionBars = getViewSite().getActionBars();
-
- IMenuManager mm = actionBars.getMenuManager();
- mm.removeAll();
- mm.add(RefreshWindowsAction.getAction());
-
- IToolBarManager tm = actionBars.getToolBarManager();
- tm.removeAll();
- tm.add(RefreshWindowsAction.getAction());
-
- if (doTreeViewStuff) {
- mm.add(LoadViewHierarchyAction.getAction());
- tm.add(LoadViewHierarchyAction.getAction());
- }
- if (doPixelPerfectStuff) {
- mm.add(InspectScreenshotAction.getAction());
- tm.add(InspectScreenshotAction.getAction());
- }
-
- mm.updateAll(true);
- tm.update(true);
- actionBars.updateActionBars();
- }
-
- @Override
- public void setFocus() {
- mDeviceSelector.setFocus();
- }
-
- @Override
- public void perspectiveActivated(IWorkbenchPage page, IPerspectiveDescriptor perspective) {
- if (perspective.getId().equals(PixelPerfectPespective.ID)) {
- mDeviceSelector.setMode(false, true);
- placeActions(false, true);
- } else if (perspective.getId().equals(TreeViewPerspective.ID)) {
- mDeviceSelector.setMode(true, false);
- placeActions(true, false);
- } else {
- mDeviceSelector.setMode(true, true);
- placeActions(true, true);
- }
- }
-
- @Override
- public void perspectiveChanged(IWorkbenchPage page, IPerspectiveDescriptor perspective,
- String changeId) {
- // pass
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/LayoutView.java b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/LayoutView.java
deleted file mode 100644
index 83cf38b57..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/LayoutView.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.hierarchyviewer.views;
-
-import com.android.ddmuilib.ImageLoader;
-import com.android.hierarchyviewerlib.HierarchyViewerDirector;
-import com.android.hierarchyviewerlib.models.TreeViewModel;
-import com.android.hierarchyviewerlib.models.TreeViewModel.ITreeChangeListener;
-import com.android.hierarchyviewerlib.ui.LayoutViewer;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.part.ViewPart;
-
-public class LayoutView extends ViewPart implements ITreeChangeListener {
-
- public static final String ID = "com.android.ide.eclipse.hierarchyviewer.views.LayoutView"; //$NON-NLS-1$
-
- private LayoutViewer mLayoutViewer;
-
- private Image mOnBlack;
-
- private Image mOnWhite;
-
- private Action mShowExtrasAction = new Action("Show &Extras", Action.AS_CHECK_BOX) {
- @Override
- public void run() {
- mLayoutViewer.setShowExtras(isChecked());
- }
- };
-
- private Action mLoadAllViewsAction = new Action("Load All &Views") {
- @Override
- public void run() {
- HierarchyViewerDirector.getDirector().loadAllViews();
- mShowExtrasAction.setChecked(true);
- mLayoutViewer.setShowExtras(true);
- }
- };
-
- private Action mOnBlackWhiteAction = new Action("Change Background &Color") {
- @Override
- public void run() {
- boolean newValue = !mLayoutViewer.getOnBlack();
- mLayoutViewer.setOnBlack(newValue);
- if (newValue) {
- setImageDescriptor(ImageDescriptor.createFromImage(mOnWhite));
- } else {
- setImageDescriptor(ImageDescriptor.createFromImage(mOnBlack));
- }
- }
- };
-
- @Override
- public void createPartControl(Composite parent) {
- mShowExtrasAction.setAccelerator(SWT.MOD1 + 'E');
- ImageLoader imageLoader = ImageLoader.getLoader(HierarchyViewerDirector.class);
- Image image = imageLoader.loadImage("show-extras.png", Display.getDefault()); //$NON-NLS-1$
- mShowExtrasAction.setImageDescriptor(ImageDescriptor.createFromImage(image));
- mShowExtrasAction.setToolTipText("Show images");
- mShowExtrasAction.setEnabled(TreeViewModel.getModel().getTree() != null);
-
- mOnWhite = imageLoader.loadImage("on-white.png", Display.getDefault()); //$NON-NLS-1$
- mOnBlack = imageLoader.loadImage("on-black.png", Display.getDefault()); //$NON-NLS-1$
-
- mOnBlackWhiteAction.setAccelerator(SWT.MOD1 + 'C');
- mOnBlackWhiteAction.setImageDescriptor(ImageDescriptor.createFromImage(mOnWhite));
- mOnBlackWhiteAction.setToolTipText("Change layout viewer background color");
-
- mLoadAllViewsAction.setAccelerator(SWT.MOD1 + 'V');
- image = imageLoader.loadImage("load-all-views.png", Display.getDefault()); //$NON-NLS-1$
- mLoadAllViewsAction.setImageDescriptor(ImageDescriptor.createFromImage(image));
- mLoadAllViewsAction.setToolTipText("Load all view images");
- mLoadAllViewsAction.setEnabled(TreeViewModel.getModel().getTree() != null);
-
- parent.setLayout(new FillLayout());
-
- mLayoutViewer = new LayoutViewer(parent);
-
- placeActions();
-
- TreeViewModel.getModel().addTreeChangeListener(this);
- }
-
- public void placeActions() {
- IActionBars actionBars = getViewSite().getActionBars();
-
- IMenuManager mm = actionBars.getMenuManager();
- mm.removeAll();
- mm.add(mOnBlackWhiteAction);
- mm.add(mShowExtrasAction);
- mm.add(mLoadAllViewsAction);
-
- IToolBarManager tm = actionBars.getToolBarManager();
- tm.removeAll();
- tm.add(mOnBlackWhiteAction);
- tm.add(mShowExtrasAction);
- tm.add(mLoadAllViewsAction);
- }
-
- @Override
- public void dispose() {
- super.dispose();
- TreeViewModel.getModel().removeTreeChangeListener(this);
- }
-
- @Override
- public void setFocus() {
- mLayoutViewer.setFocus();
- }
-
- @Override
- public void selectionChanged() {
- // pass
- }
-
- @Override
- public void treeChanged() {
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- mLoadAllViewsAction.setEnabled(TreeViewModel.getModel().getTree() != null);
- mShowExtrasAction.setEnabled(TreeViewModel.getModel().getTree() != null);
- }
- });
- }
-
- @Override
- public void viewportChanged() {
- // pass
- }
-
- @Override
- public void zoomChanged() {
- // pass
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/PixelPerfectLoupeView.java b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/PixelPerfectLoupeView.java
deleted file mode 100644
index 93ad5986a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/PixelPerfectLoupeView.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.hierarchyviewer.views;
-
-import com.android.ddmuilib.ImageLoader;
-import com.android.hierarchyviewerlib.HierarchyViewerDirector;
-import com.android.hierarchyviewerlib.actions.PixelPerfectAutoRefreshAction;
-import com.android.hierarchyviewerlib.models.PixelPerfectModel;
-import com.android.hierarchyviewerlib.models.PixelPerfectModel.IImageChangeListener;
-import com.android.hierarchyviewerlib.ui.PixelPerfectControls;
-import com.android.hierarchyviewerlib.ui.PixelPerfectLoupe;
-import com.android.hierarchyviewerlib.ui.PixelPerfectPixelPanel;
-
-import org.eclipse.jface.action.Action;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.part.ViewPart;
-
-public class PixelPerfectLoupeView extends ViewPart implements IImageChangeListener {
-
- public static final String ID =
- "com.android.ide.eclipse.hierarchyviewer.views.PixelPerfectLoupeView"; //$NON-NLS-1$
-
- private PixelPerfectLoupe mPixelPerfectLoupe;
-
- private Action mShowInLoupeAction = new Action("&Show Overlay", Action.AS_CHECK_BOX) {
- @Override
- public void run() {
- mPixelPerfectLoupe.setShowOverlay(isChecked());
- }
- };
- @Override
- public void createPartControl(Composite parent) {
- mShowInLoupeAction.setAccelerator(SWT.MOD1 + 'S');
- ImageLoader imageLoader = ImageLoader.getLoader(HierarchyViewerDirector.class);
- Image image = imageLoader.loadImage("show-overlay.png", Display.getDefault()); //$NON-NLS-1$
- mShowInLoupeAction.setImageDescriptor(ImageDescriptor.createFromImage(image));
- mShowInLoupeAction.setToolTipText("Show the overlay in the loupe view");
- mShowInLoupeAction.setEnabled(PixelPerfectModel.getModel().getOverlayImage() != null);
- PixelPerfectModel.getModel().addImageChangeListener(this);
-
- GridLayout loupeLayout = new GridLayout();
- loupeLayout.marginWidth = loupeLayout.marginHeight = 0;
- loupeLayout.horizontalSpacing = loupeLayout.verticalSpacing = 0;
- parent.setLayout(loupeLayout);
-
- Composite pixelPerfectLoupeBorder = new Composite(parent, SWT.BORDER);
- pixelPerfectLoupeBorder.setLayoutData(new GridData(GridData.FILL_BOTH));
- GridLayout pixelPerfectLoupeBorderGridLayout = new GridLayout();
- pixelPerfectLoupeBorderGridLayout.marginWidth =
- pixelPerfectLoupeBorderGridLayout.marginHeight = 0;
- pixelPerfectLoupeBorderGridLayout.horizontalSpacing =
- pixelPerfectLoupeBorderGridLayout.verticalSpacing = 0;
- pixelPerfectLoupeBorder.setLayout(pixelPerfectLoupeBorderGridLayout);
-
- mPixelPerfectLoupe = new PixelPerfectLoupe(pixelPerfectLoupeBorder);
- mPixelPerfectLoupe.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- PixelPerfectPixelPanel pixelPerfectPixelPanel =
- new PixelPerfectPixelPanel(pixelPerfectLoupeBorder);
- pixelPerfectPixelPanel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- // https://code.google.com/p/android/issues/detail?id=69199
- // Disabled until accessibility issues are fixed
- // PixelPerfectControls pixelPerfectControls =
- // new PixelPerfectControls(parent);
- // pixelPerfectControls.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- placeActions();
- }
-
- private void placeActions() {
- IActionBars actionBars = getViewSite().getActionBars();
-
- IMenuManager mm = actionBars.getMenuManager();
- mm.removeAll();
- mm.add(PixelPerfectAutoRefreshAction.getAction());
- mm.add(mShowInLoupeAction);
-
- IToolBarManager tm = actionBars.getToolBarManager();
- tm.removeAll();
- tm.add(PixelPerfectAutoRefreshAction.getAction());
- tm.add(mShowInLoupeAction);
- }
-
- @Override
- public void dispose() {
- super.dispose();
- PixelPerfectModel.getModel().removeImageChangeListener(this);
- }
-
- @Override
- public void setFocus() {
- mPixelPerfectLoupe.setFocus();
- }
-
- @Override
- public void crosshairMoved() {
- // pass
- }
-
- @Override
- public void treeChanged() {
- // pass
- }
-
- @Override
- public void imageChanged() {
- // pass
- }
-
- @Override
- public void imageLoaded() {
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- Image overlayImage = PixelPerfectModel.getModel().getOverlayImage();
- mShowInLoupeAction.setEnabled(overlayImage != null);
- }
- });
- }
-
- @Override
- public void overlayChanged() {
- Display.getDefault().syncExec(new Runnable() {
- @Override
- public void run() {
- mShowInLoupeAction
- .setEnabled(PixelPerfectModel.getModel().getOverlayImage() != null);
- }
- });
- }
-
- @Override
- public void overlayTransparencyChanged() {
- // pass
- }
-
- @Override
- public void selectionChanged() {
- // pass
- }
-
- @Override
- public void zoomChanged() {
- // pass
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/PixelPerfectTreeView.java b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/PixelPerfectTreeView.java
deleted file mode 100644
index f3591f7d4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/PixelPerfectTreeView.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.hierarchyviewer.views;
-
-import com.android.hierarchyviewerlib.actions.RefreshPixelPerfectTreeAction;
-import com.android.hierarchyviewerlib.ui.PixelPerfectTree;
-
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.part.ViewPart;
-
-public class PixelPerfectTreeView extends ViewPart {
-
- public static final String ID =
- "com.android.ide.eclipse.hierarchyviewer.views.PixelPerfectTreeView"; //$NON-NLS-1$
-
- private PixelPerfectTree mPixelPerfectTree;
-
- @Override
- public void createPartControl(Composite parent) {
- parent.setLayout(new FillLayout());
- mPixelPerfectTree = new PixelPerfectTree(parent);
-
- placeActions();
- }
-
- private void placeActions() {
- IActionBars actionBars = getViewSite().getActionBars();
-
- IMenuManager mm = actionBars.getMenuManager();
- mm.removeAll();
- mm.add(RefreshPixelPerfectTreeAction.getAction());
-
- IToolBarManager tm = actionBars.getToolBarManager();
- tm.removeAll();
- tm.add(RefreshPixelPerfectTreeAction.getAction());
- }
-
- @Override
- public void setFocus() {
- mPixelPerfectTree.setFocus();
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/PixelPerfectView.java b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/PixelPerfectView.java
deleted file mode 100644
index 943a6c8af..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/PixelPerfectView.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.hierarchyviewer.views;
-
-import com.android.hierarchyviewerlib.actions.LoadOverlayAction;
-import com.android.hierarchyviewerlib.actions.RefreshPixelPerfectAction;
-import com.android.hierarchyviewerlib.actions.SavePixelPerfectAction;
-import com.android.hierarchyviewerlib.ui.PixelPerfect;
-
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.part.ViewPart;
-
-public class PixelPerfectView extends ViewPart {
-
- public static final String ID =
- "com.android.ide.eclipse.hierarchyviewer.views.PixelPerfectView"; //$NON-NLS-1$
-
- private PixelPerfect mPixelPerfect;
-
- @Override
- public void createPartControl(Composite parent) {
- parent.setLayout(new FillLayout());
- mPixelPerfect = new PixelPerfect(parent);
-
- placeActions();
- }
-
- private void placeActions() {
- IActionBars actionBars = getViewSite().getActionBars();
-
- IMenuManager mm = actionBars.getMenuManager();
- mm.removeAll();
- mm.add(SavePixelPerfectAction.getAction(getSite().getShell()));
- mm.add(RefreshPixelPerfectAction.getAction());
- mm.add(LoadOverlayAction.getAction(getSite().getShell()));
-
- IToolBarManager tm = actionBars.getToolBarManager();
- tm.removeAll();
- tm.add(SavePixelPerfectAction.getAction(getSite().getShell()));
- tm.add(RefreshPixelPerfectAction.getAction());
- tm.add(LoadOverlayAction.getAction(getSite().getShell()));
- }
-
- @Override
- public void setFocus() {
- mPixelPerfect.setFocus();
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/PropertyView.java b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/PropertyView.java
deleted file mode 100644
index 74f50fdb2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/PropertyView.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.hierarchyviewer.views;
-
-import com.android.hierarchyviewerlib.ui.PropertyViewer;
-
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.part.ViewPart;
-
-public class PropertyView extends ViewPart {
-
- public static final String ID = "com.android.ide.eclipse.hierarchyviewer.views.PropertyView"; //$NON-NLS-1$
-
- private PropertyViewer mPropertyViewer;
-
- @Override
- public void createPartControl(Composite parent) {
- parent.setLayout(new FillLayout());
-
- mPropertyViewer = new PropertyViewer(parent);
- }
-
- @Override
- public void setFocus() {
- mPropertyViewer.setFocus();
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/TreeOverviewView.java b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/TreeOverviewView.java
deleted file mode 100644
index e18771b79..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/TreeOverviewView.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.hierarchyviewer.views;
-
-import com.android.hierarchyviewerlib.ui.TreeViewOverview;
-
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.part.ViewPart;
-
-public class TreeOverviewView extends ViewPart {
-
- public static final String ID =
- "com.android.ide.eclipse.hierarchyviewer.views.TreeOverviewView"; //$NON-NLS-1$
-
- private TreeViewOverview mTreeViewOverview;
- @Override
- public void createPartControl(Composite parent) {
- parent.setLayout(new FillLayout());
-
- mTreeViewOverview = new TreeViewOverview(parent);
- }
-
- @Override
- public void setFocus() {
- mTreeViewOverview.setFocus();
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/TreeViewView.java b/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/TreeViewView.java
deleted file mode 100644
index 98bd909d7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.hierarchyviewer/src/com/android/ide/eclipse/hierarchyviewer/views/TreeViewView.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.hierarchyviewer.views;
-
-import com.android.hierarchyviewerlib.actions.CapturePSDAction;
-import com.android.hierarchyviewerlib.actions.DisplayViewAction;
-import com.android.hierarchyviewerlib.actions.DumpDisplayListAction;
-import com.android.hierarchyviewerlib.actions.InvalidateAction;
-import com.android.hierarchyviewerlib.actions.ProfileNodesAction;
-import com.android.hierarchyviewerlib.actions.RefreshViewAction;
-import com.android.hierarchyviewerlib.actions.RequestLayoutAction;
-import com.android.hierarchyviewerlib.actions.SaveTreeViewAction;
-import com.android.hierarchyviewerlib.ui.TreeView;
-import com.android.hierarchyviewerlib.ui.TreeViewControls;
-
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.IToolBarManager;
-import org.eclipse.jface.action.Separator;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.FillLayout;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.ui.IActionBars;
-import org.eclipse.ui.part.ViewPart;
-
-// Awesome name.
-public class TreeViewView extends ViewPart {
-
- public static final String ID = "com.android.ide.eclipse.hierarchyviewer.views.TreeViewView"; //$NON-NLS-1$
-
- private TreeView mTreeView;
-
- @Override
- public void createPartControl(Composite parent) {
- GridLayout layout = new GridLayout();
- layout.marginWidth = layout.marginHeight = 0;
- layout.horizontalSpacing = layout.verticalSpacing = 0;
- parent.setLayout(layout);
-
- Composite treeViewContainer = new Composite(parent, SWT.BORDER);
- treeViewContainer.setLayoutData(new GridData(GridData.FILL_BOTH));
- treeViewContainer.setLayout(new FillLayout());
-
- mTreeView = new TreeView(treeViewContainer);
-
- TreeViewControls treeViewControls = new TreeViewControls(parent);
- treeViewControls.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- placeActions();
- }
-
- public void placeActions() {
- IActionBars actionBars = getViewSite().getActionBars();
-
- IMenuManager mm = actionBars.getMenuManager();
- mm.removeAll();
- mm.add(SaveTreeViewAction.getAction(getSite().getShell()));
- mm.add(CapturePSDAction.getAction(getSite().getShell()));
- mm.add(new Separator());
- mm.add(RefreshViewAction.getAction());
- mm.add(DisplayViewAction.getAction(getSite().getShell()));
- mm.add(new Separator());
- mm.add(InvalidateAction.getAction());
- mm.add(RequestLayoutAction.getAction());
- mm.add(DumpDisplayListAction.getAction());
- mm.add(ProfileNodesAction.getAction());
-
- IToolBarManager tm = actionBars.getToolBarManager();
- tm.removeAll();
- tm.add(SaveTreeViewAction.getAction(getSite().getShell()));
- tm.add(CapturePSDAction.getAction(getSite().getShell()));
- tm.add(new Separator());
- tm.add(RefreshViewAction.getAction());
- tm.add(DisplayViewAction.getAction(getSite().getShell()));
- tm.add(new Separator());
- tm.add(InvalidateAction.getAction());
- tm.add(RequestLayoutAction.getAction());
- tm.add(DumpDisplayListAction.getAction());
- tm.add(ProfileNodesAction.getAction());
- }
-
-
- @Override
- public void setFocus() {
- mTreeView.setFocus();
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/.classpath b/eclipse/plugins/com.android.ide.eclipse.monitor/.classpath
deleted file mode 100644
index fa341c0e1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/.classpath
+++ /dev/null
@@ -1,10 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry kind="src" path="src"/>
- <classpathentry exported="true" kind="lib" path="libs/sdkuilib.jar"/>
- <classpathentry combineaccessrules="false" kind="src" path="/ddmlib"/>
- <classpathentry combineaccessrules="false" kind="src" path="/ddmuilib"/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/.project b/eclipse/plugins/com.android.ide.eclipse.monitor/.project
deleted file mode 100644
index e7ca0c942..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/.project
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>plugin-monitor</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/.settings/org.eclipse.jdt.core.prefs b/eclipse/plugins/com.android.ide.eclipse.monitor/.settings/org.eclipse.jdt.core.prefs
deleted file mode 100644
index ea661960a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/.settings/org.eclipse.jdt.core.prefs
+++ /dev/null
@@ -1,98 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore
-org.eclipse.jdt.core.compiler.annotation.nonnull=com.android.annotations.NonNull
-org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=com.android.annotations.NonNullByDefault
-org.eclipse.jdt.core.compiler.annotation.nonnullisdefault=disabled
-org.eclipse.jdt.core.compiler.annotation.nullable=com.android.annotations.Nullable
-org.eclipse.jdt.core.compiler.annotation.nullanalysis=enabled
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
-org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
-org.eclipse.jdt.core.compiler.compliance=1.6
-org.eclipse.jdt.core.compiler.debug.lineNumber=generate
-org.eclipse.jdt.core.compiler.debug.localVariable=generate
-org.eclipse.jdt.core.compiler.debug.sourceFile=generate
-org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
-org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
-org.eclipse.jdt.core.compiler.problem.deadCode=warning
-org.eclipse.jdt.core.compiler.problem.deprecation=warning
-org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
-org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
-org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
-org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore
-org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning
-org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled
-org.eclipse.jdt.core.compiler.problem.fieldHiding=warning
-org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
-org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
-org.eclipse.jdt.core.compiler.problem.forbiddenReference=error
-org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
-org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=enabled
-org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
-org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning
-org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
-org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning
-org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
-org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore
-org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled
-org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=warning
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=error
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
-org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
-org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
-org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
-org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
-org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
-org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=warning
-org.eclipse.jdt.core.compiler.problem.nullReference=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecInsufficientInfo=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecViolation=warning
-org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=ignore
-org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
-org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
-org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullSpecViolation=error
-org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=warning
-org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=warning
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
-org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
-org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
-org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=enabled
-org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
-org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
-org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning
-org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=disabled
-org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
-org.eclipse.jdt.core.compiler.problem.unclosedCloseable=error
-org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
-org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
-org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning
-org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
-org.eclipse.jdt.core.compiler.problem.unusedImport=warning
-org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
-org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
-org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=warning
-org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
-org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
-org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
-org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
-org.eclipse.jdt.core.compiler.source=1.6
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/META-INF/MANIFEST.MF b/eclipse/plugins/com.android.ide.eclipse.monitor/META-INF/MANIFEST.MF
deleted file mode 100644
index 48a3aa366..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,17 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: %Bundle-Name
-Bundle-SymbolicName: com.android.ide.eclipse.monitor;singleton:=true
-Bundle-Version: 24.3.3.qualifier
-Bundle-Activator: com.android.ide.eclipse.monitor.MonitorPlugin
-Require-Bundle: org.eclipse.ui,
- org.eclipse.core.runtime,
- com.android.ide.eclipse.ddms,
- com.android.ide.eclipse.traceview,
- com.android.ide.eclipse.base
-Bundle-ActivationPolicy: lazy
-Bundle-Vendor: %Bundle-Vendor
-Bundle-ClassPath: .,
- libs/sdkuilib.jar
-Bundle-Localization: plugin
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/build.properties b/eclipse/plugins/com.android.ide.eclipse.monitor/build.properties
deleted file mode 100644
index 643fe5ef0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/build.properties
+++ /dev/null
@@ -1,10 +0,0 @@
-source.. = src/
-output.. = bin/
-bin.includes = META-INF/,\
- .,\
- plugin.xml,\
- plugin_customization.ini,\
- plugin.properties,\
- images/,\
- libs/,\
- splash.bmp
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/images/avd_manager.png b/eclipse/plugins/com.android.ide.eclipse.monitor/images/avd_manager.png
deleted file mode 100644
index f8a173ca3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/images/avd_manager.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/images/ddms-128.png b/eclipse/plugins/com.android.ide.eclipse.monitor/images/ddms-128.png
deleted file mode 100644
index 392a8f3ab..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/images/ddms-128.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/images/ddms-16.png b/eclipse/plugins/com.android.ide.eclipse.monitor/images/ddms-16.png
deleted file mode 100644
index f77bee200..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/images/ddms-16.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/images/ddms-32.png b/eclipse/plugins/com.android.ide.eclipse.monitor/images/ddms-32.png
deleted file mode 100644
index 4fe68167d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/images/ddms-32.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/images/ddms.icns b/eclipse/plugins/com.android.ide.eclipse.monitor/images/ddms.icns
deleted file mode 100644
index eeacbde8d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/images/ddms.icns
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/images/sdk_manager.png b/eclipse/plugins/com.android.ide.eclipse.monitor/images/sdk_manager.png
deleted file mode 100644
index 08ffda85b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/images/sdk_manager.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/monitor.launch b/eclipse/plugins/com.android.ide.eclipse.monitor/monitor.launch
deleted file mode 100644
index f56a37de1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/monitor.launch
+++ /dev/null
@@ -1,32 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<launchConfiguration type="org.eclipse.pde.ui.RuntimeWorkbench">
-<booleanAttribute key="append.args" value="true"/>
-<booleanAttribute key="askclear" value="true"/>
-<booleanAttribute key="automaticAdd" value="true"/>
-<booleanAttribute key="automaticValidate" value="false"/>
-<stringAttribute key="bootstrap" value=""/>
-<stringAttribute key="checked" value="[NONE]"/>
-<booleanAttribute key="clearConfig" value="false"/>
-<booleanAttribute key="clearws" value="false"/>
-<booleanAttribute key="clearwslog" value="false"/>
-<stringAttribute key="configLocation" value="${workspace_loc}/.metadata/.plugins/org.eclipse.pde.core/monitor"/>
-<booleanAttribute key="default" value="false"/>
-<stringAttribute key="deselected_workspace_plugins" value="com.android.ide.eclipse.adt,com.android.ide.eclipse.adt.package,com.android.ide.eclipse.gldebugger.tests,overlay.com.android.ide.eclipse.adt.overlay"/>
-<booleanAttribute key="includeOptional" value="true"/>
-<stringAttribute key="location" value="${workspace_loc}/../runtime-monitor-idea133-ksr2"/>
-<booleanAttribute key="org.eclipse.jdt.launching.ATTR_USE_START_ON_FIRST_THREAD" value="true"/>
-<stringAttribute key="org.eclipse.jdt.launching.JRE_CONTAINER" value="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
-<stringAttribute key="org.eclipse.jdt.launching.PROGRAM_ARGUMENTS" value="-os ${target.os} -ws ${target.ws} -arch ${target.arch} -nl ${target.nl} -consoleLog -data @noDefault"/>
-<stringAttribute key="org.eclipse.jdt.launching.SOURCE_PATH_PROVIDER" value="org.eclipse.pde.ui.workbenchClasspathProvider"/>
-<stringAttribute key="pde.version" value="3.3"/>
-<stringAttribute key="product" value="com.android.ide.eclipse.monitor.product"/>
-<stringAttribute key="selected_target_plugins" value="com.android.tools.common@default:default,com.android.tools.ddms.ddmlib@default:default,com.android.tools.ddms.ddmuilib@default:default,com.android.tools.dvlib@default:default,com.android.tools.external.liblzf@default:default,com.android.tools.external.libprotobuf-java-lite@default:default,com.android.tools.hierarchyviewer2lib@default:default,com.android.tools.layoutlib.api@default:default,com.android.tools.sdklib@default:default,com.android.tools.sdkstats@default:default,com.android.tools.sdkuilib@default:default,com.android.tools.swtmenubar@default:default,com.android.tools.traceview@default:default,com.android.tools.uiautomatorviewer@default:default,com.google.guava@default:default,com.ibm.icu@default:default,javax.annotation@default:default,javax.inject@default:default,javax.servlet@default:default,javax.xml@default:default,jfree.chart-swt@default:default,jfree.chart@default:default,jfree.jcommon@default:default,net.sf.kxml.2@default:default,org.apache.batik.css@default:default,org.apache.batik.util.gui@default:default,org.apache.batik.util@default:default,org.apache.commons.codec*1.4.0.v201209201156@default:default,org.apache.commons.compress@default:default,org.apache.commons.logging*1.1.1.v201101211721@default:default,org.apache.httpcomponents.httpclient*4.1.3.v201209201135@default:default,org.apache.httpcomponents.httpcore*4.1.4.v201203221030@default:default,org.eclipse.ant.core@default:default,org.eclipse.compare.core@default:default,org.eclipse.core.commands@default:default,org.eclipse.core.contenttype@default:default,org.eclipse.core.databinding.observable@default:default,org.eclipse.core.databinding.property@default:default,org.eclipse.core.databinding@default:default,org.eclipse.core.expressions@default:default,org.eclipse.core.filesystem.linux.x86_64@default:false,org.eclipse.core.filesystem@default:default,org.eclipse.core.jobs@default:default,org.eclipse.core.resources@default:default,org.eclipse.core.runtime.compatibility.registry@default:false,org.eclipse.core.runtime@default:true,org.eclipse.core.variables@default:default,org.eclipse.e4.core.commands@default:default,org.eclipse.e4.core.contexts@default:default,org.eclipse.e4.core.di.extensions@default:default,org.eclipse.e4.core.di@default:default,org.eclipse.e4.core.services@default:default,org.eclipse.e4.ui.bindings@default:default,org.eclipse.e4.ui.css.core@default:default,org.eclipse.e4.ui.css.swt.theme@default:default,org.eclipse.e4.ui.css.swt@default:default,org.eclipse.e4.ui.di@default:default,org.eclipse.e4.ui.model.workbench@default:default,org.eclipse.e4.ui.services@default:default,org.eclipse.e4.ui.widgets@default:default,org.eclipse.e4.ui.workbench.addons.swt@default:default,org.eclipse.e4.ui.workbench.renderers.swt@default:default,org.eclipse.e4.ui.workbench.swt@default:default,org.eclipse.e4.ui.workbench3@default:default,org.eclipse.e4.ui.workbench@default:default,org.eclipse.emf.common@default:default,org.eclipse.emf.ecore.change@default:default,org.eclipse.emf.ecore.xmi@default:default,org.eclipse.emf.ecore@default:default,org.eclipse.equinox.app@default:default,org.eclipse.equinox.bidi@default:default,org.eclipse.equinox.common@2:true,org.eclipse.equinox.ds@1:true,org.eclipse.equinox.event@default:default,org.eclipse.equinox.p2.core@default:default,org.eclipse.equinox.p2.engine@default:default,org.eclipse.equinox.p2.metadata.repository@default:default,org.eclipse.equinox.p2.metadata@default:default,org.eclipse.equinox.p2.repository@default:default,org.eclipse.equinox.preferences@default:default,org.eclipse.equinox.registry@default:default,org.eclipse.equinox.security@default:default,org.eclipse.equinox.util@default:default,org.eclipse.help@default:default,org.eclipse.jface.databinding@default:default,org.eclipse.jface.text@default:default,org.eclipse.jface@default:default,org.eclipse.osgi.services@default:default,org.eclipse.osgi@-1:true,org.eclipse.swt.gtk.linux.x86_64@default:false,org.eclipse.swt@default:default,org.eclipse.text@default:default,org.eclipse.ui.console@default:default,org.eclipse.ui.forms@default:default,org.eclipse.ui.ide@default:default,org.eclipse.ui.views@default:default,org.eclipse.ui.workbench.texteditor@default:default,org.eclipse.ui.workbench@default:default,org.eclipse.ui@default:default,org.w3c.css.sac@default:default,org.w3c.dom.smil@default:default,org.w3c.dom.svg@default:default"/>
-<stringAttribute key="selected_workspace_plugins" value="com.android.ide.eclipse.base@default:default,com.android.ide.eclipse.ddms@default:default,com.android.ide.eclipse.gldebugger@default:default,com.android.ide.eclipse.hierarchyviewer@default:default,com.android.ide.eclipse.monitor@default:default,com.android.ide.eclipse.ndk@default:default,com.android.ide.eclipse.pdt@default:default,com.android.ide.eclipse.tests@default:false,com.android.ide.eclipse.traceview@default:default"/>
-<booleanAttribute key="show_selected_only" value="false"/>
-<stringAttribute key="templateConfig" value="${target_home}/configuration/config.ini"/>
-<booleanAttribute key="tracing" value="false"/>
-<booleanAttribute key="useCustomFeatures" value="false"/>
-<booleanAttribute key="useDefaultConfig" value="true"/>
-<booleanAttribute key="useDefaultConfigArea" value="true"/>
-<booleanAttribute key="useProduct" value="true"/>
-</launchConfiguration>
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/plugin.properties b/eclipse/plugins/com.android.ide.eclipse.monitor/plugin.properties
deleted file mode 100644
index f25aa6e31..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/plugin.properties
+++ /dev/null
@@ -1,8 +0,0 @@
-#Properties file for com.android.ide.eclipse.monitor
-#TODO: update with new year date (search this to find other occurrences to update)
-Bundle-Vendor = The Android Open Source Project
-Bundle-Name = Monitor
-aboutText = \n\
-Android Device Monitor\n\
-Version: 24.3.3 \n\
-Copyright 2012, The Android Open Source Project \n\
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/plugin.xml b/eclipse/plugins/com.android.ide.eclipse.monitor/plugin.xml
deleted file mode 100644
index 32c44d058..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/plugin.xml
+++ /dev/null
@@ -1,132 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<?eclipse version="3.4"?>
-<plugin>
- <extension
- id="com.android.ide.eclipse.monitor.Application"
- point="org.eclipse.core.runtime.applications">
- <application
- cardinality="singleton-global"
- thread="main"
- visible="true">
- <run
- class="com.android.ide.eclipse.monitor.MonitorApplication">
- </run>
- </application>
- </extension>
- <extension
- id="com.android.ide.eclipse.monitor.product"
- point="org.eclipse.core.runtime.products">
- <product
- application="com.android.ide.eclipse.monitor.Application"
- name="Android Device Monitor">
- <property
- name="appName"
- value="Monitor">
- </property>
- <property
- name="preferenceCustomization"
- value="plugin_customization.ini">
- </property>
- <property
- name="windowImages"
- value="images/ddms-16.png,images/ddms-32.png,images/ddms-128.png">
- </property>
- <property
- name="aboutImage"
- value="images/ddms-128.png">
- </property>
- <property
- name="aboutText"
- value="%aboutText">
- </property>
-
- </product>
- </extension>
- <extension
- point="com.android.ide.eclipse.ddms.toolsLocator">
- <locator
- class="com.android.ide.eclipse.monitor.ToolsLocator">
- </locator>
- </extension>
- <extension
- point="org.eclipse.ui.commands">
- <command
- defaultHandler="com.android.ide.eclipse.monitor.handlers.StaticPortConfigHandler"
- id="com.android.monitor.commands.StaticPortConfiguration"
- name="Static Port Configuration">
- </command>
- </extension>
- <extension
- point="org.eclipse.ui.menus">
- <menuContribution
- allPopups="false"
- locationURI="menu:file?after=additions">
- <command
- commandId="com.android.monitor.commands.StaticPortConfiguration"
- label="Static Port Configuration"
- style="push"
- tooltip="Configure static debug ports">
- </command>
- </menuContribution>
- <menuContribution
- allPopups="false"
- locationURI="menu:window?after=additions">
- <command
- commandId="org.eclipse.ui.views.showView"
- style="push">
- </command>
- </menuContribution>
- </extension>
- <extension
- point="org.eclipse.ui.preferencePages">
- <page
- class="com.android.ide.eclipse.monitor.AndroidPreferencePage"
- id="com.android.ide.eclipse.preferences.main"
- name="Android">
- </page>
- </extension>
- <extension
- point="org.eclipse.ui.startup">
- <startup
- class="com.android.ide.eclipse.monitor.MonitorStartup">
- </startup>
- </extension>
- <extension
- point="org.eclipse.ui.actionSets">
- <actionSet
- id="monitor.actionSet.AvdSdkManager"
- label="Android SDK and AVD Manager"
- visible="true">
- <action
- class="com.android.ide.eclipse.monitor.actions.AvdManagerAction"
- icon="images/avd_manager.png"
- id="com.android.ide.eclipse.monitor.avdmanager"
- label="Android Virtual Device Manager"
- menubarPath="Window/additions"
- style="push"
- toolbarPath="android_project">
- </action>
- <action
- class="com.android.ide.eclipse.monitor.actions.SdkManagerAction"
- icon="images/sdk_manager.png"
- id="com.android.ide.eclipse.monitor.sdkmanager"
- label="Android SDK Manager"
- menubarPath="Window/additions"
- style="push"
- toolbarPath="android_project">
- </action>
- </actionSet>
- </extension>
- <extension
- id="product"
- point="org.eclipse.core.runtime.products">
- <product
- application="com.android.ide.eclipse.monitor.Application"
- name="monitor">
- <property
- name="appName"
- value="monitor">
- </property>
- </product>
- </extension>
-</plugin>
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/plugin_customization.ini b/eclipse/plugins/com.android.ide.eclipse.monitor/plugin_customization.ini
deleted file mode 100644
index fa9d8a2b3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/plugin_customization.ini
+++ /dev/null
@@ -1,6 +0,0 @@
-org.eclipse.ui/DOCK_PERSPECTIVE_BAR=topRight
-org.eclipse.ui/SHOW_TEXT_ON_PERSPECTIVE_BAR=true
-org.eclipse.ui/PERSPECTIVE_BAR_EXTRAS=com.android.ide.eclipse.ddms.Perspective,com.android.ide.eclipse.hierarchyviewer.TreeViewPerspective
-org.eclipse.ui/SHOW_TRADITIONAL_STYLE_TABS=true
-org.eclipse.ui/SHOW_MEMORY_MONITOR=true
-org.eclipse.ui/SHOW_PROGRESS_ON_STARTUP = false
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/pom.xml b/eclipse/plugins/com.android.ide.eclipse.monitor/pom.xml
deleted file mode 100644
index 425057feb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/pom.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <version>24.3.3-SNAPSHOT</version>
- <artifactId>com.android.ide.eclipse.monitor</artifactId>
- <packaging>eclipse-plugin</packaging>
- <name>monitor</name>
-
- <parent>
- <relativePath>../../pom.xml</relativePath>
- <groupId>adt.group</groupId>
- <artifactId>parent</artifactId>
- <version>1.0.0-SNAPSHOT</version>
- </parent>
-</project>
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/splash.bmp b/eclipse/plugins/com.android.ide.eclipse.monitor/splash.bmp
deleted file mode 100644
index 54880bf35..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/splash.bmp
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/AndroidPreferencePage.java b/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/AndroidPreferencePage.java
deleted file mode 100644
index b85f0163d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/AndroidPreferencePage.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.monitor;
-
-import org.eclipse.jface.preference.PreferencePage;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-
-public class AndroidPreferencePage extends PreferencePage implements IWorkbenchPreferencePage {
- public AndroidPreferencePage() {
- super(""); //$NON-NLS-1$
- setPreferenceStore(MonitorPlugin.getDefault().getPreferenceStore());
- }
-
- @Override
- public void init(IWorkbench workbench) {
- }
-
- @Override
- protected Control createContents(Composite parent) {
- // TODO: This page is empty currently. It is only used as the top level
- // to which DDMS & logcat attach their preference pages.
- // ADT's root page contains the path to the Android SDK, and we should recreate
- // that here once we figure out how to share this across plugins.
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/MonitorActionBarAdvisor.java b/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/MonitorActionBarAdvisor.java
deleted file mode 100644
index e31e45ebe..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/MonitorActionBarAdvisor.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.monitor;
-
-import org.eclipse.jface.action.GroupMarker;
-import org.eclipse.jface.action.IMenuManager;
-import org.eclipse.jface.action.MenuManager;
-import org.eclipse.ui.IWorkbenchActionConstants;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.actions.ActionFactory;
-import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
-import org.eclipse.ui.application.ActionBarAdvisor;
-import org.eclipse.ui.application.IActionBarConfigurer;
-import org.eclipse.ui.internal.IWorkbenchGraphicConstants;
-import org.eclipse.ui.internal.WorkbenchImages;
-
-public class MonitorActionBarAdvisor extends ActionBarAdvisor {
- private IWorkbenchAction mQuitAction;
- private IWorkbenchAction mCopyAction;
- private IWorkbenchAction mSelectAllAction;
- private IWorkbenchAction mFindAction;
- private IWorkbenchAction mOpenPerspectiveAction;
- private IWorkbenchAction mResetPerspectiveAction;
- private IWorkbenchAction mPreferencesAction;
- private IWorkbenchAction mAboutAction;
-
- public MonitorActionBarAdvisor(IActionBarConfigurer configurer) {
- super(configurer);
- }
-
- @Override
- protected void makeActions(IWorkbenchWindow window) {
- mQuitAction = ActionFactory.QUIT.create(window);
- register(mQuitAction);
-
- mCopyAction = ActionFactory.COPY.create(window);
- register(mCopyAction);
-
- mSelectAllAction = ActionFactory.SELECT_ALL.create(window);
- register(mSelectAllAction);
-
- mFindAction = ActionFactory.FIND.create(window);
- mFindAction.setText("Find..."); // replace the default "Find and Replace..."
- register(mFindAction);
-
- mOpenPerspectiveAction = ActionFactory.OPEN_PERSPECTIVE_DIALOG.create(window);
- register(mOpenPerspectiveAction);
-
- mResetPerspectiveAction = ActionFactory.RESET_PERSPECTIVE.create(window);
- register(mResetPerspectiveAction);
-
- mPreferencesAction = ActionFactory.PREFERENCES.create(window);
- register(mPreferencesAction);
-
- mAboutAction = ActionFactory.ABOUT.create(window);
- register(mAboutAction);
- }
-
- @Override
- protected void fillMenuBar(IMenuManager menuBar) {
- MenuManager fileMenu = new MenuManager("&File", IWorkbenchActionConstants.M_FILE);
- MenuManager editMenu = new MenuManager("&Edit", IWorkbenchActionConstants.M_EDIT);
- MenuManager helpMenu = new MenuManager("&Help", IWorkbenchActionConstants.M_HELP);
- MenuManager windowMenu = new MenuManager("&Window", IWorkbenchActionConstants.M_WINDOW);
-
- menuBar.add(fileMenu);
- menuBar.add(editMenu);
- menuBar.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
- menuBar.add(windowMenu);
- menuBar.add(helpMenu);
-
- // contents of File menu
- fileMenu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
- fileMenu.add(mQuitAction);
-
- // contents of Edit menu
- editMenu.add(mCopyAction);
- editMenu.add(mSelectAllAction);
- editMenu.add(mFindAction);
-
- // contents of Window menu
- windowMenu.add(mOpenPerspectiveAction);
- windowMenu.add(mResetPerspectiveAction);
- windowMenu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
- windowMenu.add(mPreferencesAction);
-
- // contents of Help menu
- helpMenu.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
- helpMenu.add(mAboutAction);
- };
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/MonitorApplication.java b/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/MonitorApplication.java
deleted file mode 100644
index 425786f6f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/MonitorApplication.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.monitor;
-
-import com.android.ide.eclipse.monitor.SdkToolsLocator.SdkInstallStatus;
-import com.android.prefs.AndroidLocation;
-import com.android.sdklib.SdkManager;
-import com.android.sdkstats.SdkStatsService;
-import com.android.sdkuilib.internal.repository.ui.AdtUpdateDialog;
-import com.android.utils.ILogger;
-import com.android.utils.NullLogger;
-
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.equinox.app.IApplication;
-import org.eclipse.equinox.app.IApplicationContext;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.window.Window;
-import org.eclipse.osgi.service.datalocation.Location;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.PlatformUI;
-
-import java.io.File;
-
-public class MonitorApplication implements IApplication {
- private static final String SDK_PATH_ENVVAR = "com.android.sdk.path";
- private static final String MONITOR_WORKSPACE_PATH = "monitor-workspace";
-
- @Override
- public Object start(IApplicationContext context) throws Exception {
- Display display = PlatformUI.createDisplay();
-
- // set workspace location
- Location instanceLoc = Platform.getInstanceLocation();
- IPath workspacePath = new Path(AndroidLocation.getFolder()).append(MONITOR_WORKSPACE_PATH);
- instanceLoc.set(workspacePath.toFile().toURI().toURL(), true);
-
- // figure out path to SDK
- String sdkPath = findSdkPath(display);
- if (!isValidSdkLocation(sdkPath)) {
- // exit with return code -1
- return Integer.valueOf(-1);
- }
- MonitorPlugin.getDefault().setSdkFolder(new File(sdkPath));
-
- // install platform tools if necessary
- ILogger sdkLog = NullLogger.getLogger();
- SdkManager manager = SdkManager.createManager(sdkPath, sdkLog);
- if (manager.getPlatformToolsVersion() == null) {
- boolean install = MessageDialog.openQuestion(new Shell(display),
- "Monitor",
- "The platform tools package that provides adb is missing from your SDK installation. "
- + "Monitor requires this package to work properly. Would you like to install that package now?");
- if (!install) {
- return Integer.valueOf(-1);
- }
- AdtUpdateDialog window = new AdtUpdateDialog(new Shell(display), sdkLog, sdkPath);
- window.installPlatformTools();
- }
-
- // If this is the first time using ddms or adt, open up the stats service
- // opt out dialog, and request user for permissions.
- // Note that the actual ping is performed in MonitorStartup
- SdkStatsService stats = new SdkStatsService();
- stats.checkUserPermissionForPing(new Shell(display));
-
- // open up RCP
- try {
- int returnCode = PlatformUI.createAndRunWorkbench(display,
- new MonitorWorkbenchAdvisor());
- if (returnCode == PlatformUI.RETURN_RESTART) {
- return IApplication.EXIT_RESTART;
- }
- return IApplication.EXIT_OK;
- } finally {
- display.dispose();
- }
- }
-
- @Override
- public void stop() {
- if (!PlatformUI.isWorkbenchRunning())
- return;
- final IWorkbench workbench = PlatformUI.getWorkbench();
- final Display display = workbench.getDisplay();
- display.syncExec(new Runnable() {
- @Override
- public void run() {
- if (!display.isDisposed())
- workbench.close();
- }
- });
- }
-
- private String findSdkPath(Display display) {
- // see if there is a system property set (passed in via a command line arg)
- String sdkLocation = System.getProperty(SDK_PATH_ENVVAR);
- if (isValidSdkLocation(sdkLocation)) {
- return sdkLocation;
- }
-
- // see if there is an environment variable set
- sdkLocation = System.getenv(SDK_PATH_ENVVAR);
- if (isValidSdkLocation(sdkLocation)) {
- return sdkLocation;
- }
-
- // The monitor app should be located in "<sdk>/tools/lib/monitor-platform/"
- // So see if the folder one level up from the install location is a valid SDK.
- Location install = Platform.getInstallLocation();
- if (install != null && install.getURL() != null) {
- File libFolder = new File(install.getURL().getFile()).getParentFile();
- if (libFolder != null) {
- String toolsFolder = libFolder.getParent();
- if (toolsFolder != null) {
- sdkLocation = new File(toolsFolder).getParent();
- if (isValidSdkLocation(sdkLocation)) {
- MonitorPlugin.getDdmsPreferenceStore().setLastSdkPath(sdkLocation);
- return sdkLocation;
- }
- }
-
- }
- }
-
- // check for the last used SDK
- sdkLocation = MonitorPlugin.getDdmsPreferenceStore().getLastSdkPath();
- if (isValidSdkLocation(sdkLocation)) {
- return sdkLocation;
- }
-
- // if nothing else works, prompt the user
- sdkLocation = getSdkLocationFromUser(new Shell(display));
- if (isValidSdkLocation(sdkLocation)) {
- MonitorPlugin.getDdmsPreferenceStore().setLastSdkPath(sdkLocation);
- }
-
- return sdkLocation;
- }
-
- private boolean isValidSdkLocation(String sdkLocation) {
- if (sdkLocation == null) {
- return false;
- }
-
- if (sdkLocation.trim().length() == 0) {
- return false;
- }
-
- SdkToolsLocator locator = new SdkToolsLocator(new File(sdkLocation));
- return locator.isValidInstallation() == SdkInstallStatus.VALID;
- }
-
- private String getSdkLocationFromUser(Shell shell) {
- SdkLocationChooserDialog dlg = new SdkLocationChooserDialog(shell);
- if (dlg.open() == Window.OK) {
- return dlg.getPath();
- } else {
- return null;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/MonitorPlugin.java b/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/MonitorPlugin.java
deleted file mode 100644
index a61eb4ab8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/MonitorPlugin.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.monitor;
-
-import com.android.sdkstats.DdmsPreferenceStore;
-
-import org.eclipse.jface.resource.ImageDescriptor;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.osgi.framework.BundleContext;
-
-import java.io.File;
-
-public class MonitorPlugin extends AbstractUIPlugin {
- public static final String PLUGIN_ID = "com.android.ide.eclipse.monitor"; //$NON-NLS-1$
- private static MonitorPlugin sPlugin;
- private static final DdmsPreferenceStore sDdmsPreferenceStore = new DdmsPreferenceStore();
- private File mSdkFolder;
-
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
-
- sPlugin = this;
- }
-
- @Override
- public void stop(BundleContext context) throws Exception {
- sPlugin = null;
- super.stop(context);
- }
-
- public static MonitorPlugin getDefault() {
- return sPlugin;
- }
-
- public static ImageDescriptor getImageDescriptor(String path) {
- return imageDescriptorFromPlugin(PLUGIN_ID, path);
- }
-
- public static DdmsPreferenceStore getDdmsPreferenceStore() {
- return sDdmsPreferenceStore;
- }
-
- public void setSdkFolder(File sdkFolder) {
- mSdkFolder = sdkFolder;
- }
-
- public File getSdkFolder() {
- return mSdkFolder;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/MonitorStartup.java b/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/MonitorStartup.java
deleted file mode 100644
index 2de260ee6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/MonitorStartup.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.monitor;
-
-import com.android.SdkConstants;
-import com.android.sdkstats.SdkStatsService;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.ui.IStartup;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.util.Properties;
-
-public class MonitorStartup implements IStartup {
- @Override
- public void earlyStartup() {
- Job pingJob = new Job("Android SDK Ping") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- SdkStatsService stats = new SdkStatsService();
- File sdkFolder = MonitorPlugin.getDefault().getSdkFolder();
- if (sdkFolder == null) {
- return Status.OK_STATUS;
- }
-
- String toolsPath = new File(sdkFolder, SdkConstants.FD_TOOLS).getAbsolutePath();
- ping(stats, toolsPath);
- return Status.OK_STATUS;
- }
- };
- pingJob.setPriority(Job.DECORATE); // lowest priority
- pingJob.schedule();
- }
-
- private static void ping(SdkStatsService stats, String toolsLocation) {
- Properties p = new Properties();
- try{
- File sourceProp;
- if (toolsLocation != null && toolsLocation.length() > 0) {
- sourceProp = new File(toolsLocation, "source.properties"); //$NON-NLS-1$
- } else {
- sourceProp = new File("source.properties"); //$NON-NLS-1$
- }
- FileInputStream fis = null;
- try {
- fis = new FileInputStream(sourceProp);
- p.load(fis);
- } finally {
- if (fis != null) {
- try {
- fis.close();
- } catch (IOException ignore) {
- }
- }
- }
-
- String revision = p.getProperty("Pkg.Revision"); //$NON-NLS-1$
- if (revision != null && revision.length() > 0) {
- stats.ping("ddms", revision); //$NON-NLS-1$
- }
- } catch (FileNotFoundException e) {
- // couldn't find the file? don't ping.
- } catch (IOException e) {
- // couldn't find the file? don't ping.
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/MonitorWorkbenchAdvisor.java b/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/MonitorWorkbenchAdvisor.java
deleted file mode 100644
index c79803f4d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/MonitorWorkbenchAdvisor.java
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.monitor;
-
-import com.android.ide.eclipse.ddms.Perspective;
-
-import org.eclipse.ui.application.IWorkbenchConfigurer;
-import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
-import org.eclipse.ui.application.WorkbenchAdvisor;
-import org.eclipse.ui.application.WorkbenchWindowAdvisor;
-
-public class MonitorWorkbenchAdvisor extends WorkbenchAdvisor {
- @Override
- public String getInitialWindowPerspectiveId() {
- return Perspective.ID;
- }
-
- @Override
- public void initialize(IWorkbenchConfigurer configurer) {
- super.initialize(configurer);
- configurer.setSaveAndRestore(true);
- }
-
- @Override
- public WorkbenchWindowAdvisor createWorkbenchWindowAdvisor(
- IWorkbenchWindowConfigurer configurer) {
- return new MonitorWorkbenchWindowAdvisor(configurer);
- };
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/MonitorWorkbenchWindowAdvisor.java b/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/MonitorWorkbenchWindowAdvisor.java
deleted file mode 100644
index 137d3b184..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/MonitorWorkbenchWindowAdvisor.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.monitor;
-
-import org.eclipse.ui.application.ActionBarAdvisor;
-import org.eclipse.ui.application.IActionBarConfigurer;
-import org.eclipse.ui.application.IWorkbenchWindowConfigurer;
-import org.eclipse.ui.application.WorkbenchWindowAdvisor;
-
-public class MonitorWorkbenchWindowAdvisor extends WorkbenchWindowAdvisor {
- public MonitorWorkbenchWindowAdvisor(IWorkbenchWindowConfigurer configurer) {
- super(configurer);
- }
-
- @Override
- public ActionBarAdvisor createActionBarAdvisor(IActionBarConfigurer configurer) {
- return new MonitorActionBarAdvisor(configurer);
- };
-
- @Override
- public void preWindowOpen() {
- IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
- configurer.setShowStatusLine(true);
- configurer.setShowPerspectiveBar(true);
- configurer.setTitle("Android Device Monitor");
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/SdkLocationChooserDialog.java b/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/SdkLocationChooserDialog.java
deleted file mode 100644
index 04f60c796..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/SdkLocationChooserDialog.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.monitor;
-
-import com.android.ide.eclipse.monitor.SdkToolsLocator.SdkInstallStatus;
-
-import org.eclipse.jface.dialogs.Dialog;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.layout.GridDataFactory;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.DirectoryDialog;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-
-import java.io.File;
-
-public class SdkLocationChooserDialog extends Dialog {
- private static final String TITLE = "Android Device Monitor";
- private static final String DEFAULT_MESSAGE = "Provide the path to the Android SDK";
-
- private Label mStatusLabel;
- private Text mTextBox;
- private String mPath;
-
- public SdkLocationChooserDialog(Shell parentShell) {
- super(parentShell);
- }
-
- @Override
- protected Control createDialogArea(Composite parent) {
- getShell().setText(TITLE);
-
- Composite c = new Composite((Composite) super.createDialogArea(parent), SWT.NONE);
- c.setLayout(new GridLayout(2, false));
- c.setLayoutData(new GridData(GridData.FILL_BOTH));
-
- Label l = new Label(c, SWT.NONE);
- l.setText(DEFAULT_MESSAGE);
- GridDataFactory.fillDefaults().span(2, 1).applyTo(l);
-
- mTextBox = new Text(c, SWT.BORDER);
- mTextBox.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- GridDataFactory.fillDefaults()
- .hint(SwtUtils.getFontWidth(mTextBox) * 80, SWT.DEFAULT)
- .applyTo(mTextBox);
- mTextBox.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- validateInstall();
- }
- });
-
- Button browse = new Button(c, SWT.PUSH);
- browse.setText("Browse");
- browse.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- DirectoryDialog dlg = new DirectoryDialog(getShell(), SWT.OPEN);
- dlg.setText("Android SDK location");
- String dir = dlg.open();
- if (dir != null) {
- mTextBox.setText(dir);
- validateInstall();
- }
- }
- });
-
- mStatusLabel = new Label(c, SWT.WRAP);
- mStatusLabel.setText("");
- mStatusLabel.setForeground(getShell().getDisplay().getSystemColor(SWT.COLOR_RED));
- GridDataFactory.fillDefaults().span(2, 1).applyTo(mStatusLabel);
-
- return super.createDialogArea(parent);
- }
-
- private void validateInstall() {
- SdkToolsLocator locator = new SdkToolsLocator(new File(mTextBox.getText()));
- SdkInstallStatus status = locator.isValidInstallation();
- if (status.isValid()) {
- mStatusLabel.setText("");
- getButton(IDialogConstants.OK_ID).setEnabled(true);
- } else {
- mStatusLabel.setText(status.getErrorMessage());
- mStatusLabel.pack();
- getButton(IDialogConstants.OK_ID).setEnabled(false);
- }
- }
-
- @Override
- public boolean close() {
- mPath = mTextBox.getText();
- return super.close();
- }
-
- public String getPath() {
- return mPath;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/SdkToolsLocator.java b/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/SdkToolsLocator.java
deleted file mode 100644
index bd8ef60cb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/SdkToolsLocator.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.monitor;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.ddms.IToolsLocator;
-
-import java.io.File;
-import java.util.Arrays;
-import java.util.List;
-
-/**
- * {@link SdkToolsLocator} has two functions: <ul>
- * <li> It implements all the methods of {@link IToolsLocator} interface, and
- * so can be used as such. </li>
- * <li> It provides the {@link #isValidInstallation()} method to check the validity
- * of an installation. </li>
- * The only reason this class does not explicitly implement the {@link IToolsLocator} interface
- * is that it is used very early during the startup to check the validity of the installation.
- * Actually implementing that interface causes other bundles to be activated before the
- * Eclipse Platform is fully initialized, resulting in startup error.
- */
-public class SdkToolsLocator {
- public static final String PLATFORM_EXECUTABLE_EXTENSION =
- (SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_WINDOWS) ?
- ".exe" : ""; //$NON-NLS-1$
-
- public static final String PLATFORM_SCRIPT_EXTENSION =
- (SdkConstants.CURRENT_PLATFORM == SdkConstants.PLATFORM_WINDOWS) ?
- ".bat" : ""; //$NON-NLS-1$
-
- public static final String FN_HPROF_CONV = "hprof-conv" + PLATFORM_EXECUTABLE_EXTENSION; //$NON-NLS-1$
- public static final String FN_TRACEVIEW = "traceview" + PLATFORM_SCRIPT_EXTENSION; //$NON-NLS-1$
-
- private final File mSdkFolder;
-
- public SdkToolsLocator(File sdkFolder) {
- mSdkFolder = sdkFolder;
- }
-
- public String getAdbLocation() {
- return new File(getSdkPlatformToolsFolder(), SdkConstants.FN_ADB).getAbsolutePath();
- }
-
- public String getTraceViewLocation() {
- return new File(getSdkToolsFolder(), FN_TRACEVIEW).getAbsolutePath();
- }
-
- public String getHprofConvLocation() {
- return new File(getSdkPlatformToolsFolder(), FN_HPROF_CONV).getAbsolutePath();
- }
-
- private String getSdkToolsFolder() {
- return new File(mSdkFolder, SdkConstants.FD_TOOLS).getAbsolutePath();
- }
-
- private String getSdkPlatformToolsFolder() {
- return new File(mSdkFolder, SdkConstants.FD_PLATFORM_TOOLS).getAbsolutePath();
- }
-
- public SdkInstallStatus isValidInstallation() {
- List<String> executables = Arrays.asList(
- getTraceViewLocation(),
- getHprofConvLocation());
-
- for (String exe : executables) {
- File f = new File(exe);
- if (!f.exists()) {
- return SdkInstallStatus.invalidInstallation(exe + " not present.");
- }
- if (!f.canExecute()) {
- return SdkInstallStatus.invalidInstallation(exe + " is not executable.");
- }
- }
-
- return SdkInstallStatus.VALID;
- }
-
- public static class SdkInstallStatus {
- private boolean mValid;
- private String mCause;
-
- private SdkInstallStatus(boolean valid, String errorMessage) {
- mValid = valid;
- mCause = errorMessage;
- }
-
- public boolean isValid() {
- return mValid;
- }
-
- public String getErrorMessage() {
- return mCause;
- }
-
- public static final SdkInstallStatus VALID = new SdkInstallStatus(true, "");
-
- public static SdkInstallStatus invalidInstallation(String errorMessage) {
- return new SdkInstallStatus(false, errorMessage);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/SwtUtils.java b/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/SwtUtils.java
deleted file mode 100644
index bae7f0b32..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/SwtUtils.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.monitor;
-
-import org.eclipse.swt.graphics.GC;
-import org.eclipse.swt.widgets.Control;
-
-public class SwtUtils {
- public static int getFontWidth(Control c) {
- GC gc = new GC(c);
- int avgCharWidth = gc.getFontMetrics().getAverageCharWidth();
- gc.dispose();
- return avgCharWidth;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/ToolsLocator.java b/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/ToolsLocator.java
deleted file mode 100644
index 75971817c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/ToolsLocator.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.monitor;
-
-import com.android.ide.eclipse.ddms.IToolsLocator;
-
-public class ToolsLocator implements IToolsLocator {
- private SdkToolsLocator mLocator;
-
- public ToolsLocator() {
- mLocator = new SdkToolsLocator(MonitorPlugin.getDefault().getSdkFolder());
- }
-
- @Override
- public String getAdbLocation() {
- return mLocator.getAdbLocation();
- }
-
- @Override
- public String getTraceViewLocation() {
- return mLocator.getTraceViewLocation();
- }
-
- @Override
- public String getHprofConvLocation() {
- return mLocator.getHprofConvLocation();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/actions/AvdManagerAction.java b/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/actions/AvdManagerAction.java
deleted file mode 100644
index 2510bd34a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/actions/AvdManagerAction.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.monitor.actions;
-
-public class AvdManagerAction extends SdkManagerAction {
- @Override
- protected String getAndroidBatArgument() {
- return "avd";
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/actions/SdkManagerAction.java b/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/actions/SdkManagerAction.java
deleted file mode 100644
index 573ed7c07..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/actions/SdkManagerAction.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.monitor.actions;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.monitor.MonitorPlugin;
-
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.dialogs.ErrorDialog;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.IWorkbenchWindowActionDelegate;
-import org.eclipse.ui.PlatformUI;
-
-import java.io.File;
-import java.io.IOException;
-
-public class SdkManagerAction implements IWorkbenchWindowActionDelegate {
- @Override
- public void run(IAction action) {
- File sdk = MonitorPlugin.getDefault().getSdkFolder();
- if (sdk != null) {
- File tools = new File(sdk, SdkConstants.FD_TOOLS);
- File androidBat = new File(tools, SdkConstants.androidCmdName());
- if (androidBat.exists()) {
- String[] cmd = new String[] {
- androidBat.getAbsolutePath(),
- getAndroidBatArgument(),
- };
- try {
- Runtime.getRuntime().exec(cmd);
- } catch (IOException e) {
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- if (window != null) {
- ErrorDialog.openError(
- window.getShell(),
- "Monitor",
- "Error while launching SDK Manager",
- new Status(Status.ERROR,
- MonitorPlugin.PLUGIN_ID,
- "Error while launching SDK Manager",
- e));
- }
- }
- }
- }
- }
-
- protected String getAndroidBatArgument() {
- return "sdk";
- }
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
- }
-
- @Override
- public void dispose() {
- }
-
- @Override
- public void init(IWorkbenchWindow window) {
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/ddms/DebugPortProvider.java b/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/ddms/DebugPortProvider.java
deleted file mode 100644
index a2ffa042b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/ddms/DebugPortProvider.java
+++ /dev/null
@@ -1,165 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.monitor.ddms;
-
-import com.android.ddmlib.DebugPortManager.IDebugPortProvider;
-import com.android.ddmlib.IDevice;
-import com.android.ide.eclipse.ddms.DdmsPlugin;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * DDMS implementation of the IDebugPortProvider interface.
- * This class handles saving/loading the list of static debug port from
- * the preference store and provides the port number to the Device Monitor.
- */
-public class DebugPortProvider implements IDebugPortProvider {
-
- private static DebugPortProvider sThis = new DebugPortProvider();
-
- /** Preference name for the static port list. */
- public static final String PREFS_STATIC_PORT_LIST = "android.staticPortList"; //$NON-NLS-1$
-
- /**
- * Mapping device serial numbers to maps. The embedded maps are mapping application names to
- * debugger ports.
- */
- private Map<String, Map<String, Integer>> mMap;
-
- public static DebugPortProvider getInstance() {
- return sThis;
- }
-
- private DebugPortProvider() {
- computePortList();
- }
-
- /**
- * Returns a static debug port for the specified application running on the
- * specified {@link IDevice}.
- * @param device The device the application is running on.
- * @param appName The application name, as defined in the
- * AndroidManifest.xml package attribute.
- * @return The static debug port or {@link #NO_STATIC_PORT} if there is none setup.
- *
- * @see IDebugPortProvider#getPort(IDevice, String)
- */
- @Override
- public int getPort(IDevice device, String appName) {
- if (mMap != null) {
- Map<String, Integer> deviceMap = mMap.get(device.getSerialNumber());
- if (deviceMap != null) {
- Integer i = deviceMap.get(appName);
- if (i != null) {
- return i.intValue();
- }
- }
- }
- return IDebugPortProvider.NO_STATIC_PORT;
- }
-
- /**
- * Returns the map of Static debugger ports. The map links device serial numbers to
- * a map linking application name to debugger ports.
- */
- public Map<String, Map<String, Integer>> getPortList() {
- return mMap;
- }
-
- /**
- * Create the map member from the values contained in the Preference Store.
- */
- private void computePortList() {
- mMap = new HashMap<String, Map<String, Integer>>();
-
- // get the prefs store
- IPreferenceStore store = DdmsPlugin.getDefault().getPreferenceStore();
- String value = store.getString(PREFS_STATIC_PORT_LIST);
-
- if (value != null && value.length() > 0) {
- // format is
- // port1|port2|port3|...
- // where port# is
- // appPackageName:appPortNumber:device-serial-number
- String[] portSegments = value.split("\\|"); //$NON-NLS-1$
- for (String seg : portSegments) {
- String[] entry = seg.split(":"); //$NON-NLS-1$
-
- // backward compatibility support. if we have only 2 entry, we default
- // to the first emulator.
- String deviceName = null;
- if (entry.length == 3) {
- deviceName = entry[2];
- } else {
- deviceName = IDevice.FIRST_EMULATOR_SN;
- }
-
- // get the device map
- Map<String, Integer> deviceMap = mMap.get(deviceName);
- if (deviceMap == null) {
- deviceMap = new HashMap<String, Integer>();
- mMap.put(deviceName, deviceMap);
- }
-
- deviceMap.put(entry[0], Integer.valueOf(entry[1]));
- }
- }
- }
-
- /**
- * Sets new [device, app, port] values.
- * The values are also sync'ed in the preference store.
- * @param map The map containing the new values.
- */
- public void setPortList(Map<String, Map<String,Integer>> map) {
- // update the member map.
- mMap.clear();
- mMap.putAll(map);
-
- // create the value to store in the preference store.
- // see format definition in getPortList
- StringBuilder sb = new StringBuilder();
-
- Set<String> deviceKeys = map.keySet();
- for (String deviceKey : deviceKeys) {
- Map<String, Integer> deviceMap = map.get(deviceKey);
- if (deviceMap != null) {
- Set<String> appKeys = deviceMap.keySet();
-
- for (String appKey : appKeys) {
- Integer port = deviceMap.get(appKey);
- if (port != null) {
- sb.append(appKey).append(':').append(port.intValue()).append(':').
- append(deviceKey).append('|');
- }
- }
- }
- }
-
- String value = sb.toString();
-
- // get the prefs store.
- IPreferenceStore store = DdmsPlugin.getDefault().getPreferenceStore();
-
- // and give it the new value.
- store.setValue(PREFS_STATIC_PORT_LIST, value);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/ddms/StaticPortConfigDialog.java b/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/ddms/StaticPortConfigDialog.java
deleted file mode 100644
index 456cdcf51..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/ddms/StaticPortConfigDialog.java
+++ /dev/null
@@ -1,396 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.monitor.ddms;
-
-import com.android.ddmuilib.TableHelper;
-import com.android.ide.eclipse.ddms.DdmsPlugin;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Dialog;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Table;
-import org.eclipse.swt.widgets.TableItem;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * Dialog to configure the static debug ports.
- *
- */
-public class StaticPortConfigDialog extends Dialog {
-
- /** Preference name for the 0th column width */
- private static final String PREFS_DEVICE_COL = "spcd.deviceColumn"; //$NON-NLS-1$
-
- /** Preference name for the 1st column width */
- private static final String PREFS_APP_COL = "spcd.AppColumn"; //$NON-NLS-1$
-
- /** Preference name for the 2nd column width */
- private static final String PREFS_PORT_COL = "spcd.PortColumn"; //$NON-NLS-1$
-
- private static final int COL_DEVICE = 0;
- private static final int COL_APPLICATION = 1;
- private static final int COL_PORT = 2;
-
-
- private static final int DLG_WIDTH = 500;
- private static final int DLG_HEIGHT = 300;
-
- private Shell mShell;
- private Shell mParent;
-
- private Table mPortTable;
-
- /**
- * Array containing the list of already used static port to avoid
- * duplication.
- */
- private ArrayList<Integer> mPorts = new ArrayList<Integer>();
-
- /**
- * Basic constructor.
- * @param parent
- */
- public StaticPortConfigDialog(Shell parent) {
- super(parent, SWT.DIALOG_TRIM | SWT.BORDER | SWT.APPLICATION_MODAL);
- }
-
- /**
- * Open and display the dialog. This method returns only when the
- * user closes the dialog somehow.
- *
- */
- public void open() {
- createUI();
-
- if (mParent == null || mShell == null) {
- return;
- }
-
- updateFromStore();
-
- // Set the dialog size.
- mShell.setMinimumSize(DLG_WIDTH, DLG_HEIGHT);
- Rectangle r = mParent.getBounds();
- // get the center new top left.
- int cx = r.x + r.width/2;
- int x = cx - DLG_WIDTH / 2;
- int cy = r.y + r.height/2;
- int y = cy - DLG_HEIGHT / 2;
- mShell.setBounds(x, y, DLG_WIDTH, DLG_HEIGHT);
-
- mShell.pack();
-
- // actually open the dialog
- mShell.open();
-
- // event loop until the dialog is closed.
- Display display = mParent.getDisplay();
- while (!mShell.isDisposed()) {
- if (!display.readAndDispatch())
- display.sleep();
- }
- }
-
- /**
- * Creates the dialog ui.
- */
- private void createUI() {
- mParent = getParent();
- mShell = new Shell(mParent, getStyle());
- mShell.setText("Static Port Configuration");
-
- mShell.setLayout(new GridLayout(1, true));
-
- mShell.addListener(SWT.Close, new Listener() {
- @Override
- public void handleEvent(Event event) {
- event.doit = true;
- }
- });
-
- // center part with the list on the left and the buttons
- // on the right.
- Composite main = new Composite(mShell, SWT.NONE);
- main.setLayoutData(new GridData(GridData.FILL_BOTH));
- main.setLayout(new GridLayout(2, false));
-
- // left part: list view
- mPortTable = new Table(main, SWT.SINGLE | SWT.FULL_SELECTION);
- mPortTable.setLayoutData(new GridData(GridData.FILL_BOTH));
- mPortTable.setHeaderVisible(true);
- mPortTable.setLinesVisible(true);
-
- TableHelper.createTableColumn(mPortTable, "Device Serial Number",
- SWT.LEFT, "emulator-5554", //$NON-NLS-1$
- PREFS_DEVICE_COL, DdmsPlugin.getDefault().getPreferenceStore());
-
- TableHelper.createTableColumn(mPortTable, "Application Package",
- SWT.LEFT, "com.android.samples.phone", //$NON-NLS-1$
- PREFS_APP_COL, DdmsPlugin.getDefault().getPreferenceStore());
-
- TableHelper.createTableColumn(mPortTable, "Debug Port",
- SWT.RIGHT, "Debug Port", //$NON-NLS-1$
- PREFS_PORT_COL, DdmsPlugin.getDefault().getPreferenceStore());
-
- // right part: buttons
- Composite buttons = new Composite(main, SWT.NONE);
- buttons.setLayoutData(new GridData(GridData.FILL_VERTICAL));
- buttons.setLayout(new GridLayout(1, true));
-
- Button newButton = new Button(buttons, SWT.NONE);
- newButton.setText("New...");
- newButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- StaticPortEditDialog dlg = new StaticPortEditDialog(mShell,
- mPorts);
- if (dlg.open()) {
- // get the text
- String device = dlg.getDeviceSN();
- String app = dlg.getAppName();
- int port = dlg.getPortNumber();
-
- // add it to the list
- addEntry(device, app, port);
- }
- }
- });
-
- final Button editButton = new Button(buttons, SWT.NONE);
- editButton.setText("Edit...");
- editButton.setEnabled(false);
- editButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- int index = mPortTable.getSelectionIndex();
- String oldDeviceName = getDeviceName(index);
- String oldAppName = getAppName(index);
- String oldPortNumber = getPortNumber(index);
- StaticPortEditDialog dlg = new StaticPortEditDialog(mShell,
- mPorts, oldDeviceName, oldAppName, oldPortNumber);
- if (dlg.open()) {
- // get the text
- String deviceName = dlg.getDeviceSN();
- String app = dlg.getAppName();
- int port = dlg.getPortNumber();
-
- // add it to the list
- replaceEntry(index, deviceName, app, port);
- }
- }
- });
-
- final Button deleteButton = new Button(buttons, SWT.NONE);
- deleteButton.setText("Delete");
- deleteButton.setEnabled(false);
- deleteButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- int index = mPortTable.getSelectionIndex();
- removeEntry(index);
- }
- });
-
- // bottom part with the ok/cancel
- Composite bottomComp = new Composite(mShell, SWT.NONE);
- bottomComp.setLayoutData(new GridData(
- GridData.HORIZONTAL_ALIGN_CENTER));
- bottomComp.setLayout(new GridLayout(2, true));
-
- Button okButton = new Button(bottomComp, SWT.NONE);
- okButton.setText("OK");
- okButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- updateStore();
- mShell.close();
- }
- });
-
- Button cancelButton = new Button(bottomComp, SWT.NONE);
- cancelButton.setText("Cancel");
- cancelButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- mShell.close();
- }
- });
-
- mPortTable.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- // get the selection index
- int index = mPortTable.getSelectionIndex();
-
- boolean enabled = index != -1;
- editButton.setEnabled(enabled);
- deleteButton.setEnabled(enabled);
- }
- });
-
- mShell.pack();
-
- }
-
- /**
- * Add a new entry in the list.
- * @param deviceName the serial number of the device
- * @param appName java package for the application
- * @param portNumber port number
- */
- private void addEntry(String deviceName, String appName, int portNumber) {
- // create a new item for the table
- TableItem item = new TableItem(mPortTable, SWT.NONE);
-
- item.setText(COL_DEVICE, deviceName);
- item.setText(COL_APPLICATION, appName);
- item.setText(COL_PORT, Integer.toString(portNumber));
-
- // add the port to the list of port number used.
- mPorts.add(portNumber);
- }
-
- /**
- * Remove an entry from the list.
- * @param index The index of the entry to be removed
- */
- private void removeEntry(int index) {
- // remove from the ui
- mPortTable.remove(index);
-
- // and from the port list.
- mPorts.remove(index);
- }
-
- /**
- * Replace an entry in the list with new values.
- * @param index The index of the item to be replaced
- * @param deviceName the serial number of the device
- * @param appName The new java package for the application
- * @param portNumber The new port number.
- */
- private void replaceEntry(int index, String deviceName, String appName, int portNumber) {
- // get the table item by index
- TableItem item = mPortTable.getItem(index);
-
- // set its new value
- item.setText(COL_DEVICE, deviceName);
- item.setText(COL_APPLICATION, appName);
- item.setText(COL_PORT, Integer.toString(portNumber));
-
- // and replace the port number in the port list.
- mPorts.set(index, portNumber);
- }
-
-
- /**
- * Returns the device name for a specific index
- * @param index The index
- * @return the java package name of the application
- */
- private String getDeviceName(int index) {
- TableItem item = mPortTable.getItem(index);
- return item.getText(COL_DEVICE);
- }
-
- /**
- * Returns the application name for a specific index
- * @param index The index
- * @return the java package name of the application
- */
- private String getAppName(int index) {
- TableItem item = mPortTable.getItem(index);
- return item.getText(COL_APPLICATION);
- }
-
- /**
- * Returns the port number for a specific index
- * @param index The index
- * @return the port number
- */
- private String getPortNumber(int index) {
- TableItem item = mPortTable.getItem(index);
- return item.getText(COL_PORT);
- }
-
- /**
- * Updates the ui from the value in the preference store.
- */
- private void updateFromStore() {
- // get the map from the debug port manager
- DebugPortProvider provider = DebugPortProvider.getInstance();
- Map<String, Map<String, Integer>> map = provider.getPortList();
-
- // we're going to loop on the keys and fill the table.
- Set<String> deviceKeys = map.keySet();
-
- for (String deviceKey : deviceKeys) {
- Map<String, Integer> deviceMap = map.get(deviceKey);
- if (deviceMap != null) {
- Set<String> appKeys = deviceMap.keySet();
-
- for (String appKey : appKeys) {
- Integer port = deviceMap.get(appKey);
- if (port != null) {
- addEntry(deviceKey, appKey, port);
- }
- }
- }
- }
- }
-
- /**
- * Update the store from the content of the ui.
- */
- private void updateStore() {
- // create a new Map object and fill it.
- HashMap<String, Map<String, Integer>> map = new HashMap<String, Map<String, Integer>>();
-
- int count = mPortTable.getItemCount();
-
- for (int i = 0 ; i < count ; i++) {
- TableItem item = mPortTable.getItem(i);
- String deviceName = item.getText(COL_DEVICE);
-
- Map<String, Integer> deviceMap = map.get(deviceName);
- if (deviceMap == null) {
- deviceMap = new HashMap<String, Integer>();
- map.put(deviceName, deviceMap);
- }
-
- deviceMap.put(item.getText(COL_APPLICATION), Integer.valueOf(item.getText(COL_PORT)));
- }
-
- // set it in the store through the debug port manager.
- DebugPortProvider provider = DebugPortProvider.getInstance();
- provider.setPortList(map);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/ddms/StaticPortEditDialog.java b/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/ddms/StaticPortEditDialog.java
deleted file mode 100644
index a9b0cd45e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/ddms/StaticPortEditDialog.java
+++ /dev/null
@@ -1,334 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.monitor.ddms;
-
-import com.android.ddmlib.IDevice;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Dialog;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Listener;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-
-import java.util.ArrayList;
-
-/**
- * Small dialog box to edit a static port number.
- */
-public class StaticPortEditDialog extends Dialog {
-
- private static final int DLG_WIDTH = 400;
- private static final int DLG_HEIGHT = 200;
-
- private Shell mParent;
-
- private Shell mShell;
-
- private boolean mOk = false;
-
- private String mAppName;
-
- private String mPortNumber;
-
- private Button mOkButton;
-
- private Label mWarning;
-
- /** List of ports already in use */
- private ArrayList<Integer> mPorts;
-
- /** This is the port being edited. */
- private int mEditPort = -1;
- private String mDeviceSn;
-
- /**
- * Creates a dialog with empty fields.
- * @param parent The parent Shell
- * @param ports The list of already used port numbers.
- */
- public StaticPortEditDialog(Shell parent, ArrayList<Integer> ports) {
- super(parent, SWT.DIALOG_TRIM | SWT.BORDER | SWT.APPLICATION_MODAL);
- mPorts = ports;
- mDeviceSn = IDevice.FIRST_EMULATOR_SN;
- }
-
- /**
- * Creates a dialog with predefined values.
- * @param shell The parent shell
- * @param ports The list of already used port numbers.
- * @param oldDeviceSN the device serial number to display
- * @param oldAppName The application name to display
- * @param oldPortNumber The port number to display
- */
- public StaticPortEditDialog(Shell shell, ArrayList<Integer> ports,
- String oldDeviceSN, String oldAppName, String oldPortNumber) {
- this(shell, ports);
-
- mDeviceSn = oldDeviceSN;
- mAppName = oldAppName;
- mPortNumber = oldPortNumber;
- mEditPort = Integer.valueOf(mPortNumber);
- }
-
- /**
- * Opens the dialog. The method will return when the user closes the dialog
- * somehow.
- *
- * @return true if ok was pressed, false if cancelled.
- */
- public boolean open() {
- createUI();
-
- if (mParent == null || mShell == null) {
- return false;
- }
-
- mShell.setMinimumSize(DLG_WIDTH, DLG_HEIGHT);
- Rectangle r = mParent.getBounds();
- // get the center new top left.
- int cx = r.x + r.width/2;
- int x = cx - DLG_WIDTH / 2;
- int cy = r.y + r.height/2;
- int y = cy - DLG_HEIGHT / 2;
- mShell.setBounds(x, y, DLG_WIDTH, DLG_HEIGHT);
-
- mShell.open();
-
- Display display = mParent.getDisplay();
- while (!mShell.isDisposed()) {
- if (!display.readAndDispatch())
- display.sleep();
- }
-
- return mOk;
- }
-
- public String getDeviceSN() {
- return mDeviceSn;
- }
-
- public String getAppName() {
- return mAppName;
- }
-
- public int getPortNumber() {
- return Integer.valueOf(mPortNumber);
- }
-
- private void createUI() {
- mParent = getParent();
- mShell = new Shell(mParent, getStyle());
- mShell.setText("Static Port");
-
- mShell.setLayout(new GridLayout(1, false));
-
- mShell.addListener(SWT.Close, new Listener() {
- @Override
- public void handleEvent(Event event) {
- }
- });
-
- // center part with the edit field
- Composite main = new Composite(mShell, SWT.NONE);
- main.setLayoutData(new GridData(GridData.FILL_BOTH));
- main.setLayout(new GridLayout(2, false));
-
- Label l0 = new Label(main, SWT.NONE);
- l0.setText("Device Name:");
-
- final Text deviceSNText = new Text(main, SWT.SINGLE | SWT.BORDER);
- deviceSNText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- if (mDeviceSn != null) {
- deviceSNText.setText(mDeviceSn);
- }
- deviceSNText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- mDeviceSn = deviceSNText.getText().trim();
- validate();
- }
- });
-
- Label l = new Label(main, SWT.NONE);
- l.setText("Application Name:");
-
- final Text appNameText = new Text(main, SWT.SINGLE | SWT.BORDER);
- if (mAppName != null) {
- appNameText.setText(mAppName);
- }
- appNameText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- appNameText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- mAppName = appNameText.getText().trim();
- validate();
- }
- });
-
- Label l2 = new Label(main, SWT.NONE);
- l2.setText("Debug Port:");
-
- final Text debugPortText = new Text(main, SWT.SINGLE | SWT.BORDER);
- if (mPortNumber != null) {
- debugPortText.setText(mPortNumber);
- }
- debugPortText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- debugPortText.addModifyListener(new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- mPortNumber = debugPortText.getText().trim();
- validate();
- }
- });
-
- // warning label
- Composite warningComp = new Composite(mShell, SWT.NONE);
- warningComp.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
- warningComp.setLayout(new GridLayout(1, true));
-
- mWarning = new Label(warningComp, SWT.NONE);
- mWarning.setText("");
- mWarning.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- // bottom part with the ok/cancel
- Composite bottomComp = new Composite(mShell, SWT.NONE);
- bottomComp
- .setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_CENTER));
- bottomComp.setLayout(new GridLayout(2, true));
-
- mOkButton = new Button(bottomComp, SWT.NONE);
- mOkButton.setText("OK");
- mOkButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- mOk = true;
- mShell.close();
- }
- });
- mOkButton.setEnabled(false);
- mShell.setDefaultButton(mOkButton);
-
- Button cancelButton = new Button(bottomComp, SWT.NONE);
- cancelButton.setText("Cancel");
- cancelButton.addSelectionListener(new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- mShell.close();
- }
- });
-
- validate();
- }
-
- /**
- * Validates the content of the 2 text fields and enable/disable "ok", while
- * setting up the warning/error message.
- */
- private void validate() {
- // first we reset the warning dialog. This allows us to latter
- // display warnings.
- mWarning.setText(""); //$NON-NLS-1$
-
- // check the device name field is not empty
- if (mDeviceSn == null || mDeviceSn.length() == 0) {
- mWarning.setText("Device name missing.");
- mOkButton.setEnabled(false);
- return;
- }
-
- // check the application name field is not empty
- if (mAppName == null || mAppName.length() == 0) {
- mWarning.setText("Application name missing.");
- mOkButton.setEnabled(false);
- return;
- }
-
- String packageError = "Application name must be a valid Java package name.";
-
- // validate the package name as well. It must be a fully qualified
- // java package.
- String[] packageSegments = mAppName.split("\\."); //$NON-NLS-1$
- for (String p : packageSegments) {
- if (p.matches("^[a-zA-Z][a-zA-Z0-9]*") == false) { //$NON-NLS-1$
- mWarning.setText(packageError);
- mOkButton.setEnabled(false);
- return;
- }
-
- // lets also display a warning if the package contains upper case
- // letters.
- if (p.matches("^[a-z][a-z0-9]*") == false) { //$NON-NLS-1$
- mWarning.setText("Lower case is recommended for Java packages.");
- }
- }
-
- // the split will not detect the last char being a '.'
- // so we test it manually
- if (mAppName.charAt(mAppName.length()-1) == '.') {
- mWarning.setText(packageError);
- mOkButton.setEnabled(false);
- return;
- }
-
- // now we test the package name field is not empty.
- if (mPortNumber == null || mPortNumber.length() == 0) {
- mWarning.setText("Port Number missing.");
- mOkButton.setEnabled(false);
- return;
- }
-
- // then we check it only contains digits.
- if (mPortNumber.matches("[0-9]*") == false) { //$NON-NLS-1$
- mWarning.setText("Port Number invalid.");
- mOkButton.setEnabled(false);
- return;
- }
-
- // get the int from the port number to validate
- long port = Long.valueOf(mPortNumber);
- if (port >= 32767) {
- mOkButton.setEnabled(false);
- return;
- }
-
- // check if its in the list of already used ports
- if (port != mEditPort) {
- for (Integer i : mPorts) {
- if (port == i.intValue()) {
- mWarning.setText("Port already in use.");
- mOkButton.setEnabled(false);
- return;
- }
- }
- }
-
- // at this point there's not error, so we enable the ok button.
- mOkButton.setEnabled(true);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/handlers/StaticPortConfigHandler.java b/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/handlers/StaticPortConfigHandler.java
deleted file mode 100644
index ff63aca2f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.monitor/src/com/android/ide/eclipse/monitor/handlers/StaticPortConfigHandler.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.monitor.handlers;
-
-import com.android.ide.eclipse.monitor.ddms.StaticPortConfigDialog;
-
-import org.eclipse.core.commands.AbstractHandler;
-import org.eclipse.core.commands.ExecutionEvent;
-import org.eclipse.core.commands.ExecutionException;
-import org.eclipse.ui.handlers.HandlerUtil;
-
-public class StaticPortConfigHandler extends AbstractHandler {
- @Override
- public Object execute(ExecutionEvent event) throws ExecutionException {
- StaticPortConfigDialog dlg = new StaticPortConfigDialog(HandlerUtil.getActiveShell(event));
- dlg.open();
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/.classpath b/eclipse/plugins/com.android.ide.eclipse.ndk/.classpath
deleted file mode 100644
index 36a1bdaec..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/.classpath
+++ /dev/null
@@ -1,10 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry kind="src" path="src"/>
- <classpathentry kind="output" path="bin"/>
- <classpathentry combineaccessrules="false" kind="src" path="/ddmlib"/>
- <classpathentry combineaccessrules="false" kind="src" path="/ddmuilib"/>
- <classpathentry combineaccessrules="false" kind="src" path="/sdklib"/>
-</classpath>
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/.project b/eclipse/plugins/com.android.ide.eclipse.ndk/.project
deleted file mode 100644
index 416aa2edc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/.project
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>plugin-ndk</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/.settings/org.eclipse.jdt.core.prefs b/eclipse/plugins/com.android.ide.eclipse.ndk/.settings/org.eclipse.jdt.core.prefs
deleted file mode 100644
index ea661960a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/.settings/org.eclipse.jdt.core.prefs
+++ /dev/null
@@ -1,98 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore
-org.eclipse.jdt.core.compiler.annotation.nonnull=com.android.annotations.NonNull
-org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=com.android.annotations.NonNullByDefault
-org.eclipse.jdt.core.compiler.annotation.nonnullisdefault=disabled
-org.eclipse.jdt.core.compiler.annotation.nullable=com.android.annotations.Nullable
-org.eclipse.jdt.core.compiler.annotation.nullanalysis=enabled
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
-org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
-org.eclipse.jdt.core.compiler.compliance=1.6
-org.eclipse.jdt.core.compiler.debug.lineNumber=generate
-org.eclipse.jdt.core.compiler.debug.localVariable=generate
-org.eclipse.jdt.core.compiler.debug.sourceFile=generate
-org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
-org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
-org.eclipse.jdt.core.compiler.problem.deadCode=warning
-org.eclipse.jdt.core.compiler.problem.deprecation=warning
-org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
-org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
-org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
-org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore
-org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning
-org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled
-org.eclipse.jdt.core.compiler.problem.fieldHiding=warning
-org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
-org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
-org.eclipse.jdt.core.compiler.problem.forbiddenReference=error
-org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
-org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=enabled
-org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
-org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning
-org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
-org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning
-org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
-org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore
-org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled
-org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=warning
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=error
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
-org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
-org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
-org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
-org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
-org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
-org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=warning
-org.eclipse.jdt.core.compiler.problem.nullReference=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecInsufficientInfo=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecViolation=warning
-org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=ignore
-org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
-org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
-org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullSpecViolation=error
-org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=warning
-org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=warning
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
-org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
-org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
-org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=enabled
-org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
-org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
-org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning
-org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=disabled
-org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
-org.eclipse.jdt.core.compiler.problem.unclosedCloseable=error
-org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
-org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
-org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning
-org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
-org.eclipse.jdt.core.compiler.problem.unusedImport=warning
-org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
-org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
-org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=warning
-org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
-org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
-org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
-org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
-org.eclipse.jdt.core.compiler.source=1.6
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/META-INF/MANIFEST.MF b/eclipse/plugins/com.android.ide.eclipse.ndk/META-INF/MANIFEST.MF
deleted file mode 100644
index df1e88c78..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,28 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: ADT CDT Integration
-Bundle-SymbolicName: com.android.ide.eclipse.ndk;singleton:=true
-Bundle-Version: 24.3.3.qualifier
-Bundle-Activator: com.android.ide.eclipse.ndk.internal.Activator
-Bundle-Vendor: The Android Open Source Project
-Require-Bundle: org.eclipse.core.runtime,
- org.eclipse.core.resources,
- org.eclipse.core.variables,
- org.eclipse.ui,
- org.eclipse.debug.core,
- org.eclipse.debug.ui,
- org.eclipse.cdt.core,
- org.eclipse.cdt.ui,
- org.eclipse.cdt.managedbuilder.core,
- org.eclipse.cdt.managedbuilder.ui,
- org.eclipse.cdt.debug.core,
- org.eclipse.cdt.debug.ui,
- org.eclipse.cdt.dsf,
- org.eclipse.cdt.dsf.gdb,
- org.eclipse.cdt.dsf.gdb.ui,
- org.eclipse.cdt.launch,
- com.android.ide.eclipse.adt,
- com.android.ide.eclipse.base,
- com.android.ide.eclipse.ddms
-Bundle-ActivationPolicy: lazy
-Bundle-ClassPath: .
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/MODULE_LICENSE_EPL b/eclipse/plugins/com.android.ide.eclipse.ndk/MODULE_LICENSE_EPL
deleted file mode 100644
index e69de29bb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/MODULE_LICENSE_EPL
+++ /dev/null
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/NOTICE b/eclipse/plugins/com.android.ide.eclipse.ndk/NOTICE
deleted file mode 100644
index 49c101df7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/NOTICE
+++ /dev/null
@@ -1,224 +0,0 @@
-*Eclipse Public License - v 1.0*
-
-THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE
-PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF
-THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
-
-*1. DEFINITIONS*
-
-"Contribution" means:
-
-a) in the case of the initial Contributor, the initial code and
-documentation distributed under this Agreement, and
-b) in the case of each subsequent Contributor:
-
-i) changes to the Program, and
-
-ii) additions to the Program;
-
-where such changes and/or additions to the Program originate from and
-are distributed by that particular Contributor. A Contribution
-'originates' from a Contributor if it was added to the Program by such
-Contributor itself or anyone acting on such Contributor's behalf.
-Contributions do not include additions to the Program which: (i) are
-separate modules of software distributed in conjunction with the Program
-under their own license agreement, and (ii) are not derivative works of
-the Program.
-
-"Contributor" means any person or entity that distributes the Program.
-
-"Licensed Patents " mean patent claims licensable by a Contributor which
-are necessarily infringed by the use or sale of its Contribution alone
-or when combined with the Program.
-
-"Program" means the Contributions distributed in accordance with this
-Agreement.
-
-"Recipient" means anyone who receives the Program under this Agreement,
-including all Contributors.
-
-*2. GRANT OF RIGHTS*
-
-a) Subject to the terms of this Agreement, each Contributor hereby
-grants Recipient a non-exclusive, worldwide, royalty-free copyright
-license to reproduce, prepare derivative works of, publicly display,
-publicly perform, distribute and sublicense the Contribution of such
-Contributor, if any, and such derivative works, in source code and
-object code form.
-
-b) Subject to the terms of this Agreement, each Contributor hereby
-grants Recipient a non-exclusive, worldwide, royalty-free patent license
-under Licensed Patents to make, use, sell, offer to sell, import and
-otherwise transfer the Contribution of such Contributor, if any, in
-source code and object code form. This patent license shall apply to the
-combination of the Contribution and the Program if, at the time the
-Contribution is added by the Contributor, such addition of the
-Contribution causes such combination to be covered by the Licensed
-Patents. The patent license shall not apply to any other combinations
-which include the Contribution. No hardware per se is licensed hereunder.
-
-c) Recipient understands that although each Contributor grants the
-licenses to its Contributions set forth herein, no assurances are
-provided by any Contributor that the Program does not infringe the
-patent or other intellectual property rights of any other entity. Each
-Contributor disclaims any liability to Recipient for claims brought by
-any other entity based on infringement of intellectual property rights
-or otherwise. As a condition to exercising the rights and licenses
-granted hereunder, each Recipient hereby assumes sole responsibility to
-secure any other intellectual property rights needed, if any. For
-example, if a third party patent license is required to allow Recipient
-to distribute the Program, it is Recipient's responsibility to acquire
-that license before distributing the Program.
-
-d) Each Contributor represents that to its knowledge it has sufficient
-copyright rights in its Contribution, if any, to grant the copyright
-license set forth in this Agreement.
-
-*3. REQUIREMENTS*
-
-A Contributor may choose to distribute the Program in object code form
-under its own license agreement, provided that:
-
-a) it complies with the terms and conditions of this Agreement; and
-
-b) its license agreement:
-
-i) effectively disclaims on behalf of all Contributors all warranties
-and conditions, express and implied, including warranties or conditions
-of title and non-infringement, and implied warranties or conditions of
-merchantability and fitness for a particular purpose;
-
-ii) effectively excludes on behalf of all Contributors all liability for
-damages, including direct, indirect, special, incidental and
-consequential damages, such as lost profits;
-
-iii) states that any provisions which differ from this Agreement are
-offered by that Contributor alone and not by any other party; and
-
-iv) states that source code for the Program is available from such
-Contributor, and informs licensees how to obtain it in a reasonable
-manner on or through a medium customarily used for software exchange.
-
-When the Program is made available in source code form:
-
-a) it must be made available under this Agreement; and
-
-b) a copy of this Agreement must be included with each copy of the Program.
-
-Contributors may not remove or alter any copyright notices contained
-within the Program.
-
-Each Contributor must identify itself as the originator of its
-Contribution, if any, in a manner that reasonably allows subsequent
-Recipients to identify the originator of the Contribution.
-
-*4. COMMERCIAL DISTRIBUTION*
-
-Commercial distributors of software may accept certain responsibilities
-with respect to end users, business partners and the like. While this
-license is intended to facilitate the commercial use of the Program, the
-Contributor who includes the Program in a commercial product offering
-should do so in a manner which does not create potential liability for
-other Contributors. Therefore, if a Contributor includes the Program in
-a commercial product offering, such Contributor ("Commercial
-Contributor") hereby agrees to defend and indemnify every other
-Contributor ("Indemnified Contributor") against any losses, damages and
-costs (collectively "Losses") arising from claims, lawsuits and other
-legal actions brought by a third party against the Indemnified
-Contributor to the extent caused by the acts or omissions of such
-Commercial Contributor in connection with its distribution of the
-Program in a commercial product offering. The obligations in this
-section do not apply to any claims or Losses relating to any actual or
-alleged intellectual property infringement. In order to qualify, an
-Indemnified Contributor must: a) promptly notify the Commercial
-Contributor in writing of such claim, and b) allow the Commercial
-Contributor to control, and cooperate with the Commercial Contributor
-in, the defense and any related settlement negotiations. The Indemnified
-Contributor may participate in any such claim at its own expense.
-
-For example, a Contributor might include the Program in a commercial
-product offering, Product X. That Contributor is then a Commercial
-Contributor. If that Commercial Contributor then makes performance
-claims, or offers warranties related to Product X, those performance
-claims and warranties are such Commercial Contributor's responsibility
-alone. Under this section, the Commercial Contributor would have to
-defend claims against the other Contributors related to those
-performance claims and warranties, and if a court requires any other
-Contributor to pay any damages as a result, the Commercial Contributor
-must pay those damages.
-
-*5. NO WARRANTY*
-
-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED
-ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
-EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES
-OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR
-A PARTICULAR PURPOSE. Each Recipient is solely responsible for
-determining the appropriateness of using and distributing the Program
-and assumes all risks associated with its exercise of rights under this
-Agreement , including but not limited to the risks and costs of program
-errors, compliance with applicable laws, damage to or loss of data,
-programs or equipment, and unavailability or interruption of operations.
-
-*6. DISCLAIMER OF LIABILITY*
-
-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR
-ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT,
-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING
-WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF
-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR
-DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
-HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-
-*7. GENERAL*
-
-If any provision of this Agreement is invalid or unenforceable under
-applicable law, it shall not affect the validity or enforceability of
-the remainder of the terms of this Agreement, and without further action
-by the parties hereto, such provision shall be reformed to the minimum
-extent necessary to make such provision valid and enforceable.
-
-If Recipient institutes patent litigation against any entity (including
-a cross-claim or counterclaim in a lawsuit) alleging that the Program
-itself (excluding combinations of the Program with other software or
-hardware) infringes such Recipient's patent(s), then such Recipient's
-rights granted under Section 2(b) shall terminate as of the date such
-litigation is filed.
-
-All Recipient's rights under this Agreement shall terminate if it fails
-to comply with any of the material terms or conditions of this Agreement
-and does not cure such failure in a reasonable period of time after
-becoming aware of such noncompliance. If all Recipient's rights under
-this Agreement terminate, Recipient agrees to cease use and distribution
-of the Program as soon as reasonably practicable. However, Recipient's
-obligations under this Agreement and any licenses granted by Recipient
-relating to the Program shall continue and survive.
-
-Everyone is permitted to copy and distribute copies of this Agreement,
-but in order to avoid inconsistency the Agreement is copyrighted and may
-only be modified in the following manner. The Agreement Steward reserves
-the right to publish new versions (including revisions) of this
-Agreement from time to time. No one other than the Agreement Steward has
-the right to modify this Agreement. The Eclipse Foundation is the
-initial Agreement Steward. The Eclipse Foundation may assign the
-responsibility to serve as the Agreement Steward to a suitable separate
-entity. Each new version of the Agreement will be given a distinguishing
-version number. The Program (including Contributions) may always be
-distributed subject to the version of the Agreement under which it was
-received. In addition, after a new version of the Agreement is
-published, Contributor may elect to distribute the Program (including
-its Contributions) under the new version. Except as expressly stated in
-Sections 2(a) and 2(b) above, Recipient receives no rights or licenses
-to the intellectual property of any Contributor under this Agreement,
-whether expressly, by implication, estoppel or otherwise. All rights in
-the Program not expressly granted under this Agreement are reserved.
-
-This Agreement is governed by the laws of the State of New York and the
-intellectual property laws of the United States of America. No party to
-this Agreement will bring a legal action under this Agreement more than
-one year after the cause of action arose. Each party waives its rights
-to a jury trial in any resulting litigation.
-
-
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/about.html b/eclipse/plugins/com.android.ide.eclipse.ndk/about.html
deleted file mode 100644
index bc621cb3e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/about.html
+++ /dev/null
@@ -1,106 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
-<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
-<title>About</title>
-</head>
-<body lang="EN-US">
-<h2>About This Content</h2>
-
-<p>September 19, 2010</p>
-<h3>License</h3>
-
-<pre>
- Eclipse Public License - v 1.0
-
-THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE (&quot;AGREEMENT&quot;). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT&apos;S ACCEPTANCE OF THIS AGREEMENT.
-
-1. DEFINITIONS
-
-&quot;Contribution&quot; means:
-
-a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and
-
-b) in the case of each subsequent Contributor:
-
-i) changes to the Program, and
-
-ii) additions to the Program;
-
-where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution &apos;originates&apos; from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor&apos;s behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program.
-
-&quot;Contributor&quot; means any person or entity that distributes the Program.
-
-&quot;Licensed Patents&quot; mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program.
-
-&quot;Program&quot; means the Contributions distributed in accordance with this Agreement.
-
-&quot;Recipient&quot; means anyone who receives the Program under this Agreement, including all Contributors.
-
-2. GRANT OF RIGHTS
-
-a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form.
-
-b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder.
-
-c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient&apos;s responsibility to acquire that license before distributing the Program.
-
-d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement.
-
-3. REQUIREMENTS
-
-A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that:
-
-a) it complies with the terms and conditions of this Agreement; and
-
-b) its license agreement:
-
-i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose;
-
-ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits;
-
-iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and
-
-iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange.
-
-When the Program is made available in source code form:
-
-a) it must be made available under this Agreement; and
-
-b) a copy of this Agreement must be included with each copy of the Program.
-
-Contributors may not remove or alter any copyright notices contained within the Program.
-
-Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution.
-
-4. COMMERCIAL DISTRIBUTION
-
-Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor (&quot;Commercial Contributor&quot;) hereby agrees to defend and indemnify every other Contributor (&quot;Indemnified Contributor&quot;) against any losses, damages and costs (collectively &quot;Losses&quot;) arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense.
-
-For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor&apos;s responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages.
-
-5. NO WARRANTY
-
-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN &quot;AS IS&quot; BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations.
-
-6. DISCLAIMER OF LIABILITY
-
-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-
-7. GENERAL
-
-If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
-
-If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient&apos;s patent(s), then such Recipient&apos;s rights granted under Section 2(b) shall terminate as of the date such litigation is filed.
-
-All Recipient&apos;s rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient&apos;s rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient&apos;s obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive.
-
-Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved.
-
-This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation.
-
-</pre>
-
-</body>
-</html>
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/about.ini b/eclipse/plugins/com.android.ide.eclipse.ndk/about.ini
deleted file mode 100644
index 2d7cdaad6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/about.ini
+++ /dev/null
@@ -1,2 +0,0 @@
-aboutText=%blurb
-featureImage=icons/android-32.png \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/about.properties b/eclipse/plugins/com.android.ide.eclipse.ndk/about.properties
deleted file mode 100755
index 34218e997..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/about.properties
+++ /dev/null
@@ -1,7 +0,0 @@
-blurb=Android Development Toolkit\n\
-\n\
-Version\: {featureVersion}\n\
-\n\
-(c) Copyright 2007-2011 The Android Open Source Project. All rights reserved.\n\
-Visit http://developer.android.com/sdk/eclipse-adt.html
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/build.properties b/eclipse/plugins/com.android.ide.eclipse.ndk/build.properties
deleted file mode 100644
index 4842ac1c7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/build.properties
+++ /dev/null
@@ -1,12 +0,0 @@
-source.. = src/
-output.. = bin/
-bin.includes = META-INF/,\
- .,\
- plugin.xml,\
- icons/,\
- templates/,\
- discovery/,\
- NOTICE,\
- about.html,\
- about.ini,\
- about.properties
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/discovery/test.c b/eclipse/plugins/com.android.ide.eclipse.ndk/discovery/test.c
deleted file mode 100644
index e69de29bb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/discovery/test.c
+++ /dev/null
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/discovery/test.cpp b/eclipse/plugins/com.android.ide.eclipse.ndk/discovery/test.cpp
deleted file mode 100644
index e69de29bb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/discovery/test.cpp
+++ /dev/null
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/icons/android-32.png b/eclipse/plugins/com.android.ide.eclipse.ndk/icons/android-32.png
deleted file mode 100644
index 4e0cc138d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/icons/android-32.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/icons/android_app.png b/eclipse/plugins/com.android.ide.eclipse.ndk/icons/android_app.png
deleted file mode 100644
index 8ca377009..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/icons/android_app.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/icons/obj16/c_app.gif b/eclipse/plugins/com.android.ide.eclipse.ndk/icons/obj16/c_app.gif
deleted file mode 100644
index 504ef509f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/icons/obj16/c_app.gif
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/icons/view16/debugger_tab.gif b/eclipse/plugins/com.android.ide.eclipse.ndk/icons/view16/debugger_tab.gif
deleted file mode 100644
index d90a29fea..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/icons/view16/debugger_tab.gif
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/icons/view16/startup_tab.gif b/eclipse/plugins/com.android.ide.eclipse.ndk/icons/view16/startup_tab.gif
deleted file mode 100644
index 7b3a92e09..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/icons/view16/startup_tab.gif
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/plugin.xml b/eclipse/plugins/com.android.ide.eclipse.ndk/plugin.xml
deleted file mode 100644
index 93e9bc440..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/plugin.xml
+++ /dev/null
@@ -1,208 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<?eclipse version="3.4"?>
-<plugin>
- <extension
- point="org.eclipse.cdt.managedbuilder.core.buildDefinitions">
- <managedBuildRevision
- fileVersion="4.0.0">
- </managedBuildRevision>
- <toolChain
- configurationEnvironmentSupplier="com.android.ide.eclipse.ndk.internal.build.NdkEnvSupplier"
- id="com.android.toolchain.gcc"
- isAbstract="false"
- name="Android GCC">
- <targetPlatform
- binaryParser="org.eclipse.cdt.core.ELF"
- id="com.android.targetPlatform"
- isAbstract="false">
- </targetPlatform>
- <builder
- cleanBuildTarget="clean"
- command="ndk-build"
- commandLauncher="com.android.ide.eclipse.ndk.internal.build.NdkCommandLauncher"
- id="com.android.builder"
- isAbstract="false"
- isVariableCaseSensitive="false"
- name="Android Builder">
- </builder>
- <tool
- id="com.android.gcc.compiler"
- isAbstract="false"
- name="Android GCC Compiler"
- natureFilter="both">
- <option
- browseType="directory"
- id="com.android.gcc.option.includePath"
- isAbstract="false"
- resourceFilter="all"
- valueType="includePath">
- </option>
- <inputType
- id="com.android.gcc.inputType"
- scannerConfigDiscoveryProfileId="com.android.AndroidPerProjectProfile"
- sources="c,cpp">
- </inputType>
- </tool>
- </toolChain>
- </extension>
- <extension
- id="com.android.AndroidPerProjectProfile"
- name="Android Per Project Profile"
- point="org.eclipse.cdt.make.core.ScannerConfigurationDiscoveryProfile">
- <scannerInfoCollector
- class="com.android.ide.eclipse.ndk.internal.discovery.NdkScannerInfoCollector"
- scope="project">
- </scannerInfoCollector>
- </extension>
- <extension
- point="org.eclipse.cdt.core.templateProcessTypes">
- <processType
- name="SetFolders"
- processRunner="com.android.ide.eclipse.ndk.internal.templates.SetFolders">
- <simple
- name="projectName">
- </simple>
- <simpleArray
- name="sourceFolders">
- </simpleArray>
- <simpleArray
- name="outputFolders">
- </simpleArray>
- </processType>
- <processType
- name="SimpleFile"
- processRunner="com.android.ide.eclipse.ndk.internal.templates.SimpleFile">
- <simple
- name="projectName">
- </simple>
- <complexArray
- name="files">
- <baseType>
- <simple
- name="source">
- </simple>
- <simple
- name="destination">
- </simple></baseType>
- </complexArray>
- </processType>
- </extension>
- <extension
- point="org.eclipse.cdt.core.templates">
- <template
- id="com.android.ide.eclipse.ndk.addNdkSupport"
- location="templates/addNdkSupport.xml"
- projectType="none">
- </template>
- </extension>
- <extension
- point="org.eclipse.ui.preferencePages">
- <page
- category="com.android.ide.eclipse.preferences.main"
- class="com.android.ide.eclipse.ndk.internal.preferences.NdkPreferencePage"
- id="org.eclipse.cdt.android.page"
- name="NDK">
- </page>
- </extension>
- <extension
- point="org.eclipse.ui.popupMenus">
- <objectContribution
- adaptable="true"
- id="com.android.ide.eclipse.ndk.projectContribution"
- objectClass="org.eclipse.core.resources.IProject">
- <visibility>
- <and>
- <objectState
- name="projectNature"
- value="com.android.ide.eclipse.adt.AndroidNature">
- </objectState>
- <not>
- <objectState
- name="projectNature"
- value="org.eclipse.cdt.core.cnature">
- </objectState>
- </not>
- </and>
- </visibility>
- <action
- class="com.android.ide.eclipse.ndk.internal.actions.AddNativeAction"
- enablesFor="1"
- id="org.eclipse.cdt.android.action1"
- label="Add Native Support..."
- menubarPath="com.android.ide.eclipse.adt.AndroidTools/ndk">
- </action>
- </objectContribution>
- </extension>
- <extension
- point="org.eclipse.core.runtime.preferences">
- <initializer
- class="com.android.ide.eclipse.ndk.internal.preferences.NdkPreferenceInitializer">
- </initializer>
- </extension>
- <extension
- point="org.eclipse.debug.core.launchConfigurationTypes">
- <launchConfigurationType
- delegate="com.android.ide.eclipse.ndk.internal.launch.NdkGdbLaunchDelegate"
- delegateName="Android ndk-gdb Launcher"
- id="com.android.ide.eclipse.ndk.debug.LaunchConfigType"
- modes="debug"
- name="Android Native Application"
- public="true"
- sourceLocatorId="org.eclipse.cdt.debug.core.sourceLocator"
- sourcePathComputerId="org.eclipse.cdt.debug.core.sourcePathComputer">
- </launchConfigurationType>
- </extension>
- <extension
- point="org.eclipse.debug.ui.launchConfigurationTypeImages">
- <launchConfigurationTypeImage
- configTypeID="com.android.ide.eclipse.ndk.debug.LaunchConfigType"
- icon="icons/android_app.png"
- id="com.android.ide.eclipse.ndk.debug.LaunchConfigTypeImage">
- </launchConfigurationTypeImage>
- </extension>
- <extension
- point="org.eclipse.debug.ui.launchConfigurationTabGroups">
- <launchConfigurationTabGroup
- class="com.android.ide.eclipse.ndk.internal.launch.NdkGdbLaunchConfigTabGroups"
- description="Android Native Application"
- id="com.android.ide.eclipse.ndk.debug.LaunchConfigTabGroup"
- type="com.android.ide.eclipse.ndk.debug.LaunchConfigType">
- </launchConfigurationTabGroup>
- </extension>
- <extension
- point="org.eclipse.debug.ui.launchShortcuts">
- <shortcut
- class="com.android.ide.eclipse.ndk.internal.launch.NdkGdbLaunchShortcut"
- id="com.android.ide.eclipse.ndk.debug.LaunchConfigShortcut"
- label="Android Native Application"
- modes="debug">
- <contextualLaunch>
- <enablement>
- <with variable="selection">
- <count value="1" />
- <iterate>
- <and>
- <test property="org.eclipse.jdt.launching.isContainer" />
- <test
- property="org.eclipse.jdt.launching.hasProjectNature"
- args="com.android.ide.eclipse.adt.AndroidNature" />
- </and>
- </iterate>
- </with>
- </enablement>
- </contextualLaunch>
- <perspective id="org.eclipse.jdt.ui.JavaPerspective" />
- <perspective id="org.eclipse.debug.ui.DebugPerspective" />
- <perspective
- id="org.eclipse.cdt.ui.CPerspective">
- </perspective>
- <configurationType id="com.android.ide.eclipse.ndk.debug.LaunchConfigType">
- </configurationType>
- <description
- description="Debug as Android Native Application"
- mode="debug">
- </description>
- </shortcut>
- </extension>
-
-</plugin>
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/pom.xml b/eclipse/plugins/com.android.ide.eclipse.ndk/pom.xml
deleted file mode 100644
index 53d9c47a0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/pom.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <version>24.3.3-SNAPSHOT</version>
- <artifactId>com.android.ide.eclipse.ndk</artifactId>
- <packaging>eclipse-plugin</packaging>
- <name>ndk</name>
-
- <parent>
- <relativePath>../../pom.xml</relativePath>
- <groupId>adt.group</groupId>
- <artifactId>parent</artifactId>
- <version>1.0.0-SNAPSHOT</version>
- </parent>
-</project>
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/Activator.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/Activator.java
deleted file mode 100644
index e165df1c5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/Activator.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal;
-
-import org.eclipse.core.runtime.FileLocator;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-
-import java.net.URL;
-
-/**
- * The activator class controls the plug-in life cycle
- */
-public class Activator extends AbstractUIPlugin {
-
- // The plug-in ID
- public static final String PLUGIN_ID = "com.android.ide.eclipse.ndk"; //$NON-NLS-1$
-
- // The shared instance
- private static Activator mPlugin;
-
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
- mPlugin = this;
- }
-
- @Override
- public void stop(BundleContext context) throws Exception {
- mPlugin = null;
- super.stop(context);
- }
-
- public static Activator getDefault() {
- return mPlugin;
- }
-
- public static <T> T getService(Class<T> clazz) {
- BundleContext context = mPlugin.getBundle().getBundleContext();
- ServiceReference ref = context.getServiceReference(clazz.getName());
- return (ref != null) ? (T) context.getService(ref) : null;
- }
-
- public static Bundle getBundle(String id) {
- for (Bundle bundle : mPlugin.getBundle().getBundleContext().getBundles()) {
- if (bundle.getSymbolicName().equals(id)) {
- return bundle;
- }
- }
- return null;
- }
-
- public static IStatus newStatus(Exception e) {
- return new Status(IStatus.ERROR, PLUGIN_ID, e.getMessage(), e);
- }
-
- public static void log(Exception e) {
- mPlugin.getLog().log(newStatus(e));
- }
-
- public static URL findFile(IPath path) {
- return FileLocator.find(mPlugin.getBundle(), path, null);
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/Messages.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/Messages.java
deleted file mode 100644
index cd6c4a31f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/Messages.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal;
-
-import org.eclipse.osgi.util.NLS;
-
-public class Messages extends NLS {
- private static final String BUNDLE_NAME = "com.android.ide.eclipse.ndk.internal.messages"; //$NON-NLS-1$
-
- public static String AddNativeWizardPage_Description;
-
- public static String AddNativeWizardPage_LibraryName;
-
- public static String AddNativeWizardPage_Location_not_valid;
-
- public static String AddNativeWizardPage_Title;
-
- public static String NDKPreferencePage_Location;
-
- public static String NDKPreferencePage_not_a_valid_directory;
-
- public static String NDKPreferencePage_not_a_valid_NDK_directory;
-
- public static String NDKPreferencePage_Preferences;
-
- public static String SetFolders_Missing_project_name;
-
- public static String SetFolders_No_folders;
-
- public static String SetFolders_Project_does_not_exist;
-
- public static String SimpleFile_Bad_file_operation;
-
- public static String SimpleFile_Bundle_not_found;
-
- public static String SimpleFile_Could_not_fine_source;
-
- public static String SimpleFile_No_project_name;
-
- public static String SimpleFile_Project_does_not_exist;
-
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
-
- private Messages() {
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/NativeAbi.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/NativeAbi.java
deleted file mode 100644
index 3c7654266..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/NativeAbi.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal;
-
-import com.android.SdkConstants;
-
-public enum NativeAbi {
- armeabi(SdkConstants.ABI_ARMEABI),
- armeabi_v7a(SdkConstants.ABI_ARMEABI_V7A),
- mips(SdkConstants.ABI_MIPS),
- x86(SdkConstants.ABI_INTEL_ATOM);
-
- private final String mAbi;
-
- private NativeAbi(String abi) {
- mAbi = abi;
- }
-
- public String getAbi() {
- return mAbi;
- }
-
- public static NativeAbi getByString(String abi) {
- for (NativeAbi a: values()) {
- if (a.getAbi().equals(abi)) {
- return a;
- }
- }
-
- throw new IllegalArgumentException("Unknown abi: " + abi);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/NdkHelper.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/NdkHelper.java
deleted file mode 100644
index 8ad1f24c4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/NdkHelper.java
+++ /dev/null
@@ -1,184 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.ndk.internal.launch.NdkLaunchConstants;
-
-import org.eclipse.cdt.core.CommandLauncher;
-import org.eclipse.cdt.core.ICommandLauncher;
-import org.eclipse.cdt.debug.core.ICDTLaunchConfigurationConstants;
-import org.eclipse.cdt.dsf.gdb.IGDBLaunchConfigurationConstants;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.EnumSet;
-import java.util.List;
-import java.util.Set;
-
-@SuppressWarnings("restriction")
-public class NdkHelper {
- private static final String MAKE = "make"; //$NON-NLS-1$
- private static final String CORE_MAKEFILE_PATH = "/build/core/build-local.mk"; //$NON-NLS-1$
-
- /**
- * Obtain the ABI's the application is compatible with.
- * The ABI's are obtained by reading the result of the following command:
- * make --no-print-dir -f ${NdkRoot}/build/core/build-local.mk -C <project-root> DUMP_APP_ABI
- */
- public static Collection<NativeAbi> getApplicationAbis(IProject project,
- IProgressMonitor monitor) {
- ICommandLauncher launcher = new CommandLauncher();
- launcher.setProject(project);
- String[] args = new String[] {
- "--no-print-dir", //$NON-NLS-1$
- "-f", //$NON-NLS-1$
- NdkManager.getNdkLocation() + CORE_MAKEFILE_PATH,
- "-C", //$NON-NLS-1$
- project.getLocation().toOSString(),
- "DUMP_APP_ABI", //$NON-NLS-1$
- };
- try {
- launcher.execute(getPathToMake(), args, null, project.getLocation(), monitor);
- } catch (CoreException e) {
- AdtPlugin.printErrorToConsole(e.getLocalizedMessage());
- return Collections.emptyList();
- }
-
- ByteArrayOutputStream stdout = new ByteArrayOutputStream();
- ByteArrayOutputStream stderr = new ByteArrayOutputStream();
- launcher.waitAndRead(stdout, stderr, monitor);
-
- String abis = stdout.toString().trim();
- Set<NativeAbi> nativeAbis = EnumSet.noneOf(NativeAbi.class);
- for (String abi: abis.split(" ")) { //$NON-NLS-1$
- if (abi.equals("all")) { //$NON-NLS-1$
- return EnumSet.allOf(NativeAbi.class);
- }
-
- try {
- nativeAbis.add(NativeAbi.getByString(abi));
- } catch (IllegalArgumentException e) {
- AdtPlugin.printErrorToConsole(project, "Unknown Application ABI: ", abi);
- }
- }
-
- return nativeAbis;
- }
-
- /**
- * Obtain the toolchain prefix to use for given project and abi.
- * The prefix is obtained by reading the result of:
- * make --no-print-dir -f ${NdkRoot}/build/core/build-local.mk \
- * -C <project-root> \
- * DUMP_TOOLCHAIN_PREFIX APP_ABI=abi
- */
- public static String getToolchainPrefix(IProject project, NativeAbi abi,
- IProgressMonitor monitor) {
- ICommandLauncher launcher = new CommandLauncher();
- launcher.setProject(project);
- String[] args = new String[] {
- "--no-print-dir", //$NON-NLS-1$
- "-f", //$NON-NLS-1$
- NdkManager.getNdkLocation() + CORE_MAKEFILE_PATH,
- "-C", //$NON-NLS-1$
- project.getLocation().toOSString(),
- "DUMP_TOOLCHAIN_PREFIX", //$NON-NLS-1$
- "APP_ABI=" + abi.getAbi(), //$NON-NLS-1$
- };
- try {
- launcher.execute(getPathToMake(), args, null, project.getLocation(), monitor);
- } catch (CoreException e) {
- AdtPlugin.printErrorToConsole(e.getLocalizedMessage());
- return null;
- }
-
- ByteArrayOutputStream stdout = new ByteArrayOutputStream();
- ByteArrayOutputStream stderr = new ByteArrayOutputStream();
- launcher.waitAndRead(stdout, stderr, monitor);
- return stdout.toString().trim();
- }
-
- private static IPath getPathToMake() {
- return getFullPathTo(MAKE);
- }
-
- /**
- * Obtain a path to the utilities prebuilt folder in NDK. This is typically
- * "${NdkRoot}/prebuilt/<platform>/bin/". If the executable is not found, it simply returns
- * the name of the executable (which is equal to assuming that it is available on the path).
- */
- private static synchronized IPath getFullPathTo(String executable) {
- if (Platform.getOS().equals(Platform.OS_WIN32)) {
- executable += ".exe";
- }
-
- IPath ndkRoot = new Path(NdkManager.getNdkLocation());
- IPath prebuilt = ndkRoot.append("prebuilt"); //$NON-NLS-1$
- if (!prebuilt.toFile().exists() || !prebuilt.toFile().canRead()) {
- return new Path(executable);
- }
-
- File[] platforms = prebuilt.toFile().listFiles();
- if (platforms != null) {
- for (File p: platforms) {
- IPath exePath = prebuilt.append(p.getName())
- .append("bin") //$NON-NLS-1$
- .append(executable);
- if (exePath.toFile().exists()) {
- return exePath;
- }
- }
- }
-
- return new Path(executable);
- }
-
- public static void setLaunchConfigDefaults(ILaunchConfigurationWorkingCopy config) {
- config.setAttribute(IGDBLaunchConfigurationConstants.ATTR_REMOTE_TCP, true);
- config.setAttribute(NdkLaunchConstants.ATTR_NDK_GDB, NdkLaunchConstants.DEFAULT_GDB);
- config.setAttribute(IGDBLaunchConfigurationConstants.ATTR_GDB_INIT,
- NdkLaunchConstants.DEFAULT_GDBINIT);
- config.setAttribute(IGDBLaunchConfigurationConstants.ATTR_PORT,
- NdkLaunchConstants.DEFAULT_GDB_PORT);
- config.setAttribute(IGDBLaunchConfigurationConstants.ATTR_HOST, "localhost"); //$NON-NLS-1$
- config.setAttribute(ICDTLaunchConfigurationConstants.ATTR_DEBUGGER_STOP_AT_MAIN, false);
- config.setAttribute(ICDTLaunchConfigurationConstants.ATTR_DEBUGGER_START_MODE,
- IGDBLaunchConfigurationConstants.DEBUGGER_MODE_REMOTE_ATTACH);
- config.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME,
- NdkLaunchConstants.DEFAULT_PROGRAM);
-
- config.setAttribute(ICDTLaunchConfigurationConstants.ATTR_DEBUGGER_START_MODE,
- IGDBLaunchConfigurationConstants.DEBUGGER_MODE_REMOTE);
- config.setAttribute(ICDTLaunchConfigurationConstants.ATTR_DEBUGGER_ID,
- "gdbserver"); //$NON-NLS-1$
-
- List<String> solibPaths = new ArrayList<String>(2);
- solibPaths.add(NdkLaunchConstants.DEFAULT_SOLIB_PATH);
- config.setAttribute(NdkLaunchConstants.ATTR_NDK_SOLIB, solibPaths);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/NdkManager.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/NdkManager.java
deleted file mode 100644
index 98fccff02..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/NdkManager.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- * Copyright (C) 2010, 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal;
-
-import org.eclipse.cdt.core.templateengine.TemplateCore;
-import org.eclipse.cdt.core.templateengine.TemplateEngine;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.SubProgressMonitor;
-
-import java.io.File;
-import java.util.Map;
-
-public class NdkManager {
-
- public static final String NDK_LOCATION = "ndkLocation"; //$NON-NLS-1$
-
- public static final String LIBRARY_NAME = "libraryName"; //$NON-NLS-1$
-
- public static String getNdkLocation() {
- return Activator.getDefault().getPreferenceStore().getString(NDK_LOCATION);
- }
-
- public static boolean isNdkLocationValid() {
- String location = getNdkLocation();
- if (location.length() == 0)
- return false;
-
- return isValidNdkLocation(location);
- }
-
- public static boolean isValidNdkLocation(String location) {
- File dir = new File(location);
- if (!dir.isDirectory())
- return false;
-
- // Must contain the ndk-build script which we call to build
- if (!new File(dir, "ndk-build").isFile()) //$NON-NLS-1$
- return false;
-
- return true;
- }
-
- public static void addNativeSupport(final IProject project, Map<String, String> templateArgs,
- IProgressMonitor monitor)
- throws CoreException {
- // Launch our template to set up the project contents
- TemplateCore template = TemplateEngine.getDefault().getTemplateById("AddNdkSupport"); //$NON-NLS-1$
- Map<String, String> valueStore = template.getValueStore();
- valueStore.put("projectName", project.getName()); //$NON-NLS-1$
- valueStore.putAll(templateArgs);
- template.executeTemplateProcesses(monitor, false);
-
- // refresh project resources
- project.refreshLocal(IResource.DEPTH_INFINITE, new SubProgressMonitor(monitor, 10));
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/NdkVariables.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/NdkVariables.java
deleted file mode 100644
index 0e1cd206c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/NdkVariables.java
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal;
-
-/** Eclipse variables that are understood by the NDK while launching programs. */
-public class NdkVariables {
- /** Variable that expands to the full path of NDK's ABI specific gdb. */
- public static final String NDK_GDB = "NdkGdb";
-
- /** Variable that expands to point to the full path of the project used in the launch
- * configuration. */
- public static final String NDK_PROJECT = "NdkProject";
-
- /** Variable that indicates the ABI that is compatible between the device and the
- * application being launched. */
- public static final String NDK_COMPAT_ABI = "NdkCompatAbi";
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/actions/AddNativeAction.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/actions/AddNativeAction.java
deleted file mode 100644
index 11f65a4bf..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/actions/AddNativeAction.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal.actions;
-
-import com.android.ide.eclipse.ndk.internal.wizards.AddNativeWizard;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.PlatformObject;
-import org.eclipse.jface.action.IAction;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.jface.wizard.WizardDialog;
-import org.eclipse.ui.IObjectActionDelegate;
-import org.eclipse.ui.IWorkbenchPart;
-
-public class AddNativeAction implements IObjectActionDelegate {
-
- private IWorkbenchPart mPart;
- private ISelection mSelection;
-
- @Override
- public void run(IAction action) {
- IProject project = null;
- if (mSelection instanceof IStructuredSelection) {
- IStructuredSelection ss = (IStructuredSelection) mSelection;
- if (ss.size() == 1) {
- Object obj = ss.getFirstElement();
- if (obj instanceof IProject) {
- project = (IProject) obj;
- } else if (obj instanceof PlatformObject) {
- project = (IProject) ((PlatformObject) obj).getAdapter(IProject.class);
- }
- }
- }
-
- if (project != null) {
- AddNativeWizard wizard = new AddNativeWizard(project, mPart.getSite()
- .getWorkbenchWindow());
- WizardDialog dialog = new WizardDialog(mPart.getSite().getShell(), wizard);
- dialog.open();
- }
-
- }
-
- @Override
- public void selectionChanged(IAction action, ISelection selection) {
- mSelection = selection;
- }
-
- @Override
- public void setActivePart(IAction action, IWorkbenchPart targetPart) {
- mPart = targetPart;
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/build/NdkCommandLauncher.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/build/NdkCommandLauncher.java
deleted file mode 100644
index 0a1f7dc81..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/build/NdkCommandLauncher.java
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal.build;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.ndk.internal.NdkManager;
-
-import org.eclipse.cdt.core.CommandLauncher;
-import org.eclipse.cdt.utils.CygPath;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.runtime.Platform;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.List;
-
-@SuppressWarnings("restriction") // for AdtPlugin internal classes
-public class NdkCommandLauncher extends CommandLauncher {
- private static CygPath sCygPath = null;
-
- private static final List<String> WINDOWS_NATIVE_EXECUTABLES = Arrays.asList(
- "exe", //$NON-NLS-1$
- "cmd", //$NON-NLS-1$
- "bat" //$NON-NLS-1$
- );
-
- static {
- if (Platform.OS_WIN32.equals(Platform.getOS())) {
- try {
- sCygPath = new CygPath();
- } catch (IOException e) {
- AdtPlugin.printErrorToConsole("Unable to launch cygpath. Is Cygwin on the path?",
- e);
- }
- }
- }
-
- @Override
- public Process execute(IPath commandPath, String[] args, String[] env, IPath changeToDirectory,
- IProgressMonitor monitor)
- throws CoreException {
- if (!commandPath.isAbsolute())
- commandPath = new Path(NdkManager.getNdkLocation()).append(commandPath);
-
- if (Platform.getOS().equals(Platform.OS_WIN32)) {
- // convert cygwin paths to standard paths
- if (sCygPath != null && commandPath.toString().startsWith("/cygdrive")) { //$NON-NLS-1$
- try {
- String path = sCygPath.getFileName(commandPath.toString());
- commandPath = new Path(path);
- } catch (IOException e) {
- AdtPlugin.printErrorToConsole(
- "Unexpected error while transforming cygwin path.", e);
- }
- }
-
- if (isWindowsExecutable(commandPath)) {
- // append necessary extension
- commandPath = appendExecutableExtension(commandPath);
- } else {
- // Invoke using Cygwin shell if this is not a native windows executable
- String[] newargs = new String[args.length + 1];
- newargs[0] = commandPath.toOSString();
- System.arraycopy(args, 0, newargs, 1, args.length);
-
- commandPath = new Path("sh"); //$NON-NLS-1$
- args = newargs;
- }
- }
-
- return super.execute(commandPath, args, env, changeToDirectory, monitor);
- }
-
- private boolean isWindowsExecutable(IPath commandPath) {
- String ext = commandPath.getFileExtension();
- if (isWindowsExecutableExtension(ext)) {
- return true;
- }
-
- ext = findWindowsExecutableExtension(commandPath);
- if (ext != null) {
- return true;
- }
-
- return false;
- }
-
- private IPath appendExecutableExtension(IPath commandPath) {
- if (isWindowsExecutableExtension(commandPath.getFileExtension())) {
- return commandPath;
- }
-
- String ext = findWindowsExecutableExtension(commandPath);
- if (ext != null) {
- return commandPath.addFileExtension(ext);
- }
-
- return commandPath;
- }
-
- private String findWindowsExecutableExtension(IPath command) {
- for (String e: WINDOWS_NATIVE_EXECUTABLES) {
- File exeFile = command.addFileExtension(e).toFile();
- if (exeFile.exists()) {
- return e;
- }
- }
-
- return null;
- }
-
- private boolean isWindowsExecutableExtension(String extension) {
- return extension != null && WINDOWS_NATIVE_EXECUTABLES.contains(extension);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/build/NdkEnvSupplier.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/build/NdkEnvSupplier.java
deleted file mode 100644
index 65645537f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/build/NdkEnvSupplier.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal.build;
-
-import org.eclipse.cdt.managedbuilder.core.IConfiguration;
-import org.eclipse.cdt.managedbuilder.envvar.IBuildEnvironmentVariable;
-import org.eclipse.cdt.managedbuilder.envvar.IConfigurationEnvironmentVariableSupplier;
-import org.eclipse.cdt.managedbuilder.envvar.IEnvironmentVariableProvider;
-import org.eclipse.core.runtime.Platform;
-
-import java.io.File;
-import java.util.HashMap;
-import java.util.Map;
-
-public class NdkEnvSupplier implements IConfigurationEnvironmentVariableSupplier {
-
- private static Map<String, IBuildEnvironmentVariable> mEnvVars;
-
- private synchronized void init() {
- if (mEnvVars != null)
- return;
-
- mEnvVars = new HashMap<String, IBuildEnvironmentVariable>();
-
- if (Platform.getOS().equals(Platform.OS_WIN32)) {
- // For Windows, need to add a shell to the path
- IBuildEnvironmentVariable path = new IBuildEnvironmentVariable() {
- @Override
- public String getName() {
- return "PATH"; //$NON-NLS-1$
- }
-
- @Override
- public String getValue() {
- // I'm giving MSYS precedence over Cygwin. I'm biased that
- // way :)
- // TODO using the default paths for now, need smarter ways
- // to get at them
- // Alternatively the user can add the bin to their path
- // themselves.
- File bin = new File("C:\\MinGW\\msys\\1.0\\bin"); //$NON-NLS-1$
- if (bin.isDirectory()) {
- return bin.getAbsolutePath();
- }
-
- bin = new File("C:\\cygwin\\bin"); //$NON-NLS-1$
- if (bin.isDirectory())
- return bin.getAbsolutePath();
-
- return null;
- }
-
- @Override
- public int getOperation() {
- return ENVVAR_PREPEND;
- }
-
- @Override
- public String getDelimiter() {
- return ";"; //$NON-NLS-1$
- }
- };
- if (path.getValue() != null)
- mEnvVars.put(path.getName(), path);
-
- // Since we're using real paths, need to tell cygwin it's OK
- IBuildEnvironmentVariable cygwin = new IBuildEnvironmentVariable() {
- @Override
- public String getName() {
- return "CYGWIN"; //$NON-NLS-1$
- }
-
- @Override
- public String getValue() {
- return "nodosfilewarning"; //$NON-NLS-1$
- }
-
- @Override
- public int getOperation() {
- return ENVVAR_REPLACE;
- }
-
- @Override
- public String getDelimiter() {
- return null;
- }
- };
-
- mEnvVars.put(cygwin.getName(), cygwin);
- }
- }
-
- @Override
- public IBuildEnvironmentVariable getVariable(String variableName,
- IConfiguration configuration, IEnvironmentVariableProvider provider) {
- init();
- return mEnvVars.get(variableName);
- }
-
- @Override
- public IBuildEnvironmentVariable[] getVariables(
- IConfiguration configuration, IEnvironmentVariableProvider provider) {
- init();
- return mEnvVars.values().toArray(new IBuildEnvironmentVariable[mEnvVars.size()]);
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/discovery/NdkDiscoveredPathInfo.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/discovery/NdkDiscoveredPathInfo.java
deleted file mode 100644
index 83ce7f40e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/discovery/NdkDiscoveredPathInfo.java
+++ /dev/null
@@ -1,203 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal.discovery;
-
-import com.android.ide.eclipse.ndk.internal.Activator;
-
-import org.eclipse.cdt.core.CCorePlugin;
-import org.eclipse.cdt.core.model.CoreModel;
-import org.eclipse.cdt.make.core.scannerconfig.IDiscoveredPathManager.IDiscoveredPathInfo;
-import org.eclipse.cdt.make.core.scannerconfig.IDiscoveredPathManager.IDiscoveredScannerInfoSerializable;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.Path;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.PrintStream;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-public class NdkDiscoveredPathInfo implements IDiscoveredPathInfo {
-
- private final IProject mProject;
- private long mLastUpdate = IFile.NULL_STAMP;
- private IPath[] mIncludePaths;
- private Map<String, String> mSymbols;
- private boolean mNeedReindexing = false;
- private static final IPath ANDROID_MK = new Path("jni/Android.mk");
-
- // Keys for preferences
- public static final String LAST_UPDATE = "lastUpdate"; //$NON-NLS-1$
-
- public NdkDiscoveredPathInfo(IProject project) {
- this.mProject = project;
- load();
- }
-
- @Override
- public IProject getProject() {
- return mProject;
- }
-
- @Override
- public IPath[] getIncludePaths() {
- if (mNeedReindexing) {
- // Call for a reindex
- // TODO this is probably a bug. a new include path should trigger
- // reindexing anyway, no?
- // BTW, can't do this in the update since the indexer runs before
- // this gets called
- CCorePlugin.getIndexManager().reindex(CoreModel.getDefault().create(mProject));
- mNeedReindexing = false;
- }
- return mIncludePaths;
- }
-
- void setIncludePaths(List<String> pathStrings) {
- mIncludePaths = new IPath[pathStrings.size()];
- int i = 0;
- for (String path : pathStrings)
- mIncludePaths[i++] = new Path(path);
- mNeedReindexing = true;
- }
-
- @Override
- public Map<String, String> getSymbols() {
- if (mSymbols == null)
- mSymbols = new HashMap<String, String>();
- return mSymbols;
- }
-
- void setSymbols(Map<String, String> symbols) {
- this.mSymbols = symbols;
- }
-
- @Override
- public IDiscoveredScannerInfoSerializable getSerializable() {
- return null;
- }
-
- public void update(IProgressMonitor monitor) throws CoreException {
- if (!needUpdating())
- return;
-
- new NdkDiscoveryUpdater(this).runUpdate(monitor);
-
- if (mIncludePaths != null && mSymbols != null) {
- recordUpdate();
- save();
- }
- }
-
- private boolean needUpdating() {
- if (mLastUpdate == IFile.NULL_STAMP)
- return true;
- return mProject.getFile(ANDROID_MK).getLocalTimeStamp() > mLastUpdate;
- }
-
- private void recordUpdate() {
- mLastUpdate = mProject.getFile(ANDROID_MK).getLocalTimeStamp();
- }
-
- public void delete() {
- mLastUpdate = IFile.NULL_STAMP;
- }
-
- private File getInfoFile() {
- File stateLoc = Activator.getDefault().getStateLocation().toFile();
- return new File(stateLoc, mProject.getName() + ".pathInfo"); //$NON-NLS-1$
- }
-
- private void save() {
- try {
- File infoFile = getInfoFile();
- infoFile.getParentFile().mkdirs();
- PrintStream out = new PrintStream(infoFile);
-
- // timestamp
- out.print("t,"); //$NON-NLS-1$
- out.print(mLastUpdate);
- out.println();
-
- for (IPath include : mIncludePaths) {
- out.print("i,"); //$NON-NLS-1$
- out.print(include.toPortableString());
- out.println();
- }
-
- for (Entry<String, String> symbol : mSymbols.entrySet()) {
- out.print("d,"); //$NON-NLS-1$
- out.print(symbol.getKey());
- out.print(","); //$NON-NLS-1$
- out.print(symbol.getValue());
- out.println();
- }
-
- out.close();
- } catch (IOException e) {
- Activator.log(e);
- }
-
- }
-
- private void load() {
- try {
- File infoFile = getInfoFile();
- if (!infoFile.exists())
- return;
-
- long timestamp = IFile.NULL_STAMP;
- List<IPath> includes = new ArrayList<IPath>();
- Map<String, String> defines = new HashMap<String, String>();
-
- BufferedReader reader = new BufferedReader(new FileReader(infoFile));
- for (String line = reader.readLine(); line != null; line = reader.readLine()) {
- switch (line.charAt(0)) {
- case 't':
- timestamp = Long.valueOf(line.substring(2));
- break;
- case 'i':
- includes.add(Path.fromPortableString(line.substring(2)));
- break;
- case 'd':
- int n = line.indexOf(',', 2);
- if (n == -1)
- defines.put(line.substring(2), ""); //$NON-NLS-1$
- else
- defines.put(line.substring(2, n), line.substring(n + 1));
- break;
- }
- }
- reader.close();
-
- mLastUpdate = timestamp;
- mIncludePaths = includes.toArray(new IPath[includes.size()]);
- mSymbols = defines;
- } catch (IOException e) {
- Activator.log(e);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/discovery/NdkDiscoveryUpdater.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/discovery/NdkDiscoveryUpdater.java
deleted file mode 100644
index a6b88f462..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/discovery/NdkDiscoveryUpdater.java
+++ /dev/null
@@ -1,314 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal.discovery;
-
-import com.android.ide.eclipse.ndk.internal.Activator;
-import com.android.ide.eclipse.ndk.internal.build.NdkCommandLauncher;
-
-import org.eclipse.cdt.core.CCorePlugin;
-import org.eclipse.cdt.core.envvar.IEnvironmentVariable;
-import org.eclipse.cdt.core.envvar.IEnvironmentVariableManager;
-import org.eclipse.cdt.core.settings.model.ICConfigurationDescription;
-import org.eclipse.cdt.managedbuilder.core.IBuilder;
-import org.eclipse.cdt.managedbuilder.core.IManagedBuildInfo;
-import org.eclipse.cdt.managedbuilder.core.ManagedBuildManager;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.FileLocator;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.Path;
-
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-public class NdkDiscoveryUpdater {
- private final NdkDiscoveredPathInfo mPathInfo;
- private final IProject mProject;
-
- private boolean mCPlusPlus = false;
- private String mCommand;
- private List<String> mArguments = new ArrayList<String>();
-
- public NdkDiscoveryUpdater(NdkDiscoveredPathInfo pathInfo) {
- mPathInfo = pathInfo;
- mProject = pathInfo.getProject();
- }
-
- public void runUpdate(IProgressMonitor monitor) throws CoreException {
- try {
- // Run ndk-build -nB to get the list of commands
- IPath commandPath = new Path("ndk-build"); //$NON-NLS-1$
- String[] args = {
- "-nB"}; //$NON-NLS-1$
- String[] env = calcEnvironment();
- File projectDir = new File(mProject.getLocationURI());
- IPath changeToDirectory = new Path(projectDir.getAbsolutePath());
- Process proc = new NdkCommandLauncher().execute(commandPath, args, env,
- changeToDirectory, monitor);
- if (proc == null)
- // proc failed to start
- return;
- BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
- String line = reader.readLine();
- while (line != null) {
- checkBuildLine(line);
- line = reader.readLine();
- }
-
- if (mCommand == null) {
- return;
- }
-
- // Run the unique commands with special gcc options to extract the
- // symbols and paths
- // -E -P -v -dD
- mArguments.add("-E"); //$NON-NLS-1$
- mArguments.add("-P"); //$NON-NLS-1$
- mArguments.add("-v"); //$NON-NLS-1$
- mArguments.add("-dD"); //$NON-NLS-1$
-
- URL url = Activator.findFile(new Path(
- "discovery/" + (mCPlusPlus ? "test.cpp" : "test.c"))); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
- File testFile = new File(FileLocator.toFileURL(url).toURI());
- String testFileName = testFile.getAbsolutePath().replace('\\', '/');
- mArguments.add(testFileName);
-
- args = mArguments.toArray(new String[mArguments.size()]);
- proc = new NdkCommandLauncher().execute(new Path(mCommand), args, env,
- changeToDirectory, monitor);
- // Error stream has the includes
- final InputStream errStream = proc.getErrorStream();
- new Thread() {
- @Override
- public void run() {
- checkIncludes(errStream);
- };
- }.start();
-
- // Input stream has the defines
- checkDefines(proc.getInputStream());
- } catch (IOException e) {
- throw new CoreException(Activator.newStatus(e));
- } catch (URISyntaxException e) {
- throw new CoreException(Activator.newStatus(e));
- }
- }
-
- private String[] calcEnvironment() throws CoreException {
- IManagedBuildInfo info = ManagedBuildManager.getBuildInfo(mProject);
- IBuilder builder = info.getDefaultConfiguration().getBuilder();
- HashMap<String, String> envMap = new HashMap<String, String>();
- if (builder.appendEnvironment()) {
- ICConfigurationDescription cfgDes = ManagedBuildManager
- .getDescriptionForConfiguration(builder.getParent().getParent());
- IEnvironmentVariableManager mngr = CCorePlugin.getDefault()
- .getBuildEnvironmentManager();
- IEnvironmentVariable[] vars = mngr.getVariables(cfgDes, true);
- for (IEnvironmentVariable var : vars) {
- envMap.put(var.getName(), var.getValue());
- }
- }
- // Add variables from build info
- Map<String, String> builderEnv = builder.getExpandedEnvironment();
- if (builderEnv != null)
- envMap.putAll(builderEnv);
- List<String> strings = new ArrayList<String>(envMap.size());
- for (Entry<String, String> entry : envMap.entrySet()) {
- StringBuffer buffer = new StringBuffer(entry.getKey());
- buffer.append('=').append(entry.getValue());
- strings.add(buffer.toString());
- }
- return strings.toArray(new String[strings.size()]);
- }
-
- private static class Line {
- private final String line;
- private int pos;
-
- public Line(String line) {
- this.line = line;
- }
-
- public Line(String line, int pos) {
- this(line);
- this.pos = pos;
- }
-
- public String getToken() {
- skipWhiteSpace();
- if (pos == line.length())
- return null;
-
- int start = pos;
- boolean inQuote = false;
-
- while (true) {
- char c = line.charAt(pos);
- if (c == ' ') {
- if (!inQuote)
- return line.substring(start, pos);
- } else if (c == '"') {
- inQuote = !inQuote;
- }
-
- if (++pos == line.length())
- return null;
- }
-
- }
-
- private String getRemaining() {
- if (pos == line.length())
- return null;
-
- skipWhiteSpace();
- String rc = line.substring(pos);
- pos = line.length();
- return rc;
- }
-
- private void skipWhiteSpace() {
- while (true) {
- if (pos == line.length())
- return;
- char c = line.charAt(pos);
- if (c == ' ')
- pos++;
- else
- return;
- }
- }
- }
-
- private void checkBuildLine(String text) {
- Line line = new Line(text);
- String cmd = line.getToken();
- if (cmd == null) {
- return;
- } else if (cmd.endsWith("g++")) { //$NON-NLS-1$
- if (mCommand == null || !mCPlusPlus) {
- mCommand = cmd;
- mCPlusPlus = true;
- }
- gatherOptions(line);
- } else if (cmd.endsWith("gcc")) { //$NON-NLS-1$
- if (mCommand == null)
- mCommand = cmd;
- gatherOptions(line);
- }
- }
-
- private void gatherOptions(Line line) {
- for (String option = line.getToken(); option != null; option = line.getToken()) {
- if (option.startsWith("-")) { //$NON-NLS-1$
- // only look at options
- if (option.equals("-I")) { //$NON-NLS-1$
- String dir = line.getToken();
- if (dir != null)
- addArg(option + dir);
- } else if (option.startsWith("-I")) { //$NON-NLS-1$
- addArg(option);
- } else if (option.equals("-D")) { //$NON-NLS-1$
- String def = line.getToken();
- if (def != null)
- addArg(option + def);
- } else if (option.startsWith("-D")) { //$NON-NLS-1$
- addArg(option);
- } else if (option.startsWith("-f")) { //$NON-NLS-1$
- addArg(option);
- } else if (option.startsWith("-m")) { //$NON-NLS-1$
- addArg(option);
- } else if (option.startsWith("--sysroot")) { //$NON-NLS-1$
- addArg(option);
- }
- }
- }
- }
-
- private void addArg(String arg) {
- if (!mArguments.contains(arg))
- mArguments.add(arg);
- }
-
- private void checkIncludes(InputStream in) {
- try {
- List<String> includes = new ArrayList<String>();
- boolean inIncludes1 = false;
- boolean inIncludes2 = false;
- BufferedReader reader = new BufferedReader(new InputStreamReader(in));
- String line = reader.readLine();
- while (line != null) {
- if (!inIncludes1) {
- if (line.equals("#include \"...\" search starts here:")) //$NON-NLS-1$
- inIncludes1 = true;
- } else {
- if (!inIncludes2) {
- if (line.equals("#include <...> search starts here:")) //$NON-NLS-1$
- inIncludes2 = true;
- else
- includes.add(line.trim());
- } else {
- if (line.equals("End of search list.")) { //$NON-NLS-1$
- mPathInfo.setIncludePaths(includes);
- } else {
- includes.add(line.trim());
- }
- }
- }
- line = reader.readLine();
- }
- } catch (IOException e) {
- Activator.log(e);
- }
- }
-
- private void checkDefines(InputStream in) {
- try {
- Map<String, String> defines = new HashMap<String, String>();
- BufferedReader reader = new BufferedReader(new InputStreamReader(in));
- String line = reader.readLine();
- while (line != null) {
- if (line.startsWith("#define")) { //$NON-NLS-1$
- Line l = new Line(line, 7);
- String var = l.getToken();
- if (var == null)
- continue;
- String value = l.getRemaining();
- if (value == null)
- value = ""; //$NON-NLS-1$
- defines.put(var, value);
- }
- line = reader.readLine();
- }
- mPathInfo.setSymbols(defines);
- } catch (IOException e) {
- Activator.log(e);
- }
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/discovery/NdkScannerInfoCollector.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/discovery/NdkScannerInfoCollector.java
deleted file mode 100644
index 29f3e7f09..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/discovery/NdkScannerInfoCollector.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal.discovery;
-
-import org.eclipse.cdt.make.core.scannerconfig.IDiscoveredPathManager.IDiscoveredPathInfo;
-import org.eclipse.cdt.make.core.scannerconfig.IScannerInfoCollector3;
-import org.eclipse.cdt.make.core.scannerconfig.IScannerInfoCollectorCleaner;
-import org.eclipse.cdt.make.core.scannerconfig.InfoContext;
-import org.eclipse.cdt.make.core.scannerconfig.ScannerInfoTypes;
-import org.eclipse.cdt.managedbuilder.scannerconfig.IManagedScannerInfoCollector;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-
-import java.util.List;
-import java.util.Map;
-
-public class NdkScannerInfoCollector implements IScannerInfoCollector3,
- IScannerInfoCollectorCleaner, IManagedScannerInfoCollector {
-
- private NdkDiscoveredPathInfo mPathInfo;
-
- @Override
- public void contributeToScannerConfig(Object resource, Map scannerInfo) {
- throw new Error("Not implemented"); //$NON-NLS-1$
- }
-
- @Override
- public List getCollectedScannerInfo(Object resource, ScannerInfoTypes type) {
- throw new Error("Not implemented"); //$NON-NLS-1$
- }
-
- @Override
- public void setProject(IProject project) {
- throw new Error("Not implemented"); //$NON-NLS-1$
- }
-
- @Override
- public void updateScannerConfiguration(IProgressMonitor monitor) throws CoreException {
- mPathInfo.update(monitor);
- }
-
- @Override
- public IDiscoveredPathInfo createPathInfoObject() {
- return mPathInfo;
- }
-
- @Override
- public Map<String, String> getDefinedSymbols() {
- throw new Error("Not implemented"); //$NON-NLS-1$
- }
-
- @Override
- public List getIncludePaths() {
- throw new Error("Not implemented"); //$NON-NLS-1$
- }
-
- @Override
- public void setInfoContext(InfoContext context) {
- mPathInfo = new NdkDiscoveredPathInfo(context.getProject());
- }
-
- @Override
- public void deleteAllPaths(IResource resource) {
- throw new Error("Not implemented"); //$NON-NLS-1$
- }
-
- @Override
- public void deleteAllSymbols(IResource resource) {
- throw new Error("Not implemented"); //$NON-NLS-1$
- }
-
- @Override
- public void deletePath(IResource resource, String path) {
- throw new Error("Not implemented"); //$NON-NLS-1$
- }
-
- @Override
- public void deleteSymbol(IResource resource, String symbol) {
- throw new Error("Not implemented"); //$NON-NLS-1$
- }
-
- @Override
- public void deleteAll(IResource resource) {
- mPathInfo.delete();
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/GdbServerTask.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/GdbServerTask.java
deleted file mode 100644
index 23486ee6f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/GdbServerTask.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal.launch;
-
-import com.android.ddmlib.IDevice;
-import com.android.ddmlib.IShellOutputReceiver;
-
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * The {@link GdbServerTask} launches gdbserver on the given device and attaches it to
- * provided pid.
- */
-public class GdbServerTask implements Runnable {
- private IDevice mDevice;
- private String mRunAs;
- private String mSocket;
- private int mPid;
- private CountDownLatch mAttachLatch;
-
- private GdbServerOutputReceiver mOutputReceiver;
- private Exception mLaunchException;
-
- private AtomicBoolean mCancelled = new AtomicBoolean(false);
- private AtomicBoolean mHasCompleted = new AtomicBoolean(false);
-
- /**
- * Construct a gdbserver task.
- * @param device device to run gdbserver on
- * @param runAsPackage name of the package in which gdbserver resides
- * @param socketName name of the local socket on which the server will listen
- * @param pid pid of task to attach to
- * @param attachLatch latch to notify when gdbserver gets attached to the task
- */
- public GdbServerTask(IDevice device, String runAsPackage, String socketName, int pid,
- CountDownLatch attachLatch) {
- mDevice = device;
- mRunAs = runAsPackage;
- mSocket = socketName;
- mPid = pid;
- mAttachLatch = attachLatch;
-
- mOutputReceiver = new GdbServerOutputReceiver();
- }
-
- /**
- * Runs gdbserver on the device and connects to the given task. If gdbserver manages to
- * successfully attach itself to the process, then it counts down on its attach latch.
- */
- @Override
- public void run() {
- // Launch gdbserver on the device.
- String command = String.format("run-as %s lib/gdbserver +%s --attach %d",
- mRunAs, mSocket, mPid);
- try {
- mDevice.executeShellCommand(command, mOutputReceiver, 0);
- } catch (Exception e) {
- mLaunchException = e;
- }
- }
-
- /** Returns any exceptions that might have occurred while launching gdbserver. */
- public Exception getLaunchException() {
- return mLaunchException;
- }
-
- /** Cancel gdbserver if it is running. */
- public void setCancelled() {
- mCancelled.set(true);
- }
-
- public String getShellOutput() {
- return mOutputReceiver.getOutput();
- }
-
- private class GdbServerOutputReceiver implements IShellOutputReceiver {
- private StringBuffer mOutput = new StringBuffer(100);
-
- @Override
- public synchronized void addOutput(byte[] data, int offset, int length) {
- mOutput.append(new String(data, offset, length));
-
- // notify other threads that gdbserver has attached to the task
- if (mOutput.toString().contains("Attached")) {
- mAttachLatch.countDown();
- }
- }
-
- @Override
- public void flush() {
- mHasCompleted.set(true);
- }
-
- @Override
- public boolean isCancelled() {
- return mCancelled.get();
- }
-
- public synchronized String getOutput() {
- return mOutput.toString();
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/Messages.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/Messages.java
deleted file mode 100644
index 10f68e48e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/Messages.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal.launch;
-
-import org.eclipse.osgi.util.NLS;
-
-public class Messages extends NLS {
- private static final String BUNDLE_NAME = "com.android.ide.eclipse.ndk.internal.launch.messages"; //$NON-NLS-1$
- public static String NdkGdbLaunchDelegate_LaunchError_gdbserverOutput;
- public static String NdkGdbLaunchDelegate_Action_ActivityLaunch;
- public static String NdkGdbLaunchDelegate_Action_CheckAndroidDeviceVersion;
- public static String NdkGdbLaunchDelegate_Action_KillExistingGdbServer;
- public static String NdkGdbLaunchDelegate_Action_LaunchHostGdb;
- public static String NdkGdbLaunchDelegate_Action_LaunchingGdbServer;
- public static String NdkGdbLaunchDelegate_Action_ObtainAppAbis;
- public static String NdkGdbLaunchDelegate_Action_ObtainDevice;
- public static String NdkGdbLaunchDelegate_Action_ObtainDeviceABI;
- public static String NdkGdbLaunchDelegate_Action_PerformIncrementalBuild;
- public static String NdkGdbLaunchDelegate_Action_SettingUpPortForward;
- public static String NdkGdbLaunchDelegate_Action_SyncAppToDevice;
- public static String NdkGdbLaunchDelegate_Action_WaitGdbServerAttach;
- public static String NdkGdbLaunchDelegate_Action_WaitingForActivity;
- public static String NdkGdbLaunchDelegate_LaunchError_ActivityLaunchError;
- public static String NdkGdbLaunchDelegate_LaunchError_Api8Needed;
- public static String NdkGdbLaunchDelegate_LaunchError_CouldNotGetProject;
- public static String NdkGdbLaunchDelegate_LaunchError_gdbserverLaunchException;
- public static String NdkGdbLaunchDelegate_LaunchError_InstallError;
- public static String NdkGdbLaunchDelegate_LaunchError_InterruptedWaitingForGdbserver;
- public static String NdkGdbLaunchDelegate_LaunchError_NoActivityInManifest;
- public static String NdkGdbLaunchDelegate_LaunchError_NoCompatibleAbi;
- public static String NdkGdbLaunchDelegate_LaunchError_NoLauncherActivity;
- public static String NdkGdbLaunchDelegate_LaunchError_NoSuchActivity;
- public static String NdkGdbLaunchDelegate_LaunchError_NullApk;
- public static String NdkGdbLaunchDelegate_LaunchError_ObtainingAppFolder;
- public static String NdkGdbLaunchDelegate_LaunchError_PortForwarding;
- public static String NdkGdbLaunchDelegate_LaunchError_ProjectHasErrors;
- public static String NdkGdbLaunchDelegate_LaunchError_PullFileError;
- public static String NdkGdbLaunchDelegate_LaunchError_UnableToDetectAppAbi;
- public static String NdkGdbLaunchDelegate_LaunchError_UnknownAndroidDeviceVersion;
- public static String NdkGdbLaunchDelegate_LaunchError_VerifyIfDebugBuild;
- static {
- // initialize resource bundle
- NLS.initializeMessages(BUNDLE_NAME, Messages.class);
- }
-
- private Messages() {
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/NdkDebuggerTab.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/NdkDebuggerTab.java
deleted file mode 100644
index 64e7dd80d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/NdkDebuggerTab.java
+++ /dev/null
@@ -1,311 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal.launch;
-
-import com.android.ide.eclipse.ndk.internal.NdkHelper;
-import com.android.ide.eclipse.ndk.internal.NdkManager;
-
-import org.eclipse.cdt.dsf.gdb.IGDBLaunchConfigurationConstants;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.debug.core.ILaunchConfiguration;
-import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
-import org.eclipse.debug.ui.AbstractLaunchConfigurationTab;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.ModifyEvent;
-import org.eclipse.swt.events.ModifyListener;
-import org.eclipse.swt.events.SelectionAdapter;
-import org.eclipse.swt.events.SelectionEvent;
-import org.eclipse.swt.events.SelectionListener;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.layout.RowLayout;
-import org.eclipse.swt.widgets.Button;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Control;
-import org.eclipse.swt.widgets.DirectoryDialog;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Group;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.swt.widgets.Text;
-
-import java.io.File;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-public class NdkDebuggerTab extends AbstractLaunchConfigurationTab {
- private static String sLastGdbPath;
- private static String sLastSolibPath;
-
- private Text mGdbPathText;
- private Text mGdbInitPathText;
- private Text mGdbRemotePortText;
-
- private org.eclipse.swt.widgets.List mSoliblist;
- private Button mAddSolibButton;
- private Button mDeleteSolibButton;
-
- /**
- * @wbp.parser.entryPoint (Window Builder Entry Point)
- */
- @Override
- public void createControl(Composite parent) {
- Composite comp = new Composite(parent, SWT.NONE);
- setControl(comp);
- comp.setLayout(new GridLayout(1, false));
-
- Group grpGdb = new Group(comp, SWT.NONE);
- grpGdb.setText("Launch Options");
- grpGdb.setLayout(new GridLayout(3, false));
- grpGdb.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
-
- Label lblDebugger = new Label(grpGdb, SWT.NONE);
- lblDebugger.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- lblDebugger.setText("Debugger:");
-
- mGdbPathText = new Text(grpGdb, SWT.BORDER);
- mGdbPathText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
-
- final Button btnBrowseGdb = new Button(grpGdb, SWT.NONE);
- btnBrowseGdb.setText("Browse...");
-
- Label lblNewLabel = new Label(grpGdb, SWT.NONE);
- lblNewLabel.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- lblNewLabel.setText("GDB Command File:");
-
- mGdbInitPathText = new Text(grpGdb, SWT.BORDER);
- mGdbInitPathText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
-
- final Button btnBrowseGdbInit = new Button(grpGdb, SWT.NONE);
- btnBrowseGdbInit.setText("Browse...");
-
- SelectionListener browseListener = new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- Shell shell = ((Control) e.getSource()).getShell();
- if (e.getSource() == btnBrowseGdb) {
- browseForGdb(shell);
- } else {
- browseForGdbInit(shell);
- }
- checkParameters();
- updateLaunchConfigurationDialog();
- }
- };
- btnBrowseGdb.addSelectionListener(browseListener);
- btnBrowseGdbInit.addSelectionListener(browseListener);
-
- Label lblPort = new Label(grpGdb, SWT.NONE);
- lblPort.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false, 1, 1));
- lblPort.setText("Port:");
-
- mGdbRemotePortText = new Text(grpGdb, SWT.BORDER);
- GridData gd_text_2 = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
- gd_text_2.widthHint = 100;
- mGdbRemotePortText.setLayoutData(gd_text_2);
-
- ModifyListener m = new ModifyListener() {
- @Override
- public void modifyText(ModifyEvent e) {
- checkParameters();
- updateLaunchConfigurationDialog();
- }
- };
- mGdbPathText.addModifyListener(m);
- mGdbInitPathText.addModifyListener(m);
- mGdbRemotePortText.addModifyListener(m);
-
- Group grpSharedLibraries = new Group(comp, SWT.NONE);
- grpSharedLibraries.setText("Shared Libraries");
- grpSharedLibraries.setLayout(new GridLayout(2, false));
- GridData gd_grpSharedLibraries = new GridData(GridData.FILL_BOTH);
- gd_grpSharedLibraries.verticalAlignment = SWT.TOP;
- gd_grpSharedLibraries.grabExcessVerticalSpace = true;
- grpSharedLibraries.setLayoutData(gd_grpSharedLibraries);
-
- mSoliblist = new org.eclipse.swt.widgets.List(grpSharedLibraries,
- SWT.BORDER | SWT.V_SCROLL | SWT.SINGLE);
- GridData gd_list = new GridData(GridData.FILL_BOTH);
- gd_list.heightHint = 133;
- gd_list.grabExcessVerticalSpace = false;
- gd_list.verticalSpan = 1;
- mSoliblist.setLayoutData(gd_list);
-
- Composite composite = new Composite(grpSharedLibraries, SWT.NONE);
- composite.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, false, false, 1, 1));
- composite.setLayout(new RowLayout(SWT.VERTICAL));
-
- mAddSolibButton = new Button(composite, SWT.NONE);
- mAddSolibButton.setText("Add...");
-
- mDeleteSolibButton = new Button(composite, SWT.NONE);
- mDeleteSolibButton.setText("Remove");
- mDeleteSolibButton.setEnabled(false);
-
- SelectionListener l = new SelectionAdapter() {
- @Override
- public void widgetSelected(SelectionEvent e) {
- Control c = (Control) e.getSource();
- if (c == mSoliblist) {
- // enable delete only if there is a selection
- mDeleteSolibButton.setEnabled(mSoliblist.getSelectionCount() > 0);
- } else if (c == mAddSolibButton) {
- addSolib(c.getShell());
- } else {
- // delete current selection
- int index = mSoliblist.getSelectionIndex();
- if (index >= 0) {
- mSoliblist.remove(index);
- }
- }
- updateLaunchConfigurationDialog();
- }
- };
-
- mSoliblist.addSelectionListener(l);
- mAddSolibButton.addSelectionListener(l);
- mDeleteSolibButton.addSelectionListener(l);
- }
-
- private void addSolib(Shell shell) {
- DirectoryDialog dd = new DirectoryDialog(shell);
- if (sLastSolibPath != null) {
- dd.setFilterPath(sLastSolibPath);
- }
- String solibPath = dd.open();
-
- if (solibPath != null) {
- mSoliblist.add(solibPath);
- sLastSolibPath = new File(solibPath).getParent();
- }
- }
-
- private void browseForGdb(Shell shell) {
- if (sLastGdbPath == null) {
- sLastGdbPath = NdkManager.getNdkLocation();
- }
-
- FileDialog fd = new FileDialog(shell);
- fd.setFilterPath(sLastGdbPath);
-
- String gdbPath = fd.open();
- if (gdbPath != null) {
- mGdbPathText.setText(gdbPath);
- sLastGdbPath = new File(gdbPath).getParent();
- }
- }
-
- private void browseForGdbInit(Shell shell) {
- FileDialog fd = new FileDialog(shell);
- String gdbInit = fd.open();
- if (gdbInit != null) {
- mGdbInitPathText.setText(gdbInit);
- }
- }
-
- private void checkParameters() {
- // check gdb path
- String gdb = mGdbPathText.getText().trim();
- if (!gdb.equals(NdkLaunchConstants.DEFAULT_GDB)) {
- File f = new File(gdb);
- if (!f.exists() || !f.canExecute()) {
- setErrorMessage("Invalid gdb location.");
- return;
- }
- }
-
- // check gdb init path
- String gdbInit = mGdbInitPathText.getText().trim();
- if (!gdbInit.isEmpty()) {
- File f = new File(gdbInit);
- if (!f.exists() || !f.isFile()) {
- setErrorMessage("Invalid gdbinit location.");
- return;
- }
- }
-
- // port should be a valid integer
- String port = mGdbRemotePortText.getText().trim();
- try {
- Integer.parseInt(port, 10);
- } catch (NumberFormatException e) {
- setErrorMessage("Port should be a valid integer");
- return;
- }
-
- // no errors
- setErrorMessage(null);
- setMessage(null);
- }
-
- @Override
- public void setDefaults(ILaunchConfigurationWorkingCopy config) {
- NdkHelper.setLaunchConfigDefaults(config);
- }
-
- @Override
- public void initializeFrom(ILaunchConfiguration config) {
- mGdbPathText.setText(getAttribute(config, NdkLaunchConstants.ATTR_NDK_GDB,
- NdkLaunchConstants.DEFAULT_GDB));
- mGdbInitPathText.setText(getAttribute(config,
- IGDBLaunchConfigurationConstants.ATTR_GDB_INIT,
- NdkLaunchConstants.DEFAULT_GDBINIT));
- mGdbRemotePortText.setText(getAttribute(config, IGDBLaunchConfigurationConstants.ATTR_PORT,
- NdkLaunchConstants.DEFAULT_GDB_PORT));
-
- List<String> solibs = getAttribute(config, NdkLaunchConstants.ATTR_NDK_SOLIB,
- Collections.EMPTY_LIST);
- mSoliblist.removeAll();
- for (String s: solibs) {
- mSoliblist.add(s);
- }
- }
-
- private String getAttribute(ILaunchConfiguration config, String key, String defaultValue) {
- try {
- return config.getAttribute(key, defaultValue);
- } catch (CoreException e) {
- return defaultValue;
- }
- }
-
- private List<String> getAttribute(ILaunchConfiguration config, String key,
- List<String> defaultValue) {
- try {
- return config.getAttribute(key, defaultValue);
- } catch (CoreException e) {
- return defaultValue;
- }
- }
-
- @Override
- public void performApply(ILaunchConfigurationWorkingCopy config) {
- config.setAttribute(NdkLaunchConstants.ATTR_NDK_GDB, mGdbPathText.getText().trim());
- config.setAttribute(IGDBLaunchConfigurationConstants.ATTR_GDB_INIT,
- mGdbInitPathText.getText().trim());
- config.setAttribute(IGDBLaunchConfigurationConstants.ATTR_PORT,
- mGdbRemotePortText.getText().trim());
- config.setAttribute(NdkLaunchConstants.ATTR_NDK_SOLIB,
- Arrays.asList(mSoliblist.getItems()));
- }
-
- @Override
- public String getName() {
- return "Debugger";
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/NdkGdbLaunchConfigTabGroups.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/NdkGdbLaunchConfigTabGroups.java
deleted file mode 100644
index f8cf73c9f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/NdkGdbLaunchConfigTabGroups.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal.launch;
-
-import org.eclipse.debug.ui.AbstractLaunchConfigurationTabGroup;
-import org.eclipse.debug.ui.CommonTab;
-import org.eclipse.debug.ui.ILaunchConfigurationDialog;
-import org.eclipse.debug.ui.ILaunchConfigurationTab;
-import org.eclipse.debug.ui.sourcelookup.SourceLookupTab;
-
-public class NdkGdbLaunchConfigTabGroups extends AbstractLaunchConfigurationTabGroup {
- public NdkGdbLaunchConfigTabGroups() {
- }
-
- @Override
- public void createTabs(ILaunchConfigurationDialog dialog, String mode) {
- ILaunchConfigurationTab[] tabs = new ILaunchConfigurationTab[] {
- new NdkMainLaunchConfigTab(),
- new NdkDebuggerTab(),
- new SourceLookupTab(),
- new CommonTab()
- };
- setTabs(tabs);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/NdkGdbLaunchDelegate.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/NdkGdbLaunchDelegate.java
deleted file mode 100644
index 0b124f249..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/NdkGdbLaunchDelegate.java
+++ /dev/null
@@ -1,506 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal.launch;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ddmlib.AdbCommandRejectedException;
-import com.android.ddmlib.AndroidDebugBridge;
-import com.android.ddmlib.Client;
-import com.android.ddmlib.CollectingOutputReceiver;
-import com.android.ddmlib.IDevice;
-import com.android.ddmlib.IDevice.DeviceUnixSocketNamespace;
-import com.android.ddmlib.InstallException;
-import com.android.ddmlib.ShellCommandUnresponsiveException;
-import com.android.ddmlib.SyncException;
-import com.android.ddmlib.TimeoutException;
-import com.android.ide.common.xml.ManifestData;
-import com.android.ide.common.xml.ManifestData.Activity;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.ide.eclipse.adt.internal.launch.AndroidLaunchController;
-import com.android.ide.eclipse.adt.internal.launch.DeviceChooserDialog;
-import com.android.ide.eclipse.adt.internal.launch.DeviceChooserDialog.DeviceChooserResponse;
-import com.android.ide.eclipse.adt.internal.launch.LaunchConfigDelegate;
-import com.android.ide.eclipse.adt.internal.project.AndroidManifestHelper;
-import com.android.ide.eclipse.adt.internal.project.ProjectHelper;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.ndk.internal.NativeAbi;
-import com.android.ide.eclipse.ndk.internal.NdkHelper;
-import com.android.ide.eclipse.ndk.internal.NdkVariables;
-import com.android.sdklib.AndroidVersion;
-import com.android.sdklib.IAndroidTarget;
-import com.google.common.base.Joiner;
-
-import org.eclipse.cdt.core.model.ICProject;
-import org.eclipse.cdt.debug.core.CDebugUtils;
-import org.eclipse.cdt.debug.core.ICDTLaunchConfigurationConstants;
-import org.eclipse.cdt.dsf.gdb.IGDBLaunchConfigurationConstants;
-import org.eclipse.cdt.dsf.gdb.launching.GdbLaunchDelegate;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.core.variables.IStringVariableManager;
-import org.eclipse.core.variables.IValueVariable;
-import org.eclipse.core.variables.VariablesPlugin;
-import org.eclipse.debug.core.DebugPlugin;
-import org.eclipse.debug.core.ILaunch;
-import org.eclipse.debug.core.ILaunchConfiguration;
-import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
-import org.eclipse.jface.dialogs.Dialog;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-
-@SuppressWarnings("restriction")
-public class NdkGdbLaunchDelegate extends GdbLaunchDelegate {
- public static final String LAUNCH_TYPE_ID =
- "com.android.ide.eclipse.ndk.debug.LaunchConfigType"; //$NON-NLS-1$
-
- private static final Joiner JOINER = Joiner.on(", ").skipNulls();
-
- private static final String DEBUG_SOCKET = "debugsock"; //$NON-NLS-1$
-
- @Override
- public void launch(ILaunchConfiguration config, String mode, ILaunch launch,
- IProgressMonitor monitor) throws CoreException {
- boolean launched = doLaunch(config, mode, launch, monitor);
- if (!launched) {
- if (launch.canTerminate()) {
- launch.terminate();
- }
- DebugPlugin.getDefault().getLaunchManager().removeLaunch(launch);
- }
- }
-
- public boolean doLaunch(final ILaunchConfiguration config, String mode, ILaunch launch,
- IProgressMonitor monitor) throws CoreException {
- IProject project = null;
- ICProject cProject = CDebugUtils.getCProject(config);
- if (cProject != null) {
- project = cProject.getProject();
- }
-
- if (project == null) {
- AdtPlugin.printErrorToConsole(
- Messages.NdkGdbLaunchDelegate_LaunchError_CouldNotGetProject);
- return false;
- }
-
- // make sure the project and its dependencies are built and PostCompilerBuilder runs.
- // This is a synchronous call which returns when the build is done.
- monitor.setTaskName(Messages.NdkGdbLaunchDelegate_Action_PerformIncrementalBuild);
- ProjectHelper.doFullIncrementalDebugBuild(project, monitor);
-
- // check if the project has errors, and abort in this case.
- if (ProjectHelper.hasError(project, true)) {
- AdtPlugin.printErrorToConsole(project,
- Messages.NdkGdbLaunchDelegate_LaunchError_ProjectHasErrors);
- return false;
- }
-
- final ManifestData manifestData = AndroidManifestHelper.parseForData(project);
- final ManifestInfo manifestInfo = ManifestInfo.get(project);
- final AndroidVersion minSdkVersion = new AndroidVersion(
- manifestInfo.getMinSdkVersion(),
- manifestInfo.getMinSdkCodeName());
-
- // Get the activity name to launch
- String activityName = getActivityToLaunch(
- getActivityNameInLaunchConfig(config),
- manifestData.getLauncherActivity(),
- manifestData.getActivities(),
- project);
-
- // Get ABI's supported by the application
- monitor.setTaskName(Messages.NdkGdbLaunchDelegate_Action_ObtainAppAbis);
- Collection<NativeAbi> appAbis = NdkHelper.getApplicationAbis(project, monitor);
- if (appAbis.size() == 0) {
- AdtPlugin.printErrorToConsole(project,
- Messages.NdkGdbLaunchDelegate_LaunchError_UnableToDetectAppAbi);
- return false;
- }
-
- // Obtain device to use:
- // - if there is only 1 device, just use that
- // - if we have previously launched this config, and the device used is present, use that
- // - otherwise show the DeviceChooserDialog
- final String configName = config.getName();
- monitor.setTaskName(Messages.NdkGdbLaunchDelegate_Action_ObtainDevice);
- IDevice device = null;
- IDevice[] devices = AndroidDebugBridge.getBridge().getDevices();
- if (devices.length == 1) {
- device = devices[0];
- } else if ((device = getLastUsedDevice(config, devices)) == null) {
- final IAndroidTarget projectTarget = Sdk.getCurrent().getTarget(project);
- final DeviceChooserResponse response = new DeviceChooserResponse();
- final boolean continueLaunch[] = new boolean[] { false };
- AdtPlugin.getDisplay().syncExec(new Runnable() {
- @Override
- public void run() {
- DeviceChooserDialog dialog = new DeviceChooserDialog(
- AdtPlugin.getDisplay().getActiveShell(),
- response,
- manifestData.getPackage(),
- projectTarget, minSdkVersion, false /*** FIXME! **/);
- if (dialog.open() == Dialog.OK) {
- AndroidLaunchController.updateLaunchConfigWithLastUsedDevice(config,
- response);
- continueLaunch[0] = true;
- }
- };
- });
-
- if (!continueLaunch[0]) {
- return false;
- }
-
- device = response.getDeviceToUse();
- }
-
- // ndk-gdb requires device > Froyo
- monitor.setTaskName(Messages.NdkGdbLaunchDelegate_Action_CheckAndroidDeviceVersion);
- AndroidVersion deviceVersion = Sdk.getDeviceVersion(device);
- if (deviceVersion == null) {
- AdtPlugin.printErrorToConsole(project,
- Messages.NdkGdbLaunchDelegate_LaunchError_UnknownAndroidDeviceVersion);
- return false;
- } else if (!deviceVersion.isGreaterOrEqualThan(8)) {
- AdtPlugin.printErrorToConsole(project,
- Messages.NdkGdbLaunchDelegate_LaunchError_Api8Needed);
- return false;
- }
-
- // get Device ABI
- monitor.setTaskName(Messages.NdkGdbLaunchDelegate_Action_ObtainDeviceABI);
- String deviceAbi1 = device.getProperty("ro.product.cpu.abi"); //$NON-NLS-1$
- String deviceAbi2 = device.getProperty("ro.product.cpu.abi2"); //$NON-NLS-1$
-
- // get the abi that is supported by both the device and the application
- NativeAbi compatAbi = getCompatibleAbi(deviceAbi1, deviceAbi2, appAbis);
- if (compatAbi == null) {
- AdtPlugin.printErrorToConsole(project,
- Messages.NdkGdbLaunchDelegate_LaunchError_NoCompatibleAbi);
- AdtPlugin.printErrorToConsole(project,
- String.format("ABI's supported by the application: %s", JOINER.join(appAbis)));
- AdtPlugin.printErrorToConsole(project,
- String.format("ABI's supported by the device: %s, %s", //$NON-NLS-1$
- deviceAbi1,
- deviceAbi2));
- return false;
- }
-
- // sync app
- monitor.setTaskName(Messages.NdkGdbLaunchDelegate_Action_SyncAppToDevice);
- IFile apk = ProjectHelper.getApplicationPackage(project);
- if (apk == null) {
- AdtPlugin.printErrorToConsole(project,
- Messages.NdkGdbLaunchDelegate_LaunchError_NullApk);
- return false;
- }
- try {
- device.installPackage(apk.getLocation().toOSString(), true);
- } catch (InstallException e1) {
- AdtPlugin.printErrorToConsole(project,
- Messages.NdkGdbLaunchDelegate_LaunchError_InstallError, e1);
- return false;
- }
-
- // launch activity
- monitor.setTaskName(Messages.NdkGdbLaunchDelegate_Action_ActivityLaunch + activityName);
- String command = String.format("am start -n %s/%s", manifestData.getPackage(), //$NON-NLS-1$
- activityName);
- try {
- CountDownLatch launchedLatch = new CountDownLatch(1);
- CollectingOutputReceiver receiver = new CollectingOutputReceiver(launchedLatch);
- device.executeShellCommand(command, receiver);
- launchedLatch.await(5, TimeUnit.SECONDS);
- String shellOutput = receiver.getOutput();
- if (shellOutput.contains("Error type")) { //$NON-NLS-1$
- throw new RuntimeException(receiver.getOutput());
- }
- } catch (Exception e) {
- AdtPlugin.printErrorToConsole(project,
- Messages.NdkGdbLaunchDelegate_LaunchError_ActivityLaunchError, e);
- return false;
- }
-
- // kill existing gdbserver
- monitor.setTaskName(Messages.NdkGdbLaunchDelegate_Action_KillExistingGdbServer);
- for (Client c: device.getClients()) {
- String description = c.getClientData().getClientDescription();
- if (description != null && description.contains("gdbserver")) { //$NON-NLS-1$
- c.kill();
- }
- }
-
- // pull app_process & libc from the device
- IPath solibFolder = project.getLocation().append("obj/local").append(compatAbi.getAbi());
- try {
- pull(device, "/system/bin/app_process", solibFolder); //$NON-NLS-1$
- pull(device, "/system/lib/libc.so", solibFolder); //$NON-NLS-1$
- } catch (Exception e) {
- AdtPlugin.printErrorToConsole(project,
- Messages.NdkGdbLaunchDelegate_LaunchError_PullFileError, e);
- return false;
- }
-
- // wait for a couple of seconds for activity to be launched
- monitor.setTaskName(Messages.NdkGdbLaunchDelegate_Action_WaitingForActivity);
- try {
- Thread.sleep(2000);
- } catch (InterruptedException e1) {
- // uninterrupted
- }
-
- // get pid of activity
- Client app = device.getClient(manifestData.getPackage());
- int pid = app.getClientData().getPid();
-
- // launch gdbserver
- monitor.setTaskName(Messages.NdkGdbLaunchDelegate_Action_LaunchingGdbServer);
- CountDownLatch attachLatch = new CountDownLatch(1);
- GdbServerTask gdbServer = new GdbServerTask(device, manifestData.getPackage(),
- DEBUG_SOCKET, pid, attachLatch);
- new Thread(gdbServer,
- String.format("gdbserver for %s", manifestData.getPackage())).start(); //$NON-NLS-1$
-
- // wait for gdbserver to attach
- monitor.setTaskName(Messages.NdkGdbLaunchDelegate_Action_WaitGdbServerAttach);
- boolean attached = false;
- try {
- attached = attachLatch.await(3, TimeUnit.SECONDS);
- } catch (InterruptedException e) {
- AdtPlugin.printErrorToConsole(project,
- Messages.NdkGdbLaunchDelegate_LaunchError_InterruptedWaitingForGdbserver);
- return false;
- }
-
- // if gdbserver failed to attach, we report any errors that may have occurred
- if (!attached) {
- if (gdbServer.getLaunchException() != null) {
- AdtPlugin.printErrorToConsole(project,
- Messages.NdkGdbLaunchDelegate_LaunchError_gdbserverLaunchException,
- gdbServer.getLaunchException());
- } else {
- AdtPlugin.printErrorToConsole(project,
- Messages.NdkGdbLaunchDelegate_LaunchError_gdbserverOutput,
- gdbServer.getShellOutput());
- }
- AdtPlugin.printErrorToConsole(project,
- Messages.NdkGdbLaunchDelegate_LaunchError_VerifyIfDebugBuild);
-
- // shut down the gdbserver thread
- gdbServer.setCancelled();
- return false;
- }
-
- // Obtain application working directory
- String appDir = null;
- try {
- appDir = getAppDirectory(device, manifestData.getPackage(), 5, TimeUnit.SECONDS);
- } catch (Exception e) {
- AdtPlugin.printErrorToConsole(project,
- Messages.NdkGdbLaunchDelegate_LaunchError_ObtainingAppFolder, e);
- return false;
- }
-
- // setup port forwarding between local port & remote (device) unix domain socket
- monitor.setTaskName(Messages.NdkGdbLaunchDelegate_Action_SettingUpPortForward);
- String localport = config.getAttribute(IGDBLaunchConfigurationConstants.ATTR_PORT,
- NdkLaunchConstants.DEFAULT_GDB_PORT);
- try {
- device.createForward(Integer.parseInt(localport),
- String.format("%s/%s", appDir, DEBUG_SOCKET), //$NON-NLS-1$
- DeviceUnixSocketNamespace.FILESYSTEM);
- } catch (Exception e) {
- AdtPlugin.printErrorToConsole(project,
- Messages.NdkGdbLaunchDelegate_LaunchError_PortForwarding, e);
- return false;
- }
-
- // update launch attributes based on device
- ILaunchConfiguration config2 = performVariableSubstitutions(config, project, compatAbi,
- monitor);
-
- // launch gdb
- monitor.setTaskName(Messages.NdkGdbLaunchDelegate_Action_LaunchHostGdb);
- super.launch(config2, mode, launch, monitor);
- return true;
- }
-
- @Nullable
- private IDevice getLastUsedDevice(ILaunchConfiguration config, @NonNull IDevice[] devices) {
- try {
- boolean reuse = config.getAttribute(LaunchConfigDelegate.ATTR_REUSE_LAST_USED_DEVICE,
- false);
- if (!reuse) {
- return null;
- }
-
- String serial = config.getAttribute(LaunchConfigDelegate.ATTR_LAST_USED_DEVICE,
- (String)null);
- return AndroidLaunchController.getDeviceIfOnline(serial, devices);
- } catch (CoreException e) {
- return null;
- }
- }
-
- private void pull(IDevice device, String remote, IPath solibFolder) throws
- SyncException, IOException, AdbCommandRejectedException, TimeoutException {
- String remoteFileName = new Path(remote).toFile().getName();
- String targetFile = solibFolder.append(remoteFileName).toString();
- device.pullFile(remote, targetFile);
- }
-
- private ILaunchConfiguration performVariableSubstitutions(ILaunchConfiguration config,
- IProject project, NativeAbi compatAbi, IProgressMonitor monitor) throws CoreException {
- ILaunchConfigurationWorkingCopy wcopy = config.getWorkingCopy();
-
- String toolchainPrefix = NdkHelper.getToolchainPrefix(project, compatAbi, monitor);
- String gdb = toolchainPrefix + "gdb"; //$NON-NLS-1$
-
- IStringVariableManager manager = VariablesPlugin.getDefault().getStringVariableManager();
- IValueVariable ndkGdb = manager.newValueVariable(NdkVariables.NDK_GDB,
- NdkVariables.NDK_GDB, true, gdb);
- IValueVariable ndkProject = manager.newValueVariable(NdkVariables.NDK_PROJECT,
- NdkVariables.NDK_PROJECT, true, project.getLocation().toOSString());
- IValueVariable ndkCompatAbi = manager.newValueVariable(NdkVariables.NDK_COMPAT_ABI,
- NdkVariables.NDK_COMPAT_ABI, true, compatAbi.getAbi());
-
- IValueVariable[] ndkVars = new IValueVariable[] { ndkGdb, ndkProject, ndkCompatAbi };
- manager.addVariables(ndkVars);
-
- // fix path to gdb
- String userGdbPath = wcopy.getAttribute(NdkLaunchConstants.ATTR_NDK_GDB,
- NdkLaunchConstants.DEFAULT_GDB);
- wcopy.setAttribute(IGDBLaunchConfigurationConstants.ATTR_DEBUG_NAME,
- elaborateExpression(manager, userGdbPath));
-
- // setup program name
- wcopy.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME,
- elaborateExpression(manager, NdkLaunchConstants.DEFAULT_PROGRAM));
-
- // fix solib paths
- List<String> solibPaths = wcopy.getAttribute(
- NdkLaunchConstants.ATTR_NDK_SOLIB,
- Collections.singletonList(NdkLaunchConstants.DEFAULT_SOLIB_PATH));
- List<String> fixedSolibPaths = new ArrayList<String>(solibPaths.size());
- for (String u : solibPaths) {
- fixedSolibPaths.add(elaborateExpression(manager, u));
- }
- wcopy.setAttribute(IGDBLaunchConfigurationConstants.ATTR_DEBUGGER_SOLIB_PATH,
- fixedSolibPaths);
-
- manager.removeVariables(ndkVars);
-
- return wcopy.doSave();
- }
-
- private String elaborateExpression(IStringVariableManager manager, String expr)
- throws CoreException{
- boolean DEBUG = true;
-
- String eval = manager.performStringSubstitution(expr);
- if (DEBUG) {
- AdtPlugin.printToConsole("Substitute: ", expr, " --> ", eval);
- }
-
- return eval;
- }
-
- /**
- * Returns the activity name to launch. If the user has requested a particular activity to
- * be launched, then this method will confirm that the requested activity is defined in the
- * manifest. If the user has not specified any activities, then it returns the default
- * launcher activity.
- * @param activityNameInLaunchConfig activity to launch as requested by the user.
- * @param activities list of activities as defined in the application's manifest
- * @param project android project
- * @return activity name that should be launched, or null if no launchable activity.
- */
- private String getActivityToLaunch(String activityNameInLaunchConfig, Activity launcherActivity,
- Activity[] activities, IProject project) {
- if (activities.length == 0) {
- AdtPlugin.printErrorToConsole(project,
- Messages.NdkGdbLaunchDelegate_LaunchError_NoActivityInManifest);
- return null;
- } else if (activityNameInLaunchConfig == null && launcherActivity != null) {
- return launcherActivity.getName();
- } else {
- for (Activity a : activities) {
- if (a != null && a.getName().equals(activityNameInLaunchConfig)) {
- return activityNameInLaunchConfig;
- }
- }
-
- AdtPlugin.printErrorToConsole(project,
- Messages.NdkGdbLaunchDelegate_LaunchError_NoSuchActivity);
- if (launcherActivity != null) {
- return launcherActivity.getName();
- } else {
- AdtPlugin.printErrorToConsole(
- Messages.NdkGdbLaunchDelegate_LaunchError_NoLauncherActivity);
- return null;
- }
- }
- }
-
- private NativeAbi getCompatibleAbi(String deviceAbi1, String deviceAbi2,
- Collection<NativeAbi> appAbis) {
- for (NativeAbi abi: appAbis) {
- if (abi.getAbi().equals(deviceAbi1) || abi.getAbi().equals(deviceAbi2)) {
- return abi;
- }
- }
-
- return null;
- }
-
- /** Returns the name of the activity as defined in the launch configuration. */
- private String getActivityNameInLaunchConfig(ILaunchConfiguration configuration) {
- String empty = ""; //$NON-NLS-1$
- String activityName;
- try {
- activityName = configuration.getAttribute(LaunchConfigDelegate.ATTR_ACTIVITY, empty);
- } catch (CoreException e) {
- return null;
- }
-
- return (activityName != empty) ? activityName : null;
- }
-
- private String getAppDirectory(IDevice device, String app, long timeout, TimeUnit timeoutUnit)
- throws TimeoutException, AdbCommandRejectedException, ShellCommandUnresponsiveException,
- IOException, InterruptedException {
- String command = String.format("run-as %s /system/bin/sh -c pwd", app); //$NON-NLS-1$
-
- CountDownLatch commandCompleteLatch = new CountDownLatch(1);
- CollectingOutputReceiver receiver = new CollectingOutputReceiver(commandCompleteLatch);
- device.executeShellCommand(command, receiver);
- commandCompleteLatch.await(timeout, timeoutUnit);
- return receiver.getOutput().trim();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/NdkGdbLaunchShortcut.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/NdkGdbLaunchShortcut.java
deleted file mode 100644
index 22eb118a2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/NdkGdbLaunchShortcut.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal.launch;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.launch.AndroidLaunchController;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.ndk.internal.NdkHelper;
-
-import org.eclipse.cdt.core.model.CoreModel;
-import org.eclipse.cdt.debug.core.ICDTLaunchConfigurationConstants;
-import org.eclipse.cdt.dsf.gdb.IGDBLaunchConfigurationConstants;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.debug.core.ILaunchConfiguration;
-import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
-import org.eclipse.debug.ui.DebugUITools;
-import org.eclipse.debug.ui.ILaunchShortcut;
-import org.eclipse.jface.viewers.ISelection;
-import org.eclipse.jface.viewers.IStructuredSelection;
-import org.eclipse.ui.IEditorPart;
-
-@SuppressWarnings("restriction") // for adt.internal classes
-public class NdkGdbLaunchShortcut implements ILaunchShortcut {
- @Override
- public void launch(ISelection selection, String mode) {
- if (!(selection instanceof IStructuredSelection)) {
- return;
- }
-
- Object s = ((IStructuredSelection) selection).getFirstElement();
- if (!(s instanceof IAdaptable)) {
- return;
- }
-
- IResource r = (IResource) ((IAdaptable) s).getAdapter(IResource.class);
- if (r == null) {
- return;
- }
-
- IProject project = r.getProject();
- if (project == null) {
- return;
- }
-
- // verify that this is a non library Android project
- ProjectState state = Sdk.getProjectState(project);
- if (state == null || state.isLibrary()) {
- return;
- }
-
- // verify that this project has C/C++ nature
- if (!CoreModel.hasCCNature(project) && !CoreModel.hasCNature(project)) {
- AdtPlugin.printErrorToConsole(project,
- String.format("Selected project (%s) does not have C/C++ nature. "
- + "To add native support, right click on the project, "
- + "Android Tools -> Add Native Support",
- project.getName()));
- return;
- }
-
- debugProject(project, mode);
- }
-
- @Override
- public void launch(IEditorPart editor, String mode) {
- }
-
- private void debugProject(IProject project, String mode) {
- // obtain existing native debug config for project
- ILaunchConfiguration config = AndroidLaunchController.getLaunchConfig(project,
- NdkGdbLaunchDelegate.LAUNCH_TYPE_ID);
- if (config == null) {
- return;
- }
-
- // Set the ndk gdb specific launch attributes in the config (if necessary)
- if (!hasNdkAttributes(config)) {
- try {
- config = setNdkDefaults(config, project);
- } catch (CoreException e) {
- AdtPlugin.printErrorToConsole(project,
- "Unable to create launch configuration for project.");
- return;
- }
- }
-
- // launch
- DebugUITools.launch(config, mode);
- }
-
- private boolean hasNdkAttributes(ILaunchConfiguration config) {
- try {
- // All NDK launch configurations have ATTR_REMOTE_TCP set to true
- boolean isRemote = config.getAttribute(IGDBLaunchConfigurationConstants.ATTR_REMOTE_TCP,
- false);
- return isRemote;
- } catch (CoreException e) {
- return false;
- }
- }
-
- private ILaunchConfiguration setNdkDefaults(ILaunchConfiguration config, IProject project)
- throws CoreException {
- ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
- NdkHelper.setLaunchConfigDefaults(wc);
- wc.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME, project.getName());
- return wc.doSave();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/NdkLaunchConstants.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/NdkLaunchConstants.java
deleted file mode 100644
index ff70b2e1f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/NdkLaunchConstants.java
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal.launch;
-
-import com.android.ide.eclipse.ndk.internal.Activator;
-import com.android.ide.eclipse.ndk.internal.NdkVariables;
-
-public class NdkLaunchConstants {
- private static final String PREFIX = Activator.PLUGIN_ID + ".ndklaunch."; //$NON-NLS-1$
-
- public static final String ATTR_NDK_GDB = PREFIX + "gdb"; //$NON-NLS-1$
- public static final String ATTR_NDK_GDBINIT = PREFIX + "gdbinit"; //$NON-NLS-1$
- public static final String ATTR_NDK_SOLIB = PREFIX + "solib"; //$NON-NLS-1$
-
- public static final String DEFAULT_GDB_PORT = "5039"; //$NON-NLS-1$
- public static final String DEFAULT_GDB = getVar(NdkVariables.NDK_GDB);
- public static final String DEFAULT_GDBINIT = ""; //$NON-NLS-1$
- public static final String DEFAULT_PROGRAM =
- String.format("%1$s/obj/local/%2$s/app_process", //$NON-NLS-1$
- getVar(NdkVariables.NDK_PROJECT),
- getVar(NdkVariables.NDK_COMPAT_ABI));
- public static final String DEFAULT_SOLIB_PATH =
- String.format("%1$s/obj/local/%2$s/", //$NON-NLS-1$
- getVar(NdkVariables.NDK_PROJECT),
- getVar(NdkVariables.NDK_COMPAT_ABI));
-
- private static String getVar(String varName) {
- return "${" + varName + '}'; //$NON-NLS-1$
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/NdkMainLaunchConfigTab.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/NdkMainLaunchConfigTab.java
deleted file mode 100644
index 1e4b39e91..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/NdkMainLaunchConfigTab.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal.launch;
-
-import com.android.ide.eclipse.adt.internal.launch.MainLaunchConfigTab;
-import com.android.ide.eclipse.adt.internal.project.ProjectChooserHelper.IProjectChooserFilter;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-
-import org.eclipse.cdt.core.model.CoreModel;
-import org.eclipse.cdt.debug.core.ICDTLaunchConfigurationConstants;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
-
-@SuppressWarnings("restriction")
-public class NdkMainLaunchConfigTab extends MainLaunchConfigTab {
- private static class NdkProjectOnlyFilter implements IProjectChooserFilter {
- @Override
- public boolean accept(IProject project) {
- ProjectState state = Sdk.getProjectState(project);
- if (state == null) {
- return false;
- }
-
- return !state.isLibrary()
- && (CoreModel.hasCCNature(project) || CoreModel.hasCNature(project));
- }
-
- @Override
- public boolean useCache() {
- return true;
- }
- }
-
- @Override
- protected IProjectChooserFilter getProjectFilter() {
- return new NdkProjectOnlyFilter();
- }
-
- @Override
- public void performApply(ILaunchConfigurationWorkingCopy configuration) {
- super.performApply(configuration);
-
- configuration.setAttribute(ICDTLaunchConfigurationConstants.ATTR_PROJECT_NAME,
- mProjText.getText().trim());
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/messages.properties b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/messages.properties
deleted file mode 100644
index 6770f2de4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/launch/messages.properties
+++ /dev/null
@@ -1,32 +0,0 @@
-NdkGdbLaunchDelegate_Action_ActivityLaunch=Launching activity
-NdkGdbLaunchDelegate_Action_CheckAndroidDeviceVersion=Checking Android version on device
-NdkGdbLaunchDelegate_Action_KillExistingGdbServer=Killing existing gdbserver
-NdkGdbLaunchDelegate_Action_LaunchHostGdb=Launching host gdb
-NdkGdbLaunchDelegate_Action_LaunchingGdbServer=Launching gdbserver
-NdkGdbLaunchDelegate_Action_ObtainAppAbis=Obtaining ABI's supported by the application
-NdkGdbLaunchDelegate_Action_ObtainDevice=Obtaining device to use
-NdkGdbLaunchDelegate_Action_ObtainDeviceABI=Obtaining ABI's supported by the device
-NdkGdbLaunchDelegate_Action_PerformIncrementalBuild=Performing Incremental Build
-NdkGdbLaunchDelegate_Action_SettingUpPortForward=Setting up port forwarding
-NdkGdbLaunchDelegate_Action_SyncAppToDevice=Syncing application to device
-NdkGdbLaunchDelegate_Action_WaitGdbServerAttach=Waiting for gdbserver to attach to process
-NdkGdbLaunchDelegate_Action_WaitingForActivity=Waiting for activity to be launched
-NdkGdbLaunchDelegate_LaunchError_ActivityLaunchError=Error launching activity
-NdkGdbLaunchDelegate_LaunchError_Api8Needed=Native debugging requires API level 8 or above.
-NdkGdbLaunchDelegate_LaunchError_CouldNotGetProject=Couldn't get project object\!
-NdkGdbLaunchDelegate_LaunchError_gdbserverLaunchException=Exception while launching gdbserver:
-NdkGdbLaunchDelegate_LaunchError_gdbserverOutput=gdbserver output:
-NdkGdbLaunchDelegate_LaunchError_InstallError=Installation error
-NdkGdbLaunchDelegate_LaunchError_InterruptedWaitingForGdbserver=Interrupted while waiting for gdbserver to attach
-NdkGdbLaunchDelegate_LaunchError_NoActivityInManifest=The Manifest defines no activity\!
-NdkGdbLaunchDelegate_LaunchError_NoCompatibleAbi=Unable to find a compatible ABI
-NdkGdbLaunchDelegate_LaunchError_NoLauncherActivity=No launcher activity specified. Aborting launch.
-NdkGdbLaunchDelegate_LaunchError_NoSuchActivity=The specified activity does not exist\! Getting the launcher activity.
-NdkGdbLaunchDelegate_LaunchError_NullApk=Null APK
-NdkGdbLaunchDelegate_LaunchError_ObtainingAppFolder=Error while obtaining application data folder on device
-NdkGdbLaunchDelegate_LaunchError_PortForwarding=Error while setting up port forwarding
-NdkGdbLaunchDelegate_LaunchError_ProjectHasErrors=Your project contains error(s), please fix them before running your application.
-NdkGdbLaunchDelegate_LaunchError_PullFileError=Error while obtaining file from device
-NdkGdbLaunchDelegate_LaunchError_UnableToDetectAppAbi=Unable to detect application ABI's
-NdkGdbLaunchDelegate_LaunchError_UnknownAndroidDeviceVersion=Unknown Android version on device.
-NdkGdbLaunchDelegate_LaunchError_VerifyIfDebugBuild=Verify if the application was built with NDK_DEBUG=1
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/messages.properties b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/messages.properties
deleted file mode 100644
index 63400ffc7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/messages.properties
+++ /dev/null
@@ -1,16 +0,0 @@
-AddNativeWizardPage_Description=Settings for generated native components for project.
-AddNativeWizardPage_LibraryName=Library Name:
-AddNativeWizardPage_Location_not_valid=NDK location not valid in preferences.
-AddNativeWizardPage_Title=Add Android Native Support
-NDKPreferencePage_Location=NDK Location
-NDKPreferencePage_not_a_valid_directory=Not a valid directory
-NDKPreferencePage_not_a_valid_NDK_directory=Not a valid NDK directory
-NDKPreferencePage_Preferences=Android NDK Preferences
-SetFolders_Missing_project_name=Missing project name
-SetFolders_No_folders=No folders
-SetFolders_Project_does_not_exist=Project does not exist
-SimpleFile_Bad_file_operation=bad file operation
-SimpleFile_Bundle_not_found=bundle not found
-SimpleFile_Could_not_fine_source=could not find source file:
-SimpleFile_No_project_name=no project name
-SimpleFile_Project_does_not_exist=project does not exist
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/preferences/NdkPreferenceInitializer.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/preferences/NdkPreferenceInitializer.java
deleted file mode 100644
index 9c0350517..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/preferences/NdkPreferenceInitializer.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal.preferences;
-
-import com.android.ide.eclipse.ndk.internal.Activator;
-import com.android.ide.eclipse.ndk.internal.NdkManager;
-
-import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
-import org.eclipse.jface.preference.IPreferenceStore;
-
-public class NdkPreferenceInitializer extends AbstractPreferenceInitializer {
-
- @Override
- public void initializeDefaultPreferences() {
- IPreferenceStore store = Activator.getDefault().getPreferenceStore();
-
- store.setDefault(NdkManager.NDK_LOCATION, ""); //$NON-NLS-1$
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/preferences/NdkPreferencePage.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/preferences/NdkPreferencePage.java
deleted file mode 100644
index e1ab24768..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/preferences/NdkPreferencePage.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal.preferences;
-
-import com.android.ide.eclipse.ndk.internal.Activator;
-import com.android.ide.eclipse.ndk.internal.Messages;
-import com.android.ide.eclipse.ndk.internal.NdkManager;
-
-import org.eclipse.jface.preference.DirectoryFieldEditor;
-import org.eclipse.jface.preference.FieldEditorPreferencePage;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Text;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-
-public class NdkPreferencePage extends FieldEditorPreferencePage implements
- IWorkbenchPreferencePage {
-
- private NdkDirectoryFieldEditor mNdkDirectoryEditor;
-
- public NdkPreferencePage() {
- super(GRID);
- setPreferenceStore(Activator.getDefault().getPreferenceStore());
- setDescription(Messages.NDKPreferencePage_Preferences);
- }
-
- @Override
- protected void createFieldEditors() {
- mNdkDirectoryEditor = new NdkDirectoryFieldEditor(NdkManager.NDK_LOCATION,
- Messages.NDKPreferencePage_Location, getFieldEditorParent());
- addField(mNdkDirectoryEditor);
- }
-
- private static class NdkDirectoryFieldEditor extends DirectoryFieldEditor {
- public NdkDirectoryFieldEditor(String name, String labelText, Composite parent) {
- super(name, labelText, parent);
- setEmptyStringAllowed(true);
- }
-
- @Override
- protected boolean doCheckState() {
- if (!super.doCheckState()) {
- setErrorMessage(Messages.NDKPreferencePage_not_a_valid_directory);
- return false;
- }
-
- String dirname = getTextControl().getText().trim();
- if (!dirname.isEmpty() && !NdkManager.isValidNdkLocation(dirname)) {
- setErrorMessage(Messages.NDKPreferencePage_not_a_valid_NDK_directory);
- return false;
- }
-
- return true;
- }
-
- @Override
- public Text getTextControl(Composite parent) {
- setValidateStrategy(VALIDATE_ON_KEY_STROKE);
- return super.getTextControl(parent);
- }
-
- }
-
- @Override
- public void init(IWorkbench workbench) {
- // Nothing to do herea
- }
-
- @Override
- public void dispose() {
- super.dispose();
-
- if (mNdkDirectoryEditor != null) {
- mNdkDirectoryEditor.dispose();
- mNdkDirectoryEditor = null;
- }
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/templates/SetFolders.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/templates/SetFolders.java
deleted file mode 100644
index 2e8f714bb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/templates/SetFolders.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal.templates;
-
-import com.android.ide.eclipse.ndk.internal.Messages;
-
-import org.eclipse.cdt.core.CCorePlugin;
-import org.eclipse.cdt.core.model.CoreModel;
-import org.eclipse.cdt.core.model.ICProject;
-import org.eclipse.cdt.core.model.IPathEntry;
-import org.eclipse.cdt.core.templateengine.TemplateCore;
-import org.eclipse.cdt.core.templateengine.process.ProcessArgument;
-import org.eclipse.cdt.core.templateengine.process.ProcessFailureException;
-import org.eclipse.cdt.core.templateengine.process.ProcessRunner;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.Path;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class SetFolders extends ProcessRunner {
-
- @Override
- public void process(TemplateCore template, ProcessArgument[] args, String processId,
- IProgressMonitor monitor)
- throws ProcessFailureException {
- String projectName = null;
- String[] sourceFolders = null;
- String[] outputFolders = null;
-
- for (ProcessArgument arg : args) {
- String argName = arg.getName();
- if (argName.equals("projectName")) { //$NON-NLS-1$
- projectName = arg.getSimpleValue();
- } else if (argName.equals("sourceFolders")) { //$NON-NLS-1$
- sourceFolders = arg.getSimpleArrayValue();
- } else if (argName.equals("outputFolders")) { //$NON-NLS-1$
- outputFolders = arg.getSimpleArrayValue();
- }
- }
-
- // Get the project
- if (projectName == null)
- throw new ProcessFailureException(Messages.SetFolders_Missing_project_name);
-
- IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
- if (!project.exists())
- throw new ProcessFailureException(Messages.SetFolders_Project_does_not_exist);
-
- // Create the folders
- if (sourceFolders == null && outputFolders == null)
- throw new ProcessFailureException(Messages.SetFolders_No_folders);
-
- try {
- // Add them in
- ICProject cproject = CCorePlugin.getDefault().getCoreModel().create(project);
- IPathEntry[] pathEntries = cproject.getRawPathEntries();
- List<IPathEntry> newEntries = new ArrayList<IPathEntry>(pathEntries.length);
- for (IPathEntry pathEntry : pathEntries) {
- // remove the old source and output entries
- if (pathEntry.getEntryKind() != IPathEntry.CDT_SOURCE
- && pathEntry.getEntryKind() != IPathEntry.CDT_OUTPUT) {
- newEntries.add(pathEntry);
- }
- }
- if (sourceFolders != null)
- for (String sourceFolder : sourceFolders) {
- IFolder folder = project.getFolder(new Path(sourceFolder));
- if (!folder.exists())
- folder.create(true, true, monitor);
- newEntries.add(CoreModel.newSourceEntry(folder.getFullPath()));
- }
- if (outputFolders != null)
- for (String outputFolder : outputFolders) {
- IFolder folder = project.getFolder(new Path(outputFolder));
- if (!folder.exists())
- folder.create(true, true, monitor);
- newEntries.add(CoreModel.newOutputEntry(folder.getFullPath()));
- }
- cproject.setRawPathEntries(newEntries.toArray(new IPathEntry[newEntries.size()]),
- monitor);
- } catch (CoreException e) {
- throw new ProcessFailureException(e);
- }
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/templates/SimpleFile.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/templates/SimpleFile.java
deleted file mode 100644
index 7f249cacb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/templates/SimpleFile.java
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal.templates;
-
-import com.android.ide.eclipse.ndk.internal.Activator;
-import com.android.ide.eclipse.ndk.internal.Messages;
-
-import org.eclipse.cdt.core.templateengine.TemplateCore;
-import org.eclipse.cdt.core.templateengine.process.ProcessArgument;
-import org.eclipse.cdt.core.templateengine.process.ProcessFailureException;
-import org.eclipse.cdt.core.templateengine.process.ProcessRunner;
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.FileLocator;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.osgi.framework.Bundle;
-
-import java.io.IOException;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.List;
-
-public class SimpleFile extends ProcessRunner {
-
- private static final class FileOp {
- public String source;
- public String destination;
- }
-
- @Override
- public void process(TemplateCore template, ProcessArgument[] args, String processId,
- IProgressMonitor monitor)
- throws ProcessFailureException {
-
- // Fetch the args
- String projectName = null;
- List<FileOp> fileOps = new ArrayList<FileOp>();
-
- for (ProcessArgument arg : args) {
- if (arg.getName().equals("projectName")) //$NON-NLS-1$
- projectName = arg.getSimpleValue();
- else if (arg.getName().equals("files")) { //$NON-NLS-1$
- ProcessArgument[][] files = arg.getComplexArrayValue();
- for (ProcessArgument[] file : files) {
- FileOp op = new FileOp();
- for (ProcessArgument fileArg : file) {
- if (fileArg.getName().equals("source")) //$NON-NLS-1$
- op.source = fileArg.getSimpleValue();
- else if (fileArg.getName().equals("destination")) //$NON-NLS-1$
- op.destination = fileArg.getSimpleValue();
- }
- if (op.source == null || op.destination == null)
- throw new ProcessFailureException(Messages.SimpleFile_Bad_file_operation);
- fileOps.add(op);
- }
- }
- }
-
- if (projectName == null)
- throw new ProcessFailureException(Messages.SimpleFile_No_project_name);
- IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName);
- if (!project.exists())
- throw new ProcessFailureException(Messages.SimpleFile_Project_does_not_exist);
-
- // Find bundle to find source files
- Bundle bundle = Activator.getBundle(template.getTemplateInfo().getPluginId());
- if (bundle == null)
- throw new ProcessFailureException(Messages.SimpleFile_Bundle_not_found);
-
- try {
- for (FileOp op : fileOps) {
- IFile destFile = project.getFile(new Path(op.destination));
- if (destFile.exists())
- // don't overwrite files if they exist already
- continue;
-
- // Make sure parent folders are created
- mkDirs(project, destFile.getParent(), monitor);
-
- URL sourceURL = FileLocator.find(bundle, new Path(op.source), null);
- if (sourceURL == null)
- throw new ProcessFailureException(Messages.SimpleFile_Could_not_fine_source
- + op.source);
-
- TemplatedInputStream in = new TemplatedInputStream(sourceURL.openStream(),
- template.getValueStore());
- destFile.create(in, true, monitor);
- in.close();
- }
- } catch (IOException e) {
- throw new ProcessFailureException(e);
- } catch (CoreException e) {
- throw new ProcessFailureException(e);
- }
-
- }
-
- private void mkDirs(IProject project, IContainer container, IProgressMonitor monitor)
- throws CoreException {
- if (container.exists())
- return;
- mkDirs(project, container.getParent(), monitor);
- ((IFolder) container).create(true, true, monitor);
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/templates/TemplatedInputStream.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/templates/TemplatedInputStream.java
deleted file mode 100644
index 129caa327..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/templates/TemplatedInputStream.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal.templates;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Map;
-
-/**
- * Reads from a template substituting marked values from the supplied Map.
- */
-public class TemplatedInputStream extends InputStream {
-
- private final InputStream mIn;
- private final Map<String, String> mMap;
- private char[] mSub;
- private int mPos;
- private int mMark;
-
- public TemplatedInputStream(InputStream in, Map<String, String> map) {
- this.mIn = in;
- this.mMap = map;
- }
-
- @Override
- public int read() throws IOException {
- // if from a mark, return the char
- if (mMark != 0) {
- int c = mMark;
- mMark = 0;
- return c;
- }
-
- // return char from sub layer if available
- if (mSub != null) {
- char c = mSub[mPos++];
- if (mPos >= mSub.length)
- mSub = null;
- return c;
- }
-
- int c = mIn.read();
- if (c == '%') {
- // check if it's a sub
- c = mIn.read();
- if (c == '{') {
- // it's a sub
- StringBuffer buff = new StringBuffer();
- for (c = mIn.read(); c != '}' && c >= 0; c = mIn.read())
- buff.append((char) c);
- String str = mMap.get(buff.toString());
- if (str != null) {
- mSub = str.toCharArray();
- mPos = 0;
- }
- return read(); // recurse to get the real char
- } else {
- // not a sub
- mMark = c;
- return '%';
- }
- }
-
- return c;
- }
-
- @Override
- public void close() throws IOException {
- super.close();
- mIn.close();
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/wizards/AddNativeWizard.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/wizards/AddNativeWizard.java
deleted file mode 100644
index b3675ed27..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/wizards/AddNativeWizard.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal.wizards;
-
-import com.android.ide.eclipse.ndk.internal.Activator;
-import com.android.ide.eclipse.ndk.internal.NdkManager;
-
-import org.eclipse.cdt.core.CCorePlugin;
-import org.eclipse.cdt.make.core.MakeCorePlugin;
-import org.eclipse.cdt.ui.CUIPlugin;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.IWorkspaceRunnable;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.wizard.Wizard;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.WorkbenchException;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.HashMap;
-import java.util.Map;
-
-public class AddNativeWizard extends Wizard {
-
- private final IProject mProject;
- private final IWorkbenchWindow mWindow;
-
- private AddNativeWizardPage mAddNativeWizardPage;
- private Map<String, String> mTemplateArgs = new HashMap<String, String>();
-
- public AddNativeWizard(IProject project, IWorkbenchWindow window) {
- mProject = project;
- mWindow = window;
- mTemplateArgs.put(NdkManager.LIBRARY_NAME, project.getName());
- }
-
- @Override
- public void addPages() {
- mAddNativeWizardPage = new AddNativeWizardPage(mTemplateArgs);
- addPage(mAddNativeWizardPage);
- }
-
- @Override
- public boolean performFinish() {
- // Switch to C/C++ Perspective
- try {
- mWindow.getWorkbench().showPerspective(CUIPlugin.ID_CPERSPECTIVE, mWindow);
- } catch (WorkbenchException e1) {
- Activator.log(e1);
- }
-
- mAddNativeWizardPage.updateArgs(mTemplateArgs);
-
- IRunnableWithProgress op = new IRunnableWithProgress() {
- @Override
- public void run(IProgressMonitor monitor) throws InvocationTargetException,
- InterruptedException {
- IWorkspaceRunnable op1 = new IWorkspaceRunnable() {
- @Override
- public void run(IProgressMonitor monitor1) throws CoreException {
- // Convert to CDT project
- CCorePlugin.getDefault().convertProjectToCC(mProject, monitor1,
- MakeCorePlugin.MAKE_PROJECT_ID);
- // Set up build information
- new NdkWizardHandler().convertProject(mProject, monitor1);
-
- // When using CDT 8.1.x, disable the language settings provider mechanism
- // for scanner discovery. Use the classloader to load the class since it
- // will not be available pre 8.1.
- try {
- @SuppressWarnings("rawtypes")
- Class c = getClass().getClassLoader().loadClass(
- "org.eclipse.cdt.core.language.settings.providers.ScannerDiscoveryLegacySupport"); //$NON-NLS-1$
-
- @SuppressWarnings("unchecked")
- Method m = c.getMethod(
- "setLanguageSettingsProvidersFunctionalityEnabled", //$NON-NLS-1$
- IProject.class, boolean.class);
-
- m.invoke(null, mProject, false);
- } catch (Exception e) {
- // ignore all exceptions: On pre 8.1.x CDT, this class will not be
- // found, but this options only needs to be set in 8.1.x
- }
-
- // Run the template
- NdkManager.addNativeSupport(mProject, mTemplateArgs, monitor1);
- }
- };
- // TODO run from a job
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- try {
- workspace.run(op1, workspace.getRoot(), 0, new NullProgressMonitor());
- } catch (CoreException e) {
- throw new InvocationTargetException(e);
- }
- }
- };
- try {
- getContainer().run(false, true, op);
- return true;
- } catch (InterruptedException e) {
- Activator.log(e);
- return false;
- } catch (InvocationTargetException e) {
- Activator.log(e);
- return false;
- }
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/wizards/AddNativeWizardPage.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/wizards/AddNativeWizardPage.java
deleted file mode 100644
index 65af270b0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/wizards/AddNativeWizardPage.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal.wizards;
-
-import com.android.ide.eclipse.ndk.internal.Messages;
-import com.android.ide.eclipse.ndk.internal.NdkManager;
-
-import org.eclipse.jface.wizard.WizardPage;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Text;
-
-import java.util.Map;
-
-public class AddNativeWizardPage extends WizardPage {
-
- private final String defaultLibraryName;
-
- private Text libraryNameText;
-
- public AddNativeWizardPage(Map<String, String> templateArgs) {
- super("addNativeWizardPage"); //$NON-NLS-1$
- setDescription(Messages.AddNativeWizardPage_Description);
- setTitle(Messages.AddNativeWizardPage_Title);
-
- defaultLibraryName = templateArgs.get(NdkManager.LIBRARY_NAME);
- if (!NdkManager.isNdkLocationValid()) {
- setErrorMessage(Messages.AddNativeWizardPage_Location_not_valid);
- }
- }
-
- @Override
- public boolean isPageComplete() {
- return NdkManager.isNdkLocationValid();
- }
-
- @Override
- public void createControl(Composite parent) {
- Composite container = new Composite(parent, SWT.NULL);
- setControl(container);
- container.setLayout(new GridLayout(2, false));
-
- Label lblLibraryName = new Label(container, SWT.NONE);
- lblLibraryName.setText(Messages.AddNativeWizardPage_LibraryName);
-
- Composite composite = new Composite(container, SWT.NONE);
- composite.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- composite.setLayout(new GridLayout(3, false));
-
- Label lblLib = new Label(composite, SWT.NONE);
- lblLib.setText("lib"); //$NON-NLS-1$
-
- libraryNameText = new Text(composite, SWT.BORDER);
- libraryNameText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
- libraryNameText.setText(defaultLibraryName);
-
- Label lblso = new Label(composite, SWT.NONE);
- lblso.setText(".so"); //$NON-NLS-1$
- }
-
- public void updateArgs(Map<String, String> templateArgs) {
- templateArgs.put(NdkManager.LIBRARY_NAME, libraryNameText.getText());
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/wizards/NdkWizardHandler.java b/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/wizards/NdkWizardHandler.java
deleted file mode 100644
index fa0b92bb0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/src/com/android/ide/eclipse/ndk/internal/wizards/NdkWizardHandler.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.ndk.internal.wizards;
-
-import org.eclipse.cdt.managedbuilder.core.IToolChain;
-import org.eclipse.cdt.managedbuilder.core.ManagedBuildManager;
-import org.eclipse.cdt.managedbuilder.ui.wizards.STDWizardHandler;
-
-public class NdkWizardHandler extends STDWizardHandler {
-
- public NdkWizardHandler() {
- super(null, null);
- }
-
- @Override
- public IToolChain[] getSelectedToolChains() {
- IToolChain[] tcs = ManagedBuildManager.getRealToolChains();
- for (IToolChain tc : tcs) {
- if (tc.getId().equals("com.android.toolchain.gcc")) //$NON-NLS-1$
- return new IToolChain[] {
- tc
- };
- }
- return super.getSelectedToolChains();
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/templates/addNdkSupport.xml b/eclipse/plugins/com.android.ide.eclipse.ndk/templates/addNdkSupport.xml
deleted file mode 100644
index 40c795460..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/templates/addNdkSupport.xml
+++ /dev/null
@@ -1,33 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<template
- type="ProjTempl"
- version="1.0"
- revision="1.0"
- id="AddNdkSupport"
- label="Add Android NDK Support"
- description="Adds NDK support to Android Java projects"
- help="help.html">
- <process type="com.android.ide.eclipse.ndk.SetFolders">
- <simple name="projectName" value="$(projectName)"/>
- <simple-array name="sourceFolders">
- <element value="jni"/>
- </simple-array>
- <simple-array name="outputFolders">
- <element value="obj"/>
- <element value="libs"/>
- </simple-array>
- </process>
- <process type="com.android.ide.eclipse.ndk.SimpleFile">
- <simple name="projectName" value="$(projectName)"/>
- <complex-array name="files">
- <element>
- <simple name="source" value="templates/resources/tAndroid.mk"/>
- <simple name="destination" value="jni/Android.mk"/>
- </element>
- <element>
- <simple name="source" value="templates/resources/main.cpp"/>
- <simple name="destination" value="jni/$(libraryName).cpp"/>
- </element>
- </complex-array>
- </process>
-</template>
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/templates/resources/main.cpp b/eclipse/plugins/com.android.ide.eclipse.ndk/templates/resources/main.cpp
deleted file mode 100644
index 6434c6677..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/templates/resources/main.cpp
+++ /dev/null
@@ -1 +0,0 @@
-#include <jni.h>
diff --git a/eclipse/plugins/com.android.ide.eclipse.ndk/templates/resources/tAndroid.mk b/eclipse/plugins/com.android.ide.eclipse.ndk/templates/resources/tAndroid.mk
deleted file mode 100644
index cd9d479db..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.ndk/templates/resources/tAndroid.mk
+++ /dev/null
@@ -1,8 +0,0 @@
-LOCAL_PATH := $(call my-dir)
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := %{libraryName}
-LOCAL_SRC_FILES := %{libraryName}.cpp
-
-include $(BUILD_SHARED_LIBRARY)
diff --git a/eclipse/plugins/com.android.ide.eclipse.pdt/.classpath b/eclipse/plugins/com.android.ide.eclipse.pdt/.classpath
deleted file mode 100644
index 751c8f2e5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.pdt/.classpath
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="src" path="src"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
diff --git a/eclipse/plugins/com.android.ide.eclipse.pdt/.project b/eclipse/plugins/com.android.ide.eclipse.pdt/.project
deleted file mode 100644
index 091b01328..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.pdt/.project
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>plugin-pdt</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
diff --git a/eclipse/plugins/com.android.ide.eclipse.pdt/.settings/org.eclipse.jdt.core.prefs b/eclipse/plugins/com.android.ide.eclipse.pdt/.settings/org.eclipse.jdt.core.prefs
deleted file mode 100644
index ea661960a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.pdt/.settings/org.eclipse.jdt.core.prefs
+++ /dev/null
@@ -1,98 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore
-org.eclipse.jdt.core.compiler.annotation.nonnull=com.android.annotations.NonNull
-org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=com.android.annotations.NonNullByDefault
-org.eclipse.jdt.core.compiler.annotation.nonnullisdefault=disabled
-org.eclipse.jdt.core.compiler.annotation.nullable=com.android.annotations.Nullable
-org.eclipse.jdt.core.compiler.annotation.nullanalysis=enabled
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
-org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
-org.eclipse.jdt.core.compiler.compliance=1.6
-org.eclipse.jdt.core.compiler.debug.lineNumber=generate
-org.eclipse.jdt.core.compiler.debug.localVariable=generate
-org.eclipse.jdt.core.compiler.debug.sourceFile=generate
-org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
-org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
-org.eclipse.jdt.core.compiler.problem.deadCode=warning
-org.eclipse.jdt.core.compiler.problem.deprecation=warning
-org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
-org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
-org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
-org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore
-org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning
-org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled
-org.eclipse.jdt.core.compiler.problem.fieldHiding=warning
-org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
-org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
-org.eclipse.jdt.core.compiler.problem.forbiddenReference=error
-org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
-org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=enabled
-org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
-org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning
-org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
-org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning
-org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
-org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore
-org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled
-org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=warning
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=error
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
-org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
-org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
-org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
-org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
-org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
-org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=warning
-org.eclipse.jdt.core.compiler.problem.nullReference=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecInsufficientInfo=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecViolation=warning
-org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=ignore
-org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
-org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
-org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullSpecViolation=error
-org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=warning
-org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=warning
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
-org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
-org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
-org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=enabled
-org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
-org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
-org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning
-org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=disabled
-org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
-org.eclipse.jdt.core.compiler.problem.unclosedCloseable=error
-org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
-org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
-org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning
-org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
-org.eclipse.jdt.core.compiler.problem.unusedImport=warning
-org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
-org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
-org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=warning
-org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
-org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
-org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
-org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
-org.eclipse.jdt.core.compiler.source=1.6
diff --git a/eclipse/plugins/com.android.ide.eclipse.pdt/META-INF/MANIFEST.MF b/eclipse/plugins/com.android.ide.eclipse.pdt/META-INF/MANIFEST.MF
deleted file mode 100644
index a888ae462..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.pdt/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,21 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: Pdt
-Bundle-SymbolicName: com.android.ide.eclipse.pdt;singleton:=true
-Bundle-Version: 24.3.3.qualifier
-Bundle-Vendor: The Android Open Source Project
-Require-Bundle: org.eclipse.ui,
- org.eclipse.core.runtime,
- com.android.ide.eclipse.ddms,
- org.eclipse.core.resources,
- org.eclipse.jdt.core,
- org.eclipse.jdt.ui,
- org.eclipse.jface.text,
- org.eclipse.ui.editors,
- org.eclipse.jdt.launching,
- org.eclipse.debug.core,
- org.eclipse.debug.ui,
- org.eclipse.ui.ide
-Bundle-Activator: com.android.ide.eclipse.pdt.PdtPlugin
-Bundle-ActivationPolicy: lazy
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
diff --git a/eclipse/plugins/com.android.ide.eclipse.pdt/build.properties b/eclipse/plugins/com.android.ide.eclipse.pdt/build.properties
deleted file mode 100644
index e9863e281..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.pdt/build.properties
+++ /dev/null
@@ -1,5 +0,0 @@
-source.. = src/
-output.. = bin/
-bin.includes = META-INF/,\
- .,\
- plugin.xml
diff --git a/eclipse/plugins/com.android.ide.eclipse.pdt/plugin.xml b/eclipse/plugins/com.android.ide.eclipse.pdt/plugin.xml
deleted file mode 100644
index b2d622a6d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.pdt/plugin.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<?eclipse version="3.4"?>
-<plugin>
- <extension
- point="org.eclipse.ui.preferencePages">
- <page
- class="com.android.ide.eclipse.pdt.internal.preferences.PrefPage"
- id="com.android.ide.eclipse.preferences.main"
- name="Android"/>
- </extension>
- <extension
- point="com.android.ide.eclipse.ddms.toolsLocator">
- <locator
- class="com.android.ide.eclipse.pdt.internal.ToolsLocator">
- </locator>
- </extension>
- <extension
- point="com.android.ide.eclipse.ddms.debuggerConnector">
- <connector
- class="com.android.ide.eclipse.pdt.internal.DebuggerConnector">
- </connector>
- </extension>
- <extension
- point="com.android.ide.eclipse.ddms.sourceRevealer">
- <revealer
- class="com.android.ide.eclipse.pdt.internal.SourceRevealer">
- </revealer>
- </extension>
-
-</plugin>
diff --git a/eclipse/plugins/com.android.ide.eclipse.pdt/src/com/android/ide/eclipse/pdt/PdtPlugin.java b/eclipse/plugins/com.android.ide.eclipse.pdt/src/com/android/ide/eclipse/pdt/PdtPlugin.java
deleted file mode 100644
index 3b538505d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.pdt/src/com/android/ide/eclipse/pdt/PdtPlugin.java
+++ /dev/null
@@ -1,146 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.pdt;
-
-import com.android.ide.eclipse.ddms.DdmsPlugin;
-import com.android.ide.eclipse.pdt.internal.preferences.PrefPage;
-
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.util.IPropertyChangeListener;
-import org.eclipse.jface.util.PropertyChangeEvent;
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.osgi.framework.BundleContext;
-
-public class PdtPlugin extends AbstractUIPlugin {
-
- public final static String PLUGIN_ID = "com.android.ide.eclipse.pdt"; //$NON-NLS-1$
- private static PdtPlugin sPlugin;
-
- public PdtPlugin() {
- sPlugin = this;
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static synchronized PdtPlugin getDefault() {
- return sPlugin;
- }
-
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
-
- // set the listener for the preference change
- getPreferenceStore().addPropertyChangeListener(new IPropertyChangeListener() {
- @Override
- public void propertyChange(PropertyChangeEvent event) {
- // if the SDK changed, we have to do some extra work
- if (PrefPage.PREFS_DEVTREE_DIR.equals(event.getProperty())) {
- // restart adb, in case it's a different version
- DdmsPlugin.setToolsLocation(getAdbLocation(), true /* startAdb */,
- getHprofConvLocation(), getTraceViewLocation());
- }
- }
- });
- }
-
- /**
- * Returns the location of the dev tree or <code>null</code> if unknown.
- */
- public static String getDevTree() {
- // this always return a store, even a temp one if an error occurred.
- IPreferenceStore store = sPlugin.getPreferenceStore();
-
- // returns an empty, non-null, string if the preference is not found.
- String devTree = store.getString(PrefPage.PREFS_DEVTREE_DIR);
-
- if (devTree.length() == 0) {
- devTree = System.getenv("ANDROID_BUILD_TOP"); //$NON-NLS-1$
- }
-
- return devTree;
- }
-
- /**
- * Returns the location of adb or <code>null</code> if unknown.
- */
- public static String getAdbLocation() {
- String devTreeBin = getDevTreeOutBin();
-
- if (devTreeBin != null && devTreeBin.length() > 0) {
- return devTreeBin + "adb"; //$NON-NLS-1$
- }
-
- return null;
- }
-
- /**
- * Returns the location of hprof-conv or <code>null</code> if unknown.
- */
- public static String getHprofConvLocation() {
- String devTreeBin = getDevTreeOutBin();
-
- if (devTreeBin != null && devTreeBin.length() > 0) {
- return devTreeBin + "hprof-conv"; //$NON-NLS-1$
- }
-
- return null;
- }
-
- /**
- * Returns the location of traceview or <code>null</code> if unknown.
- */
- public static String getTraceViewLocation() {
- String devTreeBin = getDevTreeOutBin();
-
- if (devTreeBin != null && devTreeBin.length() > 0) {
- return devTreeBin + "traceview"; //$NON-NLS-1$
- }
-
- return null;
- }
-
- private static String getDevTreeOutBin() {
- String devTree = getDevTree();
-
- if (devTree != null && devTree.length() > 0) {
- return devTree + "/out/host/" + currentPlatform() + "/bin/"; //$NON-NLS-1$ //$NON-NLS-2$
- }
-
- return null;
- }
-
- /**
- * Returns the current platform name as used by the Android build system
- *
- */
- private static String currentPlatform() {
- String os = System.getProperty("os.name"); //$NON-NLS-1$
- if (os.startsWith("Mac OS")) { //$NON-NLS-1$
- return "darwin-x86"; //$NON-NLS-1$
- } else if (os.startsWith("Windows")) { //$NON-NLS-1$
- return "windows"; //$NON-NLS-1$
- } else if (os.startsWith("Linux")) { //$NON-NLS-1$
- return "linux-x86"; //$NON-NLS-1$
- }
-
- return ""; //$NON-NLS-1$
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.pdt/src/com/android/ide/eclipse/pdt/internal/DebuggerConnector.java b/eclipse/plugins/com.android.ide.eclipse.pdt/src/com/android/ide/eclipse/pdt/internal/DebuggerConnector.java
deleted file mode 100644
index 238cad32f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.pdt/src/com/android/ide/eclipse/pdt/internal/DebuggerConnector.java
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.pdt.internal;
-
-import com.android.ide.eclipse.ddms.IDebuggerConnector;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.debug.core.DebugPlugin;
-import org.eclipse.debug.core.ILaunchConfiguration;
-import org.eclipse.debug.core.ILaunchConfigurationType;
-import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
-import org.eclipse.debug.core.ILaunchManager;
-import org.eclipse.debug.ui.DebugUITools;
-import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Implementation of the com.android.ide.ddms.debuggerConnector extension point.
- */
-public class DebuggerConnector extends DevTreeProjectProvider implements IDebuggerConnector {
-
- private final static String ATTR_CONNECT_MAP_PORT = "port"; //$NON-NLS-1$
- private final static String ATTR_CONNECT_MAP_HOSTNAME = "hostname"; //$NON-NLS-1$
-
- @Override
- public boolean isWorkspaceApp(String appName) {
- return getProject() != null;
- }
-
- @Override
- public boolean connectDebugger(String appName, int appPort, int selectedPort) {
- IProject project = getProject();
-
- if (project != null) {
- // get the launch manager
- ILaunchManager manager = DebugPlugin.getDefault().getLaunchManager();
-
- // get the config for the remote launch config.
- ILaunchConfigurationType configType = manager.getLaunchConfigurationType(
- IJavaLaunchConfigurationConstants.ID_REMOTE_JAVA_APPLICATION);
-
- String projectName = project.getName();
-
- // look for an existing launch config
- ILaunchConfiguration config = findConfig(manager, configType, projectName,
- selectedPort);
-
- if (config == null) {
- // Didn't find a matching config, so we make one.
- // It'll be made in the "working copy" object first.
- ILaunchConfigurationWorkingCopy wc = null;
-
- try {
- // make the working copy object with a unique name
- wc = configType.newInstance(null,
- manager.generateUniqueLaunchConfigurationNameFrom(projectName));
-
- // set the project name
- wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME,
- projectName);
-
- // set the connect map info
- Map<String, String> connectMap = new HashMap<String, String>();
- connectMap.put(ATTR_CONNECT_MAP_PORT, Integer.toString(selectedPort));
- connectMap.put(ATTR_CONNECT_MAP_HOSTNAME, "localhost"); //$NON-NLS-1$
- wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_CONNECT_MAP, connectMap);
-
- // set the VM connector ID
- wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_VM_CONNECTOR,
- IJavaLaunchConfigurationConstants.ID_SOCKET_ATTACH_VM_CONNECTOR);
-
- // save the working copy to get the launch config object which we return.
- config = wc.doSave();
-
- } catch (CoreException e) {
-
- }
-
- }
-
- if (config != null) {
- DebugUITools.launch(config, ILaunchManager.DEBUG_MODE);
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * Looks for and returns an existing {@link ILaunchConfiguration} object for a
- * specified project and connection port.
- * @param manager The {@link ILaunchManager}.
- * @param type The {@link ILaunchConfigurationType}.
- * @param projectName The name of the project
- * @param connectionPort the remote connection port.
- * @return an existing <code>ILaunchConfiguration</code> object matching the project, or
- * <code>null</code>.
- */
- private static ILaunchConfiguration findConfig(ILaunchManager manager,
- ILaunchConfigurationType type,
- String projectName, int connectionPort) {
- try {
- ILaunchConfiguration[] configs = manager.getLaunchConfigurations(type);
-
- // look for one set up for the project with a debug equal to the selected debug port.
- for (ILaunchConfiguration config : configs) {
-
- Map<?, ?> attributes = config.getAttributes();
-
- String name = (String) attributes.get(
- IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME);
-
- if (name == null || name.equals(projectName) == false) {
- continue;
- }
-
- Map<?, ?> connectMap = (Map<?, ?>) attributes.get(
- IJavaLaunchConfigurationConstants.ATTR_CONNECT_MAP);
-
- if (connectMap != null) {
- String portStr = (String) connectMap.get(ATTR_CONNECT_MAP_PORT);
- if (portStr != null) {
- Integer port = Integer.valueOf(portStr);
- if (connectionPort == port) {
- return config;
- }
- }
- }
-
- }
- } catch (CoreException e) {
- }
-
- // didn't find anything that matches. Return null
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.pdt/src/com/android/ide/eclipse/pdt/internal/DevTreeProjectProvider.java b/eclipse/plugins/com.android.ide.eclipse.pdt/src/com/android/ide/eclipse/pdt/internal/DevTreeProjectProvider.java
deleted file mode 100644
index b44d2cb49..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.pdt/src/com/android/ide/eclipse/pdt/internal/DevTreeProjectProvider.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.pdt.internal;
-
-import com.android.ide.eclipse.pdt.PdtPlugin;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jface.viewers.IStructuredContentProvider;
-import org.eclipse.jface.viewers.LabelProvider;
-import org.eclipse.jface.viewers.Viewer;
-import org.eclipse.jface.window.Window;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.dialogs.ListDialog;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-/**
- * Base class providing a {@link #getProject()} method to find the project matching the dev tree.
- *
- */
-class DevTreeProjectProvider {
- protected IProject getProject() {
- // Get the list of project for the current workspace
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- List<IProject> projects = Arrays.asList(workspace.getRoot().getProjects());
- if (projects.size() == 0) {
- return null;
- }
-
- // get the location of the Dev tree
- String devTree = PdtPlugin.getDevTree();
- IPath devTreePath = null;
- if (devTree != null) {
- devTreePath = new Path(devTree);
- }
-
- // filter the list of projects in workspace by 2 conditions:
- // 1. Only look at Java projects
- // 2. If dev tree location is set, only look at projects within the dev tree
-
- List<IProject> devTreeProjects = new ArrayList<IProject>(projects.size());
-
- for (IProject p: projects) {
- if (!p.isOpen()) {
- continue;
- }
-
- if (!hasJavaNature(p)) {
- continue;
- }
-
- if (devTreePath == null || devTreePath.isPrefixOf(p.getLocation())) {
- devTreeProjects.add(p);
- }
- }
-
- return selectProject(devTreeProjects);
- }
-
- private IProject selectProject(List<IProject> devTreeProjects) {
- if (devTreeProjects.size() == 0) {
- return null;
- }
-
- if (devTreeProjects.size() == 1) {
- return devTreeProjects.get(0);
- }
-
- // if there are multiple choices, prompt the user
- IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
- if (window == null) {
- return null;
- }
-
- ListDialog dlg = new ListDialog(window.getShell());
- dlg.setMessage("Select Project");
- dlg.setInput(devTreeProjects);
- dlg.setContentProvider(new IStructuredContentProvider() {
- @Override
- public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
- }
-
- @Override
- public void dispose() {
- }
-
- @Override
- public Object[] getElements(Object inputElement) {
- return ((List<?>) inputElement).toArray();
- }
- });
- dlg.setLabelProvider(new LabelProvider() {
- @Override
- public String getText(Object element) {
- return ((IProject) element).getName();
- }
- });
- dlg.setHelpAvailable(false);
-
- if (dlg.open() == Window.OK) {
- Object[] selectedMatches = dlg.getResult();
- if (selectedMatches.length > 0) {
- return (IProject) selectedMatches[0];
- }
- }
-
- return null;
- }
-
- private boolean hasJavaNature(IProject p) {
- try {
- return p.hasNature(JavaCore.NATURE_ID);
- } catch (CoreException e) {
- return false;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.pdt/src/com/android/ide/eclipse/pdt/internal/SourceRevealer.java b/eclipse/plugins/com.android.ide.eclipse.pdt/src/com/android/ide/eclipse/pdt/internal/SourceRevealer.java
deleted file mode 100644
index 51011e119..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.pdt/src/com/android/ide/eclipse/pdt/internal/SourceRevealer.java
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.pdt.internal;
-
-import com.android.ide.eclipse.ddms.ISourceRevealer;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IMethod;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.core.JavaCore;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.core.search.IJavaSearchConstants;
-import org.eclipse.jdt.core.search.SearchEngine;
-import org.eclipse.jdt.core.search.SearchMatch;
-import org.eclipse.jdt.core.search.SearchParticipant;
-import org.eclipse.jdt.core.search.SearchPattern;
-import org.eclipse.jdt.core.search.SearchRequestor;
-import org.eclipse.jdt.ui.JavaUI;
-import org.eclipse.jdt.ui.actions.OpenJavaPerspectiveAction;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IPerspectiveRegistry;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.WorkbenchException;
-import org.eclipse.ui.texteditor.IDocumentProvider;
-import org.eclipse.ui.texteditor.ITextEditor;
-
-/**
- * Implementation of the com.android.ide.ddms.sourceRevealer extension point.
- * This implementation is a copy of com.android.ide.eclipse.adt.SourceRevealer.
- */
-public class SourceRevealer extends DevTreeProjectProvider implements ISourceRevealer {
-
- @Override
- public boolean reveal(String applicationName, String className, int line) {
- IProject project = getProject();
-
- if (project != null) {
- // Inner classes are pointless: All we need is the enclosing type to find the file,
- // and the line number.
- // Since the anonymous ones will cause IJavaProject#findType to fail, we remove
- // all of them.
- int pos = className.indexOf('$');
- if (pos != -1) {
- className = className.substring(0, pos);
- }
-
- // get the java project
- IJavaProject javaProject = JavaCore.create(project);
-
- try {
- // look for the IType matching the class name.
- IType result = javaProject.findType(className);
- if (result != null && result.exists()) {
- // before we show the type in an editor window, we make sure the current
- // workbench page has an editor area (typically the ddms perspective doesn't).
- IWorkbench workbench = PlatformUI.getWorkbench();
- IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
- IWorkbenchPage page = window.getActivePage();
- if (page.isEditorAreaVisible() == false) {
- // no editor area? we open the java perspective.
- new OpenJavaPerspectiveAction().run();
- }
-
- IEditorPart editor = JavaUI.openInEditor(result);
- if (editor instanceof ITextEditor) {
- // get the text editor that was just opened.
- ITextEditor textEditor = (ITextEditor)editor;
-
- IEditorInput input = textEditor.getEditorInput();
-
- // get the location of the line to show.
- IDocumentProvider documentProvider = textEditor.getDocumentProvider();
- IDocument document = documentProvider.getDocument(input);
- IRegion lineInfo = document.getLineInformation(line - 1);
-
- // select and reveal the line.
- textEditor.selectAndReveal(lineInfo.getOffset(), lineInfo.getLength());
- }
-
- return true;
- }
- } catch (JavaModelException e) {
- } catch (PartInitException e) {
- } catch (BadLocationException e) {
- }
- }
-
- return false;
- }
-
- @Override
- public boolean revealMethod(String fqmn, String fileName, int lineNumber, String perspective) {
- SearchEngine se = new SearchEngine();
- SearchPattern searchPattern = SearchPattern.createPattern(
- fqmn,
- IJavaSearchConstants.METHOD,
- IJavaSearchConstants.DECLARATIONS,
- SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);
- MethodSearchRequestor requestor = new MethodSearchRequestor(perspective);
- try {
- se.search(searchPattern,
- new SearchParticipant[] {SearchEngine.getDefaultSearchParticipant()},
- SearchEngine.createWorkspaceScope(),
- requestor,
- new NullProgressMonitor());
- } catch (CoreException e) {
- return false;
- }
-
- return requestor.didMatch();
- }
-
- private static class MethodSearchRequestor extends SearchRequestor {
- private boolean mFoundMatch = false;
- private final String mPerspective;
-
- public MethodSearchRequestor(String perspective) {
- mPerspective = perspective;
- }
-
- public boolean didMatch() {
- return mFoundMatch;
- }
-
- @Override
- public void acceptSearchMatch(SearchMatch match) throws CoreException {
- Object element = match.getElement();
- if (element instanceof IMethod && !mFoundMatch) {
- if (mPerspective != null) {
- SourceRevealer.switchToPerspective(mPerspective);
- }
-
- IMethod method = (IMethod) element;
- JavaUI.openInEditor(method);
- mFoundMatch = true;
- }
- }
- }
-
- public static void switchToPerspective(String perspectiveId) {
- IWorkbench workbench = PlatformUI.getWorkbench();
- IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
- IPerspectiveRegistry perspectiveRegistry = workbench.getPerspectiveRegistry();
- if (perspectiveId != null
- && perspectiveId.length() > 0
- && perspectiveRegistry.findPerspectiveWithId(perspectiveId) != null) {
- try {
- workbench.showPerspective(perspectiveId, window);
- } catch (WorkbenchException e) {
- // ignore exception, perspective won't be switched
- }
- }
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.pdt/src/com/android/ide/eclipse/pdt/internal/ToolsLocator.java b/eclipse/plugins/com.android.ide.eclipse.pdt/src/com/android/ide/eclipse/pdt/internal/ToolsLocator.java
deleted file mode 100644
index a7291cbc7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.pdt/src/com/android/ide/eclipse/pdt/internal/ToolsLocator.java
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.pdt.internal;
-
-import com.android.ide.eclipse.ddms.IToolsLocator;
-import com.android.ide.eclipse.pdt.PdtPlugin;
-
-/**
- * Implementation of the com.android.ide.ddms.adbLocator extension point.
- */
-public class ToolsLocator implements IToolsLocator {
-
- @Override
- public String getAdbLocation() {
- return PdtPlugin.getAdbLocation();
- }
-
- @Override
- public String getHprofConvLocation() {
- return PdtPlugin.getHprofConvLocation();
- }
-
- @Override
- public String getTraceViewLocation() {
- return PdtPlugin.getTraceViewLocation();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.pdt/src/com/android/ide/eclipse/pdt/internal/preferences/PrefPage.java b/eclipse/plugins/com.android.ide.eclipse.pdt/src/com/android/ide/eclipse/pdt/internal/preferences/PrefPage.java
deleted file mode 100644
index 565b6adbe..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.pdt/src/com/android/ide/eclipse/pdt/internal/preferences/PrefPage.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.pdt.internal.preferences;
-
-import com.android.ide.eclipse.pdt.PdtPlugin;
-
-import org.eclipse.jface.preference.DirectoryFieldEditor;
-import org.eclipse.jface.preference.FieldEditorPreferencePage;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPreferencePage;
-
-public class PrefPage extends FieldEditorPreferencePage implements
- IWorkbenchPreferencePage {
-
- public final static String PREFS_DEVTREE_DIR = PdtPlugin.PLUGIN_ID + ".devtree"; //$NON-NLS-1$
-
- private DirectoryFieldEditor mDirectoryField;
-
- public PrefPage() {
- super(GRID);
- IPreferenceStore store = PdtPlugin.getDefault().getPreferenceStore();
- setPreferenceStore(store);
- setDescription("Android Preferences");
- }
-
- @Override
- protected void createFieldEditors() {
- mDirectoryField = new DirectoryFieldEditor(PREFS_DEVTREE_DIR,
- "Dev Tree Location:", getFieldEditorParent());
-
- addField(mDirectoryField);
- }
-
- @Override
- public void init(IWorkbench workbench) {
- }
-
- @Override
- public void dispose() {
- super.dispose();
-
- if (mDirectoryField != null) {
- mDirectoryField.dispose();
- mDirectoryField = null;
- }
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/.classpath b/eclipse/plugins/com.android.ide.eclipse.tests/.classpath
deleted file mode 100644
index f76017492..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/.classpath
+++ /dev/null
@@ -1,24 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="src" path="src"/>
- <classpathentry kind="src" path="unittests"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry kind="output" path="bin"/>
- <classpathentry kind="lib" path="libs/kxml2-2.3.0.jar"/>
- <classpathentry kind="lib" path="libs/easymock.jar"/>
- <classpathentry kind="lib" path="libs/testutils.jar"/>
- <classpathentry kind="lib" path="/plugin-adt/libs/ninepatch.jar" sourcepath="/ninepatch"/>
- <classpathentry kind="lib" path="/plugin-base/libs/sdklib.jar" sourcepath="/SdkLib"/>
- <classpathentry kind="lib" path="/plugin-adt/libs/sdkuilib.jar" sourcepath="/SdkUiLib"/>
- <classpathentry kind="lib" path="/plugin-adt/libs/rule-api.jar" sourcepath="/rule-api"/>
- <classpathentry kind="lib" path="/plugin-base/libs/common.jar" sourcepath="/common"/>
- <classpathentry kind="lib" path="/plugin-adt/libs/lint-api.jar" sourcepath="/lint-api"/>
- <classpathentry kind="lib" path="/plugin-adt/libs/lint-checks.jar" sourcepath="/lint-checks"/>
- <classpathentry kind="lib" path="/plugin-base/libs/sdk-common.jar"/>
- <classpathentry kind="lib" path="/plugin-adt/libs/lombok-ast-0.2.2.jar"/>
- <classpathentry kind="lib" path="/plugin-adt/libs/asm-5.0.3.jar"/>
- <classpathentry kind="lib" path="/plugin-adt/libs/asm-analysis-5.0.3.jar"/>
- <classpathentry kind="lib" path="/plugin-adt/libs/asm-tree-5.0.3.jar"/>
- <classpathentry kind="lib" path="/plugin-adt/libs/manifest-merger.jar" sourcepath="/manifest-merger"/>
-</classpath>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/.project b/eclipse/plugins/com.android.ide.eclipse.tests/.project
deleted file mode 100644
index d37e27b11..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/.project
+++ /dev/null
@@ -1,29 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>plugin-tests</name>
- <comment></comment>
- <projects>
- <project>SdkLib</project>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/.settings/org.eclipse.jdt.core.prefs b/eclipse/plugins/com.android.ide.eclipse.tests/.settings/org.eclipse.jdt.core.prefs
deleted file mode 100644
index ea661960a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/.settings/org.eclipse.jdt.core.prefs
+++ /dev/null
@@ -1,98 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore
-org.eclipse.jdt.core.compiler.annotation.nonnull=com.android.annotations.NonNull
-org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=com.android.annotations.NonNullByDefault
-org.eclipse.jdt.core.compiler.annotation.nonnullisdefault=disabled
-org.eclipse.jdt.core.compiler.annotation.nullable=com.android.annotations.Nullable
-org.eclipse.jdt.core.compiler.annotation.nullanalysis=enabled
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
-org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
-org.eclipse.jdt.core.compiler.compliance=1.6
-org.eclipse.jdt.core.compiler.debug.lineNumber=generate
-org.eclipse.jdt.core.compiler.debug.localVariable=generate
-org.eclipse.jdt.core.compiler.debug.sourceFile=generate
-org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
-org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
-org.eclipse.jdt.core.compiler.problem.deadCode=warning
-org.eclipse.jdt.core.compiler.problem.deprecation=warning
-org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
-org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
-org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
-org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore
-org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning
-org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled
-org.eclipse.jdt.core.compiler.problem.fieldHiding=warning
-org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
-org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
-org.eclipse.jdt.core.compiler.problem.forbiddenReference=error
-org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
-org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=enabled
-org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
-org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning
-org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
-org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning
-org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
-org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore
-org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled
-org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=warning
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=error
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
-org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
-org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
-org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
-org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
-org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
-org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=warning
-org.eclipse.jdt.core.compiler.problem.nullReference=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecInsufficientInfo=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecViolation=warning
-org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=ignore
-org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
-org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
-org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullSpecViolation=error
-org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=warning
-org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=warning
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
-org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
-org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
-org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=enabled
-org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
-org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
-org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning
-org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=disabled
-org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
-org.eclipse.jdt.core.compiler.problem.unclosedCloseable=error
-org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
-org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
-org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning
-org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
-org.eclipse.jdt.core.compiler.problem.unusedImport=warning
-org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
-org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
-org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=warning
-org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
-org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
-org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
-org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
-org.eclipse.jdt.core.compiler.source=1.6
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/META-INF/MANIFEST.MF b/eclipse/plugins/com.android.ide.eclipse.tests/META-INF/MANIFEST.MF
deleted file mode 100644
index 8289d64ed..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,16 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: Android Plugin Tests
-Bundle-SymbolicName: com.android.ide.eclipse.tests
-Bundle-Version: 24.3.3.qualifier
-Bundle-Vendor: The Android Open Source Project
-Fragment-Host: com.android.ide.eclipse.adt;bundle-version="21.0.0"
-Require-Bundle: org.junit
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
-Bundle-ClassPath: .,
- libs/kxml2-2.3.0.jar,
- libs/testutils.jar,
- libs/lint-api.jar,
- libs/lint-checks.jar,
- libs/easymock.jar
-Import-Package: com.android.tools.lint.detector.api
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/MODULE_LICENSE_EPL b/eclipse/plugins/com.android.ide.eclipse.tests/MODULE_LICENSE_EPL
deleted file mode 100644
index e69de29bb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/MODULE_LICENSE_EPL
+++ /dev/null
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/NOTICE b/eclipse/plugins/com.android.ide.eclipse.tests/NOTICE
deleted file mode 100644
index 49c101df7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/NOTICE
+++ /dev/null
@@ -1,224 +0,0 @@
-*Eclipse Public License - v 1.0*
-
-THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE
-PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF
-THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
-
-*1. DEFINITIONS*
-
-"Contribution" means:
-
-a) in the case of the initial Contributor, the initial code and
-documentation distributed under this Agreement, and
-b) in the case of each subsequent Contributor:
-
-i) changes to the Program, and
-
-ii) additions to the Program;
-
-where such changes and/or additions to the Program originate from and
-are distributed by that particular Contributor. A Contribution
-'originates' from a Contributor if it was added to the Program by such
-Contributor itself or anyone acting on such Contributor's behalf.
-Contributions do not include additions to the Program which: (i) are
-separate modules of software distributed in conjunction with the Program
-under their own license agreement, and (ii) are not derivative works of
-the Program.
-
-"Contributor" means any person or entity that distributes the Program.
-
-"Licensed Patents " mean patent claims licensable by a Contributor which
-are necessarily infringed by the use or sale of its Contribution alone
-or when combined with the Program.
-
-"Program" means the Contributions distributed in accordance with this
-Agreement.
-
-"Recipient" means anyone who receives the Program under this Agreement,
-including all Contributors.
-
-*2. GRANT OF RIGHTS*
-
-a) Subject to the terms of this Agreement, each Contributor hereby
-grants Recipient a non-exclusive, worldwide, royalty-free copyright
-license to reproduce, prepare derivative works of, publicly display,
-publicly perform, distribute and sublicense the Contribution of such
-Contributor, if any, and such derivative works, in source code and
-object code form.
-
-b) Subject to the terms of this Agreement, each Contributor hereby
-grants Recipient a non-exclusive, worldwide, royalty-free patent license
-under Licensed Patents to make, use, sell, offer to sell, import and
-otherwise transfer the Contribution of such Contributor, if any, in
-source code and object code form. This patent license shall apply to the
-combination of the Contribution and the Program if, at the time the
-Contribution is added by the Contributor, such addition of the
-Contribution causes such combination to be covered by the Licensed
-Patents. The patent license shall not apply to any other combinations
-which include the Contribution. No hardware per se is licensed hereunder.
-
-c) Recipient understands that although each Contributor grants the
-licenses to its Contributions set forth herein, no assurances are
-provided by any Contributor that the Program does not infringe the
-patent or other intellectual property rights of any other entity. Each
-Contributor disclaims any liability to Recipient for claims brought by
-any other entity based on infringement of intellectual property rights
-or otherwise. As a condition to exercising the rights and licenses
-granted hereunder, each Recipient hereby assumes sole responsibility to
-secure any other intellectual property rights needed, if any. For
-example, if a third party patent license is required to allow Recipient
-to distribute the Program, it is Recipient's responsibility to acquire
-that license before distributing the Program.
-
-d) Each Contributor represents that to its knowledge it has sufficient
-copyright rights in its Contribution, if any, to grant the copyright
-license set forth in this Agreement.
-
-*3. REQUIREMENTS*
-
-A Contributor may choose to distribute the Program in object code form
-under its own license agreement, provided that:
-
-a) it complies with the terms and conditions of this Agreement; and
-
-b) its license agreement:
-
-i) effectively disclaims on behalf of all Contributors all warranties
-and conditions, express and implied, including warranties or conditions
-of title and non-infringement, and implied warranties or conditions of
-merchantability and fitness for a particular purpose;
-
-ii) effectively excludes on behalf of all Contributors all liability for
-damages, including direct, indirect, special, incidental and
-consequential damages, such as lost profits;
-
-iii) states that any provisions which differ from this Agreement are
-offered by that Contributor alone and not by any other party; and
-
-iv) states that source code for the Program is available from such
-Contributor, and informs licensees how to obtain it in a reasonable
-manner on or through a medium customarily used for software exchange.
-
-When the Program is made available in source code form:
-
-a) it must be made available under this Agreement; and
-
-b) a copy of this Agreement must be included with each copy of the Program.
-
-Contributors may not remove or alter any copyright notices contained
-within the Program.
-
-Each Contributor must identify itself as the originator of its
-Contribution, if any, in a manner that reasonably allows subsequent
-Recipients to identify the originator of the Contribution.
-
-*4. COMMERCIAL DISTRIBUTION*
-
-Commercial distributors of software may accept certain responsibilities
-with respect to end users, business partners and the like. While this
-license is intended to facilitate the commercial use of the Program, the
-Contributor who includes the Program in a commercial product offering
-should do so in a manner which does not create potential liability for
-other Contributors. Therefore, if a Contributor includes the Program in
-a commercial product offering, such Contributor ("Commercial
-Contributor") hereby agrees to defend and indemnify every other
-Contributor ("Indemnified Contributor") against any losses, damages and
-costs (collectively "Losses") arising from claims, lawsuits and other
-legal actions brought by a third party against the Indemnified
-Contributor to the extent caused by the acts or omissions of such
-Commercial Contributor in connection with its distribution of the
-Program in a commercial product offering. The obligations in this
-section do not apply to any claims or Losses relating to any actual or
-alleged intellectual property infringement. In order to qualify, an
-Indemnified Contributor must: a) promptly notify the Commercial
-Contributor in writing of such claim, and b) allow the Commercial
-Contributor to control, and cooperate with the Commercial Contributor
-in, the defense and any related settlement negotiations. The Indemnified
-Contributor may participate in any such claim at its own expense.
-
-For example, a Contributor might include the Program in a commercial
-product offering, Product X. That Contributor is then a Commercial
-Contributor. If that Commercial Contributor then makes performance
-claims, or offers warranties related to Product X, those performance
-claims and warranties are such Commercial Contributor's responsibility
-alone. Under this section, the Commercial Contributor would have to
-defend claims against the other Contributors related to those
-performance claims and warranties, and if a court requires any other
-Contributor to pay any damages as a result, the Commercial Contributor
-must pay those damages.
-
-*5. NO WARRANTY*
-
-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED
-ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
-EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES
-OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR
-A PARTICULAR PURPOSE. Each Recipient is solely responsible for
-determining the appropriateness of using and distributing the Program
-and assumes all risks associated with its exercise of rights under this
-Agreement , including but not limited to the risks and costs of program
-errors, compliance with applicable laws, damage to or loss of data,
-programs or equipment, and unavailability or interruption of operations.
-
-*6. DISCLAIMER OF LIABILITY*
-
-EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR
-ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT,
-INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING
-WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF
-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR
-DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
-HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-
-*7. GENERAL*
-
-If any provision of this Agreement is invalid or unenforceable under
-applicable law, it shall not affect the validity or enforceability of
-the remainder of the terms of this Agreement, and without further action
-by the parties hereto, such provision shall be reformed to the minimum
-extent necessary to make such provision valid and enforceable.
-
-If Recipient institutes patent litigation against any entity (including
-a cross-claim or counterclaim in a lawsuit) alleging that the Program
-itself (excluding combinations of the Program with other software or
-hardware) infringes such Recipient's patent(s), then such Recipient's
-rights granted under Section 2(b) shall terminate as of the date such
-litigation is filed.
-
-All Recipient's rights under this Agreement shall terminate if it fails
-to comply with any of the material terms or conditions of this Agreement
-and does not cure such failure in a reasonable period of time after
-becoming aware of such noncompliance. If all Recipient's rights under
-this Agreement terminate, Recipient agrees to cease use and distribution
-of the Program as soon as reasonably practicable. However, Recipient's
-obligations under this Agreement and any licenses granted by Recipient
-relating to the Program shall continue and survive.
-
-Everyone is permitted to copy and distribute copies of this Agreement,
-but in order to avoid inconsistency the Agreement is copyrighted and may
-only be modified in the following manner. The Agreement Steward reserves
-the right to publish new versions (including revisions) of this
-Agreement from time to time. No one other than the Agreement Steward has
-the right to modify this Agreement. The Eclipse Foundation is the
-initial Agreement Steward. The Eclipse Foundation may assign the
-responsibility to serve as the Agreement Steward to a suitable separate
-entity. Each new version of the Agreement will be given a distinguishing
-version number. The Program (including Contributions) may always be
-distributed subject to the version of the Agreement under which it was
-received. In addition, after a new version of the Agreement is
-published, Contributor may elect to distribute the Program (including
-its Contributions) under the new version. Except as expressly stated in
-Sections 2(a) and 2(b) above, Recipient receives no rights or licenses
-to the intellectual property of any Contributor under this Agreement,
-whether expressly, by implication, estoppel or otherwise. All rights in
-the Program not expressly granted under this Agreement are reserved.
-
-This Agreement is governed by the laws of the State of New York and the
-intellectual property laws of the United States of America. No party to
-this Agreement will bring a legal action under this Agreement more than
-one year after the cause of action arose. Each party waives its rights
-to a jury trial in any resulting litigation.
-
-
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/README.txt b/eclipse/plugins/com.android.ide.eclipse.tests/README.txt
deleted file mode 100644
index fe69958d3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/README.txt
+++ /dev/null
@@ -1,101 +0,0 @@
-This project contains the tests for the Android Eclipse Plugins.
-
-You can do three things:
-1- Run the unit tests as a full "eclipse plugin" suite
-2- Run the unit tests as independent JUnit tests (not as plugin)
-3. Run the functional tests as a full "eclipse plugin" suite (require a real SDK)
-
-The unit tests are isolated tests that do not require external dependencies such as an SDK.
-The functional tests are higher level tests that may require a real SDK.
-
-------------------------------------------
-1- Running the unit tests as a full "eclipse plugin" suite
-------------------------------------------
-
-Steps to run the test suite:
-
-A- In Eclipse, import following projects from development/tools/eclipse/plugins:
- - adt-tests
- - adt
- - ddms
-
-B- Create a new "JUnit Plug-in Test" run configuration via the "Run > Open Run Dialog..." menu
-Set the launch configuration's data as follows:
-i. "Test" tab:
- Select "Run a single test"
- Project: adt-tests
- Test class: com.android.ide.eclipse.tests.UnitTests
- Test runner: JUnit 3
-ii. "Arguments" tab:
- Set "VM Arguments" to
-"-Dtest_data=<adt>/plugins/com.android.ide.eclipse.tests/unittests/data/"
-replacing "<adt>" with absolute filesystem path to the android plugin source location
-
-All other fields can be left with their default values
-
-C. Run the newly created launch configuration
-
-Running the tests will run a secondary instance of Eclipse.
-
-Please note the following constraints to be aware of when writing tests to run within a plugin environment:
-
-a. Access restrictions: cannot access package or protected members in a different
-plugin, even if they are in the same declared package
-b. Using classloader.getResource or getResourceAsStream to access test data will
-likely fail in the plugin environment. Instead, use AdtTestData to access test files
-in conjunction with the "test_data" environment variable mentioned above
-
-
--------------------------------------------
-2- Run the unit tests as independent JUnit tests (not plugin)
--------------------------------------------
-
-A- In Eclipse, import following projects from development/tools/eclipse/plugins:
- - adt-tests
- - adt
- - ddms
-
-B- Select the "unittests" source folder, right-click and select
- "Run As > JUnit Test" (i.e. not the plugin tests)
-
-This creates a debug configuration of type "JUnit Test" running all tests
-in the source folder "unittests". The runtime must be JUnit 3.
-
-Note: this method runs the tests within a regular JVM environment (ie not within
-an Eclipse instance). This method has the advantage of being quicker than running
-as a JUnit plugin test, and requires less potential set-up, but has the
-disadvantage of not properly replicating how the tests will be run in the
-continuous test environment. Tests that pass when run as "JUnit Tests" can
-fail when run as "JUnit Plugin Tests", due to the extra constraints imposed by
-running within an Eclipse plug-in noted in section 1.
-
-------------------------------------------
-3- Running the functional tests as a full "eclipse plugin" suite
-------------------------------------------
-
-Steps to run the test suite:
-
-A- In Eclipse, import following projects from development/tools/eclipse/plugins:
- - adt-tests
- - adt
- - ddms
-
-B - Setup an SDK on host machine, that is compatible with the Eclipse ADT plugins under test
-
-C- Create a new "JUnit Plug-in Test" run configuration via the "Run > Open Run Dialog..." menu
-Set the launch configuration's data as follows:
-i. "Test" tab:
- Select "Run a single test"
- Project: adt-tests
- Test class: com.android.ide.eclipse.tests.FuncTests
- Test runner: JUnit 3
-ii. "Environment" tab:
- Add a "sdk_home" environment variable, setting its path to the SDK from step B
-
-All other fields can be left with their default values
-
-D. Run the newly created launch configuration
-
-Running the tests will run a secondary instance of Eclipse.
-
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/build.properties b/eclipse/plugins/com.android.ide.eclipse.tests/build.properties
deleted file mode 100644
index 2a82227c5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/build.properties
+++ /dev/null
@@ -1,17 +0,0 @@
-source.. = src/,\
- unittests/
-output.. = bin/
-bin.includes = META-INF/,\
- .,\
- test.xml,\
- prefs.template,\
- unittest.xml,\
- kxml2-2.3.0.jar,\
- testutils.jar,\
- layoutlib.jar,\
- lint-api.jar,\
- lint-checks.jar,\
- unittests/com/android/sdklib/testdata/,\
- unittests/com/android/layoutlib/testdata/,\
- unittests/com/android/ide/eclipse/testdata/,\
- easymock.jar
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/not_source_folder/jar/example/Class1.java b/eclipse/plugins/com.android.ide.eclipse.tests/not_source_folder/jar/example/Class1.java
deleted file mode 100644
index 3cf102733..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/not_source_folder/jar/example/Class1.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package jar.example;
-
-public class Class1 {
-
- public static final int sStaticField = 1;
-
- /** constructor */
- public Class1() {
- int a = 1;
- }
-
- public static class InnerStaticClass1 {
-
- }
-
- public class InnerClass2 {
-
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/not_source_folder/jar/example/Class2.java b/eclipse/plugins/com.android.ide.eclipse.tests/not_source_folder/jar/example/Class2.java
deleted file mode 100644
index 4d15c4772..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/not_source_folder/jar/example/Class2.java
+++ /dev/null
@@ -1,21 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package jar.example;
-
-public class Class2 extends Class1 {
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/pom.xml b/eclipse/plugins/com.android.ide.eclipse.tests/pom.xml
deleted file mode 100644
index 71bbad8f4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/pom.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <version>24.3.3-SNAPSHOT</version>
- <artifactId>com.android.ide.eclipse.tests</artifactId>
- <packaging>eclipse-test-plugin</packaging>
- <name>tests</name>
-
- <parent>
- <relativePath>../../pom.xml</relativePath>
- <groupId>adt.group</groupId>
- <artifactId>parent</artifactId>
- <version>1.0.0-SNAPSHOT</version>
- </parent>
-</project>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/prefs.template b/eclipse/plugins/com.android.ide.eclipse.tests/prefs.template
deleted file mode 100644
index e0037decc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/prefs.template
+++ /dev/null
@@ -1,3 +0,0 @@
-#Wed Feb 20 16:56:40 PST 2008
-com.android.ide.eclipse.adt.sdk=sdk_home
-eclipse.preferences.version=1
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/build/AaptParserTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/build/AaptParserTest.java
deleted file mode 100644
index af4e2b7c5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/build/AaptParserTest.java
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build;
-
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.layout.refactoring.AdtProjectTest;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-
-import java.io.File;
-import java.util.Collections;
-import java.util.List;
-
-public class AaptParserTest extends AdtProjectTest {
-
- public void testBasic() throws Exception {
- // Test the "at 'property' with value 'value' range matching included with most aapt errors
- checkRanges("quickfix1.xml", "res/layout/quickfix1.xml",
- "quickfix1.xml:7: error: Error: No resource found that matches the given name (at"
- + " 'text' with value '@string/firststring').",
- "android:text=\"^@string/firststring\"",
- "android:text=\"@string/firststring^\"");
- }
-
- public void testRange1() throws Exception {
- // Check that when the actual aapt error occurs on a line later than the original error
- // line, the forward search which looks for a value match does not stop on an
- // earlier line that happens to have the same value prefix
- checkRanges("aapterror1.xml", "res/layout/aapterror1.xml",
- "aapterror1.xml:5: error: Error: Integer types not allowed (at "
- + "'layout_marginBottom' with value '50').",
- "marginBottom=\"^50\"", "marginBottom=\"50^\"");
- }
-
- public void testRange2() throws Exception {
- // Check that when we have a duplicate resource error, we highlight both the original
- // property and the original definition.
- // This tests the second, duplicate declaration ration.
- checkRanges("aapterror2.xml", "res/values/aapterror2.xml",
- "aapterror2.xml:7: error: Resource entry repeatedStyle1 already has bag item "
- + "android:gravity.",
- "<item name=\"^android:gravity\">bottom</item>",
- "<item name=\"android:gravity^\">bottom</item>");
- }
-
- public void testRange3() throws Exception {
- // Check that when we have a duplicate resource error, we highlight both the original
- // property and the original definition.
- // This tests the original definition. Note that we don't have enough position info
- // so we simply highlight the whitespace portion of the line.
- checkRanges("aapterror2.xml", "res/values/aapterror2.xml",
- "aapterror2.xml:4: Originally defined here.",
- "^<item name=\"android:gravity\">left</item>",
- "<item name=\"android:gravity\">left</item>^");
- }
-
- public void testRange4() throws Exception {
- // Check for aapt error which occurs when the attribute name in an item style declaration
- // is nonexistent
- checkRanges("aapterror3.xml", "res/values/aapterror3.xml",
- "aapterror3.xml:4: error: Error: No resource found that matches the given name: "
- + "attr 'nonexistent'.",
- "<item name=\"^nonexistent\">5</item>",
- "<item name=\"nonexistent^\">5</item>");
- }
-
- public void testRange5() throws Exception {
- // Test missing resource name
- checkRanges("aapterror4.xml", "res/values/aapterror4.xml",
- "aapterror4.xml:3: error: A 'name' attribute is required for <style>",
- "<^style>",
- "<style^>");
- }
-
- public void testRange6() throws Exception {
- checkRanges("aapterror4.xml", "res/values/aapterror4.xml",
- "aapterror4.xml:6: error: A 'type' attribute is required for <item>",
- "<^item></item>",
- "<item^></item>");
- }
-
- public void testRange7() throws Exception {
- // Test missing resource name
- checkRanges("aapterror4.xml", "res/values/aapterror4.xml",
- "aapterror4.xml:6: error: A 'name' attribute is required for <item>",
- "<^item></item>",
- "<item^></item>");
- }
-
- // This test is disabled because I can't find a useful scenario for handling this error
- // message. When this error occurs, we will also get a warning on a missing attribute, and
- // that warning already underlines the element name.
- //public void testRange8() throws Exception {
- // // Test missing resource name
- // checkRanges("aapterror4.xml", "res/values/aapterror4.xml",
- // "aapterror4.xml:4: error: Error: Resource id cannot be an empty string: attr ''.",
- // " ^<item />",
- // " <item />^");
- //}
-
- public void testRange9() throws Exception {
- // Test missing resource name
- checkRanges("aapterror5.xml", "res/values/aapterror5.xml",
- "aapterror5.xml:4: error: Error: String types not allowed (at "
- + "'android:layout_width' with value '').",
- " <item name=\"^android:layout_width\"></item>",
- " <item name=\"android:layout_width^\"></item>");
- }
-
- public void testRange10() throws Exception {
- // Test missing resource name
- checkRanges("aapterror6.xml", "res/layout/aapterror6.xml",
- "aapterror6.xml:5: error: Error: String types not allowed (at 'layout_marginTop'"
- + " with value '').",
- "android:layout_marginTop=^\"\"",
- "android:layout_marginTop=\"\"^");
- }
-
- public void testRange11() throws Exception {
- // Test missing resource name
- checkRanges("aapterror6.xml", "res/layout/aapterror6.xml",
- "aapterror1.xml:5: error: Error: String types not allowed (at 'layout_marginLeft'"
- + " with value '').",
- "android:layout_marginLeft=^''",
- "android:layout_marginLeft=''^");
- }
-
- public void testRange12() throws Exception {
- // Test missing resource name
- checkRanges("aapterror7.xml", "res/layout/aapterror7.xml",
- "aapterror7.xml:5: error: Error: String types not allowed (at 'id'"
- + " with value '').",
- "android:id=^\"\"",
- "android:id=\"\"^");
- }
-
- private void checkRanges(String name, String destPath, String aaptError,
- String expectCaretBegin, String expectCaretEnd)
- throws Exception {
- IProject project = getProject();
- IFile file = getTestDataFile(project, name, destPath);
-
- // Make file paths absolute
- String osRoot = project.getLocation().toOSString();
- String fileRelativePath = file.getProjectRelativePath().toPortableString();
- String filePath = osRoot + File.separator + fileRelativePath;
- String originalError = filePath + aaptError.substring(aaptError.indexOf(':'));
- List<String> errors = Collections.singletonList(originalError);
-
- // Remove anything already placed there by the project create/build automatic
- // (this usually only happens while debugging so the background thread has a chance
- // to get things going)
- IMarker[] markers = file.findMarkers(AdtConstants.MARKER_AAPT_COMPILE, true,
- IResource.DEPTH_ZERO);
- for (IMarker marker : markers) {
- marker.delete();
- }
-
- AaptParser.parseOutput(errors, project);
- markers = file.findMarkers(AdtConstants.MARKER_AAPT_COMPILE, true,
- IResource.DEPTH_ZERO);
- assertNotNull(markers);
- assertEquals(1, markers.length);
-
- String fileContents = AdtPlugin.readFile(file);
- int rangeBegin = getCaretOffset(file, expectCaretBegin);
- int rangeEnd = getCaretOffset(file, expectCaretEnd);
-
- // Check text range
- IMarker marker = markers[0];
- String message = marker.getAttribute(IMarker.MESSAGE, ""); //$NON-NLS-1$
- String simplerMessage = aaptError.substring(aaptError.indexOf(' ') + 1);
- assertEquals(simplerMessage, message);
- int start = marker.getAttribute(IMarker.CHAR_START, 0);
- int end = marker.getAttribute(IMarker.CHAR_END, 0);
-
- assertEquals("Wrong start offset, expected " + expectCaretBegin + " but was "
- + getCaretContext(fileContents, start), rangeBegin, start);
- assertEquals("Wrong end offset, expected " + expectCaretEnd + " but was "
- + getCaretContext(fileContents, end), rangeEnd, end);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/build/AaptQuickFixTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/build/AaptQuickFixTest.java
deleted file mode 100644
index cc3504f58..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/build/AaptQuickFixTest.java
+++ /dev/null
@@ -1,289 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build;
-
-import static com.android.SdkConstants.FD_RES;
-import static com.android.SdkConstants.FD_RES_COLOR;
-import static com.android.SdkConstants.FD_RES_LAYOUT;
-
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.layout.refactoring.AdtProjectTest;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IMarkerResolution;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.ui.part.FileEditorInput;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.List;
-
-public class AaptQuickFixTest extends AdtProjectTest {
- @Override
- protected boolean testCaseNeedsUniqueProject() {
- // Make a separate test project for this test such that we don't pollute code assist
- // tests with our new resources
- return true;
- }
-
- public void testQuickFix1() throws Exception {
- // Test adding a value into an existing file (res/values/strings.xml)
- checkResourceFix("quickfix1.xml", "android:text=\"@string/firs^tstring\"",
- "res/values/strings.xml");
- }
-
- public void testQuickFix2() throws Exception {
- // Test adding a value into a new file (res/values/dimens.xml, will be created)
- checkResourceFix("quickfix1.xml", "android:layout_width=\"@dimen/^testdimen\"",
- "res/values/dimens.xml");
- }
-
- public void testQuickFix3() throws Exception {
- // Test adding a file based resource (uses new file wizard machinery)
- checkResourceFix("quickfix1.xml", "layout=\"@layout/^testlayout\"",
- "res/layout/testlayout.xml");
- }
-
- public void testQuickFix4() throws Exception {
- // Test adding a value into a new file (res/values/dimens.xml, will be created)
- checkNamespaceFix("quickfix2.xml", "<c^olor");
- }
-
- private void checkResourceFix(String name, String caretLocation, String expectedNewPath)
- throws Exception {
- IProject project = getProject();
- IFile file = getTestDataFile(project, name, FD_RES + "/" + FD_RES_LAYOUT + "/" + name);
-
- // Determine the offset
- final int offset = getCaretOffset(file, caretLocation);
-
-
- String osRoot = project.getLocation().toOSString();
- List<String> errors = new ArrayList<String>();
- String fileRelativePath = file.getProjectRelativePath().toPortableString();
- String filePath = osRoot + File.separator + fileRelativePath;
- // Run AaptParser such that markers are added...
- // When debugging these tests, the project gets a chance to build itself so
- // the real aapt errors are there. But when the test is run directly, aapt has
- // not yet run. I tried waiting for the build (using the code in SampleProjectTest)
- // but this had various adverse effects (exception popups from the Eclipse debugger
- // etc) so instead this test just hardcodes the aapt errors that should be
- // observed on quickfix1.xml.
- assertEquals("Unit test is hardcoded to errors for quickfix1.xml", "quickfix1.xml", name);
- errors.add(filePath + ":7: error: Error: No resource found that matches the given name"
- + " (at 'text' with value '@string/firststring').");
- errors.add(filePath + ":7: error: Error: No resource found that matches the given name"
- + " (at 'layout_width' with value '@dimen/testdimen').");
- errors.add(filePath + ":13: error: Error: No resource found that matches the given name"
- + " (at 'layout' with value '@layout/testlayout').");
- AaptParser.parseOutput(errors, project);
-
- AaptQuickFix aaptQuickFix = new AaptQuickFix();
-
- // Open file
- IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
- assertNotNull(page);
- IEditorPart editor = IDE.openEditor(page, file);
- assertTrue(editor instanceof AndroidXmlEditor);
- AndroidXmlEditor layoutEditor = (AndroidXmlEditor) editor;
- final ISourceViewer viewer = layoutEditor.getStructuredSourceViewer();
-
- // Test marker resolution.
- IMarker[] markers = file.findMarkers(AdtConstants.MARKER_AAPT_COMPILE, true,
- IResource.DEPTH_ZERO);
- for (IMarker marker : markers) {
- int start = marker.getAttribute(IMarker.CHAR_START, 0);
- int end = marker.getAttribute(IMarker.CHAR_END, 0);
- if (offset >= start && offset <= end) {
- // Found the target marker. Now check the marker resolution of it.
- assertTrue(aaptQuickFix.hasResolutions(marker));
- IMarkerResolution[] resolutions = aaptQuickFix.getResolutions(marker);
- assertNotNull(resolutions);
- assertEquals(1, resolutions.length);
- IMarkerResolution resolution = resolutions[0];
- assertNotNull(resolution);
- assertTrue(resolution.getLabel().contains("Create resource"));
-
- // Not running marker yet -- if we create the files here they already
- // exist when the quick assist code runs. (The quick fix and the quick assist
- // mostly share code for the implementation anyway.)
- //resolution.run(marker);
- break;
- }
- }
-
- // Next test quick assist.
-
- IQuickAssistInvocationContext invocationContext = new IQuickAssistInvocationContext() {
- @Override
- public int getLength() {
- return 0;
- }
-
- @Override
- public int getOffset() {
- return offset;
- }
-
- @Override
- public ISourceViewer getSourceViewer() {
- return viewer;
- }
- };
- ICompletionProposal[] proposals = aaptQuickFix
- .computeQuickAssistProposals(invocationContext);
- assertNotNull(proposals);
- assertTrue(proposals.length == 1);
- ICompletionProposal proposal = proposals[0];
-
- assertNotNull(proposal.getAdditionalProposalInfo());
- assertNotNull(proposal.getImage());
- assertTrue(proposal.getDisplayString().contains("Create resource"));
-
- IDocument document = new Document();
- String fileContent = AdtPlugin.readFile(file);
- document.set(fileContent);
-
- // Apply quick fix
- proposal.apply(document);
-
- IPath path = new Path(expectedNewPath);
- IFile newFile = project.getFile(path);
- assertNotNull(path.toPortableString(), newFile);
-
- // Ensure that the newly created file was opened
- IEditorPart currentFile = AdtUtils.getActiveEditor();
- assertEquals(newFile.getProjectRelativePath(),
- ((FileEditorInput) currentFile.getEditorInput()).getFile().getProjectRelativePath());
-
- // Look up caret offset
- assertTrue(currentFile != null ? currentFile.getClass().getName() : "null",
- currentFile instanceof AndroidXmlEditor);
- AndroidXmlEditor newEditor = (AndroidXmlEditor) currentFile;
- ISourceViewer newViewer = newEditor.getStructuredSourceViewer();
- Point selectedRange = newViewer.getSelectedRange();
-
- String newFileContents = AdtPlugin.readFile(newFile);
-
- // Insert selection markers -- [ ] for the selection range, ^ for the caret
- String newFileWithCaret = addSelection(newFileContents, selectedRange);
- newFileWithCaret = removeSessionData(newFileWithCaret);
-
- assertEqualsGolden(name, newFileWithCaret);
- }
-
- private void checkNamespaceFix(String name, String caretLocation)
- throws Exception {
- IProject project = getProject();
- IFile file = getTestDataFile(project, name, FD_RES + "/" + FD_RES_COLOR + "/" + name);
-
- // Determine the offset
- final int offset = getCaretOffset(file, caretLocation);
-
- String osRoot = project.getLocation().toOSString();
- List<String> errors = new ArrayList<String>();
- String fileRelativePath = file.getProjectRelativePath().toPortableString();
- String filePath = osRoot + File.separator + fileRelativePath;
- assertEquals("Unit test is hardcoded to errors for quickfix2.xml", "quickfix2.xml", name);
- errors.add(filePath + ":5: error: Error parsing XML: unbound prefix");
- AaptParser.parseOutput(errors, project);
-
- AaptQuickFix aaptQuickFix = new AaptQuickFix();
-
- // Open file
- IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
- assertNotNull(page);
- IEditorPart editor = IDE.openEditor(page, file);
- assertTrue(editor instanceof AndroidXmlEditor);
- AndroidXmlEditor layoutEditor = (AndroidXmlEditor) editor;
- final ISourceViewer viewer = layoutEditor.getStructuredSourceViewer();
-
- // Test marker resolution.
- IMarker[] markers = file.findMarkers(AdtConstants.MARKER_AAPT_COMPILE, true,
- IResource.DEPTH_ZERO);
- assertEquals(1, markers.length);
- IMarker marker = markers[0];
- // Found the target marker. Now check the marker resolution of it.
- assertTrue(aaptQuickFix.hasResolutions(marker));
- IMarkerResolution[] resolutions = aaptQuickFix.getResolutions(marker);
- assertNotNull(resolutions);
- assertEquals(1, resolutions.length);
- IMarkerResolution resolution = resolutions[0];
- assertNotNull(resolution);
- assertTrue(resolution.getLabel().contains("Insert namespace"));
-
- // Next test quick assist.
-
- IQuickAssistInvocationContext invocationContext = new IQuickAssistInvocationContext() {
- @Override
- public int getLength() {
- return 0;
- }
-
- @Override
- public int getOffset() {
- return offset;
- }
-
- @Override
- public ISourceViewer getSourceViewer() {
- return viewer;
- }
- };
- ICompletionProposal[] proposals = aaptQuickFix
- .computeQuickAssistProposals(invocationContext);
- assertNotNull(proposals);
- assertTrue(proposals.length == 1);
- ICompletionProposal proposal = proposals[0];
-
- assertNotNull(proposal.getAdditionalProposalInfo());
- assertNotNull(proposal.getImage());
- assertTrue(proposal.getDisplayString().contains("Insert namespace"));
-
- // Open the file to ensure we can get an XML model with getExistingModelForEdit:
- AdtPlugin.openFile(file, null);
- IEditorPart newEditor = AdtUtils.getActiveEditor();
- assertTrue(newEditor instanceof AndroidXmlEditor);
-
- AndroidXmlEditor xmlEditor = (AndroidXmlEditor) newEditor;
- IDocument document = xmlEditor.getStructuredSourceViewer().getDocument();
-
- // Apply quick fix
- String before = document.get();
- proposal.apply(document);
- String after = document.get();
- String diff = getDiff(before, after);
- assertEqualsGolden(name, diff);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/AndroidContentAssistTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/AndroidContentAssistTest.java
deleted file mode 100644
index 700e68bad..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/AndroidContentAssistTest.java
+++ /dev/null
@@ -1,990 +0,0 @@
-/*
-
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors;
-
-import static com.android.SdkConstants.FD_RES;
-import static com.android.SdkConstants.FD_RES_ANIM;
-import static com.android.SdkConstants.FD_RES_ANIMATOR;
-import static com.android.SdkConstants.FD_RES_COLOR;
-import static com.android.SdkConstants.FD_RES_DRAWABLE;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.animator.AnimationContentAssist;
-import com.android.ide.eclipse.adt.internal.editors.color.ColorContentAssist;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.drawable.DrawableContentAssist;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutContentAssist;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.refactoring.AdtProjectTest;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestContentAssist;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestEditor;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.editors.values.ValuesContentAssist;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.ide.IDE;
-
-@SuppressWarnings("javadoc")
-public class AndroidContentAssistTest extends AdtProjectTest {
- private static final String CARET = "^"; //$NON-NLS-1$
-
- @Override
- protected boolean testCaseNeedsUniqueProject() {
- return true;
- }
-
- public void testStartsWith() {
- assertTrue(AndroidContentAssist.startsWith("", ""));
- assertTrue(AndroidContentAssist.startsWith("a", ""));
- assertTrue(AndroidContentAssist.startsWith("A", ""));
- assertTrue(AndroidContentAssist.startsWith("A", "a"));
- assertTrue(AndroidContentAssist.startsWith("A", "A"));
- assertTrue(AndroidContentAssist.startsWith("Ab", "a"));
- assertTrue(AndroidContentAssist.startsWith("ab", "A"));
- assertTrue(AndroidContentAssist.startsWith("ab", "AB"));
- assertFalse(AndroidContentAssist.startsWith("ab", "ABc"));
- assertFalse(AndroidContentAssist.startsWith("", "ABc"));
- }
-
- public void testNameStartsWith() {
- String fullWord = "android:marginTop";
- for (int i = 0; i < fullWord.length(); i++) {
- assertTrue(i + ":" + fullWord.substring(0, i),
- AndroidContentAssist.nameStartsWith(
- "android:layout_marginTop", fullWord.substring(0, i), "android:"));
- }
-
- fullWord = "android:layout_marginTop";
- for (int i = 0; i < fullWord.length(); i++) {
- assertTrue(i + ":" + fullWord.substring(0, i),
- AndroidContentAssist.nameStartsWith("android:layout_marginTop", fullWord
- .substring(0, i), "android:"));
- }
-
- fullWord = "layout_marginTop";
- for (int i = 0; i < fullWord.length(); i++) {
- assertTrue(i + ":" + fullWord.substring(0, i),
- AndroidContentAssist.nameStartsWith("android:layout_marginTop", fullWord
- .substring(0, i), "android:"));
- }
-
- fullWord = "marginTop";
- for (int i = 0; i < fullWord.length(); i++) {
- assertTrue(i + ":" + fullWord.substring(0, i),
- AndroidContentAssist.nameStartsWith("android:layout_marginTop", fullWord
- .substring(0, i), "android:"));
- }
-
- assertFalse(AndroidContentAssist.nameStartsWith("ab", "ABc", null));
- assertFalse(AndroidContentAssist.nameStartsWith("", "ABc", null));
- }
-
- public void testCompletion1() throws Exception {
- // Change attribute name completion
- checkLayoutCompletion("completion1.xml", "layout_w^idth=\"fill_parent\"");
- }
-
- public void testCompletion2() throws Exception {
- // Check attribute value completion for enum
- checkLayoutCompletion("completion1.xml", "layout_width=\"^fill_parent\"");
- }
-
- public void testCompletion3() throws Exception {
- // Check attribute value completion for enum with a prefix
- checkLayoutCompletion("completion1.xml", "layout_width=\"fi^ll_parent\"");
- }
-
- public void testCompletion4() throws Exception {
- // Check attribute value completion on units
- checkLayoutCompletion("completion1.xml", "marginBottom=\"50^\"");
- }
-
- public void testCompletion5() throws Exception {
- // Check attribute value completion on units with prefix
- checkLayoutCompletion("completion1.xml", "layout_marginLeft=\"50d^p\"");
- }
-
- public void testCompletion6() throws Exception {
- // Check resource sorting - "style" should bubble to the top for a style attribute
- checkLayoutCompletion("completion1.xml", "style=\"@android:^style/Widget.Button\"");
- }
-
- public void testCompletion7a() throws Exception {
- // Check flags (multiple values inside a single XML value, separated by | - where
- // the prefix is reset as soon as you pass each | )
- checkLayoutCompletion("completion1.xml", "android:gravity=\"l^eft|bottom\"");
- }
-
- public void testCompletion7b() throws Exception {
- checkLayoutCompletion("completion1.xml", "android:gravity=\"left|b^ottom\"");
- }
-
- public void testCompletion8() throws Exception {
- // Test completion right at the "=" sign; this will be taken to be the last
- // character of the attribute name (the caret is between the last char and before
- // the = characters), so it should match a single attribute
- checkLayoutCompletion("completion1.xml", "layout_width^=\"fill_parent\"");
- }
-
- public void testCompletion9() throws Exception {
- // Test completion right after the "=" sign; this will be taken to be the beginning
- // of the attribute value, but all values will also include a leading quote
- checkLayoutCompletion("completion1.xml", "layout_width=^\"fill_parent\"");
- }
-
- public void testCompletion10() throws Exception {
- // Test completion of element names
- checkLayoutCompletion("completion1.xml", "<T^extView");
- }
-
- public void testCompletion11() throws Exception {
- // Test completion of element names at the outside of the <. This should include
- // all the elements too (along with the leading <).
- checkLayoutCompletion("completion1.xml", "^<TextView");
- }
-
- public void testCompletion12() throws Exception {
- // Test completion of element names inside a nested XML; ensure that this will
- // correctly compute element names, not previous attribute
- checkLayoutCompletion("completion1.xml", "btn_default\">^</FrameLayout>");
- }
-
- public void testCompletion13a() throws Exception {
- checkLayoutCompletion("completion2.xml", "gravity=\"left|bottom|^cen");
- }
-
- public void testCompletion13b() throws Exception {
- checkLayoutCompletion("completion2.xml", "gravity=\"left|bottom|cen^");
- }
-
- public void testCompletion13c() throws Exception {
- checkLayoutCompletion("completion2.xml", "gravity=\"left|bottom^|cen");
- }
-
- public void testCompletion14() throws Exception {
- // Test completion of permissions
- checkManifestCompletion("manifest.xml", "android.permission.ACC^ESS_NETWORK_STATE");
- }
-
- public void testCompletion15() throws Exception {
- // Test completion of intents
- checkManifestCompletion("manifest.xml", "android.intent.category.L^AUNCHER");
- }
-
- public void testCompletion16() throws Exception {
- // Test completion of top level elements
- checkManifestCompletion("manifest.xml", "<^application android:i");
- }
-
- public void testCompletion17() throws Exception {
- // Test completion of attributes on the manifest element
- checkManifestCompletion("manifest.xml", "^android:versionCode=\"1\"");
- }
-
- public void testCompletion18() throws Exception {
- // Test completion of attributes on the manifest element
- checkManifestCompletion("manifest.xml",
- "<activity android:^name=\".TestActivity\"");
- }
-
- public void testCompletion19() throws Exception {
- // Test special case where completing on a new element in an otherwise blank line
- // does not add in full completion (with closing tags)
- checkLayoutCompletion("broken3.xml", "<EditT^");
- }
-
- public void testCompletion20() throws Exception {
- checkLayoutCompletion("broken1.xml", "android:textColorHigh^");
- }
-
- public void testCompletion21() throws Exception {
- checkLayoutCompletion("broken2.xml", "style=^");
- }
-
- public void testCompletion22() throws Exception {
- // Test completion where the cursor is inside an element (e.g. the next
- // char is NOT a <) - should not complete with end tags
- checkLayoutCompletion("completion4.xml", "<Button^");
- }
-
- // Test completion in style files
-
- public void testCompletion23() throws Exception {
- checkResourceCompletion("completionvalues1.xml", "android:textS^ize");
- }
-
- public void testCompletion24() throws Exception {
- checkResourceCompletion("completionvalues1.xml", "17^sp");
- }
-
- public void testCompletion25() throws Exception {
- checkResourceCompletion("completionvalues1.xml", "textColor\">^@color/title_color</item>");
- }
-
- public void testCompletion26() throws Exception {
- checkResourceCompletion("completionvalues1.xml",
- "<item name=\"android:shadowColor\">@an^</item>");
- }
-
- public void testCompletion27() throws Exception {
- checkResourceCompletion("completionvalues1.xml",
- "<item name=\"android:gravity\">^ </item>");
- }
-
- public void testCompletion28() throws Exception {
- checkResourceCompletion("completionvalues1.xml",
- "<item name=\"android:gravity\"> ^</item>");
- }
-
- public void testCompletion29() throws Exception {
- checkResourceCompletion("completionvalues1.xml", "<item name=\"gr^\">");
- }
-
- public void testCompletion30() throws Exception {
- checkResourceCompletion("completionvalues1.xml", "<item name=\"an^\">");
- }
-
- public void testCompletion31() throws Exception {
- checkResourceCompletion("completionvalues1.xml", "<item ^></item>");
- }
-
- public void testCompletion32() throws Exception {
- checkResourceCompletion("completionvalues1.xml", "<item name=\"^\"></item>");
- }
-
- public void testCompletion33() throws Exception {
- checkResourceCompletion("completionvalues1.xml",
- "<item name=\"android:allowSingleTap\">^</item>");
- }
-
- public void testCompletion34() throws Exception {
- checkResourceCompletion("completionvalues1.xml",
- "<item name=\"android:alwaysDrawnWithCache\">^ false </item>");
- }
-
- public void testCompletion35() throws Exception {
- checkResourceCompletion("completionvalues1.xml",
- "<item name=\"android:alwaysDrawnWithCache\"> ^false </item>");
- }
-
- public void testCompletion36() throws Exception {
- checkResourceCompletion("completionvalues1.xml",
- "<item name=\"android:alwaysDrawnWithCache\"> f^alse </item>");
- }
-
- public void testCompletion37() throws Exception {
- checkResourceCompletion("completionvalues1.xml",
- "<item name=\"android:orientation\">h^</item>");
- }
-
- public void testCompletion38() throws Exception {
- checkResourceCompletion("completionvalues1.xml",
- " c^");
- }
-
- public void testCompletion39() throws Exception {
- // If you are at the end of a closing quote (but with no space), completion should
- // include a separating space.
- checkLayoutCompletion("completion1.xml", "marginBottom=\"50\"^");
- }
-
- public void testCompletion40() throws Exception {
- // Same as test 39 but with single quote
- checkLayoutCompletion("completion5.xml", "android:id='@+id/button2'^");
- }
-
- public void testCompletion41() throws Exception {
- // Test prefix matching on layout_ with namespace prefix
- checkLayoutCompletion("completion8.xml", "android:mar^=\"50dp\"");
- }
-
- public void testCompletion42() throws Exception {
- // Test prefix matching on layout_ with namespace prefix
- checkLayoutCompletion("completion8.xml", "android:w^i=\"100\"");
- }
-
- public void testCompletion43() throws Exception {
- // Test prefix matching on layout_ without namespace prefix
- checkLayoutCompletion("completion8.xml", "mar^=\"60dp\"");
- }
-
- public void testCompletion44() throws Exception {
- // Test prefix matching on layout_ without namespace prefix
- checkLayoutCompletion("completion8.xml", "android:layo^ut_width=\"fill_parent\"");
- }
-
- public void testCompletion45() throws Exception {
- // Test top level elements in colors
- checkColorCompletion("color1.xml", "^<selector");
- }
-
- public void testCompletion46a() throws Exception {
- // Test children of selector: should offer item
- checkColorCompletion("color1.xml", "^<item android");
- }
-
- public void testCompletion46b() throws Exception {
- // Test attribute matching in color files
- checkColorCompletion("color1.xml", "<item ^android:state_focused=\"true\"/>");
- }
-
- public void testCompletion47() throws Exception {
- // Check root completion in drawables: should list all drawable root elements
- checkDrawableCompletion("drawable1.xml", "^<layer-list");
- }
-
- public void testCompletion48() throws Exception {
- // Check attributes of the layer list
- checkDrawableCompletion("drawable1.xml", "^xmlns:android");
- }
-
- public void testCompletion49() throws Exception {
- // Check attributes of the <item> element inside a <layer-list>
- checkDrawableCompletion("drawable1.xml", "<item ^></item>");
- }
-
- public void testCompletion50() throws Exception {
- // Check elements nested inside the <item> in a layer list: can use any drawable again
- checkDrawableCompletion("drawable1.xml", "<item >^</item>");
- }
-
- public void testCompletion51() throws Exception {
- // Check attributes of <shape> element
- checkDrawableCompletion("drawable2.xml", "^android:innerRadiusRatio=\"2\"");
- }
-
- public void testCompletion52() throws Exception {
- // Check list of available elements inside a shape
- checkDrawableCompletion("drawable2.xml", "^<gradient");
- }
-
- public void testCompletion53() throws Exception {
- // Check list of root anim elements
- checkAnimCompletion("anim1.xml", "^<set xmlns");
- }
-
- public void testCompletion54() throws Exception {
- // Check that we can nest inside <set>'s
- checkAnimCompletion("anim1.xml", "^<translate android:id=");
- }
-
- public void testCompletion55() throws Exception {
- // translate properties
- checkAnimCompletion("anim1.xml", "android:^fromXDelta=");
- }
-
- public void testCompletion56() throws Exception {
- // alpha properties
- checkAnimCompletion("anim1.xml", "android:^fromAlpha=");
- }
-
- public void testCompletion57() throws Exception {
- // Fractional properties
- checkAnimCompletion("anim1.xml", "android:fromXDelta=\"100^%p\"");
- }
-
- public void testCompletion58() throws Exception {
- // Top level animator elements
- checkAnimatorCompletion("animator1.xml", "^<set xmlns");
- }
-
- public void testCompletion59() throws Exception {
- // objectAnimator properties
- checkAnimatorCompletion("animator1.xml", "android:^duration=\"2000\"");
- }
-
- public void testCompletion60() throws Exception {
- // propertyName completion
- checkAnimatorCompletion("animator1.xml", "android:propertyName=\"scal^eX\"/>");
- }
-
- public void testCompletion61() throws Exception {
- // Interpolator completion
- checkAnimatorCompletion("animator1.xml",
- "android:interpolator=\"^@android:anim/bounce_interpolator\"");
- }
-
- public void testCompletion62() throws Exception {
- // Test completing inside an element that contains .'s, such as a custom view tag
- checkLayoutCompletion("completion9.xml", "android:layout_wi^dth=");
- }
-
- public void testCompletion63() throws Exception {
- // Test attribute completion inside a custom view tag
- // TODO: This works in a running IDE but not in a test context; figure out why.
- //checkLayoutCompletion("completion9.xml", "android:drawable^Top");
- }
-
- public void testCompletion64() throws Exception {
- // Test element completion inside a custom view tag
- checkLayoutCompletion("completion9.xml", "^<Button");
- }
-
- public void testCompletion65() throws Exception {
- // Test completion replacement when there is a selection
- // (see issue http://code.google.com/p/android/issues/detail?id=18607 )
- checkLayoutCompletion("completion10.xml", "\"[^wrap_content]\"");
- }
-
- public void testCompletion66() throws Exception {
- checkResourceCompletion("completionvalues1.xml", "17[^sp]");
- }
-
- public void testCompletion67() throws Exception {
- checkResourceCompletion("completionvalues1.xml", "17[^sp]");
- }
-
- public void testCompletion68() throws Exception {
- checkResourceCompletion("completionvalues1.xml", "[^false]");
- }
-
- public void testCompletion69() throws Exception {
- // Test minimum SDK completion
- checkManifestCompletion("manifest.xml", "<uses-sdk android:minSdkVersion=\"^11\" />");
- }
-
- public void testCompletion70() throws Exception {
- checkResourceCompletion("completionvalues2.xml",
- "<item name=\"main_layout4\" type=\"layout\">^</item>");
- }
-
- public void testCompletion71() throws Exception {
- checkResourceCompletion("completionvalues2.xml",
- "<item name=\"main_layout5\" type=\"string\">@string/^app_name</item>");
- }
-
- public void testCompletion72() throws Exception {
- // Test completion of theme attributes
- checkLayoutCompletion("completion11.xml", "?^android:attr/Textapp");
- }
-
- public void testCompletion73() throws Exception {
- checkLayoutCompletion("completion11.xml", "?android:attr/Textapp^");
- }
-
- public void testCompletion74() throws Exception {
- checkLayoutCompletion("completion11.xml", "?and^roid:attr/Textapp");
- }
-
- public void testCompletion75() throws Exception {
- // Test <include> attributes
- checkLayoutCompletion("completion12.xml", "<include ^/>");
- }
-
- public void testComplation76() throws Exception {
- // Test theme completion with implicit attr
- checkLayoutCompletion("navigation1.xml", "?android:a^ttr/alertDialogStyle");
- }
-
- public void testComplation77() throws Exception {
- // Test <fragment class="^" completion
- checkLayoutCompletion("fragmentlayout.xml", "android:name=\"^com");
- }
-
- public void testComplation78() throws Exception {
- // Test <fragment android:name="^" completion
- checkLayoutCompletion("fragmentlayout.xml", "class=\"^com");
- }
-
- public void testComplation79() throws Exception {
- // Test tools context completion
- checkLayoutCompletion("completion11.xml", "tools:context=\"^.MainActivity\"");
- }
-
- public void testComplation80() throws Exception {
- // Test manifest class completion
- checkManifestCompletion("manifest.xml", "<activity android:name=\"^.");
- }
-
- // TODO: Test <view completion!
-
- // ---- Test *applying* code completion ----
-
- // The following tests check -applying- a specific code completion
- // match - this verifies that the document is updated correctly, the
- // caret is moved appropriately, etc.
-
- public void testApplyCompletion1() throws Exception {
- // Change attribute name completion
- checkApplyLayoutCompletion("completion1.xml", "layout_w^idth=\"fill_parent\"",
- "android:layout_weight");
- }
-
- public void testApplyCompletion2() throws Exception {
- // Check attribute value completion for enum
- checkApplyLayoutCompletion("completion1.xml", "layout_width=\"^fill_parent\"",
- "match_parent");
- }
-
- public void testApplyCompletion3() throws Exception {
- // Check attribute value completion for enum with a prefix
- checkApplyLayoutCompletion("completion1.xml", "layout_width=\"fi^ll_parent\"",
- "fill_parent");
- }
-
- public void testApplyCompletion4() throws Exception {
- // Check attribute value completion on units
- checkApplyLayoutCompletion("completion1.xml", "marginBottom=\"50^\"", "50mm");
- }
-
- public void testApplyCompletion5() throws Exception {
- // Check attribute value completion on units with prefix
- checkApplyLayoutCompletion("completion1.xml", "layout_marginLeft=\"50d^p\"", "50dp");
- }
-
- public void testApplyCompletion6() throws Exception {
- // Check resource sorting - "style" should bubble to the top for a style attribute
- checkApplyLayoutCompletion("completion1.xml", "style=\"@android:^style/Widget.Button\"",
- "@android:drawable/");
- }
-
- public void testApplyCompletion7a() throws Exception {
- // Check flags (multiple values inside a single XML value, separated by | - where
- // the prefix is reset as soon as you pass each | )
- checkApplyLayoutCompletion("completion1.xml", "android:gravity=\"l^eft|bottom\"",
- "left");
- // NOTE - this will replace all flag values with the newly selected value.
- // That may not be the best behavior - perhaps we should only replace one portion
- // of the value.
- }
-
- public void testApplyCompletion7b() throws Exception {
- checkApplyLayoutCompletion("completion1.xml", "android:gravity=\"left|b^ottom\"",
- "bottom");
- // NOTE - this will replace all flag values with the newly selected value.
- // That may not be the best behavior - perhaps we should only replace one portion
- // of the value.
- }
-
- public void testApplyCompletion8() throws Exception {
- // Test completion right at the "=" sign; this will be taken to be the last
- // character of the attribute name (the caret is between the last char and before
- // the = characters), so it should match a single attribute
- checkApplyLayoutCompletion("completion1.xml", "layout_width^=\"fill_parent\"",
- "android:layout_width");
- }
-
- public void testApplyCompletion9() throws Exception {
- // Test completion right after the "=" sign; this will be taken to be the beginning
- // of the attribute value, but all values will also include a leading quote
- checkApplyLayoutCompletion("completion1.xml", "layout_width=^\"fill_parent\"",
- "\"wrap_content\"");
- }
-
- public void testApplyCompletion10() throws Exception {
- // Test completion of element names
- checkApplyLayoutCompletion("completion1.xml", "<T^extView", "TableLayout");
- }
-
- public void testApplyCompletion11a() throws Exception {
- // Test completion of element names at the outside of the <. This should include
- // all the elements too (along with the leading <).
- checkApplyLayoutCompletion("completion1.xml", "^<TextView", "<RadioGroup ></RadioGroup>");
- }
-
- public void testApplyCompletion11b() throws Exception {
- // Similar to testApplyCompletion11a, but replacing with an element that does not
- // have children (to test the closing tag insertion code)
- checkApplyLayoutCompletion("completion1.xml", "^<TextView", "<CheckBox />");
- }
-
- public void testApplyCompletion12() throws Exception {
- // Test completion of element names inside a nested XML; ensure that this will
- // correctly compute element names, not previous attribute
- checkApplyLayoutCompletion("completion1.xml", "btn_default\">^</FrameLayout>",
- "<FrameLayout ></FrameLayout>");
- }
-
- public void testApplyCompletion13a() throws Exception {
- checkApplyLayoutCompletion("completion2.xml", "gravity=\"left|bottom|^cen",
- "fill_vertical");
- }
-
- public void testApplyCompletion13b() throws Exception {
- checkApplyLayoutCompletion("completion2.xml", "gravity=\"left|bottom|cen^",
- "center_horizontal");
- }
-
- public void testApplyCompletion13c() throws Exception {
- checkApplyLayoutCompletion("completion2.xml", "gravity=\"left|bottom^|cen",
- "bottom|fill_horizontal");
- }
-
- public void testApplyCompletion14() throws Exception {
- // Test special case where completing on a new element in an otherwise blank line
- // does not add in full completion (with closing tags)
- checkApplyLayoutCompletion("broken3.xml", "<EditT^", "EditText />");
- }
-
- public void testApplyCompletion15() throws Exception {
- checkApplyLayoutCompletion("broken1.xml", "android:textColorHigh^",
- "android:textColorHighlight");
- }
-
- public void testApplyCompletion16() throws Exception {
- checkApplyLayoutCompletion("broken2.xml", "style=^",
- "\"@android:\"");
- }
-
- public void testApplyCompletion17() throws Exception {
- // Make sure that completion right before a / inside an element still
- // inserts the ="" part (e.g. handles it as "insertNew)
- checkApplyLayoutCompletion("completion3.xml", "<EditText ^/>",
- "android:textColorHighlight");
- }
-
- public void testApplyCompletion18() throws Exception {
- // Make sure that completion right before a > inside an element still
- // inserts the ="" part (e.g. handles it as "insertNew)
- checkApplyLayoutCompletion("completion3.xml", "<Button ^></Button>",
- "android:paddingRight");
- }
-
- public void testApplyCompletion19() throws Exception {
- // Test completion with single quotes (apostrophe)
- checkApplyLayoutCompletion("completion5.xml", "android:orientation='^'", "horizontal");
- }
-
- public void testApplyCompletion20() throws Exception {
- // Test completion with single quotes (apostrophe)
- checkApplyLayoutCompletion("completion5.xml", "android:layout_marginTop='50^dp'", "50pt");
- }
-
- public void testApplyCompletion21() throws Exception {
- // Test completion with single quotes (apostrophe)
- checkApplyLayoutCompletion("completion5.xml", "android:layout_width='^wrap_content'",
- "match_parent");
- // Still broken - but not a common case
- //checkApplyLayoutCompletion("completion5.xml", "android:layout_width=^'wrap_content'",
- // "\"match_parent\"");
- }
-
- public void testApplyCompletion22() throws Exception {
- // Test completion in an empty string
- checkApplyLayoutCompletion("completion6.xml", "android:orientation=\"^\"", "horizontal");
- }
-
- public void testApplyCompletion23() throws Exception {
- // Test completion in an empty string
- checkApplyLayoutCompletion("completion7.xml", "android:orientation=\"^", "horizontal");
- }
-
- // Test completion in style files
-
- public void testApplyCompletion24a() throws Exception {
- checkApplyResourceCompletion("completionvalues1.xml", "android:textS^ize",
- "android:textSelectHandleLeft");
- }
-
- public void testApplyCompletion24b() throws Exception {
- checkApplyResourceCompletion("completionvalues1.xml", "17^sp", "17mm");
- }
-
- public void testApplyCompletion25() throws Exception {
- checkApplyResourceCompletion("completionvalues1.xml",
- "textColor\">^@color/title_color</item>", "@android:");
- }
-
- public void testApplyCompletion26() throws Exception {
- checkApplyResourceCompletion("completionvalues1.xml",
- "<item name=\"android:shadowColor\">@an^</item>", "@android:");
- }
-
- public void testApplyCompletion27() throws Exception {
- checkApplyResourceCompletion("completionvalues1.xml",
- "<item name=\"android:gravity\">^ </item>", "center_vertical");
- }
-
- public void testApplyCompletion28() throws Exception {
- checkApplyResourceCompletion("completionvalues1.xml",
- "<item name=\"android:gravity\"> ^</item>", "left");
- }
-
- public void testApplyCompletion29() throws Exception {
- checkApplyResourceCompletion("completionvalues1.xml", "<item name=\"gr^\">",
- "android:gravity");
- }
-
- public void testApplyCompletion30() throws Exception {
- checkApplyResourceCompletion("completionvalues1.xml", "<item name=\"an^\">",
- "android:animateOnClick");
- }
-
- public void testApplyCompletion31() throws Exception {
- checkApplyResourceCompletion("completionvalues1.xml", "<item ^></item>", "name");
- }
-
- public void testApplyCompletion32() throws Exception {
- checkApplyResourceCompletion("completionvalues1.xml", "<item name=\"^\"></item>",
- "android:background");
- }
-
- public void testApplyCompletion33() throws Exception {
- checkApplyResourceCompletion("completionvalues1.xml",
- "<item name=\"android:allowSingleTap\">^</item>", "true");
- }
-
- public void testApplyCompletion34() throws Exception {
- checkApplyResourceCompletion("completionvalues1.xml",
- "<item name=\"android:alwaysDrawnWithCache\">^ false </item>", "true");
- }
-
- public void testApplyCompletion35() throws Exception {
- checkApplyResourceCompletion("completionvalues1.xml",
- "<item name=\"android:alwaysDrawnWithCache\"> ^false </item>", "true");
- }
-
- public void testApplyCompletion36() throws Exception {
- checkApplyResourceCompletion("completionvalues1.xml",
- "<item name=\"android:alwaysDrawnWithCache\"> f^alse </item>", "false");
- }
-
- public void testApplyCompletion37() throws Exception {
- checkApplyResourceCompletion("completionvalues1.xml",
- "<item name=\"android:orientation\">h^</item>", "horizontal");
- }
-
- public void testApplyCompletion38() throws Exception {
- checkApplyResourceCompletion("completionvalues1.xml",
- " c^", "center");
- }
-
- public void testApplyCompletion39() throws Exception {
- // If you are at the end of a closing quote (but with no space), completion should
- // include a separating space.
- checkApplyLayoutCompletion("completion1.xml", "marginBottom=\"50\"^", " android:maxEms");
- }
-
- public void testApplyCompletion40() throws Exception {
- // If you are at the end of a closing quote (but with no space), completion should
- // include a separating space.
- checkApplyLayoutCompletion("completion5.xml", "android:id='@+id/button2'^",
- " android:maxWidth");
- }
-
- public void testApplyCompletion41() throws Exception {
- // Test prefix matching on layout_ with namespace prefix
- checkApplyLayoutCompletion("completion8.xml", "android:mar^=\"50dp\"",
- "android:layout_marginRight");
- }
-
- public void testApplyCompletion42() throws Exception {
- // Test completion replacement when there is a selection
- // (see issue http://code.google.com/p/android/issues/detail?id=18607 )
- checkApplyLayoutCompletion("completion10.xml", "\"[^wrap_content]\"", "fill_parent");
- }
-
- public void testApplyCompletion43() throws Exception {
- // Same as testApplyCompletion42 but with a smaller selection range
- checkApplyLayoutCompletion("completion10.xml", "\"[^wrap_c]ontent\"", "fill_parent");
- }
-
- public void testApplyCompletion44() throws Exception {
- checkApplyResourceCompletion("completionvalues1.xml", "[^false]", "true");
- }
-
- public void testApplyCompletion45() throws Exception {
- checkApplyResourceCompletion("completionvalues2.xml",
- "@string/^app_name", "@string/hello");
- }
-
- public void testApplyCompletion46() throws Exception {
- checkApplyLayoutCompletion("completion11.xml",
- "?android:attr/Textapp^", "?android:attr/textAppearanceLargeInverse");
- }
-
- public void testApplyCompletion47() throws Exception {
- // Test applying <fragment android:name="^" completion
- checkApplyLayoutCompletion("fragmentlayout.xml", "class=\"^com",
- "android.app.ListFragment");
- }
-
- // --- Code Completion test infrastructure ----
-
- private void checkLayoutCompletion(String name, String caretLocation) throws Exception {
- IFile file = getLayoutFile(getProject(), name);
- IDE.setDefaultEditor(file, CommonXmlEditor.ID);
- checkCompletion(name, file, caretLocation,
- new LayoutContentAssist());
- }
-
- private void checkColorCompletion(String name, String caretLocation) throws Exception {
- IFile file = getTestDataFile(getProject(), name, FD_RES + "/" + FD_RES_COLOR + "/" + name);
- IDE.setDefaultEditor(file, CommonXmlEditor.ID);
- checkCompletion(name, file, caretLocation, new ColorContentAssist());
- }
-
- private void checkAnimCompletion(String name, String caretLocation) throws Exception {
- IFile file = getTestDataFile(getProject(), name, FD_RES + "/" + FD_RES_ANIM + "/" + name);
- IDE.setDefaultEditor(file, CommonXmlEditor.ID);
- checkCompletion(name, file, caretLocation, new AnimationContentAssist());
- }
-
- private void checkAnimatorCompletion(String name, String caretLocation) throws Exception {
- IFile file = getTestDataFile(getProject(), name, FD_RES + "/" + FD_RES_ANIMATOR + "/"
- + name);
- IDE.setDefaultEditor(file, CommonXmlEditor.ID);
- checkCompletion(name, file, caretLocation, new AnimationContentAssist());
- }
-
- private void checkDrawableCompletion(String name, String caretLocation) throws Exception {
- IFile file = getTestDataFile(getProject(), name, FD_RES + "/" + FD_RES_DRAWABLE + "/"
- + name);
- IDE.setDefaultEditor(file, CommonXmlEditor.ID);
- checkCompletion(name, file, caretLocation, new DrawableContentAssist());
- }
-
- private void checkManifestCompletion(String name, String caretLocation) throws Exception {
- // Manifest files must be named AndroidManifest.xml. Must overwrite to replace
- // the default manifest created in the test project.
- IFile file = getTestDataFile(getProject(), name, "AndroidManifest.xml", true);
- IDE.setDefaultEditor(file, ManifestEditor.ID);
-
- checkCompletion(name, file, caretLocation,
- new ManifestContentAssist());
- }
-
- private void checkApplyLayoutCompletion(String name, String caretLocation,
- String match) throws Exception {
- checkApplyCompletion(name, getLayoutFile(getProject(), name), caretLocation,
- new LayoutContentAssist(), match);
- }
-
- private void checkResourceCompletion(String name, String caretLocation) throws Exception {
- checkCompletion(name, getValueFile(getProject(), name), caretLocation,
- new ValuesContentAssist());
- }
-
- private void checkApplyResourceCompletion(String name, String caretLocation,
- String match) throws Exception {
- checkApplyCompletion(name, getValueFile(getProject(), name), caretLocation,
- new ValuesContentAssist(), match);
- }
-
- private ICompletionProposal[] complete(IFile file, String caretLocation,
- AndroidContentAssist assist) throws Exception {
-
- // Open file
- IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
- assertNotNull(page);
- IEditorPart editor = IDE.openEditor(page, file);
- assertTrue(editor instanceof AndroidXmlEditor);
- AndroidXmlEditor xmlEditor = (AndroidXmlEditor) editor;
-
- UiElementNode root = xmlEditor.getUiRootNode();
- ElementDescriptor descriptor = root.getDescriptor();
- if (descriptor instanceof ViewElementDescriptor) {
- ViewElementDescriptor vd = (ViewElementDescriptor) descriptor;
- AttributeDescriptor[] attributes = vd.getAttributes();
- assertTrue(Integer.toString(attributes.length), attributes.length > 0);
- }
-
- ISourceViewer viewer = xmlEditor.getStructuredSourceViewer();
-
- // Determine the offset, and possibly make text range selections as well
- int offset = updateCaret(viewer, caretLocation);
-
- // Run code completion
- ICompletionProposal[] proposals = assist.computeCompletionProposals(viewer, offset);
- if (proposals == null) {
- proposals = new ICompletionProposal[0];
- }
-
- editor.getEditorSite().getPage().closeAllEditors(false);
-
- return proposals;
- }
-
- private void checkApplyCompletion(String basename, IFile file, String caretLocation,
- AndroidContentAssist assist, String match) throws Exception {
- ICompletionProposal[] proposals = complete(file, caretLocation, assist);
- ICompletionProposal chosen = null;
- for (ICompletionProposal proposal : proposals) {
- if (proposal.getDisplayString().equals(match)) {
- chosen = proposal;
- break;
- }
- }
- assertNotNull(chosen);
- assert chosen != null; // Eclipse null pointer analysis doesn't believe the JUnit assertion
-
- String fileContent = AdtPlugin.readFile(file);
- IDocument document = new Document();
- document.set(fileContent);
-
- // Apply code completion
- chosen.apply(document);
-
- // Insert caret location as well
- Point location = chosen.getSelection(document);
- document.replace(location.x, 0, CARET);
-
- String actual = document.get();
-
- int offset = getCaretOffset(fileContent, caretLocation);
- String beforeWithCaret = fileContent.substring(0, offset) + CARET
- + fileContent.substring(offset);
-
- String diff = getDiff(beforeWithCaret, actual);
- assertTrue(diff + " versus " + actual, diff.length() > 0 || beforeWithCaret.equals(actual));
-
- StringBuilder summary = new StringBuilder();
- summary.append("Code completion in " + basename + " for " + caretLocation + " selecting "
- + match + ":\n");
- if (diff.length() == 0) {
- diff = "No changes";
- }
- summary.append(diff);
-
- // assertEqualsGolden(basename, actual);
- assertEqualsGolden(basename, summary.toString(), "diff");
- }
-
- private void checkCompletion(String basename, IFile file, String caretLocation,
- AndroidContentAssist assist) throws Exception {
- ICompletionProposal[] proposals = complete(file, caretLocation, assist);
- StringBuilder sb = new StringBuilder(1000);
- sb.append("Code completion in " + basename + " for " + caretLocation + ":\n");
- for (ICompletionProposal proposal : proposals) {
- // TODO: assertNotNull(proposal.getImage());
- int length = sb.length();
- sb.append(proposal.getDisplayString().trim());
- String help = proposal.getAdditionalProposalInfo();
- if (help != null && help.trim().length() > 0) {
- sb.append(" : ");
- sb.append(help.replace('\n', ' ').trim());
- if (sb.length() > length + 300) {
- sb.setLength(length + 300 - "...".length());
- sb.append("...");
- }
- }
- sb.append('\n');
- }
- assertEqualsGolden(basename, sb.toString(), "txt");
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/AndroidXmlAutoEditStrategyTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/AndroidXmlAutoEditStrategyTest.java
deleted file mode 100644
index 27661b3f2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/AndroidXmlAutoEditStrategyTest.java
+++ /dev/null
@@ -1,473 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors;
-
-import com.android.ide.eclipse.adt.internal.editors.layout.refactoring.AdtProjectTest;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.jface.text.DocumentCommand;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.ide.IDE;
-
-@SuppressWarnings("javadoc")
-public class AndroidXmlAutoEditStrategyTest extends AdtProjectTest {
-
- public void checkInsertNewline(String before, String after) throws Exception {
- AndroidXmlAutoEditStrategy s = new AndroidXmlAutoEditStrategy();
-
- // All tests just operate on the "edithandling" document; the contents are
- // ignored and replaced with the before-document passed in
- IFile file = getLayoutFile(getProject(), "edithandling.xml");
-
- IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
- assertNotNull(page);
- IEditorPart editor = IDE.openEditor(page, file);
- assertTrue(editor instanceof AndroidXmlEditor);
- AndroidXmlEditor layoutEditor = (AndroidXmlEditor) editor;
- ISourceViewer viewer = layoutEditor.getStructuredSourceViewer();
-
- String newDocumentContent = stripCaret(before);
- IDocument document = viewer.getDocument();
- document.replace(0, document.getLength(), newDocumentContent);
-
- // Determine the offset, and possibly make text range selections as well
- int offset = updateCaret(viewer, before);
-
- DocumentCommand c = new TestDocumentCommand();
- c.doit = true;
- c.offset = offset;
- c.caretOffset = -1;
- c.length = 0;
- c.text = "\n";
-
- s.customizeDocumentCommand(document, c);
-
- if (c.doit) {
- if (c.length == 0 && c.text == null) {
- return;
- }
-
- document.replace(c.offset, c.length, c.text);
-
- int caretOffset = c.offset + c.text.length();
-
- // The shiftsCaret flag doesn't behave the way it's documented to
- //if (c.shiftsCaret && c.caretOffset != -1) {
- if (c.caretOffset != -1) {
- caretOffset = c.caretOffset;
- }
- viewer.setSelectedRange(caretOffset, 0);
- }
-
- String text = document.get();
- Point selectedRange = viewer.getSelectedRange();
- assert selectedRange.y == 0;
- String textWithCaret = text;
- if (selectedRange.x >= 0) {
- textWithCaret = text.substring(0, selectedRange.x) + "^" +
- text.substring(selectedRange.x);
- }
-
- assertEquals(after, textWithCaret);
- }
-
- private static String stripCaret(String s) {
- int index = s.indexOf('^');
- assertTrue(index != -1);
- return s.substring(0, index) + s.substring(index + 1);
- }
-
- public void testCornerCase1() throws Exception {
- checkInsertNewline("^", "\n^");
- }
-
- public void testCornerCase2() throws Exception {
- checkInsertNewline(
- "\n^",
-
- "\n\n^");
- }
-
- public void testCornerCase3() throws Exception {
- checkInsertNewline(
- " ^",
-
- " \n" +
- " ^");
- }
-
- public void testSimpleIndentation1() throws Exception {
- checkInsertNewline(
- " ^ ",
-
- " \n" +
- " ^ ");
- }
-
- public void testSimpleIndentation2() throws Exception {
- checkInsertNewline(
- "\n" +
- " foo^\n",
-
- "\n" +
- " foo\n" +
- " ^\n");
- }
-
- public void testSimpleIndentation3() throws Exception {
- checkInsertNewline(
- "\n" +
- " <newtag>^\n",
-
- "\n" +
- " <newtag>\n" +
- " ^\n");
- }
-
- public void testSimpleIndentation4() throws Exception {
- checkInsertNewline(
- "\n" +
- " <newtag/>^\n",
-
- "\n" +
- " <newtag/>\n" +
- " ^\n");
- }
-
- public void testSimpleIndentation5() throws Exception {
- checkInsertNewline(
- "\n" +
- " <newtag^\n",
- "\n" +
- " <newtag\n" +
- " ^\n");
- }
-
- public void testSplitAttribute() throws Exception {
- checkInsertNewline(
- "\n" +
- " <newtag ^attribute='value'/>\n",
-
- "\n" +
- " <newtag \n" +
- " ^attribute='value'/>\n");
- }
-
- public void testIndentationInComments1() throws Exception {
- // Make sure that inside a comment we ignore tags etc
- checkInsertNewline(
- "<!--\n foo^\n--->\n",
-
- "<!--\n foo\n ^\n--->\n");
- }
-
- public void testIndentationInComments2() throws Exception {
- // Make sure that inside a comment we ignore tags etc
- checkInsertNewline(
- "\n" +
- "<!--\n" +
- "<foo><^\n" +
- "-->\n",
-
- "\n" +
- "<!--\n" +
- "<foo><\n" +
- "^\n" +
- "-->\n");
- }
-
- public void testSurroundCaret() throws Exception {
- checkInsertNewline(
- "\n" +
- " <item>^</item>\n",
-
- "\n" +
- " <item>\n" +
- " ^\n" +
- " </item>\n");
- }
-
- public void testSurroundCaret2() throws Exception {
- // This test combines both surround with and continuing earlier lines (where
- // it searches for a matching tag)
- checkInsertNewline(
- "\n" +
- " <foo\n" +
- " name='value'>^</foo>\n",
-
- "\n" +
- " <foo\n" +
- " name='value'>\n" +
- " ^\n" +
- " </foo>\n");
- }
-
- public void testContinueEarlierLine1() throws Exception {
- // Here we need to indent to the exact location of an earlier line
- checkInsertNewline(
- "\n" +
- " <foo\n" +
- " name='value'/>^\n",
-
- "\n" +
- " <foo\n" +
- " name='value'/>\n" +
- " ^\n");
- }
-
- public void testContinueEarlierLine2() throws Exception {
- checkInsertNewline(
- "\n" +
- " <foo\n" +
- " name='value'></foo>^\n",
-
- "\n" +
- " <foo\n" +
- " name='value'></foo>\n" +
- " ^\n");
- // Note that
- // <foo
- // >
- // </foo>
- // does not require special handling, this only happens with the closing tag is sharing
- // a line.
- }
-
- public void testContinueEarlierLine3() throws Exception {
- // Make sure the code to look up the corresponding opening tag works properly
- checkInsertNewline(
- "\n" +
- " <foo\n" +
- " name='value'><bar></bar><baz/></foo>^\n",
-
- "\n" +
- " <foo\n" +
- " name='value'><bar></bar><baz/></foo>\n" +
- " ^\n");
- }
-
- public void testContinueEarlierLine4() throws Exception {
- checkInsertNewline(
- " <Button\n" +
- " android:id=\"@+id/button1\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:text=\"Button\" >^\n" +
- " </Button>\n",
-
- " <Button\n" +
- " android:id=\"@+id/button1\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:text=\"Button\" >\n" +
- " ^\n" +
- " </Button>\n");
- }
-
- public void testIndent() throws Exception {
- checkInsertNewline(
- " <Button\n" +
- " attr=\"value\"></Button>^\n",
-
- " <Button\n" +
- " attr=\"value\"></Button>\n" +
- " ^\n" +
- "");
- }
-
- public void testLineBeginning1() throws Exception {
- // Test that if you insert on a blank line, we just add a newline and indent
- checkInsertNewline(
- "<foo>\n" +
- "^\n" +
- "</foo>",
-
- "<foo>\n" +
- "\n" +
- " ^\n" +
- "</foo>");
- }
-
- public void testLineBeginning2() throws Exception {
- // Test that if you insert with the caret on the beginning of a line that has
- // content, we insert an indent correctly
- checkInsertNewline(
- "<foo>\n" +
- "^ <bar/>\n" +
- "</foo>",
-
- "<foo>\n" +
- "\n" +
- " ^<bar/>\n" +
- "</foo>");
- }
-
- public void testLineBeginning3() throws Exception {
- checkInsertNewline(
- "<foo>\n" +
- " <bar>\n" +
- "^\n" +
- " <baz/>\n" +
- " </bar>\n" +
- "</foo>",
-
- "<foo>\n" +
- " <bar>\n" +
- "\n" +
- " ^\n" +
- " <baz/>\n" +
- " </bar>\n" +
- "</foo>");
-
- }
-
- public void testLineBeginning4() throws Exception {
- // Test that if you insert with the caret on the beginning of a line that has
- // content, we insert an indent correctly
- checkInsertNewline(
- "<foo>\n" +
- " <bar>\n" +
- "\n" +
- "^ <baz/>\n" +
- " </bar>\n" +
- "</foo>",
-
- "<foo>\n" +
- " <bar>\n" +
- "\n" +
- "\n" +
- " ^<baz/>\n" +
- " </bar>\n" +
- "</foo>");
- }
-
- public void testLineBeginning5() throws Exception {
- // Test that if you insert with the caret on the beginning of a line that has
- // content, we insert an indent correctly
- checkInsertNewline(
- "<foo>\n" +
- " <bar>\n" +
- "\n" +
- " ^ <baz/>\n" +
- " </bar>\n" +
- "</foo>",
-
- "<foo>\n" +
- " <bar>\n" +
- "\n" +
- " \n" +
- " ^<baz/>\n" +
- " </bar>\n" +
- "</foo>");
- }
-
- public void testLineBeginning6() throws Exception {
-
- checkInsertNewline(
- " <foo>\n" +
- " <bar>\n" +
- " \n" +
- " \n" +
- "^ </bar>\n" +
- " </foo>\n",
-
- " <foo>\n" +
- " <bar>\n" +
- " \n" +
- " \n" +
- "\n" +
- " ^</bar>\n" +
- " </foo>\n");
- }
-
- public void testBlankContinuation() throws Exception {
-
- checkInsertNewline(
- " <foo>\n" +
- " <bar>\n" +
- " ^\n" +
- " </bar>\n" +
- " </foo>\n" +
- "",
-
- " <foo>\n" +
- " <bar>\n" +
- " \n" +
- " ^\n" +
- " </bar>\n" +
- " </foo>\n" +
- "");
- }
-
- public void testIssue22332a() throws Exception {
- checkInsertNewline(
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<resources>\n" +
- "\n" +
- " <string name=\"hello\">Hello World, MainActivity!</string>^\n" +
- "\n" +
- "</resources>",
-
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<resources>\n" +
- "\n" +
- " <string name=\"hello\">Hello World, MainActivity!</string>\n" +
- " ^\n" +
- "\n" +
- "</resources>");
- }
-
- public void testIssue22332b() throws Exception {
- checkInsertNewline(
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<resources>\n" +
- "\n" +
- " <string name=\"hello\">Hello World, MainActivity!</string>\n" +
- " ^\n" +
- "\n" +
- "</resources>",
-
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<resources>\n" +
- "\n" +
- " <string name=\"hello\">Hello World, MainActivity!</string>\n" +
- " \n" +
- " ^\n" +
- "\n" +
- "</resources>");
- }
-
- /**
- * To test
- * When you press / after < I should reindent the current line. For example,
- * if you have
- * <foo>
- * <bar>
- * </ the moment you've typed this we should dedent it back out
- * When you press newline we need to reindent
- */
-
- /** Subclassed for test usage since constructor is protected */
- private class TestDocumentCommand extends DocumentCommand {
- public TestDocumentCommand() {
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/AndroidXmlCharacterMatcherTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/AndroidXmlCharacterMatcherTest.java
deleted file mode 100644
index acb2b049b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/AndroidXmlCharacterMatcherTest.java
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors;
-
-import com.android.ide.eclipse.adt.internal.editors.layout.refactoring.AdtProjectTest;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-
-@SuppressWarnings("restriction")
-public class AndroidXmlCharacterMatcherTest extends AdtProjectTest {
- public void testGotoMatchingFwd1() throws Exception {
- checkGotoMatching(
- "<app^lication android:icon",
- "^</application>");
- }
-
- public void testGotoMatchingFwd2() throws Exception {
- checkGotoMatching(
- "^<application android:icon",
- "^</application>");
- }
-
- public void testGotoMatchingFwd3() throws Exception {
- checkGotoMatching(
- "<application^ android:icon",
- "^</application>");
- }
-
- public void testGotoMatchingBwd1() throws Exception {
- checkGotoMatching(
- "^</application>",
- "^<application android:icon");
- }
-
- public void testGotoMatchingBwd2() throws Exception {
- checkGotoMatching(
- "<^/application>",
- "^<application android:icon");
- }
-
- public void testGotoMatchingBwd3() throws Exception {
- checkGotoMatching(
- "</^application>",
- "^<application android:icon");
- }
-
- public void testGotoMatchingBwd4() throws Exception {
- checkGotoMatching(
- "</app^lication>",
- "^<application android:icon");
- }
-
- public void testGotoMatchingBwd5() throws Exception {
- checkGotoMatching(
- "</^application>",
- "^<application android:icon");
- }
-
- public void testGotoMatchingBwd6() throws Exception {
- checkGotoMatching(
- "</^application>",
- "^<application android:icon");
- }
-
- public void testGotoMatchingFwd4() throws Exception {
- checkGotoMatching(
- "<intent-filter^>",
- "^</intent-filter>");
- }
-
- public void testGotoMatchingFwd5() throws Exception {
- checkGotoMatching(
- "<intent-filter>^",
- "^</intent-filter>");
- }
-
- public void testGotoMatchingFallback() throws Exception {
- // Character matching is done by the superclass; ensure that fallback to the
- // other XML matchers is working
- checkGotoMatching(
- "android:icon=^\"@drawable/icon\"",
- "android:icon=\"@drawable/icon^\"");
- }
-
- private void checkGotoMatching(IFile file, String caretBefore,
- String caretAfter) throws Exception {
- IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
- assertNotNull(page);
- IEditorPart editor = IDE.openEditor(page, file);
- assertTrue(editor instanceof AndroidXmlEditor);
- AndroidXmlEditor layoutEditor = (AndroidXmlEditor) editor;
- ISourceViewer viewer = layoutEditor.getStructuredSourceViewer();
-
- int caretPosBefore = updateCaret(viewer, caretBefore);
-
- AndroidXmlCharacterMatcher matcher = new AndroidXmlCharacterMatcher();
- IStructuredDocument document = layoutEditor.getStructuredDocument();
-
- IRegion match = matcher.match(document, caretPosBefore);
- assertNotNull(match);
-
- String text = document.get();
- final String after = stripCaret(caretAfter);
- int index = text.indexOf(after);
- int caretPosAfter = match.getOffset() - index;
- String textWithCaret = after.substring(0, caretPosAfter)
- + "^" + after.substring(caretPosAfter);
-
- assertEquals(caretAfter, textWithCaret);
- }
-
- private static String stripCaret(String s) {
- int index = s.indexOf('^');
- assertTrue(index != -1);
- return s.substring(0, index) + s.substring(index + 1);
- }
-
- private void checkGotoMatching(String caretBefore,
- String caretAfter) throws Exception {
- checkGotoMatching(
- getTestDataFile(getProject(), "manifest.xml", "AndroidManifest.xml", true),
- caretBefore, caretAfter);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/HyperlinksTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/HyperlinksTest.java
deleted file mode 100644
index 20aae846b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/HyperlinksTest.java
+++ /dev/null
@@ -1,320 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors;
-
-import static com.android.SdkConstants.FD_SOURCES;
-
-import com.android.ide.common.resources.ResourceFile;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.Hyperlinks.ResourceLink;
-import com.android.ide.eclipse.adt.internal.editors.Hyperlinks.XmlResolver;
-import com.android.ide.eclipse.adt.internal.editors.layout.refactoring.AdtProjectTest;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.jface.text.IRegion;
-import org.eclipse.jface.text.Region;
-import org.eclipse.jface.text.hyperlink.IHyperlink;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.ide.IDE;
-import org.eclipse.ui.internal.ErrorEditorPart;
-import org.eclipse.ui.internal.browser.WebBrowserEditor;
-import org.eclipse.wst.sse.ui.StructuredTextEditor;
-import org.eclipse.wst.sse.ui.internal.StructuredTextViewer;
-import org.eclipse.wst.xml.ui.internal.tabletree.XMLMultiPageEditorPart;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-
-@SuppressWarnings({
- "restriction", "javadoc"
-})
-public class HyperlinksTest extends AdtProjectTest {
- @Override
- protected boolean testCaseNeedsUniqueProject() {
- return true;
- }
-
- public void testFqnRegexp() throws Exception {
- assertTrue(Hyperlinks.isViewClassName("com.android.Foo"));
- assertTrue(Hyperlinks.isViewClassName("com.android.pk_g.Foo_Bar1"));
- assertTrue(Hyperlinks.isViewClassName("com.android.Foo$Inner"));
-
- // Should we allow non-standard packages and class names?
- // For now, we're allowing it -- see how this works out in practice.
- //assertFalse(XmlHyperlinkResolver.isViewClassName("Foo.bar"));
- assertTrue(Hyperlinks.isViewClassName("Foo.bar"));
-
- assertFalse(Hyperlinks.isViewClassName("LinearLayout"));
- assertFalse(Hyperlinks.isViewClassName("."));
- assertFalse(Hyperlinks.isViewClassName(".F"));
- assertFalse(Hyperlinks.isViewClassName("f."));
- assertFalse(Hyperlinks.isViewClassName("Foo"));
- assertFalse(Hyperlinks.isViewClassName("com.android.1Foo"));
- assertFalse(Hyperlinks.isViewClassName("1com.Foo"));
- }
-
- public void testNavigate1() throws Exception {
- // Check navigating to a local resource
- checkXmlNavigation("navigation1.xml", "res/layout/navigation1.xml",
- "android:text=\"@string/app^_name\"");
- }
-
- public void testNavigate2() throws Exception {
- // Check navigating to a framework resource
- checkXmlNavigation("navigation1.xml", "res/layout/navigation1.xml",
- "marginLeft=\"@android:dimen/app_ico^n_size\"");
- }
-
- public void testNavigate3() throws Exception {
- // Check navigating to a style
- checkXmlNavigation("navigation1.xml", "res/layout/navigation1.xml",
- "style=\"@android:style/Widget.B^utton\"");
- }
-
- public void testNavigate4() throws Exception {
- // Check navigating to resource with many resolutions
- checkXmlNavigation("navigation1.xml", "res/layout/navigation1.xml",
- "android:text=\"@android:st^ring/ok\"");
- }
-
- public void testNavigate5() throws Exception {
- // Check navigating to styles
- checkXmlNavigation("navigationstyles.xml", "res/values/navigationstyles.xml",
- "parent=\"android:Theme.Li^ght\">");
- }
-
- public void testNavigate6() throws Exception {
- // Check navigating to a portion of a style (this should pick android:Theme, not
- // android:Theme.Light
- checkXmlNavigation("navigationstyles.xml", "res/values/navigationstyles.xml",
- "parent=\"android:The^me.Light\">");
- }
-
- public void testNavigate7() throws Exception {
- // Check navigating to a resource inside text content
- checkXmlNavigation("navigationstyles.xml", "res/values/navigationstyles.xml",
- "popupBackground\">@android:drawable/spinner_dr^opdown_background</item>");
- }
-
- public void testNavigate8() throws Exception {
- // Check navigating to a resource inside text content where there is space around
- // the URL
- checkXmlNavigation("navigationstyles.xml", "res/values/navigationstyles.xml",
- "colorBackground\"> @color/cust^om_theme_color </item>");
- }
-
- public void testNavigate9a() throws Exception {
- // Check navigating to a an activity
- checkXmlNavigation("manifest.xml", "AndroidManifest.xml",
- "<activity android:name=\".Test^Activity\"");
- }
-
- /* Not yet implemented
- public void testNavigate9b() throws Exception {
- // Check navigating to a an activity - clicking on the activity element should
- // work too
- checkXmlNavigation("manifest.xml", "AndroidManifest.xml",
- "<acti^vity android:name=\".TestActivity\"");
- }
- */
-
- public void testNavigate10() throws Exception {
- // Check navigating to a permission
- checkXmlNavigation("manifest.xml", "AndroidManifest.xml",
- "<uses-permission android:name=\"android.permission.AC^CESS_NETWORK_STATE\" />");
- }
-
- public void testNavigate11a() throws Exception {
- // Check navigating to an intent
- checkXmlNavigation("manifest.xml", "AndroidManifest.xml",
- "<action android:name=\"android.intent.ac^tion.MAIN\" />");
- }
-
- public void testNavigate11g() throws Exception {
- // Check navigating to an intent
- checkXmlNavigation("manifest.xml", "AndroidManifest.xml",
- "<category android:name=\"android.intent.category.LA^UNCHER\" />");
- }
-
- public void testNavigate12() throws Exception {
- // Check navigating to a custom view class
- checkXmlNavigation("navigation1.xml", "res/layout/navigation1.xml",
- "<my.Cust^omView></my.CustomView>");
- }
-
- public void testNavigate13() throws Exception {
- // Check jumping to classes pointed to by fragments
-
- getTestDataFile(getProject(), "TestFragment.java.txt",
- FD_SOURCES + "/" + TEST_PROJECT_PACKAGE.replace('.', '/') + "/TestFragment.java");
- checkXmlNavigation("fragmentlayout.xml", "res/layout/fragmentlayout.xml",
- "android:name=\"com.android.ecl^ipse.tests.TestFragment\"");
- }
-
- public void testNavigate14() throws Exception {
- // Check jumping to classes pointed to by fragments
-
- getTestDataFile(getProject(), "TestFragment.java.txt",
- FD_SOURCES + "/" + TEST_PROJECT_PACKAGE.replace('.', '/') + "/TestFragment.java");
- checkXmlNavigation("fragmentlayout.xml", "res/layout/fragmentlayout.xml",
- "class=\"com.and^roid.eclipse.tests.TestFragment\"");
- }
-
- public void testNavigate15() throws Exception {
- // Check navigating to a theme resource
- checkXmlNavigation("navigation1.xml", "res/layout/navigation1.xml",
- "?android:attr/alert^DialogStyle");
- }
-
- public void testNavigate16() throws Exception {
- // Check navigating to a theme resource
- checkXmlNavigation("navigation1.xml", "res/layout/navigation1.xml",
- "?android:alert^DialogStyle");
- }
-
- // Left to test:
- // onClick handling
- // class attributes
- // Test that the correct file is actually opened!
-
- private void checkXmlNavigation(String basename, String targetPath,
- String caretLocation) throws Exception {
- IFile file = getTestDataFile(getProject(), basename, targetPath, true);
-
- // Determine the offset
- int offset = getCaretOffset(file, caretLocation);
-
- // Open file
- IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
- assertNotNull(page);
- IEditorPart editor = IDE.openEditor(page, file);
- assertTrue(editor.getClass().getName(), editor instanceof AndroidXmlEditor);
- AndroidXmlEditor layoutEditor = (AndroidXmlEditor) editor;
- ISourceViewer viewer = layoutEditor.getStructuredSourceViewer();
-
- XmlResolver resolver = new Hyperlinks.XmlResolver();
- IHyperlink[] links = resolver.detectHyperlinks(viewer, new Region(offset, 0), true);
- assertNotNull(links);
-
- StringBuilder sb = new StringBuilder(1000);
- sb.append("Go To Declaration in " + basename + " for " + caretLocation + ":\n");
- for (IHyperlink link : links) {
- sb.append(link.getHyperlinkText());
- sb.append(" : ");
- sb.append(" [");
- IRegion region = link.getHyperlinkRegion();
- sb.append(viewer.getDocument().get(region.getOffset(), region.getLength()));
- sb.append("]");
- if (link instanceof Hyperlinks.ResourceLink) {
- Hyperlinks.ResourceLink resourceLink = (ResourceLink) link;
- sb.append("\n ");
- ResourceFile resourceFile = resourceLink.getFile();
- String desc = resourceFile.toString();
- desc = desc.replace('\\', '/');
- // For files in the SDK folder, strip out file prefix
- int dataRes = desc.indexOf("data/res");
- if (dataRes != -1) {
- desc = desc.substring(dataRes);
- }
- desc = removeSessionData(desc);
- sb.append(desc);
- }
- sb.append('\n');
- }
-
- // Open the first link
- IHyperlink link = links[0];
- link.open();
- IEditorPart newEditor = AdtUtils.getActiveEditor();
- // Ensure that this isn't an invalid file (e.g. opening the SDK platform files
- // with incorrect content binding could cause this)
- assertTrue(!(newEditor instanceof ErrorEditorPart));
-
- IDocument document = null;
- Point selection = null;
-
- if (newEditor instanceof AndroidXmlEditor) {
- AndroidXmlEditor xmlEditor = (AndroidXmlEditor) newEditor;
- document = xmlEditor.getStructuredSourceViewer().getDocument();
- selection = xmlEditor.getStructuredSourceViewer().getSelectedRange();
- } else if (newEditor instanceof XMLMultiPageEditorPart) {
- XMLMultiPageEditorPart xmlEditor = (XMLMultiPageEditorPart) newEditor;
- Field field = xmlEditor.getClass().getDeclaredField("fTextEditor");
- field.setAccessible(true);
- StructuredTextEditor ste = (StructuredTextEditor) field.get(newEditor);
- if (ste == null) {
- Method method = xmlEditor.getClass().getMethod("getTextEditor", new Class[0]);
- ste = (StructuredTextEditor) method.invoke(newEditor, new Object[0]);
- }
- StructuredTextViewer textViewer = ste.getTextViewer();
- document = textViewer.getDocument();
- selection = textViewer.getSelectedRange();
- } else if (newEditor instanceof WebBrowserEditor) {
- WebBrowserEditor browser = (WebBrowserEditor) newEditor;
- Field field = browser.getClass().getDeclaredField("initialURL");
- field.setAccessible(true);
- String initialUrl = (String) field.get(newEditor);
- int index = initialUrl.indexOf("reference");
- if (index != -1) {
- initialUrl = initialUrl.substring(index);
- }
- initialUrl = initialUrl.replace('\\', '/');
- sb.append("\n\nAfter open, a browser is shown with this URL:\n");
- sb.append(" ");
- sb.append(initialUrl);
- sb.append("\n");
- } else if (newEditor instanceof JavaEditor) {
- JavaEditor javaEditor = (JavaEditor) newEditor;
- document = javaEditor.getDocumentProvider().getDocument(javaEditor.getEditorInput());
- IRegion range = javaEditor.getHighlightRange();
- selection = new Point(range.getOffset(), range.getLength());
- } else {
- fail("Unhandled editor type: " + newEditor.getClass().getName());
- return;
- }
-
- if (document != null && selection != null) {
- int lineStart = document.getLineInformationOfOffset(selection.x).getOffset();
- IRegion lineEndInfo = document.getLineInformationOfOffset(selection.x + selection.y);
- int lineEnd = lineEndInfo.getOffset() + lineEndInfo.getLength();
- String text = document.get(lineStart, lineEnd - lineStart);
- int selectionStart = selection.x - lineStart;
- int selectionEnd = selectionStart + selection.y;
- if (selectionEnd > selectionStart) {
- // Selection range
- text = text.substring(0, selectionStart) + "[^" +
- text.substring(selectionStart, selectionEnd) + "]" +
- text.substring(selectionEnd);
- } else {
- text = text.substring(0, selectionStart) + "^" +
- text.substring(selectionStart);
- }
- text = removeSessionData(text);
-
- sb.append("\n\nAfter open, the selected text is:\n");
- sb.append(text);
- sb.append("\n");
- }
-
- assertEqualsGolden(basename, sb.toString(), "txt");
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/formatting/EclipseXmlPrettyPrinterTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/formatting/EclipseXmlPrettyPrinterTest.java
deleted file mode 100644
index ac5fd0196..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/formatting/EclipseXmlPrettyPrinterTest.java
+++ /dev/null
@@ -1,978 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.formatting;
-
-import com.android.ide.common.xml.XmlFormatStyle;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-
-import org.eclipse.jface.preference.PreferenceStore;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings({
- "javadoc", "restriction"
-})
-public class EclipseXmlPrettyPrinterTest extends TestCase {
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- PreferenceStore store = new PreferenceStore();
- AdtPrefs.init(store);
- AdtPrefs prefs = AdtPrefs.getPrefs();
- prefs.initializeStoreWithDefaults(store);
- prefs.loadValues(null);
- EclipseXmlFormatPreferences formatPrefs = EclipseXmlFormatPreferences.create();
- assertTrue(formatPrefs.oneAttributeOnFirstLine);
- }
-
- private void checkFormat(EclipseXmlFormatPreferences prefs, String baseLocation,
- String xml,
- String expected, String delimiter, String startNodeName,
- boolean openTagOnly, String endNodeName) throws Exception {
-
- IStructuredModel model = DomUtilities.createStructuredModel(xml);
- assertNotNull(model);
- model.setBaseLocation(baseLocation);
- Document document = null;
- if (model instanceof IDOMModel) {
- IDOMModel domModel = (IDOMModel) model;
- document = domModel.getDocument();
- } else {
- fail("Can't get DOM model");
- return;
- }
- XmlFormatStyle style = AndroidXmlFormattingStrategy.guessStyle(model, document);
-
- EclipseXmlPrettyPrinter printer = new EclipseXmlPrettyPrinter(prefs, style, delimiter);
- printer.setEndWithNewline(xml.endsWith("\n"));
-
- StringBuilder sb = new StringBuilder(1000);
- Node startNode = document;
- Node endNode = document;
- if (startNodeName != null) {
- startNode = findNode(document.getDocumentElement(), startNodeName);
- }
- if (endNodeName != null) {
- endNode = findNode(document.getDocumentElement(), endNodeName);
- }
-
- printer.prettyPrint(-1, document, startNode, endNode, sb, false/*openTagOnly*/);
- String formatted = sb.toString();
- if (!expected.equals(formatted)) {
- System.out.println(formatted);
- }
- assertEquals(expected, formatted);
- }
-
- private Node findNode(Node node, String nodeName) {
- if (node.getNodeName().equals(nodeName)) {
- return node;
- }
-
- NodeList children = node.getChildNodes();
- for (int i = 0, n = children.getLength(); i < n; i++) {
- Node child = children.item(i);
- Node result = findNode(child, nodeName);
- if (result != null) {
- return result;
- }
- }
-
- return null;
- }
-
- protected int getCaretOffset(String fileContent, String caretLocation) {
- int caretDelta = caretLocation.indexOf("^"); //$NON-NLS-1$
- assertTrue(caretLocation, caretDelta != -1);
-
- String caretContext = caretLocation.substring(0, caretDelta)
- + caretLocation.substring(caretDelta + 1); // +1: skip "^"
- int caretContextIndex = fileContent.indexOf(caretContext);
- assertTrue("Caret content " + caretContext + " not found in file",
- caretContextIndex != -1);
- return caretContextIndex + caretDelta;
- }
-
- private void checkFormat(EclipseXmlFormatPreferences prefs, String baseLocation, String xml,
- String expected, String delimiter) throws Exception {
- checkFormat(prefs, baseLocation, xml, expected, delimiter, null, false, null);
- }
-
- private void checkFormat(EclipseXmlFormatPreferences prefs, String baseLocation, String xml,
- String expected) throws Exception {
- checkFormat(prefs, baseLocation, xml, expected, "\n"); //$NON-NLS-1$
- }
- private void checkFormat(String baseLocation, String xml, String expected)
- throws Exception {
- EclipseXmlFormatPreferences prefs = EclipseXmlFormatPreferences.create();
- checkFormat(prefs, baseLocation, xml, expected);
- }
-
- public void testLayout1() throws Exception {
- checkFormat(
- "res/layout-port/layout1.xml",
- "<LinearLayout><Button></Button></LinearLayout>",
-
- "<LinearLayout>\n" +
- "\n" +
- " <Button>\n" +
- " </Button>\n" +
- "\n" +
- "</LinearLayout>");
- }
-
- public void testLayout2() throws Exception {
- checkFormat(
- "res/layout-port/layout2.xml",
- "<LinearLayout><Button foo=\"bar\"></Button></LinearLayout>",
-
- "<LinearLayout>\n" +
- "\n" +
- " <Button foo=\"bar\" >\n" +
- " </Button>\n" +
- "\n" +
- "</LinearLayout>");
- }
-
- public void testLayout3() throws Exception {
- EclipseXmlFormatPreferences prefs = EclipseXmlFormatPreferences.create();
- prefs.oneAttributeOnFirstLine = true;
- checkFormat(
- prefs, "res/layout-land/layout3.xml",
- "<LinearLayout><Button foo=\"bar\"></Button></LinearLayout>",
-
- "<LinearLayout>\n" +
- "\n" +
- " <Button foo=\"bar\" >\n" +
- " </Button>\n" +
- "\n" +
- "</LinearLayout>");
- }
-
- public void testClosedElements() throws Exception {
- checkFormat(
- "res/values/strings.xml",
- "<resources>\n" +
- "<item name=\"title_container\" type=\"id\" />\n" +
- "<item name=\"title_logo\" type=\"id\"/>\n" +
- "</resources>\n",
-
- "<resources>\n" +
- "\n" +
- " <item name=\"title_container\" type=\"id\"/>\n" +
- " <item name=\"title_logo\" type=\"id\"/>\n" +
- "\n" +
- "</resources>\n");
- }
-
- public void testResources() throws Exception {
- checkFormat(
- "res/values-us/strings.xml",
- "<resources><item name=\"foo\">Text value here </item></resources>",
- "<resources>\n\n" +
- " <item name=\"foo\">Text value here </item>\n" +
- "\n</resources>");
- }
-
- public void testNodeTypes() throws Exception {
- // Ensures that a document with all kinds of node types is serialized correctly
- checkFormat(
- "res/layout-xlarge/layout.xml",
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<!--\n" +
- "/**\n" +
- " * Licensed under the Apache License, Version 2.0 (the \"License\");\n" +
- " */\n" +
- "-->\n" +
- "<!DOCTYPE metadata [\n" +
- "<!ELEMENT metadata (category)*>\n" +
- "<!ENTITY % ISOLat2\n" +
- " SYSTEM \"http://www.xml.com/iso/isolat2-xml.entities\" >\n" +
- "]>\n" +
- "<LinearLayout\n" +
- " xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " android:orientation=\"vertical\">\n" +
- "<![CDATA[\n" +
- "This is character data!\n" +
- "<!-- This is not a comment! -->\n" +
- "and <this is not an element>\n" +
- "]]> \n" +
- "This is text: &lt; and &amp;\n" +
- "<!-- comment 1 \"test\"... -->\n" +
- "<!-- ... comment2 -->\n" +
- "%ISOLat2; \n" +
- "<!-- \n" +
- "Type <key>less-than</key> (&#x3C;)\n" +
- "--> \n" +
- "</LinearLayout>",
-
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<!--\n" +
- "/**\n" +
- " * Licensed under the Apache License, Version 2.0 (the \"License\");\n" +
- " */\n" +
- "-->\n" +
- "<!DOCTYPE metadata [\n" +
- "<!ELEMENT metadata (category)*>\n" +
- "<!ENTITY % ISOLat2\n" +
- " SYSTEM \"http://www.xml.com/iso/isolat2-xml.entities\" >\n" +
- "]>\n" +
- "<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " android:orientation=\"vertical\" >\n" +
- "<![CDATA[\n" +
- "This is character data!\n" +
- "<!-- This is not a comment! -->\n" +
- "and <this is not an element>\n" +
- "]]>\n" +
- "This is text: &lt; and &amp;\n" +
- " <!-- comment 1 \"test\"... -->\n" +
- " <!-- ... comment2 -->\n" +
- "%ISOLat2; \n" +
- "<!-- Type <key>less-than</key> (&#x3C;) -->\n" +
- "\n" +
- "</LinearLayout>");
- }
-
- public void testWindowsDelimiters() throws Exception {
- checkFormat(
- EclipseXmlFormatPreferences.create(), "res/layout-xlarge/layout.xml",
- "<LinearLayout><Button foo=\"bar\"></Button></LinearLayout>",
-
- "<LinearLayout>\r\n" +
- "\r\n" +
- " <Button foo=\"bar\" >\r\n" +
- " </Button>\r\n" +
- "\r\n" +
- "</LinearLayout>",
- "\r\n");
- }
-
- public void testRemoveBlanklines() throws Exception {
- EclipseXmlFormatPreferences prefs = EclipseXmlFormatPreferences.create();
- prefs.removeEmptyLines = true;
- checkFormat(
- prefs, "res/layout-xlarge/layout.xml",
- "<foo><bar><baz1></baz1><baz2></baz2></bar><bar2></bar2><bar3><baz12></baz12></bar3></foo>",
-
- "<foo>\n" +
- " <bar>\n" +
- " <baz1>\n" +
- " </baz1>\n" +
- " <baz2>\n" +
- " </baz2>\n" +
- " </bar>\n" +
- " <bar2>\n" +
- " </bar2>\n" +
- " <bar3>\n" +
- " <baz12>\n" +
- " </baz12>\n" +
- " </bar3>\n" +
- "</foo>");
- }
-
- public void testRange() throws Exception {
- checkFormat(
- EclipseXmlFormatPreferences.create(), "res/layout-xlarge/layout.xml",
- "<LinearLayout><Button foo=\"bar\"></Button><CheckBox/></LinearLayout>",
- "\n" +
- " <Button foo=\"bar\" >\n" +
- " </Button>\n" +
- "\n" +
- " <CheckBox />\n",
- "\n",
- "Button", false, "CheckBox");
- }
-
- public void testOpenTagOnly() throws Exception {
- checkFormat(
- EclipseXmlFormatPreferences.create(), "res/layout-xlarge/layout.xml",
- "<LinearLayout><Button foo=\"bar\"></Button><CheckBox/></LinearLayout>",
- "\n" +
- " <Button foo=\"bar\" >\n" +
- " </Button>\n",
- "\n",
-
- "Button", true, "Button");
- }
-
- public void testRange2() throws Exception {
- EclipseXmlFormatPreferences prefs = EclipseXmlFormatPreferences.create();
- prefs.removeEmptyLines = true;
- checkFormat(
- prefs, "res/layout-xlarge/layout.xml",
- "<foo><bar><baz1></baz1><baz2></baz2></bar><bar2></bar2><bar3><baz12></baz12></bar3></foo>",
-
- " <baz1>\n" +
- " </baz1>\n" +
- " <baz2>\n" +
- " </baz2>\n" +
- " </bar>\n" +
- " <bar2>\n" +
- " </bar2>\n" +
- " <bar3>\n" +
- " <baz12>\n" +
- " </baz12>\n",
- "\n",
- "baz1", false, "baz12");
- }
-
- public void testEOLcomments() throws Exception {
- checkFormat(
- "res/drawable-mdpi/states.xml",
- "<selector xmlns:android=\"http://schemas.android.com/apk/res/android\">\n" +
- " <item android:state_pressed=\"true\"\n" +
- " android:color=\"#ffff0000\"/> <!-- pressed -->\n" +
- " <item android:state_focused=\"true\"\n" +
- " android:color=\"#ff0000ff\"/> <!-- focused -->\n" +
- " <item android:color=\"#ff000000\"/> <!-- default -->\n" +
- "</selector>",
- "<selector xmlns:android=\"http://schemas.android.com/apk/res/android\">\n" +
- "\n" +
- " <item android:state_pressed=\"true\" android:color=\"#ffff0000\"/> <!-- pressed -->\n" +
- " <item android:state_focused=\"true\" android:color=\"#ff0000ff\"/> <!-- focused -->\n" +
- " <item android:color=\"#ff000000\"/> <!-- default -->\n" +
- "\n" +
- "</selector>");
- }
-
- public void testFormatColorList() throws Exception {
- checkFormat(
- "res/drawable-hdpi/states.xml",
- "<selector xmlns:android=\"http://schemas.android.com/apk/res/android\">\n" +
- "<item android:state_activated=\"true\" android:color=\"#FFFFFF\"/>\n" +
- "<item android:color=\"#777777\" /> <!-- not selected -->\n" +
- "</selector>",
- "<selector xmlns:android=\"http://schemas.android.com/apk/res/android\">\n" +
- "\n" +
- " <item android:state_activated=\"true\" android:color=\"#FFFFFF\"/>\n" +
- " <item android:color=\"#777777\"/> <!-- not selected -->\n" +
- "\n" +
- "</selector>");
- }
-
- public void testPreserveNewlineAfterComment() throws Exception {
- checkFormat(
- "res/values/dimen.xml",
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<resources><dimen name=\"colorstrip_height\">6dip</dimen>\n" +
- " <!-- comment1 --><dimen name=\"title_height\">45dip</dimen>\n" +
- "\n" +
- " <!-- comment2: newline above --><dimen name=\"now_playing_height\">90dip</dimen>\n" +
- " <dimen name=\"text_size_small\">14sp</dimen>\n" +
- "\n" +
- "\n" +
- " <!-- comment3: newline above and below -->\n" +
- "\n" +
- "\n" +
- "\n" +
- " <dimen name=\"text_size_medium\">18sp</dimen><dimen name=\"text_size_large\">22sp</dimen>\n" +
- "</resources>",
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<resources>\n" +
- "\n" +
- " <dimen name=\"colorstrip_height\">6dip</dimen>\n" +
- " <!-- comment1 -->\n" +
- " <dimen name=\"title_height\">45dip</dimen>\n" +
- "\n" +
- " <!-- comment2: newline above -->\n" +
- " <dimen name=\"now_playing_height\">90dip</dimen>\n" +
- " <dimen name=\"text_size_small\">14sp</dimen>\n" +
- "\n" +
- " <!-- comment3: newline above and below -->\n" +
- "\n" +
- " <dimen name=\"text_size_medium\">18sp</dimen>\n" +
- " <dimen name=\"text_size_large\">22sp</dimen>\n" +
- "\n" +
- "</resources>");
- }
-
- public void testPlurals() throws Exception {
- checkFormat(
- "res/values-us/strings.xml",
- "<resources xmlns:xliff=\"urn:oasis:names:tc:xliff:document:1.2\">\n" +
- "<string name=\"toast_sync_error\">Sync error: <xliff:g id=\"error\">%1$s</xliff:g></string>\n" +
- "<string name=\"session_subtitle\"><xliff:g id=\"time\">%1$s</xliff:g> in <xliff:g id=\"room\">%2$s</xliff:g></string>\n" +
- "<plurals name=\"now_playing_countdown\">\n" +
- "<item quantity=\"zero\"><xliff:g id=\"remaining_time\">%2$s</xliff:g></item>\n" +
- "<item quantity=\"one\"><xliff:g id=\"number_of_days\">%1$s</xliff:g> day, <xliff:g id=\"remaining_time\">%2$s</xliff:g></item>\n" +
- "<item quantity=\"other\"><xliff:g id=\"number_of_days\">%1$s</xliff:g> days, <xliff:g id=\"remaining_time\">%2$s</xliff:g></item>\n" +
- "</plurals>\n" +
- "</resources>",
- "<resources xmlns:xliff=\"urn:oasis:names:tc:xliff:document:1.2\">\n" +
- "\n" +
- " <string name=\"toast_sync_error\">Sync error: <xliff:g id=\"error\">%1$s</xliff:g></string>\n" +
- " <string name=\"session_subtitle\"><xliff:g id=\"time\">%1$s</xliff:g> in <xliff:g id=\"room\">%2$s</xliff:g></string>\n" +
- "\n" +
- " <plurals name=\"now_playing_countdown\">\n" +
- " <item quantity=\"zero\"><xliff:g id=\"remaining_time\">%2$s</xliff:g></item>\n" +
- " <item quantity=\"one\"><xliff:g id=\"number_of_days\">%1$s</xliff:g> day, <xliff:g id=\"remaining_time\">%2$s</xliff:g></item>\n" +
- " <item quantity=\"other\"><xliff:g id=\"number_of_days\">%1$s</xliff:g> days, <xliff:g id=\"remaining_time\">%2$s</xliff:g></item>\n" +
- " </plurals>\n" +
- "\n" +
- "</resources>");
- }
-
- public void testMultiAttributeResource() throws Exception {
- checkFormat(
- "res/values-us/strings.xml",
- "<resources><string name=\"debug_enable_debug_logging_label\" translatable=\"false\">Enable extra debug logging?</string></resources>",
- "<resources>\n" +
- "\n" +
- " <string name=\"debug_enable_debug_logging_label\" translatable=\"false\">Enable extra debug logging?</string>\n" +
- "\n" +
- "</resources>");
- }
-
- public void testMultilineCommentAlignment() throws Exception {
- checkFormat(
- "res/values-us/strings.xml",
- "<resources>" +
- " <!-- Deprecated strings - Move the identifiers to this section, mark as DO NOT TRANSLATE,\n" +
- " and remove the actual text. These will be removed in a bulk operation. -->\n" +
- " <!-- Do Not Translate. Unused string. -->\n" +
- " <string name=\"meeting_invitation\"></string>\n" +
- "</resources>",
- "<resources>\n" +
- "\n" +
- " <!--\n" +
- " Deprecated strings - Move the identifiers to this section, mark as DO NOT TRANSLATE,\n" +
- " and remove the actual text. These will be removed in a bulk operation.\n" +
- " -->\n" +
- " <!-- Do Not Translate. Unused string. -->\n" +
- " <string name=\"meeting_invitation\"></string>\n" +
- "\n" +
- "</resources>");
- }
-
- public void testLineCommentSpacing() throws Exception {
- checkFormat(
- "res/values-us/strings.xml",
- "<resources>\n" +
- "\n" +
- " <dimen name=\"colorstrip_height\">6dip</dimen>\n" +
- " <!-- comment1 -->\n" +
- " <dimen name=\"title_height\">45dip</dimen>\n" +
- " <!-- comment2: no newlines -->\n" +
- " <dimen name=\"now_playing_height\">90dip</dimen>\n" +
- " <dimen name=\"text_size_small\">14sp</dimen>\n" +
- "\n" +
- " <!-- comment3: newline above and below -->\n" +
- "\n" +
- " <dimen name=\"text_size_medium\">18sp</dimen>\n" +
- " <dimen name=\"text_size_large\">22sp</dimen>\n" +
- "\n" +
- "</resources>",
-
- "<resources>\n" +
- "\n" +
- " <dimen name=\"colorstrip_height\">6dip</dimen>\n" +
- " <!-- comment1 -->\n" +
- " <dimen name=\"title_height\">45dip</dimen>\n" +
- " <!-- comment2: no newlines -->\n" +
- " <dimen name=\"now_playing_height\">90dip</dimen>\n" +
- " <dimen name=\"text_size_small\">14sp</dimen>\n" +
- "\n" +
- " <!-- comment3: newline above and below -->\n" +
- "\n" +
- " <dimen name=\"text_size_medium\">18sp</dimen>\n" +
- " <dimen name=\"text_size_large\">22sp</dimen>\n" +
- "\n" +
- "</resources>");
- }
-
- public void testCommentHandling() throws Exception {
- checkFormat(
- EclipseXmlFormatPreferences.create(), "res/layout/layout1.xml",
- "<foo >\n" +
- "\n" +
- " <!-- abc\n" +
- " def\n" +
- " ghi -->\n" +
- "\n" +
- " <!-- abc\n" +
- " def\n" +
- " ghi -->\n" +
- " \n" +
- "<!-- abc\n" +
- "def\n" +
- "ghi -->\n" +
- "\n" +
- "</foo>",
-
- "<foo>\n" +
- "\n" +
- " <!--\n" +
- " abc\n" +
- " def\n" +
- " ghi\n" +
- " -->\n" +
- "\n" +
- "\n" +
- " <!--\n" +
- " abc\n" +
- " def\n" +
- " ghi\n" +
- " -->\n" +
- "\n" +
- "\n" +
- " <!--\n" +
- "abc\n" +
- "def\n" +
- "ghi\n" +
- " -->\n" +
- "\n" +
- "</foo>");
- }
-
- public void testCommentHandling2() throws Exception {
- checkFormat(
- EclipseXmlFormatPreferences.create(), "res/layout-xlarge/layout.xml",
- "<foo >\n" +
- " <!-- multi -->\n" +
- "\n" +
- " <bar />\n" +
- "</foo>",
-
- "<foo>\n" +
- "\n" +
- " <!-- multi -->\n" +
- "\n" +
- " <bar />\n" +
- "\n" +
- "</foo>");
- }
-
- public void testMenus1() throws Exception {
- checkFormat(
- EclipseXmlFormatPreferences.create(), "res/menu/menu1.xml",
- // http://code.google.com/p/android/issues/detail?id=21383
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<menu xmlns:android=\"http://schemas.android.com/apk/res/android\" >\n" +
- "\n" +
- " <item\n" +
- " android:id=\"@+id/menu_debug\"\n" +
- " android:icon=\"@android:drawable/ic_menu_more\"\n" +
- " android:showAsAction=\"ifRoom|withText\"\n" +
- " android:title=\"@string/menu_debug\">\n" +
- " \n" +
- " <menu>\n" +
- " <item\n" +
- " android:id=\"@+id/menu_debug_clearCache_memory\"\n" +
- " android:icon=\"@android:drawable/ic_menu_delete\"\n" +
- " android:showAsAction=\"ifRoom|withText\"\n" +
- " android:title=\"@string/menu_debug_clearCache_memory\"/>\n" +
- " \n" +
- " <item\n" +
- " android:id=\"@+id/menu_debug_clearCache_file\"\n" +
- " android:icon=\"@android:drawable/ic_menu_delete\"\n" +
- " android:showAsAction=\"ifRoom|withText\"\n" +
- " android:title=\"@string/menu_debug_clearCache_file\"/>\n" +
- " </menu>\n" +
- " </item>\n" +
- "</menu>",
-
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<menu xmlns:android=\"http://schemas.android.com/apk/res/android\" >\n" +
- "\n" +
- " <item\n" +
- " android:id=\"@+id/menu_debug\"\n" +
- " android:icon=\"@android:drawable/ic_menu_more\"\n" +
- " android:showAsAction=\"ifRoom|withText\"\n" +
- " android:title=\"@string/menu_debug\">\n" +
- " <menu>\n" +
- " <item\n" +
- " android:id=\"@+id/menu_debug_clearCache_memory\"\n" +
- " android:icon=\"@android:drawable/ic_menu_delete\"\n" +
- " android:showAsAction=\"ifRoom|withText\"\n" +
- " android:title=\"@string/menu_debug_clearCache_memory\"/>\n" +
- " <item\n" +
- " android:id=\"@+id/menu_debug_clearCache_file\"\n" +
- " android:icon=\"@android:drawable/ic_menu_delete\"\n" +
- " android:showAsAction=\"ifRoom|withText\"\n" +
- " android:title=\"@string/menu_debug_clearCache_file\"/>\n" +
- " </menu>\n" +
- " </item>\n" +
- "\n" +
- "</menu>");
- }
-
- public void testMenus2() throws Exception {
- EclipseXmlFormatPreferences prefs = EclipseXmlFormatPreferences.create();
- prefs.removeEmptyLines = true;
- checkFormat(
- prefs, "res/drawable-hdpi/layerlist.xml",
- // http://code.google.com/p/android/issues/detail?id=21346
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<layer-list xmlns:android=\"http://schemas.android.com/apk/res/android\">\n" +
- " <item>\n" +
- " <shape android:shape=\"rectangle\">\n" +
- " <stroke\n" +
- " android:width=\"1dip\"\n" +
- " android:color=\"@color/line_separator\"/>\n" +
- " <solid android:color=\"@color/event_header_background\"/>\n" +
- " </shape>\n" +
- " </item>\n" +
- " <item\n" +
- " android:bottom=\"1dip\"\n" +
- " android:top=\"1dip\">\n" +
- " <shape android:shape=\"rectangle\">\n" +
- " <stroke\n" +
- " android:width=\"1dip\"\n" +
- " android:color=\"@color/event_header_background\"/>\n" +
- " <solid android:color=\"@color/transparent\"/>\n" +
- " </shape>\n" +
- " </item>\n" +
- "</layer-list>",
-
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<layer-list xmlns:android=\"http://schemas.android.com/apk/res/android\" >\n" +
- " <item>\n" +
- " <shape android:shape=\"rectangle\" >\n" +
- " <stroke\n" +
- " android:width=\"1dip\"\n" +
- " android:color=\"@color/line_separator\" />\n" +
- " <solid android:color=\"@color/event_header_background\" />\n" +
- " </shape>\n" +
- " </item>\n" +
- " <item\n" +
- " android:bottom=\"1dip\"\n" +
- " android:top=\"1dip\">\n" +
- " <shape android:shape=\"rectangle\" >\n" +
- " <stroke\n" +
- " android:width=\"1dip\"\n" +
- " android:color=\"@color/event_header_background\" />\n" +
- " <solid android:color=\"@color/transparent\" />\n" +
- " </shape>\n" +
- " </item>\n" +
- "</layer-list>");
- }
-
- public void testMenus3() throws Exception {
- checkFormat(
- EclipseXmlFormatPreferences.create(), "res/menu/menu1.xml",
- // http://code.google.com/p/android/issues/detail?id=21227
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<menu xmlns:android=\"http://schemas.android.com/apk/res/android\" >\n" +
- "\n" +
- " <item\n" +
- " android:icon=\"@android:drawable/ic_menu_more\"\n" +
- " android:title=\"@string/account_list_menu_more\">\n" +
- " <menu>\n" +
- " <item\n" +
- " android:id=\"@+id/account_list_menu_backup_restore\"\n" +
- " android:icon=\"@android:drawable/ic_menu_save\"\n" +
- " android:title=\"@string/account_list_menu_backup_restore\"/>\n" +
- " </menu>\n" +
- " </item>\n" +
- "\n" +
- "</menu>",
-
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<menu xmlns:android=\"http://schemas.android.com/apk/res/android\" >\n" +
- "\n" +
- " <item\n" +
- " android:icon=\"@android:drawable/ic_menu_more\"\n" +
- " android:title=\"@string/account_list_menu_more\">\n" +
- " <menu>\n" +
- " <item\n" +
- " android:id=\"@+id/account_list_menu_backup_restore\"\n" +
- " android:icon=\"@android:drawable/ic_menu_save\"\n" +
- " android:title=\"@string/account_list_menu_backup_restore\"/>\n" +
- " </menu>\n" +
- " </item>\n" +
- "\n" +
- "</menu>");
-
- }
-
- public void testColors1() throws Exception {
- checkFormat(
- EclipseXmlFormatPreferences.create(), "res/values/colors.xml",
- "<resources>\n" +
- " <color name=\"enrollment_error\">#99e21f14</color>\n" +
- "\n" +
- " <color name=\"service_starting_up\">#99000000</color>\n" +
- "</resources>",
-
- "<resources>\n" +
- "\n" +
- " <color name=\"enrollment_error\">#99e21f14</color>\n" +
- " <color name=\"service_starting_up\">#99000000</color>\n" +
- "\n" +
- "</resources>");
- }
-
- public void testEclipseFormatStyle1() throws Exception {
- EclipseXmlFormatPreferences prefs = new EclipseXmlFormatPreferences() {
- @Override
- public String getOneIndentUnit() {
- return "\t";
- }
-
- @Override
- public int getTabWidth() {
- return 8;
- }
- };
- checkFormat(
- prefs, "res/values/colors.xml",
- "<resources>\n" +
- " <color name=\"enrollment_error\">#99e21f14</color>\n" +
- "\n" +
- " <color name=\"service_starting_up\">#99000000</color>\n" +
- "</resources>",
-
- "<resources>\n" +
- "\n" +
- "\t<color name=\"enrollment_error\">#99e21f14</color>\n" +
- "\t<color name=\"service_starting_up\">#99000000</color>\n" +
- "\n" +
- "</resources>");
- }
-
- public void testEclipseFormatStyle2() throws Exception {
- EclipseXmlFormatPreferences prefs = new EclipseXmlFormatPreferences() {
- @Override
- public String getOneIndentUnit() {
- return " ";
- }
-
- @Override
- public int getTabWidth() {
- return 2;
- }
- };
- prefs.useEclipseIndent = true;
- checkFormat(
- prefs, "res/values/colors.xml",
- "<resources>\n" +
- " <color name=\"enrollment_error\">#99e21f14</color>\n" +
- "\n" +
- " <color name=\"service_starting_up\">#99000000</color>\n" +
- "</resources>",
-
- "<resources>\n" +
- "\n" +
- " <color name=\"enrollment_error\">#99e21f14</color>\n" +
- " <color name=\"service_starting_up\">#99000000</color>\n" +
- "\n" +
- "</resources>");
- }
-
- public void testNameSorting() throws Exception {
- checkFormat(
- "res/values/dimen.xml",
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<resources>\n" +
- " <attr format=\"integer\" name=\"no\" />\n" +
- "</resources>",
-
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<resources>\n" +
- "\n" +
- " <attr name=\"no\" format=\"integer\" />\n" +
- "\n" +
- "</resources>");
- }
-
- public void testStableText() throws Exception {
- checkFormat(
- "res/layout/stable.xml",
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\"\n" +
- " android:orientation=\"vertical\">\n" +
- " Hello World\n" +
- "\n" +
- "</LinearLayout>",
-
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\"\n" +
- " android:orientation=\"vertical\" >\n" +
- " Hello World\n" +
- "\n" +
- "</LinearLayout>");
- }
-
- public void testResources1() throws Exception {
- checkFormat(
- "res/values/strings.xml",
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<resources>\n" +
- "\n" +
- " <string name=\"test_string\">a\n" +
- " </string>\n" +
- "\n" +
- "</resources>",
-
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<resources>\n" +
- "\n" +
- " <string name=\"test_string\">a</string>\n" +
- "\n" +
- "</resources>");
- }
-
- public void testMarkup() throws Exception {
- checkFormat(
- "res/values/strings.xml",
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<resources>\n" +
- "\n" +
- "<string name=\"welcome\">Welcome to <b>Android</b>!</string>" +
- "<string name=\"glob_settings_top_text\"><b>To install a 24 Clock Widget, " +
- "please <i>long press</i> in Home Screen.</b> Configure the Global Settings " +
- "here.</string>" +
- "" +
- "\n" +
- "</resources>",
-
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<resources>\n" +
- "\n" +
- " <string name=\"welcome\">Welcome to <b>Android</b>!</string>\n" +
- " <string name=\"glob_settings_top_text\"><b>To install a 24 Clock Widget, " +
- "please <i>long press</i> in Home Screen.</b> Configure the Global Settings " +
- "here.</string>\n" +
- "\n" +
- "</resources>");
- }
-
- public void testPreserveEntities() throws Exception {
- // Ensure that entities such as &gt; in the input string are preserved in the output
- // format
- checkFormat(
- "res/values/strings.xml",
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<resources><string name=\"untitled\">&lt;untitled2></string>\n" +
- "<string name=\"untitled2\">&lt;untitled2&gt;</string>\n" +
- "<string name=\"untitled3\">&apos;untitled3&quot;</string></resources>\n",
-
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<resources>\n" +
- "\n" +
- " <string name=\"untitled\">&lt;untitled2></string>\n" +
- " <string name=\"untitled2\">&lt;untitled2&gt;</string>\n" +
- " <string name=\"untitled3\">&apos;untitled3&quot;</string>\n" +
- "\n" +
- "</resources>\n");
- }
-
- public void testCData1() throws Exception {
- checkFormat(
- "res/values/strings.xml",
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<resources>\n" +
- " <string name=\"foo\"><![CDATA[bar]]></string>\n" +
- "</resources>",
-
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<resources>\n" +
- "\n" +
- " <string name=\"foo\"><![CDATA[bar]]></string>\n" +
- "\n" +
- "</resources>");
- }
-
- public void testCData2() throws Exception {
- checkFormat(
- "res/values/strings.xml",
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<resources>\n" +
- " <string name=\"foo1\"><![CDATA[bar1\n" +
- "bar2\n" +
- "bar3]]></string>\n" +
- " <string name=\"foo2\"><![CDATA[bar]]></string>\n" +
- "</resources>",
-
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<resources>\n" +
- "\n" +
- " <string name=\"foo1\">\n" +
- "<![CDATA[bar1\n" +
- "bar2\n" +
- "bar3]]>\n" +
- " </string>\n" +
- " <string name=\"foo2\"><![CDATA[bar]]></string>\n" +
- "\n" +
- "</resources>");
- }
-
- public void testComplexString() throws Exception {
- checkFormat(
- "res/values/strings.xml",
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<resources>\n" +
- "<string name=\"progress_completed_export_all\">The database has " +
- "<b>successfully</b> been exported into: <br /><br /><font size=\"14\">" +
- "\\\"<i>%s</i>\\\"</font></string>" +
- "</resources>",
-
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<resources>\n" +
- "\n" +
- " <string name=\"progress_completed_export_all\">The database has " +
- "<b>successfully</b> been exported into: <br /><br /><font size=\"14\">" +
- "\\\"<i>%s</i>\\\"</font></string>\n" +
- "\n" +
- "</resources>");
- }
-
- public void test52887() throws Exception {
- // https://code.google.com/p/android/issues/detail?id=52887
- checkFormat(
- "res/layout/relative.xml",
-
- "<!--Comment-->\n" +
- "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\"/>\n",
-
- "<!-- Comment -->\n" +
- "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\" />\n");
- }
-
- public void testPreserveLastNewline() throws Exception {
- checkFormat(
- "res/values/strings.xml",
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<resources>\n" +
- "<string name=\"progress_completed_export_all\">The database has " +
- "<b>successfully</b> been exported into: <br /><br /><font size=\"14\">" +
- "\\\"<i>%s</i>\\\"</font></string>" +
- "</resources>\n",
-
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<resources>\n" +
- "\n" +
- " <string name=\"progress_completed_export_all\">The database has " +
- "<b>successfully</b> been exported into: <br /><br /><font size=\"14\">" +
- "\\\"<i>%s</i>\\\"</font></string>\n" +
- "\n" +
- "</resources>\n");
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutMetadataTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutMetadataTest.java
deleted file mode 100644
index c71064eba..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutMetadataTest.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ID_PREFIX;
-import static com.android.SdkConstants.NEW_ID_PREFIX;
-import static com.android.SdkConstants.TOOLS_PREFIX;
-import static com.android.SdkConstants.TOOLS_URI;
-
-import com.android.ide.common.layout.BaseLayoutRule;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.layout.refactoring.AdtProjectTest;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.utils.Pair;
-import com.android.utils.XmlUtils;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-/**
- *
- */
-@SuppressWarnings({"restriction", "javadoc", "deprecation"}) // XML DOM model
-public class LayoutMetadataTest extends AdtProjectTest {
-
- public void testMetadata1() throws Exception {
- Pair<IDocument, UiElementNode> pair = getNode("metadata.xml", "listView1");
- UiElementNode uiNode = pair.getSecond();
- Node node = uiNode.getXmlNode();
-
- assertNull(LayoutMetadata.getProperty(node, "foo"));
-
- Element element = (Element) node;
- String prefix = XmlUtils.lookupNamespacePrefix(element, TOOLS_URI, null, false);
- if (prefix == null) {
- // Add in new prefix...
- prefix = XmlUtils.lookupNamespacePrefix(element,
- TOOLS_URI, TOOLS_PREFIX, true);
- }
- element.setAttribute(prefix + ':' + "foo", "bar");
- }
-
- // ==== Test utilities ====
-
- private static String getText(IDocument document, Node node) throws Exception {
- IndexedRegion region = (IndexedRegion) node;
- // This often returns the wrong value:
- //int length = region.getLength();
- int length = region.getEndOffset() - region.getStartOffset();
- return document.get(region.getStartOffset(), length);
- }
-
- private Pair<IDocument, UiElementNode> getNode(String filename, String targetId)
- throws Exception, PartInitException {
- IFile file = getLayoutFile(getProject(), filename);
- AdtPlugin.openFile(file, null);
- IEditorPart newEditor = AdtUtils.getActiveEditor();
- assertTrue(newEditor instanceof AndroidXmlEditor);
- AndroidXmlEditor xmlEditor = (AndroidXmlEditor) newEditor;
- IStructuredDocument document = xmlEditor.getStructuredDocument();
- UiElementNode root = xmlEditor.getUiRootNode();
- assertNotNull(root);
- UiElementNode node = findById(root, targetId);
- assertNotNull(node);
- Pair<IDocument, UiElementNode> pair = Pair.<IDocument, UiElementNode>of(document, node);
- return pair;
- }
-
- private static UiElementNode findById(UiElementNode node, String targetId) {
- assertFalse(targetId.startsWith(NEW_ID_PREFIX));
- assertFalse(targetId.startsWith(ID_PREFIX));
-
- String id = node.getAttributeValue(ATTR_ID);
- if (id != null && targetId.equals(BaseLayoutRule.stripIdPrefix(id))) {
- return node;
- }
-
- for (UiElementNode child : node.getUiChildren()) {
- UiElementNode result = findById(child, targetId);
- if (result != null) {
- return result;
- }
- }
-
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/AdtProjectTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/AdtProjectTest.java
deleted file mode 100644
index 9c48ccdad..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/AdtProjectTest.java
+++ /dev/null
@@ -1,495 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import static com.android.SdkConstants.FD_RES;
-import static com.android.SdkConstants.FD_RES_LAYOUT;
-import static com.android.SdkConstants.FD_RES_VALUES;
-
-import com.android.ide.common.sdk.LoadStatus;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.LayoutDescriptors;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiDocumentNode;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.internal.wizards.newproject.NewProjectCreator;
-import com.android.ide.eclipse.adt.internal.wizards.newproject.NewProjectWizardState;
-import com.android.ide.eclipse.adt.internal.wizards.newproject.NewProjectWizardState.Mode;
-import com.android.ide.eclipse.tests.SdkLoadingTestCase;
-import com.android.sdklib.IAndroidTarget;
-
-import org.eclipse.core.resources.IContainer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.wst.sse.core.StructuredModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.InputStream;
-import java.lang.reflect.InvocationTargetException;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-@SuppressWarnings({"restriction", "javadoc"})
-public abstract class AdtProjectTest extends SdkLoadingTestCase {
- private static final int TARGET_API_LEVEL = 16;
- public static final String TEST_PROJECT_PACKAGE = "com.android.eclipse.tests"; //$NON-NLS-1$
- private static final long TESTS_START_TIME = System.currentTimeMillis();
- private static final String PROJECTNAME_PREFIX = "testproject-";
-
- /**
- * We don't stash the project used by each test case as a field such that test cases
- * can share a single project instance (which is typically much faster).
- * However, see {@link #getProjectName()} for exceptions to this sharing scheme.
- */
- private static Map<String, IProject> sProjectMap = new HashMap<String, IProject>();
-
- @Override
- protected String getTestDataRelPath() {
- return "eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/"
- + "internal/editors/layout/refactoring/testdata";
- }
-
- @Override
- protected InputStream getTestResource(String relativePath, boolean expectExists) {
- String path = "testdata" + File.separator + relativePath; //$NON-NLS-1$
- InputStream stream =
- AdtProjectTest.class.getResourceAsStream(path);
- if (!expectExists && stream == null) {
- return null;
- }
- return stream;
- }
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
-
- // Prevent preview icon computation during plugin test to make test faster
- if (AdtPlugin.getDefault() == null) {
- fail("This test must be run as an Eclipse plugin test, not a plain JUnit test!");
- }
- AdtPrefs.getPrefs().setPaletteModes("ICON_TEXT"); //$NON-NLS-1$
-
- getProject();
-
- Sdk current = Sdk.getCurrent();
- assertNotNull(current);
- LoadStatus sdkStatus = AdtPlugin.getDefault().getSdkLoadStatus();
- assertSame(LoadStatus.LOADED, sdkStatus);
- IAndroidTarget target = current.getTarget(getProject());
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(getProject());
- assertNotNull(javaProject);
- int iterations = 0;
- while (true) {
- if (iterations == 100) {
- fail("Couldn't load target; ran out of time");
- }
- LoadStatus status = current.checkAndLoadTargetData(target, javaProject);
- if (status == LoadStatus.FAILED) {
- fail("Couldn't load target " + target);
- }
- if (status != LoadStatus.LOADING) {
- break;
- }
- Thread.sleep(250);
- iterations++;
- }
- AndroidTargetData targetData = current.getTargetData(target);
- assertNotNull(targetData);
- LayoutDescriptors layoutDescriptors = targetData.getLayoutDescriptors();
- assertNotNull(layoutDescriptors);
- List<ViewElementDescriptor> viewDescriptors = layoutDescriptors.getViewDescriptors();
- assertNotNull(viewDescriptors);
- assertTrue(viewDescriptors.size() > 0);
- List<ViewElementDescriptor> layoutParamDescriptors =
- layoutDescriptors.getLayoutDescriptors();
- assertNotNull(layoutParamDescriptors);
- assertTrue(layoutParamDescriptors.size() > 0);
- }
-
- /** Set to true if the subclass test case should use a per-instance project rather
- * than a shared project. This is needed by projects which modify the project in such
- * a way that it affects what other tests see (for example, the quickfix resource creation
- * tests will add in new resources, which the code completion tests will then list as
- * possible matches if the code completion test is run after the quickfix test.)
- * @return true to create a per-instance project instead of the default shared project
- */
- protected boolean testCaseNeedsUniqueProject() {
- return false;
- }
-
- protected boolean testNeedsUniqueProject() {
- return false;
- }
-
- @Override
- protected boolean validateSdk(IAndroidTarget target) {
- // Not quite working yet. When enabled will make tests run faster.
- //if (target.getVersion().getApiLevel() < TARGET_API_LEVEL) {
- // return false;
- //}
-
- return true;
- }
-
- /** Returns a name to use for the project used in this test. Subclasses do not need to
- * override this if they can share a project with others - which is the case if they do
- * not modify the project in a way that does not affect other tests. For example
- * the resource quickfix test will create new resources which affect what shows up
- * in the code completion results, so the quickfix tests will override this method
- * to produce a unique project for its own tests.
- */
- private String getProjectName() {
- if (testNeedsUniqueProject()) {
- return PROJECTNAME_PREFIX + getClass().getSimpleName() + "-" + getName();
- } else if (testCaseNeedsUniqueProject()) {
- return PROJECTNAME_PREFIX + getClass().getSimpleName();
- } else {
- return PROJECTNAME_PREFIX + TESTS_START_TIME;
- }
- }
-
- protected IProject getProject() {
- String projectName = getProjectName();
- IProject project = sProjectMap.get(projectName);
- if (project == null) {
- project = createProject(projectName);
- assertNotNull(project);
- sProjectMap.put(projectName, project);
- }
- if (!testCaseNeedsUniqueProject() && !testNeedsUniqueProject()) {
- addCleanupDir(AdtUtils.getAbsolutePath(project).toFile());
- }
- addCleanupDir(project.getFullPath().toFile());
- return project;
- }
-
- protected IFile getTestDataFile(IProject project, String name) throws Exception {
- return getTestDataFile(project, name, name);
- }
-
- protected IFile getLayoutFile(IProject project, String name) throws Exception {
- return getTestDataFile(project, name, FD_RES + "/" + FD_RES_LAYOUT + "/" + name);
- }
-
- protected IFile getValueFile(IProject project, String name) throws Exception {
- return getTestDataFile(project, name, FD_RES + "/" + FD_RES_VALUES + "/" + name);
- }
-
- protected IFile getTestDataFile(IProject project, String sourceName,
- String destPath) throws Exception {
- return getTestDataFile(project, sourceName, destPath, false);
- }
-
- protected IFile getTestDataFile(IProject project, String sourceName,
- String destPath, boolean overwrite) throws Exception {
- String[] split = destPath.split("/"); //$NON-NLS-1$
- IContainer parent;
- String name;
- if (split.length == 1) {
- parent = project;
- name = destPath;
- } else {
- IFolder folder = project.getFolder(split[0]);
- NullProgressMonitor monitor = new NullProgressMonitor();
- if (!folder.exists()) {
- folder.create(true /* force */, true /* local */, monitor);
- }
- for (int i = 1, n = split.length; i < n -1; i++) {
- IFolder subFolder = folder.getFolder(split[i]);
- if (!subFolder.exists()) {
- subFolder.create(true /* force */, true /* local */, monitor);
- }
- folder = subFolder;
- }
- name = split[split.length - 1];
- parent = folder;
- }
- IFile file = parent.getFile(new Path(name));
- if (overwrite && file.exists()) {
- String currentContents = AdtPlugin.readFile(file);
- String newContents = readTestFile(sourceName, true);
- if (currentContents == null || !currentContents.equals(newContents)) {
- file.delete(true, new NullProgressMonitor());
- } else {
- return file;
- }
- }
- if (!file.exists()) {
- String xml = readTestFile(sourceName, true);
- InputStream bstream = new ByteArrayInputStream(xml.getBytes("UTF-8")); //$NON-NLS-1$
- NullProgressMonitor monitor = new NullProgressMonitor();
- file.create(bstream, false /* force */, monitor);
- }
-
- return file;
- }
-
- protected IProject createProject(String name) {
- IAndroidTarget target = null;
-
- IAndroidTarget[] targets = getSdk().getTargets();
- for (IAndroidTarget t : targets) {
- if (!t.isPlatform()) {
- continue;
- }
- if (t.getVersion().getApiLevel() >= TARGET_API_LEVEL) {
- target = t;
- break;
- }
- }
- assertNotNull(target);
-
- IRunnableContext context = new IRunnableContext() {
- @Override
- public void run(boolean fork, boolean cancelable, IRunnableWithProgress runnable)
- throws InvocationTargetException, InterruptedException {
- runnable.run(new NullProgressMonitor());
- }
- };
- NewProjectWizardState state = new NewProjectWizardState(Mode.ANY);
- state.projectName = name;
- state.target = target;
- state.packageName = TEST_PROJECT_PACKAGE;
- state.activityName = name;
- state.applicationName = name;
- state.createActivity = false;
- state.useDefaultLocation = true;
- if (getMinSdk() != -1) {
- state.minSdk = Integer.toString(getMinSdk());
- }
-
- NewProjectCreator creator = new NewProjectCreator(state, context);
- creator.createAndroidProjects();
- return validateProjectExists(name);
- }
-
- protected int getMinSdk() {
- return -1;
- }
-
- public void createTestProject() {
- IAndroidTarget target = null;
-
- IAndroidTarget[] targets = getSdk().getTargets();
- for (IAndroidTarget t : targets) {
- if (t.getVersion().getApiLevel() >= TARGET_API_LEVEL) {
- target = t;
- break;
- }
- }
- assertNotNull(target);
- }
-
- protected static IProject validateProjectExists(String name) {
- IProject iproject = getProject(name);
- assertTrue(String.format("%s project not created", name), iproject.exists());
- assertTrue(String.format("%s project not opened", name), iproject.isOpen());
- return iproject;
- }
-
- private static IProject getProject(String name) {
- IProject iproject = ResourcesPlugin.getWorkspace().getRoot().getProject(name);
- return iproject;
- }
-
- protected int getCaretOffset(IFile file, String caretLocation) {
- assertTrue(caretLocation, caretLocation.contains("^"));
-
- String fileContent = AdtPlugin.readFile(file);
- return getCaretOffset(fileContent, caretLocation);
- }
-
- /**
- * If the given caret location string contains a selection range, select that range in
- * the given viewer
- *
- * @param viewer the viewer to contain the selection
- * @param caretLocation the location string
- */
- protected int updateCaret(ISourceViewer viewer, String caretLocation) {
- assertTrue(caretLocation, caretLocation.contains("^")); //$NON-NLS-1$
-
- int caretDelta = caretLocation.indexOf("^"); //$NON-NLS-1$
- assertTrue(caretLocation, caretDelta != -1);
- String text = viewer.getTextWidget().getText();
-
- int length = 0;
-
- // String around caret/range without the range and caret marker characters
- String caretContext;
-
- if (caretLocation.contains("[^")) { //$NON-NLS-1$
- caretDelta--;
- assertTrue(caretLocation, caretLocation.startsWith("[^", caretDelta)); //$NON-NLS-1$
-
- int caretRangeEnd = caretLocation.indexOf(']', caretDelta + 2);
- assertTrue(caretLocation, caretRangeEnd != -1);
- length = caretRangeEnd - caretDelta - 2;
- assertTrue(length > 0);
- caretContext = caretLocation.substring(0, caretDelta)
- + caretLocation.substring(caretDelta + 2, caretRangeEnd)
- + caretLocation.substring(caretRangeEnd + 1);
- } else {
- caretContext = caretLocation.substring(0, caretDelta)
- + caretLocation.substring(caretDelta + 1); // +1: skip "^"
- }
-
- int caretContextIndex = text.indexOf(caretContext);
-
- assertTrue("Caret content " + caretContext + " not found in file",
- caretContextIndex != -1);
-
- int offset = caretContextIndex + caretDelta;
- viewer.setSelectedRange(offset, length);
-
- return offset;
- }
-
- protected String addSelection(String newFileContents, Point selectedRange) {
- int selectionBegin = selectedRange.x;
- int selectionEnd = selectionBegin + selectedRange.y;
- return addSelection(newFileContents, selectionBegin, selectionEnd);
- }
-
- @Override
- protected String removeSessionData(String data) {
- data = super.removeSessionData(data);
- if (getProject() != null) {
- data = data.replace(getProject().getName(), "PROJECTNAME");
- }
-
- return data;
- }
-
- public static ViewElementDescriptor createDesc(String name, String fqn, boolean hasChildren) {
- if (hasChildren) {
- return new ViewElementDescriptor(name, name, fqn, "", "", new AttributeDescriptor[0],
- new AttributeDescriptor[0], new ElementDescriptor[1], false);
- } else {
- return new ViewElementDescriptor(name, fqn);
- }
- }
-
- public static UiViewElementNode createNode(UiViewElementNode parent, String fqn,
- boolean hasChildren) {
- String name = fqn.substring(fqn.lastIndexOf('.') + 1);
- ViewElementDescriptor descriptor = createDesc(name, fqn, hasChildren);
- if (parent == null) {
- // All node hierarchies should be wrapped inside a document node at the root
- parent = new UiViewElementNode(createDesc("doc", "doc", true));
- }
- return (UiViewElementNode) parent.appendNewUiChild(descriptor);
- }
-
- public static UiViewElementNode createNode(String fqn, boolean hasChildren) {
- return createNode(null, fqn, hasChildren);
- }
-
- /** Special editor context set on the model to be rendered */
- protected static class TestLayoutEditorDelegate extends LayoutEditorDelegate {
-
- public TestLayoutEditorDelegate(
- IFile file,
- IStructuredDocument structuredDocument,
- UiDocumentNode uiRootNode) {
- super(new TestAndroidXmlCommonEditor(file, structuredDocument, uiRootNode));
- }
-
- static class TestAndroidXmlCommonEditor extends CommonXmlEditor {
-
- private final IFile mFile;
- private final IStructuredDocument mStructuredDocument;
- private UiDocumentNode mUiRootNode;
-
- TestAndroidXmlCommonEditor(
- IFile file,
- IStructuredDocument structuredDocument,
- UiDocumentNode uiRootNode) {
- mFile = file;
- mStructuredDocument = structuredDocument;
- mUiRootNode = uiRootNode;
- }
-
- @Override
- public IFile getInputFile() {
- return mFile;
- }
-
- @Override
- public IProject getProject() {
- return mFile.getProject();
- }
-
- @Override
- public IStructuredDocument getStructuredDocument() {
- return mStructuredDocument;
- }
-
- @Override
- public UiDocumentNode getUiRootNode() {
- return mUiRootNode;
- }
-
- @Override
- public void editorDirtyStateChanged() {
- }
-
- @Override
- public IStructuredModel getModelForRead() {
- IModelManager mm = StructuredModelManager.getModelManager();
- if (mm != null) {
- try {
- return mm.getModelForRead(mFile);
- } catch (Exception e) {
- fail(e.toString());
- }
- }
-
- return null;
- }
- }
- }
-
- public void testDummy() {
- // This class contains shared test functionality for testcase subclasses,
- // but without an actual test in the class JUnit complains (even if we make
- // it abstract)
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeLayoutRefactoringTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeLayoutRefactoringTest.java
deleted file mode 100644
index a716a75a3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeLayoutRefactoringTest.java
+++ /dev/null
@@ -1,136 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import static com.android.SdkConstants.FQCN_GRID_LAYOUT;
-import static com.android.SdkConstants.FQCN_LINEAR_LAYOUT;
-import static com.android.SdkConstants.FQCN_RELATIVE_LAYOUT;
-
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.CanvasViewInfo;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.w3c.dom.Element;
-
-import java.util.Collections;
-import java.util.List;
-
-@SuppressWarnings("javadoc")
-public class ChangeLayoutRefactoringTest extends RefactoringTest {
-
- public void testChangeLayout1a() throws Exception {
- // Test a basic layout which performs some nesting -- tests basic grid layout conversion
- checkRefactoring("sample1a.xml", true);
- }
-
- public void testChangeLayout1b() throws Exception {
- // Same as 1a, but with different formatting to look for edit handling to for example
- // remove a line that is made empty when its only attribute is removed
- checkRefactoring("sample1b.xml", true);
- }
-
- public void testChangeLayout2() throws Exception {
- // Test code which analyzes an embedded RelativeLayout
- checkRefactoring("sample2.xml", true);
- }
-
- public void testChangeLayout3() throws Exception {
- // Test handling of LinearLayout "weight" attributes on its children: the child with
- // weight > 0 should fill and subsequent children attach on the bottom/right
- checkRefactoring("sample3.xml", true);
- }
-
- public void testChangeLayout4() throws Exception {
- checkRefactoring("sample4.xml", true);
- }
-
- public void testChangeLayout5() throws Exception {
- // Test handling of LinearLayout "gravity" attributes on its children
- checkRefactoring("sample5.xml", true);
- }
-
- public void testChangeLayout6() throws Exception {
- // Check handling of the LinearLayout "baseline" attribute
- checkRefactoring("sample6.xml", true);
- }
-
- public void testGridLayout1() throws Exception {
- checkRefactoring(FQCN_GRID_LAYOUT, "sample1a.xml", true);
- }
-
- public void testGridLayout2() throws Exception {
- // Test code which analyzes an embedded RelativeLayout
- checkRefactoring(FQCN_GRID_LAYOUT, "sample2.xml", true);
- }
-
- public void testGridLayout5() throws Exception {
- // Test handling of LinearLayout "gravity" attributes on its children
- checkRefactoring(FQCN_GRID_LAYOUT, "sample5.xml", true);
- }
-
- public void testConvertToGrid() throws Exception {
- checkRefactoring(FQCN_GRID_LAYOUT, "sample9.xml", true);
- }
-
- public void testConvertFromGrid() throws Exception {
- checkRefactoring(FQCN_LINEAR_LAYOUT, "sample10.xml", true);
- }
-
- private void checkRefactoring(String basename, boolean flatten) throws Exception {
- checkRefactoring(FQCN_RELATIVE_LAYOUT, basename, flatten);
- }
-
- public void testInitialAttributes() throws Exception {
- checkRefactoring(FQCN_LINEAR_LAYOUT, "sample10.xml", true, "android:orientation=vertical");
- }
-
- public void testInsertSpacer() throws Exception {
- checkRefactoring(FQCN_GRID_LAYOUT, "sample11.xml", true);
- }
-
- private void checkRefactoring(String newLayoutType, String basename,
- boolean flatten) throws Exception {
- checkRefactoring(newLayoutType, basename, flatten, null);
- }
-
- @Override
- protected int getMinSdk() {
- return 14;
- }
-
- private void checkRefactoring(String newLayoutType, String basename,
- boolean flatten, String initialAttributes) throws Exception {
- IFile file = getLayoutFile(getProject(), basename);
- TestContext info = setupTestContext(file, basename);
- TestLayoutEditorDelegate layoutEditor = info.mLayoutEditorDelegate;
- CanvasViewInfo rootView = info.mRootView;
- Element element = info.mElement;
-
- List<Element> selectedElements = Collections.singletonList(element);
- ChangeLayoutRefactoring refactoring = new ChangeLayoutRefactoring(selectedElements,
- layoutEditor);
- refactoring.setFlatten(flatten);
- refactoring.setType(newLayoutType);
- if (initialAttributes != null) {
- refactoring.setInitializedAttributes(initialAttributes);
- }
- refactoring.setRootView(rootView);
-
- List<Change> changes = refactoring.computeChanges(new NullProgressMonitor());
- checkEdits(basename, changes);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeViewRefactoringTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeViewRefactoringTest.java
deleted file mode 100644
index 582ed0f27..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ChangeViewRefactoringTest.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import static com.android.SdkConstants.FQCN_RADIO_BUTTON;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.w3c.dom.Element;
-
-import java.util.List;
-
-public class ChangeViewRefactoringTest extends RefactoringTest {
-
- public void testChangeView1() throws Exception {
- checkRefactoring("sample1a.xml", FQCN_RADIO_BUTTON, "@+id/button1", "@+id/button6");
- }
-
- public void testChangeView2() throws Exception {
- // Tests (1) updating references to the renamed id of the changed widgets
- // (e.g. button3 is renamed to imageButton1 and layout references to button3
- // must be updated), and (2) removal of attributes not available in the new type
- // (the text property is removed since it is not available on the new widget
- // type ImageButton)
- checkRefactoring("sample2.xml", "android.widget.ImageButton",
- "@+id/button3", "@+id/button5");
- }
-
- private void checkRefactoring(String basename, String newType,
- String... ids) throws Exception {
- assertTrue(ids.length > 0);
-
- IFile file = getLayoutFile(getProject(), basename);
- TestContext info = setupTestContext(file, basename);
- TestLayoutEditorDelegate layoutEditor = info.mLayoutEditorDelegate;
- List<Element> selectedElements = getElements(info.mElement, ids);
-
- ChangeViewRefactoring refactoring = new ChangeViewRefactoring(selectedElements,
- layoutEditor);
- refactoring.setType(newType);
-
- List<Change> changes = refactoring.computeChanges(new NullProgressMonitor());
- checkEdits(basename, changes);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractIncludeRefactoringTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractIncludeRefactoringTest.java
deleted file mode 100644
index 1667649c5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractIncludeRefactoringTest.java
+++ /dev/null
@@ -1,170 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import static com.android.SdkConstants.DOT_XML;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.w3c.dom.Element;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-public class ExtractIncludeRefactoringTest extends RefactoringTest {
-
- @Override
- protected boolean autoFormat() {
- return false;
- }
-
- @Override
- protected boolean testCaseNeedsUniqueProject() {
- // Because some of these tests look at ALL layouts in the project
- // to identify matches
- return true;
- }
-
- public void testExtract1() throws Exception {
- // Basic: Extract a single button
- checkRefactoring("sample3.xml", "newlayout1", false, null, 2, false /* diffs */,
- "@+id/button2");
- }
-
- public void testExtract2() throws Exception {
- // Extract a couple of elements
- checkRefactoring("sample3.xml", "newlayout2", false, null, 2, false /* diffs */,
- "@+id/button2", "@+id/android_logo");
- }
-
- public void testExtract3() throws Exception {
- // Test to make sure layout attributes are updated
- checkRefactoring("sample2.xml", "newlayout3", false, null, 2, false /* diffs */,
- "@+id/button3");
- }
-
- public void testExtract4() throws Exception {
- // Tests extracting from -multiple- files (as well as with custom android namespace
- // prefix)
-
- // Make sure the variation-files exist
- Map<IPath, String> extraFiles = new HashMap<IPath, String>();
- extraFiles.put(getTestDataFile(getProject(), "sample3-variation1.xml",
- "res/layout-land/sample3.xml").getProjectRelativePath(),
- "sample3-variation1.xml");
- extraFiles.put(getTestDataFile(getProject(), "sample3-variation2.xml",
- "res/layout-xlarge-land/sample3.xml").getProjectRelativePath(),
- "sample3-variation2.xml");
-
- checkRefactoring("sample3.xml", "newlayout3", true, extraFiles, 4, false /* diffs */,
- "@+id/android_logo");
- }
-
- public void testExtract5() throws Exception {
- // Tests extracting from multiple files with -contiguous regions-.
-
- // Make sure the variation-files exist
- Map<IPath, String> extraFiles = new HashMap<IPath, String>();
- extraFiles.put(getTestDataFile(getProject(), "sample3-variation1.xml",
- "res/layout-land/sample3.xml").getProjectRelativePath(),
- "sample3-variation1.xml");
- extraFiles.put(getTestDataFile(getProject(), "sample3-variation2.xml",
- "res/layout-xlarge-land/sample3.xml").getProjectRelativePath(),
- "sample3-variation2.xml");
-
- checkRefactoring("sample3.xml", "newlayout3", true, extraFiles, 4, false /* diffs */,
- "@+id/android_logo", "@+id/button1");
- }
-
- public void testExtract6() throws Exception {
- // Tests extracting from multiple files where the layouts are completely
- // different/unrelated files
-
- // Create the duplicate files
- Map<IPath, String> extraFiles = new HashMap<IPath, String>();
- extraFiles.put(getTestDataFile(getProject(), "sample1a.xml",
- "res/layout/sample1a.xml").getProjectRelativePath(),
- "sample1a.xml");
- extraFiles.put(getTestDataFile(getProject(), "sample7.xml", "res/layout/sample7.xml")
- .getProjectRelativePath(), "sample7.xml");
- extraFiles.put(getTestDataFile(getProject(), "sample8.xml", "res/layout/sample8.xml")
- .getProjectRelativePath(), "sample8.xml");
-
- checkRefactoring("sample7.xml", "newlayout6", true, extraFiles, 4, true /* diffs */,
- "@+id/linearLayout4");
- }
-
- public void testExtract7() throws Exception {
- // Just like testExtract6, except we turn on auto-formatting
- IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore();
- AdtPrefs.init(store);
- AdtPrefs prefs = AdtPrefs.getPrefs();
- prefs.initializeStoreWithDefaults(store);
- store.setValue(AdtPrefs.PREFS_FORMAT_GUI_XML, true);
- prefs.loadValues(null);
-
- assertTrue(AdtPrefs.getPrefs().getFormatGuiXml());
-
- testExtract6();
- }
-
-
- private void checkRefactoring(String basename, String layoutName,
- boolean replaceOccurrences, Map<IPath,String> extraFiles,
- int expectedModifiedFileCount, boolean createDiffs, String... ids) throws Exception {
- assertTrue(ids.length > 0);
-
- IFile file = getLayoutFile(getProject(), basename);
- TestContext info = setupTestContext(file, basename);
- TestLayoutEditorDelegate layoutEditor = info.mLayoutEditorDelegate;
- List<Element> selectedElements = getElements(info.mElement, ids);
-
- ExtractIncludeRefactoring refactoring = new ExtractIncludeRefactoring(selectedElements,
- layoutEditor);
- refactoring.setLayoutName(layoutName);
- refactoring.setReplaceOccurrences(replaceOccurrences);
- List<Change> changes = refactoring.computeChanges(new NullProgressMonitor());
-
- assertTrue(changes.size() >= 3);
-
- Map<IPath,String> fileToGolden = new HashMap<IPath,String>();
- IPath sourcePath = file.getProjectRelativePath();
- fileToGolden.put(sourcePath, basename);
- IPath newPath = sourcePath.removeLastSegments(1).append(layoutName + DOT_XML);
- fileToGolden.put(newPath, layoutName + DOT_XML);
- if (extraFiles != null) {
- fileToGolden.putAll(extraFiles);
- }
-
- checkEdits(changes, fileToGolden, createDiffs);
-
- int modifiedFileCount = 0;
- for (Change change : changes) {
- if (change instanceof TextFileChange) {
- modifiedFileCount++;
- }
- }
- assertEquals(expectedModifiedFileCount, modifiedFileCount);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractStyleRefactoringTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractStyleRefactoringTest.java
deleted file mode 100644
index f64555dd6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/ExtractStyleRefactoringTest.java
+++ /dev/null
@@ -1,232 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import com.android.utils.Pair;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.text.ITextSelection;
-import org.eclipse.jface.text.TextSelection;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.ide.IDE;
-import org.w3c.dom.Attr;
-import org.w3c.dom.Element;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-public class ExtractStyleRefactoringTest extends RefactoringTest {
- @Override
- protected boolean testCaseNeedsUniqueProject() {
- return true;
- }
-
- public void testExtract1() throws Exception {
- // Test extracting into a new style file
- checkRefactoring("extractstyle1.xml", "newstyles.xml", "newstyle",
- false /* removeExtracted */, false /* applyStyle */, null, 1, "@+id/button2");
- }
-
- public void testExtract1b() throws Exception {
- // Extract and apply new style
- checkRefactoring("extractstyle1.xml", "newstyles2.xml", "newstyle",
- false /* removeExtracted */, true /* applyStyle */, null, 2, "@+id/button2");
- }
-
- public void testExtract1c() throws Exception {
- // Extract and remove extracted
- checkRefactoring("extractstyle1.xml", "newstyles3.xml", "newstyle",
- true /* removeExtracted */, false /* applyStyle */, null, 2, "@+id/button2");
- }
-
- public void testExtract1d() throws Exception {
- // Extract and apply style and remove extracted
- checkRefactoring("extractstyle1.xml", "newstyles4.xml", "newstyle",
- true /* removeExtracted */, true /* applyStyle */, null, 2, "@+id/button2");
- }
-
- public void testExtract2() throws Exception {
- getTestDataFile(getProject(), "navigationstyles.xml", "res/values/navigationstyles.xml");
-
- // -Modify- the existing styles.xml file
- checkRefactoring("extractstyle1.xml", "navigationstyles.xml", "newstyle",
- true /* removeExtracted */, true /* applyStyle */, null, 2, "@+id/button2");
- }
-
- public void testExtract3() throws Exception {
- // Select multiple elements - overlap in values.
- checkRefactoring("extractstyle1.xml", "newstyles4.xml", "newstyle",
- true /* removeExtracted */, true /* applyStyle */, null, 2,
- "@+id/button1", "@+id/button2");
- }
-
- // This test fails for some reason - not in the refactoring (checked manually)
- // but the DOM model returns null when run in a test context.
- public void testExtract4() throws Exception {
- // Test extracting on a single caret position over an attribute: Should extract
- // just that one attribute
- checkRefactoringByOffset("extractstyle1.xml", "newstyles5.xml", "newstyle",
- true /* removeExtracted */, true /* applyStyle */, null, 2,
- "android:text^Color=\"#FF00FF\"", "android:text^Color=\"#FF00FF\"");
- }
-
- public void testExtract5() throws Exception {
- // Test extracting on a range selection inside an element: should extract just
- // the attributes that overlap the selection
- checkRefactoringByOffset("extractstyle1.xml", "newstyles6.xml", "newstyle",
- true /* removeExtracted */, true /* applyStyle */, null, 2,
- "android:^textSize=\"20pt",
- "android:id=\"@+id/button1\" android:layout_a^lignParentBottom");
- }
-
- public void testExtract6() throws Exception {
- // Test extracting on a single caret position which is not over any attributes:
- checkRefactoringByOffset("extractstyle1.xml", "newstyles7.xml", "newstyle",
- true /* removeExtracted */, true /* applyStyle */, null, 0,
- "<Bu^tton", "<Bu^tton");
- }
-
- public void testExtract7() throws Exception {
- // Verify that even with a different namespace prefix we end up with android:
- // in the extracted style
- checkRefactoring("extractstyle2.xml", "newstyles8.xml", "newstyle",
- true /* removeExtracted */, true /* applyStyle */, null, 2,
- "@+id/button1", "@+id/button2");
- }
-
- public void testExtract8() throws Exception {
- // Test setting parent style
- checkRefactoring("extractstyle1.xml", "newstyles3.xml", "newstyle",
- true /* removeExtracted */, false /* applyStyle */, "android:Widget.Button",
- 2, "@+id/button2");
- }
-
- // Check extract style on a selection of elements
- private void checkRefactoring(String basename, String styleFileName, String newStyleName,
- boolean removeExtracted, boolean applyStyle, String parentStyle,
- int expectedModifiedFileCount, String... ids) throws Exception {
- assertTrue(ids.length > 0);
-
- IFile file = getLayoutFile(getProject(), basename);
- TestContext info = setupTestContext(file, basename);
- TestLayoutEditorDelegate layoutEditor = info.mLayoutEditorDelegate;
- List<Element> selectedElements = getElements(info.mElement, ids);
-
- // Open the file such that ModelManager.getExistingModelForRead() in DomUtilities
- // will succeed
- IWorkbench workbench = PlatformUI.getWorkbench();
- IWorkbenchWindow activeWorkbenchWindow = workbench.getActiveWorkbenchWindow();
- IWorkbenchPage page = activeWorkbenchWindow.getActivePage();
- IDE.openEditor(page, file);
-
- ExtractStyleRefactoring refactoring = new ExtractStyleRefactoring(selectedElements,
- layoutEditor);
- checkRefactoring(basename, styleFileName, newStyleName, removeExtracted, applyStyle,
- parentStyle, expectedModifiedFileCount, file, refactoring);
- }
-
- // Check extract style against a set of editor text locations
- private void checkRefactoringByOffset(String basename, String styleFileName,
- String newStyleName, boolean removeExtracted, boolean applyStyle,
- String parentStyle,
- int expectedModifiedFileCount, String beginCaretLocation, String endCaretLocation)
- throws Exception {
- IFile file = getLayoutFile(getProject(), basename);
- int beginOffset = getCaretOffset(file, beginCaretLocation);
- int endOffset = getCaretOffset(file, endCaretLocation);
-
- TestContext info = setupTestContext(file, basename);
- TestLayoutEditorDelegate layoutEditor = info.mLayoutEditorDelegate;
-
- // Open the file such that ModelManager.getExistingModelForRead() in DomUtilities
- // will succeed
- IWorkbench workbench = PlatformUI.getWorkbench();
- IWorkbenchWindow activeWorkbenchWindow = workbench.getActiveWorkbenchWindow();
- IWorkbenchPage page = activeWorkbenchWindow.getActivePage();
- IDE.openEditor(page, file);
-
- ITextSelection selection = new TextSelection(beginOffset, endOffset - beginOffset);
- ExtractStyleRefactoring refactoring = new ExtractStyleRefactoring(file,
- layoutEditor, selection, null);
- checkRefactoring(basename, styleFileName, newStyleName, removeExtracted, applyStyle,
- parentStyle, expectedModifiedFileCount, file, refactoring);
- }
-
- // Common test code used by the other two check methods
- private void checkRefactoring(String basename, String styleFileName, String newStyleName,
- boolean removeExtracted, boolean applyStyle, String parentStyle,
- int expectedModifiedFileCount, IFile file,
- ExtractStyleRefactoring refactoring) throws Exception {
- refactoring.setStyleName(newStyleName);
- refactoring.setApplyStyle(applyStyle);
- refactoring.setRemoveExtracted(removeExtracted);
- refactoring.setStyleFileName(styleFileName);
- refactoring.setParent(parentStyle);
-
- // Pick the attributes to extract -- for now everything (and where there are
- // conflicting values, pick the first one)
- Pair<Map<String, List<Attr>>, Set<Attr>> result = refactoring.getAvailableAttributes();
- Map<String, List<Attr>> availableAttributes = result.getFirst();
- Set<Attr> selected = result.getSecond();
- List<Attr> chosenAttributes = new ArrayList<Attr>();
- for (List<Attr> list : availableAttributes.values()) {
- Collections.sort(list, new Comparator<Attr>() {
- @Override
- public int compare(Attr a1, Attr a2) {
- return a1.getValue().compareTo(a2.getValue());
- }
- });
- Attr attr = list.get(0);
- if (selected.contains(attr)) {
- chosenAttributes.add(attr);
- }
- }
- refactoring.setChosenAttributes(chosenAttributes);
-
- List<Change> changes = refactoring.computeChanges(new NullProgressMonitor());
- assertEquals(expectedModifiedFileCount, changes.size());
-
- Map<IPath,String> fileToGolden = new HashMap<IPath,String>();
- IPath sourcePath = file.getProjectRelativePath();
- fileToGolden.put(sourcePath, basename);
- IPath newPath = refactoring.getStyleFile(getProject()).getProjectRelativePath();
- fileToGolden.put(newPath, styleFileName);
-
- checkEdits(changes, fileToGolden, true);
-
- int modifiedFileCount = 0;
- for (Change change : changes) {
- if (change instanceof TextFileChange) {
- modifiedFileCount++;
- }
- }
- assertEquals(expectedModifiedFileCount, modifiedFileCount);
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/RefactoringAssistantTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/RefactoringAssistantTest.java
deleted file mode 100644
index b22717991..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/RefactoringAssistantTest.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import static com.android.SdkConstants.FD_RES;
-import static com.android.SdkConstants.FD_RES_LAYOUT;
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.AndroidXmlEditor;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jface.text.contentassist.ICompletionProposal;
-import org.eclipse.jface.text.quickassist.IQuickAssistInvocationContext;
-import org.eclipse.jface.text.source.ISourceViewer;
-import org.eclipse.ui.IEditorPart;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.ide.IDE;
-
-public class RefactoringAssistantTest extends AdtProjectTest {
- public void testAssistant1() throws Exception {
- // "Extract String"
- checkFixes("sample1a.xml", "<Button android:text=\"Fir^stButton\"");
- }
-
- public void testAssistant2() throws Exception {
- // Visual refactoring operations
- checkFixes("sample1a.xml", "<Bu^tton android:text");
- }
-
- public void testAssistant3() throws Exception {
- checkFixes("sample1a.xml", "<Button andr^oid:text=\"FirstButton\"");
- }
-
- public void testAssistant4() throws Exception {
- // Check for resource rename refactoring (and don't offer extract string)
- checkFixes("sample1a.xml", "android:id=\"@+id/Linea^rLayout2\"");
- }
-
- private void checkFixes(String name, String caretLocation)
- throws Exception {
- IProject project = getProject();
- IFile file = getTestDataFile(project, name, FD_RES + "/" + FD_RES_LAYOUT + "/" + name);
-
- // Determine the offset
- String fileContent = AdtPlugin.readFile(file);
- int caretDelta = caretLocation.indexOf("^");
- assertTrue(caretLocation, caretDelta != -1);
- String caretContext = caretLocation.substring(0, caretDelta)
- + caretLocation.substring(caretDelta + "^".length());
- int caretContextIndex = fileContent.indexOf(caretContext);
- assertTrue("Caret content " + caretContext + " not found in file",
- caretContextIndex != -1);
- final int offset = caretContextIndex + caretDelta;
-
-
- RefactoringAssistant refactoringAssistant = new RefactoringAssistant();
-
- // Open file
- IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
- assertNotNull(page);
- IEditorPart editor = IDE.openEditor(page, file);
- assertTrue(editor instanceof AndroidXmlEditor);
- AndroidXmlEditor layoutEditor = (AndroidXmlEditor) editor;
- final ISourceViewer viewer = layoutEditor.getStructuredSourceViewer();
-
- IQuickAssistInvocationContext invocationContext = new IQuickAssistInvocationContext() {
- @Override
- public int getLength() {
- return 0;
- }
-
- @Override
- public int getOffset() {
- return offset;
- }
-
- @Override
- public ISourceViewer getSourceViewer() {
- return viewer;
- }
- };
- ICompletionProposal[] proposals = refactoringAssistant
- .computeQuickAssistProposals(invocationContext);
-
- if (proposals != null) {
- for (ICompletionProposal proposal : proposals) {
- assertNotNull(proposal.getAdditionalProposalInfo());
- assertNotNull(proposal.getImage());
- }
- }
-
- StringBuilder sb = new StringBuilder(1000);
- sb.append("Quick assistant in " + name + " for " + caretLocation + ":\n");
- if (proposals != null) {
- for (ICompletionProposal proposal : proposals) {
- sb.append(proposal.getDisplayString());
- String help = proposal.getAdditionalProposalInfo();
- if (help != null && help.trim().length() > 0) {
- sb.append(" : ");
- sb.append(help.replace('\n', ' '));
- }
- sb.append('\n');
- }
- } else {
- sb.append("None found.\n");
- }
- assertEqualsGolden(name, sb.toString(), "txt");
-
- // No "apply" test on these assists since they are interactive. Refactoring
- // is tested elsewhere.
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/RefactoringTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/RefactoringTest.java
deleted file mode 100644
index 9565183bc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/RefactoringTest.java
+++ /dev/null
@@ -1,334 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import static com.android.SdkConstants.ANDROID_WIDGET_PREFIX;
-import static com.android.SdkConstants.DOT_XML;
-
-import com.android.ide.common.rendering.api.ViewInfo;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.CanvasViewInfo;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.jface.preference.IPreferenceStore;
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.text.edits.MultiTextEdit;
-import org.eclipse.text.edits.TextEdit;
-import org.eclipse.wst.sse.core.StructuredModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IModelManager;
-import org.eclipse.wst.sse.core.internal.provisional.IStructuredModel;
-import org.eclipse.wst.sse.core.internal.provisional.IndexedRegion;
-import org.eclipse.wst.sse.core.internal.provisional.text.IStructuredDocument;
-import org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel;
-import org.w3c.dom.Element;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-@SuppressWarnings("restriction")
-public class RefactoringTest extends AdtProjectTest {
-
- protected boolean autoFormat() {
- return true;
- }
-
- @Override
- protected void setUp() throws Exception {
-
- // Ensure that the defaults are initialized so for example formatting options are
- // initialized properly
- IPreferenceStore store = AdtPlugin.getDefault().getPreferenceStore();
- AdtPrefs.init(store);
- AdtPrefs prefs = AdtPrefs.getPrefs();
- prefs.initializeStoreWithDefaults(store);
-
- store.setValue(AdtPrefs.PREFS_FORMAT_GUI_XML, autoFormat());
-
- prefs.loadValues(null);
-
- super.setUp();
- }
-
- protected static Element findElementById(Element root, String id) {
- if (id.equals(VisualRefactoring.getId(root))) {
- return root;
- }
-
- for (Element child : DomUtilities.getChildren(root)) {
- Element result = findElementById(child, id);
- if (result != null) {
- return result;
- }
- }
-
- return null;
- }
-
- protected static List<Element> getElements(Element root, String... ids) {
- List<Element> selectedElements = new ArrayList<Element>();
- for (String id : ids) {
- Element element = findElementById(root, id);
- assertNotNull(element);
- selectedElements.add(element);
- }
- return selectedElements;
- }
-
- protected void checkEdits(String basename, List<Change> changes) throws BadLocationException,
- IOException {
- IDocument document = new Document();
-
- String xml = readTestFile(basename, false);
- if (xml == null) { // New file
- xml = ""; //$NON-NLS-1$
- }
- document.set(xml);
-
- for (Change change : changes) {
- if (change instanceof TextFileChange) {
- TextFileChange tf = (TextFileChange) change;
- TextEdit edit = tf.getEdit();
- IFile file = tf.getFile();
- String contents = AdtPlugin.readFile(file);
- assertEquals(contents, xml);
- if (edit instanceof MultiTextEdit) {
- MultiTextEdit edits = (MultiTextEdit) edit;
- edits.apply(document);
- } else {
- edit.apply(document);
- }
- } else {
- System.out.println("Ignoring non-textfilechange in refactoring result");
- }
- }
-
- String actual = document.get();
-
- // Ensure that the document is still valid to make sure the edits don't
- // mangle it:
- org.w3c.dom.Document doc = DomUtilities.parseDocument(actual, true);
- assertNotNull(actual, doc);
-
- assertEqualsGolden(basename, actual);
- }
-
- protected void checkEdits(List<Change> changes,
- Map<IPath, String> fileToGoldenName) throws BadLocationException, IOException {
- checkEdits(changes, fileToGoldenName, false);
- }
-
- protected void checkEdits(List<Change> changes,
- Map<IPath, String> fileToGoldenName, boolean createDiffs)
- throws BadLocationException, IOException {
- for (Change change : changes) {
- if (change instanceof TextFileChange) {
- TextFileChange tf = (TextFileChange) change;
- IFile file = tf.getFile();
- assertNotNull(file);
- IPath path = file.getProjectRelativePath();
- String goldenName = fileToGoldenName.get(path);
- assertNotNull("Not found: " + path.toString(), goldenName);
-
- String xml = readTestFile(goldenName, false);
- if (xml == null) { // New file
- xml = ""; //$NON-NLS-1$
- }
- IDocument document = new Document();
- document.set(xml);
-
- String before = document.get();
-
- TextEdit edit = tf.getEdit();
- if (edit instanceof MultiTextEdit) {
- MultiTextEdit edits = (MultiTextEdit) edit;
- edits.apply(document);
- } else {
- edit.apply(document);
- }
-
- String actual = document.get();
-
- if (createDiffs) {
- // Use a diff as the golden file instead of the after
- actual = getDiff(before, actual);
- if (goldenName.endsWith(DOT_XML)) {
- goldenName = goldenName.substring(0,
- goldenName.length() - DOT_XML.length())
- + ".diff";
- }
- }
-
- assertEqualsGolden(goldenName, actual);
- } else {
- System.out.println("Ignoring non-textfilechange in refactoring result");
- assertNull(change.getAffectedObjects());
- }
- }
- }
-
- protected UiViewElementNode createModel(UiViewElementNode parent, Element element) {
- List<Element> children = DomUtilities.getChildren(element);
- String fqcn = ANDROID_WIDGET_PREFIX + element.getTagName();
- boolean hasChildren = children.size() > 0;
- UiViewElementNode node = createNode(parent, fqcn, hasChildren);
- node.setXmlNode(element);
- for (Element child : children) {
- createModel(node, child);
- }
-
- return node;
- }
-
- /**
- * Builds up a ViewInfo hierarchy for the given model. This is done by
- * reading .info dump files which record the exact pixel sizes of each
- * ViewInfo object. These files are assumed to match up exactly with the
- * model objects. This is done rather than rendering an actual layout
- * hierarchy to insulate the test from pixel difference (in say font size)
- * among platforms, as well as tying the test to particulars about relative
- * sizes of things which may change with theme adjustments etc.
- * <p>
- * Each file can be generated by the dump method in the ViewHierarchy.
- */
- protected ViewInfo createInfos(UiElementNode model, String relativePath) throws IOException {
- String basename = relativePath.substring(0, relativePath.lastIndexOf('.') + 1);
- String relative = basename + "info"; //$NON-NLS-1$
- String info = readTestFile(relative, true);
- // Parse the info file and build up a model from it
- // Each line contains a new info.
- // If indented it is a child of the parent.
- String[] lines = info.split("\n"); //$NON-NLS-1$
-
- // Iteration order for the info file should match exactly the UI model so
- // we can just advance the line index sequentially as we traverse
-
- return create(model, Arrays.asList(lines).iterator());
- }
-
- protected ViewInfo create(UiElementNode node, Iterator<String> lineIterator) {
- // android.widget.LinearLayout [0,36,240,320]
- Pattern pattern = Pattern.compile("(\\s*)(\\S+) \\[(\\d+),(\\d+),(\\d+),(\\d+)\\].*");
- assertTrue(lineIterator.hasNext());
- String description = lineIterator.next();
- Matcher matcher = pattern.matcher(description);
- assertTrue(matcher.matches());
- //String indent = matcher.group(1);
- //String fqcn = matcher.group(2);
- String left = matcher.group(3);
- String top = matcher.group(4);
- String right = matcher.group(5);
- String bottom = matcher.group(6);
-
- ViewInfo view = new ViewInfo(node.getXmlNode().getLocalName(), node,
- Integer.parseInt(left), Integer.parseInt(top),
- Integer.parseInt(right), Integer.parseInt(bottom));
-
- List<UiElementNode> childNodes = node.getUiChildren();
- if (childNodes.size() > 0) {
- List<ViewInfo> children = new ArrayList<ViewInfo>();
- for (UiElementNode child : childNodes) {
- children.add(create(child, lineIterator));
- }
- view.setChildren(children);
- }
-
- return view;
- }
-
- protected TestContext setupTestContext(IFile file, String relativePath) throws Exception {
- IStructuredModel structuredModel = null;
- org.w3c.dom.Document domDocument = null;
- IStructuredDocument structuredDocument = null;
- Element element = null;
-
- try {
- IModelManager modelManager = StructuredModelManager.getModelManager();
- structuredModel = modelManager.getModelForRead(file);
- if (structuredModel instanceof IDOMModel) {
- IDOMModel domModel = (IDOMModel) structuredModel;
- domDocument = domModel.getDocument();
- element = domDocument.getDocumentElement();
- structuredDocument = structuredModel.getStructuredDocument();
- }
- } finally {
- if (structuredModel != null) {
- structuredModel.releaseFromRead();
- }
- }
-
- assertNotNull(structuredModel);
- assertNotNull(domDocument);
- assertNotNull(element);
- assertNotNull(structuredDocument);
- assertTrue(element instanceof IndexedRegion);
-
- UiViewElementNode model = createModel(null, element);
- ViewInfo info = createInfos(model, relativePath);
- CanvasViewInfo rootView = CanvasViewInfo.create(info, true /* layoutlib5 */).getFirst();
- TestLayoutEditorDelegate layoutEditor =
- new TestLayoutEditorDelegate(file, structuredDocument, null);
-
- TestContext testInfo = createTestContext();
- testInfo.mFile = file;
- testInfo.mStructuredModel = structuredModel;
- testInfo.mStructuredDocument = structuredDocument;
- testInfo.mElement = element;
- testInfo.mDomDocument = domDocument;
- testInfo.mUiModel = model;
- testInfo.mViewInfo = info;
- testInfo.mRootView = rootView;
- testInfo.mLayoutEditorDelegate = layoutEditor;
-
- return testInfo;
- }
-
- protected TestContext createTestContext() {
- return new TestContext();
- }
-
- protected static class TestContext {
- protected IFile mFile;
- protected IStructuredModel mStructuredModel;
- protected IStructuredDocument mStructuredDocument;
- protected org.w3c.dom.Document mDomDocument;
- protected Element mElement;
- protected UiViewElementNode mUiModel;
- protected ViewInfo mViewInfo;
- protected CanvasViewInfo mRootView;
- protected TestLayoutEditorDelegate mLayoutEditorDelegate;
- }
-
- @Override
- public void testDummy() {
- // To avoid JUnit warning that this class contains no tests, even though
- // this is an abstract class and JUnit shouldn't try
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UnwrapRefactoringTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UnwrapRefactoringTest.java
deleted file mode 100644
index e03ea9e06..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UnwrapRefactoringTest.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.w3c.dom.Element;
-
-import java.util.List;
-
-public class UnwrapRefactoringTest extends RefactoringTest {
-
- public void testUnwrap1() throws Exception {
- // Unwrap view with parent, no children - this will unwrap the parent (frame layout)
- checkRefactoring("unwrap.xml", "@+id/button");
- }
-
- public void testUnwrap2() throws Exception {
- // Unwrap view with parent and children; this should unwrap the element itself
- checkRefactoring("unwrap.xml", "@+id/frame");
- }
-
- public void testUnwrap3() throws Exception {
- // Unwrap root: should transfer namespace
- checkRefactoring("unwrap.xml", "@+id/linear");
- }
-
- private void checkRefactoring(String basename, String id) throws Exception {
- IFile file = getLayoutFile(getProject(), basename);
- TestContext info = setupTestContext(file, basename);
- TestLayoutEditorDelegate layoutEditor = info.mLayoutEditorDelegate;
- List<Element> selectedElements = getElements(info.mElement, id);
- assertEquals(1, selectedElements.size());
-
- UnwrapRefactoring refactoring = new UnwrapRefactoring(selectedElements,
- layoutEditor);
-
- RefactoringStatus status = refactoring.checkInitialConditions(new NullProgressMonitor());
- assertFalse(status.hasError());
- List<Change> changes = refactoring.computeChanges(new NullProgressMonitor());
- checkEdits(basename, changes);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UseCompoundDrawableRefactoringTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UseCompoundDrawableRefactoringTest.java
deleted file mode 100644
index 01a0e1e7d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/UseCompoundDrawableRefactoringTest.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import static com.android.ide.eclipse.adt.internal.editors.layout.refactoring.UseCompoundDrawableRefactoring.combine;
-
-import com.android.ide.eclipse.adt.AdtUtils;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.w3c.dom.Element;
-
-import java.util.List;
-
-@SuppressWarnings("javadoc")
-public class UseCompoundDrawableRefactoringTest extends RefactoringTest {
- public void testCombine() throws Exception {
- assertNull(combine(null, null));
- assertNull(combine("@dimen/foo", "@dimen/bar"));
- assertNull(combine("@dimen/foo", "@dimen/bar"));
- assertNull(combine("1sp", "@dimen/bar"));
- assertNull(combine("1sp", "2dp"));
- assertNull(combine(null, ""));
- assertNull(combine("", null));
-
- assertEquals("@dimen/foo", combine(null, "@dimen/foo"));
- assertEquals("@dimen/foo", combine("@dimen/foo", null));
- assertEquals("5sp", combine("5sp", null));
-
- assertEquals("10sp", combine("8sp", "2sp"));
- assertEquals("50dp", combine("30dp", "20dp"));
- }
-
- public void test1() throws Exception {
- // Test converting an image above a text view
- checkRefactoring("refactoring/usecompound/compound1.xml", "@+id/layout1");
- }
-
- public void test2() throws Exception {
- // Test converting an image below a text view
- checkRefactoring("refactoring/usecompound/compound2.xml", "@+id/layout2");
- }
-
- public void test3() throws Exception {
- // Test converting an image to the left of a text view
- checkRefactoring("refactoring/usecompound/compound3.xml", "@+id/layout3");
- }
-
- public void test4() throws Exception {
- // Test converting an image to the right of a text view
- checkRefactoring("refactoring/usecompound/compound4.xml", "@+id/layout4");
- }
-
- public void test5() throws Exception {
- // Test converting an image where the LinearLayout is referenced (in a relative layout)
- // and the text view has an id
- checkRefactoring("refactoring/usecompound/compound_all.xml", "@+id/layout2");
- }
-
- public void test6() throws Exception {
- // Test converting an image where the LinearLayout is referenced (in a relative layout)
- // and the text view does not have an id
- checkRefactoring("refactoring/usecompound/compound_all.xml", "@+id/layout3");
- }
-
- public void test7() throws Exception {
- // Test converting where a namespace needs to be migrated
- checkRefactoring("refactoring/usecompound/compound5.xml", "@+id/layout");
- }
-
- public void test8() throws Exception {
- // Test padding handling
- checkRefactoring("refactoring/usecompound/compound6.xml", "@+id/layout1");
- }
-
- public void test9() throws Exception {
- // Test margin combination
- checkRefactoring("refactoring/usecompound/compound7.xml", "@+id/layout1");
- }
-
- private void checkRefactoring(String basename, String id)
- throws Exception {
- IFile file = getLayoutFile(getProject(), basename);
- TestContext info = setupTestContext(file, basename);
- TestLayoutEditorDelegate layoutEditor = info.mLayoutEditorDelegate;
- List<Element> selectedElements = getElements(info.mElement, new String[] { id });
-
- UseCompoundDrawableRefactoring refactoring = new UseCompoundDrawableRefactoring(
- selectedElements, layoutEditor);
- List<Change> changes = refactoring.computeChanges(new NullProgressMonitor());
-
- CompositeChange cc = new CompositeChange("Combined from unit test",
- changes.toArray(new Change[changes.size()]));
- cc.markAsSynthetic();
- addCleanupDir(AdtUtils.getAbsolutePath(getProject()).toFile());
-
- checkEdits(basename, changes);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/WrapInRefactoringTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/WrapInRefactoringTest.java
deleted file mode 100644
index 2dc6744e6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/WrapInRefactoringTest.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.refactoring;
-
-import static com.android.SdkConstants.FQCN_GESTURE_OVERLAY_VIEW;
-import static com.android.SdkConstants.FQCN_LINEAR_LAYOUT;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.w3c.dom.Element;
-
-import java.util.List;
-
-public class WrapInRefactoringTest extends RefactoringTest {
-
- public void testWrapIn1() throws Exception {
- // Test wrapping view: should indent view
- checkRefactoring("sample3.xml", FQCN_LINEAR_LAYOUT, "@+id/button2");
- }
-
- public void testWrapIn2() throws Exception {
- // Test wrapping the root: should move namespace
- checkRefactoring("sample3.xml", FQCN_GESTURE_OVERLAY_VIEW, "@+id/newlinear");
- }
-
- public void testWrapIn3() throws Exception {
- // Test wrap multiple adjacent elements - should wrap all as a unit
- checkRefactoring("sample3.xml", FQCN_LINEAR_LAYOUT, "@+id/button2", "@+id/android_logo");
- }
-
- private void checkRefactoring(String basename, String fqcn, String... ids) throws Exception {
- assertTrue(ids.length > 0);
-
- IFile file = getLayoutFile(getProject(), basename);
- TestContext info = setupTestContext(file, basename);
- TestLayoutEditorDelegate layoutEditor = info.mLayoutEditorDelegate;
- List<Element> selectedElements = getElements(info.mElement, ids);
-
- WrapInRefactoring refactoring = new WrapInRefactoring(selectedElements,
- layoutEditor);
- refactoring.setType(fqcn);
- List<Change> changes = refactoring.computeChanges(new NullProgressMonitor());
- checkEdits(basename, changes);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/TestFragment.java.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/TestFragment.java.txt
deleted file mode 100644
index 0942a19fe..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/TestFragment.java.txt
+++ /dev/null
@@ -1,15 +0,0 @@
-package com.android.eclipse.tests;
-
-import android.app.Fragment;
-import android.os.Bundle;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-
-public class TestFragment extends Fragment {
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- return null;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror1.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror1.xml
deleted file mode 100644
index d72f4ba4c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror1.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<FrameLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content"
- android:layout_height="match_parent">
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_marginTop="50pt"
- android:layout_marginLeft="50dp"
- android:layout_marginBottom="50"
- />
-</FrameLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror2.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror2.xml
deleted file mode 100644
index b720daac8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror2.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources xmlns:android="http://schemas.android.com/apk/res/android">
- <style name="repeatedStyle1">
- <item name="android:gravity">left</item>
- </style>
- <style name="repeatedStyle1">
- <item name="android:gravity">bottom</item>
- </style>
-</resources>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror3.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror3.xml
deleted file mode 100644
index bc9c134c7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror3.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources xmlns:android="http://schemas.android.com/apk/res/android">
- <style name="wrongAttribute">
- <item name="nonexistent">5</item>
- </style>
-</resources>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror4.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror4.xml
deleted file mode 100644
index 28dd46786..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror4.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
- <style>
- <item />
- </style>
- <item></item>
-</resources>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror5.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror5.xml
deleted file mode 100644
index ee89ac4be..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror5.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
- <style name="test">
- <item name="android:layout_width"></item>
- </style>
-</resources>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror6.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror6.xml
deleted file mode 100644
index e552ff797..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror6.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<FrameLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content"
- android:layout_height="match_parent">
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_marginTop=""
- android:layout_marginLeft=''
- />
-</FrameLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror7.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror7.xml
deleted file mode 100644
index d47f4ae83..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/aapterror7.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-<FrameLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content"
- android:layout_height="match_parent">
- <TextView
- android:id=""
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- />
-</FrameLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/anim1-expected-completion53.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/anim1-expected-completion53.txt
deleted file mode 100644
index 3e44918d9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/anim1-expected-completion53.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-Code completion in anim1.xml for ^<set xmlns:
-<alpha />
-<rotate />
-<scale />
-<set ></set>
-<translate />
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/anim1-expected-completion54.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/anim1-expected-completion54.txt
deleted file mode 100644
index f5e5cba69..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/anim1-expected-completion54.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-Code completion in anim1.xml for ^<translate android:id=:
-<alpha />
-<rotate />
-<scale />
-<set ></set>
-<translate />
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/anim1-expected-completion55.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/anim1-expected-completion55.txt
deleted file mode 100644
index 385f4761b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/anim1-expected-completion55.txt
+++ /dev/null
@@ -1,16 +0,0 @@
-Code completion in anim1.xml for android:^fromXDelta=:
-android:fromXDelta : [float, fraction]
-android:toXDelta : [float, fraction]
-android:fromYDelta : [float, fraction]
-android:toYDelta : [float, fraction]
-android:interpolator : Defines the interpolator used to smooth the animation movement in time. [reference]
-android:fillEnabled : When set to true, the value of fillBefore is taken into account. [boolean]
-android:fillBefore : When set to true or when fillEnabled is not set to true, the animation transformation is applied before the animation has started. [boolean]
-android:fillAfter : When set to true, the animation transformation is applied after the animation is over. [boolean]
-android:duration : Amount of time (in milliseconds) for the animation to run. [integer]
-android:startOffset : Delay in milliseconds before the animation runs, once start time is reached. [integer]
-android:repeatCount : Defines how many times the animation should repeat. [integer, enum]
-android:repeatMode : Defines the animation behavior when it reaches the end and the repeat count is greater than 0 or infinite. [enum]
-android:zAdjustment : Allows for an adjustment of the Z ordering of the content being animated for the duration of the animation. [enum]
-android:background : Special background behind animation. [color, reference]
-android:detachWallpaper : Special option for window animations: if this window is on top of a wallpaper, don't animate the wallpaper with it. [boolean]
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/anim1-expected-completion56.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/anim1-expected-completion56.txt
deleted file mode 100644
index e12a66fa5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/anim1-expected-completion56.txt
+++ /dev/null
@@ -1,14 +0,0 @@
-Code completion in anim1.xml for android:^fromAlpha=:
-android:fromAlpha : [float]
-android:toAlpha : [float]
-android:interpolator : Defines the interpolator used to smooth the animation movement in time. [reference]
-android:fillEnabled : When set to true, the value of fillBefore is taken into account. [boolean]
-android:fillBefore : When set to true or when fillEnabled is not set to true, the animation transformation is applied before the animation has started. [boolean]
-android:fillAfter : When set to true, the animation transformation is applied after the animation is over. [boolean]
-android:duration : Amount of time (in milliseconds) for the animation to run. [integer]
-android:startOffset : Delay in milliseconds before the animation runs, once start time is reached. [integer]
-android:repeatCount : Defines how many times the animation should repeat. [integer, enum]
-android:repeatMode : Defines the animation behavior when it reaches the end and the repeat count is greater than 0 or infinite. [enum]
-android:zAdjustment : Allows for an adjustment of the Z ordering of the content being animated for the duration of the animation. [enum]
-android:background : Special background behind animation. [color, reference]
-android:detachWallpaper : Special option for window animations: if this window is on top of a wallpaper, don't animate the wallpaper with it. [boolean]
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/anim1-expected-completion57.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/anim1-expected-completion57.txt
deleted file mode 100644
index 9225dac46..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/anim1-expected-completion57.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Code completion in anim1.xml for android:fromXDelta="100^%p":
-100% : <b>Fraction</b> - a percentage of the base size
-100%p : <b>Fraction</b> - a percentage relative to parent container
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/anim1.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/anim1.xml
deleted file mode 100644
index 48fefc2ba..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/anim1.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<set xmlns:android="http://schemas.android.com/apk/res/android">
- <translate android:id="@+id/test1"
- android:fromXDelta="100%p"
- android:pivotY="60%p"
- android:toXDelta="40%p"
- android:toYDelta="33%p"
- android:fillBefore="true"
- android:fillAfter="true"
- android:startOffset="1000"
- android:duration="1000" />
- <alpha
- android:id="@+id/test2"
- android:fromAlpha="1.0"
- android:toAlpha="0.0"
- android:startOffset="3000"
- android:duration="250"
- android:fillBefore="true"
- android:fillAfter="false"
- />
-</set>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/animator1-expected-completion58.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/animator1-expected-completion58.txt
deleted file mode 100644
index 075941502..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/animator1-expected-completion58.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in animator1.xml for ^<set xmlns:
-<animator ></animator>
-<objectAnimator ></objectAnimator>
-<set ></set>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/animator1-expected-completion59.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/animator1-expected-completion59.txt
deleted file mode 100644
index 474fe7761..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/animator1-expected-completion59.txt
+++ /dev/null
@@ -1,10 +0,0 @@
-Code completion in animator1.xml for android:^duration="2000":
-android:propertyName : Name of the property being animated. [string]
-android:interpolator : Defines the interpolator used to smooth the animation movement in time. [reference]
-android:duration : Amount of time (in milliseconds) for the animation to run. [integer]
-android:startOffset : Delay in milliseconds before the animation runs, once start time is reached. [integer]
-android:repeatCount : Defines how many times the animation should repeat. [integer, enum]
-android:repeatMode : Defines the animation behavior when it reaches the end and the repeat count is greater than 0 or infinite. [enum]
-android:valueFrom : Value the animation starts from. [integer, float, color, dimension]
-android:valueTo : Value the animation animates to. [integer, float, color, dimension]
-android:valueType : The type of valueFrom and valueTo. [enum]
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/animator1-expected-completion60.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/animator1-expected-completion60.txt
deleted file mode 100644
index 3e5e6b127..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/animator1-expected-completion60.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Code completion in animator1.xml for android:propertyName="scal^eX"/>:
-scaleX : scale of the view in the x direction.
-scaleY : scale of the view in the y direction.
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/animator1-expected-completion61.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/animator1-expected-completion61.txt
deleted file mode 100644
index b298ac0b4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/animator1-expected-completion61.txt
+++ /dev/null
@@ -1,19 +0,0 @@
-Code completion in animator1.xml for android:interpolator="^@android:anim/bounce_interpolator":
-@android:anim/accelerate_decelerate_interpolator
-@android:anim/accelerate_interpolator
-@android:anim/decelerate_interpolator
-@android:anim/anticipate_interpolator
-@android:anim/overshoot_interpolator
-@android:anim/anticipate_overshoot_interpolator
-@android:anim/bounce_interpolator
-@android:anim/linear_interpolator
-@android:anim/cycle_interpolator
-@android:
-@+id/
-@anim/
-@color/
-@drawable/
-@id/
-@layout/
-@string/
-@style/
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/animator1.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/animator1.xml
deleted file mode 100644
index bdf10dced..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/animator1.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<!-- Simple bounce animation -->
-<set xmlns:android="http://schemas.android.com/apk/res/android"
- android:ordering="sequentially">
- <set>
- <objectAnimator
- android:duration="2000"
- android:valueTo="310"
- android:propertyName="x"/>
- <objectAnimator
- android:duration="2000"
- android:valueTo="130"
- android:propertyName="y"
- android:interpolator="@android:anim/bounce_interpolator"/>
- <objectAnimator
- android:duration="2000"
- android:valueTo=".4"
- android:propertyName="scaleX"/>
- <objectAnimator
- android:duration="2000"
- android:valueTo=".4"
- android:propertyName="scaleY"/>
- </set>
- <objectAnimator
- android:duration="500"
- android:valueTo="0"
- android:propertyName="alpha"/>
-</set>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken1-expected-applyCompletion15.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken1-expected-applyCompletion15.diff
deleted file mode 100644
index 4ce3540da..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken1-expected-applyCompletion15.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in broken1.xml for android:textColorHigh^ selecting android:textColorHighlight:
-@@ -8 +8
-- android:textColorHigh^
-+ android:textColorHighlight="^"
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken1-expected-completion20.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken1-expected-completion20.txt
deleted file mode 100644
index 063dc8c4b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken1-expected-completion20.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-Code completion in broken1.xml for android:textColorHigh^:
-android:textColorHighlight : Color of the text selection highlight. [color, reference]
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken1.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken1.xml
deleted file mode 100644
index 161b9818c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken1.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <Button
- android:text="@string/app_name"
- android:textColorHigh
- android:layout_marginLeft="@android:dimen/app_icon_size"
- android:id="@+id/button1"
- ></Button>
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken2-expected-applyCompletion16.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken2-expected-applyCompletion16.diff
deleted file mode 100644
index 3337ad265..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken2-expected-applyCompletion16.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in broken2.xml for style=^ selecting "@android:":
-@@ -9 +9
-- style=^
-+ style="@android:^"
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken2-expected-completion21.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken2-expected-completion21.txt
deleted file mode 100644
index 1ee2585cd..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken2-expected-completion21.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-Code completion in broken2.xml for style=^:
-"@android:"
-"@+id/"
-"@drawable/"
-"@id/"
-"@layout/"
-"@string/"
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken2.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken2.xml
deleted file mode 100644
index 60644b90c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken2.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <Button
- android:text="@string/app_name"
- android:layout_marginLeft="@android:dimen/app_icon_size"
- style=
- android:id="@+id/button1"
- ></Button>
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken3-expected-applyCompletion14.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken3-expected-applyCompletion14.diff
deleted file mode 100644
index 2787380ee..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken3-expected-applyCompletion14.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in broken3.xml for <EditT^ selecting EditText />:
-@@ -6 +6
-- <EditT^
-+ <EditText ^/>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken3-expected-completion19.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken3-expected-completion19.txt
deleted file mode 100644
index ccc6a4c66..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken3-expected-completion19.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-Code completion in broken3.xml for <EditT^:
-EditText />
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken3.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken3.xml
deleted file mode 100644
index b8b168586..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/broken3.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <EditT
- <Button
- android:text="@string/app_name"
- android:layout_marginLeft="@android:dimen/app_icon_size"
- android:id="@+id/button1"
- ></Button>
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/color1-expected-completion45.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/color1-expected-completion45.txt
deleted file mode 100644
index c799b8094..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/color1-expected-completion45.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-Code completion in color1.xml for ^<selector:
-<selector ></selector> : Required. This must be the root element. Contains one or more <item> elements.
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/color1-expected-completion46a.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/color1-expected-completion46a.txt
deleted file mode 100644
index 32f0066b6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/color1-expected-completion46a.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-Code completion in color1.xml for ^<item android:
-<item /> : Drawable states.
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/color1-expected-completion46b.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/color1-expected-completion46b.txt
deleted file mode 100644
index def6d13b1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/color1-expected-completion46b.txt
+++ /dev/null
@@ -1,20 +0,0 @@
-Code completion in color1.xml for <item ^android:state_focused="true"/>:
-android:state_focused : State value for StateListDrawable, set when a view has input focus. [boolean]
-android:state_window_focused : State value for StateListDrawable, set when a view's window has input focus. [boolean]
-android:state_enabled : State value for StateListDrawable, set when a view is enabled. [boolean]
-android:state_checkable : State identifier indicating that the object <var>may</var> display a check mark. [boolean]
-android:state_checked : State identifier indicating that the object is currently checked. [boolean]
-android:state_selected : State value for StateListDrawable, set when a view (or one of its parents) is currently selected. [boolean]
-android:state_pressed : State value for StateListDrawable, set when the user is pressing down in a view. [boolean]
-android:state_activated : State value for StateListDrawable, set when a view or its parent has been "activated" meaning the user has currently marked it as being of interest. [boolean]
-android:state_active : State value for StateListDrawable. [boolean]
-android:state_single : State value for StateListDrawable. [boolean]
-android:state_first : State value for StateListDrawable. [boolean]
-android:state_middle : State value for StateListDrawable. [boolean]
-android:state_last : State value for StateListDrawable. [boolean]
-android:state_accelerated : State value for StateListDrawable, indicating that the Drawable is in a view that is hardware accelerated. [boolean]
-android:state_hovered : State value for StateListDrawable, set when a pointer is hovering over the view. [boolean]
-android:state_drag_can_accept : State for StateListDrawable indicating that the Drawable is in a view that is capable of accepting a drop of the content currently being manipulated in a drag-and-drop operation. [boolean]
-android:state_drag_hovered : State for StateListDrawable indicating that a drag operation (for which the Drawable's view is a valid recipient) is currently positioned over the Drawable. [boolean]
-android:state_accessibility_focused : State for StateListDrawable indicating that a View has accessibility focus. [boolean]
-android:color : Hexadeximal color. Required. The color is specified with an RGB value and optional alpha channel. The value always begins with a pound (#) character and then followed by the Alpha-Red-Green-Blue information in one of the following formats: * RGB * ARGB * RRGGBB * AARRGGBB
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/color1.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/color1.xml
deleted file mode 100644
index a8482abac..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/color1.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<selector
- xmlns:android="http://schemas.android.com/apk/res/android">
- <item android:state_focused="true"/>
- <item />
-</selector>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-actual-applyCompletion1.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-actual-applyCompletion1.xml
deleted file mode 100644
index 2413658a7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-actual-applyCompletion1.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">
-<!--
- This file deliberately contains errors - it represents partial keyboard
- typing for interactive code completion
--->
- <TextView
- android:layout_weight^="fill_parent"
- android:layout_height="wrap_content"
- android:layout_marginTop="@android:dimen/app_icon_size"
- android:layout_marginLeft="50dp"
- android:layout_marginBottom="50"
- android:textColor="#000000"
- style="@android:style/Widget.Button"
- android:gravity="left|bottom"
- android:text="@string/hello"
- android:hint="hint" />
- <FrameLayout android:foreground="@android:drawable/btn_default"></FrameLayout>
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion1.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion1.diff
deleted file mode 100644
index 6b0556615..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion1.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion1.xml for layout_w^idth="fill_parent" selecting android:layout_weight:
-@@ -8 +8
-- android:layout_w^idth="fill_parent"
-+ android:layout_weight^="fill_parent"
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion10.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion10.diff
deleted file mode 100644
index 7b448c29f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion10.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion1.xml for <T^extView selecting TableLayout:
-@@ -7 +7
-- <T^extView
-+ <TableLayout^
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion11a.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion11a.diff
deleted file mode 100644
index 1a5f24d6c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion11a.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion1.xml for ^<TextView selecting <RadioGroup ></RadioGroup>:
-@@ -7 +7
-- ^<TextView
-+ <RadioGroup ^></RadioGroup><TextView
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion11b.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion11b.diff
deleted file mode 100644
index 9010bf60c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion11b.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion1.xml for ^<TextView selecting <CheckBox />:
-@@ -7 +7
-- ^<TextView
-+ <CheckBox ^/><TextView
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion12.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion12.diff
deleted file mode 100644
index a7a463877..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion12.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion1.xml for btn_default">^</FrameLayout> selecting <FrameLayout ></FrameLayout>:
-@@ -18 +18
-- <FrameLayout android:foreground="@android:drawable/btn_default">^</FrameLayout>
-+ <FrameLayout android:foreground="@android:drawable/btn_default"><FrameLayout ^></FrameLayout></FrameLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion2.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion2.diff
deleted file mode 100644
index 77761316d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion2.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion1.xml for layout_width="^fill_parent" selecting match_parent:
-@@ -8 +8
-- android:layout_width="^fill_parent"
-+ android:layout_width="match_parent"^
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion3.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion3.diff
deleted file mode 100644
index e67a3369d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion3.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion1.xml for layout_width="fi^ll_parent" selecting fill_parent:
-@@ -8 +8
-- android:layout_width="fi^ll_parent"
-+ android:layout_width="fill_parent"^
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion39.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion39.diff
deleted file mode 100644
index fe63acd22..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion39.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion1.xml for marginBottom="50"^ selecting android:maxEms:
-@@ -12 +12
-- android:layout_marginBottom="50"^
-+ android:layout_marginBottom="50" android:maxEms="^"
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion4.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion4.diff
deleted file mode 100644
index 2d229f3c4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion4.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion1.xml for marginBottom="50^" selecting 50mm:
-@@ -12 +12
-- android:layout_marginBottom="50^"
-+ android:layout_marginBottom="50mm"^
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion5.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion5.diff
deleted file mode 100644
index 5a2b413d1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion5.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion1.xml for layout_marginLeft="50d^p" selecting 50dp:
-@@ -11 +11
-- android:layout_marginLeft="50d^p"
-+ android:layout_marginLeft="50dp"^
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion6.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion6.diff
deleted file mode 100644
index d3a8c1120..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion6.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion1.xml for style="@android:^style/Widget.Button" selecting @android:drawable/:
-@@ -14 +14
-- style="@android:^style/Widget.Button"
-+ style="@android:drawable/^"
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion7a.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion7a.diff
deleted file mode 100644
index afd7e21e0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion7a.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion1.xml for android:gravity="l^eft|bottom" selecting left:
-@@ -15 +15
-- android:gravity="l^eft|bottom"
-+ android:gravity="left^"
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion7b.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion7b.diff
deleted file mode 100644
index 73f2bd48a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion7b.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion1.xml for android:gravity="left|b^ottom" selecting bottom:
-@@ -15 +15
-- android:gravity="left|b^ottom"
-+ android:gravity="left|bottom^"
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion8.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion8.diff
deleted file mode 100644
index 655afc529..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion8.diff
+++ /dev/null
@@ -1,2 +0,0 @@
-Code completion in completion1.xml for layout_width^="fill_parent" selecting android:layout_width:
-No changes \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion9.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion9.diff
deleted file mode 100644
index 1b4198e43..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-applyCompletion9.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion1.xml for layout_width=^"fill_parent" selecting "wrap_content":
-@@ -8 +8
-- android:layout_width=^"fill_parent"
-+ android:layout_width="wrap_content"^
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion1.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion1.txt
deleted file mode 100644
index c3e75ad54..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion1.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Code completion in completion1.xml for layout_w^idth="fill_parent":
-android:layout_width : Specifies the basic width of the view. [dimension, enum]
-android:layout_weight : [float]
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion10.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion10.txt
deleted file mode 100644
index 973d95eff..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion10.txt
+++ /dev/null
@@ -1,11 +0,0 @@
-Code completion in completion1.xml for <T^extView:
-TabHost
-TabWidget
-TableLayout
-TableRow
-TextSwitcher
-TextView
-TextureView
-TimePicker
-ToggleButton
-TwoLineListItem
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion11.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion11.txt
deleted file mode 100644
index 20dad3a53..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion11.txt
+++ /dev/null
@@ -1,67 +0,0 @@
-Code completion in completion1.xml for ^<TextView:
-<AbsoluteLayout ></AbsoluteLayout>
-<AdapterViewFlipper ></AdapterViewFlipper>
-<AnalogClock />
-<AutoCompleteTextView />
-<Button />
-<CalendarView />
-<CheckBox />
-<CheckedTextView />
-<Chronometer />
-<DatePicker />
-<DialerFilter ></DialerFilter>
-<DigitalClock />
-<EditText />
-<ExpandableListView ></ExpandableListView>
-<FrameLayout ></FrameLayout>
-<Gallery />
-<GridLayout ></GridLayout>
-<GridView ></GridView>
-<HorizontalScrollView ></HorizontalScrollView>
-<ImageButton />
-<ImageSwitcher ></ImageSwitcher>
-<ImageView />
-<LinearLayout ></LinearLayout>
-<ListView ></ListView>
-<MediaController ></MediaController>
-<MultiAutoCompleteTextView />
-<NumberPicker />
-<ProgressBar />
-<QuickContactBadge />
-<RadioButton />
-<RadioGroup ></RadioGroup>
-<RatingBar />
-<RelativeLayout ></RelativeLayout>
-<ScrollView ></ScrollView>
-<SearchView ></SearchView>
-<SeekBar />
-<SlidingDrawer ></SlidingDrawer> : SlidingDrawer specific attributes.
-<Space />
-<Spinner />
-<StackView ></StackView>
-<SurfaceView />
-<Switch />
-<TabHost ></TabHost>
-<TabWidget ></TabWidget>
-<TableLayout ></TableLayout>
-<TableRow ></TableRow>
-<TextSwitcher ></TextSwitcher>
-<TextView />
-<TextureView />
-<TimePicker />
-<ToggleButton />
-<TwoLineListItem />
-<VideoView />
-<View /> : Attributes that can be used with android.view.View or any of its subclasses.
-<ViewAnimator ></ViewAnimator>
-<ViewFlipper ></ViewFlipper>
-<ViewStub /> : A android.view.ViewStub lets you lazily include other XML layouts inside your application at runtime.
-<ViewSwitcher ></ViewSwitcher>
-<WebView />
-<ZoomButton />
-<ZoomControls />
-<android.gesture.GestureOverlayView ></android.gesture.GestureOverlayView> : GestureOverlayView specific attributes.
-<fragment /> : A Fragment is a piece of an application's user interface or behavior that can be placed in an Activity
-<include /> : Lets you statically include XML layouts inside other XML layouts.
-<requestFocus /> : Requests focus for the parent element or one of its descendants
-<view /> : A view tag whose class attribute names the class to be instantiated
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion12.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion12.txt
deleted file mode 100644
index 8da18db43..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion12.txt
+++ /dev/null
@@ -1,67 +0,0 @@
-Code completion in completion1.xml for btn_default">^</FrameLayout>:
-<AbsoluteLayout ></AbsoluteLayout>
-<AdapterViewFlipper ></AdapterViewFlipper>
-<AnalogClock />
-<AutoCompleteTextView />
-<Button />
-<CalendarView />
-<CheckBox />
-<CheckedTextView />
-<Chronometer />
-<DatePicker />
-<DialerFilter ></DialerFilter>
-<DigitalClock />
-<EditText />
-<ExpandableListView ></ExpandableListView>
-<FrameLayout ></FrameLayout>
-<Gallery />
-<GridLayout ></GridLayout>
-<GridView ></GridView>
-<HorizontalScrollView ></HorizontalScrollView>
-<ImageButton />
-<ImageSwitcher ></ImageSwitcher>
-<ImageView />
-<LinearLayout ></LinearLayout>
-<ListView ></ListView>
-<MediaController ></MediaController>
-<MultiAutoCompleteTextView />
-<NumberPicker />
-<ProgressBar />
-<QuickContactBadge />
-<RadioButton />
-<RadioGroup ></RadioGroup>
-<RatingBar />
-<RelativeLayout ></RelativeLayout>
-<ScrollView ></ScrollView>
-<SearchView ></SearchView>
-<SeekBar />
-<SlidingDrawer ></SlidingDrawer> : SlidingDrawer specific attributes.
-<Space />
-<Spinner />
-<StackView ></StackView>
-<SurfaceView />
-<Switch />
-<TabHost ></TabHost>
-<TabWidget ></TabWidget>
-<TableLayout ></TableLayout>
-<TableRow ></TableRow>
-<TextSwitcher ></TextSwitcher>
-<TextView />
-<TextureView />
-<TimePicker />
-<ToggleButton />
-<TwoLineListItem />
-<VideoView />
-<View /> : Attributes that can be used with android.view.View or any of its subclasses.
-<ViewAnimator ></ViewAnimator>
-<ViewFlipper ></ViewFlipper>
-<ViewStub /> : A android.view.ViewStub lets you lazily include other XML layouts inside your application at runtime.
-<ViewSwitcher ></ViewSwitcher>
-<WebView />
-<ZoomButton />
-<ZoomControls />
-<android.gesture.GestureOverlayView ></android.gesture.GestureOverlayView> : GestureOverlayView specific attributes.
-<fragment /> : A Fragment is a piece of an application's user interface or behavior that can be placed in an Activity
-<include /> : Lets you statically include XML layouts inside other XML layouts.
-<requestFocus /> : Requests focus for the parent element or one of its descendants
-<view /> : A view tag whose class attribute names the class to be instantiated
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion2.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion2.txt
deleted file mode 100644
index 136a6fe4d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion2.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion1.xml for layout_width="^fill_parent":
-fill_parent
-match_parent
-wrap_content
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion3.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion3.txt
deleted file mode 100644
index 09c27ce2d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion3.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-Code completion in completion1.xml for layout_width="fi^ll_parent":
-fill_parent
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion39.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion39.txt
deleted file mode 100644
index 2ac2d3186..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion39.txt
+++ /dev/null
@@ -1,156 +0,0 @@
-Code completion in completion1.xml for marginBottom="50"^:
-style : A reference to a custom style [reference]
-android:bufferType : Determines the minimum type that getText() will return. [enum]
-android:text : Text to display. [string]
-android:hint : Hint text to display when the text is empty. [string]
-android:textColor : Text color. [color, reference]
-android:textColorHighlight : Color of the text selection highlight. [color, reference]
-android:textColorHint : Color of the hint text. [color, reference]
-android:textAppearance : Base text color, typeface, size, and style. [reference]
-android:textSize : Size of the text. [dimension]
-android:textScaleX : Sets the horizontal scaling factor for the text. [float]
-android:typeface : Typeface (normal, sans, serif, monospace) for the text. [enum]
-android:textStyle : Style (bold, italic, bolditalic) for the text. [flag]
-android:fontFamily : Font family (named by string) for the text. [string]
-android:textColorLink : Text color for links. [color, reference]
-android:cursorVisible : Makes the cursor visible (the default) or invisible. [boolean]
-android:maxLines : Makes the TextView be at most this many lines tall. [integer]
-android:maxHeight : Makes the TextView be at most this many pixels tall. [dimension]
-android:lines : Makes the TextView be exactly this many lines tall. [integer]
-android:height : Makes the TextView be exactly this many pixels tall. [dimension]
-android:minLines : Makes the TextView be at least this many lines tall. [integer]
-android:minHeight : Makes the TextView be at least this many pixels tall. [dimension]
-android:maxEms : Makes the TextView be at most this many ems wide. [integer]
-android:maxWidth : Makes the TextView be at most this many pixels wide. [dimension]
-android:ems : Makes the TextView be exactly this many ems wide. [integer]
-android:width : Makes the TextView be exactly this many pixels wide. [dimension]
-android:minEms : Makes the TextView be at least this many ems wide. [integer]
-android:minWidth : Makes the TextView be at least this many pixels wide. [dimension]
-android:gravity : Specifies how to align the text by the view's x- and/or y-axis when the text is smaller than the view. [flag]
-android:scrollHorizontally : Whether the text is allowed to be wider than the view (and therefore can be scrolled horizontally). [boolean]
-android:password : Whether the characters of the field are displayed as password dots instead of themselves. * Deprecated: Use inputType instead. [boolean]
-android:singleLine : Constrains the text to a single horizontally scrolling line instead of letting it wrap onto multiple lines, and advances focus instead of inserting a newline when you press the enter key. * Deprecated: This attribute is deprecated. Use "maxLines" instead to change the layo...
-android:enabled : Specifies whether the widget is enabled. [boolean]
-android:selectAllOnFocus : If the text is selectable, select it all when the view takes focus. [boolean]
-android:includeFontPadding : Leave enough room for ascenders and descenders instead of using the font ascent and descent strictly. [boolean]
-android:maxLength : Set an input filter to constrain the text length to the specified number. [integer]
-android:shadowColor : Place a shadow of the specified color behind the text. [color]
-android:shadowDx : Horizontal offset of the shadow. [float]
-android:shadowDy : Vertical offset of the shadow. [float]
-android:shadowRadius : Radius of the shadow. [float]
-android:autoLink : Controls whether links such as urls and email addresses are automatically found and converted to clickable links. [flag]
-android:linksClickable : If set to false, keeps the movement method from being set to the link movement method even if autoLink causes links to be found. [boolean]
-android:numeric : If set, specifies that this TextView has a numeric input method. * Deprecated: Use inputType instead. [flag]
-android:digits : If set, specifies that this TextView has a numeric input method and that these specific characters are the ones that it will accept. [string]
-android:phoneNumber : If set, specifies that this TextView has a phone number input method. * Deprecated: Use inputType instead. [boolean]
-android:inputMethod : If set, specifies that this TextView should use the specified input method (specified by fully-qualified class name). * Deprecated: Use inputType instead. [string]
-android:capitalize : If set, specifies that this TextView has a textual input method and should automatically capitalize what the user types. * Deprecated: Use inputType instead. [enum]
-android:autoText : If set, specifies that this TextView has a textual input method and automatically corrects some common spelling errors. * Deprecated: Use inputType instead. [boolean]
-android:editable : If set, specifies that this TextView has an input method. * Deprecated: Use inputType instead. [boolean]
-android:freezesText : If set, the text view will include its current complete text inside of its frozen icicle in addition to meta-data such as the current cursor position. [boolean]
-android:ellipsize : If set, causes words that are longer than the view is wide to be ellipsized instead of broken in the middle. [enum]
-android:drawableTop : The drawable to be drawn above the text. [color, reference]
-android:drawableBottom : The drawable to be drawn below the text. [color, reference]
-android:drawableLeft : The drawable to be drawn to the left of the text. [color, reference]
-android:drawableRight : The drawable to be drawn to the right of the text. [color, reference]
-android:drawableStart : The drawable to be drawn to the start of the text. [color, reference]
-android:drawableEnd : The drawable to be drawn to the end of the text. [color, reference]
-android:drawablePadding : The padding between the drawables and the text. [dimension]
-android:lineSpacingExtra : Extra spacing between lines of text. [dimension]
-android:lineSpacingMultiplier : Extra spacing between lines of text, as a multiplier. [float]
-android:marqueeRepeatLimit : The number of times to repeat the marquee animation. [integer, enum]
-android:inputType : The type of data being placed in a text field, used to help an input method decide how to let the user enter text. [flag]
-android:imeOptions : Additional features you can enable in an IME associated with an editor to improve the integration with your application. [flag]
-android:privateImeOptions : An addition content type description to supply to the input method attached to the text view, which is private to the implementation of the input method. [string]
-android:imeActionLabel : Supply a value for EditorInfo.actionLabel used when an input method is connected to the text view. [string]
-android:imeActionId : Supply a value for EditorInfo.actionId used when an input method is connected to the text view. [integer]
-android:editorExtras : Reference to an "input-extras" XML resource containing additional data to supply to an input method, which is private to the implementation of the input method. [reference]
-android:textSelectHandleLeft : Reference to a drawable that will be used to display a text selection anchor on the left side of a selection region. [reference]
-android:textSelectHandleRight : Reference to a drawable that will be used to display a text selection anchor on the right side of a selection region. [reference]
-android:textSelectHandle : Reference to a drawable that will be used to display a text selection anchor for positioning the cursor within text. [reference]
-android:textEditPasteWindowLayout : The layout of the view that is displayed on top of the cursor to paste inside a TextEdit field. [reference]
-android:textEditNoPasteWindowLayout : Variation of textEditPasteWindowLayout displayed when the clipboard is empty. [reference]
-android:textEditSidePasteWindowLayout : Used instead of textEditPasteWindowLayout when the window is moved on the side of the insertion cursor because it would be clipped if it were positioned on top. [reference]
-android:textEditSideNoPasteWindowLayout : Variation of textEditSidePasteWindowLayout displayed when the clipboard is empty. [reference]
-android:textEditSuggestionItemLayout : Layout of the TextView item that will populate the suggestion popup window. [reference]
-android:textCursorDrawable : Reference to a drawable that will be drawn under the insertion cursor. [reference]
-android:textIsSelectable : Indicates that the content of a non-editable text can be selected. [boolean]
-android:textAllCaps : Present the text in ALL CAPS. [boolean]
-android:id : Supply an identifier name for this view, to later retrieve it with View.findViewById() or Activity.findViewById(). [reference]
-android:tag : Supply a tag for this view containing a String, to be retrieved later with View.getTag() or searched for with View.findViewWithTag() . [string]
-android:scrollX : The initial horizontal scroll offset, in pixels. [dimension]
-android:scrollY : The initial vertical scroll offset, in pixels. [dimension]
-android:background : A drawable to use as the background. [color, reference]
-android:padding : Sets the padding, in pixels, of all four edges. [dimension]
-android:paddingLeft : Sets the padding, in pixels, of the left edge; see padding. [dimension]
-android:paddingTop : Sets the padding, in pixels, of the top edge; see padding. [dimension]
-android:paddingRight : Sets the padding, in pixels, of the right edge; see padding. [dimension]
-android:paddingBottom : Sets the padding, in pixels, of the bottom edge; see padding. [dimension]
-android:paddingStart : Sets the padding, in pixels, of the start edge; see padding. [dimension]
-android:paddingEnd : Sets the padding, in pixels, of the end edge; see padding. [dimension]
-android:focusable : Boolean that controls whether a view can take focus. [boolean]
-android:focusableInTouchMode : Boolean that controls whether a view can take focus while in touch mode. [boolean]
-android:visibility : Controls the initial visibility of the view. [enum]
-android:fitsSystemWindows : Boolean internal attribute to adjust view layout based on system windows such as the status bar. [boolean]
-android:scrollbars : Defines which scrollbars should be displayed on scrolling or not. [flag]
-android:scrollbarStyle : Controls the scrollbar style and position. [enum]
-android:isScrollContainer : Set this if the view will serve as a scrolling container, meaing that it can be resized to shrink its overall window so that there will be space for an input method. [boolean]
-android:fadeScrollbars : Defines whether to fade out scrollbars when they are not in use. [boolean]
-android:scrollbarFadeDuration : Defines the delay in milliseconds that a scrollbar takes to fade out. [integer]
-android:scrollbarDefaultDelayBeforeFade : Defines the delay in milliseconds that a scrollbar waits before fade out. [integer]
-android:scrollbarSize : Sets the width of vertical scrollbars and height of horizontal scrollbars. [dimension]
-android:scrollbarThumbHorizontal : Defines the horizontal scrollbar thumb drawable. [reference]
-android:scrollbarThumbVertical : Defines the vertical scrollbar thumb drawable. [reference]
-android:scrollbarTrackHorizontal : Defines the horizontal scrollbar track drawable. [reference]
-android:scrollbarTrackVertical : Defines the vertical scrollbar track drawable. [reference]
-android:scrollbarAlwaysDrawHorizontalTrack : Defines whether the horizontal scrollbar track should always be drawn. [boolean]
-android:scrollbarAlwaysDrawVerticalTrack : Defines whether the vertical scrollbar track should always be drawn. [boolean]
-android:fadingEdge : This attribute is deprecated and will be ignored as of API level 14 (ICE_CREAM_SANDWICH). [flag]
-android:requiresFadingEdge : Defines which edges should be faded on scrolling. [flag]
-android:fadingEdgeLength : Defines the length of the fading edges. [dimension]
-android:nextFocusLeft : Defines the next view to give focus to when the next focus is FOCUS_LEFT. [reference]
-android:nextFocusRight : Defines the next view to give focus to when the next focus is FOCUS_RIGHT If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a java.lang.RuntimeException will result when the reference is accessed. [reference]
-android:nextFocusUp : Defines the next view to give focus to when the next focus is FOCUS_UP If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a java.lang.RuntimeException will result when the reference is accessed. [reference]
-android:nextFocusDown : Defines the next view to give focus to when the next focus is FOCUS_DOWN If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a java.lang.RuntimeException will result when the reference is accessed. [reference]
-android:nextFocusForward : Defines the next view to give focus to when the next focus is FOCUS_FORWARD If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a java.lang.RuntimeException will result when the reference is accessed. [reference]
-android:clickable : Defines whether this view reacts to click events. [boolean]
-android:longClickable : Defines whether this view reacts to long click events. [boolean]
-android:saveEnabled : If unset, no state will be saved for this view when it is being frozen. [boolean]
-android:filterTouchesWhenObscured : Specifies whether to filter touches when the view's window is obscured by another visible window. [boolean]
-android:drawingCacheQuality : Defines the quality of translucent drawing caches. [enum]
-android:keepScreenOn : Controls whether the view's window should keep the screen on while visible. [boolean]
-android:duplicateParentState : When this attribute is set to true, the view gets its drawable state (focused, pressed, etc.) from its direct parent rather than from itself. [boolean]
-android:minHeight : Defines the minimum height of the view.
-android:minWidth : Defines the minimum width of the view.
-android:soundEffectsEnabled : Boolean that controls whether a view should have sound effects enabled for events such as clicking and touching. [boolean]
-android:hapticFeedbackEnabled : Boolean that controls whether a view should have haptic feedback enabled for events such as long presses. [boolean]
-android:contentDescription : Defines text that briefly describes content of the view. [string]
-android:onClick : Name of the method in this View's context to invoke when the view is clicked. [string]
-android:overScrollMode : Defines over-scrolling behavior. [enum]
-android:alpha : alpha property of the view, as a value between 0 (completely transparent) and 1 (completely opaque). [float]
-android:translationX : translation in x of the view. [dimension]
-android:translationY : translation in y of the view. [dimension]
-android:transformPivotX : x location of the pivot point around which the view will rotate and scale. [dimension]
-android:transformPivotY : y location of the pivot point around which the view will rotate and scale. [dimension]
-android:rotation : rotation of the view, in degrees. [float]
-android:rotationX : rotation of the view around the x axis, in degrees. [float]
-android:rotationY : rotation of the view around the y axis, in degrees. [float]
-android:scaleX : scale of the view in the x direction. [float]
-android:scaleY : scale of the view in the y direction. [float]
-android:verticalScrollbarPosition : Determines which side the vertical scroll bar should be placed on. [enum]
-android:layerType : Specifies the type of layer backing this view. [enum]
-android:layoutDirection : Defines the direction of layout drawing. [enum]
-android:textDirection : Direction of the text. [integer, enum]
-android:textAlignment : Alignment of the text. [integer, enum]
-android:importantForAccessibility : Controls how this View is important for accessibility which is if it fires accessibility events and if it is reported to accessibility services that query the screen. [integer, enum]
-android:layout_width : Specifies the basic width of the view. [dimension, enum]
-android:layout_height : Specifies the basic height of the view. [dimension, enum]
-android:layout_weight : [float]
-android:layout_gravity : Standard gravity constant that a child can supply to its parent. [flag]
-android:layout_margin : Specifies extra space on the left, top, right and bottom sides of this view. [dimension]
-android:layout_marginLeft : Specifies extra space on the left side of this view. [dimension]
-android:layout_marginTop : Specifies extra space on the top side of this view. [dimension]
-android:layout_marginRight : Specifies extra space on the right side of this view. [dimension]
-android:layout_marginBottom : Specifies extra space on the bottom side of this view. [dimension]
-android:layout_marginStart : Specifies extra space on the start side of this view. [dimension]
-android:layout_marginEnd : Specifies extra space on the end side of this view. [dimension]
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion4.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion4.txt
deleted file mode 100644
index a9111eb31..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion4.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-Code completion in completion1.xml for marginBottom="50^":
-50dp : <b>Density-independent Pixels</b> - an abstract unit that is based on the physical density of the screen.
-50sp : <b>Scale-independent Pixels</b> - this is like the dp unit, but it is also scaled by the user's font size preference.
-50pt : <b>Points</b> - 1/72 of an inch based on the physical size of the screen.
-50mm : <b>Millimeters</b> - based on the physical size of the screen.
-50in : <b>Inches</b> - based on the physical size of the screen.
-50px : <b>Pixels</b> - corresponds to actual pixels on the screen. Not recommended.
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion5.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion5.txt
deleted file mode 100644
index 6b1c99363..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion5.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-Code completion in completion1.xml for layout_marginLeft="50d^p":
-50dp : <b>Density-independent Pixels</b> - an abstract unit that is based on the physical density of the screen.
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion6.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion6.txt
deleted file mode 100644
index 99f92b8f3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion6.txt
+++ /dev/null
@@ -1,23 +0,0 @@
-Code completion in completion1.xml for style="@android:^style/Widget.Button":
-@android:style/
-@android:anim/
-@android:animator/
-@android:array/
-@android:attr/
-@android:bool/
-@android:color/
-@android:declare-styleable/
-@android:dimen/
-@android:drawable/
-@android:fraction/
-@android:id/
-@android:integer/
-@android:interpolator/
-@android:layout/
-@android:menu/
-@android:mipmap/
-@android:plurals/
-@android:public/
-@android:raw/
-@android:string/
-@android:xml/
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion7a.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion7a.txt
deleted file mode 100644
index cf373adde..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion7a.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-Code completion in completion1.xml for android:gravity="l^eft|bottom":
-left
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion7b.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion7b.txt
deleted file mode 100644
index 66276d628..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion7b.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-Code completion in completion1.xml for android:gravity="left|b^ottom":
-bottom
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion8.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion8.txt
deleted file mode 100644
index a364bc3ff..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion8.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-Code completion in completion1.xml for layout_width^="fill_parent":
-android:layout_width : Specifies the basic width of the view. [dimension, enum]
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion9.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion9.txt
deleted file mode 100644
index ab6a0d249..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1-expected-completion9.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion1.xml for layout_width=^"fill_parent":
-"fill_parent"
-"match_parent"
-"wrap_content"
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1.xml
deleted file mode 100644
index d523eeb3d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion1.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">
-<!--
- This file deliberately contains errors - it represents partial keyboard
- typing for interactive code completion
--->
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_marginTop="@android:dimen/app_icon_size"
- android:layout_marginLeft="50dp"
- android:layout_marginBottom="50"
- android:textColor="#000000"
- style="@android:style/Widget.Button"
- android:gravity="left|bottom"
- android:text="@string/hello"
- android:hint="hint" />
- <FrameLayout android:foreground="@android:drawable/btn_default"></FrameLayout>
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion10-expected-applyCompletion42.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion10-expected-applyCompletion42.diff
deleted file mode 100644
index af28a1343..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion10-expected-applyCompletion42.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion10.xml for "[^wrap_content]" selecting fill_parent:
-@@ -9 +9
-- android:layout_height="^wrap_content"/>
-+ android:layout_height="fill_parent"^/>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion10-expected-applyCompletion43.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion10-expected-applyCompletion43.diff
deleted file mode 100644
index 0a4d338e2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion10-expected-applyCompletion43.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion10.xml for "[^wrap_c]ontent" selecting fill_parent:
-@@ -9 +9
-- android:layout_height="^wrap_content"/>
-+ android:layout_height="fill_parent"^/>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion10-expected-completion65.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion10-expected-completion65.txt
deleted file mode 100644
index 69fae0da3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion10-expected-completion65.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion10.xml for "[^wrap_content]":
-fill_parent
-match_parent
-wrap_content
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion10.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion10.xml
deleted file mode 100644
index 57b38ee11..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion10.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:gravity="center_vertical">
-<Gallery xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/gallery"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"/>
-</RelativeLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion11-expected-applyCompletion46.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion11-expected-applyCompletion46.diff
deleted file mode 100644
index 321deaa46..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion11-expected-applyCompletion46.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion11.xml for ?android:attr/Textapp^ selecting ?android:attr/textAppearanceLargeInverse:
-@@ -7 +7
-- style="?android:attr/Textapp^"
-+ style="?android:attr/textAppearanceLargeInverse^"
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion11-expected-complation79.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion11-expected-complation79.txt
deleted file mode 100644
index 3748c77ec..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion11-expected-complation79.txt
+++ /dev/null
@@ -1,10 +0,0 @@
-Code completion in completion11.xml for tools:context="^.MainActivity":
-android.accounts.AccountAuthenticatorActivity : <p>See <code><a href="/reference/android/app/SearchManager.html">android.app.SearchManager</a></code> for more details.</td> </tr> <tr class=" api apilevel-1" > <td class="jd-typecol">int</td> <td class="jd-linkcol"...
-android.app.ActivityGroup : <p> <p class="caution"> <strong>This class was deprecated in API level 13</strong>.<br/> Use the new <code><a href="/reference/android/app/Fragment.html">Fragment</a></code> and <code><a href="/reference/android/app/FragmentManager.html">FragmentManager</...
-android.app.AliasActivity : <p>See <code><a href="/reference/android/app/SearchManager.html">android.app.SearchManager</a></code> for more details.</td> </tr> <tr class=" api apilevel-1" > <td class="jd-typecol">int</td> <td class="jd-linkcol"><a href="/reference...
-android.app.ExpandableListActivity : <p> ExpandableListActivity hosts a <code><a href="/reference/android/widget/ExpandableListView.html">ExpandableListView</a></code> object that can be bound to different data sources that provide a two-levels of data (the top-level is group, and below each ...
-android.app.LauncherActivity : <div id="jd-header"> public abstract class <h1 itemprop="name">LauncherActivity</h1> extends <a href="/reference/android/app/ListActivity.html">ListActivity</a><br/> ...
-android.app.ListActivity : <p> ListActivity hosts a <code><a href="/reference/android/widget/ListView.html">ListView</a></code> object that can be bound to different data sources, typically either an array or a Cursor holding query results. Binding, screen layout, and row layout are discussed ...
-android.app.NativeActivity : <p>A typical manifest would look like: <pre>&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.native_activity" android:versionCode="1" android:versionName="1.0"&gt; &lt;!-- This is the platform ...
-android.app.TabActivity : <p> <p class="caution"> <strong>This class was deprecated in API level 13</strong>.<br/> New applications should use Fragments instead of this class; to continue to run on older devices, you can use the v4 support library which provides a version of the F...
-android.preference.PreferenceActivity : <p>This activity shows one or more headers of preferences, each of which is associated with a <code><a href="/reference/android/preference/PreferenceFragment.html">PreferenceFragment</a></code> to display the preferences of that header. The actual layout...
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion11-expected-completion72.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion11-expected-completion72.txt
deleted file mode 100644
index e4c21f9a4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion11-expected-completion72.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Code completion in completion11.xml for ?^android:attr/Textapp:
-?android:attr/
-?attr/
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion11-expected-completion73.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion11-expected-completion73.txt
deleted file mode 100644
index 04cbbce93..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion11-expected-completion73.txt
+++ /dev/null
@@ -1,16 +0,0 @@
-Code completion in completion11.xml for ?android:attr/Textapp^:
-?android:attr/textAppearance : Base text color, typeface, size, and style.
-?android:attr/textAppearanceButton
-?android:attr/textAppearanceInverse
-?android:attr/textAppearanceLarge
-?android:attr/textAppearanceLargeInverse
-?android:attr/textAppearanceLargePopupMenu
-?android:attr/textAppearanceListItem
-?android:attr/textAppearanceListItemSmall
-?android:attr/textAppearanceMedium
-?android:attr/textAppearanceMediumInverse
-?android:attr/textAppearanceSearchResultSubtitle
-?android:attr/textAppearanceSearchResultTitle
-?android:attr/textAppearanceSmall
-?android:attr/textAppearanceSmallInverse
-?android:attr/textAppearanceSmallPopupMenu
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion11-expected-completion74.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion11-expected-completion74.txt
deleted file mode 100644
index 9579c93db..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion11-expected-completion74.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-Code completion in completion11.xml for ?and^roid:attr/Textapp:
-?android:attr/
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion11.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion11.xml
deleted file mode 100644
index e15b83019..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion11.xml
+++ /dev/null
@@ -1,15 +0,0 @@
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
-
- <TextView
- style="?android:attr/Textapp"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerHorizontal="true"
- android:layout_centerVertical="true"
- android:text="@string/hello_world"
- tools:context=".MainActivity" />
-
-</RelativeLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion12-expected-completion75.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion12-expected-completion75.txt
deleted file mode 100644
index 5ad38e61c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion12-expected-completion75.txt
+++ /dev/null
@@ -1,96 +0,0 @@
-Code completion in completion12.xml for <include ^/>:
-layout : [reference]. * Required.
-style : A reference to a custom style [reference]
-android:id : Supply an identifier name for this view, to later retrieve it with View.findViewById() or Activity.findViewById(). [reference]
-android:tag : Supply a tag for this view containing a String, to be retrieved later with View.getTag() or searched for with View.findViewWithTag() . [string]
-android:scrollX : The initial horizontal scroll offset, in pixels. [dimension]
-android:scrollY : The initial vertical scroll offset, in pixels. [dimension]
-android:background : A drawable to use as the background. [color, reference]
-android:padding : Sets the padding, in pixels, of all four edges. [dimension]
-android:paddingLeft : Sets the padding, in pixels, of the left edge; see padding. [dimension]
-android:paddingTop : Sets the padding, in pixels, of the top edge; see padding. [dimension]
-android:paddingRight : Sets the padding, in pixels, of the right edge; see padding. [dimension]
-android:paddingBottom : Sets the padding, in pixels, of the bottom edge; see padding. [dimension]
-android:paddingStart : Sets the padding, in pixels, of the start edge; see padding. [dimension]
-android:paddingEnd : Sets the padding, in pixels, of the end edge; see padding. [dimension]
-android:focusable : Boolean that controls whether a view can take focus. [boolean]
-android:focusableInTouchMode : Boolean that controls whether a view can take focus while in touch mode. [boolean]
-android:visibility : Controls the initial visibility of the view. [enum]
-android:fitsSystemWindows : Boolean internal attribute to adjust view layout based on system windows such as the status bar. [boolean]
-android:scrollbars : Defines which scrollbars should be displayed on scrolling or not. [flag]
-android:scrollbarStyle : Controls the scrollbar style and position. [enum]
-android:isScrollContainer : Set this if the view will serve as a scrolling container, meaing that it can be resized to shrink its overall window so that there will be space for an input method. [boolean]
-android:fadeScrollbars : Defines whether to fade out scrollbars when they are not in use. [boolean]
-android:scrollbarFadeDuration : Defines the delay in milliseconds that a scrollbar takes to fade out. [integer]
-android:scrollbarDefaultDelayBeforeFade : Defines the delay in milliseconds that a scrollbar waits before fade out. [integer]
-android:scrollbarSize : Sets the width of vertical scrollbars and height of horizontal scrollbars. [dimension]
-android:scrollbarThumbHorizontal : Defines the horizontal scrollbar thumb drawable. [reference]
-android:scrollbarThumbVertical : Defines the vertical scrollbar thumb drawable. [reference]
-android:scrollbarTrackHorizontal : Defines the horizontal scrollbar track drawable. [reference]
-android:scrollbarTrackVertical : Defines the vertical scrollbar track drawable. [reference]
-android:scrollbarAlwaysDrawHorizontalTrack : Defines whether the horizontal scrollbar track should always be drawn. [boolean]
-android:scrollbarAlwaysDrawVerticalTrack : Defines whether the vertical scrollbar track should always be drawn. [boolean]
-android:fadingEdge : This attribute is deprecated and will be ignored as of API level 14 (ICE_CREAM_SANDWICH). [flag]
-android:requiresFadingEdge : Defines which edges should be faded on scrolling. [flag]
-android:fadingEdgeLength : Defines the length of the fading edges. [dimension]
-android:nextFocusLeft : Defines the next view to give focus to when the next focus is FOCUS_LEFT. [reference]
-android:nextFocusRight : Defines the next view to give focus to when the next focus is FOCUS_RIGHT If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a java.lang.RuntimeException will result when the reference is accessed. [reference]
-android:nextFocusUp : Defines the next view to give focus to when the next focus is FOCUS_UP If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a java.lang.RuntimeException will result when the reference is accessed. [reference]
-android:nextFocusDown : Defines the next view to give focus to when the next focus is FOCUS_DOWN If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a java.lang.RuntimeException will result when the reference is accessed. [reference]
-android:nextFocusForward : Defines the next view to give focus to when the next focus is FOCUS_FORWARD If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a java.lang.RuntimeException will result when the reference is accessed. [reference]
-android:clickable : Defines whether this view reacts to click events. [boolean]
-android:longClickable : Defines whether this view reacts to long click events. [boolean]
-android:saveEnabled : If unset, no state will be saved for this view when it is being frozen. [boolean]
-android:filterTouchesWhenObscured : Specifies whether to filter touches when the view's window is obscured by another visible window. [boolean]
-android:drawingCacheQuality : Defines the quality of translucent drawing caches. [enum]
-android:keepScreenOn : Controls whether the view's window should keep the screen on while visible. [boolean]
-android:duplicateParentState : When this attribute is set to true, the view gets its drawable state (focused, pressed, etc.) from its direct parent rather than from itself. [boolean]
-android:minHeight : Defines the minimum height of the view.
-android:minWidth : Defines the minimum width of the view.
-android:soundEffectsEnabled : Boolean that controls whether a view should have sound effects enabled for events such as clicking and touching. [boolean]
-android:hapticFeedbackEnabled : Boolean that controls whether a view should have haptic feedback enabled for events such as long presses. [boolean]
-android:contentDescription : Defines text that briefly describes content of the view. [string]
-android:onClick : Name of the method in this View's context to invoke when the view is clicked. [string]
-android:overScrollMode : Defines over-scrolling behavior. [enum]
-android:alpha : alpha property of the view, as a value between 0 (completely transparent) and 1 (completely opaque). [float]
-android:translationX : translation in x of the view. [dimension]
-android:translationY : translation in y of the view. [dimension]
-android:transformPivotX : x location of the pivot point around which the view will rotate and scale. [dimension]
-android:transformPivotY : y location of the pivot point around which the view will rotate and scale. [dimension]
-android:rotation : rotation of the view, in degrees. [float]
-android:rotationX : rotation of the view around the x axis, in degrees. [float]
-android:rotationY : rotation of the view around the y axis, in degrees. [float]
-android:scaleX : scale of the view in the x direction. [float]
-android:scaleY : scale of the view in the y direction. [float]
-android:verticalScrollbarPosition : Determines which side the vertical scroll bar should be placed on. [enum]
-android:layerType : Specifies the type of layer backing this view. [enum]
-android:layoutDirection : Defines the direction of layout drawing. [enum]
-android:textDirection : Direction of the text. [integer, enum]
-android:textAlignment : Alignment of the text. [integer, enum]
-android:importantForAccessibility : Controls how this View is important for accessibility which is if it fires accessibility events and if it is reported to accessibility services that query the screen. [integer, enum]
-android:layout_toLeftOf : Positions the right edge of this view to the left of the given anchor view ID. [reference]
-android:layout_toRightOf : Positions the left edge of this view to the right of the given anchor view ID. [reference]
-android:layout_above : Positions the bottom edge of this view above the given anchor view ID. [reference]
-android:layout_below : Positions the top edge of this view below the given anchor view ID. [reference]
-android:layout_alignBaseline : Positions the baseline of this view on the baseline of the given anchor view ID. [reference]
-android:layout_alignLeft : Makes the left edge of this view match the left edge of the given anchor view ID. [reference]
-android:layout_alignTop : Makes the top edge of this view match the top edge of the given anchor view ID. [reference]
-android:layout_alignRight : Makes the right edge of this view match the right edge of the given anchor view ID. [reference]
-android:layout_alignBottom : Makes the bottom edge of this view match the bottom edge of the given anchor view ID. [reference]
-android:layout_alignParentLeft : If true, makes the left edge of this view match the left edge of the parent. [boolean]
-android:layout_alignParentTop : If true, makes the top edge of this view match the top edge of the parent. [boolean]
-android:layout_alignParentRight : If true, makes the right edge of this view match the right edge of the parent. [boolean]
-android:layout_alignParentBottom : If true, makes the bottom edge of this view match the bottom edge of the parent. [boolean]
-android:layout_centerInParent : If true, centers this child horizontally and vertically within its parent. [boolean]
-android:layout_centerHorizontal : If true, centers this child horizontally within its parent. [boolean]
-android:layout_centerVertical : If true, centers this child vertically within its parent. [boolean]
-android:layout_alignWithParentIfMissing : If set to true, the parent will be used as the anchor when the anchor cannot be be found for layout_toLeftOf, layout_toRightOf, etc. [boolean]
-android:layout_width : Specifies the basic width of the view. [dimension, enum]
-android:layout_height : Specifies the basic height of the view. [dimension, enum]
-android:layout_margin : Specifies extra space on the left, top, right and bottom sides of this view. [dimension]
-android:layout_marginLeft : Specifies extra space on the left side of this view. [dimension]
-android:layout_marginTop : Specifies extra space on the top side of this view. [dimension]
-android:layout_marginRight : Specifies extra space on the right side of this view. [dimension]
-android:layout_marginBottom : Specifies extra space on the bottom side of this view. [dimension]
-android:layout_marginStart : Specifies extra space on the start side of this view. [dimension]
-android:layout_marginEnd : Specifies extra space on the end side of this view. [dimension]
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion12.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion12.xml
deleted file mode 100644
index 946a23277..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion12.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
-
- <include />
-
-</RelativeLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2-expected-applyCompletion13a.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2-expected-applyCompletion13a.diff
deleted file mode 100644
index b36573657..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2-expected-applyCompletion13a.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion2.xml for gravity="left|bottom|^cen selecting fill_vertical:
-@@ -4 +4
-- <TextView android:gravity="left|bottom|^cen"></TextView>
-+ <TextView android:gravity="left|bottom|fill_vertical^"></TextView>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2-expected-applyCompletion13b.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2-expected-applyCompletion13b.diff
deleted file mode 100644
index 46268af6d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2-expected-applyCompletion13b.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion2.xml for gravity="left|bottom|cen^ selecting center_horizontal:
-@@ -4 +4
-- <TextView android:gravity="left|bottom|cen^"></TextView>
-+ <TextView android:gravity="left|bottom|center_horizontal^"></TextView>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2-expected-applyCompletion13c.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2-expected-applyCompletion13c.diff
deleted file mode 100644
index bcac56d16..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2-expected-applyCompletion13c.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion2.xml for gravity="left|bottom^|cen selecting bottom|fill_horizontal:
-@@ -4 +4
-- <TextView android:gravity="left|bottom^|cen"></TextView>
-+ <TextView android:gravity="left|bottom|fill_horizontal^"></TextView>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2-expected-completion13a.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2-expected-completion13a.txt
deleted file mode 100644
index dd28c7365..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2-expected-completion13a.txt
+++ /dev/null
@@ -1,15 +0,0 @@
-Code completion in completion2.xml for gravity="left|bottom|^cen:
-top
-bottom
-left
-right
-center_vertical
-fill_vertical
-center_horizontal
-fill_horizontal
-center
-fill
-clip_vertical
-clip_horizontal
-start
-end
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2-expected-completion13b.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2-expected-completion13b.txt
deleted file mode 100644
index 8e6d4d865..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2-expected-completion13b.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion2.xml for gravity="left|bottom|cen^:
-center_vertical
-center_horizontal
-center
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2-expected-completion13c.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2-expected-completion13c.txt
deleted file mode 100644
index 0aebfedea..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2-expected-completion13c.txt
+++ /dev/null
@@ -1,14 +0,0 @@
-Code completion in completion2.xml for gravity="left|bottom^|cen:
-bottom
-bottom|top
-bottom|right
-bottom|center_vertical
-bottom|fill_vertical
-bottom|center_horizontal
-bottom|fill_horizontal
-bottom|center
-bottom|fill
-bottom|clip_vertical
-bottom|clip_horizontal
-bottom|start
-bottom|end
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2.xml
deleted file mode 100644
index 0921674cd..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion2.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">
- <!-- Test multiple pipes in the flag value -->
- <TextView android:gravity="left|bottom|cen"></TextView>
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion3-expected-applyCompletion17.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion3-expected-applyCompletion17.diff
deleted file mode 100644
index ef070b28e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion3-expected-applyCompletion17.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion3.xml for <EditText ^/> selecting android:textColorHighlight:
-@@ -3 +3
-- <EditText ^/>
-+ <EditText android:textColorHighlight="^"/>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion3-expected-applyCompletion18.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion3-expected-applyCompletion18.diff
deleted file mode 100644
index 283636b4e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion3-expected-applyCompletion18.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion3.xml for <Button ^></Button> selecting android:paddingRight:
-@@ -4 +4
-- <Button ^></Button>
-+ <Button android:paddingRight="^"></Button>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion3.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion3.xml
deleted file mode 100644
index afb64b827..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion3.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">
- <EditText />
- <Button ></Button>
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion4-expected-completion22.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion4-expected-completion22.txt
deleted file mode 100644
index c7170dfcc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion4-expected-completion22.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-Code completion in completion4.xml for <Button^:
-Button
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion4.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion4.xml
deleted file mode 100644
index 0047772f5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion4.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <Button
- android:text="@string/app_name"
- android:layout_marginLeft="@android:dimen/app_icon_size"
- android:id="@+id/button1"
- ></Button>
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion5-expected-applyCompletion19.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion5-expected-applyCompletion19.diff
deleted file mode 100644
index 3f7866324..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion5-expected-applyCompletion19.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion5.xml for android:orientation='^' selecting horizontal:
-@@ -5 +5
-- android:orientation='^'
-+ android:orientation='horizontal'^
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion5-expected-applyCompletion20.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion5-expected-applyCompletion20.diff
deleted file mode 100644
index 4933d1320..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion5-expected-applyCompletion20.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion5.xml for android:layout_marginTop='50^dp' selecting 50pt:
-@@ -10 +10
-- android:layout_marginTop='50^dp'
-+ android:layout_marginTop='50pt'^
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion5-expected-applyCompletion21.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion5-expected-applyCompletion21.diff
deleted file mode 100644
index a4c88d7fc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion5-expected-applyCompletion21.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion5.xml for android:layout_width='^wrap_content' selecting match_parent:
-@@ -11 +11
-- android:layout_width='^wrap_content'
-+ android:layout_width='match_parent'^
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion5-expected-applyCompletion40.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion5-expected-applyCompletion40.diff
deleted file mode 100644
index 705f865ce..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion5-expected-applyCompletion40.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion5.xml for android:id='@+id/button2'^ selecting android:maxWidth:
-@@ -15 +15
-- android:id='@+id/button2'^
-+ android:id='@+id/button2' android:maxWidth="^"
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion5-expected-completion40.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion5-expected-completion40.txt
deleted file mode 100644
index a4cf0fa45..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion5-expected-completion40.txt
+++ /dev/null
@@ -1,156 +0,0 @@
-Code completion in completion5.xml for android:id='@+id/button2'^:
-style : A reference to a custom style [reference]
-android:bufferType : Determines the minimum type that getText() will return. [enum]
-android:text : Text to display. [string]
-android:hint : Hint text to display when the text is empty. [string]
-android:textColor : Text color. [color, reference]
-android:textColorHighlight : Color of the text selection highlight. [color, reference]
-android:textColorHint : Color of the hint text. [color, reference]
-android:textAppearance : Base text color, typeface, size, and style. [reference]
-android:textSize : Size of the text. [dimension]
-android:textScaleX : Sets the horizontal scaling factor for the text. [float]
-android:typeface : Typeface (normal, sans, serif, monospace) for the text. [enum]
-android:textStyle : Style (bold, italic, bolditalic) for the text. [flag]
-android:fontFamily : Font family (named by string) for the text. [string]
-android:textColorLink : Text color for links. [color, reference]
-android:cursorVisible : Makes the cursor visible (the default) or invisible. [boolean]
-android:maxLines : Makes the TextView be at most this many lines tall. [integer]
-android:maxHeight : Makes the TextView be at most this many pixels tall. [dimension]
-android:lines : Makes the TextView be exactly this many lines tall. [integer]
-android:height : Makes the TextView be exactly this many pixels tall. [dimension]
-android:minLines : Makes the TextView be at least this many lines tall. [integer]
-android:minHeight : Makes the TextView be at least this many pixels tall. [dimension]
-android:maxEms : Makes the TextView be at most this many ems wide. [integer]
-android:maxWidth : Makes the TextView be at most this many pixels wide. [dimension]
-android:ems : Makes the TextView be exactly this many ems wide. [integer]
-android:width : Makes the TextView be exactly this many pixels wide. [dimension]
-android:minEms : Makes the TextView be at least this many ems wide. [integer]
-android:minWidth : Makes the TextView be at least this many pixels wide. [dimension]
-android:gravity : Specifies how to align the text by the view's x- and/or y-axis when the text is smaller than the view. [flag]
-android:scrollHorizontally : Whether the text is allowed to be wider than the view (and therefore can be scrolled horizontally). [boolean]
-android:password : Whether the characters of the field are displayed as password dots instead of themselves. * Deprecated: Use inputType instead. [boolean]
-android:singleLine : Constrains the text to a single horizontally scrolling line instead of letting it wrap onto multiple lines, and advances focus instead of inserting a newline when you press the enter key. * Deprecated: This attribute is deprecated. Use "maxLines" instead to change the layo...
-android:enabled : Specifies whether the widget is enabled. [boolean]
-android:selectAllOnFocus : If the text is selectable, select it all when the view takes focus. [boolean]
-android:includeFontPadding : Leave enough room for ascenders and descenders instead of using the font ascent and descent strictly. [boolean]
-android:maxLength : Set an input filter to constrain the text length to the specified number. [integer]
-android:shadowColor : Place a shadow of the specified color behind the text. [color]
-android:shadowDx : Horizontal offset of the shadow. [float]
-android:shadowDy : Vertical offset of the shadow. [float]
-android:shadowRadius : Radius of the shadow. [float]
-android:autoLink : Controls whether links such as urls and email addresses are automatically found and converted to clickable links. [flag]
-android:linksClickable : If set to false, keeps the movement method from being set to the link movement method even if autoLink causes links to be found. [boolean]
-android:numeric : If set, specifies that this TextView has a numeric input method. * Deprecated: Use inputType instead. [flag]
-android:digits : If set, specifies that this TextView has a numeric input method and that these specific characters are the ones that it will accept. [string]
-android:phoneNumber : If set, specifies that this TextView has a phone number input method. * Deprecated: Use inputType instead. [boolean]
-android:inputMethod : If set, specifies that this TextView should use the specified input method (specified by fully-qualified class name). * Deprecated: Use inputType instead. [string]
-android:capitalize : If set, specifies that this TextView has a textual input method and should automatically capitalize what the user types. * Deprecated: Use inputType instead. [enum]
-android:autoText : If set, specifies that this TextView has a textual input method and automatically corrects some common spelling errors. * Deprecated: Use inputType instead. [boolean]
-android:editable : If set, specifies that this TextView has an input method. * Deprecated: Use inputType instead. [boolean]
-android:freezesText : If set, the text view will include its current complete text inside of its frozen icicle in addition to meta-data such as the current cursor position. [boolean]
-android:ellipsize : If set, causes words that are longer than the view is wide to be ellipsized instead of broken in the middle. [enum]
-android:drawableTop : The drawable to be drawn above the text. [color, reference]
-android:drawableBottom : The drawable to be drawn below the text. [color, reference]
-android:drawableLeft : The drawable to be drawn to the left of the text. [color, reference]
-android:drawableRight : The drawable to be drawn to the right of the text. [color, reference]
-android:drawableStart : The drawable to be drawn to the start of the text. [color, reference]
-android:drawableEnd : The drawable to be drawn to the end of the text. [color, reference]
-android:drawablePadding : The padding between the drawables and the text. [dimension]
-android:lineSpacingExtra : Extra spacing between lines of text. [dimension]
-android:lineSpacingMultiplier : Extra spacing between lines of text, as a multiplier. [float]
-android:marqueeRepeatLimit : The number of times to repeat the marquee animation. [integer, enum]
-android:inputType : The type of data being placed in a text field, used to help an input method decide how to let the user enter text. [flag]
-android:imeOptions : Additional features you can enable in an IME associated with an editor to improve the integration with your application. [flag]
-android:privateImeOptions : An addition content type description to supply to the input method attached to the text view, which is private to the implementation of the input method. [string]
-android:imeActionLabel : Supply a value for EditorInfo.actionLabel used when an input method is connected to the text view. [string]
-android:imeActionId : Supply a value for EditorInfo.actionId used when an input method is connected to the text view. [integer]
-android:editorExtras : Reference to an "input-extras" XML resource containing additional data to supply to an input method, which is private to the implementation of the input method. [reference]
-android:textSelectHandleLeft : Reference to a drawable that will be used to display a text selection anchor on the left side of a selection region. [reference]
-android:textSelectHandleRight : Reference to a drawable that will be used to display a text selection anchor on the right side of a selection region. [reference]
-android:textSelectHandle : Reference to a drawable that will be used to display a text selection anchor for positioning the cursor within text. [reference]
-android:textEditPasteWindowLayout : The layout of the view that is displayed on top of the cursor to paste inside a TextEdit field. [reference]
-android:textEditNoPasteWindowLayout : Variation of textEditPasteWindowLayout displayed when the clipboard is empty. [reference]
-android:textEditSidePasteWindowLayout : Used instead of textEditPasteWindowLayout when the window is moved on the side of the insertion cursor because it would be clipped if it were positioned on top. [reference]
-android:textEditSideNoPasteWindowLayout : Variation of textEditSidePasteWindowLayout displayed when the clipboard is empty. [reference]
-android:textEditSuggestionItemLayout : Layout of the TextView item that will populate the suggestion popup window. [reference]
-android:textCursorDrawable : Reference to a drawable that will be drawn under the insertion cursor. [reference]
-android:textIsSelectable : Indicates that the content of a non-editable text can be selected. [boolean]
-android:textAllCaps : Present the text in ALL CAPS. [boolean]
-android:id : Supply an identifier name for this view, to later retrieve it with View.findViewById() or Activity.findViewById(). [reference]
-android:tag : Supply a tag for this view containing a String, to be retrieved later with View.getTag() or searched for with View.findViewWithTag() . [string]
-android:scrollX : The initial horizontal scroll offset, in pixels. [dimension]
-android:scrollY : The initial vertical scroll offset, in pixels. [dimension]
-android:background : A drawable to use as the background. [color, reference]
-android:padding : Sets the padding, in pixels, of all four edges. [dimension]
-android:paddingLeft : Sets the padding, in pixels, of the left edge; see padding. [dimension]
-android:paddingTop : Sets the padding, in pixels, of the top edge; see padding. [dimension]
-android:paddingRight : Sets the padding, in pixels, of the right edge; see padding. [dimension]
-android:paddingBottom : Sets the padding, in pixels, of the bottom edge; see padding. [dimension]
-android:paddingStart : Sets the padding, in pixels, of the start edge; see padding. [dimension]
-android:paddingEnd : Sets the padding, in pixels, of the end edge; see padding. [dimension]
-android:focusable : Boolean that controls whether a view can take focus. [boolean]
-android:focusableInTouchMode : Boolean that controls whether a view can take focus while in touch mode. [boolean]
-android:visibility : Controls the initial visibility of the view. [enum]
-android:fitsSystemWindows : Boolean internal attribute to adjust view layout based on system windows such as the status bar. [boolean]
-android:scrollbars : Defines which scrollbars should be displayed on scrolling or not. [flag]
-android:scrollbarStyle : Controls the scrollbar style and position. [enum]
-android:isScrollContainer : Set this if the view will serve as a scrolling container, meaing that it can be resized to shrink its overall window so that there will be space for an input method. [boolean]
-android:fadeScrollbars : Defines whether to fade out scrollbars when they are not in use. [boolean]
-android:scrollbarFadeDuration : Defines the delay in milliseconds that a scrollbar takes to fade out. [integer]
-android:scrollbarDefaultDelayBeforeFade : Defines the delay in milliseconds that a scrollbar waits before fade out. [integer]
-android:scrollbarSize : Sets the width of vertical scrollbars and height of horizontal scrollbars. [dimension]
-android:scrollbarThumbHorizontal : Defines the horizontal scrollbar thumb drawable. [reference]
-android:scrollbarThumbVertical : Defines the vertical scrollbar thumb drawable. [reference]
-android:scrollbarTrackHorizontal : Defines the horizontal scrollbar track drawable. [reference]
-android:scrollbarTrackVertical : Defines the vertical scrollbar track drawable. [reference]
-android:scrollbarAlwaysDrawHorizontalTrack : Defines whether the horizontal scrollbar track should always be drawn. [boolean]
-android:scrollbarAlwaysDrawVerticalTrack : Defines whether the vertical scrollbar track should always be drawn. [boolean]
-android:fadingEdge : This attribute is deprecated and will be ignored as of API level 14 (ICE_CREAM_SANDWICH). [flag]
-android:requiresFadingEdge : Defines which edges should be faded on scrolling. [flag]
-android:fadingEdgeLength : Defines the length of the fading edges. [dimension]
-android:nextFocusLeft : Defines the next view to give focus to when the next focus is FOCUS_LEFT. [reference]
-android:nextFocusRight : Defines the next view to give focus to when the next focus is FOCUS_RIGHT If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a java.lang.RuntimeException will result when the reference is accessed. [reference]
-android:nextFocusUp : Defines the next view to give focus to when the next focus is FOCUS_UP If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a java.lang.RuntimeException will result when the reference is accessed. [reference]
-android:nextFocusDown : Defines the next view to give focus to when the next focus is FOCUS_DOWN If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a java.lang.RuntimeException will result when the reference is accessed. [reference]
-android:nextFocusForward : Defines the next view to give focus to when the next focus is FOCUS_FORWARD If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a java.lang.RuntimeException will result when the reference is accessed. [reference]
-android:clickable : Defines whether this view reacts to click events. [boolean]
-android:longClickable : Defines whether this view reacts to long click events. [boolean]
-android:saveEnabled : If unset, no state will be saved for this view when it is being frozen. [boolean]
-android:filterTouchesWhenObscured : Specifies whether to filter touches when the view's window is obscured by another visible window. [boolean]
-android:drawingCacheQuality : Defines the quality of translucent drawing caches. [enum]
-android:keepScreenOn : Controls whether the view's window should keep the screen on while visible. [boolean]
-android:duplicateParentState : When this attribute is set to true, the view gets its drawable state (focused, pressed, etc.) from its direct parent rather than from itself. [boolean]
-android:minHeight : Defines the minimum height of the view.
-android:minWidth : Defines the minimum width of the view.
-android:soundEffectsEnabled : Boolean that controls whether a view should have sound effects enabled for events such as clicking and touching. [boolean]
-android:hapticFeedbackEnabled : Boolean that controls whether a view should have haptic feedback enabled for events such as long presses. [boolean]
-android:contentDescription : Defines text that briefly describes content of the view. [string]
-android:onClick : Name of the method in this View's context to invoke when the view is clicked. [string]
-android:overScrollMode : Defines over-scrolling behavior. [enum]
-android:alpha : alpha property of the view, as a value between 0 (completely transparent) and 1 (completely opaque). [float]
-android:translationX : translation in x of the view. [dimension]
-android:translationY : translation in y of the view. [dimension]
-android:transformPivotX : x location of the pivot point around which the view will rotate and scale. [dimension]
-android:transformPivotY : y location of the pivot point around which the view will rotate and scale. [dimension]
-android:rotation : rotation of the view, in degrees. [float]
-android:rotationX : rotation of the view around the x axis, in degrees. [float]
-android:rotationY : rotation of the view around the y axis, in degrees. [float]
-android:scaleX : scale of the view in the x direction. [float]
-android:scaleY : scale of the view in the y direction. [float]
-android:verticalScrollbarPosition : Determines which side the vertical scroll bar should be placed on. [enum]
-android:layerType : Specifies the type of layer backing this view. [enum]
-android:layoutDirection : Defines the direction of layout drawing. [enum]
-android:textDirection : Direction of the text. [integer, enum]
-android:textAlignment : Alignment of the text. [integer, enum]
-android:importantForAccessibility : Controls how this View is important for accessibility which is if it fires accessibility events and if it is reported to accessibility services that query the screen. [integer, enum]
-android:layout_width : Specifies the basic width of the view. [dimension, enum]
-android:layout_height : Specifies the basic height of the view. [dimension, enum]
-android:layout_weight : [float]
-android:layout_gravity : Standard gravity constant that a child can supply to its parent. [flag]
-android:layout_margin : Specifies extra space on the left, top, right and bottom sides of this view. [dimension]
-android:layout_marginLeft : Specifies extra space on the left side of this view. [dimension]
-android:layout_marginTop : Specifies extra space on the top side of this view. [dimension]
-android:layout_marginRight : Specifies extra space on the right side of this view. [dimension]
-android:layout_marginBottom : Specifies extra space on the bottom side of this view. [dimension]
-android:layout_marginStart : Specifies extra space on the start side of this view. [dimension]
-android:layout_marginEnd : Specifies extra space on the end side of this view. [dimension]
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion5.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion5.xml
deleted file mode 100644
index 757be8b8e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion5.xml
+++ /dev/null
@@ -1,23 +0,0 @@
-<?xml version='1.0' encoding='utf-8'?>
-<LinearLayout
- xmlns:android='http://schemas.android.com/apk/res/android'
- android:layout_width='match_parent'
- android:orientation=''
- android:layout_height='match_parent'>
- <Button
- android:text="what's up doc?"
- android:id='@+id/button1'
- android:layout_marginTop='50dp'
- android:layout_width='wrap_content'
- android:layout_height='wrap_content'></Button>
- <Button
- android:text="quote='"
- android:id='@+id/button2'
- android:layout_width='wrap_content'
- android:layout_height='wrap_content'></Button>
- <Button
- android:text='quote="'
- android:id='@+id/button2'
- android:layout_width='wrap_content'
- android:layout_height='wrap_content'></Button>
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion6-expected-applyCompletion22.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion6-expected-applyCompletion22.diff
deleted file mode 100644
index 92cd2f2ab..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion6-expected-applyCompletion22.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion6.xml for android:orientation="^" selecting horizontal:
-@@ -5 +5
-- android:orientation="^"
-+ android:orientation="horizontal"^
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion6.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion6.xml
deleted file mode 100644
index 55bfa0c93..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion6.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version='1.0' encoding='utf-8'?>
-<LinearLayout
- xmlns:android='http://schemas.android.com/apk/res/android'
- android:layout_width='match_parent'
- android:orientation=""
- android:layout_height='match_parent'>
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion7-expected-applyCompletion23.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion7-expected-applyCompletion23.diff
deleted file mode 100644
index 1aaadc267..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion7-expected-applyCompletion23.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion7.xml for android:orientation="^ selecting horizontal:
-@@ -5 +5
-- android:orientation="^
-+ android:orientation="horizontal^
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion7.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion7.xml
deleted file mode 100644
index 30afbaf4f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion7.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version='1.0' encoding='utf-8'?>
-<LinearLayout
- xmlns:android='http://schemas.android.com/apk/res/android'
- android:layout_width='match_parent'
- android:orientation="
- android:layout_height='match_parent'>
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion8-expected-applyCompletion41.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion8-expected-applyCompletion41.diff
deleted file mode 100644
index 7678740d1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion8-expected-applyCompletion41.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion8.xml for android:mar^="50dp" selecting android:layout_marginRight:
-@@ -6 +6
-- android:mar^="50dp"
-+ android:layout_marginRight^="50dp"
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion8-expected-completion41.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion8-expected-completion41.txt
deleted file mode 100644
index 0c2e215ec..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion8-expected-completion41.txt
+++ /dev/null
@@ -1,9 +0,0 @@
-Code completion in completion8.xml for android:mar^="50dp":
-android:layout_margin : Specifies extra space on the left, top, right and bottom sides of this view. [dimension]
-android:layout_marginLeft : Specifies extra space on the left side of this view. [dimension]
-android:layout_marginTop : Specifies extra space on the top side of this view. [dimension]
-android:layout_marginRight : Specifies extra space on the right side of this view. [dimension]
-android:layout_marginBottom : Specifies extra space on the bottom side of this view. [dimension]
-android:layout_marginStart : Specifies extra space on the start side of this view. [dimension]
-android:layout_marginEnd : Specifies extra space on the end side of this view. [dimension]
-android:marqueeRepeatLimit : The number of times to repeat the marquee animation. [integer, enum]
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion8-expected-completion42.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion8-expected-completion42.txt
deleted file mode 100644
index f5b072093..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion8-expected-completion42.txt
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completion8.xml for android:w^i="100":
-android:layout_width : Specifies the basic width of the view. [dimension, enum]
-android:layout_weight : [float]
-android:width : Makes the TextView be exactly this many pixels wide. [dimension]
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion8-expected-completion43.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion8-expected-completion43.txt
deleted file mode 100644
index 50f13d18b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion8-expected-completion43.txt
+++ /dev/null
@@ -1,9 +0,0 @@
-Code completion in completion8.xml for mar^="60dp":
-android:layout_margin : Specifies extra space on the left, top, right and bottom sides of this view. [dimension]
-android:layout_marginLeft : Specifies extra space on the left side of this view. [dimension]
-android:layout_marginTop : Specifies extra space on the top side of this view. [dimension]
-android:layout_marginRight : Specifies extra space on the right side of this view. [dimension]
-android:layout_marginBottom : Specifies extra space on the bottom side of this view. [dimension]
-android:layout_marginStart : Specifies extra space on the start side of this view. [dimension]
-android:layout_marginEnd : Specifies extra space on the end side of this view. [dimension]
-android:marqueeRepeatLimit : The number of times to repeat the marquee animation. [integer, enum]
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion8-expected-completion44.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion8-expected-completion44.txt
deleted file mode 100644
index 357814507..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion8-expected-completion44.txt
+++ /dev/null
@@ -1,13 +0,0 @@
-Code completion in completion8.xml for android:layo^ut_width="fill_parent":
-android:layout_width : Specifies the basic width of the view. [dimension, enum]
-android:layout_height : Specifies the basic height of the view. [dimension, enum]
-android:layout_weight : [float]
-android:layout_gravity : Standard gravity constant that a child can supply to its parent. [flag]
-android:layout_margin : Specifies extra space on the left, top, right and bottom sides of this view. [dimension]
-android:layout_marginLeft : Specifies extra space on the left side of this view. [dimension]
-android:layout_marginTop : Specifies extra space on the top side of this view. [dimension]
-android:layout_marginRight : Specifies extra space on the right side of this view. [dimension]
-android:layout_marginBottom : Specifies extra space on the bottom side of this view. [dimension]
-android:layout_marginStart : Specifies extra space on the start side of this view. [dimension]
-android:layout_marginEnd : Specifies extra space on the end side of this view. [dimension]
-android:layoutDirection : Defines the direction of layout drawing. [enum]
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion8.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion8.xml
deleted file mode 100644
index 3f9d6b537..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion8.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:mar="50dp"
- android:wi="100"
- mar="60dp"
- />
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion9-expected-completion62.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion9-expected-completion62.txt
deleted file mode 100644
index 9189a827c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion9-expected-completion62.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-Code completion in completion9.xml for android:layout_wi^dth=:
-android:layout_width : Specifies the basic width of the view. [dimension, enum]
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion9-expected-completion63.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion9-expected-completion63.txt
deleted file mode 100644
index c6ee31dbe..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion9-expected-completion63.txt
+++ /dev/null
@@ -1 +0,0 @@
-Code completion in completion9.xml for android:drawable^Top:
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion9-expected-completion64.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion9-expected-completion64.txt
deleted file mode 100644
index 2085e96da..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion9-expected-completion64.txt
+++ /dev/null
@@ -1,68 +0,0 @@
-Code completion in completion9.xml for ^<Button:
-<AbsoluteLayout ></AbsoluteLayout>
-<AdapterViewFlipper ></AdapterViewFlipper>
-<AnalogClock />
-<AutoCompleteTextView />
-<Button />
-<CalendarView />
-<CheckBox />
-<CheckedTextView />
-<Chronometer />
-<DatePicker />
-<DialerFilter ></DialerFilter>
-<DigitalClock />
-<EditText />
-<ExpandableListView ></ExpandableListView>
-<FrameLayout ></FrameLayout>
-<Gallery />
-<GridLayout ></GridLayout>
-<GridView ></GridView>
-<HorizontalScrollView ></HorizontalScrollView>
-<ImageButton />
-<ImageSwitcher ></ImageSwitcher>
-<ImageView />
-<LinearLayout ></LinearLayout>
-<ListView ></ListView>
-<MediaController ></MediaController>
-<MultiAutoCompleteTextView />
-<NumberPicker />
-<ProgressBar />
-<QuickContactBadge />
-<RadioButton />
-<RadioGroup ></RadioGroup>
-<RatingBar />
-<RelativeLayout ></RelativeLayout>
-<ScrollView ></ScrollView>
-<SearchView ></SearchView>
-<SeekBar />
-<SlidingDrawer ></SlidingDrawer> : SlidingDrawer specific attributes.
-<Space />
-<Spinner />
-<StackView ></StackView>
-<SurfaceView />
-<Switch />
-<TabHost ></TabHost>
-<TabWidget ></TabWidget>
-<TableLayout ></TableLayout>
-<TableRow ></TableRow>
-<TextSwitcher ></TextSwitcher>
-<TextView />
-<TextureView />
-<TimePicker />
-<ToggleButton />
-<TwoLineListItem />
-<VideoView />
-<View /> : Attributes that can be used with android.view.View or any of its subclasses.
-<ViewAnimator ></ViewAnimator>
-<ViewFlipper ></ViewFlipper>
-<ViewStub /> : A android.view.ViewStub lets you lazily include other XML layouts inside your application at runtime.
-<ViewSwitcher ></ViewSwitcher>
-<WebView />
-<ZoomButton />
-<ZoomControls />
-<android.gesture.GestureOverlayView ></android.gesture.GestureOverlayView> : GestureOverlayView specific attributes.
-<fragment /> : A Fragment is a piece of an application's user interface or behavior that can be placed in an Activity
-<include /> : Lets you statically include XML layouts inside other XML layouts.
-<merge ></merge> : A root tag useful for XML layouts inflated using a ViewStub.
-<requestFocus /> : Requests focus for the parent element or one of its descendants
-<view /> : A view tag whose class attribute names the class to be instantiated
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion9.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion9.xml
deleted file mode 100644
index 9040d8c1f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completion9.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-<com.google.android.apps.iosched.ui.widget.DashboardLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
-
- <Button android:id="@+id/home_btn_schedule"
- style="@style/DashboardButton"
- android:text="@string/btn_schedule"
- android:drawableTop="@drawable/home_btn_schedule" />
-</com.google.android.apps.iosched.ui.widget.DashboardLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion24a.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion24a.diff
deleted file mode 100644
index d3232190c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion24a.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completionvalues1.xml for android:textS^ize selecting android:textSelectHandleLeft:
-@@ -4 +4
-- <item name="android:textS^ize">17sp</item>
-+ <item name="android:textSelectHandleLeft"^>17sp</item>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion24b.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion24b.diff
deleted file mode 100644
index ac71df7eb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion24b.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completionvalues1.xml for 17^sp selecting 17mm:
-@@ -4 +4
-- <item name="android:textSize">17^sp</item>
-+ <item name="android:textSize">17mm^</item>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion25.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion25.diff
deleted file mode 100644
index df6fceb9e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion25.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completionvalues1.xml for textColor">^@color/title_color</item> selecting @android::
-@@ -5 +5
-- <item name="android:textColor">^@color/title_color</item>
-+ <item name="android:textColor">@android:^</item>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion26.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion26.diff
deleted file mode 100644
index 36fce8b9e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion26.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completionvalues1.xml for <item name="android:shadowColor">@an^</item> selecting @android::
-@@ -6 +6
-- <item name="android:shadowColor">@an^</item>
-+ <item name="android:shadowColor">@android:^</item>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion27.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion27.diff
deleted file mode 100644
index 6315fc4fd..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion27.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completionvalues1.xml for <item name="android:gravity">^ </item> selecting center_vertical:
-@@ -7 +7
-- <item name="android:gravity">^ </item>
-+ <item name="android:gravity">center_vertical^</item>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion28.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion28.diff
deleted file mode 100644
index 1db9773a1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion28.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completionvalues1.xml for <item name="android:gravity"> ^</item> selecting left:
-@@ -7 +7
-- <item name="android:gravity"> ^</item>
-+ <item name="android:gravity"> left^</item>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion29.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion29.diff
deleted file mode 100644
index 63076464d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion29.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completionvalues1.xml for <item name="gr^"> selecting android:gravity:
-@@ -8 +8
-- <item name="gr^">@color/title_color</item>
-+ <item name="android:gravity"^>@color/title_color</item>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion30.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion30.diff
deleted file mode 100644
index c8a119fd9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion30.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completionvalues1.xml for <item name="an^"> selecting android:animateOnClick:
-@@ -9 +9
-- <item name="an^">@color/title_color</item>
-+ <item name="android:animateOnClick"^>@color/title_color</item>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion31.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion31.diff
deleted file mode 100644
index 9b3743807..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion31.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completionvalues1.xml for <item ^></item> selecting name:
-@@ -10 +10
-- <item ^></item>
-+ <item name="^"></item>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion32.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion32.diff
deleted file mode 100644
index b34a8ec5c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion32.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completionvalues1.xml for <item name="^"></item> selecting android:background:
-@@ -11 +11
-- <item name="^"></item>
-+ <item name="android:background"^></item>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion33.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion33.diff
deleted file mode 100644
index b78adee5b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion33.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completionvalues1.xml for <item name="android:allowSingleTap">^</item> selecting true:
-@@ -12 +12
-- <item name="android:allowSingleTap">^</item>
-+ <item name="android:allowSingleTap">true^</item>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion34.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion34.diff
deleted file mode 100644
index 5af6c92d5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion34.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completionvalues1.xml for <item name="android:alwaysDrawnWithCache">^ false </item> selecting true:
-@@ -13 +13
-- <item name="android:alwaysDrawnWithCache">^ false </item>
-+ <item name="android:alwaysDrawnWithCache">true^</item>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion35.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion35.diff
deleted file mode 100644
index f48f10143..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion35.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completionvalues1.xml for <item name="android:alwaysDrawnWithCache"> ^false </item> selecting true:
-@@ -13 +13
-- <item name="android:alwaysDrawnWithCache"> ^false </item>
-+ <item name="android:alwaysDrawnWithCache"> true^</item>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion36.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion36.diff
deleted file mode 100644
index 8c246a8ff..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion36.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completionvalues1.xml for <item name="android:alwaysDrawnWithCache"> f^alse </item> selecting false:
-@@ -13 +13
-- <item name="android:alwaysDrawnWithCache"> f^alse </item>
-+ <item name="android:alwaysDrawnWithCache"> false^</item>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion37.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion37.diff
deleted file mode 100644
index 082f2b25c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion37.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completionvalues1.xml for <item name="android:orientation">h^</item> selecting horizontal:
-@@ -14 +14
-- <item name="android:orientation">h^</item>
-+ <item name="android:orientation">horizontal^</item>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion38.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion38.diff
deleted file mode 100644
index 47580e1d8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion38.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completionvalues1.xml for c^ selecting center:
-@@ -16 +16
-- c^
-+ center^
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion44.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion44.diff
deleted file mode 100644
index 57fe472e5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-applyCompletion44.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completionvalues1.xml for [^false] selecting true:
-@@ -13 +13
-- <item name="android:alwaysDrawnWithCache"> ^false </item>
-+ <item name="android:alwaysDrawnWithCache"> true^</item>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion23.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion23.txt
deleted file mode 100644
index a2f64dc72..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion23.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-Code completion in completionvalues1.xml for android:textS^ize:
-android:textScaleX : Sets the horizontal scaling factor for the text. [float]
-android:textSelectHandle : Reference to a drawable that will be used to display a text selection anchor for positioning the cursor within text. [reference]
-android:textSelectHandleLeft : Reference to a drawable that will be used to display a text selection anchor on the left side of a selection region. [reference]
-android:textSelectHandleRight : Reference to a drawable that will be used to display a text selection anchor on the right side of a selection region. [reference]
-android:textSize : Size of the text. [dimension]
-android:textStyle : Style (bold, italic, bolditalic) for the text. [flag]
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion24.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion24.txt
deleted file mode 100644
index c1de9ec99..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion24.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-Code completion in completionvalues1.xml for 17^sp:
-17dp : <b>Density-independent Pixels</b> - an abstract unit that is based on the physical density of the screen.
-17sp : <b>Scale-independent Pixels</b> - this is like the dp unit, but it is also scaled by the user's font size preference.
-17pt : <b>Points</b> - 1/72 of an inch based on the physical size of the screen.
-17mm : <b>Millimeters</b> - based on the physical size of the screen.
-17in : <b>Inches</b> - based on the physical size of the screen.
-17px : <b>Pixels</b> - corresponds to actual pixels on the screen. Not recommended.
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion25.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion25.txt
deleted file mode 100644
index b57246dd0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion25.txt
+++ /dev/null
@@ -1,8 +0,0 @@
-Code completion in completionvalues1.xml for textColor">^@color/title_color</item>:
-@android:
-@+id/
-@drawable/
-@id/
-@layout/
-@string/
-@style/
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion26.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion26.txt
deleted file mode 100644
index b1c541c38..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion26.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-Code completion in completionvalues1.xml for <item name="android:shadowColor">@an^</item>:
-@android:
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion27.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion27.txt
deleted file mode 100644
index 22b636ddf..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion27.txt
+++ /dev/null
@@ -1,15 +0,0 @@
-Code completion in completionvalues1.xml for <item name="android:gravity">^ </item>:
-top
-bottom
-left
-right
-center_vertical
-fill_vertical
-center_horizontal
-fill_horizontal
-center
-fill
-clip_vertical
-clip_horizontal
-start
-end
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion28.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion28.txt
deleted file mode 100644
index 2a850294d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion28.txt
+++ /dev/null
@@ -1,15 +0,0 @@
-Code completion in completionvalues1.xml for <item name="android:gravity"> ^</item>:
-top
-bottom
-left
-right
-center_vertical
-fill_vertical
-center_horizontal
-fill_horizontal
-center
-fill
-clip_vertical
-clip_horizontal
-start
-end
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion29.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion29.txt
deleted file mode 100644
index c082ce44b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion29.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Code completion in completionvalues1.xml for <item name="gr^">:
-android:gravity : Specifies how to place the content of an object, both on the x- and y-axis, within the object itself. [flag]
-android:groupIndicator : Indicator shown beside the group View. [reference]
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion30.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion30.txt
deleted file mode 100644
index efee2bcf5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion30.txt
+++ /dev/null
@@ -1,8 +0,0 @@
-Code completion in completionvalues1.xml for <item name="an^">:
-android:
-android:animateFirstView : Defines whether to animate the current View when the ViewAnimation is first displayed. [boolean]
-android:animateLayoutChanges : Defines whether changes in layout (caused by adding and removing items) should cause a LayoutTransition to run. [boolean]
-android:animateOnClick : Indicates whether the drawer should be opened/closed with an animation when the user clicks the handle. [boolean]
-android:animationCache : Defines whether layout animations should create a drawing cache for their children. [boolean]
-android:animationDuration : Sets how long a transition animation should run (in milliseconds) when layout has changed. [integer]
-android:animationResolution : Timeout between frames of animation in milliseconds * Deprecated: Not used by the framework. [integer]
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion31.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion31.txt
deleted file mode 100644
index 90441643c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion31.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-Code completion in completionvalues1.xml for <item ^></item>:
-name : The mandatory name used in referring to this item.
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion32.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion32.txt
deleted file mode 100644
index 57684d7ce..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion32.txt
+++ /dev/null
@@ -1,317 +0,0 @@
-Code completion in completionvalues1.xml for <item name="^"></item>:
-android:
-android:addStatesFromChildren : Sets whether this ViewGroup's drawable states also include its children's drawable states. [boolean]
-android:adjustViewBounds : Set this to true if you want the ImageView to adjust its bounds to preserve the aspect ratio of its drawable. [boolean]
-android:alignmentMode : When set to alignMargins, causes alignment to take place between the outer boundary of a view, as defined by its margins. [enum]
-android:allowSingleTap : Indicates whether the drawer can be opened/closed by a single tap on the handle. [boolean]
-android:alpha : alpha property of the view, as a value between 0 (completely transparent) and 1 (completely opaque). [float]
-android:alwaysDrawnWithCache : Defines whether the ViewGroup should always draw its children using their drawing cache or not. [boolean]
-android:animateFirstView : Defines whether to animate the current View when the ViewAnimation is first displayed. [boolean]
-android:animateLayoutChanges : Defines whether changes in layout (caused by adding and removing items) should cause a LayoutTransition to run. [boolean]
-android:animateOnClick : Indicates whether the drawer should be opened/closed with an animation when the user clicks the handle. [boolean]
-android:animationCache : Defines whether layout animations should create a drawing cache for their children. [boolean]
-android:animationDuration : Sets how long a transition animation should run (in milliseconds) when layout has changed. [integer]
-android:animationResolution : Timeout between frames of animation in milliseconds * Deprecated: Not used by the framework. [integer]
-android:autoLink : Controls whether links such as urls and email addresses are automatically found and converted to clickable links. [flag]
-android:autoStart : When true, automatically start animating [boolean]
-android:autoText : If set, specifies that this TextView has a textual input method and automatically corrects some common spelling errors. * Deprecated: Use inputType instead. [boolean]
-android:background : A drawable to use as the background. [color, reference]
-android:baseline : The offset of the baseline within this view. [dimension]
-android:baselineAlignBottom : If true, the image view will be baseline aligned with based on its bottom edge. [boolean]
-android:baselineAligned : When set to false, prevents the layout from aligning its children's baselines. [boolean]
-android:baselineAlignedChildIndex : When a linear layout is part of another layout that is baseline aligned, it can specify which of its children to baseline align to (that is, which child TextView). [integer]
-android:bottomOffset : Extra offset for the handle at the bottom of the SlidingDrawer. [dimension]
-android:bufferType : Determines the minimum type that getText() will return. [enum]
-android:button : Drawable used for the button graphic (e.g. checkbox, radio button, etc). [reference]
-android:cacheColorHint : Indicates that this list will always be drawn on top of solid, single-color opaque background. [color]
-android:calendarViewShown : Whether the calendar view is shown. [boolean]
-android:capitalize : If set, specifies that this TextView has a textual input method and should automatically capitalize what the user types. * Deprecated: Use inputType instead. [enum]
-android:checkMark : Drawable used for the check mark graphic. [reference]
-android:checked : Indicates the initial checked state of this button. [boolean]
-android:checkedButton : The id of the child radio button that should be checked by default within this radio group. [integer]
-android:childDivider : Drawable or color that is used as a divider for children. [color, reference]
-android:childIndicator : Indicator shown beside the child View. [reference]
-android:childIndicatorLeft : The left bound for a child's indicator. [dimension]
-android:childIndicatorRight : The right bound for a child's indicator. [dimension]
-android:choiceMode : Defines the choice behavior for the view. [enum]
-class : Supply the name of the view class to instantiate
-android:clickColor : Color of the outline of click feedback. [color]
-android:clickable : Defines whether this view reacts to click events. [boolean]
-android:clipChildren : Defines whether a child is limited to draw inside of its bounds or not. [boolean]
-android:clipToPadding : Defines whether the ViewGroup will clip its drawing surface so as to exclude the padding area. [boolean]
-android:collapseColumns : The zero-based index of the columns to collapse. [string]
-android:columnCount : The maxmimum number of columns to create when automatically positioning children. [integer]
-android:columnOrderPreserved : When set to true, forces column boundaries to appear in the same order as column indices. [boolean]
-android:columnWidth : Specifies the fixed width for each column. [dimension]
-android:completionHint : Defines the hint displayed in the drop down menu. [string]
-android:completionHintView : Defines the hint view displayed in the drop down menu. [reference]
-android:completionThreshold : Defines the number of characters that the user must type before completion suggestions are displayed in a drop down menu. [integer]
-android:content : Identifier for the child that represents the drawer's content. [reference]
-android:contentDescription : Defines text that briefly describes content of the view. [string]
-android:cropToPadding : If true, the image will be cropped to fit within its padding. [boolean]
-android:cursorVisible : Makes the cursor visible (the default) or invisible. [boolean]
-android:dateTextAppearance : The text appearance for the calendar dates. [reference]
-android:descendantFocusability : Defines the relationship between the ViewGroup and its descendants when looking for a View to take focus. [enum]
-android:dial : [reference]
-android:digits : If set, specifies that this TextView has a numeric input method and that these specific characters are the ones that it will accept. [string]
-android:disableChildrenWhenDisabled : Whether this spinner should mark child views as enabled/disabled when the spinner itself is enabled/disabled. [boolean]
-android:disabledAlpha : The alpha to apply to the indicator when disabled. [float]
-android:divider : Drawable to use as a vertical divider between buttons.
-android:dividerHeight : Height of the divider. [dimension]
-android:dividerPadding : Size of padding on either end of a divider. [dimension]
-android:drawSelectorOnTop : When set to true, the selector will be drawn over the selected item. [boolean]
-android:drawableBottom : The drawable to be drawn below the text. [color, reference]
-android:drawableEnd : The drawable to be drawn to the end of the text. [color, reference]
-android:drawableLeft : The drawable to be drawn to the left of the text. [color, reference]
-android:drawablePadding : The padding between the drawables and the text. [dimension]
-android:drawableRight : The drawable to be drawn to the right of the text. [color, reference]
-android:drawableStart : The drawable to be drawn to the start of the text. [color, reference]
-android:drawableTop : The drawable to be drawn above the text. [color, reference]
-android:drawingCacheQuality : Defines the quality of translucent drawing caches. [enum]
-android:dropDownAnchor : View to anchor the auto-complete dropdown to. [reference]
-android:dropDownHeight : Specifies the basic height of the dropdown. [dimension, enum]
-android:dropDownHorizontalOffset : Horizontal offset from the spinner widget for positioning the dropdown in spinnerMode="dropdown". [dimension]
-android:dropDownSelector : List selector to use for spinnerMode="dropdown" display. [color, reference]
-android:dropDownVerticalOffset : Vertical offset from the spinner widget for positioning the dropdown in spinnerMode="dropdown". [dimension]
-android:dropDownWidth : Width of the dropdown in spinnerMode="dropdown". [dimension, enum]
-android:duplicateParentState : When this attribute is set to true, the view gets its drawable state (focused, pressed, etc.) from its direct parent rather than from itself. [boolean]
-android:editable : If set, specifies that this TextView has an input method. * Deprecated: Use inputType instead. [boolean]
-android:editorExtras : Reference to an "input-extras" XML resource containing additional data to supply to an input method, which is private to the implementation of the input method. [reference]
-android:ellipsize : If set, causes words that are longer than the view is wide to be ellipsized instead of broken in the middle. [enum]
-android:ems : Makes the TextView be exactly this many ems wide. [integer]
-android:enabled : Specifies whether the widget is enabled. [boolean]
-android:endYear : The last year (inclusive), for example "2010". * Deprecated: Use maxDate instead. [integer]
-android:entries : Reference to an array resource that will populate the Spinner. [reference]
-android:eventsInterceptionEnabled : Defines whether the overlay should intercept the motion events when a gesture is recognized. [boolean]
-android:fadeDuration : Duration, in milliseconds, of the fade out effect after the user is done drawing a gesture. [integer]
-android:fadeEnabled : Defines whether the gesture will automatically fade out after being recognized. [boolean]
-android:fadeOffset : Time, in milliseconds, to wait before the gesture fades out after the user is done drawing it. [integer]
-android:fadeScrollbars : Defines whether to fade out scrollbars when they are not in use. [boolean]
-android:fadingEdge : This attribute is deprecated and will be ignored as of API level 14 (ICE_CREAM_SANDWICH). [flag]
-android:fadingEdgeLength : Defines the length of the fading edges. [dimension]
-android:fastScrollAlwaysVisible : When set to true, the list will always show the fast scroll interface. [boolean]
-android:fastScrollEnabled : Enables the fast scroll thumb that can be dragged to quickly scroll through the list. [boolean]
-android:fillViewport : Defines whether the scrollview should stretch its content to fill the viewport. [boolean]
-android:filterTouchesWhenObscured : Specifies whether to filter touches when the view's window is obscured by another visible window. [boolean]
-android:firstDayOfWeek : The first day of week according to java.util.Calendar. [integer]
-android:fitsSystemWindows : Boolean internal attribute to adjust view layout based on system windows such as the status bar. [boolean]
-android:flipInterval : [integer]
-android:focusable : Boolean that controls whether a view can take focus. [boolean]
-android:focusableInTouchMode : Boolean that controls whether a view can take focus while in touch mode. [boolean]
-android:focusedMonthDateColor : The color for the dates of the focused month. [color, reference]
-android:fontFamily : Font family (named by string) for the text. [string]
-android:footerDividersEnabled : When set to false, the ListView will not draw the divider before each footer view. [boolean]
-android:foreground : Defines the drawable to draw over the content. [color, reference]
-android:foregroundGravity : Defines the gravity to apply to the foreground drawable. [flag]
-android:foregroundInsidePadding : Defines whether the foreground drawable should be drawn inside the padding. [boolean]
-android:format : Format string: if specified, the Chronometer will display this string, with the first "%s" replaced by the current timer value in "MM:SS" or "H:MM:SS" form. [string]
-android:freezesText : If set, the text view will include its current complete text inside of its frozen icicle in addition to meta-data such as the current cursor position. [boolean]
-android:gestureColor : Color used to draw a gesture. [color]
-android:gestureStrokeAngleThreshold : Minimum curve angle a stroke must contain before it is recognized as a gesture. [float]
-android:gestureStrokeLengthThreshold : Minimum length of a stroke before it is recognized as a gesture. [float]
-android:gestureStrokeSquarenessThreshold : Squareness threshold of a stroke before it is recognized as a gesture. [float]
-android:gestureStrokeType : Defines the type of strokes that define a gesture. [enum]
-android:gestureStrokeWidth : Width of the stroke used to draw the gesture. [float]
-android:gravity : Specifies how to place the content of an object, both on the x- and y-axis, within the object itself. [flag]
-android:groupIndicator : Indicator shown beside the group View. [reference]
-android:hand_hour : [reference]
-android:hand_minute : [reference]
-android:handle : Identifier for the child that represents the drawer's handle. [reference]
-android:hapticFeedbackEnabled : Boolean that controls whether a view should have haptic feedback enabled for events such as long presses. [boolean]
-android:headerDividersEnabled : When set to false, the ListView will not draw the divider after each header view. [boolean]
-android:height : Makes the TextView be exactly this many pixels tall. [dimension]
-android:hint : Hint text to display when the text is empty. [string]
-android:horizontalSpacing : Defines the default horizontal spacing between columns. [dimension]
-android:iconifiedByDefault : The default state of the SearchView. [boolean]
-android:id : Supply an identifier name for the top-level view, to later retrieve it with View.findViewById() or Activity.findViewById(). [reference]
-android:ignoreGravity : Indicates what view should not be affected by gravity. [reference]
-android:imeActionId : Supply a value for EditorInfo.actionId used when an input method is connected to the text view. [integer]
-android:imeActionLabel : Supply a value for EditorInfo.actionLabel used when an input method is connected to the text view. [string]
-android:imeOptions : Additional features you can enable in an IME associated with an editor to improve the integration with your application. [flag]
-android:importantForAccessibility : Controls how this View is important for accessibility which is if it fires accessibility events and if it is reported to accessibility services that query the screen. [integer, enum]
-android:inAnimation : Identifier for the animation to use when a view is shown. [reference]
-android:includeFontPadding : Leave enough room for ascenders and descenders instead of using the font ascent and descent strictly. [boolean]
-android:indeterminate : Allows to enable the indeterminate mode. [boolean]
-android:indeterminateBehavior : Defines how the indeterminate mode should behave when the progress reaches max. [enum]
-android:indeterminateDrawable : Drawable used for the indeterminate mode. [reference]
-android:indeterminateDuration : Duration of the indeterminate animation. [integer]
-android:indeterminateOnly : Restricts to ONLY indeterminate mode (state-keeping progress mode will not work). [boolean]
-android:indicatorLeft : The left bound for an item's indicator. [dimension]
-android:indicatorRight : The right bound for an item's indicator. [dimension]
-android:inflatedId : Overrides the id of the inflated View with this value. [reference]
-android:inputMethod : If set, specifies that this TextView should use the specified input method (specified by fully-qualified class name). * Deprecated: Use inputType instead. [string]
-android:inputType : The type of data being placed in a text field, used to help an input method decide how to let the user enter text. [flag]
-android:interpolator : [reference]
-android:isIndicator : Whether this rating bar is an indicator (and non-changeable by the user). [boolean]
-android:isScrollContainer : Set this if the view will serve as a scrolling container, meaing that it can be resized to shrink its overall window so that there will be space for an input method. [boolean]
-android:keepScreenOn : Controls whether the view's window should keep the screen on while visible. [boolean]
-android:layerType : Specifies the type of layer backing this view. [enum]
-layout : [reference]. * Required.
-android:layoutAnimation : Defines the layout animation to use the first time the ViewGroup is laid out. [reference]
-android:layoutDirection : Defines the direction of layout drawing. [enum]
-android:lineSpacingExtra : Extra spacing between lines of text. [dimension]
-android:lineSpacingMultiplier : Extra spacing between lines of text, as a multiplier. [float]
-android:lines : Makes the TextView be exactly this many lines tall. [integer]
-android:linksClickable : If set to false, keeps the movement method from being set to the link movement method even if autoLink causes links to be found. [boolean]
-android:listSelector : Drawable used to indicate the currently selected item in the list. [color, reference]
-android:longClickable : Defines whether this view reacts to long click events. [boolean]
-android:loopViews : Defines whether the animator loops to the first view once it has reached the end of the list. [boolean]
-android:marqueeRepeatLimit : The number of times to repeat the marquee animation. [integer, enum]
-android:max : Defines the maximum value the progress can take. [integer]
-android:maxDate : The minimal date shown by this calendar view in mm/dd/yyyy format. [string]
-android:maxEms : Makes the TextView be at most this many ems wide. [integer]
-android:maxHeight : An optional argument to supply a maximum height for this view. [dimension]
-android:maxLength : Set an input filter to constrain the text length to the specified number. [integer]
-android:maxLines : Makes the TextView be at most this many lines tall. [integer]
-android:maxWidth : An optional argument to supply a maximum width for this view. [dimension]
-android:measureAllChildren : Determines whether to measure all children or just those in the VISIBLE or INVISIBLE state when measuring. [boolean]
-android:measureWithLargestChild : When set to true, all children with a weight will be considered having the minimum size of the largest child. [boolean]
-android:minDate : The minimal date shown by this calendar view in mm/dd/yyyy format. [string]
-android:minEms : Makes the TextView be at least this many ems wide. [integer]
-android:minHeight : Defines the minimum height of the view.
-android:minLines : Makes the TextView be at least this many lines tall. [integer]
-android:minWidth : Defines the minimum width of the view.
-android:mode : [enum]
-android:name : Supply the name of the fragment class to instantiate.
-android:nextFocusDown : Defines the next view to give focus to when the next focus is FOCUS_DOWN If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a java.lang.RuntimeException will result when the reference is accessed. [reference]
-android:nextFocusForward : Defines the next view to give focus to when the next focus is FOCUS_FORWARD If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a java.lang.RuntimeException will result when the reference is accessed. [reference]
-android:nextFocusLeft : Defines the next view to give focus to when the next focus is FOCUS_LEFT. [reference]
-android:nextFocusRight : Defines the next view to give focus to when the next focus is FOCUS_RIGHT If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a java.lang.RuntimeException will result when the reference is accessed. [reference]
-android:nextFocusUp : Defines the next view to give focus to when the next focus is FOCUS_UP If the reference refers to a view that does not exist or is part of a hierarchy that is invisible, a java.lang.RuntimeException will result when the reference is accessed. [reference]
-android:numColumns : Defines how many columns to show. [integer, enum]
-android:numStars : The number of stars (or rating items) to show. [integer]
-android:numeric : If set, specifies that this TextView has a numeric input method. * Deprecated: Use inputType instead. [flag]
-android:onClick : Name of the method in this View's context to invoke when the view is clicked. [string]
-android:orientation : Should the layout be a column or a row? Use "horizontal" for a row, "vertical" for a column. [enum]
-android:outAnimation : Identifier for the animation to use when a view is hidden. [reference]
-android:overScrollFooter : Drawable to draw below list content. [color, reference]
-android:overScrollHeader : Drawable to draw above list content. [color, reference]
-android:overScrollMode : Defines over-scrolling behavior. [enum]
-android:padding : Sets the padding, in pixels, of all four edges. [dimension]
-android:paddingBottom : Sets the padding, in pixels, of the bottom edge; see padding. [dimension]
-android:paddingEnd : Sets the padding, in pixels, of the end edge; see padding. [dimension]
-android:paddingLeft : Sets the padding, in pixels, of the left edge; see padding. [dimension]
-android:paddingRight : Sets the padding, in pixels, of the right edge; see padding. [dimension]
-android:paddingStart : Sets the padding, in pixels, of the start edge; see padding. [dimension]
-android:paddingTop : Sets the padding, in pixels, of the top edge; see padding. [dimension]
-android:password : Whether the characters of the field are displayed as password dots instead of themselves. * Deprecated: Use inputType instead. [boolean]
-android:persistentDrawingCache : Defines the persistence of the drawing cache. [flag]
-android:phoneNumber : If set, specifies that this TextView has a phone number input method. * Deprecated: Use inputType instead. [boolean]
-android:popupBackground : Background drawable to use for the dropdown in spinnerMode="dropdown". [color, reference]
-android:popupPromptView : Reference to a layout to use for displaying a prompt in the dropdown for spinnerMode="dropdown". [reference]
-android:privateImeOptions : An addition content type description to supply to the input method attached to the text view, which is private to the implementation of the input method. [string]
-android:progress : Defines the default progress value, between 0 and max. [integer]
-android:progressDrawable : Drawable used for the progress mode. [reference]
-android:prompt : The prompt to display when the spinner's dialog is shown. [reference]
-android:queryHint : An optional query hint string to be displayed in the empty query field. [string]
-android:quickContactWindowSize : [enum]
-android:rating : The rating to set by default. [float]
-android:requiresFadingEdge : Defines which edges should be faded on scrolling. [flag]
-android:resOutColor : Color of the res-out outline. [color]
-android:rotation : rotation of the view, in degrees. [float]
-android:rotationX : rotation of the view around the x axis, in degrees. [float]
-android:rotationY : rotation of the view around the y axis, in degrees. [float]
-android:rowCount : The maxmimum number of rows to create when automatically positioning children. [integer]
-android:rowOrderPreserved : When set to true, forces row boundaries to appear in the same order as row indices. [boolean]
-android:saveEnabled : If unset, no state will be saved for this view when it is being frozen. [boolean]
-android:scaleType : Controls how the image should be resized or moved to match the size of this ImageView. [enum]
-android:scaleX : scale of the view in the x direction. [float]
-android:scaleY : scale of the view in the y direction. [float]
-android:scrollHorizontally : Whether the text is allowed to be wider than the view (and therefore can be scrolled horizontally). [boolean]
-android:scrollX : The initial horizontal scroll offset, in pixels. [dimension]
-android:scrollY : The initial vertical scroll offset, in pixels. [dimension]
-android:scrollbarAlwaysDrawHorizontalTrack : Defines whether the horizontal scrollbar track should always be drawn. [boolean]
-android:scrollbarAlwaysDrawVerticalTrack : Defines whether the vertical scrollbar track should always be drawn. [boolean]
-android:scrollbarDefaultDelayBeforeFade : Defines the delay in milliseconds that a scrollbar waits before fade out. [integer]
-android:scrollbarFadeDuration : Defines the delay in milliseconds that a scrollbar takes to fade out. [integer]
-android:scrollbarSize : Sets the width of vertical scrollbars and height of horizontal scrollbars. [dimension]
-android:scrollbarStyle : Controls the scrollbar style and position. [enum]
-android:scrollbarThumbHorizontal : Defines the horizontal scrollbar thumb drawable. [reference]
-android:scrollbarThumbVertical : Defines the vertical scrollbar thumb drawable. [reference]
-android:scrollbarTrackHorizontal : Defines the horizontal scrollbar track drawable. [reference]
-android:scrollbarTrackVertical : Defines the vertical scrollbar track drawable. [reference]
-android:scrollbars : Defines which scrollbars should be displayed on scrolling or not. [flag]
-android:scrollingCache : When set to true, the list uses a drawing cache during scrolling. [boolean]
-android:secondaryProgress : Defines the secondary progress value, between 0 and max. [integer]
-android:selectAllOnFocus : If the text is selectable, select it all when the view takes focus. [boolean]
-android:selectedDateVerticalBar : Drawable for the vertical bar shown at the beginning and at the end of the selected date. [reference]
-android:selectedWeekBackgroundColor : The background color for the selected week. [color, reference]
-android:shadowColor : Place a shadow of the specified color behind the text. [color]
-android:shadowDx : Horizontal offset of the shadow. [float]
-android:shadowDy : Vertical offset of the shadow. [float]
-android:shadowRadius : Radius of the shadow. [float]
-android:showDividers : Setting for which dividers to show. [flag]
-android:showWeekNumber : Whether do show week numbers. [boolean]
-android:shownWeekCount : The number of weeks to be shown. [integer]
-android:shrinkColumns : The zero-based index of the columns to shrink. [string]
-android:singleLine : Constrains the text to a single horizontally scrolling line instead of letting it wrap onto multiple lines, and advances focus instead of inserting a newline when you press the enter key. * Deprecated: This attribute is deprecated. Use "maxLines" instead to change the layo...
-android:smoothScrollbar : When set to true, the list will use a more refined calculation method based on the pixels height of the items visible on screen. [boolean]
-android:soundEffectsEnabled : Boolean that controls whether a view should have sound effects enabled for events such as clicking and touching. [boolean]
-android:spacing : [dimension]
-android:spinnerMode : Display mode for spinner options. [enum]
-android:spinnersShown : Whether the spinners are shown. [boolean]
-android:splitMotionEvents : Sets whether this ViewGroup should split MotionEvents to separate child views during touch event dispatch. [boolean]
-android:src : Sets a drawable as the content of this ImageView. [color, reference]
-android:stackFromBottom : Used by ListView and GridView to stack their content from the bottom. [boolean]
-android:startYear : The first year (inclusive), for example "1940". * Deprecated: Use minDate instead. [integer]
-android:stepSize : The step size of the rating. [float]
-android:stretchColumns : The zero-based index of the columns to stretch. [string]
-android:stretchMode : Defines how columns should stretch to fill the available empty space, if any. [enum]
-style : A reference to a custom style [reference]
-android:switchMinWidth : Minimum width for the switch component [dimension]
-android:switchPadding : Minimum space between the switch and caption text [dimension]
-android:switchTextAppearance : TextAppearance style for text displayed on the switch thumb. [reference]
-android:tabLayout : Layout used to organize each tab's content. [reference]
-android:tabStripEnabled : Determines whether the strip under the tab indicators is drawn or not. [boolean]
-android:tabStripLeft : Drawable used to draw the left part of the strip underneath the tabs. [reference]
-android:tabStripRight : Drawable used to draw the right part of the strip underneath the tabs. [reference]
-android:tag : Supply a tag for the top-level view containing a String, to be retrieved later with View.getTag() or searched for with View.findViewWithTag() . [string]
-android:text : Text to display. [string]
-android:textAlignment : Alignment of the text. [integer, enum]
-android:textAllCaps : Present the text in ALL CAPS. [boolean]
-android:textAppearance : Base text color, typeface, size, and style. [reference]
-android:textColor : Text color. [color, reference]
-android:textColorHighlight : Color of the text selection highlight. [color, reference]
-android:textColorHint : Color of the hint text. [color, reference]
-android:textColorLink : Text color for links. [color, reference]
-android:textCursorDrawable : Reference to a drawable that will be drawn under the insertion cursor. [reference]
-android:textDirection : Direction of the text. [integer, enum]
-android:textEditNoPasteWindowLayout : Variation of textEditPasteWindowLayout displayed when the clipboard is empty. [reference]
-android:textEditPasteWindowLayout : The layout of the view that is displayed on top of the cursor to paste inside a TextEdit field. [reference]
-android:textEditSideNoPasteWindowLayout : Variation of textEditSidePasteWindowLayout displayed when the clipboard is empty. [reference]
-android:textEditSidePasteWindowLayout : Used instead of textEditPasteWindowLayout when the window is moved on the side of the insertion cursor because it would be clipped if it were positioned on top. [reference]
-android:textEditSuggestionItemLayout : Layout of the TextView item that will populate the suggestion popup window. [reference]
-android:textFilterEnabled : When set to true, the list will filter results as the user types. [boolean]
-android:textIsSelectable : Indicates that the content of a non-editable text can be selected. [boolean]
-android:textOff : The text for the button when it is not checked. [string]
-android:textOn : The text for the button when it is checked. [string]
-android:textScaleX : Sets the horizontal scaling factor for the text. [float]
-android:textSelectHandle : Reference to a drawable that will be used to display a text selection anchor for positioning the cursor within text. [reference]
-android:textSelectHandleLeft : Reference to a drawable that will be used to display a text selection anchor on the left side of a selection region. [reference]
-android:textSelectHandleRight : Reference to a drawable that will be used to display a text selection anchor on the right side of a selection region. [reference]
-android:textSize : Size of the text. [dimension]
-android:textStyle : Style (bold, italic, bolditalic) for the text. [flag]
-android:thumb : Drawable to use as the "thumb" that switches back and forth. [reference]
-android:thumbOffset : An offset for the thumb that allows it to extend out of the range of the track. [dimension]
-android:thumbTextPadding : Amount of padding on either side of text within the switch thumb. [dimension]
-android:tint : Set a tinting color for the image. [color]
-android:topOffset : Extra offset for the handle at the top of the SlidingDrawer. [dimension]
-android:track : Drawable to use as the "track" that the switch thumb slides within. [reference]
-android:transcriptMode : Sets the transcript mode for the list. [enum]
-android:transformPivotX : x location of the pivot point around which the view will rotate and scale. [dimension]
-android:transformPivotY : y location of the pivot point around which the view will rotate and scale. [dimension]
-android:translationX : translation in x of the view. [dimension]
-android:translationY : translation in y of the view. [dimension]
-android:typeface : Typeface (normal, sans, serif, monospace) for the text. [enum]
-android:uncertainGestureColor : Color used to draw the user's strokes until we are sure it's a gesture. [color]
-android:unfocusedMonthDateColor : The color for the dates of an unfocused month. [color, reference]
-android:unselectedAlpha : Sets the alpha on the items that are not selected. [float]
-android:useDefaultMargins : When set to true, tells GridLayout to use default margins when none are specified in a view's layout parameters. [boolean]
-android:verticalScrollbarPosition : Determines which side the vertical scroll bar should be placed on. [enum]
-android:verticalSpacing : Defines the default vertical spacing between rows. [dimension]
-android:visibility : Controls the initial visibility of the view. [enum]
-android:weekDayTextAppearance : The text appearance for the week day abbreviation of the calendar header. [reference]
-android:weekNumberColor : The color for the week numbers. [color, reference]
-android:weekSeparatorLineColor : The color for the separator line between weeks. [color, reference]
-android:weightSum : Defines the maximum weight sum. [float]
-android:width : Makes the TextView be exactly this many pixels wide. [dimension]
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion33.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion33.txt
deleted file mode 100644
index f9c008d25..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion33.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Code completion in completionvalues1.xml for <item name="android:allowSingleTap">^</item>:
-true
-false
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion34.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion34.txt
deleted file mode 100644
index 861a41334..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion34.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Code completion in completionvalues1.xml for <item name="android:alwaysDrawnWithCache">^ false </item>:
-true
-false
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion35.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion35.txt
deleted file mode 100644
index 25e8a0b1d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion35.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Code completion in completionvalues1.xml for <item name="android:alwaysDrawnWithCache"> ^false </item>:
-true
-false
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion36.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion36.txt
deleted file mode 100644
index d85133f57..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion36.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-Code completion in completionvalues1.xml for <item name="android:alwaysDrawnWithCache"> f^alse </item>:
-false
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion37.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion37.txt
deleted file mode 100644
index 1d4135106..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion37.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-Code completion in completionvalues1.xml for <item name="android:orientation">h^</item>:
-horizontal
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion38.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion38.txt
deleted file mode 100644
index 8819bcd39..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion38.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-Code completion in completionvalues1.xml for c^:
-center_vertical
-center_horizontal
-center
-clip_vertical
-clip_horizontal
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion66.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion66.txt
deleted file mode 100644
index 4f29a8b71..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion66.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-Code completion in completionvalues1.xml for 17[^sp]:
-17dp : <b>Density-independent Pixels</b> - an abstract unit that is based on the physical density of the screen.
-17sp : <b>Scale-independent Pixels</b> - this is like the dp unit, but it is also scaled by the user's font size preference.
-17pt : <b>Points</b> - 1/72 of an inch based on the physical size of the screen.
-17mm : <b>Millimeters</b> - based on the physical size of the screen.
-17in : <b>Inches</b> - based on the physical size of the screen.
-17px : <b>Pixels</b> - corresponds to actual pixels on the screen. Not recommended.
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion67.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion67.txt
deleted file mode 100644
index 4f29a8b71..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion67.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-Code completion in completionvalues1.xml for 17[^sp]:
-17dp : <b>Density-independent Pixels</b> - an abstract unit that is based on the physical density of the screen.
-17sp : <b>Scale-independent Pixels</b> - this is like the dp unit, but it is also scaled by the user's font size preference.
-17pt : <b>Points</b> - 1/72 of an inch based on the physical size of the screen.
-17mm : <b>Millimeters</b> - based on the physical size of the screen.
-17in : <b>Inches</b> - based on the physical size of the screen.
-17px : <b>Pixels</b> - corresponds to actual pixels on the screen. Not recommended.
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion68.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion68.txt
deleted file mode 100644
index 5aa1d43c1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1-expected-completion68.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Code completion in completionvalues1.xml for [^false]:
-true
-false
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1.xml
deleted file mode 100644
index 89b5f4609..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues1.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources xmlns:android="http://schemas.android.com/apk/res/android">
- <style name="stylename">
- <item name="android:textSize">17sp</item>
- <item name="android:textColor">@color/title_color</item>
- <item name="android:shadowColor">@an</item>
- <item name="android:gravity"> </item>
- <item name="gr">@color/title_color</item>
- <item name="an">@color/title_color</item>
- <item ></item>
- <item name=""></item>
- <item name="android:allowSingleTap"></item>
- <item name="android:alwaysDrawnWithCache"> false </item>
- <item name="android:orientation">h</item>
- <item name="android:gravity">
- c
- </item>
- </style>
-</resources>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues2-expected-applyCompletion45.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues2-expected-applyCompletion45.diff
deleted file mode 100644
index 649866860..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues2-expected-applyCompletion45.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in completionvalues2.xml for @string/^app_name selecting @string/hello:
-< <item name="main_layout5" type="string">@string/^app_name</item>
----
-> <item name="main_layout5" type="string">@string/hello^</item>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues2-expected-completion70.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues2-expected-completion70.txt
deleted file mode 100644
index 20f8a7442..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues2-expected-completion70.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Code completion in completionvalues2.xml for <item name="main_layout4" type="layout">^</item>:
-@android:
-@layout/
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues2-expected-completion71.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues2-expected-completion71.txt
deleted file mode 100644
index c491feabe..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues2-expected-completion71.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-Code completion in completionvalues2.xml for <item name="main_layout5" type="string">@string/^app_name</item>:
-@string/app_name
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues2.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues2.xml
deleted file mode 100644
index 293abc01a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/completionvalues2.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
- <item name="main_layout" type="layout">@layout/main2</item>
- <item name="main_layout2" type="layout"> @layout/main_layout </item>
- <item name="main_layout3" type="layout"> </item>
- <item name="main_layout4" type="layout"></item>
- <item name="main_layout5" type="string">@string/app_name</item>
-</resources>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable1-expected-completion47.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable1-expected-completion47.txt
deleted file mode 100644
index c7f495b1b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable1-expected-completion47.txt
+++ /dev/null
@@ -1,12 +0,0 @@
-Code completion in drawable1.xml for ^<layer-list:
-<animation-list /> : Drawable used to render several animated frames.
-<bitmap /> : Drawable used to draw bitmaps.
-<clip />
-<color /> : Drawable used to draw a single color.
-<inset />
-<layer-list ></layer-list> : Drawable used to render several drawables stacked on top of each other.
-<nine-patch /> : Drawable used to draw 9-patches.
-<rotate /> : Drawable used to rotate another drawable.
-<scale />
-<selector ></selector> : Drawable used to render several states.
-<shape ></shape> : Drawable used to render a geometric shape, with a gradient or a solid color.
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable1-expected-completion48.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable1-expected-completion48.txt
deleted file mode 100644
index 024cdebe4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable1-expected-completion48.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Code completion in drawable1.xml for ^xmlns:android:
-android:opacity : Indicates the opacity of the layer. [enum]
-xmlns:android
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable1-expected-completion49.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable1-expected-completion49.txt
deleted file mode 100644
index 269fd86f0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable1-expected-completion49.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-Code completion in drawable1.xml for <item ^></item>:
-android:left : Left coordinate of the layer. [dimension]
-android:top : Top coordinate of the layer. [dimension]
-android:right : Right coordinate of the layer. [dimension]
-android:bottom : Bottom coordinate of the layer. [dimension]
-android:drawable : Drawable used to render the layer. [reference]
-android:id : Identifier of the layer. [reference]
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable1-expected-completion50.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable1-expected-completion50.txt
deleted file mode 100644
index d05bc768c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable1-expected-completion50.txt
+++ /dev/null
@@ -1,12 +0,0 @@
-Code completion in drawable1.xml for <item >^</item>:
-<animation-list /> : Drawable used to render several animated frames.
-<bitmap /> : Drawable used to draw bitmaps.
-<clip />
-<color /> : Drawable used to draw a single color.
-<inset />
-<layer-list ></layer-list> : Drawable used to render several drawables stacked on top of each other.
-<nine-patch /> : Drawable used to draw 9-patches.
-<rotate /> : Drawable used to rotate another drawable.
-<scale />
-<selector ></selector> : Drawable used to render several states.
-<shape ></shape> : Drawable used to render a geometric shape, with a gradient or a solid color.
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable1.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable1.xml
deleted file mode 100644
index 9513f1709..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable1.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<layer-list
- xmlns:android="http://schemas.android.com/apk/res/android">
- <item ></item>
-</layer-list>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable2-expected-completion51.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable2-expected-completion51.txt
deleted file mode 100644
index 438bd768c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable2-expected-completion51.txt
+++ /dev/null
@@ -1,10 +0,0 @@
-Code completion in drawable2.xml for ^android:innerRadiusRatio="2":
-android:visible : Indicates whether the drawable should intially be visible. [boolean]
-android:dither : Enables or disables dithering. [boolean]
-android:shape : Indicates what shape to fill with a gradient. [enum]
-android:innerRadiusRatio : Inner radius of the ring expressed as a ratio of the ring's width. [float]
-android:thicknessRatio : Thickness of the ring expressed as a ratio of the ring's width. [float]
-android:innerRadius : Inner radius of the ring. [dimension]
-android:thickness : Thickness of the ring. [dimension]
-android:useLevel : Indicates whether the drawable's level affects the way the gradient is drawn.
-xmlns:android
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable2-expected-completion52.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable2-expected-completion52.txt
deleted file mode 100644
index 2a2853363..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable2-expected-completion52.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-Code completion in drawable2.xml for ^<gradient:
-<corners /> : Describes the corners for the rectangle shape of a GradientDrawable.
-<gradient /> : Used to describe the gradient used to fill the shape of a GradientDrawable.
-<padding /> : Used to specify the optional padding of a GradientDrawable.
-<size /> : Used to specify the size of the shape for GradientDrawable.
-<solid /> : Used to fill the shape of GradientDrawable with a solid color.
-<stroke /> : Used to describe the optional stroke of a GradientDrawable.
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable2.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable2.xml
deleted file mode 100644
index c6a672fd8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/drawable2.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<shape xmlns:android="http://schemas.android.com/apk/res/android"
- android:innerRadiusRatio="2">
- <gradient />
-</shape>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/edithandling.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/edithandling.xml
deleted file mode 100644
index 0488fd6f1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/edithandling.xml
+++ /dev/null
@@ -1,3 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract1b.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract1b.diff
deleted file mode 100644
index e21c594d1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract1b.diff
+++ /dev/null
@@ -1,34 +0,0 @@
-@@ -2 +2
-- android:layout_width="wrap_content" android:layout_height="match_parent">
-- <Button android:text="Button"
-- android:layout_width="wrap_content" android:layout_height="wrap_content"
-- android:textColor="#FF0000" android:textSize="20pt"
-- android:id="@+id/button1" android:layout_alignParentBottom="true"></Button>
-- <Button android:text="Button"
-- android:layout_width="wrap_content" android:layout_height="fill_parent"
-- android:textColor="#FF00FF" android:textSize="20pt"
-- android:id="@+id/button2" android:layout_alignParentBottom="true"></Button>
-+ android:layout_width="wrap_content"
-+ android:layout_height="match_parent" >
-+
-+ <Button
-+ android:id="@+id/button1"
-+ android:layout_width="wrap_content"
-+ android:layout_height="wrap_content"
-+ android:layout_alignParentBottom="true"
-+ android:text="Button"
-+ android:textColor="#FF0000"
-+ android:textSize="20pt" >
-+ </Button>
-+
-+ <Button
-+ android:id="@+id/button2"
-+ style="@style/newstyle"
-+ android:layout_width="wrap_content"
-+ android:layout_height="fill_parent"
-+ android:layout_alignParentBottom="true"
-+ android:text="Button"
-+ android:textColor="#FF00FF"
-+ android:textSize="20pt" >
-+ </Button>
-+
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract1c.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract1c.diff
deleted file mode 100644
index 8c12b7cde..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract1c.diff
+++ /dev/null
@@ -1,31 +0,0 @@
-@@ -2 +2
-- android:layout_width="wrap_content" android:layout_height="match_parent">
-- <Button android:text="Button"
-- android:layout_width="wrap_content" android:layout_height="wrap_content"
-- android:textColor="#FF0000" android:textSize="20pt"
-- android:id="@+id/button1" android:layout_alignParentBottom="true"></Button>
-- <Button android:text="Button"
-- android:layout_width="wrap_content" android:layout_height="fill_parent"
-- android:textColor="#FF00FF" android:textSize="20pt"
-- android:id="@+id/button2" android:layout_alignParentBottom="true"></Button>
-+ android:layout_width="wrap_content"
-+ android:layout_height="match_parent" >
-+
-+ <Button
-+ android:id="@+id/button1"
-+ android:layout_width="wrap_content"
-+ android:layout_height="wrap_content"
-+ android:layout_alignParentBottom="true"
-+ android:text="Button"
-+ android:textColor="#FF0000"
-+ android:textSize="20pt" >
-+ </Button>
-+
-+ <Button
-+ android:id="@+id/button2"
-+ android:layout_width="wrap_content"
-+ android:layout_height="fill_parent"
-+ android:layout_alignParentBottom="true"
-+ android:text="Button" >
-+ </Button>
-+
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract1d.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract1d.diff
deleted file mode 100644
index c819b09aa..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract1d.diff
+++ /dev/null
@@ -1,32 +0,0 @@
-@@ -2 +2
-- android:layout_width="wrap_content" android:layout_height="match_parent">
-- <Button android:text="Button"
-- android:layout_width="wrap_content" android:layout_height="wrap_content"
-- android:textColor="#FF0000" android:textSize="20pt"
-- android:id="@+id/button1" android:layout_alignParentBottom="true"></Button>
-- <Button android:text="Button"
-- android:layout_width="wrap_content" android:layout_height="fill_parent"
-- android:textColor="#FF00FF" android:textSize="20pt"
-- android:id="@+id/button2" android:layout_alignParentBottom="true"></Button>
-+ android:layout_width="wrap_content"
-+ android:layout_height="match_parent" >
-+
-+ <Button
-+ android:id="@+id/button1"
-+ android:layout_width="wrap_content"
-+ android:layout_height="wrap_content"
-+ android:layout_alignParentBottom="true"
-+ android:text="Button"
-+ android:textColor="#FF0000"
-+ android:textSize="20pt" >
-+ </Button>
-+
-+ <Button
-+ android:id="@+id/button2"
-+ style="@style/newstyle"
-+ android:layout_width="wrap_content"
-+ android:layout_height="fill_parent"
-+ android:layout_alignParentBottom="true"
-+ android:text="Button" >
-+ </Button>
-+
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract2.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract2.diff
deleted file mode 100644
index c819b09aa..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract2.diff
+++ /dev/null
@@ -1,32 +0,0 @@
-@@ -2 +2
-- android:layout_width="wrap_content" android:layout_height="match_parent">
-- <Button android:text="Button"
-- android:layout_width="wrap_content" android:layout_height="wrap_content"
-- android:textColor="#FF0000" android:textSize="20pt"
-- android:id="@+id/button1" android:layout_alignParentBottom="true"></Button>
-- <Button android:text="Button"
-- android:layout_width="wrap_content" android:layout_height="fill_parent"
-- android:textColor="#FF00FF" android:textSize="20pt"
-- android:id="@+id/button2" android:layout_alignParentBottom="true"></Button>
-+ android:layout_width="wrap_content"
-+ android:layout_height="match_parent" >
-+
-+ <Button
-+ android:id="@+id/button1"
-+ android:layout_width="wrap_content"
-+ android:layout_height="wrap_content"
-+ android:layout_alignParentBottom="true"
-+ android:text="Button"
-+ android:textColor="#FF0000"
-+ android:textSize="20pt" >
-+ </Button>
-+
-+ <Button
-+ android:id="@+id/button2"
-+ style="@style/newstyle"
-+ android:layout_width="wrap_content"
-+ android:layout_height="fill_parent"
-+ android:layout_alignParentBottom="true"
-+ android:text="Button" >
-+ </Button>
-+
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract3.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract3.diff
deleted file mode 100644
index 36186b83f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract3.diff
+++ /dev/null
@@ -1,32 +0,0 @@
-@@ -2 +2
-- android:layout_width="wrap_content" android:layout_height="match_parent">
-- <Button android:text="Button"
-- android:layout_width="wrap_content" android:layout_height="wrap_content"
-- android:textColor="#FF0000" android:textSize="20pt"
-- android:id="@+id/button1" android:layout_alignParentBottom="true"></Button>
-- <Button android:text="Button"
-- android:layout_width="wrap_content" android:layout_height="fill_parent"
-- android:textColor="#FF00FF" android:textSize="20pt"
-- android:id="@+id/button2" android:layout_alignParentBottom="true"></Button>
-+ android:layout_width="wrap_content"
-+ android:layout_height="match_parent" >
-+
-+ <Button
-+ android:id="@+id/button1"
-+ style="@style/newstyle"
-+ android:layout_width="wrap_content"
-+ android:layout_height="wrap_content"
-+ android:layout_alignParentBottom="true"
-+ android:text="Button" >
-+ </Button>
-+
-+ <Button
-+ android:id="@+id/button2"
-+ style="@style/newstyle"
-+ android:layout_width="wrap_content"
-+ android:layout_height="fill_parent"
-+ android:layout_alignParentBottom="true"
-+ android:text="Button"
-+ android:textColor="#FF00FF" >
-+ </Button>
-+
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract4.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract4.diff
deleted file mode 100644
index 83837f57b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract4.diff
+++ /dev/null
@@ -1,33 +0,0 @@
-@@ -2 +2
-- android:layout_width="wrap_content" android:layout_height="match_parent">
-- <Button android:text="Button"
-- android:layout_width="wrap_content" android:layout_height="wrap_content"
-- android:textColor="#FF0000" android:textSize="20pt"
-- android:id="@+id/button1" android:layout_alignParentBottom="true"></Button>
-- <Button android:text="Button"
-- android:layout_width="wrap_content" android:layout_height="fill_parent"
-- android:textColor="#FF00FF" android:textSize="20pt"
-- android:id="@+id/button2" android:layout_alignParentBottom="true"></Button>
-+ android:layout_width="wrap_content"
-+ android:layout_height="match_parent" >
-+
-+ <Button
-+ android:id="@+id/button1"
-+ android:layout_width="wrap_content"
-+ android:layout_height="wrap_content"
-+ android:layout_alignParentBottom="true"
-+ android:text="Button"
-+ android:textColor="#FF0000"
-+ android:textSize="20pt" >
-+ </Button>
-+
-+ <Button
-+ android:id="@+id/button2"
-+ style="@style/newstyle"
-+ android:layout_width="wrap_content"
-+ android:layout_height="fill_parent"
-+ android:layout_alignParentBottom="true"
-+ android:text="Button"
-+ android:textSize="20pt" >
-+ </Button>
-+
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract5.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract5.diff
deleted file mode 100644
index 55d658ddd..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract5.diff
+++ /dev/null
@@ -1,33 +0,0 @@
-@@ -2 +2
-- android:layout_width="wrap_content" android:layout_height="match_parent">
-- <Button android:text="Button"
-- android:layout_width="wrap_content" android:layout_height="wrap_content"
-- android:textColor="#FF0000" android:textSize="20pt"
-- android:id="@+id/button1" android:layout_alignParentBottom="true"></Button>
-- <Button android:text="Button"
-- android:layout_width="wrap_content" android:layout_height="fill_parent"
-- android:textColor="#FF00FF" android:textSize="20pt"
-- android:id="@+id/button2" android:layout_alignParentBottom="true"></Button>
-+ android:layout_width="wrap_content"
-+ android:layout_height="match_parent" >
-+
-+ <Button
-+ android:id="@+id/button1"
-+ style="@style/newstyle"
-+ android:layout_width="wrap_content"
-+ android:layout_height="wrap_content"
-+ android:layout_alignParentBottom="true"
-+ android:text="Button"
-+ android:textColor="#FF0000" >
-+ </Button>
-+
-+ <Button
-+ android:id="@+id/button2"
-+ android:layout_width="wrap_content"
-+ android:layout_height="fill_parent"
-+ android:layout_alignParentBottom="true"
-+ android:text="Button"
-+ android:textColor="#FF00FF"
-+ android:textSize="20pt" >
-+ </Button>
-+
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract6.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract6.diff
deleted file mode 100644
index 1db5e3811..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract6.diff
+++ /dev/null
@@ -1,6 +0,0 @@
-< <Button android:text="Button"
-< android:layout_width="wrap_content" android:layout_height="wrap_content"
-< android:textColor="#FF0000" android:textSize="20pt"
-< android:id="@+id/button1" android:layout_alignParentBottom="true"></Button>
----
-> <Button style="@style/newstyle" android:id="@+id/button1" ></Button>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract8.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract8.diff
deleted file mode 100644
index 8c12b7cde..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1-expected-extract8.diff
+++ /dev/null
@@ -1,31 +0,0 @@
-@@ -2 +2
-- android:layout_width="wrap_content" android:layout_height="match_parent">
-- <Button android:text="Button"
-- android:layout_width="wrap_content" android:layout_height="wrap_content"
-- android:textColor="#FF0000" android:textSize="20pt"
-- android:id="@+id/button1" android:layout_alignParentBottom="true"></Button>
-- <Button android:text="Button"
-- android:layout_width="wrap_content" android:layout_height="fill_parent"
-- android:textColor="#FF00FF" android:textSize="20pt"
-- android:id="@+id/button2" android:layout_alignParentBottom="true"></Button>
-+ android:layout_width="wrap_content"
-+ android:layout_height="match_parent" >
-+
-+ <Button
-+ android:id="@+id/button1"
-+ android:layout_width="wrap_content"
-+ android:layout_height="wrap_content"
-+ android:layout_alignParentBottom="true"
-+ android:text="Button"
-+ android:textColor="#FF0000"
-+ android:textSize="20pt" >
-+ </Button>
-+
-+ <Button
-+ android:id="@+id/button2"
-+ android:layout_width="wrap_content"
-+ android:layout_height="fill_parent"
-+ android:layout_alignParentBottom="true"
-+ android:text="Button" >
-+ </Button>
-+
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1.info b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1.info
deleted file mode 100644
index 69f773989..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1.info
+++ /dev/null
@@ -1,3 +0,0 @@
-android.widget.LinearLayout [0,36,140,320] <LinearLayout>
- android.widget.Button [0,0,140,62] <Button>
- android.widget.Button [0,62,140,284] <Button>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1.xml
deleted file mode 100644
index 64c49b2c1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle1.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content" android:layout_height="match_parent">
- <Button android:text="Button"
- android:layout_width="wrap_content" android:layout_height="wrap_content"
- android:textColor="#FF0000" android:textSize="20pt"
- android:id="@+id/button1" android:layout_alignParentBottom="true"></Button>
- <Button android:text="Button"
- android:layout_width="wrap_content" android:layout_height="fill_parent"
- android:textColor="#FF00FF" android:textSize="20pt"
- android:id="@+id/button2" android:layout_alignParentBottom="true"></Button>
-</FrameLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle2-expected-extract7.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle2-expected-extract7.diff
deleted file mode 100644
index bb2960e48..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle2-expected-extract7.diff
+++ /dev/null
@@ -1,33 +0,0 @@
-@@ -2 +2
-- foo:layout_width="wrap_content" foo:layout_height="match_parent" foo:orientation="vertical">
-- <Button foo:text="Button"
-- foo:layout_width="wrap_content" foo:layout_height="wrap_content"
-- foo:textColor="#FF0000" foo:textSize="20pt"
-- foo:id="@+id/button1" foo:layout_alignParentBottom="true"></Button>
-- <Button foo:text="Button"
-- foo:layout_width="wrap_content" foo:layout_height="fill_parent"
-- foo:textColor="#00FF00" foo:textSize="20pt"
-- foo:id="@+id/button2" foo:layout_alignParentBottom="true"></Button>
-+ foo:layout_width="wrap_content"
-+ foo:layout_height="match_parent"
-+ foo:orientation="vertical" >
-+
-+ <Button
-+ foo:id="@+id/button1"
-+ style="@style/newstyle"
-+ foo:layout_width="wrap_content"
-+ foo:layout_height="wrap_content"
-+ foo:layout_alignParentBottom="true"
-+ foo:text="Button"
-+ foo:textColor="#FF0000" >
-+ </Button>
-+
-+ <Button
-+ foo:id="@+id/button2"
-+ style="@style/newstyle"
-+ foo:layout_width="wrap_content"
-+ foo:layout_height="fill_parent"
-+ foo:layout_alignParentBottom="true"
-+ foo:text="Button" >
-+ </Button>
-+
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle2.info b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle2.info
deleted file mode 100644
index 69f773989..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle2.info
+++ /dev/null
@@ -1,3 +0,0 @@
-android.widget.LinearLayout [0,36,140,320] <LinearLayout>
- android.widget.Button [0,0,140,62] <Button>
- android.widget.Button [0,62,140,284] <Button>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle2.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle2.xml
deleted file mode 100644
index 3cb966f30..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/extractstyle2.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<LinearLayout xmlns:foo="http://schemas.android.com/apk/res/android"
- foo:layout_width="wrap_content" foo:layout_height="match_parent" foo:orientation="vertical">
- <Button foo:text="Button"
- foo:layout_width="wrap_content" foo:layout_height="wrap_content"
- foo:textColor="#FF0000" foo:textSize="20pt"
- foo:id="@+id/button1" foo:layout_alignParentBottom="true"></Button>
- <Button foo:text="Button"
- foo:layout_width="wrap_content" foo:layout_height="fill_parent"
- foo:textColor="#00FF00" foo:textSize="20pt"
- foo:id="@+id/button2" foo:layout_alignParentBottom="true"></Button>
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/fragmentlayout-expected-applyCompletion47.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/fragmentlayout-expected-applyCompletion47.diff
deleted file mode 100644
index 3ed60f13d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/fragmentlayout-expected-applyCompletion47.diff
+++ /dev/null
@@ -1,4 +0,0 @@
-Code completion in fragmentlayout.xml for class="^com selecting android.app.ListFragment:
-@@ -16 +16
-- <fragment class="^com.android.eclipse.tests.TestFragment"
-+ <fragment class="android.app.ListFragment^"
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/fragmentlayout-expected-complation77.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/fragmentlayout-expected-complation77.txt
deleted file mode 100644
index 6e8687f4f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/fragmentlayout-expected-complation77.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-Code completion in fragmentlayout.xml for android:name="^com:
-android.app.DialogFragment : <p>Implementations should override this class and implement <code><a href="/reference/android/app/Fragment.html#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)">onCreateView(LayoutInflater, ViewGroup, Bundle)</a></code> to supply ...
-android.app.ListFragment : <p> ListFragment hosts a <code><a href="/reference/android/widget/ListView.html">ListView</a></code> object that can be bound to different data sources, typically either an array or a Cursor holding query results. Binding, screen layout, and row layout are discussed ...
-android.preference.PreferenceFragment : <p> Furthermore, the preferences shown will follow the visual style of system preferences. It is easy to create a hierarchy of preferences (that can be shown on multiple screens) via XML. For these reasons, it is recommended to use this fragment (as a s...
-android.webkit.WebViewFragment : <p> The WebView is automically paused or resumed when the Fragment is paused or resumed. </p> </div><!-- jd-descr --> <div class="jd-descr"> <h2>Summary</h2> <!-- =========== ENUM CONSTANT SUMMARY =========== --> <table id="...
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/fragmentlayout-expected-complation78.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/fragmentlayout-expected-complation78.txt
deleted file mode 100644
index e02637c86..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/fragmentlayout-expected-complation78.txt
+++ /dev/null
@@ -1,5 +0,0 @@
-Code completion in fragmentlayout.xml for class="^com:
-android.app.DialogFragment : <p>Implementations should override this class and implement <code><a href="/reference/android/app/Fragment.html#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)">onCreateView(LayoutInflater, ViewGroup, Bundle)</a></code> to supply ...
-android.app.ListFragment : <p> ListFragment hosts a <code><a href="/reference/android/widget/ListView.html">ListView</a></code> object that can be bound to different data sources, typically either an array or a Cursor holding query results. Binding, screen layout, and row layout are discussed ...
-android.preference.PreferenceFragment : <p> Furthermore, the preferences shown will follow the visual style of system preferences. It is easy to create a hierarchy of preferences (that can be shown on multiple screens) via XML. For these reasons, it is recommended to use this fragment (as a s...
-android.webkit.WebViewFragment : <p> The WebView is automically paused or resumed when the Fragment is paused or resumed. </p> </div><!-- jd-descr --> <div class="jd-descr"> <h2>Summary</h2> <!-- =========== ENUM CONSTANT SUMMARY =========== --> <table id="...
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/fragmentlayout-expected-navigate13.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/fragmentlayout-expected-navigate13.txt
deleted file mode 100644
index ae30d58a3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/fragmentlayout-expected-navigate13.txt
+++ /dev/null
@@ -1,12 +0,0 @@
-Go To Declaration in fragmentlayout.xml for android:name="com.android.ecl^ipse.tests.TestFragment":
-Open XML Declaration : [com.android.eclipse.tests.TestFragment]
-
-
-After open, the selected text is:
-[^public class TestFragment extends Fragment {
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- return null;
- }
-}]
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/fragmentlayout-expected-navigate14.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/fragmentlayout-expected-navigate14.txt
deleted file mode 100644
index 0046483fc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/fragmentlayout-expected-navigate14.txt
+++ /dev/null
@@ -1,12 +0,0 @@
-Go To Declaration in fragmentlayout.xml for class="com.and^roid.eclipse.tests.TestFragment":
-Open XML Declaration : [com.android.eclipse.tests.TestFragment]
-
-
-After open, the selected text is:
-[^public class TestFragment extends Fragment {
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- return null;
- }
-}]
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/fragmentlayout.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/fragmentlayout.xml
deleted file mode 100644
index 758599c9c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/fragmentlayout.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/home_root"
- android:orientation="horizontal"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
-
- <LinearLayout android:orientation="vertical"
- android:layout_width="wrap_content"
- android:layout_height="fill_parent">
- <fragment android:name="com.android.eclipse.tests.TestFragment"
- android:id="@+id/test_fragment"
- android:layout_marginLeft="20dp"
- android:layout_weight="1"
- android:layout_width="fill_parent"
- android:layout_height="0dp" />
- <fragment class="com.android.eclipse.tests.TestFragment"
- android:id="@+id/test_fragment2" />
- </LinearLayout>
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-complation80.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-complation80.txt
deleted file mode 100644
index cb1d0ce9d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-complation80.txt
+++ /dev/null
@@ -1,8 +0,0 @@
-Code completion in manifest.xml for <activity android:name="^.:
-android.accounts.AccountAuthenticatorActivity
-android.app.ActivityGroup
-android.app.AliasActivity
-android.app.ExpandableListActivity
-android.app.ListActivity
-android.app.NativeActivity
-android.app.TabActivity
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-completion14.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-completion14.txt
deleted file mode 100644
index 478e4357c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-completion14.txt
+++ /dev/null
@@ -1,10 +0,0 @@
-Code completion in manifest.xml for android.permission.ACC^ESS_NETWORK_STATE:
-android.permission.ACCESS_CHECKIN_PROPERTIES
-android.permission.ACCESS_COARSE_LOCATION
-android.permission.ACCESS_FINE_LOCATION
-android.permission.ACCESS_LOCATION_EXTRA_COMMANDS
-android.permission.ACCESS_MOCK_LOCATION
-android.permission.ACCESS_NETWORK_STATE
-android.permission.ACCESS_SURFACE_FLINGER
-android.permission.ACCESS_WIFI_STATE
-android.permission.ACCOUNT_MANAGER
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-completion15.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-completion15.txt
deleted file mode 100644
index c6b35386d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-completion15.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Code completion in manifest.xml for android.intent.category.L^AUNCHER:
-android.intent.category.LAUNCHER
-android.intent.category.LE_DESK_DOCK
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-completion16.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-completion16.txt
deleted file mode 100644
index f3367c72a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-completion16.txt
+++ /dev/null
@@ -1,15 +0,0 @@
-Code completion in manifest.xml for <^application android:i:
-application : The "application" tag describes application-level components contained in the package, as well as general application attributes.
-compatible-screens
-instrumentation : Attributes that can be supplied in an AndroidManifest.xml "instrumentation" tag, a child of the root manifest tag.
-original-package : Private tag to declare the original package name that this package is based on.
-package-verifier : Attributes relating to a package verifier.
-permission : The "permission" tag declares a security permission that can be used to control access from other packages to specific components or features in your package (or other packages).
-permission-group : The "permission-group" tag declares a logical grouping of related permissions.
-permission-tree : The "permission-tree" tag declares the base of a tree of permission values: it declares that this package has ownership of the given permission name, as well as all names underneath it (separated by '.').
-protected-broadcast : Private tag to declare system protected broadcast actions.
-supports-screens : The "supports-screens" specifies the screen dimensions an application supports.
-uses-configuration : The "uses-configuration" tag specifies a specific hardware configuration value used by the application.
-uses-feature : The "uses-feature" tag specifies a specific feature used by the application.
-uses-permission : The "uses-permission" tag requests a "permission" that the containing package must be granted in order for it to operate correctly.
-uses-sdk : The "uses-sdk" tag describes the SDK features that the containing package must be running on to operate correctly.
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-completion17.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-completion17.txt
deleted file mode 100644
index 8244f0a81..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-completion17.txt
+++ /dev/null
@@ -1,8 +0,0 @@
-Code completion in manifest.xml for ^android:versionCode="1":
-xmlns:android
-package : This attribute gives a unique name for the package, using a Java-style naming convention to avoid name collisions. For example, applications published by Google could have names of the form com.google.app.appname
-android:versionCode : Internal version code. [integer]
-android:versionName : The text shown to the user to indicate the version they have. [string]
-android:sharedUserId : Specify the name of a user ID that will be shared between multiple packages. [string]
-android:sharedUserLabel : Specify a label for the shared user UID of this package. [reference]
-android:installLocation : The default install location defined by an application. [enum]
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-completion18.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-completion18.txt
deleted file mode 100644
index 12152445e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-completion18.txt
+++ /dev/null
@@ -1,29 +0,0 @@
-Code completion in manifest.xml for <activity android:^name=".TestActivity":
-android:name : Required name of the class implementing the activity, deriving from android.app.Activity. [string]. * Required.
-android:theme : The overall theme to use for an activity. [reference]
-android:label : A user-legible name for the given item. [string, reference]
-android:description : Descriptive text for the associated data. [reference]
-android:icon : [reference]
-android:logo : A Drawable resource providing an extended graphical logo for its associated item. [reference]
-android:launchMode : Specify how an activity should be launched. [enum]
-android:screenOrientation : Specify the orientation an activity should be run in. [enum]
-android:configChanges : Specify one or more configuration changes that the activity will handle itself. [flag]
-android:permission : Specify a permission that a client is required to have in order to use the associated object. [string]
-android:multiprocess : Specify whether a component is allowed to have multiple instances of itself running in different processes. [boolean]
-android:process : Specify a specific process that the associated code is to run in. [string]
-android:taskAffinity : Specify a task name that activities have an "affinity" to. [string]
-android:allowTaskReparenting : Specify that an activity can be moved out of a task it is in to the task it has an affinity for when appropriate. [boolean]
-android:finishOnTaskLaunch : Specify whether an activity should be finished when its task is brought to the foreground by relaunching from the home screen. [boolean]
-android:finishOnCloseSystemDialogs : Specify whether an activity should be finished when a "close system windows" request has been made. [boolean]
-android:clearTaskOnLaunch : Specify whether an activity's task should be cleared when it is re-launched from the home screen. [boolean]
-android:noHistory : Specify whether an activity should be kept in its history stack. [boolean]
-android:alwaysRetainTaskState : Specify whether an acitivty's task state should always be maintained by the system, or if it is allowed to reset the task to its initial state in certain situations. [boolean]
-android:stateNotNeeded : Indicates that an Activity does not need to have its freeze state (as returned by onSaveInstanceState retained in order to be restarted. [boolean]
-android:excludeFromRecents : Indicates that an Activity should be excluded from the list of recently launched activities. [boolean]
-android:enabled : Specify whether the activity is enabled or not (that is, can be instantiated by the system). [boolean]
-android:exported : Flag indicating whether the given application component is available to other applications. [boolean]
-android:windowSoftInputMode : Specify the default soft-input mode for the main window of this activity. [flag]
-android:immersive : Flag declaring this activity to be 'immersive'; immersive activities should not be interrupted with other activities or notifications. [boolean]
-android:hardwareAccelerated : <p>Flag indicating whether the application's rendering should be hardware accelerated if possible. [boolean]
-android:uiOptions : Extra options for an activity's UI. [flag]
-android:parentActivityName : The name of the logical parent of the activity as it appears in the manifest. [string]
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-completion69.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-completion69.txt
deleted file mode 100644
index cf7e0f4a1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-completion69.txt
+++ /dev/null
@@ -1,18 +0,0 @@
-Code completion in manifest.xml for <uses-sdk android:minSdkVersion="^11" />:
-17 : API 17: Android 4.2 (Jelly Bean)
-16 : API 16: Android 4.1 (Jelly Bean)
-15 : API 15: Android 4.0.3 (IceCreamSandwich)
-14 : API 14: Android 4.0 (IceCreamSandwich)
-13 : API 13: Android 3.2 (Honeycomb)
-12 : API 12: Android 3.1 (Honeycomb)
-11 : API 11: Android 3.0 (Honeycomb)
-10 : API 10: Android 2.3.3 (Gingerbread)
-9 : API 9: Android 2.3 (Gingerbread)
-8 : API 8: Android 2.2 (Froyo)
-7 : API 7: Android 2.1 (Eclair)
-6 : API 6: Android 2.0.1 (Eclair)
-5 : API 5: Android 2.0 (Eclair)
-4 : API 4: Android 1.6 (Donut)
-3 : API 3: Android 1.5 (Cupcake)
-2 : API 2: Android 1.1
-1 : API 1: Android 1.0
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-navigate10.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-navigate10.txt
deleted file mode 100644
index c745f54d3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-navigate10.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-Go To Declaration in manifest.xml for <uses-permission android:name="android.permission.AC^CESS_NETWORK_STATE" />:
-Open XML Declaration : [android.permission.ACCESS_NETWORK_STATE]
-
-
-After open, a browser is shown with this URL:
- reference/android/Manifest.permission.html#ACCESS_NETWORK_STATE
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-navigate11a.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-navigate11a.txt
deleted file mode 100644
index eaeddf9ef..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-navigate11a.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-Go To Declaration in manifest.xml for <action android:name="android.intent.ac^tion.MAIN" />:
-Open XML Declaration : [android.intent.action.MAIN]
-
-
-After open, a browser is shown with this URL:
- reference/android/content/Intent.html#ACTION_MAIN
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-navigate11g.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-navigate11g.txt
deleted file mode 100644
index 9acb3308a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-navigate11g.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-Go To Declaration in manifest.xml for <category android:name="android.intent.category.LA^UNCHER" />:
-Open XML Declaration : [android.intent.category.LAUNCHER]
-
-
-After open, a browser is shown with this URL:
- reference/android/content/Intent.html#CATEGORY_LAUNCHER
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-navigate9a.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-navigate9a.txt
deleted file mode 100644
index 2221e377c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest-expected-navigate9a.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-Go To Declaration in manifest.xml for <activity android:name=".Test^Activity":
-Open XML Declaration : [.TestActivity]
-
-
-After open, the selected text is:
-^<?xml version="1.0" encoding="utf-8"?>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest.xml
deleted file mode 100644
index 2c0024f04..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/manifest.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="foo.bar"
- android:versionCode="1"
- android:versionName="1.0">
- <uses-sdk android:minSdkVersion="11" />
- <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
-
- <application android:icon="@drawable/icon" android:label="@string/app_name">
- <activity android:name=".TestActivity"
- android:label="@string/app_name">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
-
- </application>
-</manifest>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/metadata.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/metadata.xml
deleted file mode 100644
index 9262f97cd..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/metadata.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout android:id="@+id/LinearLayout1"
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical" android:layout_width="match_parent"
- android:layout_height="match_parent">
- <ListView android:layout_width="match_parent" android:id="@+id/listView1"
- android:layout_height="wrap_content">
- </ListView>
- <Button android:text="Button" android:id="@+id/button1"/>
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-complation76.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-complation76.txt
deleted file mode 100644
index 6b9cf5b45..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-complation76.txt
+++ /dev/null
@@ -1,76 +0,0 @@
-Code completion in navigation1.xml for ?android:a^ttr/alertDialogStyle:
-?android:attr/
-?android:allowClearUserData
-?android:authorities
-?android:action
-?android:alertDialogStyle
-?android:absListViewStyle
-?android:autoCompleteTextViewStyle
-?android:autoLink
-?android:activityOpenEnterAnimation
-?android:activityOpenExitAnimation
-?android:activityCloseEnterAnimation
-?android:activityCloseExitAnimation
-?android:animationCache
-?android:alwaysDrawnWithCache
-?android:addStatesFromChildren
-?android:animationDuration
-?android:antialias
-?android:adjustViewBounds
-?android:autoText
-?android:angle
-?android:animation
-?android:animationOrder
-?android:alphabeticShortcut
-?android:alwaysRetainTaskState
-?android:allowTaskReparenting
-?android:apiKey
-?android:allowSingleTap
-?android:animateOnClick
-?android:anyDensity
-?android:allowBackup
-?android:autoUrlDetect
-?android:accountType
-?android:accountPreferences
-?android:author
-?android:autoStart
-?android:allContactsName
-?android:actionBarStyle
-?android:animateFirstView
-?android:actionDropDownStyle
-?android:actionButtonStyle
-?android:actionModeBackground
-?android:actionModeCloseDrawable
-?android:actionBarSize
-?android:animateLayoutChanges
-?android:actionBarTabStyle
-?android:actionBarTabBarStyle
-?android:actionBarTabTextStyle
-?android:actionOverflowButtonStyle
-?android:actionModeCloseButtonStyle
-?android:actionLayout
-?android:actionViewClass
-?android:activatedBackgroundIndicator
-?android:alertDialogTheme
-?android:autoAdvanceViewId
-?android:actionModeCutDrawable
-?android:actionModeCopyDrawable
-?android:actionModePasteDrawable
-?android:animationResolution
-?android:alpha
-?android:allowParallelSyncs
-?android:alertDialogIcon
-?android:actionMenuTextAppearance
-?android:actionMenuTextColor
-?android:alignmentMode
-?android:actionModeSelectAllDrawable
-?android:accessibilityEventTypes
-?android:accessibilityFeedbackType
-?android:accessibilityFlags
-?android:actionBarSplitStyle
-?android:actionProviderClass
-?android:actionModeStyle
-?android:actionBarWidgetTheme
-?android:actionBarDivider
-?android:actionBarItemBackground
-?android:actionModeSplitBackground
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate1.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate1.txt
deleted file mode 100644
index 7308a4832..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate1.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-Go To Declaration in navigation1.xml for android:text="@string/app^_name":
-Open Declaration in values/strings.xml : [@string/app_name]
- L/PROJECTNAME/res/values/strings.xml
-
-
-After open, the selected text is:
- [^<string name="app_name">PROJECTNAME</string>]
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate12.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate12.txt
deleted file mode 100644
index 23fa07e00..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate12.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-Go To Declaration in navigation1.xml for <my.Cust^omView></my.CustomView>:
-Open XML Declaration : [my.CustomView]
-
-
-After open, the selected text is:
-^<?xml version="1.0" encoding="utf-8"?>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate15.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate15.txt
deleted file mode 100644
index e36c5f30b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate15.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-Go To Declaration in navigation1.xml for ?android:attr/alert^DialogStyle:
-Open Declaration in values/attrs.xml : [?android:attr/alertDialogStyle]
- data/res/values/attrs.xml
-
-
-After open, the selected text is:
- <attr name="alertDialogStyle" format="reference" />^
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate16.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate16.txt
deleted file mode 100644
index b6f6cb2bc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate16.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-Go To Declaration in navigation1.xml for ?android:alert^DialogStyle:
-Open Declaration in values/attrs.xml : [?android:alertDialogStyle]
- data/res/values/attrs.xml
-
-
-After open, the selected text is:
- <attr name="alertDialogStyle" format="reference" />^
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate2.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate2.txt
deleted file mode 100644
index f91e1f9ae..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate2.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-Go To Declaration in navigation1.xml for marginLeft="@android:dimen/app_ico^n_size":
-Open Declaration in values/dimens.xml : [@android:dimen/app_icon_size]
- data/res/values/dimens.xml
-
-
-After open, the selected text is:
- <dimen name="app_icon_size">^48dip</dimen>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate3.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate3.txt
deleted file mode 100644
index 53776a062..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate3.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-Go To Declaration in navigation1.xml for style="@android:style/Widget.B^utton":
-Open Declaration in values/styles.xml : [@android:style/Widget.Button]
- data/res/values/styles.xml
-
-
-After open, the selected text is:
- <style name="Widget.Button">^
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate4.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate4.txt
deleted file mode 100644
index ec5ee3801..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1-expected-navigate4.txt
+++ /dev/null
@@ -1,89 +0,0 @@
-Go To Declaration in navigation1.xml for android:text="@android:st^ring/ok":
-Open Declaration in values-en-rGB/strings.xml : [@android:string/ok]
- data/res/values-en-rGB/strings.xml
-Open Declaration in values/strings.xml : [@android:string/ok]
- data/res/values/strings.xml
-Open Declaration in values-ar/strings.xml : [@android:string/ok]
- data/res/values-ar/strings.xml
-Open Declaration in values-bg/strings.xml : [@android:string/ok]
- data/res/values-bg/strings.xml
-Open Declaration in values-ca/strings.xml : [@android:string/ok]
- data/res/values-ca/strings.xml
-Open Declaration in values-cs/strings.xml : [@android:string/ok]
- data/res/values-cs/strings.xml
-Open Declaration in values-da/strings.xml : [@android:string/ok]
- data/res/values-da/strings.xml
-Open Declaration in values-de/strings.xml : [@android:string/ok]
- data/res/values-de/strings.xml
-Open Declaration in values-el/strings.xml : [@android:string/ok]
- data/res/values-el/strings.xml
-Open Declaration in values-es/strings.xml : [@android:string/ok]
- data/res/values-es/strings.xml
-Open Declaration in values-es-rUS/strings.xml : [@android:string/ok]
- data/res/values-es-rUS/strings.xml
-Open Declaration in values-fa/strings.xml : [@android:string/ok]
- data/res/values-fa/strings.xml
-Open Declaration in values-fi/strings.xml : [@android:string/ok]
- data/res/values-fi/strings.xml
-Open Declaration in values-fr/strings.xml : [@android:string/ok]
- data/res/values-fr/strings.xml
-Open Declaration in values-hr/strings.xml : [@android:string/ok]
- data/res/values-hr/strings.xml
-Open Declaration in values-hu/strings.xml : [@android:string/ok]
- data/res/values-hu/strings.xml
-Open Declaration in values-in/strings.xml : [@android:string/ok]
- data/res/values-in/strings.xml
-Open Declaration in values-it/strings.xml : [@android:string/ok]
- data/res/values-it/strings.xml
-Open Declaration in values-iw/strings.xml : [@android:string/ok]
- data/res/values-iw/strings.xml
-Open Declaration in values-ja/strings.xml : [@android:string/ok]
- data/res/values-ja/strings.xml
-Open Declaration in values-ko/strings.xml : [@android:string/ok]
- data/res/values-ko/strings.xml
-Open Declaration in values-lt/strings.xml : [@android:string/ok]
- data/res/values-lt/strings.xml
-Open Declaration in values-lv/strings.xml : [@android:string/ok]
- data/res/values-lv/strings.xml
-Open Declaration in values-nb/strings.xml : [@android:string/ok]
- data/res/values-nb/strings.xml
-Open Declaration in values-nl/strings.xml : [@android:string/ok]
- data/res/values-nl/strings.xml
-Open Declaration in values-pl/strings.xml : [@android:string/ok]
- data/res/values-pl/strings.xml
-Open Declaration in values-pt/strings.xml : [@android:string/ok]
- data/res/values-pt/strings.xml
-Open Declaration in values-pt-rPT/strings.xml : [@android:string/ok]
- data/res/values-pt-rPT/strings.xml
-Open Declaration in values-rm/strings.xml : [@android:string/ok]
- data/res/values-rm/strings.xml
-Open Declaration in values-ro/strings.xml : [@android:string/ok]
- data/res/values-ro/strings.xml
-Open Declaration in values-ru/strings.xml : [@android:string/ok]
- data/res/values-ru/strings.xml
-Open Declaration in values-sk/strings.xml : [@android:string/ok]
- data/res/values-sk/strings.xml
-Open Declaration in values-sl/strings.xml : [@android:string/ok]
- data/res/values-sl/strings.xml
-Open Declaration in values-sr/strings.xml : [@android:string/ok]
- data/res/values-sr/strings.xml
-Open Declaration in values-sv/strings.xml : [@android:string/ok]
- data/res/values-sv/strings.xml
-Open Declaration in values-th/strings.xml : [@android:string/ok]
- data/res/values-th/strings.xml
-Open Declaration in values-tl/strings.xml : [@android:string/ok]
- data/res/values-tl/strings.xml
-Open Declaration in values-tr/strings.xml : [@android:string/ok]
- data/res/values-tr/strings.xml
-Open Declaration in values-uk/strings.xml : [@android:string/ok]
- data/res/values-uk/strings.xml
-Open Declaration in values-vi/strings.xml : [@android:string/ok]
- data/res/values-vi/strings.xml
-Open Declaration in values-zh-rCN/strings.xml : [@android:string/ok]
- data/res/values-zh-rCN/strings.xml
-Open Declaration in values-zh-rTW/strings.xml : [@android:string/ok]
- data/res/values-zh-rTW/strings.xml
-
-
-After open, the selected text is:
- <string name="ok" msgid="5970060430562524910">^"OK"</string>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1.xml
deleted file mode 100644
index c5b292e7b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigation1.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <Button
- android:text="@string/app_name"
- android:layout_marginLeft="@android:dimen/app_icon_size"
- style="@android:style/Widget.Button"
- android:id="@+id/button1"
- ></Button>
- <my.CustomView></my.CustomView>
- <EditText
- android:text="@android:string/ok"
- </EditText>
- <EditText android:text="?android:attr/alertDialogStyle" />
- <EditText android:text="?android:alertDialogStyle" />
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigationstyles-expected-extract2.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigationstyles-expected-extract2.diff
deleted file mode 100644
index 8890f79ea..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigationstyles-expected-extract2.diff
+++ /dev/null
@@ -1,5 +0,0 @@
-@@ -28 +28
-+ <style name="newstyle">
-+ <item name="android:textColor">#FF00FF</item>
-+ <item name="android:textSize">20pt</item>
-+ </style>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigationstyles-expected-navigate5.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigationstyles-expected-navigate5.txt
deleted file mode 100644
index 15c91d1be..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigationstyles-expected-navigate5.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-Go To Declaration in navigationstyles.xml for parent="android:Theme.Li^ght">:
-Open Declaration in values/themes.xml : [android:Theme.Light]
- data/res/values/themes.xml
-
-
-After open, the selected text is:
- <style name="Theme.Light">^
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigationstyles-expected-navigate6.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigationstyles-expected-navigate6.txt
deleted file mode 100644
index 5a4f40aa4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigationstyles-expected-navigate6.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-Go To Declaration in navigationstyles.xml for parent="android:The^me.Light">:
-Open Declaration in values/themes.xml : [android:Theme]
- data/res/values/themes.xml
-
-
-After open, the selected text is:
- <style name="Theme">^
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigationstyles-expected-navigate7.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigationstyles-expected-navigate7.txt
deleted file mode 100644
index 8f7eb46b8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigationstyles-expected-navigate7.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-Go To Declaration in navigationstyles.xml for popupBackground">@android:drawable/spinner_dr^opdown_background</item>:
-Open Declaration in drawable/spinner_dropdown_background.xml : [@android:drawable/spinner_dropdown_background]
- data/res/drawable/spinner_dropdown_background.xml
-
-
-After open, the selected text is:
-^<?xml version="1.0" encoding="utf-8"?>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigationstyles-expected-navigate8.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigationstyles-expected-navigate8.txt
deleted file mode 100644
index b74c67681..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigationstyles-expected-navigate8.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-Go To Declaration in navigationstyles.xml for colorBackground"> @color/cust^om_theme_color </item>:
-Open Declaration in values/navigationstyles.xml : [@color/custom_theme_color]
- L/PROJECTNAME/res/values/navigationstyles.xml
-
-
-After open, the selected text is:
- [^<color name="custom_theme_color">#b0b0ff</color>]
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigationstyles.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigationstyles.xml
deleted file mode 100644
index da4bbf289..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/navigationstyles.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
- <color name="custom_theme_color">#b0b0ff</color>
- <style name="CustomTheme" parent="android:Theme.Light">
- <item name="android:windowBackground">@color/custom_theme_color</item>
- <item name="android:colorBackground"> @color/custom_theme_color </item>
- </style>
-
- <style name="BrowserTheme" parent="@android:Theme.Black">
- <item name="android:autoCompleteTextViewStyle">@style/AutoCompleteTextView</item>
- <item name="android:windowNoTitle">true</item>
- </style>
-
- <style name="AutoCompleteTextView">
- <item name="android:focusable">true</item>
- <item name="android:focusableInTouchMode">true</item>
- <item name="android:clickable">true</item>
- <item name="android:completionHintView">@android:layout/simple_dropdown_item_1line</item>
- <item name="android:textAppearance">?android:attr/textAppearanceLargeInverse</item>
- <item name="android:completionThreshold">2</item>
- <item name="android:dropDownSelector">@android:drawable/list_selector_background</item>
- <item name="android:popupBackground">@android:drawable/spinner_dropdown_background</item>
- </style>
-
- <style name="CustomTitle" parent="@android:Theme">
- <item name="android:windowTitleSize">60dip</item>
- </style>
-</resources>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout1-expected-extract1.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout1-expected-extract1.xml
deleted file mode 100644
index 2a0e9477c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout1-expected-extract1.xml
+++ /dev/null
@@ -1,2 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Button xmlns:android="http://schemas.android.com/apk/res/android" android:text="Button" android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout2-expected-extract2.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout2-expected-extract2.xml
deleted file mode 100644
index b2d1789aa..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout2-expected-extract2.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<merge xmlns:android="http://schemas.android.com/apk/res/android">
- <ImageView android:id="@+id/android_logo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/android_button" android:focusable="false" android:clickable="false" android:layout_weight="1.0" />
- <Button android:text="Button" android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
-</merge>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout3-expected-extract3.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout3-expected-extract3.xml
deleted file mode 100644
index 6ba61c838..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout3-expected-extract3.xml
+++ /dev/null
@@ -1,2 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<Button xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:id="@+id/button3" android:layout_height="wrap_content" android:text="Button" ></Button>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout3-expected-extract4.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout3-expected-extract4.xml
deleted file mode 100644
index ee8568e68..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout3-expected-extract4.xml
+++ /dev/null
@@ -1,2 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<ImageView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/android_logo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/android_button" android:focusable="false" android:clickable="false" />
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout3-expected-extract5.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout3-expected-extract5.xml
deleted file mode 100644
index be5706645..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout3-expected-extract5.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<merge xmlns:android="http://schemas.android.com/apk/res/android">
- <Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
- <ImageView android:id="@+id/android_logo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/android_button" android:focusable="false" android:clickable="false" android:layout_weight="1.0" />
-</merge>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout6-expected-extract6.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout6-expected-extract6.diff
deleted file mode 100644
index 6772a8fa2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout6-expected-extract6.diff
+++ /dev/null
@@ -1,12 +0,0 @@
-@@ -1 +1
--
-@@ -2 +1
-+ <?xml version="1.0" encoding="utf-8"?>
-+ <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:id="@+id/linearLayout4" android:layout_width="match_parent">
-+ <LinearLayout android:layout_height="match_parent" android:id="@+id/linearLayout5" android:layout_width="wrap_content">
-+ <LinearLayout android:layout_height="match_parent" android:id="@+id/linearLayout6" android:layout_width="wrap_content">
-+ <!-- Comment -->
-+ <Button android:text="Button" android:id="@+id/button6" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
-+ </LinearLayout>
-+ </LinearLayout>
-+ </LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout6-expected-extract7.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout6-expected-extract7.diff
deleted file mode 100644
index d0fdc92e5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newlayout6-expected-extract7.diff
+++ /dev/null
@@ -1,29 +0,0 @@
-@@ -1 +1
-+ <?xml version="1.0" encoding="utf-8"?>
-+ <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-+ android:id="@+id/linearLayout4"
-+ android:layout_width="match_parent"
-+ android:layout_height="wrap_content" >
-@@ -2 +7
-+ <LinearLayout
-+ android:id="@+id/linearLayout5"
-+ android:layout_width="wrap_content"
-+ android:layout_height="match_parent" >
-+
-+ <LinearLayout
-+ android:id="@+id/linearLayout6"
-+ android:layout_width="wrap_content"
-+ android:layout_height="match_parent" >
-+
-+ <!-- Comment -->
-+
-+ <Button
-+ android:id="@+id/button6"
-+ android:layout_width="wrap_content"
-+ android:layout_height="wrap_content"
-+ android:text="Button" >
-+ </Button>
-+ </LinearLayout>
-+ </LinearLayout>
-+
-+ </LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles-expected-extract1.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles-expected-extract1.diff
deleted file mode 100644
index 0949fbd01..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles-expected-extract1.diff
+++ /dev/null
@@ -1,10 +0,0 @@
-@@ -1 +1
--
-@@ -2 +1
-+ <?xml version="1.0" encoding="utf-8"?>
-+ <resources xmlns:android="http://schemas.android.com/apk/res/android">
-+ <style name="newstyle">
-+ <item name="android:textColor">#FF00FF</item>
-+ <item name="android:textSize">20pt</item>
-+ </style>
-+ </resources>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles2-expected-extract1b.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles2-expected-extract1b.diff
deleted file mode 100644
index 0949fbd01..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles2-expected-extract1b.diff
+++ /dev/null
@@ -1,10 +0,0 @@
-@@ -1 +1
--
-@@ -2 +1
-+ <?xml version="1.0" encoding="utf-8"?>
-+ <resources xmlns:android="http://schemas.android.com/apk/res/android">
-+ <style name="newstyle">
-+ <item name="android:textColor">#FF00FF</item>
-+ <item name="android:textSize">20pt</item>
-+ </style>
-+ </resources>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles3-expected-extract1c.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles3-expected-extract1c.diff
deleted file mode 100644
index 0949fbd01..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles3-expected-extract1c.diff
+++ /dev/null
@@ -1,10 +0,0 @@
-@@ -1 +1
--
-@@ -2 +1
-+ <?xml version="1.0" encoding="utf-8"?>
-+ <resources xmlns:android="http://schemas.android.com/apk/res/android">
-+ <style name="newstyle">
-+ <item name="android:textColor">#FF00FF</item>
-+ <item name="android:textSize">20pt</item>
-+ </style>
-+ </resources>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles3-expected-extract8.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles3-expected-extract8.diff
deleted file mode 100644
index e8b553ec9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles3-expected-extract8.diff
+++ /dev/null
@@ -1,10 +0,0 @@
-@@ -1 +1
--
-@@ -2 +1
-+ <?xml version="1.0" encoding="utf-8"?>
-+ <resources xmlns:android="http://schemas.android.com/apk/res/android">
-+ <style name="newstyle" parent="android:Widget.Button">
-+ <item name="android:textColor">#FF00FF</item>
-+ <item name="android:textSize">20pt</item>
-+ </style>
-+ </resources>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles4-expected-extract1d.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles4-expected-extract1d.diff
deleted file mode 100644
index 0949fbd01..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles4-expected-extract1d.diff
+++ /dev/null
@@ -1,10 +0,0 @@
-@@ -1 +1
--
-@@ -2 +1
-+ <?xml version="1.0" encoding="utf-8"?>
-+ <resources xmlns:android="http://schemas.android.com/apk/res/android">
-+ <style name="newstyle">
-+ <item name="android:textColor">#FF00FF</item>
-+ <item name="android:textSize">20pt</item>
-+ </style>
-+ </resources>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles4-expected-extract3.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles4-expected-extract3.diff
deleted file mode 100644
index 88a94e7e0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles4-expected-extract3.diff
+++ /dev/null
@@ -1,10 +0,0 @@
-@@ -1 +1
--
-@@ -2 +1
-+ <?xml version="1.0" encoding="utf-8"?>
-+ <resources xmlns:android="http://schemas.android.com/apk/res/android">
-+ <style name="newstyle">
-+ <item name="android:textColor">#FF0000</item>
-+ <item name="android:textSize">20pt</item>
-+ </style>
-+ </resources>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles5-expected-extract4.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles5-expected-extract4.diff
deleted file mode 100644
index 49043b93c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles5-expected-extract4.diff
+++ /dev/null
@@ -1,9 +0,0 @@
-@@ -1 +1
--
-@@ -2 +1
-+ <?xml version="1.0" encoding="utf-8"?>
-+ <resources xmlns:android="http://schemas.android.com/apk/res/android">
-+ <style name="newstyle">
-+ <item name="android:textColor">#FF00FF</item>
-+ </style>
-+ </resources>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles6-expected-extract5.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles6-expected-extract5.diff
deleted file mode 100644
index 49ab2c3ee..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles6-expected-extract5.diff
+++ /dev/null
@@ -1,9 +0,0 @@
-@@ -1 +1
--
-@@ -2 +1
-+ <?xml version="1.0" encoding="utf-8"?>
-+ <resources xmlns:android="http://schemas.android.com/apk/res/android">
-+ <style name="newstyle">
-+ <item name="android:textSize">20pt</item>
-+ </style>
-+ </resources>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles7-expected-extract6.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles7-expected-extract6.diff
deleted file mode 100644
index 51f0812c9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles7-expected-extract6.diff
+++ /dev/null
@@ -1,13 +0,0 @@
-<
----
-> <?xml version="1.0" encoding="utf-8"?>
-> <resources xmlns:android="http://schemas.android.com/apk/res/android">
-> <style name="newstyle">
-> <item name="android:layout_alignParentBottom">true</item>
-> <item name="android:layout_height">wrap_content</item>
-> <item name="android:layout_width">wrap_content</item>
-> <item name="android:text">Button</item>
-> <item name="android:textColor">#FF0000</item>
-> <item name="android:textSize">20pt</item>
-> </style>
-> </resources>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles8-expected-extract7.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles8-expected-extract7.diff
deleted file mode 100644
index 6bcd6ffd4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/newstyles8-expected-extract7.diff
+++ /dev/null
@@ -1,10 +0,0 @@
-@@ -1 +1
--
-@@ -2 +1
-+ <?xml version="1.0" encoding="utf-8"?>
-+ <resources xmlns:android="http://schemas.android.com/apk/res/android">
-+ <style name="newstyle">
-+ <item name="android:textColor">#00FF00</item>
-+ <item name="android:textSize">20pt</item>
-+ </style>
-+ </resources>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/quickfix1-expected-quickFix1.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/quickfix1-expected-quickFix1.xml
deleted file mode 100644
index a51abf407..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/quickfix1-expected-quickFix1.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
-
- <string name="app_name">PROJECTNAME</string>
- <string name="firststring">[^TODO]</string>
-
-</resources> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/quickfix1-expected-quickFix2.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/quickfix1-expected-quickFix2.xml
deleted file mode 100644
index a0d04fb6e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/quickfix1-expected-quickFix2.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<resources>
- <dimen name="testdimen">[^1dp]</dimen>
-</resources>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/quickfix1-expected-quickFix3.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/quickfix1-expected-quickFix3.xml
deleted file mode 100644
index 900c42064..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/quickfix1-expected-quickFix3.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
- ^
-
-</LinearLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/quickfix1.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/quickfix1.xml
deleted file mode 100644
index 927c8d1db..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/quickfix1.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
-
- <Button android:text="@string/firststring"
- android:id="@+id/button1"
- android:layout_width="@dimen/testdimen"
- android:layout_height="wrap_content">
- </Button>
-
- <include layout="@layout/testlayout" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
-
-</LinearLayout>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/quickfix2-expected-quickFix4.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/quickfix2-expected-quickFix4.xml
deleted file mode 100644
index 7b638c645..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/quickfix2-expected-quickFix4.xml
+++ /dev/null
@@ -1,4 +0,0 @@
-@@ -5 +5
-- <color android:color="#0000000"/>
-@@ -6 +5
-+ <color android:color="#0000000" xmlns:android="http://schemas.android.com/apk/res/android"/>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/quickfix2.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/quickfix2.xml
deleted file mode 100644
index 4f2a925a5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/quickfix2.xml
+++ /dev/null
@@ -1,5 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
- <!--
- Random comment here
- -->
-<color android:color="#0000000"/>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound1-expected-1.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound1-expected-1.xml
deleted file mode 100644
index e72638f57..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound1-expected-1.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <TextView
- android:id="@+id/TextView1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:drawableTop="@drawable/ic_launcher"
- android:gravity="center"
- android:text="Hello World" >
- </TextView>
-
-</LinearLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound1.info b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound1.info
deleted file mode 100644
index 4f0aea55e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound1.info
+++ /dev/null
@@ -1,4 +0,0 @@
-android.widget.LinearLayout [0,121,800,480] <LinearLayout>
- android.widget.LinearLayout [0,0,109,97] <LinearLayout>
- android.widget.ImageView [18,0,90,72] <ImageView>
- android.widget.TextView [0,72,109,97] <TextView>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound1.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound1.xml
deleted file mode 100644
index e4f5bf20e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound1.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <LinearLayout
- android:id="@+id/layout1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:gravity="center"
- android:orientation="vertical" >
-
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:src="@drawable/ic_launcher" />
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Hello World" />
- </LinearLayout>
-
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound2-expected-2.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound2-expected-2.xml
deleted file mode 100644
index 2b9d338d1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound2-expected-2.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <TextView
- android:id="@+id/TextView1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:drawableBottom="@drawable/ic_launcher"
- android:gravity="center"
- android:text="Hello World" >
- </TextView>
-
-</LinearLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound2.info b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound2.info
deleted file mode 100644
index 37084fb88..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound2.info
+++ /dev/null
@@ -1,5 +0,0 @@
-android.widget.LinearLayout [0,121,800,480] <LinearLayout>
- android.widget.LinearLayout [0,0,109,97] <LinearLayout>
- android.widget.TextView [0,0,109,25] <TextView>
- android.widget.ImageView [18,25,90,97] <ImageView>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound2.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound2.xml
deleted file mode 100644
index c24fb211c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound2.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <LinearLayout
- android:id="@+id/layout2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:gravity="center"
- android:orientation="vertical" >
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Hello World" />
-
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:src="@drawable/ic_launcher" />
- </LinearLayout>
-
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound3-expected-3.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound3-expected-3.xml
deleted file mode 100644
index ac8ffa8ce..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound3-expected-3.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <TextView
- android:id="@+id/TextView1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:drawableLeft="@drawable/ic_launcher"
- android:gravity="center"
- android:text="Hello World" >
- </TextView>
-
-</LinearLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound3.info b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound3.info
deleted file mode 100644
index 01d1127f1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound3.info
+++ /dev/null
@@ -1,4 +0,0 @@
-android.widget.LinearLayout [0,121,800,480] <LinearLayout>
- android.widget.LinearLayout [0,0,181,72] <LinearLayout>
- android.widget.ImageView [0,0,72,72] <ImageView>
- android.widget.TextView [72,23,181,48] <TextView>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound3.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound3.xml
deleted file mode 100644
index 2444e4830..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound3.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <LinearLayout
- android:id="@+id/layout3"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:gravity="center"
- android:orientation="horizontal" >
-
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:src="@drawable/ic_launcher" />
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Hello World" />
- </LinearLayout>
-
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound4-expected-4.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound4-expected-4.xml
deleted file mode 100644
index af9b1c922..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound4-expected-4.xml
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <TextView
- android:id="@+id/TextView1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:drawableRight="@drawable/ic_launcher"
- android:gravity="center"
- android:text="Hello World" >
- </TextView>
-
-</LinearLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound4.info b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound4.info
deleted file mode 100644
index 4b39be81e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound4.info
+++ /dev/null
@@ -1,4 +0,0 @@
-android.widget.LinearLayout [0,121,800,480] <LinearLayout>
- android.widget.LinearLayout [0,0,181,72] <LinearLayout>
- android.widget.TextView [0,23,109,48] <TextView>
- android.widget.ImageView [109,0,181,72] <ImageView>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound4.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound4.xml
deleted file mode 100644
index 2f6afd2f7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound4.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <LinearLayout
- android:id="@+id/layout4"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:gravity="center"
- android:orientation="horizontal" >
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Hello World" />
-
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:src="@drawable/ic_launcher" />
- </LinearLayout>
-
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound5-expected-7.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound5-expected-7.xml
deleted file mode 100644
index e909811cf..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound5-expected-7.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<TextView xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/TextView1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:drawableBottom="@drawable/ic_launcher"
- android:text="Hello World" >
-
-</TextView> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound5.info b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound5.info
deleted file mode 100644
index 8eb5c4b86..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound5.info
+++ /dev/null
@@ -1,3 +0,0 @@
-android.widget.LinearLayout [0,74,480,800] <LinearLayout>
- android.widget.TextView [0,0,107,26] <TextView>
- android.widget.ImageView [0,26,72,98] <ImageView>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound5.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound5.xml
deleted file mode 100644
index 49c0594da..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound5.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:id="@+id/layout"
- android:orientation="vertical" >
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Hello World" />
-
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:src="@drawable/ic_launcher" />
-
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound6-expected-8.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound6-expected-8.xml
deleted file mode 100644
index 1ef5d78c6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound6-expected-8.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <TextView
- android:id="@+id/TextView1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:drawableLeft="@drawable/ic_launcher"
- android:drawablePadding="@android:dimen/thumbnail_width"
- android:gravity="center"
- android:text="Hello World" >
- </TextView>
-
-</LinearLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound6.info b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound6.info
deleted file mode 100644
index 4f0aea55e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound6.info
+++ /dev/null
@@ -1,4 +0,0 @@
-android.widget.LinearLayout [0,121,800,480] <LinearLayout>
- android.widget.LinearLayout [0,0,109,97] <LinearLayout>
- android.widget.ImageView [18,0,90,72] <ImageView>
- android.widget.TextView [0,72,109,97] <TextView>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound6.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound6.xml
deleted file mode 100644
index 94a363ba5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound6.xml
+++ /dev/null
@@ -1,25 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <LinearLayout
- android:id="@+id/layout1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:gravity="center" >
-
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginRight="@android:dimen/thumbnail_width"
- android:src="@drawable/ic_launcher" />
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Hello World" />
- </LinearLayout>
-
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound7-expected-9.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound7-expected-9.xml
deleted file mode 100644
index 1b2a8643e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound7-expected-9.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <TextView
- android:id="@+id/TextView1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:drawablePadding="35dp"
- android:drawableTop="@drawable/ic_launcher"
- android:gravity="center"
- android:text="Hello World" >
- </TextView>
-
-</LinearLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound7.info b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound7.info
deleted file mode 100644
index 4f0aea55e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound7.info
+++ /dev/null
@@ -1,4 +0,0 @@
-android.widget.LinearLayout [0,121,800,480] <LinearLayout>
- android.widget.LinearLayout [0,0,109,97] <LinearLayout>
- android.widget.ImageView [18,0,90,72] <ImageView>
- android.widget.TextView [0,72,109,97] <TextView>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound7.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound7.xml
deleted file mode 100644
index 46393fe0e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound7.xml
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <LinearLayout
- android:id="@+id/layout1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:gravity="center"
- android:orientation="vertical" >
-
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginBottom="10dp"
- android:src="@drawable/ic_launcher" />
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginTop="25dp"
- android:text="Hello World" />
- </LinearLayout>
-
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound_all-expected-5.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound_all-expected-5.xml
deleted file mode 100644
index 35bebf5f1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound_all-expected-5.xml
+++ /dev/null
@@ -1,73 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/RelativeLayout1"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" >
-
- <LinearLayout
- android:id="@+id/layout1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:gravity="center"
- android:orientation="vertical" >
-
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:src="@drawable/ic_launcher" />
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Hello World" />
- </LinearLayout>
-
- <TextView
- android:id="@+id/textView2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@+id/layout1"
- android:drawableBottom="@drawable/ic_launcher"
- android:gravity="center"
- android:text="Hello World" >
- </TextView>
-
- <LinearLayout
- android:id="@+id/layout3"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@+id/textView2"
- android:gravity="center"
- android:orientation="horizontal" >
-
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:src="@drawable/ic_launcher" />
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Hello World" />
- </LinearLayout>
-
- <LinearLayout
- android:id="@+id/layout4"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@+id/layout3"
- android:gravity="center"
- android:orientation="horizontal" >
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Hello World" />
-
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:src="@drawable/ic_launcher" />
- </LinearLayout>
-
-</RelativeLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound_all-expected-6.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound_all-expected-6.xml
deleted file mode 100644
index 6d9925674..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound_all-expected-6.xml
+++ /dev/null
@@ -1,74 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/RelativeLayout1"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" >
-
- <LinearLayout
- android:id="@+id/layout1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:gravity="center"
- android:orientation="vertical" >
-
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:src="@drawable/ic_launcher" />
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Hello World" />
- </LinearLayout>
-
- <LinearLayout
- android:id="@+id/layout2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@+id/layout1"
- android:gravity="center"
- android:orientation="vertical" >
-
- <TextView
- android:id="@+id/textView2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Hello World" />
-
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:src="@drawable/ic_launcher" />
- </LinearLayout>
-
- <TextView
- android:id="@+id/TextView1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@+id/layout2"
- android:drawableLeft="@drawable/ic_launcher"
- android:gravity="center"
- android:text="Hello World" >
- </TextView>
-
- <LinearLayout
- android:id="@+id/layout4"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@+id/TextView1"
- android:gravity="center"
- android:orientation="horizontal" >
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Hello World" />
-
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:src="@drawable/ic_launcher" />
- </LinearLayout>
-
-</RelativeLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound_all.info b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound_all.info
deleted file mode 100644
index 57508bd72..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound_all.info
+++ /dev/null
@@ -1,13 +0,0 @@
-android.widget.RelativeLayout [0,121,800,480] <RelativeLayout>
- android.widget.LinearLayout [0,0,109,97] <LinearLayout>
- android.widget.ImageView [18,0,90,72] <ImageView>
- android.widget.TextView [0,72,109,97] <TextView>
- android.widget.LinearLayout [0,97,109,194] <LinearLayout>
- android.widget.TextView [0,0,109,25] <TextView>
- android.widget.ImageView [18,25,90,97] <ImageView>
- android.widget.LinearLayout [0,194,181,266] <LinearLayout>
- android.widget.ImageView [0,0,72,72] <ImageView>
- android.widget.TextView [72,23,181,48] <TextView>
- android.widget.LinearLayout [0,266,181,338] <LinearLayout>
- android.widget.TextView [0,23,109,48] <TextView>
- android.widget.ImageView [109,0,181,72] <ImageView>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound_all.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound_all.xml
deleted file mode 100644
index 0406b171d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/refactoring/usecompound/compound_all.xml
+++ /dev/null
@@ -1,83 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/RelativeLayout1"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" >
-
- <LinearLayout
- android:id="@+id/layout1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:gravity="center"
- android:orientation="vertical" >
-
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:src="@drawable/ic_launcher" />
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Hello World" />
- </LinearLayout>
-
- <LinearLayout
- android:id="@+id/layout2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@+id/layout1"
- android:gravity="center"
- android:orientation="vertical" >
-
- <TextView
- android:id="@+id/textView2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Hello World" />
-
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:src="@drawable/ic_launcher" />
- </LinearLayout>
-
- <LinearLayout
- android:id="@+id/layout3"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@+id/layout2"
- android:gravity="center"
- android:orientation="horizontal" >
-
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:src="@drawable/ic_launcher" />
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Hello World" />
- </LinearLayout>
-
- <LinearLayout
- android:id="@+id/layout4"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@+id/layout3"
- android:gravity="center"
- android:orientation="horizontal" >
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Hello World" />
-
- <ImageView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:src="@drawable/ic_launcher" />
- </LinearLayout>
-
-</RelativeLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample10-expected-convertFromGrid.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample10-expected-convertFromGrid.xml
deleted file mode 100644
index 98e1f36f4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample10-expected-convertFromGrid.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/LinearLayout1"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:columnCount="2"
- android:orientation="horizontal" >
-
- <Button
- android:id="@+id/button1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Button" />
-
- <RadioButton
- android:id="@+id/radioButton1"
- android:layout_width="150dp"
- android:layout_height="wrap_content"
- android:layout_column="0"
- android:layout_row="1"
- android:text="RadioButton" />
-
- <RadioButton
- android:id="@+id/radioButton2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="RadioButton" />
-
- <CheckBox
- android:id="@+id/checkBox1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="CheckBox" />
-
-</LinearLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample10-expected-initialAttributes.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample10-expected-initialAttributes.xml
deleted file mode 100644
index aa8ecdac2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample10-expected-initialAttributes.xml
+++ /dev/null
@@ -1,35 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/LinearLayout1"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:columnCount="2"
- android:orientation="vertical" >
-
- <Button
- android:id="@+id/button1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Button" />
-
- <RadioButton
- android:id="@+id/radioButton1"
- android:layout_width="150dp"
- android:layout_height="wrap_content"
- android:layout_column="0"
- android:layout_row="1"
- android:text="RadioButton" />
-
- <RadioButton
- android:id="@+id/radioButton2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="RadioButton" />
-
- <CheckBox
- android:id="@+id/checkBox1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="CheckBox" />
-
-</LinearLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample10.info b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample10.info
deleted file mode 100644
index c964b0eba..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample10.info
+++ /dev/null
@@ -1,5 +0,0 @@
-android.widget.GridLayout [0,73,320,480] <GridLayout>
- android.widget.Button [0,0,79,48] <Button>
- android.widget.RadioButton [0,48,150,86] <RadioButton>
- android.widget.RadioButton [150,48,273,86] <RadioButton>
- android.widget.CheckBox [0,86,107,124] <CheckBox>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample10.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample10.xml
deleted file mode 100644
index 1fcaab569..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample10.xml
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/GridLayout1"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:columnCount="2"
- android:orientation="horizontal" >
-
- <Button
- android:id="@+id/button1"
- android:text="Button" />
-
- <RadioButton
- android:id="@+id/radioButton1"
- android:layout_width="150dp"
- android:layout_column="0"
- android:layout_row="1"
- android:text="RadioButton" />
-
- <RadioButton
- android:id="@+id/radioButton2"
- android:text="RadioButton" />
-
- <CheckBox
- android:id="@+id/checkBox1"
- android:text="CheckBox" />
-
-</GridLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample11-expected-insertSpacer.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample11-expected-insertSpacer.xml
deleted file mode 100644
index d10626a90..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample11-expected-insertSpacer.xml
+++ /dev/null
@@ -1,59 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- Copyright 2010 Google Inc.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/home_root"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:columnCount="3"
- android:orientation="horizontal" >
-
- <Button
- android:layout_gravity="fill_horizontal"
- android:layout_weight="1" />
-
- <Button
- android:layout_gravity="fill_horizontal"
- android:layout_weight="1" />
-
- <Button
- android:layout_column="0"
- android:layout_gravity="fill_horizontal"
- android:layout_weight="1"
- android:gravity="center_horizontal" />
-
- <Button
- android:layout_gravity="fill_horizontal"
- android:layout_weight="1"
- android:gravity="center_horizontal" />
-
- <Button
- android:layout_column="0"
- android:layout_gravity="fill_horizontal"
- android:layout_weight="1"
- android:gravity="center_horizontal" />
-
- <Button
- android:layout_gravity="fill_horizontal"
- android:layout_weight="1"
- android:gravity="center_horizontal" />
-
- <Space
- android:layout_column="2"
- android:layout_gravity="fill_vertical"
- android:layout_row="3" />
-
-</GridLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample11.info b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample11.info
deleted file mode 100644
index 560e8a877..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample11.info
+++ /dev/null
@@ -1,11 +0,0 @@
-android.widget.LinearLayout [0,50,480,320] <LinearLayout>
- android.widget.LinearLayout [0,0,480,270] <LinearLayout>
- android.widget.LinearLayout [6,6,474,92] <LinearLayout>
- android.widget.Button [0,19,234,67] <Button>
- android.widget.Button [234,19,468,67] <Button>
- android.widget.LinearLayout [6,92,474,178] <LinearLayout>
- android.widget.Button [0,19,234,67] <Button>
- android.widget.Button [234,19,468,67] <Button>
- android.widget.LinearLayout [6,178,474,264] <LinearLayout>
- android.widget.Button [0,19,234,67] <Button>
- android.widget.Button [234,19,468,67] <Button>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample11.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample11.xml
deleted file mode 100644
index 4df91a190..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample11.xml
+++ /dev/null
@@ -1,92 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
- Copyright 2010 Google Inc.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
--->
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/home_root"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical" >
-
- <LinearLayout
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- android:orientation="vertical"
- android:padding="6dip" >
-
- <LinearLayout
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- android:orientation="horizontal" >
-
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_gravity="center_vertical"
- android:layout_weight="1" />
-
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_gravity="center_vertical"
- android:layout_weight="1" />
- </LinearLayout>
-
- <LinearLayout
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- android:orientation="horizontal" >
-
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_gravity="center_vertical"
- android:layout_weight="1"
- android:gravity="center_horizontal" />
-
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_gravity="center_vertical"
- android:layout_weight="1"
- android:gravity="center_horizontal" />
- </LinearLayout>
-
- <LinearLayout
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- android:orientation="horizontal" >
-
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_gravity="center_vertical"
- android:layout_weight="1"
- android:gravity="center_horizontal" />
-
- <Button
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_gravity="center_vertical"
- android:layout_weight="1"
- android:gravity="center_horizontal" />
- </LinearLayout>
- </LinearLayout>
-
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-assistant1.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-assistant1.txt
deleted file mode 100644
index 8eccdfc52..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-assistant1.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Quick assistant in sample1a.xml for <Button android:text="Fir^stButton":
-Extract Android String : Initiates the "Extract Android String" refactoring
-Extract Style : Initiates the "Extract Style" refactoring
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-assistant2.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-assistant2.txt
deleted file mode 100644
index b435ef49c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-assistant2.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-Quick assistant in sample1a.xml for <Bu^tton android:text:
-Wrap in Container : Initiates the "Wrap in Container" refactoring
-Remove Container : Initiates the "Remove Container" refactoring
-Change Widget Type : Initiates the "Change Widget Type" refactoring
-Change Layout : Initiates the "Change Layout" refactoring
-Extract as Include : Initiates the "Extract as Include" refactoring
-Extract Style : Initiates the "Extract Style" refactoring
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-assistant3.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-assistant3.txt
deleted file mode 100644
index a7c46c026..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-assistant3.txt
+++ /dev/null
@@ -1,7 +0,0 @@
-Quick assistant in sample1a.xml for <Button andr^oid:text="FirstButton":
-Wrap in Container : Initiates the "Wrap in Container" refactoring
-Remove Container : Initiates the "Remove Container" refactoring
-Change Widget Type : Initiates the "Change Widget Type" refactoring
-Change Layout : Initiates the "Change Layout" refactoring
-Extract as Include : Initiates the "Extract as Include" refactoring
-Extract Style : Initiates the "Extract Style" refactoring
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-assistant4.txt b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-assistant4.txt
deleted file mode 100644
index 30bb00b25..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-assistant4.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Quick assistant in sample1a.xml for android:id="@+id/Linea^rLayout2":
-Rename Android Resource : Initiates the "Rename Android Resource" refactoring
-Extract Style : Initiates the "Extract Style" refactoring
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-changeLayout1a.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-changeLayout1a.xml
deleted file mode 100644
index d03c92535..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-changeLayout1a.xml
+++ /dev/null
@@ -1,75 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/RelativeLayout1"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
-
- <Button
- android:id="@+id/button1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_alignParentTop="true"
- android:text="FirstButton" >
- </Button>
-
- <Button
- android:id="@+id/button2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_below="@+id/button1"
- android:layout_marginTop="2dp"
- android:text="SecondButton" >
- </Button>
-
- <Button
- android:id="@+id/button3"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignBaseline="@+id/button2"
- android:layout_alignTop="@+id/button2"
- android:layout_toRightOf="@+id/button2"
- android:text="ThirdButton" >
- </Button>
-
- <CheckBox
- android:id="@+id/checkBox1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignBaseline="@+id/button2"
- android:layout_below="@+id/button1"
- android:layout_toRightOf="@+id/button3"
- android:text="CheckBox" >
- </CheckBox>
-
- <Button
- android:id="@+id/button4"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_below="@+id/checkBox1"
- android:text="FourthButton" >
- </Button>
-
- <Button
- android:id="@+id/button5"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_below="@+id/button4"
- android:layout_gravity="right"
- android:text="FifthButton" >
- </Button>
-
- <Button
- android:id="@+id/button6"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_below="@+id/button5"
- android:text="Button" >
- </Button>
-
-</RelativeLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-changeView1.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-changeView1.xml
deleted file mode 100644
index f4a08d023..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-changeView1.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout android:id="@+id/LinearLayout2" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
- <RadioButton android:text="FirstButton" android:id="@+id/RadioButton1" android:layout_width="wrap_content" android:layout_height="wrap_content"></RadioButton>
- <LinearLayout android:layout_width="match_parent" android:id="@+id/linearLayout1" android:layout_height="wrap_content">
- <Button android:text="SecondButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button2"></Button>
- <Button android:text="ThirdButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button3"></Button>
- <CheckBox android:id="@+id/checkBox1" android:text="CheckBox" android:layout_width="wrap_content" android:layout_height="wrap_content"></CheckBox>
- </LinearLayout>
- <Button android:layout_height="wrap_content" android:text="FourthButton" android:id="@+id/button4" android:layout_width="match_parent"></Button>
- <LinearLayout android:layout_height="wrap_content" android:id="@+id/linearLayout3" android:layout_width="match_parent">
- <Button android:layout_gravity="right" android:id="@+id/button5" android:text="FifthButton" android:layout_height="wrap_content" android:layout_width="wrap_content"></Button>
- </LinearLayout>
- <LinearLayout android:layout_height="wrap_content" android:id="@+id/linearLayout4" android:layout_width="match_parent">
- <LinearLayout android:layout_height="match_parent" android:id="@+id/linearLayout5" android:layout_width="wrap_content">
- <LinearLayout android:layout_height="match_parent" android:id="@+id/linearLayout6" android:layout_width="wrap_content">
- <RadioButton android:text="Button" android:id="@+id/RadioButton2" android:layout_width="wrap_content" android:layout_height="wrap_content"></RadioButton>
- </LinearLayout>
- </LinearLayout>
- </LinearLayout>
-</LinearLayout>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-extract6.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-extract6.diff
deleted file mode 100644
index 1ae5748e4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-extract6.diff
+++ /dev/null
@@ -1,9 +0,0 @@
-@@ -13 +13
-- <LinearLayout android:layout_height="wrap_content" android:id="@+id/linearLayout4" android:layout_width="match_parent">
-- <LinearLayout android:layout_height="match_parent" android:id="@+id/linearLayout5" android:layout_width="wrap_content">
-- <LinearLayout android:layout_height="match_parent" android:id="@+id/linearLayout6" android:layout_width="wrap_content">
-- <Button android:text="Button" android:id="@+id/button6" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
-- </LinearLayout>
-- </LinearLayout>
-- </LinearLayout>
-+ <include layout="@layout/newlayout6" android:id="@+id/linearLayout4_ref" android:layout_width="match_parent" android:layout_height="wrap_content"/>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-extract7.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-extract7.diff
deleted file mode 100644
index 6d18aab26..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-extract7.diff
+++ /dev/null
@@ -1,84 +0,0 @@
-@@ -2 +2
-- <LinearLayout android:id="@+id/LinearLayout2" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
-- <Button android:text="FirstButton" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
-- <LinearLayout android:layout_width="match_parent" android:id="@+id/linearLayout1" android:layout_height="wrap_content">
-- <Button android:text="SecondButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button2"></Button>
-- <Button android:text="ThirdButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button3"></Button>
-- <CheckBox android:id="@+id/checkBox1" android:text="CheckBox" android:layout_width="wrap_content" android:layout_height="wrap_content"></CheckBox>
-- </LinearLayout>
-- <Button android:layout_height="wrap_content" android:text="FourthButton" android:id="@+id/button4" android:layout_width="match_parent"></Button>
-- <LinearLayout android:layout_height="wrap_content" android:id="@+id/linearLayout3" android:layout_width="match_parent">
-- <Button android:layout_gravity="right" android:id="@+id/button5" android:text="FifthButton" android:layout_height="wrap_content" android:layout_width="wrap_content"></Button>
-+ <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-+ android:id="@+id/LinearLayout2"
-+ android:layout_width="match_parent"
-+ android:layout_height="match_parent"
-+ android:orientation="vertical" >
-+
-+ <Button
-+ android:id="@+id/button1"
-+ android:layout_width="wrap_content"
-+ android:layout_height="wrap_content"
-+ android:text="FirstButton" >
-+ </Button>
-+
-+ <LinearLayout
-+ android:id="@+id/linearLayout1"
-+ android:layout_width="match_parent"
-+ android:layout_height="wrap_content" >
-+
-+ <Button
-+ android:id="@+id/button2"
-+ android:layout_width="wrap_content"
-+ android:layout_height="wrap_content"
-+ android:text="SecondButton" >
-+ </Button>
-+
-+ <Button
-+ android:id="@+id/button3"
-+ android:layout_width="wrap_content"
-+ android:layout_height="wrap_content"
-+ android:text="ThirdButton" >
-+ </Button>
-+
-+ <CheckBox
-+ android:id="@+id/checkBox1"
-+ android:layout_width="wrap_content"
-+ android:layout_height="wrap_content"
-+ android:text="CheckBox" >
-+ </CheckBox>
-@@ -13 +41
-- <LinearLayout android:layout_height="wrap_content" android:id="@+id/linearLayout4" android:layout_width="match_parent">
-- <LinearLayout android:layout_height="match_parent" android:id="@+id/linearLayout5" android:layout_width="wrap_content">
-- <LinearLayout android:layout_height="match_parent" android:id="@+id/linearLayout6" android:layout_width="wrap_content">
-- <Button android:text="Button" android:id="@+id/button6" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
-- </LinearLayout>
-- </LinearLayout>
-+
-+ <Button
-+ android:id="@+id/button4"
-+ android:layout_width="match_parent"
-+ android:layout_height="wrap_content"
-+ android:text="FourthButton" >
-+ </Button>
-+
-+ <LinearLayout
-+ android:id="@+id/linearLayout3"
-+ android:layout_width="match_parent"
-+ android:layout_height="wrap_content" >
-+
-+ <Button
-+ android:id="@+id/button5"
-+ android:layout_width="wrap_content"
-+ android:layout_height="wrap_content"
-+ android:layout_gravity="right"
-+ android:text="FifthButton" >
-+ </Button>
-@@ -20 +62
-+
-+ <include
-+ android:id="@+id/linearLayout4_ref"
-+ android:layout_width="match_parent"
-+ android:layout_height="wrap_content"
-+ layout="@layout/newlayout6" />
-+
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-gridLayout1.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-gridLayout1.xml
deleted file mode 100644
index 72fe214ce..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a-expected-gridLayout1.xml
+++ /dev/null
@@ -1,61 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/GridLayout1"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:columnCount="4"
- android:orientation="horizontal" >
-
- <Button
- android:id="@+id/button1"
- android:layout_gravity="left"
- android:text="FirstButton" >
- </Button>
-
- <Button
- android:id="@+id/button2"
- android:layout_column="0"
- android:layout_gravity="left"
- android:text="SecondButton" >
- </Button>
-
- <Button
- android:id="@+id/button3"
- android:layout_gravity="left"
- android:text="ThirdButton" >
- </Button>
-
- <CheckBox
- android:id="@+id/checkBox1"
- android:layout_gravity="left"
- android:text="CheckBox" >
- </CheckBox>
-
- <Button
- android:id="@+id/button4"
- android:layout_column="0"
- android:layout_columnSpan="3"
- android:layout_gravity="fill_horizontal"
- android:text="FourthButton" >
- </Button>
-
- <Button
- android:id="@+id/button5"
- android:layout_column="0"
- android:layout_gravity="right"
- android:text="FifthButton" >
- </Button>
-
- <Button
- android:id="@+id/button6"
- android:layout_column="0"
- android:layout_gravity="left"
- android:text="Button" >
- </Button>
-
- <Space
- android:layout_column="3"
- android:layout_gravity="fill_vertical"
- android:layout_row="5" />
-
-</GridLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a.info b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a.info
deleted file mode 100644
index 20a23b08d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a.info
+++ /dev/null
@@ -1,13 +0,0 @@
-android.widget.LinearLayout [0,36,240,320] <LinearLayout>
- android.widget.Button [0,0,70,36] <Button>
- android.widget.LinearLayout [0,36,240,72] <LinearLayout>
- android.widget.Button [0,2,84,38] <Button>
- android.widget.Button [84,2,158,38] <Button>
- android.widget.CheckBox [158,0,238,36] <CheckBox>
- android.widget.Button [0,72,240,108] <Button>
- android.widget.LinearLayout [0,108,240,144] <LinearLayout>
- android.widget.Button [0,0,71,36] <Button>
- android.widget.LinearLayout [0,144,240,180] <LinearLayout>
- android.widget.LinearLayout [0,0,49,36] <LinearLayout>
- android.widget.LinearLayout [0,0,49,36] <LinearLayout>
- android.widget.Button [0,0,49,36] <Button>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a.xml
deleted file mode 100644
index 9a9493592..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1a.xml
+++ /dev/null
@@ -1,21 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout android:id="@+id/LinearLayout2" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
- <Button android:text="FirstButton" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
- <LinearLayout android:layout_width="match_parent" android:id="@+id/linearLayout1" android:layout_height="wrap_content">
- <Button android:text="SecondButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button2"></Button>
- <Button android:text="ThirdButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button3"></Button>
- <CheckBox android:id="@+id/checkBox1" android:text="CheckBox" android:layout_width="wrap_content" android:layout_height="wrap_content"></CheckBox>
- </LinearLayout>
- <Button android:layout_height="wrap_content" android:text="FourthButton" android:id="@+id/button4" android:layout_width="match_parent"></Button>
- <LinearLayout android:layout_height="wrap_content" android:id="@+id/linearLayout3" android:layout_width="match_parent">
- <Button android:layout_gravity="right" android:id="@+id/button5" android:text="FifthButton" android:layout_height="wrap_content" android:layout_width="wrap_content"></Button>
- </LinearLayout>
- <LinearLayout android:layout_height="wrap_content" android:id="@+id/linearLayout4" android:layout_width="match_parent">
- <LinearLayout android:layout_height="match_parent" android:id="@+id/linearLayout5" android:layout_width="wrap_content">
- <LinearLayout android:layout_height="match_parent" android:id="@+id/linearLayout6" android:layout_width="wrap_content">
- <Button android:text="Button" android:id="@+id/button6" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
- </LinearLayout>
- </LinearLayout>
- </LinearLayout>
-</LinearLayout>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1b-expected-changeLayout1b.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1b-expected-changeLayout1b.xml
deleted file mode 100644
index d03c92535..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1b-expected-changeLayout1b.xml
+++ /dev/null
@@ -1,75 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/RelativeLayout1"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
-
- <Button
- android:id="@+id/button1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_alignParentTop="true"
- android:text="FirstButton" >
- </Button>
-
- <Button
- android:id="@+id/button2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_below="@+id/button1"
- android:layout_marginTop="2dp"
- android:text="SecondButton" >
- </Button>
-
- <Button
- android:id="@+id/button3"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignBaseline="@+id/button2"
- android:layout_alignTop="@+id/button2"
- android:layout_toRightOf="@+id/button2"
- android:text="ThirdButton" >
- </Button>
-
- <CheckBox
- android:id="@+id/checkBox1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignBaseline="@+id/button2"
- android:layout_below="@+id/button1"
- android:layout_toRightOf="@+id/button3"
- android:text="CheckBox" >
- </CheckBox>
-
- <Button
- android:id="@+id/button4"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_below="@+id/checkBox1"
- android:text="FourthButton" >
- </Button>
-
- <Button
- android:id="@+id/button5"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_below="@+id/button4"
- android:layout_gravity="right"
- android:text="FifthButton" >
- </Button>
-
- <Button
- android:id="@+id/button6"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_below="@+id/button5"
- android:text="Button" >
- </Button>
-
-</RelativeLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1b.info b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1b.info
deleted file mode 100644
index 7807227c3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1b.info
+++ /dev/null
@@ -1,14 +0,0 @@
-android.widget.LinearLayout [0,36,240,320] <LinearLayout>
- android.widget.Button [0,0,70,36] <Button>
- android.widget.LinearLayout [0,36,240,72] <LinearLayout>
- android.widget.Button [0,2,84,38] <Button>
- android.widget.Button [84,2,158,38] <Button>
- android.widget.CheckBox [158,0,238,36] <CheckBox>
- android.widget.Button [0,72,240,108] <Button>
- android.widget.LinearLayout [0,108,240,144] <LinearLayout>
- android.widget.Button [0,0,71,36] <Button>
- android.widget.LinearLayout [0,144,240,180] <LinearLayout>
- android.widget.LinearLayout [0,0,49,36] <LinearLayout>
- android.widget.LinearLayout [0,0,49,36] <LinearLayout>
- android.widget.Button [0,0,49,36] <Button>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1b.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1b.xml
deleted file mode 100644
index 6b800ae77..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample1b.xml
+++ /dev/null
@@ -1,70 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout
- android:id="@+id/LinearLayout2"
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical">
- <Button
- android:text="FirstButton"
- android:id="@+id/button1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"></Button>
- <LinearLayout
- android:layout_width="match_parent"
- android:id="@+id/linearLayout1"
- android:layout_height="wrap_content">
- <Button
- android:text="SecondButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:id="@+id/button2"></Button>
- <Button
- android:text="ThirdButton"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:id="@+id/button3"></Button>
- <CheckBox
- android:id="@+id/checkBox1"
- android:text="CheckBox"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"></CheckBox>
- </LinearLayout>
- <Button
- android:layout_height="wrap_content"
- android:text="FourthButton"
- android:id="@+id/button4"
- android:layout_width="match_parent"></Button>
- <LinearLayout
- android:layout_height="wrap_content"
- android:id="@+id/linearLayout3"
- android:layout_width="match_parent">
- <Button
- android:layout_gravity="right"
- android:id="@+id/button5"
- android:text="FifthButton"
- android:layout_height="wrap_content"
- android:layout_width="wrap_content"></Button>
- </LinearLayout>
- <LinearLayout
- android:layout_height="wrap_content"
- android:id="@+id/linearLayout4"
- android:layout_width="match_parent">
- <LinearLayout
- android:layout_height="match_parent"
- android:id="@+id/linearLayout5"
- android:layout_width="wrap_content">
- <LinearLayout
- android:layout_height="match_parent"
- android:id="@+id/linearLayout6"
- android:layout_width="wrap_content">
- <Button
- android:text="Button"
- android:id="@+id/button6"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"></Button>
- </LinearLayout>
- </LinearLayout>
- </LinearLayout>
-</LinearLayout>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample2-expected-changeLayout2.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample2-expected-changeLayout2.xml
deleted file mode 100644
index 06420c483..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample2-expected-changeLayout2.xml
+++ /dev/null
@@ -1,62 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/RelativeLayout1"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
-
- <Button
- android:id="@+id/button1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_alignParentTop="true"
- android:text="Button" >
- </Button>
-
- <Button
- android:id="@+id/button2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_below="@+id/button1"
- android:text="Button" >
- </Button>
-
- <Button
- android:id="@+id/button3"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@+id/button2"
- android:layout_toRightOf="@+id/button2"
- android:text="Button" >
- </Button>
-
- <Button
- android:id="@+id/button4"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@+id/button3"
- android:layout_toRightOf="@+id/button3"
- android:text="Button" >
- </Button>
-
- <CheckBox
- android:id="@+id/checkBox1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@+id/button4"
- android:layout_toLeftOf="@+id/button4"
- android:text="CheckBox" >
- </CheckBox>
-
- <Button
- android:id="@+id/button5"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentRight="true"
- android:layout_alignTop="@+id/button2"
- android:text="Button" >
- </Button>
-
-</RelativeLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample2-expected-changeView2.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample2-expected-changeView2.xml
deleted file mode 100644
index 366c8df70..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample2-expected-changeView2.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
- <Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
- <RelativeLayout android:layout_height="match_parent" android:id="@+id/relativeLayout1" android:layout_width="match_parent">
- <Button android:layout_width="wrap_content" android:layout_alignParentLeft="true" android:id="@+id/button2" android:layout_height="wrap_content" android:text="Button"></Button>
- <ImageButton android:layout_width="wrap_content" android:id="@+id/ImageButton1" android:layout_below="@+id/button2" android:layout_height="wrap_content" android:text="Button" android:layout_toRightOf="@+id/button2"></ImageButton>
- <Button android:layout_width="wrap_content" android:id="@+id/button4" android:layout_below="@+id/ImageButton1" android:layout_height="wrap_content" android:text="Button" android:layout_toRightOf="@+id/ImageButton1"></Button>
- <CheckBox android:layout_width="wrap_content" android:layout_below="@+id/button4" android:id="@+id/checkBox1" android:layout_height="wrap_content" android:text="CheckBox" android:layout_toLeftOf="@+id/button4"></CheckBox>
- <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" android:id="@+id/ImageButton2" android:layout_alignParentRight="true"></ImageButton>
- </RelativeLayout>
-</LinearLayout>
-
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample2-expected-extract3.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample2-expected-extract3.xml
deleted file mode 100644
index e4ff73166..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample2-expected-extract3.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
- <Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
- <RelativeLayout android:layout_height="match_parent" android:id="@+id/relativeLayout1" android:layout_width="match_parent">
- <Button android:layout_width="wrap_content" android:layout_alignParentLeft="true" android:id="@+id/button2" android:layout_height="wrap_content" android:text="Button"></Button>
- <include layout="@layout/newlayout3" android:id="@+id/button3_ref" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/button2" android:layout_toRightOf="@+id/button2"/>
- <Button android:layout_width="wrap_content" android:id="@+id/button4" android:layout_below="@+id/button3_ref" android:layout_height="wrap_content" android:text="Button" android:layout_toRightOf="@+id/button3_ref"></Button>
- <CheckBox android:layout_width="wrap_content" android:layout_below="@+id/button4" android:id="@+id/checkBox1" android:layout_height="wrap_content" android:text="CheckBox" android:layout_toLeftOf="@+id/button4"></CheckBox>
- <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" android:id="@+id/button5" android:layout_alignParentRight="true"></Button>
- </RelativeLayout>
-</LinearLayout>
-
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample2-expected-gridLayout2.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample2-expected-gridLayout2.xml
deleted file mode 100644
index 8b9056216..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample2-expected-gridLayout2.xml
+++ /dev/null
@@ -1,67 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/GridLayout1"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:columnCount="6"
- android:orientation="horizontal" >
-
- <Button
- android:id="@+id/button1"
- android:layout_columnSpan="2"
- android:layout_gravity="left"
- android:text="Button" >
- </Button>
-
- <Button
- android:id="@+id/button2"
- android:layout_alignParentLeft="true"
- android:layout_column="0"
- android:layout_columnSpan="2"
- android:layout_gravity="left"
- android:text="Button" >
- </Button>
-
- <Button
- android:id="@+id/button3"
- android:layout_below="@+id/button2"
- android:layout_gravity="left"
- android:layout_row="2"
- android:layout_toRightOf="@+id/button2"
- android:text="Button" >
- </Button>
-
- <Button
- android:id="@+id/button4"
- android:layout_below="@+id/button3"
- android:layout_gravity="left"
- android:layout_row="3"
- android:layout_toRightOf="@+id/button3"
- android:text="Button" >
- </Button>
-
- <CheckBox
- android:id="@+id/checkBox1"
- android:layout_below="@+id/button4"
- android:layout_column="1"
- android:layout_columnSpan="2"
- android:layout_gravity="left"
- android:layout_toLeftOf="@+id/button4"
- android:text="CheckBox" >
- </CheckBox>
-
- <Button
- android:id="@+id/button5"
- android:layout_alignParentRight="true"
- android:layout_column="4"
- android:layout_gravity="left"
- android:layout_row="1"
- android:text="Button" >
- </Button>
-
- <Space
- android:layout_column="5"
- android:layout_gravity="fill_vertical"
- android:layout_row="5" />
-
-</GridLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample2.info b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample2.info
deleted file mode 100644
index 44d3b626d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample2.info
+++ /dev/null
@@ -1,9 +0,0 @@
-android.widget.LinearLayout [0,36,240,320] <LinearLayout>
- android.widget.Button [0,0,49,36] <Button>
- android.widget.RelativeLayout [0,36,240,284] <RelativeLayout>
- android.widget.Button [0,0,49,36] <Button>
- android.widget.Button [49,36,98,72] <Button>
- android.widget.Button [98,72,147,108] <Button>
- android.widget.CheckBox [18,108,98,144] <CheckBox>
- android.widget.Button [191,0,240,36] <Button>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample2.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample2.xml
deleted file mode 100644
index 0697c645c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample2.xml
+++ /dev/null
@@ -1,13 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
- <Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
- <RelativeLayout android:layout_height="match_parent" android:id="@+id/relativeLayout1" android:layout_width="match_parent">
- <Button android:layout_width="wrap_content" android:layout_alignParentLeft="true" android:id="@+id/button2" android:layout_height="wrap_content" android:text="Button"></Button>
- <Button android:layout_width="wrap_content" android:id="@+id/button3" android:layout_below="@+id/button2" android:layout_height="wrap_content" android:text="Button" android:layout_toRightOf="@+id/button2"></Button>
- <Button android:layout_width="wrap_content" android:id="@+id/button4" android:layout_below="@+id/button3" android:layout_height="wrap_content" android:text="Button" android:layout_toRightOf="@+id/button3"></Button>
- <CheckBox android:layout_width="wrap_content" android:layout_below="@+id/button4" android:id="@+id/checkBox1" android:layout_height="wrap_content" android:text="CheckBox" android:layout_toLeftOf="@+id/button4"></CheckBox>
- <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" android:id="@+id/button5" android:layout_alignParentRight="true"></Button>
- </RelativeLayout>
-</LinearLayout>
-
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-changeLayout3.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-changeLayout3.xml
deleted file mode 100644
index 268688b83..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-changeLayout3.xml
+++ /dev/null
@@ -1,38 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/newlinear"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
-
- <Button
- android:id="@+id/button1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_alignParentTop="true"
- android:text="Button" >
- </Button>
-
- <ImageView
- android:id="@+id/android_logo"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_above="@+id/button2"
- android:layout_alignParentLeft="true"
- android:layout_below="@+id/button1"
- android:layout_weight="1.0"
- android:clickable="false"
- android:focusable="false"
- android:src="@drawable/android_button" />
-
- <Button
- android:id="@+id/button2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentBottom="true"
- android:layout_alignParentLeft="true"
- android:text="Button" >
- </Button>
-
-</RelativeLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-extract1.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-extract1.xml
deleted file mode 100644
index 70f576ed6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-extract1.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/newlinear" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
- <Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
- <ImageView android:id="@+id/android_logo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/android_button" android:focusable="false" android:clickable="false" android:layout_weight="1.0" />
- <include layout="@layout/newlayout1" android:id="@+id/button2_ref" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
-</LinearLayout>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-extract2.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-extract2.xml
deleted file mode 100644
index 9a30a96b5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-extract2.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/newlinear" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
- <Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
- <include layout="@layout/newlayout2" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
-</LinearLayout>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-extract4.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-extract4.xml
deleted file mode 100644
index 445f88ac0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-extract4.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/newlinear" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
- <Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
- <include layout="@layout/newlayout3" android:id="@+id/android_logo_ref" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1.0"/>
- <Button android:text="Button" android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
-</LinearLayout>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-extract5.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-extract5.xml
deleted file mode 100644
index 8df41ca2e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-extract5.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/newlinear" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
- <include layout="@layout/newlayout3" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
- <Button android:text="Button" android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
-</LinearLayout>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-wrapIn1.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-wrapIn1.xml
deleted file mode 100644
index 097f87046..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-wrapIn1.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/newlinear"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
-
- <Button
- android:id="@+id/button1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Button" >
- </Button>
-
- <ImageView
- android:id="@+id/android_logo"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_weight="1.0"
- android:clickable="false"
- android:focusable="false"
- android:src="@drawable/android_button" />
-
- <LinearLayout
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" >
-
- <Button
- android:id="@+id/button2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Button" >
- </Button>
- </LinearLayout>
-
-</LinearLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-wrapIn2.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-wrapIn2.xml
deleted file mode 100644
index 2921e40e7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-wrapIn2.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<android.gesture.GestureOverlayView xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent" >
-
- <LinearLayout
- android:id="@+id/newlinear"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
-
- <Button
- android:id="@+id/button1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Button" >
- </Button>
-
- <ImageView
- android:id="@+id/android_logo"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_weight="1.0"
- android:clickable="false"
- android:focusable="false"
- android:src="@drawable/android_button" />
-
- <Button
- android:id="@+id/button2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Button" >
- </Button>
- </LinearLayout>
-
-</android.gesture.GestureOverlayView> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-wrapIn3.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-wrapIn3.xml
deleted file mode 100644
index 6b57216a6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-expected-wrapIn3.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/newlinear"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
-
- <Button
- android:id="@+id/button1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Button" >
- </Button>
-
- <LinearLayout
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" >
-
- <ImageView
- android:id="@+id/android_logo"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_weight="1.0"
- android:clickable="false"
- android:focusable="false"
- android:src="@drawable/android_button" />
-
- <Button
- android:id="@+id/button2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Button" >
- </Button>
- </LinearLayout>
-
-</LinearLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-variation1-expected-extract4.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-variation1-expected-extract4.xml
deleted file mode 100644
index d616269ab..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-variation1-expected-extract4.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/newlinear" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
- <Button android:text="Button" android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
- <LinearLayout android:id="@+id/newlinear2" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
- <Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
- <include layout="@layout/newlayout3" android:id="@+id/android_logo_ref" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1.0"/>
- </LinearLayout>
-</LinearLayout>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-variation1-expected-extract5.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-variation1-expected-extract5.xml
deleted file mode 100644
index b37e7bebb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-variation1-expected-extract5.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/newlinear" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
- <Button android:text="Button" android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
- <LinearLayout android:id="@+id/newlinear2" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
- <include layout="@layout/newlayout3" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
- </LinearLayout>
-</LinearLayout>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-variation1.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-variation1.xml
deleted file mode 100644
index 9cf3c434a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-variation1.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/newlinear" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
- <Button android:text="Button" android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
- <LinearLayout android:id="@+id/newlinear2" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
- <Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
- <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/android_button"
- android:focusable="false" android:clickable="false" android:layout_weight="1.0" android:id="@+id/android_logo" />
- </LinearLayout>
-</LinearLayout>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-variation2-expected-extract4.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-variation2-expected-extract4.xml
deleted file mode 100644
index 40676abd1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-variation2-expected-extract4.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:customprefix="http://schemas.android.com/apk/res/android" customprefix:id="@+id/newlinear" customprefix:orientation="vertical" customprefix:layout_width="match_parent" customprefix:layout_height="match_parent">
- <include layout="@layout/newlayout3" customprefix:id="@+id/android_logo_ref" customprefix:layout_width="wrap_content" customprefix:layout_height="wrap_content" customprefix:layout_weight="1.0"/>
- <Button customprefix:text="Button" customprefix:id="@+id/button1" customprefix:layout_width="wrap_content" customprefix:layout_height="wrap_content"></Button>
- <Button customprefix:text="Button" customprefix:id="@+id/button2" customprefix:layout_width="wrap_content" customprefix:layout_height="wrap_content"></Button>
-</LinearLayout>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-variation2-expected-extract5.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-variation2-expected-extract5.xml
deleted file mode 100644
index c51dc3797..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-variation2-expected-extract5.xml
+++ /dev/null
@@ -1,6 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:customprefix="http://schemas.android.com/apk/res/android" customprefix:id="@+id/newlinear" customprefix:orientation="vertical" customprefix:layout_width="match_parent" customprefix:layout_height="match_parent">
- <include layout="@layout/newlayout3" customprefix:layout_width="wrap_content" customprefix:layout_height="wrap_content"/>
- <Button customprefix:text="Button" customprefix:id="@+id/button2" customprefix:layout_width="wrap_content" customprefix:layout_height="wrap_content"></Button>
-</LinearLayout>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-variation2.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-variation2.xml
deleted file mode 100644
index 48d479024..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3-variation2.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:customprefix="http://schemas.android.com/apk/res/android" customprefix:id="@+id/newlinear" customprefix:orientation="vertical" customprefix:layout_width="match_parent" customprefix:layout_height="match_parent">
- <ImageView customprefix:id="@+id/android_logo" customprefix:layout_width="wrap_content"
- customprefix:layout_height="wrap_content" customprefix:src="@drawable/android_button" customprefix:focusable="false" customprefix:clickable="false" customprefix:layout_weight="1.0" />
- <Button customprefix:text="Button" customprefix:id="@+id/button1" customprefix:layout_width="wrap_content" customprefix:layout_height="wrap_content"></Button>
- <Button customprefix:text="Button" customprefix:id="@+id/button2" customprefix:layout_width="wrap_content" customprefix:layout_height="wrap_content"></Button>
-</LinearLayout>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3.info b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3.info
deleted file mode 100644
index ef3324eb4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3.info
+++ /dev/null
@@ -1,5 +0,0 @@
-android.widget.LinearLayout [0,36,240,320] <LinearLayout>
- android.widget.Button [0,0,49,36] <Button>
- android.widget.ImageView [0,36,128,248] <ImageView>
- android.widget.Button [0,248,49,284] <Button>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3.xml
deleted file mode 100644
index ddd136ce8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample3.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/newlinear" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
- <Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
- <ImageView android:id="@+id/android_logo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/android_button" android:focusable="false" android:clickable="false" android:layout_weight="1.0" />
- <Button android:text="Button" android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
-</LinearLayout>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample4-expected-changeLayout4.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample4-expected-changeLayout4.xml
deleted file mode 100644
index 6e5552950..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample4-expected-changeLayout4.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/RelativeLayout1"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
-
- <CheckBox
- android:id="@+id/checkBox1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_alignParentTop="true"
- android:text="CheckBox" >
- </CheckBox>
-
- <Button
- android:id="@+id/button5"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentRight="true"
- android:layout_below="@+id/checkBox1"
- android:text="Button" >
- </Button>
-
-</RelativeLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample4.info b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample4.info
deleted file mode 100644
index 605c17793..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample4.info
+++ /dev/null
@@ -1,5 +0,0 @@
-android.widget.LinearLayout [0,36,240,320] <LinearLayout>
- android.widget.CheckBox [0,0,80,36] <CheckBox>
- android.widget.RelativeLayout [0,36,240,284] <RelativeLayout>
- android.widget.Button [191,0,240,36] <Button>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample4.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample4.xml
deleted file mode 100644
index a56f27294..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample4.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
- <CheckBox android:text="CheckBox" android:id="@+id/checkBox1" android:layout_width="wrap_content" android:layout_height="wrap_content"></CheckBox>
- <RelativeLayout android:layout_height="match_parent" android:id="@+id/relativeLayout1" android:layout_width="match_parent">
- <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" android:id="@+id/button5" android:layout_alignParentRight="true"></Button>
- </RelativeLayout>
-</LinearLayout>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample5-expected-changeLayout5.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample5-expected-changeLayout5.xml
deleted file mode 100644
index 06b236dfb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample5-expected-changeLayout5.xml
+++ /dev/null
@@ -1,70 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/RelativeLayout1"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
-
- <Button
- android:id="@+id/button1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentTop="true"
- android:layout_centerHorizontal="true"
- android:layout_gravity="center_horizontal"
- android:text="Button" >
- </Button>
-
- <Button
- android:id="@+id/button2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@+id/button1"
- android:layout_centerHorizontal="true"
- android:layout_gravity="center"
- android:text="Button" >
- </Button>
-
- <Button
- android:id="@+id/button3"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentRight="true"
- android:layout_below="@+id/button2"
- android:layout_gravity="right"
- android:text="Button" >
- </Button>
-
- <Button
- android:id="@+id/button4"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_below="@+id/button3"
- android:layout_gravity="center"
- android:layout_marginTop="70dp"
- android:text="Button" >
- </Button>
-
- <Button
- android:id="@+id/button5"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignBaseline="@+id/button4"
- android:layout_alignTop="@+id/button4"
- android:layout_gravity="center_vertical"
- android:layout_toRightOf="@+id/button4"
- android:text="Button" >
- </Button>
-
- <Button
- android:id="@+id/button6"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentBottom="true"
- android:layout_gravity="bottom"
- android:layout_toRightOf="@+id/button5"
- android:text="Button" >
- </Button>
-
-</RelativeLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample5-expected-gridLayout5.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample5-expected-gridLayout5.xml
deleted file mode 100644
index dd9f18cf2..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample5-expected-gridLayout5.xml
+++ /dev/null
@@ -1,51 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/GridLayout1"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:columnCount="4"
- android:orientation="horizontal" >
-
- <Button
- android:id="@+id/button1"
- android:layout_columnSpan="2"
- android:layout_gravity="center_horizontal"
- android:text="Button" >
- </Button>
-
- <Button
- android:id="@+id/button2"
- android:layout_columnSpan="2"
- android:layout_gravity="center"
- android:layout_row="1"
- android:text="Button" >
- </Button>
-
- <Button
- android:id="@+id/button3"
- android:layout_column="2"
- android:layout_columnSpan="2"
- android:layout_gravity="right"
- android:text="Button" >
- </Button>
-
- <Button
- android:id="@+id/button4"
- android:layout_gravity="center"
- android:text="Button" >
- </Button>
-
- <Button
- android:id="@+id/button5"
- android:layout_columnSpan="2"
- android:layout_gravity="center_vertical"
- android:text="Button" >
- </Button>
-
- <Button
- android:id="@+id/button6"
- android:layout_gravity="bottom"
- android:text="Button" >
- </Button>
-
-</GridLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample5.info b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample5.info
deleted file mode 100644
index fce532ecd..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample5.info
+++ /dev/null
@@ -1,9 +0,0 @@
-android.widget.LinearLayout [0,36,240,320] <LinearLayout>
- android.widget.Button [95,0,144,36] <Button>
- android.widget.Button [95,36,144,72] <Button>
- android.widget.Button [191,72,240,108] <Button>
- android.widget.LinearLayout [0,108,240,284] <LinearLayout>
- android.widget.Button [0,70,49,106] <Button>
- android.widget.Button [49,70,98,106] <Button>
- android.widget.Button [98,140,147,176] <Button>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample5.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample5.xml
deleted file mode 100644
index afc19388d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample5.xml
+++ /dev/null
@@ -1,12 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
- <Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal"></Button>
- <Button android:text="Button" android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center"></Button>
- <Button android:text="Button" android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right"></Button>
- <LinearLayout android:id="@+id/linearLayout1" android:layout_width="match_parent" android:layout_height="match_parent">
- <Button android:layout_height="wrap_content" android:layout_gravity="center" android:text="Button" android:id="@+id/button4" android:layout_width="wrap_content"></Button>
- <Button android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:text="Button" android:id="@+id/button5" android:layout_width="wrap_content"></Button>
- <Button android:layout_height="wrap_content" android:text="Button" android:id="@+id/button6" android:layout_width="wrap_content" android:layout_gravity="bottom"></Button>
- </LinearLayout>
-</LinearLayout>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample6-expected-changeLayout6.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample6-expected-changeLayout6.xml
deleted file mode 100644
index a91ad1e7b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample6-expected-changeLayout6.xml
+++ /dev/null
@@ -1,37 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/RelativeLayout1"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:baselineAligned="true" >
-
- <Button
- android:id="@+id/button1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignBaseline="@+id/button2"
- android:layout_alignParentLeft="true"
- android:layout_alignParentTop="true"
- android:text="Button" >
- </Button>
-
- <RadioButton
- android:id="@+id/radioButton1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignBaseline="@+id/button2"
- android:layout_alignParentTop="true"
- android:layout_toRightOf="@+id/button1"
- android:text="RadioButton" >
- </RadioButton>
-
- <Button
- android:id="@+id/button2"
- android:layout_width="wrap_content"
- android:layout_height="150dip"
- android:layout_alignParentTop="true"
- android:layout_toRightOf="@+id/radioButton1"
- android:text="Button" >
- </Button>
-
-</RelativeLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample6.info b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample6.info
deleted file mode 100644
index 7a7a44ab5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample6.info
+++ /dev/null
@@ -1,5 +0,0 @@
-android.widget.LinearLayout [0,36,240,320] <LinearLayout>
- android.widget.Button [0,38,49,74] <Button>
- android.widget.RadioButton [49,36,143,72] <RadioButton>
- android.widget.Button [143,0,192,113] <Button>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample6.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample6.xml
deleted file mode 100644
index 5cdc82493..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample6.xml
+++ /dev/null
@@ -1,7 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:baselineAligned="true">
- <Button android:text="Button" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
- <RadioButton android:text="RadioButton" android:id="@+id/radioButton1" android:layout_width="wrap_content" android:layout_height="wrap_content"></RadioButton>
- <Button android:layout_width="wrap_content" android:id="@+id/button2" android:text="Button" android:layout_height="150dip"></Button>
-</LinearLayout>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample7-expected-extract6.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample7-expected-extract6.diff
deleted file mode 100644
index 8a01599a6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample7-expected-extract6.diff
+++ /dev/null
@@ -1,10 +0,0 @@
-@@ -4 +4
-- <LinearLayout android:layout_height="wrap_content" android:id="@+id/linearLayout4" android:layout_width="match_parent">
-- <LinearLayout android:layout_height="match_parent" android:id="@+id/linearLayout5" android:layout_width="wrap_content">
-- <LinearLayout android:layout_height="match_parent" android:id="@+id/linearLayout6" android:layout_width="wrap_content">
-- <!-- Comment -->
-- <Button android:text="Button" android:id="@+id/button6" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
-- </LinearLayout>
-- </LinearLayout>
-- </LinearLayout>
-+ <include layout="@layout/newlayout6" android:id="@+id/linearLayout4_ref" android:layout_width="match_parent" android:layout_height="wrap_content"/>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample7-expected-extract7.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample7-expected-extract7.diff
deleted file mode 100644
index 3de135d77..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample7-expected-extract7.diff
+++ /dev/null
@@ -1,69 +0,0 @@
-@@ -2 +2
-- <LinearLayout android:id="@+id/LinearLayout2" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
-- <Button android:text="FirstButton" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
-- <LinearLayout android:layout_height="wrap_content" android:id="@+id/linearLayout4" android:layout_width="match_parent">
-- <LinearLayout android:layout_height="match_parent" android:id="@+id/linearLayout5" android:layout_width="wrap_content">
-- <LinearLayout android:layout_height="match_parent" android:id="@+id/linearLayout6" android:layout_width="wrap_content">
-- <!-- Comment -->
-- <Button android:text="Button" android:id="@+id/button6" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
-- </LinearLayout>
-- </LinearLayout>
-- </LinearLayout>
-- <LinearLayout android:layout_width="match_parent" android:id="@+id/linearLayout9" android:layout_height="wrap_content">
-- <Button android:text="SecondButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button2"></Button>
-- <Button android:text="ThirdButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button3"></Button>
-- <CheckBox android:id="@+id/checkBox1" android:text="CheckBox" android:layout_width="wrap_content" android:layout_height="wrap_content"></CheckBox>
-+ <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-+ android:id="@+id/LinearLayout2"
-+ android:layout_width="match_parent"
-+ android:layout_height="match_parent"
-+ android:orientation="vertical" >
-+
-+ <Button
-+ android:id="@+id/button1"
-+ android:layout_width="wrap_content"
-+ android:layout_height="wrap_content"
-+ android:text="FirstButton" >
-+ </Button>
-+
-+ <include
-+ android:id="@+id/linearLayout4_ref"
-+ android:layout_width="match_parent"
-+ android:layout_height="wrap_content"
-+ layout="@layout/newlayout6" />
-+
-+ <LinearLayout
-+ android:id="@+id/linearLayout9"
-+ android:layout_width="match_parent"
-+ android:layout_height="wrap_content" >
-+
-+ <Button
-+ android:id="@+id/button2"
-+ android:layout_width="wrap_content"
-+ android:layout_height="wrap_content"
-+ android:text="SecondButton" >
-+ </Button>
-+
-+ <Button
-+ android:id="@+id/button3"
-+ android:layout_width="wrap_content"
-+ android:layout_height="wrap_content"
-+ android:text="ThirdButton" >
-+ </Button>
-+
-+ <CheckBox
-+ android:id="@+id/checkBox1"
-+ android:layout_width="wrap_content"
-+ android:layout_height="wrap_content"
-+ android:text="CheckBox" >
-+ </CheckBox>
-@@ -17 +47
-- <Button android:layout_height="wrap_content" android:text="FourthButton" android:id="@+id/button4" android:layout_width="match_parent"></Button>
-+
-+ <Button
-+ android:id="@+id/button4"
-+ android:layout_width="match_parent"
-+ android:layout_height="wrap_content"
-+ android:text="FourthButton" >
-+ </Button>
-+
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample7.info b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample7.info
deleted file mode 100644
index 134234c44..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample7.info
+++ /dev/null
@@ -1,11 +0,0 @@
-android.widget.LinearLayout [0,0,240,320] <LinearLayout>
- android.widget.Button [0,0,101,36] <Button>
- android.widget.LinearLayout [0,36,240,72] <LinearLayout>
- android.widget.LinearLayout [0,0,73,36] <LinearLayout>
- android.widget.LinearLayout [0,0,73,36] <LinearLayout>
- android.widget.Button [0,0,73,36] <Button>
- android.widget.LinearLayout [0,72,240,192] <LinearLayout>
- android.widget.Button [0,0,117,36] <Button>
- android.widget.Button [117,0,223,36] <Button>
- android.widget.CheckBox [223,10,240,130] <CheckBox>
- android.widget.Button [0,192,240,228] <Button>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample7.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample7.xml
deleted file mode 100644
index 0445bbf8f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample7.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout android:id="@+id/LinearLayout2" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
- <Button android:text="FirstButton" android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
- <LinearLayout android:layout_height="wrap_content" android:id="@+id/linearLayout4" android:layout_width="match_parent">
- <LinearLayout android:layout_height="match_parent" android:id="@+id/linearLayout5" android:layout_width="wrap_content">
- <LinearLayout android:layout_height="match_parent" android:id="@+id/linearLayout6" android:layout_width="wrap_content">
- <!-- Comment -->
- <Button android:text="Button" android:id="@+id/button6" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
- </LinearLayout>
- </LinearLayout>
- </LinearLayout>
- <LinearLayout android:layout_width="match_parent" android:id="@+id/linearLayout9" android:layout_height="wrap_content">
- <Button android:text="SecondButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button2"></Button>
- <Button android:text="ThirdButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/button3"></Button>
- <CheckBox android:id="@+id/checkBox1" android:text="CheckBox" android:layout_width="wrap_content" android:layout_height="wrap_content"></CheckBox>
- </LinearLayout>
- <Button android:layout_height="wrap_content" android:text="FourthButton" android:id="@+id/button4" android:layout_width="match_parent"></Button>
-</LinearLayout>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample8-expected-extract6.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample8-expected-extract6.diff
deleted file mode 100644
index ea3afc2e3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample8-expected-extract6.diff
+++ /dev/null
@@ -1,15 +0,0 @@
-@@ -10 +10
-- <LinearLayout android:layout_height="wrap_content"
-- android:id="@+id/linearLayout4" android:layout_width="match_parent">
-- <LinearLayout android:layout_height="match_parent"
-- android:layout_width="wrap_content" android:id="@+id/linearLayout5">
-- <LinearLayout android:layout_height="match_parent"
-- android:id="@+id/linearLayout6"
-- android:layout_width="wrap_content">
-- <Button android:text="Button" android:id="@+id/button6"
-- android:layout_width="wrap_content"
-- android:layout_height="wrap_content"></Button>
-- </LinearLayout>
-- </LinearLayout>
-- </LinearLayout>
-+ <include layout="@layout/newlayout6" android:id="@+id/linearLayout4_ref" android:layout_width="match_parent" android:layout_height="wrap_content"/>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample8-expected-extract7.diff b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample8-expected-extract7.diff
deleted file mode 100644
index 8228b597e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample8-expected-extract7.diff
+++ /dev/null
@@ -1,85 +0,0 @@
-@@ -2 +2
-- <LinearLayout android:id="@+id/LinearLayout2"
-- xmlns:android="http://schemas.android.com/apk/res/android"
-- android:layout_width="match_parent" android:layout_height="match_parent"
-- android:orientation="vertical">
-- <Button android:text="FirstButton" android:id="@+id/button1"
-- android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
-- <FrameLayout android:id="@+id/outer"
-- android:layout_width="match_parent" android:layout_height="wrap_content">
-- <LinearLayout android:layout_height="wrap_content"
-- android:id="@+id/linearLayout4" android:layout_width="match_parent">
-- <LinearLayout android:layout_height="match_parent"
-- android:layout_width="wrap_content" android:id="@+id/linearLayout5">
-- <LinearLayout android:layout_height="match_parent"
-- android:id="@+id/linearLayout6"
-- android:layout_width="wrap_content">
-- <Button android:text="Button" android:id="@+id/button6"
-- android:layout_width="wrap_content"
-- android:layout_height="wrap_content"></Button>
-- </LinearLayout>
-- </LinearLayout>
-- </LinearLayout>
-+ <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
-+ android:id="@+id/LinearLayout2"
-+ android:layout_width="match_parent"
-+ android:layout_height="match_parent"
-+ android:orientation="vertical" >
-+
-+ <Button
-+ android:id="@+id/button1"
-+ android:layout_width="wrap_content"
-+ android:layout_height="wrap_content"
-+ android:text="FirstButton" >
-+ </Button>
-+
-+ <FrameLayout
-+ android:id="@+id/outer"
-+ android:layout_width="match_parent"
-+ android:layout_height="wrap_content" >
-+
-+ <include
-+ android:id="@+id/linearLayout4_ref"
-+ android:layout_width="match_parent"
-+ android:layout_height="wrap_content"
-+ layout="@layout/newlayout6" />
-@@ -24 +26
-- <FrameLayout android:id="@+id/outer"
-- android:layout_width="match_parent" android:layout_height="wrap_content">
-- <LinearLayout android:layout_height="wrap_content"
-- android:id="@+id/linearLayout4" android:layout_width="match_parent">
-- <LinearLayout android:layout_height="match_parent"
-- android:layout_width="wrap_content" android:id="@+id/linearLayout5">
-- <LinearLayout android:layout_height="match_parent"
-+
-+ <FrameLayout
-+ android:id="@+id/outer"
-+ android:layout_width="match_parent"
-+ android:layout_height="wrap_content" >
-+
-+ <LinearLayout
-+ android:id="@+id/linearLayout4"
-+ android:layout_width="match_parent"
-+ android:layout_height="wrap_content" >
-+
-+ <LinearLayout
-+ android:id="@+id/linearLayout5"
-+ android:layout_width="wrap_content"
-+ android:layout_height="match_parent" >
-+
-+ <LinearLayout
-@@ -32 +44
-- android:layout_width="wrap_content">
-- <Button android:text="Button" android:id="@+id/button6"
-+ android:layout_width="wrap_content"
-+ android:layout_height="match_parent" >
-+
-+ <Button
-+ android:id="@+id/button6"
-@@ -35 +50
-- android:layout_height="wrap_content"></Button>
-+ android:layout_height="wrap_content"
-+ android:text="Button" >
-+ </Button>
-@@ -40 +57
-+
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample8.info b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample8.info
deleted file mode 100644
index ca294ba10..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample8.info
+++ /dev/null
@@ -1,12 +0,0 @@
-android.widget.LinearLayout [0,0,240,320] <LinearLayout>
- android.widget.Button [0,0,101,36] <Button>
- android.widget.FrameLayout [0,36,240,72] <FrameLayout>
- android.widget.LinearLayout [0,0,240,36] <LinearLayout>
- android.widget.LinearLayout [0,0,73,36] <LinearLayout>
- android.widget.LinearLayout [0,0,73,36] <LinearLayout>
- android.widget.Button [0,0,73,36] <Button>
- android.widget.FrameLayout [0,72,240,108] <FrameLayout>
- android.widget.LinearLayout [0,0,240,36] <LinearLayout>
- android.widget.LinearLayout [0,0,73,36] <LinearLayout>
- android.widget.LinearLayout [0,0,73,36] <LinearLayout>
- android.widget.Button [0,0,73,36] <Button>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample8.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample8.xml
deleted file mode 100644
index c7984692e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample8.xml
+++ /dev/null
@@ -1,40 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout android:id="@+id/LinearLayout2"
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent" android:layout_height="match_parent"
- android:orientation="vertical">
- <Button android:text="FirstButton" android:id="@+id/button1"
- android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
- <FrameLayout android:id="@+id/outer"
- android:layout_width="match_parent" android:layout_height="wrap_content">
- <LinearLayout android:layout_height="wrap_content"
- android:id="@+id/linearLayout4" android:layout_width="match_parent">
- <LinearLayout android:layout_height="match_parent"
- android:layout_width="wrap_content" android:id="@+id/linearLayout5">
- <LinearLayout android:layout_height="match_parent"
- android:id="@+id/linearLayout6"
- android:layout_width="wrap_content">
- <Button android:text="Button" android:id="@+id/button6"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"></Button>
- </LinearLayout>
- </LinearLayout>
- </LinearLayout>
- </FrameLayout>
- <FrameLayout android:id="@+id/outer"
- android:layout_width="match_parent" android:layout_height="wrap_content">
- <LinearLayout android:layout_height="wrap_content"
- android:id="@+id/linearLayout4" android:layout_width="match_parent">
- <LinearLayout android:layout_height="match_parent"
- android:layout_width="wrap_content" android:id="@+id/linearLayout5">
- <LinearLayout android:layout_height="match_parent"
- android:id="@+id/linearLayout6"
- android:layout_width="wrap_content">
- <Button android:text="Button" android:id="@+id/button6"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"></Button>
- </LinearLayout>
- </LinearLayout>
- </LinearLayout>
- </FrameLayout>
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample9-expected-convertToGrid.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample9-expected-convertToGrid.xml
deleted file mode 100644
index 03ffac714..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample9-expected-convertToGrid.xml
+++ /dev/null
@@ -1,37 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/GridLayout1"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:columnCount="3"
- android:orientation="horizontal" >
-
- <Button
- android:id="@+id/button1"
- android:layout_gravity="left"
- android:text="Button" />
-
- <RadioButton
- android:id="@+id/radioButton1"
- android:layout_width="150dp"
- android:layout_column="0"
- android:layout_gravity="left"
- android:text="RadioButton" />
-
- <RadioButton
- android:id="@+id/radioButton2"
- android:layout_gravity="left"
- android:text="RadioButton" />
-
- <CheckBox
- android:id="@+id/checkBox1"
- android:layout_column="0"
- android:layout_gravity="left"
- android:text="CheckBox" />
-
- <Space
- android:layout_column="2"
- android:layout_gravity="fill_vertical"
- android:layout_row="3" />
-
-</GridLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample9.info b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample9.info
deleted file mode 100644
index 3085ff074..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample9.info
+++ /dev/null
@@ -1,6 +0,0 @@
-android.widget.LinearLayout [0,73,320,480] <LinearLayout>
- android.widget.Button [0,0,79,48] <Button>
- android.widget.LinearLayout [0,48,320,86] <LinearLayout>
- android.widget.RadioButton [0,0,150,38] <RadioButton>
- android.widget.RadioButton [150,0,273,38] <RadioButton>
- android.widget.CheckBox [0,86,107,124] <CheckBox>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample9.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample9.xml
deleted file mode 100644
index 13068e763..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/sample9.xml
+++ /dev/null
@@ -1,39 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/LinearLayout1"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
-
- <Button
- android:id="@+id/button1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Button" />
-
- <LinearLayout
- android:id="@+id/linearLayout2"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" >
-
- <RadioButton
- android:id="@+id/radioButton1"
- android:layout_width="150dp"
- android:layout_height="wrap_content"
- android:text="RadioButton" />
-
- <RadioButton
- android:id="@+id/radioButton2"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="RadioButton" />
-
- </LinearLayout>
-
- <CheckBox
- android:id="@+id/checkBox1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="CheckBox" />
-
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/unwrap-expected-unwrap1.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/unwrap-expected-unwrap1.xml
deleted file mode 100644
index e5aba11bb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/unwrap-expected-unwrap1.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/linear"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:orientation="vertical" >
-
- <TextView
- android:id="@+id/text"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello" />
-
- <Button
- android:id="@+id/button"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello" />
-
-</LinearLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/unwrap-expected-unwrap2.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/unwrap-expected-unwrap2.xml
deleted file mode 100644
index e5aba11bb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/unwrap-expected-unwrap2.xml
+++ /dev/null
@@ -1,20 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/linear"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:orientation="vertical" >
-
- <TextView
- android:id="@+id/text"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello" />
-
- <Button
- android:id="@+id/button"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello" />
-
-</LinearLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/unwrap-expected-unwrap3.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/unwrap-expected-unwrap3.xml
deleted file mode 100644
index 348b2bc81..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/unwrap-expected-unwrap3.xml
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/frame"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content" >
-
- <TextView
- android:id="@+id/text"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello" />
-
- <Button
- android:id="@+id/button"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello" />
-
-</FrameLayout> \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/unwrap.info b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/unwrap.info
deleted file mode 100644
index c5461b399..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/unwrap.info
+++ /dev/null
@@ -1,4 +0,0 @@
-android.widget.LinearLayout [0,56,1280,104] <LinearLayout>
- android.widget.FrameLayout [0,0,1280,48] <FrameLayout>
- android.widget.TextView [0,0,1280,17] <TextView>
- android.widget.Button [0,0,1280,48] <Button>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/unwrap.xml b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/unwrap.xml
deleted file mode 100644
index db94dc358..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/layout/refactoring/testdata/unwrap.xml
+++ /dev/null
@@ -1,26 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:id="@+id/linear"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:orientation="vertical" >
-
- <FrameLayout
- android:id="@+id/frame"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content" >
-
- <TextView
- android:id="@+id/text"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello" />
-
- <Button
- android:id="@+id/button"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="@string/hello" />
- </FrameLayout>
-
-</LinearLayout>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/manifest/ManifestInfoTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/manifest/ManifestInfoTest.java
deleted file mode 100644
index 43f9d681f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/editors/manifest/ManifestInfoTest.java
+++ /dev/null
@@ -1,424 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.manifest;
-
-import static com.android.resources.ScreenSize.LARGE;
-import static com.android.resources.ScreenSize.NORMAL;
-import static com.android.resources.ScreenSize.XLARGE;
-
-import com.android.annotations.NonNull;
-import com.android.ide.eclipse.adt.internal.editors.layout.refactoring.AdtProjectTest;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo.ActivityAttributes;
-import com.android.ide.eclipse.adt.internal.resources.ResourceHelper;
-import com.android.sdklib.AndroidVersion;
-import com.android.sdklib.BuildToolInfo;
-import com.android.sdklib.IAndroidTarget;
-import com.android.sdklib.ISystemImage;
-import com.android.sdklib.repository.descriptors.IdDisplay;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.runtime.NullProgressMonitor;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-@SuppressWarnings("javadoc")
-public class ManifestInfoTest extends AdtProjectTest {
- @Override
- protected boolean testCaseNeedsUniqueProject() {
- return true;
- }
-
- public void testGetActivityThemes1() throws Exception {
- ManifestInfo info = getManifestInfo(
- "<manifest xmlns:android='http://schemas.android.com/apk/res/android'\n" +
- " package='com.android.unittest'>\n" +
- " <uses-sdk android:minSdkVersion='3' android:targetSdkVersion='4'/>\n" +
- "</manifest>\n");
- Map<String, ActivityAttributes> map = info.getActivityAttributesMap();
- assertEquals(map.toString(), 0, map.size());
- assertEquals("com.android.unittest", info.getPackage());
- assertEquals("Theme", ResourceHelper.styleToTheme(info.getDefaultTheme(null, NORMAL)));
- assertEquals("@android:style/Theme", info.getDefaultTheme(null, null));
- assertEquals("Theme", ResourceHelper.styleToTheme(info.getDefaultTheme(null, XLARGE)));
- }
-
- public void testGetActivityThemes2() throws Exception {
- ManifestInfo info = getManifestInfo(
- "<manifest xmlns:android='http://schemas.android.com/apk/res/android'\n" +
- " package='com.android.unittest'>\n" +
- " <uses-sdk android:minSdkVersion='3' android:targetSdkVersion='11'/>\n" +
- "</manifest>\n");
- Map<String, ActivityAttributes> map = info.getActivityAttributesMap();
- assertEquals(map.toString(), 0, map.size());
- assertEquals("com.android.unittest", info.getPackage());
- assertEquals("Theme.Holo", ResourceHelper.styleToTheme(info.getDefaultTheme(null,
- XLARGE)));
- assertEquals("Theme", ResourceHelper.styleToTheme(info.getDefaultTheme(null, LARGE)));
- }
-
- public void testGetActivityThemes3() throws Exception {
- ManifestInfo info = getManifestInfo(
- "<manifest xmlns:android='http://schemas.android.com/apk/res/android'\n" +
- " package='com.android.unittest'>\n" +
- " <uses-sdk android:minSdkVersion='11'/>\n" +
- "</manifest>\n");
- Map<String, ActivityAttributes> map = info.getActivityAttributesMap();
- assertEquals(map.toString(), 0, map.size());
- assertEquals("com.android.unittest", info.getPackage());
- assertEquals("Theme.Holo", ResourceHelper.styleToTheme(info.getDefaultTheme(null,
- XLARGE)));
- assertEquals("Theme", ResourceHelper.styleToTheme(info.getDefaultTheme(null, NORMAL)));
- }
-
- public void testGetActivityThemes4() throws Exception {
- ManifestInfo info = getManifestInfo(
- "<manifest xmlns:android='http://schemas.android.com/apk/res/android'\n" +
- " package='com.android.unittest'>\n" +
- " <application\n" +
- " android:label='@string/app_name'\n" +
- " android:name='.app.TestApp' android:icon='@drawable/app_icon'>\n" +
- "\n" +
- " <activity\n" +
- " android:name='.prefs.PrefsActivity'\n" +
- " android:label='@string/prefs_title' />\n" +
- "\n" +
- " <activity\n" +
- " android:name='.app.IntroActivity'\n" +
- " android:label='@string/intro_title'\n" +
- " android:theme='@android:style/Theme.Dialog' />\n" +
- " </application>\n" +
- " <uses-sdk android:minSdkVersion='3' android:targetSdkVersion='4'/>\n" +
- "</manifest>\n" +
- ""
- );
- assertEquals("com.android.unittest", info.getPackage());
- assertEquals("Theme", ResourceHelper.styleToTheme(info.getDefaultTheme(null, XLARGE)));
-
- Map<String, ActivityAttributes> map = info.getActivityAttributesMap();
- assertEquals(map.toString(), 2, map.size());
- assertNull(map.get("com.android.unittest.prefs.PrefsActivity").getTheme());
- assertEquals("@android:style/Theme.Dialog",
- map.get("com.android.unittest.app.IntroActivity").getTheme());
- }
-
- public void testGetActivityThemes5() throws Exception {
- ManifestInfo info = getManifestInfo(
- "<manifest xmlns:android='http://schemas.android.com/apk/res/android'\n" +
- " package='com.android.unittest'>\n" +
- " <application\n" +
- " android:label='@string/app_name'\n" +
- " android:theme='@style/NoBackground'\n" +
- " android:name='.app.TestApp' android:icon='@drawable/app_icon'>\n" +
- "\n" +
- " <activity\n" +
- " android:name='.prefs.PrefsActivity'\n" +
- " android:label='@string/prefs_title' />\n" +
- "\n" +
- " <activity\n" +
- " android:name='.app.IntroActivity'\n" +
- " android:label='@string/intro_title'\n" +
- " android:theme='@android:style/Theme.Dialog' />\n" +
- " </application>\n" +
- " <uses-sdk android:minSdkVersion='3' android:targetSdkVersion='4'/>\n" +
- "</manifest>\n" +
- ""
- );
-
- assertEquals("@style/NoBackground", info.getDefaultTheme(null, XLARGE));
- assertEquals("@style/NoBackground", info.getDefaultTheme(null, NORMAL));
- assertEquals("NoBackground", ResourceHelper.styleToTheme(info.getDefaultTheme(null,
- NORMAL)));
-
- Map<String, ActivityAttributes> map = info.getActivityAttributesMap();
- assertEquals(map.toString(), 2, map.size());
- assertNull(map.get("com.android.unittest.prefs.PrefsActivity").getTheme());
- assertEquals("@android:style/Theme.Dialog",
- map.get("com.android.unittest.app.IntroActivity").getTheme());
- }
-
- public void testGetActivityThemes6() throws Exception {
- // Ensures that when the *rendering* target is less than version 11, we don't
- // use Holo even though the manifest SDK version calls for it.
- ManifestInfo info = getManifestInfo(
- "<manifest xmlns:android='http://schemas.android.com/apk/res/android'\n" +
- " package='com.android.unittest'>\n" +
- " <uses-sdk android:minSdkVersion='3' android:targetSdkVersion='11'/>\n" +
- "</manifest>\n");
- Map<String, ActivityAttributes> map = info.getActivityAttributesMap();
- assertEquals(map.toString(), 0, map.size());
- assertEquals("com.android.unittest", info.getPackage());
- assertEquals("Theme.Holo", ResourceHelper.styleToTheme(info.getDefaultTheme(null,
- XLARGE)));
-
- // Here's the check
- IAndroidTarget olderVersion = new TestAndroidTarget(4);
- assertEquals("Theme", ResourceHelper.styleToTheme(info.getDefaultTheme(olderVersion,
- XLARGE)));
-
- }
-
- public void testGetApplicationLabelAndIcon() throws Exception {
- ManifestInfo info = getManifestInfo(
- "<manifest xmlns:android='http://schemas.android.com/apk/res/android'\n" +
- " package='com.android.unittest'>\n" +
- " <application android:icon=\"@drawable/icon\"\n" +
- " android:label=\"@string/app_name\">\n" +
- " </application>\n" +
- "" +
- "</manifest>\n");
- Map<String, ActivityAttributes> map = info.getActivityAttributesMap();
- assertEquals(map.toString(), 0, map.size());
- assertEquals("com.android.unittest", info.getPackage());
-
- assertEquals("Theme", ResourceHelper.styleToTheme(info.getDefaultTheme(null, NORMAL)));
- assertEquals("@drawable/icon", info.getApplicationIcon());
- assertEquals("@string/app_name", info.getApplicationLabel());
- }
-
- public void testGetApplicationNoLabelOrIcon() throws Exception {
- ManifestInfo info = getManifestInfo(
- "<manifest xmlns:android='http://schemas.android.com/apk/res/android'\n" +
- " package='com.android.unittest'>\n" +
- " <application>\n" +
- " </application>\n" +
- "" +
- "</manifest>\n");
- Map<String, ActivityAttributes> map = info.getActivityAttributesMap();
- assertEquals(map.toString(), 0, map.size());
- assertEquals("com.android.unittest", info.getPackage());
-
- assertEquals("Theme", ResourceHelper.styleToTheme(info.getDefaultTheme(null, NORMAL)));
- assertNull(info.getApplicationIcon());
- assertNull(info.getApplicationLabel());
- }
-
- private ManifestInfo getManifestInfo(String manifestContents) throws Exception {
- InputStream bstream = new ByteArrayInputStream(
- manifestContents.getBytes("UTF-8")); //$NON-NLS-1$
-
- IFile file = getProject().getFile("AndroidManifest.xml");
- if (file.exists()) {
- file.setContents(bstream, IFile.FORCE, new NullProgressMonitor());
- } else {
- file.create(bstream, false /* force */, new NullProgressMonitor());
- }
- ManifestInfo info = ManifestInfo.get(getProject());
- info.clear();
- return info;
- }
-
- public void testGetMinSdkVersionName() throws Exception {
- ManifestInfo info;
-
- info = getManifestInfo(
- "<manifest xmlns:android='http://schemas.android.com/apk/res/android'\n" +
- " package='com.android.unittest'>\n" +
- " <uses-sdk android:minSdkVersion='3' android:targetSdkVersion='4'/>\n" +
- "</manifest>\n");
- assertEquals(3, info.getMinSdkVersion());
- assertEquals("3", info.getMinSdkName());
- assertEquals(4, info.getTargetSdkVersion());
- assertNull(info.getMinSdkCodeName());
-
- info = getManifestInfo(
- "<manifest xmlns:android='http://schemas.android.com/apk/res/android'\n" +
- " package='com.android.unittest'>\n" +
- " <uses-sdk android:targetSdkVersion='4'/>\n" +
- "</manifest>\n");
- assertEquals("1", info.getMinSdkName());
- assertEquals(1, info.getMinSdkVersion());
- assertEquals(4, info.getTargetSdkVersion());
- assertNull(info.getMinSdkCodeName());
-
- info = getManifestInfo(
- "<manifest xmlns:android='http://schemas.android.com/apk/res/android'\n" +
- " package='com.android.unittest'>\n" +
- " <uses-sdk android:minSdkVersion='JellyBean' />\n" +
- "</manifest>\n");
- assertEquals("JellyBean", info.getMinSdkName());
- assertEquals("JellyBean", info.getMinSdkCodeName());
- }
-
- private static class TestAndroidTarget implements IAndroidTarget {
- private final int mApiLevel;
-
- public TestAndroidTarget(int apiLevel) {
- mApiLevel = apiLevel;
- }
-
- @Override
- public boolean canRunOn(IAndroidTarget target) {
- return false;
- }
-
- @Override
- public String getClasspathName() {
- return null;
- }
-
- @Override
- public File getDefaultSkin() {
- return null;
- }
-
- @Override
- public String getDescription() {
- return null;
- }
-
- @Override
- public String getFullName() {
- return null;
- }
-
- @Override
- public ISystemImage getSystemImage(IdDisplay tag, String abiType) {
- return null;
- }
-
- @Override
- public ISystemImage[] getSystemImages() {
- return new ISystemImage[0];
- }
-
- @Override
- public String getLocation() {
- return null;
- }
-
- @Override
- public String getName() {
- return null;
- }
-
- @Override
- public IOptionalLibrary[] getOptionalLibraries() {
- return null;
- }
-
- @Override
- public IAndroidTarget getParent() {
- return null;
- }
-
- @Override
- public String getPath(int pathId) {
- return null;
- }
-
- @Override
- public File getFile(int pathId) {
- return null;
- }
-
-
- @Override
- public String[] getPlatformLibraries() {
- return null;
- }
-
- @Override
- public Map<String, String> getProperties() {
- return null;
- }
-
- @Override
- public String getProperty(String name) {
- return null;
- }
-
- @Override
- public Integer getProperty(String name, Integer defaultValue) {
- return null;
- }
-
- @Override
- public Boolean getProperty(String name, Boolean defaultValue) {
- return null;
- }
-
- @Override
- public int getRevision() {
- return 0;
- }
-
- @Override
- public File[] getSkins() {
- return null;
- }
-
- @Override
- public int getUsbVendorId() {
- return 0;
- }
-
- @Override
- public String getVendor() {
- return null;
- }
-
- @Override
- public AndroidVersion getVersion() {
- return new AndroidVersion(mApiLevel, null);
- }
-
- @Override
- public String getVersionName() {
- return null;
- }
-
- @Override
- public String hashString() {
- return null;
- }
-
- @Override
- public boolean isPlatform() {
- return false;
- }
-
- @Override
- public int compareTo(IAndroidTarget o) {
- return 0;
- }
-
- @Override
- public boolean hasRenderingLibrary() {
- return false;
- }
-
- @Override
- public String getShortClasspathName() {
- return null;
- }
-
- @Override
- @NonNull
- public List<String> getBootClasspath() {
- return new ArrayList<String>();
- }
-
- @Override
- public BuildToolInfo getBuildToolInfo() {
- return null;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/launch/JUnitLaunchConfigDelegateTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/launch/JUnitLaunchConfigDelegateTest.java
deleted file mode 100644
index 58f686adc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/launch/JUnitLaunchConfigDelegateTest.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.launch;
-
-import com.android.ide.eclipse.adt.internal.launch.JUnitLaunchConfigDelegate;
-
-import java.io.IOException;
-import java.util.Arrays;
-import junit.framework.TestCase;
-
-public class JUnitLaunchConfigDelegateTest extends TestCase {
-
- public void testAbleToFetchJunitJar() throws IOException {
- assertTrue(JUnitLaunchConfigDelegate.getJunitJarLocation().endsWith("junit.jar"));
- }
-
- public void testFixBootpathExtWithAndroidJar() {
- String[][] testArray = {
- null,
- {},
- { "android.jar"},
- null,
- { "some_other_jar.jar" },
- };
-
- String[][] expectedArray = {
- null,
- {},
- null,
- null,
- { "some_other_jar.jar" },
- };
-
- assertEqualsArrays(expectedArray, JUnitLaunchConfigDelegate.fixBootpathExt(testArray));
- }
-
- public void testFixBootpathExtWithNoAndroidJar() {
- String[][] testArray = {
- null,
- { "somejar.jar"},
- null,
- };
-
- String[][] expectedArray = {
- null,
- { "somejar.jar"},
- null,
- };
-
- assertEqualsArrays(expectedArray, JUnitLaunchConfigDelegate.fixBootpathExt(testArray));
- }
-
- public void testFixClasspathWithJunitJar() throws IOException {
- String[] testArray = {
- JUnitLaunchConfigDelegate.getJunitJarLocation(),
- };
-
- String[] expectedArray = {
- JUnitLaunchConfigDelegate.getJunitJarLocation(),
- };
-
- assertEqualsArrays(expectedArray,
- JUnitLaunchConfigDelegate.fixClasspath(testArray, "test"));
- }
-
- public void testFixClasspathWithoutJunitJar() throws IOException {
- String[] testArray = {
- "random.jar",
- };
-
- String[] expectedArray = {
- "random.jar",
- JUnitLaunchConfigDelegate.getJunitJarLocation(),
- };
-
- assertEqualsArrays(expectedArray,
- JUnitLaunchConfigDelegate.fixClasspath(testArray, "test"));
- }
-
-
- public void testFixClasspathWithNoJars() throws IOException {
- String[] testArray = {
- };
-
- String[] expectedArray = {
- JUnitLaunchConfigDelegate.getJunitJarLocation(),
- };
-
- assertEqualsArrays(expectedArray,
- JUnitLaunchConfigDelegate.fixClasspath(testArray, "test"));
- }
-
- private void assertEqualsArrays(String[][] a1, String[][] a2) {
- assertTrue(Arrays.deepEquals(a1, a2));
- }
-
- private void assertEqualsArrays(String[] a1, String[] a2) {
- assertTrue(Arrays.deepEquals(a1, a2));
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/lint/ProjectLintConfigurationTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/lint/ProjectLintConfigurationTest.java
deleted file mode 100644
index f8ea8c435..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/lint/ProjectLintConfigurationTest.java
+++ /dev/null
@@ -1,218 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.lint;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.internal.editors.layout.refactoring.AdtProjectTest;
-import com.android.tools.lint.checks.DuplicateIdDetector;
-import com.android.tools.lint.checks.UnusedResourceDetector;
-import com.android.tools.lint.client.api.Configuration;
-import com.android.tools.lint.client.api.JavaParser;
-import com.android.tools.lint.client.api.LintClient;
-import com.android.tools.lint.client.api.XmlParser;
-import com.android.tools.lint.detector.api.Context;
-import com.android.tools.lint.detector.api.Issue;
-import com.android.tools.lint.detector.api.Location;
-import com.android.tools.lint.detector.api.Project;
-import com.android.tools.lint.detector.api.Severity;
-import com.android.tools.lint.detector.api.TextFormat;
-
-import org.eclipse.core.resources.IProject;
-
-import java.io.File;
-
-@SuppressWarnings("javadoc")
-public class ProjectLintConfigurationTest extends AdtProjectTest {
- public void testBasic() {
- Configuration parent = null;
- LintClient client = new TestClient();
-
- File dir = getTargetDir();
- if (!dir.exists()) {
- boolean ok = dir.mkdirs();
- assertTrue(dir.getPath(), ok);
- }
- Project project = client.getProject(dir, dir);
-
- ProjectLintConfiguration config =
- new ProjectLintConfiguration(client, project, parent, false /*fatalOnly*/);
-
- Issue usuallyEnabledIssue = DuplicateIdDetector.WITHIN_LAYOUT;
- Issue usuallyDisabledIssue = UnusedResourceDetector.ISSUE_IDS;
-
- assertTrue(config.isEnabled(usuallyEnabledIssue));
- assertFalse(config.isEnabled(usuallyDisabledIssue));
-
- config.setSeverity(usuallyEnabledIssue, Severity.IGNORE);
- config.setSeverity(usuallyDisabledIssue, Severity.ERROR);
- assertFalse(config.isEnabled(usuallyEnabledIssue));
- assertTrue(config.isEnabled(usuallyDisabledIssue));
-
- // Make a NEW config object to ensure the state is persisted properly, not just
- // kept on the config object!
- config = new ProjectLintConfiguration(client, project, parent, false /*fatalOnly*/);
- assertFalse(config.isEnabled(usuallyEnabledIssue));
- assertTrue(config.isEnabled(usuallyDisabledIssue));
- }
-
- public void testInheritance() {
- Configuration parent = null;
- LintClient client = new TestClient();
-
- File dir = getTargetDir();
- assertTrue(dir.mkdirs());
- Project project = client.getProject(dir, dir);
-
- File otherDir = new File(dir, "otherConfig");
- assertTrue(otherDir.mkdir());
- Project otherProject = client.getProject(otherDir, otherDir);
-
- ProjectLintConfiguration otherConfig =
- new ProjectLintConfiguration(client, otherProject, parent, false);
-
- ProjectLintConfiguration config =
- new ProjectLintConfiguration(client, project, otherConfig, false);
-
- Issue usuallyEnabledIssue = DuplicateIdDetector.WITHIN_LAYOUT;
- Issue usuallyDisabledIssue = UnusedResourceDetector.ISSUE_IDS;
-
- assertTrue(config.isEnabled(usuallyEnabledIssue));
- assertFalse(config.isEnabled(usuallyDisabledIssue));
-
- otherConfig.setSeverity(usuallyEnabledIssue, Severity.IGNORE);
- otherConfig.setSeverity(usuallyDisabledIssue, Severity.ERROR);
-
- // Ensure inheritance works
- assertFalse(config.isEnabled(usuallyEnabledIssue));
- assertTrue(config.isEnabled(usuallyDisabledIssue));
-
- // Revert
- otherConfig.setSeverity(usuallyEnabledIssue, Severity.ERROR);
- otherConfig.setSeverity(usuallyDisabledIssue, Severity.IGNORE);
- assertTrue(config.isEnabled(usuallyEnabledIssue));
- assertFalse(config.isEnabled(usuallyDisabledIssue));
-
- // Now override in child
- config.setSeverity(usuallyEnabledIssue, Severity.ERROR);
- config.setSeverity(usuallyDisabledIssue, Severity.IGNORE);
- assertTrue(config.isEnabled(usuallyEnabledIssue));
- assertFalse(config.isEnabled(usuallyDisabledIssue));
-
- // Now change in parent: no change in child
- otherConfig.setSeverity(usuallyEnabledIssue, Severity.IGNORE);
- otherConfig.setSeverity(usuallyDisabledIssue, Severity.ERROR);
- assertTrue(config.isEnabled(usuallyEnabledIssue));
- assertFalse(config.isEnabled(usuallyDisabledIssue));
- assertFalse(otherConfig.isEnabled(usuallyEnabledIssue));
- assertTrue(otherConfig.isEnabled(usuallyDisabledIssue));
-
- // Clear override in child
- config.setSeverity(usuallyEnabledIssue, null);
- config.setSeverity(usuallyDisabledIssue, null);
- assertFalse(config.isEnabled(usuallyEnabledIssue));
- assertTrue(config.isEnabled(usuallyDisabledIssue));
- }
-
- public void testBulkEditing() {
- Configuration parent = null;
- LintClient client = new TestClient();
-
- File dir = getTargetDir();
- assertTrue(dir.mkdirs());
- Project project = client.getProject(dir, dir);
-
- ProjectLintConfiguration config =
- new ProjectLintConfiguration(client, project, parent, false /*fatalOnly*/);
-
- Issue usuallyEnabledIssue = DuplicateIdDetector.WITHIN_LAYOUT;
- Issue usuallyDisabledIssue = UnusedResourceDetector.ISSUE_IDS;
-
- assertTrue(config.isEnabled(usuallyEnabledIssue));
- assertFalse(config.isEnabled(usuallyDisabledIssue));
-
- config.setSeverity(usuallyEnabledIssue, Severity.IGNORE);
- assertFalse(config.isEnabled(usuallyEnabledIssue));
- assertFalse(config.isEnabled(usuallyDisabledIssue));
-
- File configFile = new File(dir, "lint.xml");
- assertTrue(configFile.getPath(), configFile.exists());
- long lastModified = configFile.lastModified();
-
- // We need to make sure that the timestamp of the file is a couple of seconds
- // after the last update or we can't tell whether the file was updated or not
-
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- System.err.println("Sleep interrupted, test may not work.");
- }
- config.startBulkEditing();
- assertFalse(lastModified < configFile.lastModified());
- assertEquals(lastModified, configFile.lastModified());
- config.setSeverity(usuallyDisabledIssue, Severity.ERROR);
- config.finishBulkEditing();
- assertTrue(lastModified < configFile.lastModified());
-
- assertTrue(config.isEnabled(usuallyDisabledIssue));
- }
-
- public void testPersistence() {
- // Ensure that we use the same configuration object repeatedly for a
- // single project, such that we don't recompute and parse XML for each and
- // every lint run!
- IProject project = getProject();
- TestClient client = new TestClient();
- ProjectLintConfiguration config1 = ProjectLintConfiguration.get(client, project, false);
- ProjectLintConfiguration config2 = ProjectLintConfiguration.get(client, project, false);
- assertSame(config1, config2);
- }
-
- @Override
- protected File getTargetDir() {
- File targetDir = new File(getTempDir(), getClass().getSimpleName() + "_" + getName());
- addCleanupDir(targetDir);
- return targetDir;
- }
-
- private static class TestClient extends LintClient {
- @Override
- public void report(@NonNull Context context, @NonNull Issue issue,
- @NonNull Severity severity, @Nullable Location location,
- @NonNull String message, @NonNull TextFormat format) {
- }
-
- @Override
- public void log(@NonNull Severity severity, @Nullable Throwable exception,
- @Nullable String format, @Nullable Object... args) {
- }
-
- @Override
- public XmlParser getXmlParser() {
- return null;
- }
-
- @Override
- public @NonNull String readFile(@NonNull File file) {
- return null;
- }
-
- @Override
- public JavaParser getJavaParser(@Nullable Project project) {
- return null;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/refactorings/core/AndroidPackageRenameParticipantTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/refactorings/core/AndroidPackageRenameParticipantTest.java
deleted file mode 100644
index 1df0b0c5e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/refactorings/core/AndroidPackageRenameParticipantTest.java
+++ /dev/null
@@ -1,293 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.refactorings.core;
-
-import com.android.annotations.NonNull;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IPackageFragment;
-import org.eclipse.jdt.core.JavaModelException;
-import org.eclipse.jdt.internal.corext.refactoring.rename.RenamePackageProcessor;
-import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
-
-/**
- * TODO: Test renaming a DIFFERENT package than the application package!
- */
-@SuppressWarnings({"javadoc", "restriction"})
-public class AndroidPackageRenameParticipantTest extends RefactoringTestBase {
- public void testRefactor1() throws Exception {
- renamePackage(
- TEST_PROJECT,
- false /*renameSubpackages*/,
- true /*updateReferences*/,
- "my.pkg.name",
-
- "CHANGES:\n" +
- "-------\n" +
- "[x] Rename package 'com.example.refactoringtest' to 'my.pkg.name'\n" +
- "\n" +
- "[x] MainActivity.java - /testRefactor1/src/com/example/refactoringtest/MainActivity.java\n" +
- " @@ -3 +3\n" +
- " + import com.example.refactoringtest.R;\n" +
- " +\n" +
- "\n" +
- "\n" +
- "[x] activity_main.xml - /testRefactor1/res/layout/activity_main.xml\n" +
- " @@ -33 +33\n" +
- " - <fragment android:name=\"com.example.refactoringtest.MyFragment\"/>\n" +
- " + <fragment android:name=\"my.pkg.name.MyFragment\"/>\n" +
- "\n" +
- "\n" +
- "[x] AndroidManifest.xml - /testRefactor1/AndroidManifest.xml\n" +
- " @@ -16 +16\n" +
- " - android:name=\"com.example.refactoringtest.MainActivity\"\n" +
- " + android:name=\"my.pkg.name.MainActivity\"\n" +
- " @@ -25 +25\n" +
- " - android:name=\".MainActivity2\"\n" +
- " + android:name=\"my.pkg.name.MainActivity2\"",
- true);
- }
-
- public void testRefactor1_noreferences() throws Exception {
- renamePackage(
- TEST_PROJECT,
- false /*renameSubpackages*/,
- false /*updateReferences*/,
- "my.pkg.name",
-
- "CHANGES:\n" +
- "-------\n" +
- "[x] Rename package 'com.example.refactoringtest' to 'my.pkg.name'",
- false);
- }
-
- public void testRefactor2() throws Exception {
- // Tests custom view handling
- renamePackage(
- TEST_PROJECT2,
- false /*renameSubpackages*/,
- true /*updateReferences*/,
- "my.pkg.name",
-
- "CHANGES:\n" +
- "-------\n" +
- "[x] Rename package 'com.example.refactoringtest' to 'my.pkg.name'\n" +
- "\n" +
- "[x] MainActivity.java - /testRefactor2/src/com/example/refactoringtest/MainActivity.java\n" +
- " @@ -3 +3\n" +
- " + import com.example.refactoringtest.R;\n" +
- " +\n" +
- "\n" +
- "\n" +
- "[x] customviews.xml - /testRefactor2/res/layout/customviews.xml\n" +
- " @@ -9 +9\n" +
- " - <com.example.refactoringtest.CustomView1\n" +
- " + <my.pkg.name.CustomView1\n" +
- "\n" +
- "\n" +
- "[x] activity_main.xml - /testRefactor2/res/layout/activity_main.xml\n" +
- " @@ -33 +33\n" +
- " - <fragment android:name=\"com.example.refactoringtest.MyFragment\"/>\n" +
- " + <fragment android:name=\"my.pkg.name.MyFragment\"/>\n" +
- "\n" +
- "\n" +
- "[x] customviews.xml - /testRefactor2/res/layout-land/customviews.xml\n" +
- " @@ -9 +9\n" +
- " - <com.example.refactoringtest.CustomView1\n" +
- " + <my.pkg.name.CustomView1\n" +
- "\n" +
- "\n" +
- "[x] AndroidManifest.xml - /testRefactor2/AndroidManifest.xml\n" +
- " @@ -16 +16\n" +
- " - android:name=\"com.example.refactoringtest.MainActivity\"\n" +
- " + android:name=\"my.pkg.name.MainActivity\"\n" +
- " @@ -25 +25\n" +
- " - android:name=\".MainActivity2\"\n" +
- " + android:name=\"my.pkg.name.MainActivity2\"",
- true);
- }
-
- public void testRefactor2_renamesub() throws Exception {
- // Tests custom view handling
- renamePackage(
- TEST_PROJECT2,
- true /*renameSubpackages*/,
- true /*updateReferences*/,
- "my.pkg.name",
-
- "CHANGES:\n" +
- "-------\n" +
- "[x] Rename package 'com.example.refactoringtest' and subpackages to 'my.pkg.name'\n" +
- "\n" +
- "[x] MainActivity.java - /testRefactor2_renamesub/src/com/example/refactoringtest/MainActivity.java\n" +
- " @@ -3 +3\n" +
- " + import com.example.refactoringtest.R;\n" +
- " +\n" +
- "\n" +
- "\n" +
- "[x] customviews.xml - /testRefactor2_renamesub/res/layout/customviews.xml\n" +
- " @@ -9 +9\n" +
- " - <com.example.refactoringtest.CustomView1\n" +
- " + <my.pkg.name.CustomView1\n" +
- "\n" +
- "\n" +
- "[x] activity_main.xml - /testRefactor2_renamesub/res/layout/activity_main.xml\n" +
- " @@ -33 +33\n" +
- " - <fragment android:name=\"com.example.refactoringtest.MyFragment\"/>\n" +
- " + <fragment android:name=\"my.pkg.name.MyFragment\"/>\n" +
- "\n" +
- "\n" +
- "[x] customviews.xml - /testRefactor2_renamesub/res/layout-land/customviews.xml\n" +
- " @@ -9 +9\n" +
- " - <com.example.refactoringtest.CustomView1\n" +
- " + <my.pkg.name.CustomView1\n" +
- "\n" +
- "\n" +
- "[x] AndroidManifest.xml - /testRefactor2_renamesub/AndroidManifest.xml\n" +
- " @@ -16 +16\n" +
- " - android:name=\"com.example.refactoringtest.MainActivity\"\n" +
- " + android:name=\"my.pkg.name.MainActivity\"\n" +
- " @@ -25 +25\n" +
- " - android:name=\".MainActivity2\"\n" +
- " + android:name=\"my.pkg.name.MainActivity2\"\n" +
- "\n" +
- "\n" +
- "[x] customviews.xml - /testRefactor2_renamesub/res/layout/customviews.xml\n" +
- " @@ -15 +15\n" +
- " - <com.example.refactoringtest.subpackage.CustomView2\n" +
- " + <my.pkg.name.subpackage.CustomView2\n" +
- "\n" +
- "\n" +
- "[x] customviews.xml - /testRefactor2_renamesub/res/layout-land/customviews.xml\n" +
- " @@ -15 +15\n" +
- " - <com.example.refactoringtest.subpackage.CustomView2\n" +
- " + <my.pkg.name.subpackage.CustomView2",
- true);
- }
-
- public void testRefactor2_renamesub_norefs() throws Exception {
- // Tests custom view handling
- renamePackage(
- TEST_PROJECT2,
- true /*renameSubpackages*/,
- false /*updateReferences*/,
- "my.pkg.name",
-
- "CHANGES:\n" +
- "-------\n" +
- "[x] Rename package 'com.example.refactoringtest' and subpackages to 'my.pkg.name'",
- false);
- }
-
-
- // ---- Test infrastructure ----
-
- protected void renamePackage(
- @NonNull Object[] testData,
- boolean renameSubpackages,
- boolean updateReferences,
- @NonNull String newName,
- @NonNull String expected,
- boolean expectedAppPackageRenameWarning) throws Exception {
- IProject project = createProject(testData);
- String expectedWarnings = expectedAppPackageRenameWarning ?
- EXPECTED_WARNINGS_TEMPLATE.replace("PROJECTNAME", project.getName()) : null;
- renamePackage(project, renameSubpackages, updateReferences, newName, expected,
- expectedWarnings);
- }
-
- protected void renamePackage(
- @NonNull IProject project,
- boolean renameSubpackages,
- boolean updateReferences,
- @NonNull String newName,
- @NonNull String expected,
- @NonNull String expectedWarnings) throws Exception {
- ManifestInfo info = ManifestInfo.get(project);
- String currentPackage = info.getPackage();
- assertNotNull(currentPackage);
-
- IPackageFragment pkgFragment = getPackageFragment(project, currentPackage);
- RenamePackageProcessor processor = new RenamePackageProcessor(pkgFragment);
- processor.setNewElementName(newName);
- processor.setRenameSubpackages(renameSubpackages);
- processor.setUpdateReferences(updateReferences);
- assertNotNull(processor);
-
- RenameRefactoring refactoring = new RenameRefactoring(processor);
- checkRefactoring(refactoring, expected, expectedWarnings);
- }
-
- private static IPackageFragment getPackageFragment(IProject project, String pkg)
- throws CoreException, JavaModelException {
- IPackageFragment pkgFragment = null;
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
- assertNotNull(javaProject);
- IPackageFragment[] fragments = javaProject.getPackageFragments();
- for (IPackageFragment fragment : fragments) {
- String name = fragment.getElementName();
- if (pkg.equals(name)) {
- pkgFragment = fragment;
- break;
- }
- }
- return pkgFragment;
- }
-
- private static String EXPECTED_WARNINGS_TEMPLATE =
- "<INFO\n" +
- "\t\n" +
- "INFO: You are refactoring the same package as your application's package (specified in the manifest).\n" +
- "\n" +
- "Context: L/PROJECTNAME/AndroidManifest.xml\n" +
- "code: none\n" +
- "Data: null\n" +
- "\t\n" +
- "INFO: Note that this refactoring does NOT also update your application package.\n" +
- "Context: L/PROJECTNAME/AndroidManifest.xml\n" +
- "code: none\n" +
- "Data: null\n" +
- "\t\n" +
- "INFO: The application package defines your application's identity.\n" +
- "Context: L/PROJECTNAME/AndroidManifest.xml\n" +
- "code: none\n" +
- "Data: null\n" +
- "\t\n" +
- "INFO: If you change it, then it is considered to be a different application.\n" +
- "Context: L/PROJECTNAME/AndroidManifest.xml\n" +
- "code: none\n" +
- "Data: null\n" +
- "\t\n" +
- "INFO: (Users of the previous version cannot update to the new version.)\n" +
- "Context: L/PROJECTNAME/AndroidManifest.xml\n" +
- "code: none\n" +
- "Data: null\n" +
- "\t\n" +
- "INFO: The application package, and the package containing the code, can differ.\n" +
- "Context: L/PROJECTNAME/AndroidManifest.xml\n" +
- "code: none\n" +
- "Data: null\n" +
- "\t\n" +
- "INFO: To really change application package, choose \"Android Tools\" > \"Rename Application Package.\" from the project context menu.\n" +
- "Context: L/PROJECTNAME/AndroidManifest.xml\n" +
- "code: none\n" +
- "Data: null\n" +
- ">";
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/refactorings/core/RefactoringTestBase.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/refactorings/core/RefactoringTestBase.java
deleted file mode 100644
index 41838e24b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/refactorings/core/RefactoringTestBase.java
+++ /dev/null
@@ -1,757 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.refactorings.core;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.refactoring.AdtProjectTest;
-import com.google.common.base.Charsets;
-import com.google.common.base.Splitter;
-import com.google.common.io.ByteStreams;
-import com.google.common.io.Files;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jdt.internal.corext.refactoring.changes.RenameCompilationUnitChange;
-import org.eclipse.jdt.internal.corext.refactoring.changes.RenamePackageChange;
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.eclipse.ltk.core.refactoring.Refactoring;
-import org.eclipse.ltk.core.refactoring.RefactoringStatus;
-import org.eclipse.ltk.core.refactoring.TextChange;
-import org.eclipse.ltk.core.refactoring.TextFileChange;
-import org.eclipse.ltk.core.refactoring.resource.MoveResourceChange;
-import org.eclipse.ltk.core.refactoring.resource.RenameResourceChange;
-import org.eclipse.text.edits.TextEdit;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
-
-@SuppressWarnings({"javadoc","restriction"})
-public abstract class RefactoringTestBase extends AdtProjectTest {
- protected void checkRefactoring(Refactoring refactoring, String expected) throws Exception {
- checkRefactoring(refactoring, expected, null);
- }
-
- @Override
- protected void setUp() throws Exception {
- // Not calling super.setUp
- }
-
- protected void checkRefactoring(Refactoring refactoring, String expected,
- @Nullable String expectedWarnings) throws Exception {
- RefactoringStatus status = refactoring.checkAllConditions(new NullProgressMonitor());
- assertNotNull(status);
- if (expectedWarnings == null) {
- expectedWarnings = "<OK\n>";
- }
- if (status.toString().trim().startsWith(
- "<WARNING\n" +
- "\t\n" +
- "WARNING: Code modification may not be accurate as affected resource '")) {
- // Test instability, probably a timing issue with getting the new project
- // compiled (to recognize Android classpath entries)
- // Just continue to ensure that the refactoring list matches.
- } else {
- assertEquals(status.toString().trim(), expectedWarnings.trim());
- }
- if (!status.isOK()) {
- return;
- }
- assertTrue(status.toString(), status.isOK());
- Change change = refactoring.createChange(new NullProgressMonitor());
- assertNotNull(change);
- String explanation = "CHANGES:\n-------\n" + describe(change);
- if (!expected.trim().equals(explanation.trim())) { // allow trimming endlines in expected
- assertEquals(expected, explanation);
- }
- }
-
- private IProject mProject;
-
- @Override
- protected IProject getProject() {
- return mProject;
- }
-
- protected IProject createProject(Object[] testData) throws Exception {
- String name = getName();
- IProject project = createProject(name);
- mProject = project;
- File projectDir = AdtUtils.getAbsolutePath(project).toFile();
- assertNotNull(projectDir);
- assertTrue(projectDir.getPath(), projectDir.exists());
- createTestDataDir(projectDir, testData);
- project.refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
-
- for (int i = 0; i < testData.length; i+= 2) {
- assertTrue(testData[i].toString(), testData[i] instanceof String);
- String relative = (String) testData[i];
- IResource member = project.findMember(relative);
- assertNotNull(relative, member);
- assertTrue(member.getClass().getSimpleName(), member instanceof IFile);
- }
-
- return project;
- }
-
- public static String describe(Change change) throws Exception {
- StringBuilder sb = new StringBuilder(1000);
- describe(sb, change, 0);
-
- // Trim trailing space
- for (int i = sb.length() - 1; i >= 0; i--) {
- if (!Character.isWhitespace(sb.charAt(i))) {
- sb.setLength(i + 1);
- break;
- }
- }
-
- return sb.toString();
- }
-
- protected static void describe(StringBuilder sb, Change change, int indent) throws Exception {
- if (change instanceof CompositeChange
- && ((CompositeChange) change).isSynthetic()) {
- // Don't display information about synthetic changes
- } else {
- String changeName = change.getName();
-
- if (changeName.contains("MoreUnit")) {
- // If MoreUnit plugin is installed, don't include in unit test results
- return;
- }
-
- // Describe this change
- indent(sb, indent);
- if (change.isEnabled()) {
- sb.append("[x] ");
- } else {
- sb.append("[ ] ");
- }
- sb.append(changeName);
-
- IFile file = getFile(change);
- if (file != null) {
- sb.append(" - ");
- sb.append(file.getFullPath());
- sb.append('\n');
- } else {
- sb.append('\n');
- }
-
- if (change instanceof TextFileChange) {
- assertNotNull(file);
- if (file != null) {
- TextChange tc = (TextChange) change;
- TextEdit edit = tc.getEdit();
- byte[] bytes = ByteStreams.toByteArray(file.getContents());
- String before = new String(bytes, Charsets.UTF_8);
- IDocument document = new Document();
- document.replace(0, 0, before);
- // Make a copy: edits are sometimes destructive when run repeatedly!
- edit.copy().apply(document);
- String after = document.get();
-
- String diff = getDiff(before, after);
- for (String line : Splitter.on('\n').split(diff)) {
- if (!line.trim().isEmpty()) {
- indent(sb, indent + 1);
- sb.append(line);
- }
- sb.append('\n');
- }
- }
- } else if (change instanceof RenameCompilationUnitChange) {
- // Change name, appended above, is adequate
- } else if (change instanceof RenameResourceChange) {
- // Change name, appended above, is adequate
- } else if (change instanceof RenamePackageChange) {
- // Change name, appended above, is adequate
- } else if (change instanceof MoveResourceChange) {
- // Change name, appended above, is adequate
- } else if (change instanceof CompositeChange) {
- // Don't print details about children here; they'll be nested below
- } else {
- indent(sb, indent);
- sb.append("<UNKNOWN CHANGE TYPE " + change.getClass().getName() + ">");
- }
- sb.append('\n');
- }
-
- if (change instanceof CompositeChange) {
- CompositeChange composite = (CompositeChange) change;
- Change[] children = composite.getChildren();
- List<Change> sorted = Arrays.asList(children);
- // Process children in a fixed (output-alphabetical) order to ensure stable output
- Collections.sort(sorted, new Comparator<Change>() {
- @Override
- public int compare(Change change1, Change change2) {
- try {
- IFile file1 = getFile(change1);
- IFile file2 = getFile(change2);
- if (file1 != null && file2 != null) {
- // Sort in decreasing order. This places the most interesting
- // files first: res > src > gen
- int fileDelta = file2.getFullPath().toOSString().compareToIgnoreCase(
- file1.getFullPath().toOSString());
- if (fileDelta != 0) {
- return fileDelta;
- }
- }
-
- int nameDelta = change2.getName().compareTo(change1.getName());
- if (nameDelta != 0) {
- return nameDelta;
- }
-
- // This is pretty inefficient but ensures stable output
- return describe(change2).compareTo(describe(change1));
- } catch (Exception e) {
- fail(e.getLocalizedMessage());
- return 0;
- }
- }
-
- });
- for (Change child : sorted) {
- describe(sb, child, indent + (composite.isSynthetic() ? 0 : 1));
- }
- }
- }
-
- @Nullable
- private static IFile getFile(@NonNull Change change) {
- if (change instanceof TextFileChange) {
- TextFileChange tfc = (TextFileChange) change;
- return tfc.getFile();
- }
-
- return null;
- }
-
- protected static void indent(StringBuilder sb, int indent) {
- for (int i = 0; i < indent; i++) {
- sb.append(" ");
- }
- }
-
- protected void createTestDataDir(File dir, Object[] data) throws IOException {
- for (int i = 0, n = data.length; i < n; i += 2) {
- assertTrue("Must be a path: " + data[i], data[i] instanceof String);
- String relativePath = ((String) data[i]).replace('/', File.separatorChar);
- File to = new File(dir, relativePath);
- File parent = to.getParentFile();
- if (!parent.exists()) {
- boolean mkdirs = parent.mkdirs();
- assertTrue(to.getPath(), mkdirs);
- }
-
- Object o = data[i + 1];
- if (o instanceof String) {
- String contents = (String) o;
- Files.write(contents, to, Charsets.UTF_8);
- } else if (o instanceof byte[]) {
- Files.write((byte[]) o, to);
- } else {
- fail("Data must be a String or a byte[] for " + to);
- }
- }
- }
-
- // Test sources
-
- protected static final String SAMPLE_MANIFEST =
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " package=\"com.example.refactoringtest\"\n" +
- " android:versionCode=\"1\"\n" +
- " android:versionName=\"1.0\" >\n" +
- "\n" +
- " <uses-sdk\n" +
- " android:minSdkVersion=\"8\"\n" +
- " android:targetSdkVersion=\"17\" />\n" +
- "\n" +
- " <application\n" +
- " android:icon=\"@drawable/ic_launcher\"\n" +
- " android:label=\"@string/app_name\"\n" +
- " android:theme=\"@style/AppTheme\" >\n" +
- " <activity\n" +
- " android:name=\"com.example.refactoringtest.MainActivity\"\n" +
- " android:label=\"@string/app_name\" >\n" +
- " <intent-filter>\n" +
- " <action android:name=\"android.intent.action.MAIN\" />\n" +
- "\n" +
- " <category android:name=\"android.intent.category.LAUNCHER\" />\n" +
- " </intent-filter>\n" +
- " </activity>\n" +
- " <activity\n" +
- " android:name=\".MainActivity2\"\n" +
- " android:label=\"@string/app_name2\" >\n" +
- " </activity>\n" +
- " </application>\n" +
- "\n" +
- "</manifest>";
-
- protected static final String SAMPLE_MAIN_ACTIVITY =
- "package com.example.refactoringtest;\n" +
- "\n" +
- "import android.os.Bundle;\n" +
- "import android.app.Activity;\n" +
- "import android.view.Menu;\n" +
- "import android.view.View;\n" +
- "\n" +
- "public class MainActivity extends Activity {\n" +
- "\n" +
- " @Override\n" +
- " protected void onCreate(Bundle savedInstanceState) {\n" +
- " super.onCreate(savedInstanceState);\n" +
- " setContentView(R.layout.activity_main);\n" +
- " View view1 = findViewById(R.id.textView1);\n" +
- " }\n" +
- "\n" +
- " @Override\n" +
- " public boolean onCreateOptionsMenu(Menu menu) {\n" +
- " // Inflate the menu; this adds items to the action bar if it is present.\n" +
- " getMenuInflater().inflate(R.menu.activity_main, menu);\n" +
- " return true;\n" +
- " }\n" +
- "\n" +
- "}\n";
-
- protected static final String SAMPLE_MAIN_ACTIVITY2 =
- "package com.example.refactoringtest;\n" +
- "\n" +
- "import android.os.Bundle;\n" +
- "import android.app.Activity;\n" +
- "import android.view.Menu;\n" +
- "import android.view.View;\n" +
- "\n" +
- "public class MainActivity2 extends Activity {\n" +
- "\n" +
- " @Override\n" +
- " protected void onCreate(Bundle savedInstanceState) {\n" +
- " super.onCreate(savedInstanceState);\n" +
- " }\n" +
- "\n" +
- "}\n";
-
- protected static final String MY_FRAGMENT =
- "package com.example.refactoringtest;\n" +
- "import android.support.v4.app.ListFragment;\n" +
- "\n" +
- "public class MyFragment extends ListFragment {\n" +
- "\n" +
- "}\n";
-
- protected static final String SAMPLE_LAYOUT =
- "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " xmlns:tools=\"http://schemas.android.com/tools\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\"\n" +
- " tools:context=\".MainActivity\" >\n" +
- "\n" +
- " <TextView\n" +
- " android:id=\"@+id/textView1\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_centerVertical=\"true\"\n" +
- " android:layout_toRightOf=\"@+id/button2\"\n" +
- " android:text=\"@string/hello_world\" />\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button1\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignLeft=\"@+id/textView1\"\n" +
- " android:layout_below=\"@+id/textView1\"\n" +
- " android:layout_marginLeft=\"22dp\"\n" +
- " android:layout_marginTop=\"24dp\"\n" +
- " android:text=\"Button\" />\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button2\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignParentLeft=\"true\"\n" +
- " android:layout_alignParentTop=\"true\"\n" +
- " android:text=\"Button\" />\n" +
- "\n" +
- " <fragment android:name=\"com.example.refactoringtest.MyFragment\"/>" +
- "\n" +
- "</RelativeLayout>";
-
- protected static final String SAMPLE_LAYOUT_2 =
- "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " xmlns:tools=\"http://schemas.android.com/tools\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\"\n" +
- " tools:context=\".MainActivity\" >\n" +
- "\n" +
- " <ListView\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " tools:listitem=\"@layout/preview\" >\n" +
- " </ListView>\n" +
- "\n" +
- " <fragment\n" +
- " android:name=\"android.support.v4.app.ListFragment\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " tools:layout=\"@layout/preview\" />\n" +
- "\n" +
- "\n" +
- "</RelativeLayout>";
-
-
- protected static final String SAMPLE_MENU =
- "<menu xmlns:android=\"http://schemas.android.com/apk/res/android\" >\n" +
- "\n" +
- " <item\n" +
- " android:id=\"@+id/menu_settings\"\n" +
- " android:orderInCategory=\"100\"\n" +
- " android:showAsAction=\"never\"\n" +
- " android:title=\"@string/menu_settings\"/>\n" +
- "\n" +
- "</menu>";
-
- protected static final String SAMPLE_STRINGS =
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<resources>\n" +
- "\n" +
- " <string name=\"app_name\">RefactoringTest</string>\n" +
- " <string name=\"hello_world\">Hello world!</string>\n" +
- " <string name=\"menu_settings\">Settings</string>\n" +
- "\n" +
- "</resources>";
-
- protected static final String SAMPLE_STYLES =
- "<resources>\n" +
- "\n" +
- " <!--\n" +
- " Base application theme, dependent on API level. This theme is replaced\n" +
- " by AppBaseTheme from res/values-vXX/styles.xml on newer devices.\n" +
- " -->\n" +
- " <style name=\"AppBaseTheme\" parent=\"android:Theme.Light\">\n" +
- " <!--\n" +
- " Theme customizations available in newer API levels can go in\n" +
- " res/values-vXX/styles.xml, while customizations related to\n" +
- " backward-compatibility can go here.\n" +
- " -->\n" +
- " </style>\n" +
- "\n" +
- " <!-- Application theme. -->\n" +
- " <style name=\"AppTheme\" parent=\"AppBaseTheme\">\n" +
- " <!-- All customizations that are NOT specific to a particular API-level can go here. -->\n" +
- " </style>\n" +
- "\n" +
- "</resources>";
-
- protected static final String SAMPLE_R =
- "/* AUTO-GENERATED FILE. DO NOT MODIFY.\n" +
- " *\n" +
- " * This class was automatically generated by the\n" +
- " * aapt tool from the resource data it found. It\n" +
- " * should not be modified by hand.\n" +
- " */\n" +
- "\n" +
- "package com.example.refactoringtest;\n" +
- "\n" +
- "public final class R {\n" +
- " public static final class attr {\n" +
- " }\n" +
- " public static final class drawable {\n" +
- " public static final int ic_launcher=0x7f020000;\n" +
- " }\n" +
- " public static final class id {\n" +
- " public static final int button1=0x7f070002;\n" +
- " public static final int button2=0x7f070001;\n" +
- " public static final int menu_settings=0x7f070003;\n" +
- " public static final int textView1=0x7f070000;\n" +
- " }\n" +
- " public static final class layout {\n" +
- " public static final int activity_main=0x7f030000;\n" +
- " }\n" +
- " public static final class menu {\n" +
- " public static final int activity_main=0x7f060000;\n" +
- " }\n" +
- " public static final class string {\n" +
- " public static final int app_name=0x7f040000;\n" +
- " public static final int hello_world=0x7f040001;\n" +
- " public static final int menu_settings=0x7f040002;\n" +
- " }\n" +
- " public static final class style {\n" +
- " /** \n" +
- " Base application theme, dependent on API level. This theme is replaced\n" +
- " by AppBaseTheme from res/values-vXX/styles.xml on newer devices.\n" +
- " \n" +
- "\n" +
- " Theme customizations available in newer API levels can go in\n" +
- " res/values-vXX/styles.xml, while customizations related to\n" +
- " backward-compatibility can go here.\n" +
- " \n" +
- "\n" +
- " Base application theme for API 11+. This theme completely replaces\n" +
- " AppBaseTheme from res/values/styles.xml on API 11+ devices.\n" +
- " \n" +
- " API 11 theme customizations can go here. \n" +
- "\n" +
- " Base application theme for API 14+. This theme completely replaces\n" +
- " AppBaseTheme from BOTH res/values/styles.xml and\n" +
- " res/values-v11/styles.xml on API 14+ devices.\n" +
- " \n" +
- " API 14 theme customizations can go here. \n" +
- " */\n" +
- " public static final int AppBaseTheme=0x7f050000;\n" +
- " /** Application theme. \n" +
- " All customizations that are NOT specific to a particular API-level can go here. \n" +
- " */\n" +
- " public static final int AppTheme=0x7f050001;\n" +
- " }\n" +
- "}\n";
-
- protected static final Object[] TEST_PROJECT = new Object[] {
- "AndroidManifest.xml",
- SAMPLE_MANIFEST,
-
- "src/com/example/refactoringtest/MainActivity.java",
- SAMPLE_MAIN_ACTIVITY,
-
- "src/com/example/refactoringtest/MainActivity2.java",
- SAMPLE_MAIN_ACTIVITY2,
-
- "gen/com/example/refactoringtest/R.java",
- SAMPLE_R,
-
- "res/drawable-xhdpi/ic_launcher.png",
- new byte[] { 0 },
- "res/drawable-hdpi/ic_launcher.png",
- new byte[] { 0 },
- "res/drawable-ldpi/ic_launcher.png",
- new byte[] { 0 },
- "res/drawable-mdpi/ic_launcher.png",
- new byte[] { 0 },
-
- "res/layout/activity_main.xml",
- SAMPLE_LAYOUT,
-
- "res/layout-land/activity_main.xml",
- SAMPLE_LAYOUT_2,
-
- "res/menu/activity_main.xml",
- SAMPLE_MENU,
-
- "res/values/strings.xml", // file 3
- SAMPLE_STRINGS,
-
- "res/values/styles.xml", // file 3
- SAMPLE_STYLES,
- };
-
- // More test data
-
- protected static final String CUSTOM_VIEW_1 =
- "package com.example.refactoringtest;\n" +
- "\n" +
- "import android.content.Context;\n" +
- "import android.widget.Button;\n" +
- "\n" +
- "public class CustomView1 extends Button {\n" +
- " public CustomView1(Context context) {\n" +
- " super(context);\n" +
- " }\n" +
- "}\n";
-
- protected static final String CUSTOM_VIEW_1_STYLES =
- "<resources>\n" +
- "\n" +
- " <!-- Aattributes for the custom view -->\n" +
- " <declare-styleable name=\"CustomView1\">\n" +
- " <attr name=\"exampleString\" format=\"string\" />\n" +
- " <attr name=\"exampleDimension\" format=\"dimension\" />\n" +
- " <attr name=\"exampleColor\" format=\"color\" />\n" +
- " <attr name=\"exampleDrawable\" format=\"color|reference\" />\n" +
- " </declare-styleable>\n" +
- "\n" +
- "</resources>";
-
- protected static final String CUSTOM_VIEW_2 =
- "package com.example.refactoringtest.subpackage;\n" +
- "\n" +
- "import android.content.Context;\n" +
- "import android.widget.Button;\n" +
- "\n" +
- "public class CustomView2 extends Button {\n" +
- " public CustomView2(Context context) {\n" +
- " super(context);\n" +
- " }\n" +
- "}\n";
-
- protected static final String CUSTOM_VIEW_LAYOUT =
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " xmlns:tools=\"http://schemas.android.com/tools\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\"\n" +
- " android:orientation=\"vertical\"\n" +
- " tools:ignore=\"HardcodedText\" >\n" +
- "\n" +
- " <com.example.refactoringtest.CustomView1\n" +
- " android:id=\"@+id/customView1\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:text=\"CustomView1\" />\n" +
- "\n" +
- " <com.example.refactoringtest.subpackage.CustomView2\n" +
- " android:id=\"@+id/customView2\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:text=\"CustomView2\" />\n" +
- "\n" +
- "</LinearLayout>";
-
- protected static final Object[] TEST_PROJECT2 = new Object[] {
- "AndroidManifest.xml",
- SAMPLE_MANIFEST,
-
- "src/com/example/refactoringtest/MainActivity.java",
- SAMPLE_MAIN_ACTIVITY,
-
- "src/com/example/refactoringtest/CustomView1.java",
- CUSTOM_VIEW_1,
-
- "res/values/attrs_custom_view.xml",
- CUSTOM_VIEW_1_STYLES,
-
- "src/com/example/refactoringtest/subpackage/CustomView2.java",
- CUSTOM_VIEW_2,
-
- "src/com/example/refactoringtest/MyFragment.java",
- MY_FRAGMENT,
-
- "gen/com/example/refactoringtest/R.java",
- SAMPLE_R,
-
- "res/drawable-xhdpi/ic_launcher.png",
- new byte[] { 0 },
- "res/drawable-hdpi/ic_launcher.png",
- new byte[] { 0 },
- "res/drawable-ldpi/ic_launcher.png",
- new byte[] { 0 },
- "res/drawable-mdpi/ic_launcher.png",
- new byte[] { 0 },
-
- "res/layout/activity_main.xml",
- SAMPLE_LAYOUT,
-
- "res/layout-land/activity_main.xml",
- SAMPLE_LAYOUT_2,
-
- "res/layout/customviews.xml",
- CUSTOM_VIEW_LAYOUT,
-
- "res/layout-land/customviews.xml",
- CUSTOM_VIEW_LAYOUT,
-
- "res/menu/activity_main.xml",
- SAMPLE_MENU,
-
- "res/values/strings.xml", // file 3
- SAMPLE_STRINGS,
-
- "res/values/styles.xml", // file 3
- SAMPLE_STYLES,
-
- // Just a gen file, should not be refactored
- "bin/AndroidManifest.xml",
- SAMPLE_MANIFEST,
-
- };
-
-
- protected static final String MANIFEST =
- "/* AUTO-GENERATED FILE. DO NOT MODIFY.\n" +
- " *\n" +
- " * This class was automatically generated by the\n" +
- " * aapt tool from the resource data it found. It\n" +
- " * should not be modified by hand.\n" +
- " */\n" +
- "\n" +
- "package com.example.refactoringtest;\n" +
- "\n" +
- "public final class Manifest {\n" +
- " public static final class permission {\n" +
- " public static final String WRITE_SCHEDULE=\"com.example.refactoringtest.permission.WRITE_SCHEDULE\";\n" +
- " }\n" +
- "}";
-
- protected static final String BUILD_CONFIG =
- "/** Automatically generated file. DO NOT MODIFY */\n" +
- "package com.example.refactoringtest;\n" +
- "\n" +
- "public final class BuildConfig {\n" +
- " public final static boolean DEBUG = true;\n" +
- "}";
-
- protected static final String MORE_CODE_JAVA =
- "package com.example.refactoringtest.subpkg;\n" +
- "\n" +
- "import android.os.Bundle;\n" +
- "import android.app.Activity;\n" +
- "import android.view.Menu;\n" +
- "import android.view.View;\n" +
- "import com.example.refactoringtest.BuildConfig;\n" +
- "import com.example.refactoringtest.Manifest;\n" +
- "import com.example.refactoringtest.R;\n" +
- "\n" +
- "public class MoreCode extends Activity {\n" +
- "\n" +
- " protected void code() {\n" +
- " if (BuildConfig.DEBUG) {\n" +
- " System.out.println(Manifest.permission);\n" +
- " }" +
- " System.out.println(com.example.refactoringtest.BuildConfig.DEBUG);\n" +
- " }\n" +
- "\n" +
- "}\n";
-
- /** Project which includes references to BuildConfig, Manifest, and R */
- protected static final Object[] TEST_PROJECT3;
- static {
- Object[] additional = new Object[] {
- "src/com/example/refactoringtest/subpkg/MoreCode.java",
- MORE_CODE_JAVA,
-
- "gen/com/example/refactoringtest/BuildConfig.java",
- BUILD_CONFIG,
-
- "gen/com/example/refactoringtest/Manifest.java",
- MANIFEST,
- };
- TEST_PROJECT3 = new Object[TEST_PROJECT2.length + additional.length];
- System.arraycopy(TEST_PROJECT2, 0, TEST_PROJECT3, 0, TEST_PROJECT2.length);
- System.arraycopy(additional, 0, TEST_PROJECT3, TEST_PROJECT2.length, additional.length);
- };
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourceParticipantTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourceParticipantTest.java
deleted file mode 100644
index 3f029b93b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourceParticipantTest.java
+++ /dev/null
@@ -1,402 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.refactorings.core;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.resources.ResourceUrl;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.resources.ResourceType;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jdt.core.IField;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.internal.corext.refactoring.rename.RenameFieldProcessor;
-import org.eclipse.ltk.core.refactoring.participants.RenameProcessor;
-import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
-
-@SuppressWarnings({"javadoc", "restriction"})
-public class RenameResourceParticipantTest extends RefactoringTestBase {
- public void testRefactor1() throws Exception {
- renameResource(
- TEST_PROJECT,
- "@string/app_name",
- true /*updateReferences*/,
- "myname",
-
- "CHANGES:\n" +
- "-------\n" +
- "[x] strings.xml - /testRefactor1/res/values/strings.xml\n" +
- " @@ -4 +4\n" +
- " - <string name=\"app_name\">RefactoringTest</string>\n" +
- " + <string name=\"myname\">RefactoringTest</string>\n" +
- "\n" +
- "\n" +
- "[ ] R.java - /testRefactor1/gen/com/example/refactoringtest/R.java\n" +
- " @@ -29 +29\n" +
- " - public static final int app_name=0x7f040000;\n" +
- " + public static final int myname=0x7f040000;\n" +
- "\n" +
- "\n" +
- "[x] AndroidManifest.xml - /testRefactor1/AndroidManifest.xml\n" +
- " @@ -13 +13\n" +
- " - android:label=\"@string/app_name\"\n" +
- " + android:label=\"@string/myname\"\n" +
- " @@ -17 +17\n" +
- " - android:label=\"@string/app_name\" >\n" +
- " + android:label=\"@string/myname\" >");
- }
-
- public void testRefactor2() throws Exception {
- renameResource(
- TEST_PROJECT,
- "@+id/menu_settings",
- true /*updateReferences*/,
- "new_id_for_the_action_bar",
-
- "CHANGES:\n" +
- "-------\n" +
- "[x] activity_main.xml - /testRefactor2/res/menu/activity_main.xml\n" +
- " @@ -4 +4\n" +
- " - android:id=\"@+id/menu_settings\"\n" +
- " + android:id=\"@+id/new_id_for_the_action_bar\"\n" +
- "\n" +
- "\n" +
- "[ ] R.java - /testRefactor2/gen/com/example/refactoringtest/R.java\n" +
- " @@ -19 +19\n" +
- " - public static final int menu_settings=0x7f070003;\n" +
- " + public static final int new_id_for_the_action_bar=0x7f070003;");
- }
-
- public void testRefactor3() throws Exception {
- renameResource(
- TEST_PROJECT,
- "@+id/textView1",
- true /*updateReferences*/,
- "output",
-
- "CHANGES:\n" +
- "-------\n" +
- "[x] activity_main.xml - /testRefactor3/res/layout/activity_main.xml\n" +
- " @@ -8 +8\n" +
- " - android:id=\"@+id/textView1\"\n" +
- " + android:id=\"@+id/output\"\n" +
- " @@ -19 +19\n" +
- " - android:layout_alignLeft=\"@+id/textView1\"\n" +
- " - android:layout_below=\"@+id/textView1\"\n" +
- " + android:layout_alignLeft=\"@+id/output\"\n" +
- " + android:layout_below=\"@+id/output\"\n" +
- "\n" +
- "\n" +
- "[x] MainActivity.java - /testRefactor3/src/com/example/refactoringtest/MainActivity.java\n" +
- " @@ -14 +14\n" +
- " - View view1 = findViewById(R.id.textView1);\n" +
- " + View view1 = findViewById(R.id.output);\n" +
- "\n" +
- "\n" +
- "[ ] R.java - /testRefactor3/gen/com/example/refactoringtest/R.java\n" +
- " @@ -20 +20\n" +
- " - public static final int textView1=0x7f070000;\n" +
- " + public static final int output=0x7f070000;");
- }
-
- public void testRefactor4() throws Exception {
- renameResource(
- TEST_PROJECT,
- // same as testRefactor3, but use @id rather than @+id even though @+id is in file
- "@id/textView1",
- true /*updateReferences*/,
- "output",
-
- "CHANGES:\n" +
- "-------\n" +
- "[x] activity_main.xml - /testRefactor4/res/layout/activity_main.xml\n" +
- " @@ -8 +8\n" +
- " - android:id=\"@+id/textView1\"\n" +
- " + android:id=\"@+id/output\"\n" +
- " @@ -19 +19\n" +
- " - android:layout_alignLeft=\"@+id/textView1\"\n" +
- " - android:layout_below=\"@+id/textView1\"\n" +
- " + android:layout_alignLeft=\"@+id/output\"\n" +
- " + android:layout_below=\"@+id/output\"\n" +
- "\n" +
- "\n" +
- "[x] MainActivity.java - /testRefactor4/src/com/example/refactoringtest/MainActivity.java\n" +
- " @@ -14 +14\n" +
- " - View view1 = findViewById(R.id.textView1);\n" +
- " + View view1 = findViewById(R.id.output);\n" +
- "\n" +
- "\n" +
- "[ ] R.java - /testRefactor4/gen/com/example/refactoringtest/R.java\n" +
- " @@ -20 +20\n" +
- " - public static final int textView1=0x7f070000;\n" +
- " + public static final int output=0x7f070000;");
- }
-
- public void testRefactor5() throws Exception {
- renameResource(
- TEST_PROJECT,
- "@layout/activity_main",
- true /*updateReferences*/,
- "newlayout",
-
- "CHANGES:\n" +
- "-------\n" +
- "[x] MainActivity.java - /testRefactor5/src/com/example/refactoringtest/MainActivity.java\n" +
- " @@ -13 +13\n" +
- " - setContentView(R.layout.activity_main);\n" +
- " + setContentView(R.layout.newlayout);\n" +
- "\n" +
- "\n" +
- "[ ] R.java - /testRefactor5/gen/com/example/refactoringtest/R.java\n" +
- " @@ -23 +23\n" +
- " - public static final int activity_main=0x7f030000;\n" +
- " + public static final int newlayout=0x7f030000;\n" +
- "\n" +
- "\n" +
- "[x] Rename 'testRefactor5/res/layout/activity_main.xml' to 'newlayout.xml'\n" +
- "\n" +
- "[x] Rename 'testRefactor5/res/layout-land/activity_main.xml' to 'newlayout.xml'");
- }
-
- public void testRefactor6() throws Exception {
- renameResource(
- TEST_PROJECT,
- "@drawable/ic_launcher",
- true /*updateReferences*/,
- "newlauncher",
-
- "CHANGES:\n" +
- "-------\n" +
- "[ ] R.java - /testRefactor6/gen/com/example/refactoringtest/R.java\n" +
- " @@ -14 +14\n" +
- " - public static final int ic_launcher=0x7f020000;\n" +
- " + public static final int newlauncher=0x7f020000;\n" +
- "\n" +
- "\n" +
- "[x] Rename 'testRefactor6/res/drawable-xhdpi/ic_launcher.png' to 'newlauncher.png'\n" +
- "\n" +
- "[x] Rename 'testRefactor6/res/drawable-mdpi/ic_launcher.png' to 'newlauncher.png'\n" +
- "\n" +
- "[x] Rename 'testRefactor6/res/drawable-ldpi/ic_launcher.png' to 'newlauncher.png'\n" +
- "\n" +
- "[x] Rename 'testRefactor6/res/drawable-hdpi/ic_launcher.png' to 'newlauncher.png'\n" +
- "\n" +
- "[x] AndroidManifest.xml - /testRefactor6/AndroidManifest.xml\n" +
- " @@ -12 +12\n" +
- " - android:icon=\"@drawable/ic_launcher\"\n" +
- " + android:icon=\"@drawable/newlauncher\"");
- }
-
- public void testRefactor7() throws Exception {
- // Test refactoring initiated on a file rename
- IProject project = createProject(TEST_PROJECT);
- IFile file = project.getFile("res/layout/activity_main.xml");
- renameResource(
- project,
- file,
- true /*updateReferences*/,
- "newlayout",
-
- "CHANGES:\n" +
- "-------\n" +
- "[x] MainActivity.java - /testRefactor7/src/com/example/refactoringtest/MainActivity.java\n" +
- " @@ -13 +13\n" +
- " - setContentView(R.layout.activity_main);\n" +
- " + setContentView(R.layout.newlayout);\n" +
- "\n" +
- "\n" +
- "[ ] R.java - /testRefactor7/gen/com/example/refactoringtest/R.java\n" +
- " @@ -23 +23\n" +
- " - public static final int activity_main=0x7f030000;\n" +
- " + public static final int newlayout=0x7f030000;\n" +
- "\n" +
- "\n" +
- "[x] Rename 'testRefactor7/res/layout-land/activity_main.xml' to 'newlayout.xml'\n" +
- "\n" +
- "[x] Rename 'testRefactor7/res/layout/activity_main.xml' to 'newlayout.xml'",
- null);
- }
-
- public void testRefactor8() throws Exception {
- // Test refactoring initiated on a Java field rename
- IProject project = createProject(TEST_PROJECT);
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
- assertNotNull(javaProject);
- IType type = javaProject.findType("com.example.refactoringtest.R.layout");
- if (type == null || !type.exists()) {
- type = javaProject.findType("com.example.refactoringtest.R$layout");
- System.out.println("Had to switch to $ notation");
- }
- assertNotNull(type);
- assertTrue(type.exists());
- IField field = type.getField("activity_main");
- assertNotNull(field);
- assertTrue(field.exists());
-
- renameResource(
- project,
- field,
- true /*updateReferences*/,
- "newlauncher",
-
- "CHANGES:\n" +
- "-------\n" +
- "[x] Rename 'testRefactor8/res/layout/activity_main.xml' to 'newlauncher.xml'\n" +
- "\n" +
- "[x] Rename 'testRefactor8/res/layout-land/activity_main.xml' to 'newlauncher.xml'\n" +
- "\n" +
- "[x] MainActivity.java - /testRefactor8/src/com/example/refactoringtest/MainActivity.java\n" +
- " @@ -13 +13\n" +
- " - setContentView(R.layout.activity_main);\n" +
- " + setContentView(R.layout.newlauncher);\n" +
- "\n" +
- "\n" +
- "[ ] R.java - /testRefactor8/gen/com/example/refactoringtest/R.java\n" +
- " @@ -23 +23\n" +
- " - public static final int activity_main=0x7f030000;\n" +
- " + public static final int newlauncher=0x7f030000;",
- null);
- }
-
- public void testInvalidName() throws Exception {
- renameResource(
- TEST_PROJECT,
- "@drawable/ic_launcher",
- true /*updateReferences*/,
- "Newlauncher",
-
- "",
- "<ERROR\n" +
- "\t\n" +
- "ERROR: File-based resource names must start with a lowercase letter.\n" +
- "Context: <Unspecified context>\n" +
- "code: none\n" +
- "Data: null\n" +
- ">");
- }
-
- public void testRefactor9() throws Exception {
- // same as testRefactor4, but not updating references
- renameResource(
- TEST_PROJECT,
- "@id/textView1",
- false /*updateReferences*/,
- "output",
-
- "CHANGES:\n" +
- "-------\n" +
- "[x] activity_main.xml - /testRefactor9/res/layout/activity_main.xml\n" +
- " @@ -8 +8\n" +
- " - android:id=\"@+id/textView1\"\n" +
- " + android:id=\"@+id/output\"\n" +
- "\n" +
- "\n" +
- "[ ] R.java - /testRefactor9/gen/com/example/refactoringtest/R.java\n" +
- " @@ -20 +20\n" +
- " - public static final int textView1=0x7f070000;\n" +
- " + public static final int output=0x7f070000;");
- }
-
- public void testRefactor10() throws Exception {
- // Check updating tools: attributes
- renameResource(
- TEST_PROJECT,
- "@layout/preview",
- true /*updateReferences*/,
- "newlayout",
-
- "CHANGES:\n" +
- "-------\n" +
- "[x] activity_main.xml - /testRefactor10/res/layout-land/activity_main.xml\n" +
- " @@ -10 +10\n" +
- " - tools:listitem=\"@layout/preview\" >\n" +
- " + tools:listitem=\"@layout/newlayout\" >\n" +
- " @@ -17 +17\n" +
- " - tools:layout=\"@layout/preview\" />\n" +
- " + tools:layout=\"@layout/newlayout\" />");
- }
-
- // ---- Test infrastructure ----
-
- protected void renameResource(
- @NonNull Object[] testData,
- @NonNull Object resource,
- boolean updateReferences,
- @NonNull String newName,
- @NonNull String expected) throws Exception {
- renameResource(testData, resource, updateReferences, newName, expected, null);
- }
-
- protected void renameResource(
- @NonNull Object[] testData,
- @NonNull Object resource,
- boolean updateReferences,
- @NonNull String newName,
- @NonNull String expected,
- @NonNull String expectedWarnings) throws Exception {
- IProject project = createProject(testData);
- renameResource(project, resource, updateReferences, newName, expected, expectedWarnings);
- }
-
- protected void renameResource(
- @NonNull IProject project,
- @NonNull Object resource,
- boolean updateReferences,
- @NonNull String newName,
- @NonNull String expected,
- @NonNull String expectedWarnings) throws Exception {
- RenameProcessor processor = null;
- if (resource instanceof String) {
- String url = (String) resource;
- assert url.startsWith("@") : resource;
-
- ResourceUrl parsedUrl = ResourceUrl.parse(url);
- assertNotNull(url, parsedUrl);
- assert parsedUrl != null; // null analysis doesn't recognize assertNotNull
- ResourceType type = parsedUrl.type;
- String currentName = parsedUrl.name;
- RenameResourceProcessor p;
- p = new RenameResourceProcessor(project, type, currentName, newName);
- p.setUpdateReferences(updateReferences);
- processor = p;
- } else if (resource instanceof IResource) {
- IResource r = (IResource) resource;
- org.eclipse.ltk.internal.core.refactoring.resource.RenameResourceProcessor p;
- p = new org.eclipse.ltk.internal.core.refactoring.resource.RenameResourceProcessor(r);
- String fileName = r.getName();
- int dot = fileName.indexOf('.');
- String extension = (dot != -1) ? fileName.substring(dot) : "";
- p.setNewResourceName(newName + extension);
- p.setUpdateReferences(updateReferences);
- processor = p;
- } else if (resource instanceof IField) {
- RenameFieldProcessor p = new RenameFieldProcessor((IField) resource);
- p.setNewElementName(newName);
- p.setUpdateReferences(updateReferences);
- processor = p;
- } else {
- fail("Unsupported resource element in tests: " + resource);
- }
-
- assertNotNull(processor);
-
- RenameRefactoring refactoring = new RenameRefactoring(processor);
- checkRefactoring(refactoring, expected, expectedWarnings);
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/refactorings/renamepackage/ApplicationPackageNameRefactoringTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/refactorings/renamepackage/ApplicationPackageNameRefactoringTest.java
deleted file mode 100644
index 0ac034430..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/refactorings/renamepackage/ApplicationPackageNameRefactoringTest.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.refactorings.renamepackage;
-
-import com.android.annotations.NonNull;
-import com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo;
-import com.android.ide.eclipse.adt.internal.refactorings.core.RefactoringTestBase;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jdt.core.dom.AST;
-import org.eclipse.jdt.core.dom.Name;
-
-@SuppressWarnings("javadoc")
-public class ApplicationPackageNameRefactoringTest extends RefactoringTestBase {
- public void testRefactor1() throws Exception {
- renamePackage(
- TEST_PROJECT,
- "my.pkg.name",
-
- "CHANGES:\n" +
- "-------\n" +
- "[x] MainActivity.java - /testRefactor1/src/com/example/refactoringtest/MainActivity.java\n" +
- " @@ -7 +7\n" +
- " + import my.pkg.name.R;\n" +
- "\n" +
- "\n" +
- "[x] Make Manifest edits - /testRefactor1/AndroidManifest.xml\n" +
- " @@ -3 +3\n" +
- " - package=\"com.example.refactoringtest\"\n" +
- " + package=\"my.pkg.name\"\n" +
- " @@ -25 +25\n" +
- " - android:name=\".MainActivity2\"\n" +
- " + android:name=\"com.example.refactoringtest.MainActivity2\"");
- }
-
- public void testRefactor2() throws Exception {
- // Tests custom view handling
- renamePackage(
- TEST_PROJECT2,
- "my.pkg.name",
-
- "CHANGES:\n" +
- "-------\n" +
- "[x] MainActivity.java - /testRefactor2/src/com/example/refactoringtest/MainActivity.java\n" +
- " @@ -7 +7\n" +
- " + import my.pkg.name.R;\n" +
- "\n" +
- "\n" +
- "[x] Make Manifest edits - /testRefactor2/AndroidManifest.xml\n" +
- " @@ -3 +3\n" +
- " - package=\"com.example.refactoringtest\"\n" +
- " + package=\"my.pkg.name\"\n" +
- " @@ -25 +25\n" +
- " - android:name=\".MainActivity2\"\n" +
- " + android:name=\"com.example.refactoringtest.MainActivity2\"");
- }
-
- public void testRefactor3() throws Exception {
- // Tests BuildConfig imports and updates
- renamePackage(
- TEST_PROJECT3,
- "my.pkg.name",
-
- "CHANGES:\n" +
- "-------\n" +
- "[x] MoreCode.java - /testRefactor3/src/com/example/refactoringtest/subpkg/MoreCode.java\n" +
- " @@ -7 +7\n" +
- " - import com.example.refactoringtest.BuildConfig;\n" +
- " - import com.example.refactoringtest.Manifest;\n" +
- " - import com.example.refactoringtest.R;\n" +
- " + import my.pkg.name.BuildConfig;\n" +
- " + import my.pkg.name.Manifest;\n" +
- " + import my.pkg.name.R;\n" +
- "\n" +
- "\n" +
- "[x] MainActivity.java - /testRefactor3/src/com/example/refactoringtest/MainActivity.java\n" +
- " @@ -7 +7\n" +
- " + import my.pkg.name.R;\n" +
- "\n" +
- "\n" +
- "[x] Make Manifest edits - /testRefactor3/AndroidManifest.xml\n" +
- " @@ -3 +3\n" +
- " - package=\"com.example.refactoringtest\"\n" +
- " + package=\"my.pkg.name\"\n" +
- " @@ -25 +25\n" +
- " - android:name=\".MainActivity2\"\n" +
- " + android:name=\"com.example.refactoringtest.MainActivity2\"");
- }
-
- // ---- Test infrastructure ----
-
- protected void renamePackage(
- @NonNull Object[] testData,
- @NonNull String newName,
- @NonNull String expected) throws Exception {
- IProject project = createProject(testData);
- renamePackage(project, newName, expected);
- }
-
- protected void renamePackage(
- @NonNull IProject project,
- @NonNull String newName,
- @NonNull String expected) throws Exception {
- ManifestInfo info = ManifestInfo.get(project);
- String currentPackage = info.getPackage();
- assertNotNull(currentPackage);
-
- final AST astValidator = AST.newAST(AST.JLS3);
- Name oldPackageName = astValidator.newName(currentPackage);
- Name newPackageName = astValidator.newName(newName);
- ApplicationPackageNameRefactoring refactoring =
- new ApplicationPackageNameRefactoring(project, oldPackageName, newPackageName);
- checkRefactoring(refactoring, expected);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ExportGradleTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ExportGradleTest.java
deleted file mode 100644
index f5cc58bcf..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/wizards/exportgradle/ExportGradleTest.java
+++ /dev/null
@@ -1,303 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.exportgradle;
-
-import static com.android.sdklib.internal.project.ProjectProperties.PROPERTY_LIBRARY;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.editors.layout.refactoring.AdtProjectTest;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-import com.android.ide.eclipse.adt.internal.sdk.ProjectState;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.adt.internal.wizards.newproject.NewProjectCreator;
-import com.android.ide.eclipse.adt.internal.wizards.newproject.NewProjectWizardState;
-import com.android.ide.eclipse.adt.internal.wizards.newproject.NewProjectWizardState.Mode;
-import com.android.sdklib.internal.project.ProjectPropertiesWorkingCopy;
-import com.google.common.base.Charsets;
-import com.google.common.io.Files;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.QualifiedName;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-
-import java.io.File;
-import java.lang.reflect.InvocationTargetException;
-import java.util.Collections;
-
-public class ExportGradleTest extends AdtProjectTest {
- private QualifiedName ERROR_KEY = new QualifiedName(AdtPlugin.PLUGIN_ID, "JobErrorKey");
- private Throwable mLastThrown;
-
- @Override
- public void setUp() throws Exception {
- super.setUp();
- mLastThrown = null;
- }
-
- @Override
- protected boolean testCaseNeedsUniqueProject() {
- return true;
- }
-
- public void testSimpleAndroidApp() throws Throwable {
- IProject project = getProject("simple-app");
- final IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
-
- final ProjectSetupBuilder builder = new ProjectSetupBuilder();
- builder.setProject(Collections.singletonList(javaProject));
-
- Job job = new Job("Validate project") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- BuildFileCreator.createBuildFiles(builder, null, monitor);
- File buildfile = new File(javaProject.getResource().getLocation().toString(),
- BuildFileCreator.BUILD_FILE);
- assertTrue(buildfile.exists());
- String contents = Files.toString(buildfile, Charsets.UTF_8);
- String expectedContents =
- "buildscript {\n" +
- " repositories {\n" +
- " " + BuildFileCreator.MAVEN_REPOSITORY + "\n" +
- " }\n" +
- " dependencies {\n" +
- " " + BuildFileCreator.PLUGIN_CLASSPATH + "\n" +
- " }\n" +
- "}\n" +
- "apply plugin: 'android'\n" +
- "\n" +
- "dependencies {\n" +
- "}\n" +
- "\n" +
- "android {\n" +
- " compileSdkVersion 16\n" +
- " buildToolsVersion \"16\"\n" +
- "\n" +
- " defaultConfig {\n" +
- " minSdkVersion 1\n" +
- " targetSdkVersion 1\n" +
- " }\n" +
- " sourceSets {\n" +
- " main {\n" +
- " manifest.srcFile 'AndroidManifest.xml'\n" +
- " java.srcDirs = ['src']\n" +
- " resources.srcDirs = ['src']\n" +
- " aidl.srcDirs = ['src']\n" +
- " renderscript.srcDirs = ['src']\n" +
- " res.srcDirs = ['res']\n" +
- " assets.srcDirs = ['assets']\n" +
- " }\n" +
- " instrumentTest.setRoot('tests')\n" +
- " }\n" +
- "}";
-
- assertEqualsWhitespaceInsensitive(expectedContents, contents);
- } catch (Throwable t) {
- mLastThrown = t;
- }
- return null;
- }
- };
- job.schedule(1000);
- job.join();
- Object property = job.getProperty(ERROR_KEY);
- assertNull(property);
- if (mLastThrown != null) {
- throw mLastThrown;
- }
- }
-
- public void testSimpleAndroidLib() throws Throwable {
- final IProject project = getProject("simple-library");
- ProjectState projectState = Sdk.getProjectState(project.getProject());
- ProjectPropertiesWorkingCopy propertiesWorkingCopy = projectState.getProperties().makeWorkingCopy();
- propertiesWorkingCopy.setProperty(PROPERTY_LIBRARY, "true");
- propertiesWorkingCopy.save();
- IResource projectProp = project.findMember(SdkConstants.FN_PROJECT_PROPERTIES);
- if (projectProp != null) {
- projectProp.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor());
- }
-
- Job job = new Job("Validate project") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
-
- final ProjectSetupBuilder builder = new ProjectSetupBuilder();
- builder.setProject(Collections.singletonList(javaProject));
-
- BuildFileCreator.createBuildFiles(builder, null, monitor);
- File buildfile = new File(javaProject.getResource().getLocation().toString(),
- BuildFileCreator.BUILD_FILE);
- assertTrue(buildfile.exists());
- String contents = Files.toString(buildfile, Charsets.UTF_8);
- String expectedContents =
- "buildscript {\n" +
- " repositories {\n" +
- " " + BuildFileCreator.MAVEN_REPOSITORY + "\n" +
- " }\n" +
- " dependencies {\n" +
- " " + BuildFileCreator.PLUGIN_CLASSPATH + "\n" +
- " }\n" +
- "}\n" +
- "apply plugin: 'android-library'\n" +
- "\n" +
- "dependencies {\n" +
- "}\n" +
- "\n" +
- "android {\n" +
- " compileSdkVersion 16\n" +
- " buildToolsVersion \"16\"\n" +
- "\n" +
- " defaultConfig {\n" +
- " minSdkVersion 1\n" +
- " targetSdkVersion 1\n" +
- " }\n" +
- " sourceSets {\n" +
- " main {\n" +
- " manifest.srcFile 'AndroidManifest.xml'\n" +
- " java.srcDirs = ['src']\n" +
- " resources.srcDirs = ['src']\n" +
- " aidl.srcDirs = ['src']\n" +
- " renderscript.srcDirs = ['src']\n" +
- " res.srcDirs = ['res']\n" +
- " assets.srcDirs = ['assets']\n" +
- " }\n" +
- " instrumentTest.setRoot('tests')\n" +
- " }\n" +
- "}";
-
- assertEqualsWhitespaceInsensitive(expectedContents, contents);
- } catch (Throwable t) {
- mLastThrown = t;
- }
- return null;
- }
- };
- job.schedule(1000);
- job.join();
- Object property = job.getProperty(ERROR_KEY);
- assertNull(property);
- if (mLastThrown != null) {
- throw mLastThrown;
- }
- }
-
- public void testPlainJavaProject() throws Throwable {
- IProject project = getJavaProject("simple-java");
- final IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
-
- final ProjectSetupBuilder builder = new ProjectSetupBuilder();
- builder.setProject(Collections.singletonList(javaProject));
-
- BuildFileCreator.createBuildFiles(builder, null, null);
- Job job = new Job("Validate project") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- File buildfile = new File(javaProject.getResource().getLocation().toString(), "build.gradle");
- assertTrue(buildfile.exists());
- String contents = Files.toString(buildfile, Charsets.UTF_8);
- String expectedContents =
- "apply plugin: 'java'\n" +
- "sourceSets {\n" +
- " main.java.srcDirs = ['src']\n" +
- "}";
-
- assertEqualsWhitespaceInsensitive(expectedContents, contents);
- } catch (Throwable t) {
- mLastThrown = t;
- }
- return null;
- }
- };
- job.schedule(1000);
- job.join();
- Object property = job.getProperty(ERROR_KEY);
- assertNull(property);
- if (mLastThrown != null) {
- throw mLastThrown;
- }
- }
-
- protected IProject getProject(String projectName) {
- IProject project = createProject(projectName);
- assertNotNull(project);
- if (!testCaseNeedsUniqueProject() && !testNeedsUniqueProject()) {
- addCleanupDir(AdtUtils.getAbsolutePath(project).toFile());
- }
- addCleanupDir(project.getFullPath().toFile());
- return project;
- }
-
- protected IProject getJavaProject(String projectName) {
- IProject project = createJavaProject(projectName);
- assertNotNull(project);
- if (!testCaseNeedsUniqueProject() && !testNeedsUniqueProject()) {
- addCleanupDir(AdtUtils.getAbsolutePath(project).toFile());
- }
- addCleanupDir(project.getFullPath().toFile());
- return project;
- }
-
- protected IProject createJavaProject(String name) {
- IRunnableContext context = new IRunnableContext() {
- @Override
- public void run(boolean fork, boolean cancelable, IRunnableWithProgress runnable)
- throws InvocationTargetException, InterruptedException {
- runnable.run(new NullProgressMonitor());
- }
- };
- NewProjectWizardState state = new NewProjectWizardState(Mode.ANY);
- state.projectName = name;
- state.packageName = TEST_PROJECT_PACKAGE;
- state.activityName = name;
- state.applicationName = name;
- state.createActivity = false;
- state.useDefaultLocation = true;
- if (getMinSdk() != -1) {
- state.minSdk = Integer.toString(getMinSdk());
- }
-
- NewProjectCreator creator = new NewProjectCreator(state, context);
- creator.createJavaProjects();
- return validateProjectExists(name);
- }
-
- /**
- * Compares two strings, disregarding whitespace. This makes the test less brittle with respect
- * to insignificant changes.
- */
- protected void assertEqualsWhitespaceInsensitive(String a, String b) {
- a = stripWhitespace(a);
- b = stripWhitespace(b);
- assertEquals("Expected:\n" + a + "\nbut was:\n" + b + "\n\n", a, b);
- }
-
- protected String stripWhitespace(String s) {
- return s.replaceAll("\\s","");
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateHandlerTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateHandlerTest.java
deleted file mode 100644
index 9d3bc60c6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateHandlerTest.java
+++ /dev/null
@@ -1,901 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import static com.android.SdkConstants.CURRENT_PLATFORM;
-import static com.android.SdkConstants.FD_TOOLS;
-import static com.android.SdkConstants.PLATFORM_WINDOWS;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.ATTR_MIN_API;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectWizard.ATTR_MIN_BUILD_API;
-import static com.android.ide.eclipse.adt.internal.wizards.templates.TemplateHandler.ATTR_ID;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.sdklib.SdkVersionInfo;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.lint.EclipseLintClient;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.ide.eclipse.tests.SdkLoadingTestCase;
-import com.android.sdklib.IAndroidTarget;
-import com.android.utils.GrabProcessOutput;
-import com.android.utils.GrabProcessOutput.IProcessOutput;
-import com.android.utils.GrabProcessOutput.Wait;
-import com.android.tools.lint.checks.ManifestDetector;
-import com.android.tools.lint.checks.SecurityDetector;
-import com.android.tools.lint.client.api.Configuration;
-import com.android.tools.lint.client.api.DefaultConfiguration;
-import com.android.tools.lint.client.api.JavaParser;
-import com.android.tools.lint.client.api.LintClient;
-import com.android.tools.lint.client.api.LintDriver;
-import com.android.tools.lint.client.api.XmlParser;
-import com.android.tools.lint.detector.api.Category;
-import com.android.tools.lint.detector.api.Context;
-import com.android.tools.lint.detector.api.Issue;
-import com.android.tools.lint.detector.api.Location;
-import com.android.tools.lint.detector.api.Project;
-import com.android.tools.lint.detector.api.Scope;
-import com.android.tools.lint.detector.api.Severity;
-import com.android.tools.lint.detector.api.TextFormat;
-import com.google.common.base.Charsets;
-import com.google.common.base.Stopwatch;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-import com.google.common.io.Files;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.Platform;
-import org.eclipse.core.runtime.QualifiedName;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.ltk.core.refactoring.Change;
-import org.eclipse.ltk.core.refactoring.CompositeChange;
-import org.w3c.dom.Element;
-
-import java.io.File;
-import java.io.IOException;
-import java.lang.reflect.InvocationTargetException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-
-/**
- * Unit tests for template instantiation.
- * <p>
- * Note: This test can take multiple hours to run!
- *
- * <p>
- * TODO: Test all permutations of variables (it currently just varies one at a time with the
- * rest of the defaults)
- * TODO: Test trying to change strings arguments (currently just varies enums and booleans)
- * TODO: Test adding multiple instances of the templates (to look for resource conflicts)
- */
-@SuppressWarnings("javadoc")
-public class TemplateHandlerTest extends SdkLoadingTestCase {
- /**
- * Flag used to quickly check each template once (for one version), to get
- * quicker feedback on whether something is broken instead of waiting for
- * all the versions for each template first
- */
- private static final boolean TEST_FEWER_API_VERSIONS = true;
- private static final boolean TEST_JUST_ONE_MIN_SDK = false;
- private static final boolean TEST_JUST_ONE_BUILD_TARGET = true;
- private static final boolean TEST_JUST_ONE_TARGET_SDK_VERSION = true;
- private QualifiedName ERROR_KEY = new QualifiedName(AdtPlugin.PLUGIN_ID, "JobErrorKey");
- private static int sCount = 0;
- /**
- * If true, check this template with all the interesting (
- * {@link #isInterestingApiLevel(int)}) api versions
- */
- private boolean mApiSensitiveTemplate;
- /**
- * Set of templates already tested with separate unit test; remainder is
- * checked in {@link #testCreateRemainingProjects()}
- */
- private static final Set<File> sProjectTestedSeparately = Sets.newHashSet();
- /**
- * Set of templates already tested with separate unit test; remainder is
- * checked in {@link #testCreateRemainingTemplates()}
- */
- private static final Set<File> sTemplateTestedSeparately = Sets.newHashSet();
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- mApiSensitiveTemplate = true;
- }
-
- /**
- * Is the given api level interesting for testing purposes? This is used to
- * skip gaps, such that we for example only check say api 8, 9, 11, 14, etc
- * -- versions where the <b>templates</b> are doing conditional changes. To
- * be EXTRA comprehensive, occasionally try returning true unconditionally
- * here to test absolutely everything.
- */
- private boolean isInterestingApiLevel(int api) {
- // For templates that aren't API sensitive, only test with API = 16
- if (!mApiSensitiveTemplate) {
- return api == 16;
- }
-
- switch (api) {
- case 1:
- case 8:
- return true;
- case 11:
- return true;
- case 14:
- return true;
- case 9:
- case 16:
- return !TEST_FEWER_API_VERSIONS;
- default:
- return false;
- }
- }
-
- public void testNewBlankProject() throws Exception {
- Stopwatch stopwatch = Stopwatch.createUnstarted();
- stopwatch.start();
- checkProjectWithActivity(null);
- stopwatch.stop();
- System.out.println("Checked blank project successfully in "
- + stopwatch.toString());
- }
-
- public void testNewBlankActivity() throws Exception {
- checkCreateTemplate("activities", "BlankActivity");
- }
-
- public void testBlankActivityInProject() throws Exception {
- checkCreateActivityInProject("BlankActivity");
- }
-
- public void testNewMasterDetailFlow() throws Exception {
- checkCreateTemplate("activities", "MasterDetailFlow");
- }
-
- public void testMasterDetailFlowInProject() throws Exception {
- checkCreateActivityInProject("MasterDetailFlow");
- }
-
- public void testNewFullscreen() throws Exception {
- checkCreateTemplate("activities", "FullscreenActivity");
- }
-
- public void testFullscreenInProject() throws Exception {
- checkCreateActivityInProject("FullscreenActivity");
- }
-
- public void testNewLoginActivity() throws Exception {
- checkCreateTemplate("activities", "LoginActivity");
- }
-
- public void testLoginActivityInProject() throws Exception {
- checkCreateActivityInProject("MasterDetailFlow");
- }
-
- public void testNewSettingsActivity() throws Exception {
- checkCreateTemplate("activities", "SettingsActivity");
- }
-
- public void testSettingsActivityInProject() throws Exception {
- checkCreateActivityInProject("SettingsActivity");
- }
-
- public void testNewBroadcastReceiver() throws Exception {
- // No need to try this template with multiple platforms, one is adequate
- mApiSensitiveTemplate = false;
- checkCreateTemplate("other", "BroadcastReceiver");
- }
-
- public void testNewContentProvider() throws Exception {
- mApiSensitiveTemplate = false;
- checkCreateTemplate("other", "ContentProvider");
- }
-
- public void testNewCustomView() throws Exception {
- mApiSensitiveTemplate = false;
- checkCreateTemplate("other", "CustomView");
- }
-
- public void testNewService() throws Exception {
- mApiSensitiveTemplate = false;
- checkCreateTemplate("other", "Service");
- }
-
- public void testCreateRemainingTemplates() throws Exception {
- sCount = 0;
- long begin = System.currentTimeMillis();
- TemplateManager manager = new TemplateManager();
- List<File> other = manager.getTemplates("other");
- for (File templateFile : other) {
- if (sTemplateTestedSeparately.contains(templateFile)) {
- continue;
- }
- checkTemplate(templateFile);
- }
- // Also try creating templates, not as part of creating a project
- List<File> activities = manager.getTemplates("activities");
- for (File templateFile : activities) {
- if (sTemplateTestedSeparately.contains(templateFile)) {
- continue;
- }
- checkTemplate(templateFile);
- }
- long end = System.currentTimeMillis();
- System.out.println("Successfully checked " + sCount + " template permutations in "
- + ((end - begin) / (1000 * 60)) + " minutes");
- }
-
- public void testCreateRemainingProjects() throws Exception {
- sCount = 0;
- long begin = System.currentTimeMillis();
- TemplateManager manager = new TemplateManager();
- List<File> templates = manager.getTemplates("activities");
- for (File activityFile : templates) {
- if (sTemplateTestedSeparately.contains(activityFile)) {
- continue;
- }
- checkProjectWithActivity(activityFile.getName());
- }
- long end = System.currentTimeMillis();
- System.out.println("Successfully checked " + sCount + " project permutations in "
- + ((end - begin) / (1000 * 60)) + " minutes");
- }
-
- // ---- Test support code below ----
-
- private void checkCreateActivityInProject(String activityName) throws Exception {
- Stopwatch stopwatch = Stopwatch.createUnstarted();
- stopwatch.start();
- File templateFile = findTemplate("activities", activityName);
- sProjectTestedSeparately.add(templateFile);
- checkProjectWithActivity(templateFile.getName());
- stopwatch.stop();
- System.out.println("Checked " + templateFile.getName() + " successfully in "
- + stopwatch.toString());
- }
-
- private void checkCreateTemplate(String category, String name) throws Exception {
- Stopwatch stopwatch = Stopwatch.createUnstarted();
- stopwatch.start();
- File templateFile = findTemplate(category, name);
- assertNotNull(templateFile);
- sTemplateTestedSeparately.add(templateFile);
- checkTemplate(templateFile);
- stopwatch.stop();
- System.out.println("Checked " + templateFile.getName() + " successfully in "
- + stopwatch.toString());
- }
-
- private static File findTemplate(String category, String name) {
- File templateRootFolder = TemplateManager.getTemplateRootFolder();
- assertNotNull(templateRootFolder);
- File file = new File(templateRootFolder, category + File.separator + name);
- assertTrue(file.getPath(), file.exists());
- return file;
- }
-
- private void checkTemplate(File templateFile) throws Exception {
- NewProjectWizardState values = new NewProjectWizardState();
- values.applicationName = "My Application";
- values.packageName = "my.pkg2";
-
- values.isLibrary = false;
- values.createIcon = false;
- values.useDefaultLocation = true;
- values.createActivity = false;
-
- String projectNameBase = "MyTemplateProject_" + templateFile.getName();
- values.projectName = projectNameBase;
- values.createActivity = false;
-
- // Create the new template
-
- NewTemplateWizardState state = new NewTemplateWizardState();
- state.setTemplateLocation(templateFile);
- state.minSdkLevel = values.minSdkLevel;
-
- // Iterate over all (valid) combinations of build target, minSdk and targetSdk
- IAndroidTarget[] targets = Sdk.getCurrent().getTargets();
- for (int i = targets.length - 1; i >= 0; i--) {
- IAndroidTarget target = targets[i];
- if (!target.isPlatform()) {
- continue;
- }
- if (!isInterestingApiLevel(target.getVersion().getApiLevel())) {
- continue;
- }
-
- for (int minSdk = 1;
- minSdk <= SdkVersionInfo.HIGHEST_KNOWN_API;
- minSdk++) {
- // Don't bother checking *every* single minSdk, just pick some interesting ones
- if (!isInterestingApiLevel(minSdk)) {
- continue;
- }
-
- for (int targetSdk = minSdk;
- targetSdk <= SdkVersionInfo.HIGHEST_KNOWN_API;
- targetSdk++) {
- if (!isInterestingApiLevel(targetSdk)) {
- continue;
- }
-
- // Make sure this template is supported with these versions
- IStatus status = values.template.validateTemplate(
- minSdk, target.getVersion().getApiLevel());
- if (status != null && !status.isOK()) {
- continue;
- }
-
- // Also make sure activity is enabled for these versions
- status = state.getTemplateHandler().validateTemplate(
- minSdk, target.getVersion().getApiLevel());
- if (status != null && !status.isOK()) {
- continue;
- }
-
- // Iterate over all new new project templates
-
- // should I try all options of theme with all platforms?
- // or just try all platforms, with one setting for each?
- // doesn't seem like I need to multiply
- // just pick the best setting that applies instead for each platform
- List<Parameter> parameters = values.template.getTemplate().getParameters();
- projectParameters:
- for (Parameter parameter : parameters) {
- List<Element> options = parameter.getOptions();
- if (parameter.type == Parameter.Type.ENUM) {
- for (Element element : options) {
- Option option = Option.get(element);
- String optionId = option.id;
- int optionMinSdk = option.minSdk;
- int optionMinBuildApi = option.minBuild;
- if (optionMinSdk <= minSdk &&
- optionMinBuildApi <= target.getVersion().getApiLevel()) {
- values.parameters.put(parameter.id, optionId);
- if (parameter.id.equals("baseTheme")) {
- String base = projectNameBase + "_min_" + minSdk
- + "_target_" + targetSdk
- + "_build_" + target.getVersion().getApiLevel()
- + "_theme_" + optionId;
- System.out.println("checking base " + base);
-
- checkApiTarget(minSdk, targetSdk, target, values, base,
- state);
- break projectParameters;
- }
- }
- }
- }
- }
-
- if (TEST_JUST_ONE_TARGET_SDK_VERSION) {
- break;
- }
- }
-
- if (TEST_JUST_ONE_MIN_SDK) {
- break;
- }
- }
-
- if (TEST_JUST_ONE_BUILD_TARGET) {
- break;
- }
- }
- }
-
- private void checkProjectWithActivity(String activity) throws Exception {
- NewProjectWizardState values = new NewProjectWizardState();
- values.applicationName = "My Application";
- values.packageName = "my.pkg";
-
- values.isLibrary = false;
- values.createIcon = false;
- values.useDefaultLocation = true;
-
- // These are basically unused; passed as defaults
- values.activityName = activity == null ? "Blank" : activity;
- values.activityTitle = "My Activity Title";
-
- String projectNameBase = "MyProject_" + values.activityName;
- values.projectName = projectNameBase;
-
- values.createActivity = activity != null;
- NewTemplateWizardState activityValues = values.activityValues;
- assertNotNull(activityValues);
- activityValues.minSdkLevel = values.minSdkLevel;
-
-
- // Iterate over all (valid) combinations of build target, minSdk and targetSdk
- IAndroidTarget[] targets = Sdk.getCurrent().getTargets();
- for (int i = targets.length - 1; i >= 0; i--) {
- IAndroidTarget target = targets[i];
- if (!target.isPlatform()) {
- continue;
- }
- if (!isInterestingApiLevel(target.getVersion().getApiLevel())) {
- continue;
- }
-
- for (int minSdk = 1;
- minSdk <= SdkVersionInfo.HIGHEST_KNOWN_API;
- minSdk++) {
- // Don't bother checking *every* single minSdk, just pick some interesting ones
- if (!isInterestingApiLevel(minSdk)) {
- continue;
- }
-
- for (int targetSdk = minSdk;
- targetSdk <= SdkVersionInfo.HIGHEST_KNOWN_API;
- targetSdk++) {
- if (!isInterestingApiLevel(targetSdk)) {
- continue;
- }
-
- // Make sure this template is supported with these versions
- IStatus status = values.template.validateTemplate(
- values.minSdkLevel, values.getBuildApi());
- if (status != null && !status.isOK()) {
- continue;
- }
-
- // Also make sure activity is enabled for these versions
- status = values.activityValues.getTemplateHandler().validateTemplate(
- values.minSdkLevel, values.getBuildApi());
- if (status != null && !status.isOK()) {
- continue;
- }
-
- // Iterate over all new new project templates
-
- // should I try all options of theme with all platforms?
- // or just try all platforms, with one setting for each?
- // doesn't seem like I need to multiply
- // just pick the best setting that applies instead for each platform
- List<Parameter> parameters = values.template.getTemplate().getParameters();
- for (Parameter parameter : parameters) {
- List<Element> options = parameter.getOptions();
- if (parameter.type == Parameter.Type.ENUM) {
- for (Element element : options) {
- Option option = Option.get(element);
- String optionId = option.id;
- int optionMinSdk = option.minSdk;
- int optionMinBuildApi = option.minBuild;
- if (optionMinSdk <= minSdk &&
- optionMinBuildApi <= target.getVersion().getApiLevel()) {
- values.parameters.put(parameter.id, optionId);
- if (parameter.id.equals("baseTheme")) {
- String base = projectNameBase + "_min_" + minSdk
- + "_target_" + targetSdk
- + "_build_" + target.getVersion().getApiLevel()
- + "_theme_" + optionId;
- System.out.println("checking base " + base);
-
- checkApiTarget(minSdk, targetSdk, target, values, base,
- null);
-
- }
- }
- }
- }
- }
-
- if (TEST_JUST_ONE_TARGET_SDK_VERSION) {
- break;
- }
- }
-
- if (TEST_JUST_ONE_MIN_SDK) {
- break;
- }
- }
-
- if (TEST_JUST_ONE_BUILD_TARGET) {
- break;
- }
- }
- }
-
- private void checkApiTarget(
- int minSdk,
- int targetSdk,
- @NonNull IAndroidTarget target,
- @NonNull NewProjectWizardState projectValues,
- @NonNull String projectNameBase,
- @Nullable NewTemplateWizardState templateValues)
- throws Exception {
- NewTemplateWizardState values =
- projectValues.createActivity ? projectValues.activityValues : templateValues;
-
- projectValues.minSdk = Integer.toString(minSdk);
- projectValues.minSdkLevel = minSdk;
- projectValues.targetSdkLevel = targetSdk;
- projectValues.target = target;
-
- if (values == null) {
- checkProject(projectValues, templateValues);
- return;
- }
-
- // Next check all other parameters, cycling through booleans and enums.
- TemplateHandler templateHandler = values.getTemplateHandler();
- TemplateMetadata template = templateHandler.getTemplate();
- assertNotNull(template);
- List<Parameter> parameters = template.getParameters();
-
- if (!projectValues.createActivity) {
- for (Parameter parameter : parameters) {
- values.parameters.put(parameter.id, parameter.value);
- }
- }
-
- for (Parameter parameter : parameters) {
- if (parameter.type == Parameter.Type.SEPARATOR
- || parameter.type == Parameter.Type.STRING) {
- // TODO: Consider whether we should attempt some strings here
- continue;
- }
-
- // The initial (default value); revert to this one after cycling,
- Object initial = values.parameters.get(parameter.id);
-
- if (parameter.type == Parameter.Type.ENUM) {
- List<Element> options = parameter.getOptions();
- for (Element element : options) {
- Option option = Option.get(element);
- String optionId = option.id;
- int optionMinSdk = option.minSdk;
- int optionMinBuildApi = option.minBuild;
- if (projectValues.minSdkLevel >= optionMinSdk &&
- projectValues.getBuildApi() >= optionMinBuildApi) {
- values.parameters.put(parameter.id, optionId);
- projectValues.projectName = projectNameBase + "_" + parameter.id
- + "_" + optionId;
- checkProject(projectValues, templateValues);
- }
- }
- } else {
- assert parameter.type == Parameter.Type.BOOLEAN;
- if (parameter.id.equals("isLauncher") && projectValues.createActivity) {
- // Skipping this one: always true when launched from new project
- continue;
- }
- boolean value = false;
- values.parameters.put(parameter.id, value);
- projectValues.projectName = projectNameBase + "_" + parameter.id
- + "_" + value;
- checkProject(projectValues, templateValues);
-
- value = true;
- values.parameters.put(parameter.id, value);
- projectValues.projectName = projectNameBase + "_" + parameter.id
- + "_" + value;
- checkProject(projectValues, templateValues);
- }
-
- values.parameters.put(parameter.id, initial);
- }
- }
-
- private final class OutputGrabber implements IProcessOutput {
- private final List<String> output = Lists.newArrayList();
- private final List<String> error = Lists.newArrayList();
-
- @Override
- public void out(@Nullable String line) {
- if (line != null) {
- output.add(line);
- }
- }
-
- @Override
- public void err(@Nullable String line) {
- if (line != null) {
- error.add(line);
- }
- }
-
- @NonNull
- private List<String> getOutput() {
- return output;
- }
-
- @NonNull
- private List<String> getError() {
- return error;
- }
- }
-
- private static class Option {
- private String id;
- private int minSdk;
- private int minBuild;
-
- public Option(String id, int minSdk, int minBuild) {
- this.id = id;
- this.minSdk = minSdk;
- this.minBuild = minBuild;
- }
-
- private static Option get(Element option) {
- String optionId = option.getAttribute(ATTR_ID);
- String minApiString = option.getAttribute(ATTR_MIN_API);
- int optionMinSdk = 1;
- if (minApiString != null && !minApiString.isEmpty()) {
- try {
- optionMinSdk = Integer.parseInt(minApiString);
- } catch (NumberFormatException nufe) {
- // Templates aren't allowed to contain codenames, should
- // always be an integer
- AdtPlugin.log(nufe, null);
- optionMinSdk = 1;
- }
- }
- String minBuildApiString = option.getAttribute(ATTR_MIN_BUILD_API);
- int optionMinBuildApi = 1;
- if (minBuildApiString != null && !minBuildApiString.isEmpty()) {
- try {
- optionMinBuildApi = Integer.parseInt(minBuildApiString);
- } catch (NumberFormatException nufe) {
- // Templates aren't allowed to contain codenames, should
- // always be an integer
- AdtPlugin.log(nufe, null);
- optionMinBuildApi = 1;
- }
- }
-
-
- return new Option(optionId, optionMinSdk, optionMinBuildApi);
- }
- }
-
- private void checkProject(
- @NonNull NewProjectWizardState projectValues,
- @Nullable NewTemplateWizardState templateValues) throws Exception {
- NewTemplateWizardState values =
- projectValues.createActivity ? projectValues.activityValues : templateValues;
- if (values != null) { // if not, creating blank project
- // Validate that a template is only being used in a context it is compatible with!
- IStatus status = values.getTemplateHandler().validateTemplate(
- projectValues.minSdkLevel, projectValues.getBuildApi());
- if (status != null && !status.isOK()) {
- fail(status.toString());
- }
- }
-
- assertNotNull(projectValues.projectName);
- projectValues.projectName = AdtUtils.getUniqueProjectName(projectValues.projectName, "");
- IPath workspace = Platform.getLocation();
- String projectLocation = workspace.append(projectValues.projectName).toOSString();
- projectValues.projectLocation = projectLocation;
-
- // Create project with the given parameter map
- final IProject project = createProject(projectValues);
- assertNotNull(project);
-
- if (templateValues != null) {
- templateValues.project = project;
- List<Change> changes = templateValues.computeChanges();
- if (!changes.isEmpty()) {
- try {
- CompositeChange composite = new CompositeChange("",
- changes.toArray(new Change[changes.size()]));
- composite.perform(new NullProgressMonitor());
- } catch (CoreException e) {
- fail(e.getLocalizedMessage());
- }
- }
- }
-
- // Project creation has some async hooks so don't attempt to build it *right* away
- Job job = new Job("Validate project") {
- @Override
- protected IStatus run(IProgressMonitor monitor) {
- try {
- ensureValidProject(this, project);
- return Status.OK_STATUS;
- } catch (Exception e) {
- fail(e.toString());
- }
- return null;
- }
- };
- job.schedule(1000);
- job.join();
- Object property = job.getProperty(ERROR_KEY);
- assertNull(property);
- }
-
- private IProject createProject(NewProjectWizardState values) throws InvocationTargetException {
- NewProjectWizard wizard = new NewProjectWizard();
- wizard.setValues(values);
- wizard.performFinish(new NullProgressMonitor());
-
- if (TemplateHandler.sMostRecentException != null) {
- fail(values.projectName + ": " + TemplateHandler.sMostRecentException.toString());
- }
-
- IProject project = wizard.getProject();
- assertNotNull(project);
- assertTrue(project.exists());
- System.out.println("Created project " + project + " : " + AdtUtils.getAbsolutePath(project));
- return project;
- }
-
- private void ensureValidProject(@NonNull Job job, @NonNull IProject project) throws Exception {
- System.out.println("Begin build error check");
- ensureNoBuildErrors(job, project);
- System.out.println("Finished build error check");
-
- System.out.println("Begin lint check");
- ensureNoLintWarnings(job, project);
- System.out.println("Finished lint check");
-
- sCount++;
- }
-
- private void ensureNoLintWarnings(final Job job, IProject project) {
- System.setProperty("com.android.tools.lint.bindir", AdtPrefs.getPrefs().getOsSdkFolder()
- + File.separator + FD_TOOLS);
-
- LintDriver driver = new LintDriver(EclipseLintClient.getRegistry(), new LintClient() {
- @Override
- public void report(@NonNull Context context,
- @NonNull Issue issue, @NonNull Severity severity,
- @Nullable Location location, @NonNull String message, @NonNull TextFormat format) {
- String s = "Found lint error: " + issue.getId() + ": " + message + " at " + location;
- job.setProperty(ERROR_KEY, s);
- fail(s);
- }
-
- @Override
- public Configuration getConfiguration(@NonNull Project p) {
- return new DefaultConfiguration(this, p, null, new File("dummy.xml")) {
- @Override
- public boolean isEnabled(@NonNull Issue issue) {
- // Doesn't work: hangs in unit test context, something about
- // loading native libs.
- if (issue.getCategory() == Category.ICONS){
- return false;
- }
-
- if (issue == ManifestDetector.TARGET_NEWER) {
- // Don't complain about targetSdk < latest: we're deliberately
- // testing that (to make sure templates compile etc in compat
- // mode)
- return false;
- }
-
- if (issue == SecurityDetector.EXPORTED_SERVICE
- || issue == SecurityDetector.EXPORTED_PROVIDER
- || issue == SecurityDetector.EXPORTED_RECEIVER) {
- // Don't complain about missing permissions when exporting: the
- // unit test is deliberately turning on exported
- return false;
- }
-
- return true;
- }
- };
- }
-
- @Override
- @NonNull
- public String readFile(@NonNull File file) {
- try {
- return Files.toString(file, Charsets.UTF_8);
- } catch (IOException e) {
- fail(e.toString() + " for " + file.getPath());
- return "";
- }
- }
-
- @Override
- public void log(@NonNull Severity severity, @Nullable Throwable exception,
- @Nullable String format, @Nullable Object... args) {
- if (exception != null) {
- exception.printStackTrace();
- }
- if (format != null) {
- if (args != null) {
- System.err.println("Log: " + String.format(format, args));
- } else {
- System.err.println("Unexpected log message " + format);
- }
- }
- }
-
- @Override
- @Nullable
- public JavaParser getJavaParser(@Nullable Project project) {
- return new EclipseLintClient(null, null, null, false).getJavaParser(project);
- }
-
- @Override
- public XmlParser getXmlParser() {
- return new EclipseLintClient(null, null, null, false).getXmlParser();
- }
- });
- File projectDir = AdtUtils.getAbsolutePath(project).toFile();
- assertNotNull(projectDir);
- assertTrue(projectDir.getPath(), projectDir.isDirectory());
- driver.analyze(Collections.singletonList(projectDir), Scope.ALL);
- }
-
- // Wait for test build support.
- // This is copied from {@link SampleProjectTest}
-
- private void ensureNoBuildErrors(final Job job, final IProject project) throws Exception {
- File projectDir = AdtUtils.getAbsolutePath(project).toFile();
-
- // Checking the build in Eclipse doesn't work well, because of asynchronous issues
- // (it looks like not all necessary changes are applied, and even adding waits works
- // unpredictably.)
- //
- // So instead we do it via the command line.
- // First add ant support:
- // $ android update project -p .
- // Then we run ant and look at the exit code to make sure it worked.
-
- List<String> command = new ArrayList<String>();
- command.add(AdtPlugin.getOsSdkToolsFolder() + "android" +
- (CURRENT_PLATFORM == PLATFORM_WINDOWS ? ".bat" : ""));
- command.add("update");
- command.add("project");
- command.add("-p");
- command.add(projectDir.getPath());
-
- // launch the command line process
- Process process = Runtime.getRuntime().exec(command.toArray(new String[command.size()]));
-
-
- OutputGrabber processOutput = new OutputGrabber();
- int status = GrabProcessOutput.grabProcessOutput(
- process,
- Wait.WAIT_FOR_READERS, // we really want to make sure we get all the output!
- processOutput);
- if (status != 0) {
- fail(processOutput.getOutput().toString() + processOutput.getError().toString());
- }
- assertEquals(0, status);
-
- // Run ant
- String antCmd = "ant" + (CURRENT_PLATFORM == PLATFORM_WINDOWS ? ".bat" : "");
- String antTarget = "debug";
- process = Runtime.getRuntime().exec(antCmd + " " + antTarget, null, projectDir);
- processOutput = new OutputGrabber();
- status = GrabProcessOutput.grabProcessOutput(
- process,
- Wait.WAIT_FOR_READERS, // we really want to make sure we get all the output!
- processOutput);
- if (status != 0) {
- fail(processOutput.getOutput().toString() + processOutput.getError().toString());
- }
- assertEquals(0, status);
- System.out.println("Ant succeeded (code=" + status + ")");
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/AdtTestData.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/AdtTestData.java
deleted file mode 100644
index c86f4cf5f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/AdtTestData.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License"); you
- * may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.android.ide.eclipse.tests;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.AdtConstants;
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import org.eclipse.core.runtime.FileLocator;
-import org.eclipse.core.runtime.Platform;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.URL;
-import java.util.logging.Logger;
-
-/**
- * Helper class for retrieving test data
- * <p/>
- * All tests which need to retrieve paths to test data files should go through this class.
- */
-public class AdtTestData {
-
- /** singleton instance */
- private static AdtTestData sInstance = null;
- private static final Logger sLogger = Logger.getLogger(AdtTestData.class.getName());
-
- /** The prefered directory separator to use. */
- private static final String DIR_SEP_STR = "/";
- private static final char DIR_SEP_CHAR = '/';
-
- /** The absolute file path to the plugin's contents. */
- private String mOsRootDataPath;
-
- private AdtTestData() {
- // can set test_data env variable to override default behavior of
- // finding data using class loader
- // useful when running in plugin environment, where test data is inside
- // bundled jar, and must be extracted to temp filesystem location to be
- // accessed normally
- mOsRootDataPath = System.getProperty("test_data");
- if (mOsRootDataPath == null) {
- sLogger.info("Cannot find test_data environment variable, init to class loader");
- URL url = this.getClass().getClassLoader().getResource("."); //$NON-NLS-1$
-
- if (Platform.isRunning()) {
- sLogger.info("Running as an Eclipse Plug-in JUnit test, using FileLocator");
- try {
- mOsRootDataPath = FileLocator.resolve(url).getFile();
- if (SdkConstants.currentPlatform() == SdkConstants.PLATFORM_WINDOWS) {
- // Fix the path returned by the URL resolver
- // so that it actually works on Windows.
-
- // First, Windows paths don't start with a / especially
- // if they contain a drive spec such as C:/...
- int pos = mOsRootDataPath.indexOf(':');
- if (pos > 0 && mOsRootDataPath.charAt(0) == '/') {
- mOsRootDataPath = mOsRootDataPath.substring(1);
- }
-
- // Looking for "." probably inserted a /./, so clean it up
- mOsRootDataPath = mOsRootDataPath.replace("/./", "/");
- }
- } catch (IOException e) {
- sLogger.warning("IOException while using FileLocator, reverting to url");
- mOsRootDataPath = url.getFile();
- }
- } else {
- sLogger.info("Running as an plain JUnit test, using url as-is");
- mOsRootDataPath = url.getFile();
- }
- }
-
- if (mOsRootDataPath.equals(AdtConstants.WS_SEP)) {
- sLogger.warning("Resource data not found using class loader!, Defaulting to no path");
- }
-
- if (File.separatorChar == '\\') {
- // On Windows, uniformize all separators to use the / convention
- mOsRootDataPath.replace('\\', DIR_SEP_CHAR);
- }
-
- if (!mOsRootDataPath.endsWith(File.separator) && !mOsRootDataPath.endsWith(DIR_SEP_STR)) {
- sLogger.info("Fixing test_data env variable (does not end with path separator)");
- mOsRootDataPath += DIR_SEP_STR;
- }
- }
-
- /** Get the singleton instance of AdtTestData */
- public static AdtTestData getInstance() {
- if (sInstance == null) {
- sInstance = new AdtTestData();
- }
- return sInstance;
- }
-
- /**
- * Returns the absolute file path to a file located in this plugin.
- *
- * @param osRelativePath {@link String} path to file contained in plugin. Must
- * use path separators appropriate to host OS
- *
- * @return absolute OS path to test file
- */
- public String getTestFilePath(String osRelativePath) {
- File path = new File(mOsRootDataPath, osRelativePath);
-
- if (!path.exists()) {
- // On Windows at least this ends up using the wrong plugin path.
- String pkgAdt = AdtPlugin .class.getPackage().getName();
- String pkgTests = AdtTestData.class.getPackage().getName();
-
- if (mOsRootDataPath.contains(pkgAdt)) {
- path = new File(mOsRootDataPath.replace(pkgAdt, pkgTests), osRelativePath);
- }
-
- assert path.exists();
- }
-
- return path.getAbsolutePath();
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/AllTests.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/AllTests.java
deleted file mode 100644
index 5386142a8..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/AllTests.java
+++ /dev/null
@@ -1,40 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License"); you
- * may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.android.ide.eclipse.tests;
-
-import junit.framework.TestSuite;
-
-
-/**
- * Container TestSuite for all eclipse tests, both functional and unit
- */
-public class AllTests extends TestSuite {
-
- public AllTests() {
-
- }
-
- /**
- * Returns a suite of test cases to be run.
- */
- public static TestSuite suite() {
- TestSuite suite = new TestSuite();
- suite.addTest(FuncTests.suite());
- suite.addTest(UnitTests.suite());
- return suite;
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/EclipseTestCollector.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/EclipseTestCollector.java
deleted file mode 100644
index 6bbc955ee..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/EclipseTestCollector.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License"); you
- * may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.android.ide.eclipse.tests;
-
-import org.eclipse.core.runtime.Plugin;
-
-import java.lang.reflect.Modifier;
-import java.net.URL;
-import java.util.Enumeration;
-
-import junit.framework.TestCase;
-import junit.framework.TestSuite;
-
-/**
- * Class for collecting all test cases in an eclipse plugin
- *
- */
-public class EclipseTestCollector {
-
- /**
- * Constructor
- */
- public EclipseTestCollector() {
-
- }
-
- /**
- * Searches through given plugin, adding all TestCase classes to given suite
- * @param suite - TestSuite to add to
- * @param plugin - Plugin to search for tests
- * @param expectedPackage - expected package for tests. Only test classes
- * that start with this package name will be added to suite
- */
- @SuppressWarnings({"cast", "unchecked"})
- public void addTestCases(TestSuite suite, Plugin plugin, String expectedPackage) {
- if (plugin != null) {
- Enumeration<?> entries = plugin.getBundle().findEntries("/", "*.class", true);
-
- while (entries.hasMoreElements()) {
- URL entry = (URL)entries.nextElement();
- String filePath = entry.getPath().replace(".class", "");
- try {
- Class<?> testClass = getClass(filePath, expectedPackage);
- if (isTestClass(testClass)) {
- // In Eclipse 3.6 RCP Windows-x64, the signature has changed from
- // addTestSuite(Class)
- // to:
- // addTestSuite(Class<? extends TestCase>)
- // which is enough to create an error. To solve it, we cast into the
- // generics expected by the JUnit framework used by 3.6 and suppress the
- // warnings generated by the compiler under 3.5
- suite.addTestSuite((Class<? extends TestCase>)testClass);
- }
- }
- catch (ClassNotFoundException e) {
- // ignore, this is not the class we're looking for
- //sLogger.log(Level.INFO, "Could not load class " + filePath);
- }
- }
- }
- }
-
- /**
- * Returns true if given class should be added to suite
- */
- protected boolean isTestClass(Class<?> testClass) {
- return TestCase.class.isAssignableFrom(testClass) &&
- Modifier.isPublic(testClass.getModifiers()) &&
- hasPublicConstructor(testClass);
- }
-
- /**
- * Returns true if given class has a public constructor
- */
- @SuppressWarnings({"unchecked", "cast"})
- protected boolean hasPublicConstructor(Class<?> testClass) {
- try {
- // In Eclipse 3.6 RCP Windows-x64, the signature has changed from
- // getTestConstructor(Class)
- // to:
- // getTestConstructor(Class<? extends TestCase>)
- // which is enough to create an error. To solve it, we cast into the
- // generics expected by the JUnit framework used by 3.6 and suppress the
- // warnings generated by the compiler under 3.5
- TestSuite.getTestConstructor((Class<? extends TestCase>) testClass);
- } catch(NoSuchMethodException e) {
- return false;
- }
- return true;
- }
-
- /**
- * Load the class given by the plugin aka bundle file path
- * @param filePath - path of class in bundle
- * @param expectedPackage - expected package of class
- * @throws ClassNotFoundException
- */
- protected Class<?> getClass(String filePath, String expectedPackage) throws ClassNotFoundException {
- String dotPath = filePath.replace('/', '.');
- // remove the output folders, by finding where package name starts
- int index = dotPath.indexOf(expectedPackage);
- if (index == -1) {
- throw new ClassNotFoundException();
- }
- String packagePath = dotPath.substring(index);
- return Class.forName(packagePath);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/FuncTests.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/FuncTests.java
deleted file mode 100644
index efa880126..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/FuncTests.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License"); you
- * may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.android.ide.eclipse.tests;
-
-import com.android.ide.eclipse.tests.functests.layoutRendering.ApiDemosRenderingTest;
-
-import junit.framework.TestSuite;
-
-/**
- * Container TestSuite for all eclipse tests to be run
- */
-
-public class FuncTests extends TestSuite {
-
- static final String FUNC_TEST_PACKAGE = "com.android.ide.eclipse.tests.functests";
-
- public FuncTests() {
-
- }
-
- /**
- * Returns a suite of test cases to be run.
- * Needed for JUnit3 compliant command line test runner
- */
- public static TestSuite suite() {
- TestSuite suite = new TestSuite();
-
- // TODO: uncomment this when 'gen' folder error on create is fixed
- // suite.addTestSuite(SampleProjectTest.class);
- suite.addTestSuite(ApiDemosRenderingTest.class);
-
- return suite;
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/SdkLoadingTestCase.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/SdkLoadingTestCase.java
deleted file mode 100644
index 65ce8e1d7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/SdkLoadingTestCase.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License"); you
- * may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.android.ide.eclipse.tests;
-
-import com.android.ide.common.sdk.LoadStatus;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.preferences.AdtPrefs;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetParser;
-import com.android.ide.eclipse.adt.internal.sdk.Sdk;
-import com.android.sdklib.IAndroidTarget;
-import com.android.testutils.SdkTestCase;
-
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.NullProgressMonitor;
-
-/**
- * A test case which uses the SDK loaded by the ADT plugin.
- */
-public abstract class SdkLoadingTestCase extends SdkTestCase {
-
- private Sdk mSdk;
-
- protected SdkLoadingTestCase() {
- }
-
- /**
- * Retrieve the {@link Sdk} under test.
- */
- protected Sdk getSdk() {
- if (mSdk == null) {
- mSdk = loadSdk();
- assertNotNull(mSdk);
- validateSdk(mSdk);
- }
- return mSdk;
- }
-
- /**
- * Gets the current SDK from ADT, waiting if necessary.
- */
- private Sdk loadSdk() {
- AdtPlugin adt = AdtPlugin.getDefault();
-
- // We'll never get an AdtPlugin object when running this with the
- // non-Eclipse jUnit test runner.
- if (adt == null) {
- return null;
- }
-
- // We'll never break out of the SDK load-wait-loop if the AdtPlugin doesn't
- // actually have a valid SDK location because it won't have started an async load:
- String sdkLocation = AdtPrefs.getPrefs().getOsSdkFolder();
- assertTrue("No valid SDK installation is set; for tests you typically need to set the"
- + " environment variable ADT_TEST_SDK_PATH to point to an SDK folder",
- sdkLocation != null && sdkLocation.length() > 0);
-
- Object sdkLock = Sdk.getLock();
- LoadStatus loadStatus = LoadStatus.LOADING;
- // wait for ADT to load the SDK on a separate thread
- // loop max of 600 times * 200 ms = 2 minutes
- final int maxWait = 600;
- for (int i=0; i < maxWait && loadStatus == LoadStatus.LOADING; i++) {
- try {
- Thread.sleep(200);
- }
- catch (InterruptedException e) {
- // ignore
- }
- synchronized (sdkLock) {
- loadStatus = adt.getSdkLoadStatus();
- }
- }
- Sdk sdk = null;
- synchronized (sdkLock) {
- assertEquals(LoadStatus.LOADED, loadStatus);
- sdk = Sdk.getCurrent();
- }
- assertNotNull(sdk);
- return sdk;
- }
-
- protected boolean validateSdk(IAndroidTarget target) {
- return true;
- }
-
- /**
- * Checks that the provided sdk contains one or more valid targets.
- * @param sdk the {@link Sdk} to validate.
- */
- private void validateSdk(Sdk sdk) {
- assertTrue("sdk has no targets", sdk.getTargets().length > 0);
- for (IAndroidTarget target : sdk.getTargets()) {
- if (!validateSdk(target)) {
- continue;
- }
- if (false) { // This takes forEVER
- IStatus status = new AndroidTargetParser(target).run(new NullProgressMonitor());
- if (status.getCode() != IStatus.OK) {
- fail("Failed to parse targets data");
- }
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/UnitTests.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/UnitTests.java
deleted file mode 100644
index 15d38715c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/UnitTests.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License"); you
- * may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.android.ide.eclipse.tests;
-
-
-import com.android.ide.eclipse.adt.AdtPlugin;
-
-import junit.framework.Test;
-import junit.framework.TestSuite;
-
-/**
- * Container TestSuite for all eclipse unit tests to be run
- *
- * Uses Eclipse OSGI to find and then run all junit.junit.framework.Tests in
- * this plugin, excluding tests in the FuncTests.FUNC_TEST_PACKAGE package
- *
- * Since it uses Eclipse OSGI, it must be run in a Eclipse plugin environment
- * i.e. from Eclipse workbench, this suite must be run using the
- * "JUnit Plug-in Test" launch configuration as opposed to as a "JUnit Test"
- *
- */
-public class UnitTests {
- private static final String TEST_PACKAGE = "com.android";
-
- public static Test suite() {
- TestSuite suite = new TestSuite();
-
- UnitTestCollector collector = new UnitTestCollector();
- // since this plugin is a fragment which runs insde adt, gather tests from AdtPlugin
- collector.addTestCases(suite, AdtPlugin.getDefault(), TEST_PACKAGE);
-
- return suite;
- }
-
- /**
- * Specialized test collector which will skip adding functional tests
- */
- private static class UnitTestCollector extends EclipseTestCollector {
- /**
- * Override parent class to exclude functional tests
- */
- @Override
- protected boolean isTestClass(Class<?> testClass) {
- return super.isTestClass(testClass) &&
- !testClass.getPackage().getName().startsWith(FuncTests.FUNC_TEST_PACKAGE);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/functests/layoutRendering/ApiDemosRenderingTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/functests/layoutRendering/ApiDemosRenderingTest.java
deleted file mode 100644
index d6b401b62..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/functests/layoutRendering/ApiDemosRenderingTest.java
+++ /dev/null
@@ -1,328 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License"); you
- * may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-
-package com.android.ide.eclipse.tests.functests.layoutRendering;
-
-import com.android.SdkConstants;
-import com.android.ide.common.rendering.LayoutLibrary;
-import com.android.ide.common.rendering.api.ActionBarCallback;
-import com.android.ide.common.rendering.api.AdapterBinding;
-import com.android.ide.common.rendering.api.HardwareConfig;
-import com.android.ide.common.rendering.api.ILayoutPullParser;
-import com.android.ide.common.rendering.api.IProjectCallback;
-import com.android.ide.common.rendering.api.RenderSession;
-import com.android.ide.common.rendering.api.ResourceReference;
-import com.android.ide.common.rendering.api.ResourceValue;
-import com.android.ide.common.rendering.api.SessionParams;
-import com.android.ide.common.rendering.api.SessionParams.RenderingMode;
-import com.android.ide.common.resources.ResourceItem;
-import com.android.ide.common.resources.ResourceRepository;
-import com.android.ide.common.resources.ResourceResolver;
-import com.android.ide.common.resources.configuration.DensityQualifier;
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.common.resources.configuration.KeyboardStateQualifier;
-import com.android.ide.common.resources.configuration.NavigationMethodQualifier;
-import com.android.ide.common.resources.configuration.NavigationStateQualifier;
-import com.android.ide.common.resources.configuration.ScreenDimensionQualifier;
-import com.android.ide.common.resources.configuration.ScreenHeightQualifier;
-import com.android.ide.common.resources.configuration.ScreenOrientationQualifier;
-import com.android.ide.common.resources.configuration.ScreenRatioQualifier;
-import com.android.ide.common.resources.configuration.ScreenSizeQualifier;
-import com.android.ide.common.resources.configuration.ScreenWidthQualifier;
-import com.android.ide.common.resources.configuration.SmallestScreenWidthQualifier;
-import com.android.ide.common.resources.configuration.TextInputMethodQualifier;
-import com.android.ide.common.resources.configuration.TouchScreenQualifier;
-import com.android.ide.common.sdk.LoadStatus;
-import com.android.ide.eclipse.adt.internal.resources.manager.ResourceManager;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidTargetData;
-import com.android.ide.eclipse.tests.SdkLoadingTestCase;
-import com.android.io.FolderWrapper;
-import com.android.resources.Density;
-import com.android.resources.Keyboard;
-import com.android.resources.KeyboardState;
-import com.android.resources.Navigation;
-import com.android.resources.NavigationState;
-import com.android.resources.ResourceType;
-import com.android.resources.ScreenOrientation;
-import com.android.resources.ScreenRatio;
-import com.android.resources.ScreenSize;
-import com.android.resources.TouchScreen;
-import com.android.sdklib.IAndroidTarget;
-import com.android.util.Pair;
-
-import org.kxml2.io.KXmlParser;
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.Map;
-
-import javax.imageio.ImageIO;
-
-public class ApiDemosRenderingTest extends SdkLoadingTestCase {
-
- /**
- * Custom parser that implements {@link ILayoutPullParser} (which itself extends
- * {@link XmlPullParser}).
- */
- private final static class TestParser extends KXmlParser implements ILayoutPullParser {
- /**
- * Since we're not going to go through the result of the rendering/layout, we can return
- * null for the View Key.
- */
- @Override
- public Object getViewCookie() {
- return null;
- }
-
- @Override
- public ILayoutPullParser getParser(String layoutName) {
- return null;
- }
- }
-
- private final static class ProjectCallBack implements IProjectCallback {
- // resource id counter.
- // We start at 0x7f000000 to avoid colliding with the framework id
- // since we have no access to the project R.java and we need to generate them automatically.
- private int mIdCounter = 0x7f000000;
-
- // in some cases, the id that getResourceValue(String type, String name) returns
- // will be sent back to get the type/name. This map stores the id/type/name we generate
- // to be able to do the reverse resolution.
- private Map<Integer, Pair<ResourceType, String>> mResourceMap =
- new HashMap<Integer, Pair<ResourceType, String>>();
-
- private boolean mCustomViewAttempt = false;
-
- @Override
- public String getNamespace() {
- // TODO: read from the ApiDemos manifest.
- return "com.example.android.apis";
- }
-
- @Override
- @SuppressWarnings("unchecked")
- public Object loadView(String name, Class[] constructorSignature, Object[] constructorArgs)
- throws ClassNotFoundException, Exception {
- mCustomViewAttempt = true;
- return null;
- }
-
- @Override
- public Integer getResourceId(ResourceType type, String name) {
- Integer result = ++mIdCounter;
- mResourceMap.put(result, Pair.of(type, name));
- return result;
- }
-
- @Override
- public Pair<ResourceType, String> resolveResourceId(int id) {
- return mResourceMap.get(id);
- }
-
- @Override
- public String resolveResourceId(int[] id) {
- return null;
- }
-
- @Override
- public ILayoutPullParser getParser(String layoutName) {
- return null;
- }
-
- @Override
- public Object getAdapterItemValue(ResourceReference adapterView, Object adapterCookie,
- ResourceReference itemRef, int fullPosition, int typePosition,
- int fullChildPosition, int typeChildPosition,
- ResourceReference viewRef, ViewAttribute viewAttribute, Object defaultValue) {
- return null;
- }
-
- @Override
- public AdapterBinding getAdapterBinding(ResourceReference adapterView,
- Object adapterCookie, Object viewObject) {
- return null;
- }
-
- @Override
- public ILayoutPullParser getParser(ResourceValue layoutResource) {
- return null;
- }
-
- @Override
- public ActionBarCallback getActionBarCallback() {
- return new ActionBarCallback();
- }
- }
-
- public void testApiDemos() throws IOException, XmlPullParserException {
- findApiDemos();
- }
-
- private void findApiDemos() throws IOException, XmlPullParserException {
- IAndroidTarget[] targets = getSdk().getTargets();
-
- for (IAndroidTarget target : targets) {
- String path = target.getPath(IAndroidTarget.SAMPLES);
- File samples = new File(path);
- if (samples.isDirectory()) {
- File[] files = samples.listFiles();
- for (File file : files) {
- if ("apidemos".equalsIgnoreCase(file.getName())) {
- testSample(target, file);
- return;
- }
- }
- }
- }
-
- fail("Failed to find ApiDemos!");
- }
-
- private void testSample(IAndroidTarget target, File sampleProject) throws IOException, XmlPullParserException {
- AndroidTargetData data = getSdk().getTargetData(target);
- if (data == null) {
- fail("No AndroidData!");
- }
-
- LayoutLibrary layoutLib = data.getLayoutLibrary();
- if (layoutLib.getStatus() != LoadStatus.LOADED) {
- fail("Fail to load the bridge: " + layoutLib.getLoadMessage());
- }
-
- FolderWrapper resFolder = new FolderWrapper(sampleProject, SdkConstants.FD_RES);
- if (resFolder.exists() == false) {
- fail("Sample project has no res folder!");
- }
-
- // look for the layout folder
- File layoutFolder = new File(resFolder, SdkConstants.FD_RES_LAYOUT);
- if (layoutFolder.isDirectory() == false) {
- fail("Sample project has no layout folder!");
- }
-
- // first load the project's target framework resource
- ResourceRepository framework = ResourceManager.getInstance().loadFrameworkResources(target);
-
- // now load the project resources
- ResourceRepository project = new ResourceRepository(resFolder, false) {
- @Override
- protected ResourceItem createResourceItem(String name) {
- return new ResourceItem(name);
- }
-
- };
-
- // Create a folder configuration that will be used for the rendering:
- FolderConfiguration config = getConfiguration();
-
- // get the configured resources
- Map<ResourceType, Map<String, ResourceValue>> configuredFramework =
- framework.getConfiguredResources(config);
- Map<ResourceType, Map<String, ResourceValue>> configuredProject =
- project.getConfiguredResources(config);
-
- boolean saveFiles = System.getenv("save_file") != null;
-
- // loop on the layouts and render them
- File[] layouts = layoutFolder.listFiles();
- for (File layout : layouts) {
- // create a parser for the layout file
- TestParser parser = new TestParser();
- parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
- parser.setInput(new FileReader(layout));
-
- System.out.println("Rendering " + layout.getName());
-
- ProjectCallBack projectCallBack = new ProjectCallBack();
-
- ResourceResolver resolver = ResourceResolver.create(
- configuredProject, configuredFramework,
- "Theme", false /*isProjectTheme*/);
-
- HardwareConfig hardwareConfig = new HardwareConfig(
- 320,
- 480,
- Density.MEDIUM,
- 160, //xdpi
- 160, // ydpi
- ScreenSize.NORMAL,
- ScreenOrientation.PORTRAIT,
- false /*software buttons */);
-
- RenderSession session = layoutLib.createSession(new SessionParams(
- parser,
- RenderingMode.NORMAL,
- null /*projectKey*/,
- hardwareConfig,
- resolver,
- projectCallBack,
- 1, // minSdkVersion
- 1, // targetSdkVersion
- null //logger
- ));
-
- if (session.getResult().isSuccess() == false) {
- if (projectCallBack.mCustomViewAttempt == false) {
- System.out.println("FAILED");
- fail(String.format("Rendering %1$s: %2$s", layout.getName(),
- session.getResult().getErrorMessage()));
- } else {
- System.out.println("Ignore custom views for now");
- }
- } else {
- if (saveFiles) {
- File tmp = File.createTempFile(layout.getName(), ".png");
- ImageIO.write(session.getImage(), "png", tmp);
- }
- System.out.println("Success!");
- }
- }
- }
-
- /**
- * Returns a config. This must be a valid config like a device would return. This is to
- * prevent issues where some resources don't exist in all cases and not in the default
- * (for instance only available in hdpi and mdpi but not in default).
- * @return
- */
- private FolderConfiguration getConfiguration() {
- FolderConfiguration config = new FolderConfiguration();
-
- // this matches an ADP1.
- config.addQualifier(new SmallestScreenWidthQualifier(320));
- config.addQualifier(new ScreenWidthQualifier(320));
- config.addQualifier(new ScreenHeightQualifier(480));
- config.addQualifier(new ScreenSizeQualifier(ScreenSize.NORMAL));
- config.addQualifier(new ScreenRatioQualifier(ScreenRatio.NOTLONG));
- config.addQualifier(new ScreenOrientationQualifier(ScreenOrientation.PORTRAIT));
- config.addQualifier(new DensityQualifier(Density.MEDIUM));
- config.addQualifier(new TouchScreenQualifier(TouchScreen.FINGER));
- config.addQualifier(new KeyboardStateQualifier(KeyboardState.HIDDEN));
- config.addQualifier(new TextInputMethodQualifier(Keyboard.QWERTY));
- config.addQualifier(new NavigationStateQualifier(NavigationState.HIDDEN));
- config.addQualifier(new NavigationMethodQualifier(Navigation.TRACKBALL));
- config.addQualifier(new ScreenDimensionQualifier(480, 320));
-
- config.updateScreenWidthAndHeight();
-
- return config;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/functests/sampleProjects/AndroidManifestWriter.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/functests/sampleProjects/AndroidManifestWriter.java
deleted file mode 100644
index 141e7e000..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/functests/sampleProjects/AndroidManifestWriter.java
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License"); you
- * may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.android.ide.eclipse.tests.functests.sampleProjects;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.internal.project.AndroidManifestHelper;
-import com.android.xml.AndroidManifest;
-
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
-import org.xml.sax.SAXException;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.transform.Result;
-import javax.xml.transform.Source;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerConfigurationException;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-
-/**
- * Helper class for modifying an AndroidManifest.
- * <p/>
- * TODO: consider merging this with AndroidManifestParser.
- */
-class AndroidManifestWriter {
-
- private static final Logger sLogger = Logger.getLogger(AndroidManifestWriter.class.getName());
-
- private final Document mDoc;
- private final String mOsManifestFilePath;
-
- private AndroidManifestWriter(Document doc, String osManifestFilePath) {
- mDoc = doc;
- mOsManifestFilePath = osManifestFilePath;
- }
-
- /**
- * Sets the minimum SDK version for this manifest
- * @param minSdkVersion - the minimim sdk version to use
- * @returns <code>true</code> on success, false otherwise
- */
- public boolean setMinSdkVersion(String minSdkVersion) {
- Element usesSdkElement = null;
- NodeList nodeList = mDoc.getElementsByTagName(AndroidManifest.NODE_USES_SDK);
- if (nodeList.getLength() > 0) {
- usesSdkElement = (Element) nodeList.item(0);
- } else {
- usesSdkElement = mDoc.createElement(AndroidManifest.NODE_USES_SDK);
- mDoc.getDocumentElement().appendChild(usesSdkElement);
- }
- Attr minSdkAttr = mDoc.createAttributeNS(SdkConstants.NS_RESOURCES,
- AndroidManifest.ATTRIBUTE_MIN_SDK_VERSION);
- String prefix = mDoc.lookupPrefix(SdkConstants.NS_RESOURCES);
- minSdkAttr.setPrefix(prefix);
- minSdkAttr.setValue(minSdkVersion);
- usesSdkElement.setAttributeNodeNS(minSdkAttr);
- return saveXmlToFile();
- }
-
- private boolean saveXmlToFile() {
- try {
- // Prepare the DOM document for writing
- Source source = new DOMSource(mDoc);
-
- // Prepare the output file
- File file = new File(mOsManifestFilePath);
- Result result = new StreamResult(file);
-
- // Write the DOM document to the file
- Transformer xformer = TransformerFactory.newInstance().newTransformer();
- xformer.transform(source, result);
- } catch (TransformerConfigurationException e) {
- sLogger.log(Level.SEVERE, "Failed to write xml file", e);
- return false;
- } catch (TransformerException e) {
- sLogger.log(Level.SEVERE, "Failed to write xml file", e);
- return false;
- }
- return true;
- }
-
- /**
- * Parses the manifest file, and collects data.
- *
- * @param osManifestFilePath The OS path of the manifest file to parse.
- * @return an {@link AndroidManifestHelper} or null if parsing failed
- */
- public static AndroidManifestWriter parse(String osManifestFilePath) {
- try {
- DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
- docFactory.setNamespaceAware(true);
- DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
- Document doc = docBuilder.parse(osManifestFilePath);
- return new AndroidManifestWriter(doc, osManifestFilePath);
- } catch (ParserConfigurationException e) {
- sLogger.log(Level.SEVERE, "Error parsing file", e);
- return null;
- } catch (SAXException e) {
- sLogger.log(Level.SEVERE, "Error parsing file", e);
- return null;
- } catch (IOException e) {
- sLogger.log(Level.SEVERE, "Error parsing file", e);
- return null;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/functests/sampleProjects/SampleProjectTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/functests/sampleProjects/SampleProjectTest.java
deleted file mode 100644
index 3fb705dfb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/src/com/android/ide/eclipse/tests/functests/sampleProjects/SampleProjectTest.java
+++ /dev/null
@@ -1,263 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License"); you
- * may not use this file except in compliance with the License. You may obtain a
- * copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
- * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
- * License for the specific language governing permissions and limitations under
- * the License.
- */
-package com.android.ide.eclipse.tests.functests.sampleProjects;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.AdtUtils;
-import com.android.ide.eclipse.adt.internal.wizards.newproject.NewProjectCreator;
-import com.android.ide.eclipse.adt.internal.wizards.newproject.NewProjectWizardState;
-import com.android.ide.eclipse.adt.internal.wizards.newproject.NewProjectWizardState.Mode;
-import com.android.ide.eclipse.tests.SdkLoadingTestCase;
-import com.android.sdklib.IAndroidTarget;
-
-import org.eclipse.core.resources.IMarker;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.resources.IResourceChangeEvent;
-import org.eclipse.core.resources.IResourceChangeListener;
-import org.eclipse.core.resources.IResourceDelta;
-import org.eclipse.core.resources.IResourceDeltaVisitor;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.jface.operation.IRunnableContext;
-import org.eclipse.jface.operation.IRunnableWithProgress;
-import org.eclipse.swt.widgets.Display;
-
-import java.io.File;
-import java.lang.reflect.InvocationTargetException;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * Test case that verifies all SDK sample projects can be imported, and built in
- * Eclipse.
- * <p/>
- * TODO: add support for deploying apps onto emulator and verifying successful
- * execution there
- *
- */
-public class SampleProjectTest extends SdkLoadingTestCase {
-
- private static final Logger sLogger = Logger.getLogger(SampleProjectTest.class.getName());
-
- /**
- * Finds all samples projects in set SDK and verify they can be built in Eclipse.
- * <p/>
- * TODO: add install and run on emulator test
- * @throws CoreException
- */
- public void testSamples() throws CoreException {
- // TODO: For reporting purposes, it would be better if a separate test success or failure
- // could be reported for each sample
- IAndroidTarget[] targets = getSdk().getTargets();
- for (IAndroidTarget target : targets) {
- doTestSamplesForTarget(target);
- }
- }
-
- private void doTestSamplesForTarget(IAndroidTarget target) throws CoreException {
- String path = target.getPath(IAndroidTarget.SAMPLES);
- File samples = new File(path);
- if (samples.isDirectory()) {
- File[] files = samples.listFiles();
- for (File file : files) {
- if (file.isDirectory()) {
- doTestSampleProject(file.getName(), file.getAbsolutePath(), target);
- }
- }
- }
- }
-
- /**
- * Tests the sample project with the given name
- *
- * @param target - SDK target of project
- * @param name - name of sample project to test
- * @param path - absolute file system path
- * @throws CoreException
- */
- private void doTestSampleProject(String name, String path, IAndroidTarget target)
- throws CoreException {
- IProject iproject = null;
- try {
- sLogger.log(Level.INFO, String.format("Testing sample %s for target %s", name,
- target.getName()));
-
- prepareProject(path, target);
-
- IRunnableContext context = new IRunnableContext() {
- @Override
- public void run(boolean fork, boolean cancelable, IRunnableWithProgress runnable)
- throws InvocationTargetException, InterruptedException {
- runnable.run(new NullProgressMonitor());
- }
- };
- NewProjectWizardState state = new NewProjectWizardState(Mode.SAMPLE);
- state.projectName = name;
- state.target = target;
- state.packageName = "com.android.samples";
- state.activityName = name;
- state.applicationName = name;
- state.chosenSample = new File(path);
- state.useDefaultLocation = false;
- state.createActivity = false;
-
- NewProjectCreator creator = new NewProjectCreator(state, context);
- creator.createAndroidProjects();
- iproject = validateProjectExists(name);
- validateNoProblems(iproject);
- }
- catch (CoreException e) {
- sLogger.log(Level.SEVERE,
- String.format("Unexpected exception when creating sample project %s " +
- "for target %s", name, target.getName()));
- throw e;
- } finally {
- if (iproject != null) {
- iproject.delete(false, true, new NullProgressMonitor());
- }
- }
- }
-
- private void prepareProject(String path, IAndroidTarget target) {
- if (target.getVersion().isPreview()) {
- // need to explicitly set preview's version in manifest for project to compile
- final String manifestPath = path + File.separatorChar +
- SdkConstants.FN_ANDROID_MANIFEST_XML;
- AndroidManifestWriter manifestWriter =
- AndroidManifestWriter.parse(manifestPath);
- assertNotNull(String.format("could not read manifest %s", manifestPath),
- manifestWriter);
- assertTrue(manifestWriter.setMinSdkVersion(target.getVersion().getApiString()));
- }
- }
-
- private IProject validateProjectExists(String name) {
- IProject iproject = getIProject(name);
- assertTrue(String.format("%s project not created", name), iproject.exists());
- assertTrue(String.format("%s project not opened", name), iproject.isOpen());
- return iproject;
- }
-
- private IProject getIProject(String name) {
- IProject iproject = ResourcesPlugin.getWorkspace().getRoot()
- .getProject(name);
- return iproject;
- }
-
- private void validateNoProblems(IProject iproject) throws CoreException {
- waitForBuild(iproject);
-
- boolean hasErrors = false;
- StringBuilder failureBuilder = new StringBuilder(String.format("%s project has errors:",
- iproject.getName()));
- IMarker[] markers = iproject.findMarkers(IMarker.PROBLEM, true, IResource.DEPTH_INFINITE);
- if (markers != null && markers.length > 0) {
- // the project has marker(s). even though they are "problem" we
- // don't know their severity. so we loop on them and figure if they
- // are warnings or errors
- for (IMarker m : markers) {
- int s = m.getAttribute(IMarker.SEVERITY, -1);
- if (s == IMarker.SEVERITY_ERROR) {
- hasErrors = true;
- failureBuilder.append("\n");
- failureBuilder.append(m.getAttribute(IMarker.MESSAGE, ""));
- }
- }
- }
- failureBuilder.append("Project location: " + AdtUtils.getAbsolutePath(iproject));
- assertFalse(failureBuilder.toString(), hasErrors);
- }
-
- /**
- * Waits for build to complete.
- *
- * @param iproject
- */
- private void waitForBuild(final IProject iproject) {
-
- final BuiltProjectDeltaVisitor deltaVisitor = new BuiltProjectDeltaVisitor(iproject);
- IResourceChangeListener newBuildListener = new IResourceChangeListener() {
-
- @Override
- public void resourceChanged(IResourceChangeEvent event) {
- try {
- event.getDelta().accept(deltaVisitor);
- }
- catch (CoreException e) {
- fail();
- }
- }
-
- };
- iproject.getWorkspace().addResourceChangeListener(newBuildListener,
- IResourceChangeEvent.POST_BUILD);
-
- // poll build listener to determine when build is done
- // loop max of 1200 times * 50 ms = 60 seconds
- final int maxWait = 1200;
- for (int i=0; i < maxWait; i++) {
- if (deltaVisitor.isProjectBuilt()) {
- return;
- }
- try {
- Thread.sleep(50);
- }
- catch (InterruptedException e) {
- // ignore
- }
- if (Display.getCurrent() != null) {
- Display.getCurrent().readAndDispatch();
- }
- }
-
- sLogger.log(Level.SEVERE, "expected build event never happened?");
- fail(String.format("Expected build event never happened for %s", iproject.getName()));
- }
-
- /**
- * Scans a given IResourceDelta looking for a "build event" change for given IProject
- *
- */
- private class BuiltProjectDeltaVisitor implements IResourceDeltaVisitor {
-
- private IProject mIProject;
- private boolean mIsBuilt;
-
- public BuiltProjectDeltaVisitor(IProject iproject) {
- mIProject = iproject;
- mIsBuilt = false;
- }
-
- @Override
- public boolean visit(IResourceDelta delta) {
- if (mIProject.equals(delta.getResource())) {
- setBuilt(true);
- return false;
- }
- return true;
- }
-
- private synchronized void setBuilt(boolean b) {
- mIsBuilt = b;
- }
-
- public synchronized boolean isProjectBuilt() {
- return mIsBuilt;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/test.xml b/eclipse/plugins/com.android.ide.eclipse.tests/test.xml
deleted file mode 100644
index e5519b002..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/test.xml
+++ /dev/null
@@ -1,76 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<!-- test launcher file for Android Eclipse tests -->
-<project name="testsuite" default="run" basedir=".">
- <!--The following properties should be passed into this script, set to some default value for now -->
- <property name="eclipse.home" value="/opt/eclipse" />
- <property name="sdk_home" value="/tmp/sdk" />
- <property name="eclipse_test" value="${eclipse.home}/plugins/org.eclipse.test_3.2.0" />
-
- <!-- eclipse scripts use an annoying mixture of eclipse-home and eclipse.home -->
- <!-- lets define both...-->
- <property name="eclipse-home" value="${eclipse.home}" />
- <property name="test-folder" value="${eclipse.home}/test_folder" />
-
- <!-- sets the properties eclipse.home, and library-file -->
- <property name="plugin-name" value="com.android.ide.eclipse.tests" />
- <property name="library-file" value="${eclipse_test}/library.xml" />
-
- <!-- location of adt preference file (within workspace) -->
- <property name="prefs_path" value="${test-folder}/.metadata/.plugins/org.eclipse.core.runtime/.settings/com.android.ide.eclipse.adt.prefs" />
- <!-- location of pref template file relative to this file -->
-
- <property name="prefs_template" value="prefs.template" />
-
- <!-- This target holds all initialization code that needs to be done for -->
- <!-- all tests that are to be run. -->
- <target name="init">
- <tstamp />
- <echo message="eclipse.home: ${eclipse.home}" />
- <echo message="libfile: ${library-file}" />
-
- <!-- delete test eclipse workspace -->
- <delete dir="${test-folder}" quiet="true" />
-
- <!-- delete test results dir -->
- <delete dir="${eclipse.home}/results" quiet="true" />
-
- <!-- Copy a preference file into the test workspace. -->
- <!-- This is done to ensure Android SDK preference is set on startup -->
- <copy file="${prefs_template}" tofile="${prefs_path}" />
- <!-- replace sdk path placeholder token with actual sdk path -->
- <replace file="${prefs_path}" token="sdk_home" value="${sdk_home}" />
-
- <!-- if this is on windows, escape the drive and file separators -->
- <replace file="${prefs_path}" token="\" value="\\" />
- <replace file="${prefs_path}" token=":" value="\:" />
- </target>
-
- <!-- This target defines the tests that need to be run. -->
- <target name="suite">
- <!-- launch as ui-test ie as a test which needs Eclipse workbench -->
- <ant target="ui-test" antfile="${library-file}" dir="${eclipse.home}">
- <property name="data-dir" value="${test-folder}" />
- <property name="plugin-name" value="${plugin-name}" />
- <property name="classname" value="com.android.ide.eclipse.tests.AllTests" />
- <!-- pass extra vm arg to set sdk_home env and test_data env variable -->
- <property name="extraVMargs" value="-Dtest_data=${test_data}" />
- </ant>
- </target>
-
- <!-- This target holds code to cleanup the testing environment after -->
- <!-- after all of the tests have been run. You can use this target to -->
- <!-- delete temporary files that have been created. -->
- <target name="cleanup">
- </target>
-
- <!-- This target runs the test suite. Any actions that need to happen -->
- <!-- after all the tests have been run should go here. -->
- <target name="run" depends="init,suite,cleanup">
- <ant target="collect" antfile="${library-file}" dir="${eclipse.home}/results">
- <property name="includes" value="com*.xml" />
- <property name="output-file" value="${plugin-name}.xml" />
- </ant>
- </target>
-</project>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittest.xml b/eclipse/plugins/com.android.ide.eclipse.tests/unittest.xml
deleted file mode 100644
index 83e00ec19..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittest.xml
+++ /dev/null
@@ -1,54 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<!-- test launcher file for Android Eclipse unit tests -->
-<project name="testsuite" default="run" basedir=".">
- <!--The following properties should be passed into this script, set to some default value for now -->
- <property name="eclipse.home" value="/opt/eclipse" />
- <property name="eclipse_test" value="${eclipse.home}/plugins/org.eclipse.test_3.2.0" />
-
- <!-- eclipse scripts use an annoying mixture of eclipse-home and eclipse.home -->
- <!-- lets define both...-->
- <property name="eclipse-home" value="${eclipse.home}" />
- <property name="test-folder" value="${eclipse.home}/unittest_ws" />
-
- <!-- sets the properties eclipse.home, and library-file -->
- <property name="plugin-name" value="com.android.ide.eclipse.tests" />
- <property name="library-file" value="${eclipse_test}/library.xml" />
-
- <!-- This target holds all initialization code that needs to be done for -->
- <!-- all tests that are to be run. -->
- <target name="init">
- <ant antfile="test.xml" target="init">
- <property name="test-folder" value="${test-folder}" />
- </ant>
- </target>
-
- <!-- This target defines the tests that need to be run. -->
- <target name="suite">
- <!-- need to launch as ui-test since all ADT plugins depend on ui-->
- <!-- otherwise other plugins will not load -->
- <ant target="ui-test" antfile="${library-file}" dir="${eclipse.home}">
- <property name="data-dir" value="${test-folder}" />
- <property name="plugin-name" value="${plugin-name}" />
- <property name="classname" value="com.android.ide.eclipse.tests.UnitTests" />
- <!-- pass extra vm arg to set test_data env variable -->
- <property name="extraVMargs" value="-Dtest_data=${test_data}" />
- </ant>
- </target>
-
- <!-- This target holds code to cleanup the testing environment after -->
- <!-- after all of the tests have been run. You can use this target to -->
- <!-- delete temporary files that have been created. -->
- <target name="cleanup">
- </target>
-
- <!-- This target runs the test suite. Any actions that need to happen -->
- <!-- after all the tests have been run should go here. -->
- <target name="run" depends="init,suite,cleanup">
- <ant target="collect" antfile="${library-file}" dir="${eclipse.home}/results">
- <property name="includes" value="com*.xml" />
- <property name="output-file" value="${plugin-name}.xml" />
- </ant>
- </target>
-</project>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/api/PointTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/api/PointTest.java
deleted file mode 100755
index 54b6ff64c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/api/PointTest.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.api;
-
-import com.android.ide.common.api.Point;
-
-import junit.framework.TestCase;
-
-public class PointTest extends TestCase {
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- public final void testPointIntInt() {
- Point p = new Point(1, 2);
- assertEquals(1, p.x);
- assertEquals(2, p.y);
-
- p = new Point(-3, -4);
- assertEquals(-3, p.x);
- assertEquals(-4, p.y);
- }
-
- public final void testSet() {
- Point p = new Point(1, 2);
- assertEquals(1, p.x);
- assertEquals(2, p.y);
-
- p.set(-3, -4);
- assertEquals(-3, p.x);
- assertEquals(-4, p.y);
- }
-
- public final void testPointPoint() {
- Point p = new Point(1, 2);
- Point p2 = new Point(p);
-
- assertNotSame(p, p2);
- assertEquals(p, p2);
- }
-
- public final void testPointPoint_Null() {
- // Constructing a point with null throws an NPE
- try {
- new Point(null);
- } catch (NullPointerException ignore) {
- return; // success
- }
-
- fail("new Point(null) failed to throew NullPointerException");
- }
-
- public final void testCopy() {
- Point p = new Point(1, 2);
- Point p2 = p.copy();
-
- assertNotSame(p, p2);
- assertEquals(p, p2);
- }
-
- public final void testOffsetBy() {
- Point p = new Point(1, 2);
- Point p2 = p.offsetBy(3, 4);
-
- assertSame(p, p2);
- assertEquals(1+3, p.x);
- assertEquals(2+4, p.y);
- }
-
- public final void testEquals_Null() {
- Point p = new Point(1, 2);
- assertFalse(p.equals(null));
- }
-
- public final void testEquals_UnknownObject() {
- Point p = new Point(1, 2);
- assertFalse(p.equals(new Object()));
- }
-
- public final void testEquals_Point() {
- Point p = new Point(1, 2);
- Point p1 = new Point(1, 2);
- Point p2 = new Point(-3, -4);
-
- assertNotSame(p1, p);
- assertTrue(p.equals(p1));
-
- assertFalse(p.equals(p2));
- }
-
- public final void testHashCode() {
- Point p = new Point(1, 2);
- Point p1 = new Point(1, 2);
- Point p2 = new Point(-3, -4);
-
- assertNotSame(p1, p);
- assertEquals(p1.hashCode(), p.hashCode());
-
- assertFalse(p2.hashCode() == p.hashCode());
- }
-
- public final void testToString() {
- Point p = new Point(1, 2);
- assertEquals("Point [1x2]", p.toString());
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/api/RectTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/api/RectTest.java
deleted file mode 100755
index 2f2c59a75..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/api/RectTest.java
+++ /dev/null
@@ -1,301 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.api;
-
-import junit.framework.TestCase;
-
-public class RectTest extends TestCase {
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- public final void testRect() {
- Rect r = new Rect();
- assertEquals(0, r.x);
- assertEquals(0, r.y);
- assertEquals(0, r.w);
- assertEquals(0, r.h);
- }
-
- public final void testRectIntIntIntInt() {
- Rect r = new Rect(1, 2, 3, 4);
- assertEquals(1, r.x);
- assertEquals(2, r.y);
- assertEquals(3, r.w);
- assertEquals(4, r.h);
- }
-
- public final void testRectRect() {
- Rect r = new Rect(1, 2, 3, 4);
- Rect r2 = new Rect(r);
-
- assertNotSame(r2, r);
- assertEquals(r2, r);
- }
-
- public final void testSetIntIntIntInt() {
- Rect r = new Rect(1, 2, 3, 4);
- Rect r2 = r.set(3, 4, 20, 30);
-
- assertSame(r2, r);
- assertEquals(3, r2.x);
- assertEquals(4, r2.y);
- assertEquals(20, r2.w);
- assertEquals(30, r2.h);
- }
-
- public final void testSetRect() {
- Rect r = new Rect(1, 2, 3, 4);
- Rect r2 = new Rect(3, 4, 20, 30);
- Rect r3 = r.set(r2);
-
- assertSame(r3, r);
- assertNotSame(r3, r2);
- assertEquals(3, r.x);
- assertEquals(4, r.y);
- assertEquals(20, r.w);
- assertEquals(30, r.h);
- }
-
- public final void testCopy() {
- Rect r = new Rect(1, 2, 3, 4);
- Rect r2 = r.copy();
-
- assertNotSame(r2, r);
- assertEquals(r2, r);
- }
-
- public final void testIsValid() {
- Rect r = new Rect();
- assertFalse(r.isValid());
-
- r = new Rect(1, 2, 3, 4);
- assertTrue(r.isValid());
-
- // Rectangles must have a width > 0 to be valid
- r = new Rect(1, 2, 0, 4);
- assertFalse(r.isValid());
- r = new Rect(1, 2, -5, 4);
- assertFalse(r.isValid());
-
- // Rectangles must have a height > 0 to be valid
- r = new Rect(1, 2, 3, 0);
- assertFalse(r.isValid());
- r = new Rect(1, 2, 3, -5);
- assertFalse(r.isValid());
-
- r = new Rect(1, 2, 0, 0);
- assertFalse(r.isValid());
- r = new Rect(1, 2, -20, -5);
- assertFalse(r.isValid());
- }
-
- public final void testContainsIntInt() {
- Rect r = new Rect(3, 4, 20, 30);
-
- assertTrue(r.contains(3, 4));
- assertTrue(r.contains(3+19, 4));
- assertTrue(r.contains(3+19, 4+29));
- assertTrue(r.contains(3, 4+29));
-
- assertFalse(r.contains(3-1, 4));
- assertFalse(r.contains(3, 4-1));
- assertFalse(r.contains(3-1, 4-1));
-
- assertFalse(r.contains(3+20, 4));
- assertFalse(r.contains(3+20, 4+30));
- assertFalse(r.contains(3, 4+30));
- }
-
- public final void testContainsIntInt_Invalid() {
- // Invalid rects always return false
- Rect r = new Rect(3, 4, -20, -30);
- assertFalse(r.contains(3, 4));
- }
-
- public final void testContainsPoint_Null() {
- // contains(null) returns false rather than an NPE
- Rect r = new Rect(3, 4, -20, -30);
- assertFalse(r.contains((Point) null));
- }
-
- public final void testContainsRect_Null() {
- // contains(null) returns false rather than an NPE
- Rect r = new Rect(3, 4, -20, -30);
- assertFalse(r.contains((Rect) null));
- }
-
- public final void testContainsPoint() {
- Rect r = new Rect(3, 4, 20, 30);
-
- assertTrue(r.contains(new Point(3, 4)));
- assertTrue(r.contains(new Point(3+19, 4)));
- assertTrue(r.contains(new Point(3+19, 4+29)));
- assertTrue(r.contains(new Point(3, 4+29)));
-
- assertFalse(r.contains(new Point(3-1, 4)));
- assertFalse(r.contains(new Point(3, 4-1)));
- assertFalse(r.contains(new Point(3-1, 4-1)));
-
- assertFalse(r.contains(new Point(3+20, 4)));
- assertFalse(r.contains(new Point(3+20, 4+30)));
- assertFalse(r.contains(new Point(3, 4+30)));
- }
-
- public final void testContainsRect() {
- Rect r = new Rect(3, 4, 20, 30);
-
- assertTrue(r.contains(new Rect(3, 4, 5, 10)));
- assertFalse(r.contains(new Rect(3 - 1, 4, 5, 10)));
- }
-
- public final void testIntersects() {
- Rect r1 = new Rect(0, 0, 10, 10);
- Rect r2 = new Rect(1, 1, 5, 5);
- Rect r3 = new Rect(10, 0, 1, 1);
- Rect r4 = new Rect(5, 5, 10, 10);
- Rect r5 = new Rect(-1, 0, 1, 1);
- Rect r6 = new Rect(0, 10, 1, 1);
-
- assertTrue(r1.intersects(r2));
- assertTrue(r2.intersects(r1));
- assertTrue(r1.intersects(r4));
- assertFalse(r1.intersects(r3));
- assertFalse(r1.intersects(r5));
- assertFalse(r1.intersects(r6));
- }
-
- public final void testMoveTo() {
- Rect r = new Rect(3, 4, 20, 30);
- Rect r2 = r.moveTo(100, 200);
-
- assertSame(r2, r);
- assertEquals(100, r.x);
- assertEquals(200, r.y);
- assertEquals(20, r.w);
- assertEquals(30, r.h);
- }
-
- public final void testOffsetBy() {
- Rect r = new Rect(3, 4, 20, 30);
- Rect r2 = r.offsetBy(100, 200);
-
- assertSame(r2, r);
- assertEquals(103, r.x);
- assertEquals(204, r.y);
- assertEquals(20, r.w);
- assertEquals(30, r.h);
- }
-
- public final void testGetCenter() {
- Rect r = new Rect(3, 4, 20, 30);
- Point p = r.getCenter();
-
- assertEquals(3+20/2, p.x);
- assertEquals(4+30/2, p.y);
- }
-
- public final void testGetTopLeft() {
- Rect r = new Rect(3, 4, 20, 30);
- Point p = r.getTopLeft();
-
- assertEquals(3, p.x);
- assertEquals(4, p.y);
- }
-
- public final void testGetBottomLeft() {
- Rect r = new Rect(3, 4, 20, 30);
- Point p = r.getBottomLeft();
-
- assertEquals(3, p.x);
- assertEquals(4+30, p.y);
- }
-
- public final void testGetTopRight() {
- Rect r = new Rect(3, 4, 20, 30);
- Point p = r.getTopRight();
-
- assertEquals(3+20, p.x);
- assertEquals(4, p.y);
- }
-
- public final void testGetBottomRight() {
- Rect r = new Rect(3, 4, 20, 30);
- Point p = r.getBottomRight();
-
- assertEquals(3+20, p.x);
- assertEquals(4+30, p.y);
- }
-
- public final void testToString() {
- Rect r = new Rect(3, 4, 20, 30);
-
- assertEquals("Rect [(3,4)-(23,34): 20x30]", r.toString());
- }
-
- public final void testEqualsObject() {
- Rect r = new Rect(3, 4, 20, 30);
-
- assertFalse(r.equals(null));
- assertFalse(r.equals(new Object()));
- assertTrue(r.equals(new Rect(3, 4, 20, 30)));
- }
-
- public final void testEqualsObject_Invalid() {
- Rect r = new Rect(3, 4, 20, 30);
- assertTrue(r.isValid());
-
- Rect i1 = new Rect(3, 4, 0, 0);
- assertFalse(i1.isValid());
- Rect i2 = new Rect(10, 20, 0, 0);
- assertFalse(i2.isValid());
-
- // valid rects can't be equal to invalid rects
- assertFalse(r.equals(i1));
- assertFalse(r.equals(i2));
-
- // invalid rects are equal to each other whatever their content is
- assertEquals(i2, i1);
- }
-
- public final void testHashCode() {
- Rect r = new Rect(1, 2, 3, 4);
- Rect r1 = new Rect(3, 4, 20, 30);
- Rect r2 = new Rect(3, 4, 20, 30);
-
- assertFalse(r1.hashCode() == r.hashCode());
- assertEquals(r2.hashCode(), r1.hashCode());
- }
-
-
- public final void testCenter() {
- Rect r = new Rect(10, 20, 30, 40);
- Point center = r.center();
- assertEquals(25, center.x);
- assertEquals(40, center.y);
- assertEquals(25, r.centerX());
- assertEquals(40, r.centerY());
- }
-
- public final void testX2Y2() {
- Rect r = new Rect(1, 2, 3, 4);
- assertEquals(4, r.x2());
- assertEquals(6, r.y2());
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/AbsoluteLayoutRuleTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/AbsoluteLayoutRuleTest.java
deleted file mode 100644
index 1a14bdda4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/AbsoluteLayoutRuleTest.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.Point;
-import com.android.ide.common.api.Rect;
-
-/** Test the {@link AbsoluteLayoutRule} */
-public class AbsoluteLayoutRuleTest extends LayoutTestBase {
- // Utility for other tests
- protected INode dragInto(Rect dragBounds, Point dragPoint, int insertIndex, int currentIndex,
- String... graphicsFragments) {
- INode layout = TestNode.create("android.widget.AbsoluteLayout").id("@+id/AbsoluteLayout01")
- .bounds(new Rect(0, 0, 240, 480)).add(
- TestNode.create("android.widget.Button").id("@+id/Button01").bounds(
- new Rect(0, 0, 100, 80)),
- TestNode.create("android.widget.Button").id("@+id/Button02").bounds(
- new Rect(0, 100, 100, 80)),
- TestNode.create("android.widget.Button").id("@+id/Button03").bounds(
- new Rect(0, 200, 100, 80)),
- TestNode.create("android.widget.Button").id("@+id/Button04").bounds(
- new Rect(0, 300, 100, 80)));
-
- return super.dragInto(new AbsoluteLayoutRule(), layout, dragBounds, dragPoint, null,
- insertIndex, currentIndex, graphicsFragments);
- }
-
- public void testDragMiddle() {
- INode inserted = dragInto(
- // Bounds of the dragged item
- new Rect(0, 0, 105, 80),
- // Drag point
- new Point(30, -10),
- // Expected insert location: We just append in absolute layout
- 4,
- // Not dragging one of the existing children
- -1,
-
-
- // Bounds rectangle
- "useStyle(DROP_RECIPIENT), drawRect(Rect[0,0,240,480])",
-
- // Drop preview
- "useStyle(DROP_PREVIEW), drawRect(30,-10,135,70)");
-
- assertEquals("30dp", inserted.getStringAttr(ANDROID_URI, "layout_x"));
- assertEquals("-10dp", inserted.getStringAttr(ANDROID_URI, "layout_y"));
-
- // Without drag bounds we should just draw guide lines instead
- inserted = dragInto(new Rect(0, 0, 0, 0), new Point(30, -10), 4, -1,
- "useStyle(DROP_RECIPIENT), drawRect(Rect[0,0,240,480])",
- // Guideline
- "useStyle(GUIDELINE), drawLine(30,0,30,480), drawLine(0,-10,240,-10)",
- // Drop preview
- "useStyle(DROP_PREVIEW), drawLine(30,-10,240,-10), drawLine(30,-10,30,480)");
- assertEquals("30dp", inserted.getStringAttr(ANDROID_URI, "layout_x"));
- assertEquals("-10dp", inserted.getStringAttr(ANDROID_URI, "layout_y"));
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/BaseLayoutRuleTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/BaseLayoutRuleTest.java
deleted file mode 100644
index d176fe7d1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/BaseLayoutRuleTest.java
+++ /dev/null
@@ -1,245 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_ID;
-
-import com.android.ide.common.api.IDragElement;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.layout.BaseLayoutRule.AttributeFilter;
-import com.android.utils.Pair;
-
-import java.util.Arrays;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-// TODO: Check assertions
-// TODO: Check equals() but not == strings by using new String("") to prevent interning
-// TODO: Rename BaseLayout to BaseLayoutRule, and tests too of course
-
-public class BaseLayoutRuleTest extends LayoutTestBase {
-
- /** Provides test data used by other test cases */
- private IDragElement[] createSampleElements() {
- IDragElement[] elements = TestDragElement.create(TestDragElement.create(
- "android.widget.Button", new Rect(0, 0, 100, 80)).id("@+id/Button01"),
- TestDragElement.create("android.widget.LinearLayout", new Rect(0, 80, 100, 280))
- .id("@+id/LinearLayout01").add(
- TestDragElement.create("android.widget.Button",
- new Rect(0, 80, 100, 80)).id("@+id/Button011"),
- TestDragElement.create("android.widget.Button",
- new Rect(0, 180, 100, 80)).id("@+id/Button012")),
- TestDragElement.create("android.widget.Button", new Rect(100, 0, 100, 80)).id(
- "@+id/Button02"));
- return elements;
- }
-
- /** Test {@link BaseLayoutRule#collectIds}: Check that basic lookup of id works */
- public final void testCollectIds1() {
- IDragElement[] elements = TestDragElement.create(TestDragElement.create(
- "android.widget.Button", new Rect(0, 0, 100, 80)).id("@+id/Button01"));
- Map<String, Pair<String, String>> idMap = new HashMap<String, Pair<String, String>>();
- Map<String, Pair<String, String>> ids = new BaseLayoutRule().collectIds(idMap, elements);
- assertEquals(1, ids.size());
- assertEquals("@+id/Button01", ids.keySet().iterator().next());
- }
-
- /**
- * Test {@link BaseLayoutRule#collectIds}: Check that with the wrong URI we
- * don't pick up the ID
- */
- public final void testCollectIds2() {
- IDragElement[] elements = TestDragElement.create(TestDragElement.create(
- "android.widget.Button", new Rect(0, 0, 100, 80)).set("myuri", ATTR_ID,
- "@+id/Button01"));
-
- Map<String, Pair<String, String>> idMap = new HashMap<String, Pair<String, String>>();
- Map<String, Pair<String, String>> ids = new BaseLayoutRule().collectIds(idMap, elements);
- assertEquals(0, ids.size());
- }
-
- /**
- * Test {@link BaseLayoutRule#normalizeId(String)}
- */
- public final void testNormalizeId() {
- assertEquals("foo", new BaseLayoutRule().normalizeId("foo"));
- assertEquals("@+id/name", new BaseLayoutRule().normalizeId("@id/name"));
- assertEquals("@+id/name", new BaseLayoutRule().normalizeId("@+id/name"));
- }
-
- /**
- * Test {@link BaseLayoutRule#collectExistingIds}
- */
- public final void testCollectExistingIds1() {
- Set<String> existing = new HashSet<String>();
- INode node = TestNode.create("android.widget.Button").id("@+id/Button012").add(
- TestNode.create("android.widget.Button").id("@+id/Button2"));
-
- new BaseLayoutRule().collectExistingIds(node, existing);
-
- assertEquals(2, existing.size());
- assertContainsSame(Arrays.asList("@+id/Button2", "@+id/Button012"), existing);
- }
-
- /**
- * Test {@link BaseLayoutRule#collectIds}: Check that with multiple elements and
- * some children we still pick up all the right id's
- */
- public final void testCollectIds3() {
- Map<String, Pair<String, String>> idMap = new HashMap<String, Pair<String, String>>();
-
- IDragElement[] elements = createSampleElements();
- Map<String, Pair<String, String>> ids = new BaseLayoutRule().collectIds(idMap, elements);
- assertEquals(5, ids.size());
- assertContainsSame(Arrays.asList("@+id/Button01", "@+id/Button02", "@+id/Button011",
- "@+id/Button012", "@+id/LinearLayout01"), ids.keySet());
-
- // Make sure the Pair has the right stuff too;
- // (having the id again in the pair seems redundant; see if I really
- // need it in the implementation)
- assertEquals(Pair.of("@+id/LinearLayout01", "android.widget.LinearLayout"), ids
- .get("@+id/LinearLayout01"));
- }
-
- /**
- * Test {@link BaseLayoutRule#remapIds}: Ensure that it identifies a conflict
- */
- public final void testRemapIds1() {
- Map<String, Pair<String, String>> idMap = new HashMap<String, Pair<String, String>>();
- BaseLayoutRule baseLayout = new BaseLayoutRule();
- IDragElement[] elements = createSampleElements();
- baseLayout.collectIds(idMap, elements);
- INode node = TestNode.create("android.widget.Button").id("@+id/Button012").add(
- TestNode.create("android.widget.Button").id("@+id/Button2"));
-
- assertEquals(5, idMap.size());
- Map<String, Pair<String, String>> remapped = baseLayout.remapIds(node, idMap);
- // 4 original from the sample elements, plus overlap with one
- // (Button012) - one new
- // button added in
- assertEquals(6, remapped.size());
-
- // TODO: I'm a little confused about what exactly this method should do;
- // check with Raphael.
- }
-
-
- /**
- * Test {@link BaseLayoutRule#getDropIdMap}
- */
- public final void testGetDropIdMap() {
- BaseLayoutRule baseLayout = new BaseLayoutRule();
- IDragElement[] elements = createSampleElements();
- INode node = TestNode.create("android.widget.Button").id("@+id/Button012").add(
- TestNode.create("android.widget.Button").id("@+id/Button2"));
-
- Map<String, Pair<String, String>> idMap = baseLayout.getDropIdMap(node, elements, true);
- assertContainsSame(Arrays.asList("@+id/Button01", "@+id/Button012", "@+id/Button011",
- "@id/Button012", "@+id/Button02", "@+id/LinearLayout01"), idMap
- .keySet());
-
- // TODO: I'm a little confused about what exactly this method should do;
- // check with Raphael.
- }
-
- public final void testAddAttributes1() {
- BaseLayoutRule layout = new BaseLayoutRule();
-
- // First try with no filter
- IDragElement oldElement = TestDragElement.create("a.w.B").id("@+id/foo");
- INode newNode = TestNode.create("a.w.B").id("@+id/foo").set("u", "key", "value").set("u",
- "nothidden", "nothiddenvalue");
- ;
- AttributeFilter filter = null;
- // No references in this test case
- Map<String, Pair<String, String>> idMap = null;
-
- layout.addAttributes(newNode, oldElement, idMap, filter);
- assertEquals("value", newNode.getStringAttr("u", "key"));
- assertEquals("nothiddenvalue", newNode.getStringAttr("u", "nothidden"));
- }
-
- public final void testAddAttributes2() {
- // Test filtering
- BaseLayoutRule layout = new BaseLayoutRule();
-
- // First try with no filter
- IDragElement oldElement = TestDragElement.create("a.w.B").id("@+id/foo");
- INode newNode = TestNode.create("a.w.B").id("@+id/foo").set("u", "key", "value").set("u",
- "hidden", "hiddenvalue");
- AttributeFilter filter = new AttributeFilter() {
-
- @Override
- public String replace(String attributeUri, String attributeName,
- String attributeValue) {
- if (attributeName.equals("hidden")) {
- return null;
- }
-
- return attributeValue;
- }
- };
- // No references in this test case
- Map<String, Pair<String, String>> idMap = null;
-
- layout.addAttributes(newNode, oldElement, idMap, filter);
- assertEquals("value", newNode.getStringAttr("u", "key"));
- }
-
- public final void testFindNewId() {
- BaseLayoutRule baseLayout = new BaseLayoutRule();
- Set<String> existing = new HashSet<String>();
- assertEquals("@+id/Widget01", baseLayout.findNewId("a.w.Widget", existing));
-
- existing.add("@+id/Widget01");
- assertEquals("@+id/Widget02", baseLayout.findNewId("a.w.Widget", existing));
-
- existing.add("@+id/Widget02");
- assertEquals("@+id/Widget03", baseLayout.findNewId("a.w.Widget", existing));
-
- existing.remove("@+id/Widget02");
- assertEquals("@+id/Widget02", baseLayout.findNewId("a.w.Widget", existing));
- }
-
- public final void testDefaultAttributeFilter() {
- assertEquals("true", BaseLayoutRule.DEFAULT_ATTR_FILTER.replace("myuri", "layout_alignRight",
- "true"));
- assertEquals(null, BaseLayoutRule.DEFAULT_ATTR_FILTER.replace(ANDROID_URI,
- "layout_alignRight", "true"));
- assertEquals("true", BaseLayoutRule.DEFAULT_ATTR_FILTER.replace(ANDROID_URI,
- "myproperty", "true"));
- }
-
- public final void testAddInnerElements() {
- IDragElement oldElement = TestDragElement.create("root").add(
- TestDragElement.create("a.w.B").id("@+id/child1")
- .set("uri", "childprop1", "value1"),
- TestDragElement.create("a.w.B").id("@+id/child2").set("uri", "childprop2a",
- "value2a").set("uri", "childprop2b", "value2b"));
- INode newNode = TestNode.create("a.w.B").id("@+id/foo");
- Map<String, Pair<String, String>> idMap = new HashMap<String, Pair<String, String>>();
- BaseLayoutRule layout = new BaseLayoutRule();
- layout.addInnerElements(newNode, oldElement, idMap);
- assertEquals(2, newNode.getChildren().length);
-
- assertEquals("value2b", newNode.getChildren()[1].getStringAttr("uri", "childprop2b"));
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/BaseViewRuleTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/BaseViewRuleTest.java
deleted file mode 100644
index 6d46b1efc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/BaseViewRuleTest.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import java.util.Arrays;
-import java.util.Collections;
-
-import junit.framework.TestCase;
-
-public class BaseViewRuleTest extends TestCase {
-
- public final void testGetAttributeDisplayName() {
- assertEquals(null, BaseViewRule.getAttributeDisplayName(null));
- assertEquals("", BaseViewRule.getAttributeDisplayName(""));
- assertEquals("Foo", BaseViewRule.getAttributeDisplayName("foo"));
- assertEquals("FooBar", BaseViewRule.getAttributeDisplayName("fooBar"));
- assertEquals("Foo Bar", BaseViewRule.getAttributeDisplayName("foo_bar"));
- // TBD: Should we also handle CamelCase properties?
- // assertEquals("Foo Bar", BaseViewRule.getAttributeDisplayName("fooBar"));
- }
-
- public final void testJoin() {
- assertEquals("foo", BaseViewRule.join('|', Arrays.asList("foo")));
- assertEquals("", BaseViewRule.join('|', Collections.<String>emptyList()));
- assertEquals("foo,bar", BaseViewRule.join(',', Arrays.asList("foo", "bar")));
- assertEquals("foo|bar", BaseViewRule.join('|', Arrays.asList("foo", "bar")));
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/FrameLayoutRuleTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/FrameLayoutRuleTest.java
deleted file mode 100644
index 4a60566d9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/FrameLayoutRuleTest.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.Point;
-import com.android.ide.common.api.Rect;
-
-/** Test the {@link FrameLayoutRule} */
-public class FrameLayoutRuleTest extends LayoutTestBase {
- // Utility for other tests
- protected void dragInto(Rect dragBounds, Point dragPoint, int insertIndex, int currentIndex,
- String... graphicsFragments) {
- INode layout = TestNode.create("android.widget.FrameLayout").id("@+id/FrameLayout01")
- .bounds(new Rect(0, 0, 240, 480)).add(
- TestNode.create("android.widget.Button").id("@+id/Button01").bounds(
- new Rect(0, 0, 100, 80)),
- TestNode.create("android.widget.Button").id("@+id/Button02").bounds(
- new Rect(0, 100, 100, 80)),
- TestNode.create("android.widget.Button").id("@+id/Button03").bounds(
- new Rect(0, 200, 100, 80)),
- TestNode.create("android.widget.Button").id("@+id/Button04").bounds(
- new Rect(0, 300, 100, 80)));
-
- super.dragInto(new FrameLayoutRule(), layout, dragBounds, dragPoint, null,
- insertIndex, currentIndex, graphicsFragments);
- }
-
- public void testDragMiddle() {
- dragInto(
- // Bounds of the dragged item
- new Rect(0, 0, 105, 80),
- // Drag point
- new Point(30, -10),
- // Expected insert location: We just append in absolute layout
- 4,
- // Not dragging one of the existing children
- -1,
- // Bounds rectangle
- "useStyle(DROP_RECIPIENT), drawRect(Rect[0,0,240,480])",
-
- // Drop Preview
- "useStyle(DROP_PREVIEW), drawRect(0,0,105,80)");
- // Without drag bounds we should just draw guide lines instead
- dragInto(new Rect(0, 0, 0, 0), new Point(30, -10), 4, -1,
- "useStyle(DROP_RECIPIENT), drawRect(Rect[0,0,240,480])",
- "useStyle(DROP_PREVIEW), drawLine(1,0,1,480), drawLine(0,1,240,1)");
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/GravityHelperTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/GravityHelperTest.java
deleted file mode 100644
index 8161babbe..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/GravityHelperTest.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout;
-
-import static com.android.ide.common.layout.GravityHelper.GRAVITY_BOTTOM;
-import static com.android.ide.common.layout.GravityHelper.GRAVITY_CENTER_HORIZ;
-import static com.android.ide.common.layout.GravityHelper.GRAVITY_CENTER_VERT;
-import static com.android.ide.common.layout.GravityHelper.GRAVITY_END;
-import static com.android.ide.common.layout.GravityHelper.GRAVITY_FILL_HORIZ;
-import static com.android.ide.common.layout.GravityHelper.GRAVITY_FILL_VERT;
-import static com.android.ide.common.layout.GravityHelper.GRAVITY_LEFT;
-import static com.android.ide.common.layout.GravityHelper.GRAVITY_RIGHT;
-import static com.android.ide.common.layout.GravityHelper.GRAVITY_START;
-import static com.android.ide.common.layout.GravityHelper.GRAVITY_TOP;
-import static com.android.ide.common.layout.GravityHelper.getGravity;
-
-import com.android.utils.XmlUtils;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class GravityHelperTest extends TestCase {
- public void testGravity() throws Exception {
- assertEquals(GRAVITY_BOTTOM, GravityHelper.getGravity("bottom", 0));
- assertEquals(GRAVITY_BOTTOM | GRAVITY_LEFT, GravityHelper.getGravity("bottom|left", 0));
- assertEquals(GRAVITY_BOTTOM | GRAVITY_LEFT | GRAVITY_START,
- GravityHelper.getGravity("bottom|left|start", 0));
- assertEquals(GRAVITY_BOTTOM | GRAVITY_LEFT | GRAVITY_START,
- GravityHelper.getGravity("bottom|start|left", 0));
- assertEquals(GRAVITY_BOTTOM | GRAVITY_RIGHT | GRAVITY_END,
- GravityHelper.getGravity("bottom|right|end", 0));
- assertEquals(GRAVITY_BOTTOM | GRAVITY_RIGHT | GRAVITY_END,
- GravityHelper.getGravity("bottom|end|right", 0));
- assertEquals(GRAVITY_CENTER_HORIZ | GRAVITY_CENTER_VERT,
- GravityHelper.getGravity("center", 0));
- }
-
- public void testGravityString() throws Exception {
- assertEquals("left", getGravity(GRAVITY_LEFT));
- assertEquals("start", getGravity(GRAVITY_START));
- assertEquals("right", getGravity(GRAVITY_RIGHT));
- assertEquals("end", getGravity(GRAVITY_END));
- assertEquals("top", getGravity(GRAVITY_TOP));
- assertEquals("bottom", getGravity(GRAVITY_BOTTOM));
- assertEquals("center_horizontal", getGravity(GRAVITY_CENTER_HORIZ));
- assertEquals("center_vertical", getGravity(GRAVITY_CENTER_VERT));
- assertEquals("fill_horizontal", getGravity(GRAVITY_FILL_HORIZ));
- assertEquals("fill_vertical", getGravity(GRAVITY_FILL_VERT));
-
- assertEquals("center", getGravity(GRAVITY_CENTER_HORIZ|GRAVITY_CENTER_VERT));
-
- assertEquals("left|bottom", getGravity(GRAVITY_LEFT|GRAVITY_BOTTOM));
- assertEquals("left|start|bottom", getGravity(GRAVITY_LEFT|GRAVITY_START|GRAVITY_BOTTOM));
- assertEquals("center_horizontal|top", getGravity(GRAVITY_CENTER_HORIZ|GRAVITY_TOP));
- }
-
- public void testConstrained() throws Exception {
- assertTrue(GravityHelper.isConstrainedHorizontally(GRAVITY_LEFT));
- assertTrue(GravityHelper.isConstrainedHorizontally(GRAVITY_START));
- assertTrue(GravityHelper.isConstrainedHorizontally(GRAVITY_RIGHT));
- assertTrue(GravityHelper.isConstrainedHorizontally(GRAVITY_END));
- assertTrue(GravityHelper.isConstrainedHorizontally(GRAVITY_CENTER_HORIZ));
- assertTrue(GravityHelper.isConstrainedHorizontally(GRAVITY_FILL_HORIZ));
-
- assertFalse(GravityHelper.isConstrainedVertically(GRAVITY_LEFT));
- assertFalse(GravityHelper.isConstrainedVertically(GRAVITY_START));
- assertFalse(GravityHelper.isConstrainedVertically(GRAVITY_RIGHT));
- assertFalse(GravityHelper.isConstrainedVertically(GRAVITY_END));
- assertFalse(GravityHelper.isConstrainedVertically(GRAVITY_CENTER_HORIZ));
- assertFalse(GravityHelper.isConstrainedVertically(GRAVITY_FILL_HORIZ));
-
- assertTrue(GravityHelper.isConstrainedVertically(GRAVITY_TOP));
- assertTrue(GravityHelper.isConstrainedVertically(GRAVITY_BOTTOM));
- assertTrue(GravityHelper.isConstrainedVertically(GRAVITY_CENTER_VERT));
- assertTrue(GravityHelper.isConstrainedVertically(GRAVITY_FILL_VERT));
-
- assertFalse(GravityHelper.isConstrainedHorizontally(GRAVITY_TOP));
- assertFalse(GravityHelper.isConstrainedHorizontally(GRAVITY_BOTTOM));
- assertFalse(GravityHelper.isConstrainedHorizontally(GRAVITY_CENTER_VERT));
- assertFalse(GravityHelper.isConstrainedHorizontally(GRAVITY_FILL_VERT));
- }
-
- public void testAligned() throws Exception {
- assertTrue(GravityHelper.isLeftAligned(GRAVITY_LEFT|GRAVITY_TOP));
- assertTrue(GravityHelper.isLeftAligned(GRAVITY_START|GRAVITY_TOP));
- assertTrue(GravityHelper.isLeftAligned(GRAVITY_LEFT));
- assertTrue(GravityHelper.isLeftAligned(GRAVITY_START));
- assertFalse(GravityHelper.isLeftAligned(GRAVITY_RIGHT));
- assertFalse(GravityHelper.isLeftAligned(GRAVITY_END));
-
- assertTrue(GravityHelper.isTopAligned(GRAVITY_LEFT|GRAVITY_TOP));
- assertTrue(GravityHelper.isTopAligned(GRAVITY_START|GRAVITY_TOP));
- assertTrue(GravityHelper.isTopAligned(GRAVITY_TOP));
- assertFalse(GravityHelper.isTopAligned(GRAVITY_BOTTOM));
- }
-
- public void testElement() throws Exception {
- Document document = XmlUtils.parseDocumentSilently(""
- + "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
- + "<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n"
- + " android:layout_width=\"match_parent\"\n"
- + " android:layout_height=\"wrap_content\"\n"
- + " android:layout_gravity=\"start|center_vertical|left\""
- + " android:orientation=\"vertical\" />\n", true);
- assertNotNull(document);
- Element element = document.getDocumentElement();
- assertNotNull(element);
- int gravity = GravityHelper.getGravity(element);
- assertEquals("left|start|center_vertical", GravityHelper.getGravity(gravity));
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/GridLayoutRuleTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/GridLayoutRuleTest.java
deleted file mode 100644
index f0483655d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/GridLayoutRuleTest.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout;
-
-
-public class GridLayoutRuleTest extends LayoutTestBase {
- @Override
- public void testDummy() {
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/LayoutTestBase.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/LayoutTestBase.java
deleted file mode 100644
index 4b4bb814a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/LayoutTestBase.java
+++ /dev/null
@@ -1,375 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_ID;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.DropFeedback;
-import com.android.ide.common.api.IClientRulesEngine;
-import com.android.ide.common.api.IDragElement;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IValidator;
-import com.android.ide.common.api.IViewMetadata;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.Margins;
-import com.android.ide.common.api.Point;
-import com.android.ide.common.api.Rect;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.ViewMetadataRepository;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Map;
-
-import junit.framework.TestCase;
-
-/**
- * Common layout helpers from LayoutRule tests
- */
-@SuppressWarnings("javadoc")
-public class LayoutTestBase extends TestCase {
- /**
- * Helper function used by tests to drag a button into a canvas containing
- * the given children.
- *
- * @param rule The rule to test on
- * @param targetNode The target layout node to drag into
- * @param dragBounds The (original) bounds of the dragged item
- * @param dropPoint The drag point we should drag to and drop
- * @param secondDropPoint An optional second drag point to drag to before
- * drawing graphics and dropping (or null if not applicable)
- * @param insertIndex The expected insert position we end up with after
- * dropping at the dropPoint
- * @param currentIndex If the dragged widget is already in the canvas this
- * should be its child index; if not, pass in -1
- * @param graphicsFragments This is a varargs array of String fragments
- * we expect to see in the graphics output on the drag over
- * event.
- * @return The inserted node
- */
- protected INode dragInto(IViewRule rule, INode targetNode, Rect dragBounds, Point dropPoint,
- Point secondDropPoint, int insertIndex, int currentIndex,
- String... graphicsFragments) {
-
- String draggedButtonId = (currentIndex == -1) ? "@+id/DraggedButton" : targetNode
- .getChildren()[currentIndex].getStringAttr(ANDROID_URI, ATTR_ID);
-
- IDragElement[] elements = TestDragElement.create(TestDragElement.create(
- "android.widget.Button", dragBounds).id(draggedButtonId));
-
- // Enter target
- DropFeedback feedback = rule.onDropEnter(targetNode, null/*targetView*/, elements);
- assertNotNull(feedback);
- assertFalse(feedback.invalidTarget);
- assertNotNull(feedback.painter);
-
- if (currentIndex != -1) {
- feedback.sameCanvas = true;
- }
-
- // Move near top left corner of the target
- feedback = rule.onDropMove(targetNode, elements, feedback, dropPoint);
- assertNotNull(feedback);
-
- if (secondDropPoint != null) {
- feedback = rule.onDropMove(targetNode, elements, feedback, secondDropPoint);
- assertNotNull(feedback);
- }
-
- if (insertIndex == -1) {
- assertTrue(feedback.invalidTarget);
- } else {
- assertFalse(feedback.invalidTarget);
- }
-
- // Paint feedback and make sure it's what we expect
- TestGraphics graphics = new TestGraphics();
- assertNotNull(feedback.painter);
- feedback.painter.paint(graphics, targetNode, feedback);
- String drawn = graphics.getDrawn().toString();
-
- // Check that each graphics fragment is drawn
- for (String fragment : graphicsFragments) {
- if (!drawn.contains(fragment)) {
- // Get drawn-output since unit test truncates message in below
- // contains-assertion
- System.out.println("Could not find: " + fragment);
- System.out.println("Full graphics output: " + drawn);
- }
- assertTrue(fragment + " not found; full=" + drawn, drawn.contains(fragment));
- }
-
- // Attempt a drop?
- if (insertIndex == -1) {
- // No, not expected to succeed (for example, when drop point is over an
- // invalid region in RelativeLayout) - just return.
- return null;
- }
- int childrenCountBefore = targetNode.getChildren().length;
- rule.onDropped(targetNode, elements, feedback, dropPoint);
-
- if (currentIndex == -1) {
- // Inserting new from outside
- assertEquals(childrenCountBefore+1, targetNode.getChildren().length);
- } else {
- // Moving from existing; must remove in old position first
- ((TestNode) targetNode).removeChild(currentIndex);
-
- assertEquals(childrenCountBefore, targetNode.getChildren().length);
- }
- // Ensure that it's inserted in the right place
- String actualId = targetNode.getChildren()[insertIndex].getStringAttr(
- ANDROID_URI, ATTR_ID);
- if (!draggedButtonId.equals(actualId)) {
- // Using assertEquals instead of fail to get nice diff view on test
- // failure
- List<String> childrenIds = new ArrayList<String>();
- for (INode child : targetNode.getChildren()) {
- childrenIds.add(child.getStringAttr(ANDROID_URI, ATTR_ID));
- }
- int index = childrenIds.indexOf(draggedButtonId);
- String message = "Button found at index " + index + " instead of " + insertIndex
- + " among " + childrenIds;
- System.out.println(message);
- assertEquals(message, draggedButtonId, actualId);
- }
-
-
- return targetNode.getChildren()[insertIndex];
- }
-
- /**
- * Utility method for asserting that two collections contain exactly the
- * same elements (regardless of order)
- * @param expected expected collection
- * @param actual actual collection
- */
- public static void assertContainsSame(Collection<String> expected, Collection<String> actual) {
- if (expected.size() != actual.size()) {
- fail("Collection sizes differ; expected " + expected.size() + " but was "
- + actual.size());
- }
-
- // Sort prior to comparison to ensure we have the same elements
- // regardless of order
- List<String> expectedList = new ArrayList<String>(expected);
- Collections.sort(expectedList);
- List<String> actualList = new ArrayList<String>(actual);
- Collections.sort(actualList);
- // Instead of just assertEquals(expectedList, actualList);
- // we iterate one element at a time so we can show the first
- // -difference-.
- for (int i = 0; i < expectedList.size(); i++) {
- String expectedElement = expectedList.get(i);
- String actualElement = actualList.get(i);
- if (!expectedElement.equals(actualElement)) {
- System.out.println("Expected items: " + expectedList);
- System.out.println("Actual items : " + actualList);
- }
- assertEquals("Collections differ; first difference:", expectedElement, actualElement);
- }
- }
-
- protected void initialize(IViewRule rule, String fqn) {
- rule.onInitialize(fqn, new TestRulesEngine(fqn));
- }
-
- public static class TestRulesEngine implements IClientRulesEngine {
- private final String mFqn;
-
- public TestRulesEngine(String fqn) {
- mFqn = fqn;
- }
-
- @Override
- public void debugPrintf(@NonNull String msg, Object... params) {
- fail("Not supported in tests yet");
- }
-
- @Override
- public void displayAlert(@NonNull String message) {
- fail("Not supported in tests yet");
- }
-
- @Override
- public String displayInput(@NonNull String message, @Nullable String value,
- @Nullable IValidator filter) {
- fail("Not supported in tests yet");
- return null;
- }
-
- @Override
- public @NonNull String getFqcn() {
- return mFqn;
- }
-
- @Override
- public @NonNull IViewMetadata getMetadata(final @NonNull String fqcn) {
- return new IViewMetadata() {
- @Override
- public @NonNull String getDisplayName() {
- // This also works when there is no "."
- return fqcn.substring(fqcn.lastIndexOf('.') + 1);
- }
-
- @Override
- public @NonNull FillPreference getFillPreference() {
- return ViewMetadataRepository.get().getFillPreference(fqcn);
- }
-
- @Override
- public @NonNull Margins getInsets() {
- return null;
- }
-
- @Override
- public @NonNull List<String> getTopAttributes() {
- return ViewMetadataRepository.get().getTopAttributes(fqcn);
- }
- };
- }
-
- @Override
- public int getMinApiLevel() {
- return 8;
- }
-
- @Override
- public IViewRule loadRule(@NonNull String fqcn) {
- fail("Not supported in tests yet");
- return null;
- }
-
- @Override
- public String displayReferenceInput(String currentValue) {
- fail("Not supported in tests yet");
- return null;
- }
-
- @Override
- public IValidator getResourceValidator(String resourceTypeName, boolean uniqueInProject,
- boolean uniqueInLayout, boolean exists, String... allowed) {
- fail("Not supported in tests yet");
- return null;
- }
-
- @Override
- public String displayResourceInput(@NonNull String resourceTypeName,
- @Nullable String currentValue) {
- fail("Not supported in tests yet");
- return null;
- }
-
- @Override
- public String[] displayMarginInput(@Nullable String all, @Nullable String left,
- @Nullable String right, @Nullable String top, @Nullable String bottom) {
- fail("Not supported in tests yet");
- return null;
- }
-
- @Override
- public String displayIncludeSourceInput() {
- fail("Not supported in tests yet");
- return null;
- }
-
- @Override
- public void select(@NonNull Collection<INode> nodes) {
- fail("Not supported in tests yet");
- }
-
- @Override
- public String displayFragmentSourceInput() {
- fail("Not supported in tests yet");
- return null;
- }
-
- @Override
- public void layout() {
- fail("Not supported in tests yet");
- }
-
- @Override
- public void redraw() {
- fail("Not supported in tests yet");
- }
-
- @Override
- public Map<INode, Rect> measureChildren(@NonNull INode parent,
- @Nullable AttributeFilter filter) {
- return null;
- }
-
- @Override
- public int pxToDp(int px) {
- // Arbitrary conversion
- return px / 3;
- }
-
- @Override
- public int dpToPx(int dp) {
- // Arbitrary conversion
- return 3 * dp;
- }
-
- @Override
- public @NonNull String getUniqueId(@NonNull String prefix) {
- fail("Not supported in tests yet");
- return null;
- }
-
- @Override
- public int screenToLayout(int pixels) {
- fail("Not supported in tests yet");
- return pixels;
- }
-
- @Override
- public @NonNull String getAppNameSpace() {
- fail("Not supported in tests yet");
- return null;
- }
-
- @Override
- public @Nullable Object getViewObject(@NonNull INode node) {
- fail("Not supported in tests yet");
- return null;
- }
-
- @Override
- public boolean rename(INode node) {
- fail("Not supported in tests yet");
- return false;
- }
-
- @Override
- @Nullable
- public String displayCustomViewClassInput() {
- fail("Not supported in tests yet");
- return null;
- }
- }
-
- public void testDummy() {
- // To avoid JUnit warning that this class contains no tests, even though
- // this is an abstract class and JUnit shouldn't try
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/LinearLayoutRuleTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/LinearLayoutRuleTest.java
deleted file mode 100644
index 9c4c934c0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/LinearLayoutRuleTest.java
+++ /dev/null
@@ -1,466 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ATTR_LAYOUT_HEIGHT;
-import static com.android.SdkConstants.ATTR_LAYOUT_WIDTH;
-import static com.android.SdkConstants.ATTR_ORIENTATION;
-import static com.android.SdkConstants.VALUE_HORIZONTAL;
-import static com.android.SdkConstants.VALUE_VERTICAL;
-
-import com.android.ide.common.api.DropFeedback;
-import com.android.ide.common.api.IAttributeInfo.Format;
-import com.android.ide.common.api.IDragElement;
-import com.android.ide.common.api.IMenuCallback;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.IViewRule;
-import com.android.ide.common.api.Point;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.api.RuleAction;
-import com.android.ide.common.api.RuleAction.NestedAction;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-/** Test the {@link LinearLayoutRule} */
-public class LinearLayoutRuleTest extends LayoutTestBase {
- // Utility for other tests
- protected void dragIntoEmpty(Rect dragBounds) {
- boolean haveBounds = dragBounds.isValid();
-
- IViewRule rule = new LinearLayoutRule();
-
- INode targetNode = TestNode.create("android.widget.LinearLayout").id(
- "@+id/LinearLayout01").bounds(new Rect(0, 0, 240, 480));
- Point dropPoint = new Point(10, 5);
-
- IDragElement[] elements = TestDragElement.create(TestDragElement.create(
- "android.widget.Button", dragBounds).id("@+id/Button01"));
-
- // Enter target
- DropFeedback feedback = rule.onDropEnter(targetNode, null/*targetView*/, elements);
- assertNotNull(feedback);
- assertFalse(feedback.invalidTarget);
- assertNotNull(feedback.painter);
-
- feedback = rule.onDropMove(targetNode, elements, feedback, dropPoint);
- assertNotNull(feedback);
- assertFalse(feedback.invalidTarget);
-
- // Paint feedback and make sure it's what we expect
- TestGraphics graphics = new TestGraphics();
- assertNotNull(feedback.painter);
- feedback.painter.paint(graphics, targetNode, feedback);
- assertEquals(
- // Expect to see a recipient rectangle around the bounds of the
- // LinearLayout,
- // as well as a single vertical line as a drop preview located
- // along the left
- // edge (for this horizontal linear layout) showing insert
- // position at index 0,
- // and finally a rectangle for the bounds of the inserted button
- // centered over
- // the middle
- "[useStyle(DROP_RECIPIENT), "
- +
- // Bounds rectangle
- "drawRect(Rect[0,0,240,480]), "
- + "useStyle(DROP_ZONE), drawLine(1,0,1,480), "
- + "useStyle(DROP_ZONE_ACTIVE), " + "useStyle(DROP_PREVIEW), " +
- // Insert position line
- "drawLine(1,0,1,480)" + (haveBounds ?
- // Outline of dragged node centered over position line
- ", useStyle(DROP_PREVIEW), " + "drawRect(1,0,101,80)"
- // Nothing when we don't have bounds
- : "") + "]", graphics.getDrawn().toString());
-
- // Attempt a drop
- assertEquals(0, targetNode.getChildren().length);
- rule.onDropped(targetNode, elements, feedback, dropPoint);
- assertEquals(1, targetNode.getChildren().length);
- assertEquals("@+id/Button01", targetNode.getChildren()[0].getStringAttr(
- ANDROID_URI, ATTR_ID));
- }
-
- // Utility for other tests
- protected INode dragInto(boolean vertical, Rect dragBounds, Point dragPoint,
- int insertIndex, int currentIndex,
- String... graphicsFragments) {
- INode linearLayout = TestNode.create("android.widget.LinearLayout").id(
- "@+id/LinearLayout01").bounds(new Rect(0, 0, 240, 480)).set(ANDROID_URI,
- ATTR_ORIENTATION,
- vertical ? VALUE_VERTICAL : VALUE_HORIZONTAL)
- .add(
- TestNode.create("android.widget.Button").id("@+id/Button01").bounds(
- new Rect(0, 0, 100, 80)),
- TestNode.create("android.widget.Button").id("@+id/Button02").bounds(
- new Rect(0, 100, 100, 80)),
- TestNode.create("android.widget.Button").id("@+id/Button03").bounds(
- new Rect(0, 200, 100, 80)),
- TestNode.create("android.widget.Button").id("@+id/Button04").bounds(
- new Rect(0, 300, 100, 80)));
-
- return super.dragInto(new LinearLayoutRule(), linearLayout, dragBounds, dragPoint, null,
- insertIndex, currentIndex, graphicsFragments);
- }
-
- // Check that the context menu registers the expected menu items
- public void testContextMenu() {
- LinearLayoutRule rule = new LinearLayoutRule();
- initialize(rule, "android.widget.LinearLayout");
- INode node = TestNode.create("android.widget.Button").id("@+id/Button012");
-
- List<RuleAction> contextMenu = new ArrayList<RuleAction>();
- rule.addContextMenuActions(contextMenu, node);
- assertEquals(6, contextMenu.size());
- assertEquals("Edit ID...", contextMenu.get(0).getTitle());
- assertTrue(contextMenu.get(1) instanceof RuleAction.Separator);
- assertEquals("Layout Width", contextMenu.get(2).getTitle());
- assertEquals("Layout Height", contextMenu.get(3).getTitle());
- assertTrue(contextMenu.get(4) instanceof RuleAction.Separator);
- assertEquals("Other Properties", contextMenu.get(5).getTitle());
-
- RuleAction propertiesMenu = contextMenu.get(5);
- assertTrue(propertiesMenu.getClass().getName(),
- propertiesMenu instanceof NestedAction);
- }
-
- public void testContextMenuCustom() {
- LinearLayoutRule rule = new LinearLayoutRule();
- initialize(rule, "android.widget.LinearLayout");
- INode node = TestNode.create("android.widget.LinearLayout").id("@+id/LinearLayout")
- .set(ANDROID_URI, ATTR_LAYOUT_WIDTH, "42dip")
- .set(ANDROID_URI, ATTR_LAYOUT_HEIGHT, "50sp");
-
- List<RuleAction> contextMenu = new ArrayList<RuleAction>();
- rule.addContextMenuActions(contextMenu, node);
- assertEquals(6, contextMenu.size());
- assertEquals("Layout Width", contextMenu.get(2).getTitle());
- RuleAction menuAction = contextMenu.get(2);
- assertTrue(menuAction instanceof RuleAction.Choices);
- RuleAction.Choices choices = (RuleAction.Choices) menuAction;
- List<String> titles = choices.getTitles();
- List<String> ids = choices.getIds();
- assertEquals("Wrap Content", titles.get(0));
- assertEquals("wrap_content", ids.get(0));
- assertEquals("Match Parent", titles.get(1));
- assertEquals("match_parent", ids.get(1));
- assertEquals("42dip", titles.get(2));
- assertEquals("42dip", ids.get(2));
- assertEquals("42dip", choices.getCurrent());
- }
-
- // Check that the context menu manipulates the orientation attribute
- public void testOrientation() {
- LinearLayoutRule rule = new LinearLayoutRule();
- initialize(rule, "android.widget.LinearLayout");
- TestNode node = TestNode.create("android.widget.LinearLayout").id("@+id/LinearLayout012");
- node.putAttributeInfo(ANDROID_URI, "orientation",
- new TestAttributeInfo(ATTR_ORIENTATION, Format.ENUM_SET,
- "android.widget.LinearLayout",
- new String[] {"horizontal", "vertical"}, null, null));
-
- assertNull(node.getStringAttr(ANDROID_URI, ATTR_ORIENTATION));
-
- List<RuleAction> contextMenu = new ArrayList<RuleAction>();
- rule.addContextMenuActions(contextMenu, node);
- assertEquals(7, contextMenu.size());
- RuleAction orientationAction = contextMenu.get(1);
- assertEquals("Orientation", orientationAction.getTitle());
-
- assertTrue(orientationAction.getClass().getName(),
- orientationAction instanceof RuleAction.Choices);
-
- RuleAction.Choices choices = (RuleAction.Choices) orientationAction;
- IMenuCallback callback = choices.getCallback();
- callback.action(orientationAction, Collections.singletonList(node), VALUE_VERTICAL, true);
-
- String orientation = node.getStringAttr(ANDROID_URI,
- ATTR_ORIENTATION);
- assertEquals(VALUE_VERTICAL, orientation);
- callback.action(orientationAction, Collections.singletonList(node), VALUE_HORIZONTAL,
- true);
- orientation = node.getStringAttr(ANDROID_URI, ATTR_ORIENTATION);
- assertEquals(VALUE_HORIZONTAL, orientation);
- }
-
- // Check that the context menu manipulates the orientation attribute
- public void testProperties() {
- LinearLayoutRule rule = new LinearLayoutRule();
- initialize(rule, "android.widget.LinearLayout");
- TestNode node = TestNode.create("android.widget.LinearLayout").id("@+id/LinearLayout012");
- node.putAttributeInfo(ANDROID_URI, "orientation",
- new TestAttributeInfo(ATTR_ORIENTATION, Format.ENUM_SET,
- "android.widget.LinearLayout",
- new String[] {"horizontal", "vertical"}, null, null));
- node.setAttributeSources(Arrays.asList("android.widget.LinearLayout",
- "android.view.ViewGroup", "android.view.View"));
- node.putAttributeInfo(ANDROID_URI, "gravity",
- new TestAttributeInfo("gravity", Format.INTEGER_SET,
- "android.widget.LinearLayout", null, null, null));
-
-
- assertNull(node.getStringAttr(ANDROID_URI, ATTR_ORIENTATION));
-
- List<RuleAction> contextMenu = new ArrayList<RuleAction>();
- rule.addContextMenuActions(contextMenu, node);
- assertEquals(8, contextMenu.size());
-
- assertEquals("Orientation", contextMenu.get(1).getTitle());
- assertEquals("Edit Gravity...", contextMenu.get(2).getTitle());
-
- assertEquals("Other Properties", contextMenu.get(7).getTitle());
-
- RuleAction propertiesMenu = contextMenu.get(7);
- assertTrue(propertiesMenu.getClass().getName(),
- propertiesMenu instanceof NestedAction);
- NestedAction nested = (NestedAction) propertiesMenu;
- List<RuleAction> nestedActions = nested.getNestedActions(node);
- assertEquals(9, nestedActions.size());
- assertEquals("Recent", nestedActions.get(0).getTitle());
- assertTrue(nestedActions.get(1) instanceof RuleAction.Separator);
- assertEquals("Defined by LinearLayout", nestedActions.get(2).getTitle());
- assertEquals("Inherited from ViewGroup", nestedActions.get(3).getTitle());
- assertEquals("Inherited from View", nestedActions.get(4).getTitle());
- assertTrue(nestedActions.get(5) instanceof RuleAction.Separator);
- assertEquals("Layout Parameters", nestedActions.get(6).getTitle());
- assertTrue(nestedActions.get(7) instanceof RuleAction.Separator);
- assertEquals("All By Name", nestedActions.get(8).getTitle());
-
- BaseViewRule.editedProperty(ATTR_ORIENTATION);
-
- RuleAction recentAction = nestedActions.get(0);
- assertTrue(recentAction instanceof NestedAction);
- NestedAction recentChoices = (NestedAction) recentAction;
- List<RuleAction> recentItems = recentChoices.getNestedActions(node);
-
- assertEquals(1, recentItems.size());
- assertEquals("Orientation", recentItems.get(0).getTitle());
-
- BaseViewRule.editedProperty("gravity");
- recentItems = recentChoices.getNestedActions(node);
- assertEquals(2, recentItems.size());
- assertEquals("Gravity...", recentItems.get(0).getTitle());
- assertEquals("Orientation", recentItems.get(1).getTitle());
-
- BaseViewRule.editedProperty(ATTR_ORIENTATION);
- recentItems = recentChoices.getNestedActions(node);
- assertEquals(2, recentItems.size());
- assertEquals("Orientation", recentItems.get(0).getTitle());
- assertEquals("Gravity...", recentItems.get(1).getTitle());
-
- // Lots of other properties -- flushes out properties that apply to this view
- for (int i = 0; i < 30; i++) {
- BaseViewRule.editedProperty("dummy_" + i);
- }
- recentItems = recentChoices.getNestedActions(node);
- assertEquals(0, recentItems.size());
-
- BaseViewRule.editedProperty("gravity");
- recentItems = recentChoices.getNestedActions(node);
- assertEquals(1, recentItems.size());
- assertEquals("Gravity...", recentItems.get(0).getTitle());
- }
-
- public void testDragInEmptyWithBounds() {
- dragIntoEmpty(new Rect(0, 0, 100, 80));
- }
-
- public void testDragInEmptyWithoutBounds() {
- dragIntoEmpty(new Rect(0, 0, 0, 0));
- }
-
- public void testDragInVerticalTop() {
- dragInto(true,
- // Bounds of the dragged item
- new Rect(0, 0, 105, 80),
- // Drag point
- new Point(30, -10),
- // Expected insert location
- 0,
- // Not dragging one of the existing children
- -1,
- // Bounds rectangle
- "useStyle(DROP_RECIPIENT), drawRect(Rect[0,0,240,480])",
-
- // Drop zones
- "useStyle(DROP_ZONE), drawLine(0,0,240,0), drawLine(0,90,240,90), "
- + "drawLine(0,190,240,190), drawLine(0,290,240,290), "
- + "drawLine(0,381,240,381)",
-
- // Active nearest line
- "useStyle(DROP_ZONE_ACTIVE), useStyle(DROP_PREVIEW), drawLine(0,0,240,0)",
-
- // Preview of the dropped rectangle
- "useStyle(DROP_PREVIEW), drawRect(0,-40,105,40)");
-
- // Without drag bounds it should be identical except no preview
- // rectangle
- dragInto(true,
- new Rect(0, 0, 0, 0), // Invalid
- new Point(30, -10), 0, -1,
- "useStyle(DROP_ZONE_ACTIVE), useStyle(DROP_PREVIEW), drawLine(0,0,240,0)");
- }
-
- public void testDragInVerticalBottom() {
- dragInto(true,
- // Bounds of the dragged item
- new Rect(0, 0, 105, 80),
- // Drag point
- new Point(30, 500),
- // Expected insert location
- 4,
- // Not dragging one of the existing children
- -1,
- // Bounds rectangle
- "useStyle(DROP_RECIPIENT), drawRect(Rect[0,0,240,480])",
-
- // Drop zones
- "useStyle(DROP_ZONE), drawLine(0,0,240,0), drawLine(0,90,240,90), "
- + "drawLine(0,190,240,190), drawLine(0,290,240,290), drawLine(0,381,240,381), ",
-
- // Active nearest line
- "useStyle(DROP_ZONE_ACTIVE), useStyle(DROP_PREVIEW), drawLine(0,381,240,381)",
-
- // Preview of the dropped rectangle
- "useStyle(DROP_PREVIEW), drawRect(0,381,105,461)");
-
- // Check without bounds too
- dragInto(true, new Rect(0, 0, 105, 80), new Point(30, 500), 4, -1,
- "useStyle(DROP_PREVIEW), drawRect(0,381,105,461)");
- }
-
- public void testDragInVerticalMiddle() {
- dragInto(true,
- // Bounds of the dragged item
- new Rect(0, 0, 105, 80),
- // Drag point
- new Point(0, 170),
- // Expected insert location
- 2,
- // Not dragging one of the existing children
- -1,
- // Bounds rectangle
- "useStyle(DROP_RECIPIENT), drawRect(Rect[0,0,240,480])",
-
- // Drop zones
- "useStyle(DROP_ZONE), drawLine(0,0,240,0), drawLine(0,90,240,90), "
- + "drawLine(0,190,240,190), drawLine(0,290,240,290)",
-
- // Active nearest line
- "useStyle(DROP_ZONE_ACTIVE), useStyle(DROP_PREVIEW), drawLine(0,190,240,190)",
-
- // Preview of the dropped rectangle
- "useStyle(DROP_PREVIEW), drawRect(0,150,105,230)");
-
- // Check without bounds too
- dragInto(true, new Rect(0, 0, 105, 80), new Point(0, 170), 2, -1,
- "useStyle(DROP_PREVIEW), drawRect(0,150,105,230)");
- }
-
- public void testDragInVerticalMiddleSelfPos() {
- // Drag the 2nd button, down to the position between 3rd and 4th
- dragInto(true,
- // Bounds of the dragged item
- new Rect(0, 100, 100, 80),
- // Drag point
- new Point(0, 250),
- // Expected insert location
- 2,
- // Dragging 1st item
- 1,
- // Bounds rectangle
-
- "useStyle(DROP_RECIPIENT), drawRect(Rect[0,0,240,480])",
-
- // Drop zones - these are different because we exclude drop
- // zones around the
- // dragged item itself (it doesn't make sense to insert directly
- // before or after
- // myself
- "useStyle(DROP_ZONE), drawLine(0,0,240,0), drawLine(0,290,240,290), "
- + "drawLine(0,381,240,381)",
-
- // Preview line along insert axis
- "useStyle(DROP_ZONE_ACTIVE), useStyle(DROP_PREVIEW), drawLine(0,290,240,290)",
-
- // Preview of dropped rectangle
- "useStyle(DROP_PREVIEW), drawRect(0,250,100,330)");
-
- // Test dropping on self (no position change):
- dragInto(true,
- // Bounds of the dragged item
- new Rect(0, 100, 100, 80),
- // Drag point
- new Point(0, 210),
- // Expected insert location
- 1,
- // Dragging from same pos
- 1,
- // Bounds rectangle
- "useStyle(DROP_RECIPIENT), drawRect(Rect[0,0,240,480])",
-
- // Drop zones - these are different because we exclude drop
- // zones around the
- // dragged item itself (it doesn't make sense to insert directly
- // before or after
- // myself
- "useStyle(DROP_ZONE), drawLine(0,0,240,0), drawLine(0,290,240,290), "
- + "drawLine(0,381,240,381)",
-
- // No active nearest line when you're over the self pos!
-
- // Preview of the dropped rectangle
- "useStyle(DROP_ZONE_ACTIVE), useStyle(DROP_PREVIEW), drawRect(0,100,100,180)");
- }
-
- public void testDragToLastPosition() {
- // Drag a button to the last position -- and confirm that the preview rectangle
- // is now shown midway between the second to last and last positions, but fully
- // below the drop zone line:
- dragInto(true,
- // Bounds of the dragged item
- new Rect(0, 100, 100, 80),
- // Drag point
- new Point(0, 400),
- // Expected insert location
- 3,
- // Dragging 1st item
- 1,
-
- // Bounds rectangle
- "useStyle(DROP_RECIPIENT), drawRect(Rect[0,0,240,480])",
-
- // Drop Zones
- "useStyle(DROP_ZONE), drawLine(0,0,240,0), drawLine(0,290,240,290), " +
- "drawLine(0,381,240,381), ",
-
- // Active Drop Zone
- "useStyle(DROP_ZONE_ACTIVE), useStyle(DROP_PREVIEW), drawLine(0,381,240,381)",
-
- // Drop Preview
- "useStyle(DROP_PREVIEW), drawRect(0,381,100,461)");
- }
-
- // Left to test:
- // Check inserting at last pos with multiple children
- // Check inserting with no bounds rectangle for dragged element
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/RelativeLayoutRuleTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/RelativeLayoutRuleTest.java
deleted file mode 100644
index f9747f39d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/RelativeLayoutRuleTest.java
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-
-import static com.android.SdkConstants.ANDROID_URI;
-
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.Point;
-import com.android.ide.common.api.Rect;
-
-/** Test the {@link RelativeLayoutRule} */
-public class RelativeLayoutRuleTest extends LayoutTestBase {
- // Utility for other tests
- protected INode dragInto(Rect dragBounds, Point dragPoint, Point secondDragPoint,
- int insertIndex, int currentIndex, String... graphicsFragments) {
- INode layout = TestNode.create("android.widget.RelativeLayout").id("@+id/RelativeLayout01")
- .bounds(new Rect(0, 0, 240, 480)).add(
- // Add centered button as the anchor
- TestNode.create("android.widget.Button").id("@+id/Centered").bounds(
- new Rect(70, 200, 100, 80)).set(ANDROID_URI,
- "layout_centerInParent", "true"),
- // Add a second button anchored to it
- TestNode.create("android.widget.Button").id("@+id/Below").bounds(
- new Rect(70, 280, 100, 80)).set(ANDROID_URI, "layout_below",
- "@+id/Centered").set(ANDROID_URI, "layout_alignLeft",
- "@+id/Centered"));
-
- return super.dragInto(new RelativeLayoutRule(), layout, dragBounds, dragPoint,
- secondDragPoint, insertIndex, currentIndex, graphicsFragments);
- }
-
- protected INode dragInto(Rect dragBounds, Point dragPoint, Point secondDragPoint,
- int insertIndex, int currentIndex, String[] extraFragments,
- String... graphicsFragments) {
-
- // When we switch to JDK6, use Arrays#copyOf instead
- String[] combined = new String[extraFragments.length + graphicsFragments.length];
- System.arraycopy(graphicsFragments, 0, combined, 0, graphicsFragments.length);
- System.arraycopy(extraFragments, 0, combined, graphicsFragments.length,
- extraFragments.length);
-
- return dragInto(dragBounds, dragPoint, secondDragPoint, insertIndex,
- currentIndex, combined);
- }
-
- /* This needs to be updated for the new interaction
- public void testDropTopEdge() {
- // If we drag right into the button itself, not a valid drop position
- INode inserted = dragInto(
- new Rect(0, 0, 105, 80), new Point(30, -10), null, 2, -1,
- // Bounds rectangle
- "useStyle(DROP_RECIPIENT), drawRect(Rect[0,0,240,480])",
-
- // Preview line + drop zone rectangle along the top
- "useStyle(DROP_ZONE), drawRect(Rect[0,-10,240,20])",
- "useStyle(DROP_ZONE_ACTIVE), fillRect(Rect[0,-10,240,20])",
- "useStyle(DROP_PREVIEW), drawLine(0,0,240,0)",
-
- // Tip
- "useStyle(HELP), drawBoxedStrings(5,15,[alignParentTop])",
-
- // Drop preview
- "useStyle(DROP_PREVIEW), drawRect(Rect[0,0,105,80])");
-
- assertEquals("true", inserted.getStringAttr(ANDROID_URI,
- "layout_alignParentTop"));
- }
-
- public void testDropZones() {
- List<Pair<Point,String[]>> zones = new ArrayList<Pair<Point,String[]>>();
-
- zones.add(Pair.of(new Point(51+10, 181+10),
- new String[] {"above=@+id/Centered", "toLeftOf=@+id/Centered"}));
- zones.add(Pair.of(new Point(71+10, 181+10),
- new String[] {"above=@+id/Centered", "alignLeft=@+id/Centered"}));
- zones.add(Pair.of(new Point(104+10, 181+10),
- new String[] {"above=@+id/Centered", "alignRight=@+id/Centered"}));
- zones.add(Pair.of(new Point(137+10, 181+10),
- new String[] {"above=@+id/Centered", "alignRight=@+id/Centered"}));
- zones.add(Pair.of(new Point(170+10, 181+10),
- new String[] {"above=@+id/Centered", "toRightOf=@+id/Centered"}));
- zones.add(Pair.of(new Point(51+10, 279+10),
- new String[] {"below=@+id/Centered", "toLeftOf=@+id/Centered"}));
- zones.add(Pair.of(new Point(71+10, 279+10),
- new String[] {"below=@+id/Centered", "alignLeft=@+id/Centered"}));
- zones.add(Pair.of(new Point(104+10, 279+10),
- new String[] {"below=@+id/Centered", "alignLeft=@+id/Centered"}));
- zones.add(Pair.of(new Point(137+10, 279+10),
- new String[] {"below=@+id/Centered", "alignRight=@+id/Centered"}));
- zones.add(Pair.of(new Point(170+10, 279+10),
- new String[] {"below=@+id/Centered", "toRightOf=@+id/Centered"}));
- zones.add(Pair.of(new Point(51+10, 201+10),
- new String[] {"toLeftOf=@+id/Centered", "alignTop=@+id/Centered"}));
- zones.add(Pair.of(new Point(51+10, 227+10),
- new String[] {"toLeftOf=@+id/Centered", "alignTop=@+id/Centered"}));
- zones.add(Pair.of(new Point(170+10, 201+10),
- new String[] {"toRightOf=@+id/Centered", "alignTop=@+id/Centered"}));
- zones.add(Pair.of(new Point(51+10, 253+10),
- new String[] {"toLeftOf=@+id/Centered", "alignBottom=@+id/Centered"}));
- zones.add(Pair.of(new Point(170+10, 227+10),
- new String[] {"toRightOf=@+id/Centered", "alignTop=@+id/Centered",
- "alignBottom=@+id/Centered"}));
- zones.add(Pair.of(new Point(170+10, 253+10),
- new String[] {"toRightOf=@+id/Centered", "alignBottom=@+id/Centered"}));
-
- for (Pair<Point,String[]> zonePair : zones) {
- Point dropPoint = zonePair.getFirst();
- String[] attachments = zonePair.getSecond();
- // If we drag right into the button itself, not a valid drop position
-
- INode inserted = dragInto(
- new Rect(0, 0, 105, 80), new Point(120, 240), dropPoint, 1, -1,
- attachments,
-
- // Bounds rectangle
- "useStyle(DROP_RECIPIENT), drawRect(Rect[0,0,240,480])",
-
- // Drop zones
- "useStyle(DROP_ZONE), "
- + "drawRect(Rect[51,181,20,20]), drawRect(Rect[71,181,33,20]), "
- + "drawRect(Rect[104,181,33,20]), drawRect(Rect[137,181,33,20]), "
- + "drawRect(Rect[170,181,20,20]), drawRect(Rect[51,279,20,20]), "
- + "drawRect(Rect[71,279,33,20]), drawRect(Rect[104,279,33,20]), "
- + "drawRect(Rect[137,279,33,20]), drawRect(Rect[170,279,20,20]), "
- + "drawRect(Rect[51,201,20,26]), drawRect(Rect[51,227,20,26]), "
- + "drawRect(Rect[51,253,20,26]), drawRect(Rect[170,201,20,26]), "
- + "drawRect(Rect[170,227,20,26]), drawRect(Rect[170,253,20,26])");
-
- for (String attachment : attachments) {
- String[] elements = attachment.split("=");
- String name = "layout_" + elements[0];
- String value = elements[1];
- assertEquals(value, inserted.getStringAttr(ANDROID_URI, name));
- }
- }
- }
-
-
- public void testDragInvalid() {
- // If we drag right into the button itself, not a valid drop position
- dragInto(new Rect(70, 200, 100, 80), new Point(120, 240), new Point(120, 240), -1, 0,
- // Bounds rectangle
- "useStyle(DROP_RECIPIENT), drawRect(Rect[0,0,240,480])",
-
- // Invalid marker
- "useStyle(INVALID), fillRect(Rect[70,200,100,80]), drawLine(70,200,170,280), "
- + "drawLine(70,280,170,200)");
- }
-
- // TODO: Test error (dragging on ancestor)
- */
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/TestAttribute.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/TestAttribute.java
deleted file mode 100644
index 752d61c77..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/TestAttribute.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.IDragElement.IDragAttribute;
-import com.android.ide.common.api.INode.IAttribute;
-import com.android.ide.common.xml.XmlAttributeSortOrder;
-
-/** Test/mock implementation of {@link IAttribute} and {@link IDragAttribute} */
-public class TestAttribute implements IAttribute, IDragAttribute {
- private String mUri;
-
- private String mName;
-
- private String mValue;
-
- public TestAttribute(String mUri, String mName, String mValue) {
- super();
- this.mName = mName;
- this.mUri = mUri;
- this.mValue = mValue;
- }
-
- @Override
- public @NonNull String getName() {
- return mName;
- }
-
- @Override
- public @NonNull String getUri() {
- return mUri;
- }
-
- @Override
- public @NonNull String getValue() {
- return mValue;
- }
-
- @Override
- public String toString() {
- return "TestAttribute [name=" + mName + ", uri=" + mUri + ", value=" + mValue + "]";
- }
-
- public int compareTo(IDragAttribute o) {
- return XmlAttributeSortOrder.compareAttributes(mName, o.getName());
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/TestAttributeInfo.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/TestAttributeInfo.java
deleted file mode 100644
index 69984bdbf..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/TestAttributeInfo.java
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.IAttributeInfo;
-
-import java.util.EnumSet;
-
-/** Test/mock implementation of {@link IAttributeInfo} */
-public class TestAttributeInfo implements IAttributeInfo {
- private final String mName;
- private final EnumSet<Format> mFormats;
- private final String mDefinedBy;
- private final String[] mEnumValues;
- private final String[] mFlagValues;
- private final String mJavadoc;
-
- public TestAttributeInfo(String name) {
- this(name, null, null, null, null, null);
- }
-
- public TestAttributeInfo(String name, EnumSet<Format> formats, String definedBy,
- String[] enumValues, String[] flagValues, String javadoc) {
- super();
- this.mName = name;
- this.mFormats = formats;
- this.mDefinedBy = definedBy;
- this.mEnumValues = enumValues;
- this.mFlagValues = flagValues;
- this.mJavadoc = javadoc;
- }
-
- @Override
- public String getDeprecatedDoc() {
- return null;
- }
-
- @Override
- public String[] getEnumValues() {
- return mEnumValues;
- }
-
- @Override
- public String[] getFlagValues() {
- return mFlagValues;
- }
-
- @Override
- public @NonNull EnumSet<Format> getFormats() {
- return mFormats;
- }
-
- @Override
- public @NonNull String getJavaDoc() {
- return mJavadoc;
- }
-
- @Override
- public @NonNull String getName() {
- return mName;
- }
-
- @Override
- public @NonNull String getDefinedBy() {
- return mDefinedBy;
- }
-} \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/TestColor.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/TestColor.java
deleted file mode 100644
index 449ad5ebb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/TestColor.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import com.android.ide.common.api.IColor;
-
-public class TestColor implements IColor {
- private int mRgb;
-
- public TestColor(int rgb) {
- this.mRgb = rgb;
- }
-
- public int getRgb() {
- return mRgb;
- }
-
- @Override
- public String toString() {
- return String.format("#%6x", mRgb);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/TestDragElement.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/TestDragElement.java
deleted file mode 100644
index b96de60c7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/TestDragElement.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_ID;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.IDragElement;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.Rect;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-/** Test/mock implementation of {@link IDragElement} */
-public class TestDragElement implements IDragElement {
- private Rect mRect;
-
- private final String mFqcn;
-
- private Map<String, TestAttribute> mAttributes = new HashMap<String, TestAttribute>();
-
- private List<TestDragElement> mChildren = new ArrayList<TestDragElement>();
-
- private TestDragElement mParent;
-
- public TestDragElement(String mFqcn, Rect mRect, List<TestDragElement> mChildren,
- TestDragElement mParent) {
- super();
- this.mRect = mRect;
- this.mFqcn = mFqcn;
- this.mChildren = mChildren;
- this.mParent = mParent;
- }
-
- public TestDragElement(String fqn) {
- this(fqn, null, null, null);
- }
-
- public TestDragElement setBounds(Rect bounds) {
- this.mRect = bounds;
-
- return this;
- }
-
- // Builder stuff
- public TestDragElement set(String uri, String name, String value) {
- if (mAttributes == null) {
- mAttributes = new HashMap<String, TestAttribute>();
- }
-
- mAttributes.put(uri + name, new TestAttribute(uri, name, value));
-
- return this;
- }
-
- public TestDragElement add(TestDragElement... children) {
- if (mChildren == null) {
- mChildren = new ArrayList<TestDragElement>();
- }
-
- for (TestDragElement child : children) {
- mChildren.add(child);
- child.mParent = this;
- }
-
- return this;
- }
-
- public TestDragElement id(String id) {
- return set(ANDROID_URI, ATTR_ID, id);
- }
-
- public static TestDragElement create(String fqn, Rect bounds) {
- return create(fqn).setBounds(bounds);
- }
-
- public static TestDragElement create(String fqn) {
- return new TestDragElement(fqn);
- }
-
- public static IDragElement[] create(TestDragElement... elements) {
- return elements;
- }
-
- // ==== IDragElement ====
-
- @Override
- public IDragAttribute getAttribute(@Nullable String uri, @NonNull String localName) {
- if (mAttributes == null) {
- return new TestAttribute(uri, localName, "");
- }
-
- return mAttributes.get(uri + localName);
- }
-
- @Override
- public @NonNull IDragAttribute[] getAttributes() {
- return mAttributes.values().toArray(new IDragAttribute[mAttributes.size()]);
- }
-
- @Override
- public @NonNull Rect getBounds() {
- return mRect;
- }
-
- @Override
- public @NonNull String getFqcn() {
- return mFqcn;
- }
-
- @Override
- public @NonNull IDragElement[] getInnerElements() {
- if (mChildren == null) {
- return new IDragElement[0];
- }
-
- return mChildren.toArray(new IDragElement[mChildren.size()]);
- }
-
- @Override
- public @NonNull Rect getParentBounds() {
- return mParent != null ? mParent.getBounds() : null;
- }
-
- @Override
- public String getParentFqcn() {
- return mParent != null ? mParent.getFqcn() : null;
- }
-
- @Override
- public String toString() {
- return "TestDragElement [fqn=" + mFqcn + ", attributes=" + mAttributes + ", bounds="
- + mRect + "]";
- }
-
- @Override
- public boolean isSame(INode node) {
- return node.getBounds().equals(getBounds());
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/TestGraphics.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/TestGraphics.java
deleted file mode 100644
index ec9321003..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/TestGraphics.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.DrawingStyle;
-import com.android.ide.common.api.IColor;
-import com.android.ide.common.api.IGraphics;
-import com.android.ide.common.api.Point;
-import com.android.ide.common.api.Rect;
-
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-// TODO: Create box of ascii art
-
-public class TestGraphics implements IGraphics {
- /** List of things we have drawn */
- private List<String> mDrawn = new ArrayList<String>();
-
- private IColor mBackground = new TestColor(0x000000);
-
- private IColor mForeground = new TestColor(0xFFFFFF);
-
- private int mAlpha = 128;
-
- /** Return log of graphics calls */
- public List<String> getDrawn() {
- return Collections.unmodifiableList(mDrawn);
- }
-
- /** Wipe out log of graphics calls */
- public void clear() {
- mDrawn.clear();
- }
-
- // ==== IGraphics ====
-
- @Override
- public void drawBoxedStrings(int x, int y, @NonNull List<?> strings) {
- mDrawn.add("drawBoxedStrings(" + x + "," + y + "," + strings + ")");
- }
-
- @Override
- public void drawLine(int x1, int y1, int x2, int y2) {
- mDrawn.add("drawLine(" + x1 + "," + y1 + "," + x2 + "," + y2 + ")");
- }
-
- @Override
- public void drawLine(@NonNull Point p1, @NonNull Point p2) {
- mDrawn.add("drawLine(" + p1 + "," + p2 + ")");
- }
-
- @Override
- public void drawRect(int x1, int y1, int x2, int y2) {
- mDrawn.add("drawRect(" + x1 + "," + y1 + "," + x2 + "," + y2 + ")");
- }
-
- @Override
- public void drawRect(@NonNull Point p1, @NonNull Point p2) {
- mDrawn.add("drawRect(" + p1 + "," + p2 + ")");
- }
-
- @Override
- public void drawRect(@NonNull Rect r) {
- mDrawn.add("drawRect(" + rectToString(r) + ")");
- }
-
- @Override
- public void drawString(@NonNull String string, int x, int y) {
- mDrawn.add("drawString(" + x + "," + y + "," + string + ")");
- }
-
- @Override
- public void drawString(@NonNull String string, @NonNull Point topLeft) {
- mDrawn.add("drawString(" + string + "," + topLeft + ")");
- }
-
- @Override
- public void fillRect(int x1, int y1, int x2, int y2) {
- mDrawn.add("fillRect(" + x1 + "," + y1 + "," + x2 + "," + y2 + ")");
- }
-
- @Override
- public void fillRect(@NonNull Point p1, @NonNull Point p2) {
- mDrawn.add("fillRect(" + p1 + "," + p2 + ")");
- }
-
- @Override
- public void fillRect(@NonNull Rect r) {
- mDrawn.add("fillRect(" + rectToString(r) + ")");
- }
-
- @Override
- public int getAlpha() {
- return mAlpha;
- }
-
- @Override
- public @NonNull IColor getBackground() {
- return mBackground;
- }
-
- @Override
- public int getFontHeight() {
- return 12;
- }
-
- @Override
- public @NonNull IColor getForeground() {
- return mForeground;
- }
-
- @Override
- public @NonNull IColor registerColor(int rgb) {
- mDrawn.add("registerColor(" + Integer.toHexString(rgb) + ")");
- return new TestColor(rgb);
- }
-
- @Override
- public void setAlpha(int alpha) {
- mAlpha = alpha;
- mDrawn.add("setAlpha(" + alpha + ")");
- }
-
- @Override
- public void setBackground(@NonNull IColor color) {
- mDrawn.add("setBackground(" + color + ")");
- mBackground = color;
- }
-
- @Override
- public void setForeground(@NonNull IColor color) {
- mDrawn.add("setForeground(" + color + ")");
- mForeground = color;
- }
-
- @Override
- public void setLineStyle(@NonNull LineStyle style) {
- mDrawn.add("setLineStyle(" + style + ")");
- }
-
- @Override
- public void setLineWidth(int width) {
- mDrawn.add("setLineWidth(" + width + ")");
- }
-
- @Override
- public void useStyle(@NonNull DrawingStyle style) {
- mDrawn.add("useStyle(" + style + ")");
- }
-
- @Override
- public void drawArrow(int x1, int y1, int x2, int y2, int size) {
- mDrawn.add("drawArrow(" + x1 + "," + y1 + "," + x2 + "," + y2 + ")");
- }
-
- @Override
- public void drawPoint(int x, int y) {
- mDrawn.add("drawPoint(" + x + "," + y + ")");
- }
-
- private static String rectToString(Rect rect) {
- return "Rect[" + rect.x + "," + rect.y + "," + rect.w + "," + rect.h + "]";
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/TestNode.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/TestNode.java
deleted file mode 100644
index 30886e4fa..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/TestNode.java
+++ /dev/null
@@ -1,477 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ANDROID_WIDGET_PREFIX;
-import static com.android.SdkConstants.ATTR_ID;
-import static junit.framework.Assert.assertEquals;
-import static junit.framework.Assert.assertNotNull;
-import static junit.framework.Assert.assertTrue;
-import static junit.framework.Assert.fail;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.IAttributeInfo;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.INodeHandler;
-import com.android.ide.common.api.Margins;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.xml.XmlFormatStyle;
-import com.android.ide.common.xml.XmlPrettyPrinter;
-import com.android.ide.eclipse.adt.internal.editors.formatting.EclipseXmlFormatPreferences;
-import com.android.ide.eclipse.adt.internal.editors.formatting.EclipseXmlPrettyPrinter;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-import com.google.common.base.Splitter;
-
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-
-import java.io.IOException;
-import java.io.StringWriter;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/** Test/mock implementation of {@link INode} */
-@SuppressWarnings("javadoc")
-public class TestNode implements INode {
- private TestNode mParent;
-
- private final List<TestNode> mChildren = new ArrayList<TestNode>();
-
- private final String mFqcn;
-
- private Rect mBounds = new Rect(); // Invalid bounds initially
-
- private Map<String, IAttribute> mAttributes = new HashMap<String, IAttribute>();
-
- private Map<String, IAttributeInfo> mAttributeInfos = new HashMap<String, IAttributeInfo>();
-
- private List<String> mAttributeSources;
-
- public TestNode(String fqcn) {
- this.mFqcn = fqcn;
- }
-
- public TestNode bounds(Rect bounds) {
- this.mBounds = bounds;
-
- return this;
- }
-
- public TestNode id(String id) {
- return set(ANDROID_URI, ATTR_ID, id);
- }
-
- public TestNode set(String uri, String name, String value) {
- setAttribute(uri, name, value);
-
- return this;
- }
-
- public TestNode add(TestNode child) {
- mChildren.add(child);
- child.mParent = this;
-
- return this;
- }
-
- public TestNode add(TestNode... children) {
- for (TestNode child : children) {
- mChildren.add(child);
- child.mParent = this;
- }
-
- return this;
- }
-
- public static TestNode create(String fcqn) {
- return new TestNode(fcqn);
- }
-
- public void removeChild(int index) {
- TestNode removed = mChildren.remove(index);
- removed.mParent = null;
- }
-
- // ==== INODE ====
-
- @Override
- public @NonNull INode appendChild(@NonNull String viewFqcn) {
- return insertChildAt(viewFqcn, mChildren.size());
- }
-
- @Override
- public void editXml(@NonNull String undoName, @NonNull INodeHandler callback) {
- callback.handle(this);
- }
-
- public void putAttributeInfo(String uri, String attrName, IAttributeInfo info) {
- mAttributeInfos.put(uri + attrName, info);
- }
-
- @Override
- public IAttributeInfo getAttributeInfo(@Nullable String uri, @NonNull String attrName) {
- return mAttributeInfos.get(uri + attrName);
- }
-
- @Override
- public @NonNull Rect getBounds() {
- return mBounds;
- }
-
- @Override
- public @NonNull INode[] getChildren() {
- return mChildren.toArray(new INode[mChildren.size()]);
- }
-
- @Override
- public @NonNull IAttributeInfo[] getDeclaredAttributes() {
- return mAttributeInfos.values().toArray(new IAttributeInfo[mAttributeInfos.size()]);
- }
-
- @Override
- public @NonNull String getFqcn() {
- return mFqcn;
- }
-
- @Override
- public @NonNull IAttribute[] getLiveAttributes() {
- return mAttributes.values().toArray(new IAttribute[mAttributes.size()]);
- }
-
- @Override
- public INode getParent() {
- return mParent;
- }
-
- @Override
- public INode getRoot() {
- TestNode curr = this;
- while (curr.mParent != null) {
- curr = curr.mParent;
- }
-
- return curr;
- }
-
- @Override
- public String getStringAttr(@Nullable String uri, @NonNull String attrName) {
- IAttribute attr = mAttributes.get(uri + attrName);
- if (attr == null) {
- return null;
- }
-
- return attr.getValue();
- }
-
- @Override
- public @NonNull INode insertChildAt(@NonNull String viewFqcn, int index) {
- TestNode child = new TestNode(viewFqcn);
- if (index == -1) {
- mChildren.add(child);
- } else {
- mChildren.add(index, child);
- }
- child.mParent = this;
- return child;
- }
-
- @Override
- public void removeChild(@NonNull INode node) {
- int index = mChildren.indexOf(node);
- if (index != -1) {
- removeChild(index);
- }
- }
-
- @Override
- public boolean setAttribute(@Nullable String uri, @NonNull String localName,
- @Nullable String value) {
- mAttributes.put(uri + localName, new TestAttribute(uri, localName, value));
- return true;
- }
-
- @Override
- public String toString() {
- String id = getStringAttr(ANDROID_URI, ATTR_ID);
- return "TestNode [id=" + (id != null ? id : "?") + ", fqn=" + mFqcn + ", infos="
- + mAttributeInfos + ", attributes=" + mAttributes + ", bounds=" + mBounds + "]";
- }
-
- @Override
- public int getBaseline() {
- return -1;
- }
-
- @Override
- public @NonNull Margins getMargins() {
- return null;
- }
-
- @Override
- public @NonNull List<String> getAttributeSources() {
- return mAttributeSources != null ? mAttributeSources : Collections.<String>emptyList();
- }
-
- public void setAttributeSources(List<String> attributeSources) {
- mAttributeSources = attributeSources;
- }
-
- /** Create a test node from the given XML */
- public static TestNode createFromXml(String xml) {
- Document document = DomUtilities.parseDocument(xml, false);
- assertNotNull(document);
- assertNotNull(document.getDocumentElement());
-
- return createFromNode(document.getDocumentElement());
- }
-
- public static String toXml(TestNode node) {
- assertTrue("This method only works with nodes constructed from XML",
- node instanceof TestXmlNode);
- Document document = ((TestXmlNode) node).mElement.getOwnerDocument();
- // Insert new whitespace nodes etc
- String xml = dumpDocument(document);
- document = DomUtilities.parseDocument(xml, false);
-
- XmlPrettyPrinter printer = new EclipseXmlPrettyPrinter(EclipseXmlFormatPreferences.create(),
- XmlFormatStyle.LAYOUT, "\n");
- StringBuilder sb = new StringBuilder(1000);
- sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
- printer.prettyPrint(-1, document, null, null, sb, false);
- return sb.toString();
- }
-
- @SuppressWarnings("deprecation")
- private static String dumpDocument(Document document) {
- // Diagnostics: print out the XML that we're about to render
- org.apache.xml.serialize.OutputFormat outputFormat =
- new org.apache.xml.serialize.OutputFormat(
- "XML", "ISO-8859-1", true); //$NON-NLS-1$ //$NON-NLS-2$
- outputFormat.setIndent(2);
- outputFormat.setLineWidth(100);
- outputFormat.setIndenting(true);
- outputFormat.setOmitXMLDeclaration(true);
- outputFormat.setOmitDocumentType(true);
- StringWriter stringWriter = new StringWriter();
- // Using FQN here to avoid having an import above, which will result
- // in a deprecation warning, and there isn't a way to annotate a single
- // import element with a SuppressWarnings.
- org.apache.xml.serialize.XMLSerializer serializer =
- new org.apache.xml.serialize.XMLSerializer(stringWriter, outputFormat);
- serializer.setNamespaces(true);
- try {
- serializer.serialize(document.getDocumentElement());
- return stringWriter.toString();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- private static TestNode createFromNode(Element element) {
- String fqcn = ANDROID_WIDGET_PREFIX + element.getTagName();
- TestNode node = new TestXmlNode(fqcn, element);
-
- for (Element child : DomUtilities.getChildren(element)) {
- node.add(createFromNode(child));
- }
-
- return node;
- }
-
- @Nullable
- public static TestNode findById(TestNode node, String id) {
- id = BaseLayoutRule.stripIdPrefix(id);
- return node.findById(id);
- }
-
- private TestNode findById(String targetId) {
- String id = getStringAttr(ANDROID_URI, ATTR_ID);
- if (id != null && targetId.equals(BaseLayoutRule.stripIdPrefix(id))) {
- return this;
- }
-
- for (TestNode child : mChildren) {
- TestNode result = child.findById(targetId);
- if (result != null) {
- return result;
- }
- }
-
- return null;
- }
-
- private static String getTagName(String fqcn) {
- return fqcn.substring(fqcn.lastIndexOf('.') + 1);
- }
-
- private static class TestXmlNode extends TestNode {
- private final Element mElement;
-
- public TestXmlNode(String fqcn, Element element) {
- super(fqcn);
- mElement = element;
- }
-
- @Override
- public @NonNull IAttribute[] getLiveAttributes() {
- List<IAttribute> result = new ArrayList<IAttribute>();
-
- NamedNodeMap attributes = mElement.getAttributes();
- for (int i = 0, n = attributes.getLength(); i < n; i++) {
- Attr attribute = (Attr) attributes.item(i);
- result.add(new TestXmlAttribute(attribute));
- }
- return result.toArray(new IAttribute[result.size()]);
- }
-
- @Override
- public boolean setAttribute(String uri, String localName, String value) {
- if (value == null) {
- mElement.removeAttributeNS(uri, localName);
- } else {
- mElement.setAttributeNS(uri, localName, value);
- }
- return super.setAttribute(uri, localName, value);
- }
-
- @Override
- public INode appendChild(String viewFqcn) {
- Element child = mElement.getOwnerDocument().createElement(getTagName(viewFqcn));
- mElement.appendChild(child);
- return new TestXmlNode(viewFqcn, child);
- }
-
- @Override
- public INode insertChildAt(String viewFqcn, int index) {
- if (index == -1) {
- return appendChild(viewFqcn);
- }
- Element child = mElement.getOwnerDocument().createElement(getTagName(viewFqcn));
- List<Element> children = DomUtilities.getChildren(mElement);
- if (children.size() >= index) {
- Element before = children.get(index);
- mElement.insertBefore(child, before);
- } else {
- fail("Unexpected index");
- mElement.appendChild(child);
- }
- return new TestXmlNode(viewFqcn, child);
- }
-
- @Override
- public String getStringAttr(String uri, String name) {
- String value;
- if (uri == null) {
- value = mElement.getAttribute(name);
- } else {
- value = mElement.getAttributeNS(uri, name);
- }
- if (value.isEmpty()) {
- value = null;
- }
-
- return value;
- }
-
- @Override
- public void removeChild(INode node) {
- assert node instanceof TestXmlNode;
- mElement.removeChild(((TestXmlNode) node).mElement);
- }
-
- @Override
- public void removeChild(int index) {
- List<Element> children = DomUtilities.getChildren(mElement);
- assertTrue(index < children.size());
- Element oldChild = children.get(index);
- mElement.removeChild(oldChild);
- }
- }
-
- public static class TestXmlAttribute implements IAttribute {
- private Attr mAttribute;
-
- public TestXmlAttribute(Attr attribute) {
- this.mAttribute = attribute;
- }
-
- @Override
- public String getUri() {
- return mAttribute.getNamespaceURI();
- }
-
- @Override
- public String getName() {
- String name = mAttribute.getLocalName();
- if (name == null) {
- name = mAttribute.getName();
- }
- return name;
- }
-
- @Override
- public String getValue() {
- return mAttribute.getValue();
- }
- }
-
- // Recursively initialize this node with the bounds specified in the given hierarchy
- // dump (from ViewHierarchy's DUMP_INFO flag
- public void assignBounds(String bounds) {
- Iterable<String> split = Splitter.on('\n').trimResults().split(bounds);
- assignBounds(split.iterator());
- }
-
- private void assignBounds(Iterator<String> iterator) {
- assertTrue(iterator.hasNext());
- String desc = iterator.next();
-
- Pattern pattern = Pattern.compile("^\\s*(.+)\\s+\\[(.+)\\]\\s*(<.+>)?\\s*(\\S+)?\\s*$");
- Matcher matcher = pattern.matcher(desc);
- assertTrue(matcher.matches());
- String fqn = matcher.group(1);
- assertEquals(getFqcn(), fqn);
- String boundsString = matcher.group(2);
- String[] bounds = boundsString.split(",");
- assertEquals(boundsString, 4, bounds.length);
- try {
- int left = Integer.parseInt(bounds[0]);
- int top = Integer.parseInt(bounds[1]);
- int right = Integer.parseInt(bounds[2]);
- int bottom = Integer.parseInt(bounds[3]);
- mBounds = new Rect(left, top, right - left, bottom - top);
- } catch (NumberFormatException nufe) {
- fail(nufe.getLocalizedMessage());
- }
- String tag = matcher.group(3);
-
- for (INode child : getChildren()) {
- assertTrue(iterator.hasNext());
- ((TestNode) child).assignBounds(iterator);
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/ZoomControlsRuleTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/ZoomControlsRuleTest.java
deleted file mode 100644
index daa487ed4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/ZoomControlsRuleTest.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.layout;
-
-import com.android.ide.common.api.DropFeedback;
-import com.android.ide.common.api.IDragElement;
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.Rect;
-
-/** Test the {@link ZoomControlsRule} */
-public class ZoomControlsRuleTest extends LayoutTestBase {
- public void testDoNothing() {
- String draggedButtonId = "@+id/DraggedButton";
-
- IDragElement[] elements = TestDragElement.create(TestDragElement.create(
- "android.widget.Button").id(draggedButtonId));
-
- INode layout = TestNode.create("android.widget.ZoomControls").id("@+id/ZoomControls01")
- .bounds(new Rect(0, 0, 240, 480)).add(
- TestNode.create("android.widget.Button").id("@+id/Button01").bounds(
- new Rect(0, 0, 100, 80)),
- TestNode.create("android.widget.Button").id("@+id/Button02").bounds(
- new Rect(0, 100, 100, 80)),
- TestNode.create("android.widget.Button").id("@+id/Button03").bounds(
- new Rect(0, 200, 100, 80)),
- TestNode.create("android.widget.Button").id("@+id/Button04").bounds(
- new Rect(0, 300, 100, 80)));
-
- ZoomControlsRule rule = new ZoomControlsRule();
-
- // Enter target
- DropFeedback feedback = rule.onDropEnter(layout, null/*targetView*/, elements);
- // Zoom controls don't respond to drags
- assertNull(feedback);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/grid/GridModelTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/grid/GridModelTest.java
deleted file mode 100644
index c4a58c6e4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/grid/GridModelTest.java
+++ /dev/null
@@ -1,852 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout.grid;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.ATTR_COLUMN_COUNT;
-import static com.android.SdkConstants.ATTR_LAYOUT_COLUMN;
-import static com.android.SdkConstants.ATTR_LAYOUT_COLUMN_SPAN;
-import static com.android.SdkConstants.ATTR_LAYOUT_ROW;
-import static com.android.SdkConstants.FQCN_BUTTON;
-
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.layout.LayoutTestBase;
-import com.android.ide.common.layout.TestNode;
-import com.android.ide.common.layout.grid.GridModel.ViewData;
-
-import java.util.Arrays;
-import java.util.Collections;
-
-
-@SuppressWarnings("javadoc")
-public class GridModelTest extends LayoutTestBase {
- public void testRemoveFlag() {
- assertEquals("left", GridModel.removeFlag("top", "top|left"));
- assertEquals("left", GridModel.removeFlag("top", "top | left"));
- assertEquals("top", GridModel.removeFlag("left", "top|left"));
- assertEquals("top", GridModel.removeFlag("left", "top | left"));
- assertEquals("left | center", GridModel.removeFlag("top", "top | left | center"));
- assertEquals(null, GridModel.removeFlag("top", "top"));
- }
-
- public void testReadModel1() {
- TestNode targetNode = TestNode.create("android.widget.GridLayout").id("@+id/GridLayout1")
- .bounds(new Rect(0, 0, 240, 480)).set(ANDROID_URI, ATTR_COLUMN_COUNT, "3");
-
- GridModel model = GridModel.get(null, targetNode, null);
- assertEquals(3, model.declaredColumnCount);
- assertEquals(1, model.actualColumnCount);
- assertEquals(1, model.actualRowCount);
-
- targetNode.add(TestNode.create(FQCN_BUTTON).id("@+id/Button1"));
- targetNode.add(TestNode.create(FQCN_BUTTON).id("@+id/Button2"));
- targetNode.add(TestNode.create(FQCN_BUTTON).id("@+id/Button3"));
- targetNode.add(TestNode.create(FQCN_BUTTON).id("@+id/Button4"));
-
- model = GridModel.get(null, targetNode, null);
- assertEquals(3, model.declaredColumnCount);
- assertEquals(3, model.actualColumnCount);
- assertEquals(2, model.actualRowCount);
- }
-
- public void testSplitColumn() {
- TestNode targetNode = TestNode.create("android.widget.GridLayout").id("@+id/GridLayout1")
- .bounds(new Rect(0, 0, 240, 480)).set(ANDROID_URI, ATTR_COLUMN_COUNT, "3");
- TestNode b1 = TestNode.create(FQCN_BUTTON).id("@+id/Button1");
- TestNode b2 = TestNode.create(FQCN_BUTTON).id("@+id/Button2");
- TestNode b3 = TestNode.create(FQCN_BUTTON).id("@+id/Button3");
- TestNode b4 = TestNode.create(FQCN_BUTTON).id("@+id/Button4");
- targetNode.add(b1);
- targetNode.add(b2);
- targetNode.add(b3);
- targetNode.add(b4);
- b4.setAttribute(ANDROID_URI, ATTR_LAYOUT_COLUMN_SPAN, "2");
-
- GridModel model = GridModel.get(new LayoutTestBase.TestRulesEngine(targetNode.getFqcn()),
- targetNode, null);
- assertEquals(3, model.declaredColumnCount);
- assertEquals(3, model.actualColumnCount);
- assertEquals(2, model.actualRowCount);
-
- model.applyPositionAttributes();
- assertEquals("0", b1.getStringAttr(ANDROID_URI, ATTR_LAYOUT_COLUMN));
- assertEquals("0", b1.getStringAttr(ANDROID_URI, ATTR_LAYOUT_ROW));
-
- assertEquals("1", b2.getStringAttr(ANDROID_URI, ATTR_LAYOUT_COLUMN));
- assertEquals("0", b2.getStringAttr(ANDROID_URI, ATTR_LAYOUT_ROW));
-
- assertEquals("2", b3.getStringAttr(ANDROID_URI, ATTR_LAYOUT_COLUMN));
- assertEquals("0", b3.getStringAttr(ANDROID_URI, ATTR_LAYOUT_ROW));
-
- assertEquals("0", b4.getStringAttr(ANDROID_URI, ATTR_LAYOUT_COLUMN));
- assertEquals("1", b4.getStringAttr(ANDROID_URI, ATTR_LAYOUT_ROW));
- assertEquals("2", b4.getStringAttr(ANDROID_URI, ATTR_LAYOUT_COLUMN_SPAN));
-
- model.splitColumn(1, false /*insertMarginColumn*/, 100 /*columnWidthDp*/, 300 /* x */);
- model.applyPositionAttributes();
-
- assertEquals(4, model.declaredColumnCount);
- assertEquals(4, model.actualColumnCount);
- assertEquals(2, model.actualRowCount);
-
- assertEquals("0", b1.getStringAttr(ANDROID_URI, ATTR_LAYOUT_COLUMN));
- assertEquals("0", b1.getStringAttr(ANDROID_URI, ATTR_LAYOUT_ROW));
-
- assertEquals("1", b2.getStringAttr(ANDROID_URI, ATTR_LAYOUT_COLUMN));
- assertEquals("2", b2.getStringAttr(ANDROID_URI, ATTR_LAYOUT_COLUMN_SPAN));
- assertEquals("0", b2.getStringAttr(ANDROID_URI, ATTR_LAYOUT_ROW));
-
- assertEquals("3", b3.getStringAttr(ANDROID_URI, ATTR_LAYOUT_COLUMN));
- assertEquals("0", b3.getStringAttr(ANDROID_URI, ATTR_LAYOUT_ROW));
-
- assertEquals("0", b4.getStringAttr(ANDROID_URI, ATTR_LAYOUT_COLUMN));
- assertEquals("1", b4.getStringAttr(ANDROID_URI, ATTR_LAYOUT_ROW));
- assertEquals("3", b4.getStringAttr(ANDROID_URI, ATTR_LAYOUT_COLUMN_SPAN));
- }
-
- public void testDeletion1() {
- String xml =
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<GridLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\"\n" +
- " android:columnCount=\"4\" >\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button1\"\n" +
- " android:layout_column=\"1\"\n" +
- " android:layout_gravity=\"left|top\"\n" +
- " android:layout_row=\"1\"\n" +
- " android:text=\"Button\" />\n" +
- "\n" +
- " <TextView\n" +
- " android:id=\"@+id/TextView1\"\n" +
- " android:layout_column=\"3\"\n" +
- " android:layout_gravity=\"left|top\"\n" +
- " android:layout_row=\"1\"\n" +
- " android:text=\"Text\" />\n" +
- "\n" +
- " <Space\n" +
- " android:id=\"@+id/wspace1\"\n" +
- " android:layout_width=\"21dp\"\n" +
- " android:layout_height=\"1dp\"\n" +
- " android:layout_column=\"0\"\n" +
- " android:layout_row=\"0\" />\n" +
- "\n" +
- " <Space\n" +
- " android:id=\"@+id/hspace1\"\n" +
- " android:layout_width=\"1dp\"\n" +
- " android:layout_height=\"55dp\"\n" +
- " android:layout_column=\"0\"\n" +
- " android:layout_row=\"0\" />\n" +
- "\n" +
- " <Space\n" +
- " android:id=\"@+id/wspace2\"\n" +
- " android:layout_width=\"10dp\"\n" +
- " android:layout_height=\"1dp\"\n" +
- " android:layout_column=\"2\"\n" +
- " android:layout_row=\"0\" />\n" +
- "\n" +
- "</GridLayout>";
-
- TestNode targetNode = TestNode.createFromXml(xml);
- assertNotNull(targetNode);
-
- TestNode button1 = TestNode.findById(targetNode, "@+id/button1");
- TestNode textView1 = TestNode.findById(targetNode, "@+id/TextView1");
- TestNode wspace1 = TestNode.findById(targetNode, "@+id/wspace1");
- TestNode wspace2 = TestNode.findById(targetNode, "@+id/wspace2");
- TestNode hspace1 = TestNode.findById(targetNode, "@+id/hspace1");
- assertNotNull(wspace1);
- assertNotNull(hspace1);
- assertNotNull(wspace2);
- assertNotNull(button1);
- assertNotNull(textView1);
-
- // Assign some bounds such that the model makes sense when merging spacer sizes
- // TODO: MAke test utility method to automatically assign half divisions!!
- button1.bounds(new Rect(90, 10, 100, 40));
- textView1.bounds(new Rect(200, 10, 100, 40));
- wspace1.bounds(new Rect(0, 0, 90, 1));
- wspace1.bounds(new Rect(190, 0, 10, 1));
- hspace1.bounds(new Rect(0, 0, 1, 10));
-
- GridModel model = GridModel.get(new LayoutTestBase.TestRulesEngine(targetNode.getFqcn()),
- targetNode, null);
- assertEquals(4, model.declaredColumnCount);
- assertEquals(4, model.actualColumnCount);
- assertEquals(2, model.actualRowCount);
-
- ViewData textViewData = model.getView(textView1);
- assertEquals(3, textViewData.column);
-
- // Delete button1
- button1.getParent().removeChild(button1);
- model.onDeleted(Arrays.<INode>asList(button1));
- model.applyPositionAttributes();
-
- assertEquals(2, model.declaredColumnCount);
- assertEquals(2, model.actualColumnCount);
- assertEquals(2, model.actualRowCount);
- assertNotNull(model.getView(textView1));
- assertNull(model.getView(button1));
-
- assertEquals(
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<GridLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\"\n" +
- " android:columnCount=\"2\">\n" +
- "\n" +
- " <TextView\n" +
- " android:id=\"@+id/TextView1\"\n" +
- " android:layout_column=\"1\"\n" +
- " android:layout_gravity=\"left|top\"\n" +
- " android:layout_row=\"1\"\n" +
- " android:text=\"Text\">\n" +
- " </TextView>\n" +
- "\n" +
- " <Space\n" +
- " android:id=\"@+id/wspace1\"\n" +
- " android:layout_width=\"66dp\"\n" +
- " android:layout_height=\"1dp\"\n" +
- " android:layout_column=\"0\"\n" +
- " android:layout_row=\"0\">\n" +
- " </Space>\n" +
- "\n" +
- " <Space\n" +
- " android:id=\"@+id/hspace1\"\n" +
- " android:layout_width=\"1dp\"\n" +
- " android:layout_height=\"55dp\"\n" +
- " android:layout_column=\"0\"\n" +
- " android:layout_row=\"0\">\n" +
- " </Space>\n" +
- "\n" +
- "</GridLayout>", TestNode.toXml(targetNode));
-
- // Delete textView1
-
- textView1.getParent().removeChild(textView1);
- model.onDeleted(Arrays.<INode>asList(textView1));
- model.applyPositionAttributes();
-
- assertEquals(2, model.declaredColumnCount);
- assertEquals(0, model.actualColumnCount);
- assertEquals(0, model.actualRowCount);
- assertNull(model.getView(textView1));
- assertNull(model.getView(button1));
-
- assertEquals(
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<GridLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\"\n" +
- " android:columnCount=\"0\">\n" +
- "\n" +
- "</GridLayout>", TestNode.toXml(targetNode));
-
- }
-
- public void testDelete2() throws Exception {
- String xml =
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<GridLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\"\n" +
- " android:columnCount=\"4\"\n" +
- " android:orientation=\"vertical\" >\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button1\"\n" +
- " android:layout_column=\"0\"\n" +
- " android:layout_columnSpan=\"2\"\n" +
- " android:layout_gravity=\"left|top\"\n" +
- " android:layout_row=\"0\"\n" +
- " android:text=\"Button1\" />\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button3\"\n" +
- " android:layout_column=\"1\"\n" +
- " android:layout_columnSpan=\"2\"\n" +
- " android:layout_gravity=\"left|top\"\n" +
- " android:layout_row=\"1\"\n" +
- " android:text=\"Button2\" />\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button2\"\n" +
- " android:layout_column=\"2\"\n" +
- " android:layout_gravity=\"left|top\"\n" +
- " android:layout_row=\"0\"\n" +
- " android:text=\"Button3\" />\n" +
- "\n" +
- " <Space\n" +
- " android:id=\"@+id/spacer_177\"\n" +
- " android:layout_width=\"46dp\"\n" +
- " android:layout_height=\"1dp\"\n" +
- " android:layout_column=\"0\"\n" +
- " android:layout_row=\"0\" />\n" +
- "\n" +
- "</GridLayout>";
-
- TestNode targetNode = TestNode.createFromXml(xml);
- assertNotNull(targetNode);
-
- TestNode button1 = TestNode.findById(targetNode, "@+id/button1");
- TestNode button2 = TestNode.findById(targetNode, "@+id/button2");
- TestNode button3 = TestNode.findById(targetNode, "@+id/button3");
- TestNode hspacer = TestNode.findById(targetNode, "@+id/spacer_177");
- assertNotNull(button1);
- assertNotNull(button2);
- assertNotNull(button3);
- assertNotNull(hspacer);
-
- // Assign some bounds such that the model makes sense when merging spacer sizes
- // TODO: MAke test utility method to automatically assign half divisions!!
- button1.bounds(new Rect(0, 0, 100, 40));
- button2.bounds(new Rect(100, 0, 100, 40));
- button3.bounds(new Rect(50, 40, 100, 40));
- hspacer.bounds(new Rect(0, 0, 50, 1));
-
- GridModel model = GridModel.get(new LayoutTestBase.TestRulesEngine(targetNode.getFqcn()),
- targetNode, null);
- assertEquals(4, model.declaredColumnCount);
- assertEquals(3, model.actualColumnCount);
- assertEquals(2, model.actualRowCount);
-
- ViewData buttonData = model.getView(button1);
- assertEquals(0, buttonData.column);
-
- // Delete button1
- button1.getParent().removeChild(button1);
- model.onDeleted(Arrays.<INode>asList(button1));
- model.applyPositionAttributes();
-
- assertEquals(3, model.declaredColumnCount);
- assertEquals(3, model.actualColumnCount);
- assertEquals(2, model.actualRowCount);
- assertNull(model.getView(button1));
-
- assertEquals(
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<GridLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\"\n" +
- " android:columnCount=\"3\"\n" +
- " android:orientation=\"vertical\">\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button3\"\n" +
- " android:layout_column=\"1\"\n" +
- " android:layout_columnSpan=\"2\"\n" +
- " android:layout_gravity=\"left|top\"\n" +
- " android:layout_row=\"1\"\n" +
- " android:text=\"Button2\">\n" +
- " </Button>\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button2\"\n" +
- " android:layout_column=\"2\"\n" +
- " android:layout_gravity=\"left|top\"\n" +
- " android:layout_row=\"0\"\n" +
- " android:text=\"Button3\">\n" +
- " </Button>\n" +
- "\n" +
- " <Space\n" +
- " android:id=\"@+id/spacer_177\"\n" +
- " android:layout_width=\"46dp\"\n" +
- " android:layout_height=\"1dp\"\n" +
- " android:layout_column=\"0\"\n" +
- " android:layout_row=\"0\">\n" +
- " </Space>\n" +
- "\n" +
- "</GridLayout>", TestNode.toXml(targetNode));
- }
-
- public void testDelete3_INCOMPLETE() throws Exception {
- String xml =
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<GridLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"\n" +
- " android:columnCount=\"6\">\n" +
- " <Button android:id=\"@+id/button1\" android:layout_column=\"1\"\n" +
- " android:layout_columnSpan=\"2\" android:layout_gravity=\"left|top\"\n" +
- " android:layout_row=\"1\" android:layout_rowSpan=\"2\" android:text=\"Button\" />\n" +
- " <TextView android:id=\"@+id/TextView1\" android:layout_column=\"4\"\n" +
- " android:layout_gravity=\"left|top\" android:layout_row=\"1\"\n" +
- " android:text=\"Text\" />\n" +
- " <Button android:id=\"@+id/button3\" android:layout_column=\"5\"\n" +
- " android:layout_gravity=\"left|top\" android:layout_row=\"2\"\n" +
- " android:layout_rowSpan=\"2\" android:text=\"Button\" />\n" +
- " <Button android:id=\"@+id/button2\" android:layout_column=\"2\"\n" +
- " android:layout_columnSpan=\"3\" android:layout_gravity=\"left|top\"\n" +
- " android:layout_row=\"4\" android:text=\"Button\" />\n" +
- " <Space android:id=\"@+id/wspace1\" android:layout_width=\"21dp\"\n" +
- " android:layout_height=\"1dp\" android:layout_column=\"0\"\n" +
- " android:layout_row=\"0\" />\n" +
- " <Space android:id=\"@+id/spacer_630\" android:layout_width=\"1dp\"\n" +
- " android:layout_height=\"55dp\" android:layout_column=\"0\"\n" +
- " android:layout_row=\"0\" />\n" +
- " <Space android:id=\"@+id/wspace2\" android:layout_width=\"10dp\"\n" +
- " android:layout_height=\"1dp\" android:layout_column=\"3\"\n" +
- " android:layout_row=\"0\" />\n" +
- " <Space android:id=\"@+id/spacer_619\" android:layout_width=\"59dp\"\n" +
- " android:layout_height=\"1dp\" android:layout_column=\"1\"\n" +
- " android:layout_row=\"0\" />\n" +
- " <Space android:id=\"@+id/spacer_102\" android:layout_width=\"1dp\"\n" +
- " android:layout_height=\"30dp\" android:layout_column=\"0\"\n" +
- " android:layout_row=\"1\" />\n" +
- " <Space android:id=\"@+id/spacer_109\" android:layout_width=\"1dp\"\n" +
- " android:layout_height=\"28dp\" android:layout_column=\"0\"\n" +
- " android:layout_row=\"2\" />\n" +
- " <Space android:id=\"@+id/spacer_146\" android:layout_width=\"1dp\"\n" +
- " android:layout_height=\"70dp\" android:layout_column=\"0\"\n" +
- " android:layout_row=\"3\" />\n" +
- "</GridLayout>";
- TestNode targetNode = TestNode.createFromXml(xml);
- assertNotNull(targetNode);
- targetNode.assignBounds(
- "android.widget.GridLayout [0,109,480,800] <GridLayout>\n" +
- " android.widget.Button [32,83,148,155] <Button> @+id/button1\n" +
- " android.widget.TextView [163,83,205,109] <TextView> @+id/TextView1\n" +
- " android.widget.Button [237,128,353,200] <Button> @+id/button3\n" +
- " android.widget.Button [121,275,237,347] <Button> @+id/button2\n" +
- " android.widget.Space [0,0,32,2] <Space> @+id/wspace1\n" +
- " android.widget.Space [0,0,2,83] <Space> @+id/spacer_630\n" +
- " android.widget.Space [148,0,163,2] <Space> @+id/wspace2\n" +
- " android.widget.Space [32,0,121,2] <Space> @+id/spacer_619\n" +
- " android.widget.Space [0,83,2,128] <Space> @+id/spacer_102\n" +
- " android.widget.Space [0,128,2,170] <Space> @+id/spacer_109\n" +
- " android.widget.Space [0,170,2,275] <Space> @+id/spacer_146\n");
- TestNode layout = TestNode.findById(targetNode, "@+id/GridLayout1");
- //TestNode button1 = TestNode.findById(targetNode, "@+id/button1");
- TestNode button2 = TestNode.findById(targetNode, "@+id/button2");
- TestNode button3 = TestNode.findById(targetNode, "@+id/button3");
-
- GridModel model = GridModel.get(new LayoutTestBase.TestRulesEngine(targetNode.getFqcn()),
- targetNode, null);
- assertEquals(6, model.declaredColumnCount);
- assertEquals(6, model.actualColumnCount);
- assertEquals(5, model.actualRowCount);
-
- // TODO: Delete button2 or button3: bad stuff happens visually
- fail("Finish test");
- }
-
- public void testDelete4_INCOMPLETE() {
- String xml = "" +
- "<GridLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " xmlns:tools=\"http://schemas.android.com/tools\" " +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\" android:columnCount=\"3\"\n" +
- " android:gravity=\"center\" android:text=\"@string/hello_world\"\n" +
- " tools:context=\".MainActivity\">\n" +
- " <Button android:id=\"@+id/button2\" android:layout_column=\"1\"\n" +
- " android:layout_columnSpan=\"2\" android:layout_gravity=\"left|top\"\n" +
- " android:layout_row=\"1\" android:text=\"Button\" />\n" +
- " <Button android:id=\"@+id/button1\" android:layout_column=\"1\"\n" +
- " android:layout_columnSpan=\"2\" android:layout_gravity=\"left|top\"\n" +
- " android:layout_row=\"3\" android:text=\"Button\" />\n" +
- " <Space android:id=\"@+id/spacer_167\" android:layout_width=\"74dp\"\n" +
- " android:layout_height=\"1dp\" android:layout_column=\"0\"\n" +
- " android:layout_row=\"0\" />\n" +
- " <Space android:id=\"@+id/spacer_133\" android:layout_width=\"1dp\"\n" +
- " android:layout_height=\"21dp\" android:layout_column=\"0\"\n" +
- " android:layout_row=\"0\" />\n" +
- " <Space android:id=\"@+id/spacer_142\" android:layout_width=\"1dp\"\n" +
- " android:layout_height=\"26dp\" android:layout_column=\"0\"\n" +
- " android:layout_row=\"2\" />\n" +
- " <Space android:id=\"@+id/spacer_673\" android:layout_width=\"43dp\"\n" +
- " android:layout_height=\"1dp\" android:layout_column=\"1\"\n" +
- " android:layout_row=\"0\" />\n" +
- " <Space android:id=\"@+id/spacer_110\" android:layout_width=\"202dp\"\n" +
- " android:layout_height=\"15dp\" android:layout_column=\"2\" />\n" +
- "</GridLayout>";
- TestNode targetNode = TestNode.createFromXml(xml);
- assertNotNull(targetNode);
- targetNode.assignBounds(
- "android.widget.GridLayout [0,109,480,800] <GridLayout>\n" +
- " android.widget.Button [111,32,227,104] <Button> @+id/button2\n" +
- " android.widget.Button [111,143,227,215] <Button> @+id/button1\n" +
- " android.widget.Space [0,0,111,2] <Space> @+id/spacer_167\n" +
- " android.widget.Space [0,0,2,32] <Space> @+id/spacer_133\n" +
- " android.widget.Space [0,104,2,143] <Space> @+id/spacer_142\n" +
- " android.widget.Space [111,0,176,2] <Space> @+id/spacer_673\n" +
- " android.widget.Space [176,668,479,691] <Space> @+id/spacer_110");
-
-
- // Remove button2; button1 shifts to the right!
-
- //TestNode layout = TestNode.findById(targetNode, "@+id/GridLayout1");
- //TestNode button1 = TestNode.findById(targetNode, "@+id/button1");
- TestNode button2 = TestNode.findById(targetNode, "@+id/button2");
- TestNode button3 = TestNode.findById(targetNode, "@+id/button3");
- assertEquals(new Rect(111, 32, 227 - 111, 104 - 32), button2.getBounds());
-
- GridModel model = GridModel.get(new LayoutTestBase.TestRulesEngine(targetNode.getFqcn()),
- targetNode, null);
- assertEquals(3, model.declaredColumnCount);
- assertEquals(3, model.actualColumnCount);
- assertEquals(4, model.actualRowCount);
- fail("Finish test");
- }
-
- public void testDelete5_INCOMPLETE() {
- String xml =
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<GridLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " android:id=\"@+id/GridLayout1\" android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\" android:columnCount=\"4\"\n" +
- " android:orientation=\"vertical\">\n" +
- " <Button android:id=\"@+id/button1\" android:layout_column=\"0\"\n" +
- " android:layout_gravity=\"center_horizontal|bottom\"\n" +
- " android:layout_row=\"0\" android:text=\"Button\" />\n" +
- " <Space android:layout_width=\"66dp\" android:layout_height=\"1dp\"\n" +
- " android:layout_column=\"0\" android:layout_row=\"0\" />\n" +
- " <Button android:id=\"@+id/button3\" android:layout_column=\"2\"\n" +
- " android:layout_gravity=\"left|bottom\" android:layout_row=\"0\"\n" +
- " android:text=\"Button\" />\n" +
- " <Button android:id=\"@+id/button2\" android:layout_column=\"3\"\n" +
- " android:layout_columnSpan=\"2\" android:layout_gravity=\"left|bottom\"\n" +
- " android:layout_row=\"0\" android:text=\"Button\" />\n" +
- " <Space android:id=\"@+id/spacer_109\" android:layout_width=\"51dp\"\n" +
- " android:layout_height=\"1dp\" android:layout_column=\"1\"\n" +
- " android:layout_row=\"0\" />\n" +
- " <Space android:layout_width=\"129dp\" android:layout_height=\"1dp\"\n" +
- " android:layout_column=\"2\" android:layout_row=\"0\" />\n" +
- " <Space android:layout_width=\"62dp\" android:layout_height=\"1dp\"\n" +
- " android:layout_column=\"3\" android:layout_row=\"0\" />\n" +
- " <Space android:id=\"@+id/spacer_397\" android:layout_width=\"1dp\"\n" +
- " android:layout_height=\"103dp\" android:layout_column=\"0\"\n" +
- " android:layout_row=\"0\" />\n" +
- " <Space android:layout_width=\"1dp\" android:layout_height=\"356dp\"\n" +
- " android:layout_column=\"0\" android:layout_row=\"1\" />\n" +
- "</GridLayout>";
- TestNode targetNode = TestNode.createFromXml(xml);
- assertNotNull(targetNode);
-
- targetNode.assignBounds(
- "android.widget.GridLayout [0,109,480,800] <GridLayout> @+id/GridLayout1\n" +
- " android.widget.Button [0,83,116,155] <Button> @+id/button1\n" +
- " android.widget.Space [0,0,99,2] <Space>\n" +
- " android.widget.Button [193,83,309,155] <Button> @+id/button3\n" +
- " android.widget.Button [387,83,503,155] <Button> @+id/button2\n" +
- " android.widget.Space [116,0,193,2] <Space> @+id/spacer_109\n" +
- " android.widget.Space [193,0,387,2] <Space>\n" +
- " android.widget.Space [387,0,480,2] <Space>\n" +
- " android.widget.Space [0,0,2,155] <Space> @+id/spacer_397\n" +
- " android.widget.Space [0,155,2,689] <Space>");
-
- // Delete button3. This causes an array out of bounds exception currently.
-
- //TestNode layout = TestNode.findById(targetNode, "@+id/GridLayout1");
- //TestNode button1 = TestNode.findById(targetNode, "@+id/button1");
- TestNode button2 = TestNode.findById(targetNode, "@+id/button2");
- TestNode button3 = TestNode.findById(targetNode, "@+id/button3");
- assertEquals(new Rect(387, 83, 503 - 387, 155- 83), button2.getBounds());
-
- GridModel model = GridModel.get(new LayoutTestBase.TestRulesEngine(targetNode.getFqcn()),
- targetNode, null);
- assertEquals(4, model.declaredColumnCount);
- assertEquals(4, model.actualColumnCount);
- assertEquals(2, model.actualRowCount);
-
- model.onDeleted(Collections.<INode>singletonList(button3));
- // Exception fixed; todo: Test that the model updates are correct.
-
- assertEquals(3, model.declaredColumnCount);
- assertEquals(3, model.actualColumnCount);
- assertEquals(2, model.actualRowCount);
-
- fail("Finish test");
- }
-
- public void testInsert1() throws Exception {
- String xml =
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<GridLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " android:id=\"@+id/GridLayout1\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\"\n" +
- " android:columnCount=\"4\"\n" +
- " android:orientation=\"vertical\" >\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button1\"\n" +
- " android:layout_column=\"0\"\n" +
- " android:layout_columnSpan=\"4\"\n" +
- " android:layout_gravity=\"center_horizontal|bottom\"\n" +
- " android:layout_row=\"0\"\n" +
- " android:text=\"Button\" />\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button2\"\n" +
- " android:layout_column=\"2\"\n" +
- " android:layout_gravity=\"left|top\"\n" +
- " android:layout_row=\"1\"\n" +
- " android:text=\"Button\" />\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button3\"\n" +
- " android:layout_column=\"3\"\n" +
- " android:layout_gravity=\"left|top\"\n" +
- " android:layout_row=\"1\"\n" +
- " android:text=\"Button\" />\n" +
- "\n" +
- " <Space\n" +
- " android:id=\"@+id/spacer_393\"\n" +
- " android:layout_width=\"81dp\"\n" +
- " android:layout_height=\"1dp\"\n" +
- " android:layout_column=\"1\"\n" +
- " android:layout_row=\"0\" />\n" +
- "\n" +
- " <Space\n" +
- " android:id=\"@+id/spacer_397\"\n" +
- " android:layout_width=\"1dp\"\n" +
- " android:layout_height=\"103dp\"\n" +
- " android:layout_column=\"0\"\n" +
- " android:layout_row=\"0\" />\n" +
- "\n" +
- "</GridLayout>";
-
- TestNode targetNode = TestNode.createFromXml(xml);
- assertNotNull(targetNode);
-
- TestNode layout = TestNode.findById(targetNode, "@+id/GridLayout1");
- TestNode button1 = TestNode.findById(targetNode, "@+id/button1");
- TestNode button2 = TestNode.findById(targetNode, "@+id/button2");
- TestNode button3 = TestNode.findById(targetNode, "@+id/button3");
- TestNode hspacer = TestNode.findById(targetNode, "@+id/spacer_393");
- TestNode vspacer = TestNode.findById(targetNode, "@+id/spacer_397");
- assertNotNull(layout);
- assertNotNull(button1);
- assertNotNull(button2);
- assertNotNull(button3);
- assertNotNull(hspacer);
-
- // Obtained by setting ViewHierarchy.DUMP_INFO=true:
- layout.bounds(new Rect(0, 109, 480, 800-109));
- button1.bounds(new Rect(182, 83, 298-182, 155-83));
- button2.bounds(new Rect(124, 155, 240-124, 227-155));
- button3.bounds(new Rect(240, 155, 356-240, 227-155));
- hspacer.bounds(new Rect(2, 0, 124-2, 2));
- vspacer.bounds(new Rect(0, 0, 2, 155));
-
- GridModel model = GridModel.get(new LayoutTestBase.TestRulesEngine(targetNode.getFqcn()),
- targetNode, null);
- assertEquals(4, model.declaredColumnCount);
- assertEquals(4, model.actualColumnCount);
- assertEquals(2, model.actualRowCount);
-
-
- model.splitColumn(1, false, 21, 32);
- int index = model.getInsertIndex(2, 1);
- GridModel.ViewData next = model.getView(index);
- INode newChild = targetNode.insertChildAt(FQCN_BUTTON, index);
- next.applyPositionAttributes();
- model.setGridAttribute(newChild, ATTR_LAYOUT_COLUMN, 1);
- model.setGridAttribute(newChild, ATTR_LAYOUT_COLUMN_SPAN, 3);
- }
-
- public void testInsert2() throws Exception {
- // Drop into a view where there is a centered view: when dropping to the right of
- // it (on a row further down), ensure that the row span is increased for the
- // non-left-justified centered view which does not horizontally overlap the view
- String xml =
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<GridLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " android:id=\"@+id/GridLayout1\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\"\n" +
- " android:columnCount=\"3\"\n" +
- " android:orientation=\"vertical\" >\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button1\"\n" +
- " android:layout_column=\"0\"\n" +
- " android:layout_columnSpan=\"3\"\n" +
- " android:layout_gravity=\"center_horizontal|bottom\"\n" +
- " android:layout_row=\"0\"\n" +
- " android:text=\"Button\" />\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button2\"\n" +
- " android:layout_column=\"1\"\n" +
- " android:layout_gravity=\"left|top\"\n" +
- " android:layout_row=\"1\"\n" +
- " android:text=\"Button\" />\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button3\"\n" +
- " android:layout_column=\"2\"\n" +
- " android:layout_gravity=\"left|top\"\n" +
- " android:layout_row=\"1\"\n" +
- " android:text=\"Button\" />\n" +
- "\n" +
- " <Space\n" +
- " android:id=\"@+id/spacer_393\"\n" +
- " android:layout_width=\"81dp\"\n" +
- " android:layout_height=\"1dp\"\n" +
- " android:layout_column=\"0\"\n" +
- " android:layout_row=\"0\" />\n" +
- "\n" +
- " \n" +
- " <Space\n" +
- " android:id=\"@+id/spacer_397\"\n" +
- " android:layout_width=\"1dp\"\n" +
- " android:layout_height=\"103dp\"\n" +
- " android:layout_column=\"0\"\n" +
- " android:layout_row=\"0\" />\n" +
- "\n" +
- " \n" +
- "</GridLayout>";
-
- TestNode targetNode = TestNode.createFromXml(xml);
- assertNotNull(targetNode);
-
- TestNode layout = TestNode.findById(targetNode, "@+id/GridLayout1");
- TestNode button1 = TestNode.findById(targetNode, "@+id/button1");
- TestNode button2 = TestNode.findById(targetNode, "@+id/button2");
- TestNode button3 = TestNode.findById(targetNode, "@+id/button3");
- TestNode hspacer = TestNode.findById(targetNode, "@+id/spacer_393");
- TestNode vspacer = TestNode.findById(targetNode, "@+id/spacer_397");
- assertNotNull(layout);
- assertNotNull(button1);
- assertNotNull(button2);
- assertNotNull(button3);
- assertNotNull(hspacer);
-
- // Obtained by setting ViewHierarchy.DUMP_INFO=true:
- layout.bounds(new Rect(0, 109, 480, 800-109));
- button1.bounds(new Rect(182, 83, 298-182, 155-83));
- button2.bounds(new Rect(122, 155, 238-122, 227-155));
- button3.bounds(new Rect(238, 155, 354-238, 227-155));
- hspacer.bounds(new Rect(0, 0, 122, 2));
- vspacer.bounds(new Rect(0, 0, 2, 155));
-
- GridModel model = GridModel.get(new LayoutTestBase.TestRulesEngine(targetNode.getFqcn()),
- targetNode, null);
- assertEquals(3, model.declaredColumnCount);
- assertEquals(3, model.actualColumnCount);
- assertEquals(2, model.actualRowCount);
-
- ViewData view = model.getView(button1);
- assertNotNull(view);
- assertEquals(0, view.column);
- assertEquals(3, view.columnSpan);
- assertEquals("3", view.node.getStringAttr(ANDROID_URI, ATTR_LAYOUT_COLUMN_SPAN));
-
- model.splitColumn(3, false, 53, 318);
- assertEquals(0, view.column);
- assertEquals(4, view.columnSpan);
- assertEquals("4", view.node.getStringAttr(ANDROID_URI, ATTR_LAYOUT_COLUMN_SPAN));
- }
-
- public void testInsert3_BROKEN() throws Exception {
- // Check that when we insert a new gap column near an existing column, the
- // view in that new column does not get moved
- String xml =
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<GridLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " android:id=\"@+id/GridLayout1\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\"\n" +
- " android:columnCount=\"3\"\n" +
- " android:orientation=\"vertical\" >\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button1\"\n" +
- " android:layout_column=\"0\"\n" +
- " android:layout_columnSpan=\"3\"\n" +
- " android:layout_gravity=\"center_horizontal|bottom\"\n" +
- " android:layout_row=\"0\"\n" +
- " android:text=\"Button\" />\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button2\"\n" +
- " android:layout_column=\"1\"\n" +
- " android:layout_gravity=\"left|top\"\n" +
- " android:layout_row=\"1\"\n" +
- " android:text=\"Button\" />\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button3\"\n" +
- " android:layout_column=\"2\"\n" +
- " android:layout_gravity=\"left|top\"\n" +
- " android:layout_row=\"1\"\n" +
- " android:text=\"Button\" />\n" +
- "\n" +
- " <Space\n" +
- " android:id=\"@+id/spacer_393\"\n" +
- " android:layout_width=\"81dp\"\n" +
- " android:layout_height=\"1dp\"\n" +
- " android:layout_column=\"0\"\n" +
- " android:layout_row=\"0\" />\n" +
- "\n" +
- " \n" +
- " <Space\n" +
- " android:id=\"@+id/spacer_397\"\n" +
- " android:layout_width=\"1dp\"\n" +
- " android:layout_height=\"103dp\"\n" +
- " android:layout_column=\"0\"\n" +
- " android:layout_row=\"0\" />\n" +
- "\n" +
- " \n" +
- "</GridLayout>";
-
- TestNode targetNode = TestNode.createFromXml(xml);
- assertNotNull(targetNode);
-
- TestNode layout = TestNode.findById(targetNode, "@+id/GridLayout1");
- TestNode button1 = TestNode.findById(targetNode, "@+id/button1");
- TestNode button2 = TestNode.findById(targetNode, "@+id/button2");
- TestNode button3 = TestNode.findById(targetNode, "@+id/button3");
- TestNode hspacer = TestNode.findById(targetNode, "@+id/spacer_393");
- TestNode vspacer = TestNode.findById(targetNode, "@+id/spacer_397");
- assertNotNull(layout);
- assertNotNull(button1);
- assertNotNull(button2);
- assertNotNull(button3);
- assertNotNull(hspacer);
-
- // Obtained by setting ViewHierarchy.DUMP_INFO=true:
- layout.bounds(new Rect(0, 109, 480, 800-109));
- button1.bounds(new Rect(182, 83, 298-182, 155-83));
- button2.bounds(new Rect(122, 155, 238-122, 227-155));
- button3.bounds(new Rect(238, 155, 354-238, 227-155));
- hspacer.bounds(new Rect(0, 0, 122, 2));
- vspacer.bounds(new Rect(0, 0, 2, 155));
-
- GridModel model = GridModel.get(new LayoutTestBase.TestRulesEngine(targetNode.getFqcn()),
- targetNode, null);
- assertEquals(3, model.declaredColumnCount);
- assertEquals(3, model.actualColumnCount);
- assertEquals(2, model.actualRowCount);
-
- ViewData view = model.getView(button3);
- assertNotNull(view);
- assertEquals(2, view.column);
- assertEquals(1, view.columnSpan);
- assertNull("1", view.node.getStringAttr(ANDROID_URI, ATTR_LAYOUT_COLUMN_SPAN));
-
- model.splitColumn(2, true, 10, 253);
- // TODO: Finish this test: Assert that the cells are in the right place
- //assertEquals(4, view.column);
- //assertEquals(1, view.columnSpan);
- //assertEquals("4", view.node.getStringAttr(ANDROID_URI, ATTR_LAYOUT_COLUMN_SPAN));
- fail("Finish test");
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/relative/DeletionHandlerTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/relative/DeletionHandlerTest.java
deleted file mode 100644
index d629a3897..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/layout/relative/DeletionHandlerTest.java
+++ /dev/null
@@ -1,445 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.layout.relative;
-
-import static com.android.SdkConstants.ATTR_ID;
-import static com.android.SdkConstants.ANDROID_URI;
-
-import com.android.ide.common.api.INode;
-import com.android.ide.common.layout.BaseViewRule;
-import com.android.ide.common.layout.TestNode;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class DeletionHandlerTest extends TestCase {
- public void testSimple() {
- String xml = "" +
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " xmlns:tools=\"http://schemas.android.com/tools\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\"\n" +
- " tools:ignore=\"HardcodedText\" >\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button1\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignParentLeft=\"true\"\n" +
- " android:text=\"A\" />\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button2\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignBaseline=\"@+id/button1\"\n" +
- " android:layout_alignBottom=\"@+id/button1\"\n" +
- " android:layout_toRightOf=\"@+id/button1\"\n" +
- " android:text=\"B\" />\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button3\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignBottom=\"@+id/button2\"\n" +
- " android:layout_toRightOf=\"@+id/button2\"\n" +
- " android:text=\"C\" />\n" +
- "\n" +
- "</RelativeLayout>";
- TestNode targetNode = TestNode.createFromXml(xml);
- assertNotNull(targetNode);
-
- TestNode button2 = TestNode.findById(targetNode, "@+id/button2");
-
- INode layout = button2.getParent();
- List<INode> deletedNodes = Collections.<INode>singletonList(button2);
- List<INode> movedNodes = Collections.<INode>emptyList();
- assertSame(layout, targetNode);
- layout.removeChild(button2);
-
- DeletionHandler handler = new DeletionHandler(deletedNodes, movedNodes, layout);
- handler.updateConstraints();
-
- String updated = TestNode.toXml(targetNode);
- assertEquals(
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " xmlns:tools=\"http://schemas.android.com/tools\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\"\n" +
- " tools:ignore=\"HardcodedText\">\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button1\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignParentLeft=\"true\"\n" +
- " android:text=\"A\">\n" +
- " </Button>\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button3\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignBaseline=\"@+id/button1\"\n" +
- " android:layout_alignBottom=\"@+id/button1\"\n" +
- " android:layout_toRightOf=\"@+id/button1\"\n" +
- " android:text=\"C\">\n" +
- " </Button>\n" +
- "\n" +
- "</RelativeLayout>",
- updated);
- assertFalse(updated.contains(BaseViewRule.stripIdPrefix(button2.getStringAttr(ANDROID_URI,
- ATTR_ID))));
- }
-
- public void testTransitive() {
- String xml = "" +
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " xmlns:tools=\"http://schemas.android.com/tools\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\"\n" +
- " tools:ignore=\"HardcodedText\" >\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button1\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignParentLeft=\"true\"\n" +
- " android:layout_alignParentTop=\"true\"\n" +
- " android:text=\"Above\" />\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button2\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignParentLeft=\"true\"\n" +
- " android:layout_below=\"@+id/button1\"\n" +
- " android:text=\"A\" />\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button3\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignBaseline=\"@+id/button2\"\n" +
- " android:layout_alignBottom=\"@+id/button2\"\n" +
- " android:layout_toRightOf=\"@+id/button2\"\n" +
- " android:text=\"B\" />\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button4\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignBottom=\"@+id/button3\"\n" +
- " android:layout_toRightOf=\"@+id/button3\"\n" +
- " android:text=\"C\" />\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button5\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignBaseline=\"@+id/button4\"\n" +
- " android:layout_alignBottom=\"@+id/button4\"\n" +
- " android:layout_toRightOf=\"@+id/button4\"\n" +
- " android:text=\"D\" />\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button6\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignBottom=\"@+id/button5\"\n" +
- " android:layout_toRightOf=\"@+id/button5\"\n" +
- " android:text=\"E\" />\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button7\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignLeft=\"@+id/button3\"\n" +
- " android:layout_below=\"@+id/button3\"\n" +
- " android:text=\"Button\" />\n" +
- "\n" +
- " <CheckBox\n" +
- " android:id=\"@+id/checkBox1\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignBaseline=\"@+id/button7\"\n" +
- " android:layout_alignBottom=\"@+id/button7\"\n" +
- " android:layout_toRightOf=\"@+id/button7\"\n" +
- " android:text=\"CheckBox\" />\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button8\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_below=\"@+id/checkBox1\"\n" +
- " android:layout_toRightOf=\"@+id/checkBox1\"\n" +
- " android:text=\"Button\" />\n" +
- "\n" +
- "</RelativeLayout>";
- TestNode targetNode = TestNode.createFromXml(xml);
- assertNotNull(targetNode);
- TestNode button7 = TestNode.findById(targetNode, "@+id/button7");
- TestNode checkBox = TestNode.findById(targetNode, "@+id/checkBox1");
-
- INode layout = button7.getParent();
- List<INode> deletedNodes = Arrays.<INode>asList(button7, checkBox);
- List<INode> movedNodes = Collections.<INode>emptyList();
- assertSame(layout, targetNode);
- layout.removeChild(button7);
- layout.removeChild(checkBox);
-
- DeletionHandler handler = new DeletionHandler(deletedNodes, movedNodes, layout);
- handler.updateConstraints();
-
- String updated = TestNode.toXml(targetNode);
- assertEquals(
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " xmlns:tools=\"http://schemas.android.com/tools\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\"\n" +
- " tools:ignore=\"HardcodedText\">\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button1\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignParentLeft=\"true\"\n" +
- " android:layout_alignParentTop=\"true\"\n" +
- " android:text=\"Above\">\n" +
- " </Button>\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button2\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignParentLeft=\"true\"\n" +
- " android:layout_below=\"@+id/button1\"\n" +
- " android:text=\"A\">\n" +
- " </Button>\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button3\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignBaseline=\"@+id/button2\"\n" +
- " android:layout_alignBottom=\"@+id/button2\"\n" +
- " android:layout_toRightOf=\"@+id/button2\"\n" +
- " android:text=\"B\">\n" +
- " </Button>\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button4\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignBottom=\"@+id/button3\"\n" +
- " android:layout_toRightOf=\"@+id/button3\"\n" +
- " android:text=\"C\">\n" +
- " </Button>\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button5\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignBaseline=\"@+id/button4\"\n" +
- " android:layout_alignBottom=\"@+id/button4\"\n" +
- " android:layout_toRightOf=\"@+id/button4\"\n" +
- " android:text=\"D\">\n" +
- " </Button>\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button6\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignBottom=\"@+id/button5\"\n" +
- " android:layout_toRightOf=\"@+id/button5\"\n" +
- " android:text=\"E\">\n" +
- " </Button>\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button8\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignLeft=\"@+id/button3\"\n" +
- " android:layout_below=\"@+id/button3\"\n" +
- " android:text=\"Button\">\n" +
- " </Button>\n" +
- "\n" +
- "</RelativeLayout>",
- updated);
- assertFalse(updated.contains(BaseViewRule.stripIdPrefix(button7.getStringAttr(ANDROID_URI,
- ATTR_ID))));
- }
-
- public void testCenter() {
- String xml =
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " xmlns:tools=\"http://schemas.android.com/tools\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\"\n" +
- " tools:ignore=\"HardcodedText\" >\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button1\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_centerInParent=\"true\"\n" +
- " android:text=\"Button\" />\n" +
- "\n" +
- " <CheckBox\n" +
- " android:id=\"@+id/checkBox1\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_below=\"@+id/button1\"\n" +
- " android:layout_toRightOf=\"@+id/button1\"\n" +
- " android:text=\"CheckBox\" />\n" +
- "\n" +
- "</RelativeLayout>";
-
- TestNode targetNode = TestNode.createFromXml(xml);
- assertNotNull(targetNode);
- TestNode button1 = TestNode.findById(targetNode, "@+id/button1");
-
- INode layout = button1.getParent();
- List<INode> deletedNodes = Collections.<INode>singletonList(button1);
- List<INode> movedNodes = Collections.<INode>emptyList();
- assertSame(layout, targetNode);
- layout.removeChild(button1);
-
- DeletionHandler handler = new DeletionHandler(deletedNodes, movedNodes, layout);
- handler.updateConstraints();
-
- String updated = TestNode.toXml(targetNode);
- assertEquals(
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " xmlns:tools=\"http://schemas.android.com/tools\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\"\n" +
- " tools:ignore=\"HardcodedText\">\n" +
- "\n" +
- " <CheckBox\n" +
- " android:id=\"@+id/checkBox1\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_centerInParent=\"true\"\n" +
- " android:text=\"CheckBox\">\n" +
- " </CheckBox>\n" +
- "\n" +
- "</RelativeLayout>",
- updated);
- assertFalse(updated.contains(BaseViewRule.stripIdPrefix(button1.getStringAttr(ANDROID_URI,
- ATTR_ID))));
-
- }
-
- public void testMove() {
- String xml = "" +
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " xmlns:tools=\"http://schemas.android.com/tools\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\"\n" +
- " tools:ignore=\"HardcodedText\" >\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button1\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignParentLeft=\"true\"\n" +
- " android:text=\"A\" />\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button2\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignBaseline=\"@+id/button1\"\n" +
- " android:layout_alignBottom=\"@+id/button1\"\n" +
- " android:layout_toRightOf=\"@+id/button1\"\n" +
- " android:text=\"B\" />\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button3\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignBottom=\"@+id/button2\"\n" +
- " android:layout_toRightOf=\"@+id/button2\"\n" +
- " android:text=\"C\" />\n" +
- "\n" +
- "</RelativeLayout>";
- TestNode targetNode = TestNode.createFromXml(xml);
- assertNotNull(targetNode);
-
- TestNode button2 = TestNode.findById(targetNode, "@+id/button2");
-
- INode layout = button2.getParent();
- List<INode> deletedNodes = Collections.<INode>singletonList(button2);
- List<INode> movedNodes = Collections.<INode>singletonList(button2);
- assertSame(layout, targetNode);
-
- DeletionHandler handler = new DeletionHandler(deletedNodes, movedNodes, layout);
- handler.updateConstraints();
-
- String updated = TestNode.toXml(targetNode);
- assertEquals(
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " xmlns:tools=\"http://schemas.android.com/tools\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\"\n" +
- " tools:ignore=\"HardcodedText\">\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button1\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignParentLeft=\"true\"\n" +
- " android:text=\"A\">\n" +
- " </Button>\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button2\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignBaseline=\"@+id/button1\"\n" +
- " android:layout_alignBottom=\"@+id/button1\"\n" +
- " android:layout_toRightOf=\"@+id/button1\"\n" +
- " android:text=\"B\">\n" +
- " </Button>\n" +
- "\n" +
- " <Button\n" +
- " android:id=\"@+id/button3\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignBottom=\"@+id/button2\"\n" +
- " android:layout_toRightOf=\"@+id/button2\"\n" +
- " android:text=\"C\">\n" +
- " </Button>\n" +
- "\n" +
- "</RelativeLayout>",
- updated);
- assertTrue(updated.contains(BaseViewRule.stripIdPrefix(button2.getStringAttr(ANDROID_URI,
- ATTR_ID))));
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/resources/platform/AttributeInfoTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/resources/platform/AttributeInfoTest.java
deleted file mode 100644
index b56292245..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/resources/platform/AttributeInfoTest.java
+++ /dev/null
@@ -1,382 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.common.resources.platform;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.DOT_XML;
-
-import com.android.SdkConstants;
-import com.android.annotations.NonNull;
-import com.android.ide.common.api.IAttributeInfo.Format;
-import com.android.ide.common.resources.ResourceItem;
-import com.android.ide.common.resources.ResourceRepository;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
-import com.android.ide.eclipse.mock.Mocks;
-import com.android.io.IAbstractFolder;
-import com.android.io.IAbstractResource;
-import com.android.resources.ResourceType;
-import com.android.utils.StdLogger;
-import com.google.common.base.Charsets;
-import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.Multimap;
-import com.google.common.collect.Sets;
-import com.google.common.io.Files;
-
-import junit.framework.TestCase;
-
-import org.w3c.dom.Attr;
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.NamedNodeMap;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.Collection;
-import java.util.EnumSet;
-import java.util.Map;
-import java.util.Set;
-
-@SuppressWarnings("javadoc")
-public class AttributeInfoTest extends TestCase {
- public void testSimple() throws Exception {
- AttributeInfo info = new AttributeInfo("test", EnumSet.noneOf(Format.class));
- assertTrue(info.isValid("", null, null));
- assertTrue(info.isValid("a b c", null, null));
- assertTrue(info.isValid("@android foo bar", null, null));
- }
-
- public void testIsValidString() throws Exception {
- AttributeInfo info = new AttributeInfo("test", Format.STRING_SET);
- assertTrue(info.isValid("", null, null));
- assertTrue(info.isValid("a b c", null, null));
- assertTrue(info.isValid("@android foo bar", null, null));
- }
-
- public void testIsValidBoolean() throws Exception {
- AttributeInfo info = new AttributeInfo("test", Format.BOOLEAN_SET);
- assertTrue(info.isValid("true", null, null));
- assertTrue(info.isValid("false", null, null));
- assertFalse(info.isValid("", null, null));
- assertTrue(info.isValid("TRUE", null, null));
- assertTrue(info.isValid("True", null, null));
- assertTrue(info.isValid("FALSE", null, null));
- assertTrue(info.isValid("False", null, null));
- }
-
- public void testIsValidInteger() throws Exception {
- AttributeInfo info = new AttributeInfo("test", Format.INTEGER_SET);
- assertTrue(info.isValid("0", null, null));
- assertTrue(info.isValid("1", null, null));
- assertTrue(info.isValid("10", null, null));
- assertTrue(info.isValid("-10", null, null));
- assertTrue(info.isValid(Integer.toString(Integer.MAX_VALUE), null, null));
-
- assertFalse(info.isValid("", null, null));
- assertFalse(info.isValid("a", null, null));
- assertFalse(info.isValid("a1", null, null));
- assertFalse(info.isValid("1a", null, null));
- assertFalse(info.isValid("1.0", null, null));
- }
-
- public void testIsValidFloat() throws Exception {
- AttributeInfo info = new AttributeInfo("test", Format.FLOAT_SET);
- assertTrue(info.isValid("0", null, null));
- assertTrue(info.isValid("1", null, null));
- assertTrue(info.isValid("10", null, null));
- assertTrue(info.isValid("-10", null, null));
- assertTrue(info.isValid("-10.1234", null, null));
- assertTrue(info.isValid(".1", null, null));
- assertTrue(info.isValid("-.1", null, null));
- assertTrue(info.isValid("1.5e22", null, null));
- assertTrue(info.isValid(Integer.toString(Integer.MAX_VALUE), null, null));
-
- assertFalse(info.isValid("", null, null));
- assertFalse(info.isValid(".", null, null));
- assertFalse(info.isValid("-.", null, null));
- assertFalse(info.isValid("a", null, null));
- assertFalse(info.isValid("a1", null, null));
- assertFalse(info.isValid("1a", null, null));
- }
-
- public void testIsValidDimension() throws Exception {
- AttributeInfo info = new AttributeInfo("test", Format.DIMENSION_SET);
- assertTrue(info.isValid("0dp", null, null));
- assertTrue(info.isValid("1dp", null, null));
- assertTrue(info.isValid("10dip", null, null));
- assertTrue(info.isValid("-10px", null, null));
- assertTrue(info.isValid("-10.1234mm", null, null));
- assertTrue(info.isValid("14sp", null, null));
- assertTrue(info.isValid("72pt", null, null));
-
- assertFalse(info.isValid("", null, null));
- assertFalse(info.isValid("5", null, null));
- assertFalse(info.isValid("50ps", null, null));
- // Since we allow resources even when not specified in format, don't assert
- // this:
- //assertFalse(info.isValid("@dimen/foo"));
- }
-
- public void testIsValidColor() throws Exception {
- AttributeInfo info = new AttributeInfo("test", Format.COLOR_SET);
- assertTrue(info.isValid("#fff", null, null));
- assertTrue(info.isValid("#ffffff", null, null));
- assertTrue(info.isValid("#12345678", null, null));
- assertTrue(info.isValid("#abcdef00", null, null));
-
- assertFalse(info.isValid("", null, null));
- assertFalse(info.isValid("#fffffffff", null, null));
- assertFalse(info.isValid("red", null, null));
- assertFalse(info.isValid("rgb(1,2,3)", null, null));
- }
-
- public void testIsValidFraction() throws Exception {
- AttributeInfo info = new AttributeInfo("test", EnumSet.<Format>of(Format.FRACTION));
- assertTrue(info.isValid("5%", null, null));
- assertTrue(info.isValid("25%p", null, null));
-
- // We don't validate fractions accurately yet
- //assertFalse(info.isValid(""));
- //assertFalse(info.isValid("50%%"));
- //assertFalse(info.isValid("50"));
- //assertFalse(info.isValid("-2%"));
- }
-
- public void testIsValidReference() throws Exception {
- AttributeInfo info = new AttributeInfo("test", Format.REFERENCE_SET);
- assertTrue(info.isValid("@android:string/foo", null, null));
- assertTrue(info.isValid("@string/foo", null, null));
- assertTrue(info.isValid("@dimen/foo", null, null));
- assertTrue(info.isValid("@color/foo", null, null));
- assertTrue(info.isValid("@animator/foo", null, null));
- assertTrue(info.isValid("@anim/foo", null, null));
- assertTrue(info.isValid("?android:attr/textAppearanceMedium", null, null));
- assertTrue(info.isValid("?textAppearanceMedium", null, null));
-
- assertFalse(info.isValid("", null, null));
- assertFalse(info.isValid("foo", null, null));
- assertFalse(info.isValid("3.4", null, null));
- }
-
- public void testIsValidEnum() throws Exception {
- AttributeInfo info = new AttributeInfo("test", Format.ENUM_SET);
- info.setEnumValues(new String[] { "wrap_content", "match_parent" });
- assertTrue(info.isValid("wrap_content", null, null));
- assertTrue(info.isValid("match_parent", null, null));
- assertFalse(info.isValid("", null, null));
- assertFalse(info.isValid("other", null, null));
- assertFalse(info.isValid("50", null, null));
- }
-
- public void testIsValidFlag() throws Exception {
- AttributeInfo info = new AttributeInfo("test", Format.FLAG_SET);
- info.setFlagValues(new String[] { "left", "top", "right", "bottom" });
- assertTrue(info.isValid("left", null, null));
- assertTrue(info.isValid("top", null, null));
- assertTrue(info.isValid("left|top", null, null));
- assertTrue(info.isValid("", null, null));
-
- assertFalse(info.isValid("other", null, null));
- assertFalse(info.isValid("50", null, null));
- }
-
- public void testCombined1() throws Exception {
- AttributeInfo info = new AttributeInfo("test", EnumSet.<Format>of(Format.INTEGER,
- Format.REFERENCE));
- assertTrue(info.isValid("1", null, null));
- assertTrue(info.isValid("@dimen/foo", null, null));
- assertFalse(info.isValid("foo", null, null));
- }
-
- public void testCombined2() throws Exception {
- AttributeInfo info = new AttributeInfo("test", EnumSet.<Format>of(Format.COLOR,
- Format.REFERENCE));
- assertTrue(info.isValid("#ff00ff00", null, null));
- assertTrue(info.isValid("@color/foo", null, null));
- assertFalse(info.isValid("foo", null, null));
- }
-
- public void testCombined3() throws Exception {
- AttributeInfo info = new AttributeInfo("test", EnumSet.<Format>of(Format.STRING,
- Format.REFERENCE));
- assertTrue(info.isValid("test", null, null));
- assertTrue(info.isValid("@color/foo", null, null));
- }
-
- public void testCombined4() throws Exception {
- AttributeInfo info = new AttributeInfo("test", EnumSet.<Format>of(Format.ENUM,
- Format.DIMENSION));
- info.setEnumValues(new String[] { "wrap_content", "match_parent" });
- assertTrue(info.isValid("wrap_content", null, null));
- assertTrue(info.isValid("match_parent", null, null));
- assertTrue(info.isValid("50dp", null, null));
- assertFalse(info.isValid("50", null, null));
- assertFalse(info.isValid("test", null, null));
- }
-
- public void testResourcesExist() throws Exception {
- IAbstractFolder folder = Mocks.createAbstractFolder(
- SdkConstants.FD_RESOURCES, new IAbstractResource[0]);
-
- AttributeInfo info = new AttributeInfo("test", Format.REFERENCE_SET);
- TestResourceRepository projectResources = new TestResourceRepository(folder,false);
- projectResources.addResource(ResourceType.STRING, "mystring");
- projectResources.addResource(ResourceType.DIMEN, "mydimen");
- TestResourceRepository frameworkResources = new TestResourceRepository(folder, true);
- frameworkResources.addResource(ResourceType.LAYOUT, "mylayout");
-
- assertTrue(info.isValid("@string/mystring", null, null));
- assertTrue(info.isValid("@dimen/mydimen", null, null));
- assertTrue(info.isValid("@android:layout/mylayout", null, null));
- assertTrue(info.isValid("?android:attr/listPreferredItemHeigh", null, null));
-
- assertTrue(info.isValid("@string/mystring", projectResources, frameworkResources));
- assertTrue(info.isValid("@dimen/mydimen", projectResources, frameworkResources));
- assertTrue(info.isValid("@android:layout/mylayout", projectResources, frameworkResources));
-
- assertFalse(info.isValid("@android:string/mystring", projectResources,
- frameworkResources));
- assertFalse(info.isValid("@android:dimen/mydimen", projectResources, frameworkResources));
- assertFalse(info.isValid("@layout/mylayout", projectResources, frameworkResources));
- assertFalse(info.isValid("@layout/foo", projectResources, frameworkResources));
- assertFalse(info.isValid("@anim/foo", projectResources, frameworkResources));
- assertFalse(info.isValid("@android:anim/foo", projectResources, frameworkResources));
- }
-
- private class TestResourceRepository extends ResourceRepository {
- private Multimap<ResourceType, String> mResources = ArrayListMultimap.create();
-
- protected TestResourceRepository(IAbstractFolder resFolder, boolean isFrameworkRepository) {
- super(resFolder, isFrameworkRepository);
- }
-
- void addResource(ResourceType type, String name) {
- mResources.put(type, name);
- }
-
- @Override
- @NonNull
- protected ResourceItem createResourceItem(@NonNull String name) {
- fail("Not used in test");
- return null;
- }
-
- @Override
- public boolean hasResourceItem(@NonNull ResourceType type, @NonNull String name) {
- Collection<String> names = mResources.get(type);
- if (names != null) {
- return names.contains(name);
- }
-
- return false;
- }
- };
-
-
- public void testIsValid() throws Exception {
- // This test loads the full attrs.xml file and then processes a bunch of platform
- // resource file and makes sure that they're all considered valid. This helps
- // make sure that isValid() closely matches what aapt accepts.
- String sdkPath = System.getenv("ADT_SDK_SOURCE_PATH");
- assertNotNull("This test requires ADT_SDK_SOURCE_PATH to be set to point to the" +
- "SDK git repository", sdkPath);
- File sdk = new File(sdkPath);
- assertNotNull("$ADT_SDK_SOURCE_PATH (" + sdk.getPath() + ") is not a directory",
- sdk.isDirectory());
- File git = sdk.getParentFile();
- File attrsPath = new File(git, "frameworks" + File.separator + "base"
- + File.separator + "core" + File.separator + "res" + File.separator + "res"
- + File.separator + "values" + File.separator + "attrs.xml");
- assertTrue(attrsPath.getPath(), attrsPath.exists());
- AttrsXmlParser parser = new AttrsXmlParser(attrsPath.getPath(),
- new StdLogger(StdLogger.Level.VERBOSE), 1100);
- parser.preload();
- Map<String, AttributeInfo> attributeMap = parser.getAttributeMap();
- assertNotNull(attributeMap);
- assertNotNull(attributeMap.get("layout_width"));
- Set<String> seen = Sets.newHashSet();
-
- checkDir(new File(git, "packages" + File.separator + "apps"), false, attributeMap, seen);
- }
-
- private void checkDir(File dir, boolean isResourceDir,
- Map<String, AttributeInfo> map, Set<String> seen) throws IOException {
- assertTrue(dir.isDirectory());
- File[] list = dir.listFiles();
- if (list != null) {
- for (File file : list) {
- if (isResourceDir && file.isFile() && file.getPath().endsWith(DOT_XML)) {
- checkXmlFile(file, map, seen);
- } else if (file.isDirectory()) {
- checkDir(file, isResourceDir || file.getName().equals("res"), map, seen);
- }
- }
- }
- }
-
- private void checkXmlFile(File file, Map<String, AttributeInfo> map,
- Set<String> seen) throws IOException {
- String xml = Files.toString(file, Charsets.UTF_8);
- if (xml != null) {
- //Document doc = DomUtilities.parseStructuredDocument(xml);
- Document doc = DomUtilities.parseDocument(xml, false);
- if (doc != null && doc.getDocumentElement() != null) {
- checkElement(file, doc.getDocumentElement(), map, seen);
- }
- }
- }
-
- private void checkElement(File file, Element element, Map<String, AttributeInfo> map,
- Set<String> seen) {
- NamedNodeMap attributes = element.getAttributes();
- for (int i = 0, n = attributes.getLength(); i < n; i++) {
- Attr attribute = (Attr) attributes.item(i);
-
- String uri = attribute.getNamespaceURI();
- String name = attribute.getLocalName();
- String value = attribute.getValue();
- if (ANDROID_URI.equals(uri)) {
- AttributeInfo info = map.get(name);
- if (info == null) {
- System.out.println("Warning: Unknown attribute '" + name + "' in " + file);
- return;
- }
- if (!info.isValid(value, null, null)) {
- if (name.equals("duration") || name.equals("exitFadeDuration")) {
- // Already known
- return;
- }
- String message = "In file " +
- file.getPath() + ":\nCould not validate value \"" + value
- + "\" for attribute '"
- + name + "' where the attribute info has formats " + info.getFormats()
- + "\n";
- System.out.println("\n" + message);
- fail(message);
- }
- if ((value.startsWith("@") || value.startsWith("?")) &&
- !info.getFormats().contains(Format.REFERENCE)) {
- // Print out errors in attrs.xml
-
- if (!seen.contains(name)) {
- seen.add(name);
- System.out.println("\"" + name + "\" with formats " + info.getFormats()
- + " was passed a reference (" + value + ") in file " + file);
- }
- }
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/resources/platform/AttrsXmlParserManifestTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/resources/platform/AttrsXmlParserManifestTest.java
deleted file mode 100755
index 82d6acafb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/resources/platform/AttrsXmlParserManifestTest.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.resources.platform;
-
-import com.android.ide.eclipse.mock.TestLogger;
-import com.android.ide.eclipse.tests.AdtTestData;
-
-import java.util.Arrays;
-import java.util.Map;
-import java.util.TreeMap;
-
-import junit.framework.TestCase;
-
-public class AttrsXmlParserManifestTest extends TestCase {
-
- private AttrsXmlParser mParser;
- private String mFilePath;
-
- private static final String MOCK_DATA_PATH =
- "com/android/ide/eclipse/testdata/mock_manifest_attrs.xml"; //$NON-NLS-1$
-
- @Override
- public void setUp() throws Exception {
- mFilePath = AdtTestData.getInstance().getTestFilePath(MOCK_DATA_PATH);
- mParser = new AttrsXmlParser(mFilePath, new TestLogger(), 100);
- }
-
- @Override
- public void tearDown() throws Exception {
- }
-
- public void testGetOsAttrsXmlPath() throws Exception {
- assertEquals(mFilePath, mParser.getOsAttrsXmlPath());
- }
-
- private Map<String, DeclareStyleableInfo> preloadAndGetStyleables() {
- assertSame(mParser, mParser.preload());
-
- Map<String, DeclareStyleableInfo> styleableList = mParser.getDeclareStyleableList();
- // For testing purposes, we want the strings sorted
- if (!(styleableList instanceof TreeMap<?, ?>)) {
- styleableList = new TreeMap<String, DeclareStyleableInfo>(styleableList);
- }
- return styleableList;
- }
-
- public final void testPreload() throws Exception {
- Map<String, DeclareStyleableInfo> styleableList = preloadAndGetStyleables();
-
- assertEquals(
- "[AndroidManifest, " +
- "AndroidManifestActivityAlias, " +
- "AndroidManifestApplication, " +
- "AndroidManifestNewElement, " +
- "AndroidManifestNewParent, " +
- "AndroidManifestPermission" +
- "]",
- Arrays.toString(styleableList.keySet().toArray()));
- }
-
- /**
- * Tests that AndroidManifestNewParentNewElement got renamed to AndroidManifestNewElement
- * and a parent named AndroidManifestNewParent was automatically created.
- */
- public final void testNewParent() throws Exception {
- Map<String, DeclareStyleableInfo> styleableList = preloadAndGetStyleables();
-
- DeclareStyleableInfo newElement = styleableList.get("AndroidManifestNewElement");
- assertNotNull(newElement);
- assertEquals("AndroidManifestNewElement", newElement.getStyleName());
- assertEquals("[AndroidManifestNewParent]",
- Arrays.toString(newElement.getParents()));
-
- DeclareStyleableInfo newParent = styleableList.get("AndroidManifestNewParent");
- assertNotNull(newParent);
- assertEquals("[AndroidManifest]",
- Arrays.toString(newParent.getParents()));
-
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/resources/platform/AttrsXmlParserTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/resources/platform/AttrsXmlParserTest.java
deleted file mode 100644
index 883577b8a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/common/resources/platform/AttrsXmlParserTest.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.common.resources.platform;
-
-
-import com.android.ide.common.api.IAttributeInfo.Format;
-import com.android.ide.eclipse.mock.TestLogger;
-import com.android.ide.eclipse.tests.AdtTestData;
-
-import java.util.Map;
-
-import junit.framework.TestCase;
-
-public class AttrsXmlParserTest extends TestCase {
-
- private AttrsXmlParser mParser;
- private String mFilePath;
-
- private static final String MOCK_DATA_PATH =
- "com/android/ide/eclipse/testdata/mock_attrs.xml"; //$NON-NLS-1$
-
- @Override
- public void setUp() throws Exception {
- mFilePath = AdtTestData.getInstance().getTestFilePath(MOCK_DATA_PATH);
- mParser = new AttrsXmlParser(mFilePath, new TestLogger(), 100);
- }
-
- @Override
- public void tearDown() throws Exception {
- }
-
- public void testGetOsAttrsXmlPath() throws Exception {
- assertEquals(mFilePath, mParser.getOsAttrsXmlPath());
- }
-
- public final void testPreload() throws Exception {
- assertSame(mParser, mParser.preload());
- }
-
-
- public final void testLoadViewAttributes() throws Exception {
- mParser.preload();
- ViewClassInfo info = new ViewClassInfo(
- false /* isLayout */,
- "mock_android.something.Theme", //$NON-NLS-1$
- "Theme"); //$NON-NLS-1$
- mParser.loadViewAttributes(info);
-
- assertEquals("These are the standard attributes that make up a complete theme.", //$NON-NLS-1$
- info.getJavaDoc());
- AttributeInfo[] attrs = info.getAttributes();
- assertEquals(1, attrs.length);
- assertEquals("scrollbarSize", info.getAttributes()[0].getName());
- assertEquals(1, info.getAttributes()[0].getFormats().size());
- assertEquals(Format.DIMENSION, info.getAttributes()[0].getFormats().iterator().next());
- }
-
- public final void testEnumFlagValues() throws Exception {
- /* The XML being read contains:
- <!-- Standard orientation constant. -->
- <attr name="orientation">
- <!-- Defines an horizontal widget. -->
- <enum name="horizontal" value="0" />
- <!-- Defines a vertical widget. -->
- <enum name="vertical" value="1" />
- </attr>
- */
-
- mParser.preload();
- Map<String, Map<String, Integer>> attrMap = mParser.getEnumFlagValues();
- assertTrue(attrMap.containsKey("orientation"));
-
- Map<String, Integer> valueMap = attrMap.get("orientation");
- assertTrue(valueMap.containsKey("horizontal"));
- assertTrue(valueMap.containsKey("vertical"));
- assertEquals(Integer.valueOf(0), valueMap.get("horizontal"));
- assertEquals(Integer.valueOf(1), valueMap.get("vertical"));
- }
-
- public final void testDeprecated() throws Exception {
- mParser.preload();
-
- DeclareStyleableInfo dep = mParser.getDeclareStyleableList().get("DeprecatedTest");
- assertNotNull(dep);
-
- AttributeInfo[] attrs = dep.getAttributes();
- assertEquals(4, attrs.length);
-
- assertEquals("deprecated-inline", attrs[0].getName());
- assertEquals("In-line deprecated.", attrs[0].getDeprecatedDoc());
- assertEquals("Deprecated comments using delimiters.", attrs[0].getJavaDoc());
-
- assertEquals("deprecated-multiline", attrs[1].getName());
- assertEquals("Multi-line version of deprecated that works till the next tag.",
- attrs[1].getDeprecatedDoc());
- assertEquals("Deprecated comments on their own line.", attrs[1].getJavaDoc());
-
- assertEquals("deprecated-not", attrs[2].getName());
- assertEquals(null, attrs[2].getDeprecatedDoc());
- assertEquals("This attribute is not deprecated.", attrs[2].getJavaDoc());
-
- assertEquals("deprecated-no-javadoc", attrs[3].getName());
- assertEquals("There is no other javadoc here.", attrs[3].getDeprecatedDoc());
- assertEquals("", attrs[3].getJavaDoc());
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/AdtPluginTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/AdtPluginTest.java
deleted file mode 100644
index e198c6e4b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/AdtPluginTest.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt;
-
-import java.io.File;
-import java.io.StringReader;
-
-import junit.framework.TestCase;
-
-public class AdtPluginTest extends TestCase {
- public void testReaderContains() throws Exception {
- String input = "this is a test";
- assertFalse(AdtPlugin.streamContains(new StringReader(input), "hello"));
- assertTrue(AdtPlugin.streamContains(new StringReader(input), "this"));
- assertFalse(AdtPlugin.streamContains(new StringReader(input), "thiss"));
- assertTrue(AdtPlugin.streamContains(new StringReader(input), "is a"));
- assertTrue(AdtPlugin.streamContains(new StringReader("ABC ABCDAB ABCDABCDABDE"),
- "ABCDABD"));
- assertFalse(AdtPlugin.streamContains(new StringReader("ABC ABCDAB ABCDABCDABDE"),
- "ABCEABD"));
- }
-
- public void testReadStream() throws Exception {
- String input = "this is a test";
- String contents = AdtPlugin.readFile(new StringReader(input));
- assertEquals(input, contents);
- }
-
- public void testReadWriteFile() throws Exception {
- File temp = File.createTempFile("test", ".txt");
- String myContent = "this is\na test";
- AdtPlugin.writeFile(temp, myContent);
- String readBack = AdtPlugin.readFile(temp);
- assertEquals(myContent, readBack);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/AdtUtilsTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/AdtUtilsTest.java
deleted file mode 100644
index c1e94ac69..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/AdtUtilsTest.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt;
-
-import junit.framework.TestCase;
-
-import java.util.Locale;
-
-@SuppressWarnings("javadoc")
-public class AdtUtilsTest extends TestCase {
- public void testExtractClassName() {
- assertEquals("Foo", AdtUtils.extractClassName("foo"));
- assertEquals("Foobar", AdtUtils.extractClassName("foo bar"));
- assertEquals("JavasTypeSystem", AdtUtils.extractClassName("Java's Type System"));
- assertEquals("Foo", AdtUtils.extractClassName("1foo "));
- }
-
- public void testStripAllExtensions() {
- assertEquals("", AdtUtils.stripAllExtensions(""));
- assertEquals("foobar", AdtUtils.stripAllExtensions("foobar"));
- assertEquals("foobar", AdtUtils.stripAllExtensions("foobar.png"));
- assertEquals("foobar", AdtUtils.stripAllExtensions("foobar.9.png"));
- assertEquals(".profile", AdtUtils.stripAllExtensions(".profile"));
- }
-
- public void testStripLastExtension() {
- assertEquals("", AdtUtils.stripLastExtension(""));
- assertEquals("foobar", AdtUtils.stripLastExtension("foobar"));
- assertEquals("foobar", AdtUtils.stripLastExtension("foobar.png"));
- assertEquals("foobar.9", AdtUtils.stripLastExtension("foobar.9.png"));
- assertEquals(".profile", AdtUtils.stripLastExtension(".profile"));
- }
-
- public void testCapitalize() {
- assertEquals("UPPER", AdtUtils.capitalize("UPPER"));
- assertEquals("Lower", AdtUtils.capitalize("lower"));
- assertEquals("Capital", AdtUtils.capitalize("Capital"));
- assertEquals("CamelCase", AdtUtils.capitalize("camelCase"));
- assertEquals("", AdtUtils.capitalize(""));
- assertSame("Foo", AdtUtils.capitalize("Foo"));
- assertNull(null, AdtUtils.capitalize(null));
- }
-
- public void testCamelCaseToUnderlines() {
- assertEquals("", AdtUtils.camelCaseToUnderlines(""));
- assertEquals("foo", AdtUtils.camelCaseToUnderlines("foo"));
- assertEquals("foo", AdtUtils.camelCaseToUnderlines("Foo"));
- assertEquals("foo_bar", AdtUtils.camelCaseToUnderlines("FooBar"));
- assertEquals("test_xml", AdtUtils.camelCaseToUnderlines("testXML"));
- assertEquals("test_foo", AdtUtils.camelCaseToUnderlines("testFoo"));
- }
-
- public void testUnderlinesToCamelCase() {
- assertEquals("", AdtUtils.underlinesToCamelCase(""));
- assertEquals("", AdtUtils.underlinesToCamelCase("_"));
- assertEquals("Foo", AdtUtils.underlinesToCamelCase("foo"));
- assertEquals("FooBar", AdtUtils.underlinesToCamelCase("foo_bar"));
- assertEquals("FooBar", AdtUtils.underlinesToCamelCase("foo__bar"));
- assertEquals("Foo", AdtUtils.underlinesToCamelCase("foo_"));
- }
-
- public void testStripSuffix() {
- assertEquals("Foo", AdtUtils.stripSuffix("Foo", ""));
- assertEquals("Fo", AdtUtils.stripSuffix("Foo", "o"));
- assertEquals("F", AdtUtils.stripSuffix("Fo", "o"));
- assertEquals("", AdtUtils.stripSuffix("Foo", "Foo"));
- assertEquals("LinearLayout_Layout",
- AdtUtils.stripSuffix("LinearLayout_LayoutParams", "Params"));
- assertEquals("Foo", AdtUtils.stripSuffix("Foo", "Bar"));
- }
-
- public void testFormatFloatValue() throws Exception {
- assertEquals("1", AdtUtils.formatFloatAttribute(1.0f));
- assertEquals("2", AdtUtils.formatFloatAttribute(2.0f));
- assertEquals("1.50", AdtUtils.formatFloatAttribute(1.5f));
- assertEquals("1.50", AdtUtils.formatFloatAttribute(1.50f));
- assertEquals("1.51", AdtUtils.formatFloatAttribute(1.51f));
- assertEquals("1.51", AdtUtils.formatFloatAttribute(1.514542f));
- assertEquals("1.52", AdtUtils.formatFloatAttribute(1.516542f));
- assertEquals("-1.51", AdtUtils.formatFloatAttribute(-1.51f));
- assertEquals("-1", AdtUtils.formatFloatAttribute(-1f));
- }
-
- public void testFormatFloatValueLocale() throws Exception {
- // Ensure that the layout float values aren't affected by
- // locale settings, like using commas instead of of periods
- Locale originalDefaultLocale = Locale.getDefault();
-
- try {
- Locale.setDefault(Locale.FRENCH);
-
- // Ensure that this is a locale which uses a comma instead of a period:
- assertEquals("5,24", String.format("%.2f", 5.236f));
-
- // Ensure that the formatFloatAttribute is immune
- assertEquals("1.50", AdtUtils.formatFloatAttribute(1.5f));
- } finally {
- Locale.setDefault(originalDefaultLocale);
- }
- }
-
- public void testEscapeUnicodeChars() throws Exception {
- assertEquals("", AdtUtils.replaceUnicodeEscapes(""));
- assertEquals("foo bar", AdtUtils.replaceUnicodeEscapes("foo bar"));
- assertEquals("\u25C0", AdtUtils.replaceUnicodeEscapes("\\u25C0"));
- assertEquals("!\u25C0\u25C1!", AdtUtils.replaceUnicodeEscapes("!\\u25C0\\u25C1!"));
- assertEquals("\u1234\\", AdtUtils.replaceUnicodeEscapes("\\u1234\\"));
-
- assertEquals("\\U25C0", AdtUtils.replaceUnicodeEscapes("\\U25C0")); // no unicode expand
- assertEquals("\\u25C", AdtUtils.replaceUnicodeEscapes("\\u25C")); // no unicode expand
- assertEquals("\\\\u25C0", AdtUtils.replaceUnicodeEscapes("\\\\u25C0")); // escaped
- assertEquals("\\u123\\", AdtUtils.replaceUnicodeEscapes("\\u123\\")); // broken
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/build/BaseBuilderTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/build/BaseBuilderTest.java
deleted file mode 100644
index a1d658b97..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/build/BaseBuilderTest.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.build;
-
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import junit.framework.TestCase;
-
-public class BaseBuilderTest extends TestCase {
-
- public void testParseAaptOutput() {
- Pattern p = Pattern.compile( "^(.+):(\\d+):\\s(.+)$"); //$NON-NLS-1$
- String s = "C:\\java\\workspace-android\\AndroidApp\\res\\values\\strings.xml:11: WARNING: empty 'some warning text";
-
- Matcher m = p.matcher(s);
- assertEquals(true, m.matches());
- assertEquals("C:\\java\\workspace-android\\AndroidApp\\res\\values\\strings.xml", m.group(1));
- assertEquals("11", m.group(2));
- assertEquals("WARNING: empty 'some warning text", m.group(3));
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/AndroidDoubleClickStrategyTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/AndroidDoubleClickStrategyTest.java
deleted file mode 100644
index 3c0805a34..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/AndroidDoubleClickStrategyTest.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors;
-
-import org.eclipse.swt.graphics.Point;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class AndroidDoubleClickStrategyTest extends TestCase {
- public void test_getWord_plain() throws Exception {
- checkWord("^foo", "[foo]");
- checkWord("'fo^o'", "'[foo]'");
- checkWord("\"foo^\"", "\"[foo]\"");
- }
-
- public void test_getWord_resources() throws Exception {
- checkWord("'@and^roid:string/ok'", "'[@android:string/ok]'");
- checkWord("'@android^:string/ok'", "'[@android:string/ok]'");
- checkWord("'^@android:string/ok'", "'[@android:string/ok]'");
- checkWord("'@android:^string/ok'", "'[@android:string/ok]'");
- checkWord("'@android:string^/ok'", "'[@android:string/ok]'");
- checkWord("'@android:string/^ok'", "'@android:string/[ok]'");
- checkWord("'@android:string/o^k'", "'@android:string/[ok]'");
- checkWord("'@android:string/ok^'", "'@android:string/[ok]'");
- checkWord("'@string/ok^'", "'@string/[ok]'");
- checkWord("'@str^ing/ok'", "'[@string/ok]'");
- }
-
- public void test_getWord_classnames() throws Exception {
- checkWord("\"co^m.example.templatetest1\"", "\"[com.example.templatetest1]\"");
- checkWord("\"com.exam^ple.templatetest1\"", "\"[com.example.templatetest1]\"");
- checkWord("\"com.example^.templatetest1\"", "\"[com.example.templatetest1]\"");
- checkWord("\"com.example.templat^etest1\"", "\"com.example.[templatetest1]\"");
- checkWord("\"com.example.^templatetest1\"", "\"com.example.[templatetest1]\"");
- checkWord("\"com.example.templatetest1^\"", "\"com.example.[templatetest1]\"");
- checkWord("\"...^\"", "\"[...]\"");
- checkWord("\"..^.\"", "\"[...]\"");
- }
-
- private void checkWord(String before, String expected) throws Exception {
- AndroidDoubleClickStrategy strategy = new AndroidDoubleClickStrategy();
- int cursor = before.indexOf('^');
- assertTrue("Must set cursor position with ^ in " + before, cursor != -1);
- before = before.substring(0, cursor) + before.substring(cursor + 1);
- assertEquals(-1, before.indexOf('^'));
- assertEquals(-1, before.indexOf('['));
- assertEquals(-1, before.indexOf(']'));
-
- Point positions = strategy.getWord(before, cursor);
- assertNotNull(positions);
- assertTrue(positions.y >= positions.x);
- String after = before.substring(0, positions.x) + '[' +
- before.substring(positions.x, positions.y) + ']' +
- before.substring(positions.y);
- assertEquals(expected, after);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/descriptors/DescriptorsUtilsTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/descriptors/DescriptorsUtilsTest.java
deleted file mode 100644
index 03db18956..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/descriptors/DescriptorsUtilsTest.java
+++ /dev/null
@@ -1,297 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-
-package com.android.ide.eclipse.adt.internal.editors.descriptors;
-
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiDocumentNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-
-import junit.framework.TestCase;
-
-/**
- * Unit tests for DescriptorsUtils in the editors plugin
- */
-@SuppressWarnings("javadoc")
-public class DescriptorsUtilsTest extends TestCase {
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- @Override
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- public void testPrettyAttributeUiName() {
- assertEquals("", DescriptorsUtils.prettyAttributeUiName(""));
-
- assertEquals("Max width for view",
- DescriptorsUtils.prettyAttributeUiName("maxWidthForView"));
-
- assertEquals("Layout width",
- DescriptorsUtils.prettyAttributeUiName("layout_width"));
-
- // X Y and Z are capitalized when used as single words (so "T" becomes "t")
- assertEquals("Axis X", DescriptorsUtils.prettyAttributeUiName("axisX"));
- assertEquals("Axis Y", DescriptorsUtils.prettyAttributeUiName("axisY"));
- assertEquals("Axis Z", DescriptorsUtils.prettyAttributeUiName("axisZ"));
- assertEquals("Axis t", DescriptorsUtils.prettyAttributeUiName("axisT"));
-
- assertEquals("The X axis", DescriptorsUtils.prettyAttributeUiName("theXAxis"));
- assertEquals("The Y axis", DescriptorsUtils.prettyAttributeUiName("theYAxis"));
- assertEquals("The Z axis", DescriptorsUtils.prettyAttributeUiName("theZAxis"));
- assertEquals("The t axis", DescriptorsUtils.prettyAttributeUiName("theTAxis"));
-
- // Special cases for "uri" and "sdk" etc
- assertEquals("Grant URI permission",
- DescriptorsUtils.prettyAttributeUiName("grantUriPermission"));
- assertEquals("URI permission",
- DescriptorsUtils.prettyAttributeUiName("uriPermission"));
- assertEquals("Min SDK version", DescriptorsUtils.prettyAttributeUiName("minSdkVersion"));
- assertEquals("SDK version", DescriptorsUtils.prettyAttributeUiName("sdkVersion"));
- assertEquals("IME action method",
- DescriptorsUtils.prettyAttributeUiName("imeActionMethod"));
- assertEquals("VM safe mode", DescriptorsUtils.prettyAttributeUiName("vmSafeMode"));
- assertEquals("UI options", DescriptorsUtils.prettyAttributeUiName("uiOptions"));
- }
-
- public void testCapitalize() {
- assertEquals("", DescriptorsUtils.capitalize(""));
-
- assertEquals("Max Width For View",
- DescriptorsUtils.capitalize("maxWidthForView"));
-
- assertEquals("Layout Width",
- DescriptorsUtils.capitalize("layout_width"));
-
- assertEquals("Axis X", DescriptorsUtils.capitalize("axisX"));
- assertEquals("Axis Y", DescriptorsUtils.capitalize("axisY"));
- assertEquals("Axis Z", DescriptorsUtils.capitalize("axisZ"));
- assertEquals("Axis T", DescriptorsUtils.capitalize("axisT"));
-
- assertEquals("The X Axis", DescriptorsUtils.capitalize("theXAxis"));
- assertEquals("The Y Axis", DescriptorsUtils.capitalize("theYAxis"));
- assertEquals("The Z Axis", DescriptorsUtils.capitalize("theZAxis"));
- assertEquals("The T Axis", DescriptorsUtils.capitalize("theTAxis"));
-
- // Special cases for "uri" and "sdk" etc
- assertEquals("Grant URI Permission", DescriptorsUtils.capitalize("grantUriPermission"));
- assertEquals("Min SDK Version", DescriptorsUtils.capitalize("minSdkVersion"));
- assertEquals("IME Action Method", DescriptorsUtils.capitalize("imeActionMethod"));
- assertEquals("URI Permission", DescriptorsUtils.capitalize("uriPermission"));
- assertEquals("SDK Version", DescriptorsUtils.capitalize("sdkVersion"));
- assertEquals("Grant IME", DescriptorsUtils.capitalize("GrantIme"));
- assertEquals("VM Safe Mode", DescriptorsUtils.capitalize("vmSafeMode"));
- assertEquals("UI Options", DescriptorsUtils.capitalize("uiOptions"));
- }
-
- public void testFormatTooltip() {
- assertEquals("", DescriptorsUtils.formatTooltip(""));
-
- assertEquals("\"application\"",
- DescriptorsUtils.formatTooltip(
- "<code>application</code>"));
-
- assertEquals("android.content.Intent",
- DescriptorsUtils.formatTooltip(
- "{@link android.content.Intent}"));
-
- assertEquals("FLAG_ACTIVITY_SINGLE_TOP",
- DescriptorsUtils.formatTooltip(
- "{@link android.content.Intent#FLAG_ACTIVITY_SINGLE_TOP}"));
-
- assertEquals("activity-alias",
- DescriptorsUtils.formatTooltip(
- "{@link \t #AndroidManifestActivityAlias \tactivity-alias }"));
-
- assertEquals("\"permission\"",
- DescriptorsUtils.formatTooltip(
- "{@link #AndroidManifestPermission &lt;permission&gt;}"));
-
- assertEquals("and etc.",
- DescriptorsUtils.formatTooltip(
- "{@link #IntentCategory <category> and etc. }"));
-
- assertEquals("Activity.onNewIntent()",
- DescriptorsUtils.formatTooltip(
- "{@link android.app.Activity#onNewIntent Activity.onNewIntent()}"));
- }
-
- public void testFormatFormText() {
- ElementDescriptor desc = new ElementDescriptor("application");
- desc.setSdkUrl(DescriptorsUtils.MANIFEST_SDK_URL + "TagApplication");
- String docBaseUrl = "http://base";
- assertEquals("<form><li style=\"image\" value=\"image\"></li></form>", DescriptorsUtils.formatFormText("", desc, docBaseUrl));
-
- assertEquals("<form><li style=\"image\" value=\"image\"><a href=\"http://base/reference/android/R.styleable.html#TagApplication\">application</a></li></form>",
- DescriptorsUtils.formatFormText(
- "<code>application</code>",
- desc, docBaseUrl));
-
- assertEquals("<form><li style=\"image\" value=\"image\"><b>android.content.Intent</b></li></form>",
- DescriptorsUtils.formatFormText(
- "{@link android.content.Intent}",
- desc, docBaseUrl));
-
- assertEquals("<form><li style=\"image\" value=\"image\"><a href=\"http://base/reference/android/R.styleable.html#AndroidManifestPermission\">AndroidManifestPermission</a></li></form>",
- DescriptorsUtils.formatFormText(
- "{@link #AndroidManifestPermission}",
- desc, docBaseUrl));
-
- assertEquals("<form><li style=\"image\" value=\"image\"><a href=\"http://base/reference/android/R.styleable.html#AndroidManifestPermission\">\"permission\"</a></li></form>",
- DescriptorsUtils.formatFormText(
- "{@link #AndroidManifestPermission &lt;permission&gt;}",
- desc, docBaseUrl));
- }
-
- public void testGetFreeWidgetId() throws Exception {
- DocumentDescriptor documentDescriptor =
- new DocumentDescriptor("layout_doc", null); //$NON-NLS-1$
- UiDocumentNode model = new UiDocumentNode(documentDescriptor);
- UiElementNode uiRoot = model.getUiRoot();
-
- assertEquals("@+id/button1", DescriptorsUtils.getFreeWidgetId(uiRoot, "Button"));
- assertEquals("@+id/linearLayout1",
- DescriptorsUtils.getFreeWidgetId(uiRoot, "LinearLayout"));
- }
-
- public void testNeedsDefaultId() throws Exception {
- assertTrue(DescriptorsUtils.needsDefaultId(new ElementDescriptor("Button")));
- assertTrue(DescriptorsUtils.needsDefaultId(new ElementDescriptor("EditText")));
- assertTrue(DescriptorsUtils.needsDefaultId(new ElementDescriptor("TextView")));
-
- assertFalse(DescriptorsUtils.needsDefaultId(new ElementDescriptor("LinearLayout")));
- assertFalse(DescriptorsUtils.needsDefaultId(new ElementDescriptor("GridLayout")));
- assertFalse(DescriptorsUtils.needsDefaultId(new ElementDescriptor("RelativeLayout")));
- assertFalse(DescriptorsUtils.needsDefaultId(new ElementDescriptor("include")));
- assertFalse(DescriptorsUtils.needsDefaultId(new ElementDescriptor("merge")));
- assertFalse(DescriptorsUtils.needsDefaultId(new ElementDescriptor("fragment")));
- assertFalse(DescriptorsUtils.needsDefaultId(new ElementDescriptor("Space")));
- }
-
- private static ViewElementDescriptor createDesc(String name, String fqn, boolean hasChildren) {
- if (hasChildren) {
- return new ViewElementDescriptor(name, name, fqn, "", "", new AttributeDescriptor[0],
- new AttributeDescriptor[0], new ElementDescriptor[1], false);
- } else {
- return new ViewElementDescriptor(name, fqn);
- }
- }
-
- public void testCanInsertChildren() throws Exception {
- assertFalse(DescriptorsUtils.canInsertChildren(createDesc("android:Button",
- "android.widget.Button", false), null));
- assertTrue(DescriptorsUtils.canInsertChildren(createDesc("android:LinearLayout",
- "android.view.LinearLayout", true), null));
- assertFalse(DescriptorsUtils.canInsertChildren(createDesc("android:ListView",
- "android.widget.ListView", true), null));
- assertFalse(DescriptorsUtils.canInsertChildren(createDesc("android:ExpandableListView",
- "android.widget.ExpandableListView", true), null));
- assertFalse(DescriptorsUtils.canInsertChildren(createDesc("android:Gallery",
- "android.widget.Gallery", true), null));
- assertFalse(DescriptorsUtils.canInsertChildren(createDesc("android:GridView",
- "android.widget.GridView", true), null));
-
- // This isn't the Android one (missing android: namespace prefix):
- // This test is disabled since I had to remove the namespace enforcement
- // (see namespace-related comment in canInsertChildren)
- //assertTrue(DescriptorsUtils.canInsertChildren(createDesc("mynamespace:ListView",
- // "android.widget.ListView", true), null));
-
- // Custom view without known view object
- assertTrue(DescriptorsUtils.canInsertChildren(createDesc("MyView",
- "foo.bar.MyView", true), null));
-
- // Custom view with known view object that extends AdapterView
- Object view = new MyClassLoader().findClass("foo.bar.MyView").newInstance();
- assertFalse(DescriptorsUtils.canInsertChildren(createDesc("MyView",
- "foo.bar.MyView", true), view));
- }
-
- /** Test class loader which finds foo.bar.MyView extends android.widget.AdapterView */
- private static class MyClassLoader extends ClassLoader {
- public MyClassLoader() {
- super(null);
- }
-
- @Override
- protected Class<?> findClass(String name) throws ClassNotFoundException {
- if (name.equals("foo.bar.MyView")) {
- // Simple class stub compiled by javac and dumped as bytes:
- //package foo.bar;
- //public class MyView extends android.widget.AdapterView {
- // public MyView() {
- // super(null);
- // }
- //}
- byte[] classData = new byte[] {
- -54,-2,-70,-66,0,0,0,49,0,17,10,0,3,0,13,7,0,14,7,0,15,1,0,6,60,105,110,
- 105,116,62,1,0,3,40,41,86,1,0,4,67,111,100,101,1,0,15,76,105,110,101,78,
- 117,109,98,101,114,84,97,98,108,101,1,0,18,76,111,99,97,108,86,97,114,
- 105,97,98,108,101,84,97,98,108,101,1,0,4,116,104,105,115,1,0,16,76,102,
- 111,111,47,98,97,114,47,77,121,86,105,101,119,59,1,0,10,83,111,117,114,
- 99,101,70,105,108,101,1,0,11,77,121,86,105,101,119,46,106,97,118,97,12,
- 0,4,0,16,1,0,14,102,111,111,47,98,97,114,47,77,121,86,105,101,119,1,0,
- 26,97,110,100,114,111,105,100,47,119,105,100,103,101,116,47,65,100,97,
- 112,116,101,114,86,105,101,119,1,0,28,40,76,97,110,100,114,111,105,100,
- 47,99,111,110,116,101,110,116,47,67,111,110,116,101,120,116,59,41,86,0,
- 33,0,2,0,3,0,0,0,0,0,1,0,1,0,4,0,5,0,1,0,6,0,0,0,52,0,2,0,1,0,0,0,6,42,
- 1,-73,0,1,-79,0,0,0,2,0,7,0,0,0,10,0,2,0,0,0,9,0,5,0,10,0,8,0,0,0,12,0,
- 1,0,0,0,6,0,9,0,10,0,0,0,1,0,11,0,0,0,2,0,12
- };
- return defineClass("foo.bar.MyView", classData, 0, classData.length);
- }
- if (name.equals("android.widget.AdapterView")) {
- // Simple class stub compiled by javac and dumped as bytes:
- //package android.widget;
- //public class AdapterView {
- // public AdapterView(android.content.Context context) { }
- //}
- byte[] classData = new byte[] {
- -54,-2,-70,-66,0,0,0,49,0,19,10,0,3,0,15,7,0,16,7,0,17,1,0,6,60,105,110,
- 105,116,62,1,0,28,40,76,97,110,100,114,111,105,100,47,99,111,110,116,101,
- 110,116,47,67,111,110,116,101,120,116,59,41,86,1,0,4,67,111,100,101,1,0,
- 15,76,105,110,101,78,117,109,98,101,114,84,97,98,108,101,1,0,18,76,111,
- 99,97,108,86,97,114,105,97,98,108,101,84,97,98,108,101,1,0,4,116,104,105,
- 115,1,0,28,76,97,110,100,114,111,105,100,47,119,105,100,103,101,116,47,
- 65,100,97,112,116,101,114,86,105,101,119,59,1,0,7,99,111,110,116,101,120,
- 116,1,0,25,76,97,110,100,114,111,105,100,47,99,111,110,116,101,110,116,
- 47,67,111,110,116,101,120,116,59,1,0,10,83,111,117,114,99,101,70,105,108,
- 101,1,0,16,65,100,97,112,116,101,114,86,105,101,119,46,106,97,118,97,12,
- 0,4,0,18,1,0,26,97,110,100,114,111,105,100,47,119,105,100,103,101,116,
- 47,65,100,97,112,116,101,114,86,105,101,119,1,0,16,106,97,118,97,47,108,
- 97,110,103,47,79,98,106,101,99,116,1,0,3,40,41,86,0,33,0,2,0,3,0,0,0,0,0,
- 1,0,1,0,4,0,5,0,1,0,6,0,0,0,57,0,1,0,2,0,0,0,5,42,-73,0,1,-79,0,0,0,2,0,
- 7,0,0,0,6,0,1,0,0,0,8,0,8,0,0,0,22,0,2,0,0,0,5,0,9,0,10,0,0,0,0,0,5,0,11,
- 0,12,0,1,0,1,0,13,0,0,0,2,0,14
- };
- return defineClass("android.widget.AdapterView", classData, 0, classData.length);
- }
-
- return super.findClass(name);
- }
- }
-
- public void testGetBasename() {
- assertEquals("Foo", DescriptorsUtils.getBasename("Foo"));
- assertEquals("Foo", DescriptorsUtils.getBasename("foo.Foo"));
- assertEquals("String", DescriptorsUtils.getBasename("java.util.String"));
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/draw9patch/graphics/GraphicsUtilitiesTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/draw9patch/graphics/GraphicsUtilitiesTest.java
deleted file mode 100644
index 4f00097bc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/draw9patch/graphics/GraphicsUtilitiesTest.java
+++ /dev/null
@@ -1,313 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.draw9patch.graphics;
-
-import java.util.Arrays;
-
-import junit.framework.TestCase;
-
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.ImageData;
-import org.eclipse.swt.widgets.Display;
-
-public class GraphicsUtilitiesTest extends TestCase {
- private static final int MASK_ALPHA = 0xFF000000;
-
- private static final String DIR = "/com/android/ide/eclipse/testdata/draw9patch/";
-
- public void testConvertToNinePatchNull() throws Exception {
- ImageData result = GraphicsUtilities.convertToNinePatch(null);
- assertNull(result);
- }
-
- public void testConvertToNinePatch() throws Exception {
- String fileName = DIR + "no-patched.png";
- Image image = new Image(Display.getDefault(),
- getClass().getResourceAsStream(fileName));
- ImageData baseData = image.getImageData();
-
- ImageData result = GraphicsUtilities.convertToNinePatch(baseData);
-
- assertEquals(baseData.width + 2, result.width);
- assertEquals(baseData.height + 2, result.height);
-
- // horizontal
- for (int x = 0; x < result.width; x++) {
-
- // top row
- assertEquals(0x0, result.getPixel(x, 0) & MASK_ALPHA);
-
- // bottom row
- assertEquals(0x0, result.getPixel(x, result.height - 1) & MASK_ALPHA);
- }
-
- // vertical
- for (int y = 0; y < result.height; y++) {
-
- // left column
- assertEquals(0x0, result.getPixel(0, y) & MASK_ALPHA);
-
- // right column
- assertEquals(0x0, result.getPixel(result.width - 1, y) & MASK_ALPHA);
- }
- }
-
- public void testClearImageDataNull() throws Exception {
- try {
- GraphicsUtilities.clearImageData(null);
- fail();
- } catch (IllegalArgumentException e) {
- }
- }
-
- public void testClearImageData() throws Exception {
- String fileName = DIR + "no-patched.png";
- Image image = new Image(Display.getDefault(),
- getClass().getResourceAsStream(fileName));
-
- ImageData baseData = image.getImageData();
- GraphicsUtilities.clearImageData(baseData);
- for (int y = 0; y < baseData.height; y++) {
- for (int x = 0; x < baseData.width; x++) {
- assertEquals(0x000000, baseData.getPixel(x, y));
- assertEquals(0x00, baseData.getAlpha(x, y));
- }
- }
-
- }
-
- public void testCopyNull() throws Exception {
- ImageData result = GraphicsUtilities.copy(null);
- assertNull(result);
- }
-
- public void testCopy() throws Exception {
- String fileName = DIR + "no-patched.png";
- Image image = new Image(Display.getDefault(),
- getClass().getResourceAsStream(fileName));
-
- ImageData baseData = image.getImageData();
- ImageData copiedData = GraphicsUtilities.copy(baseData);
-
- assertEquals(baseData.width, copiedData.width);
- assertEquals(baseData.height, copiedData.height);
- assertEquals(baseData.depth, copiedData.depth);
- assertEquals(baseData.transparentPixel, copiedData.transparentPixel);
- assertEquals(baseData.alpha, copiedData.alpha);
- assertTrue(baseData.palette.equals(copiedData.palette));
-
- final int[] baseColors = new int[baseData.width];
- final byte[] baseAlpha = new byte[baseData.width];
-
- final int[] copiedColors = new int[copiedData.width];
- final byte[] copiedAlpha = new byte[copiedData.width];
-
- for (int y = 0; y < baseData.height; y++) {
-
- baseData.getPixels(0, y, baseData.width, baseColors, 0);
- baseData.getPixels(0, y, baseData.width, copiedColors, 0);
- assertTrue(Arrays.equals(baseColors, copiedColors));
-
- baseData.getAlphas(0, y, baseData.width, baseAlpha, 0);
- baseData.getAlphas(0, y, baseData.width, copiedAlpha, 0);
- assertTrue(Arrays.equals(baseAlpha, copiedAlpha));
-
- }
- }
-
- public void testGetVerticalPixelsIllegalArgument() throws Exception {
- String fileName = DIR + "no-patched.png";
- Image image = new Image(Display.getDefault(),
- getClass().getResourceAsStream(fileName));
-
- ImageData baseData = image.getImageData();
- int[] temp = new int[baseData.width];
-
- // data must not be null
- try {
- GraphicsUtilities.getVerticalPixels(null, 0, 0, 1, temp);
- fail();
- } catch (IllegalArgumentException e) {
- }
-
- // out must not be null
- try {
- GraphicsUtilities.getVerticalPixels(baseData, 0, 0, 1, null);
- fail();
- } catch (IllegalArgumentException e) {
- }
-
- // out length must be > height
- try {
- GraphicsUtilities.getVerticalPixels(baseData, 0, 0, 1, new int[0]);
- fail();
- } catch (IllegalArgumentException e) {
- }
-
- // x must be > 0
- try {
- GraphicsUtilities.getVerticalPixels(baseData, -1, 0, 1, temp);
- fail();
- } catch (IllegalArgumentException e) {
- }
-
- // y must be > 0
- try {
- GraphicsUtilities.getVerticalPixels(baseData, 0, -1, 1, temp);
- fail();
- } catch (IllegalArgumentException e) {
- }
-
- // height must be >= 0
- try {
- GraphicsUtilities.getVerticalPixels(baseData, 0, 0, 0, temp);
- fail();
- } catch (IllegalArgumentException e) {
- }
-
- // argument x must be < data.width
- try {
- GraphicsUtilities.getVerticalPixels(baseData, baseData.width, 0, baseData.height, temp);
- fail();
- } catch (IllegalArgumentException e) {
- }
-
- // argument y must be < data.height
- try {
- GraphicsUtilities
- .getVerticalPixels(baseData, 0, baseData.height, baseData.height, temp);
- fail();
- } catch (IllegalArgumentException e) {
- }
-
- // argument height must be > (y + data.height)
- try {
- GraphicsUtilities.getVerticalPixels(baseData, 0, 1, baseData.height, temp);
- fail();
- } catch (IllegalArgumentException e) {
- }
-
- }
-
- public void testGetVerticalPixels() throws Exception {
- String fileName = DIR + "no-patched.png";
- Image image = new Image(Display.getDefault(),
- getClass().getResourceAsStream(fileName));
-
- ImageData baseData = image.getImageData();
- int[] temp = new int[baseData.width];
-
- GraphicsUtilities.getVerticalPixels(baseData, 0, 0, baseData.height, temp);
-
- int height = baseData.height;
- for (int y = 0; y < height; y++) {
- assertEquals(baseData.getPixel(0, y), temp[y]);
- }
- }
-
- public void testGetHorizontalPixelsIllegalArgument() throws Exception {
- String fileName = DIR + "no-patched.png";
- Image image = new Image(Display.getDefault(),
- getClass().getResourceAsStream(fileName));
-
- ImageData baseData = image.getImageData();
- int[] temp = new int[baseData.width];
-
- // data must not be null
- try {
- GraphicsUtilities.getHorizontalPixels(null, 0, 0, 1, temp);
- fail();
- } catch (IllegalArgumentException e) {
- }
-
- // out must not be null
- try {
- GraphicsUtilities.getHorizontalPixels(baseData, 0, 0, 1, null);
- fail();
- } catch (IllegalArgumentException e) {
- }
-
- // out length must be > width
- try {
- GraphicsUtilities.getHorizontalPixels(baseData, 0, 0, 1, new int[0]);
- fail();
- } catch (IllegalArgumentException e) {
- }
-
- // x must be > 0
- try {
- GraphicsUtilities.getHorizontalPixels(baseData, -1, 0, 1, temp);
- fail();
- } catch (IllegalArgumentException e) {
- }
-
- // y must be > 0
- try {
- GraphicsUtilities.getHorizontalPixels(baseData, 0, -1, 1, temp);
- fail();
- } catch (IllegalArgumentException e) {
- }
-
- // width must be >= 0
- try {
- GraphicsUtilities.getHorizontalPixels(baseData, 0, 0, 0, temp);
- fail();
- } catch (IllegalArgumentException e) {
- }
-
- // argument x must be < data.width
- try {
- GraphicsUtilities
- .getHorizontalPixels(baseData, baseData.width, 0, baseData.width, temp);
- fail();
- } catch (IllegalArgumentException e) {
- }
-
- // argument y must be < data.height
- try {
- GraphicsUtilities
- .getHorizontalPixels(baseData, 0, baseData.height, baseData.width, temp);
- fail();
- } catch (IllegalArgumentException e) {
- }
-
- // argument width must be > (x + data.width)
- try {
- GraphicsUtilities.getHorizontalPixels(baseData, 1, 0, baseData.width, temp);
- fail();
- } catch (IllegalArgumentException e) {
- }
-
- }
-
- public void testGetHorizontalPixels() throws Exception {
- String fileName = DIR + "no-patched.png";
- Image image = new Image(Display.getDefault(),
- getClass().getResourceAsStream(fileName));
-
- ImageData baseData = image.getImageData();
- int[] temp = new int[baseData.width];
-
- GraphicsUtilities.getHorizontalPixels(baseData, 0, 0, baseData.width, temp);
-
- int width = baseData.width;
- for (int x = 0; x < width; x++) {
- assertEquals(baseData.getPixel(x, 0), temp[x]);
- }
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/draw9patch/graphics/NinePatchedImageTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/draw9patch/graphics/NinePatchedImageTest.java
deleted file mode 100644
index 72c929618..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/draw9patch/graphics/NinePatchedImageTest.java
+++ /dev/null
@@ -1,914 +0,0 @@
-/*
- * Copyright (C) 2013 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.draw9patch.graphics;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-import org.eclipse.swt.graphics.ImageData;
-import org.eclipse.swt.graphics.Point;
-import org.eclipse.swt.graphics.Rectangle;
-
-import com.android.ide.eclipse.adt.internal.editors.draw9patch.graphics.NinePatchedImage.Chunk;
-import com.android.ide.eclipse.adt.internal.editors.draw9patch.graphics.NinePatchedImage.Projection;
-import com.android.ide.eclipse.adt.internal.editors.draw9patch.graphics.NinePatchedImage.Tick;
-
-public class NinePatchedImageTest extends TestCase {
-
- private static final String DIR = "/com/android/ide/eclipse/testdata/draw9patch/";
-
- public void testReadNoPatchedImage() throws Exception {
- String fileName = DIR + "no-patched.png";
- NinePatchedImage image = new NinePatchedImage(getClass()
- .getResourceAsStream(fileName), fileName);
- assertNotNull(image);
-
- ImageData data = image.getImageData();
- int width = data.width;
- int height = data.height;
-
- assertEquals(72, width);
- assertEquals(50, height);
-
- assertFalse(image.hasNinePatchExtension());
- }
-
- public void testReadNoPatchedInteraceImage() throws Exception {
- String fileName = DIR + "no-patched-interlace.png";
- NinePatchedImage image = new NinePatchedImage(getClass()
- .getResourceAsStream(fileName), fileName);
- assertNotNull(image);
-
- ImageData data = image.getImageData();
- int width = data.width;
- int height = data.height;
-
- assertEquals(72, width);
- assertEquals(50, height);
-
- assertFalse(image.hasNinePatchExtension());
- }
-
- public void testConvert9PatchedImage() throws Exception {
- String fileName = DIR + "no-patched.png";
- NinePatchedImage image = new NinePatchedImage(getClass()
- .getResourceAsStream(fileName), fileName);
- assertNotNull(image);
-
- ImageData data = image.getImageData();
- int width = data.width;
- int height = data.height;
-
- assertEquals(72, width);
- assertEquals(50, height);
-
- assertFalse(image.hasNinePatchExtension());
-
- image.convertToNinePatch();
-
- data = image.getImageData();
- width = data.width;
- height = data.height;
-
- // increased patch size
- assertEquals(72 + 2, width);
- assertEquals(50 + 2, height);
-
- assertTrue(image.hasNinePatchExtension());
- assertFalse(image.isDirty());
-
- // initialized patches
- List<Tick> horizontalPatches = image.getHorizontalPatches();
- List<Tick> verticalPatches = image.getVerticalPatches();
- assertEquals(1, horizontalPatches.size());
- assertEquals(1, verticalPatches.size());
-
- // initialized contents area
- List<Tick> horizontalContentsArea = image.getHorizontalContents();
- List<Tick> verticalContentsArea = image.getVerticalContents();
- assertEquals(1, horizontalContentsArea.size());
- assertEquals(1, verticalContentsArea.size());
-
- // content area rectangle
- Rectangle contentsArea = image.getContentArea();
- assertEquals(new Rectangle(1, 1, width - 2, height - 2), contentsArea);
- }
-
- public void testReadInvalidPatchedImageCorners() throws Exception {
-
- // top-left
- String fileName = DIR + "invalid-patched1.9.png";
- NinePatchedImage image = new NinePatchedImage(getClass()
- .getResourceAsStream(fileName), fileName);
- assertNotNull(image);
- assertTrue(image.hasNinePatchExtension());
- assertFalse(image.ensure9Patch());
-
- // top-right
- fileName = DIR + "invalid-patched2.9.png";
- image = new NinePatchedImage(getClass()
- .getResourceAsStream(fileName), fileName);
- assertNotNull(image);
- assertTrue(image.hasNinePatchExtension());
- assertFalse(image.ensure9Patch());
-
- // bottom-left
- fileName = DIR + "invalid-patched3.9.png";
- image = new NinePatchedImage(getClass()
- .getResourceAsStream(fileName), fileName);
- assertNotNull(image);
- assertTrue(image.hasNinePatchExtension());
- assertFalse(image.ensure9Patch());
-
- // bottom-right
- fileName = DIR + "invalid-patched4.9.png";
- image = new NinePatchedImage(getClass()
- .getResourceAsStream(fileName), fileName);
- assertNotNull(image);
- assertTrue(image.hasNinePatchExtension());
- assertFalse(image.ensure9Patch());
- }
-
- public void testReadInvalidPatchedImageLine() throws Exception {
-
- // top
- String fileName = DIR + "invalid-patched5.9.png";
- NinePatchedImage image = new NinePatchedImage(getClass()
- .getResourceAsStream(fileName), fileName);
- assertNotNull(image);
- assertTrue(image.hasNinePatchExtension());
- assertFalse(image.ensure9Patch());
-
- // right
- fileName = DIR + "invalid-patched6.9.png";
- image = new NinePatchedImage(getClass()
- .getResourceAsStream(fileName), fileName);
- assertNotNull(image);
- assertTrue(image.hasNinePatchExtension());
- assertFalse(image.ensure9Patch());
-
- // bottom
- fileName = DIR + "invalid-patched7.9.png";
- image = new NinePatchedImage(getClass()
- .getResourceAsStream(fileName), fileName);
- assertNotNull(image);
- assertTrue(image.hasNinePatchExtension());
- assertFalse(image.ensure9Patch());
-
- // left
- fileName = DIR + "invalid-patched8.9.png";
- image = new NinePatchedImage(getClass()
- .getResourceAsStream(fileName), fileName);
- assertNotNull(image);
- assertTrue(image.hasNinePatchExtension());
- assertFalse(image.ensure9Patch());
- }
-
- public void testEnsure9PatchIgnoreInvalidPixels() throws Exception {
- // top
- String fileName = DIR + "invalid-patched5.9.png";
- NinePatchedImage image = new NinePatchedImage(getClass()
- .getResourceAsStream(fileName), fileName);
- assertNotNull(image);
-
- // invalid pixel
- int invalidPixel = image.getImageData().getPixel(33, 0);
- assertTrue(0x0 != invalidPixel);
-
- assertTrue(image.hasNinePatchExtension());
- assertFalse(image.ensure9Patch());
-
- // ensure9path() ignored invalid pixels
- int invalidPixelAlpha = image.getImageData().getAlpha(33, 0);
- assertEquals(0x00, invalidPixelAlpha);
- }
-
- public void test9Patch1() throws Exception {
- String fileName = DIR + "patched1.9.png";
- NinePatchedImage image = new NinePatchedImage(getClass()
- .getResourceAsStream(fileName), fileName);
- assertNotNull(image);
-
- assertTrue(image.hasNinePatchExtension());
- assertTrue(image.ensure9Patch());
-
- // patches
- List<Tick> horizontalPatches = image.getHorizontalPatches();
- List<Tick> verticalPatches = image.getVerticalPatches();
- assertEquals(3, horizontalPatches.size());
- assertEquals(3, verticalPatches.size());
-
- Chunk[][] chunks = null;
- chunks = image.getChunks(chunks);
-
- // vertical chunk size
- assertEquals(3, chunks.length);
-
- // horizontal chunk size
- for (int i = 0; i < chunks.length; i++) {
- assertEquals(3, chunks[i].length);
- }
-
- Chunk c = null;
- Rectangle rect = null;
-
- // Row 1
- c = chunks[0][0];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL | Chunk.TYPE_VERTICAL, c.type);
- assertEquals(1, rect.x);
- assertEquals(1, rect.y);
- assertEquals(1, rect.width);
- assertEquals(1, rect.height);
-
- c = chunks[0][1];
- rect = c.rect;
- assertEquals(Chunk.TYPE_VERTICAL, c.type);
- assertEquals(2, rect.x);
- assertEquals(1, rect.y);
- assertEquals(70, rect.width);
- assertEquals(1, rect.height);
-
- c = chunks[0][2];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL | Chunk.TYPE_VERTICAL, c.type);
- assertEquals(72, rect.x);
- assertEquals(1, rect.y);
- assertEquals(1, rect.width);
- assertEquals(1, rect.height);
-
- // Row 2
- c = chunks[1][0];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL, c.type);
- assertEquals(1, rect.x);
- assertEquals(2, rect.y);
- assertEquals(1, rect.width);
- assertEquals(48, rect.height);
-
- c = chunks[1][1];
- rect = c.rect;
- assertEquals(Chunk.TYPE_FIXED, c.type);
- assertEquals(2, rect.x);
- assertEquals(2, rect.y);
- assertEquals(70, rect.width);
- assertEquals(48, rect.height);
-
- c = chunks[1][2];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL, c.type);
- assertEquals(72, rect.x);
- assertEquals(2, rect.y);
- assertEquals(1, rect.width);
- assertEquals(48, rect.height);
-
- // Row 3
- c = chunks[2][0];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL | Chunk.TYPE_VERTICAL, c.type);
- assertEquals(1, rect.x);
- assertEquals(50, rect.y);
- assertEquals(1, rect.width);
- assertEquals(1, rect.height);
-
- c = chunks[2][1];
- rect = c.rect;
- assertEquals(Chunk.TYPE_VERTICAL, c.type);
- assertEquals(2, rect.x);
- assertEquals(50, rect.y);
- assertEquals(70, rect.width);
- assertEquals(1, rect.height);
-
- c = chunks[2][2];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL | Chunk.TYPE_VERTICAL, c.type);
- assertEquals(72, rect.x);
- assertEquals(50, rect.y);
- assertEquals(1, rect.width);
- assertEquals(1, rect.height);
- }
-
- public void test9Patch2() throws Exception {
- String fileName = DIR + "patched2.9.png";
- NinePatchedImage image = new NinePatchedImage(getClass()
- .getResourceAsStream(fileName), fileName);
- assertNotNull(image);
-
- assertTrue(image.hasNinePatchExtension());
- assertTrue(image.ensure9Patch());
-
- // patches
- List<Tick> horizontalPatches = image.getHorizontalPatches();
- List<Tick> verticalPatches = image.getVerticalPatches();
- assertEquals(5, horizontalPatches.size());
- assertEquals(7, verticalPatches.size());
-
- NinePatchedImage.Chunk[][] chunks = null;
- chunks = image.getChunks(chunks);
-
- // vertical chunk size
- assertEquals(7, chunks.length);
-
- // horizontal chunk size
- for (int i = 0; i < chunks.length; i++) {
- assertEquals(5, chunks[i].length);
- }
-
- NinePatchedImage.Chunk c = null;
- Rectangle rect = null;
-
- // Row 1
- c = chunks[0][0];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL | Chunk.TYPE_VERTICAL, c.type);
- assertEquals(1, rect.x);
- assertEquals(1, rect.y);
- assertEquals(1, rect.width);
- assertEquals(1, rect.height);
-
- c = chunks[0][1];
- rect = c.rect;
- assertEquals(Chunk.TYPE_VERTICAL, c.type);
- assertEquals(2, rect.x);
- assertEquals(1, rect.y);
- assertEquals(34, rect.width);
- assertEquals(1, rect.height);
-
- c = chunks[0][2];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL | Chunk.TYPE_VERTICAL, c.type);
- assertEquals(36, rect.x);
- assertEquals(1, rect.y);
- assertEquals(1, rect.width);
- assertEquals(1, rect.height);
-
- c = chunks[0][3];
- rect = c.rect;
- assertEquals(Chunk.TYPE_VERTICAL, c.type);
- assertEquals(37, rect.x);
- assertEquals(1, rect.y);
- assertEquals(35, rect.width);
- assertEquals(1, rect.height);
-
- c = chunks[0][4];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL | Chunk.TYPE_VERTICAL, c.type);
- assertEquals(72, rect.x);
- assertEquals(1, rect.y);
- assertEquals(1, rect.width);
- assertEquals(1, rect.height);
-
- // Row 2
- c = chunks[1][0];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL, c.type);
- assertEquals(1, rect.x);
- assertEquals(2, rect.y);
- assertEquals(1, rect.width);
- assertEquals(7, rect.height);
-
- c = chunks[1][1];
- rect = c.rect;
- assertEquals(Chunk.TYPE_FIXED, c.type);
- assertEquals(2, rect.x);
- assertEquals(2, rect.y);
- assertEquals(34, rect.width);
- assertEquals(7, rect.height);
-
- c = chunks[1][2];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL, c.type);
- assertEquals(36, rect.x);
- assertEquals(2, rect.y);
- assertEquals(1, rect.width);
- assertEquals(7, rect.height);
-
- c = chunks[1][3];
- rect = c.rect;
- assertEquals(Chunk.TYPE_FIXED, c.type);
- assertEquals(37, rect.x);
- assertEquals(2, rect.y);
- assertEquals(35, rect.width);
- assertEquals(7, rect.height);
-
- c = chunks[1][4];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL, c.type);
- assertEquals(72, rect.x);
- assertEquals(2, rect.y);
- assertEquals(1, rect.width);
- assertEquals(7, rect.height);
-
- // Row 3
- c = chunks[2][0];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL | Chunk.TYPE_VERTICAL, c.type);
- assertEquals(1, rect.x);
- assertEquals(9, rect.y);
- assertEquals(1, rect.width);
- assertEquals(4, rect.height);
-
- c = chunks[2][1];
- rect = c.rect;
- assertEquals(Chunk.TYPE_VERTICAL, c.type);
- assertEquals(2, rect.x);
- assertEquals(9, rect.y);
- assertEquals(34, rect.width);
- assertEquals(4, rect.height);
-
- c = chunks[2][2];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL | Chunk.TYPE_VERTICAL, c.type);
- assertEquals(36, rect.x);
- assertEquals(9, rect.y);
- assertEquals(1, rect.width);
- assertEquals(4, rect.height);
-
- c = chunks[2][3];
- rect = c.rect;
- assertEquals(Chunk.TYPE_VERTICAL, c.type);
- assertEquals(37, rect.x);
- assertEquals(9, rect.y);
- assertEquals(35, rect.width);
- assertEquals(4, rect.height);
-
- c = chunks[2][4];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL | Chunk.TYPE_VERTICAL, c.type);
- assertEquals(72, rect.x);
- assertEquals(9, rect.y);
- assertEquals(1, rect.width);
- assertEquals(4, rect.height);
-
- // Row 4
- c = chunks[3][0];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL, c.type);
- assertEquals(1, rect.x);
- assertEquals(13, rect.y);
- assertEquals(1, rect.width);
- assertEquals(13, rect.height);
-
- c = chunks[3][1];
- rect = c.rect;
- assertEquals(Chunk.TYPE_FIXED, c.type);
- assertEquals(2, rect.x);
- assertEquals(13, rect.y);
- assertEquals(34, rect.width);
- assertEquals(13, rect.height);
-
- c = chunks[3][2];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL, c.type);
- assertEquals(36, rect.x);
- assertEquals(13, rect.y);
- assertEquals(1, rect.width);
- assertEquals(13, rect.height);
-
- c = chunks[3][3];
- rect = c.rect;
- assertEquals(Chunk.TYPE_FIXED, c.type);
- assertEquals(37, rect.x);
- assertEquals(13, rect.y);
- assertEquals(35, rect.width);
- assertEquals(13, rect.height);
-
- c = chunks[3][4];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL, c.type);
- assertEquals(72, rect.x);
- assertEquals(13, rect.y);
- assertEquals(1, rect.width);
- assertEquals(13, rect.height);
-
- // Row 5
- c = chunks[4][0];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL | Chunk.TYPE_VERTICAL, c.type);
- assertEquals(1, rect.x);
- assertEquals(26, rect.y);
- assertEquals(1, rect.width);
- assertEquals(12, rect.height);
-
- c = chunks[4][1];
- rect = c.rect;
- assertEquals(Chunk.TYPE_VERTICAL, c.type);
- assertEquals(2, rect.x);
- assertEquals(26, rect.y);
- assertEquals(34, rect.width);
- assertEquals(12, rect.height);
-
- c = chunks[4][2];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL | Chunk.TYPE_VERTICAL, c.type);
- assertEquals(36, rect.x);
- assertEquals(26, rect.y);
- assertEquals(1, rect.width);
- assertEquals(12, rect.height);
-
- c = chunks[4][3];
- rect = c.rect;
- assertEquals(Chunk.TYPE_VERTICAL, c.type);
- assertEquals(37, rect.x);
- assertEquals(26, rect.y);
- assertEquals(35, rect.width);
- assertEquals(12, rect.height);
-
- c = chunks[4][4];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL | Chunk.TYPE_VERTICAL, c.type);
- assertEquals(72, rect.x);
- assertEquals(26, rect.y);
- assertEquals(1, rect.width);
- assertEquals(12, rect.height);
-
- // Row 6
- c = chunks[5][0];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL, c.type);
- assertEquals(1, rect.x);
- assertEquals(38, rect.y);
- assertEquals(1, rect.width);
- assertEquals(12, rect.height);
-
- c = chunks[5][1];
- rect = c.rect;
- assertEquals(Chunk.TYPE_FIXED, c.type);
- assertEquals(2, rect.x);
- assertEquals(38, rect.y);
- assertEquals(34, rect.width);
- assertEquals(12, rect.height);
-
- c = chunks[5][2];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL, c.type);
- assertEquals(36, rect.x);
- assertEquals(38, rect.y);
- assertEquals(1, rect.width);
- assertEquals(12, rect.height);
-
- c = chunks[5][3];
- rect = c.rect;
- assertEquals(Chunk.TYPE_FIXED, c.type);
- assertEquals(37, rect.x);
- assertEquals(38, rect.y);
- assertEquals(35, rect.width);
- assertEquals(12, rect.height);
-
- c = chunks[5][4];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL, c.type);
- assertEquals(72, rect.x);
- assertEquals(38, rect.y);
- assertEquals(1, rect.width);
- assertEquals(12, rect.height);
-
- // Row 7
- c = chunks[6][0];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL | Chunk.TYPE_VERTICAL, c.type);
- assertEquals(1, rect.x);
- assertEquals(50, rect.y);
- assertEquals(1, rect.width);
- assertEquals(1, rect.height);
-
- c = chunks[6][1];
- rect = c.rect;
- assertEquals(Chunk.TYPE_VERTICAL, c.type);
- assertEquals(2, rect.x);
- assertEquals(50, rect.y);
- assertEquals(34, rect.width);
- assertEquals(1, rect.height);
-
- c = chunks[6][2];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL | Chunk.TYPE_VERTICAL, c.type);
- assertEquals(36, rect.x);
- assertEquals(50, rect.y);
- assertEquals(1, rect.width);
- assertEquals(1, rect.height);
-
- c = chunks[6][3];
- rect = c.rect;
- assertEquals(Chunk.TYPE_VERTICAL, c.type);
- assertEquals(37, rect.x);
- assertEquals(50, rect.y);
- assertEquals(35, rect.width);
- assertEquals(1, rect.height);
-
- c = chunks[6][4];
- rect = c.rect;
- assertEquals(Chunk.TYPE_HORIZONTAL | Chunk.TYPE_VERTICAL, c.type);
- assertEquals(72, rect.x);
- assertEquals(50, rect.y);
- assertEquals(1, rect.width);
- assertEquals(1, rect.height);
- }
-
- public void testContentArea() throws Exception {
- String fileName = DIR + "content-area.9.png";
- NinePatchedImage image = new NinePatchedImage(getClass()
- .getResourceAsStream(fileName), fileName);
- assertNotNull(image);
-
- assertTrue(image.hasNinePatchExtension());
- assertTrue(image.ensure9Patch());
-
- // contents area
- List<Tick> horizontalContentsArea = image.getHorizontalContents();
- List<Tick> verticalContentsArea = image.getVerticalContents();
- assertEquals(3, horizontalContentsArea.size());
- assertEquals(3, verticalContentsArea.size());
-
- // content area rectangle
- Rectangle contentsArea = image.getContentArea();
- assertEquals(new Rectangle(19, 13, 35, 25), contentsArea);
- }
-
- public void testContentAreaOneDot() throws Exception {
- String fileName = DIR + "content-area-one-dot.9.png";
- NinePatchedImage image = new NinePatchedImage(getClass()
- .getResourceAsStream(fileName), fileName);
- assertNotNull(image);
-
- assertTrue(image.hasNinePatchExtension());
- assertTrue(image.ensure9Patch());
-
- // contents area
- List<Tick> horizontalContentsArea = image.getHorizontalContents();
- List<Tick> verticalContentsArea = image.getVerticalContents();
- assertEquals(3, horizontalContentsArea.size());
- assertEquals(3, verticalContentsArea.size());
-
- // content area rectangle
- Rectangle contentsArea = image.getContentArea();
- assertEquals(new Rectangle(19, 13, 1, 1), contentsArea);
- }
-
- public void testContentAreaTwoDots() throws Exception {
- String fileName = DIR + "content-area-two-dots.9.png";
- NinePatchedImage image = new NinePatchedImage(getClass()
- .getResourceAsStream(fileName), fileName);
- assertNotNull(image);
-
- assertTrue(image.hasNinePatchExtension());
- assertTrue(image.ensure9Patch());
-
- // contents area
- List<Tick> horizontalContentsArea = image.getHorizontalContents();
- List<Tick> verticalContentsArea = image.getVerticalContents();
- assertEquals(5, horizontalContentsArea.size());
- assertEquals(5, verticalContentsArea.size());
-
- // content area rectangle
- Rectangle contentsArea = image.getContentArea();
- assertEquals(new Rectangle(19, 13, 35, 25), contentsArea);
-
- String fileName2 = DIR + "content-area.9.png";
- NinePatchedImage image2 = new NinePatchedImage(getClass()
- .getResourceAsStream(fileName2), fileName2);
- assertNotNull(image2);
-
- assertTrue(image2.hasNinePatchExtension());
- assertTrue(image2.ensure9Patch());
-
- // content area rectangle
- Rectangle contentsArea2 = image2.getContentArea();
- assertEquals(contentsArea2, contentsArea);
- }
-
- public void testBadPatches() throws Exception {
- String fileName = DIR + "patched-with-badpatches.9.png";
- NinePatchedImage image = new NinePatchedImage(getClass()
- .getResourceAsStream(fileName), fileName);
- assertNotNull(image);
-
- assertTrue(image.hasNinePatchExtension());
- assertTrue(image.ensure9Patch());
-
- Chunk[][] chunks = null;
- chunks = image.getChunks(chunks);
-
- // vertical chunk size
- assertEquals(5, chunks.length);
-
- // horizontal chunk size
- for (int i = 0; i < chunks.length; i++) {
- assertEquals(7, chunks[i].length);
- }
-
- chunks = image.getCorruptedChunks(chunks);
-
- Chunk c = null;
-
- // collect bad patches
- List<Point> badPatches = new ArrayList<Point>(5 * 7);
- for (int y = 0; y < chunks.length; y++) {
- for (int x = 0; x < chunks[0].length; x++) {
- c = chunks[y][x];
- if ((c.type & Chunk.TYPE_CORRUPT) != 0x0) {
- badPatches.add(new Point(y, x));
- }
- }
- }
-
- assertEquals(15, badPatches.size());
-
- assertTrue(badPatches.contains(new Point(0, 3)));
-
- assertTrue(badPatches.contains(new Point(1, 1)));
- assertTrue(badPatches.contains(new Point(1, 2)));
- assertTrue(badPatches.contains(new Point(1, 3)));
- assertTrue(badPatches.contains(new Point(1, 4)));
- assertTrue(badPatches.contains(new Point(1, 5)));
-
- assertTrue(badPatches.contains(new Point(2, 1)));
- assertTrue(badPatches.contains(new Point(2, 5)));
-
- assertTrue(badPatches.contains(new Point(3, 0)));
- assertTrue(badPatches.contains(new Point(3, 1)));
- assertTrue(badPatches.contains(new Point(3, 5)));
- assertTrue(badPatches.contains(new Point(3, 6)));
-
- assertTrue(badPatches.contains(new Point(4, 1)));
- assertTrue(badPatches.contains(new Point(4, 3)));
- assertTrue(badPatches.contains(new Point(4, 5)));
- }
-
- public void testProjection() throws Exception {
- // top
- String fileName = DIR + "patched3.9.png";
- NinePatchedImage image = new NinePatchedImage(getClass()
- .getResourceAsStream(fileName), fileName);
- assertNotNull(image);
-
- assertTrue(image.hasNinePatchExtension());
- assertTrue(image.ensure9Patch());
-
- ImageData data = image.getImageData();
- assertEquals(72 + 2, data.width);
- assertEquals(50 + 2, data.height);
-
- int width = 72 * 2;
- int height = 50 * 2;
-
- Chunk[][] chunks = null;
- chunks = image.getChunks(chunks);
-
- Projection[][] projections = null;
- projections = image.getProjections(width, height, projections);
-
- assertEquals(chunks.length, projections.length);
- for (int i = 0; i < chunks.length; i++) {
- assertEquals(chunks[i].length, projections[i].length);
- }
-
- for (int y = 0; y < projections.length; y++) {
- for (int x = 0; x < projections[y].length; x++) {
- assertEquals(projections[y][x].src, chunks[y][x].rect);
-
- // If chunk type is FIXED. Same projection size as original
- // chunk.
- if (projections[y][x].chunk.type == Chunk.TYPE_FIXED) {
- assertEquals(projections[y][x].dest.width, chunks[y][x].rect.width);
- assertEquals(projections[y][x].dest.height, chunks[y][x].rect.height);
- }
- }
- }
-
- Projection p = null;
- Rectangle rect = null;
-
- // Check start position
- p = projections[0][0];
-
- // src position start from 1, 9-patch row and column included.
- assertEquals(1, p.src.x);
- assertEquals(1, p.src.y);
-
- // dest position start from 0, 9-patch row and column ignored.
- assertEquals(0, p.dest.x);
- assertEquals(0, p.dest.y);
-
- // row 1
- p = projections[0][0];
- rect = p.dest;
- assertEquals(0, rect.x);
- assertEquals(0, rect.y);
- assertEquals(74, rect.width);
- assertEquals(5, rect.height);
-
- p = projections[0][1];
- rect = p.dest;
- assertEquals(74, rect.x);
- assertEquals(0, rect.y);
- assertEquals(62, rect.width);
- assertEquals(5, rect.height);
-
- p = projections[0][2];
- rect = p.dest;
- assertEquals(136, rect.x);
- assertEquals(0, rect.y);
- assertEquals(8, rect.width);
- assertEquals(5, rect.height);
-
- // row 2
- p = projections[1][0];
- rect = p.dest;
- assertEquals(0, rect.x);
- assertEquals(5, rect.y);
- assertEquals(74, rect.width);
- assertEquals(24, rect.height);
-
- p = projections[1][1];
- rect = p.dest;
- assertEquals(74, rect.x);
- assertEquals(5, rect.y);
- assertEquals(62, rect.width);
- assertEquals(24, rect.height);
-
- p = projections[1][2];
- rect = p.dest;
- assertEquals(136, rect.x);
- assertEquals(5, rect.y);
- assertEquals(8, rect.width);
- assertEquals(24, rect.height);
-
- // row 3
- p = projections[2][0];
- rect = p.dest;
- assertEquals(0, rect.x);
- assertEquals(29, rect.y);
- assertEquals(74, rect.width);
- assertEquals(58, rect.height);
-
- p = projections[2][1];
- rect = p.dest;
- assertEquals(74, rect.x);
- assertEquals(29, rect.y);
- assertEquals(62, rect.width);
- assertEquals(58, rect.height);
-
- p = projections[2][2];
- rect = p.dest;
- assertEquals(136, rect.x);
- assertEquals(29, rect.y);
- assertEquals(8, rect.width);
- assertEquals(58, rect.height);
-
- // row 4
- p = projections[3][0];
- rect = p.dest;
- assertEquals(0, rect.x);
- assertEquals(87, rect.y);
- assertEquals(74, rect.width);
- assertEquals(13, rect.height);
-
- p = projections[3][1];
- rect = p.dest;
- assertEquals(74, rect.x);
- assertEquals(87, rect.y);
- assertEquals(62, rect.width);
- assertEquals(13, rect.height);
-
- p = projections[3][2];
- rect = p.dest;
- assertEquals(136, rect.x);
- assertEquals(87, rect.y);
- assertEquals(8, rect.width);
- assertEquals(13, rect.height);
- }
-
- public void testReadLayoutBoundsOnlyImage() throws Exception {
- String fileName = DIR + "layout-bounds-only.9.png";
- NinePatchedImage image = new NinePatchedImage(getClass()
- .getResourceAsStream(fileName), fileName);
- assertNotNull(image);
-
- ImageData data = image.getImageData();
- int width = data.width;
- int height = data.height;
-
- assertEquals(74, width);
- assertEquals(52, height);
-
- assertTrue(image.hasNinePatchExtension());
- assertTrue(image.ensure9Patch());
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/formatting/AndroidXmlFormattingStrategyTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/formatting/AndroidXmlFormattingStrategyTest.java
deleted file mode 100644
index 9c7e25d4b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/formatting/AndroidXmlFormattingStrategyTest.java
+++ /dev/null
@@ -1,335 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.formatting;
-
-import com.android.ide.common.xml.XmlFormatPreferences;
-
-import org.eclipse.jface.text.BadLocationException;
-import org.eclipse.jface.text.Document;
-import org.eclipse.text.edits.MalformedTreeException;
-import org.eclipse.text.edits.ReplaceEdit;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class AndroidXmlFormattingStrategyTest extends TestCase {
- // In the given before document, replace in the range replaceStart to replaceEnd
- // the formatted string, and assert that it's identical to the given after string
- private void check(String before, int replaceStart, int replaceEnd, String formatted,
- String expected, XmlFormatPreferences prefs)
- throws MalformedTreeException, BadLocationException {
- Document document = new Document();
- document.set(before);
- ReplaceEdit edit = AndroidXmlFormattingStrategy.createReplaceEdit(document, replaceStart,
- replaceEnd, formatted, prefs);
- assertNotNull(edit);
- edit.apply(document);
- String contents = document.get();
- // Ensure that we don't have any mangled CRLFs
- char prev = 0;
- boolean haveCrlf = false;
- for (int i = 0, n = contents.length(); i < n; i++) {
- char c = contents.charAt(i);
- if (c == '\r') {
- haveCrlf = true;
- }
- if (!(c != '\r' || prev != '\r')) {
- fail("Mangled document: Found adjacent \\r's starting at " + i
- + ": " + contents.substring(i - 1, Math.min(contents.length(), i + 10))
- + "...");
- }
- if (haveCrlf && c == '\n' && prev != '\r') {
- fail("Mangled document: In a CRLF document, found \\n without preceeding \\r");
- }
-
- prev = c;
- }
-
- assertEquals(expected, contents);
- }
-
- // In the given before document, replace the range indicated by [ and ] with the given
- // formatted string, and assert that it's identical to the given after string
- private void check(
- String before, String insert, String expected,
- XmlFormatPreferences prefs)
- throws MalformedTreeException, BadLocationException {
- int replaceStart = before.indexOf('[');
- assertTrue(replaceStart != -1);
- before = before.substring(0, replaceStart) + before.substring(replaceStart + 1);
-
- int replaceEnd = before.indexOf(']');
- assertTrue(replaceEnd != -1);
- before = before.substring(0, replaceEnd) + before.substring(replaceEnd + 1);
-
- check(before, replaceStart, replaceEnd, insert, expected, prefs);
- }
-
- public void test1() throws Exception {
- check(
- // Before
- "<root>\n" +
- "[ <element/>\n" +
- " <second/>\n" +
- "]\n" +
- "</root>\n",
-
- // Insert
- " <element/>\n" +
- " <second/>\n",
-
- // After
- "<root>\n" +
- " <element/>\n" +
- " <second/>\n" +
- "\n" +
- "</root>\n",
-
- XmlFormatPreferences.defaults());
- }
-
- public void test2() throws Exception {
- XmlFormatPreferences prefs = XmlFormatPreferences.defaults();
- prefs.removeEmptyLines = true;
-
- check(
- // Before
- "<root>\n" +
- "\n" +
- "\n" +
- "[ <element/>\n" +
- " <second/>\n" +
- "]\n" +
- "\n" +
- "\n" +
- "</root>\n",
-
- // Insert
- " <element/>\n" +
- " <second/>\n",
-
- // After
- "<root>\n" +
- " <element/>\n" +
- " <second/>\n" +
- "</root>\n",
-
- prefs);
- }
-
- public void test3() throws Exception {
- XmlFormatPreferences prefs = XmlFormatPreferences.defaults();
- prefs.removeEmptyLines = true;
-
- check(
- // Before
- "<root>\n" +
- "\n" +
- "\n" +
- " [<element/>\n" +
- " <second/>]\n" +
- "\n" +
- "\n" +
- "\n" +
- "</root>\n",
-
- // Insert
- " <element/>\n" +
- " <second/>",
-
- // After
- "<root>\n" +
- " <element/>\n" +
- " <second/>\n" +
- "</root>\n",
-
- prefs);
- }
-
- public void test4() throws Exception {
- check(
- "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " xmlns:tools=\"http://schemas.android.com/tools\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\" >\n" +
- "\n" +
- " [<TextView\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_centerHorizontal=\"true\"\n" +
- " android:layout_centerVertical=\"true\"\n" +
- " android:text=\"foo\"\n" +
- " tools:context=\".MainActivity\" />]\n" +
- "\n" +
- "</RelativeLayout>\n",
-
- // Insert
- "\n" +
- " <TextView\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_centerHorizontal=\"true\"\n" +
- " android:layout_centerVertical=\"true\"\n" +
- " android:text=\"foo\"\n" +
- " tools:context=\".MainActivity\" />\n",
-
- // After
- "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " xmlns:tools=\"http://schemas.android.com/tools\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\" >\n" +
- "\n" +
- " <TextView\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_centerHorizontal=\"true\"\n" +
- " android:layout_centerVertical=\"true\"\n" +
- " android:text=\"foo\"\n" +
- " tools:context=\".MainActivity\" />\n" +
- "\n" +
- "</RelativeLayout>\n",
-
- XmlFormatPreferences.defaults());
- }
-
- public void testCrLf1() throws Exception {
- check(
- // Before
- "<root>\r\n" +
- "[ <element/>\r\n" +
- " <second/>\r\n" +
- "]\r\n" +
- "</root>\r\n",
-
- // Insert
- " <element/>\r\n" +
- " <second/>\r\n",
-
- // After
- "<root>\r\n" +
- " <element/>\r\n" +
- " <second/>\r\n" +
- "\r\n" +
- "</root>\r\n",
-
- XmlFormatPreferences.defaults());
- }
-
- public void testCrLf2() throws Exception {
- XmlFormatPreferences prefs = XmlFormatPreferences.defaults();
- prefs.removeEmptyLines = true;
-
- check(
- // Before
- "<root>\r\n" +
- "\r\n" +
- "\r\n" +
- "[ <element/>\r\n" +
- " <second/>\r\n" +
- "]\r\n" +
- "\r\n" +
- "\r\n" +
- "</root>\r\n",
-
- // Insert
- " <element/>\r\n" +
- " <second/>\r\n",
-
- // After
- "<root>\r\n" +
- " <element/>\r\n" +
- " <second/>\r\n" +
- "</root>\r\n",
-
- prefs);
- }
-
- public void testCrLf3() throws Exception {
- XmlFormatPreferences prefs = XmlFormatPreferences.defaults();
- prefs.removeEmptyLines = true;
-
- check(
- // Before
- "<root>\r\n" +
- "\r\n" +
- "\r\n" +
- " [<element/>\r\n" +
- " <second/>]\r\n" +
- "\r\n" +
- "\r\n" +
- "\r\n" +
- "</root>\r\n",
-
- // Insert
- " <element/>\r\n" +
- " <second/>",
-
- // After
- "<root>\r\n" +
- " <element/>\r\n" +
- " <second/>\r\n" +
- "</root>\r\n",
-
- prefs);
- }
-
-
- public void testCrlf4() throws Exception {
- check(
- "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\r\n" +
- " xmlns:tools=\"http://schemas.android.com/tools\"\r\n" +
- " android:layout_width=\"match_parent\"\r\n" +
- " android:layout_height=\"match_parent\" >\r\n" +
- "\r\n" +
- " [<TextView\r\n" +
- " android:layout_width=\"wrap_content\"\r\n" +
- " android:layout_height=\"wrap_content\"\r\n" +
- " android:layout_centerHorizontal=\"true\"\r\n" +
- " android:layout_centerVertical=\"true\"\r\n" +
- " android:text=\"foo\"\r\n" +
- " tools:context=\".MainActivity\" />]\r\n" +
- "\r\n" +
- "</RelativeLayout>\r\n",
-
- // Insert
- "\r\n" +
- " <TextView\r\n" +
- " android:layout_width=\"wrap_content\"\r\n" +
- " android:layout_height=\"wrap_content\"\r\n" +
- " android:layout_centerHorizontal=\"true\"\r\n" +
- " android:layout_centerVertical=\"true\"\r\n" +
- " android:text=\"foo\"\r\n" +
- " tools:context=\".MainActivity\" />\r\n",
-
- // After
- "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\r\n" +
- " xmlns:tools=\"http://schemas.android.com/tools\"\r\n" +
- " android:layout_width=\"match_parent\"\r\n" +
- " android:layout_height=\"match_parent\" >\r\n" +
- "\r\n" +
- " <TextView\r\n" +
- " android:layout_width=\"wrap_content\"\r\n" +
- " android:layout_height=\"wrap_content\"\r\n" +
- " android:layout_centerHorizontal=\"true\"\r\n" +
- " android:layout_centerVertical=\"true\"\r\n" +
- " android:text=\"foo\"\r\n" +
- " tools:context=\".MainActivity\" />\r\n" +
- "\r\n" +
- "</RelativeLayout>\r\n",
-
- XmlFormatPreferences.defaults());
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/ExplodeRenderingHelperTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/ExplodeRenderingHelperTest.java
deleted file mode 100644
index 0e528674a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/ExplodeRenderingHelperTest.java
+++ /dev/null
@@ -1,256 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.internal.editors.mock.MockXmlNode;
-
-import org.w3c.dom.Node;
-
-import java.util.HashSet;
-
-import junit.framework.TestCase;
-
-public class ExplodeRenderingHelperTest extends TestCase {
-
- private final HashSet<String> mLayoutNames = new HashSet<String>();
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
-
- mLayoutNames.add("LinearLayout");
- mLayoutNames.add("RelativeLayout");
- }
-
- public void testSingleHorizontalLinearLayout() {
- // Single layout, horizontal, 2 buttons.
- MockXmlNode layout = createLinearLayout(true /*horizontal*/,
- new MockXmlNode[] { createButton(), createButton()} );
-
- ExplodedRenderingHelper helper = new ExplodedRenderingHelper(layout, mLayoutNames);
- assertEquals(1, helper.getHeightPadding());
- assertEquals(1, helper.getWidthPadding());
- }
-
- public void testSingleVerticalLinearLayout() {
- // Single layout, horizontal, with 2 buttons.
- // LinearLayout(H:[Button Button])
- MockXmlNode layout = createLinearLayout(false /*horizontal*/,
- new MockXmlNode[] { createButton(), createButton()} );
-
- ExplodedRenderingHelper helper = new ExplodedRenderingHelper(layout, mLayoutNames);
- assertEquals(1, helper.getWidthPadding());
- assertEquals(1, helper.getHeightPadding());
- }
-
- public void testEmbeddedLinearLayouts() {
- /*
- * LinearLayout(vertical):
- * LinearLayout(H:[Button Button])
- * LinearLayout(H:[Button Button Button])
- *
- * Result should be 2 in x, 3 in y
- */
- MockXmlNode layout = createLinearLayout(false /*horizontal*/,
- new MockXmlNode[] {
- createLinearLayout(true /*horizontal*/,
- new MockXmlNode[] { createButton(), createButton()}),
- createLinearLayout(true /*horizontal*/,
- new MockXmlNode[] { createButton(), createButton(), createButton()}),
- } );
-
- ExplodedRenderingHelper helper = new ExplodedRenderingHelper(layout, mLayoutNames);
- assertEquals(2, helper.getWidthPadding());
- assertEquals(3, helper.getHeightPadding());
- }
-
- public void testSimpleRelativeLayoutWithOneLinearLayouts() {
- /*
- * RelativeLayout:
- * LinearLayout(H:[Button Button])
- *
- * Result should be 2 in x, 2 in y
- */
- MockXmlNode layout = createRelativeLayout(
- new MockXmlNode[] {
- createLinearLayout(true /*horizontal*/,
- new MockXmlNode[] { createButton(), createButton()}),
- } );
-
- ExplodedRenderingHelper helper = new ExplodedRenderingHelper(layout, mLayoutNames);
- assertEquals(2, helper.getWidthPadding());
- assertEquals(2, helper.getHeightPadding());
- }
-
- public void /*test*/RelativeLayoutWithVerticalLinearLayouts() {
- //FIXME: Reenable once the relative layout are properly supported.
- /*
- * Children of the relative layouts, one below the other.
- * Each with only buttons in them.
- * RelativeLayout:
- * LinearLayout(H:[Button Button])
- * ^
- * LinearLayout(H:[Button Button])
- *
- * Result should be 2 in x, 3 in y
- */
-
- // create the linearlayouts.
- MockXmlNode linear1 = createLinearLayout(true /*horizontal*/,
- new MockXmlNode[] { createButton(), createButton()});
- linear1.addAttributes(SdkConstants.NS_RESOURCES, "id", "@+id/linear1");
-
- MockXmlNode linear2 = createLinearLayout(true /*horizontal*/,
- new MockXmlNode[] { createButton(), createButton()});
- linear2.addAttributes(SdkConstants.NS_RESOURCES, "id", "@+id/linear2");
-
- // position linear2 below linear1
- linear2.addAttributes(SdkConstants.NS_RESOURCES, "layout_below", "@+id/linear1");
-
-
- MockXmlNode layout = createRelativeLayout(new MockXmlNode[] { linear1, linear2 } );
-
- ExplodedRenderingHelper helper = new ExplodedRenderingHelper(layout, mLayoutNames);
- assertEquals(2, helper.getWidthPadding());
- assertEquals(3, helper.getHeightPadding());
- }
-
- public void /*test*/RelativeLayoutWithVerticalLinearLayouts2() {
- //FIXME: Reenable once the relative layout are properly supported.
- /*
- * Children of the relative layouts, one above the other.
- * Each with only buttons in them.
- * RelativeLayout:
- * LinearLayout(H:[Button Button])
- * v
- * LinearLayout(H:[Button Button])
- *
- * Result should be 2 in x, 3 in y
- */
-
- // create the linearlayouts.
- MockXmlNode linear1 = createLinearLayout(true /*horizontal*/,
- new MockXmlNode[] { createButton(), createButton() } );
- linear1.addAttributes(SdkConstants.NS_RESOURCES, "id", "@+id/linear1");
-
- MockXmlNode linear2 = createLinearLayout(true /*horizontal*/,
- new MockXmlNode[] { createButton(), createButton() } );
- linear2.addAttributes(SdkConstants.NS_RESOURCES, "id", "@+id/linear2");
-
- // position linear2 below linear1
- linear2.addAttributes(SdkConstants.NS_RESOURCES, "layout_above", "@+id/linear1");
-
-
- MockXmlNode layout = createRelativeLayout(new MockXmlNode[] { linear1, linear2 } );
-
- ExplodedRenderingHelper helper = new ExplodedRenderingHelper(layout, mLayoutNames);
- assertEquals(2, helper.getWidthPadding());
- assertEquals(3, helper.getHeightPadding());
- }
-
- public void /*test*/ComplexRelativeLayout() {
- //FIXME: Reenable once the relative layout are properly supported.
- /*
- * RelativeLayout:
- *
- * < LinearLayout1(V: [button]) > LinearLayout2(V: [button])
- * v
- * Button1 > LinearLayout3(V: [button]) < Button2
- * v
- * < LinearLayout4(V: [button])
- * ^
- * <LinearLayout5(V: [button])
- *
- * Result should be 4 in x, 5 in y
- */
-
- // create the elements
- MockXmlNode button1 = createButton();
- button1.addAttributes(SdkConstants.NS_RESOURCES, "id", "@+id/button1");
-
- MockXmlNode button2 = createButton();
- button2.addAttributes(SdkConstants.NS_RESOURCES, "id", "@+id/button2");
-
- MockXmlNode linear1 = createLinearLayout(true /*horizontal*/,
- new MockXmlNode[] { createButton() } );
- linear1.addAttributes(SdkConstants.NS_RESOURCES, "id", "@+id/linear1");
-
- MockXmlNode linear2 = createLinearLayout(true /*horizontal*/,
- new MockXmlNode[] { createButton() } );
- linear2.addAttributes(SdkConstants.NS_RESOURCES, "id", "@+id/linear2");
-
- MockXmlNode linear3 = createLinearLayout(true /*horizontal*/,
- new MockXmlNode[] { createButton() } );
- linear3.addAttributes(SdkConstants.NS_RESOURCES, "id", "@+id/linear3");
-
- MockXmlNode linear4 = createLinearLayout(true /*horizontal*/,
- new MockXmlNode[] { createButton() } );
- linear4.addAttributes(SdkConstants.NS_RESOURCES, "id", "@+id/linear4");
-
- MockXmlNode linear5 = createLinearLayout(true /*horizontal*/,
- new MockXmlNode[] { createButton() } );
- linear5.addAttributes(SdkConstants.NS_RESOURCES, "id", "@+id/linear5");
-
-
- // link them
- button1.addAttributes(SdkConstants.NS_RESOURCES, "layout_toLeftOf", "@+id/linear3");
-
- button2.addAttributes(SdkConstants.NS_RESOURCES, "layout_toRightOf", "@+id/linear3");
-
- linear1.addAttributes(SdkConstants.NS_RESOURCES, "layout_toRightOf", "@+id/linear3");
- linear1.addAttributes(SdkConstants.NS_RESOURCES, "layout_toLeftOf", "@+id/linear2");
- linear1.addAttributes(SdkConstants.NS_RESOURCES, "layout_above", "@+id/button2");
-
- linear3.addAttributes(SdkConstants.NS_RESOURCES, "layout_above", "@+id/linear4");
-
- linear4.addAttributes(SdkConstants.NS_RESOURCES, "layout_toRightOf", "@+id/button1");
-
- linear5.addAttributes(SdkConstants.NS_RESOURCES, "layout_toRightOf", "@+id/linear4");
- linear5.addAttributes(SdkConstants.NS_RESOURCES, "layout_below", "@+id/linear4");
-
- MockXmlNode layout = createRelativeLayout(
- new MockXmlNode[] {
- button1, button2, linear1, linear2, linear3, linear4, linear5 } );
-
- ExplodedRenderingHelper helper = new ExplodedRenderingHelper(layout, mLayoutNames);
- assertEquals(4, helper.getWidthPadding());
- assertEquals(5, helper.getHeightPadding());
- }
-
-
- // ----- helper to deal with mocks
-
- private MockXmlNode createButton() {
- return new MockXmlNode(null, "Button", Node.ELEMENT_NODE, null);
- }
-
- private MockXmlNode createLinearLayout(boolean horizontal, MockXmlNode[] children) {
- MockXmlNode layout = new MockXmlNode(null, "LinearLayout", Node.ELEMENT_NODE, children);
-
- layout.addAttributes(SdkConstants.NS_RESOURCES, "orientation",
- horizontal ? "horizontal" : "vertical");
-
- return layout;
- }
-
- private MockXmlNode createRelativeLayout(MockXmlNode[] children) {
- MockXmlNode layout = new MockXmlNode(null, "RelativeLayout", Node.ELEMENT_NODE, children);
-
- return layout;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/UiElementPullParserTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/UiElementPullParserTest.java
deleted file mode 100644
index 5cac663d7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/UiElementPullParserTest.java
+++ /dev/null
@@ -1,256 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout;
-
-import com.android.SdkConstants;
-import com.android.ide.common.api.IAttributeInfo.Format;
-import com.android.ide.common.resources.platform.AttributeInfo;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.TextAttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.mock.MockXmlNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.resources.Density;
-
-import org.w3c.dom.Node;
-import org.xmlpull.v1.XmlPullParser;
-import org.xmlpull.v1.XmlPullParserException;
-
-import java.util.HashMap;
-
-import junit.framework.TestCase;
-
-public class UiElementPullParserTest extends TestCase {
-
- private UiElementNode ui;
- private HashMap<String, String> button1Map;
- private HashMap<String, String> button2Map;
- private HashMap<String, String> textMap;
-
- private TextAttributeDescriptor createTextAttrDesc(String xmlName) {
- return new TextAttributeDescriptor(
- xmlName, // xmlLocalName
- SdkConstants.NS_RESOURCES,
- new AttributeInfo(xmlName, Format.STRING_SET)
- );
- }
-
- @Override
- protected void setUp() throws Exception {
- // set up some basic descriptors.
- // We have button, textview, linear layout, relative layout.
- // only the layouts have children (all 4 descriptors possible)
- // Also add some dummy attributes.
- ElementDescriptor buttonDescriptor = new ElementDescriptor("Button", "Button", "", "",
- new AttributeDescriptor[] {
- createTextAttrDesc("name"),
- createTextAttrDesc("text"),
- },
- new ElementDescriptor[] {}, false);
-
- ElementDescriptor textDescriptor = new ElementDescriptor("TextView", "TextView", "", "",
- new AttributeDescriptor[] {
- createTextAttrDesc("name"),
- createTextAttrDesc("text"),
- },
- new ElementDescriptor[] {}, false);
-
- ElementDescriptor linearDescriptor = new ElementDescriptor("LinearLayout", "Linear Layout",
- "", "",
- new AttributeDescriptor[] {
- createTextAttrDesc("orientation"),
- },
- new ElementDescriptor[] { }, false);
-
- ElementDescriptor relativeDescriptor = new ElementDescriptor("RelativeLayout",
- "Relative Layout", "", "",
- new AttributeDescriptor[] {
- createTextAttrDesc("orientation"),
- },
- new ElementDescriptor[] { }, false);
-
- ElementDescriptor[] a = new ElementDescriptor[] {
- buttonDescriptor, textDescriptor, linearDescriptor, relativeDescriptor
- };
-
- linearDescriptor.setChildren(a);
- relativeDescriptor.setChildren(a);
-
- // document descriptor
- ElementDescriptor rootDescriptor = new ElementDescriptor("root", "", "", "",
- new AttributeDescriptor[] { }, a, false);
-
-
- ui = new UiElementNode(rootDescriptor);
-
- /* create a dummy XML file.
- * <LinearLayout android:orientation="vertical">
- * <Button android:name="button1" android:text="button1text"/>
- * <RelativeLayout android:orientation="toto">
- * <Button android:name="button2" android:text="button2text"/>
- * <TextView android:name="text1" android:text="text1text"/>
- * </RelativeLayout>
- * </LinearLayout>
- */
- MockXmlNode button1 = new MockXmlNode(null /* namespace */, "Button", Node.ELEMENT_NODE,
- null);
- button1.addAttributes(SdkConstants.NS_RESOURCES, "name", "button1");
- button1.addAttributes(SdkConstants.NS_RESOURCES, "text", "button1text");
-
- // create a map of the attributes we add to the multi-attribute nodes so that
- // we can more easily test the values when we parse the XML.
- // This is due to some attributes showing in a certain order for a node and in a different
- // order in another node. Since the order doesn't matter, we just simplify the test.
- button1Map = new HashMap<String, String>();
- button1Map.put("name", "button1");
- button1Map.put("text", "button1text");
-
- MockXmlNode button2 = new MockXmlNode(null /* namespace */, "Button", Node.ELEMENT_NODE,
- null);
- button2.addAttributes(SdkConstants.NS_RESOURCES, "name", "button2");
- button2.addAttributes(SdkConstants.NS_RESOURCES, "text", "button2text");
-
- button2Map = new HashMap<String, String>();
- button2Map.put("name", "button2");
- button2Map.put("text", "button2text");
-
- MockXmlNode text = new MockXmlNode(null /* namespace */, "TextView", Node.ELEMENT_NODE,
- null);
- text.addAttributes(SdkConstants.NS_RESOURCES, "name", "text1");
- text.addAttributes(SdkConstants.NS_RESOURCES, "text", "text1text");
-
- textMap = new HashMap<String, String>();
- textMap.put("name", "text1");
- textMap.put("text", "text1text");
-
- MockXmlNode relative = new MockXmlNode(null /* namespace */, "RelativeLayout",
- Node.ELEMENT_NODE, new MockXmlNode[] { button2, text });
- relative.addAttributes(SdkConstants.NS_RESOURCES, "orientation", "toto");
-
- MockXmlNode linear = new MockXmlNode(null /* namespace */, "LinearLayout",
- Node.ELEMENT_NODE, new MockXmlNode[] { button1, relative });
- linear.addAttributes(SdkConstants.NS_RESOURCES, "orientation", "vertical");
-
- MockXmlNode root = new MockXmlNode(null /* namespace */, "root", Node.ELEMENT_NODE,
- new MockXmlNode[] { linear });
-
- // put the namespace/prefix in place
- root.setPrefix(SdkConstants.NS_RESOURCES, "android");
-
- // load the xml into the UiElementNode
- ui.loadFromXmlNode(root);
-
- super.setUp();
- }
-
- @Override
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- public void testParser() {
- try {
- // wrap the parser around the ui element node, and start parsing
- UiElementPullParser parser = new UiElementPullParser(
- ui, // model
- false, // explodedView
- null, // explodeNodes
- Density.MEDIUM, // density (default from ConfigurationComposite)
- null // iProject
- );
-
- assertEquals(XmlPullParser.START_DOCUMENT, parser.getEventType());
-
- // top level Linear layout
- assertEquals(XmlPullParser.START_TAG, parser.next());
- assertEquals("LinearLayout", parser.getName());
- assertEquals(1, parser.getAttributeCount());
- assertEquals("orientation", parser.getAttributeName(0));
- assertEquals(SdkConstants.NS_RESOURCES, parser.getAttributeNamespace(0));
- assertEquals("android", parser.getAttributePrefix(0));
- assertEquals("vertical", parser.getAttributeValue(0));
-
- // Button
- assertEquals(XmlPullParser.START_TAG, parser.next());
- assertEquals("Button", parser.getName());
- assertEquals(2, parser.getAttributeCount());
- check(parser, 0, button1Map);
- check(parser, 1, button1Map);
- // end of button
- assertEquals(XmlPullParser.END_TAG, parser.next());
-
- // Relative Layout
- assertEquals(XmlPullParser.START_TAG, parser.next());
- assertEquals("RelativeLayout", parser.getName());
- assertEquals(1, parser.getAttributeCount());
- assertEquals("orientation", parser.getAttributeName(0));
- assertEquals(SdkConstants.NS_RESOURCES, parser.getAttributeNamespace(0));
- assertEquals("android", parser.getAttributePrefix(0));
- assertEquals("toto", parser.getAttributeValue(0));
-
- // Button
- assertEquals(XmlPullParser.START_TAG, parser.next());
- assertEquals("Button", parser.getName());
- assertEquals(2, parser.getAttributeCount());
- check(parser, 0, button2Map);
- check(parser, 1, button2Map);
- // end of button
- assertEquals(XmlPullParser.END_TAG, parser.next());
-
- // TextView
- assertEquals(XmlPullParser.START_TAG, parser.next());
- assertEquals("TextView", parser.getName());
- assertEquals(2, parser.getAttributeCount());
- check(parser, 0, textMap);
- check(parser, 1, textMap);
- // end of TextView
- assertEquals(XmlPullParser.END_TAG, parser.next());
-
- // end of RelativeLayout
- assertEquals(XmlPullParser.END_TAG, parser.next());
-
-
- // end of top level linear layout
- assertEquals(XmlPullParser.END_TAG, parser.next());
-
- assertEquals(XmlPullParser.END_DOCUMENT, parser.next());
- } catch (XmlPullParserException e) {
- e.printStackTrace();
- assertTrue(false);
- }
- }
-
- /**
- * Receives a {@link XmlPullParser} at the START_TAG level, and checks the i-th attribute
- * to be present in the {@link HashMap} with the proper (name, value)
- * @param parser
- * @param i
- * @param map
- */
- private void check(UiElementPullParser parser, int i, HashMap<String, String> map) {
- String name = parser.getAttributeName(i);
- String value = parser.getAttributeValue(i);
-
- String referenceValue = map.get(name);
- assertNotNull(referenceValue);
- assertEquals(referenceValue, value);
-
- assertEquals(SdkConstants.NS_RESOURCES, parser.getAttributeNamespace(i));
- assertEquals("android", parser.getAttributePrefix(i));
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ConfigurationTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ConfigurationTest.java
deleted file mode 100644
index 5b07d7b88..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/configuration/ConfigurationTest.java
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.configuration;
-
-import static com.android.ide.common.resources.configuration.LocaleQualifier.FAKE_VALUE;
-
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.common.resources.configuration.LocaleQualifier;
-import com.android.resources.Density;
-import com.android.sdklib.devices.Device;
-import com.android.sdklib.devices.DeviceManager;
-import com.android.sdklib.devices.Screen;
-import com.android.utils.StdLogger;
-import com.google.common.collect.Lists;
-
-import java.lang.reflect.Constructor;
-import java.util.Collection;
-import java.util.EnumSet;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class ConfigurationTest extends TestCase {
- private Configuration createConfiguration() throws Exception {
- // Using reflection instead since we want to pass null to
- // a constructor marked with @NonNull, so the test won't compile.
- Constructor<Configuration> constructor =
- Configuration.class.getDeclaredConstructor(ConfigurationChooser.class);
- constructor.setAccessible(true);
- ConfigurationChooser chooser = null;
- return constructor.newInstance(chooser);
- }
-
- public void test() throws Exception {
- Configuration configuration = createConfiguration();
- assertNotNull(configuration);
- configuration.setTheme("@style/Theme");
- assertEquals("@style/Theme", configuration.getTheme());
-
- DeviceManager deviceManager = DeviceManager.createInstance(
- null /*osSdkPath*/,
- new StdLogger(StdLogger.Level.VERBOSE));
- Collection<Device> devices = deviceManager.getDevices(DeviceManager.DeviceFilter.DEFAULT);
- assertNotNull(devices);
- assertTrue(devices.size() > 0);
- configuration.setDevice(devices.iterator().next(), false);
-
- // Check syncing
- FolderConfiguration folderConfig = configuration.getFullConfig();
- assertEquals(FAKE_VALUE, folderConfig.getLocaleQualifier().getLanguage());
- assertEquals(FAKE_VALUE, folderConfig.getLocaleQualifier().getRegion());
- assertEquals(Locale.ANY, configuration.getLocale());
-
- Locale language = Locale.create(new LocaleQualifier("nb"));
- configuration.setLocale(language, true /* skipSync */);
- assertEquals(FAKE_VALUE, folderConfig.getLocaleQualifier().getLanguage());
- assertEquals(FAKE_VALUE, folderConfig.getLocaleQualifier().getRegion());
-
- configuration.setLocale(language, false /* skipSync */);
- assertEquals(FAKE_VALUE, folderConfig.getLocaleQualifier().getRegion());
- assertEquals("nb", folderConfig.getLocaleQualifier().getLanguage());
-
- assertEquals("2.7in QVGA::nb-__:+Theme::notnight::", configuration.toPersistentString());
-
- configuration.setActivity("foo.bar.FooActivity");
- configuration.setTheme("@android:style/Theme.Holo.Light");
-
- assertEquals("2.7in QVGA",
- ConfigurationChooser.getDeviceLabel(configuration.getDevice(), true));
- assertEquals("2.7in QVGA",
- ConfigurationChooser.getDeviceLabel(configuration.getDevice(), false));
- assertEquals("Light",
- ConfigurationChooser.getThemeLabel(configuration.getTheme(), true));
- assertEquals("Theme.Holo.Light",
- ConfigurationChooser.getThemeLabel(configuration.getTheme(), false));
- assertEquals("nb",
- ConfigurationChooser.getLocaleLabel(null, configuration.getLocale(), true));
- assertEquals("Norwegian Bokm\u00e5l (nb)",
- ConfigurationChooser.getLocaleLabel(null, configuration.getLocale(), false));
-
- assertEquals("FooActivity",
- ConfigurationChooser.getActivityLabel(configuration.getActivity(), true));
- assertEquals("foo.bar.FooActivity",
- ConfigurationChooser.getActivityLabel(configuration.getActivity(), false));
-
- assertEquals("2.7in QVGA::nb-__:-Theme.Holo.Light::notnight::foo.bar.FooActivity",
- configuration.toPersistentString());
-
- assertEquals(Density.MEDIUM, configuration.getDensity());
- Screen screen = configuration.getDevice().getDefaultHardware().getScreen();
- assertEquals(145.0f, screen.getXdpi(), 0.001);
- assertEquals(145.0f, screen.getYdpi(), 0.001);
- }
-
- public void testCopy() throws Exception {
- Configuration configuration = createConfiguration();
- assertNotNull(configuration);
- configuration.setTheme("@style/Theme");
- assertEquals("@style/Theme", configuration.getTheme());
- DeviceManager deviceManager = DeviceManager.createInstance(
- null /*osSdkPath*/,
- new StdLogger(StdLogger.Level.VERBOSE));
- List<Device> devices = Lists.newArrayList(deviceManager.getDevices(DeviceManager.DeviceFilter.DEFAULT));
- assertNotNull(devices);
- assertTrue(devices.size() > 0);
- configuration.setDevice(devices.get(0), false);
- configuration.setActivity("foo.bar.FooActivity");
- configuration.setTheme("@android:style/Theme.Holo.Light");
- Locale locale = Locale.create(new LocaleQualifier("nb"));
- configuration.setLocale(locale, false /* skipSync */);
-
- Configuration copy = Configuration.copy(configuration);
- assertEquals(locale, copy.getLocale());
- assertEquals("foo.bar.FooActivity", copy.getActivity());
- assertEquals("@android:style/Theme.Holo.Light", copy.getTheme());
- assertEquals(devices.get(0), copy.getDevice());
-
- // Make sure edits to master does not affect the child
- configuration.setLocale(Locale.ANY, false);
- configuration.setTheme("@android:style/Theme.Holo");
- configuration.setDevice(devices.get(1), true);
-
- assertTrue(copy.getFullConfig().getLocaleQualifier().equals(locale.qualifier));
- assertEquals(locale, copy.getLocale());
- assertEquals("foo.bar.FooActivity", copy.getActivity());
- assertEquals("@android:style/Theme.Holo.Light", copy.getTheme());
- assertEquals(devices.get(0), copy.getDevice());
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/configuration/FlagManagerTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/configuration/FlagManagerTest.java
deleted file mode 100644
index 4286aaa30..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/configuration/FlagManagerTest.java
+++ /dev/null
@@ -1,185 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.configuration;
-
-import com.android.SdkConstants;
-import com.android.ide.common.resources.LocaleManager;
-import com.google.common.base.Function;
-import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.Multimap;
-import com.google.common.collect.Sets;
-
-import org.eclipse.swt.graphics.Image;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Locale;
-import java.util.Map;
-import java.util.Set;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class FlagManagerTest extends TestCase {
- public void testGetFlagImage() {
- FlagManager manager = FlagManager.get();
- Image us = manager.getFlag("US");
- Image gb = manager.getFlag("GB");
- Image ca = manager.getFlag("CA");
- Image es = manager.getFlag("ES");
- Image br = manager.getFlag("BR");
- Image pt = manager.getFlag("PT");
- assertSame(us, manager.getFlag("en", "US"));
- assertSame(gb, manager.getFlag("en", "GB"));
- assertSame(ca, manager.getFlag("en", "CA"));
- Locale.setDefault(Locale.US);
- assertSame(us, manager.getFlag("en", null));
- Locale.setDefault(Locale.UK);
- assertSame(gb, manager.getFlag("en", null));
- Locale.setDefault(Locale.CANADA);
- assertSame(ca, manager.getFlag("en", null));
- assertSame(manager.getFlag("NO"), manager.getFlag("nb", null));
- assertSame(manager.getFlag("FR"), manager.getFlag("fr", null));
-
- Locale.setDefault(new Locale("pt", "br"));
- assertSame(br, manager.getFlag("pt", null));
- assertSame(pt, manager.getFlag("pt", "PT"));
- Locale.setDefault(new Locale("pt", "pt"));
- assertSame(pt, manager.getFlag("pt", null));
- assertSame(br, manager.getFlag("pt", "BR"));
-
- // Special cases where we have custom flags
- assertNotSame(gb, manager.getFlag("cy", null)); // Wales
- assertNotSame(es, manager.getFlag("ca", null)); // Catalonia
-
- // Aliases - http://developer.android.com/reference/java/util/Locale.html
- assertSame(manager.getFlag("yi", null), manager.getFlag("ji", null));
- assertSame(manager.getFlag("in", null), manager.getFlag("id", null));
- assertSame(manager.getFlag("iw", null), manager.getFlag("he", null));
- assertSame(us, manager.getFlagForFolderName("values-en-rUS"));
- assertSame(gb, manager.getFlagForFolderName("values-en-rGB"));
- Locale.setDefault(Locale.CANADA);
- assertSame(ca, manager.getFlagForFolderName("values-en"));
- }
-
- public void testAvailableImages() {
- // Images we have from WindowBuilder (which are really the famfamfam
- // icons;
- // see http://www.famfamfam.com/lab/icons/flags)
- String[] icons = new String[] {
- "ad", "ae", "af", "ag", "ai", "al", "am", "ao", "ar", "as", "at", "au", "aw", "ax",
- "az", "ba", "bb", "bd", "be", "bf", "bg", "bh", "bi", "bj", "bm", "bn", "bo", "br",
- "bs", "bt", "bv", "bw", "by", "bz", "ca", "catalonia", "cc", "cd", "cf", "cg",
- "ch", "ci", "ck", "cl", "cm", "cn", "co", "cr", "cu", "cv", "cx", "cy", "cz", "de",
- "dj", "dk", "dm", "do", "dz", "ec", "ee", "eg", "eh", "england", "er", "es", "et",
- "fi", "fj", "fk", "fm", "fo", "fr", "ga", "gb", "gd", "ge", "gf", "gg", "gh", "gi",
- "gl", "gm", "gn", "gp", "gq", "gr", "gs", "gt", "gu", "gw", "gy", "hk", "hm", "hn",
- "hr", "ht", "hu", "id", "ie", "il", "im", "in", "io", "iq", "ir", "is", "it", "jm",
- "jo", "jp", "ke", "kg", "kh", "ki", "km", "kn", "kp", "kr", "kw", "ky", "kz", "la",
- "lb", "lc", "li", "lk", "lr", "ls", "lt", "lu", "lv", "ly", "ma", "mc", "md", "me",
- "mg", "mh", "mk", "ml", "mm", "mn", "mo", "mp", "mq", "mr", "ms", "mt", "mu", "mv",
- "mw", "mx", "my", "mz", "na", "nc", "ne", "nf", "ng", "ni", "nl", "no", "np", "nr",
- "nu", "nz", "om", "pa", "pe", "pf", "pg", "ph", "pk", "pl", "pm", "pn", "pr", "ps",
- "pt", "pw", "py", "qa", "re", "ro", "rs", "ru", "rw", "sa", "sb", "sc", "scotland",
- "sd", "se", "sg", "sh", "si", "sj", "sk", "sl", "sm", "sn", "so", "sr", "ss", "st",
- "sv", "sy", "sz", "tc", "td", "tf", "tg", "th", "tj", "tk", "tl", "tm", "tn", "to",
- "tr", "tt", "tv", "tw", "tz", "ua", "ug", "um", "us", "uy", "uz", "va", "vc", "ve",
- "vg", "vi", "vn", "vu", "wales", "wf", "ws", "ye", "yt", "za", "zm", "zw"
- };
-
- Set<String> sImages = new HashSet<String>(100);
- for (String code : icons) {
- if (code.length() > 2) {
- continue;
- }
- code = code.toUpperCase(Locale.US);
- sImages.add(code);
-
- if (!LocaleManager.isValidRegionCode(code)) {
- System.out.println("No region name found for region code " + code);
- }
- }
-
- Set<String> unused = Sets.newHashSet(LocaleManager.getRegionCodes(false));
- Set<String> reachable = Sets.newHashSet();
- Multimap<String, String> regionToLanguages = ArrayListMultimap.create();
- for (String language : LocaleManager.getLanguageCodes(false)) {
- for (String region : LocaleManager.getRelevantRegions(language)) {
- reachable.add(region);
- regionToLanguages.put(region, language);
- }
- }
- unused.removeAll(reachable);
-
- for (String region : reachable) {
- if (!sImages.contains(region)) {
- StringBuilder sb = new StringBuilder();
-
- sb.append("No icon found for region ").append(region).append(" ")
- .append(LocaleManager.getRegionName(region));
- sb.append(", used for languages ");
-
- for (String language : regionToLanguages.get(region)) {
- sb.append(language).append("(").append(LocaleManager.getLanguageName(language))
- .append(") ");
- }
- System.out.println(sb.toString());
- }
- }
-
- // Known regions that we don't have language to region mappings for
- unused.remove("AQ");
- unused.remove("VA");
- unused.remove("GS");
- unused.remove("TF");
- unused.remove("BV");
- unused.remove("HM");
-
- if (!unused.isEmpty()) {
- StringBuilder sb = new StringBuilder();
- sb.append("The following icons are not referenced by any of the "
- + "language to country bindings:");
- for (String code : unused) {
- sb.append(code.toLowerCase(Locale.US)).append(SdkConstants.DOT_PNG).append(" (");
- sb.append(LocaleManager.getRegionName(code)).append(") ");
- }
- System.out.println(sb.toString());
- }
- }
-
- public void testMissingFlag() {
- Image icon = FlagManager.get().getFlag("AQ");
- assertNotNull(icon);
- assertSame(FlagManager.get().getEmptyIcon(), icon);
-
- icon = FlagManager.get().getFlag("AQ");
- assertNotNull(icon);
- assertSame(FlagManager.get().getEmptyIcon(), icon);
-
- icon = FlagManager.get().getFlag("WO"); // Not used in ISO 3166-1
- assertNotNull(icon);
- assertSame(FlagManager.get().getEmptyIcon(), icon);
- }
-
- public void testKnownFlag() {
- Image icon = FlagManager.get().getFlag("US");
- assertNotNull(icon);
- assertNotSame(FlagManager.get().getEmptyIcon(), icon);
- }
-}
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/configuration/LocaleTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/configuration/LocaleTest.java
deleted file mode 100644
index 904ade39c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/configuration/LocaleTest.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.configuration;
-
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.common.resources.configuration.LocaleQualifier;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class LocaleTest extends TestCase {
- public void test1() {
- Locale locale = Locale.create("en-rUS");
- assertEquals("en", locale.qualifier.getLanguage());
- assertEquals("US", locale.qualifier.getRegion());
- assertTrue(locale.hasLanguage());
- assertTrue(locale.hasRegion());
- }
-
- public void test2() {
- Locale locale = Locale.create("zh");
- assertEquals("zh", locale.qualifier.getLanguage());
- assertNull(locale.qualifier.getRegion());
- assertTrue(locale.hasLanguage());
- assertFalse(locale.hasRegion());
- }
-
- public void testEquals() {
- Locale locale = Locale.create("zh");
- assertEquals("zh", locale.qualifier.getLanguage());
- assertNull(locale.qualifier.getRegion());
- assertTrue(locale.hasLanguage());
- assertFalse(locale.hasRegion());
- }
-
- public void test() {
- LocaleQualifier qualifier1 = LocaleQualifier.getQualifier("nb");
- LocaleQualifier qualifier2 = LocaleQualifier.getQualifier("no");
- LocaleQualifier qualifier3 = LocaleQualifier.getQualifier("nb-rNO");
- LocaleQualifier qualifier4 = LocaleQualifier.getQualifier("nb-rSE");
- LocaleQualifier qualifier5 = LocaleQualifier.getQualifier("no-rSE");
- assertNotNull(qualifier1);
- assertNotNull(qualifier2);
- assertNotNull(qualifier3);
- assertNotNull(qualifier4);
- assertNotNull(qualifier5);
-
- assertEquals(Locale.ANY, Locale.ANY);
- assertFalse(Locale.ANY.hasLanguage());
- assertFalse(Locale.ANY.hasRegion());
- // noinspection ConstantConditions
- assertFalse(Locale.create(new LocaleQualifier(LocaleQualifier.FAKE_VALUE)).hasLanguage());
- // noinspection ConstantConditions
- assertFalse(Locale.create(new LocaleQualifier(LocaleQualifier.FAKE_VALUE)).hasRegion());
-
- assertEquals(Locale.create(qualifier1), Locale.create(qualifier1));
- assertTrue(Locale.create(qualifier1).hasLanguage());
- assertFalse(Locale.create(qualifier1).hasRegion());
- assertTrue(Locale.create(qualifier3).hasLanguage());
- assertTrue(Locale.create(qualifier3).hasRegion());
-
- assertEquals(Locale.create(qualifier3), Locale.create(qualifier3));
- assertEquals(Locale.create(qualifier1), Locale.create(qualifier1));
- assertTrue(Locale.create(qualifier1).equals(Locale.create(qualifier1)));
- assertTrue(Locale.create(qualifier3).equals(Locale.create(qualifier3)));
- assertFalse(Locale.create(qualifier3).equals(Locale.create(qualifier4)));
- assertFalse(Locale.create(qualifier1).equals(Locale.create(qualifier3)));
- assertFalse(Locale.create(qualifier1).equals(Locale.create(qualifier2)));
- assertFalse(Locale.create(qualifier3).equals(Locale.create(qualifier5)));
- assertEquals("nb", Locale.create(qualifier1).toString());
- assertEquals("nb-NO", Locale.create(qualifier3).toString());
-
- assertEquals(Locale.create(qualifier1), Locale.create("b+nb"));
- assertEquals(Locale.create(qualifier3), Locale.create("b+nb+NO"));
- }
-
- public void testFolderConfig() {
- FolderConfiguration config = new FolderConfiguration();
- assertEquals(Locale.ANY, Locale.create(config));
- config.setLocaleQualifier(LocaleQualifier.getQualifier("en"));
- assertEquals(Locale.create("en"), Locale.create(config));
- config.setLocaleQualifier(LocaleQualifier.getQualifier("en-rUS"));
- assertEquals(Locale.create("en-rUS"), Locale.create(config));
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/CanvasViewInfoTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/CanvasViewInfoTest.java
deleted file mode 100644
index 5996f01c0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/CanvasViewInfoTest.java
+++ /dev/null
@@ -1,797 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.ide.common.rendering.api.Capability;
-import com.android.ide.common.rendering.api.DataBindingItem;
-import com.android.ide.common.rendering.api.MergeCookie;
-import com.android.ide.common.rendering.api.ViewInfo;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-import com.android.utils.Pair;
-
-import org.eclipse.swt.graphics.Rectangle;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Set;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class CanvasViewInfoTest extends TestCase {
-
- public static ViewElementDescriptor createDesc(String name, String fqn, boolean hasChildren) {
- if (hasChildren) {
- return new ViewElementDescriptor(name, name, fqn, "", "", new AttributeDescriptor[0],
- new AttributeDescriptor[0], new ElementDescriptor[1], false);
- } else {
- return new ViewElementDescriptor(name, fqn);
- }
- }
-
- public static UiViewElementNode createNode(UiViewElementNode parent, String fqn,
- boolean hasChildren) {
- String name = fqn.substring(fqn.lastIndexOf('.') + 1);
- ViewElementDescriptor descriptor = createDesc(name, fqn, hasChildren);
- if (parent == null) {
- // All node hierarchies should be wrapped inside a document node at the root
- parent = new UiViewElementNode(createDesc("doc", "doc", true));
- }
- return (UiViewElementNode) parent.appendNewUiChild(descriptor);
- }
-
- public static UiViewElementNode createNode(String fqn, boolean hasChildren) {
- return createNode(null, fqn, hasChildren);
- }
-
- public void testNormalCreate() throws Exception {
- normal(true);
- }
-
- public void testNormalCreateLayoutLib5() throws Exception {
- normal(false);
- }
-
- private void normal(boolean layoutlib5) {
-
- // Normal view hierarchy, no null keys anywhere
-
- UiViewElementNode rootNode = createNode("android.widget.LinearLayout", true);
- ViewInfo root = new ViewInfo("LinearLayout", rootNode, 10, 10, 100, 100);
- UiViewElementNode child1Node = createNode(rootNode, "android.widget.Button", false);
- ViewInfo child1 = new ViewInfo("Button", child1Node, 0, 0, 50, 20);
- UiViewElementNode child2Node = createNode(rootNode, "android.widget.Button", false);
- ViewInfo child2 = new ViewInfo("Button", child2Node, 0, 20, 70, 25);
- root.setChildren(Arrays.asList(child1, child2));
-
- CanvasViewInfo rootView = CanvasViewInfo.create(root, layoutlib5).getFirst();
- assertNotNull(rootView);
- assertEquals("LinearLayout", rootView.getName());
- assertEquals(new Rectangle(10, 10, 89, 89), rootView.getAbsRect());
- assertEquals(new Rectangle(10, 10, 89, 89), rootView.getSelectionRect());
- assertNull(rootView.getParent());
- assertSame(rootView.getUiViewNode(), rootNode);
- assertEquals(2, rootView.getChildren().size());
- CanvasViewInfo childView1 = rootView.getChildren().get(0);
- CanvasViewInfo childView2 = rootView.getChildren().get(1);
-
- assertEquals("Button", childView1.getName());
- assertSame(rootView, childView1.getParent());
- assertEquals(new Rectangle(10, 10, 49, 19), childView1.getAbsRect());
- assertEquals(new Rectangle(10, 10, 49, 19), childView1.getSelectionRect());
- assertSame(childView1.getUiViewNode(), child1Node);
-
- assertEquals("Button", childView2.getName());
- assertSame(rootView, childView2.getParent());
- assertEquals(new Rectangle(10, 30, 69, 4), childView2.getAbsRect());
- assertEquals(new Rectangle(10, 30, 69, 5), childView2.getSelectionRect());
- assertSame(childView2.getUiViewNode(), child2Node);
- }
-
- public void testShowIn() throws Exception {
- showIn(false);
- }
-
- public void testShowInLayoutLib5() throws Exception {
- showIn(true);
- }
-
- public void showIn(boolean layoutlib5) throws Exception {
-
- // Test rendering of "Show Included In" (included content rendered
- // within an outer content that has null keys)
-
- ViewInfo root = new ViewInfo("LinearLayout", null, 10, 10, 100, 100);
- ViewInfo child1 = new ViewInfo("CheckBox", null, 0, 0, 50, 20);
- UiViewElementNode child2Node = createNode("android.widget.RelativeLayout", true);
- ViewInfo child2 = new ViewInfo("RelativeLayout", child2Node, 0, 20, 70, 25);
- root.setChildren(Arrays.asList(child1, child2));
- UiViewElementNode child21Node = createNode("android.widget.Button", false);
- ViewInfo child21 = new ViewInfo("RadioButton", child21Node, 0, 20, 70, 25);
- child2.setChildren(Arrays.asList(child21));
-
- CanvasViewInfo rootView = CanvasViewInfo.create(root, layoutlib5).getFirst();
- assertNotNull(rootView);
- assertEquals("LinearLayout", rootView.getName());
- assertEquals(new Rectangle(10, 10, 89, 89), rootView.getAbsRect());
- assertEquals(new Rectangle(10, 10, 89, 89), rootView.getSelectionRect());
- assertNull(rootView.getParent());
- assertNull(rootView.getUiViewNode());
- assertEquals(1, rootView.getChildren().size());
- CanvasViewInfo includedView = rootView.getChildren().get(0);
-
- assertEquals("RelativeLayout", includedView.getName());
- assertSame(rootView, includedView.getParent());
- assertEquals(new Rectangle(10, 30, 69, 4), includedView.getAbsRect());
- assertEquals(new Rectangle(10, 30, 69, 5), includedView.getSelectionRect());
- assertSame(includedView.getUiViewNode(), child2Node);
-
- CanvasViewInfo grandChild = includedView.getChildren().get(0);
- assertNotNull(grandChild);
- assertEquals("RadioButton", grandChild.getName());
- assertSame(child21Node, grandChild.getUiViewNode());
- assertEquals(new Rectangle(10, 50, 69, 4), grandChild.getAbsRect());
- assertEquals(new Rectangle(10, 50, 69, 5), grandChild.getSelectionRect());
- }
-
- public void testIncludeTag() throws Exception {
- boolean layoutlib5 = true;
-
- // Test rendering of included views on layoutlib 5+ (e.g. has <include> tag)
-
- UiViewElementNode rootNode = createNode("android.widget.LinearLayout", true);
- ViewInfo root = new ViewInfo("LinearLayout", rootNode, 10, 10, 100, 100);
- UiViewElementNode child1Node = createNode(rootNode, "android.widget.Button", false);
- ViewInfo child1 = new ViewInfo("CheckBox", child1Node, 0, 0, 50, 20);
- UiViewElementNode child2Node = createNode(rootNode, "include", true);
- ViewInfo child2 = new ViewInfo("RelativeLayout", child2Node, 0, 20, 70, 25);
- root.setChildren(Arrays.asList(child1, child2));
- ViewInfo child21 = new ViewInfo("RadioButton", null, 0, 20, 70, 25);
- child2.setChildren(Arrays.asList(child21));
-
- CanvasViewInfo rootView = CanvasViewInfo.create(root, layoutlib5).getFirst();
- assertNotNull(rootView);
- assertEquals("LinearLayout", rootView.getName());
- assertEquals(new Rectangle(10, 10, 89, 89), rootView.getAbsRect());
- assertEquals(new Rectangle(10, 10, 89, 89), rootView.getSelectionRect());
- assertNull(rootView.getParent());
- assertSame(rootNode, rootView.getUiViewNode());
- assertEquals(2, rootView.getChildren().size());
-
- CanvasViewInfo childView1 = rootView.getChildren().get(0);
- CanvasViewInfo includedView = rootView.getChildren().get(1);
-
- assertEquals("CheckBox", childView1.getName());
- assertSame(rootView, childView1.getParent());
- assertEquals(new Rectangle(10, 10, 49, 19), childView1.getAbsRect());
- assertEquals(new Rectangle(10, 10, 49, 19), childView1.getSelectionRect());
- assertSame(childView1.getUiViewNode(), child1Node);
-
- assertEquals("RelativeLayout", includedView.getName());
- assertSame(rootView, includedView.getParent());
- assertEquals(new Rectangle(10, 30, 69, 4), includedView.getAbsRect());
- assertEquals(new Rectangle(10, 30, 69, 5), includedView.getSelectionRect());
- assertSame(includedView.getUiViewNode(), child2Node);
- assertEquals(0, includedView.getChildren().size());
- }
-
- public void testNoIncludeTag() throws Exception {
- boolean layoutlib5 = false;
-
- // Test rendering of included views on layoutlib 4- (e.g. no <include> tag cookie
- // in view info)
-
- UiViewElementNode rootNode = createNode("android.widget.LinearLayout", true);
- ViewInfo root = new ViewInfo("LinearLayout", rootNode, 10, 10, 100, 100);
- UiViewElementNode child1Node = createNode(rootNode, "android.widget.Button", false);
- ViewInfo child1 = new ViewInfo("CheckBox", child1Node, 0, 0, 50, 20);
- UiViewElementNode child2Node = createNode(rootNode, "include", true);
- ViewInfo child2 = new ViewInfo("RelativeLayout", null /* layoutlib 4 */, 0, 20, 70, 25);
- root.setChildren(Arrays.asList(child1, child2));
- ViewInfo child21 = new ViewInfo("RadioButton", null, 0, 20, 70, 25);
- child2.setChildren(Arrays.asList(child21));
-
- CanvasViewInfo rootView = CanvasViewInfo.create(root, layoutlib5).getFirst();
- assertNotNull(rootView);
- assertEquals("LinearLayout", rootView.getName());
- assertEquals(new Rectangle(10, 10, 89, 89), rootView.getAbsRect());
- assertEquals(new Rectangle(10, 10, 89, 89), rootView.getSelectionRect());
- assertNull(rootView.getParent());
- assertSame(rootNode, rootView.getUiViewNode());
- assertEquals(2, rootView.getChildren().size());
-
- CanvasViewInfo childView1 = rootView.getChildren().get(0);
- CanvasViewInfo includedView = rootView.getChildren().get(1);
-
- assertEquals("CheckBox", childView1.getName());
- assertSame(rootView, childView1.getParent());
- assertEquals(new Rectangle(10, 10, 49, 19), childView1.getAbsRect());
- assertEquals(new Rectangle(10, 10, 49, 19), childView1.getSelectionRect());
- assertSame(childView1.getUiViewNode(), child1Node);
-
- assertEquals("RelativeLayout", includedView.getName());
- assertSame(rootView, includedView.getParent());
- assertEquals(new Rectangle(10, 30, 69, 4), includedView.getAbsRect());
- assertEquals(new Rectangle(10, 30, 69, 5), includedView.getSelectionRect());
- assertSame(includedView.getUiViewNode(), child2Node);
- assertEquals(0, includedView.getChildren().size());
- }
-
- public void testMergeMatching() throws Exception {
- boolean layoutlib5 = false;
-
- // Test rendering of MULTIPLE included views or when there is no simple match
- // between view info and ui element node children
-
- UiViewElementNode rootNode = createNode("android.widget.LinearLayout", true);
- ViewInfo root = new ViewInfo("LinearLayout", rootNode, 10, 10, 100, 100);
- UiViewElementNode child1Node = createNode(rootNode, "android.widget.Button", false);
- ViewInfo child1 = new ViewInfo("CheckBox", child1Node, 0, 0, 50, 20);
- UiViewElementNode multiChildNode1 = createNode(rootNode, "foo", true);
- UiViewElementNode multiChildNode2 = createNode(rootNode, "bar", true);
- ViewInfo child2 = new ViewInfo("RelativeLayout", null, 0, 20, 70, 25);
- ViewInfo child3 = new ViewInfo("AbsoluteLayout", null, 10, 40, 50, 15);
- root.setChildren(Arrays.asList(child1, child2, child3));
- ViewInfo child21 = new ViewInfo("RadioButton", null, 0, 20, 70, 25);
- child2.setChildren(Arrays.asList(child21));
-
- CanvasViewInfo rootView = CanvasViewInfo.create(root, layoutlib5).getFirst();
- assertNotNull(rootView);
- assertEquals("LinearLayout", rootView.getName());
- assertEquals(new Rectangle(10, 10, 89, 89), rootView.getAbsRect());
- assertEquals(new Rectangle(10, 10, 89, 89), rootView.getSelectionRect());
- assertNull(rootView.getParent());
- assertTrue(rootView.isRoot());
- assertSame(rootNode, rootView.getUiViewNode());
- assertEquals(3, rootView.getChildren().size());
-
- CanvasViewInfo childView1 = rootView.getChildren().get(0);
- assertFalse(childView1.isRoot());
- CanvasViewInfo includedView1 = rootView.getChildren().get(1);
- assertFalse(includedView1.isRoot());
- CanvasViewInfo includedView2 = rootView.getChildren().get(2);
- assertFalse(includedView1.isRoot());
-
- assertEquals("CheckBox", childView1.getName());
- assertSame(rootView, childView1.getParent());
- assertEquals(new Rectangle(10, 10, 49, 19), childView1.getAbsRect());
- assertEquals(new Rectangle(10, 10, 49, 19), childView1.getSelectionRect());
- assertSame(childView1.getUiViewNode(), child1Node);
-
- assertEquals("RelativeLayout", includedView1.getName());
- assertSame(multiChildNode1, includedView1.getUiViewNode());
- assertEquals("foo", includedView1.getUiViewNode().getDescriptor().getXmlName());
- assertSame(multiChildNode2, includedView2.getUiViewNode());
- assertEquals("AbsoluteLayout", includedView2.getName());
- assertEquals("bar", includedView2.getUiViewNode().getDescriptor().getXmlName());
- assertSame(rootView, includedView1.getParent());
- assertSame(rootView, includedView2.getParent());
- assertEquals(new Rectangle(10, 30, 69, 4), includedView1.getAbsRect());
- assertEquals(new Rectangle(10, 30, 69, 5), includedView1.getSelectionRect());
- assertEquals(new Rectangle(20, 50, 39, -26), includedView2.getAbsRect());
- assertEquals(new Rectangle(20, 35, 39, 5), includedView2.getSelectionRect());
- assertEquals(0, includedView1.getChildren().size());
- assertEquals(0, includedView2.getChildren().size());
- }
-
- public void testMerge() throws Exception {
- boolean layoutlib5 = false;
-
- // Test rendering of MULTIPLE included views or when there is no simple match
- // between view info and ui element node children
-
- UiViewElementNode rootNode = createNode("android.widget.LinearLayout", true);
- ViewInfo root = new ViewInfo("LinearLayout", rootNode, 10, 10, 100, 100);
- UiViewElementNode child1Node = createNode(rootNode, "android.widget.Button", false);
- ViewInfo child1 = new ViewInfo("CheckBox", child1Node, 0, 0, 50, 20);
- UiViewElementNode multiChildNode = createNode(rootNode, "foo", true);
- ViewInfo child2 = new ViewInfo("RelativeLayout", null, 0, 20, 70, 25);
- ViewInfo child3 = new ViewInfo("AbsoluteLayout", null, 10, 40, 50, 15);
- root.setChildren(Arrays.asList(child1, child2, child3));
- ViewInfo child21 = new ViewInfo("RadioButton", null, 0, 20, 70, 25);
- child2.setChildren(Arrays.asList(child21));
-
- CanvasViewInfo rootView = CanvasViewInfo.create(root, layoutlib5).getFirst();
- assertNotNull(rootView);
- assertEquals("LinearLayout", rootView.getName());
- assertEquals(new Rectangle(10, 10, 89, 89), rootView.getAbsRect());
- assertEquals(new Rectangle(10, 10, 89, 89), rootView.getSelectionRect());
- assertNull(rootView.getParent());
- assertSame(rootNode, rootView.getUiViewNode());
- assertEquals(2, rootView.getChildren().size());
-
- CanvasViewInfo childView1 = rootView.getChildren().get(0);
- CanvasViewInfo includedView = rootView.getChildren().get(1);
-
- assertEquals("CheckBox", childView1.getName());
- assertSame(rootView, childView1.getParent());
- assertEquals(new Rectangle(10, 10, 49, 19), childView1.getAbsRect());
- assertEquals(new Rectangle(10, 10, 49, 19), childView1.getSelectionRect());
- assertSame(childView1.getUiViewNode(), child1Node);
-
- assertEquals("RelativeLayout", includedView.getName());
- assertSame(rootView, includedView.getParent());
- assertEquals(new Rectangle(10, 30, 69, 4), includedView.getAbsRect());
- assertEquals(new Rectangle(10, 30, 69, 5), includedView.getSelectionRect());
- assertEquals(0, includedView.getChildren().size());
- assertSame(multiChildNode, includedView.getUiViewNode());
- }
-
- public void testInsertMerge() throws Exception {
- boolean layoutlib5 = false;
-
- // Test rendering of MULTIPLE included views or when there is no simple match
- // between view info and ui element node children
-
- UiViewElementNode mergeNode = createNode("merge", true);
- UiViewElementNode rootNode = createNode(mergeNode, "android.widget.Button", false);
- ViewInfo root = new ViewInfo("Button", rootNode, 10, 10, 100, 100);
-
- CanvasViewInfo rootView = CanvasViewInfo.create(root, layoutlib5).getFirst();
- assertNotNull(rootView);
- assertEquals("merge", rootView.getName());
- assertSame(rootView.getUiViewNode(), mergeNode);
- assertEquals(new Rectangle(10, 10, 89, 89), rootView.getAbsRect());
- assertEquals(new Rectangle(10, 10, 89, 89), rootView.getSelectionRect());
- assertNull(rootView.getParent());
- assertSame(mergeNode, rootView.getUiViewNode());
- assertEquals(1, rootView.getChildren().size());
-
- CanvasViewInfo childView1 = rootView.getChildren().get(0);
-
- assertEquals("Button", childView1.getName());
- assertSame(rootView, childView1.getParent());
- assertEquals(new Rectangle(10, 10, 89, 89), childView1.getAbsRect());
- assertEquals(new Rectangle(10, 10, 89, 89), childView1.getSelectionRect());
- assertSame(childView1.getUiViewNode(), rootNode);
- }
-
- public void testUnmatchedMissing() throws Exception {
- boolean layoutlib5 = false;
-
- UiViewElementNode rootNode = createNode("android.widget.LinearLayout", true);
- ViewInfo root = new ViewInfo("LinearLayout", rootNode, 0, 0, 100, 100);
- List<ViewInfo> children = new ArrayList<ViewInfo>();
- // Should be matched up with corresponding node:
- Set<Integer> missingKeys = new HashSet<Integer>();
- // Should not be matched with any views, but should get view created:
- Set<Integer> extraKeys = new HashSet<Integer>();
- // Should not be matched with any nodes
- Set<Integer> extraViews = new HashSet<Integer>();
- int numViews = 30;
- missingKeys.add(0);
- missingKeys.add(4);
- missingKeys.add(14);
- missingKeys.add(29);
- extraKeys.add(9);
- extraKeys.add(20);
- extraKeys.add(22);
- extraViews.add(18);
- extraViews.add(24);
-
- List<String> expectedViewNames = new ArrayList<String>();
- List<String> expectedNodeNames = new ArrayList<String>();
-
- for (int i = 0; i < numViews; i++) {
- UiViewElementNode childNode = null;
- if (!extraViews.contains(i)) {
- childNode = createNode(rootNode, "childNode" + i, false);
- }
- Object cookie = missingKeys.contains(i) || extraViews.contains(i) ? null : childNode;
- ViewInfo childView = new ViewInfo("childView" + i, cookie,
- 0, i * 20, 50, (i + 1) * 20);
- children.add(childView);
-
- if (!extraViews.contains(i)) {
- expectedViewNames.add("childView" + i);
- expectedNodeNames.add("childNode" + i);
- }
-
- if (extraKeys.contains(i)) {
- createNode(rootNode, "extraNodeAt" + i, false);
-
- expectedViewNames.add("extraNodeAt" + i);
- expectedNodeNames.add("extraNodeAt" + i);
- }
- }
- root.setChildren(children);
-
- CanvasViewInfo rootView = CanvasViewInfo.create(root, layoutlib5).getFirst();
- assertNotNull(rootView);
-
- // dump(root, 0);
- // dump(rootView, 0);
-
- assertEquals("LinearLayout", rootView.getName());
- assertNull(rootView.getParent());
- assertSame(rootNode, rootView.getUiViewNode());
- assertEquals(numViews + extraKeys.size() - extraViews.size(), rootNode.getUiChildren()
- .size());
- assertEquals(numViews + extraKeys.size() - extraViews.size(),
- rootView.getChildren().size());
- assertEquals(expectedViewNames.size(), rootView.getChildren().size());
- for (int i = 0, n = rootView.getChildren().size(); i < n; i++) {
- CanvasViewInfo childView = rootView.getChildren().get(i);
- String expectedViewName = expectedViewNames.get(i);
- String expectedNodeName = expectedNodeNames.get(i);
- assertEquals(expectedViewName, childView.getName());
- assertNotNull(childView.getUiViewNode());
- assertEquals(expectedNodeName, childView.getUiViewNode().getDescriptor().getXmlName());
- }
- }
-
- public void testMergeCookies() throws Exception {
- boolean layoutlib5 = true;
-
- UiViewElementNode rootNode = createNode("android.widget.LinearLayout", true);
- ViewInfo root = new ViewInfo("LinearLayout", rootNode, 0, 0, 100, 100);
-
- // Create the merge cookies in the opposite order to ensure that we don't
- // apply our own logic when matching up views with nodes
- LinkedList<MergeCookie> cookies = new LinkedList<MergeCookie>();
- for (int i = 0; i < 10; i++) {
- UiViewElementNode node = createNode(rootNode, "childNode" + i, false);
- cookies.addFirst(new MergeCookie(node));
- }
- Iterator<MergeCookie> it = cookies.iterator();
- ArrayList<ViewInfo> children = new ArrayList<ViewInfo>();
- for (int i = 0; i < 10; i++) {
- ViewInfo childView = new ViewInfo("childView" + i, it.next(), 0, i * 20, 50,
- (i + 1) * 20);
- children.add(childView);
- }
- root.setChildren(children);
-
- CanvasViewInfo rootView = CanvasViewInfo.create(root, layoutlib5).getFirst();
- assertNotNull(rootView);
-
- assertEquals("LinearLayout", rootView.getName());
- assertNull(rootView.getParent());
- assertSame(rootNode, rootView.getUiViewNode());
- for (int i = 0, n = rootView.getChildren().size(); i < n; i++) {
- CanvasViewInfo childView = rootView.getChildren().get(i);
- assertEquals("childView" + i, childView.getName());
- assertEquals("childNode" + (9 - i), childView.getUiViewNode().getDescriptor()
- .getXmlName());
- }
- }
-
- public void testMergeCookies2() throws Exception {
- boolean layoutlib5 = true;
-
- UiViewElementNode rootNode = createNode("android.widget.LinearLayout", true);
- ViewInfo root = new ViewInfo("LinearLayout", rootNode, 0, 0, 100, 100);
-
- UiViewElementNode node1 = createNode(rootNode, "childNode1", false);
- UiViewElementNode node2 = createNode(rootNode, "childNode2", false);
- MergeCookie cookie1 = new MergeCookie(node1);
- MergeCookie cookie2 = new MergeCookie(node2);
-
- // Sets alternating merge cookies and checks whether the node sibling lists are
- // okay and merged correctly
-
- ArrayList<ViewInfo> children = new ArrayList<ViewInfo>();
- for (int i = 0; i < 10; i++) {
- Object cookie = (i % 2) == 0 ? cookie1 : cookie2;
- ViewInfo childView = new ViewInfo("childView" + i, cookie, 0, i * 20, 50,
- (i + 1) * 20);
- children.add(childView);
- }
- root.setChildren(children);
-
- Pair<CanvasViewInfo, List<Rectangle>> result = CanvasViewInfo.create(root, layoutlib5);
- CanvasViewInfo rootView = result.getFirst();
- List<Rectangle> bounds = result.getSecond();
- assertNull(bounds);
- assertNotNull(rootView);
-
- assertEquals("LinearLayout", rootView.getName());
- assertNull(rootView.getParent());
- assertSame(rootNode, rootView.getUiViewNode());
- assertEquals(10, rootView.getChildren().size());
- assertEquals(2, rootView.getUniqueChildren().size());
- for (int i = 0, n = rootView.getChildren().size(); i < n; i++) {
- CanvasViewInfo childView = rootView.getChildren().get(i);
- assertEquals("childView" + i, childView.getName());
- Object cookie = (i % 2) == 0 ? node1 : node2;
- assertSame(cookie, childView.getUiViewNode());
- List<CanvasViewInfo> nodeSiblings = childView.getNodeSiblings();
- assertEquals(5, nodeSiblings.size());
- }
- List<CanvasViewInfo> nodeSiblings = rootView.getChildren().get(0).getNodeSiblings();
- for (int j = 0; j < 5; j++) {
- assertEquals("childView" + (j * 2), nodeSiblings.get(j).getName());
- }
- nodeSiblings = rootView.getChildren().get(1).getNodeSiblings();
- for (int j = 0; j < 5; j++) {
- assertEquals("childView" + (j * 2 + 1), nodeSiblings.get(j).getName());
- }
- }
-
- public void testIncludeBounds() throws Exception {
- boolean layoutlib5 = true;
-
- UiViewElementNode rootNode = createNode("android.widget.LinearLayout", true);
- ViewInfo root = new ViewInfo("included", null, 0, 0, 100, 100);
-
- UiViewElementNode node1 = createNode(rootNode, "childNode1", false);
- UiViewElementNode node2 = createNode(rootNode, "childNode2", false);
- MergeCookie cookie1 = new MergeCookie(node1);
- MergeCookie cookie2 = new MergeCookie(node2);
-
- // Sets alternating merge cookies and checks whether the node sibling lists are
- // okay and merged correctly
-
- ArrayList<ViewInfo> children = new ArrayList<ViewInfo>();
- for (int i = 0; i < 10; i++) {
- Object cookie = (i % 2) == 0 ? cookie1 : cookie2;
- ViewInfo childView = new ViewInfo("childView" + i, cookie, 0, i * 20, 50,
- (i + 1) * 20);
- children.add(childView);
- }
- root.setChildren(children);
-
- Pair<CanvasViewInfo, List<Rectangle>> result = CanvasViewInfo.create(root, layoutlib5);
- CanvasViewInfo rootView = result.getFirst();
- List<Rectangle> bounds = result.getSecond();
- assertNotNull(rootView);
-
- assertEquals("included", rootView.getName());
- assertNull(rootView.getParent());
- assertNull(rootView.getUiViewNode());
- assertEquals(10, rootView.getChildren().size());
- assertEquals(2, rootView.getUniqueChildren().size());
- for (int i = 0, n = rootView.getChildren().size(); i < n; i++) {
- CanvasViewInfo childView = rootView.getChildren().get(i);
- assertEquals("childView" + i, childView.getName());
- Object cookie = (i % 2) == 0 ? node1 : node2;
- assertSame(cookie, childView.getUiViewNode());
- List<CanvasViewInfo> nodeSiblings = childView.getNodeSiblings();
- assertEquals(5, nodeSiblings.size());
- }
- List<CanvasViewInfo> nodeSiblings = rootView.getChildren().get(0).getNodeSiblings();
- for (int j = 0; j < 5; j++) {
- assertEquals("childView" + (j * 2), nodeSiblings.get(j).getName());
- }
- nodeSiblings = rootView.getChildren().get(1).getNodeSiblings();
- for (int j = 0; j < 5; j++) {
- assertEquals("childView" + (j * 2 + 1), nodeSiblings.get(j).getName());
- }
-
- // Only show the primary bounds as included
- assertEquals(2, bounds.size());
- assertEquals(new Rectangle(0, 0, 49, 19), bounds.get(0));
- assertEquals(new Rectangle(0, 20, 49, 19), bounds.get(1));
- }
-
- public void testIncludeBounds2() throws Exception {
- includeBounds2(false);
- }
-
- public void testIncludeBounds2LayoutLib5() throws Exception {
- includeBounds2(true);
- }
-
- public void includeBounds2(boolean layoutlib5) throws Exception {
-
- UiViewElementNode rootNode = createNode("android.widget.LinearLayout", true);
- ViewInfo root = new ViewInfo("included", null, 0, 0, 100, 100);
-
- UiViewElementNode node1 = createNode(rootNode, "childNode1", false);
- UiViewElementNode node2 = createNode(rootNode, "childNode2", false);
-
- ViewInfo childView1 = new ViewInfo("childView1", node1, 0, 20, 50, 40);
- ViewInfo childView2 = new ViewInfo("childView2", node2, 0, 40, 50, 60);
-
- root.setChildren(Arrays.asList(childView1, childView2));
-
- Pair<CanvasViewInfo, List<Rectangle>> result = CanvasViewInfo.create(root, layoutlib5);
- CanvasViewInfo rootView = result.getFirst();
- List<Rectangle> bounds = result.getSecond();
- assertNotNull(rootView);
-
- assertEquals("included", rootView.getName());
- assertNull(rootView.getParent());
- assertNull(rootView.getUiViewNode());
- assertEquals(2, rootView.getChildren().size());
- assertEquals(2, rootView.getUniqueChildren().size());
-
- Rectangle bounds1 = bounds.get(0);
- Rectangle bounds2 = bounds.get(1);
- assertEquals(new Rectangle(0, 20, 49, 19), bounds1);
- assertEquals(new Rectangle(0, 40, 49, 19), bounds2);
- }
-
- public void testCookieWorkaround() throws Exception {
- UiViewElementNode rootNode = createNode("android.widget.LinearLayout", true);
- ViewInfo root = new ViewInfo("included", null, 0, 0, 100, 100);
-
- UiViewElementNode node2 = createNode(rootNode, "childNode2", false);
- MergeCookie mergeCookie = new MergeCookie(root);
-
- ViewInfo childView1 = new ViewInfo("childView1", mergeCookie, 0, 20, 50, 40);
- ViewInfo childView2 = new ViewInfo("childView2", node2, 0, 40, 50, 60);
-
- root.setChildren(Arrays.asList(childView1, childView2));
-
- Pair<CanvasViewInfo, List<Rectangle>> result = CanvasViewInfo.create(root, true);
- CanvasViewInfo rootView = result.getFirst();
- List<Rectangle> bounds = result.getSecond();
- assertNotNull(rootView);
-
- assertEquals("included", rootView.getName());
- assertNull(rootView.getParent());
- assertNull(rootView.getUiViewNode());
- // childView1 should have been removed since it has the wrong merge cookie
- assertEquals(1, rootView.getChildren().size());
- assertEquals(1, rootView.getUniqueChildren().size());
-
- Rectangle bounds1 = bounds.get(0);
- assertEquals(new Rectangle(0, 40, 49, 19), bounds1);
- }
-
- public void testGestureOverlayView() throws Exception {
- boolean layoutlib5 = true;
-
- // Test rendering of included views on layoutlib 5+ (e.g. has <include> tag)
-
- UiViewElementNode rootNode = createNode("android.gesture.GestureOverlayView", true);
- UiViewElementNode childNode = createNode(rootNode, "android.widget.LinearLayout", false);
- UiViewElementNode grandChildNode = createNode(childNode, "android.widget.Button", false);
- ViewInfo root = new ViewInfo("GestureOverlayView", rootNode, 10, 10, 100, 100);
- ViewInfo child = new ViewInfo("LinearLayout", childNode, 0, 0, 50, 20);
- root.setChildren(Collections.singletonList(child));
- ViewInfo grandChild = new ViewInfo("Button", grandChildNode, 0, 20, 70, 25);
- child.setChildren(Collections.singletonList(grandChild));
- CanvasViewInfo rootView = CanvasViewInfo.create(root, layoutlib5).getFirst();
- assertNotNull(rootView);
- assertEquals("GestureOverlayView", rootView.getName());
-
- assertTrue(rootView.isRoot());
- assertNull(rootView.getParent());
- assertSame(rootNode, rootView.getUiViewNode());
- assertEquals(1, rootView.getChildren().size());
-
- CanvasViewInfo childView = rootView.getChildren().get(0);
- assertEquals("LinearLayout", childView.getName());
-
- // This should also be a root for the special case that the root is
- assertTrue(childView.isRoot());
-
- assertEquals(1, childView.getChildren().size());
- CanvasViewInfo grandChildView = childView.getChildren().get(0);
- assertEquals("Button", grandChildView.getName());
- assertFalse(grandChildView.isRoot());
- }
-
- public void testListView() throws Exception {
- // For ListViews we get AdapterItemReferences as cookies. Ensure that this
- // works properly.
- //
- // android.widget.FrameLayout [0,50,320,480] <FrameLayout>
- // android.widget.ListView [0,0,320,430] <ListView>
- // android.widget.LinearLayout [0,0,320,17] SessionParams$AdapterItemReference
- // android.widget.TextView [0,0,73,17]
- // android.widget.LinearLayout [0,18,320,35] SessionParams$AdapterItemReference
- // android.widget.TextView [0,0,73,17]
- // android.widget.LinearLayout [0,36,320,53] SessionParams$AdapterItemReference
- // android.widget.TextView [0,0,73,17]
- // ...
-
- UiViewElementNode rootNode = createNode("FrameLayout", true);
- UiViewElementNode childNode = createNode(rootNode, "ListView", false);
- /*UiViewElementNode grandChildNode =*/ createNode(childNode, "LinearLayout", false);
- /*UiViewElementNode greatGrandChildNode =*/ createNode(childNode, "TextView", false);
- DataBindingItem dataBindingItem = new DataBindingItem("foo");
-
- ViewInfo root = new ViewInfo("FrameLayout", rootNode, 0, 50, 320, 480);
- ViewInfo child = new ViewInfo("ListView", childNode, 0, 0, 320, 430);
- root.setChildren(Collections.singletonList(child));
- ViewInfo grandChild = new ViewInfo("LinearLayout", dataBindingItem, 0, 0, 320, 17);
- child.setChildren(Collections.singletonList(grandChild));
- ViewInfo greatGrandChild = new ViewInfo("Button", null, 0, 0, 73, 17);
- grandChild.setChildren(Collections.singletonList(greatGrandChild));
- CanvasViewInfo rootView = CanvasViewInfo.create(root, true /*layoutlib5*/).getFirst();
- assertNotNull(rootView);
-
- assertEquals("FrameLayout", rootView.getName());
- assertEquals(1, rootView.getChildren().size());
- assertSame(rootNode, rootView.getUiViewNode());
-
- CanvasViewInfo childView = rootView.getChildren().get(0);
- assertEquals("ListView", childView.getName());
- assertEquals(0, childView.getChildren().size());
- assertSame(childNode, childView.getUiViewNode());
- }
-
- /**
- * Dumps out the given {@link ViewInfo} hierarchy to standard out.
- * Useful during development.
- *
- * @param graphicalEditor the editor associated with this hierarchy
- * @param root the root of the {@link ViewInfo} hierarchy
- */
- public static void dump(GraphicalEditorPart graphicalEditor, ViewInfo root) {
- System.out.println("\n\nRendering:");
- boolean supportsEmbedding = graphicalEditor.renderingSupports(Capability.EMBEDDED_LAYOUT);
- System.out.println("Supports Embedded Layout=" + supportsEmbedding);
- System.out.println("Rendering context=" + graphicalEditor.getIncludedWithin());
- dump(root, 0);
- }
-
- /** Helper for {@link #dump(GraphicalEditorPart, ViewInfo)} */
- public static void dump(ViewInfo info, int depth) {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < depth; i++) {
- sb.append(" ");
- }
- sb.append(info.getClassName());
- sb.append(" [");
- sb.append(info.getLeft());
- sb.append(",");
- sb.append(info.getTop());
- sb.append(",");
- sb.append(info.getRight());
- sb.append(",");
- sb.append(info.getBottom());
- sb.append("] ");
- Object cookie = info.getCookie();
- if (cookie instanceof UiViewElementNode) {
- sb.append(" ");
- UiViewElementNode node = (UiViewElementNode) cookie;
- sb.append("<");
- sb.append(node.getDescriptor().getXmlName());
- sb.append("> ");
- } else if (cookie != null) {
- sb.append(" cookie=" + cookie);
- }
-
- System.out.println(sb.toString());
-
- for (ViewInfo child : info.getChildren()) {
- dump(child, depth + 1);
- }
- }
-
- /** Helper for {@link #dump(GraphicalEditorPart, ViewInfo)} */
- public static void dump(CanvasViewInfo info, int depth) {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < depth; i++) {
- sb.append(" ");
- }
- sb.append(info.getName());
- sb.append(" [");
- sb.append(info.getAbsRect());
- sb.append("], node=");
- sb.append(info.getUiViewNode());
-
- System.out.println(sb.toString());
-
- for (CanvasViewInfo child : info.getChildren()) {
- dump(child, depth + 1);
- }
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ControlPointTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ControlPointTest.java
deleted file mode 100644
index 366691e61..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ControlPointTest.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import org.eclipse.swt.events.MouseEvent;
-
-public class ControlPointTest extends PointTestCases {
- public void testCreateFromMouseEvent() throws Exception {
- MouseEvent mouseEvent = canvasMouseEvent(10, 20, 0);
-
- ControlPoint point = ControlPoint.create(mCanvas, mouseEvent);
- assertEquals(10, point.x);
- assertEquals(20, point.y);
- }
-
- public void testCreateFromCoordinates() throws Exception {
- ControlPoint point = ControlPoint.create(mCanvas, 10, 20);
- assertEquals(10, point.x);
- assertEquals(20, point.y);
- }
-
- public void testConvertToLayout() throws Exception {
- ControlPoint point = ControlPoint.create(new TestLayoutCanvas(), 10, 20);
- assertEquals(10, point.x);
- assertEquals(20, point.y);
-
- LayoutPoint layoutPoint = point.toLayout();
- assertNotNull(layoutPoint);
- assertEquals(40, layoutPoint.x);
- assertEquals(60, layoutPoint.y);
-
- // For sanity let's also convert back and verify
- ControlPoint controlPoint = layoutPoint.toControl();
- assertNotNull(controlPoint);
- assertNotSame(controlPoint, point);
- assertEquals(point, controlPoint);
- assertEquals(10, controlPoint.x);
- assertEquals(20, controlPoint.y);
- }
-
- public void testEquals() throws Exception {
- ControlPoint point1 = ControlPoint.create(mCanvas, 1, 1);
- ControlPoint point2 = ControlPoint.create(mCanvas, 1, 2);
- ControlPoint point3 = ControlPoint.create(mCanvas, 2, 1);
- ControlPoint point2b = ControlPoint.create(mCanvas, 1, 2);
-
- assertFalse(point2.equals(null));
-
- assertEquals(point2, point2);
- assertEquals(point2, point2b);
- assertEquals(point2.hashCode(), point2b.hashCode());
- assertNotSame(point2, point2b);
-
- assertFalse(point1.equals(point2));
- assertFalse(point1.equals(point3));
- assertFalse(point2.equals(point3));
- assertFalse(point1.equals(point2));
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/DomUtilitiesTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/DomUtilitiesTest.java
deleted file mode 100644
index 6576bea3a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/DomUtilitiesTest.java
+++ /dev/null
@@ -1,206 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import static com.android.SdkConstants.ANDROID_URI;
-import static com.android.SdkConstants.TOOLS_URI;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-
-import java.util.Arrays;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class DomUtilitiesTest extends TestCase {
-
- public void testIsEquivalent() throws Exception {
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- factory.setNamespaceAware(true);
- factory.setValidating(false);
- DocumentBuilder builder = factory.newDocumentBuilder();
- Document document1 = builder.newDocument();
- Document document2 = builder.newDocument();
- document1.appendChild(document1.createElement("root"));
- document2.appendChild(document2.createElement("root"));
-
- assertFalse(DomUtilities.isEquivalent(null, null));
- Element root1 = document1.getDocumentElement();
- assertFalse(DomUtilities.isEquivalent(null, root1));
- Element root2 = document2.getDocumentElement();
- assertFalse(DomUtilities.isEquivalent(root2, null));
- assertTrue(DomUtilities.isEquivalent(root1, root2));
-
- root1.appendChild(document1.createTextNode(" "));
- // Differences in text are NOT significant!
- assertTrue(DomUtilities.isEquivalent(root1, root2));
- root2.appendChild(document2.createTextNode(" "));
- assertTrue(DomUtilities.isEquivalent(root1, root2));
-
- Element foo1 = document1.createElement("foo");
- Element foo2 = document2.createElement("foo");
- root1.appendChild(foo1);
- assertFalse(DomUtilities.isEquivalent(root1, root2));
- root2.appendChild(foo2);
- assertTrue(DomUtilities.isEquivalent(root1, root2));
-
- root1.appendChild(document1.createElement("bar"));
- assertFalse(DomUtilities.isEquivalent(root1, root2));
- root2.appendChild(document2.createElement("bar"));
- assertTrue(DomUtilities.isEquivalent(root1, root2));
-
- // Add attributes in opposite order
- foo1.setAttribute("attribute1", "value1");
- foo1.setAttribute("attribute2", "value2");
- assertFalse(DomUtilities.isEquivalent(root1, root2));
- foo2.setAttribute("attribute2", "value2");
- foo2.setAttribute("attribute1", "valueWrong");
- assertFalse(DomUtilities.isEquivalent(root1, root2));
- foo2.setAttribute("attribute1", "value1");
- assertTrue(DomUtilities.isEquivalent(root1, root2));
- foo2.setAttributeNS(TOOLS_URI, "foo", "bar");
- assertTrue(DomUtilities.isEquivalent(root1, root2));
- foo2.setAttributeNS(ANDROID_URI, "foo", "bar");
- assertFalse(DomUtilities.isEquivalent(root1, root2));
-
- // TODO - test different tag names
- // TODO - test different name spaces!
- }
-
- public void testIsContiguous() throws Exception {
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- factory.setNamespaceAware(true);
- factory.setValidating(false);
- DocumentBuilder builder = factory.newDocumentBuilder();
- Document document = builder.newDocument();
- document.appendChild(document.createElement("root"));
- Element root = document.getDocumentElement();
- root.appendChild(document.createTextNode(" "));
- Element foo = document.createElement("foo");
- root.appendChild(foo);
- root.appendChild(document.createTextNode(" "));
- Element bar = document.createElement("bar");
- root.appendChild(bar);
- Element baz = document.createElement("baz");
- root.appendChild(baz);
-
- assertTrue(DomUtilities.isContiguous(Arrays.asList(foo)));
- assertTrue(DomUtilities.isContiguous(Arrays.asList(foo, bar)));
- assertTrue(DomUtilities.isContiguous(Arrays.asList(foo, bar, baz)));
- assertTrue(DomUtilities.isContiguous(Arrays.asList(foo, bar, baz)));
- assertTrue(DomUtilities.isContiguous(Arrays.asList(bar, baz, foo)));
- assertTrue(DomUtilities.isContiguous(Arrays.asList(baz, bar, foo)));
- assertTrue(DomUtilities.isContiguous(Arrays.asList(baz, foo, bar)));
-
- assertFalse(DomUtilities.isContiguous(Arrays.asList(foo, baz)));
- assertFalse(DomUtilities.isContiguous(Arrays.asList(root, baz)));
- }
-
- public void testGetCommonAncestor() throws Exception {
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- factory.setNamespaceAware(true);
- factory.setValidating(false);
- DocumentBuilder builder = factory.newDocumentBuilder();
- Document document = builder.newDocument();
-
- // A
- // / \
- // B C
- // / \
- // D E
-
- document.appendChild(document.createElement("A"));
- Element a = document.getDocumentElement();
- assertSame(a, DomUtilities.getCommonAncestor(a, a));
-
- Element b = document.createElement("B");
- a.appendChild(b);
- Element c = document.createElement("C");
- a.appendChild(c);
- Element d = document.createElement("D");
- c.appendChild(d);
- Element e = document.createElement("E");
- c.appendChild(e);
-
- assertSame(a, DomUtilities.getCommonAncestor(a, b));
- assertSame(a, DomUtilities.getCommonAncestor(b, a));
- assertSame(a, DomUtilities.getCommonAncestor(b, c));
- assertSame(a, DomUtilities.getCommonAncestor(b, d));
- assertSame(a, DomUtilities.getCommonAncestor(b, e));
- assertSame(a, DomUtilities.getCommonAncestor(a, e));
-
- assertSame(c, DomUtilities.getCommonAncestor(d, e));
- assertSame(c, DomUtilities.getCommonAncestor(c, e));
- assertSame(c, DomUtilities.getCommonAncestor(d, c));
- assertSame(c, DomUtilities.getCommonAncestor(c, c));
- }
-
- public void testGetDepth() throws Exception {
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- factory.setNamespaceAware(true);
- factory.setValidating(false);
- DocumentBuilder builder = factory.newDocumentBuilder();
- Document document = builder.newDocument();
-
- // A
- // / \
- // B C
- // / \
- // D E
-
- document.appendChild(document.createElement("A"));
- Element a = document.getDocumentElement();
- assertSame(a, DomUtilities.getCommonAncestor(a, a));
- Element b = document.createElement("B");
- a.appendChild(b);
- Element c = document.createElement("C");
- a.appendChild(c);
- Element d = document.createElement("D");
- c.appendChild(d);
- Element e = document.createElement("E");
- c.appendChild(e);
-
- assertEquals(0, DomUtilities.getDepth(document));
-
- assertEquals(1, DomUtilities.getDepth(a));
- assertEquals(2, DomUtilities.getDepth(b));
- assertEquals(2, DomUtilities.getDepth(c));
- assertEquals(3, DomUtilities.getDepth(d));
- assertEquals(3, DomUtilities.getDepth(e));
- }
-
- public void testHasChildren() throws Exception {
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- factory.setNamespaceAware(true);
- factory.setValidating(false);
- DocumentBuilder builder = factory.newDocumentBuilder();
- Document document = builder.newDocument();
- assertFalse(DomUtilities.hasElementChildren(document));
- document.appendChild(document.createElement("A"));
- Element a = document.getDocumentElement();
- assertFalse(DomUtilities.hasElementChildren(a));
- a.appendChild(document.createTextNode("foo"));
- assertFalse(DomUtilities.hasElementChildren(a));
- Element b = document.createElement("B");
- a.appendChild(b);
- assertTrue(DomUtilities.hasElementChildren(a));
- assertFalse(DomUtilities.hasElementChildren(b));
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ImageUtilsTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ImageUtilsTest.java
deleted file mode 100644
index d1c56c233..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/ImageUtilsTest.java
+++ /dev/null
@@ -1,368 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.ide.common.api.Rect;
-
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.graphics.Rectangle;
-
-import java.awt.Color;
-import java.awt.Graphics;
-import java.awt.Graphics2D;
-import java.awt.image.BufferedImage;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class ImageUtilsTest extends TestCase {
- public void testCropBlank() throws Exception {
- BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB_PRE);
- Graphics g = image.getGraphics();
- g.setColor(new Color(0, true));
- g.fillRect(0, 0, image.getWidth(), image.getHeight());
- g.dispose();
-
- BufferedImage crop = ImageUtils.cropBlank(image, null);
- assertNull(crop);
- }
-
- public void testCropBlankPre() throws Exception {
- BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB_PRE);
- Graphics g = image.getGraphics();
- g.setColor(new Color(0, true));
- g.fillRect(0, 0, image.getWidth(), image.getHeight());
- g.dispose();
-
- BufferedImage crop = ImageUtils.cropBlank(image, new Rect(5, 5, 80, 80));
- assertNull(crop);
- }
-
- public void testCropNonblank() throws Exception {
- BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB_PRE);
- Graphics g = image.getGraphics();
- g.setColor(new Color(0, false));
- g.fillRect(0, 0, image.getWidth(), image.getHeight());
- g.dispose();
-
- BufferedImage crop = ImageUtils.cropBlank(image, null);
- assertNotNull(crop);
- assertEquals(image.getWidth(), crop.getWidth());
- assertEquals(image.getHeight(), crop.getHeight());
- }
-
- public void testCropSomething() throws Exception {
- BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB_PRE);
- Graphics g = image.getGraphics();
- g.setColor(new Color(0, true));
- g.fillRect(0, 0, image.getWidth(), image.getHeight());
- g.setColor(new Color(0xFF00FF00, true));
- g.fillRect(25, 25, 50, 50);
- g.dispose();
-
- BufferedImage crop = ImageUtils.cropBlank(image, null);
- assertNotNull(crop);
- assertEquals(50, crop.getWidth());
- assertEquals(50, crop.getHeight());
- assertEquals(0xFF00FF00, crop.getRGB(0, 0));
- assertEquals(0xFF00FF00, crop.getRGB(49, 49));
- }
-
- public void testCropSomethingPre() throws Exception {
- BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB_PRE);
- Graphics g = image.getGraphics();
- g.setColor(new Color(0, true));
- g.fillRect(0, 0, image.getWidth(), image.getHeight());
- g.setColor(new Color(0xFF00FF00, true));
- g.fillRect(25, 25, 50, 50);
- g.dispose();
-
- BufferedImage crop = ImageUtils.cropBlank(image, new Rect(0, 0, 100, 100));
- assertNotNull(crop);
- assertEquals(50, crop.getWidth());
- assertEquals(50, crop.getHeight());
- assertEquals(0xFF00FF00, crop.getRGB(0, 0));
- assertEquals(0xFF00FF00, crop.getRGB(49, 49));
- }
-
- public void testCropSomethingPre2() throws Exception {
- BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB_PRE);
- Graphics g = image.getGraphics();
- g.setColor(new Color(0, true));
- g.fillRect(0, 0, image.getWidth(), image.getHeight());
- g.setColor(new Color(0xFF00FF00, true));
- g.fillRect(25, 25, 50, 50);
- g.dispose();
-
- BufferedImage crop = ImageUtils.cropBlank(image, new Rect(5, 5, 80, 80));
- assertNotNull(crop);
- assertEquals(50, crop.getWidth());
- assertEquals(50, crop.getHeight());
- assertEquals(0xFF00FF00, crop.getRGB(0, 0));
- assertEquals(0xFF00FF00, crop.getRGB(49, 49));
- }
-
- public void testCropColor() throws Exception {
- BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB_PRE);
- Graphics g = image.getGraphics();
- g.setColor(new Color(0xFF00FF00, true));
- g.fillRect(0, 0, image.getWidth(), image.getHeight());
- g.dispose();
-
- BufferedImage crop = ImageUtils.cropColor(image, 0xFF00FF00, null);
- assertNull(crop);
- }
-
- public void testCropNonColor() throws Exception {
- BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB_PRE);
- Graphics g = image.getGraphics();
- g.setColor(new Color(0xFF00FF00, true));
- g.fillRect(0, 0, image.getWidth(), image.getHeight());
- g.dispose();
-
- BufferedImage crop = ImageUtils.cropColor(image, 0xFFFF0000, null);
- assertNotNull(crop);
- assertEquals(image.getWidth(), crop.getWidth());
- assertEquals(image.getHeight(), crop.getHeight());
- }
-
- public void testCropColorSomething() throws Exception {
- BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB_PRE);
- Graphics g = image.getGraphics();
- g.setColor(new Color(0xFF00FF00, true));
- g.fillRect(0, 0, image.getWidth(), image.getHeight());
- g.setColor(new Color(0xFFFF0000, true));
- g.fillRect(25, 25, 50, 50);
- g.dispose();
-
- BufferedImage crop = ImageUtils.cropColor(image, 0xFF00FF00, null);
- assertEquals(50, crop.getWidth());
- assertEquals(50, crop.getHeight());
- assertEquals(0xFFFF0000, crop.getRGB(0, 0));
- assertEquals(0xFFFF0000, crop.getRGB(49, 49));
- }
-
- public void testNothingTodo() throws Exception {
- BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB_PRE);
- Graphics g = image.getGraphics();
- g.setColor(new Color(0xFF00FF00, true));
- g.fillRect(0, 0, image.getWidth(), image.getHeight());
- g.dispose();
-
- BufferedImage crop = ImageUtils.cropColor(image, 0xFFFF0000, new Rect(40, 40, 0, 0));
- assertNull(crop);
- }
-
- public void testContainsDarkPixels() throws Exception {
- BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB_PRE);
- Graphics g = image.getGraphics();
- g.setColor(new Color(0, true));
- g.fillRect(0, 0, image.getWidth(), image.getHeight());
- g.dispose();
-
- assertFalse(ImageUtils.containsDarkPixels(image));
-
- image.setRGB(50, 50, 0xFFFFFFFF);
- assertFalse(ImageUtils.containsDarkPixels(image));
- image.setRGB(50, 50, 0xFFAAAAAA);
- assertFalse(ImageUtils.containsDarkPixels(image));
- image.setRGB(50, 50, 0xFF00FF00);
- assertFalse(ImageUtils.containsDarkPixels(image));
- image.setRGB(50, 50, 0xFFFF8800);
- assertFalse(ImageUtils.containsDarkPixels(image));
- image.setRGB(50, 50, 0xFF333333);
- assertTrue(ImageUtils.containsDarkPixels(image));
-
- }
-
- public void testGetBoundingRectangle() {
- assertEquals(null, ImageUtils.getBoundingRectangle(Collections.<Rectangle> emptyList()));
-
- assertEquals(new Rectangle(1, 2, 3, 4), ImageUtils.getBoundingRectangle(Arrays
- .asList(new Rectangle(1, 2, 3, 4))));
- assertEquals(new Rectangle(1, 2, 3, 4), ImageUtils.getBoundingRectangle(Arrays
- .asList(new Rectangle(1, 2, 3, 4), new Rectangle(1, 2, 1, 1))));
- assertEquals(new Rectangle(5, 5, 25, 25), ImageUtils.getBoundingRectangle(Arrays.asList(
- new Rectangle(10, 10, 20, 20), new Rectangle(5, 5, 1, 1))));
- }
-
- /**
- * Paints a set of {@link Rectangle} object out of a rendered {@link BufferedImage}
- * such that the resulting image is transparent except for a minimum bounding
- * rectangle of the selected elements.
- *
- * @param image the source image
- * @param rectangles the set of rectangles to copy
- * @param boundingBox the bounding rectangle of the set of rectangles to copy, can be
- * computed by {@link ImageUtils#getBoundingRectangle}
- * @param scale a scale factor to apply to the result, e.g. 0.5 to shrink the
- * destination down 50%, 1.0 to leave it alone and 2.0 to zoom in by
- * doubling the image size
- * @return a rendered image, or null
- */
- public static BufferedImage drawRectangles(BufferedImage image,
- List<Rectangle> rectangles, Rectangle boundingBox, double scale) {
-
- // This code is not a test. When I implemented image cropping, I first implemented
- // it for BufferedImages (since it's easier; easy image painting, easy scaling,
- // easy transparency handling, etc). However, this meant that we would need to
- // convert the SWT images from the ImageOverlay to BufferedImages, crop and convert
- // back; not ideal, so I rewrote it in SWT (see SwtUtils). However, I
- // don't want to throw away the code in case we start keeping BufferedImages rather
- // than SWT images or need it for other purposes, but rather than place it in the
- // production codebase I'm leaving this utility here in the associated ImageUtils
- // test class. It was used like this:
- // @formatter:off
- //
- // BufferedImage wholeImage = SwtUtils.convertToAwt(image);
- // BufferedImage result = ImageUtils.cropSelection(wholeImage,
- // rectangles, boundingBox, scale);
- // e.image = SwtUtils.convertToSwt(image.getDevice(), result, true,
- // DRAG_TRANSPARENCY);
- //
- // @formatter:on
-
- if (boundingBox == null) {
- return null;
- }
-
- int destWidth = (int) (scale * boundingBox.width);
- int destHeight = (int) (scale * boundingBox.height);
- BufferedImage dest = new BufferedImage(destWidth, destHeight, image.getType());
-
- Graphics2D g = dest.createGraphics();
-
- for (Rectangle bounds : rectangles) {
- int dx1 = bounds.x - boundingBox.x;
- int dy1 = bounds.y - boundingBox.y;
- int dx2 = dx1 + bounds.width;
- int dy2 = dy1 + bounds.height;
-
- dx1 *= scale;
- dy1 *= scale;
- dx2 *= scale;
- dy2 *= scale;
-
- int sx1 = bounds.x;
- int sy1 = bounds.y;
- int sx2 = sx1 + bounds.width;
- int sy2 = sy1 + bounds.height;
-
- g.drawImage(image, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, null);
- }
-
- g.dispose();
-
- return dest;
- }
-
- public void testSubImage() throws Exception {
- BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB_PRE);
- Graphics g = image.getGraphics();
- g.setColor(new Color(0xFF00FF00, true));
- g.fillRect(0, 0, image.getWidth(), image.getHeight());
- g.setColor(new Color(0xFFFF0000, true));
- g.fillRect(25, 25, 50, 50);
- g.dispose();
-
- BufferedImage sub = ImageUtils.subImage(image, 25, 25, 35, 45);
- assertEquals(10, sub.getWidth());
- assertEquals(20, sub.getHeight());
- assertEquals(0xFFFF0000, sub.getRGB(0, 0));
- assertEquals(0xFFFF0000, sub.getRGB(9, 9));
-
- sub = ImageUtils.subImage(image, 23, 23, 23 + 5, 23 + 5);
- assertEquals(5, sub.getWidth());
- assertEquals(5, sub.getHeight());
- assertEquals(0xFF00FF00, sub.getRGB(0, 0));
- assertEquals(0xFFFF0000, sub.getRGB(4, 4));
- }
-
- public void testGetColor() throws Exception {
- assertEquals(0xFF000000, ImageUtils.getColor("#000"));
- assertEquals(0xFF000000, ImageUtils.getColor("#000000"));
- assertEquals(0xABCDEF91, ImageUtils.getColor("#ABCDEF91"));
- }
-
- public void testGetBrightness() throws Exception {
- assertEquals(96, ImageUtils.getBrightness(0x456789));
- assertEquals(198, ImageUtils.getBrightness(0xABCDEF));
-
- assertEquals(0, ImageUtils.getBrightness(0x0));
- assertEquals(255, ImageUtils.getBrightness(0xFFFFFF));
- assertEquals(299*255/1000, ImageUtils.getBrightness(0xFF0000));
- assertEquals(587*255/1000, ImageUtils.getBrightness(0x00FF00));
- assertEquals(114*255/1000, ImageUtils.getBrightness(0x0000FF));
- }
-
- public void testColorConversion() throws Exception {
- assertEquals(0, ImageUtils.rgbToInt(ImageUtils.intToRgb(0), 0));
- assertEquals(0xFFFFFFFF, ImageUtils.rgbToInt(ImageUtils.intToRgb(0xFFFFFF), 0xFF));
- assertEquals(0x12345678, ImageUtils.rgbToInt(ImageUtils.intToRgb(0x345678), 0x12));
- }
-
- public void testScaleImage() throws Exception {
- BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB_PRE);
- Graphics g = image.getGraphics();
- g.setColor(new Color(0xFF00FF00, true));
- g.fillRect(0, 0, image.getWidth(), image.getHeight());
- g.setColor(new Color(0xFFFF0000, true));
- g.fillRect(25, 25, 50, 50);
- g.dispose();
-
- BufferedImage scaled = ImageUtils.scale(image, 0.5, 0.5);
- assertEquals(50, scaled.getWidth());
- assertEquals(50, scaled.getHeight());
- assertEquals(0xFF00FF00, scaled.getRGB(0, 0));
- assertEquals(0xFF00FF00, scaled.getRGB(49, 49));
- assertEquals(0xFFFF0000, scaled.getRGB(25, 25));
-
- scaled = ImageUtils.scale(image, 2.0, 2.0);
- assertEquals(200, scaled.getWidth());
- assertEquals(200, scaled.getHeight());
- assertEquals(0xFF00FF00, scaled.getRGB(0, 0));
- assertEquals(0xFF00FF00, scaled.getRGB(48, 48));
- assertEquals(0xFFFF0000, scaled.getRGB(100, 100));
- assertEquals(0xFF00FF00, scaled.getRGB(199, 199));
-
- scaled = ImageUtils.scale(image, 0.25, 0.25);
- assertEquals(25, scaled.getWidth());
- assertEquals(25, scaled.getHeight());
- assertEquals(0xFF00FF00, scaled.getRGB(0, 0));
- assertEquals(0xFF00FF00, scaled.getRGB(24, 24));
- assertEquals(0xFFFF0000, scaled.getRGB(13, 13));
-
- scaled = ImageUtils.scale(image, 0.25, 0.25, 75, 95);
- assertEquals(100, scaled.getWidth());
- assertEquals(120, scaled.getHeight());
- assertEquals(0xFF00FF00, scaled.getRGB(0, 0));
- assertEquals(0xFF00FF00, scaled.getRGB(24, 24));
- assertEquals(0xFFFF0000, scaled.getRGB(13, 13));
-
- }
-
- public void testCreateColoredImage() throws Exception {
- BufferedImage image = ImageUtils.createColoredImage(120, 110, new RGB(0xFE, 0xFD, 0xFC));
- assertEquals(120, image.getWidth());
- assertEquals(110, image.getHeight());
- assertEquals(0xFFFEFDFC, image.getRGB(0, 0));
- assertEquals(0xFFFEFDFC, image.getRGB(50, 50));
- assertEquals(0xFFFEFDFC, image.getRGB(119, 109));
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/IncludeFinderTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/IncludeFinderTest.java
deleted file mode 100644
index c86623cd6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/IncludeFinderTest.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class IncludeFinderTest extends TestCase {
- public void testEncodeDecode1() throws Exception {
- // Test ending with just a key
- String s = "bar,baz,foo";
- assertEquals(s, IncludeFinder.encodeMap(IncludeFinder.decodeMap(s)));
- }
-
- public void testDecode1() throws Exception {
- // Test ending with just a key
- String s = "foo";
- assertTrue(IncludeFinder.decodeMap(s).containsKey("foo"));
- assertEquals(0, IncludeFinder.decodeMap(s).get("foo").size());
- }
-
- public void testDecode2() throws Exception {
- // Test ending with just a key
- String s = "foo=>{bar,baz}";
- assertTrue(IncludeFinder.decodeMap(s).containsKey("foo"));
- assertEquals("[bar, baz]",
- IncludeFinder.decodeMap(s).get("foo").toString());
- }
-
- public void testNoBlanks() throws Exception {
- // Make sure we skip the },
- String s = "foo=>{bar,baz},bar";
- assertNull(IncludeFinder.decodeMap(s).get(""));
- }
-
- public void testEncodeDecode2() throws Exception {
- // Test ending with just a key
- String s = "bar,key1=>{value1,value2},key2=>{value3,value4}";
- assertEquals(s, IncludeFinder.encodeMap(IncludeFinder.decodeMap(s)));
- }
-
- public void testUpdates() throws Exception {
- IncludeFinder finder = IncludeFinder.create();
- assertEquals(null, finder.getIncludedBy("foo"));
-
- finder.setIncluded("bar", Arrays.<String>asList("foo", "baz"), false);
- finder.setIncluded("baz", Arrays.<String>asList("foo"), false);
- assertEquals(Arrays.asList("bar", "baz"), finder.getIncludedBy("foo"));
- finder.setIncluded("bar", Collections.<String>emptyList(), false);
- assertEquals(Arrays.asList("baz"), finder.getIncludedBy("foo"));
- finder.setIncluded("baz", Collections.<String>emptyList(), false);
- assertEquals(Collections.emptyList(), finder.getIncludedBy("foo"));
- }
-
- public void testFindIncludes() throws Exception {
- String xml =
- "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
- "<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\"\n" +
- " android:orientation=\"vertical\" >\n" +
- "\n" +
- " <RadioButton\n" +
- " android:id=\"@+id/radioButton1\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:text=\"RadioButton\" />\n" +
- "\n" +
- " <include\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " layout=\"@layout/layout3\" />\n" +
- "\n" +
- " <include\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " layout=\"@layout/layout4\" />\n" +
- "\n" +
- "</LinearLayout>";
- List<String> includes = IncludeFinder.findIncludes(xml);
- Collections.sort(includes);
- assertEquals(Arrays.asList("layout3", "layout4"), includes);
- }
-
- public void testFindFragments() throws Exception {
- String xml =
- "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" +
- " xmlns:tools=\"http://schemas.android.com/tools\"\n" +
- " android:layout_width=\"match_parent\"\n" +
- " android:layout_height=\"match_parent\"\n" +
- " tools:context=\".MainActivity\" >\n" +
- "\n" +
- " <fragment\n" +
- " android:id=\"@+id/fragment1\"\n" +
- " android:name=\"android.app.ListFragment\"\n" +
- " android:layout_width=\"wrap_content\"\n" +
- " android:layout_height=\"wrap_content\"\n" +
- " android:layout_alignParentLeft=\"true\"\n" +
- " android:layout_alignParentTop=\"true\"\n" +
- " android:layout_marginLeft=\"58dp\"\n" +
- " android:layout_marginTop=\"74dp\"\n" +
- " tools:layout=\"@layout/myfragment\" />\n" +
- "\n" +
- "</RelativeLayout>";
- List<String> includes = IncludeFinder.findIncludes(xml);
- Collections.sort(includes);
- assertEquals(Arrays.asList("myfragment"), includes);
- }
-
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/IncludeOverlayTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/IncludeOverlayTest.java
deleted file mode 100644
index a96b1a387..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/IncludeOverlayTest.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import org.eclipse.swt.graphics.Rectangle;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-import java.util.Random;
-
-import junit.framework.TestCase;
-
-public class IncludeOverlayTest extends TestCase {
-
- public void testSubtractRectangles() throws Exception {
- checkSubtract(new Rectangle(0, 0, 100, 80), Collections.<Rectangle> emptyList());
-
- checkSubtract(new Rectangle(0, 0, 100, 80), Arrays.asList(new Rectangle(50, 50, 20, 20)));
-
- checkSubtract(new Rectangle(0, 0, 100, 80), Arrays.asList(new Rectangle(50, 50, 20, 20),
- new Rectangle(90, 90, 10, 10)));
-
- checkSubtract(new Rectangle(0, 0, 100, 80), Arrays.asList(new Rectangle(50, 50, 20, 20),
- new Rectangle(90, 90, 10, 10), new Rectangle(0, 0, 10, 10)));
-
- }
-
- private void checkSubtract(Rectangle rectangle, List<Rectangle> holes) {
- Collection<Rectangle> result = IncludeOverlay.subtractRectangles(rectangle, holes);
-
- // Do some Monte Carlo testing - pick random coordinates and check that if they
- // are within one of the holes then they are not in the result list and vice versa
- Random random = new Random(42L);
- for (int i = 0; i < 1000; i++) {
- int x = random.nextInt(rectangle.width);
- int y = random.nextInt(rectangle.height);
-
- boolean inHole = false;
- for (Rectangle hole : holes) {
- if (hole.contains(x, y)) {
- inHole = true;
- }
- }
-
- boolean inResult = false;
- for (Rectangle r : result) {
- if (r.contains(x, y)) {
- inResult = true;
- break;
- }
- }
-
- if (inHole == inResult) {
- fail("Wrong result at (" + x + "," + y + ") for rectangle=" + rectangle
- + " and holes=" + holes + " where inHole=inResult="
- + inResult);
- }
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutPointTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutPointTest.java
deleted file mode 100644
index c053de854..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/LayoutPointTest.java
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-public class LayoutPointTest extends PointTestCases {
- public void testCreateFromCoordinates() throws Exception {
- LayoutPoint point = LayoutPoint.create(mCanvas, 10, 20);
- assertEquals(10, point.x);
- assertEquals(20, point.y);
- }
-
- public void testEquals() throws Exception {
- LayoutPoint point1 = LayoutPoint.create(mCanvas, 1, 1);
- LayoutPoint point2 = LayoutPoint.create(mCanvas, 1, 2);
- LayoutPoint point3 = LayoutPoint.create(mCanvas, 2, 1);
- LayoutPoint point2b = LayoutPoint.create(mCanvas, 1, 2);
-
- assertFalse(point2.equals(null));
-
- assertEquals(point2, point2);
- assertEquals(point2, point2b);
- assertEquals(point2.hashCode(), point2b.hashCode());
- assertNotSame(point2, point2b);
-
- assertFalse(point1.equals(point2));
- assertFalse(point1.equals(point3));
- assertFalse(point2.equals(point3));
- assertFalse(point1.equals(point2));
- }
-
- public void testConvertToControl() throws Exception {
- LayoutPoint point = LayoutPoint.create(new TestLayoutCanvas(), 10, 20);
- assertEquals(10, point.x);
- assertEquals(20, point.y);
-
- ControlPoint controlPoint = point.toControl();
- assertNotNull(controlPoint);
- assertEquals(-5, controlPoint.x);
- assertEquals(0, controlPoint.y);
-
- // For sanity let's also convert back and verify
- LayoutPoint layoutPoint = controlPoint.toLayout();
- assertNotNull(layoutPoint);
- assertNotSame(layoutPoint, point);
- assertEquals(point, layoutPoint);
- assertEquals(10, layoutPoint.x);
- assertEquals(20, layoutPoint.y);
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/PointTestCases.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/PointTestCases.java
deleted file mode 100644
index 91d0e133f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/PointTestCases.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.events.MouseEvent;
-import org.eclipse.swt.widgets.Event;
-import org.eclipse.swt.widgets.List;
-import org.eclipse.swt.widgets.ScrollBar;
-import org.eclipse.swt.widgets.Shell;
-
-import junit.framework.TestCase;
-
-/**
- * Common utilities for the point tests {@link LayoutPointTest} and
- * {@link ControlPointTest}
- */
-public class PointTestCases extends TestCase {
- LayoutCanvas mCanvas = new TestLayoutCanvas();
-
- protected MouseEvent canvasMouseEvent(int x, int y, int stateMask) {
- Event event = new Event();
- event.x = x;
- event.y = y;
- event.stateMask = stateMask;
- event.widget = mCanvas;
- MouseEvent mouseEvent = new MouseEvent(event);
- return mouseEvent;
- }
-
- /** Mock implementation of LayoutCanvas */
- protected static class TestLayoutCanvas extends LayoutCanvas {
- float mScaleX;
-
- float mScaleY;
-
- float mTranslateX;
-
- float mTranslateY;
-
- public TestLayoutCanvas(float scaleX, float scaleY, float translateX, float translateY) {
- super(null, null, new Shell(), 0);
-
- this.mScaleX = scaleX;
- this.mScaleY = scaleY;
- this.mTranslateX = translateX;
- this.mTranslateY = translateY;
- }
-
- public TestLayoutCanvas() {
- this(2.0f, 2.0f, 20.0f, 20.0f);
- }
-
- @Override
- CanvasTransform getHorizontalTransform() {
- ScrollBar scrollBar = new List(this, SWT.V_SCROLL|SWT.H_SCROLL).getHorizontalBar();
- return new TestCanvasTransform(scrollBar, mScaleX, mTranslateX);
- }
-
- @Override
- CanvasTransform getVerticalTransform() {
- ScrollBar scrollBar = new List(this, SWT.V_SCROLL|SWT.H_SCROLL).getVerticalBar();
- return new TestCanvasTransform(scrollBar, mScaleY, mTranslateY);
- }
- }
-
- static class TestCanvasTransform extends CanvasTransform {
- float mScale;
-
- float mTranslate;
-
- public TestCanvasTransform(ScrollBar scrollBar, float scale, float translate) {
- super(null, scrollBar);
- this.mScale = scale;
- this.mTranslate = translate;
- }
-
- @Override
- public int translate(int value) {
- return (int) ((value - mTranslate) / mScale);
- }
-
- @Override
- public int inverseTranslate(int value) {
- return (int) (value * mScale + mTranslate);
- }
- }
-
- public void testDummy() {
- // To avoid JUnit warning that this class contains no tests, even though
- // this is an abstract class and JUnit shouldn't try
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderLoggerTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderLoggerTest.java
deleted file mode 100644
index c28d9a966..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/RenderLoggerTest.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import junit.framework.TestCase;
-
-public class RenderLoggerTest extends TestCase {
- public void testLogger1() throws Exception {
- RenderLogger l = new RenderLogger("foo", null);
- assertFalse(l.hasProblems());
- }
-
- public void testLogger2() throws Exception {
- RenderLogger l = new RenderLogger("foo", null);
- assertFalse(l.hasProblems());
- l.fidelityWarning(null, "No perspective Transforms", null, null);
- l.fidelityWarning(null, "No GPS", null, null);
- assertTrue(l.hasProblems());
- assertEquals("The graphics preview in the layout editor may not be accurate:\n"
- + "* No perspective Transforms\n" + "* No GPS\n", l.getProblems(true));
- assertFalse(l.seenTag("foo"));
- assertFalse(l.seenTag(null));
- }
-
- public void testLogger3() throws Exception {
- RenderLogger l = new RenderLogger("foo", null);
- assertFalse(l.hasProblems());
- l.error("timeout", "Sample Error", new RuntimeException(), null);
- l.warning("slow", "Sample warning", null);
- assertTrue(l.hasProblems());
- assertEquals("Sample Error\n" + "Sample warning\n"
- + "Exception details are logged in Window > Show View > Error Log",
- l.getProblems(true));
- assertFalse(l.seenTag("foo"));
- assertTrue(l.seenTag("timeout"));
- assertTrue(l.seenTag("slow"));
- assertFalse(l.seenTagPrefix("foo"));
- assertTrue(l.seenTagPrefix("timeout"));
- assertTrue(l.seenTagPrefix("slow"));
- assertTrue(l.seenTagPrefix("time"));
- assertFalse(l.seenTagPrefix("timeouts"));
- }
-
- public void testLoggerSuppressWarnings() throws Exception {
- RenderLogger l = new RenderLogger("foo", null);
- assertFalse(l.hasProblems());
- RenderLogger.ignoreFidelityWarning("No perspective Transforms");
- l.fidelityWarning(null, "No perspective Transforms", null, null);
- l.fidelityWarning(null, "No GPS", null, null);
- assertTrue(l.hasProblems());
- assertEquals("The graphics preview in the layout editor may not be accurate:\n"
- + "* No GPS\n", l.getProblems(true));
- assertEquals("", l.getProblems(false));
- assertFalse(l.seenTag("foo"));
- assertFalse(l.seenTag(null));
-
- l = new RenderLogger("foo", null);
- assertFalse(l.hasProblems());
- RenderLogger.ignoreFidelityWarning("No perspective Transforms");
- RenderLogger.ignoreFidelityWarning("No GPS");
- l.fidelityWarning(null, "No perspective Transforms", null, null);
- l.fidelityWarning(null, "No GPS", null, null);
- assertFalse(l.hasProblems());
- assertEquals("", l.getProblems(true));
- assertFalse(l.seenTag("foo"));
- assertFalse(l.seenTag(null));
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SelectionManagerTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SelectionManagerTest.java
deleted file mode 100644
index b29f9f3c5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SelectionManagerTest.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.ide.common.rendering.api.ViewInfo;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-
-import org.eclipse.swt.widgets.Shell;
-
-import java.util.Arrays;
-
-import junit.framework.TestCase;
-
-public class SelectionManagerTest extends TestCase {
- private SelectionManager createManager() {
- LayoutCanvas canvas = new LayoutCanvas(null, null, new Shell(), 0);
- return new SelectionManager(canvas);
- }
-
- public void testEmpty() {
- SelectionManager manager = createManager();
-
- assertNotNull(manager.getSelections());
- assertEquals(0, manager.getSelections().size());
- assertFalse(manager.hasMultiSelection());
- assertTrue(manager.isEmpty());
- }
-
- public void testBasic() {
- SelectionManager manager = createManager();
- assertTrue(manager.isEmpty());
-
- UiViewElementNode rootNode = CanvasViewInfoTest.createNode("android.widget.LinearLayout",
- true);
- ViewInfo root = new ViewInfo("LinearLayout", rootNode, 10, 10, 100, 100);
- UiViewElementNode child1Node = CanvasViewInfoTest.createNode(rootNode,
- "android.widget.Button", false);
- ViewInfo child1 = new ViewInfo("Button1", child1Node, 0, 0, 50, 20);
- UiViewElementNode child2Node = CanvasViewInfoTest.createNode(rootNode,
- "android.widget.Button", false);
- ViewInfo child2 = new ViewInfo("Button2", child2Node, 0, 20, 70, 25);
- root.setChildren(Arrays.asList(child1, child2));
- CanvasViewInfo rootView = CanvasViewInfo.create(root, true /* layoutlib5 */).getFirst();
- assertNotNull(rootView);
-
- manager.selectMultiple(Arrays.asList(rootView, rootView.getChildren().get(0), rootView
- .getChildren().get(1)));
- assertEquals(3, manager.getSelections().size());
- assertFalse(manager.isEmpty());
- assertTrue(manager.hasMultiSelection());
-
- // Expect read-only result; ensure that's the case
- try {
- manager.getSelections().remove(0);
- fail("Result should be read only collection");
- } catch (Exception e) {
- ; //ok, what we expected
- }
-
- manager.selectNone();
- assertEquals(0, manager.getSelections().size());
- assertTrue(manager.isEmpty());
-
- manager.selectSingle(rootView);
- assertEquals(1, manager.getSelections().size());
- assertFalse(manager.isEmpty());
- assertSame(rootView, manager.getSelections().get(0).getViewInfo());
-
- manager.selectMultiple(Arrays.asList(rootView, rootView.getChildren().get(0), rootView
- .getChildren().get(1)));
- assertEquals(3, manager.getSelections().size());
-
- manager.deselect(rootView.getChildren().get(0));
- assertEquals(2, manager.getSelections().size());
- manager.deselect(rootView);
- assertEquals(1, manager.getSelections().size());
- assertSame(rootView.getChildren().get(1), manager.getSelections().get(0).getViewInfo());
- }
-
- public void testSelectParent() {
- SelectionManager manager = createManager();
- assertTrue(manager.isEmpty());
-
- UiViewElementNode rootNode = CanvasViewInfoTest.createNode("android.widget.LinearLayout",
- true);
- ViewInfo root = new ViewInfo("LinearLayout", rootNode, 10, 10, 100, 100);
- UiViewElementNode child1Node = CanvasViewInfoTest.createNode(rootNode,
- "android.widget.Button", false);
- ViewInfo child1 = new ViewInfo("Button1", child1Node, 0, 0, 50, 20);
- UiViewElementNode child2Node = CanvasViewInfoTest.createNode(rootNode,
- "android.widget.Button", false);
- ViewInfo child2 = new ViewInfo("Button2", child2Node, 0, 20, 70, 25);
- root.setChildren(Arrays.asList(child1, child2));
- CanvasViewInfo rootView = CanvasViewInfo.create(root, true /* layoutlib5 */).getFirst();
- assertNotNull(rootView);
-
- manager.selectMultiple(Arrays.asList(rootView.getChildren().get(0)));
- assertEquals(1, manager.getSelections().size());
- assertFalse(manager.isEmpty());
- assertSame(rootView.getChildren().get(0), manager.getSelections().get(0).getViewInfo());
-
- manager.selectParent();
- assertEquals(1, manager.getSelections().size());
- assertFalse(manager.isEmpty());
- assertSame(rootView, manager.getSelections().get(0).getViewInfo());
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SimpleAttributeTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SimpleAttributeTest.java
deleted file mode 100755
index f4f8eb81a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SimpleAttributeTest.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.SdkConstants;
-
-import junit.framework.TestCase;
-
-public class SimpleAttributeTest extends TestCase {
-
- private SimpleAttribute a;
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- a = new SimpleAttribute(SdkConstants.NS_RESOURCES, "name", "value = with space ");
- }
-
- public final void testSimpleAttribute() {
- assertEquals(SdkConstants.NS_RESOURCES, a.getUri());
- assertEquals("name", a.getName());
- assertEquals("value = with space ", a.getValue());
- }
-
- public final void testGetUri() {
- assertEquals(SdkConstants.NS_RESOURCES, a.getUri());
- }
-
- public final void testGetName() {
- assertEquals("name", a.getName());
- }
-
- public final void testGetValue() {
- assertEquals("value = with space ", a.getValue());
- }
-
- public final void testToString() {
- assertEquals(
- "@name:" + SdkConstants.NS_RESOURCES + "=value = with space \n",
- a.toString());
- }
-
- public final void testParseString() {
- String s = "@name:" + SdkConstants.NS_RESOURCES + "=value = with space \n";
- SimpleAttribute b = SimpleAttribute.parseString(s);
- assertEquals(a, b);
- }
-
- public final void testEqualsObject() {
- assertFalse(a.equals(null));
- assertFalse(a.equals(new Object()));
-
- // wrong name
- assertFalse(a.equals(new SimpleAttribute(SdkConstants.NS_RESOURCES,
- "wrong name",
- "value = with space ")));
- // wrong value
- assertFalse(a.equals(new SimpleAttribute(SdkConstants.NS_RESOURCES,
- "name",
- "value")));
- // wrong uri
- assertFalse(a.equals(new SimpleAttribute("uri", "name", "value = with space ")));
- // all fields wrong
- assertFalse(a.equals(new SimpleAttribute("uri", "wrong name", "value")));
-
- assertTrue(a.equals(new SimpleAttribute(SdkConstants.NS_RESOURCES,
- "name",
- "value = with space ")));
- }
-
- public final void testHashCode() {
-
- int ah = a.hashCode();
-
- assertFalse(ah == new Object().hashCode());
-
- // wrong name
- assertFalse(ah == new SimpleAttribute(SdkConstants.NS_RESOURCES,
- "wrong name",
- "value = with space ").hashCode());
- // wrong value
- assertFalse(ah == new SimpleAttribute(SdkConstants.NS_RESOURCES,
- "name",
- "value").hashCode());
- // wrong uri
- assertFalse(ah == new SimpleAttribute("uri", "name", "value = with space ").hashCode());
- // all fields wrong
- assertFalse(ah == new SimpleAttribute("uri", "wrong name", "value").hashCode());
-
- assertEquals(ah, new SimpleAttribute(SdkConstants.NS_RESOURCES,
- "name",
- "value = with space ").hashCode());
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SimpleElementTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SimpleElementTest.java
deleted file mode 100755
index 091aa378c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SimpleElementTest.java
+++ /dev/null
@@ -1,343 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.ide.common.api.Rect;
-
-import java.util.Arrays;
-
-import junit.framework.TestCase;
-
-public class SimpleElementTest extends TestCase {
-
- private SimpleElement e;
-
- /**
- * Helper method to compare arrays' *content* is equal (instead of object identity).
- * Also produces a suitable output to understand mismatch, if any.
- * <p/>
- * Pre-requisite: The arrays' elements must properly implement {@link Object#equals(Object)}
- * and a sensible {@link Object#toString()}.
- */
- private static void assertArrayEquals(Object[] expected, Object[] actual) {
- if (!Arrays.equals(expected, actual)) {
- // In case of failure, transform the arguments into strings and let
- // assertEquals(string) handle it as it can produce a nice diff of the string.
- String strExpected = expected == null ? "(null)" : Arrays.toString(expected);
- String strActual = actual == null ? "(null)" : Arrays.toString(actual);
-
- if (strExpected.equals(strActual)) {
- fail(String.format("Array not equal:\n Expected[%d]=%s\n Actual[%d]=%s",
- expected == null ? 0 : expected.length,
- strExpected,
- actual == null ? 0 : actual.length,
- strActual));
- } else {
- assertEquals(strExpected, strActual);
- }
- }
- }
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
-
- e = new SimpleElement("android.view.LinearLayout", // fqcn
- "android.view.FrameLayout", // parentFqcn
- new Rect(10, 5, 60, 40), // bounds
- new Rect(0, 0, 320, 480)); // parentBounds
- }
-
- public final void testGetFqcn() {
- assertEquals("android.view.LinearLayout", e.getFqcn());
- }
-
- public final void testGetParentFqcn() {
- assertEquals("android.view.FrameLayout", e.getParentFqcn());
- }
-
- public final void testGetBounds() {
- assertEquals(new Rect(10, 5, 60, 40), e.getBounds());
- }
-
- public final void testGetParentBounds() {
- assertEquals(new Rect(0, 0, 320, 480), e.getParentBounds());
- }
-
- public final void testToString() {
- assertEquals("{V=3,N=android.view.LinearLayout,P=android.view.FrameLayout,R=10 5 60 40,Q=0 0 320 480\n" +
- "}\n",
- e.toString());
-
- e.addAttribute(new SimpleAttribute("uri", "name", "value"));
- e.addAttribute(new SimpleAttribute("my-uri", "second-name", "my = value "));
-
- assertEquals("{V=3,N=android.view.LinearLayout,P=android.view.FrameLayout,R=10 5 60 40,Q=0 0 320 480\n" +
- "@name:uri=value\n" +
- "@second-name:my-uri=my = value \n" +
- "}\n",
- e.toString());
-
- SimpleElement e2 = new SimpleElement("android.view.Button",
- "android.view.LinearLayout",
- new Rect(10, 20, 30, 40),
- new Rect(0, 0, 320, 480));
- e2.addAttribute(new SimpleAttribute("uri1", "name1", "value1"));
- SimpleElement e3 = new SimpleElement("android.view.CheckBox",
- "android.view.LinearLayout",
- new Rect(-1, -2, -3, -4), // invalid rect is ignored
- new Rect(-1, -2, -3, -4)); // invalid rectis ignored
- e3.addAttribute(new SimpleAttribute("uri2", "name2", "value2"));
- e3.addAttribute(new SimpleAttribute("uri3", "name3", "value3"));
- e.addInnerElement(e2);
- e.addInnerElement(e3);
-
- assertEquals("{V=3,N=android.view.LinearLayout,P=android.view.FrameLayout,R=10 5 60 40,Q=0 0 320 480\n" +
- "@name:uri=value\n" +
- "@second-name:my-uri=my = value \n" +
- "{V=3,N=android.view.Button,P=android.view.LinearLayout,R=10 20 30 40,Q=0 0 320 480\n" +
- "@name1:uri1=value1\n" +
- "}\n" +
- "{V=3,N=android.view.CheckBox,P=android.view.LinearLayout\n" +
- "@name2:uri2=value2\n" +
- "@name3:uri3=value3\n" +
- "}\n" +
- "}\n",
- e.toString());
- }
-
- public final void testParseString() {
- assertArrayEquals(
- new SimpleElement[] { new SimpleElement("android.view.LinearLayout",
- null, null, null) },
- SimpleElement.parseString(
- "{V=3,N=android.view.LinearLayout\n" +
- "}\n"));
-
- assertArrayEquals(
- new SimpleElement[] { new SimpleElement("android.view.LinearLayout",
- "android.view.FrameLayout",
- null, null) },
- SimpleElement.parseString(
- "{V=3,N=android.view.LinearLayout,P=android.view.FrameLayout\n" +
- "}\n"));
-
- assertArrayEquals(
- new SimpleElement[] { new SimpleElement("android.view.LinearLayout",
- null,
- new Rect(10, 5, 60, 40),
- new Rect(0, 0, 320, 480)) },
- SimpleElement.parseString(
- "{V=3,N=android.view.LinearLayout,R=10 5 60 40,Q=0 0 320 480\n" +
- "}\n"));
-
-
- assertArrayEquals(
- new SimpleElement[] { e },
- SimpleElement.parseString(
- "{V=3,N=android.view.LinearLayout,P=android.view.FrameLayout,R=10 5 60 40,Q=0 0 320 480\n" +
- "}\n"));
-
-
- e.addAttribute(new SimpleAttribute("uri", "name", "value"));
- e.addAttribute(new SimpleAttribute("my-uri", "second-name", "my = value "));
-
- assertArrayEquals(
- new SimpleElement[] { e },
- SimpleElement.parseString(
- "{V=3,N=android.view.LinearLayout,P=android.view.FrameLayout,R=10 5 60 40,Q=0 0 320 480\n" +
- "@name:uri=value\n" +
- "@second-name:my-uri=my = value \n" +
- "}\n"));
-
-
- SimpleElement e2 = new SimpleElement("android.view.Button",
- "android.view.LinearLayout",
- new Rect(10, 20, 30, 40),
- new Rect(0, 0, 320, 480));
- e2.addAttribute(new SimpleAttribute("uri1", "name1", "value1"));
- SimpleElement e3 = new SimpleElement("android.view.CheckBox",
- "android.view.LinearLayout",
- new Rect(-1, -2, -3, -4),
- new Rect(-1, -2, -3, -4));
- e3.addAttribute(new SimpleAttribute("uri2", "name2", "value2"));
- e3.addAttribute(new SimpleAttribute("uri3", "name3", "value3"));
- e.addInnerElement(e2);
- e.addInnerElement(e3);
-
- assertArrayEquals(
- new SimpleElement[] { e },
- SimpleElement.parseString(
- "{V=3,N=android.view.LinearLayout,P=android.view.FrameLayout,R=10 5 60 40,Q=0 0 320 480\n" +
- "@name:uri=value\n" +
- "@second-name:my-uri=my = value \n" +
- "{V=3,N=android.view.Button,P=android.view.LinearLayout,R=10 20 30 40,Q=0 0 320 480\n" +
- "@name1:uri1=value1\n" +
- "}\n" +
- "{V=3,N=android.view.CheckBox,P=android.view.LinearLayout,R=-1 -2 -3 -4,Q=-1 -2 -3 -4\n" +
- "@name2:uri2=value2\n" +
- "@name3:uri3=value3\n" +
- "}\n" +
- "}\n"));
-
- // Parse string can also parse an array of elements
- assertArrayEquals(
- new SimpleElement[] { e, e2, e3 },
- SimpleElement.parseString(
- "{V=3,N=android.view.LinearLayout,P=android.view.FrameLayout,R=10 5 60 40,Q=0 0 320 480\n" +
- "@name:uri=value\n" +
- "@second-name:my-uri=my = value \n" +
- "{V=3,N=android.view.Button,P=android.view.LinearLayout,R=10 20 30 40,Q=0 0 320 480\n" +
- "@name1:uri1=value1\n" +
- "}\n" +
- "{V=3,N=android.view.CheckBox,P=android.view.LinearLayout,R=-1 -2 -3 -4\n" +
- "@name2:uri2=value2\n" +
- "@name3:uri3=value3\n" +
- "}\n" +
- "}\n" +
- "{V=3,N=android.view.Button,P=android.view.LinearLayout,R=10 20 30 40,Q=0 0 320 480\n" +
- "@name1:uri1=value1\n" +
- "}\n" +
- "{V=3,N=android.view.CheckBox,P=android.view.LinearLayout,R=-1 -2 -3 -4,Q=-1 -2 -3 -4\n" +
- "@name2:uri2=value2\n" +
- "@name3:uri3=value3\n" +
- "}\n"));
-
- }
-
- public final void testAddGetAttribute() {
- assertNotNull(e.getAttributes());
- assertArrayEquals(
- new SimpleAttribute[] {},
- e.getAttributes());
-
- e.addAttribute(new SimpleAttribute("uri", "name", "value"));
- assertArrayEquals(
- new SimpleAttribute[] { new SimpleAttribute("uri", "name", "value") },
- e.getAttributes());
-
- e.addAttribute(new SimpleAttribute("my-uri", "second-name", "value"));
- assertArrayEquals(
- new SimpleAttribute[] { new SimpleAttribute("uri", "name", "value"),
- new SimpleAttribute("my-uri", "second-name", "value") },
- e.getAttributes());
-
- assertNull(e.getAttribute("unknown uri", "name"));
- assertNull(e.getAttribute("uri", "unknown name"));
- assertEquals(new SimpleAttribute("uri", "name", "value"),
- e.getAttribute("uri", "name"));
- assertEquals(new SimpleAttribute("my-uri", "second-name", "value"),
- e.getAttribute("my-uri", "second-name"));
- }
-
- public final void testAddGetInnerElements() {
- assertNotNull(e.getInnerElements());
- assertArrayEquals(
- new SimpleElement[] {},
- e.getInnerElements());
-
- e.addInnerElement(new SimpleElement("android.view.Button", null, null, null));
- assertArrayEquals(
- new SimpleElement[] { new SimpleElement("android.view.Button", null, null, null) },
- e.getInnerElements());
-
- e.addInnerElement(new SimpleElement("android.view.CheckBox", null, null, null));
- assertArrayEquals(
- new SimpleElement[] { new SimpleElement("android.view.Button", null, null, null),
- new SimpleElement("android.view.CheckBox", null, null, null) },
- e.getInnerElements());
- }
-
- public final void testEqualsObject() {
- assertFalse(e.equals(null));
- assertFalse(e.equals(new Object()));
-
- assertNotSame(new SimpleElement("android.view.LinearLayout",
- "android.view.FrameLayout",
- new Rect(10, 5, 60, 40),
- new Rect(0, 0, 320, 480)),
- e);
- assertEquals(new SimpleElement("android.view.LinearLayout",
- "android.view.FrameLayout",
- new Rect(10, 5, 60, 40),
- new Rect(0, 0, 320, 480)),
- e);
- assertTrue(e.equals(new SimpleElement("android.view.LinearLayout",
- "android.view.FrameLayout",
- new Rect(10, 5, 60, 40),
- new Rect(0, 0, 320, 480))));
-
- // not the same FQCN
- assertFalse(e.equals(new SimpleElement("android.view.Button",
- "android.view.FrameLayout",
- new Rect(10, 5, 60, 40),
- new Rect(0, 0, 320, 480))));
-
- // not the same parent
- assertFalse(e.equals(new SimpleElement("android.view.LinearLayout",
- "android.view.LinearLayout",
- new Rect(10, 5, 60, 40),
- new Rect(0, 0, 320, 480))));
-
- // not the same bounds
- assertFalse(e.equals(new SimpleElement("android.view.LinearLayout",
- "android.view.FrameLayout",
- new Rect(10, 25, 30, 40),
- new Rect(0, 0, 320, 480))));
-
- // not the same parent bounds
- assertFalse(e.equals(new SimpleElement("android.view.LinearLayout",
- "android.view.FrameLayout",
- new Rect(10, 5, 60, 40),
- new Rect(10, 100, 160, 240))));
- }
-
- public final void testHashCode() {
- int he = e.hashCode();
-
- assertEquals(he, new SimpleElement("android.view.LinearLayout",
- "android.view.FrameLayout",
- new Rect(10, 5, 60, 40),
- new Rect(0, 0, 320, 480)).hashCode());
-
-
- // not the same FQCN
- assertFalse(he == new SimpleElement("android.view.Button",
- "android.view.FrameLayout",
- new Rect(10, 5, 60, 40),
- new Rect(0, 0, 320, 480)).hashCode());
-
- // not the same parent
- assertFalse(he == new SimpleElement("android.view.LinearLayout",
- "android.view.Button",
- new Rect(10, 5, 60, 40),
- new Rect(0, 0, 320, 480)).hashCode());
-
- // not the same bounds
- assertFalse(he == new SimpleElement("android.view.LinearLayout",
- "android.view.FrameLayout",
- new Rect(10, 25, 30, 40),
- new Rect(0, 0, 320, 480)).hashCode());
-
- // not the same parent bounds
- assertFalse(he == new SimpleElement("android.view.LinearLayout",
- "android.view.FrameLayout",
- new Rect(10, 25, 30, 40),
- new Rect(10, 100, 160, 240)).hashCode());
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SwtUtilsTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SwtUtilsTest.java
deleted file mode 100644
index de7999c24..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gle2/SwtUtilsTest.java
+++ /dev/null
@@ -1,343 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gle2;
-
-import com.android.ide.common.api.Rect;
-
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.graphics.Image;
-import org.eclipse.swt.graphics.ImageData;
-import org.eclipse.swt.graphics.PaletteData;
-import org.eclipse.swt.graphics.RGB;
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.Shell;
-
-import java.awt.Color;
-import java.awt.Graphics;
-import java.awt.image.BufferedImage;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-public class SwtUtilsTest extends TestCase {
-
- public void testImageConvertNoAlpha() throws Exception {
- // Note: We need an TYPE_INT_ARGB SWT image here (instead of TYPE_INT_ARGB_PRE) to
- // prevent the alpha from being pre-multiplied into the RGB when drawing the image.
- BufferedImage inImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
- Graphics g = inImage.getGraphics();
- g.setColor(new Color(0xAA112233, true));
- g.fillRect(0, 0, inImage.getWidth(), inImage.getHeight());
- g.dispose();
-
- Shell shell = new Shell();
- Display display = shell.getDisplay();
-
- // Convert the RGB image, effectively discarding the alpha channel entirely.
- Image outImage = SwtUtils.convertToSwt(display, inImage, false, -1);
- assertNotNull(outImage);
-
- ImageData outData = outImage.getImageData();
- assertEquals(inImage.getWidth(), outData.width);
- assertEquals(inImage.getHeight(), outData.height);
- assertNull(outData.alphaData);
- assertEquals(SWT.TRANSPARENCY_NONE, outData.getTransparencyType());
-
- PaletteData inPalette = SwtUtils.getAwtPaletteData(inImage.getType());
- PaletteData outPalette = outData.palette;
-
- for (int y = 0; y < outData.height; y++) {
- for (int x = 0; x < outData.width; x++) {
- // Note: we can't compare pixel directly as integers since convertToSwt() might
- // have changed the RGBA ordering depending on the platform (e.g. it will on
- // Windows.)
- RGB expected = inPalette.getRGB( inImage.getRGB( x, y));
- RGB actual = outPalette.getRGB(outData.getPixel(x, y));
- assertEquals(expected, actual);
- }
- }
-
- // Convert back to AWT and compare with original AWT image
- BufferedImage awtImage = SwtUtils.convertToAwt(outImage);
- assertNotNull(awtImage);
-
- // Both image have the same RGBA ordering
- assertEquals(BufferedImage.TYPE_INT_ARGB, inImage.getType());
- assertEquals(BufferedImage.TYPE_INT_ARGB, awtImage.getType());
-
- int awtAlphaMask = 0xFF000000;
-
- for (int y = 0; y < outData.height; y++) {
- for (int x = 0; x < outData.width; x++) {
- // Note: we can compare pixels as integers since we just
- // asserted both images have the same color image type except
- // for the content of the alpha channel.
- int actual = awtImage.getRGB(x, y);
- assertEquals(awtAlphaMask, actual & awtAlphaMask);
- assertEquals(awtAlphaMask | inImage.getRGB(x, y), awtImage.getRGB(x, y));
- }
- }
- }
-
- public void testImageConvertGlobalAlpha() throws Exception {
- BufferedImage inImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
- Graphics g = inImage.getGraphics();
- g.setColor(new Color(0xAA112233, true));
- g.fillRect(0, 0, inImage.getWidth(), inImage.getHeight());
- g.dispose();
-
- Shell shell = new Shell();
- Display display = shell.getDisplay();
-
- Image outImage = SwtUtils.convertToSwt(display, inImage, false, 128);
- assertNotNull(outImage);
-
- ImageData outData = outImage.getImageData();
- assertEquals(inImage.getWidth(), outData.width);
- assertEquals(inImage.getHeight(), outData.height);
- assertEquals(128, outData.alpha);
- assertEquals(SWT.TRANSPARENCY_NONE, outData.getTransparencyType());
- assertNull(outData.alphaData);
-
- PaletteData inPalette = SwtUtils.getAwtPaletteData(inImage.getType());
- PaletteData outPalette = outData.palette;
-
- for (int y = 0; y < outData.height; y++) {
- for (int x = 0; x < outData.width; x++) {
-
- RGB expected = inPalette.getRGB( inImage.getRGB( x, y));
- RGB actual = outPalette.getRGB(outData.getPixel(x, y));
- assertEquals(expected, actual);
- }
- }
- }
-
- public void testImageConvertAlpha() throws Exception {
- BufferedImage inImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
- Graphics g = inImage.getGraphics();
- g.setColor(new Color(0xAA112233, true));
- g.fillRect(0, 0, inImage.getWidth(), inImage.getHeight());
- g.dispose();
-
- Shell shell = new Shell();
- Display display = shell.getDisplay();
-
- Image outImage = SwtUtils.convertToSwt(display, inImage, true, -1);
- assertNotNull(outImage);
-
- ImageData outData = outImage.getImageData();
- assertEquals(inImage.getWidth(), outData.width);
- assertEquals(inImage.getHeight(), outData.height);
- assertEquals(SWT.TRANSPARENCY_ALPHA, outData.getTransparencyType());
-
- PaletteData inPalette = SwtUtils.getAwtPaletteData(inImage.getType());
- PaletteData outPalette = outData.palette;
-
- for (int y = 0; y < outData.height; y++) {
- for (int x = 0; x < outData.width; x++) {
- RGB expected = inPalette.getRGB( inImage.getRGB( x, y));
- RGB actual = outPalette.getRGB(outData.getPixel(x, y));
- assertEquals(expected, actual);
-
- // Note: >> instead of >>> since we will compare with byte (a signed number)
- int expectedAlpha = inImage.getRGB(x, y) >> 24;
- int actualAlpha = outData.alphaData[y * outData.width + x];
- assertEquals(expectedAlpha, actualAlpha);
- }
- }
- }
-
- public void testImageConvertAlphaMultiplied() throws Exception {
- BufferedImage inImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
- Graphics g = inImage.getGraphics();
- g.setColor(new Color(0xAA112233, true));
- g.fillRect(0, 0, inImage.getWidth(), inImage.getHeight());
- g.dispose();
-
- Shell shell = new Shell();
- Display display = shell.getDisplay();
- Image outImage = SwtUtils.convertToSwt(display, inImage, true, 32);
- assertNotNull(outImage);
-
- // Expected alpha is 0xAA from the AWT input image pre-multiplied by 32 in convertToSwt.
- int expectedAlpha = (0xAA * 32) >> 8;
-
- ImageData outData = outImage.getImageData();
- assertEquals(inImage.getWidth(), outData.width);
- assertEquals(inImage.getHeight(), outData.height);
- assertEquals(SWT.TRANSPARENCY_ALPHA, outData.getTransparencyType());
-
- PaletteData inPalette = SwtUtils.getAwtPaletteData(inImage.getType());
- PaletteData outPalette = outData.palette;
-
- for (int y = 0; y < outData.height; y++) {
- for (int x = 0; x < outData.width; x++) {
- RGB expected = inPalette.getRGB( inImage.getRGB( x, y));
- RGB actual = outPalette.getRGB(outData.getPixel(x, y));
- assertEquals(expected, actual);
-
- byte actualAlpha = outData.alphaData[y * outData.width + x];
- assertEquals(expectedAlpha, actualAlpha);
- }
- }
- }
-
- public final void testSetRectangle() {
- Rect r = new Rect(1, 2, 3, 4);
- Rectangle r2 = new Rectangle(3, 4, 20, 30);
- SwtUtils.set(r, r2);
-
- assertEquals(3, r.x);
- assertEquals(4, r.y);
- assertEquals(20, r.w);
- assertEquals(30, r.h);
- }
-
- public final void testRectRectangle() {
- Rectangle r = new Rectangle(3, 4, 20, 30);
- Rect r2 = SwtUtils.toRect(r);
-
- assertEquals(3, r2.x);
- assertEquals(4, r2.y);
- assertEquals(20, r2.w);
- assertEquals(30, r2.h);
- }
-
- public final void testCropEmpty() {
- Image image = createSampleImage(256, 256);
- Image result = SwtUtils.drawRectangles(image, Collections.<Rectangle> emptyList(), null,
- 1.0, (byte) 121);
- assertNull(result);
- }
-
- public final void testCrop1() {
- Image image = createSampleImage(256, 256);
-
- byte alpha = 121;
- double scale = 1.0;
-
- List<Rectangle> items = new ArrayList<Rectangle>();
- items.add(new Rectangle(30, 60, 20, 20));
- Image result =
- SwtUtils.drawRectangles(image, items, ImageUtils.getBoundingRectangle(items),
- scale, alpha);
-
- assertNotNull(result);
- ImageData outData = result.getImageData();
- assertEquals(20, outData.width);
- assertEquals(20, outData.height);
-
- PaletteData outPalette = outData.palette;
- assertNotNull(outPalette);
-
- byte[] outAlphaData = outData.alphaData;
- assertNotNull(outAlphaData);
-
- for (int y = 0; y < 20; y++) {
- for (int x = 0; x < 20; x++) {
- int r = y + 60;
- int g = x + 30;
-
- RGB expected = new RGB(r, g, 0);
- RGB actual = outPalette.getRGB(outData.getPixel(x, y));
- assertEquals(expected, actual);
-
- byte actualAlpha = outAlphaData[y*20+x];
- assertEquals(alpha, actualAlpha);
- }
- }
- }
-
- public final void testCrop2() {
- Image image = createSampleImage(256, 256);
-
- byte alpha = 121;
- double scale = 1.0;
-
- List<Rectangle> items = new ArrayList<Rectangle>();
- items.add(new Rectangle(10, 10, 20, 20));
- items.add(new Rectangle(110, 80, 20, 20));
- Image result =
- SwtUtils.drawRectangles(image, items, ImageUtils.getBoundingRectangle(items),
- scale, alpha);
-
- assertNotNull(result);
- ImageData outData = result.getImageData();
- assertEquals(120, outData.width);
- assertEquals(90, outData.height);
-
- PaletteData outPalette = outData.palette;
- assertNotNull(outPalette);
-
- byte[] outAlphaData = outData.alphaData;
- assertNotNull(outAlphaData);
-
- for (int y = 0; y < 20; y++) {
- for (int x = 0; x < 20; x++) {
- int r = y + 10;
- int g = x + 10;
-
- RGB expected = new RGB(r, g, 0);
- RGB actual = outPalette.getRGB(outData.getPixel(x, y));
- assertEquals(expected, actual);
-
- assertEquals(alpha, outAlphaData[y*120+x]);
- }
- }
- for (int y = 70; y < 90; y++) {
- for (int x = 100; x < 120; x++) {
- int r = y + 10;
- int g = x + 10;
-
- RGB expected = new RGB(r, g, 0);
- RGB actual = outPalette.getRGB(outData.getPixel(x, y));
- assertEquals(expected, actual);
-
- assertEquals(alpha, outAlphaData[y*120+x]);
- }
- }
- assertEquals(0, outAlphaData[40]);
- }
-
- /**
- * Crop test utility: Create a sample image patterned with red=y and green=x, suitable
- * for checking that in image copying operations we've copied and scaled the right
- * bits. (Obviously the red/green will be mod'ed with 256).
- *
- * @param imageWidth the width of the target image
- * @param imageHeight the height of the target image
- * @return a new image with a red/green pattern
- */
- private Image createSampleImage(int imageWidth, int imageHeight) {
- Shell shell = new Shell();
- Display display = shell.getDisplay();
-
- ImageData data = new ImageData(imageWidth, imageHeight, 32, new PaletteData(0x00FF0000,
- 0x0000FF00, 0x000000FF));
- for (int y = 0; y < imageHeight; y++) {
- for (int x = 0; x < imageWidth; x++) {
- int pixelValue = (y & 0xFF) << 16 | (x & 0xFF) << 8;
- data.setPixel(x, y, pixelValue);
- }
- }
- Image image = new Image(display, data);
- return image;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gre/MockNodeProxy.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gre/MockNodeProxy.java
deleted file mode 100755
index 433d3903d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gre/MockNodeProxy.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gre;
-
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-
-import org.eclipse.swt.graphics.Rectangle;
-import org.eclipse.ui.internal.registry.ViewDescriptor;
-
-/**
- * Mocks a {@link NodeProxy}, creating it using an XML local name and generating
- * a made-up {@link UiViewElementNode} and a {@link ViewDescriptor} on the fly.
- */
-public class MockNodeProxy extends NodeProxy {
-
- /**
- * Generates a {@link NodeProxy} using an FQCN (e.g. android.view.View)
- * and making the last segment of the FQCN the XML name of the view (e.g. "View")
- * and wraps it as a {@link NodeProxy}.
- *
- * @param fqcn The fully qualified name of the class to wrap, e.g. "android.view.Button".
- * @param bounds The bounds of a the view in the canvas. Must be either: <br/>
- * - a valid rect for a view that is actually in the canvas <br/>
- * - <b>*or*</b> null (or an invalid rect) for a view that has just been added dynamically
- * to the model. We never store a null bounds rectangle in the node, a null rectangle
- * will be converted to an invalid rectangle.
- * @param factory A {@link NodeFactory} to create unique children nodes.
- */
- public MockNodeProxy(String fqcn, Rectangle bounds, NodeFactory factory) {
- super(makeUiViewNode(fqcn), bounds, factory);
- }
-
- /**
- * Generates a {@link ViewElementDescriptor} using an FQCN (e.g. android.view.View)
- * and making the last segment of the FQCN the XML name of the view (e.g. "View").
- *
- * @param fqcn The fully qualified name of the class to wrap, e.g. "android.view.Button"
- * @return A new view element node with a new descriptor for the FQCN and an XML name
- * matching the last FQCN segment (e.g. "Button")
- */
- private static UiViewElementNode makeUiViewNode(String fqcn) {
- String xmlName = fqcn;
- int pos = xmlName.lastIndexOf('.');
- if (pos > 0) {
- xmlName = xmlName.substring(pos + 1);
- }
-
- ViewElementDescriptor desc = new ViewElementDescriptor(xmlName, fqcn);
- UiViewElementNode uiNode = new UiViewElementNode(desc);
- return uiNode;
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gre/NodeFactoryTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gre/NodeFactoryTest.java
deleted file mode 100755
index 0e6d33db3..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gre/NodeFactoryTest.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gre;
-
-import com.android.ide.common.api.INode;
-import com.android.ide.common.api.Rect;
-import com.android.ide.common.rendering.api.ViewInfo;
-import com.android.ide.eclipse.adt.internal.editors.layout.descriptors.ViewElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.layout.gle2.CanvasViewInfo;
-import com.android.ide.eclipse.adt.internal.editors.layout.uimodel.UiViewElementNode;
-
-import java.util.Arrays;
-
-import junit.framework.TestCase;
-
-public class NodeFactoryTest extends TestCase {
-
- private NodeFactory m;
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- m = new NodeFactory(null);
-
- }
-
- @Override
- protected void tearDown() throws Exception {
- super.tearDown();
- m = null;
- }
-
- public final void testCreateCanvasViewInfo() {
- ViewElementDescriptor ved = new ViewElementDescriptor("xml", "com.example.MyJavaClass");
- UiViewElementNode uiv = new UiViewElementNode(ved);
- ViewInfo lvi = new ViewInfo("name", uiv, 10, 12, 110, 120);
- CanvasViewInfo cvi = CanvasViewInfo.create(lvi, true /* layoutlib5 */).getFirst();
-
- // Create a NodeProxy.
- NodeProxy proxy = m.create(cvi);
-
- // getNode() is our only internal implementation method.
- assertNotNull(proxy);
- assertSame(uiv, proxy.getNode());
-
- // Groovy scripts only see the INode interface so we want to primarily test that.
- INode inode = proxy;
- assertEquals(new Rect(10, 12, 110-10-1, 120-12-1), inode.getBounds());
- assertTrue(Arrays.equals(new INode[0], inode.getChildren()));
- assertEquals("com.example.MyJavaClass", inode.getFqcn());
- assertNull(inode.getParent());
- assertSame(inode, inode.getRoot());
-
- }
-
- public final void testCreateUiViewElementNode() {
- ViewElementDescriptor ved = new ViewElementDescriptor("xml", "com.example.MyJavaClass");
- UiViewElementNode uiv = new UiViewElementNode(ved);
-
- // Create a NodeProxy.
- NodeProxy proxy = m.create(uiv);
-
- // getNode() is our only internal implementation method.
- assertNotNull(proxy);
- assertSame(uiv, proxy.getNode());
-
- // Groovy scripts only see the INode interface so we want to primarily test that.
- INode inode = proxy;
- // Nodes constructed using this create() method do not have valid bounds.
- // There should be one invalid bound rectangle.
- assertNotNull(inode.getBounds());
- assertFalse(inode.getBounds().isValid());
- // All the other properties should be set correctly.
- assertTrue(Arrays.equals(new INode[0], inode.getChildren()));
- assertEquals("com.example.MyJavaClass", inode.getFqcn());
- assertNull(inode.getParent());
- assertSame(inode, inode.getRoot());
- }
-
- public final void testCreateDup() {
- ViewElementDescriptor ved = new ViewElementDescriptor("xml", "com.example.MyJavaClass");
- UiViewElementNode uiv = new UiViewElementNode(ved);
- ViewInfo lvi = new ViewInfo("name", uiv, 10, 12, 110, 120);
- CanvasViewInfo cvi = CanvasViewInfo.create(lvi, true /* layoutlib5 */).getFirst();
-
- // NodeProxies are cached. Creating the same one twice returns the same proxy.
- NodeProxy proxy1 = m.create(cvi);
- NodeProxy proxy2 = m.create(cvi);
- assertSame(proxy2, proxy1);
- }
-
- public final void testClear() {
- ViewElementDescriptor ved = new ViewElementDescriptor("xml", "com.example.MyJavaClass");
- UiViewElementNode uiv = new UiViewElementNode(ved);
- ViewInfo lvi = new ViewInfo("name", uiv, 10, 12, 110, 120);
- CanvasViewInfo cvi = CanvasViewInfo.create(lvi, true /* layoutlib5 */).getFirst();
-
- // NodeProxies are cached. Creating the same one twice returns the same proxy.
- NodeProxy proxy1 = m.create(cvi);
- NodeProxy proxy2 = m.create(cvi);
- assertSame(proxy2, proxy1);
-
- // Clearing the cache will force it create a new proxy.
- m.clear();
- NodeProxy proxy3 = m.create(cvi);
- assertNotSame(proxy1, proxy3);
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gre/RulesEngineTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gre/RulesEngineTest.java
deleted file mode 100755
index d9a1a3dc1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gre/RulesEngineTest.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.layout.gre;
-
-import junit.framework.TestCase;
-
-public class RulesEngineTest extends TestCase {
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- @Override
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- public void testDummy() {
- // Here to avoid warning that RulesEngineTest is empty
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gre/ViewMetadataRepositoryTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gre/ViewMetadataRepositoryTest.java
deleted file mode 100644
index 50d438cdb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/gre/ViewMetadataRepositoryTest.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.gre;
-
-import com.android.ide.common.api.IViewMetadata.FillPreference;
-import com.android.ide.eclipse.adt.internal.editors.layout.gre.ViewMetadataRepository.RenderMode;
-
-import java.util.Arrays;
-
-import junit.framework.TestCase;
-
-public class ViewMetadataRepositoryTest extends TestCase {
- public void testSingleton() throws Exception {
- assertSame(ViewMetadataRepository.get(), ViewMetadataRepository.get());
- }
-
- public void testBasic() throws Exception {
- ViewMetadataRepository repository = ViewMetadataRepository.get();
-
- assertEquals(FillPreference.WIDTH_IN_VERTICAL,
- repository.getFillPreference("android.widget.Spinner"));
- assertEquals(FillPreference.NONE,
- repository.getFillPreference("foo.bar"));
- }
-
- // Ensure that all basenames referenced in the metadata refer to other views in the file
- // (e.g. no typos)
- public void testRelatedTo() throws Exception {
- // Make sure unit tests are run with assertions on
- boolean assertionsEnabled = false;
- assert assertionsEnabled = true; // Intentional assignment
- assertTrue("This unit test must be run with assertions enabled (-ea)", assertionsEnabled);
-
- ViewMetadataRepository repository = ViewMetadataRepository.get();
- for (String fqcn : repository.getAllFqcns()) {
- repository.getRelatedTo(fqcn);
- }
- }
-
- public void testSkip() throws Exception {
- ViewMetadataRepository repository = ViewMetadataRepository.get();
- assertTrue(repository.getSkip("merge"));
- assertFalse(repository.getSkip("android.widget.Button"));
- }
-
- public void testRenderMode() throws Exception {
- ViewMetadataRepository repository = ViewMetadataRepository.get();
- assertEquals(RenderMode.NORMAL, repository.getRenderMode("android.widget.Button"));
- assertEquals(RenderMode.SKIP, repository.getRenderMode("android.widget.LinearLayout"));
- assertEquals(RenderMode.ALONE, repository.getRenderMode("android.widget.TabHost"));
- }
-
- public void testGetTopAttributes() throws Exception {
- ViewMetadataRepository repository = ViewMetadataRepository.get();
- assertEquals(Arrays.asList("id", "text", "style"),
- repository.getTopAttributes("android.widget.RadioButton"));
- assertEquals(Arrays.asList("id", "gravity", "paddingLeft", "paddingRight", "checkMark",
- "textAppearance"),
- repository.getTopAttributes("android.widget.CheckedTextView"));
- assertEquals(Arrays.asList("id"),
- repository.getTopAttributes("android.widget.NonExistent"));
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/properties/ValueCompleterTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/properties/ValueCompleterTest.java
deleted file mode 100644
index 0014fe574..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/layout/properties/ValueCompleterTest.java
+++ /dev/null
@@ -1,151 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.editors.layout.properties;
-
-import static com.android.SdkConstants.ANDROID_URI;
-
-import com.android.annotations.NonNull;
-import com.android.annotations.Nullable;
-import com.android.ide.common.api.IAttributeInfo;
-import com.android.ide.common.api.IAttributeInfo.Format;
-import com.android.ide.common.layout.TestAttributeInfo;
-import com.android.ide.eclipse.adt.internal.editors.common.CommonXmlEditor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.AttributeDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.TextAttributeDescriptor;
-
-import org.eclipse.jface.fieldassist.IContentProposal;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.EnumSet;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class ValueCompleterTest extends TestCase {
- private void checkCompletion(String text, int offset,
- String property, EnumSet<Format> formats, String[] values,
- List<String> expected) {
- assertTrue(text.length() >= offset);
-
- TestAttributeInfo info =
- new TestAttributeInfo(property, formats, "unittest", values, values, null);
- TestValueCompleter completer = new TestValueCompleter(
- new TestTextAttributeDescriptor(property, info));
- IContentProposal[] proposals = completer.getProposals(text, offset);
- List<String> actual = new ArrayList<String>();
- for (IContentProposal proposal : proposals) {
- String content = proposal.getContent();
- actual.add(content);
- }
- assertEquals(expected.toString(), actual.toString());
- }
-
- public void test() throws Exception {
- checkCompletion("@android:string", 3, "text",
- EnumSet.of(Format.REFERENCE), null,
- Arrays.asList(new String[] { }));
- }
-
- public void test1a() throws Exception {
- checkCompletion("matc", 4, "layout_width",
- EnumSet.of(Format.DIMENSION, Format.ENUM),
- new String[] { "fill_parent", "match_parent", "wrap_content" },
-
- Arrays.asList(new String[] { "match_parent", "fill_parent", "wrap_content" }));
- }
-
- public void test1b() throws Exception {
- checkCompletion("fi", 2, "layout_width",
- EnumSet.of(Format.DIMENSION, Format.ENUM),
- new String[] { "fill_parent", "match_parent", "wrap_content" },
-
- Arrays.asList(new String[] { "fill_parent", "match_parent", "wrap_content" }));
- }
-
- public void test2() throws Exception {
- checkCompletion("50", 2, "layout_width",
- EnumSet.of(Format.DIMENSION, Format.ENUM),
- new String[] { "fill_parent", "match_parent", "wrap_content" },
-
- Arrays.asList(new String[] { "50dp", "fill_parent", "match_parent",
- "wrap_content" }));
- }
-
- public void test3() throws Exception {
- checkCompletion("42", 2, "textSize",
- EnumSet.of(Format.DIMENSION),
- null,
-
- Arrays.asList(new String[] { "42sp", "42dp" }));
- }
-
- public void test4() throws Exception {
- checkCompletion("", 0, "gravity",
- EnumSet.of(Format.FLAG),
- new String[] { "top", "bottom", "left", "right", "center" },
-
- Arrays.asList(new String[] { "top", "bottom", "left", "right", "center" }));
- }
-
- public void test5() throws Exception {
- checkCompletion("left", 4, "gravity",
- EnumSet.of(Format.FLAG),
- new String[] { "top", "bottom", "left", "right", "center" },
-
- Arrays.asList(new String[] {
- "left", "left|top", "left|bottom", "left|right", "left|center" }));
- }
-
- public void test6() throws Exception {
- checkCompletion("left|top", 8, "gravity",
- EnumSet.of(Format.FLAG),
- new String[] { "top", "bottom", "left", "right", "center" },
-
- Arrays.asList(new String[] {
- "left|top", "left|top|bottom", "left|top|right", "left|top|center" }));
- }
-
- // TODO ?android
-
- private class TestTextAttributeDescriptor extends TextAttributeDescriptor {
- public TestTextAttributeDescriptor(String xmlLocalName, IAttributeInfo attrInfo) {
- super(xmlLocalName, ANDROID_URI, attrInfo);
- }
- }
-
- private class TestValueCompleter extends ValueCompleter {
- private final AttributeDescriptor mDescriptor;
-
- TestValueCompleter(AttributeDescriptor descriptor) {
- mDescriptor = descriptor;
- assert descriptor.getAttributeInfo() != null;
- }
-
- @Override
- @Nullable
- protected CommonXmlEditor getEditor() {
- return null;
- }
-
- @Override
- @NonNull
- protected AttributeDescriptor getDescriptor() {
- return mDescriptor;
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/manifest/model/UiElementNodeTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/manifest/model/UiElementNodeTest.java
deleted file mode 100644
index d19f933d0..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/manifest/model/UiElementNodeTest.java
+++ /dev/null
@@ -1,284 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.manifest.model;
-
-import com.android.SdkConstants;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor;
-import com.android.ide.eclipse.adt.internal.editors.descriptors.ElementDescriptor.Mandatory;
-import com.android.ide.eclipse.adt.internal.editors.mock.MockXmlNode;
-import com.android.ide.eclipse.adt.internal.editors.uimodel.UiElementNode;
-import com.android.utils.XmlUtils;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Element;
-import org.w3c.dom.Node;
-
-import java.util.Iterator;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class UiElementNodeTest extends TestCase {
-
- private UiElementNode ui;
- private ElementDescriptor mManifestDesc;
- private ElementDescriptor mAppDesc;
- private ElementDescriptor mUsesSdkDesc;
-
- @Override
- protected void setUp() throws Exception {
- mAppDesc = new ElementDescriptor("application", new ElementDescriptor[] {
- new ElementDescriptor("provider"),
- new ElementDescriptor("activity", new ElementDescriptor[] {
- new ElementDescriptor("intent-filter")
- }),
- }, Mandatory.MANDATORY_LAST);
-
- mUsesSdkDesc = new ElementDescriptor("uses-sdk", new ElementDescriptor[] {},
- Mandatory.MANDATORY);
-
- mManifestDesc = new ElementDescriptor("manifest", new ElementDescriptor[] {
- mAppDesc,
- mUsesSdkDesc,
- new ElementDescriptor("permission")
- }, Mandatory.MANDATORY);
-
- ui = new UiElementNode(mManifestDesc);
-
- super.setUp();
- }
-
- @Override
- protected void tearDown() throws Exception {
- super.tearDown();
- // pass
- }
-
- /**
- * Check initialization values for ui node
- */
- public void testInit() {
- assertSame(mManifestDesc, ui.getDescriptor());
- assertNull(ui.getUiParent());
- assertEquals(0, ui.getUiChildren().size());
- assertEquals(0, ui.getAllUiAttributes().size());
- }
-
- /**
- * We declared the descriptors as having a "mandatory last" application element
- * and a mandatory non-last uses-sdk element. This means if we create an empty
- * UiModel, we should get these two created, with the application element after
- * the uses-sdk.
- */
- public void testMandatoryOrder() {
- // Add the mandatory nodes with no XML backing, do it explicitly in the wrong order.
- assertEquals(0, ui.getUiChildren().size());
- ui.appendNewUiChild(mAppDesc);
- ui.appendNewUiChild(mUsesSdkDesc);
-
- assertEquals(2, ui.getUiChildren().size());
- assertSame(mAppDesc, ui.getUiChildren().get(0).getDescriptor());
- assertSame(mUsesSdkDesc, ui.getUiChildren().get(1).getDescriptor());
-
- // Parse an XML with just a manifest.
- MockXmlNode root = new MockXmlNode(null /* namespace */, "manifest", Node.ELEMENT_NODE,
- new MockXmlNode[] {
- new MockXmlNode(null /* namespace */, "application", Node.ELEMENT_NODE, null)
- });
-
- ui.loadFromXmlNode(root);
-
- // We should get 2 children, the 2 mandatory nodes but this time with uses-sdk
- // before application since it's a mandatory-last so it "moves" to the end if possible.
- assertEquals(2, ui.getUiChildren().size());
- assertSame(mUsesSdkDesc, ui.getUiChildren().get(0).getDescriptor());
- assertNull(ui.getUiChildren().get(0).getXmlNode());
- assertSame(mAppDesc, ui.getUiChildren().get(1).getDescriptor());
- assertNotNull(ui.getUiChildren().get(1).getXmlNode());
- }
-
- /**
- * loadFrom() does nothing if the root node doesn't match what's expected
- */
- public void testLoadFrom_InvalidRoot() {
- assertEquals(0, ui.getUiChildren().size());
- MockXmlNode root = new MockXmlNode(null /* namespace */, "blah", Node.ELEMENT_NODE, null);
- ui.loadFromXmlNode(root);
- assertEquals(0, ui.getUiChildren().size());
- }
-
- /**
- * UiElementNode.loadFrom should be used to populate an empty ui node from an
- * existing XML node tree.
- */
- public void testLoadFrom_NewTree_1_Node() {
- MockXmlNode root = new MockXmlNode(null /* namespace */, "manifest", Node.ELEMENT_NODE,
- new MockXmlNode[] {
- new MockXmlNode(null /* namespace */, "application", Node.ELEMENT_NODE, null)
- });
-
- // get /manifest
- ui.loadFromXmlNode(root);
- assertEquals("manifest", ui.getDescriptor().getXmlName());
- assertEquals(1, ui.getUiChildren().size());
- assertEquals(0, ui.getAllUiAttributes().size());
-
- // get /manifest/application
- Iterator<UiElementNode> ui_child_it = ui.getUiChildren().iterator();
- UiElementNode application = ui_child_it.next();
- assertEquals("application", application.getDescriptor().getXmlName());
- assertEquals(0, application.getUiChildren().size());
- assertEquals(0, application.getAllUiAttributes().size());
- }
-
-
- public void testLoadFrom_NewTree_2_Nodes() {
- MockXmlNode root = new MockXmlNode(null /* namespace */, "manifest", Node.ELEMENT_NODE,
- new MockXmlNode[] {
- new MockXmlNode(null /* namespace */, "application", Node.ELEMENT_NODE, null),
- new MockXmlNode(null /* namespace */, "permission", Node.ELEMENT_NODE, null),
- });
-
- // get /manifest
- ui.loadFromXmlNode(root);
- assertEquals("manifest", ui.getDescriptor().getXmlName());
- assertEquals(2, ui.getUiChildren().size());
- assertEquals(0, ui.getAllUiAttributes().size());
-
- // get /manifest/application
- Iterator<UiElementNode> ui_child_it = ui.getUiChildren().iterator();
- UiElementNode application = ui_child_it.next();
- assertEquals("application", application.getDescriptor().getXmlName());
- assertEquals(0, application.getUiChildren().size());
- assertEquals(0, application.getAllUiAttributes().size());
- assertEquals(0, application.getUiSiblingIndex());
-
- // get /manifest/permission
- UiElementNode first_permission = ui_child_it.next();
- assertEquals("permission", first_permission.getDescriptor().getXmlName());
- assertEquals(0, first_permission.getUiChildren().size());
- assertEquals(0, first_permission.getAllUiAttributes().size());
- assertEquals(1, first_permission.getUiSiblingIndex());
- }
-
- public void testLoadFrom_NewTree_N_Nodes() {
- MockXmlNode root = new MockXmlNode(null /* namespace */, "manifest", Node.ELEMENT_NODE,
- new MockXmlNode[] {
- new MockXmlNode(null /* namespace */, "application", Node.ELEMENT_NODE,
- new MockXmlNode[] {
- new MockXmlNode(null /* namespace */, "activity", Node.ELEMENT_NODE,
- null),
- new MockXmlNode(null /* namespace */, "activity", Node.ELEMENT_NODE,
- new MockXmlNode[] {
- new MockXmlNode(null /* namespace */, "intent-filter",
- Node.ELEMENT_NODE, null),
- }),
- new MockXmlNode(null /* namespace */, "provider", Node.ELEMENT_NODE,
- null),
- new MockXmlNode(null /* namespace */, "provider", Node.ELEMENT_NODE,
- null),
- }),
- new MockXmlNode(null /* namespace */, "permission", Node.ELEMENT_NODE,
- null),
- new MockXmlNode(null /* namespace */, "permission", Node.ELEMENT_NODE,
- null),
- });
-
- // get /manifest
- ui.loadFromXmlNode(root);
- assertEquals("manifest", ui.getDescriptor().getXmlName());
- assertEquals(3, ui.getUiChildren().size());
- assertEquals(0, ui.getAllUiAttributes().size());
-
- // get /manifest/application
- Iterator<UiElementNode> ui_child_it = ui.getUiChildren().iterator();
- UiElementNode application = ui_child_it.next();
- assertEquals("application", application.getDescriptor().getXmlName());
- assertEquals(4, application.getUiChildren().size());
- assertEquals(0, application.getAllUiAttributes().size());
-
- // get /manifest/application/activity #1
- Iterator<UiElementNode> app_child_it = application.getUiChildren().iterator();
- UiElementNode first_activity = app_child_it.next();
- assertEquals("activity", first_activity.getDescriptor().getXmlName());
- assertEquals(0, first_activity.getUiChildren().size());
- assertEquals(0, first_activity.getAllUiAttributes().size());
-
- // get /manifest/application/activity #2
- UiElementNode second_activity = app_child_it.next();
- assertEquals("activity", second_activity.getDescriptor().getXmlName());
- assertEquals(1, second_activity.getUiChildren().size());
- assertEquals(0, second_activity.getAllUiAttributes().size());
-
- // get /manifest/application/activity #2/intent-filter #1
- Iterator<UiElementNode> activity_child_it = second_activity.getUiChildren().iterator();
- UiElementNode intent_filter = activity_child_it.next();
- assertEquals("intent-filter", intent_filter.getDescriptor().getXmlName());
- assertEquals(0, intent_filter.getUiChildren().size());
- assertEquals(0, intent_filter.getAllUiAttributes().size());
-
- // get /manifest/application/provider #1
- UiElementNode first_provider = app_child_it.next();
- assertEquals("provider", first_provider.getDescriptor().getXmlName());
- assertEquals(0, first_provider.getUiChildren().size());
- assertEquals(0, first_provider.getAllUiAttributes().size());
-
- // get /manifest/application/provider #2
- UiElementNode second_provider = app_child_it.next();
- assertEquals("provider", second_provider.getDescriptor().getXmlName());
- assertEquals(0, second_provider.getUiChildren().size());
- assertEquals(0, second_provider.getAllUiAttributes().size());
-
- // get /manifest/permission #1
- UiElementNode first_permission = ui_child_it.next();
- assertEquals("permission", first_permission.getDescriptor().getXmlName());
- assertEquals(0, first_permission.getUiChildren().size());
- assertEquals(0, first_permission.getAllUiAttributes().size());
-
- // get /manifest/permission #1
- UiElementNode second_permission = ui_child_it.next();
- assertEquals("permission", second_permission.getDescriptor().getXmlName());
- assertEquals(0, second_permission.getUiChildren().size());
- assertEquals(0, second_permission.getAllUiAttributes().size());
- }
-
- public void testCreateNameSpace() throws Exception {
- // Setup
- DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
- factory.setNamespaceAware(true);
- factory.setValidating(false);
- DocumentBuilder builder = factory.newDocumentBuilder();
- Document document = builder.newDocument();
- Element rootElement = document.createElement("root");
- document.appendChild(rootElement);
- Element root = document.getDocumentElement();
- root.appendChild(document.createTextNode(" "));
- Element foo = document.createElement("foo");
- root.appendChild(foo);
- root.appendChild(document.createTextNode(" "));
- Element bar = document.createElement("bar");
- root.appendChild(bar);
- Element baz = document.createElement("baz");
- root.appendChild(baz);
-
- String prefix = XmlUtils.lookupNamespacePrefix(baz, SdkConstants.ANDROID_URI);
- assertEquals("android", prefix);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/mock/MockNamedNodeMap.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/mock/MockNamedNodeMap.java
deleted file mode 100644
index 0330216d5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/mock/MockNamedNodeMap.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.mock;
-
-import org.w3c.dom.DOMException;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-
-class MockNamedNodeMap implements NamedNodeMap {
-
- /** map for access by namespace/name */
- private final HashMap<String, HashMap<String, Node>> mNodeMap =
- new HashMap<String, HashMap<String, Node>>();
-
- /** list for access by index */
- private final ArrayList<Node> mNodeList = new ArrayList<Node>();
-
- public MockXmlNode addAttribute(String namespace, String localName, String value) {
- MockXmlNode node = new MockXmlNode(namespace, localName, value);
-
- if (namespace == null) {
- namespace = ""; // no namespace
- }
-
- // get the map for the namespace
- HashMap<String, Node> map = mNodeMap.get(namespace);
- if (map == null) {
- map = new HashMap<String, Node>();
- mNodeMap.put(namespace, map);
- }
-
-
- map.put(localName, node);
- mNodeList.add(node);
-
- return node;
- }
-
- // --------- NamedNodeMap -------
-
- @Override
- public int getLength() {
- return mNodeList.size();
- }
-
- @Override
- public Node getNamedItem(String name) {
- HashMap<String, Node> map = mNodeMap.get(""); // no namespace
- if (map != null) {
- return map.get(name);
- }
-
- return null;
- }
-
- @Override
- public Node getNamedItemNS(String namespaceURI, String localName) throws DOMException {
- if (namespaceURI == null) {
- namespaceURI = ""; //no namespace
- }
-
- HashMap<String, Node> map = mNodeMap.get(namespaceURI);
- if (map != null) {
- return map.get(localName);
- }
-
- return null;
- }
-
- @Override
- public Node item(int index) {
- return mNodeList.get(index);
- }
-
- @Override
- public Node removeNamedItem(String name) throws DOMException {
- throw new UnsupportedOperationException("Operation not implemented."); //$NON-NLS-1$
- }
-
- @Override
- public Node removeNamedItemNS(String namespaceURI, String localName) throws DOMException {
- throw new UnsupportedOperationException("Operation not implemented."); //$NON-NLS-1$
- }
-
- @Override
- public Node setNamedItem(Node arg) throws DOMException {
- throw new UnsupportedOperationException("Operation not implemented."); //$NON-NLS-1$
- }
-
- @Override
- public Node setNamedItemNS(Node arg) throws DOMException {
- throw new UnsupportedOperationException("Operation not implemented."); //$NON-NLS-1$
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/mock/MockNodeList.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/mock/MockNodeList.java
deleted file mode 100644
index ff9df19a1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/mock/MockNodeList.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.mock;
-
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-
-import java.util.ArrayList;
-
-
-/**
- * A quick mock implementation of NodeList on top of ArrayList.
- */
-public class MockNodeList implements NodeList {
-
- ArrayList<MockXmlNode> mChildren;
-
- /**
- * Constructs a node list from a given children list.
- *
- * @param children The children list. Can be null.
- */
- public MockNodeList(MockXmlNode[] children) {
- mChildren = new ArrayList<MockXmlNode>();
- if (children != null) {
- for (MockXmlNode n : children) {
- mChildren.add(n);
- }
- }
- }
-
- @Override
- public int getLength() {
- return mChildren.size();
- }
-
- @Override
- public Node item(int index) {
- if (index >= 0 && index < mChildren.size()) {
- return mChildren.get(index);
- }
- return null;
- }
-
- public ArrayList<MockXmlNode> getArrayList() {
- return mChildren;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/mock/MockXmlNode.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/mock/MockXmlNode.java
deleted file mode 100644
index 77de2c822..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/mock/MockXmlNode.java
+++ /dev/null
@@ -1,319 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.mock;
-
-import org.w3c.dom.DOMException;
-import org.w3c.dom.Document;
-import org.w3c.dom.NamedNodeMap;
-import org.w3c.dom.Node;
-import org.w3c.dom.NodeList;
-import org.w3c.dom.UserDataHandler;
-
-import java.util.HashMap;
-
-
-/**
- * A mock XML node with only a minimal set of information.
- */
-public class MockXmlNode implements Node {
-
- MockNodeList mNodeList;
- private String mLocalName;
- private String mNamespace;
- private short mNodeType;
- private MockXmlNode mParent;
- private MockXmlNode mPreviousSibling;
- private MockXmlNode mNextSibling;
- private String mAttrValue;
- private MockNamedNodeMap mAttributes;
-
- // namespace stuff only set in the root node
- /** map from namespace to prefix. */
- private HashMap<String, String> mNsMap = null;
-
- /**
- * Constructs a node from a given children list.
- *
- * @param namespace The namespace of the node or null if none
- * @param localName The XML local node name.
- * @param node_type One of Node.xxx_NODE constants, e.g. Node.ELEMENT_NODE
- * @param children The children list. Can be null.
- */
- public MockXmlNode(String namespace, String localName, short node_type,
- MockXmlNode[] children) {
- mLocalName = localName;
- mNamespace = namespace;
- mNodeType = node_type;
- mNodeList = new MockNodeList(children);
- fixNavigation();
- }
-
- /**
- * Constructs an attribute node
- *
- * @param namespace The namespace of the node or null if none
- * @param localName The XML local node name.
- * @param value the value of the attribute
- */
- public MockXmlNode(String namespace, String localName, String value) {
- mLocalName = localName;
- mNamespace = namespace;
- mAttrValue = value;
- mNodeType = Node.ATTRIBUTE_NODE;
- mNodeList = new MockNodeList(new MockXmlNode[0]);
- fixNavigation();
- }
-
- private void fixNavigation() {
- MockXmlNode prev = null;
- for (MockXmlNode n : mNodeList.getArrayList()) {
- n.mParent = this;
- n.mPreviousSibling = prev;
- if (prev != null) {
- prev.mNextSibling = n;
- }
- n.fixNavigation();
- prev = n;
- }
- }
-
- public void addAttributes(String namespaceURI, String localName, String value) {
- if (mAttributes == null) {
- mAttributes = new MockNamedNodeMap();
- }
-
- MockXmlNode node = mAttributes.addAttribute(namespaceURI, localName, value);
- node.mParent = this;
- }
-
- public void setPrefix(String namespace, String prefix) {
- if (mNsMap == null) {
- mNsMap = new HashMap<String, String>();
- }
-
- mNsMap.put(namespace, prefix);
- }
-
- public String getPrefix(String namespace) {
- if (mNsMap != null) {
- return mNsMap.get(namespace);
- }
-
- return mParent.getPrefix(namespace);
- }
-
-
- // ----------- Node methods
-
- @Override
- public Node appendChild(Node newChild) throws DOMException {
- mNodeList.getArrayList().add((MockXmlNode) newChild);
- return newChild;
- }
-
- @Override
- public NamedNodeMap getAttributes() {
- return mAttributes;
- }
-
- @Override
- public NodeList getChildNodes() {
- return mNodeList;
- }
-
- @Override
- public Node getFirstChild() {
- if (mNodeList.getLength() > 0) {
- return mNodeList.item(0);
- }
- return null;
- }
-
- @Override
- public Node getLastChild() {
- if (mNodeList.getLength() > 0) {
- return mNodeList.item(mNodeList.getLength() - 1);
- }
- return null;
- }
-
- @Override
- public Node getNextSibling() {
- return mNextSibling;
- }
-
- @Override
- public String getNodeName() {
- return mLocalName;
- }
-
- @Override
- public String getLocalName() {
- return mLocalName;
- }
-
- @Override
- public short getNodeType() {
- return mNodeType;
- }
-
- @Override
- public Node getParentNode() {
- return mParent;
- }
-
- @Override
- public Node getPreviousSibling() {
- return mPreviousSibling;
- }
-
- @Override
- public boolean hasChildNodes() {
- return mNodeList.getLength() > 0;
- }
-
- @Override
- public boolean hasAttributes() {
- throw new UnsupportedOperationException("Operation not implemented."); //$NON-NLS-1$
- }
-
- @Override
- public boolean isSameNode(Node other) {
- return this == other;
- }
-
- @Override
- public String getNodeValue() throws DOMException {
- return mAttrValue;
- }
-
- @Override
- public String getPrefix() {
- return getPrefix(getNamespaceURI());
- }
-
- @Override
- public String getNamespaceURI() {
- return mNamespace;
- }
-
-
- // --- methods not implemented ---
-
- @Override
- public Node cloneNode(boolean deep) {
- throw new UnsupportedOperationException("Operation not implemented."); //$NON-NLS-1$
- }
-
- @Override
- public short compareDocumentPosition(Node other) throws DOMException {
- throw new UnsupportedOperationException("Operation not implemented."); //$NON-NLS-1$
- }
-
- @Override
- public String getBaseURI() {
- throw new UnsupportedOperationException("Operation not implemented."); //$NON-NLS-1$
- }
-
- @Override
- public Object getFeature(String feature, String version) {
- throw new UnsupportedOperationException("Operation not implemented."); //$NON-NLS-1$
- }
-
- @Override
- public Document getOwnerDocument() {
- throw new UnsupportedOperationException("Operation not implemented."); //$NON-NLS-1$
- }
-
- @Override
- public String getTextContent() throws DOMException {
- throw new UnsupportedOperationException("Operation not implemented."); //$NON-NLS-1$
- }
-
- @Override
- public Object getUserData(String key) {
- throw new UnsupportedOperationException("Operation not implemented."); //$NON-NLS-1$
- }
-
- @Override
- public Node insertBefore(Node newChild, Node refChild)
- throws DOMException {
- throw new UnsupportedOperationException("Operation not implemented."); //$NON-NLS-1$
- }
-
- @Override
- public boolean isDefaultNamespace(String namespaceURI) {
- throw new UnsupportedOperationException("Operation not implemented."); //$NON-NLS-1$
- }
-
- @Override
- public boolean isEqualNode(Node arg) {
- throw new UnsupportedOperationException("Operation not implemented."); //$NON-NLS-1$
- }
-
- @Override
- public boolean isSupported(String feature, String version) {
- throw new UnsupportedOperationException("Operation not implemented."); //$NON-NLS-1$
- }
-
- @Override
- public String lookupNamespaceURI(String prefix) {
- throw new UnsupportedOperationException("Operation not implemented."); //$NON-NLS-1$
- }
-
- @Override
- public String lookupPrefix(String namespaceURI) {
- throw new UnsupportedOperationException("Operation not implemented."); //$NON-NLS-1$
- }
-
- @Override
- public void normalize() {
- throw new UnsupportedOperationException("Operation not implemented."); //$NON-NLS-1$
- }
-
- @Override
- public Node removeChild(Node oldChild) throws DOMException {
- throw new UnsupportedOperationException("Operation not implemented."); //$NON-NLS-1$
- }
-
- @Override
- public Node replaceChild(Node newChild, Node oldChild)
- throws DOMException {
- throw new UnsupportedOperationException("Operation not implemented."); //$NON-NLS-1$
- }
-
- @Override
- public void setNodeValue(String nodeValue) throws DOMException {
- throw new UnsupportedOperationException("Operation not implemented."); //$NON-NLS-1$
- }
-
- @Override
- public void setPrefix(String prefix) throws DOMException {
- throw new UnsupportedOperationException("Operation not implemented."); //$NON-NLS-1$
- }
-
- @Override
- public void setTextContent(String textContent) throws DOMException {
- throw new UnsupportedOperationException("Operation not implemented."); //$NON-NLS-1$
- }
-
- @Override
- public Object setUserData(String key, Object data,
- UserDataHandler handler) {
- throw new UnsupportedOperationException("Operation not implemented."); //$NON-NLS-1$
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/resources/manager/ConfigMatchTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/resources/manager/ConfigMatchTest.java
deleted file mode 100644
index a6da135b6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/editors/resources/manager/ConfigMatchTest.java
+++ /dev/null
@@ -1,297 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.editors.resources.manager;
-
-import com.android.SdkConstants;
-import com.android.ide.common.resources.ResourceFile;
-import com.android.ide.common.resources.ResourceFolder;
-import com.android.ide.common.resources.ResourceItem;
-import com.android.ide.common.resources.ResourceRepository;
-import com.android.ide.common.resources.SingleResourceFile;
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.eclipse.adt.internal.resources.manager.ProjectResources;
-import com.android.ide.eclipse.adt.io.IFileWrapper;
-import com.android.ide.eclipse.adt.io.IFolderWrapper;
-import com.android.ide.eclipse.mock.Mocks;
-import com.android.io.IAbstractFolder;
-import com.android.io.IAbstractResource;
-import com.android.resources.Keyboard;
-import com.android.resources.KeyboardState;
-import com.android.resources.Navigation;
-import com.android.resources.NavigationState;
-import com.android.resources.NightMode;
-import com.android.resources.ResourceFolderType;
-import com.android.resources.ScreenOrientation;
-import com.android.resources.TouchScreen;
-import com.android.resources.UiMode;
-
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-
-import junit.framework.TestCase;
-
-public class ConfigMatchTest extends TestCase {
- private static final String SEARCHED_FILENAME = "main.xml"; //$NON-NLS-1$
- private static final String MISC1_FILENAME = "foo.xml"; //$NON-NLS-1$
- private static final String MISC2_FILENAME = "bar.xml"; //$NON-NLS-1$
-
- private FolderConfiguration mDefaultConfig;
- private ResourceRepository mResources;
- private FolderConfiguration config4;
- private FolderConfiguration config3;
- private FolderConfiguration config2;
- private FolderConfiguration config1;
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
-
- // create a default config with all qualifiers.
- mDefaultConfig = new FolderConfiguration();
- mDefaultConfig.createDefault();
-
- IAbstractFolder folder = Mocks.createAbstractFolder(
- SdkConstants.FD_RESOURCES, new IAbstractResource[0]);
-
- // create the project resources.
- mResources = new ResourceRepository(folder, false) {
- @Override
- protected ResourceItem createResourceItem(String name) {
- return new ResourceItem(name);
- }
- };
-
- // create 2 arrays of IResource. one with the filename being looked up, and one without.
- // Since the required API uses IResource, we can use MockFolder for them.
- IFile[] validMemberList = new IFile[] {
- Mocks.createFile(MISC1_FILENAME),
- Mocks.createFile(SEARCHED_FILENAME),
- Mocks.createFile(MISC2_FILENAME),
- };
- IFile[] invalidMemberList = new IFile[] {
- Mocks.createFile(MISC1_FILENAME),
- Mocks.createFile(MISC2_FILENAME),
- };
-
- // add multiple ResourceFolder to the project resource.
- FolderConfiguration defaultConfig = getConfiguration(
- null, // country code
- null, // network code
- null, // language
- null, // region
- null, // smallest width dp
- null, // width dp
- null, // height dp
- null, // screen size
- null, // screen ratio
- null, // screen orientation
- null, // dock mode
- null, // night mode
- null, // dpi
- null, // touch mode
- null, // keyboard state
- null, // text input
- null, // navigation state
- null, // navigation method
- null, // screen dimension
- null);// version
-
- addFolder(mResources, defaultConfig, validMemberList);
-
- config1 = getConfiguration(
- null, // country code
- null, // network code
- "en", // language
- null, // region
- null, // smallest width dp
- null, // width dp
- null, // height dp
- null, // screen size
- null, // screen ratio
- null, // screen orientation
- null, // dock mode
- null, // night mode
- null, // dpi
- null, // touch mode
- KeyboardState.EXPOSED.getResourceValue(), // keyboard state
- null, // text input
- null, // navigation state
- null, // navigation method
- null, // screen dimension
- null);// version
-
- addFolder(mResources, config1, validMemberList);
-
- config2 = getConfiguration(
- null, // country code
- null, // network code
- "en", // language
- null, // region
- null, // smallest width dp
- null, // width dp
- null, // height dp
- null, // screen size
- null, // screen ratio
- null, // screen orientation
- null, // dock mode
- null, // night mode
- null, // dpi
- null, // touch mode
- KeyboardState.HIDDEN.getResourceValue(), // keyboard state
- null, // text input
- null, // navigation state
- null, // navigation method
- null, // screen dimension
- null);// version
-
- addFolder(mResources, config2, validMemberList);
-
- config3 = getConfiguration(
- null, // country code
- null, // network code
- "en", // language
- null, // region
- null, // smallest width dp
- null, // width dp
- null, // height dp
- null, // screen size
- null, // screen ratio
- ScreenOrientation.LANDSCAPE.getResourceValue(), // screen orientation
- null, // dock mode
- null, // night mode
- null, // dpi
- null, // touch mode
- null, // keyboard state
- null, // text input
- null, // navigation state
- null, // navigation method
- null, // screen dimension
- null);// version
-
- addFolder(mResources, config3, validMemberList);
-
- config4 = getConfiguration(
- "mcc310", // country code
- "mnc435", // network code
- "en", // language
- "rUS", // region
- null, // smallest width dp
- null, // width dp
- null, // height dp
- "normal", // screen size
- "notlong", // screen ratio
- ScreenOrientation.LANDSCAPE.getResourceValue(), // screen orientation
- UiMode.DESK.getResourceValue(), // dock mode
- NightMode.NIGHT.getResourceValue(), // night mode
- "mdpi", // dpi
- TouchScreen.FINGER.getResourceValue(), // touch mode
- KeyboardState.EXPOSED.getResourceValue(), // keyboard state
- Keyboard.QWERTY.getResourceValue(), // text input
- NavigationState.EXPOSED.getResourceValue(), // navigation state
- Navigation.DPAD.getResourceValue(), // navigation method
- "480x320", // screen dimension
- "v3"); // version
-
- addFolder(mResources, config4, invalidMemberList);
- }
-
- @Override
- protected void tearDown() throws Exception {
- super.tearDown();
- mResources = null;
- }
-
- public void test1() {
- FolderConfiguration testConfig = getConfiguration(
- "mcc310", // country code
- "mnc435", // network code
- "en", // language
- "rUS", // region
- null, // smallest width dp
- null, // width dp
- null, // height dp
- "normal", // screen size
- "notlong", // screen ratio
- ScreenOrientation.LANDSCAPE.getResourceValue(), // screen orientation
- UiMode.DESK.getResourceValue(), // dock mode
- NightMode.NIGHT.getResourceValue(), // night mode
- "mdpi", // dpi
- TouchScreen.FINGER.getResourceValue(), // touch mode
- KeyboardState.EXPOSED.getResourceValue(), // keyboard state
- Keyboard.QWERTY.getResourceValue(), // text input
- NavigationState.EXPOSED.getResourceValue(), // navigation state
- Navigation.DPAD.getResourceValue(), // navigation method
- "480x320", // screen dimension
- "v3"); // version
-
- ResourceFile result = mResources.getMatchingFile(SEARCHED_FILENAME,
- ResourceFolderType.LAYOUT, testConfig);
-
- boolean bresult = result.getFolder().getConfiguration().equals(config3);
- assertEquals(bresult, true);
- }
-
- /**
- * Creates a {@link FolderConfiguration}.
- * @param qualifierValues The list of qualifier values. The length must equals the total number
- * of Qualifiers. <code>null</code> is permitted and will make the FolderConfiguration not use
- * this particular qualifier.
- */
- private FolderConfiguration getConfiguration(String... qualifierValues) {
- // FolderConfiguration.getQualifierCount is always valid and up to date.
- final int count = FolderConfiguration.getQualifierCount();
-
- // Check we have the right number of qualifier.
- assertEquals(qualifierValues.length, count);
-
- FolderConfiguration config = new FolderConfiguration();
-
- for (int i = 0 ; i < count ; i++) {
- String value = qualifierValues[i];
- if (value != null) {
- assertTrue(mDefaultConfig.getQualifier(i).checkAndSet(value, config));
- }
- }
-
- return config;
- }
-
- /**
- * Adds a folder to the given {@link ProjectResources} with the given
- * {@link FolderConfiguration}. The folder is filled with files from the provided list.
- * @param resources the {@link ResourceRepository} in which to add the folder.
- * @param config the {@link FolderConfiguration} for the created folder.
- * @param memberList the list of files for the folder.
- */
- private void addFolder(ResourceRepository resources, FolderConfiguration config,
- IFile[] memberList) throws Exception {
-
- // figure out the folder name based on the configuration
- String folderName = config.getFolderName(ResourceFolderType.LAYOUT);
-
- // create the folder mock
- IFolder folder = Mocks.createFolder(folderName, memberList);
-
- // add it to the resource, and get back a ResourceFolder object.
- ResourceFolder resFolder = resources.processFolder(new IFolderWrapper(folder));
-
- // and fill it with files from the list.
- for (IFile file : memberList) {
- resFolder.addFile(new SingleResourceFile(new IFileWrapper(file), resFolder));
- }
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/project/ProjectHelperTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/project/ProjectHelperTest.java
deleted file mode 100644
index 22bfef560..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/project/ProjectHelperTest.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.project;
-
-import com.android.ide.eclipse.mock.Mocks;
-
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jdt.core.IClasspathEntry;
-import org.eclipse.jdt.core.IJavaProject;
-
-import junit.framework.TestCase;
-
-public class ProjectHelperTest extends TestCase {
-
- /** The old container id */
- private final static String OLD_CONTAINER_ID =
- "com.android.ide.eclipse.adt.project.AndroidClasspathContainerInitializer"; //$NON-NLS-1$
-
- /** The container id for the android framework jar file */
- private final static String CONTAINER_ID =
- "com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"; //$NON-NLS-1$
-
- @Override
- public void setUp() throws Exception {
- // pass for now
- }
-
- @Override
- public void tearDown() throws Exception {
- // pass for now
- }
-
- public final void testFixProjectClasspathEntriesFromOldContainer() throws Exception {
- // create a project with a path to an android .zip
- IJavaProject javaProject = Mocks.createProject(
- new IClasspathEntry[] {
- Mocks.createClasspathEntry(new Path("Project/src"), //$NON-NLS-1$
- IClasspathEntry.CPE_SOURCE),
- Mocks.createClasspathEntry(new Path(OLD_CONTAINER_ID),
- IClasspathEntry.CPE_CONTAINER),
- },
- new Path("Project/bin"));
-
- ProjectHelper.fixProjectClasspathEntries(javaProject);
-
- IClasspathEntry[] fixedEntries = javaProject.getRawClasspath();
- assertEquals(3, fixedEntries.length);
- assertEquals("Project/src", fixedEntries[0].getPath().toString());
- assertEquals(OLD_CONTAINER_ID, fixedEntries[1].getPath().toString());
- assertEquals(CONTAINER_ID, fixedEntries[2].getPath().toString());
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/refactorings/core/AndroidTypeMoveParticipantTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/refactorings/core/AndroidTypeMoveParticipantTest.java
deleted file mode 100644
index 262ea420e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/refactorings/core/AndroidTypeMoveParticipantTest.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.refactorings.core;
-
-import com.android.annotations.NonNull;
-import com.android.ide.eclipse.adt.AdtPlugin;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.jdt.core.IJavaElement;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.internal.corext.refactoring.reorg.IReorgPolicy.IMovePolicy;
-import org.eclipse.jdt.internal.corext.refactoring.reorg.JavaMoveProcessor;
-import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgDestinationFactory;
-import org.eclipse.jdt.internal.corext.refactoring.reorg.ReorgPolicyFactory;
-import org.eclipse.jdt.internal.ui.refactoring.reorg.CreateTargetQueries;
-import org.eclipse.jdt.internal.ui.refactoring.reorg.ReorgQueries;
-import org.eclipse.ltk.core.refactoring.participants.MoveRefactoring;
-import org.eclipse.swt.widgets.Shell;
-
-
-@SuppressWarnings({"javadoc", "restriction"})
-public class AndroidTypeMoveParticipantTest extends RefactoringTestBase {
- public void testRefactor1() throws Exception {
- moveType(
- TEST_PROJECT2,
- "com.example.refactoringtest.CustomView1",
- "src/com/example/refactoringtest/subpackage",
- true /*updateReferences*/,
-
- "CHANGES:\n" +
- "-------\n" +
- "[x] Move resource 'testRefactor1/src/com/example/refactoringtest/CustomView1.java' to 'subpackage'\n" +
- "\n" +
- "[x] Move resource 'testRefactor1/src/com/example/refactoringtest/CustomView1.java' to 'subpackage'\n" +
- "\n" +
- "[x] customviews.xml - /testRefactor1/res/layout/customviews.xml\n" +
- " @@ -9 +9\n" +
- " - <com.example.refactoringtest.CustomView1\n" +
- " + <com.example.refactoringtest.subpackage.CustomView1\n" +
- "\n" +
- "\n" +
- "[x] customviews.xml - /testRefactor1/res/layout-land/customviews.xml\n" +
- " @@ -9 +9\n" +
- " - <com.example.refactoringtest.CustomView1\n" +
- " + <com.example.refactoringtest.subpackage.CustomView1");
- }
-
- public void testRefactorFragment() throws Exception {
- moveType(
- TEST_PROJECT2,
- "com.example.refactoringtest.MyFragment",
- "src/com/example/refactoringtest/subpackage",
- true /*updateReferences*/,
-
- "CHANGES:\n" +
- "-------\n" +
- "[x] Move resource 'testRefactorFragment/src/com/example/refactoringtest/MyFragment.java' to 'subpackage'\n" +
- "\n" +
- "[x] Move resource 'testRefactorFragment/src/com/example/refactoringtest/MyFragment.java' to 'subpackage'\n" +
- "\n" +
- "[x] activity_main.xml - /testRefactorFragment/res/layout/activity_main.xml\n" +
- " @@ -33 +33\n" +
- " - <fragment android:name=\"com.example.refactoringtest.MyFragment\"/>\n" +
- " + <fragment android:name=\"com.example.refactoringtest.subpackage.MyFragment\"/>");
- }
-
- public void testRefactor1_norefs() throws Exception {
- moveType(
- TEST_PROJECT2,
- "com.example.refactoringtest.CustomView1",
- "src/com/example/refactoringtest/subpackage",
- false /*updateReferences*/,
-
- "CHANGES:\n" +
- "-------\n" +
- "[x] Move resource 'testRefactor1_norefs/src/com/example/refactoringtest/CustomView1.java' to 'subpackage'\n" +
- "\n" +
- "[x] Move resource 'testRefactor1_norefs/src/com/example/refactoringtest/CustomView1.java' to 'subpackage'");
- }
-
- // ---- Test infrastructure ----
-
- protected void moveType(
- @NonNull Object[] testData,
- @NonNull String typeFqcn,
- @NonNull String destination,
- boolean updateReferences,
- @NonNull String expected) throws Exception {
- IProject project = createProject(testData);
-
- IFolder destinationFolder = project.getFolder(destination);
-
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
- assertNotNull(javaProject);
- IType type = javaProject.findType(typeFqcn);
- assertNotNull(typeFqcn, type);
- assertTrue(typeFqcn, type.exists());
- IResource resource = type.getResource();
- assertNotNull(typeFqcn, resource);
- assertTrue(typeFqcn, resource.exists());
-
- IResource[] resources = new IResource[] { resource };
- IJavaElement[] elements = new IJavaElement[] { type };
- IMovePolicy policy = ReorgPolicyFactory.createMovePolicy(resources, elements);
- JavaMoveProcessor processor = new JavaMoveProcessor(policy);
- processor.setUpdateReferences(updateReferences);
- processor.setUpdateQualifiedNames(true);
- assertTrue(policy.canEnable());
- processor.setDestination(ReorgDestinationFactory.createDestination(destinationFolder));
- Shell parent = AdtPlugin.getShell();
- assertNotNull(parent);
- processor.setCreateTargetQueries(new CreateTargetQueries(parent));
- processor.setReorgQueries(new ReorgQueries(parent));
-
- MoveRefactoring refactoring = new MoveRefactoring(processor);
- checkRefactoring(refactoring, expected);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/refactorings/core/AndroidTypeRenameParticipantTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/refactorings/core/AndroidTypeRenameParticipantTest.java
deleted file mode 100644
index f65124a2c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/refactorings/core/AndroidTypeRenameParticipantTest.java
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.refactorings.core;
-
-import com.android.annotations.NonNull;
-import com.android.ide.eclipse.adt.internal.project.BaseProjectHelper;
-
-import org.eclipse.core.resources.IProject;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.IType;
-import org.eclipse.jdt.internal.corext.refactoring.rename.RenameTypeProcessor;
-import org.eclipse.ltk.core.refactoring.participants.RenameRefactoring;
-
-
-@SuppressWarnings({"javadoc", "restriction"})
-public class AndroidTypeRenameParticipantTest extends RefactoringTestBase {
- public void testRefactor1() throws Exception {
- renameType(
- TEST_PROJECT,
- "com.example.refactoringtest.MainActivity",
- true /*updateReferences*/,
- "NewActivityName",
-
- "CHANGES:\n" +
- "-------\n" +
- "[x] Rename compilation unit 'MainActivity.java' to 'NewActivityName.java'\n" +
- "\n" +
- "[x] activity_main.xml - /testRefactor1/res/layout/activity_main.xml\n" +
- " @@ -5 +5\n" +
- " - tools:context=\".MainActivity\" >\n" +
- " + tools:context=\".NewActivityName\" >\n" +
- "\n" +
- "\n" +
- "[x] activity_main.xml - /testRefactor1/res/layout-land/activity_main.xml\n" +
- " @@ -5 +5\n" +
- " - tools:context=\".MainActivity\" >\n" +
- " + tools:context=\".NewActivityName\" >\n" +
- "\n" +
- "\n" +
- "[x] AndroidManifest.xml - /testRefactor1/AndroidManifest.xml\n" +
- " @@ -16 +16\n" +
- " - android:name=\"com.example.refactoringtest.MainActivity\"\n" +
- " + android:name=\"com.example.refactoringtest.NewActivityName\"");
- }
-
- public void testRefactor1b() throws Exception {
- renameType(
- TEST_PROJECT,
- "com.example.refactoringtest.MainActivity2",
- true /*updateReferences*/,
- "NewActivityName",
-
- "CHANGES:\n" +
- "-------\n" +
- "[x] Rename compilation unit 'MainActivity2.java' to 'NewActivityName.java'\n" +
- "\n" +
- "[x] AndroidManifest.xml - /testRefactor1b/AndroidManifest.xml\n" +
- " @@ -25 +25\n" +
- " - android:name=\".MainActivity2\"\n" +
- " + android:name=\".NewActivityName\"");
- }
-
- public void testRefactor1_noreferences() throws Exception {
- renameType(
- TEST_PROJECT,
- "com.example.refactoringtest.MainActivity",
- false /*updateReferences*/,
- "NewActivityName",
-
- "CHANGES:\n" +
- "-------\n" +
- "[x] Rename compilation unit 'MainActivity.java' to 'NewActivityName.java'");
- }
-
- public void testRefactor2() throws Exception {
- renameType(
- TEST_PROJECT2,
- "com.example.refactoringtest.CustomView1",
- true /*updateReferences*/,
- "NewCustomViewName",
-
- "CHANGES:\n" +
- "-------\n" +
- "[x] Rename compilation unit 'CustomView1.java' to 'NewCustomViewName.java'\n" +
- "\n" +
- "[x] attrs_custom_view.xml - /testRefactor2/res/values/attrs_custom_view.xml\n" +
- " @@ -4 +4\n" +
- " - <declare-styleable name=\"CustomView1\">\n" +
- " + <declare-styleable name=\"NewCustomViewName\">\n" +
- "\n" +
- "\n" +
- "[x] customviews.xml - /testRefactor2/res/layout/customviews.xml\n" +
- " @@ -9 +9\n" +
- " - <com.example.refactoringtest.CustomView1\n" +
- " + <com.example.refactoringtest.NewCustomViewName\n" +
- "\n" +
- "\n" +
- "[x] customviews.xml - /testRefactor2/res/layout-land/customviews.xml\n" +
- " @@ -9 +9\n" +
- " - <com.example.refactoringtest.CustomView1\n" +
- " + <com.example.refactoringtest.NewCustomViewName");
- }
-
- public void testRefactorFragment() throws Exception {
- renameType(
- TEST_PROJECT2,
- "com.example.refactoringtest.MyFragment",
- true /*updateReferences*/,
- "NewFragmentName",
-
- "CHANGES:\n" +
- "-------\n" +
- "[x] Rename compilation unit 'MyFragment.java' to 'NewFragmentName.java'\n" +
- "\n" +
- "[x] activity_main.xml - /testRefactorFragment/res/layout/activity_main.xml\n" +
- " @@ -33 +33\n" +
- " - <fragment android:name=\"com.example.refactoringtest.MyFragment\"/>\n" +
- " + <fragment android:name=\"com.example.refactoringtest.NewFragmentName\"/>");
- }
-
- // ---- Test infrastructure ----
-
- protected void renameType(
- @NonNull Object[] testData,
- @NonNull String typeFqcn,
- boolean updateReferences,
- @NonNull String newName,
- @NonNull String expected) throws Exception {
- IProject project = createProject(testData);
- IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
- assertNotNull(javaProject);
- IType type = javaProject.findType(typeFqcn);
- assertNotNull(typeFqcn, type);
- assertTrue(typeFqcn, type.exists());
- RenameTypeProcessor processor = new RenameTypeProcessor(type);
- processor.setNewElementName(newName);
- processor.setUpdateQualifiedNames(true);
- processor.setUpdateSimilarDeclarations(false);
- //processor.setMatchStrategy(?);
- //processor.setFilePatterns(patterns);
- processor.setUpdateReferences(updateReferences);
- assertNotNull(processor);
-
- RenameRefactoring refactoring = new RenameRefactoring(processor);
- checkRefactoring(refactoring, expected);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourceXmlTextActionTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourceXmlTextActionTest.java
deleted file mode 100644
index e00a44b32..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/refactorings/core/RenameResourceXmlTextActionTest.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.refactorings.core;
-
-import com.android.ide.common.resources.ResourceUrl;
-import com.android.resources.ResourceType;
-
-import org.eclipse.jface.text.Document;
-import org.eclipse.jface.text.IDocument;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class RenameResourceXmlTextActionTest extends TestCase {
- public void test_Simple() throws Exception {
- checkWord("^foo", null);
- checkWord("'foo'^", null);
- checkWord("^@bogus", null);
- checkWord("@bo^gus", null);
- checkWord("bogus@^", null);
- checkWord(" @string/nam^e ", getUrl(ResourceType.STRING, "name"));
- checkWord("@string/nam^e ", getUrl(ResourceType.STRING, "name"));
- checkWord("\"^@string/name ", getUrl(ResourceType.STRING, "name"));
- checkWord("^@string/name ", getUrl(ResourceType.STRING, "name"));
- checkWord("\n^@string/name ", getUrl(ResourceType.STRING, "name"));
- checkWord("\n^@string/name(", getUrl(ResourceType.STRING, "name"));
- checkWord("\n^@string/name;", getUrl(ResourceType.STRING, "name"));
- checkWord("\n^@string/name5", getUrl(ResourceType.STRING, "name5"));
- checkWord("\n@string/name5^", getUrl(ResourceType.STRING, "name5"));
- checkWord("\n@string/name5^(", getUrl(ResourceType.STRING, "name5"));
- checkWord("\n@stri^ng/name5(", getUrl(ResourceType.STRING, "name5"));
- checkWord("\n@string^/name5(", getUrl(ResourceType.STRING, "name5"));
- checkWord("\n@string/^name5(", getUrl(ResourceType.STRING, "name5"));
- checkWord("\n@string^name5(", null);
- checkWord("\n@strings^/name5(", null);
- checkWord("\n@+id/^myid(", getUrl(ResourceType.ID, "myid"));
- checkWord("\n?a^ttr/foo\"", getUrl(ResourceType.ATTR, "foo"));
- checkWord("\n?f^oo\"", getUrl(ResourceType.ATTR, "foo"));
- checkWord("\n^?foo\"", getUrl(ResourceType.ATTR, "foo"));
- }
-
- private static ResourceUrl getUrl(ResourceType type, String name) {
- return ResourceUrl.create(type, name, false, false);
- }
-
- public void testClassNames() throws Exception {
- checkClassName("^foo", null);
- checkClassName("<^foo>", null);
- checkClassName("'foo.bar.Baz'^", null);
- checkClassName("<^foo.bar.Baz ", "foo.bar.Baz");
- checkClassName("<^foo.bar.Baz>", "foo.bar.Baz");
- checkClassName("<foo.^bar.Baz>", "foo.bar.Baz");
- checkClassName("<foo.bar.Baz^>", "foo.bar.Baz");
- checkClassName("<foo.bar.Baz^ >", "foo.bar.Baz");
- checkClassName("<foo.bar$Baz^ >", "foo.bar.Baz");
- checkClassName("</^foo.bar.Baz>", "foo.bar.Baz");
- checkClassName("</foo.^bar.Baz>", "foo.bar.Baz");
-
- checkClassName("\"^foo.bar.Baz\"", "foo.bar.Baz");
- checkClassName("\"foo.^bar.Baz\"", "foo.bar.Baz");
- checkClassName("\"foo.bar.Baz^\"", "foo.bar.Baz");
- checkClassName("\"foo.bar$Baz^\"", "foo.bar.Baz");
-
- checkClassName("<foo.^bar@Baz>", null);
- }
-
- private void checkClassName(String contents, String expectedClassName)
- throws Exception {
- int cursor = contents.indexOf('^');
- assertTrue("Must set cursor position with ^ in " + contents, cursor != -1);
- contents = contents.substring(0, cursor) + contents.substring(cursor + 1);
- assertEquals(-1, contents.indexOf('^'));
- assertEquals(-1, contents.indexOf('['));
- assertEquals(-1, contents.indexOf(']'));
-
- IDocument document = new Document();
- document.replace(0, 0, contents);
- String className =
- RenameResourceXmlTextAction.findClassName(document, null, cursor);
- assertEquals(expectedClassName, className);
- }
-
- private void checkWord(String contents, ResourceUrl expectedResource)
- throws Exception {
- int cursor = contents.indexOf('^');
- assertTrue("Must set cursor position with ^ in " + contents, cursor != -1);
- contents = contents.substring(0, cursor) + contents.substring(cursor + 1);
- assertEquals(-1, contents.indexOf('^'));
- assertEquals(-1, contents.indexOf('['));
- assertEquals(-1, contents.indexOf(']'));
-
- IDocument document = new Document();
- document.replace(0, 0, contents);
- ResourceUrl resource = RenameResourceXmlTextAction.findResource(document, cursor);
- assertEquals(expectedResource, resource);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/resources/ResourceHelperTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/resources/ResourceHelperTest.java
deleted file mode 100644
index de4e59101..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/resources/ResourceHelperTest.java
+++ /dev/null
@@ -1,183 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.resources;
-
-import com.android.ide.common.resources.ResourceDeltaKind;
-import com.android.ide.common.resources.configuration.FolderConfiguration;
-import com.android.ide.common.resources.configuration.ResourceQualifier;
-import com.android.resources.ResourceType;
-
-import org.eclipse.core.resources.IResourceDelta;
-
-import junit.framework.TestCase;
-
-
-/**
- * Test ResourceHelper
- */
-@SuppressWarnings("javadoc")
-public class ResourceHelperTest extends TestCase {
-
- /**
- * temp fake qualifier class.
- */
- private static class FakeQualifierClass extends ResourceQualifier {
-
- @Override
- public boolean checkAndSet(String value, FolderConfiguration config) {
- return false;
- }
-
- @Override
- public boolean equals(Object object) {
- return false;
- }
-
- @Override
- public String getFolderSegment() {
- return null;
- }
-
- @Override
- public String getLongDisplayValue() {
- return null;
- }
-
- @Override
- public String getName() {
- return null;
- }
-
- @Override
- public String getShortDisplayValue() {
- return null;
- }
-
- @Override
- public String getShortName() {
- return null;
- }
-
- @Override
- public boolean hasFakeValue() {
- return false;
- }
-
- @Override
- public int hashCode() {
- return 0;
- }
-
- @Override
- public boolean isValid() {
- return false;
- }
-
- @Override
- public int since() {
- return 0;
- }
- }
-
- public void testGetIcon() throws Exception {
- // check that the method returns null for an unknown qualifier class
- assertNull(ResourceHelper.getIcon(FakeQualifierClass.class));
-
- // find all the qualifiers through FolderConfiguration.createdefault()
- FolderConfiguration config = new FolderConfiguration();
- config.createDefault();
- final int count = FolderConfiguration.getQualifierCount();
- for (int i = 0 ; i < count ; i++) {
- ResourceQualifier qual = config.getQualifier(i);
- assertNotNull(qual);
- assertNotNull(qual.getClass().getCanonicalName(),
- ResourceHelper.getIcon(qual.getClass()));
- }
- }
-
- public void testGetResourceDeltaKind() {
- assertEquals(ResourceDeltaKind.ADDED,
- ResourceHelper.getResourceDeltaKind(IResourceDelta.ADDED));
- assertEquals(ResourceDeltaKind.REMOVED,
- ResourceHelper.getResourceDeltaKind(IResourceDelta.REMOVED));
- assertEquals(ResourceDeltaKind.CHANGED,
- ResourceHelper.getResourceDeltaKind(IResourceDelta.CHANGED));
-
- assertNull(ResourceHelper.getResourceDeltaKind(IResourceDelta.ADDED_PHANTOM));
- }
-
- public void testIsFileBasedResourceType() throws Exception {
- assertTrue(ResourceHelper.isFileBasedResourceType(ResourceType.ANIMATOR));
- assertTrue(ResourceHelper.isFileBasedResourceType(ResourceType.LAYOUT));
-
- assertFalse(ResourceHelper.isFileBasedResourceType(ResourceType.STRING));
- assertFalse(ResourceHelper.isFileBasedResourceType(ResourceType.DIMEN));
- assertFalse(ResourceHelper.isFileBasedResourceType(ResourceType.ID));
-
- // Both:
- assertTrue(ResourceHelper.isFileBasedResourceType(ResourceType.DRAWABLE));
- assertTrue(ResourceHelper.isFileBasedResourceType(ResourceType.COLOR));
- }
-
- public void testIsValueBasedResourceType() throws Exception {
- assertTrue(ResourceHelper.isValueBasedResourceType(ResourceType.STRING));
- assertTrue(ResourceHelper.isValueBasedResourceType(ResourceType.DIMEN));
- assertTrue(ResourceHelper.isValueBasedResourceType(ResourceType.ID));
-
- assertFalse(ResourceHelper.isValueBasedResourceType(ResourceType.LAYOUT));
-
- // These can be both:
- assertTrue(ResourceHelper.isValueBasedResourceType(ResourceType.DRAWABLE));
- assertTrue(ResourceHelper.isValueBasedResourceType(ResourceType.COLOR));
- }
-
- public void testCanCreateResource() throws Exception {
- assertTrue(ResourceHelper.canCreateResource("@layout/foo"));
- assertTrue(ResourceHelper.canCreateResource("@string/foo"));
- assertTrue(ResourceHelper.canCreateResource("@dimen/foo"));
- assertTrue(ResourceHelper.canCreateResource("@color/foo"));
-
- assertFalse(ResourceHelper.canCreateResource("@typo/foo")); // nonexistent type
- assertFalse(ResourceHelper.canCreateResource("@layout/foo bar")); // space
- assertFalse(ResourceHelper.canCreateResource("@layout/new")); // keyword
- assertFalse(ResourceHelper.canCreateResource("@android:string/foo")); // framework
- assertFalse(ResourceHelper.canCreateResource("@android:dimen/foo"));
- assertFalse(ResourceHelper.canCreateResource("@android:color/foo"));
- }
-
- public void testCanCreateResourceType() throws Exception {
- assertTrue(ResourceHelper.canCreateResourceType(ResourceType.LAYOUT));
- assertTrue(ResourceHelper.canCreateResourceType(ResourceType.STRING));
- assertTrue(ResourceHelper.canCreateResourceType(ResourceType.DIMEN));
- assertTrue(ResourceHelper.canCreateResourceType(ResourceType.COLOR));
-
- assertFalse(ResourceHelper.canCreateResourceType(ResourceType.RAW));
- assertFalse(ResourceHelper.canCreateResourceType(ResourceType.XML));
- }
-
- public void testStyleToTheme() throws Exception {
- assertEquals("Foo", ResourceHelper.styleToTheme("Foo"));
- assertEquals("Theme", ResourceHelper.styleToTheme("@android:style/Theme"));
- assertEquals("LocalTheme", ResourceHelper.styleToTheme("@style/LocalTheme"));
- //assertEquals("LocalTheme", ResourceHelper.styleToTheme("@foo.bar:style/LocalTheme"));
- }
-
- public void testIsProjectStyle() throws Exception {
- assertFalse(ResourceHelper.isProjectStyle("@android:style/Theme"));
- assertTrue(ResourceHelper.isProjectStyle("@style/LocalTheme"));
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/resources/ResourceNameValidatorTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/resources/ResourceNameValidatorTest.java
deleted file mode 100644
index 2cc2c932c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/resources/ResourceNameValidatorTest.java
+++ /dev/null
@@ -1,101 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.resources;
-
-import com.android.resources.ResourceFolderType;
-import com.android.resources.ResourceType;
-
-import org.eclipse.core.resources.IProject;
-
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Set;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class ResourceNameValidatorTest extends TestCase {
- public void testValidator() throws Exception {
- // Valid
- ResourceNameValidator validator = ResourceNameValidator.create(true,
- ResourceFolderType.VALUES);
- assertTrue(validator.isValid("foo") == null);
- assertTrue(validator.isValid("foo.xml") == null);
- assertTrue(validator.isValid("Foo123_$") == null);
- assertTrue(validator.isValid("foo.xm") == null); // For non-file types, . => _
-
- // Invalid
- assertTrue(validator.isValid("") != null);
- assertTrue(validator.isValid(" ") != null);
- assertTrue(validator.isValid("foo bar") != null);
- assertTrue(validator.isValid("1foo") != null);
- assertTrue(validator.isValid("foo%bar") != null);
- assertTrue(ResourceNameValidator.create(true, Collections.singleton("foo"),
- ResourceType.STRING).isValid("foo") != null);
- assertTrue(ResourceNameValidator.create(true,
- ResourceFolderType.DRAWABLE).isValid("foo.xm") != null);
- assertTrue(ResourceNameValidator.create(false,
- ResourceFolderType.DRAWABLE).isValid("foo.xm") != null);
-
- // Only lowercase chars allowed in file-based resource names
- assertTrue(ResourceNameValidator.create(true, ResourceFolderType.LAYOUT)
- .isValid("Foo123_$") != null);
- assertTrue(ResourceNameValidator.create(true, ResourceFolderType.LAYOUT)
- .isValid("foo123_") == null);
-
- // Can't start with _ in file-based resource names, is okay for value based resources
- assertTrue(ResourceNameValidator.create(true, ResourceFolderType.VALUES)
- .isValid("_foo") == null);
- assertTrue(ResourceNameValidator.create(true, ResourceFolderType.LAYOUT)
- .isValid("_foo") != null);
- assertTrue(ResourceNameValidator.create(true, ResourceFolderType.DRAWABLE)
- .isValid("_foo") != null);
- }
-
- public void testIds() throws Exception {
- ResourceNameValidator validator = ResourceNameValidator.create(false, (IProject) null,
- ResourceType.ID);
- assertTrue(validator.isValid("foo") == null);
- assertTrue(validator.isValid(" foo") != null);
- assertTrue(validator.isValid("foo ") != null);
- assertTrue(validator.isValid("foo@") != null);
- }
-
- public void testUniqueOrExists() throws Exception {
- Set<String> existing = new HashSet<String>();
- existing.add("foo1");
- existing.add("foo2");
- existing.add("foo3");
-
- ResourceNameValidator validator = ResourceNameValidator.create(true, existing,
- ResourceType.ID);
- validator.unique();
-
- assertNull(validator.isValid("foo")); // null: ok (no error message)
- assertNull(validator.isValid("foo4"));
- assertNotNull(validator.isValid("foo1"));
- assertNotNull(validator.isValid("foo2"));
- assertNotNull(validator.isValid("foo3"));
-
- validator.exist();
- assertNotNull(validator.isValid("foo"));
- assertNotNull(validator.isValid("foo4"));
- assertNull(validator.isValid("foo1"));
- assertNull(validator.isValid("foo2"));
- assertNull(validator.isValid("foo3"));
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/resources/manager/IdeScanningContextTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/resources/manager/IdeScanningContextTest.java
deleted file mode 100644
index 3104c8593..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/resources/manager/IdeScanningContextTest.java
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.resources.manager;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class IdeScanningContextTest extends TestCase {
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/sdk/AndroidJarLoaderTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/sdk/AndroidJarLoaderTest.java
deleted file mode 100644
index 5f7de429b..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/sdk/AndroidJarLoaderTest.java
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.sdk;
-
-import com.android.ide.eclipse.adt.internal.sdk.AndroidJarLoader;
-import com.android.ide.eclipse.adt.internal.sdk.IAndroidClassLoader.IClassDescriptor;
-import com.android.ide.eclipse.tests.AdtTestData;
-
-import java.lang.reflect.Field;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.HashMap;
-
-import junit.framework.TestCase;
-
-/**
- * Unit Test for {@link AndroidJarLoader}.
- *
- * Uses the classes jar.example.Class1/Class2 stored in tests/data/jar_example.jar.
- */
-public class AndroidJarLoaderTest extends TestCase {
-
- private AndroidJarLoader mFrameworkClassLoader;
-
- /** Creates an instance of {@link AndroidJarLoader} on our test data JAR */
- @Override
- public void setUp() throws Exception {
- String jarfilePath = AdtTestData.getInstance().getTestFilePath(
- "com/android/ide/eclipse/testdata/jar_example.jar"); //$NON-NLS-1$
- mFrameworkClassLoader = new AndroidJarLoader(jarfilePath);
- }
-
- @Override
- public void tearDown() throws Exception {
- mFrameworkClassLoader = null;
- System.gc();
- }
-
- /** Preloads classes. They should load just fine. */
- public final void testPreLoadClasses() throws Exception {
- mFrameworkClassLoader.preLoadClasses("jar.example.", null, null); //$NON-NLS-1$
- HashMap<String, Class<?>> map = getPrivateClassCache();
- assertEquals(0, map.size());
- HashMap<String,byte[]> data = getPrivateEntryCache();
- assertTrue(data.containsKey("jar.example.Class1")); //$NON-NLS-1$
- assertTrue(data.containsKey("jar.example.Class2")); //$NON-NLS-1$
- assertTrue(data.containsKey("jar.example.Class1$InnerStaticClass1")); //$NON-NLS-1$
- assertTrue(data.containsKey("jar.example.Class1$InnerClass2")); //$NON-NLS-1$
- assertEquals(4, data.size());
- }
-
- /** Preloads a class not in the JAR. Preloading does nothing in this case. */
- public final void testPreLoadClasses_classNotFound() throws Exception {
- mFrameworkClassLoader.preLoadClasses("not.a.package.", null, null); //$NON-NLS-1$
- HashMap<String, Class<?>> map = getPrivateClassCache();
- assertEquals(0, map.size());
- HashMap<String,byte[]> data = getPrivateEntryCache();
- assertEquals(0, data.size());
- }
-
- /** Finds a class we just preloaded. It should work. */
- public final void testFindClass_classFound() throws Exception {
- Class<?> c = _findClass(mFrameworkClassLoader, "jar.example.Class2"); //$NON-NLS-1$
- assertEquals("jar.example.Class2", c.getName()); //$NON-NLS-1$
- HashMap<String, Class<?>> map = getPrivateClassCache();
- assertTrue(map.containsKey("jar.example.Class1")); //$NON-NLS-1$
- assertTrue(map.containsKey("jar.example.Class2")); //$NON-NLS-1$
- assertEquals(2, map.size());
- }
-
- /** call the protected method findClass */
- private Class<?> _findClass(AndroidJarLoader jarLoader, String name) throws Exception {
- Method findClassMethod = AndroidJarLoader.class.getDeclaredMethod(
- "findClass", String.class); //$NON-NLS-1$
- findClassMethod.setAccessible(true);
- try {
- return (Class<?>)findClassMethod.invoke(jarLoader, name);
- }
- catch (InvocationTargetException e) {
- throw (Exception)e.getCause();
- }
- }
-
- /** Trying to find a class that we fail to preload should throw a CNFE. */
- public final void testFindClass_classNotFound() throws Exception {
- try {
- // Will throw ClassNotFoundException
- _findClass(mFrameworkClassLoader, "not.a.valid.ClassName"); //$NON-NLS-1$
- } catch (ClassNotFoundException e) {
- // check the message in the CNFE
- assertEquals("not.a.valid.ClassName", e.getMessage()); //$NON-NLS-1$
- return;
- }
- // Exception not thrown - this is a failure
- fail("Expected ClassNotFoundException not thrown");
- }
-
- public final void testFindClassesDerivingFrom() throws Exception {
- HashMap<String, ArrayList<IClassDescriptor>> found =
- mFrameworkClassLoader.findClassesDerivingFrom("jar.example.", new String[] { //$NON-NLS-1$
- "jar.example.Class1", //$NON-NLS-1$
- "jar.example.Class2" }); //$NON-NLS-1$
-
- assertTrue(found.containsKey("jar.example.Class1")); //$NON-NLS-1$
- assertTrue(found.containsKey("jar.example.Class2")); //$NON-NLS-1$
- assertEquals(2, found.size());
- // Only Class2 derives from Class1..
- // Class1 and Class1$InnerStaticClass1 derive from Object and are thus ignored.
- // Class1$InnerClass2 should never be seen either.
- assertEquals("jar.example.Class2", //$NON-NLS-1$
- found.get("jar.example.Class1").get(0).getFullClassName()); //$NON-NLS-1$
- assertEquals(1, found.get("jar.example.Class1").size()); //$NON-NLS-1$
- assertEquals(0, found.get("jar.example.Class2").size()); //$NON-NLS-1$
- }
-
- // --- Utilities ---
-
- /**
- * Retrieves the private mFrameworkClassLoader.mClassCache field using reflection.
- *
- * @throws NoSuchFieldException
- * @throws SecurityException
- * @throws IllegalAccessException
- * @throws IllegalArgumentException
- */
- @SuppressWarnings("unchecked")
- private HashMap<String, Class<?> > getPrivateClassCache()
- throws SecurityException, NoSuchFieldException,
- IllegalArgumentException, IllegalAccessException {
- Field field = AndroidJarLoader.class.getDeclaredField("mClassCache"); //$NON-NLS-1$
- field.setAccessible(true);
- return (HashMap<String, Class<?>>) field.get(mFrameworkClassLoader);
- }
-
- /**
- * Retrieves the private mFrameworkClassLoader.mEntryCache field using reflection.
- *
- * @throws NoSuchFieldException
- * @throws SecurityException
- * @throws IllegalAccessException
- * @throws IllegalArgumentException
- */
- @SuppressWarnings("unchecked")
- private HashMap<String,byte[]> getPrivateEntryCache()
- throws SecurityException, NoSuchFieldException,
- IllegalArgumentException, IllegalAccessException {
- Field field = AndroidJarLoader.class.getDeclaredField("mEntryCache"); //$NON-NLS-1$
- field.setAccessible(true);
- return (HashMap<String, byte[]>) field.get(mFrameworkClassLoader);
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/sdk/LayoutParamsParserTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/sdk/LayoutParamsParserTest.java
deleted file mode 100644
index c89dd0649..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/sdk/LayoutParamsParserTest.java
+++ /dev/null
@@ -1,182 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.adt.internal.sdk;
-
-import com.android.ide.common.resources.platform.AttrsXmlParser;
-import com.android.ide.common.resources.platform.ViewClassInfo;
-import com.android.ide.common.resources.platform.ViewClassInfo.LayoutParamsInfo;
-import com.android.ide.eclipse.adt.internal.sdk.AndroidJarLoader.ClassWrapper;
-import com.android.ide.eclipse.adt.internal.sdk.IAndroidClassLoader.IClassDescriptor;
-import com.android.ide.eclipse.mock.TestLogger;
-import com.android.ide.eclipse.tests.AdtTestData;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.TreeMap;
-
-import junit.framework.TestCase;
-
-/**
- * Test the inner private methods of PlatformDataParser.
- *
- * Convention: method names that start with an underscore are actually local wrappers
- * that call private methods from {@link AndroidTargetParser} using reflection.
- * This is inspired by the Python coding rule which mandates underscores prefixes for
- * "private" methods.
- */
-public class LayoutParamsParserTest extends TestCase {
-
- private static final String MOCK_DATA_PATH =
- "com/android/ide/eclipse/testdata/mock_attrs.xml"; //$NON-NLS-1$
-
- private static class MockFrameworkClassLoader extends AndroidJarLoader {
- MockFrameworkClassLoader() {
- super(null /* osFrameworkLocation */);
- }
-
- @Override
- public HashMap<String, ArrayList<IClassDescriptor>> findClassesDerivingFrom(
- String rootPackage, String[] superClasses) throws ClassFormatError {
- return new HashMap<String, ArrayList<IClassDescriptor>>();
- }
- }
-
- private static class MockLayoutParamsParser extends LayoutParamsParser {
- public MockLayoutParamsParser() {
- super(new MockFrameworkClassLoader(),
- new AttrsXmlParser(
- AdtTestData.getInstance().getTestFilePath(MOCK_DATA_PATH),
- new TestLogger(), 100).preload());
-
- mTopViewClass = new ClassWrapper(mock_android.view.View.class);
- mTopGroupClass = new ClassWrapper(mock_android.view.ViewGroup.class);
- mTopLayoutParamsClass = new ClassWrapper(mock_android.view.ViewGroup.LayoutParams.class);
-
- mViewList = new ArrayList<IClassDescriptor>();
- mGroupList = new ArrayList<IClassDescriptor>();
- mViewMap = new TreeMap<String, ExtViewClassInfo>();
- mGroupMap = new TreeMap<String, ExtViewClassInfo>();
- mLayoutParamsMap = new HashMap<String, LayoutParamsInfo>();
- }
- }
-
- private MockLayoutParamsParser mParser;
-
- @Override
- public void setUp() throws Exception {
- mParser = new MockLayoutParamsParser();
- }
-
- @Override
- public void tearDown() throws Exception {
- }
-
- public final void testFindLayoutParams() throws Exception {
- assertEquals(mock_android.view.ViewGroup.LayoutParams.class,
- ((ClassWrapper)_findLayoutParams(mock_android.view.ViewGroup.class)).wrappedClass());
-
- assertEquals(mock_android.widget.LinearLayout.LayoutParams.class,
- ((ClassWrapper)_findLayoutParams(mock_android.widget.LinearLayout.class)).wrappedClass());
-
- assertEquals(mock_android.widget.TableLayout.LayoutParams.class,
- ((ClassWrapper)_findLayoutParams(mock_android.widget.TableLayout.class)).wrappedClass());
- }
-
- public final void testGetLayoutParamsInfo() throws Exception {
- LayoutParamsInfo info1 = _getLayoutParamsInfo(
- mock_android.view.ViewGroup.LayoutParams.class);
- assertNotNull(info1);
- // ViewGroup.LayoutData has Object for superClass, which we don't map
- assertNull(info1.getSuperClass());
-
- LayoutParamsInfo info2 = _getLayoutParamsInfo(
- mock_android.widget.LinearLayout.LayoutParams.class);
- assertNotNull(info2);
- // LinearLayout.LayoutData links to ViewGroup.LayoutParams
- assertSame(info1, info2.getSuperClass());
-
- LayoutParamsInfo info3 = _getLayoutParamsInfo(
- mock_android.widget.TableLayout.LayoutParams.class);
- assertNotNull(info3);
- // TableLayout.LayoutData does not link to ViewGroup.LayoutParams nor
- // LinearLayout.LayoutParams
- assertNotSame(info1, info3.getSuperClass());
- assertNotSame(info2, info3.getSuperClass());
- // TableLayout.LayoutParams => ViewGroup.MarginLayoutParams => ViewGroup.LayoutParams
- assertSame(info1, info3.getSuperClass().getSuperClass());
- }
-
- public final void testGetLayoutClasses() throws Exception {
- // _getLayoutClasses();
- }
-
- //---- access to private methods
-
- /** Calls the private constructor of the parser */
- @SuppressWarnings("unused")
- private AndroidTargetParser _Constructor(String osJarPath) throws Exception {
- Constructor<AndroidTargetParser> constructor =
- AndroidTargetParser.class.getDeclaredConstructor(String.class);
- constructor.setAccessible(true);
- return constructor.newInstance(osJarPath);
- }
-
- /** calls the private getLayoutClasses() of the parser */
- @SuppressWarnings("unused")
- private void _getLayoutClasses() throws Exception {
- Method method = AndroidTargetParser.class.getDeclaredMethod("getLayoutClasses"); //$NON-NLS-1$
- method.setAccessible(true);
- method.invoke(mParser);
- }
-
- /** calls the private addGroup() of the parser */
- @SuppressWarnings("unused")
- private ViewClassInfo _addGroup(Class<?> groupClass) throws Exception {
- Method method = LayoutParamsParser.class.getDeclaredMethod("addGroup", //$NON-NLS-1$
- IClassDescriptor.class);
- method.setAccessible(true);
- return (ViewClassInfo) method.invoke(mParser, new ClassWrapper(groupClass));
- }
-
- /** calls the private addLayoutParams() of the parser */
- @SuppressWarnings("unused")
- private LayoutParamsInfo _addLayoutParams(Class<?> groupClass) throws Exception {
- Method method = LayoutParamsParser.class.getDeclaredMethod("addLayoutParams", //$NON-NLS-1$
- IClassDescriptor.class);
- method.setAccessible(true);
- return (LayoutParamsInfo) method.invoke(mParser, new ClassWrapper(groupClass));
- }
-
- /** calls the private getLayoutParamsInfo() of the parser */
- private LayoutParamsInfo _getLayoutParamsInfo(Class<?> layoutParamsClass) throws Exception {
- Method method = LayoutParamsParser.class.getDeclaredMethod("getLayoutParamsInfo", //$NON-NLS-1$
- IClassDescriptor.class);
- method.setAccessible(true);
- return (LayoutParamsInfo) method.invoke(mParser, new ClassWrapper(layoutParamsClass));
- }
-
- /** calls the private findLayoutParams() of the parser */
- private IClassDescriptor _findLayoutParams(Class<?> groupClass) throws Exception {
- Method method = LayoutParamsParser.class.getDeclaredMethod("findLayoutParams", //$NON-NLS-1$
- IClassDescriptor.class);
- method.setAccessible(true);
- return (IClassDescriptor) method.invoke(mParser, new ClassWrapper(groupClass));
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmActivityToLayoutMethodTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmActivityToLayoutMethodTest.java
deleted file mode 100644
index 9caeab25e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmActivityToLayoutMethodTest.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import freemarker.template.SimpleScalar;
-import freemarker.template.TemplateModelException;
-
-import java.util.Collections;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class FmActivityToLayoutMethodTest extends TestCase {
- @SuppressWarnings("rawtypes")
- private void check(String s, String expected) throws TemplateModelException {
- FmActivityToLayoutMethod method = new FmActivityToLayoutMethod();
- List list = Collections.singletonList(new SimpleScalar(s));
- assertEquals(expected, ((SimpleScalar) method.exec(list)).getAsString());
- }
-
- public void test1() throws Exception {
- check("FooActivity", "activity_foo");
- }
-
- public void test2() throws Exception {
- check("FooActiv", "activity_foo");
- }
-
- public void test3() throws Exception {
- check("Foo", "activity_foo");
- }
-
- public void test4() throws Exception {
- check("", "");
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmCamelCaseToUnderscoreMethodTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmCamelCaseToUnderscoreMethodTest.java
deleted file mode 100644
index dee0ce6bf..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmCamelCaseToUnderscoreMethodTest.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import freemarker.template.SimpleScalar;
-import freemarker.template.TemplateModelException;
-
-import java.util.Collections;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class FmCamelCaseToUnderscoreMethodTest extends TestCase {
- @SuppressWarnings("rawtypes")
- private void check(String s, String expected) throws TemplateModelException {
- FmCamelCaseToUnderscoreMethod method = new FmCamelCaseToUnderscoreMethod();
- List list = Collections.singletonList(new SimpleScalar(s));
- assertEquals(expected, ((SimpleScalar) method.exec(list)).getAsString());
- }
-
- public void test1() throws Exception {
- check("", "");
- }
-
- public void test2() throws Exception {
- check("foo", "foo");
- }
-
- public void test3() throws Exception {
- check("Foo", "foo");
- }
-
- public void test4() throws Exception {
- check("FooBar", "foo_bar");
- }
-
- public void test5() throws Exception {
- check("testXML", "test_xml");
- }
-
- public void test6() throws Exception {
- check("testFoo", "test_foo");
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmClassNameToResourceMethodTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmClassNameToResourceMethodTest.java
deleted file mode 100644
index ff90ea0ed..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmClassNameToResourceMethodTest.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import freemarker.template.SimpleScalar;
-import freemarker.template.TemplateModelException;
-
-import java.util.Collections;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class FmClassNameToResourceMethodTest extends TestCase {
- @SuppressWarnings("rawtypes")
- private void check(String s, String expected) throws TemplateModelException {
- FmClassNameToResourceMethod method = new FmClassNameToResourceMethod();
- List list = Collections.singletonList(new SimpleScalar(s));
- assertEquals(expected, ((SimpleScalar) method.exec(list)).getAsString());
- }
-
- public void test1() throws Exception {
- check("FooActivity", "foo");
- }
-
- public void test2() throws Exception {
- check("FooActiv", "foo");
- }
-
- public void test3() throws Exception {
- check("Foo", "foo");
- }
-
- public void test4() throws Exception {
- check("", "");
- }
-
- public void test5() throws Exception {
- check("FooFragment", "foo");
- }
-
- public void test6() throws Exception {
- check("FooService", "foo");
- }
-
- public void test7() throws Exception {
- check("FooProvider", "foo");
- }
-
- public void test8() throws Exception {
- check("FooBar", "foo_bar");
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmEscapeXmlAttributeMethodTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmEscapeXmlAttributeMethodTest.java
deleted file mode 100644
index eb1e94940..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmEscapeXmlAttributeMethodTest.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import freemarker.template.SimpleScalar;
-import freemarker.template.TemplateModelException;
-
-import java.util.Collections;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class FmEscapeXmlAttributeMethodTest extends TestCase {
- @SuppressWarnings("rawtypes")
- private void check(String s, String expected) throws TemplateModelException {
- FmEscapeXmlAttributeMethod method = new FmEscapeXmlAttributeMethod();
- List list = Collections.singletonList(new SimpleScalar(s));
- assertEquals(expected, ((SimpleScalar) method.exec(list)).getAsString());
- }
-
- public void test1() throws Exception {
- check("", "");
- }
-
- public void test2() throws Exception {
- check("foo", "foo");
- }
-
- public void test3() throws Exception {
- check("<\"'>&", "&lt;&quot;&apos;>&amp;");
- }
-
- public void test4() throws Exception {
- check("foo>bar", "foo>bar");
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmEscapeXmlStringMethodTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmEscapeXmlStringMethodTest.java
deleted file mode 100644
index 1a4289a03..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmEscapeXmlStringMethodTest.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import freemarker.template.SimpleScalar;
-import freemarker.template.TemplateModelException;
-
-import java.util.Collections;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class FmEscapeXmlStringMethodTest extends TestCase {
- @SuppressWarnings("rawtypes")
- private void check(String s, String expected) throws TemplateModelException {
- FmEscapeXmlStringMethod method = new FmEscapeXmlStringMethod();
- List list = Collections.singletonList(new SimpleScalar(s));
- assertEquals(expected, ((SimpleScalar) method.exec(list)).getAsString());
- }
-
- public void test1() throws Exception {
- check("", "");
- }
-
- public void test2() throws Exception {
- check("foo", "foo");
- }
-
- public void test3() throws Exception {
- check(" Foo Bar ", "\" Foo Bar \"");
- }
-
- public void test4() throws Exception {
- check("@foo", "\\@foo");
- }
-
- public void test5() throws Exception {
- check("Hello\nWorld", "Hello\\nWorld");
- }
-
- public void test6() throws Exception {
- check("A & B", "A &amp; B");
- }
-
- public void test7() throws Exception {
- check("Foo's Bar", "Foo\\'s Bar");
- }
-
- public void test8() throws Exception {
- check("'\"\\", "\\'\\\"\\\\");
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmEscapeXmlTextMethodTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmEscapeXmlTextMethodTest.java
deleted file mode 100644
index c08b834e9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmEscapeXmlTextMethodTest.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import freemarker.template.SimpleScalar;
-import freemarker.template.TemplateModelException;
-
-import java.util.Collections;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class FmEscapeXmlTextMethodTest extends TestCase {
- @SuppressWarnings("rawtypes")
- private void check(String s, String expected) throws TemplateModelException {
- FmEscapeXmlTextMethod method = new FmEscapeXmlTextMethod();
- List list = Collections.singletonList(new SimpleScalar(s));
- assertEquals(expected, ((SimpleScalar) method.exec(list)).getAsString());
- }
-
- public void test1() throws Exception {
- check("", "");
- }
-
- public void test2() throws Exception {
- check("foo", "foo");
- }
-
- public void test3() throws Exception {
- check("<\"'>&", "&lt;\"'>&amp;");
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmExtractLettersMethodTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmExtractLettersMethodTest.java
deleted file mode 100644
index b1d3cee13..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmExtractLettersMethodTest.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import freemarker.template.SimpleScalar;
-import freemarker.template.TemplateModelException;
-
-import java.util.Collections;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class FmExtractLettersMethodTest extends TestCase {
- @SuppressWarnings("rawtypes")
- private void check(String s, String expected) throws TemplateModelException {
- FmExtractLettersMethod method = new FmExtractLettersMethod();
- List list = Collections.singletonList(new SimpleScalar(s));
- assertEquals(expected, ((SimpleScalar) method.exec(list)).getAsString());
- }
-
- public void test1() throws Exception {
- check("", "");
- }
-
- public void test2() throws Exception {
- check("foo", "foo");
- }
-
- public void test3() throws Exception {
- check("<\"'>&foo ", "foo");
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmLayoutToActivityMethodTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmLayoutToActivityMethodTest.java
deleted file mode 100644
index af0a1dbf5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmLayoutToActivityMethodTest.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import freemarker.template.SimpleScalar;
-import freemarker.template.TemplateModelException;
-
-import java.util.Collections;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class FmLayoutToActivityMethodTest extends TestCase {
- @SuppressWarnings("rawtypes")
- private void check(String s, String expected) throws TemplateModelException {
- FmLayoutToActivityMethod method = new FmLayoutToActivityMethod();
- List list = Collections.singletonList(new SimpleScalar(s));
- assertEquals(expected, ((SimpleScalar) method.exec(list)).getAsString());
- }
-
- public void test1() throws Exception {
- check("foo", "FooActivity");
- }
-
- public void test2() throws Exception {
- check("activity_foo", "FooActivity");
- }
-
- public void test3() throws Exception {
- check("activity_", "MyActivity");
- }
-
- public void test4() throws Exception {
- check("activ", "ActivActivity");
- }
-
- public void test5() throws Exception {
- check("", "MyActivity");
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmSlashedPackageNameMethodTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmSlashedPackageNameMethodTest.java
deleted file mode 100644
index 439110237..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmSlashedPackageNameMethodTest.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import freemarker.template.SimpleScalar;
-import freemarker.template.TemplateModelException;
-
-import java.util.Collections;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class FmSlashedPackageNameMethodTest extends TestCase {
- @SuppressWarnings("rawtypes")
- private void check(String s, String expected) throws TemplateModelException {
- FmSlashedPackageNameMethod method = new FmSlashedPackageNameMethod();
- List list = Collections.singletonList(new SimpleScalar(s));
- assertEquals(expected, ((SimpleScalar) method.exec(list)).getAsString());
- }
-
- public void test1() throws Exception {
- check("", "");
- }
-
- public void test2() throws Exception {
- check("foo", "foo");
- }
-
- public void test3() throws Exception {
- check("foo.bar.baz", "foo/bar/baz");
- }
-
- public void test4() throws Exception {
- check("foo/bar/baz", "foo/bar/baz");
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmUnderscoreToCamelCaseMethodTest.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmUnderscoreToCamelCaseMethodTest.java
deleted file mode 100644
index 4955dae79..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/adt/internal/wizards/templates/FmUnderscoreToCamelCaseMethodTest.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2012 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.adt.internal.wizards.templates;
-
-import freemarker.template.SimpleScalar;
-import freemarker.template.TemplateModelException;
-
-import java.util.Collections;
-import java.util.List;
-
-import junit.framework.TestCase;
-
-@SuppressWarnings("javadoc")
-public class FmUnderscoreToCamelCaseMethodTest extends TestCase {
- @SuppressWarnings("rawtypes")
- private void check(String s, String expected) throws TemplateModelException {
- FmUnderscoreToCamelCaseMethod method = new FmUnderscoreToCamelCaseMethod();
- List list = Collections.singletonList(new SimpleScalar(s));
- assertEquals(expected, ((SimpleScalar) method.exec(list)).getAsString());
- }
-
- public void test1() throws Exception {
- check("", "");
- }
-
- public void test2() throws Exception {
- check("_", "");
- }
-
- public void test3() throws Exception {
- check("foo", "Foo");
- }
-
- public void test4() throws Exception {
- check("foo_bar", "FooBar");
- }
-
- public void test5() throws Exception {
- check("foo__bar", "FooBar");
- }
-
- public void test6() throws Exception {
- check("foo_", "Foo");
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/mock/Mocks.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/mock/Mocks.java
deleted file mode 100644
index 65e2144be..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/mock/Mocks.java
+++ /dev/null
@@ -1,189 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.mock;
-
-import static org.easymock.EasyMock.capture;
-import static org.easymock.EasyMock.createMock;
-import static org.easymock.EasyMock.createNiceMock;
-import static org.easymock.EasyMock.eq;
-import static org.easymock.EasyMock.expect;
-import static org.easymock.EasyMock.expectLastCall;
-import static org.easymock.EasyMock.isA;
-import static org.easymock.EasyMock.replay;
-
-import com.android.io.IAbstractFolder;
-import com.android.io.IAbstractResource;
-
-import org.easymock.Capture;
-import org.easymock.EasyMock;
-import org.easymock.IAnswer;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IFolder;
-import org.eclipse.core.resources.IProject;
-import org.eclipse.core.resources.IResource;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.jdt.core.IClasspathEntry;
-import org.eclipse.jdt.core.IJavaProject;
-import org.eclipse.jdt.core.JavaCore;
-
-import java.util.Map;
-
-public class Mocks {
- public static IJavaProject createProject(IClasspathEntry[] entries, IPath outputLocation)
- throws Exception {
- IJavaProject javaProject = createMock(IJavaProject.class);
- final Capture<IClasspathEntry[]> capturedEntries = new Capture<IClasspathEntry[]>();
- Capture<IPath> capturedOutput = new Capture<IPath>();
- capturedEntries.setValue(entries);
- capturedOutput.setValue(outputLocation);
-
- IProject project = createProject();
- expect(javaProject.getProject()).andReturn(project).anyTimes();
- expect(javaProject.getOutputLocation()).andReturn(capturedOutput.getValue()).anyTimes();
-
- expect(javaProject.getRawClasspath()).andAnswer(new IAnswer<IClasspathEntry[]>() {
- @Override
- public IClasspathEntry[] answer() throws Throwable {
- return capturedEntries.getValue();
- }
- }).anyTimes();
-
- javaProject.setRawClasspath(capture(capturedEntries), isA(IProgressMonitor.class));
- expectLastCall().anyTimes();
-
- javaProject.setRawClasspath(capture(capturedEntries), capture(capturedOutput),
- isA(IProgressMonitor.class));
- expectLastCall().anyTimes();
-
- final Capture<String> capturedCompliance = new Capture<String>();
- capturedCompliance.setValue("1.4");
- final Capture<String> capturedSource = new Capture<String>();
- capturedSource.setValue("1.4");
- final Capture<String> capturedTarget = new Capture<String>();
- capturedTarget.setValue("1.4");
-
- expect(javaProject.getOption(JavaCore.COMPILER_COMPLIANCE, true)).andAnswer(
- new IAnswer<String>() {
- @Override
- public String answer() throws Throwable {
- return capturedCompliance.getValue();
- }
- });
- expect(javaProject.getOption(JavaCore.COMPILER_SOURCE, true)).andAnswer(
- new IAnswer<String>() {
- @Override
- public String answer() throws Throwable {
- return capturedSource.getValue();
- }
- });
- expect(javaProject.getOption(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM, true)).andAnswer(
- new IAnswer<String>() {
- @Override
- public String answer() throws Throwable {
- return capturedTarget.getValue();
- }
- });
-
- javaProject.setOption(eq(JavaCore.COMPILER_COMPLIANCE), capture(capturedCompliance));
- expectLastCall().anyTimes();
- javaProject.setOption(eq(JavaCore.COMPILER_SOURCE), capture(capturedSource));
- expectLastCall().anyTimes();
- javaProject.setOption(eq(JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM),
- capture(capturedTarget));
- expectLastCall().anyTimes();
-
- replay(javaProject);
-
- return javaProject;
- }
-
- /**
- * Creates a mock implementation of {@link IFile}.
- * <p/>
- * Supported methods:
- * <ul>
- * <li>IFile#getName()</li>
- * <li>IFile#getLocation()</li>
- * </ul>
- */
- public static IFile createFile(String fileName) {
- IFile file = createNiceMock(IFile.class);
- expect(file.getName()).andReturn(fileName).anyTimes();
- expect(file.getLocation()).andReturn(new Path(fileName)).anyTimes();
- replay(file);
- return file;
- }
-
- /**
- * Creates a mock implementation of {@link IFolder}.
- * <p/>
- * Supported methods:
- * <ul>
- * <li>{@link IFolder#getName()}</li>
- * <li>{@link IFolder#members()}</li>
- * </ul>
- */
- public static IFolder createFolder(String name, IResource[] members) throws Exception {
- IFolder file = createNiceMock(IFolder.class);
- expect(file.getName()).andReturn(name).anyTimes();
- // expect(file.getLocation()).andReturn(new Path(name)).anyTimes();
- expect(file.members()).andReturn(members).anyTimes();
- replay(file);
- return file;
- }
-
- public static IAbstractFolder createAbstractFolder(String name, IAbstractResource[] members) {
- IAbstractFolder folder = createNiceMock(IAbstractFolder.class);
- expect(folder.getName()).andReturn(name).anyTimes();
- // expect(file.getLocation()).andReturn(new Path(name)).anyTimes();
- expect(folder.listMembers()).andReturn(members).anyTimes();
- replay(folder);
-
- return folder;
- }
-
- /**
- * Mock implementation of {@link IProject}.
- * <p/>
- * Supported methods:
- * <ul>
- * <li>{@link IProject#build(int kind, IProgressMonitor monitor)}</li>
- * <li>
- * {@link IProject#build(int kind, String builderName, Map args, IProgressMonitor monitor)}
- * </li>
- * </ul>
- */
- public static IProject createProject() {
- IProject project = EasyMock.createNiceMock(IProject.class);
- replay(project);
- return project;
- }
-
- /**
- * Creates a mock implementation of an {@link IClasspathEntry}, which supports
- * {@link IClasspathEntry#getEntryKind} and {@link IClasspathEntry#getPath}.
- */
- public static IClasspathEntry createClasspathEntry(IPath path, int kind) {
- IClasspathEntry entry = createNiceMock(IClasspathEntry.class);
- expect(entry.getEntryKind()).andReturn(kind).anyTimes();
- expect(entry.getPath()).andReturn(path).anyTimes();
- replay(entry);
- return entry;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/mock/TestLogger.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/mock/TestLogger.java
deleted file mode 100644
index f8bf4b31a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/mock/TestLogger.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.mock;
-
-
-import com.android.utils.ILogger;
-
-import junit.framework.Assert;
-
-/**
- * Implementation of {@link ILogger} suitable for test use; will fail the current test if
- * {@link #error} is called, and prints everything else to standard error.
- */
-public class TestLogger implements ILogger {
-
- @Override
- public void error(Throwable t, String errorFormat, Object... args) {
- String message = String.format(errorFormat, args);
- if (t != null) {
- message = t.toString() + ":" + message; //$NON-NLS-1$
- }
- Assert.fail(message);
- }
-
- @Override
- public void info(String msgFormat, Object... args) {
- System.out.println(String.format(msgFormat, args));
- }
-
- @Override
- public void verbose(String msgFormat, Object... args) {
- info(msgFormat, args);
- }
-
- @Override
- public void warning(String warningFormat, Object... args) {
- System.err.println(String.format(warningFormat, args));
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/content-area-one-dot.9.png b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/content-area-one-dot.9.png
deleted file mode 100644
index 690d76efc..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/content-area-one-dot.9.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/content-area-two-dots.9.png b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/content-area-two-dots.9.png
deleted file mode 100644
index c3d3e4c29..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/content-area-two-dots.9.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/content-area.9.png b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/content-area.9.png
deleted file mode 100644
index 6a7a62c59..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/content-area.9.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched1.9.png b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched1.9.png
deleted file mode 100644
index 9e5ffbf46..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched1.9.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched2.9.png b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched2.9.png
deleted file mode 100644
index cfd9c1d64..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched2.9.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched3.9.png b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched3.9.png
deleted file mode 100644
index 0f2c3eba5..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched3.9.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched4.9.png b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched4.9.png
deleted file mode 100644
index ce7321032..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched4.9.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched5.9.png b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched5.9.png
deleted file mode 100644
index 97d9cd860..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched5.9.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched6.9.png b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched6.9.png
deleted file mode 100644
index f9b8a4870..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched6.9.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched7.9.png b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched7.9.png
deleted file mode 100644
index bbbb3ad8c..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched7.9.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched8.9.png b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched8.9.png
deleted file mode 100644
index 35f04b547..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/invalid-patched8.9.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/layout-bounds-only.9.png b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/layout-bounds-only.9.png
deleted file mode 100644
index 6f7047318..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/layout-bounds-only.9.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/no-patched-interlace.png b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/no-patched-interlace.png
deleted file mode 100644
index a6d0e94af..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/no-patched-interlace.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/no-patched.png b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/no-patched.png
deleted file mode 100644
index 742b1e816..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/no-patched.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/patched-with-badpatches.9.png b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/patched-with-badpatches.9.png
deleted file mode 100644
index 1a38972cd..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/patched-with-badpatches.9.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/patched1.9.png b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/patched1.9.png
deleted file mode 100644
index 6a7a62c59..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/patched1.9.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/patched2.9.png b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/patched2.9.png
deleted file mode 100644
index 11a1a6d12..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/patched2.9.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/patched3.9.png b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/patched3.9.png
deleted file mode 100644
index 8d288c903..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/draw9patch/patched3.9.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/jar_example.jar b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/jar_example.jar
deleted file mode 100644
index f95b59588..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/jar_example.jar
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/jar_example.jardesc b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/jar_example.jardesc
deleted file mode 100644
index 14cd44f5a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/jar_example.jardesc
+++ /dev/null
@@ -1,16 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
-<jardesc>
- <jar path="jar_example.jar"/>
- <options buildIfNeeded="true" compress="true" descriptionLocation="/common/tests/data/jar_example.jardesc" exportErrors="false" exportWarnings="true" includeDirectoryEntries="false" overwrite="false" saveDescription="true" storeRefactorings="false" useSourceFolders="false"/>
- <storedRefactorings deprecationInfo="true" structuralOnly="false"/>
- <selectedProjects/>
- <manifest generateManifest="true" manifestLocation="" manifestVersion="1.0" reuseManifest="false" saveManifest="false" usesManifest="true">
- <sealing sealJar="false">
- <packagesToSeal/>
- <packagesToUnSeal/>
- </sealing>
- </manifest>
- <selectedElements exportClassFiles="true" exportJavaFiles="false" exportOutputFolder="false">
- <javaElement handleIdentifier="=common/tests&lt;jar.example"/>
- </selectedElements>
-</jardesc>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/mock_attrs.xml b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/mock_attrs.xml
deleted file mode 100644
index db77e1749..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/mock_attrs.xml
+++ /dev/null
@@ -1,340 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
--->
-<resources>
- <!-- WARNING !!! THIS IS A MOCK FILE. DO NOT USE FOR DOCUMENTATION PURPOSES.
- This file has been trimmed down to only extract a number of interesting cases
- for unit tests.
-
- What this contains:
- - View
- - ViewGroup
- - some attributes which format are defined in Theme
- - orientation, gravity and layout_gravity defined before they are used
- - ViewGroup_Layout
- - ViewGroup_MarginLayout
- - LinearLayout
- - LinearLayout_Layout
- - TableLayout
-
- Note that TableLayout does not have a TableLayout_Layout definition here
- where these is a class TableLayout.LayoutData.
- -->
-
- <!-- These are the standard attributes that make up a complete theme. -->
- <declare-styleable name="Theme">
-
- <!-- Defines the scrollbars size. -->
- <attr name="scrollbarSize" format="dimension" />
-
- </declare-styleable>
-
-
- <!-- Standard orientation constant. -->
- <attr name="orientation">
- <!-- Defines an horizontal widget. -->
- <enum name="horizontal" value="0" />
- <!-- Defines a vertical widget. -->
- <enum name="vertical" value="1" />
- </attr>
-
- <!-- Specifies how to place an object, both
- its x and y axis, within a larger containing object. -->
- <attr name="gravity">
- <!-- Push object to the top of its container, not changing its size. -->
- <flag name="top" value="0x30" />
- <!-- Push object to the bottom of its container, not changing its size. -->
- <flag name="bottom" value="0x50" />
- <!-- Push object to the left of its container, not changing its size. -->
- <flag name="left" value="0x03" />
- <!-- Push object to the right of its container, not changing its size. -->
- <flag name="right" value="0x05" />
- <!-- Place object in the vertical center of its container, not changing its size. -->
- <flag name="center_vertical" value="0x10" />
- <!-- Grow the vertical size of the object if needed so it completely fills its container. -->
- <flag name="fill_vertical" value="0x70" />
- <!-- Place object in the horizontal center of its container, not changing its size. -->
- <flag name="center_horizontal" value="0x01" />
- <!-- Grow the horizontal size of the object if needed so it completely fills its container. -->
- <flag name="fill_horizontal" value="0x07" />
- <!-- Place the object in the center of its container in both the vertical and horizontal axis, not changing its size. -->
- <flag name="center" value="0x11" />
- <!-- Grow the horizontal and vertical size of the object if needed so it completely fills its container. -->
- <flag name="fill" value="0x77" />
- </attr>
-
- <!-- Standard gravity constant that a child can supply to its parent.
- Defines how to place an object, both
- its x and y axis, within a larger containing object. -->
- <attr name="layout_gravity">
- <!-- Push object to the top of its container, not changing its size. -->
- <flag name="top" value="0x30" />
- <!-- Push object to the bottom of its container, not changing its size. -->
- <flag name="bottom" value="0x50" />
- <!-- Push object to the left of its container, not changing its size. -->
- <flag name="left" value="0x03" />
- <!-- Push object to the right of its container, not changing its size. -->
- <flag name="right" value="0x05" />
- <!-- Place object in the vertical center of its container, not changing its size. -->
- <flag name="center_vertical" value="0x10" />
- <!-- Grow the vertical size of the object if needed so it completely fills its container. -->
- <flag name="fill_vertical" value="0x70" />
- <!-- Place object in the horizontal center of its container, not changing its size. -->
- <flag name="center_horizontal" value="0x01" />
- <!-- Grow the horizontal size of the object if needed so it completely fills its container. -->
- <flag name="fill_horizontal" value="0x07" />
- <!-- Place the object in the center of its container in both the vertical and horizontal axis, not changing its size. -->
- <flag name="center" value="0x11" />
- <!-- Grow the horizontal and vertical size of the object if needed so it completely fills its container. -->
- <flag name="fill" value="0x77" />
- </attr>
-
- <declare-styleable name="View">
- <!-- NOTE: View does not have a javadoc. Do not place a comment BEFORE View to make sure it
- is NOT interpreted as Javadoc -->
-
- <!-- Supply an identifier name for this view, to later retrieve it
- with {@link android.view.View#findViewById View.findViewById()} or
- {@link android.app.Activity#findViewById Activity.findViewById()}.
- This must be a
- resource reference; typically you set this using the
- <code>@+</code> syntax to create a new ID resources.
- For example: <code>android:id="@+id/my_id"</code> which
- allows you to later retrieve the view
- with <code>findViewById(R.id.my_id)</code>. -->
- <attr name="id" format="reference" />
-
- <!-- Supply a tag for this view containing a String, to be retrieved
- later with {@link android.view.View#getTag View.getTag()} or
- searched for with {@link android.view.View#findViewWithTag
- View.findViewWithTag()}. It is generally preferable to use
- IDs (through the android:id attribute) instead of tags because
- they are faster and allow for compile-time type checking. -->
- <attr name="tag" format="string" />
-
- <!-- The initial horizontal scroll offset, in pixels.-->
- <attr name="scrollX" format="dimension" />
-
- <!-- The initial vertical scroll offset, in pixels. -->
- <attr name="scrollY" format="dimension" />
-
- <!-- A drawable to use as the background. This can be either a reference
- to a full drawable resource (such as a PNG image, 9-patch,
- XML state list description, etc), or a solid color such as "#ff000000"
- (black). -->
- <attr name="background" format="reference|color" />
-
- <!-- Boolean that controls whether a view can take focus. By default the user can not
- move focus to a view; by setting this attribute to true the view is
- allowed to take focus. This value does not impact the behavior of
- directly calling {@link android.view.View#requestFocus}, which will
- always request focus regardless of this view. It only impacts where
- focus navigation will try to move focus. -->
- <attr name="focusable" format="boolean" />
-
- <!-- Sets the circumstances under which this view will take focus. There are
- two choices: "weak" or "normal". The default value is "normal" for
- any focusable views. The focus type only applies if the view
- has been set to be focusable. -->
- <attr name="focusType">
- <!-- This view is focusable, but only if none of its descendants are already focused. -->
- <enum name="normal" value="0" />
- <!-- This view will always claim to be focusable. -->
- <enum name="weak" value="1" />
- </attr>
-
- <!-- Controls the initial visibility of the view. -->
- <attr name="visibility">
- <!-- Visible on screen; the default value. -->
- <enum name="visible" value="0" />
- <!-- Not displayed, but taken into account during layout (space is left for it). -->
- <enum name="invisible" value="1" />
- <!-- Completely hidden, as if the view had not been added. -->
- <enum name="gone" value="2" />
- </attr>
-
- <!-- Defines which scrollbars should be displayed on scrolling or not. -->
- <attr name="scrollbars">
- <!-- No scrollbar is displayed. -->
- <flag name="none" value="0x00000000" />
- <!-- Displays horizontal scrollbar only. -->
- <flag name="horizontal" value="0x00000100" />
- <!-- Displays vertical scrollbar only. -->
- <flag name="vertical" value="0x00000200" />
- </attr>
-
- <!-- Sets the width of vertical scrollbars and height of horizontal scrollbars. -->
- <attr name="scrollbarSize" />
-
- <!-- Text to display. (copied from TextView for the extra localization) -->
- <attr name="text" format="string" localization="suggested" />
-
- </declare-styleable>
-
- <!-- Attributes that can be used with a {@link android.view.ViewGroup} or any
- of its subclasses. Also see {@link #ViewGroup_Layout} for
- attributes that this class processes in its children. -->
- <declare-styleable name="ViewGroup">
- <!-- Defines whether a child is limited to draw inside of its bounds or not.
- This is useful with animations that scale the size of the children to more
- than 100% for instance. In such a case, this property should be set to false
- to allow the children to draw outside of their bounds. The default value of
- this property is true. -->
- <attr name="clipChildren" format="boolean" />
- <!-- Defines the layout animation to use the first time the ViewGroup is laid out.
- Layout animations can also be started manually after the first layout. -->
- <attr name="layoutAnimation" format="reference" />
- <!-- Defines whether a child's animation should be kept when it is over. Keeping
- the animations is useful with animation whose final state is different from
- the initial state of the View. This is particularly useful with animation
- whose fillAfter property is enabled. This property is set to false by default. -->
- <attr name="persistentDrawingCache">
- <!-- The drawing cache is not persisted after use. -->
- <flag name="none" value="0x0" />
- <!-- The drawing cache is persisted after a layout animation. -->
- <flag name="animation" value="0x1" />
- <!-- The drawing cache is persisted after a scroll. -->
- <flag name="scrolling" value="0x2" />
- <!-- The drawing cache is always persisted. -->
- <flag name="all" value="0x3" />
- </attr>
- </declare-styleable>
-
- <!-- This is the basic set of layout attributes that are common to all
- layout managers. These attributes are specified with the rest of
- a view's normal attributes (such as {@link android.R.attr#background},
- but will be parsed by the view's parent and ignored by the child.
- <p>The values defined here correspond to the base layout attribute
- class {@link android.view.ViewGroup.LayoutParams}. -->
- <declare-styleable name="ViewGroup_Layout">
- <!-- Specifies the basic width of the view. This is a required attribute
- for any view inside of a containing layout manager. Its value may
- be a dimension (such as "12dip") for a constant width or one of
- the special constants. -->
- <attr name="layout_width" format="dimension">
- <!-- The view should be as big as its parent (minus padding). -->
- <enum name="match_parent" value="-1" />
- <!-- The view should be only big enough to enclose its content (plus padding). -->
- <enum name="wrap_content" value="-2" />
- </attr>
-
- <!-- Specifies the basic height of the view. This is a required attribute
- for any view inside of a containing layout manager. Its value may
- be a dimension (such as "12dip") for a constant height or one of
- the special constants. -->
- <attr name="layout_height" format="dimension">
- <!-- The view should be as big as its parent (minus padding). -->
- <enum name="match_parent" value="-1" />
- <!-- The view should be only big enough to enclose its content (plus padding). -->
- <enum name="wrap_content" value="-2" />
- </attr>
- </declare-styleable>
-
- <!-- This is the basic set of layout attributes for layout managers that
- wish to place margins around their child views.
- These attributes are specified with the rest of
- a view's normal attributes (such as {@link android.R.attr#background},
- but will be parsed by the view's parent and ignored by the child.
- <p>The values defined here correspond to the base layout attribute
- class {@link android.view.ViewGroup.MarginLayoutParams}. -->
- <declare-styleable name="ViewGroup_MarginLayout">
- <attr name="layout_width" />
- <attr name="layout_height" />
- <!-- Specifies extra space on the left side of this view.
- This space is outside this view's bounds. -->
- <attr name="layout_marginLeft" format="dimension" />
- <!-- Specifies extra space on the top side of this view.
- This space is outside this view's bounds. -->
- <attr name="layout_marginTop" format="dimension" />
- <!-- Specifies extra space on the right side of this view.
- This space is outside this view's bounds. -->
- <attr name="layout_marginRight" format="dimension" />
- <!-- Specifies extra space on the bottom side of this view.
- This space is outside this view's bounds. -->
- <attr name="layout_marginBottom" format="dimension" />
- </declare-styleable>
-
- <!-- This is a linear layout. -->
- <declare-styleable name="LinearLayout">
- <!-- Should the layout be a column or a row? Use "horizontal"
- for a row, "vertical" for a column. The default is
- horizontal. -->
- <attr name="orientation" />
- <attr name="baselineAligned" format="boolean|reference" />
- <!-- When a linear layout is part of another layout that is baseline
- aligned, it can specify which of its children to baseline align to
- (i.e which child TextView).-->
- <attr name="baselineAlignedChildIndex" format="integer|color" min="0"/>
- <!-- Defines the maximum weight sum. If unspecified, the sum is computed
- by adding the layout_weight of all of the children. This can be
- used for instance to give a single child 50% of the total available
- space by giving it a layout_weight of 0.5 and setting the weightSum
- to 1.0. -->
- <attr name="weightSum" format="float" />
- </declare-styleable>
-
- <declare-styleable name="LinearLayout_Layout">
- <attr name="layout_width" />
- <attr name="layout_height" />
- <attr name="layout_weight" format="float" />
- <attr name="layout_gravity" />
- </declare-styleable>
-
- <declare-styleable name="TableLayout">
- <!-- The 0 based index of the columns to stretch. The column indices
- must be separated by a comma: 1, 2, 5. Illegal and duplicate
- indices are ignored. You can stretch all columns by using the
- value "*" instead. Note that a column can be marked stretchable
- and shrinkable at the same time. -->
- <attr name="stretchColumns" format="string" />
- <!-- The 0 based index of the columns to shrink. The column indices
- must be separated by a comma: 1, 2, 5. Illegal and duplicate
- indices are ignored. You can shrink all columns by using the
- value "*" instead. Note that a column can be marked stretchable
- and shrinkable at the same time. -->
- <attr name="shrinkColumns" format="string" />
- <!-- The 0 based index of the columns to collapse. The column indices
- must be separated by a comma: 1, 2, 5. Illegal and duplicate
- indices are ignored. -->
- <attr name="collapseColumns" format="string" />
- </declare-styleable>
-
- <!-- Test for deprecated attributes. -->
- <declare-styleable name="DeprecatedTest">
- <!-- Deprecated comments using delimiters.
- Ignored. {@deprecated In-line deprecated.} {@ignore Ignored}.
- -->
- <attr name="deprecated-inline" />
-
- <!-- Deprecated comments on their own line.
- @deprecated Multi-line version of deprecated
- that works till the next tag.
- @ignore This tag must be ignored
- -->
- <attr name="deprecated-multiline" />
-
- <!-- This attribute is not deprecated. -->
- <attr name="deprecated-not" />
-
- <!-- {@deprecated There is no other javadoc here. } -->
- <attr name="deprecated-no-javadoc" format="boolean" />
-
- </declare-styleable>
-
-</resources>
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/mock_manifest_attrs.xml b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/mock_manifest_attrs.xml
deleted file mode 100755
index 2335d257a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/com/android/ide/eclipse/testdata/mock_manifest_attrs.xml
+++ /dev/null
@@ -1,180 +0,0 @@
-<?xml version="1.0" encoding="utf-8"?>
-<!--
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
--->
-<resources>
- <!-- WARNING !!! THIS IS A MOCK FILE. DO NOT USE FOR DOCUMENTATION PURPOSES.
- This file has been trimmed down to only extract a number of interesting cases
- for unit tests.
-
- -->
-
- <!-- **************************************************************** -->
- <!-- These are the attributes used in AndroidManifest.xml. -->
- <!-- **************************************************************** -->
- <eat-comment />
-
- <!-- The overall theme to use for an activity. Use with either the
- application tag (to supply a default theme for all activities) or
- the activity tag (to supply a specific theme for that activity).
-
- <p>This automatically sets
- your activity's Context to use this theme, and may also be used
- for "starting" animations prior to the activity being launched (to
- better match what the activity actually looks like). It is a reference
- to a style resource defining the theme. If not set, the default
- system theme will be used. -->
- <attr name="theme" format="reference" />
-
- <!-- A user-legible name for the given item. Use with the
- application tag (to supply a default label for all application
- components), or with the activity, receiver, service, or instrumentation
- tag (to supply a specific label for that component). It may also be
- used with the intent-filter tag to supply a label to show to the
- user when an activity is being selected based on a particular Intent.
-
- <p>The given label will be used wherever the user sees information
- about its associated component; for example, as the name of a
- main activity that is displayed in the launcher. You should
- generally set this to a reference to a string resource, so that
- it can be localized, however it is also allowed to supply a plain
- string for quick and dirty programming. -->
- <attr name="label" format="reference|string" />
-
- <!-- A Drawable resource providing a graphical representation of its
- associated item. Use with the
- application tag (to supply a default icon for all application
- components), or with the activity, receiver, service, or instrumentation
- tag (to supply a specific icon for that component). It may also be
- used with the intent-filter tag to supply an icon to show to the
- user when an activity is being selected based on a particular Intent.
-
- <p>The given icon will be used to display to the user a graphical
- representation of its associated component; for example, as the icon
- for main activity that is displayed in the launcher. This must be
- a reference to a Drawable resource containing the image definition. -->
- <attr name="icon" format="reference" />
-
- <!-- A unique name for the given item. This must use a Java-style naming
- convention to ensure the name is unique, for example
- "com.mycompany.MyName". -->
- <attr name="name" format="string" />
-
- <!-- Internal version code. This is the number used to determine whether
- one version is more recent than another: it has no other meaning than
- that higher numbers are more recent. You could use this number to
- encode a "x.y" in the lower and upper 16 bits, make it a build
- number, simply increase it by one each time a new version is
- released, or define it however else you want, as long as each
- successive version has a higher number. This is not a version
- number generally shown to the user, that is usually supplied
- with {@link android.R.attr#versionName}. -->
- <attr name="versionCode" format="integer" />
-
- <!-- The text shown to the user to indicate the version they have. This
- is used for no other purpose than display to the user; the actual
- significant version number is given by {@link android.R.attr#versionCode}. -->
- <attr name="versionName" format="string" />
-
- <!-- .............. -->
-
- <!-- The <code>manifest</code> tag is the root of an
- <code>AndroidManifest.xml</code> file,
- describing the contents of an Android package (.apk) file. One
- attribute must always be supplied: <code>package</code> gives a
- unique name for the package, using a Java-style naming convention
- to avoid name collisions. For example, applications published
- by Google could have names of the form
- <code>com.google.app.<em>appname</em></code> -->
- <declare-styleable name="AndroidManifest">
- <attr name="versionCode" />
- <attr name="versionName" />
- </declare-styleable>
-
- <!-- The <code>application</code> tag describes application-level components
- contained in the package, as well as general application
- attributes. Many of the attributes you can supply here (such
- as theme, label, icon, permission, process, taskAffinity,
- and allowTaskReparenting) serve
- as default values for the corresponding attributes of components
- declared inside of the application.
-
- <p>Inside of this element you specify what the application contains,
- using the elements {@link #AndroidManifestProvider provider},
- {@link #AndroidManifestService service},
- {@link #AndroidManifestReceiver receiver},
- {@link #AndroidManifestActivity activity},
- {@link #AndroidManifestActivityAlias activity-alias}, and
- {@link #AndroidManifestUsesLibrary uses-library}. The application tag
- appears as a child of the root {@link #AndroidManifest manifest} tag. -->
- <declare-styleable name="AndroidManifestApplication" parent="AndroidManifest">
- <attr name="name" />
- <attr name="theme" />
- <attr name="label" />
- <attr name="icon" />
- <attr name="cantSaveState" format="boolean" />
- </declare-styleable>
-
- <!-- The <code>permission</code> tag declares a security permission that can be
- used to control access from other packages to specific components or
- features in your package (or other packages). See the
- <a href="{@docRoot}guide/topics/security/security.html">Security and Permissions</a>
- document for more information on permissions.
-
- <p>This appears as a child tag of the root
- {@link #AndroidManifest manifest} tag. -->
- <declare-styleable name="AndroidManifestPermission" parent="AndroidManifest">
- <!-- Required public name of the permission, which other components and
- packages will use when referring to this permission. This is a string using
- Java-style scoping to ensure it is unique. The prefix will often
- be the same as our overall package name, for example
- "com.mycompany.android.myapp.SomePermission". -->
- <attr name="name" />
- <attr name="label" />
- <attr name="icon" />
- </declare-styleable>
-
-
- <!-- The <code>activity-alias</code> tag declares a new
- name for an existing {@link #AndroidManifestActivity activity}
- tag.
-
- <p>Zero or more {@link #AndroidManifestIntentFilter intent-filter}
- tags can be included inside of an activity-alias, to specify the Intents
- that it can handle. If none are specified, the activity can
- only be started through direct specification of its class name.
- The activity-alias tag appears as a child tag of the
- {@link #AndroidManifestApplication application} tag. -->
- <declare-styleable name="AndroidManifestActivityAlias" parent="AndroidManifestApplication">
- <!-- Required name of the class implementing the activity, deriving from
- {@link android.app.Activity}. This is a fully
- qualified class name (for example, com.mycompany.myapp.MyActivity); as a
- short-hand if the first character of the class
- is a period then it is appended to your package name. -->
- <attr name="name" />
- <attr name="label" />
- <attr name="icon" />
- </declare-styleable>
-
- <declare-styleable name="AndroidManifestNewParentNewElement"
- parent="AndroidManifest.AndroidManifestNewParent">
- <attr name="name" />
- <attr name="label" />
- <attr name="icon" />
- </declare-styleable>
-
-</resources>
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/mock_android/view/View.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/mock_android/view/View.java
deleted file mode 100644
index a80a98daf..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/mock_android/view/View.java
+++ /dev/null
@@ -1,21 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mock_android.view;
-
-public class View {
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/mock_android/view/ViewGroup.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/mock_android/view/ViewGroup.java
deleted file mode 100644
index 466470fc1..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/mock_android/view/ViewGroup.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mock_android.view;
-
-public class ViewGroup extends View {
-
- public class MarginLayoutParams extends LayoutParams {
-
- }
-
- public class LayoutParams {
-
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/mock_android/widget/LinearLayout.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/mock_android/widget/LinearLayout.java
deleted file mode 100644
index 3870a63d9..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/mock_android/widget/LinearLayout.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mock_android.widget;
-
-import mock_android.view.ViewGroup;
-
-public class LinearLayout extends ViewGroup {
-
- public class LayoutParams extends mock_android.view.ViewGroup.LayoutParams {
-
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/mock_android/widget/TableLayout.java b/eclipse/plugins/com.android.ide.eclipse.tests/unittests/mock_android/widget/TableLayout.java
deleted file mode 100644
index e455e7d61..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.tests/unittests/mock_android/widget/TableLayout.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Eclipse Public License, Version 1.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.eclipse.org/org/documents/epl-v10.php
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package mock_android.widget;
-
-import mock_android.view.ViewGroup;
-
-public class TableLayout extends ViewGroup {
-
- public class LayoutParams extends MarginLayoutParams {
-
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.traceview/.classpath b/eclipse/plugins/com.android.ide.eclipse.traceview/.classpath
deleted file mode 100644
index 30837956d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.traceview/.classpath
+++ /dev/null
@@ -1,8 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="src" path="src"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
- <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/>
- <classpathentry kind="lib" path="libs/traceview.jar" sourcepath="/traceview"/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
diff --git a/eclipse/plugins/com.android.ide.eclipse.traceview/.project b/eclipse/plugins/com.android.ide.eclipse.traceview/.project
deleted file mode 100644
index 0cb5d189f..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.traceview/.project
+++ /dev/null
@@ -1,28 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>plugin-traceview</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.ManifestBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- <buildCommand>
- <name>org.eclipse.pde.SchemaBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.PluginNature</nature>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
diff --git a/eclipse/plugins/com.android.ide.eclipse.traceview/.settings/org.eclipse.jdt.core.prefs b/eclipse/plugins/com.android.ide.eclipse.traceview/.settings/org.eclipse.jdt.core.prefs
deleted file mode 100644
index ea661960a..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.traceview/.settings/org.eclipse.jdt.core.prefs
+++ /dev/null
@@ -1,98 +0,0 @@
-eclipse.preferences.version=1
-org.eclipse.jdt.core.compiler.annotation.missingNonNullByDefaultAnnotation=ignore
-org.eclipse.jdt.core.compiler.annotation.nonnull=com.android.annotations.NonNull
-org.eclipse.jdt.core.compiler.annotation.nonnullbydefault=com.android.annotations.NonNullByDefault
-org.eclipse.jdt.core.compiler.annotation.nonnullisdefault=disabled
-org.eclipse.jdt.core.compiler.annotation.nullable=com.android.annotations.Nullable
-org.eclipse.jdt.core.compiler.annotation.nullanalysis=enabled
-org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
-org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
-org.eclipse.jdt.core.compiler.compliance=1.6
-org.eclipse.jdt.core.compiler.debug.lineNumber=generate
-org.eclipse.jdt.core.compiler.debug.localVariable=generate
-org.eclipse.jdt.core.compiler.debug.sourceFile=generate
-org.eclipse.jdt.core.compiler.problem.annotationSuperInterface=warning
-org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
-org.eclipse.jdt.core.compiler.problem.autoboxing=ignore
-org.eclipse.jdt.core.compiler.problem.comparingIdentical=warning
-org.eclipse.jdt.core.compiler.problem.deadCode=warning
-org.eclipse.jdt.core.compiler.problem.deprecation=warning
-org.eclipse.jdt.core.compiler.problem.deprecationInDeprecatedCode=disabled
-org.eclipse.jdt.core.compiler.problem.deprecationWhenOverridingDeprecatedMethod=disabled
-org.eclipse.jdt.core.compiler.problem.discouragedReference=warning
-org.eclipse.jdt.core.compiler.problem.emptyStatement=ignore
-org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
-org.eclipse.jdt.core.compiler.problem.explicitlyClosedAutoCloseable=ignore
-org.eclipse.jdt.core.compiler.problem.fallthroughCase=warning
-org.eclipse.jdt.core.compiler.problem.fatalOptionalError=enabled
-org.eclipse.jdt.core.compiler.problem.fieldHiding=warning
-org.eclipse.jdt.core.compiler.problem.finalParameterBound=warning
-org.eclipse.jdt.core.compiler.problem.finallyBlockNotCompletingNormally=warning
-org.eclipse.jdt.core.compiler.problem.forbiddenReference=error
-org.eclipse.jdt.core.compiler.problem.hiddenCatchBlock=warning
-org.eclipse.jdt.core.compiler.problem.includeNullInfoFromAsserts=enabled
-org.eclipse.jdt.core.compiler.problem.incompatibleNonInheritedInterfaceMethod=warning
-org.eclipse.jdt.core.compiler.problem.incompleteEnumSwitch=warning
-org.eclipse.jdt.core.compiler.problem.indirectStaticAccess=ignore
-org.eclipse.jdt.core.compiler.problem.localVariableHiding=warning
-org.eclipse.jdt.core.compiler.problem.methodWithConstructorName=warning
-org.eclipse.jdt.core.compiler.problem.missingDefaultCase=ignore
-org.eclipse.jdt.core.compiler.problem.missingDeprecatedAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.missingEnumCaseDespiteDefault=disabled
-org.eclipse.jdt.core.compiler.problem.missingHashCodeMethod=warning
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotation=error
-org.eclipse.jdt.core.compiler.problem.missingOverrideAnnotationForInterfaceMethodImplementation=enabled
-org.eclipse.jdt.core.compiler.problem.missingSerialVersion=warning
-org.eclipse.jdt.core.compiler.problem.missingSynchronizedOnInheritedMethod=ignore
-org.eclipse.jdt.core.compiler.problem.noEffectAssignment=warning
-org.eclipse.jdt.core.compiler.problem.noImplicitStringConversion=warning
-org.eclipse.jdt.core.compiler.problem.nonExternalizedStringLiteral=ignore
-org.eclipse.jdt.core.compiler.problem.nullAnnotationInferenceConflict=warning
-org.eclipse.jdt.core.compiler.problem.nullReference=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecInsufficientInfo=warning
-org.eclipse.jdt.core.compiler.problem.nullSpecViolation=warning
-org.eclipse.jdt.core.compiler.problem.nullUncheckedConversion=ignore
-org.eclipse.jdt.core.compiler.problem.overridingPackageDefaultMethod=warning
-org.eclipse.jdt.core.compiler.problem.parameterAssignment=ignore
-org.eclipse.jdt.core.compiler.problem.possibleAccidentalBooleanAssignment=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullReference=warning
-org.eclipse.jdt.core.compiler.problem.potentialNullSpecViolation=error
-org.eclipse.jdt.core.compiler.problem.potentiallyUnclosedCloseable=warning
-org.eclipse.jdt.core.compiler.problem.rawTypeReference=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullAnnotation=warning
-org.eclipse.jdt.core.compiler.problem.redundantNullCheck=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSpecificationOfTypeArguments=ignore
-org.eclipse.jdt.core.compiler.problem.redundantSuperinterface=warning
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBePotentiallyStatic=ignore
-org.eclipse.jdt.core.compiler.problem.reportMethodCanBeStatic=ignore
-org.eclipse.jdt.core.compiler.problem.specialParameterHidingField=disabled
-org.eclipse.jdt.core.compiler.problem.staticAccessReceiver=warning
-org.eclipse.jdt.core.compiler.problem.suppressOptionalErrors=enabled
-org.eclipse.jdt.core.compiler.problem.suppressWarnings=enabled
-org.eclipse.jdt.core.compiler.problem.syntheticAccessEmulation=ignore
-org.eclipse.jdt.core.compiler.problem.typeParameterHiding=warning
-org.eclipse.jdt.core.compiler.problem.unavoidableGenericTypeProblems=disabled
-org.eclipse.jdt.core.compiler.problem.uncheckedTypeOperation=warning
-org.eclipse.jdt.core.compiler.problem.unclosedCloseable=error
-org.eclipse.jdt.core.compiler.problem.undocumentedEmptyBlock=ignore
-org.eclipse.jdt.core.compiler.problem.unhandledWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.unnecessaryElse=ignore
-org.eclipse.jdt.core.compiler.problem.unnecessaryTypeCheck=warning
-org.eclipse.jdt.core.compiler.problem.unqualifiedFieldAccess=ignore
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownException=warning
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionExemptExceptionAndThrowable=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedDeclaredThrownExceptionWhenOverriding=disabled
-org.eclipse.jdt.core.compiler.problem.unusedImport=warning
-org.eclipse.jdt.core.compiler.problem.unusedLabel=warning
-org.eclipse.jdt.core.compiler.problem.unusedLocal=warning
-org.eclipse.jdt.core.compiler.problem.unusedObjectAllocation=warning
-org.eclipse.jdt.core.compiler.problem.unusedParameter=ignore
-org.eclipse.jdt.core.compiler.problem.unusedParameterIncludeDocCommentReference=enabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenImplementingAbstract=disabled
-org.eclipse.jdt.core.compiler.problem.unusedParameterWhenOverridingConcrete=disabled
-org.eclipse.jdt.core.compiler.problem.unusedPrivateMember=warning
-org.eclipse.jdt.core.compiler.problem.unusedWarningToken=warning
-org.eclipse.jdt.core.compiler.problem.varargsArgumentNeedCast=warning
-org.eclipse.jdt.core.compiler.source=1.6
diff --git a/eclipse/plugins/com.android.ide.eclipse.traceview/META-INF/MANIFEST.MF b/eclipse/plugins/com.android.ide.eclipse.traceview/META-INF/MANIFEST.MF
deleted file mode 100644
index 8e031342e..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.traceview/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,17 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: Traceview
-Bundle-SymbolicName: com.android.ide.eclipse.traceview;singleton:=true
-Bundle-Version: 24.3.3.qualifier
-Bundle-Activator: com.android.ide.eclipse.traceview.TraceviewPlugin
-Require-Bundle: org.eclipse.ui,
- org.eclipse.core.runtime,
- org.eclipse.ui.ide,
- com.android.ide.eclipse.ddms;bundle-version="21.0.0",
- org.eclipse.core.filesystem,
- org.eclipse.core.resources
-Bundle-ActivationPolicy: lazy
-Bundle-ClassPath: .,
- libs/traceview.jar
-Bundle-Vendor: The Android Open Source Project
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
diff --git a/eclipse/plugins/com.android.ide.eclipse.traceview/about.ini b/eclipse/plugins/com.android.ide.eclipse.traceview/about.ini
deleted file mode 100644
index b61f64631..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.traceview/about.ini
+++ /dev/null
@@ -1,2 +0,0 @@
-aboutText=%blurb
-featureImage=icons/traceview-32.png \ No newline at end of file
diff --git a/eclipse/plugins/com.android.ide.eclipse.traceview/about.properties b/eclipse/plugins/com.android.ide.eclipse.traceview/about.properties
deleted file mode 100755
index b33e9f3ef..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.traceview/about.properties
+++ /dev/null
@@ -1,7 +0,0 @@
-blurb=Traceview\n\
-\n\
-Version\: {featureVersion}\n\
-\n\
-(c) Copyright 2011 The Android Open Source Project. All rights reserved.\n\
-Visit http://developer.android.com/sdk/eclipse-adt.html
-
diff --git a/eclipse/plugins/com.android.ide.eclipse.traceview/build.properties b/eclipse/plugins/com.android.ide.eclipse.traceview/build.properties
deleted file mode 100644
index 4895f9ffb..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.traceview/build.properties
+++ /dev/null
@@ -1,9 +0,0 @@
-source.. = src/
-output.. = bin/
-bin.includes = META-INF/,\
- .,\
- libs/,\
- plugin.xml,\
- icons/,\
- about.ini,\
- about.properties
diff --git a/eclipse/plugins/com.android.ide.eclipse.traceview/icons/android.png b/eclipse/plugins/com.android.ide.eclipse.traceview/icons/android.png
deleted file mode 100644
index a8dc35ec4..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.traceview/icons/android.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.traceview/icons/traceview-32.png b/eclipse/plugins/com.android.ide.eclipse.traceview/icons/traceview-32.png
deleted file mode 100644
index 4916737ec..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.traceview/icons/traceview-32.png
+++ /dev/null
Binary files differ
diff --git a/eclipse/plugins/com.android.ide.eclipse.traceview/plugin.xml b/eclipse/plugins/com.android.ide.eclipse.traceview/plugin.xml
deleted file mode 100644
index 042a630e6..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.traceview/plugin.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<?eclipse version="3.4"?>
-<plugin>
- <extension
- point="org.eclipse.ui.editors">
- <editor
- class="com.android.ide.eclipse.traceview.editors.TraceviewEditor"
- default="true"
- extensions="trace"
- icon="icons/android.png"
- id="com.android.ide.eclipse.traceview.editors.TraceviewEditor"
- name="Traceview">
- </editor>
- </extension>
- <extension
- point="com.android.ide.eclipse.ddms.traceviewLauncher">
- <launcher
- class="com.android.ide.eclipse.traceview.TraceviewLauncher">
- </launcher>
- </extension>
-
-</plugin>
diff --git a/eclipse/plugins/com.android.ide.eclipse.traceview/pom.xml b/eclipse/plugins/com.android.ide.eclipse.traceview/pom.xml
deleted file mode 100644
index e0a4df7b7..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.traceview/pom.xml
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <version>24.3.3-SNAPSHOT</version>
- <artifactId>com.android.ide.eclipse.traceview</artifactId>
- <packaging>eclipse-plugin</packaging>
- <name>traceview</name>
-
- <parent>
- <relativePath>../../pom.xml</relativePath>
- <groupId>adt.group</groupId>
- <artifactId>parent</artifactId>
- <version>1.0.0-SNAPSHOT</version>
- </parent>
-</project>
diff --git a/eclipse/plugins/com.android.ide.eclipse.traceview/src/com/android/ide/eclipse/traceview/TraceviewLauncher.java b/eclipse/plugins/com.android.ide.eclipse.traceview/src/com/android/ide/eclipse/traceview/TraceviewLauncher.java
deleted file mode 100644
index b232bac3d..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.traceview/src/com/android/ide/eclipse/traceview/TraceviewLauncher.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.ide.eclipse.traceview;
-
-import com.android.ide.eclipse.ddms.ITraceviewLauncher;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.IAdaptable;
-import org.eclipse.core.runtime.Path;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.IWorkbench;
-import org.eclipse.ui.IWorkbenchPage;
-import org.eclipse.ui.IWorkbenchWindow;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.PlatformUI;
-import org.eclipse.ui.WorkbenchException;
-import org.eclipse.ui.ide.IDE;
-
-public class TraceviewLauncher implements ITraceviewLauncher {
-
- @Override
- public boolean openFile(String osPath) {
- final IFileStore fileStore = EFS.getLocalFileSystem().getStore(new Path(osPath));
- if (!fileStore.fetchInfo().isDirectory() && fileStore.fetchInfo().exists()) {
- // before we open the file in an editor window, we make sure the current
- // workbench page has an editor area (typically the ddms perspective doesn't).
- final IWorkbench workbench = PlatformUI.getWorkbench();
- Display display = workbench.getDisplay();
- final boolean[] result = new boolean[] { false };
- display.syncExec(new Runnable() {
- @Override
- public void run() {
- IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
- IWorkbenchPage page = window.getActivePage();
- if (page.isEditorAreaVisible() == false) {
- IAdaptable input;
- if (page != null)
- input= page.getInput();
- else
- input= ResourcesPlugin.getWorkspace().getRoot();
- try {
- workbench.showPerspective("org.eclipse.debug.ui.DebugPerspective",
- window, input);
- } catch (WorkbenchException e) {
- }
- }
-
- try {
- result[0] = IDE.openEditorOnFileStore(page, fileStore) != null;
- } catch (PartInitException e) {
- // return false below
- }
- }
- });
-
- return result[0];
- }
-
- return false;
- }
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.traceview/src/com/android/ide/eclipse/traceview/TraceviewPlugin.java b/eclipse/plugins/com.android.ide.eclipse.traceview/src/com/android/ide/eclipse/traceview/TraceviewPlugin.java
deleted file mode 100644
index e11f7c929..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.traceview/src/com/android/ide/eclipse/traceview/TraceviewPlugin.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.traceview;
-
-import org.eclipse.ui.plugin.AbstractUIPlugin;
-import org.osgi.framework.BundleContext;
-
-/**
- * The activator class controls the plug-in life cycle
- */
-public class TraceviewPlugin extends AbstractUIPlugin {
-
- // The plug-in ID
- public static final String PLUGIN_ID = "com.android.ide.eclipse.traceview"; // $NON-NLS-1$
-
- // The shared instance
- private static TraceviewPlugin sPlugin;
-
- /**
- * The constructor
- */
- public TraceviewPlugin() {
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
- */
- @Override
- public void start(BundleContext context) throws Exception {
- super.start(context);
- sPlugin = this;
- }
-
- /*
- * (non-Javadoc)
- * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
- */
- @Override
- public void stop(BundleContext context) throws Exception {
- sPlugin = null;
- super.stop(context);
- }
-
- /**
- * Returns the shared instance
- *
- * @return the shared instance
- */
- public static TraceviewPlugin getDefault() {
- return sPlugin;
- }
-
-}
diff --git a/eclipse/plugins/com.android.ide.eclipse.traceview/src/com/android/ide/eclipse/traceview/editors/TraceviewEditor.java b/eclipse/plugins/com.android.ide.eclipse.traceview/src/com/android/ide/eclipse/traceview/editors/TraceviewEditor.java
deleted file mode 100644
index 6d07018cd..000000000
--- a/eclipse/plugins/com.android.ide.eclipse.traceview/src/com/android/ide/eclipse/traceview/editors/TraceviewEditor.java
+++ /dev/null
@@ -1,316 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.ide.eclipse.traceview.editors;
-
-import com.android.ide.eclipse.ddms.JavaSourceRevealer;
-import com.android.ide.eclipse.traceview.TraceviewPlugin;
-import com.android.traceview.ColorController;
-import com.android.traceview.DmTraceReader;
-import com.android.traceview.MethodData;
-import com.android.traceview.ProfileView;
-import com.android.traceview.ProfileView.MethodHandler;
-import com.android.traceview.SelectionController;
-import com.android.traceview.TimeLineView;
-import com.android.traceview.TraceReader;
-import com.android.traceview.TraceUnits;
-
-import org.eclipse.core.filesystem.EFS;
-import org.eclipse.core.filesystem.IFileStore;
-import org.eclipse.core.filesystem.URIUtil;
-import org.eclipse.core.resources.IFile;
-import org.eclipse.core.resources.IWorkspace;
-import org.eclipse.core.resources.IWorkspaceRoot;
-import org.eclipse.core.resources.ResourcesPlugin;
-import org.eclipse.core.runtime.CoreException;
-import org.eclipse.core.runtime.IPath;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.jface.dialogs.IDialogConstants;
-import org.eclipse.jface.dialogs.IMessageProvider;
-import org.eclipse.jface.dialogs.MessageDialog;
-import org.eclipse.jface.window.Window;
-import org.eclipse.swt.SWT;
-import org.eclipse.swt.custom.SashForm;
-import org.eclipse.swt.graphics.Color;
-import org.eclipse.swt.layout.GridData;
-import org.eclipse.swt.layout.GridLayout;
-import org.eclipse.swt.widgets.Composite;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.swt.widgets.FileDialog;
-import org.eclipse.swt.widgets.Label;
-import org.eclipse.swt.widgets.Shell;
-import org.eclipse.ui.IEditorInput;
-import org.eclipse.ui.IEditorSite;
-import org.eclipse.ui.PartInitException;
-import org.eclipse.ui.dialogs.SaveAsDialog;
-import org.eclipse.ui.ide.FileStoreEditorInput;
-import org.eclipse.ui.part.EditorPart;
-import org.eclipse.ui.part.FileEditorInput;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.URI;
-
-public class TraceviewEditor extends EditorPart implements MethodHandler {
-
- private Composite mParent;
- private String mFilename;
- private Composite mContents;
-
- @Override
- public void doSave(IProgressMonitor monitor) {
- // We do not modify the file
- }
-
- /*
- * Copied from org.eclipse.ui.texteditor.AbstractDecoratedTextEditor.
- */
- /**
- * Checks whether there given file store points to a file in the workspace.
- * Only returns a workspace file if there's a single match.
- *
- * @param fileStore the file store
- * @return the <code>IFile</code> that matches the given file store
- */
- private IFile getWorkspaceFile(IFileStore fileStore) {
- IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
- IFile[] files = workspaceRoot.findFilesForLocationURI(fileStore.toURI());
- if (files != null && files.length == 1)
- return files[0];
- return null;
- }
-
- /*
- * Based on the performSaveAs() method defined in class
- * org.eclipse.ui.texteditor.AbstractDecoratedTextEditor of the
- * org.eclipse.ui.editors plugin.
- */
- @Override
- public void doSaveAs() {
- Shell shell = getSite().getShell();
- final IEditorInput input = getEditorInput();
-
- final IEditorInput newInput;
-
- if (input instanceof FileEditorInput) {
- // the file is part of the current workspace
- FileEditorInput fileEditorInput = (FileEditorInput) input;
- SaveAsDialog dialog = new SaveAsDialog(shell);
-
- IFile original = fileEditorInput.getFile();
- if (original != null) {
- dialog.setOriginalFile(original);
- }
-
- dialog.create();
-
- if (original != null && !original.isAccessible()) {
- String message = String.format(
- "The original file ''%s'' has been deleted or is not accessible.",
- original.getName());
- dialog.setErrorMessage(null);
- dialog.setMessage(message, IMessageProvider.WARNING);
- }
-
- if (dialog.open() == Window.CANCEL) {
- return;
- }
-
- IPath filePath = dialog.getResult();
- if (filePath == null) {
- return;
- }
-
- IWorkspace workspace = ResourcesPlugin.getWorkspace();
- IFile file = workspace.getRoot().getFile(filePath);
-
- if (copy(shell, fileEditorInput.getURI(), file.getLocationURI()) == null) {
- return;
- }
-
- try {
- file.refreshLocal(IFile.DEPTH_ZERO, null);
- } catch (CoreException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- newInput = new FileEditorInput(file);
- setInput(newInput);
- setPartName(newInput.getName());
- } else if (input instanceof FileStoreEditorInput) {
- // the file is not part of the current workspace
- FileStoreEditorInput fileStoreEditorInput = (FileStoreEditorInput) input;
- FileDialog dialog = new FileDialog(shell, SWT.SAVE);
- IPath oldPath = URIUtil.toPath(fileStoreEditorInput.getURI());
- if (oldPath != null) {
- dialog.setFileName(oldPath.lastSegment());
- dialog.setFilterPath(oldPath.toOSString());
- }
-
- String path = dialog.open();
- if (path == null) {
- return;
- }
-
- // Check whether file exists and if so, confirm overwrite
- final File localFile = new File(path);
- if (localFile.exists()) {
- MessageDialog overwriteDialog = new MessageDialog(
- shell,
- "Save As",
- null,
- String.format(
- "%s already exists.\nDo you want to replace it?"
- , path),
- MessageDialog.WARNING,
- new String[] {
- IDialogConstants.YES_LABEL, IDialogConstants.NO_LABEL
- }, 1); // 'No' is the default
- if (overwriteDialog.open() != Window.OK) {
- return;
- }
- }
-
- IFileStore destFileStore = copy(shell, fileStoreEditorInput.getURI(), localFile.toURI());
- if (destFileStore != null) {
- IFile file = getWorkspaceFile(destFileStore);
- if (file != null) {
- newInput = new FileEditorInput(file);
- } else {
- newInput = new FileStoreEditorInput(destFileStore);
- }
- setInput(newInput);
- setPartName(newInput.getName());
- }
- }
- }
-
- private IFileStore copy(Shell shell, URI source, URI dest) {
- IFileStore destFileStore = null;
- IFileStore sourceFileStore = null;
- try {
- destFileStore = EFS.getStore(dest);
- sourceFileStore = EFS.getStore(source);
- sourceFileStore.copy(destFileStore, EFS.OVERWRITE, null);
- } catch (CoreException ex) {
- String title = "Problems During Save As...";
- String msg = String.format("Save could not be completed. %s",
- ex.getMessage());
- MessageDialog.openError(shell, title, msg);
- return null;
- }
- return destFileStore;
- }
-
- @Override
- public void init(IEditorSite site, IEditorInput input) throws PartInitException {
- // The contract of init() mentions we need to fail if we can't
- // understand the input.
- if (input instanceof FileEditorInput) {
- // We try to open a file that is part of the current workspace
- FileEditorInput fileEditorInput = (FileEditorInput) input;
- mFilename = fileEditorInput.getPath().toOSString();
- setSite(site);
- setInput(input);
- setPartName(input.getName());
- } else if (input instanceof FileStoreEditorInput) {
- // We try to open a file that is not part of the current workspace
- FileStoreEditorInput fileStoreEditorInput = (FileStoreEditorInput) input;
- mFilename = fileStoreEditorInput.getURI().getPath();
- setSite(site);
- setInput(input);
- setPartName(input.getName());
- } else {
- throw new PartInitException("Input is not of type FileEditorInput " + //$NON-NLS-1$
- "nor FileStoreEditorInput: " + //$NON-NLS-1$
- input == null ? "null" : input.toString()); //$NON-NLS-1$
- }
- }
-
- @Override
- public boolean isDirty() {
- return false;
- }
-
- @Override
- public boolean isSaveAsAllowed() {
- return true;
- }
-
- @Override
- public void createPartControl(Composite parent) {
- mParent = parent;
- try {
- TraceReader reader = new DmTraceReader(mFilename, false);
- reader.getTraceUnits().setTimeScale(TraceUnits.TimeScale.MilliSeconds);
-
- mContents = new Composite(mParent, SWT.NONE);
-
- Display display = mContents.getDisplay();
- ColorController.assignMethodColors(display, reader.getMethods());
- SelectionController selectionController = new SelectionController();
-
- GridLayout gridLayout = new GridLayout(1, false);
- gridLayout.marginWidth = 0;
- gridLayout.marginHeight = 0;
- gridLayout.horizontalSpacing = 0;
- gridLayout.verticalSpacing = 0;
- mContents.setLayout(gridLayout);
-
- Color darkGray = display.getSystemColor(SWT.COLOR_DARK_GRAY);
-
- // Create a sash form to separate the timeline view (on top)
- // and the profile view (on bottom)
- SashForm sashForm1 = new SashForm(mContents, SWT.VERTICAL);
- sashForm1.setBackground(darkGray);
- sashForm1.SASH_WIDTH = 3;
- GridData data = new GridData(GridData.FILL_BOTH);
- sashForm1.setLayoutData(data);
-
- // Create the timeline view
- new TimeLineView(sashForm1, reader, selectionController);
-
- // Create the profile view
- new ProfileView(sashForm1, reader, selectionController).setMethodHandler(this);
- } catch (IOException e) {
- Label l = new Label(parent, 0);
- l.setText("Failed to read the stack trace.");
-
- Status status = new Status(IStatus.ERROR, TraceviewPlugin.PLUGIN_ID,
- "Failed to read the stack trace.", e);
- TraceviewPlugin.getDefault().getLog().log(status);
- }
-
- mParent.layout();
- }
-
- @Override
- public void setFocus() {
- mParent.setFocus();
- }
-
- // ---- MethodHandler methods
-
- @Override
- public void handleMethod(MethodData method) {
- String methodName = method.getMethodName();
- String className = method.getClassName().replaceAll("/", "."); //$NON-NLS-1$ //$NON-NLS-2$
- String fqmn = className + "." + methodName; //$NON-NLS-1$
-
- JavaSourceRevealer.revealMethod(fqmn, null, -1, null);
- }
-}
diff --git a/eclipse/pom.xml b/eclipse/pom.xml
deleted file mode 100644
index 36e500c28..000000000
--- a/eclipse/pom.xml
+++ /dev/null
@@ -1,168 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- This script builds the monitor product which is composed of a bunch of Eclipse plugins.
-
- To run this script:
- - Have Maven3 in your path
- - $ mvn package -DANDROID_OUT=/path/to/android/out
-
- See http://wiki.eclipse.org/Tycho/Reference_Card#Examplary_parent_POM
- -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <groupId>adt.group</groupId>
- <artifactId>parent</artifactId>
- <version>1.0.0-SNAPSHOT</version>
- <packaging>pom</packaging>
- <name>ADT</name>
-
- <!-- Common properties used in all modules -->
- <properties>
- <tycho-version>0.20.0</tycho-version>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- </properties>
-
- <!--
- The following profiles allow us to change the build environment easily. The first profile uses
- the target platform as present inside the Android tree's out folder, while the other profile
- uses the target platform directly from eclipse.org.
-
- The first profile is automatically activated if the ANDROID_OUT system property is set:
- $ mvn clean install -DANDROID_OUT=/path/to/android/out
- The other profile can be tested out by:
- $ mvn clean install -Pexternal-p2-repositories
- -->
- <profiles>
- <profile>
- <id>mirrored-p2-repositories</id>
- <activation>
- <property>
- <name>ANDROID_OUT</name>
- </property>
- </activation>
- <properties>
- <!-- The target platform should have been created under the Android ANDROID_OUT folder -->
- <target-platform.base.url>file://${ANDROID_OUT}/host/maven/target</target-platform.base.url>
- </properties>
- <repositories>
- <repository>
- <id>kepler</id>
- <url>${target-platform.base.url}/platform</url>
- <layout>p2</layout>
- </repository>
- <repository>
- <id>jdt</id>
- <url>${target-platform.base.url}/jdt</url>
- <layout>p2</layout>
- </repository>
- </repositories>
- </profile>
- <profile>
- <id>external-p2-repositories</id>
- <repositories>
- <repository>
- <id>kepler</id>
- <url>http://download.eclipse.org/releases/kepler</url>
- <layout>p2</layout>
- </repository>
- </repositories>
- </profile>
- </profiles>
-
- <modules>
- <module>plugins/com.android.ide.eclipse.base</module>
- <module>plugins/com.android.ide.eclipse.ddms</module>
- <module>plugins/com.android.ide.eclipse.gldebugger</module>
- <module>plugins/com.android.ide.eclipse.hierarchyviewer</module>
- <module>plugins/com.android.ide.eclipse.monitor</module>
- <module>plugins/com.android.ide.eclipse.traceview</module>
-
- <module>features/com.android.ide.eclipse.ddms</module>
- <module>features/com.android.ide.eclipse.gldebugger</module>
- <module>features/com.android.ide.eclipse.hierarchyviewer</module>
- <module>features/com.android.ide.eclipse.traceview</module>
- <module>features/com.android.ide.eclipse.monitor</module>
-
- <module>artifacts/bundles</module>
- </modules>
-
- <build>
- <!-- Path is relative to each of the build modules defined above. -->
- <directory>../../../../out/host/maven/${project.artifactId}-${project.version}</directory>
-
- <plugins>
- <plugin>
- <groupId>org.eclipse.tycho</groupId>
- <artifactId>target-platform-configuration</artifactId>
- <version>${tycho-version}</version>
- <configuration>
- <environments>
- <environment>
- <os>win32</os>
- <ws>win32</ws>
- <arch>x86</arch>
- </environment>
- <environment>
- <os>win32</os>
- <ws>win32</ws>
- <arch>x86_64</arch>
- </environment>
- <environment>
- <os>linux</os>
- <ws>gtk</ws>
- <arch>x86</arch>
- </environment>
- <environment>
- <os>macosx</os>
- <ws>cocoa</ws>
- <arch>x86_64</arch>
- </environment>
- <environment>
- <os>linux</os>
- <ws>gtk</ws>
- <arch>x86_64</arch>
- </environment>
- </environments>
- </configuration>
- </plugin>
-
- <plugin>
- <groupId>org.eclipse.tycho</groupId>
- <artifactId>tycho-maven-plugin</artifactId>
- <version>${tycho-version}</version>
- <extensions>true</extensions>
- </plugin>
-
- <plugin>
- <groupId>org.eclipse.tycho</groupId>
- <artifactId>tycho-p2-repository-plugin</artifactId>
- <version>${tycho-version}</version>
- <configuration>
- <includeAllDependencies>true</includeAllDependencies>
- </configuration>
- </plugin>
- </plugins>
- <!--
- Don't include META-INF/maven in the jar files, this causes an unnecessary increase in the
- path length as that folder contained the files with the longest paths (one path was 190 chars).
- Windows has a limit of ~260 chars, but removing all the maven info lowers our max path length
- from 190 to about 150.
- -->
- <pluginManagement>
- <plugins>
- <plugin>
- <groupId>org.eclipse.tycho</groupId>
- <artifactId>tycho-packaging-plugin</artifactId>
- <version>${tycho-version}</version>
- <configuration>
- <archive>
- <addMavenDescriptor>false</addMavenDescriptor>
- </archive>
- </configuration>
- </plugin>
- </plugins>
- </pluginManagement>
- </build>
-</project>
diff --git a/eclipse/scripts/_mk_icons.sh b/eclipse/scripts/_mk_icons.sh
deleted file mode 100755
index b3ea35b39..000000000
--- a/eclipse/scripts/_mk_icons.sh
+++ /dev/null
@@ -1,55 +0,0 @@
-#!/bin/bash
-
-function icon() {
- # $1=letter, $2=letter's color (e.g. A red), $3=filename
- ./gen_icon.py ${3}.png 16 white black $2 $1
-}
-
-icon M green manifest
- icon S blue sharedUserId
- icon S red signature
- icon P green package
-
-icon I green instrumentation
- icon F green functionalTest
- icon H green handleProfiling
- icon I green icon
- icon T green targetPackage
-
-icon U blue uses-permission
-icon P red permission
- icon N green name
- icon L blue label
-
-icon A blue application
- icon P red permission
- icon P blue persistent
- icon P green process
- icon T green taskAffinity
- icon T blue theme
- icon P red provider
- icon A green authorities
- icon I green initOrder
- icon M green multiprocess
- icon R green readPermission
- icon W green writePermission
- icon S green syncable
- icon R green receiver
- icon S blue service
- icon A green activity
- icon C blue clearOnBackground
- icon C green configChanges
- icon E green excludeFromRecents
- icon L green launchMode
- icon S green stateNotNeeded
- icon F blue intent-filter
- icon P green priority
- icon A red action
- icon C green category
- icon D green data
- icon M green mimeType
- icon S green scheme
- icon H green host
- icon P green port
- icon P blue path
-
diff --git a/eclipse/scripts/build_adt.sh b/eclipse/scripts/build_adt.sh
deleted file mode 100755
index 7006aabc5..000000000
--- a/eclipse/scripts/build_adt.sh
+++ /dev/null
@@ -1,49 +0,0 @@
-#!/bin/bash
-# Expected arguments:
-# $1 = out_dir
-# $2 = dist_dir
-# $3 = build_number
-
-# exit on error
-set -e
-
-if [ $# -ne 3 ]
-then
- echo "Usage: $0 <out_dir> <dest_dir> <build_number>" > /dev/stderr
- echo "Given arguments: $*" > /dev/stderr
- exit 1
-fi
-
-PROG_DIR=$(dirname "$0")
-
-cd "$PROG_DIR"/../../..
-ANDROID_SRC="$PWD"
-
-OUT="$1"
-DIST="$2"
-BNUM="$3"
-
-echo "ANDROID_SRC=$ANDROID_SRC"
-echo "OUT=$OUT"
-echo "DIST=$DIST"
-echo "BNUM=$BNUM"
-
-# Steps to build Eclipse
-# 1. Generate Maven repository containing all tools
-echo Running gradle to build tools libraries...
-cd "$ANDROID_SRC"/tools
-./gradlew --no-daemon publishLocal
-
-# 2. Copy dependent jars into the libs folder of each plugin
-echo Copying jars to be embedded inside the ADT plugins
-cd "$ANDROID_SRC"
-./tools/gradlew -i -b sdk/eclipse/build.gradle --no-daemon copydeps
-
-# 3. Launch Tycho build
-echo Launching Tycho to build ADT plugins and bundle
-( set -x ; BUILD_NUMBER="$BNUM" ./tools/gradlew -i -b sdk/eclipse/build.gradle --no-daemon buildEclipse)
-
-echo Copying ADT plugins and bundle into destination folder
-cd "$ANDROID_SRC"
-cp -rv out/host/maven/bundles-*/products/*.zip "$DIST"/
-cp -rv out/host/maven/p2repo-*/p2repo-*.zip "$DIST"/p2repo-$BNUM.zip
diff --git a/eclipse/scripts/build_update_site.sh b/eclipse/scripts/build_update_site.sh
deleted file mode 100755
index 599875682..000000000
--- a/eclipse/scripts/build_update_site.sh
+++ /dev/null
@@ -1,34 +0,0 @@
-#!/bin/bash
-# Entry point to build the Eclipse plugins for local deployment.
-#
-# Input parameters:
-# $1: Optional build number. If present, will be appended to the date qualifier.
-# The build number cannot contain spaces *nor* periods (dashes are ok.)
-# -i: Optional, if present, the Google internal update site will be built. Otherwise,
-# the external site will be built
-#
-# Workflow:
-# - calls buildserver with /home/$USER/www/no_crawl and -z
-# to build and create the update size but do not zip it in the destination directory.
-
-set -e # Fail this script as soon as a command fails -- fail early, fail fast
-
-D=`dirname $0`
-BUILD_NUMBER=""
-INTERNAL_BUILD=""
-# parse input parameters
-while [ $# -gt 0 ]; do
- if [ "$1" == "-i" ]; then
- INTERNAL_BUILD="-i"
- elif [ "$1" != "" ]; then
- BUILD_NUMBER="$1"
- fi
- shift
-done
-
-DEST_DIR="$HOME"
-[ -z "$DEST_DIR" ] && [ -n "$USER" ] && DEST_DIR="/home/$USER"
-[ -z "$DEST_DIR" ] && DEST_DIR="~"
-DEST_DIR="$DEST_DIR/www/no_crawl"
-
-"$D/build_server.sh" "$DEST_DIR" "$BUILD_NUMBER" -z "$INTERNAL_BUILD"
diff --git a/eclipse/scripts/collect_sources_for_sdk.py b/eclipse/scripts/collect_sources_for_sdk.py
deleted file mode 100755
index b95ae62b8..000000000
--- a/eclipse/scripts/collect_sources_for_sdk.py
+++ /dev/null
@@ -1,180 +0,0 @@
-#!/usr/bin/python
-#
-# Copyright (C) 2009 The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-#
-"""
-Description:
- This script collects all framework Java sources from the current android
- source code and places them in a source folder suitable for the eclipse ADT
- plugin.
-
-See usage() below.
-
-Copyright (C) 2009 The Android Open Source Project
-Licensed under the Apache License, Version 2.0 (the "License").
-"""
-
-import re
-import os
-import sys
-import getopt
-import shutil
-
-_RE_PKG = re.compile("^\s*package\s+([^\s;]+)\s*;.*")
-
-# Holds cmd-line arguments
-class Params(object):
- def __init__(self):
- self.DRY = False
- self.DIR = "frameworks libcore"
- self.SRC = None
- self.DST = None
- self.CNT_USED = 0
- self.CNT_NOPKG = 0
-
-
-# Prints a usage summary
-def usage(error=None):
- print """
- Description:
- This script collects all framework Java sources from the current android
- source code and places them in a source folder suitable for the eclipse ADT
- plugin.
-
- Usage:
- %s [-n] <android-git-repo root> <sdk/platforms/xyz/sources>
-
- The source and destination directories must already exist.
- Use -n for a dry-run.
-
-""" % sys.argv[0]
-
- if error:
- print >>sys.stderr, "Error:", error
-
-
-# Parse command line args, returns a Params instance or sys.exit(2) on error
-# after printing the error and the usage.
-def parseArgs(argv):
- p = Params()
- error = None
-
- try:
- opts, args = getopt.getopt(argv[1:],
- "ns:",
- [ "--dry", "--sourcedir=" ])
- except getopt.GetoptError, e:
- error = str(e)
-
- if error is None:
- for o, a in opts:
- if o in [ "-n", "--dry" ]:
- p.DRY = True
- elif o in [ "-s", "--sourcedir" ]:
- p.DIR = a
-
- if len(args) != 2:
- error = "Missing arguments: <source> <dest>"
- else:
- p.SRC = args[0]
- p.DST = args[1]
-
- if not os.path.isdir(p.SRC):
- error = "%s is not a directory" % p.SRC
- elif not os.path.isdir(p.DST):
- error = "%s is not a directory" % p.DST
-
- if error:
- usage(error)
- sys.exit(2)
-
- return p
-
-
-# Recursively parses the given directory and process java files found
-def parseSrcDir(p, srcdir):
- if not os.path.exists(srcdir):
- print >>sys.stderr, "Error: Skipping unknown directory", srcdir
- return
-
- for f in os.listdir(srcdir):
- fp = os.path.join(srcdir, f)
- if f.endswith(".java") and os.path.isfile(fp):
- pkg = checkJavaFile(fp)
- if pkg:
- pkg = pkg.replace(".", os.path.sep) # e.g. android.view => android/view
- copy(p, fp, f, pkg)
- p.CNT_USED += 1 # one more copied
- else:
- p.CNT_NOPKG += 1 # this java file lacked a package declaration
- elif os.path.isdir(fp):
- parseSrcDir(p, fp)
-
-
-# Check a java file to find its package declaration, if any
-def checkJavaFile(path):
- print "Process", path
-
- try:
- f = None
- try:
- f = file(path)
- for l in f.readlines():
- m = _RE_PKG.match(l)
- if m:
- return m.group(1)
- finally:
- if f: f.close()
- except Exception:
- pass
-
- return None
-
-
-# Create destination directory based on package name then copy the
-# source file in there
-def copy(p, fp, f, pkg):
- dstdir = os.path.join(p.DST, pkg)
- _mkdir(p, dstdir)
- _cp(p, fp, os.path.join(dstdir, f))
-
-
-def _mkdir(p, dir):
- if not os.path.isdir(dir):
- if p.DRY:
- print "mkdir", dir
- else:
- os.makedirs(dir)
-
-
-def _cp(p, src, dst):
- if p.DRY:
- print "cp", src, dst
- else:
- shutil.copyfile(src, dst)
-
-
-def main():
- p = parseArgs(sys.argv)
- for d in p.DIR.split():
- if d:
- parseSrcDir(p, os.path.join(p.SRC, d))
- print "%d java files copied" % p.CNT_USED
- if p.CNT_NOPKG: print "%d java files ignored (no package)" % p.CNT_NOPKG
- if p.DRY: print "This was in *DRY* mode. No copies done."
-
-
-if __name__ == "__main__":
- main()
diff --git a/eclipse/scripts/gen_icon.py b/eclipse/scripts/gen_icon.py
deleted file mode 100755
index f6274e16e..000000000
--- a/eclipse/scripts/gen_icon.py
+++ /dev/null
@@ -1,71 +0,0 @@
-#!/usr/bin/python
-
-import sys
-import StringIO
-try:
- import Image, ImageDraw, ImageFont
-except ImportError, e:
- print str(e)
- print "Are you missing the Python Imaging Library? (apt-get install python-imaging)"
- sys.exit(1)
-
-FONT_PATH = "/usr/share/fonts/truetype/msttcorefonts/arial.ttf"
-
-class Args(object):
- def __init__(self, dest_name, size, circle_color, border_color,
- letter_color, letter):
- self.dest_name = dest_name
- self.size = size
- self.circle_color = circle_color
- self.border_color = border_color
- self.letter_color = letter_color
- self.letter = letter
-
-def main(args):
- data = process_args(args)
- if data:
- createImage(data)
-
-def process_args(args):
- if not args or len(args) != 6:
- usage()
- return Args(*args)
-
-def usage():
- print """Usage: %s <file_name> <size> <circle-color> <border-color> <letter-color> <letter>""" % sys.argv[0]
- sys.exit(1)
-
-def createImage(data):
- zoom = 4
- rmin = -zoom/2
- rmax = zoom/2
- if zoom > 1:
- r = range(-zoom/2, zoom/2+1)
- else:
- r = [ 0 ]
- sz = int(data.size)
- sz4 = sz * zoom
-
- img = Image.new("RGBA", (sz4, sz4), (255,255,255,0))
- draw = ImageDraw.Draw(img)
-
- draw.ellipse((0, 0, sz4-zoom, sz4-zoom),
- fill=data.circle_color, outline=None)
- for i in r:
- draw.ellipse((i, i, sz4-i-zoom, sz4-i-zoom),
- fill=None, outline=data.border_color)
-
- font = ImageFont.truetype(FONT_PATH, int(sz4 * .75))
- tsx, tsy = draw.textsize(data.letter, font=font)
-
- ptx = (sz4 - tsx) / 2
- pty = (sz4 - tsy) / 2
- for i in r:
- draw.text((ptx + i, pty), data.letter, font=font, fill=data.letter_color)
-
- img = img.resize((sz, sz), Image.BICUBIC)
- img.save(data.dest_name, "PNG")
- print "Saved", data.dest_name
-
-if __name__ == "__main__":
- main(sys.argv[1:])
diff --git a/eclipse/scripts/update_version.sh b/eclipse/scripts/update_version.sh
deleted file mode 100755
index 228be97a9..000000000
--- a/eclipse/scripts/update_version.sh
+++ /dev/null
@@ -1,80 +0,0 @@
-#!/bin/bash
-
-OLD="$1"
-NEW="$2"
-
-# sanity check in input args
-if [ -z "$OLD" ] || [ -z "$NEW" ]; then
- cat <<EOF
-Usage: $0 <old> <new>
-Changes the ADT plugin revision number.
-Example:
- cd sdk/eclipse
- scripts/update_version.sh 0.1.2 0.2.3
-EOF
- exit 1
-fi
-
-# sanity check on current dir
-if [ `basename "$PWD"` != "eclipse" ]; then
- echo "Please run this from sdk/eclipse."
- exit 1
-fi
-
-# sanity check the new version number
-if [[ "$NEW" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
- echo "## Version $NEW: seems valid."
-else
- echo "## Version $NEW: does not conform to major.mino.micro format."
- exit 1
-fi
-
-function replace() {
- if [[ -f "$1" ]]; then
- echo "### Change $SED_OLD => $SED_NEW in $1"
- if [[ $(uname) == "Linux" ]]; then
- sed -i "s/$SED_OLD/$SED_NEW/g" "$1"
- else
- # sed on Mac doesn't handle -i the same way as on Linux
- sed -i "" "s/$SED_OLD/$SED_NEW/g" "$1"
- fi
- fi
-}
-
-# ---1--- Change Eclipse's qualified version numbers
-# quote dots for regexps
-SED_OLD="${OLD//./\.}\.qualifier"
-SED_NEW="${NEW//./\.}\.qualifier"
-
-for i in $(grep -rl "$OLD" * | grep -E "\.xml$|\.MF$|\.product$"); do
- if [[ -f "$i" && $(basename "$i") != "build.xml" ]]; then
- replace "$i"
- fi
-done
-
-# ---2--- Change unqualified version numbers in specific files
-SED_OLD="${OLD//./\.}"
-SED_NEW="${NEW//./\.}"
-for i in artifacts/*/pom.xml \
- monitor/build.gradle \
- plugins/com.android.ide.eclipse.adt.package/ide.product \
- plugins/com.android.ide.eclipse.monitor/monitor.product \
- plugins/com.android.ide.eclipse.monitor/plugin.properties \
- plugins/com.android.ide.eclipse.*/pom.xml \
- features/com.android.ide.eclipse.*/pom.xml \
- features/com.android.ide.eclipse.adt.package/feature.xml ; do
- if grep -qs "$OLD" "$i"; then
- replace "$i"
- fi
-done
-
-# do another grep for older version without the qualifier. We don't
-# want to replace those automatically as it could be something else.
-# Printing out occurence helps find ones to update manually, but exclude
-# some known useless files.
-echo
-echo "#### ----------------"
-echo "#### Remaining instances of $OLD"
-echo
-grep -r "$OLD" * | grep -v -E "/build.xml:|/javaCompiler\.\.\.args:"
-
diff --git a/eclipse/settings.xml b/eclipse/settings.xml
deleted file mode 100644
index e5e53b2c9..000000000
--- a/eclipse/settings.xml
+++ /dev/null
@@ -1,8 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- Run as: mvn -s /path/to/settings.xml -->
-<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
- <localRepository>../../prebuilts/eclipse/mavenplugins/tycho/tycho-dependencies-m2repo/</localRepository>
- <offline>true</offline>
-</settings>
diff --git a/eclipse/sites/external/.gitignore b/eclipse/sites/external/.gitignore
deleted file mode 100644
index ccfee1d0a..000000000
--- a/eclipse/sites/external/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-*.jar
-*/*.jar \ No newline at end of file
diff --git a/eclipse/sites/external/.project b/eclipse/sites/external/.project
deleted file mode 100644
index 3a6f8899a..000000000
--- a/eclipse/sites/external/.project
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>site-external</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.pde.UpdateSiteBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.UpdateSiteNature</nature>
- </natures>
-</projectDescription>
diff --git a/eclipse/sites/external/index.html b/eclipse/sites/external/index.html
deleted file mode 100644
index 784be4b84..000000000
--- a/eclipse/sites/external/index.html
+++ /dev/null
@@ -1,60 +0,0 @@
-<html>
-<head>
-<title>Android Development Toolkit update site.</title>
-<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
-<style>@import url("web/site.css");</style>
-<script type="text/javascript">
- var returnval = 0;
- var stylesheet, xmlFile, cache, doc;
- function init(){
- // NSCP 7.1+ / Mozilla 1.4.1+ / Safari
- // Use the standard DOM Level 2 technique, if it is supported
- if (document.implementation && document.implementation.createDocument) {
- xmlFile = document.implementation.createDocument("", "", null);
- stylesheet = document.implementation.createDocument("", "", null);
- if (xmlFile.load){
- xmlFile.load("site.xml");
- stylesheet.load("web/site.xsl");
- } else {
- alert("Document could not be loaded by browser.");
- }
- xmlFile.addEventListener("load", transform, false);
- stylesheet.addEventListener("load", transform, false);
- }
- //IE 6.0+ solution
- else if (window.ActiveXObject) {
- xmlFile = new ActiveXObject("msxml2.DOMDocument.3.0");
- xmlFile.async = false;
- xmlFile.load("site.xml");
- stylesheet = new ActiveXObject("msxml2.FreeThreadedDOMDocument.3.0");
- stylesheet.async = false;
- stylesheet.load("web/site.xsl");
- cache = new ActiveXObject("msxml2.XSLTemplate.3.0");
- cache.stylesheet = stylesheet;
- transformData();
- }
- }
- // separate transformation function for IE 6.0+
- function transformData(){
- var processor = cache.createProcessor();
- processor.input = xmlFile;
- processor.transform();
- data.innerHTML = processor.output;
- }
- // separate transformation function for NSCP 7.1+ and Mozilla 1.4.1+
- function transform(){
- returnval+=1;
- if (returnval==2){
- var processor = new XSLTProcessor();
- processor.importStylesheet(stylesheet);
- doc = processor.transformToDocument(xmlFile);
- document.getElementById("data").innerHTML = doc.documentElement.innerHTML;
- }
- }
-</script>
-</head>
-<body onload="init();">
-<!--[insert static HTML here]-->
-<div id="data"><!-- this is where the transformed data goes --></div>
-</body>
-</html>
diff --git a/eclipse/sites/external/site.xml b/eclipse/sites/external/site.xml
deleted file mode 100644
index f16898caf..000000000
--- a/eclipse/sites/external/site.xml
+++ /dev/null
@@ -1,34 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<site>
- <description url="https://dl-ssl.google.com/android/eclipse/">
- Update Site for Android Development Toolkit
- </description>
- <feature url="features/com.android.ide.eclipse.adt_24.3.3.qualifier.jar" id="com.android.ide.eclipse.adt" version="24.3.3.qualifier">
- <category name="developer"/>
- </feature>
- <feature url="features/com.android.ide.eclipse.ddms_24.3.3.qualifier.jar" id="com.android.ide.eclipse.ddms" version="24.3.3.qualifier">
- <category name="developer"/>
- </feature>
- <feature url="features/com.android.ide.eclipse.hierarchyviewer_24.3.3.qualifier.jar" id="com.android.ide.eclipse.hierarchyviewer" version="24.3.3.qualifier">
- <category name="developer"/>
- </feature>
- <feature url="features/com.android.ide.eclipse.traceview_24.3.3.qualifier.jar" id="com.android.ide.eclipse.traceview" version="24.3.3.qualifier">
- <category name="developer"/>
- </feature>
- <feature url="features/com.android.ide.eclipse.gldebugger_24.3.3.qualifier.jar" id="com.android.ide.eclipse.gldebugger" version="24.3.3.qualifier">
- <category name="developer"/>
- </feature>
- <feature url="features/com.android.ide.eclipse.ndk_24.3.3.qualifier.jar" id="com.android.ide.eclipse.ndk" version="24.3.3.qualifier">
- <category name="ndk"/>
- </feature>
- <category-def name="developer" label="Developer Tools">
- <description>
- Features that add Android support to Eclipse for application developers.
- </description>
- </category-def>
- <category-def name="ndk" label="NDK Plugins">
- <description>
- Support for NDK build and debug in Eclipse.
- </description>
- </category-def>
-</site>
diff --git a/eclipse/sites/external/web/site.css b/eclipse/sites/external/web/site.css
deleted file mode 100644
index 62c6f9ffa..000000000
--- a/eclipse/sites/external/web/site.css
+++ /dev/null
@@ -1,12 +0,0 @@
-<STYLE type="text/css">
-td.spacer {padding-bottom: 10px; padding-top: 10px;}
-.title { font-family: sans-serif; color: #99AACC;}
-.bodyText { font-family: sans-serif; font-size: 9pt; color:#000000; }
-.sub-header { font-family: sans-serif; font-style: normal; font-weight: bold; font-size: 9pt; color: white;}
-.log-text {font-family: sans-serif; font-style: normal; font-weight: lighter; font-size: 8pt; color:black;}
-.big-header { font-family: sans-serif; font-style: normal; font-weight: bold; font-size: 9pt; color: white; border-top:10px solid white;}
-.light-row {background:#FFFFFF}
-.dark-row {background:#EEEEFF}
-.header {background:#99AADD}
-#indent {word-wrap : break-word;width :300px;text-indent:10px;}
-</STYLE>
diff --git a/eclipse/sites/external/web/site.xsl b/eclipse/sites/external/web/site.xsl
deleted file mode 100644
index a94157d82..000000000
--- a/eclipse/sites/external/web/site.xsl
+++ /dev/null
@@ -1,214 +0,0 @@
-<xsl:stylesheet version = '1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:msxsl="urn:schemas-microsoft-com:xslt">
-<xsl:output method="html" encoding="UTF-8"/>
-<xsl:key name="cat" match="category" use="@name"/>
-<xsl:template match="/">
-<xsl:for-each select="site">
- <html>
- <head>
- <title>update-site</title>
- <style>@import url("web/site.css");</style>
- </head>
- <body>
- <h1 class="title">update-site</h1>
- <p class="bodyText"><xsl:value-of select="description"/></p>
- <table width="100%" border="0" cellspacing="1" cellpadding="2">
- <xsl:for-each select="category-def">
- <xsl:sort select="@label" order="ascending" case-order="upper-first"/>
- <xsl:sort select="@name" order="ascending" case-order="upper-first"/>
- <xsl:if test="count(key('cat',@name)) != 0">
- <tr class="header">
- <td class="sub-header" width="30%">
- <xsl:value-of select="@name"/>
- </td>
- <td class="sub-header" width="70%">
- <xsl:value-of select="@label"/>
- </td>
- </tr>
- <xsl:for-each select="key('cat',@name)">
- <xsl:sort select="ancestor::feature//@version" order="ascending"/>
- <xsl:sort select="ancestor::feature//@id" order="ascending" case-order="upper-first"/>
- <tr>
- <xsl:choose>
- <xsl:when test="(position() mod 2 = 1)">
- <xsl:attribute name="class">dark-row</xsl:attribute>
- </xsl:when>
- <xsl:otherwise>
- <xsl:attribute name="class">light-row</xsl:attribute>
- </xsl:otherwise>
- </xsl:choose>
- <td class="log-text" id="indent">
- <xsl:choose>
- <xsl:when test="ancestor::feature//@label">
- <a href="{ancestor::feature//@url}"><xsl:value-of select="ancestor::feature//@label"/></a>
- <br/>
- <div id="indent">
- (<xsl:value-of select="ancestor::feature//@id"/> - <xsl:value-of select="ancestor::feature//@version"/>)
- </div>
- </xsl:when>
- <xsl:otherwise>
- <a href="{ancestor::feature//@url}"><xsl:value-of select="ancestor::feature//@id"/> - <xsl:value-of select="ancestor::feature//@version"/></a>
- </xsl:otherwise>
- </xsl:choose>
- <br />
- </td>
- <td>
- <table>
- <xsl:if test="ancestor::feature//@os">
- <tr><td class="log-text" id="indent">Operating Systems:</td>
- <td class="log-text" id="indent"><xsl:value-of select="ancestor::feature//@os"/></td>
- </tr>
- </xsl:if>
- <xsl:if test="ancestor::feature//@ws">
- <tr><td class="log-text" id="indent">Windows Systems:</td>
- <td class="log-text" id="indent"><xsl:value-of select="ancestor::feature//@ws"/></td>
- </tr>
- </xsl:if>
- <xsl:if test="ancestor::feature//@nl">
- <tr><td class="log-text" id="indent">Languages:</td>
- <td class="log-text" id="indent"><xsl:value-of select="ancestor::feature//@nl"/></td>
- </tr>
- </xsl:if>
- <xsl:if test="ancestor::feature//@arch">
- <tr><td class="log-text" id="indent">Architecture:</td>
- <td class="log-text" id="indent"><xsl:value-of select="ancestor::feature//@arch"/></td>
- </tr>
- </xsl:if>
- </table>
- </td>
- </tr>
- </xsl:for-each>
- <tr><td class="spacer"><br/></td><td class="spacer"><br/></td></tr>
- </xsl:if>
- </xsl:for-each>
- <xsl:if test="count(feature) &gt; count(feature/category)">
- <tr class="header">
- <td class="sub-header" colspan="2">
- Uncategorized
- </td>
- </tr>
- </xsl:if>
- <xsl:choose>
- <xsl:when test="function-available('msxsl:node-set')">
- <xsl:variable name="rtf-nodes">
- <xsl:for-each select="feature[not(category)]">
- <xsl:sort select="@id" order="ascending" case-order="upper-first"/>
- <xsl:sort select="@version" order="ascending" />
- <xsl:value-of select="."/>
- <xsl:copy-of select="." />
- </xsl:for-each>
- </xsl:variable>
- <xsl:variable name="myNodeSet" select="msxsl:node-set($rtf-nodes)/*"/>
- <xsl:for-each select="$myNodeSet">
- <tr>
- <xsl:choose>
- <xsl:when test="position() mod 2 = 1">
- <xsl:attribute name="class">dark-row</xsl:attribute>
- </xsl:when>
- <xsl:otherwise>
- <xsl:attribute name="class">light-row</xsl:attribute>
- </xsl:otherwise>
- </xsl:choose>
- <td class="log-text" id="indent">
- <xsl:choose>
- <xsl:when test="@label">
- <a href="{@url}"><xsl:value-of select="@label"/></a>
- <br />
- <div id="indent">
- (<xsl:value-of select="@id"/> - <xsl:value-of select="@version"/>)
- </div>
- </xsl:when>
- <xsl:otherwise>
- <a href="{@url}"><xsl:value-of select="@id"/> - <xsl:value-of select="@version"/></a>
- </xsl:otherwise>
- </xsl:choose>
- <br /><br />
- </td>
- <td>
- <table>
- <xsl:if test="@os">
- <tr><td class="log-text" id="indent">Operating Systems:</td>
- <td class="log-text" id="indent"><xsl:value-of select="@os"/></td>
- </tr>
- </xsl:if>
- <xsl:if test="@ws">
- <tr><td class="log-text" id="indent">Windows Systems:</td>
- <td class="log-text" id="indent"><xsl:value-of select="@ws"/></td>
- </tr>
- </xsl:if>
- <xsl:if test="@nl">
- <tr><td class="log-text" id="indent">Languages:</td>
- <td class="log-text" id="indent"><xsl:value-of select="@nl"/></td>
- </tr>
- </xsl:if>
- <xsl:if test="@arch">
- <tr><td class="log-text" id="indent">Architecture:</td>
- <td class="log-text" id="indent"><xsl:value-of select="@arch"/></td>
- </tr>
- </xsl:if>
- </table>
- </td>
- </tr>
- </xsl:for-each>
- </xsl:when>
- <xsl:otherwise>
- <xsl:for-each select="feature[not(category)]">
- <xsl:sort select="@id" order="ascending" case-order="upper-first"/>
- <xsl:sort select="@version" order="ascending" />
- <tr>
- <xsl:choose>
- <xsl:when test="count(preceding-sibling::feature[not(category)]) mod 2 = 1">
- <xsl:attribute name="class">dark-row</xsl:attribute>
- </xsl:when>
- <xsl:otherwise>
- <xsl:attribute name="class">light-row</xsl:attribute>
- </xsl:otherwise>
- </xsl:choose>
- <td class="log-text" id="indent">
- <xsl:choose>
- <xsl:when test="@label">
- <a href="{@url}"><xsl:value-of select="@label"/></a>
- <br />
- <div id="indent">
- (<xsl:value-of select="@id"/> - <xsl:value-of select="@version"/>)
- </div>
- </xsl:when>
- <xsl:otherwise>
- <a href="{@url}"><xsl:value-of select="@id"/> - <xsl:value-of select="@version"/></a>
- </xsl:otherwise>
- </xsl:choose>
- <br /><br />
- </td>
- <td>
- <table>
- <xsl:if test="@os">
- <tr><td class="log-text" id="indent">Operating Systems:</td>
- <td class="log-text" id="indent"><xsl:value-of select="@os"/></td>
- </tr>
- </xsl:if>
- <xsl:if test="@ws">
- <tr><td class="log-text" id="indent">Windows Systems:</td>
- <td class="log-text" id="indent"><xsl:value-of select="@ws"/></td>
- </tr>
- </xsl:if>
- <xsl:if test="@nl">
- <tr><td class="log-text" id="indent">Languages:</td>
- <td class="log-text" id="indent"><xsl:value-of select="@nl"/></td>
- </tr>
- </xsl:if>
- <xsl:if test="@arch">
- <tr><td class="log-text" id="indent">Architecture:</td>
- <td class="log-text" id="indent"><xsl:value-of select="@arch"/></td>
- </tr>
- </xsl:if>
- </table>
- </td>
- </tr>
- </xsl:for-each>
- </xsl:otherwise>
- </xsl:choose>
- </table>
- </body>
- </html>
-</xsl:for-each>
-</xsl:template>
-</xsl:stylesheet>
diff --git a/eclipse/sites/internal/.gitignore b/eclipse/sites/internal/.gitignore
deleted file mode 100644
index ccfee1d0a..000000000
--- a/eclipse/sites/internal/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-*.jar
-*/*.jar \ No newline at end of file
diff --git a/eclipse/sites/internal/.project b/eclipse/sites/internal/.project
deleted file mode 100644
index d1ef73bb4..000000000
--- a/eclipse/sites/internal/.project
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>site-internal</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.pde.UpdateSiteBuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.pde.UpdateSiteNature</nature>
- </natures>
-</projectDescription>
diff --git a/eclipse/sites/internal/index.html b/eclipse/sites/internal/index.html
deleted file mode 100644
index 784be4b84..000000000
--- a/eclipse/sites/internal/index.html
+++ /dev/null
@@ -1,60 +0,0 @@
-<html>
-<head>
-<title>Android Development Toolkit update site.</title>
-<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
-<style>@import url("web/site.css");</style>
-<script type="text/javascript">
- var returnval = 0;
- var stylesheet, xmlFile, cache, doc;
- function init(){
- // NSCP 7.1+ / Mozilla 1.4.1+ / Safari
- // Use the standard DOM Level 2 technique, if it is supported
- if (document.implementation && document.implementation.createDocument) {
- xmlFile = document.implementation.createDocument("", "", null);
- stylesheet = document.implementation.createDocument("", "", null);
- if (xmlFile.load){
- xmlFile.load("site.xml");
- stylesheet.load("web/site.xsl");
- } else {
- alert("Document could not be loaded by browser.");
- }
- xmlFile.addEventListener("load", transform, false);
- stylesheet.addEventListener("load", transform, false);
- }
- //IE 6.0+ solution
- else if (window.ActiveXObject) {
- xmlFile = new ActiveXObject("msxml2.DOMDocument.3.0");
- xmlFile.async = false;
- xmlFile.load("site.xml");
- stylesheet = new ActiveXObject("msxml2.FreeThreadedDOMDocument.3.0");
- stylesheet.async = false;
- stylesheet.load("web/site.xsl");
- cache = new ActiveXObject("msxml2.XSLTemplate.3.0");
- cache.stylesheet = stylesheet;
- transformData();
- }
- }
- // separate transformation function for IE 6.0+
- function transformData(){
- var processor = cache.createProcessor();
- processor.input = xmlFile;
- processor.transform();
- data.innerHTML = processor.output;
- }
- // separate transformation function for NSCP 7.1+ and Mozilla 1.4.1+
- function transform(){
- returnval+=1;
- if (returnval==2){
- var processor = new XSLTProcessor();
- processor.importStylesheet(stylesheet);
- doc = processor.transformToDocument(xmlFile);
- document.getElementById("data").innerHTML = doc.documentElement.innerHTML;
- }
- }
-</script>
-</head>
-<body onload="init();">
-<!--[insert static HTML here]-->
-<div id="data"><!-- this is where the transformed data goes --></div>
-</body>
-</html>
diff --git a/eclipse/sites/internal/site.xml b/eclipse/sites/internal/site.xml
deleted file mode 100644
index d5cb3fd4b..000000000
--- a/eclipse/sites/internal/site.xml
+++ /dev/null
@@ -1,50 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<site>
- <description url="https://android.corp.google.com/adt/">
- Update Site for Android Development Toolkit
- </description>
- <feature url="features/com.android.ide.eclipse.adt_24.3.3.qualifier.jar" id="com.android.ide.eclipse.adt" version="24.3.3.qualifier">
- <category name="developer"/>
- </feature>
- <feature url="features/com.android.ide.eclipse.ddms_24.3.3.qualifier.jar" id="com.android.ide.eclipse.ddms" version="24.3.3.qualifier">
- <category name="developer"/>
- <category name="platform"/>
- </feature>
- <feature url="features/com.android.ide.eclipse.hierarchyviewer_24.3.3.qualifier.jar" id="com.android.ide.eclipse.hierarchyviewer" version="24.3.3.qualifier">
- <category name="developer"/>
- <category name="platform"/>
- </feature>
- <feature url="features/com.android.ide.eclipse.tests_24.3.3.qualifier.jar" id="com.android.ide.eclipse.tests" version="24.3.3.qualifier">
- <category name="test"/>
- </feature>
- <feature url="features/com.android.ide.eclipse.pdt_24.3.3.qualifier.jar" id="com.android.ide.eclipse.pdt" version="24.3.3.qualifier">
- <category name="platform"/>
- </feature>
- <feature url="features/com.android.ide.eclipse.traceview_24.3.3.qualifier.jar" id="com.android.ide.eclipse.traceview" version="24.3.3.qualifier">
- <category name="developer"/>
- <category name="platform"/>
- </feature>
- <feature url="features/com.android.ide.eclipse.gldebugger_24.3.3.qualifier.jar" id="com.android.ide.eclipse.gldebugger" version="24.3.3.qualifier">
- <category name="developer"/>
- <category name="platform"/>
- </feature>
- <feature url="features/com.android.ide.eclipse.ndk_24.3.3.qualifier.jar" id="com.android.ide.eclipse.ndk" version="24.3.3.qualifier">
- <category name="developer"/>
- <category name="platform"/>
- </feature>
- <category-def name="developer" label="Application Developer Tools">
- <description>
- Features that add Android support to Eclipse for application developers.
- </description>
- </category-def>
- <category-def name="test" label="Plugin Developer Tests">
- <description>
- Tests for the other Android plugins
- </description>
- </category-def>
- <category-def name="platform" label="Platform Tools">
- <description>
- Features that add Android support to Eclipse for platform developers.
- </description>
- </category-def>
-</site>
diff --git a/eclipse/sites/internal/web/site.css b/eclipse/sites/internal/web/site.css
deleted file mode 100644
index 62c6f9ffa..000000000
--- a/eclipse/sites/internal/web/site.css
+++ /dev/null
@@ -1,12 +0,0 @@
-<STYLE type="text/css">
-td.spacer {padding-bottom: 10px; padding-top: 10px;}
-.title { font-family: sans-serif; color: #99AACC;}
-.bodyText { font-family: sans-serif; font-size: 9pt; color:#000000; }
-.sub-header { font-family: sans-serif; font-style: normal; font-weight: bold; font-size: 9pt; color: white;}
-.log-text {font-family: sans-serif; font-style: normal; font-weight: lighter; font-size: 8pt; color:black;}
-.big-header { font-family: sans-serif; font-style: normal; font-weight: bold; font-size: 9pt; color: white; border-top:10px solid white;}
-.light-row {background:#FFFFFF}
-.dark-row {background:#EEEEFF}
-.header {background:#99AADD}
-#indent {word-wrap : break-word;width :300px;text-indent:10px;}
-</STYLE>
diff --git a/eclipse/sites/internal/web/site.xsl b/eclipse/sites/internal/web/site.xsl
deleted file mode 100644
index a94157d82..000000000
--- a/eclipse/sites/internal/web/site.xsl
+++ /dev/null
@@ -1,214 +0,0 @@
-<xsl:stylesheet version = '1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:msxsl="urn:schemas-microsoft-com:xslt">
-<xsl:output method="html" encoding="UTF-8"/>
-<xsl:key name="cat" match="category" use="@name"/>
-<xsl:template match="/">
-<xsl:for-each select="site">
- <html>
- <head>
- <title>update-site</title>
- <style>@import url("web/site.css");</style>
- </head>
- <body>
- <h1 class="title">update-site</h1>
- <p class="bodyText"><xsl:value-of select="description"/></p>
- <table width="100%" border="0" cellspacing="1" cellpadding="2">
- <xsl:for-each select="category-def">
- <xsl:sort select="@label" order="ascending" case-order="upper-first"/>
- <xsl:sort select="@name" order="ascending" case-order="upper-first"/>
- <xsl:if test="count(key('cat',@name)) != 0">
- <tr class="header">
- <td class="sub-header" width="30%">
- <xsl:value-of select="@name"/>
- </td>
- <td class="sub-header" width="70%">
- <xsl:value-of select="@label"/>
- </td>
- </tr>
- <xsl:for-each select="key('cat',@name)">
- <xsl:sort select="ancestor::feature//@version" order="ascending"/>
- <xsl:sort select="ancestor::feature//@id" order="ascending" case-order="upper-first"/>
- <tr>
- <xsl:choose>
- <xsl:when test="(position() mod 2 = 1)">
- <xsl:attribute name="class">dark-row</xsl:attribute>
- </xsl:when>
- <xsl:otherwise>
- <xsl:attribute name="class">light-row</xsl:attribute>
- </xsl:otherwise>
- </xsl:choose>
- <td class="log-text" id="indent">
- <xsl:choose>
- <xsl:when test="ancestor::feature//@label">
- <a href="{ancestor::feature//@url}"><xsl:value-of select="ancestor::feature//@label"/></a>
- <br/>
- <div id="indent">
- (<xsl:value-of select="ancestor::feature//@id"/> - <xsl:value-of select="ancestor::feature//@version"/>)
- </div>
- </xsl:when>
- <xsl:otherwise>
- <a href="{ancestor::feature//@url}"><xsl:value-of select="ancestor::feature//@id"/> - <xsl:value-of select="ancestor::feature//@version"/></a>
- </xsl:otherwise>
- </xsl:choose>
- <br />
- </td>
- <td>
- <table>
- <xsl:if test="ancestor::feature//@os">
- <tr><td class="log-text" id="indent">Operating Systems:</td>
- <td class="log-text" id="indent"><xsl:value-of select="ancestor::feature//@os"/></td>
- </tr>
- </xsl:if>
- <xsl:if test="ancestor::feature//@ws">
- <tr><td class="log-text" id="indent">Windows Systems:</td>
- <td class="log-text" id="indent"><xsl:value-of select="ancestor::feature//@ws"/></td>
- </tr>
- </xsl:if>
- <xsl:if test="ancestor::feature//@nl">
- <tr><td class="log-text" id="indent">Languages:</td>
- <td class="log-text" id="indent"><xsl:value-of select="ancestor::feature//@nl"/></td>
- </tr>
- </xsl:if>
- <xsl:if test="ancestor::feature//@arch">
- <tr><td class="log-text" id="indent">Architecture:</td>
- <td class="log-text" id="indent"><xsl:value-of select="ancestor::feature//@arch"/></td>
- </tr>
- </xsl:if>
- </table>
- </td>
- </tr>
- </xsl:for-each>
- <tr><td class="spacer"><br/></td><td class="spacer"><br/></td></tr>
- </xsl:if>
- </xsl:for-each>
- <xsl:if test="count(feature) &gt; count(feature/category)">
- <tr class="header">
- <td class="sub-header" colspan="2">
- Uncategorized
- </td>
- </tr>
- </xsl:if>
- <xsl:choose>
- <xsl:when test="function-available('msxsl:node-set')">
- <xsl:variable name="rtf-nodes">
- <xsl:for-each select="feature[not(category)]">
- <xsl:sort select="@id" order="ascending" case-order="upper-first"/>
- <xsl:sort select="@version" order="ascending" />
- <xsl:value-of select="."/>
- <xsl:copy-of select="." />
- </xsl:for-each>
- </xsl:variable>
- <xsl:variable name="myNodeSet" select="msxsl:node-set($rtf-nodes)/*"/>
- <xsl:for-each select="$myNodeSet">
- <tr>
- <xsl:choose>
- <xsl:when test="position() mod 2 = 1">
- <xsl:attribute name="class">dark-row</xsl:attribute>
- </xsl:when>
- <xsl:otherwise>
- <xsl:attribute name="class">light-row</xsl:attribute>
- </xsl:otherwise>
- </xsl:choose>
- <td class="log-text" id="indent">
- <xsl:choose>
- <xsl:when test="@label">
- <a href="{@url}"><xsl:value-of select="@label"/></a>
- <br />
- <div id="indent">
- (<xsl:value-of select="@id"/> - <xsl:value-of select="@version"/>)
- </div>
- </xsl:when>
- <xsl:otherwise>
- <a href="{@url}"><xsl:value-of select="@id"/> - <xsl:value-of select="@version"/></a>
- </xsl:otherwise>
- </xsl:choose>
- <br /><br />
- </td>
- <td>
- <table>
- <xsl:if test="@os">
- <tr><td class="log-text" id="indent">Operating Systems:</td>
- <td class="log-text" id="indent"><xsl:value-of select="@os"/></td>
- </tr>
- </xsl:if>
- <xsl:if test="@ws">
- <tr><td class="log-text" id="indent">Windows Systems:</td>
- <td class="log-text" id="indent"><xsl:value-of select="@ws"/></td>
- </tr>
- </xsl:if>
- <xsl:if test="@nl">
- <tr><td class="log-text" id="indent">Languages:</td>
- <td class="log-text" id="indent"><xsl:value-of select="@nl"/></td>
- </tr>
- </xsl:if>
- <xsl:if test="@arch">
- <tr><td class="log-text" id="indent">Architecture:</td>
- <td class="log-text" id="indent"><xsl:value-of select="@arch"/></td>
- </tr>
- </xsl:if>
- </table>
- </td>
- </tr>
- </xsl:for-each>
- </xsl:when>
- <xsl:otherwise>
- <xsl:for-each select="feature[not(category)]">
- <xsl:sort select="@id" order="ascending" case-order="upper-first"/>
- <xsl:sort select="@version" order="ascending" />
- <tr>
- <xsl:choose>
- <xsl:when test="count(preceding-sibling::feature[not(category)]) mod 2 = 1">
- <xsl:attribute name="class">dark-row</xsl:attribute>
- </xsl:when>
- <xsl:otherwise>
- <xsl:attribute name="class">light-row</xsl:attribute>
- </xsl:otherwise>
- </xsl:choose>
- <td class="log-text" id="indent">
- <xsl:choose>
- <xsl:when test="@label">
- <a href="{@url}"><xsl:value-of select="@label"/></a>
- <br />
- <div id="indent">
- (<xsl:value-of select="@id"/> - <xsl:value-of select="@version"/>)
- </div>
- </xsl:when>
- <xsl:otherwise>
- <a href="{@url}"><xsl:value-of select="@id"/> - <xsl:value-of select="@version"/></a>
- </xsl:otherwise>
- </xsl:choose>
- <br /><br />
- </td>
- <td>
- <table>
- <xsl:if test="@os">
- <tr><td class="log-text" id="indent">Operating Systems:</td>
- <td class="log-text" id="indent"><xsl:value-of select="@os"/></td>
- </tr>
- </xsl:if>
- <xsl:if test="@ws">
- <tr><td class="log-text" id="indent">Windows Systems:</td>
- <td class="log-text" id="indent"><xsl:value-of select="@ws"/></td>
- </tr>
- </xsl:if>
- <xsl:if test="@nl">
- <tr><td class="log-text" id="indent">Languages:</td>
- <td class="log-text" id="indent"><xsl:value-of select="@nl"/></td>
- </tr>
- </xsl:if>
- <xsl:if test="@arch">
- <tr><td class="log-text" id="indent">Architecture:</td>
- <td class="log-text" id="indent"><xsl:value-of select="@arch"/></td>
- </tr>
- </xsl:if>
- </table>
- </td>
- </tr>
- </xsl:for-each>
- </xsl:otherwise>
- </xsl:choose>
- </table>
- </body>
- </html>
-</xsl:for-each>
-</xsl:template>
-</xsl:stylesheet>
diff --git a/files/typos/typos-de.txt b/files/typos/typos-de.txt
deleted file mode 100644
index 5bcdffc49..000000000
--- a/files/typos/typos-de.txt
+++ /dev/null
@@ -1,2219 +0,0 @@
-# This file contains a number of common German typos:
-andriod->android
-
-# The remainder of this file contains misspellings from
-# http://de.m.wikipedia.org/wiki/Wikipedia:Liste_von_Tippfehlern/F%C3%BCr_Maschinen
-# plus some post-processing to fix invalid entries, remove duplicates, etc.
-#
-# The content is available under the
-# "Creative Commons Attribution-ShareAlike License"
-# http://creativecommons.org/licenses/by-sa/3.0/
-#
-# THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE
-# COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY
-# COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS
-# AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
-#
-# BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE
-# TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY
-# BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS
-# CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND
-# CONDITIONS.
-#
-# *1. Definitions*
-#
-# 1. *"Adaptation"* means a work based upon the Work, or upon the Work
-# and other pre-existing works, such as a translation, adaptation,
-# derivative work, arrangement of music or other alterations of a
-# literary or artistic work, or phonogram or performance and includes
-# cinematographic adaptations or any other form in which the Work may
-# be recast, transformed, or adapted including in any form
-# recognizably derived from the original, except that a work that
-# constitutes a Collection will not be considered an Adaptation for
-# the purpose of this License. For the avoidance of doubt, where the
-# Work is a musical work, performance or phonogram, the
-# synchronization of the Work in timed-relation with a moving image
-# ("synching") will be considered an Adaptation for the purpose of
-# this License.
-# 2. *"Collection"* means a collection of literary or artistic works,
-# such as encyclopedias and anthologies, or performances, phonograms
-# or broadcasts, or other works or subject matter other than works
-# listed in Section 1(f) below, which, by reason of the selection and
-# arrangement of their contents, constitute intellectual creations, in
-# which the Work is included in its entirety in unmodified form along
-# with one or more other contributions, each constituting separate and
-# independent works in themselves, which together are assembled into a
-# collective whole. A work that constitutes a Collection will not be
-# considered an Adaptation (as defined below) for the purposes of this
-# License.
-# 3. *"Creative Commons Compatible License"* means a license that is
-# listed at http://creativecommons.org/compatiblelicenses that has
-# been approved by Creative Commons as being essentially equivalent to
-# this License, including, at a minimum, because that license: (i)
-# contains terms that have the same purpose, meaning and effect as the
-# License Elements of this License; and, (ii) explicitly permits the
-# relicensing of adaptations of works made available under that
-# license under this License or a Creative Commons jurisdiction
-# license with the same License Elements as this License.
-# 4. *"Distribute"* means to make available to the public the original
-# and copies of the Work or Adaptation, as appropriate, through sale
-# or other transfer of ownership.
-# 5. *"License Elements"* means the following high-level license
-# attributes as selected by Licensor and indicated in the title of
-# this License: Attribution, ShareAlike.
-# 6. *"Licensor"* means the individual, individuals, entity or entities
-# that offer(s) the Work under the terms of this License.
-# 7. *"Original Author"* means, in the case of a literary or artistic
-# work, the individual, individuals, entity or entities who created
-# the Work or if no individual or entity can be identified, the
-# publisher; and in addition (i) in the case of a performance the
-# actors, singers, musicians, dancers, and other persons who act,
-# sing, deliver, declaim, play in, interpret or otherwise perform
-# literary or artistic works or expressions of folklore; (ii) in the
-# case of a phonogram the producer being the person or legal entity
-# who first fixes the sounds of a performance or other sounds; and,
-# (iii) in the case of broadcasts, the organization that transmits the
-# broadcast.
-# 8. *"Work"* means the literary and/or artistic work offered under the
-# terms of this License including without limitation any production in
-# the literary, scientific and artistic domain, whatever may be the
-# mode or form of its expression including digital form, such as a
-# book, pamphlet and other writing; a lecture, address, sermon or
-# other work of the same nature; a dramatic or dramatico-musical work;
-# a choreographic work or entertainment in dumb show; a musical
-# composition with or without words; a cinematographic work to which
-# are assimilated works expressed by a process analogous to
-# cinematography; a work of drawing, painting, architecture,
-# sculpture, engraving or lithography; a photographic work to which
-# are assimilated works expressed by a process analogous to
-# photography; a work of applied art; an illustration, map, plan,
-# sketch or three-dimensional work relative to geography, topography,
-# architecture or science; a performance; a broadcast; a phonogram; a
-# compilation of data to the extent it is protected as a copyrightable
-# work; or a work performed by a variety or circus performer to the
-# extent it is not otherwise considered a literary or artistic work.
-# 9. *"You"* means an individual or entity exercising rights under this
-# License who has not previously violated the terms of this License
-# with respect to the Work, or who has received express permission
-# from the Licensor to exercise rights under this License despite a
-# previous violation.
-# 10. *"Publicly Perform"* means to perform public recitations of the Work
-# and to communicate to the public those public recitations, by any
-# means or process, including by wire or wireless means or public
-# digital performances; to make available to the public Works in such
-# a way that members of the public may access these Works from a place
-# and at a place individually chosen by them; to perform the Work to
-# the public by any means or process and the communication to the
-# public of the performances of the Work, including by public digital
-# performance; to broadcast and rebroadcast the Work by any means
-# including signs, sounds or images.
-# 11. *"Reproduce"* means to make copies of the Work by any means
-# including without limitation by sound or visual recordings and the
-# right of fixation and reproducing fixations of the Work, including
-# storage of a protected performance or phonogram in digital form or
-# other electronic medium.
-#
-# *2. Fair Dealing Rights.* Nothing in this License is intended to reduce,
-# limit, or restrict any uses free from copyright or rights arising from
-# limitations or exceptions that are provided for in connection with the
-# copyright protection under copyright law or other applicable laws.
-#
-# *3. License Grant.* Subject to the terms and conditions of this License,
-# Licensor hereby grants You a worldwide, royalty-free, non-exclusive,
-# perpetual (for the duration of the applicable copyright) license to
-# exercise the rights in the Work as stated below:
-#
-# 1. to Reproduce the Work, to incorporate the Work into one or more
-# Collections, and to Reproduce the Work as incorporated in the
-# Collections;
-# 2. to create and Reproduce Adaptations provided that any such
-# Adaptation, including any translation in any medium, takes
-# reasonable steps to clearly label, demarcate or otherwise identify
-# that changes were made to the original Work. For example, a
-# translation could be marked "The original work was translated from
-# English to Spanish," or a modification could indicate "The original
-# work has been modified.";
-# 3. to Distribute and Publicly Perform the Work including as
-# incorporated in Collections; and,
-# 4. to Distribute and Publicly Perform Adaptations.
-# 5.
-#
-# For the avoidance of doubt:
-#
-# 1. *Non-waivable Compulsory License Schemes*. In those
-# jurisdictions in which the right to collect royalties through
-# any statutory or compulsory licensing scheme cannot be waived,
-# the Licensor reserves the exclusive right to collect such
-# royalties for any exercise by You of the rights granted under
-# this License;
-# 2. *Waivable Compulsory License Schemes*. In those jurisdictions in
-# which the right to collect royalties through any statutory or
-# compulsory licensing scheme can be waived, the Licensor waives
-# the exclusive right to collect such royalties for any exercise
-# by You of the rights granted under this License; and,
-# 3. *Voluntary License Schemes*. The Licensor waives the right to
-# collect royalties, whether individually or, in the event that
-# the Licensor is a member of a collecting society that
-# administers voluntary licensing schemes, via that society, from
-# any exercise by You of the rights granted under this License.
-#
-# The above rights may be exercised in all media and formats whether now
-# known or hereafter devised. The above rights include the right to make
-# such modifications as are technically necessary to exercise the rights
-# in other media and formats. Subject to Section 8(f), all rights not
-# expressly granted by Licensor are hereby reserved.
-#
-# *4. Restrictions.* The license granted in Section 3 above is expressly
-# made subject to and limited by the following restrictions:
-#
-# 1. You may Distribute or Publicly Perform the Work only under the terms
-# of this License. You must include a copy of, or the Uniform Resource
-# Identifier (URI) for, this License with every copy of the Work You
-# Distribute or Publicly Perform. You may not offer or impose any
-# terms on the Work that restrict the terms of this License or the
-# ability of the recipient of the Work to exercise the rights granted
-# to that recipient under the terms of the License. You may not
-# sublicense the Work. You must keep intact all notices that refer to
-# this License and to the disclaimer of warranties with every copy of
-# the Work You Distribute or Publicly Perform. When You Distribute or
-# Publicly Perform the Work, You may not impose any effective
-# technological measures on the Work that restrict the ability of a
-# recipient of the Work from You to exercise the rights granted to
-# that recipient under the terms of the License. This Section 4(a)
-# applies to the Work as incorporated in a Collection, but this does
-# not require the Collection apart from the Work itself to be made
-# subject to the terms of this License. If You create a Collection,
-# upon notice from any Licensor You must, to the extent practicable,
-# remove from the Collection any credit as required by Section 4(c),
-# as requested. If You create an Adaptation, upon notice from any
-# Licensor You must, to the extent practicable, remove from the
-# Adaptation any credit as required by Section 4(c), as requested.
-# 2. You may Distribute or Publicly Perform an Adaptation only under the
-# terms of: (i) this License; (ii) a later version of this License
-# with the same License Elements as this License; (iii) a Creative
-# Commons jurisdiction license (either this or a later license
-# version) that contains the same License Elements as this License
-# (e.g., Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons
-# Compatible License. If you license the Adaptation under one of the
-# licenses mentioned in (iv), you must comply with the terms of that
-# license. If you license the Adaptation under the terms of any of the
-# licenses mentioned in (i), (ii) or (iii) (the "Applicable License"),
-# you must comply with the terms of the Applicable License generally
-# and the following provisions: (I) You must include a copy of, or the
-# URI for, the Applicable License with every copy of each Adaptation
-# You Distribute or Publicly Perform; (II) You may not offer or impose
-# any terms on the Adaptation that restrict the terms of the
-# Applicable License or the ability of the recipient of the Adaptation
-# to exercise the rights granted to that recipient under the terms of
-# the Applicable License; (III) You must keep intact all notices that
-# refer to the Applicable License and to the disclaimer of warranties
-# with every copy of the Work as included in the Adaptation You
-# Distribute or Publicly Perform; (IV) when You Distribute or Publicly
-# Perform the Adaptation, You may not impose any effective
-# technological measures on the Adaptation that restrict the ability
-# of a recipient of the Adaptation from You to exercise the rights
-# granted to that recipient under the terms of the Applicable License.
-# This Section 4(b) applies to the Adaptation as incorporated in a
-# Collection, but this does not require the Collection apart from the
-# Adaptation itself to be made subject to the terms of the Applicable
-# License.
-# 3. If You Distribute, or Publicly Perform the Work or any Adaptations
-# or Collections, You must, unless a request has been made pursuant to
-# Section 4(a), keep intact all copyright notices for the Work and
-# provide, reasonable to the medium or means You are utilizing: (i)
-# the name of the Original Author (or pseudonym, if applicable) if
-# supplied, and/or if the Original Author and/or Licensor designate
-# another party or parties (e.g., a sponsor institute, publishing
-# entity, journal) for attribution ("Attribution Parties") in
-# Licensor's copyright notice, terms of service or by other reasonable
-# means, the name of such party or parties; (ii) the title of the Work
-# if supplied; (iii) to the extent reasonably practicable, the URI, if
-# any, that Licensor specifies to be associated with the Work, unless
-# such URI does not refer to the copyright notice or licensing
-# information for the Work; and (iv) , consistent with Ssection 3(b),
-# in the case of an Adaptation, a credit identifying the use of the
-# Work in the Adaptation (e.g., "French translation of the Work by
-# Original Author," or "Screenplay based on original Work by Original
-# Author"). The credit required by this Section 4(c) may be
-# implemented in any reasonable manner; provided, however, that in the
-# case of a Adaptation or Collection, at a minimum such credit will
-# appear, if a credit for all contributing authors of the Adaptation
-# or Collection appears, then as part of these credits and in a manner
-# at least as prominent as the credits for the other contributing
-# authors. For the avoidance of doubt, You may only use the credit
-# required by this Section for the purpose of attribution in the
-# manner set out above and, by exercising Your rights under this
-# License, You may not implicitly or explicitly assert or imply any
-# connection with, sponsorship or endorsement by the Original Author,
-# Licensor and/or Attribution Parties, as appropriate, of You or Your
-# use of the Work, without the separate, express prior written
-# permission of the Original Author, Licensor and/or Attribution Parties.
-# 4. Except as otherwise agreed in writing by the Licensor or as may be
-# otherwise permitted by applicable law, if You Reproduce, Distribute
-# or Publicly Perform the Work either by itself or as part of any
-# Adaptations or Collections, You must not distort, mutilate, modify
-# or take other derogatory action in relation to the Work which would
-# be prejudicial to the Original Author's honor or reputation.
-# Licensor agrees that in those jurisdictions (e.g. Japan), in which
-# any exercise of the right granted in Section 3(b) of this License
-# (the right to make Adaptations) would be deemed to be a distortion,
-# mutilation, modification or other derogatory action prejudicial to
-# the Original Author's honor and reputation, the Licensor will waive
-# or not assert, as appropriate, this Section, to the fullest extent
-# permitted by the applicable national law, to enable You to
-# reasonably exercise Your right under Section 3(b) of this License
-# (right to make Adaptations) but not otherwise.
-#
-# *5. Representations, Warranties and Disclaimer*
-#
-# UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR
-# OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY
-# KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE,
-# INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY,
-# FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF
-# LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS,
-# WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE
-# EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.
-#
-# *6. Limitation on Liability.* EXCEPT TO THE EXTENT REQUIRED BY
-# APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL
-# THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY
-# DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF
-# LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-#
-# *7. Termination*
-#
-# 1. This License and the rights granted hereunder will terminate
-# automatically upon any breach by You of the terms of this License.
-# Individuals or entities who have received Adaptations or Collections
-# from You under this License, however, will not have their licenses
-# terminated provided such individuals or entities remain in full
-# compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will
-# survive any termination of this License.
-# 2. Subject to the above terms and conditions, the license granted here
-# is perpetual (for the duration of the applicable copyright in the
-# Work). Notwithstanding the above, Licensor reserves the right to
-# release the Work under different license terms or to stop
-# distributing the Work at any time; provided, however that any such
-# election will not serve to withdraw this License (or any other
-# license that has been, or is required to be, granted under the terms
-# of this License), and this License will continue in full force and
-# effect unless terminated as stated above.
-#
-# *8. Miscellaneous*
-#
-# 1. Each time You Distribute or Publicly Perform the Work or a
-# Collection, the Licensor offers to the recipient a license to the
-# Work on the same terms and conditions as the license granted to You
-# under this License.
-# 2. Each time You Distribute or Publicly Perform an Adaptation, Licensor
-# offers to the recipient a license to the original Work on the same
-# terms and conditions as the license granted to You under this License.
-# 3. If any provision of this License is invalid or unenforceable under
-# applicable law, it shall not affect the validity or enforceability
-# of the remainder of the terms of this License, and without further
-# action by the parties to this agreement, such provision shall be
-# reformed to the minimum extent necessary to make such provision
-# valid and enforceable.
-# 4. No term or provision of this License shall be deemed waived and no
-# breach consented to unless such waiver or consent shall be in
-# writing and signed by the party to be charged with such waiver or
-# consent.
-# 5. This License constitutes the entire agreement between the parties
-# with respect to the Work licensed here. There are no understandings,
-# agreements or representations with respect to the Work not specified
-# here. Licensor shall not be bound by any additional provisions that
-# may appear in any communication from You. This License may not be
-# modified without the mutual written agreement of the Licensor and You.
-# 6. The rights granted under, and the subject matter referenced, in this
-# License were drafted utilizing the terminology of the Berne
-# Convention for the Protection of Literary and Artistic Works (as
-# amended on September 28, 1979), the Rome Convention of 1961, the
-# WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms
-# Treaty of 1996 and the Universal Copyright Convention (as revised on
-# July 24, 1971). These rights and subject matter take effect in the
-# relevant jurisdiction in which the License terms are sought to be
-# enforced according to the corresponding provisions of the
-# implementation of those treaty provisions in the applicable national
-# law. If the standard suite of rights granted under applicable
-# copyright law includes additional rights not granted under this
-# License, such additional rights are deemed to be included in the
-# License; this License is not intended to restrict the license of any
-# rights under applicable law.
-Aaachen->Aachen
-aberufen->abgerufen
-abgekürtzt->abgekürzt
-abgeschloßen->abgeschlossen
-Abhängikeit->Abhängigkeit
-Abhängkeit->Abhängigkeit
-abolvieren->absolvieren
-abolviert->absolviert
-abschliessen->abschließen
-abschliessend->abschließend
-abschliessende->abschließende
-abschliessenden->abschließenden
-abschliessender->abschließender
-abschliesst->abschließt
-Absorbtion->Absorption
-abzuschliessen->abzuschließen
-achsial*->axial*
-achzig->achtzig
-Addresse->Adresse
-addressiert->adressiert
-Adjudant->Adjutant
-Aeropag->Areopag
-Aeropagos->Areopag
-afrz->afrz.
-agberufen->abgerufen
-Agendas->Agenden
-agerufen->abgerufen
-agraisch->agrarisch
-agressiv->aggressiv
-akkomodieren->akkommodieren
-Akkustik->Akustik
-akreditiert->akkreditiert
-Aktivitiäten->Aktivitäten
-Aktzeptanz->Akzeptanz
-alamiert->alarmiert
-aler->aller
-alerdings->allerdings
-Algorhitmus->Algorithmus
-Algoritmus->Algorithmus
-aliiert->alliiert
-allerding->allerdings
-allgmein->allgemein
-alliert->alliiert
-allredings->allerdings
-all zu->allzu
-Alstadt->Altstadt
-am einem->an einem,am einen
-amerikanich->amerikanisch
-amerikansch->amerikanisch
-amerkanisch->amerikanisch
-am seinem->an seinem
-Amtsitz->Amtssitz
-Amtsprache->Amtssprache
-Amtsprachen->Amtssprachen
-Anaesthesie->Anästhesie
-Analen->Annalen
-anderere->andere
-andereren->anderen
-andererer->anderer
-andereseits->andererseits
-anders herum->andersherum
-andersrum->besser: andersherum
-angelsächisch->angelsächsisch
-angelsächsiche->angelsächsische
-angelsächsichen->angelsächsischen
-angesehendsten->angesehensten
-anlaesslich->anlässlich
-anlaeßlich->anlässlich
-änlich->ähnlich
-annährend->annähernd
-Annährung->Annäherung
-Annektion->Annexion
-annerkannt->anerkannt
-annerkannte->anerkannte
-Annerkennung->Anerkennung
-annuliert->annulliert
-Annulierung->Annullierung
-Anordung->Anordnung
-Anschaung->Anschauung
-anschliessen->anschließen
-anschliessend->anschließend
-anschliessende->anschließende
-anschliessenden->anschließenden
-anschliessender->anschließender
-anschliessendes->anschließendes
-anschliesst->anschließt
-Anstoss->Anstoß
-anvisiert->angekündigt,avisiert
-Anwendund->Anwendung
-Anwort->Antwort
-Appartment*->Apartment*,Appartement*
-aquirieren->akquirieren
-Aquisition->Akquisition
-archälogische->archäologische
-archälogischen->archäologischen
-Archeologe->Archäologe
-Argentur*->Agentur*
-Arikel->Artikel
-arithmetrisch->arithmetisch
-Artzt->Arzt
-assozial->asozial
-asymetrisch*->asymmetrisch*
-Atacke->Attacke
-atackieren->attackieren
-atakieren->attackieren
-Athleth*->Athlet*
-Athmosphäre*->Atmosphäre*
-athmosphärisch*->atmosphärisch*
-Atrappe->Attrappe
-attakieren->attackieren
-Aufällig->Auffällig
-Aufassung->Auffassung
-Aufassungen->Auffassungen
-auf dem ersten Blick->auf den ersten Blick
-auf eigenem Wunsch->auf eigenen Wunsch,aus eigenem Wunsch
-Aufenhalt->Aufenthalt
-Aufname->Aufnahme
-Auforderung->Aufforderung
-aufrecht erhält->aufrechterhält
-aufrecht erhalten->aufrechterhalten
-aufrecht erhielt->aufrechterhielt
-aufrecht zu erhalten->aufrechtzuerhalten
-Aufsteig->Aufstieg
-Auftieg->Aufstieg
-auftretenen->auftretenden
-auftretten->auftreten
-Augenlied->Augenlid
-augenommen->aufgenommen,ausgenommen
-auml->Ä,ä
-Ausage->Aussage
-Ausagen->Aussagen
-auschliesslich->ausschließlich
-auschließlich->ausschließlich
-auschliessliche->ausschließliche
-auschliesslichen->ausschließlichen
-Auseinadersetzung->Auseinandersetzung
-Auseindersetzung->Auseinandersetzung
-auserdem->außerdem
-auserhalb->außerhalb
-Ausgangpunkt->Ausgangspunkt
-ausgeschalten->ausgeschaltet
-Ausicht->Aussicht
-Ausmass->Ausmaß
-Ausprache->Aussprache
-Auspruch->Ausspruch
-ausschliessen->ausschließen
-ausschliesslich->ausschließlich
-ausschliesst->ausschließt
-Ausschwitz->Auschwitz
-aussen->außen
-Aussenminister->Außenminister
-ausser->außer
-ausserdem->außerdem
-äussere->äußere
-äusseren->äußeren
-äusserer->äußerer
-äusseres->äußeres
-aussergewöhnlich->außergewöhnlich
-aussergewöhnlichen->außergewöhnlichen
-ausserhalb->außerhalb
-ausserirdisch->außerirdisch
-ausserirdische->außerirdische
-ausserirdischen->außerirdischen
-äussern->äußern
-ausserordentlich->außerordentlich
-ausserordentliche->außerordentliche
-ausserordentlichem->außerordentlichem
-ausserordentlichen->außerordentlichen
-ausserordentlicher->außerordentlicher
-ausserordentliches->außerordentliches
-äusserst->äußerst
-äusserste->äußerste
-äussersten->äußersten
-äusserte->äußerte
-äusserten->äußerten
-Äusserung->Äußerung
-Äusserungen->Äußerungen
-aussschliesslich->ausschließlich
-aussschließlich->ausschließlich
-außschließlich->ausschließlich
-Austattung->Ausstattung
-Austellung->Ausstellung
-Austellungen->Ausstellungen
-Austerben->Aussterben
-Auszeichung->Auszeichnung
-Auszeichungen->Auszeichnungen
-auszuschliessen->auszuschließen
-Author des->Autor des
-authorisieren->autorisieren
-authorisiert->autorisiert
-Authorisierung*->Autorisierung*
-Authorität->Autorität
-dem Autoren->dem Autor
-des Autoren->des Autors
-vom Autoren->vom Autor
-Babies->Babys
-bafand->befand
-Balett->Ballett
-bassierend->basierend
-Batallion->Bataillon
-Battaillon->Bataillon
-Battallion->Bataillon
-Bauerhof->Bauernhof
-Bauerhöfe->Bauernhöfe
-bedeudend->bedeutend
-bedeudende->bedeutende
-bedeudenden->bedeutenden
-bedeudender->bedeutender
-bedeudendes->bedeutendes
-bedeudet->bedeutet
-bedeudete->bedeutete
-bedeutendeste->bedeutendste
-bedeutenste->bedeutendste
-bedeutensten->bedeutendsten
-bedeutenster->bedeutendster
-bedeutenstes->bedeutendstes
-bedeutesten->bedeutendsten
-Bedinung->Bedingung/Bedienung
-Bedürfniss->Bedürfnis
-beeinflußen->beeinflussen
-Beeinflußung->Beeinflussung
-beeinhalten->beinhalten
-beeinhaltet->beinhaltet
-befindet auf->befindet sich auf
-befindet ein*->befindet sich ein*
-befindet in->befindet sich in
-begang->beging,begann
-beherrbergt->beherbergt
-beherschen->beherrschen
-beherscht->beherrscht
-beherschte->beherrschte
-beidemale->beide Male
-beim dem->bei dem,beim
-beim der->bei der,beim,bei dem
-beindrucken->beeindrucken
-beinflussen->beeinflussen
-beinflusst*->beeinflusst*
-Beipiel*->Beispiel*
-Beispeil*->Beispiel*
-beispielswiese->beispielsweise
-beispielweise->beispielsweise
-Beitag->Beitrag
-bekammen->bekamen
-Bekenntniss->Bekenntnis
-Benefitz->Benefiz
-bennant->benannt
-Bennenung->Benennung
-Berechung->Berechnung
-bereit gehalten->bereitgehalten
-bereit gestellt->bereitgestellt
-bereit hält->bereithält
-bereit stand->bereitstand
-bereit stehen->bereitstehen
-bereit steht->bereitsteht
-bereit stellt->bereitstellt
-bereit zu halten->bereitzuhalten
-bereit zu stellen->bereitzustellen
-Berfung->Berufung
-Berreich->Bereich
-berücksichtig->berücksichtigt
-berümt->berühmt
-berümte->berühmte
-besass->besaß
-besassen->besaßen
-besitzten->besitzen
-Bespiel->Beispiel
-Bestandsteil->Bestandteil
-Bestandtteil->Bestandteil
-bestbezahltest*->bestbezahlt*
-bestimmmt->bestimmt
-bestreitete->bestritt
-Betreung->Betreuung
-Betriebsystem*->Betriebssystem*
-Bevökerung->Bevölkerung
-Beweiß->Beweis
-bezeichent->bezeichnet
-bezeichet->bezeichnet
-Bezeichung*->Bezeichnung*
-Biograpfie->Biografie
-bischen->bisschen
-Bischofsitz->Bischofssitz
-Bisquit->Biskuit
-bloss->bloß
-blosse->bloße
-blossen->bloßen
-blosser->bloßer
-blosses->bloßes
-an Board->an Bord
-on Bord->an Bord
-bombadieren->bombardieren
-bombadiert->bombardiert
-Bombadierung->Bombardierung
-boolsch->boolesch
-brilliant->brillant
-britsch->britisch
-britsche->britische
-britschen->britischen
-britscher->britischer
-britsches->britisches
-Bronzemedaillie*->Bronzemedaille*
-Bronzemedallie*->Bronzemedaille*
-Bügermeister->Bürgermeister
-Bundesaussenminister->Bundesaußenminister
-Bundesstrasse->Bundesstraße
-Bundestaat*->Bundesstaat*
-Bundestraße->Bundesstraße
-Bundsandstein*->Buntsandstein*
-byzantisch*->byzantinisch*
-chinesiche->chinesische
-chinesichen->chinesischen
-chinesicher->chinesischer
-Chirugie->Chirurgie
-Chonik->Chronik
-Chonist->Chronist
-chonologisch->chronologisch
-cirka->zirka,circa
-dadruch->dadurch
-daduch->dadurch
-danaben->daneben
-danch->danach
-dannach->danach
-deuten daraufhin->deuten darauf hin
-deutet daraufhin->deutet darauf hin
-weisen daraufhin->weisen darauf hin
-weist daraufhin->weist darauf hin
-darüberhinaus->darüber hinaus
-daruf->darauf
-darufhin->daraufhin
-das es sich bei->dass es sich bei
-das es sich um->dass es sich um
-so das der->so dass der
-so das die->so dass die
-so das er->so dass er
-so das sie->so dass sie
-dass heißt->das heißt
-dastellt->darstellt
-dazu gehörige*->dazugehörige*
-Debutalbum->Debütalbum
-Definiton->Definition
-definitv->definitiv
-Defintion->Definition
-deligiert->delegiert
-dem selben->demselben
-denoch->dennoch
-den selben->denselben
-derem->deren
-der Niederlanden->der Niederlande,den Niederlanden
-der selbe->derselbe
-der selben->derselben
-in der USA->in den USA
-des des->des
-des eines->eines,des,der eines,dem eines
-des selben->desselben
-dessem->dessen
-desshalb->deshalb
-desweiteren->des Weiteren
-desweitern->des Weiteren
-des Weitern->des Weiteren
-detailiert*->detailliert*
-detalliert->detailliert
-dezeit->derzeit
-Dezmber->Dezember
-die selbe->dieselbe
-die selben->dieselben
-Differentation->Differentiation
-Dikator->Diktator
-Dikatur->Diktatur
-Diphterie->Diphtherie
-Diphtong->Diphthong
-Dirgent->Dirigent
-Discografie->Diskografie
-Discographie->Diskographie
-diskreminieren->diskriminieren
-diskrimierend*->diskriminierend*
-Diskrimierung*->Diskriminierung*
-Diskusion->Diskussion
-Disseration->Dissertation
-Divison*->Division*
-Divsion*->Division*
-Diziplin*->Disziplin*
-Dollmetscher->Dolmetscher
-dort hin->dorthin
-draufhin->daraufhin
-draussen->draußen
-Dreick->Dreieck
-dreissig->dreißig
-dreissiger->dreißiger
-druch->durch
-druchgeführt->durchgeführt
-duch->durch
-duchführen->durchführen
-Duchführung->Durchführung
-duchgeführt->durchgeführt
-Duchschnitt->Durchschnitt
-durch geführt->durchgeführt
-Durchschlagkraft->Durchschlagskraft
-Durchsetztung->Durchsetzung
-durchstossen->durchstoßen
-Durschnitt->Durchschnitt
-durschnittlich->durchschnittlich
-durschnittliche->durchschnittliche
-durschnittlichen->durchschnittlichen
-ebefalls->ebenfalls
-eben dies->ebendies
-eben diese->ebendiese
-eben diesem->ebendiesem
-eben diesen->ebendiesen
-eben dieser->ebendieser
-eben dieses->ebendieses
-ebendso->ebenso
-ebenfall->ebenfalls
-ebenfals->ebenfalls
-Editon->Edition
-Edtion->Edition
-einem eigenem->einem eigenen
-ihrem eigenem->ihrem eigenen
-seinem eigenem->seinem eigenen
-eigenen sich->eignen sich
-mit einen->mit einem
-eines des->eines der
-Einflüße->Einflüsse
-Einfuss->Einfluss
-einge->einige
-eingen->einigen
-eingentlich->eigentlich
-einger->einiger
-einges->einiges
-eingesetz->eingesetzt
-eingesetzen->eingesetzten
-einigemal->einige Mal
-einklich->eigentlich
-Einordung->Einordnung
-einschliessen->einschließen
-einschliesslich->einschließlich
-einschliesst->einschließt
-einzelen->einzelne
-einzigste->einzige
-einzigster->einziger
-einzigstes->einziges
-ekklektizistisch->eklektizistisch
-ekstasisch->ekstatisch
-elekrisch->elektrisch
-elekronisch->elektronisch
-eleminieren->eliminieren
-eleminiert->eliminiert
-emigiert->emigriert
-emigiriert->emigriert
-Emmigrant->Emigrant
-Emmigration->Emigration
-emmigriert->emigriert
-emprisch->empirisch
-Emsemble->Ensemble
-endeckt->entdeckt
-endeckte->entdeckte
-Endeckung*->Entdeckung*
-enfernt->entfernt
-enfernte->entfernte
-Enfernung->Entfernung
-Enfernungen->Entfernungen
-Engeneering->Engineering
-englsich->englisch
-engültig->endgültig
-enhält->enthält
-enhalten->enthalten
-Enscheidung->Entscheidung
-enstand->entstand
-enstanden->entstanden
-enstehen->entstehen
-ensteht->entsteht
-Enstehung->Entstehung
-entgegen gebracht*->entgegengebracht*
-entgegen gesetzt*->entgegengesetzt*
-entgegen kam->entgegenkam
-entgegen nahm->entgegennahm
-entgegen zu gehen->entgegenzugehen
-entgegen zu kommen->entgegenzukommen
-entgegen zu nehmen->entgegenzunehmen
-entgegen zu schleudern->entgegenzuschleudern
-entgegen zu setzen->entgegenzusetzen
-entgegen zu stellen->entgegenzustellen
-entgegen zu treten->entgegenzutreten
-entgegen zu wirken->entgegenzuwirken
-Entgeld->Entgelt
-entgültig*->endgültig*
-entlang führt*->entlangführt*
-entlang geführt*->entlanggeführt*
-entprechend->entsprechend
-entprechende->entsprechende
-entprechender->entsprechender
-entsant->entsandt
-entscheidene*->entscheidende*
-entscheident->entscheidend
-entschloß->entschloss
-entspechen*->entsprechen*
-entsprechene->entsprechende
-entsprechenen->entsprechenden
-entstandt->entstand
-enwickelt->entwickelt
-enwickelte->entwickelte
-enwickelten->entwickelten
-enwickelter->entwickelter
-enwickeltes->entwickeltes
-Enwicklung->Entwicklung
-Enwicklungen->Entwicklungen
-ereichen->erreichen
-ereicht->erreicht
-ereichte->erreichte
-Ereignise->Ereignisse
-Ereignisen->Ereignissen
-Ereigniss->Ereignis
-Erfog->Erfolg
-erfogreich->erfolgreich
-erfolgslos->erfolglos
-erfolgsversprechend->erfolgversprechend
-Erfurcht->Ehrfurcht
-Ergebniss->Ergebnis
-Erkentnis->Erkenntnis
-Erkentnisse->Erkenntnisse
-erklährt->erklärt
-ermöglich->ermöglicht,ermöglichen
-erorbert->erobert
-errinnern->erinnern
-errinnert->erinnert
-errreichen->erreichen
-errreicht->erreicht
-errreichte->erreichte
-errrichtet->errichtet
-ersmals->erstmals
-dem erstem->dem ersten
-im erstem->im ersten
-erzeilt->erzielt
-erzeilte->erzielte
-erziehlen->erzielen
-erziehlt->erzielt
-estisch->estnisch
-Ettikett*->Etikett*
-dem europäischem->dem europäischen
-im europäischem->im europäischen
-Examplar->Exemplar
-examplarisch->exemplarisch
-exellent->exzellent
-exisitiert->existiert
-Existens->Existenz
-Expediton->Expedition
-experimentiell->experimentell
-Extase->Ekstase
-Fahradtour->Fahrradtour
-fälschlicher Weise->fälschlicherweise
-familär*->familiär*
-Famile->Familie
-Familen*->Familien*
-Famlie*->Familie*
-Februrar->Februar
-Feburar->Februar
-fern geblieben->ferngeblieben
-fern gehalten->ferngehalten
-fern zu halten->fernzuhalten
-Fersehen->Fernsehen
-Ferseh*->Fernseh*
-fertigestellt->fertiggestellt
-festellen->feststellen
-Festellung->Feststellung
-fidet->findet
-Fiedrich->Friedrich
-Flagschiff->Flaggschiff
-Flektion->Flexion
-fliessen->fließen
-fliesst->fließt
-des Flughafen->des Flughafens
-Fluß->Fluss
-Flüße->Flüsse
-fokusieren->fokussieren
-fokusiert->fokussiert
-Fokusierung->Fokussierung
-Foschung->Forschung
-Fotographie->Fotografie,Photographie
-Fotographien->Fotografien,Photographien
-fotographiert->fotografiert
-franösisch*->französisch*
-frantösisch*->französisch*
-franzöisch*->französisch*
-französich*->französisch*
-dem französischem->dem französischen
-einem französischem->einem französischen
-im französischem->im französischen
-Freidrich->Friedrich
-frei gestellt->freigestellt
-Freimauerei->Freimaurerei
-Fremsprache->Fremdsprache
-Friedenschluss->Friedensschluss
-Friedich->Friedrich
-Frima->Firma
-fröhnen->frönen
-Frühjar->Frühjahr
-frühre->frühere
-fuer->für
-füher*->früher*,Führer*
-Fuktion*->Funktion*
-Funier*->Furnier*
-für für->für
-Fuss->Fuß
-Fussball->Fußball
-Fussballer->Fußballer
-Fussballerin->Fußballerin
-Fussballspieler->Fußballspieler
-Fussballspielerin->Fußballspielerin
-Fußballstadium->Fußballstadion
-Fusse->Fuße
-Füsse->Füße
-Füst->Fürst
-gabe es->gab es
-Gallerie->Galerie
-Gallerien->Galerien
-Gallionsfigur->Galionsfigur
-garnicht->gar nicht
-Garnision->Garnison
-Garnision*->Garnison*
-Gebäde->Gebäude
-Gebahren->Gebaren
-gebähren->gebären
-Gebaüde->Gebäude
-Gebaude->Gebäude
-Gebäuder->Gebäude
-gebornen->geborenen
-Gedult->Geduld
-Gedänk*->Gedenk*
-einem geeignetem->einem geeigneten
-Gefäss->Gefäß
-gegebenfalls->gegebenenfalls
-gegen einander->gegeneinander
-gegenüber gestellt->gegenübergestellt
-gegn->gegen
-gegnüber->gegenüber
-gehöhren->gehören
-gehöhrt*->gehört*
-gekührt->gekürt
-gelanden->geladen
-gemäss->gemäß
-gemeinsammen->gemeinsamen
-gemeisam->gemeinsam
-genant->genannt
-genanten->genannten
-Genaral*->General*
-geniessen->genießen
-gennant*->genannt*
-gennannt*->genannt*
-Gerneral*->General*
-gesäht->gesät
-gesammt->gesamt
-gesammten->gesamten
-gesammter->gesamter
-Gesandschaft*->Gesandtschaft*
-Geschichtschreiber->Geschichtsschreiber
-Geschichtschreibung->Geschichtsschreibung
-geschiet->geschieht
-geschlosssen->geschlossen
-gesetztlich->gesetzlich
-Gesichtpunkt->Gesichtspunkt
-gesponsort->gesponsert
-gesteift->gestreift
-gewan->gewann
-gewissermassen->gewissermaßen
-gewunken->gewinkt
-Ghandi->Gandhi
-giebt->gibt
-Giessen->Gießen
-gleichbleiben->gleich bleiben
-gleich zu tun->gleichzutun
-Gogle->Google
-Goldmedaillie*->Goldmedaille*
-Goldmedallie*->Goldmedaille*
-Gothik->Gotik
-gothisch->gotisch
-Grabmahl->Grabmal
-Gradwanderung->Gratwanderung
-Graftschaft*->Grafschaft*
-groesse->größe
-groeße->größe
-gröhlen->grölen
-Grossaufgebot->Großaufgebot
-Grossbritanien->Großbritannien
-Großbritanien->Großbritannien
-Grossbritannien->Großbritannien
-Grossbrittanien->Großbritannien
-Großbrittanien->Großbritannien
-Grossbrittannien->Großbritannien
-Großbrittannien->Großbritannien
-grosse->große
-grösse->größe
-grossem->großem
-einem großem->einem großen
-grossen->großen
-grossenteils->großenteils
-größenteils->größtenteils
-grosser->großer
-grösser->größer
-grössere->größere
-grösserem->größerem
-grösseren->größeren
-grösserer->größerer
-grösseres->größeres
-grosses->großes
-grösste->größte
-Grossteil->Großteil
-grossteils->großteils
-grössten->größten
-grösstenteils->größtenteils
-grösster->größter
-grösstes->größtes
-Gründstück*->Grundstück*
-einem grünem->einem grünen
-Guerrillakampf->Guerillakampf
-Guiness->Guinness
-Guiseppe->Giuseppe
-einem gutem->einem guten
-Güterloh*->Gütersloh*
-Häckchen->Häkchen
-haetten->hätten
-Handelschiff->Handelsschiff
-Handies->Handys
-hahnebüchen->hanebüchen
-hattte->hatte,hatten
-Haupstadt->Hauptstadt
-haupsächlich->hauptsächlich
-Haupstädte->Hauptstädte
-des Haus->des Hauses
-heiratetet->heiratet
-heiss->heiß
-heisser->heißer
-heisst->heißt
-heraus gebracht->herausgebracht
-herausragenste->herausragendste
-Herausvorderung->Herausforderung
-herraus->heraus
-herrausragend->herausragend
-Herrrschaft->Herrschaft
-Herrrscher->Herrscher
-Herschaft->Herrschaft
-Herscher->Herrscher
-hervoragen->hervorragen
-hervoragend->hervorragend
-hervor gegangen*->hervorgegangen*
-hervor ging->hervorging
-hervorragenste->hervorragendste
-Hierachie->Hierarchie
-hierachisch->hierarchisch
-hiess->hieß
-hinaus gehende*->hinausgehende*
-hingegegen->hingegen
-Hintegrund->Hintergrund
-Hintergund->Hintergrund
-hinterliess->hinterließ
-hinterliessen->hinterließen
-hinweg täuschen->hinwegtäuschen
-hinzu gefügt*->hinzugefügt*
-hinzu gekommen*->hinzugekommen*
-Hobbies->Hobbys
-Hochaus->Hochhaus
-Hochäuser->Hochhäuser
-höchst gelegene*->höchstgelegene*
-Hofffnung->Hoffnung
-Hoffung->Hoffnung
-höherere*->höhere*
-höherwertigere*->höherwertige*
-höhren->hören,höheren
-höhrt->hört
-Homage->Hommage
-hunderste*->hundertste*
-idendifiziert->identifiziert
-idenfiziert->identifiziert
-idiopatisch->idiopathisch
-im besonderen Maße->in besonderem Maße
-im Bezug auf->in Bezug auf
-Imbus->Inbus
-im dem->in dem,im
-im den->in den,in dem,ihm den
-im der->in der,im,ihm der
-im deutschsprachigem->im deutschsprachigen
-im einem->in einem
-im großem->in großem,im großen
-im großen Umfang->in großem Umfang
-im hohen Maße->in hohem Maße
-immernoch->immer noch
-immmer->immer
-Impendanz->Impedanz
-im seinem->in seinem
-im selbem->im selben
-inbesondere->insbesondere
-inclusive->inklusive
-Independet->Independent
-indeß->indes
-individiuell->individuell
-Industie->Industrie
-Industriealisierung->Industrialisierung
-in englisch->in Englisch
-inerhalb->innerhalb
-Infantrie->Infanterie
-infiszieren->infizieren
-in Folge->infolge
-in Folge der->infolge der
-in Folge des->infolge des
-in Folge einer->infolge einer
-in Folge eines->infolge eines
-in Folge von->infolge von
-in Folge dessen->infolgedessen,infolge dessen,in dessen Folge
-Ingeneur->Ingenieur
-ingesamt->insgesamt
-Ingredenzien->Ingredienzien
-Inhaltstoff->Inhaltsstoff
-Initation->Initiation,Imitation
-Initative->Initiative
-Initator->Initiator
-Initialie->Initiale
-Initialien->Initialen
-initieren->initiieren
-initiert->initiiert
-Inititative->Initiative
-Iniziative->Initiative
-in mitten->inmitten
-inne gehabt->innegehabt
-inne haben->innehaben
-inne hat->innehat
-inne hatte->innehatte
-inne hatten->innehatten
-Innenaustattung->Innenausstattung
-innnerhalb->innerhalb
-Insbruck->Innsbruck
-in selben Jahr->im selben Jahr
-insgeamt->insgesamt
-insgesammt->insgesamt
-Insitut->Institut
-Insitution->Institution
-in so fern->insofern
-in sofern->insofern
-instandgehalten->instand gehalten,in Stand gehalten
-instandgesetzt->instand gesetzt,in Stand gesetzt
-instandhalten->instand halten,in Stand halten
-instandsetzen->instand setzen,in Stand setzen
-instandzusetzen->instand zu setzen,in Stand zu setzen
-Instituion->Institution
-Instiut->Institut
-Instiution->Institution
-Instutition*->Institution*
-inszinieren->inszenieren
-Inszinierung->Inszenierung
-integiert->integriert
-intelektuell*->intellektuell*
-intenational->international
-intepretiert->interpretiert
-Interese->Interesse
-interesiert->interessiert
-Intergration->Integration
-intergriert->integriert
-Internetpräsens->Internetpräsenz
-interresiert->interessiert
-Interresse->Interesse
-interressiert->interessiert
-Intiative->Initiative
-intressiert->interessiert
-Intrument*->Instrument*
-Inverstor->Investor
-in wie weit->inwieweit
-in wieweit->inwieweit
-inwischen->inzwischen
-irgend ein->irgendein
-irgend eine->irgendeine
-irgend einem->irgendeinem
-irgend einen->irgendeinen
-irgend einer->irgendeiner
-irgend eines->irgendeines
-irgentwie->irgendwie
-irrtümlicher Weise->irrtümlicherweise
-ist meis->ist meist
-ist meisten->ist meistens
-italenisch->italienisch
-italiensch->italienisch
-italiensich->italienisch
-Jägerbatallion->Jägerbataillon
-Jahhundert->Jahrhundert
-Jahhunderte->Jahrhunderte
-Jahhunderts->Jahrhunderts
-des Jahre->des Jahres
-Jahrhudert->Jahrhundert
-Jahrhunder->Jahrhundert
-Jahrundert->Jahrhundert
-Jahrunderte->Jahrhunderte
-Jahrunderts->Jahrhunderts
-Jahrzent->Jahrzehnt
-Jahrzente->Jahrzehnte
-Jahundert->Jahrhundert
-Jahunderte->Jahrhunderte
-Jahunderts->Jahrhunderts
-Jäner->Jänner
-Janur->Januar
-Jarh->Jahr
-Jarhundert->Jahrhundert
-Jarhunderte->Jahrhunderte
-Jarhunderts->Jahrhunderts
-jdoch->jedoch
-jedch->jedoch
-jeoch->jedoch
-jeodch->jedoch
-jeweil->jeweils
-jeweis->jeweils
-Jounalist->Journalist
-Jubiliäum->Jubiläum
-Jungend*->Jugend*
-Justitz->Justiz
-Kabaret->Kabarett
-Kaiserlautern->Kaiserslautern
-Kandidad->Kandidat
-Kanditat->Kandidat
-Kappelle->Kapelle
-Karierre->Karriere
-Karrikaturist->Karikaturist
-karrikieren->karikieren
-Kasette*->Kassette*
-kathegorisch->kategorisch
-Kenntnise->Kenntnis
-Kenntniss->Kenntnis
-Kennzeichnug->Kennzeichnung
-Kentnis->Kenntnis
-Kentnisse->Kenntnisse
-Kirchtum->Kirchturm
-klassich->klassisch
-klassiche->klassische
-klassichen->klassischen
-klassicher->klassischer
-Klink->Klinik
-des Kloster->des Klosters
-km2->km²
-kmh->km/h
-Kofession*->Konfession*
-Kollission*->Kollision*
-Kollonade->Kolonnade
-Komandant->Kommandant
-Komandanten->Kommandanten
-Komando->Kommando
-Komandos->Kommandos
-komerziell->kommerziell
-Komissar->Kommissar
-Komissariat->Kommissariat
-komissarisch->kommissarisch
-Komission->Kommission
-komlett->komplett
-Kommilitionen->Kommilitonen
-Kommision->Kommission
-Kommitee->Komitee
-Kommittee->Komitee
-kommmen->kommen
-Kommunkation->Kommunikation
-Kompentenz->Kompetenz
-Könföderierte->Konföderierte
-Konförderierte->Konföderierte
-könglich->königlich
-Köngreich->Königreich
-Königsreich->Königreich
-Königstum->Königtum
-Konkurenz*->Konkurrenz*
-konkurieren*->konkurrieren*
-konkuriert*->konkurriert*
-könnnen->können,Können
-Konservationslexikon->Konversationslexikon
-Kontak->Kontakt
-konte->konnte
-Kontigent*->Kontingent*
-konventionnell->konventionell
-korregieren->korrigieren
-korregiert->korrigiert
-Krankeit*->Krankheit*
-Krankenaus->Krankenhaus
-Kreuzug*->Kreuzung*,Kreuzzug*
-Kriche->Kirche
-Kriegschiff->Kriegsschiff
-kummulieren->kumulieren
-Kunsstoff*->Kunststoff*
-Kunstaustellung*->Kunstausstellung*
-Kunstoff->Kunststoff
-Kunstoffe->Kunststoffe
-Kurfüst*->Kurfürst*
-kurzeitig*->kurzzeitig*
-läd->lädt
-Landesaustellung->Landesausstellung
-Landesprache->Landessprache
-Landwirschaft->Landwirtschaft
-landwirschaftlich->landwirtschaftlich
-langläufig->landläufig
-Lapalie->Lappalie
-Lassithi->Lasithi
-läst->lässt
-lateinsch->lateinisch
-lateinsche->lateinische
-lateinschen->lateinischen
-lateinscher->lateinischer
-lateinsches->lateinisches
-Lebenstil->Lebensstil
-Lebenweise->Lebensweise
-legänder->legendär
-Leibzig->Leipzig
-Leichathlet*->Leichtathlet*
-Leichnahm->Leichnam
-letze->letzte
-letzem->letztem
-letzen->letzten
-letzendlich->letztendlich
-letzer->letzter
-letzere->letztere
-letzerem->letzterem
-letzeren->letzteren
-letzerer->letzterer
-letzeres->letzteres
-letzes->letztes
-letzlich->letztlich
-letztenendes->letzten Endes
-Lexikas->Lexika
-Liason->Liaison
-liess->ließ
-liesse->ließe
-liessen->ließen
-ließt->er/sie/es liest; ließ; fließt
-Lilliputaner->Liliputaner
-literaisch->literarisch
-literatisch->literarisch
-lizensieren->lizenzieren
-lizensiert->lizenziert
-lizensierte->lizenzierte
-lizensiertem->lizenziertem
-lizensierten->lizenzierten
-lizensierter->lizenzierter
-lizensiertes->lizenziertes
-Lizensierung->Lizenzierung
-los zu werden->loszuwerden
-Louisana->Louisiana
-Lousiana->Louisiana
-Luwig->Ludwig
-Lybien->Libyen
-lybisch->libysch
-lybische->libysche
-lybischem->libyschem
-lybischen->libyschen
-lybischer->libyscher
-lybisches->libysches
-machmal->manchmal
-Manhatan->Manhattan
-Manhatta->Manhattan
-Manhatten->Manhattan
-Manhetten->Manhattan
-Manschaft->Mannschaft
-Manmschaft->Mannschaft
-Mannhattan->Manhattan
-Mannöver->Manöver
-Mannschaf->Mannschaft
-Mannschaftt->Mannschaft
-Mannshcaft->Mannschaft
-Mansardach->Mansarddach
-Mansardendach->Mansarddach
-Mansnchaften->Mannschaft
-Manssarddach->Mansarddach
-marrokanisch*->marokkanisch*
-marrokkanisch*->marokkanisch*
-Marrokko->Marokko
-Marroko->Marokko
-Marylin->meist Marilyn
-Marytrium->Martyrium
-Märtyrium->Martyrium
-Maschiene->Maschine
-Maschienen->Maschinen
-mässig->mäßig
-mässige->mäßige
-mässigem->mäßigem
-mässigen->mäßigen
-mässiger->mäßiger
-mässiges->mäßiges
-Mass->Maß
-Massgabe->Maßgabe
-Massgaben->Maßgaben
-massgebend->maßgebend
-massgebende->maßgebende
-massgebendem->maßgebendem
-massgebenden->maßgebenden
-massgebender->maßgebender
-massgebendes->maßgebendes
-massgeblich->maßgeblich
-massgebliche->maßgebliche
-massgeblichem->maßgeblichem
-massgeblichen->maßgeblichen
-massgeblicher->maßgeblicher
-massgebliches->maßgebliches
-masslos->maßlos
-masslose->maßlose
-masslosen->maßlosen
-massloser->maßloser
-massloses->maßloses
-Massnahme->Maßnahme
-Massnahmen->Maßnahmen
-Matraze->Matratze
-Matritze->Matrize,Matrix
-Maximillian->meist Maximilian
-Medailie->Medaille
-Medaillie->Medaille
-Medailliengewinner->Medaillengewinner
-Medailliengewinnerin->Medaillengewinnerin
-Medallie->Medaille
-Medalliengewinner->Medaillengewinner
-Medalliengewinnerin->Medaillengewinnerin
-medizinsch->medizinisch
-medizisch->medizinisch
-medizische->medizinische
-medizischem->medizinischem
-medizischen->medizinischen
-medizischer->medizinischer
-medizisches->medizinisches
-Meerespiegel->Meeresspiegel
-Meeresspegel->Meeresspiegel
-mehere->mehrere
-meheren->mehreren
-meherer->mehrerer
-mehre->meist mehrere
-mehren->gelegentlich mehreren
-mehrer->häufig mehrerer,mehrere
-mehrerere->mehrere
-mehrtätige->mehrtägige
-meisst->meist
-meißt->meist
-meißten->meisten
-meißtens->meistens
-meistbesuchtesten->meistbesuchten
-meist gelesene*->meistgelesene*
-meist gesehene*->meistgesehene*
-meist gesuchte*->meistgesuchte*
-meits->meist
-mengemässig->mengenmäßig
-mengenmässig->mengenmäßig
-Mensche->Menschen
-Menscheit->Menschheit
-Menschens->Menschen
-Meßgerät->Messgerät
-Meßgeräte->Messgeräte
-Messystem->Messsystem
-Meßsystem->Messsystem
-Metallegierung->Metalllegierung
-Metereologe->Meteorologe
-Metereologie->Meteorologie
-metereologisch->meteorologisch
-Meterologie->Meteorologie
-meterologisch->meteorologisch
-Mettal->Metall
-mhd->mittelhochdeutsch
-Micheal->meist Michael
-Miglied->Mitglied
-Milionen->Millionen
-Militärdikatur->Militärdiktatur
-Millarde->Milliarde
-Millarden*->Milliarden*
-Millenium->Millennium
-Millione->Millionen
-Millitär->Militär
-millitärisch->militärisch
-eine Millionen->eine Million
-Millon->Million
-Millonen->Millionen
-Miltär->Militär
-miltärisch->militärisch
-Miltitär->Militär
-miltitärisch->militärisch
-minimalste->minimale
-minimalster->minimaler
-minimalstes->minimales
-Ministerpäsident->Ministerpräsident
-mit einander->miteinander
-Mitgleid->Mitglied
-mitlerweile->mittlerweile
-mittlerweilen->mittlerweile
-Mitlgiled->Mitglied
-Mitlied->Mitglied
-mit samt->mitsamt
-Mittelater->Mittelalter
-mittelaterlich->mittelalterlich
-mittelständige->mittelständische
-mittelständigen->mittelständischen
-mittelständiger->mittelständischer
-mittelständiges->mittelständisches
-Mitteralter->Mittelalter
-mitteralterlich->mittelalterlich
-Mitterand->Mitterrand
-Mittglied->Mitglied
-Mittschnitt->Mitschnitt
-mnachmal->manchmal
-Mobiletelefon->Mobiltelefon
-moeglich->möglich
-moegliche->mögliche
-moeglichen->möglichen
-moeglicher->möglicher
-moegliches->mögliches
-möglicht->möglich,möglichst
-mordern->modern
-morderne->moderne
-mordernen->modernen
-morderner->moderner
-mordernes->modernes
-morgentlich*->morgendlich*
-morgends->morgens
-muß->muss
-mußte->musste
-mußten->mussten
-Museeum->Museum
-mutmasslich->mutmaßlich
-mutmassliche->mutmaßliche
-mutmasslichem->mutmaßlichem
-mutmasslichen->mutmaßlichen
-mutmasslicher->mutmaßlicher
-mutmassliches->mutmaßliches
-nachdem Krieg->nach dem Krieg
-Nachkommens->Nachkommen
-nächst gelegene*->nächstgelegene*
-nächst größere*->nächstgrößere*
-nächst höhere*->nächsthöhere*
-nächst kleinere*->nächstkleinere*
-nächst niedrigere*->nächstniedrigere*
-nächst tiefere*->nächsttiefere*
-Nahaufname->Nahaufnahme
-nahegelegenste->nächstgelegene
-naheste->nächste
-nahesten->nächsten
-nähmlich->nämlich
-namenlich->namentlich
-namenslos->namenlos
-des Names->des Namens
-Namne->Namen
-narzistisch->narzisstisch
-Natiomnal*->National*
-Nazionalsoz*->Nationalsoz*
-nciht->nicht
-Nervösität->Nervosität
-nich->nicht
-die Niederlanden->die Niederlande
-niedersächisch->niedersächsisch
-niedersächsiche->niedersächsische
-niedersächsichen->niedersächsischen
-niedrieg->niedrig
-Niesche->Nische
-nihct->nicht
-nix->nichts
-nocheinmal->noch einmal
-nordeutsch->norddeutsch
-Nordeutschland->Norddeutschland
-nordlich->nördlich
-nördöstlich*->nordöstlich*
-nördwestlich*->nordwestlich*
-normanisch*->normannisch*
-notwenig*->notwendig*
-numehr->nunmehr
-Numerus Clausus->Numerus clausus
-objekiv->objektiv
-obrige->obige
-obrigen->obigen
-obriger->obiger
-offizell*->offiziell*
-Offizer->Offizier
-offiziel->offiziell
-offiziele*->offizielle*
-offziell->offiziell
-offzielle->offizielle
-ofiziell->offiziell
-Olympiamedaillie*->Olympiamedaille*
-Olympiamedallie*->Olympiamedaille*
-Olympische Bronzemedaille->olympische Bronzemedaille
-Olympische Goldmedaille->olympische Goldmedaille
-Olympische Silbermedaille->olympische Silbermedaille
-Omlett->Omelett
-optimalste->optimale
-optimalster->optimaler
-optimalstes->optimales
-Ordnug->Ordnung
-Ordung->Ordnung
-Orgeon->Oregon
-Organistion->Organisation
-Organsiation->Organisation
-organsich->organisch
-Organsisation->Organisation
-organisert->organisiert
-orginal->original
-orginale->originale
-orginalen->originalen
-orginell->originell
-orignal->original
-orignell->originell
-Orsteil->Ortsteil
-Orsteile->Ortsteile
-Ortteil->Ortsteil
-ouml->Ö/ö
-Overtüre->Ouvertüre
-öffenlich->öffentlich
-Ökö->Öko
-Östereich->Österreich
-Österrreich->Österreich
-Österreisch->Österreich
-östereichisch*->österreichisch*
-österreichich->österreichisch
-Packet->Paket
-palästinesisch->palästinensisch
-Palete->Palette
-Paleten->Paletten
-Pallete->Palette
-Palleten->Paletten
-Pallette->Palette
-Palletten->Paletten
-paralell->parallel
-Parcour->Parcours
-parralel->parallel
-parrallel->parallel
-Päsident->Präsident
-patroullieren->patrouillieren
-patroulliert->patrouilliert
-Pavillion->Pavillon
-Peleponnes*->Peloponnes*
-Pepperoni->Peperoni
-Perlmut->Perlmutt
-perönlich*->persönlich*
-persöhnlich*->persönlich*
-Persönlichleit->Persönlichkeit
-Philantrop*->Philanthrop*
-Philipinen->Philippinen
-Philipinisch->Philippinisch
-philipinischer->philippinischer
-Philippienen->Philippinen
-Philisoph->Philosoph
-Philisophie->Philosophie
-philisophisch->philosophisch
-Phillipinen->Philippinen
-Philosopie->Philosophie
-Philosph->Philosoph
-Philosphie->Philosophie
-philosphisch->philosophisch
-Philsophie->Philosophie
-philsophisch->philosophisch
-photografiert->fotografiert,photographiert
-piktoresk->pittoresk
-Planze->Pflanze
-Planzen*->Pflanzen*
-Politk->Politik
-Politker->Politiker
-politsch->politisch
-politsche->politische
-politschen->politischen
-politscher->politischer
-politsches->politisches
-poltisch*->politisch*
-portugiesich*->portugiesisch*
-Positon->Position
-postiv->positiv
-prinzipell*->prinzipiell*
-Prinzipen->Prinzipien
-Priveleg->Privileg
-priveligiert->privilegiert
-Priviligien*->Privilegien*
-priviligiert->privilegiert
-Progrom->Pogrom
-projezieren->projizieren
-projeziert->projiziert
-Prophezeihung*->Prophezeiung*
-Provinzhaupstadt->Provinzhauptstadt
-Prozeße->Prozesse
-Psychatrie->Psychiatrie
-pysikalisch->physikalisch
-Quattrologie->Tetralogie
-Ralley->Rallye
-Ralleyfahrer->Rallyefahrer
-rechlich->rechtlich
-Rechtsprache->Rechtssprache
-Rechtspruch->Rechtsspruch
-Rechtssprechung->Rechtsprechung
-Rechtstaat->Rechtsstaat
-rechtstaatlich->rechtsstaatlich
-rechtwinklich->rechtwinklig
-rechtwinkling->rechtwinklig
-rechzeitig->rechtzeitig
-Reeling->Reling
-Reflektion->Reflexion
-regelmässig->regelmäßig
-regelmässige->regelmäßige
-regelmässigen->regelmäßigen
-regelmässiger->regelmäßiger
-regelmässiges->regelmäßiges
-Reichtags*->Reichstags*
-Relgion*->Religion*
-relgiös->religiös
-Religiösität->Religiosität
-Religon->Religion
-Religonen->Religionen
-religös->religiös
-religösen->religiösen
-Relion->Religion
-reliösen->religiösen
-Remineszenz->Reminiszenz
-Rendevous->Rendezvous
-Rennaisance->Renaissance
-Rennaissance->Renaissance
-des Rennes->des Rennens
-Renomee->Renommee
-renomiert->renommiert
-Renomme->Renommee
-repäsentieren->repräsentieren
-repäsentiert->repräsentiert
-Reperatur->Reparatur
-Resourcen->Ressourcen
-Rhytmen->Rhythmen
-rhytmisch->rhythmisch
-rhytmische->rhythmische
-Rhytmus->Rhythmus
-Richtline->Richtlinie
-Richung->Richtung
-rigde->ridge
-rihgt->right
-Riskio->Risiko
-Risko->Risiko
-Rossevelt->Roosevelt
-Rückgrad->Rückgrat
-Rückrad->Rückgrat
-Rückrat->Rückgrat
-russich->russisch
-russiche->russische
-russichen->russischen
-russicher->russischer
-russsich->russisch
-russsisch->russisch
-russsische->russische
-russsischen->russischen
-Rythmen->Rhythmen
-rythmisch->rhythmisch
-rythmische->rhythmische
-Rythmus->Rhythmus
-sächisch->sächsisch
-sächsich->sächsisch
-sächsiche->sächsische
-sächsichen->sächsischen
-Santiago de Compostella->Santiago de Compostela
-Sarkopharg->Sarkophag
-sassen->saßen
-satzungsgemäss->satzungsgemäß
-S-Bahnstation->S-Bahn-Station
-schafte->schaffte
-Schaupiel*->Schauspiel*
-Scheiz->Schweiz
-schillernste*->schillerndste*
-schliessen->schließen
-schliesslich->schließlich
-schliesst->schließt
-Schrifsteller*->Schriftsteller*
-Schriftseller->Schriftsteller
-schweizer->Schweizer
-Seeman->Seemann
-seemänisch->seemännisch
-sehenwert->sehenswert
-Sehenwürdigkeit->Sehenswürdigkeit
-Sehenwürdigkeiten->Sehenswürdigkeiten
-seit dem->seitdem
-seit dem die->seitdem die
-seit dem ein->seitdem ein
-seit dem hat->seitdem hat
-seit dem ist->seitdem ist
-seit dem war->seitdem war
-seperat->separat
-seperate->separate
-seperatem->separatem
-seperaten->separaten
-Seperation->Separation
-Seperatist*->Separatist*
-Septmber->September
-Septmeber->September
-Seriösität->Seriosität
-sicher gestellt->sichergestellt
-sich er sich->er sich
-sicher stellen->sicherstellen
-sicher stellt*->sicherstellt*
-sicher zu stellen->sicherzustellen
-Silbermedaillie*->Silbermedaille*
-Silbermedallie*->Silbermedaille*
-Siluette->Silhouette
-sinvoll->sinnvoll
-Situtation->Situation
-Skagerak->Skagerrak
-sobald wie möglich->so bald wie möglich
-sobald als möglich->so bald als möglich
-sodas->sodass,so dass
-sodaß->sodass,so dass
-sogenante->sogenannte
-sogenanten->sogenannten
-sonder->sondern
-Souveranität->Souveränität
-soweit wie->so weit wie
-Sowietunion->Sowjetunion
-spezialiseren->spezialisieren
-spezialisert*->spezialisiert*
-speziel->speziell
-sponsorte->sponserte
-Spritualität->Spiritualität
-sprituell->spirituell
-Staatstreich->Staatsstreich
-Stadbild->Stadtbild
-Staddteil->Stadtteil
-Stadteil->Stadtteil
-Stadteile->Stadtteile
-Stadteilen->Stadtteilen
-Stadteils->Stadtteils
-Standart->Standard
-Standarts->Standards
-statt fand->stattfand
-statt finden->stattfinden
-statt findet->stattfindet
-statt gegeben->stattgegeben
-Stehgreif->Stegreif
-stellverteten->stellvertreten
-Stellverteter->Stellvertreter
-stiess->stieß
-Stimmulation->Stimulation
-Stömung->Strömung
-Stoss->Stoß
-stossen->stoßen
-Stossfänger->Stoßfänger
-Stossstange->Stoßstange
-stösst->stößt
-Strasse->Straße
-strukur*->struktur*
-subsummieren->subsumieren
-subsummiert->subsumiert
-sumieren->summieren
-sumiert->summiert
-svw->svw., bzw., so viel wie
-symetrisch->symmetrisch
-symphatisiert->sympathisiert
-Synomym->Synonym
-Synomyn->Synonym
-Syphon->Siphon
-Sytem->System
-Sytematik->Systematik
-sytematisch->systematisch
-Tag- und Nachtgleiche->Tagundnachtgleiche,Tag-und-Nacht-Gleiche
-Taiwanese->Taiwaner
-Taiwanesen->Taiwaner
-tasächlich->tatsächlich
-tatächlich->tatsächlich
-Teakwondo->Taekwondo
-teiweise->teilweise
-Temparatur->Temperatur
-tendentiell*->tendenziell*
-Terasse->Terrasse
-Terassen->Terrassen
-Terrabyte->Terabyte
-Tocher->Tochter
-Tolleranz->Toleranz
-tollerieren->tolerieren
-tolleriert->toleriert
-Tradion*->Tradition*
-traditionel->traditionell
-Traditon*->Tradition*
-Tradtion*->Tradition*
-Trainig*->Training*
-Transskript->Transkript
-Triologie->Trilogie
-Triumpf->Triumph
-trotzdessen->trotzdem
-trozdem->trotzdem
-Tryptichon->Triptychon
-Triptichon->Triptychon
-Tryptychon->Triptychon
-Tunier->Turnier
-Turismus->Tourismus
-Turist->Tourist
-U-Bahnnetz->U-Bahn-Netz
-U-Bahnstation->U-Bahn-Station
-U-Bahntunnel->U-Bahn-Tunnel
-überarbeitetet->überarbeitet
-überlegende->überlegene
-überlegenden->überlegenen
-überlicherweise->üblicherweise
-Überwachungstaat->Überwachungsstaat
-U-Bootkrieg->U-Boot-Krieg
-umbennen->umbenennen
-umbennenen->umbenennen
-umbennennen->umbenennen
-umbennant->umbenannt
-Umbennennung->Umbenennung
-Umbennenung->Umbenennung
-Umbennung->Umbenennung,Umnennung
-umd->und,um
-Umgangsprache->Umgangssprache
-umgangsprachlich->umgangssprachlich
-umgangsprachliche->umgangssprachliche
-umgangsprachlicher->umgangssprachlicher
-umgenannt->umbenannt
-umittelbar->unmittelbar
-umstrittend*->umstritten*
-umzubennen->umzubenennen,umzunennen
-Unabhängikeit->Unabhängigkeit
-Unabhängkeit->Unabhängigkeit
-unabhänig->unabhängig
-Unabhänigkeit->Unabhängigkeit
-unauthorisiert->unautorisiert
-unbenannt wurde->umbenannt wurde
-und sowie->und/sowie
-und und->und
-Unfang->Umfang
-ungekehrt->umgekehrt
-Univerität->Universität
-Universiät->Universität
-Universtät->Universität
-Universtität->Universität
-unsymetrisch->unsymmetrisch
-unteranderem->unter anderem
-Untergund->Untergrund
-Untericht->Unterricht
-unterichtet->unterrichtet
-unteriridisch->unterirdisch
-Unternehmes*->Unternehmens*
-Unternehms*->Unternehmens*
-unterstüzt->unterstützt
-Unterstüzung->Unterstützung
-Unversität->Universität
-unwegbar->unwägbar,unwegsam
-Urprung->Ursprung
-urprünglich*->ursprünglich*
-ürsprünglich*->ursprünglich*
-urspünglich*->ursprünglich*
-Ursurpator->Usurpator
-us-amerikanischen->US-amerikanischen,amerikanischen
-usprünglich*->ursprünglich*
-variert->variiert
-varrieren->variieren
-Vehrkehr*->Verkehr*
-Vekehr*->Verkehr*
-venezuelanisch*->venezolanisch*
-venizianisch*->venezianisch*
-verabeitet->verarbeitet
-Verabeitung*->Verarbeitung*
-veraltert*->veraltet*
-verantworlich*->verantwortlich*
-Veranwtortung->Verantwortung
-Verbauch*->Verbrauch*
-verbeitet*->verbreitet*
-Verbeitung*->Verbreitung*
-verbreiteste*->verbreitetste*
-verbreiteteste*->verbreitetste*
-vereingt*->vereinigt*
-vereiningt->vereinigt
-vergleichweise->vergleichsweise
-vergößert*->vergrößert*
-Vergößerung->Vergrößerung
-vergrössern->vergrößern
-vergrössert->vergrößert
-vergrösserte->vergrößerte
-vergrösserten->vergrößerten
-vergrösserter->vergrößerter
-Vergrösserung->Vergrößerung
-verhaeltnismaessig->verhältnismäßig
-verhältnismässig->verhältnismäßig
-verheiratetet->verheiratet
-verkündetet->verkündet
-verliess->verließ
-veröffendlicht->veröffentlicht
-Veröffendlichung->Veröffentlichung
-veröffentlich->veröffentlicht
-verplichtet->verpflichtet
-verschiedende*->verschiedene*
-verschiedendste*->verschiedenste*
-Verschleiss->Verschleiß
-verschohnen->verschonen
-verspühren->verspüren
-verspührt->verspürt
-Verständis->Verständnis
-Vertäge->Verträge
-vertaglich->vertraglich
-Verteidung->Verteidigung
-Verwaltungsitz->Verwaltungssitz
-Verwandschaft->Verwandtschaft
-verwandschaftlich*->verwandtschaftlich*
-Vetrag->Vertrag
-Veträge->Verträge
-vetraglich->vertraglich
-vetraut->vertraut
-vieleicht->vielleicht
-vom dem->von dem,vom
-vom der->von der,vom,der
-von einander->voneinander
-getrennt von einander->getrennt voneinander
-unabhängig von einander->unabhängig voneinander
-von einander entfernt->voneinander entfernt
-von einander getrennt->voneinander getrennt
-von einander unterscheiden->voneinander unterscheiden
-von einander unterschieden->voneinander unterschieden
-von einander zu->voneinander zu
-von nöten->vonnöten,z. B. vonnöten sein
-von statten->vonstatten
-von von->von
-vorallem->vor allem
-vorallen->vor allem
-vor allen in->vor allem in
-voran bringen->voranbringen
-Vorang->Vorrang
-voran gegangen*->vorangegangen*
-vorangig->vorrangig
-voran zu bringen->voranzubringen
-voran zu treiben->voranzutreiben
-Vorausetzung->Voraussetzung
-Vorausetzungen->Voraussetzungen
-voraus gegangen*->vorausgegangen*
-vorausichtlich->voraussichtlich
-Vorfahrens->Vorfahren
-Vorgesetze->Vorgesetzte
-vorkommene->vorkommende
-Vormachtsstellung->Vormachtstellung
-vorranging->vorrangig
-vorraus*->voraus*
-vorrüber*->vorüber*
-vorweg genommen*->vorweggenommen*
-Wachholder->Wacholder
-wachesen->wachsen
-währe->wäre
-währendessen->währenddessen
-wahr genommen->wahrgenommen
-Walfahrer->Wallfahrer
-Walfahrt->Wallfahrt
-Walfahrtskirche->Wallfahrtskirche
-Walfahrtsort->Wallfahrtsort
-wärend->während
-Warheit->Wahrheit
-warscheinlich->wahrscheinlich
-Webblog*->Weblog*
-Webpräsens->Webpräsenz
-Wehrmutstropfen->Wermutstropfen
-weiss->weiß
-Weisswein->Weißwein
-einem weiterem->einem weiteren
-im weiterem->im weiteren
-weiterere->weitere
-weitereren->weiteren
-weitesgehend->weitestgehend
-Weltanschaung->Weltanschauung
-Wepräsenz->Webpräsenz
-wesendlich->wesentlich
-im Wesentlichem->im Wesentlichen
-wichig->wichtig
-wichtigeste->wichtigste
-Widerstandkämpfer->Widerstandskämpfer
-widerum->wiederum
-Wiedererichtung->Wiedererrichtung
-wieder kehrend*->wiederkehrend*
-Wiedersacher->Widersacher
-wiedersetzen->widersetzen
-wiederspiegeln->widerspiegeln
-wiederspiegelt->widerspiegelt
-wiederspiegelte->widerspiegelte
-wiederspiegelten->widerspiegelten
-wiedersprechen->widersprechen
-wiedersprechend->widersprechend
-wiedersprechende->widersprechende
-Wiederspruch->Widerspruch
-Wiedersprüche->Widersprüche
-wiedersprüchlich->widersprüchlich
-wiedersprüchliche->widersprüchliche
-wiedersprüchlichen->widersprüchlichen
-Wiederstand->Widerstand
-Wiederstandskampf->Widerstandskampf
-wiederstehen->widerstehen
-wiederzuspiegeln->widerzuspiegeln
-Wihelm->Wilhelm
-Wikipeda->Wikipedia
-Wikpedia->Wikipedia
-wirtschaflich->wirtschaftlich
-wissenschaflich->wissenschaftlich
-wissenschafltich->wissenschaftlich
-Wissentschaft->Wissenschaft
-wissentschaftlich->wissenschaftlich
-Wochende->Wochenende
-woduch->wodurch
-Wolfang->Wolfgang
-wurd->wurde
-wurde wurde->wurde
-Würtemberg->Württemberg
-würtembergische->württembergische
-zahreich->zahlreich
-zeimlich->ziemlich
-der Zeit seines Lebens->der zeit seines Lebens
-er Zeit seines Lebens->er zeit seines Lebens
-sie Zeit ihres Lebens->sie zeit ihres Lebens
-war Zeit ihres Lebens->war zeit ihres Lebens
-war Zeit seines Lebens->war zeit seines Lebens
-zeitgenösisch->zeitgenössisch
-zeitgenössich->zeitgenössisch
-zerissen->zerrissen
-Ziffernblatt->Zifferblatt
-Zohne->Zone
-zu allererst->zuallererst
-zuammen->zusammen
-Zuammenhang->Zusammenhang
-zueigen->zu eigen
-zuende->zu Ende
-zu Folge->zufolge,zur Folge
-zufrieden geben->zufriedengeben
-zugrundeliegen->zugrunde liegen,zu Grunde liegen
-zugrundeliegt->zugrunde liegt,zu Grunde liegt
-zu letzt->zuletzt
-zum dem->zu dem,zum
-zum den->zu den,zu dem,zum
-zum erstem->zum ersten
-zumindestens->zumindest
-in zunehmenden Maße->in zunehmendem Maße
-mit zunehmenden Alter->mit zunehmendem Alter
-zunehmends->zunehmend
-zur der->zu der,zur
-zur dieser->zu dieser
-zur einem->zu einem
-zur einer->zu einer,zur
-zur ihr->zu ihr
-zur ihrem->zu ihrem
-zur ihren->zu ihren
-zur ihrer->zu ihrer,zur
-zur seiner->zu seiner,zur
-zurecht->zurecht
-zurecht finden->zurechtfinden
-zurecht kam->zurechtkam
-zurecht kommen->zurechtkommen
-zurecht kommt->zurechtkommt
-zurecht zu finden->zurechtzufinden
-zurecht zu kommen->zurechtzukommen
-zurfolge->zur Folge,zufolge
-zurück ge*->zurückge*
-zurück gegangen*->zurückgegangen*
-zurück blicken->zurückblicken
-zurück erobert->zurückerobert
-zurück ging->zurückging
-zurück greif*->zurückgreif*
-zurück kehrte->zurückkehrte
-zurück trat->zurücktrat
-zurück verfolgen->zurückverfolgen
-zurück verfolgt->zurückverfolgt
-zurück ziehen->zurückziehen
-zurück zog->zurückzog
-zurück zu bekommen->zurückzubekommen
-zurück zu bringen->zurückzubringen
-zurück zu drängen->zurückzudrängen
-zurück zu erobern->zurückzuerobern
-zurück zu führen->zurückzuführen
-zurück zuführen->zurückzuführen
-zurück zu gewinnen->zurückzugewinnen
-zurück zu holen->zurückzuholen
-zurück zu kehren->zurückzukehren
-zurück zu ziehen->zurückzuziehen
-zusamen->zusammen
-Zusamenhang->Zusammenhang
-zusammen arbeiten->zusammenarbeiten
-zusammen arbeitete->zusammenarbeitete
-zusammen arbeiteten->zusammenarbeiteten
-zusammen gearbeitet->zusammengearbeitet
-zusammen gefasst->zusammengefasst
-zusammen geschlossen*->zusammengeschlossen*
-zusammen schloss*->zusammenschloss*
-zusammen zu arbeiten->zusammenzuarbeiten
-zusammen zu schließen->zusammenzuschließen
-zusammmen->zusammen
-zusätlich->zusätzlich
-zusehens->zusehends
-zustandegekommen->zustande gekommen,zu Stande gekommen
-zustandekam->zustande kam,zu Stande kam
-zustandekommt->zustande kommt,zu Stande kommt
-zustätzlich->zusätzlich
-zu teil werden->zuteilwerden
-zu teil wird->zuteilwird
-zu teil wurde->zuteilwurde
-zu zu->zu,zuzu
-zu zuordnen*->zuzuordnen*
-zu zuwenden*->zuzuwenden*
-Zweidrittel->zwei Drittel
-Zweidrittel-Mehrheit->Zweidrittelmehrheit
-Zweiliga*->Zweitliga*
-dem zweitem->dem zweiten
-im zweitem->im zweiten
diff --git a/files/typos/typos-en.txt b/files/typos/typos-en.txt
deleted file mode 100644
index 74fbd089e..000000000
--- a/files/typos/typos-en.txt
+++ /dev/null
@@ -1,4576 +0,0 @@
-# This file contains a number of common English typos:
-andriod->android
-
-# The remainder of this file contains misspellings from
-# http://en.wikipedia.org/wiki/Wikipedia:Lists_of_common_misspellings/For_machines
-# plus some post-processing to fix invalid entries, remove duplicates, etc.
-#
-# The content is available under the
-# "Creative Commons Attribution-ShareAlike License"
-# http://creativecommons.org/licenses/by-sa/3.0/
-#
-# THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE
-# COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY
-# COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS
-# AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
-#
-# BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE
-# TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY
-# BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS
-# CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND
-# CONDITIONS.
-#
-# *1. Definitions*
-#
-# 1. *"Adaptation"* means a work based upon the Work, or upon the Work
-# and other pre-existing works, such as a translation, adaptation,
-# derivative work, arrangement of music or other alterations of a
-# literary or artistic work, or phonogram or performance and includes
-# cinematographic adaptations or any other form in which the Work may
-# be recast, transformed, or adapted including in any form
-# recognizably derived from the original, except that a work that
-# constitutes a Collection will not be considered an Adaptation for
-# the purpose of this License. For the avoidance of doubt, where the
-# Work is a musical work, performance or phonogram, the
-# synchronization of the Work in timed-relation with a moving image
-# ("synching") will be considered an Adaptation for the purpose of
-# this License.
-# 2. *"Collection"* means a collection of literary or artistic works,
-# such as encyclopedias and anthologies, or performances, phonograms
-# or broadcasts, or other works or subject matter other than works
-# listed in Section 1(f) below, which, by reason of the selection and
-# arrangement of their contents, constitute intellectual creations, in
-# which the Work is included in its entirety in unmodified form along
-# with one or more other contributions, each constituting separate and
-# independent works in themselves, which together are assembled into a
-# collective whole. A work that constitutes a Collection will not be
-# considered an Adaptation (as defined below) for the purposes of this
-# License.
-# 3. *"Creative Commons Compatible License"* means a license that is
-# listed at http://creativecommons.org/compatiblelicenses that has
-# been approved by Creative Commons as being essentially equivalent to
-# this License, including, at a minimum, because that license: (i)
-# contains terms that have the same purpose, meaning and effect as the
-# License Elements of this License; and, (ii) explicitly permits the
-# relicensing of adaptations of works made available under that
-# license under this License or a Creative Commons jurisdiction
-# license with the same License Elements as this License.
-# 4. *"Distribute"* means to make available to the public the original
-# and copies of the Work or Adaptation, as appropriate, through sale
-# or other transfer of ownership.
-# 5. *"License Elements"* means the following high-level license
-# attributes as selected by Licensor and indicated in the title of
-# this License: Attribution, ShareAlike.
-# 6. *"Licensor"* means the individual, individuals, entity or entities
-# that offer(s) the Work under the terms of this License.
-# 7. *"Original Author"* means, in the case of a literary or artistic
-# work, the individual, individuals, entity or entities who created
-# the Work or if no individual or entity can be identified, the
-# publisher; and in addition (i) in the case of a performance the
-# actors, singers, musicians, dancers, and other persons who act,
-# sing, deliver, declaim, play in, interpret or otherwise perform
-# literary or artistic works or expressions of folklore; (ii) in the
-# case of a phonogram the producer being the person or legal entity
-# who first fixes the sounds of a performance or other sounds; and,
-# (iii) in the case of broadcasts, the organization that transmits the
-# broadcast.
-# 8. *"Work"* means the literary and/or artistic work offered under the
-# terms of this License including without limitation any production in
-# the literary, scientific and artistic domain, whatever may be the
-# mode or form of its expression including digital form, such as a
-# book, pamphlet and other writing; a lecture, address, sermon or
-# other work of the same nature; a dramatic or dramatico-musical work;
-# a choreographic work or entertainment in dumb show; a musical
-# composition with or without words; a cinematographic work to which
-# are assimilated works expressed by a process analogous to
-# cinematography; a work of drawing, painting, architecture,
-# sculpture, engraving or lithography; a photographic work to which
-# are assimilated works expressed by a process analogous to
-# photography; a work of applied art; an illustration, map, plan,
-# sketch or three-dimensional work relative to geography, topography,
-# architecture or science; a performance; a broadcast; a phonogram; a
-# compilation of data to the extent it is protected as a copyrightable
-# work; or a work performed by a variety or circus performer to the
-# extent it is not otherwise considered a literary or artistic work.
-# 9. *"You"* means an individual or entity exercising rights under this
-# License who has not previously violated the terms of this License
-# with respect to the Work, or who has received express permission
-# from the Licensor to exercise rights under this License despite a
-# previous violation.
-# 10. *"Publicly Perform"* means to perform public recitations of the Work
-# and to communicate to the public those public recitations, by any
-# means or process, including by wire or wireless means or public
-# digital performances; to make available to the public Works in such
-# a way that members of the public may access these Works from a place
-# and at a place individually chosen by them; to perform the Work to
-# the public by any means or process and the communication to the
-# public of the performances of the Work, including by public digital
-# performance; to broadcast and rebroadcast the Work by any means
-# including signs, sounds or images.
-# 11. *"Reproduce"* means to make copies of the Work by any means
-# including without limitation by sound or visual recordings and the
-# right of fixation and reproducing fixations of the Work, including
-# storage of a protected performance or phonogram in digital form or
-# other electronic medium.
-#
-# *2. Fair Dealing Rights.* Nothing in this License is intended to reduce,
-# limit, or restrict any uses free from copyright or rights arising from
-# limitations or exceptions that are provided for in connection with the
-# copyright protection under copyright law or other applicable laws.
-#
-# *3. License Grant.* Subject to the terms and conditions of this License,
-# Licensor hereby grants You a worldwide, royalty-free, non-exclusive,
-# perpetual (for the duration of the applicable copyright) license to
-# exercise the rights in the Work as stated below:
-#
-# 1. to Reproduce the Work, to incorporate the Work into one or more
-# Collections, and to Reproduce the Work as incorporated in the
-# Collections;
-# 2. to create and Reproduce Adaptations provided that any such
-# Adaptation, including any translation in any medium, takes
-# reasonable steps to clearly label, demarcate or otherwise identify
-# that changes were made to the original Work. For example, a
-# translation could be marked "The original work was translated from
-# English to Spanish," or a modification could indicate "The original
-# work has been modified.";
-# 3. to Distribute and Publicly Perform the Work including as
-# incorporated in Collections; and,
-# 4. to Distribute and Publicly Perform Adaptations.
-# 5.
-#
-# For the avoidance of doubt:
-#
-# 1. *Non-waivable Compulsory License Schemes*. In those
-# jurisdictions in which the right to collect royalties through
-# any statutory or compulsory licensing scheme cannot be waived,
-# the Licensor reserves the exclusive right to collect such
-# royalties for any exercise by You of the rights granted under
-# this License;
-# 2. *Waivable Compulsory License Schemes*. In those jurisdictions in
-# which the right to collect royalties through any statutory or
-# compulsory licensing scheme can be waived, the Licensor waives
-# the exclusive right to collect such royalties for any exercise
-# by You of the rights granted under this License; and,
-# 3. *Voluntary License Schemes*. The Licensor waives the right to
-# collect royalties, whether individually or, in the event that
-# the Licensor is a member of a collecting society that
-# administers voluntary licensing schemes, via that society, from
-# any exercise by You of the rights granted under this License.
-#
-# The above rights may be exercised in all media and formats whether now
-# known or hereafter devised. The above rights include the right to make
-# such modifications as are technically necessary to exercise the rights
-# in other media and formats. Subject to Section 8(f), all rights not
-# expressly granted by Licensor are hereby reserved.
-#
-# *4. Restrictions.* The license granted in Section 3 above is expressly
-# made subject to and limited by the following restrictions:
-#
-# 1. You may Distribute or Publicly Perform the Work only under the terms
-# of this License. You must include a copy of, or the Uniform Resource
-# Identifier (URI) for, this License with every copy of the Work You
-# Distribute or Publicly Perform. You may not offer or impose any
-# terms on the Work that restrict the terms of this License or the
-# ability of the recipient of the Work to exercise the rights granted
-# to that recipient under the terms of the License. You may not
-# sublicense the Work. You must keep intact all notices that refer to
-# this License and to the disclaimer of warranties with every copy of
-# the Work You Distribute or Publicly Perform. When You Distribute or
-# Publicly Perform the Work, You may not impose any effective
-# technological measures on the Work that restrict the ability of a
-# recipient of the Work from You to exercise the rights granted to
-# that recipient under the terms of the License. This Section 4(a)
-# applies to the Work as incorporated in a Collection, but this does
-# not require the Collection apart from the Work itself to be made
-# subject to the terms of this License. If You create a Collection,
-# upon notice from any Licensor You must, to the extent practicable,
-# remove from the Collection any credit as required by Section 4(c),
-# as requested. If You create an Adaptation, upon notice from any
-# Licensor You must, to the extent practicable, remove from the
-# Adaptation any credit as required by Section 4(c), as requested.
-# 2. You may Distribute or Publicly Perform an Adaptation only under the
-# terms of: (i) this License; (ii) a later version of this License
-# with the same License Elements as this License; (iii) a Creative
-# Commons jurisdiction license (either this or a later license
-# version) that contains the same License Elements as this License
-# (e.g., Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons
-# Compatible License. If you license the Adaptation under one of the
-# licenses mentioned in (iv), you must comply with the terms of that
-# license. If you license the Adaptation under the terms of any of the
-# licenses mentioned in (i), (ii) or (iii) (the "Applicable License"),
-# you must comply with the terms of the Applicable License generally
-# and the following provisions: (I) You must include a copy of, or the
-# URI for, the Applicable License with every copy of each Adaptation
-# You Distribute or Publicly Perform; (II) You may not offer or impose
-# any terms on the Adaptation that restrict the terms of the
-# Applicable License or the ability of the recipient of the Adaptation
-# to exercise the rights granted to that recipient under the terms of
-# the Applicable License; (III) You must keep intact all notices that
-# refer to the Applicable License and to the disclaimer of warranties
-# with every copy of the Work as included in the Adaptation You
-# Distribute or Publicly Perform; (IV) when You Distribute or Publicly
-# Perform the Adaptation, You may not impose any effective
-# technological measures on the Adaptation that restrict the ability
-# of a recipient of the Adaptation from You to exercise the rights
-# granted to that recipient under the terms of the Applicable License.
-# This Section 4(b) applies to the Adaptation as incorporated in a
-# Collection, but this does not require the Collection apart from the
-# Adaptation itself to be made subject to the terms of the Applicable
-# License.
-# 3. If You Distribute, or Publicly Perform the Work or any Adaptations
-# or Collections, You must, unless a request has been made pursuant to
-# Section 4(a), keep intact all copyright notices for the Work and
-# provide, reasonable to the medium or means You are utilizing: (i)
-# the name of the Original Author (or pseudonym, if applicable) if
-# supplied, and/or if the Original Author and/or Licensor designate
-# another party or parties (e.g., a sponsor institute, publishing
-# entity, journal) for attribution ("Attribution Parties") in
-# Licensor's copyright notice, terms of service or by other reasonable
-# means, the name of such party or parties; (ii) the title of the Work
-# if supplied; (iii) to the extent reasonably practicable, the URI, if
-# any, that Licensor specifies to be associated with the Work, unless
-# such URI does not refer to the copyright notice or licensing
-# information for the Work; and (iv) , consistent with Ssection 3(b),
-# in the case of an Adaptation, a credit identifying the use of the
-# Work in the Adaptation (e.g., "French translation of the Work by
-# Original Author," or "Screenplay based on original Work by Original
-# Author"). The credit required by this Section 4(c) may be
-# implemented in any reasonable manner; provided, however, that in the
-# case of a Adaptation or Collection, at a minimum such credit will
-# appear, if a credit for all contributing authors of the Adaptation
-# or Collection appears, then as part of these credits and in a manner
-# at least as prominent as the credits for the other contributing
-# authors. For the avoidance of doubt, You may only use the credit
-# required by this Section for the purpose of attribution in the
-# manner set out above and, by exercising Your rights under this
-# License, You may not implicitly or explicitly assert or imply any
-# connection with, sponsorship or endorsement by the Original Author,
-# Licensor and/or Attribution Parties, as appropriate, of You or Your
-# use of the Work, without the separate, express prior written
-# permission of the Original Author, Licensor and/or Attribution Parties.
-# 4. Except as otherwise agreed in writing by the Licensor or as may be
-# otherwise permitted by applicable law, if You Reproduce, Distribute
-# or Publicly Perform the Work either by itself or as part of any
-# Adaptations or Collections, You must not distort, mutilate, modify
-# or take other derogatory action in relation to the Work which would
-# be prejudicial to the Original Author's honor or reputation.
-# Licensor agrees that in those jurisdictions (e.g. Japan), in which
-# any exercise of the right granted in Section 3(b) of this License
-# (the right to make Adaptations) would be deemed to be a distortion,
-# mutilation, modification or other derogatory action prejudicial to
-# the Original Author's honor and reputation, the Licensor will waive
-# or not assert, as appropriate, this Section, to the fullest extent
-# permitted by the applicable national law, to enable You to
-# reasonably exercise Your right under Section 3(b) of this License
-# (right to make Adaptations) but not otherwise.
-#
-# *5. Representations, Warranties and Disclaimer*
-#
-# UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR
-# OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY
-# KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE,
-# INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY,
-# FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF
-# LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS,
-# WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE
-# EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.
-#
-# *6. Limitation on Liability.* EXCEPT TO THE EXTENT REQUIRED BY
-# APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL
-# THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY
-# DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF
-# LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-#
-# *7. Termination*
-#
-# 1. This License and the rights granted hereunder will terminate
-# automatically upon any breach by You of the terms of this License.
-# Individuals or entities who have received Adaptations or Collections
-# from You under this License, however, will not have their licenses
-# terminated provided such individuals or entities remain in full
-# compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will
-# survive any termination of this License.
-# 2. Subject to the above terms and conditions, the license granted here
-# is perpetual (for the duration of the applicable copyright in the
-# Work). Notwithstanding the above, Licensor reserves the right to
-# release the Work under different license terms or to stop
-# distributing the Work at any time; provided, however that any such
-# election will not serve to withdraw this License (or any other
-# license that has been, or is required to be, granted under the terms
-# of this License), and this License will continue in full force and
-# effect unless terminated as stated above.
-#
-# *8. Miscellaneous*
-#
-# 1. Each time You Distribute or Publicly Perform the Work or a
-# Collection, the Licensor offers to the recipient a license to the
-# Work on the same terms and conditions as the license granted to You
-# under this License.
-# 2. Each time You Distribute or Publicly Perform an Adaptation, Licensor
-# offers to the recipient a license to the original Work on the same
-# terms and conditions as the license granted to You under this License.
-# 3. If any provision of this License is invalid or unenforceable under
-# applicable law, it shall not affect the validity or enforceability
-# of the remainder of the terms of this License, and without further
-# action by the parties to this agreement, such provision shall be
-# reformed to the minimum extent necessary to make such provision
-# valid and enforceable.
-# 4. No term or provision of this License shall be deemed waived and no
-# breach consented to unless such waiver or consent shall be in
-# writing and signed by the party to be charged with such waiver or
-# consent.
-# 5. This License constitutes the entire agreement between the parties
-# with respect to the Work licensed here. There are no understandings,
-# agreements or representations with respect to the Work not specified
-# here. Licensor shall not be bound by any additional provisions that
-# may appear in any communication from You. This License may not be
-# modified without the mutual written agreement of the Licensor and You.
-# 6. The rights granted under, and the subject matter referenced, in this
-# License were drafted utilizing the terminology of the Berne
-# Convention for the Protection of Literary and Artistic Works (as
-# amended on September 28, 1979), the Rome Convention of 1961, the
-# WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms
-# Treaty of 1996 and the Universal Copyright Convention (as revised on
-# July 24, 1971). These rights and subject matter take effect in the
-# relevant jurisdiction in which the License terms are sought to be
-# enforced according to the corresponding provisions of the
-# implementation of those treaty provisions in the applicable national
-# law. If the standard suite of rights granted under applicable
-# copyright law includes additional rights not granted under this
-# License, such additional rights are deemed to be included in the
-# License; this License is not intended to restrict the license of any
-# rights under applicable law.
-
-abandonned->abandoned
-aberation->aberration
-abilties->abilities
-abilty->ability
-abondon->abandon
-abbout->about
-abotu->about
-abouta->about a
-aboutit->about it
-aboutthe->about the
-abscence->absence
-abondoned->abandoned
-abondoning->abandoning
-abondons->abandons
-aborigene->aborigine
-accesories->accessories
-accidant->accident
-abortificant->abortifacient
-abreviate->abbreviate
-abreviated->abbreviated
-abreviation->abbreviation
-abritrary->arbitrary
-absail->abseil
-absailing->abseiling
-absense->absence
-absolutly->absolutely
-absorbsion->absorption
-absorbtion->absorption
-abudance->abundance
-abundacies->abundances
-abundancies->abundances
-abundunt->abundant
-abutts->abuts
-acadamy->academy
-acadmic->academic
-accademic->academic
-accademy->academy
-acccused->accused
-accelleration->acceleration
-accension->accession, ascension
-acceptence->acceptance
-acceptible->acceptable
-accessable->accessible
-accidentaly->accidentally
-accidently->accidentally
-acclimitization->acclimatization
-accomadate->accommodate
-accomadated->accommodated
-accomadates->accommodates
-accomadating->accommodating
-accomadation->accommodation
-accomadations->accommodations
-accomdate->accommodate
-accomodate->accommodate
-accomodated->accommodated
-accomodates->accommodates
-accomodating->accommodating
-accomodation->accommodation
-accomodations->accommodations
-accompanyed->accompanied
-accordeon->accordion
-accordian->accordion
-accoring->according
-accoustic->acoustic
-accquainted->acquainted
-accrediation->accreditation
-accredidation->accreditation
-accross->across
-accussed->accused
-acedemic->academic
-acheive->achieve
-acheived->achieved
-acheivement->achievement
-acheivements->achievements
-acheives->achieves
-acheiving->achieving
-acheivment->achievement
-acheivments->achievements
-achievment->achievement
-achievments->achievements
-achive->achieve, archive
-achived->achieved, archived
-achivement->achievement
-achivements->achievements
-acknowldeged->acknowledged
-acknowledgeing->acknowledging
-ackward->awkward, backward
-acommodate->accommodate
-acomplish->accomplish
-acomplished->accomplished
-acomplishment->accomplishment
-acomplishments->accomplishments
-acording->according
-acordingly->accordingly
-acquaintence->acquaintance
-acquaintences->acquaintances
-acquiantence->acquaintance
-acquiantences->acquaintances
-acquited->acquitted
-activites->activities
-activly->actively
-actualy->actually
-acuracy->accuracy
-acused->accused
-acustom->accustom
-acustommed->accustomed
-adavanced->advanced
-adbandon->abandon
-addional->additional
-addionally->additionally
-additinally->additionally
-additionaly->additionally
-additonal->additional
-additonally->additionally
-addmission->admission
-addopt->adopt
-addopted->adopted
-addoptive->adoptive
-addres->address, adders
-addresable->addressable
-addresed->addressed
-addresing->addressing
-addressess->addresses
-addtion->addition
-addtional->additional
-adecuate->adequate
-adequit->adequate
-adhearing->adhering
-adherance->adherence
-admendment->amendment
-admininistrative->administrative
-adminstered->administered
-adminstrate->administrate
-adminstration->administration
-adminstrative->administrative
-adminstrator->administrator
-admissability->admissibility
-admissable->admissible
-admited->admitted
-admitedly->admittedly
-adn->and
-adolecent->adolescent
-adquire->acquire
-adquired->acquired
-adquires->acquires
-adquiring->acquiring
-adres->address
-adresable->addressable
-adresing->addressing
-adress->address
-adressable->addressable
-adressed->addressed
-adressing->addressing, dressing
-adventrous->adventurous
-advertisment->advertisement
-advertisments->advertisements
-advesary->adversary
-adviced->advised
-aeriel->aerial
-aeriels->aerials
-afair->affair
-afficianados->aficionados
-afficionado->aficionado
-afficionados->aficionados
-affilate->affiliate
-affilliate->affiliate
-affort->afford, effort
-aforememtioned->aforementioned
-againnst->against
-agains->against
-agaisnt->against
-aganist->against
-aggaravates->aggravates
-aggreed->agreed
-aggreement->agreement
-aggregious->egregious
-aggresive->aggressive
-agian->again
-agianst->against
-agin->again
-agina->again, angina
-aginst->against
-agravate->aggravate
-agre->agree
-agred->agreed
-agreeement->agreement
-agreemnt->agreement
-agregate->aggregate
-agregates->aggregates
-agreing->agreeing
-agression->aggression
-agressive->aggressive
-agressively->aggressively
-agressor->aggressor
-agricultue->agriculture
-agriculure->agriculture
-agricuture->agriculture
-agrieved->aggrieved
-ahev->have
-ahppen->happen
-ahve->have
-aicraft->aircraft
-aiport->airport
-airbourne->airborne
-aircaft->aircraft
-aircrafts->aircraft
-airporta->airports
-airrcraft->aircraft
-aisian->asian
-albiet->albeit
-alchohol->alcohol
-alchoholic->alcoholic
-alchol->alcohol
-alcholic->alcoholic
-alcohal->alcohol
-alcoholical->alcoholic
-aledge->allege
-aledged->alleged
-aledges->alleges
-alege->allege
-aleged->alleged
-alegience->allegiance
-algebraical->algebraic
-algorhitms->algorithms
-algoritm->algorithm
-algoritms->algorithms
-alientating->alienating
-alledge->allege
-alledged->alleged
-alledgedly->allegedly
-alledges->alleges
-allegedely->allegedly
-allegedy->allegedly
-allegely->allegedly
-allegence->allegiance
-allegience->allegiance
-allign->align
-alligned->aligned
-alliviate->alleviate
-allopone->allophone
-allopones->allophones
-allready->already
-allthough->although
-alltime->all-time
-alltogether->altogether
-almsot->almost
-alochol->alcohol
-alomst->almost
-alot->a lot, allot
-alotted->allotted
-alowed->allowed
-alowing->allowing
-alreayd->already
-alse->else
-alsot->also
-alternitives->alternatives
-altho->although
-althought->although
-altough->although
-alusion->allusion, illusion
-alwasy->always
-alwyas->always
-amalgomated->amalgamated
-amatuer->amateur
-amature->armature, amateur
-amendmant->amendment
-Amercia->America
-amerliorate->ameliorate
-amke->make
-amking->making
-ammend->amend
-ammended->amended
-ammendment->amendment
-ammendments->amendments
-ammount->amount
-ammused->amused
-amoung->among
-amoungst->amongst
-amung->among
-amunition->ammunition
-analagous->analogous
-analitic->analytic
-analogeous->analogous
-anarchim->anarchism
-anarchistm->anarchism
-anbd->and
-ancestory->ancestry
-ancilliary->ancillary
-andd->and
-androgenous->androgynous
-androgeny->androgyny
-anihilation->annihilation
-aniversary->anniversary
-annoint->anoint
-annointed->anointed
-annointing->anointing
-annoints->anoints
-annouced->announced
-annualy->annually
-annuled->annulled
-anohter->another
-anomolies->anomalies
-anomolous->anomalous
-anomoly->anomaly
-anonimity->anonymity
-anounced->announced
-anouncement->announcement
-ansalisation->nasalisation
-ansalization->nasalization
-ansestors->ancestors
-antartic->antarctic
-anthromorphization->anthropomorphization
-anthropolgist->anthropologist
-anthropolgy->anthropology
-anual->annual
-anulled->annulled
-anwsered->answered
-anyhwere->anywhere
-anyother->any other
-anytying->anything
-aparent->apparent
-aparment->apartment
-apenines->apennines, Apennines
-aplication->application
-aplied->applied
-apolegetics->apologetics
-apon->upon, apron
-apparant->apparent
-apparantly->apparently
-appart->apart
-appartment->apartment
-appartments->apartments
-appealling->appealing, appalling
-appeareance->appearance
-appearence->appearance
-appearences->appearances
-appenines->apennines, Apennines
-apperance->appearance
-apperances->appearances
-appereance->appearance
-appereances->appearances
-applicaiton->application
-applicaitons->applications
-appologies->apologies
-appology->apology
-apprearance->appearance
-apprieciate->appreciate
-approachs->approaches
-appropiate->appropriate
-appropraite->appropriate
-appropropiate->appropriate
-approproximate->approximate
-approxamately->approximately
-approxiately->approximately
-approximitely->approximately
-aprehensive->apprehensive
-apropriate->appropriate
-aproval->approval
-aproximate->approximate
-aproximately->approximately
-aquaduct->aqueduct
-aquaintance->acquaintance
-aquainted->acquainted
-aquiantance->acquaintance
-aquire->acquire
-aquired->acquired
-aquiring->acquiring
-aquisition->acquisition
-aquitted->acquitted
-aranged->arranged
-arangement->arrangement
-arbitarily->arbitrarily
-arbitary->arbitrary
-archaelogical->archaeological
-archaelogists->archaeologists
-archaelogy->archaeology
-archaoelogy->archeology, archaeology
-archaology->archeology, archaeology
-archeaologist->archeologist, archaeologist
-archeaologists->archeologists, archaeologists
-archetect->architect
-archetects->architects
-archetectural->architectural
-archetecturally->architecturally
-archetecture->architecture
-archiac->archaic
-archictect->architect
-archimedian->archimedean
-architecht->architect
-architechturally->architecturally
-architechture->architecture
-architechtures->architectures
-architectual->architectural
-archtype->archetype
-archtypes->archetypes
-aready->already
-areodynamics->aerodynamics
-argubly->arguably
-arguement->argument
-arguements->arguments
-arised->arose
-arival->arrival
-armamant->armament
-armistace->armistice
-arogant->arrogant
-arogent->arrogant
-aroud->around
-arrangment->arrangement
-arrangments->arrangements
-arrengement->arrangement
-arrengements->arrangements
-arround->around
-artcile->article
-artical->article
-artice->article
-articel->article
-artifical->artificial
-artifically->artificially
-artillary->artillery
-arund->around
-asetic->ascetic
-asfar->as far
-asign->assign
-aslo->also
-asociated->associated
-asorbed->absorbed
-asphyxation->asphyxiation
-assasin->assassin
-assasinate->assassinate
-assasinated->assassinated
-assasinates->assassinates
-assasination->assassination
-assasinations->assassinations
-assasined->assassinated
-assasins->assassins
-assassintation->assassination
-assemple->assemble
-assertation->assertion
-asside->aside
-assisnate->assassinate
-assit->assist
-assitant->assistant
-assocation->association
-assoicate->associate
-assoicated->associated
-assoicates->associates
-assosication->assassination
-asssassans->assassins
-assualt->assault
-assualted->assaulted
-assymetric->asymmetric
-assymetrical->asymmetrical
-asteriod->asteroid
-asthetic->aesthetic
-asthetical->aesthetical
-asthetically->aesthetically
-asume->assume
-aswell->as well
-atain->attain
-atempting->attempting
-atheistical->atheistic
-athenean->athenian
-atheneans->athenians
-athiesm->atheism
-athiest->atheist
-atorney->attorney
-atribute->attribute
-atributed->attributed
-atributes->attributes
-attaindre->attainder, attained
-attemp->attempt
-attemped->attempted
-attemt->attempt
-attemted->attempted
-attemting->attempting
-attemts->attempts
-attendence->attendance
-attendent->attendant
-attendents->attendants
-attened->attended
-attension->attention
-attitide->attitude
-attributred->attributed
-attrocities->atrocities
-audeince->audience
-auromated->automated
-austrailia->Australia
-austrailian->Australian
-auther->author
-authobiographic->autobiographic
-authobiography->autobiography
-authorative->authoritative
-authorites->authorities
-authorithy->authority
-authoritiers->authorities
-authoritive->authoritative
-authrorities->authorities
-autochtonous->autochthonous
-autoctonous->autochthonous
-automaticly->automatically
-automibile->automobile
-automonomous->autonomous
-autor->author
-autority->authority
-auxilary->auxiliary
-auxillaries->auxiliaries
-auxillary->auxiliary
-auxilliaries->auxiliaries
-auxilliary->auxiliary
-availabe->available
-availablity->availability
-availaible->available
-availble->available
-availiable->available
-availible->available
-avalable->available
-avalance->avalanche
-avaliable->available
-avation->aviation
-avengence->a vengeance
-averageed->averaged
-avilable->available
-awared->awarded
-awya->away
-azn->asian
-baceause->because
-backgorund->background
-backrounds->backgrounds
-bakc->back
-banannas->bananas
-bandwith->bandwidth
-bankrupcy->bankruptcy
-banruptcy->bankruptcy
-baout->about, bout
-basicaly->basically
-basicly->basically
-bcak->back
-beachead->beachhead
-beacuse->because
-beastiality->bestiality
-beatiful->beautiful
-beaurocracy->bureaucracy
-beaurocratic->bureaucratic
-beautyfull->beautiful
-becamae->became
-becames->becomes, became
-becasue->because
-beccause->because
-becomeing->becoming
-becomming->becoming
-becouse->because
-becuase->because
-bedore->before
-beeing->being
-befoer->before
-beggin->begin, begging
-begginer->beginner
-begginers->beginners
-beggining->beginning
-begginings->beginnings
-beggins->begins
-begining->beginning
-beginnig->beginning
-behavour->behavior, behaviour
-beleagured->beleaguered
-beleif->belief
-beleive->believe
-beleived->believed
-beleives->believes
-beleiving->believing
-beligum->belgium
-belive->believe
-belived->believed, beloved
-belives->believes, beliefs
-belligerant->belligerent
-bellweather->bellwether
-bemusemnt->bemusement
-beneficary->beneficiary
-beng->being
-benificial->beneficial
-benifit->benefit
-benifits->benefits
-bergamont->bergamot
-Bernouilli->Bernoulli
-beseige->besiege
-beseiged->besieged
-beseiging->besieging
-beteen->between
-betwen->between
-beween->between
-bewteen->between
-bilateraly->bilaterally
-billingualism->bilingualism
-binominal->binomial
-bizzare->bizarre
-blaim->blame
-blaimed->blamed
-blessure->blessing
-Blitzkreig->Blitzkrieg
-boaut->bout, boat, about
-bodydbuilder->bodybuilder
-bombardement->bombardment
-bombarment->bombardment
-bondary->boundary
-Bonnano->Bonanno
-borke->broke
-boundry->boundary
-bouyancy->buoyancy
-bouyant->buoyant
-boyant->buoyant
-Brasillian->Brazilian
-breakthough->breakthrough
-breakthroughts->breakthroughs
-breif->brief
-breifly->briefly
-brethen->brethren
-bretheren->brethren
-briliant->brilliant
-brillant->brilliant
-brimestone->brimstone
-Britian->Britain
-Brittish->British
-broacasted->broadcast
-broadacasting->broadcasting
-broady->broadly
-Buddah->Buddha
-Buddist->Buddhist
-buisness->business
-buisnessman->businessman
-buoancy->buoyancy
-buring->burying, burning, burin, during
-burried->buried
-busines->business
-busineses->business, businesses
-busness->business
-bussiness->business
-caculater->calculator
-cacuses->caucuses
-cahracters->characters
-calaber->caliber
-calander->calendar, calender, colander
-calculater->calculator
-calculs->calculus
-calenders->calendars
-caligraphy->calligraphy
-caluclate->calculate
-caluclated->calculated
-caluculate->calculate
-caluculated->calculated
-calulate->calculate
-calulated->calculated
-calulater->calculator
-Cambrige->Cambridge
-camoflage->camouflage
-campain->campaign
-campains->campaigns
-candadate->candidate
-candiate->candidate
-candidiate->candidate
-cannister->canister
-cannisters->canisters
-cannnot->cannot
-cannonical->canonical
-cannotation->connotation
-cannotations->connotations
-cant->cannot, can not, can't
-caost->coast
-caperbility->capability
-Capetown->Cape Town
-capible->capable
-captial->capital
-captued->captured
-capturd->captured
-carachter->character
-caracterized->characterized
-carcas->carcass, Caracas
-carefull->careful
-careing->caring
-carismatic->charismatic
-Carmalite->Carmelite
-Carnagie->Carnegie
-Carnagie-Mellon->Carnegie-Mellon
-carnege->carnage, Carnegie
-carnige->carnage, Carnegie
-Carnigie->Carnegie
-Carnigie-Mellon->Carnegie-Mellon
-carniverous->carnivorous
-carreer->career
-carrers->careers
-Carribbean->Caribbean
-Carribean->Caribbean
-cartdridge->cartridge
-Carthagian->Carthaginian
-carthographer->cartographer
-cartilege->cartilage
-cartilidge->cartilage
-cartrige->cartridge
-casette->cassette
-casion->caisson
-cassawory->cassowary
-cassowarry->cassowary
-casue->cause
-casued->caused
-casues->causes
-casuing->causing
-casulaties->casualties
-casulaty->casualty
-catagories->categories
-catagorized->categorized
-catagory->category
-Cataline->Catiline, Catalina
-catapillar->caterpillar
-catapillars->caterpillars
-catapiller->caterpillar
-catapillers->caterpillars
-catepillar->caterpillar
-catepillars->caterpillars
-catergorize->categorize
-catergorized->categorized
-caterpilar->caterpillar
-caterpilars->caterpillars
-caterpiller->caterpillar
-caterpillers->caterpillars
-cathlic->catholic
-catholocism->catholicism
-catterpilar->caterpillar
-catterpilars->caterpillars
-catterpillar->caterpillar
-catterpillars->caterpillars
-cattleship->battleship
-causalities->casualties
-Ceasar->Caesar
-Celcius->Celsius
-cellpading->cellpadding
-cementary->cemetery
-cemetarey->cemetery
-cemetaries->cemeteries
-cemetary->cemetery
-cencus->census
-censur->censor, censure
-cententenial->centennial
-centruies->centuries
-centruy->century
-centuties->centuries
-centuty->century
-ceratin->certain, keratin
-cerimonial->ceremonial
-cerimonies->ceremonies
-cerimonious->ceremonious
-cerimony->ceremony
-ceromony->ceremony
-certainity->certainty
-certian->certain
-cervial->cervical, servile, serval
-chalenging->challenging
-challange->challenge
-challanged->challenged
-challege->challenge
-Champange->Champagne
-changable->changeable
-charachter->character
-charachters->characters
-charactersistic->characteristic
-charactor->character
-charactors->characters
-charasmatic->charismatic
-charaterized->characterized
-chariman->chairman
-charistics->characteristics
-chasr->chaser, chase
-cheif->chief
-cheifs->chiefs
-chemcial->chemical
-chemcially->chemically
-chemestry->chemistry
-chemicaly->chemically
-childbird->childbirth
-childen->children
-choosen->chosen
-chracter->character
-chuch->church
-churchs->churches
-Cincinatti->Cincinnati
-Cincinnatti->Cincinnati
-circulaton->circulation
-circumsicion->circumcision
-circut->circuit
-ciricuit->circuit
-ciriculum->curriculum
-civillian->civilian
-claer->clear
-claerer->clearer
-claerly->clearly
-claimes->claims
-clas->class
-clasic->classic
-clasical->classical
-clasically->classically
-cleareance->clearance
-clera->clear, sclera
-clincial->clinical
-clinicaly->clinically
-cmo->com
-cmoputer->computer
-co-incided->coincided
-coctail->cocktail
-coform->conform
-cognizent->cognizant
-coincedentally->coincidentally
-colaborations->collaborations
-colateral->collateral
-colelctive->collective
-collaberative->collaborative
-collecton->collection
-collegue->colleague
-collegues->colleagues
-collonade->colonnade
-collonies->colonies
-collony->colony
-collosal->colossal
-colonizators->colonizers
-comander->commander, commandeer
-comando->commando
-comandos->commandos
-comany->company
-comapany->company
-comback->comeback
-combanations->combinations
-combinatins->combinations
-combusion->combustion
-comdemnation->condemnation
-comemmorates->commemorates
-comemoretion->commemoration
-comision->commission
-comisioned->commissioned
-comisioner->commissioner
-comisioning->commissioning
-comisions->commissions
-comission->commission
-comissioned->commissioned
-comissioner->commissioner
-comissioning->commissioning
-comissions->commissions
-comited->committed
-comiting->committing
-comitted->committed
-comittee->committee
-comitting->committing
-commandoes->commandos
-commedic->comedic
-commemerative->commemorative
-commemmorate->commemorate
-commemmorating->commemorating
-commerical->commercial
-commerically->commercially
-commericial->commercial
-commericially->commercially
-commerorative->commemorative
-comming->coming
-comminication->communication
-commision->commission
-commisioned->commissioned
-commisioner->commissioner
-commisioning->commissioning
-commisions->commissions
-commited->committed
-commitee->committee
-commiting->committing
-committe->committee
-committment->commitment
-committments->commitments
-commmemorated->commemorated
-commongly->commonly
-commonweath->commonwealth
-commuications->communications
-commuinications->communications
-communciation->communication
-communiation->communication
-communites->communities
-compability->compatibility
-comparision->comparison
-comparisions->comparisons
-comparitive->comparative
-comparitively->comparatively
-compatabilities->compatibilities
-compatability->compatibility
-compatable->compatible
-compatablities->compatibilities
-compatablity->compatibility
-compatiable->compatible
-compatiblities->compatibilities
-compatiblity->compatibility
-compeitions->competitions
-compensantion->compensation
-competance->competence
-competant->competent
-competative->competitive
-competion->competition, completion
-competitiion->competition
-competive->competitive
-competiveness->competitiveness
-comphrehensive->comprehensive
-compitent->competent
-completedthe->completed the
-completelyl->completely
-completetion->completion
-complier->compiler
-componant->component
-comprable->comparable
-comprimise->compromise
-compulsary->compulsory
-compulsery->compulsory
-computarized->computerized
-concensus->consensus
-concider->consider
-concidered->considered
-concidering->considering
-conciders->considers
-concieted->conceited
-concieved->conceived
-concious->conscious
-conciously->consciously
-conciousness->consciousness
-condamned->condemned
-condemmed->condemned
-condidtion->condition
-condidtions->conditions
-conditionsof->conditions of
-conected->connected
-conection->connection
-conesencus->consensus
-confidental->confidential
-confidentally->confidentially
-confids->confides
-configureable->configurable
-confortable->comfortable
-congradulations->congratulations
-congresional->congressional
-conived->connived
-conjecutre->conjecture
-conjuction->conjunction
-Conneticut->Connecticut
-conotations->connotations
-conquerd->conquered
-conquerer->conqueror
-conquerers->conquerors
-conqured->conquered
-conscent->consent
-consciouness->consciousness
-consdider->consider
-consdidered->considered
-consdiered->considered
-consectutive->consecutive
-consenquently->consequently
-consentrate->concentrate
-consentrated->concentrated
-consentrates->concentrates
-consept->concept
-consequentually->consequently
-consequeseces->consequences
-consern->concern
-conserned->concerned
-conserning->concerning
-conservitive->conservative
-consiciousness->consciousness
-consicousness->consciousness
-considerd->considered
-consideres->considered
-consious->conscious
-consistant->consistent
-consistantly->consistently
-consituencies->constituencies
-consituency->constituency
-consituted->constituted
-consitution->constitution
-consitutional->constitutional
-consolodate->consolidate
-consolodated->consolidated
-consonent->consonant
-consonents->consonants
-consorcium->consortium
-conspiracys->conspiracies
-conspiriator->conspirator
-constaints->constraints
-constanly->constantly
-constarnation->consternation
-constatn->constant
-constinually->continually
-constituant->constituent
-constituants->constituents
-constituion->constitution
-constituional->constitutional
-consttruction->construction
-constuction->construction
-contstruction->construction
-consulant->consultant
-consumate->consummate
-consumated->consummated
-contaiminate->contaminate
-containes->contains
-contamporaries->contemporaries
-contamporary->contemporary
-contempoary->contemporary
-contemporaneus->contemporaneous
-contempory->contemporary
-contendor->contender
-contibute->contribute
-contibuted->contributed
-contibutes->contributes
-contigent->contingent
-contined->continued
-continous->continuous
-continously->continuously
-continueing->continuing
-contravercial->controversial
-contraversy->controversy
-contributer->contributor
-contributers->contributors
-contritutions->contributions
-controled->controlled
-controling->controlling
-controll->control
-controlls->controls
-controvercial->controversial
-controvercy->controversy
-controveries->controversies
-controversal->controversial
-controversey->controversy
-controvertial->controversial
-controvery->controversy
-contruction->construction
-conveinent->convenient
-convenant->covenant
-convential->conventional
-convertables->convertibles
-convertion->conversion
-conviced->convinced
-convienient->convenient
-coordiantion->coordination
-coorperation->cooperation, corporation
-coorperations->corporations
-copmetitors->competitors
-coputer->computer
-copywrite->copyright
-coridal->cordial
-cornmitted->committed
-corosion->corrosion
-corparate->corporate
-corperations->corporations
-correcters->correctors
-correponding->corresponding
-correposding->corresponding
-correspondant->correspondent
-correspondants->correspondents
-corridoors->corridors
-corrispond->correspond
-corrispondant->correspondent
-corrispondants->correspondents
-corrisponded->corresponded
-corrisponding->corresponding
-corrisponds->corresponds
-costitution->constitution
-coucil->council
-coudl->could, cloud
-councellor->councillor, counselor, councilor
-councellors->councillors, counselors, councilors
-counries->countries
-countains->contains
-countires->countries
-countrie's->countries, countries', country's
-coururier->courier, couturier
-coverted->converted, covered, coveted
-cpoy->coy, copy
-creaeted->created
-creche->crèche
-creedence->credence
-critereon->criterion
-criterias->criteria
-criticists->critics
-critising->criticising, criticizing
-critisising->criticising
-critisism->criticism
-critisisms->criticisms
-critisize->criticise, criticize
-critisized->criticised, criticized
-critisizes->criticises, criticizes
-critisizing->criticising, criticizing
-critized->criticized
-critizing->criticizing
-crockodiles->crocodiles
-crowm->crown
-crtical->critical
-crticised->criticised
-crucifiction->crucifixion
-crusies->cruises
-crystalisation->crystallisation
-culiminating->culminating
-cumulatative->cumulative
-curch->church
-curcuit->circuit
-currenly->currently
-curriculem->curriculum
-cxan->cyan
-cyclinder->cylinder
-dacquiri->daiquiri
-daed->dead
-dael->deal, dial, dahl
-dalmation->dalmatian
-damenor->demeanor
-dammage->damage
-Dardenelles->Dardanelles
-daugher->daughter
-debateable->debatable
-decendant->descendant
-decendants->descendants
-decendent->descendant
-decendents->descendants
-decideable->decidable
-decidely->decidedly
-decieved->deceived
-decison->decision
-decomissioned->decommissioned
-decomposit->decompose
-decomposited->decomposed
-decompositing->decomposing
-decomposits->decomposes
-decress->decrees
-decribe->describe
-decribed->described
-decribes->describes
-decribing->describing
-dectect->detect
-defendent->defendant
-defendents->defendants
-deffensively->defensively
-deffine->define
-deffined->defined
-definance->defiance
-definate->definite
-definately->definitely
-definatly->definitely
-definetly->definitely
-definining->defining
-definit->definite
-definitly->definitely
-definiton->definition
-defintion->definition
-degrate->degrade
-delagates->delegates
-delapidated->dilapidated
-delerious->delirious
-delevopment->development
-deliberatly->deliberately
-delusionally->delusively
-demenor->demeanor
-demographical->demographic
-demolision->demolition
-demorcracy->democracy
-demostration->demonstration
-denegrating->denigrating
-densly->densely
-deparment->department
-deparmental->departmental
-deparments->departments
-dependance->dependence
-dependancy->dependency
-dependant->dependent
-deram->dram, dream
-deriviated->derived
-derivitive->derivative
-derogitory->derogatory
-descendands->descendants
-descibed->described
-descision->decision
-descisions->decisions
-descriibes->describes
-descripters->descriptors
-descripton->description
-desctruction->destruction
-descuss->discuss
-desgined->designed
-deside->decide
-desigining->designing
-desinations->destinations
-desintegrated->disintegrated
-desintegration->disintegration
-desireable->desirable
-desitned->destined
-desktiop->desktop
-desorder->disorder
-desoriented->disoriented
-desparate->desperate, disparate
-despict->depict
-despiration->desperation
-dessicated->desiccated
-dessigned->designed
-destablized->destabilized
-destory->destroy
-detailled->detailed
-detatched->detached
-deteoriated->deteriorated
-deteriate->deteriorate
-deterioriating->deteriorating
-determinining->determining
-detremental->detrimental
-devasted->devastated
-develope->develop
-developement->development
-developped->developed
-develpment->development
-devels->delves
-devestated->devastated
-devestating->devastating
-devide->divide
-devided->divided
-devistating->devastating
-devolopement->development
-diablical->diabolical
-diamons->diamonds
-diaster->disaster
-dichtomy->dichotomy
-diconnects->disconnects
-dicover->discover
-dicovered->discovered
-dicovering->discovering
-dicovers->discovers
-dicovery->discovery
-dicussed->discussed
-didnt->didn't
-diea->idea, die
-dieing->dying, dyeing
-dieties->deities
-diety->deity
-diferent->different
-diferrent->different
-differentiatiations->differentiations
-differnt->different
-difficulity->difficulty
-diffrent->different
-dificulties->difficulties
-dificulty->difficulty
-dimenions->dimensions
-dimention->dimension
-dimentional->dimensional
-dimentions->dimensions
-dimesnional->dimensional
-diminuitive->diminutive
-dimunitive->diminutive
-diosese->diocese
-diphtong->diphthong
-diphtongs->diphthongs
-diplomancy->diplomacy
-dipthong->diphthong
-dipthongs->diphthongs
-dirived->derived
-disagreeed->disagreed
-disapeared->disappeared
-disapointing->disappointing
-disappearred->disappeared
-disaproval->disapproval
-disasterous->disastrous
-disatisfaction->dissatisfaction
-disatisfied->dissatisfied
-disatrous->disastrous
-discontentment->discontent
-discribe->describe
-discribed->described
-discribes->describes
-discribing->describing
-disctinction->distinction
-disctinctive->distinctive
-disemination->dissemination
-disenchanged->disenchanted
-disiplined->disciplined
-disobediance->disobedience
-disobediant->disobedient
-disolved->dissolved
-disover->discover
-dispair->despair
-disparingly->disparagingly
-dispence->dispense
-dispenced->dispensed
-dispencing->dispensing
-dispicable->despicable
-dispite->despite
-dispostion->disposition
-disproportiate->disproportionate
-disputandem->disputandum
-disricts->districts
-dissagreement->disagreement
-dissapear->disappear
-dissapearance->disappearance
-dissapeared->disappeared
-dissapearing->disappearing
-dissapears->disappears
-dissappear->disappear
-dissappears->disappears
-dissappointed->disappointed
-dissarray->disarray
-dissobediance->disobedience
-dissobediant->disobedient
-dissobedience->disobedience
-dissobedient->disobedient
-distiction->distinction
-distingish->distinguish
-distingished->distinguished
-distingishes->distinguishes
-distingishing->distinguishing
-distingquished->distinguished
-distrubution->distribution
-distruction->destruction
-distructive->destructive
-ditributed->distributed
-diversed->diverse, diverged
-divice->device
-divison->division
-divisons->divisions
-dum->dumb
-doccument->document
-doccumented->documented
-doccuments->documents
-docrines->doctrines
-doctines->doctrines
-documenatry->documentary
-doens->does
-doesnt->doesn't
-doign->doing
-dominaton->domination
-dominent->dominant
-dominiant->dominant
-donig->doing
-dosen't->doesn't
-doub->doubt, daub
-doulbe->double
-dowloads->downloads
-dramtic->dramatic
-draughtman->draughtsman
-Dravadian->Dravidian
-dreasm->dreams
-driectly->directly
-drnik->drink
-druming->drumming
-drummless->drumless
-dupicate->duplicate
-durig->during
-durring->during
-duting->during
-dyas->dryas
-eahc->each
-ealier->earlier
-earlies->earliest
-earnt->earned
-ecclectic->eclectic
-eceonomy->economy
-ecidious->deciduous
-eclispe->eclipse
-ecomonic->economic
-ect->etc
-eearly->early
-efel->evil
-effeciency->efficiency
-effecient->efficient
-effeciently->efficiently
-efficency->efficiency
-efficent->efficient
-efficently->efficiently
-efford->effort, afford
-effords->efforts, affords
-effulence->effluence
-eigth->eighth, eight
-eiter->either
-elction->election
-electic->eclectic, electric
-electon->election, electron
-electrial->electrical
-electricly->electrically
-electricty->electricity
-elementay->elementary
-eleminated->eliminated
-eleminating->eliminating
-eles->eels
-eletricity->electricity
-elicided->elicited
-eligable->eligible
-elimentary->elementary
-ellected->elected
-elphant->elephant
-embarass->embarrass
-embarassed->embarrassed
-embarassing->embarrassing
-embarassment->embarrassment
-embargos->embargoes
-embarras->embarrass
-embarrased->embarrassed
-embarrasing->embarrassing
-embarrasment->embarrassment
-embezelled->embezzled
-emblamatic->emblematic
-eminate->emanate
-eminated->emanated
-emision->emission
-emited->emitted
-emiting->emitting
-emition->emission, emotion
-emmediately->immediately
-emmigrated->emigrated, immigrated
-emminent->eminent, imminent
-emminently->eminently
-emmisaries->emissaries
-emmisarries->emissaries
-emmisarry->emissary
-emmisary->emissary
-emmision->emission
-emmisions->emissions
-emmited->emitted
-emmiting->emitting
-emmitted->emitted
-emmitting->emitting
-emnity->enmity
-emperical->empirical
-emphaised->emphasised
-emphsis->emphasis
-emphysyma->emphysema
-empirial->empirical, imperial
-emprisoned->imprisoned
-enameld->enameled
-enchancement->enhancement
-encouraing->encouraging
-encryptiion->encryption
-encylopedia->encyclopedia
-endevors->endeavors
-endevour->endeavour
-endig->ending
-endolithes->endoliths
-enduce->induce
-ened->need
-enflamed->inflamed
-enforceing->enforcing
-engagment->engagement
-engeneer->engineer
-engeneering->engineering
-engieneer->engineer
-engieneers->engineers
-enlargment->enlargement
-enlargments->enlargements
-Enlish->English, enlist
-enourmous->enormous
-enourmously->enormously
-ensconsed->ensconced
-entaglements->entanglements
-enteratinment->entertainment
-enthusiatic->enthusiastic
-entitity->entity
-entitlied->entitled
-entrepeneur->entrepreneur
-entrepeneurs->entrepreneurs
-enviorment->environment
-enviormental->environmental
-enviormentally->environmentally
-enviorments->environments
-enviornment->environment
-enviornmental->environmental
-enviornmentalist->environmentalist
-enviornmentally->environmentally
-enviornments->environments
-enviroment->environment
-enviromental->environmental
-enviromentalist->environmentalist
-enviromentally->environmentally
-enviroments->environments
-envolutionary->evolutionary
-envrionments->environments
-enxt->next
-epidsodes->episodes
-epsiode->episode
-equialent->equivalent
-equilibium->equilibrium
-equilibrum->equilibrium
-equiped->equipped
-equippment->equipment
-equitorial->equatorial
-equivelant->equivalent
-equivelent->equivalent
-equivilant->equivalent
-equivilent->equivalent
-equivlalent->equivalent
-erally->orally, really
-eratic->erratic
-eratically->erratically
-eraticly->erratically
-erested->arrested, erected
-errupted->erupted
-esential->essential
-esitmated->estimated
-esle->else
-especialy->especially
-essencial->essential
-essense->essence
-essentail->essential
-essentialy->essentially
-essentual->essential
-essesital->essential
-estabishes->establishes
-establising->establishing
-ethnocentricm->ethnocentrism
-ethose->those, ethos
-Europian->European
-Europians->Europeans
-Eurpean->European
-Eurpoean->European
-evenhtually->eventually
-eventally->eventually
-eventhough->even though
-eventially->eventually
-eventualy->eventually
-everthing->everything
-everytime->every time
-everyting->everything
-eveyr->every
-evidentally->evidently
-exagerate->exaggerate
-exagerated->exaggerated
-exagerates->exaggerates
-exagerating->exaggerating
-exagerrate->exaggerate
-exagerrated->exaggerated
-exagerrates->exaggerates
-exagerrating->exaggerating
-examinated->examined
-exampt->exempt
-exapansion->expansion
-excact->exact
-excange->exchange
-excecute->execute
-excecuted->executed
-excecutes->executes
-excecuting->executing
-excecution->execution
-excedded->exceeded
-excelent->excellent
-excell->excel
-excellance->excellence
-excellant->excellent
-excells->excels
-excercise->exercise
-exchanching->exchanging
-excisted->existed
-exculsivly->exclusively
-execising->exercising
-exection->execution
-exectued->executed
-exeedingly->exceedingly
-exelent->excellent
-exellent->excellent
-exemple->example
-exept->except
-exeptional->exceptional
-exerbate->exacerbate
-exerbated->exacerbated
-exerciese->exercises
-exerpt->excerpt
-exerpts->excerpts
-exersize->exercise
-exerternal->external
-exhalted->exalted
-exhibtion->exhibition
-exibition->exhibition
-exibitions->exhibitions
-exicting->exciting
-exinct->extinct
-existance->existence
-existant->existent
-existince->existence
-exliled->exiled
-exludes->excludes
-exmaple->example
-exonorate->exonerate
-exoskelaton->exoskeleton
-expalin->explain
-expatriot->expatriate
-expeced->expected
-expecially->especially
-expeditonary->expeditionary
-expeiments->experiments
-expell->expel
-expells->expels
-experiance->experience
-experianced->experienced
-expiditions->expeditions
-expierence->experience
-explaination->explanation
-explaning->explaining
-explictly->explicitly
-exploititive->exploitative
-explotation->exploitation
-expropiated->expropriated
-expropiation->expropriation
-exressed->expressed
-extemely->extremely
-extention->extension
-extentions->extensions
-extered->exerted
-extermist->extremist
-extint->extinct, extant
-extradiction->extradition
-extraterrestial->extraterrestrial
-extraterrestials->extraterrestrials
-extravagent->extravagant
-extrememly->extremely
-extremeophile->extremophile
-extremly->extremely
-extrordinarily->extraordinarily
-extrordinary->extraordinary
-eyar->year, eyas
-eyars->years, eyas
-eyasr->years, eyas
-faciliate->facilitate
-faciliated->facilitated
-faciliates->facilitates
-facilites->facilities
-facillitate->facilitate
-facinated->fascinated
-facist->fascist
-familes->families
-familliar->familiar
-famoust->famous
-fanatism->fanaticism
-Farenheit->Fahrenheit
-fatc->fact
-faught->fought
-favoutrable->favourable
-feasable->feasible
-Febuary->February
-Feburary->February
-fedreally->federally
-feromone->pheromone
-fertily->fertility
-fianite->finite
-fianlly->finally
-ficticious->fictitious
-fictious->fictitious
-fidn->find
-fiel->feel, field, file, phial
-fiels->feels, fields, files, phials
-fiercly->fiercely
-fightings->fighting
-filiament->filament
-fimilies->families
-finacial->financial
-finaly->finally
-financialy->financially
-firends->friends
-firts->flirts, first
-fisionable->fissionable
-flamable->flammable
-flawess->flawless
-fleed->fled, freed
-Flemmish->Flemish
-florescent->fluorescent
-flourescent->fluorescent
-flourine->fluorine
-fluorish->flourish
-flourishment->flourishing
-follwoing->following
-folowing->following
-fomed->formed
-fomr->from, form
-fonetic->phonetic
-fontrier->fontier
-foootball->football
-forbad->forbade
-forbiden->forbidden
-foreward->foreword
-forfiet->forfeit
-forhead->forehead
-foriegn->foreign
-Formalhaut->Fomalhaut
-formallize->formalize
-formallized->formalized
-formaly->formally, formerly
-formelly->formerly
-formidible->formidable
-formost->foremost
-forsaw->foresaw
-forseeable->foreseeable
-fortelling->foretelling
-forunner->forerunner
-foucs->focus
-foudn->found
-fougth->fought
-foundaries->foundries
-foundary->foundry
-Foundland->Newfoundland
-fourties->forties
-fourty->forty
-fouth->fourth
-foward->forward
-Fransiscan->Franciscan
-Fransiscans->Franciscans
-freind->friend
-freindly->friendly
-frequentily->frequently
-frome->from
-fromed->formed
-froniter->frontier
-fucntion->function
-fucntioning->functioning
-fufill->fulfill
-fufilled->fulfilled
-fulfiled->fulfilled
-fullfill->fulfill
-fullfilled->fulfilled
-fundametal->fundamental
-fundametals->fundamentals
-funguses->fungi
-funtion->function
-furuther->further
-futher->further
-futhermore->furthermore
-futhroc->futhark, futhorc
-gae->game, Gael, gale
-galatic->galactic
-Galations->Galatians
-gallaxies->galaxies
-galvinized->galvanized
-Gameboy->Game Boy
-ganerate->generate
-ganes->games
-ganster->gangster
-garantee->guarantee
-garanteed->guaranteed
-garantees->guarantees
-gardai->gardaí
-garnison->garrison
-gauarana->guaraná
-gaurantee->guarantee
-gauranteed->guaranteed
-gaurantees->guarantees
-gaurd->guard, gourd
-gaurentee->guarantee
-gaurenteed->guaranteed
-gaurentees->guarantees
-geneological->genealogical
-geneologies->genealogies
-geneology->genealogy
-generaly->generally
-generatting->generating
-genialia->genitalia
-geographicial->geographical
-geometrician->geometer
-geometricians->geometers
-gerat->great
-Ghandi->Gandhi
-glight->flight
-gnawwed->gnawed
-godess->goddess
-godesses->goddesses
-Godounov->Godunov
-gogin->going, Gauguin
-goign->going
-gonig->going
-Gothenberg->Gothenburg
-Gottleib->Gottlieb
-gouvener->governor
-govement->government
-govenment->government
-govenrment->government
-goverance->governance
-goverment->government
-govermental->governmental
-governer->governor
-governmnet->government
-govorment->government
-govormental->governmental
-govornment->government
-gracefull->graceful
-graet->great
-grafitti->graffiti
-gramatically->grammatically
-grammaticaly->grammatically
-grammer->grammar
-grat->great
-gratuitious->gratuitous
-greatful->grateful
-greatfully->gratefully
-greif->grief
-gridles->griddles
-gropu->group
-grwo->grow
-Guaduloupe->Guadalupe, Guadeloupe
-Guadulupe->Guadalupe, Guadeloupe
-guage->gauge
-guarentee->guarantee
-guarenteed->guaranteed
-guarentees->guarantees
-Guatamala->Guatemala
-Guatamalan->Guatemalan
-guerrila->guerrilla
-guerrilas->guerrillas
-guidence->guidance
-Guilia->Giulia
-Guilio->Giulio
-Guiness->Guinness
-Guiseppe->Giuseppe
-gunanine->guanine
-gurantee->guarantee
-guranteed->guaranteed
-gurantees->guarantees
-guttaral->guttural
-gutteral->guttural
-habaeus->habeas
-habeus->habeas
-Habsbourg->Habsburg
-haemorrage->haemorrhage
-haev->have, heave
-halarious->hilarious
-Hallowean->Hallowe'en, Halloween
-halp->help
-hapen->happen
-hapened->happened
-hapening->happening
-happend->happened
-happended->happened
-happenned->happened
-harased->harassed
-harases->harasses
-harasment->harassment
-harasments->harassments
-harassement->harassment
-harras->harass
-harrased->harassed
-harrases->harasses
-harrasing->harassing
-harrasment->harassment
-harrasments->harassments
-harrassed->harassed
-harrasses->harassed
-harrassing->harassing
-harrassment->harassment
-harrassments->harassments
-hasnt->hasn't
-Hatian->Haitian
-haviest->heaviest
-headquarer->headquarter
-headquater->headquarter
-headquatered->headquartered
-headquaters->headquarters
-healthercare->healthcare
-heared->heard
-heathy->healthy
-Heidelburg->Heidelberg
-heigher->higher
-heirarchy->hierarchy
-heiroglyphics->hieroglyphics
-helment->helmet
-helpfull->helpful
-helpped->helped
-hemmorhage->hemorrhage
-herad->heard, Hera
-heridity->heredity
-heroe->hero
-heros->heroes
-hertiage->heritage
-hertzs->hertz
-hesistant->hesitant
-heterogenous->heterogeneous
-hieght->height
-hierachical->hierarchical
-hierachies->hierarchies
-hierachy->hierarchy
-hierarcical->hierarchical
-hierarcy->hierarchy
-hieroglph->hieroglyph
-hieroglphs->hieroglyphs
-higer->higher
-higest->highest
-higway->highway
-hillarious->hilarious
-himselv->himself
-hinderance->hindrance
-hinderence->hindrance
-hindrence->hindrance
-hipopotamus->hippopotamus
-hismelf->himself
-histocompatability->histocompatibility
-historicians->historians
-hitsingles->hit singles
-holf->hold
-holliday->holiday
-homestate->home state
-homogeneize->homogenize
-homogeneized->homogenized
-honory->honorary
-horrifing->horrifying
-hosited->hoisted
-hospitible->hospitable
-hounour->honour
-housr->hours, house
-howver->however
-hsitorians->historians
-hstory->history
-hten->then, hen, the
-htere->there, here
-htey->they
-htikn->think
-hting->thing
-htink->think
-htis->this
-humer->humor, humour
-humerous->humorous, humerus
-huminoid->humanoid
-humoural->humoral
-humurous->humorous
-husban->husband
-hvae->have
-hvaing->having
-hvea->have, heave
-hwihc->which
-hwile->while
-hwole->whole
-hydogen->hydrogen
-hydropile->hydrophile
-hydropilic->hydrophilic
-hydropobe->hydrophobe
-hydropobic->hydrophobic
-hygeine->hygiene
-hypocracy->hypocrisy
-hypocrasy->hypocrisy
-hypocricy->hypocrisy
-hypocrit->hypocrite
-hypocrits->hypocrites
-iconclastic->iconoclastic
-idaeidae->idea
-idaes->ideas
-idealogies->ideologies
-idealogy->ideology
-identicial->identical
-identifers->identifiers
-ideosyncratic->idiosyncratic
-idesa->ideas, ides
-idiosyncracy->idiosyncrasy
-Ihaca->Ithaca
-illegimacy->illegitimacy
-illegitmate->illegitimate
-illess->illness
-illiegal->illegal
-illution->illusion
-ilness->illness
-ilogical->illogical
-imagenary->imaginary
-imagin->imagine
-imaginery->imaginary, imagery
-imanent->eminent, imminent
-imcomplete->incomplete
-imediately->immediately
-imense->immense
-imigrant->emigrant, immigrant
-imigrated->emigrated, immigrated
-imigration->emigration, immigration
-iminent->eminent, imminent, immanent
-immediatley->immediately
-immediatly->immediately
-immidately->immediately
-immidiately->immediately
-immitate->imitate
-immitated->imitated
-immitating->imitating
-immitator->imitator
-immunosupressant->immunosuppressant
-impecabbly->impeccably
-impedence->impedance
-implamenting->implementing
-impliment->implement
-implimented->implemented
-imploys->employs
-importamt->important
-impressario->impresario
-imprioned->imprisoned
-imprisonned->imprisoned
-improvision->improvisation
-improvments->improvements
-inablility->inability
-inaccessable->inaccessible
-inadiquate->inadequate
-inadquate->inadequate
-inadvertant->inadvertent
-inadvertantly->inadvertently
-inagurated->inaugurated
-inaguration->inauguration
-inappropiate->inappropriate
-inaugures->inaugurates
-inbalance->imbalance
-inbalanced->imbalanced
-inbetween->between
-incarcirated->incarcerated
-incidentially->incidentally
-incidently->incidentally
-inclreased->increased
-includ->include
-includng->including
-incompatabilities->incompatibilities
-incompatability->incompatibility
-incompatable->incompatible
-incompatablities->incompatibilities
-incompatablity->incompatibility
-incompatiblities->incompatibilities
-incompatiblity->incompatibility
-incompetance->incompetence
-incompetant->incompetent
-incomptable->incompatible
-incomptetent->incompetent
-inconsistant->inconsistent
-incoroporated->incorporated
-incorperation->incorporation
-incorportaed->incorporated
-incorprates->incorporates
-incorruptable->incorruptible
-incramentally->incrementally
-increadible->incredible
-incredable->incredible
-inctroduce->introduce
-inctroduced->introduced
-incuding->including
-incunabla->incunabula
-indefinately->indefinitely
-indefineable->undefinable
-indefinitly->indefinitely
-indentical->identical
-indepedantly->independently
-indepedence->independence
-independance->independence
-independant->independent
-independantly->independently
-independece->independence
-independendet->independent
-indespensable->indispensable
-indespensible->indispensable
-indictement->indictment
-indigineous->indigenous
-indipendence->independence
-indipendent->independent
-indipendently->independently
-indispensible->indispensable
-indisputible->indisputable
-indisputibly->indisputably
-indite->indict
-individualy->individually
-indpendent->independent
-indpendently->independently
-indulgue->indulge
-indutrial->industrial
-indviduals->individuals
-inefficienty->inefficiently
-inevatible->inevitable
-inevitible->inevitable
-inevititably->inevitably
-infalability->infallibility
-infallable->infallible
-infectuous->infectious
-infered->inferred
-infilitrate->infiltrate
-infilitrated->infiltrated
-infilitration->infiltration
-infinit->infinite
-inflamation->inflammation
-influencial->influential
-influented->influenced
-infomation->information
-informtion->information
-infrantryman->infantryman
-infrigement->infringement
-ingenius->ingenious
-ingreediants->ingredients
-inhabitans->inhabitants
-inherantly->inherently
-inheritage->heritage, inheritance
-inheritence->inheritance
-inital->initial
-initally->initially
-initation->initiation
-initiaitive->initiative
-inlcuding->including
-inmigrant->immigrant
-inmigrants->immigrants
-innoculated->inoculated
-inocence->innocence
-inofficial->unofficial
-inot->into
-inpeach->impeach
-inpolite->impolite
-inprisonment->imprisonment
-inproving->improving
-insectiverous->insectivorous
-insensative->insensitive
-inseperable->inseparable
-insistance->insistence
-insitution->institution
-insitutions->institutions
-inspite->in spite, inspire
-instade->instead
-instatance->instance
-institue->institute
-instuction->instruction
-instuments->instruments
-instutionalized->institutionalized
-instutions->intuitions
-insurence->insurance
-intelectual->intellectual
-inteligence->intelligence
-inteligent->intelligent
-intenational->international
-intented->intended, indented
-intepretation->interpretation
-intepretator->interpretor
-interational->international
-interbread->interbreed, interbred
-interchangable->interchangeable
-interchangably->interchangeably
-intercontinetal->intercontinental
-intered->interred, interned
-interelated->interrelated
-interferance->interference
-interfereing->interfering
-intergrated->integrated
-intergration->integration
-interm->interim
-internation->international
-interpet->interpret
-interrim->interim
-interrugum->interregnum
-intertaining->entertaining
-interupt->interrupt
-intervines->intervenes
-intevene->intervene
-intial->initial
-intially->initially
-intrduced->introduced
-intrest->interest
-introdued->introduced
-intruduced->introduced
-intrument->instrument
-intrumental->instrumental
-intruments->instruments
-intrusted->entrusted
-intutive->intuitive
-intutively->intuitively
-inudstry->industry
-inumerable->enumerable, innumerable
-inventer->inventor
-invertibrates->invertebrates
-investingate->investigate
-involvment->involvement
-irelevent->irrelevant
-iresistable->irresistible
-iresistably->irresistibly
-iresistible->irresistible
-iresistibly->irresistibly
-iritable->irritable
-iritated->irritated
-ironicly->ironically
-irregardless->regardless
-irrelevent->irrelevant
-irreplacable->irreplaceable
-irresistable->irresistible
-irresistably->irresistibly
-isnt->isn't
-Israelies->Israelis
-issueing->issuing
-itnroduced->introduced
-iunior->junior
-iwll->will
-iwth->with
-Janurary->January
-Januray->January
-Japanes->Japanese
-jaques->jacques
-jeapardy->jeopardy
-jewllery->jewellery
-Johanine->Johannine
-jorunal->journal
-Jospeh->Joseph
-jouney->journey
-journied->journeyed
-journies->journeys
-jstu->just
-jsut->just
-Juadaism->Judaism
-Juadism->Judaism
-judical->judicial
-judisuary->judiciary
-juducial->judicial
-juristiction->jurisdiction
-juristictions->jurisdictions
-kindergarden->kindergarten
-klenex->kleenex
-knifes->knives
-knive->knife
-knowlege->knowledge
-knowlegeable->knowledgeable
-knwo->know
-knwos->knows
-konw->know
-konws->knows
-kwno->know
-labatory->lavatory, laboratory
-labled->labelled, labeled
-labratory->laboratory
-laguage->language
-laguages->languages
-larg->large
-largst->largest
-larrry->larry
-lastr->last
-lattitude->latitude
-launchs->launch, launches
-launhed->launched
-lavae->larvae
-layed->laid
-lazyness->laziness
-leage->league
-leanr->lean, learn, leaner
-leathal->lethal
-lefted->left
-legitamate->legitimate
-legitmate->legitimate
-leibnitz->leibniz
-lenght->length
-leran->learn
-lerans->learns
-leutenant->lieutenant
-levetate->levitate
-levetated->levitated
-levetates->levitates
-levetating->levitating
-levle->level
-liasion->liaison
-liason->liaison
-liasons->liaisons
-libary->library
-libell->libel
-libguistic->linguistic
-libguistics->linguistics
-libitarianisn->libertarianism
-lible->libel, liable
-lieing->lying
-liek->like
-liekd->liked
-liesure->leisure
-lieuenant->lieutenant
-lieved->lived
-liftime->lifetime
-lightyear->light year
-lightyears->light years
-likelyhood->likelihood
-linnaena->linnaean
-lippizaner->lipizzaner
-liquify->liquefy
-liscense->license, licence
-lisence->license, licence
-lisense->license, licence
-listners->listeners
-litature->literature
-literaly->literally
-literture->literature
-littel->little
-litterally->literally
-liuke->like
-livley->lively
-lmits->limits
-loev->love
-lonelyness->loneliness
-longitudonal->longitudinal
-lonley->lonely
-lonly->lonely, only
-loosing->losing
-lotharingen->lothringen
-lsat->last
-lukid->likud
-lveo->love
-lvoe->love
-Lybia->Libya
-maching->machine, marching, matching
-mackeral->mackerel
-magasine->magazine
-magincian->magician
-magnificient->magnificent
-magolia->magnolia
-mailny->mainly
-maintainance->maintenance
-maintainence->maintenance
-maintance->maintenance
-maintenence->maintenance
-maintinaing->maintaining
-maintioned->mentioned
-majoroty->majority
-maked->marked, made
-makse->makes
-Malcom->Malcolm
-maltesian->Maltese
-mamal->mammal
-mamalian->mammalian
-managable->manageable, manageably
-managment->management
-maneouvre->manoeuvre
-maneouvred->manoeuvred
-maneouvres->manoeuvres
-maneouvring->manoeuvring
-manisfestations->manifestations
-manoeuverability->maneuverability
-manouver->maneuver, manoeuvre
-manouverability->maneuverability, manoeuvrability, manoeuverability
-manouverable->maneuverable, manoeuvrable
-manouvers->maneuvers, manoeuvres
-mantained->maintained
-manuever->maneuver, manoeuvre
-manuevers->maneuvers, manoeuvres
-manufacturedd->manufactured
-manufature->manufacture
-manufatured->manufactured
-manufaturing->manufacturing
-manuver->maneuver
-mariage->marriage
-marjority->majority
-markes->marks
-marketting->marketing
-marmelade->marmalade
-marrage->marriage
-marraige->marriage
-marrtyred->martyred
-marryied->married
-Massachussets->Massachusetts
-Massachussetts->Massachusetts
-massmedia->mass media
-masterbation->masturbation
-mataphysical->metaphysical
-materalists->materialist
-mathamatics->mathematics
-mathematican->mathematician
-mathematicas->mathematics
-matheticians->mathematicians
-mathmatically->mathematically
-mathmatician->mathematician
-mathmaticians->mathematicians
-mccarthyst->mccarthyist
-mchanics->mechanics
-meaninng->meaning
-mear->wear, mere, mare
-mechandise->merchandise
-medacine->medicine
-medeival->medieval
-medevial->medieval
-mediciney->mediciny
-medievel->medieval
-mediterainnean->mediterranean
-Mediteranean->Mediterranean
-meerkrat->meerkat
-melieux->milieux
-membranaphone->membranophone
-memeber->member
-menally->mentally
-meranda->veranda, Miranda
-mercentile->mercantile
-messanger->messenger
-messenging->messaging
-metalic->metallic
-metalurgic->metallurgic
-metalurgical->metallurgical
-metalurgy->metallurgy
-metamorphysis->metamorphosis
-metaphoricial->metaphorical
-meterologist->meteorologist
-meterology->meteorology
-methaphor->metaphor
-methaphors->metaphors
-Michagan->Michigan
-micoscopy->microscopy
-midwifes->midwives
-mileau->milieu
-milennia->millennia
-milennium->millennium
-mileu->milieu
-miliary->military
-milion->million
-miliraty->military
-millenia->millennia
-millenial->millennial
-millenialism->millennialism
-millenium->millennium
-millepede->millipede
-millioniare->millionaire
-millitary->military
-millon->million
-miltary->military
-minature->miniature
-minerial->mineral
-miniscule->minuscule
-ministery->ministry
-minstries->ministries
-minstry->ministry
-minumum->minimum
-mirrorred->mirrored
-miscelaneous->miscellaneous
-miscellanious->miscellaneous
-miscellanous->miscellaneous
-mischeivous->mischievous
-mischevious->mischievous
-mischievious->mischievous
-misdameanor->misdemeanor
-misdameanors->misdemeanors
-misdemenor->misdemeanor
-misdemenors->misdemeanors
-misfourtunes->misfortunes
-misile->missile
-Misouri->Missouri
-mispell->misspell
-mispelled->misspelled
-mispelling->misspelling
-missen->mizzen
-Missisipi->Mississippi
-Missisippi->Mississippi
-missle->missile
-missonary->missionary
-misterious->mysterious
-mistery->mystery
-misteryous->mysterious
-mkae->make
-mkaes->makes
-mkaing->making
-mkea->make
-moderm->modem
-modle->model
-moent->moment
-moeny->money
-mohammedans->muslims
-moil->mohel,soil
-moleclues->molecules
-momento->memento
-monestaries->monasteries
-monestary->monastery, monetary
-monickers->monikers
-monolite->monolithic
-Monserrat->Montserrat
-montains->mountains
-montanous->mountainous
-Montnana->Montana
-monts->months
-montypic->monotypic
-moreso->more, more so
-morgage->mortgage
-Morisette->Morissette
-Morrisette->Morissette
-morroccan->moroccan
-morrocco->morocco
-morroco->morocco
-mortage->mortgage
-mosture->moisture
-motiviated->motivated
-mounth->month
-movei->movie
-movment->movement
-mroe->more
-mucuous->mucous
-muder->murder
-mudering->murdering
-muhammadan->muslim
-multicultralism->multiculturalism
-multipled->multiplied
-multiplers->multipliers
-munbers->numbers
-muncipalities->municipalities
-muncipality->municipality
-munnicipality->municipality
-muscels->mussels, muscles
-muscial->musical
-muscician->musician
-muscicians->musicians
-mutiliated->mutilated
-myraid->myriad
-mysef->myself
-mysogynist->misogynist
-mysogyny->misogyny
-mysterous->mysterious
-Mythraic->Mithraic
-naieve->naive
-Naploeon->Napoleon
-Napolean->Napoleon
-Napoleonian->Napoleonic
-naturaly->naturally
-naturely->naturally
-naturual->natural
-naturually->naturally
-Nazereth->Nazareth
-neccesarily->necessarily
-neccesary->necessary
-neccessarily->necessarily
-neccessary->necessary
-neccessities->necessities
-necesarily->necessarily
-necesary->necessary
-necessiate->necessitate
-neglible->negligible
-negligable->negligible
-negociate->negotiate
-negociation->negotiation
-negociations->negotiations
-negotation->negotiation
-neice->niece, nice
-neigborhood->neighborhood
-neigbour->neighbour, neighbor
-neigbourhood->neighbourhood
-neigbouring->neighbouring, neighboring
-neigbours->neighbours, neighbors
-neolitic->neolithic
-nessasarily->necessarily
-nessecary->necessary
-nestin->nesting
-neverthless->nevertheless
-newletters->newsletters
-Newyorker->New Yorker
-nickle->nickel
-nightfa;;->nightfall
-nightime->nighttime
-nineth->ninth
-ninteenth->nineteenth
-ninties->1990s
-ninty->ninety
-nkow->know
-nkwo->know
-nmae->name
-noncombatents->noncombatants
-nonsence->nonsense
-nontheless->nonetheless
-noone->no one
-norhern->northern
-northen->northern
-northereastern->northeastern
-notabley->notably
-noteable->notable
-noteably->notably
-noteriety->notoriety
-noth->north
-nothern->northern
-noticable->noticeable
-noticably->noticeably
-noticeing->noticing
-noticible->noticeable
-notwhithstanding->notwithstanding
-noveau->nouveau
-Novermber->November
-nowdays->nowadays
-nowe->now
-nto->not
-nucular->nuclear
-nuculear->nuclear
-nuisanse->nuisance
-Nullabour->Nullarbor
-numberous->numerous
-Nuremburg->Nuremberg
-nusance->nuisance
-nutritent->nutrient
-nutritents->nutrients
-nuturing->nurturing
-obediance->obedience
-obediant->obedient
-obession->obsession
-obssessed->obsessed
-obstacal->obstacle
-obstancles->obstacles
-obstruced->obstructed
-ocasion->occasion
-ocasional->occasional
-ocasionally->occasionally
-ocasionaly->occasionally
-ocasioned->occasioned
-ocasions->occasions
-ocassion->occasion
-ocassional->occasional
-ocassionally->occasionally
-ocassionaly->occasionally
-ocassioned->occasioned
-ocassions->occasions
-occaison->occasion
-occassion->occasion
-occassional->occasional
-occassionally->occasionally
-occassionaly->occasionally
-occassioned->occasioned
-occassions->occasions
-occationally->occasionally
-occour->occur
-occurance->occurrence
-occurances->occurrences
-occured->occurred
-occurence->occurrence
-occurences->occurrences
-occuring->occurring
-occurr->occur
-occurrance->occurrence
-occurrances->occurrences
-octohedra->octahedra
-octohedral->octahedral
-octohedron->octahedron
-ocuntries->countries
-ocuntry->country
-ocurr->occur
-ocurrance->occurrence
-ocurred->occurred
-ocurrence->occurrence
-offcers->officers
-offcially->officially
-offereings->offerings
-offical->official
-offically->officially
-officals->officials
-officaly->officially
-officialy->officially
-offred->offered
-oftenly->often
-oging->going, ogling
-ok->OK
-omision->omission
-omited->omitted
-omiting->omitting
-omlette->omelette
-ommision->omission
-ommited->omitted
-ommiting->omitting
-ommitted->omitted
-ommitting->omitting
-omniverous->omnivorous
-omniverously->omnivorously
-omre->more
-onot->note, not
-onyl->only
-openess->openness
-oponent->opponent
-oportunity->opportunity
-opose->oppose
-oposite->opposite
-oposition->opposition
-oppenly->openly
-oppinion->opinion
-opponant->opponent
-oppononent->opponent
-oppositition->opposition
-oppossed->opposed
-opprotunity->opportunity
-opression->oppression
-opressive->oppressive
-opthalmic->ophthalmic
-opthalmologist->ophthalmologist
-opthalmology->ophthalmology
-opthamologist->ophthalmologist
-optmizations->optimizations
-optomism->optimism
-orded->ordered
-organim->organism
-organistion->organisation
-organiztion->organization
-orgin->origin, organ
-orginal->original
-orginally->originally
-orginize->organise
-oridinarily->ordinarily
-origanaly->originally
-originall->original, originally
-originaly->originally
-originially->originally
-originnally->originally
-origional->original
-orignally->originally
-orignially->originally
-otehr->other
-oublisher->publisher
-ouevre->oeuvre
-oustanding->outstanding
-overshaddowed->overshadowed
-overthere->over there
-overwelming->overwhelming
-overwheliming->overwhelming
-owrk->work
-owudl->would
-oxigen->oxygen
-oximoron->oxymoron
-p0enis->penis
-paide->paid
-paitience->patience
-palce->place, palace
-paleolitic->paleolithic
-paliamentarian->parliamentarian
-Palistian->Palestinian
-Palistinian->Palestinian
-Palistinians->Palestinians
-pallete->palette
-pamflet->pamphlet
-pamplet->pamphlet
-pantomine->pantomime
-Papanicalou->Papanicolaou
-paralel->parallel
-paralell->parallel
-paralelly->parallelly
-paralely->parallelly
-parallely->parallelly
-paranthesis->parenthesis
-paraphenalia->paraphernalia
-parellels->parallels
-parituclar->particular
-parliment->parliament
-parrakeets->parakeets
-parralel->parallel
-parrallel->parallel
-parrallell->parallel
-parrallelly->parallelly
-parrallely->parallelly
-partialy->partially
-particually->particularly
-particualr->particular
-particuarly->particularly
-particularily->particularly
-particulary->particularly
-pary->party
-pased->passed
-pasengers->passengers
-passerbys->passersby
-pasttime->pastime
-pastural->pastoral
-paticular->particular
-pattented->patented
-pavillion->pavilion
-payed->paid
-pblisher->publisher
-pbulisher->publisher
-peacefuland->peaceful and
-peageant->pageant
-peculure->peculiar
-pedestrain->pedestrian
-peformed->performed
-peice->piece
-Peloponnes->Peloponnesus
-penatly->penalty
-penerator->penetrator
-penisula->peninsula
-penisular->peninsular
-penninsula->peninsula
-penninsular->peninsular
-pennisula->peninsula
-Pennyslvania->Pennsylvania
-pensinula->peninsula
-peom->poem
-peoms->poems
-peopel->people
-peotry->poetry
-perade->parade
-percepted->perceived
-percieve->perceive
-percieved->perceived
-perenially->perennially
-perfomance->performance
-perfomers->performers
-performence->performance
-performes->performed, performs
-perhasp->perhaps
-perheaps->perhaps
-perhpas->perhaps
-peripathetic->peripatetic
-peristent->persistent
-perjery->perjury
-perjorative->pejorative
-permanant->permanent
-permenant->permanent
-permenantly->permanently
-permissable->permissible
-perogative->prerogative
-peronal->personal
-perosnality->personality
-perphas->perhaps
-perpindicular->perpendicular
-perseverence->perseverance
-persistance->persistence
-persistant->persistent
-personel->personnel, personal
-personell->personnel
-personnell->personnel
-persuded->persuaded
-persue->pursue
-persued->pursued
-persuing->pursuing
-persuit->pursuit
-persuits->pursuits
-pertubation->perturbation
-pertubations->perturbations
-pessiary->pessary
-petetion->petition
-Pharoah->Pharaoh
-phenomenom->phenomenon
-phenomenonal->phenomenal
-phenomenonly->phenomenally
-phenomonenon->phenomenon
-phenomonon->phenomenon
-phenonmena->phenomena
-Philipines->Philippines
-philisopher->philosopher
-philisophical->philosophical
-philisophy->philosophy
-Phillipine->Philippine
-Phillipines->Philippines
-Phillippines->Philippines
-phillosophically->philosophically
-philospher->philosopher
-philosphies->philosophies
-philosphy->philosophy
-Phonecian->Phoenecian
-phongraph->phonograph
-phylosophical->philosophical
-physicaly->physically
-piblisher->publisher
-pich->pitch
-pilgrimmage->pilgrimage
-pilgrimmages->pilgrimages
-pinapple->pineapple
-pinnaple->pineapple
-pinoneered->pioneered
-plagarism->plagiarism
-planation->plantation
-planed->planned
-plantiff->plaintiff
-plateu->plateau
-plausable->plausible
-playright->playwright
-playwrite->playwright
-playwrites->playwrights
-pleasent->pleasant
-plebicite->plebiscite
-plesant->pleasant
-poenis->penis
-poeoples->peoples
-poety->poetry
-poisin->poison
-polical->political
-polinator->pollinator
-polinators->pollinators
-politican->politician
-politicans->politicians
-poltical->political
-polute->pollute
-poluted->polluted
-polutes->pollutes
-poluting->polluting
-polution->pollution
-polyphonyic->polyphonic
-polysaccaride->polysaccharide
-polysaccharid->polysaccharide
-pomegranite->pomegranate
-pomotion->promotion
-poportional->proportional
-popoulation->population
-popularaty->popularity
-populare->popular
-populer->popular
-portait->portrait
-portayed->portrayed
-portraing->portraying
-Portugese->Portuguese
-portuguease->portuguese
-portugues->Portuguese
-posess->possess
-posessed->possessed
-posesses->possesses
-posessing->possessing
-posession->possession
-posessions->possessions
-posion->poison
-positon->position, positron
-possable->possible
-possably->possibly
-posseses->possesses
-possesing->possessing
-possesion->possession
-possessess->possesses
-possibile->possible
-possibilty->possibility
-possiblility->possibility
-possiblilty->possibility
-possiblities->possibilities
-possiblity->possibility
-possition->position
-Postdam->Potsdam
-posthomous->posthumous
-postion->position
-postive->positive
-potatos->potatoes
-potrait->portrait
-potrayed->portrayed
-poulations->populations
-poverful->powerful
-poweful->powerful
-powerfull->powerful
-ppublisher->publisher
-practial->practical
-practially->practically
-practicaly->practically
-practicioner->practitioner
-practicioners->practitioners
-practicly->practically
-practioner->practitioner
-practioners->practitioners
-prairy->prairie
-prarie->prairie
-praries->prairies
-pratice->practice
-preample->preamble
-precedessor->predecessor
-preceed->precede
-preceeded->preceded
-preceeding->preceding
-preceeds->precedes
-precentage->percentage
-precice->precise
-precisly->precisely
-precurser->precursor
-predecesors->predecessors
-predicatble->predictable
-predicitons->predictions
-predomiantly->predominately
-prefered->preferred
-prefering->preferring
-preferrably->preferably
-pregancies->pregnancies
-preiod->period
-preliferation->proliferation
-premeire->premiere
-premeired->premiered
-premillenial->premillennial
-preminence->preeminence
-premission->permission
-Premonasterians->Premonstratensians
-preocupation->preoccupation
-prepair->prepare
-prepartion->preparation
-prepatory->preparatory
-preperation->preparation
-preperations->preparations
-preriod->period
-presedential->presidential
-presense->presence
-presidenital->presidential
-presidental->presidential
-presitgious->prestigious
-prespective->perspective
-prestigeous->prestigious
-prestigous->prestigious
-presumabely->presumably
-presumibly->presumably
-pretection->protection
-prevelant->prevalent
-preverse->perverse
-previvous->previous
-pricipal->principal
-priciple->principle
-priestood->priesthood
-primarly->primarily
-primative->primitive
-primatively->primitively
-primatives->primitives
-primordal->primordial
-principlaity->principality
-principaly->principality
-principial->principal
-principly->principally
-prinicipal->principal
-privalege->privilege
-privaleges->privileges
-priveledges->privileges
-privelege->privilege
-priveleged->privileged
-priveleges->privileges
-privelige->privilege
-priveliged->privileged
-priveliges->privileges
-privelleges->privileges
-privilage->privilege
-priviledge->privilege
-priviledges->privileges
-privledge->privilege
-privte->private
-probabilaty->probability
-probablistic->probabilistic
-probablly->probably
-probalibity->probability
-probaly->probably
-probelm->problem
-proccess->process
-proccessing->processing
-procede->proceed, precede
-proceded->proceeded, preceded
-procedes->proceeds, precedes
-procedger->procedure
-proceding->proceeding, preceding
-procedings->proceedings
-proceedure->procedure
-proces->process
-processer->processor
-proclaimation->proclamation
-proclamed->proclaimed
-proclaming->proclaiming
-proclomation->proclamation
-profesion->profusion, profession
-profesor->professor
-professer->professor
-proffesed->professed
-proffesion->profession
-proffesional->professional
-proffesor->professor
-profilic->prolific
-progessed->progressed
-programable->programmable
-progrom->pogrom, program
-progroms->pogroms, programs
-prohabition->prohibition
-prologomena->prolegomena
-prominance->prominence
-prominant->prominent
-prominantly->prominently
-prominately->prominently, predominately
-promiscous->promiscuous
-promotted->promoted
-pronomial->pronominal
-pronouced->pronounced
-pronounched->pronounced
-pronounciation->pronunciation
-proove->prove
-prooved->proved
-prophacy->prophecy
-propietary->proprietary
-propmted->prompted
-propoganda->propaganda
-propogate->propagate
-propogates->propagates
-propogation->propagation
-propostion->proposition
-propotions->proportions
-propper->proper
-propperly->properly
-proprietory->proprietary
-proseletyzing->proselytizing
-protaganist->protagonist
-protaganists->protagonists
-protocal->protocol
-protoganist->protagonist
-protrayed->portrayed
-protruberance->protuberance
-protruberances->protuberances
-prouncements->pronouncements
-provacative->provocative
-provded->provided
-provicial->provincial
-provinicial->provincial
-provisiosn->provision
-provisonal->provisional
-proximty->proximity
-pseudononymous->pseudonymous
-pseudonyn->pseudonym
-psuedo->pseudo
-psycology->psychology
-psyhic->psychic
-pubilsher->publisher
-pubisher->publisher
-publiaher->publisher
-publically->publicly
-publicaly->publicly
-publicher->publisher
-publihser->publisher
-publisehr->publisher
-publiser->publisher
-publisger->publisher
-publisheed->published
-publisherr->publisher
-publishher->publisher
-publishor->publisher
-publishre->publisher
-publissher->publisher
-publlisher->publisher
-publsiher->publisher
-publusher->publisher
-puchasing->purchasing
-Pucini->Puccini
-Puertorrican->Puerto Rican
-Puertorricans->Puerto Ricans
-pulisher->publisher
-pumkin->pumpkin
-puplisher->publisher
-puritannical->puritanical
-purposedly->purposely
-purpotedly->purportedly
-pursuade->persuade
-pursuaded->persuaded
-pursuades->persuades
-pususading->persuading
-puting->putting
-pwoer->power
-pyscic->psychic
-qtuie->quite, quiet
-quantaty->quantity
-quantitiy->quantity
-quarantaine->quarantine
-Queenland->Queensland
-questonable->questionable
-quicklyu->quickly
-quinessential->quintessential
-quitted->quit
-quizes->quizzes
-qutie->quite, quiet
-rabinnical->rabbinical
-racaus->raucous
-radiactive->radioactive
-radify->ratify
-raelly->really
-rarified->rarefied
-reaccurring->recurring
-reacing->reaching
-reacll->recall
-readmition->readmission
-realitvely->relatively
-realsitic->realistic
-realtions->relations
-realy->really
-realyl->really
-reasearch->research
-rebiulding->rebuilding
-rebllions->rebellions
-rebounce->rebound
-reccomend->recommend
-reccomendations->recommendations
-reccomended->recommended
-reccomending->recommending
-reccommend->recommend
-reccommended->recommended
-reccommending->recommending
-reccuring->recurring
-receeded->receded
-receeding->receding
-receivedfrom->received from
-recepient->recipient
-recepients->recipients
-receving->receiving
-rechargable->rechargeable
-reched->reached
-recide->reside
-recided->resided
-recident->resident
-recidents->residents
-reciding->residing
-reciepents->recipients
-reciept->receipt
-recieve->receive
-recieved->received
-reciever->receiver
-recievers->receivers
-recieves->receives
-recieving->receiving
-recipiant->recipient
-recipiants->recipients
-recived->received
-recivership->receivership
-recogise->recognise
-recogize->recognize
-recomend->recommend
-recomended->recommended
-recomending->recommending
-recomends->recommends
-recommedations->recommendations
-recompence->recompense
-reconaissance->reconnaissance
-reconcilation->reconciliation
-reconized->recognized
-reconnaisance->reconnaissance
-reconnaissence->reconnaissance
-recontructed->reconstructed
-recordproducer->record producer
-recquired->required
-recrational->recreational
-recrod->record
-recuiting->recruiting
-recuring->recurring
-recurrance->recurrence
-rediculous->ridiculous
-reedeming->redeeming
-reenforced->reinforced
-refect->reflect
-refedendum->referendum
-referal->referral
-referece->reference
-refereces->references
-refered->referred
-referemce->reference
-referemces->references
-referencs->references
-referenece->reference
-refereneced->referenced
-refereneces->references
-referiang->referring
-refering->referring
-refernce->reference,references
-refernces->references
-referrence->reference
-referrences->references
-referrs->refers
-reffered->referred
-refference->reference
-reffering->referring
-refrence->reference
-refrences->references
-refrers->refers
-refridgeration->refrigeration
-refridgerator->refrigerator
-refromist->reformist
-refusla->refusal
-regardes->regards
-regluar->regular
-reguarly->regularly
-regulaion->regulation
-regulaotrs->regulators
-regularily->regularly
-rehersal->rehearsal
-reicarnation->reincarnation
-reigining->reigning
-reknown->renown
-reknowned->renowned
-rela->real
-relaly->really
-relatiopnship->relationship
-relativly->relatively
-relected->reelected
-releive->relieve
-releived->relieved
-releiver->reliever
-releses->releases
-relevence->relevance
-relevent->relevant
-reliablity->reliability
-relient->reliant
-religeous->religious
-religous->religious
-religously->religiously
-relinqushment->relinquishment
-relitavely->relatively
-relized->realised, realized
-relpacement->replacement
-remaing->remaining
-remeber->remember
-rememberable->memorable
-rememberance->remembrance
-remembrence->remembrance
-remenant->remnant
-remenicent->reminiscent
-reminent->remnant
-reminescent->reminiscent
-reminscent->reminiscent
-reminsicent->reminiscent
-rendevous->rendezvous
-rendezous->rendezvous
-renedered->rende
-renewl->renewal
-rennovate->renovate
-rennovated->renovated
-rennovating->renovating
-rennovation->renovation
-rentors->renters
-reoccurrence->recurrence
-reorganision->reorganisation
-repatition->repetition, repartition
-repblic->republic
-repblican->republican
-repblicans->republicans
-repblics->republics
-repectively->respectively
-repeition->repetition
-repentence->repentance
-repentent->repentant
-repeteadly->repeatedly
-repetion->repetition
-repid->rapid
-reponse->response
-reponsible->responsible
-reportadly->reportedly
-represantative->representative
-representive->representative
-representives->representatives
-reproducable->reproducible
-reprtoire->repertoire
-repsectively->respectively
-reptition->repetition
-repubic->republic
-repubican->republican
-repubicans->republicans
-repubics->republics
-republi->republic
-republian->republican
-republians->republicans
-republis->republics
-repulic->republic
-repulican->republican
-repulicans->republicans
-repulics->republics
-requirment->requirement
-requred->required
-resaurant->restaurant
-resembelance->resemblance
-resembes->resembles
-resemblence->resemblance
-resevoir->reservoir
-residental->residential
-resignement->resignment
-resistable->resistible
-resistence->resistance
-resistent->resistant
-respectivly->respectively
-responce->response
-responibilities->responsibilities
-responisble->responsible
-responnsibilty->responsibility
-responsability->responsibility
-responsibile->responsible
-responsibilites->responsibilities
-responsiblities->responsibilities
-responsiblity->responsibility
-ressemblance->resemblance
-ressemble->resemble
-ressembled->resembled
-ressemblence->resemblance
-ressembling->resembling
-resssurecting->resurrecting
-ressurect->resurrect
-ressurected->resurrected
-ressurection->resurrection
-ressurrection->resurrection
-restarant->restaurant
-restarants->restaurants
-restaraunt->restaurant
-restaraunteur->restaurateur
-restaraunteurs->restaurateurs
-restaraunts->restaurants
-restauranteurs->restaurateurs
-restauration->restoration
-restauraunt->restaurant
-resteraunt->restaurant
-resteraunts->restaurants
-resticted->restricted
-restraunt->restraint, restaurant
-resturant->restaurant
-resturants->restaurants
-resturaunt->restaurant
-resturaunts->restaurants
-resurecting->resurrecting
-retalitated->retaliated
-retalitation->retaliation
-retreive->retrieve
-returnd->returned
-revaluated->reevaluated
-reveiw->review
-reveral->reversal
-reversable->reversible
-revolutionar->revolutionary
-rewitten->rewritten
-rewriet->rewrite
-rference->reference
-rferences->references
-rhymme->rhyme
-rhythem->rhythm
-rhythim->rhythm
-rhytmic->rhythmic
-rigeur->rigueur, rigour, rigor
-rigourous->rigorous
-rininging->ringing
-rised->rose
-Rockerfeller->Rockefeller
-rococco->rococo
-rocord->record
-roomate->roommate
-rougly->roughly
-rucuperate->recuperate
-rudimentatry->rudimentary
-rulle->rule
-runing->running
-runnung->running
-russina->Russian
-Russion->Russian
-rwite->write
-rythem->rhythm
-rythim->rhythm
-rythm->rhythm
-rythmic->rhythmic
-rythyms->rhythms
-sacrafice->sacrifice
-sacreligious->sacrilegious
-sacrifical->sacrificial
-saftey->safety
-safty->safety
-salery->salary
-sanctionning->sanctioning
-sandwhich->sandwich
-Sanhedrim->Sanhedrin
-santioned->sanctioned
-sargant->sergeant
-sargeant->sergeant
-sasy->says, sassy
-satelite->satellite
-satelites->satellites
-Saterday->Saturday
-Saterdays->Saturdays
-satisfactority->satisfactorily
-satric->satiric
-satrical->satirical
-satrically->satirically
-sattelite->satellite
-sattelites->satellites
-saught->sought
-saveing->saving
-saxaphone->saxophone
-scaleable->scalable
-scandanavia->Scandinavia
-scaricity->scarcity
-scavanged->scavenged
-schedual->schedule
-scholarhip->scholarship
-scholarstic->scholastic, scholarly
-scientfic->scientific
-scientifc->scientific
-scientis->scientist
-scince->science
-scinece->science
-scirpt->script
-scoll->scroll
-screenwrighter->screenwriter
-scrutinity->scrutiny
-scuptures->sculptures
-seach->search
-seached->searched
-seaches->searches
-secceeded->seceded, succeeded
-seceed->succeed, secede
-seceeded->succeeded, seceded
-secratary->secretary
-secretery->secretary
-sedereal->sidereal
-seeked->sought
-segementation->segmentation
-seguoys->segues
-seige->siege
-seing->seeing
-seinor->senior
-seldomly->seldom
-senarios->scenarios
-sence->sense, since
-senstive->sensitive
-sensure->censure
-seperate->separate
-seperated->separated
-seperately->separately
-seperates->separates
-seperating->separating
-seperation->separation
-seperatism->separatism
-seperatist->separatist
-sepina->subpoena
-sepulchure->sepulchre, sepulcher
-sepulcre->sepulchre, sepulcher
-sergent->sergeant
-settelement->settlement
-settlment->settlement
-severeal->several
-severley->severely
-severly->severely
-sevice->service
-shadasloo->shadaloo
-shaddow->shadow
-shadoloo->shadaloo
-shamen->shaman, shamans
-sheat->sheath, sheet, cheat
-sheild->shield
-sherif->sheriff
-shineing->shining
-shiped->shipped
-shiping->shipping
-shopkeeepers->shopkeepers
-shorly->shortly
-shortwhile->short while
-shoudl->should
-shoudln->should, shouldn't
-shouldnt->shouldn't
-shreak->shriek
-shrinked->shrunk
-sicne->since
-sideral->sidereal
-sieze->seize, size
-siezed->seized, sized
-siezing->seizing, sizing
-siezure->seizure
-siezures->seizures
-siginificant->significant
-signficant->significant
-signficiant->significant
-signfies->signifies
-signifantly->significantly
-significently->significantly
-signifigant->significant
-signifigantly->significantly
-signitories->signatories
-signitory->signatory
-similarily->similarly
-similiar->similar
-similiarity->similarity
-similiarly->similarly
-simmilar->similar
-simpley->simply
-simplier->simpler
-simultanous->simultaneous
-simultanously->simultaneously
-sincerley->sincerely
-singsog->singsong
-sinse->sines, since
-Sionist->Zionist
-Sionists->Zionists
-Sixtin->Sistine
-Skagerak->Skagerrak
-skateing->skating
-slaugterhouses->slaughterhouses
-slighly->slightly
-slippy->slippery
-slowy->slowly
-smae->same
-smealting->smelting
-smoe->some
-sneeks->sneaks
-snese->sneeze
-socalism->socialism
-socities->societies
-soem->some
-sofware->software
-sohw->show
-soilders->soldiers
-solatary->solitary
-soley->solely
-soliders->soldiers
-soliliquy->soliloquy
-soluable->soluble
-somene->someone
-somtimes->sometimes
-somwhere->somewhere
-sophicated->sophisticated
-sophmore->sophomore
-sorceror->sorcerer
-sorrounding->surrounding
-sotry->story
-sotyr->satyr, story
-soudn->sound
-soudns->sounds
-sould->could, should, sold, soul
-sountrack->soundtrack
-sourth->south
-sourthern->southern
-souvenier->souvenir
-souveniers->souvenirs
-soveits->soviets
-sovereignity->sovereignty
-soverign->sovereign
-soverignity->sovereignty
-soverignty->sovereignty
-spainish->Spanish
-speach->speech
-specfic->specific
-speciallized->specialised, specialized
-specif->specific, specify
-specifiying->specifying
-speciman->specimen
-spectauclar->spectacular
-spectaulars->spectaculars
-spects->aspects, expects
-spectum->spectrum
-speices->species
-spendour->splendour
-spermatozoan->spermatozoon
-spoace->space
-sponser->sponsor
-sponsered->sponsored
-spontanous->spontaneous
-sponzored->sponsored
-spoonfulls->spoonfuls
-sppeches->speeches
-spreaded->spread
-sprech->speech
-spred->spread
-spriritual->spiritual
-spritual->spiritual
-sqaure->square
-stablility->stability
-stainlees->stainless
-staion->station
-standars->standards
-stange->strange
-startegic->strategic
-startegies->strategies
-startegy->strategy
-stateman->statesman
-statememts->statements
-statment->statement
-steriods->steroids
-sterotypes->stereotypes
-stilus->stylus
-stingent->stringent
-stiring->stirring
-stirrs->stirs
-stlye->style
-stomache->stomach
-stong->strong
-stopry->story
-storeis->stories
-storise->stories
-stornegst->strongest
-stoyr->story
-stpo->stop
-stradegies->strategies
-stradegy->strategy
-strat->start, strata
-stratagically->strategically
-streemlining->streamlining
-stregth->strength
-strenghen->strengthen
-strenghened->strengthened
-strenghening->strengthening
-strenght->strength
-strenghten->strengthen
-strenghtened->strengthened
-strenghtening->strengthening
-strengtened->strengthened
-strenous->strenuous
-strictist->strictest
-strikely->strikingly
-strnad->strand
-stroy->story, destroy
-structual->structural
-stubborness->stubbornness
-stucture->structure
-stuctured->structured
-studdy->study
-studing->studying
-stuggling->struggling
-sturcture->structure
-subcatagories->subcategories
-subcatagory->subcategory
-subconsiously->subconsciously
-subjudgation->subjugation
-submachne->submachine
-subpecies->subspecies
-subsidary->subsidiary
-subsiduary->subsidiary
-subsquent->subsequent
-subsquently->subsequently
-substace->substance
-substancial->substantial
-substatial->substantial
-substituded->substituted
-substract->subtract
-substracted->subtracted
-substracting->subtracting
-substraction->subtraction
-substracts->subtracts
-subtances->substances
-subterranian->subterranean
-suburburban->suburban
-succceeded->succeeded
-succcesses->successes
-succedded->succeeded
-succeded->succeeded
-succeds->succeeds
-succesful->successful
-succesfully->successfully
-succesfuly->successfully
-succesion->succession
-succesive->successive
-successfull->successful
-successully->successfully
-succsess->success
-succsessfull->successful
-suceed->succeed
-suceeded->succeeded
-suceeding->succeeding
-suceeds->succeeds
-sucesful->successful
-sucesfully->successfully
-sucesfuly->successfully
-sucesion->succession
-sucess->success
-sucesses->successes
-sucessful->successful
-sucessfull->successful
-sucessfully->successfully
-sucessfuly->successfully
-sucession->succession
-sucessive->successive
-sucessor->successor
-sucessot->successor
-sucide->suicide
-sucidial->suicidal
-sufferage->suffrage
-sufferred->suffered
-sufferring->suffering
-sufficent->sufficient
-sufficently->sufficiently
-sumary->summary
-sunglases->sunglasses
-suop->soup
-superceeded->superseded
-superintendant->superintendent
-suphisticated->sophisticated
-suplimented->supplemented
-supose->suppose
-suposed->supposed
-suposedly->supposedly
-suposes->supposes
-suposing->supposing
-supplamented->supplemented
-suppliementing->supplementing
-suppoed->supposed
-supposingly->supposedly
-suppy->supply
-supress->suppress
-supressed->suppressed
-supresses->suppresses
-supressing->suppressing
-suprise->surprise
-suprised->surprised
-suprising->surprising
-suprisingly->surprisingly
-suprize->surprise
-suprized->surprised
-suprizing->surprising
-suprizingly->surprisingly
-surfce->surface
-surley->surly, surely
-suround->surround
-surounded->surrounded
-surounding->surrounding
-suroundings->surroundings
-surounds->surrounds
-surplanted->supplanted
-surpress->suppress
-surpressed->suppressed
-surprize->surprise
-surprized->surprised
-surprizing->surprising
-surprizingly->surprisingly
-surrended->surrounded, surrendered
-surrepetitious->surreptitious
-surrepetitiously->surreptitiously
-surreptious->surreptitious
-surreptiously->surreptitiously
-surronded->surrounded
-surrouded->surrounded
-surrouding->surrounding
-surrundering->surrendering
-surveilence->surveillance
-surveill->surveil
-surveyer->surveyor
-surviver->survivor
-survivers->survivors
-survivied->survived
-suseptable->susceptible
-suseptible->susceptible
-suspention->suspension
-swaer->swear
-swaers->swears
-swepth->swept
-swiming->swimming
-syas->says
-symetrical->symmetrical
-symetrically->symmetrically
-symetry->symmetry
-symettric->symmetric
-symmetral->symmetric
-symmetricaly->symmetrically
-synagouge->synagogue
-syncronization->synchronization
-synonomous->synonymous
-synonymns->synonyms
-synphony->symphony
-syphyllis->syphilis
-sypmtoms->symptoms
-syrap->syrup
-sysmatically->systematically
-sytem->system
-sytle->style
-tabacco->tobacco
-tahn->than
-taht->that
-talekd->talked
-targetted->targeted
-targetting->targeting
-tast->taste
-tath->that
-tattooes->tattoos
-taxanomic->taxonomic
-taxanomy->taxonomy
-teached->taught
-techician->technician
-techicians->technicians
-techiniques->techniques
-technitian->technician
-technnology->technology
-technolgy->technology
-teh->the
-tehy->they
-telelevision->television
-televsion->television
-telphony->telephony
-temerature->temperature
-tempalte->template
-tempaltes->templates
-temparate->temperate
-temperarily->temporarily
-temperment->temperament
-tempertaure->temperature
-temperture->temperature
-temprary->temporary
-tenacle->tentacle
-tenacles->tentacles
-tendacy->tendency
-tendancies->tendencies
-tendancy->tendency
-tennisplayer->tennis player
-tepmorarily->temporarily
-terrestial->terrestrial
-terriories->territories
-terriory->territory
-territorist->terrorist
-territoy->territory
-terroist->terrorist
-testiclular->testicular
-tghe->the
-thast->that, that's
-theather->theater
-theese->these
-theif->thief
-theives->thieves
-themselfs->themselves
-themslves->themselves
-ther->there, their, the
-therafter->thereafter
-therby->thereby
-theri->their
-theyre->they're
-thgat->that
-thge->the
-thier->their
-thign->thing
-thigns->things
-thigsn->things
-thikn->think
-thikning->thinking, thickening
-thikns->thinks
-thiunk->think
-thn->then
-thna->than
-thne->then
-thnig->thing
-thnigs->things
-thoughout->throughout
-threatend->threatened
-threatning->threatening
-threee->three
-threshhold->threshold
-thrid->third
-throrough->thorough
-throughly->thoroughly
-throught->thought, through, throughout
-througout->throughout
-thru->through
-thsi->this
-thsoe->those
-thta->that
-thyat->that
-tiem->time, Tim
-tihkn->think
-tihs->this
-timne->time
-tiome->time, tome
-tje->the
-tjhe->the
-tjpanishad->upanishad
-tkae->take
-tkaes->takes
-tkaing->taking
-tlaking->talking
-tobbaco->tobacco
-todays->today's
-todya->today
-toghether->together
-toke->took
-tolerence->tolerance
-Tolkein->Tolkien
-tomatos->tomatoes
-tommorow->tomorrow
-tommorrow->tomorrow
-tongiht->tonight
-toriodal->toroidal
-tormenters->tormentors
-tornadoe->tornado
-torpeados->torpedoes
-torpedos->torpedoes
-tothe->to the
-toubles->troubles
-tounge->tongue
-tourch->torch, touch
-towords->towards
-towrad->toward
-tradionally->traditionally
-traditionaly->traditionally
-traditionnal->traditional
-traditition->tradition
-tradtionally->traditionally
-trafficed->trafficked
-trafficing->trafficking
-trafic->traffic
-trancendent->transcendent
-trancending->transcending
-tranform->transform
-tranformed->transformed
-transcendance->transcendence
-transcendant->transcendent
-transcendentational->transcendental
-transcripting->transcribing, transcription
-transending->transcending
-transesxuals->transsexuals
-transfered->transferred
-transfering->transferring
-transformaton->transformation
-transistion->transition
-translater->translator
-translaters->translators
-transmissable->transmissible
-transporation->transportation
-tremelo->tremolo
-tremelos->tremolos
-triguered->triggered
-triology->trilogy
-troling->trolling
-troup->troupe
-troups->troupes, troops
-truely->truly
-trustworthyness->trustworthiness
-turnk->turnkey, trunk
-Tuscon->Tucson
-tust->trust
-twelth->twelfth
-twon->town
-twpo->two
-tyhat->that
-tyhe->they
-typcial->typical
-typicaly->typically
-tyranies->tyrannies
-tyrany->tyranny
-tyrranies->tyrannies
-tyrrany->tyranny
-ubiquitious->ubiquitous
-ublisher->publisher
-uise->use
-Ukranian->Ukrainian
-ultimely->ultimately
-unacompanied->unaccompanied
-unahppy->unhappy
-unanymous->unanimous
-unathorised->unauthorised
-unavailible->unavailable
-unballance->unbalance
-unbeknowst->unbeknownst
-unbeleivable->unbelievable
-uncertainity->uncertainty
-unchallengable->unchallengeable
-unchangable->unchangeable
-uncompetive->uncompetitive
-unconcious->unconscious
-unconciousness->unconsciousness
-unconfortability->discomfort
-uncontitutional->unconstitutional
-unconvential->unconventional
-undecideable->undecidable
-understoon->understood
-undesireable->undesirable
-undetecable->undetectable
-undoubtely->undoubtedly
-undreground->underground
-uneccesary->unnecessary
-unecessary->unnecessary
-unequalities->inequalities
-unforetunately->unfortunately
-unforgetable->unforgettable
-unforgiveable->unforgivable
-unfortunatley->unfortunately
-unfortunatly->unfortunately
-unfourtunately->unfortunately
-unihabited->uninhabited
-unilateraly->unilaterally
-unilatreal->unilateral
-unilatreally->unilaterally
-uninterruped->uninterrupted
-uninterupted->uninterrupted
-UnitesStates->UnitedStates
-univeral->universal
-univeristies->universities
-univeristy->university
-univerity->university
-universtiy->university
-univesities->universities
-univesity->university
-unkown->unknown
-unlikey->unlikely
-unmanouverable->unmaneuverable, unmanoeuvrable
-unmistakeably->unmistakably
-unneccesarily->unnecessarily
-unneccesary->unnecessary
-unneccessarily->unnecessarily
-unneccessary->unnecessary
-unnecesarily->unnecessarily
-unnecesary->unnecessary
-unoffical->unofficial
-unoperational->nonoperational
-unoticeable->unnoticeable
-unplease->displease
-unplesant->unpleasant
-unprecendented->unprecedented
-unprecidented->unprecedented
-unrepentent->unrepentant
-unrepetant->unrepentant
-unrepetent->unrepentant
-unsed->used, unused, unsaid
-unsubstanciated->unsubstantiated
-unsuccesful->unsuccessful
-unsuccesfully->unsuccessfully
-unsuccessfull->unsuccessful
-unsucesful->unsuccessful
-unsucesfuly->unsuccessfully
-unsucessful->unsuccessful
-unsucessfull->unsuccessful
-unsucessfully->unsuccessfully
-unsuprised->unsurprised
-unsuprising->unsurprising
-unsuprisingly->unsurprisingly
-unsuprized->unsurprised
-unsuprizing->unsurprising
-unsuprizingly->unsurprisingly
-unsurprized->unsurprised
-unsurprizing->unsurprising
-unsurprizingly->unsurprisingly
-untill->until
-untranslateable->untranslatable
-unuseable->unusable
-unusuable->unusable
-unviersity->university
-unwarrented->unwarranted
-unweildly->unwieldy
-unwieldly->unwieldy
-upcomming->upcoming
-upgradded->upgraded
-upto->up to
-usally->usually
-useage->usage
-usefull->useful
-usefuly->usefully
-useing->using
-usualy->usually
-ususally->usually
-vaccum->vacuum
-vaccume->vacuum
-vacinity->vicinity
-vaguaries->vagaries
-vaieties->varieties
-vailidty->validity
-valetta->valletta
-valuble->valuable
-valueable->valuable
-varations->variations
-varient->variant
-variey->variety
-varing->varying
-varities->varieties
-varity->variety
-vasall->vassal
-vasalls->vassals
-vegatarian->vegetarian
-vegitable->vegetable
-vegitables->vegetables
-vegtable->vegetable
-vehicule->vehicle
-vell->well
-venemous->venomous
-vengance->vengeance
-vengence->vengeance
-verfication->verification
-verison->version
-verisons->versions
-vermillion->vermilion
-versitilaty->versatility
-versitlity->versatility
-vetween->between
-veyr->very
-vigeur->vigueur, vigour, vigor
-vigilence->vigilance
-vigourous->vigorous
-villian->villain
-villification->vilification
-villify->vilify
-villin->villi, villain, villein
-vincinity->vicinity
-violentce->violence
-virtualy->virtually
-virutal->virtual
-virutally->virtually
-visable->visible
-visably->visibly
-visting->visiting
-vistors->visitors
-vitories->victories
-volcanoe->volcano
-voleyball->volleyball
-volontary->voluntary
-volonteer->volunteer
-volonteered->volunteered
-volonteering->volunteering
-volonteers->volunteers
-volounteer->volunteer
-volounteered->volunteered
-volounteering->volunteering
-volounteers->volunteers
-volumne->volume
-vreity->variety
-vrey->very
-vriety->variety
-vulnerablility->vulnerability
-vyer->very
-vyre->very
-waht->what
-wanna->want to
-warantee->warranty
-wardobe->wardrobe
-warrent->warrant
-warrriors->warriors
-wasnt->wasn't
-wass->was
-watn->want
-wayword->wayward
-weaponary->weaponry
-weas->was
-wehn->when
-weild->wield, wild
-weilded->wielded
-wendsay->Wednesday
-wensday->Wednesday
-wereabouts->whereabouts
-whant->want
-whants->wants
-whcih->which
-wheras->whereas
-wherease->whereas
-whereever->wherever
-whic->which
-whihc->which
-whith->with
-whlch->which
-whn->when
-wholey->wholly
-wholy->wholly, holy
-whta->what
-whther->whether
-wich->which, witch
-widesread->widespread
-wief->wife
-wierd->weird
-wiew->view
-wih->with
-wiht->with
-wille->will
-willk->will
-willingless->willingness
-wirting->writing
-withdrawl->withdrawal, withdraw
-witheld->withheld
-withh->with
-withing->within
-withold->withhold
-witht->with
-witn->with
-wiull->will
-wnat->want
-wnated->wanted
-wnats->wants
-wohle->whole
-wokr->work
-wokring->working
-wonderfull->wonderful
-wordlwide->worldwide
-workststion->workstation
-worls->world
-worstened->worsened
-woudl->would
-wresters->wrestlers
-wriet->write
-writen->written
-wroet->wrote
-wrok->work
-wroking->working
-wtih->with
-wupport->support
-xenophoby->xenophobia
-yaching->yachting
-yaer->year
-yaerly->yearly
-yaers->years
-yatch->yacht
-yearm->year
-yeasr->years
-yeild->yield
-yeilding->yielding
-yera->year
-yrea->year
-yeras->years
-yersa->years
-yotube->youtube
-youseff->yousef
-youself->yourself
-ytou->you
-yuo->you
-zeebra->zebra
diff --git a/files/typos/typos-es.txt b/files/typos/typos-es.txt
deleted file mode 100644
index af2bccb23..000000000
--- a/files/typos/typos-es.txt
+++ /dev/null
@@ -1,733 +0,0 @@
-# This file contains a number of common Spanish typos:
-andriod->android
-
-# The remainder of this file contains misspellings from
-# http://es.wikipedia.org/wiki/Wikipedia:Lista_de_errores_ortogr%C3%A1ficos_comunes/M%C3%A1quinas
-# plus some post-processing to fix invalid entries, remove duplicates, etc.
-#
-# The content is available under the
-# "Creative Commons Attribution-ShareAlike License"
-# http://creativecommons.org/licenses/by-sa/3.0/
-#
-# THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE
-# COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY
-# COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS
-# AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
-#
-# BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE
-# TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY
-# BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS
-# CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND
-# CONDITIONS.
-#
-# *1. Definitions*
-#
-# 1. *"Adaptation"* means a work based upon the Work, or upon the Work
-# and other pre-existing works, such as a translation, adaptation,
-# derivative work, arrangement of music or other alterations of a
-# literary or artistic work, or phonogram or performance and includes
-# cinematographic adaptations or any other form in which the Work may
-# be recast, transformed, or adapted including in any form
-# recognizably derived from the original, except that a work that
-# constitutes a Collection will not be considered an Adaptation for
-# the purpose of this License. For the avoidance of doubt, where the
-# Work is a musical work, performance or phonogram, the
-# synchronization of the Work in timed-relation with a moving image
-# ("synching") will be considered an Adaptation for the purpose of
-# this License.
-# 2. *"Collection"* means a collection of literary or artistic works,
-# such as encyclopedias and anthologies, or performances, phonograms
-# or broadcasts, or other works or subject matter other than works
-# listed in Section 1(f) below, which, by reason of the selection and
-# arrangement of their contents, constitute intellectual creations, in
-# which the Work is included in its entirety in unmodified form along
-# with one or more other contributions, each constituting separate and
-# independent works in themselves, which together are assembled into a
-# collective whole. A work that constitutes a Collection will not be
-# considered an Adaptation (as defined below) for the purposes of this
-# License.
-# 3. *"Creative Commons Compatible License"* means a license that is
-# listed at http://creativecommons.org/compatiblelicenses that has
-# been approved by Creative Commons as being essentially equivalent to
-# this License, including, at a minimum, because that license: (i)
-# contains terms that have the same purpose, meaning and effect as the
-# License Elements of this License; and, (ii) explicitly permits the
-# relicensing of adaptations of works made available under that
-# license under this License or a Creative Commons jurisdiction
-# license with the same License Elements as this License.
-# 4. *"Distribute"* means to make available to the public the original
-# and copies of the Work or Adaptation, as appropriate, through sale
-# or other transfer of ownership.
-# 5. *"License Elements"* means the following high-level license
-# attributes as selected by Licensor and indicated in the title of
-# this License: Attribution, ShareAlike.
-# 6. *"Licensor"* means the individual, individuals, entity or entities
-# that offer(s) the Work under the terms of this License.
-# 7. *"Original Author"* means, in the case of a literary or artistic
-# work, the individual, individuals, entity or entities who created
-# the Work or if no individual or entity can be identified, the
-# publisher; and in addition (i) in the case of a performance the
-# actors, singers, musicians, dancers, and other persons who act,
-# sing, deliver, declaim, play in, interpret or otherwise perform
-# literary or artistic works or expressions of folklore; (ii) in the
-# case of a phonogram the producer being the person or legal entity
-# who first fixes the sounds of a performance or other sounds; and,
-# (iii) in the case of broadcasts, the organization that transmits the
-# broadcast.
-# 8. *"Work"* means the literary and/or artistic work offered under the
-# terms of this License including without limitation any production in
-# the literary, scientific and artistic domain, whatever may be the
-# mode or form of its expression including digital form, such as a
-# book, pamphlet and other writing; a lecture, address, sermon or
-# other work of the same nature; a dramatic or dramatico-musical work;
-# a choreographic work or entertainment in dumb show; a musical
-# composition with or without words; a cinematographic work to which
-# are assimilated works expressed by a process analogous to
-# cinematography; a work of drawing, painting, architecture,
-# sculpture, engraving or lithography; a photographic work to which
-# are assimilated works expressed by a process analogous to
-# photography; a work of applied art; an illustration, map, plan,
-# sketch or three-dimensional work relative to geography, topography,
-# architecture or science; a performance; a broadcast; a phonogram; a
-# compilation of data to the extent it is protected as a copyrightable
-# work; or a work performed by a variety or circus performer to the
-# extent it is not otherwise considered a literary or artistic work.
-# 9. *"You"* means an individual or entity exercising rights under this
-# License who has not previously violated the terms of this License
-# with respect to the Work, or who has received express permission
-# from the Licensor to exercise rights under this License despite a
-# previous violation.
-# 10. *"Publicly Perform"* means to perform public recitations of the Work
-# and to communicate to the public those public recitations, by any
-# means or process, including by wire or wireless means or public
-# digital performances; to make available to the public Works in such
-# a way that members of the public may access these Works from a place
-# and at a place individually chosen by them; to perform the Work to
-# the public by any means or process and the communication to the
-# public of the performances of the Work, including by public digital
-# performance; to broadcast and rebroadcast the Work by any means
-# including signs, sounds or images.
-# 11. *"Reproduce"* means to make copies of the Work by any means
-# including without limitation by sound or visual recordings and the
-# right of fixation and reproducing fixations of the Work, including
-# storage of a protected performance or phonogram in digital form or
-# other electronic medium.
-#
-# *2. Fair Dealing Rights.* Nothing in this License is intended to reduce,
-# limit, or restrict any uses free from copyright or rights arising from
-# limitations or exceptions that are provided for in connection with the
-# copyright protection under copyright law or other applicable laws.
-#
-# *3. License Grant.* Subject to the terms and conditions of this License,
-# Licensor hereby grants You a worldwide, royalty-free, non-exclusive,
-# perpetual (for the duration of the applicable copyright) license to
-# exercise the rights in the Work as stated below:
-#
-# 1. to Reproduce the Work, to incorporate the Work into one or more
-# Collections, and to Reproduce the Work as incorporated in the
-# Collections;
-# 2. to create and Reproduce Adaptations provided that any such
-# Adaptation, including any translation in any medium, takes
-# reasonable steps to clearly label, demarcate or otherwise identify
-# that changes were made to the original Work. For example, a
-# translation could be marked "The original work was translated from
-# English to Spanish," or a modification could indicate "The original
-# work has been modified.";
-# 3. to Distribute and Publicly Perform the Work including as
-# incorporated in Collections; and,
-# 4. to Distribute and Publicly Perform Adaptations.
-# 5.
-#
-# For the avoidance of doubt:
-#
-# 1. *Non-waivable Compulsory License Schemes*. In those
-# jurisdictions in which the right to collect royalties through
-# any statutory or compulsory licensing scheme cannot be waived,
-# the Licensor reserves the exclusive right to collect such
-# royalties for any exercise by You of the rights granted under
-# this License;
-# 2. *Waivable Compulsory License Schemes*. In those jurisdictions in
-# which the right to collect royalties through any statutory or
-# compulsory licensing scheme can be waived, the Licensor waives
-# the exclusive right to collect such royalties for any exercise
-# by You of the rights granted under this License; and,
-# 3. *Voluntary License Schemes*. The Licensor waives the right to
-# collect royalties, whether individually or, in the event that
-# the Licensor is a member of a collecting society that
-# administers voluntary licensing schemes, via that society, from
-# any exercise by You of the rights granted under this License.
-#
-# The above rights may be exercised in all media and formats whether now
-# known or hereafter devised. The above rights include the right to make
-# such modifications as are technically necessary to exercise the rights
-# in other media and formats. Subject to Section 8(f), all rights not
-# expressly granted by Licensor are hereby reserved.
-#
-# *4. Restrictions.* The license granted in Section 3 above is expressly
-# made subject to and limited by the following restrictions:
-#
-# 1. You may Distribute or Publicly Perform the Work only under the terms
-# of this License. You must include a copy of, or the Uniform Resource
-# Identifier (URI) for, this License with every copy of the Work You
-# Distribute or Publicly Perform. You may not offer or impose any
-# terms on the Work that restrict the terms of this License or the
-# ability of the recipient of the Work to exercise the rights granted
-# to that recipient under the terms of the License. You may not
-# sublicense the Work. You must keep intact all notices that refer to
-# this License and to the disclaimer of warranties with every copy of
-# the Work You Distribute or Publicly Perform. When You Distribute or
-# Publicly Perform the Work, You may not impose any effective
-# technological measures on the Work that restrict the ability of a
-# recipient of the Work from You to exercise the rights granted to
-# that recipient under the terms of the License. This Section 4(a)
-# applies to the Work as incorporated in a Collection, but this does
-# not require the Collection apart from the Work itself to be made
-# subject to the terms of this License. If You create a Collection,
-# upon notice from any Licensor You must, to the extent practicable,
-# remove from the Collection any credit as required by Section 4(c),
-# as requested. If You create an Adaptation, upon notice from any
-# Licensor You must, to the extent practicable, remove from the
-# Adaptation any credit as required by Section 4(c), as requested.
-# 2. You may Distribute or Publicly Perform an Adaptation only under the
-# terms of: (i) this License; (ii) a later version of this License
-# with the same License Elements as this License; (iii) a Creative
-# Commons jurisdiction license (either this or a later license
-# version) that contains the same License Elements as this License
-# (e.g., Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons
-# Compatible License. If you license the Adaptation under one of the
-# licenses mentioned in (iv), you must comply with the terms of that
-# license. If you license the Adaptation under the terms of any of the
-# licenses mentioned in (i), (ii) or (iii) (the "Applicable License"),
-# you must comply with the terms of the Applicable License generally
-# and the following provisions: (I) You must include a copy of, or the
-# URI for, the Applicable License with every copy of each Adaptation
-# You Distribute or Publicly Perform; (II) You may not offer or impose
-# any terms on the Adaptation that restrict the terms of the
-# Applicable License or the ability of the recipient of the Adaptation
-# to exercise the rights granted to that recipient under the terms of
-# the Applicable License; (III) You must keep intact all notices that
-# refer to the Applicable License and to the disclaimer of warranties
-# with every copy of the Work as included in the Adaptation You
-# Distribute or Publicly Perform; (IV) when You Distribute or Publicly
-# Perform the Adaptation, You may not impose any effective
-# technological measures on the Adaptation that restrict the ability
-# of a recipient of the Adaptation from You to exercise the rights
-# granted to that recipient under the terms of the Applicable License.
-# This Section 4(b) applies to the Adaptation as incorporated in a
-# Collection, but this does not require the Collection apart from the
-# Adaptation itself to be made subject to the terms of the Applicable
-# License.
-# 3. If You Distribute, or Publicly Perform the Work or any Adaptations
-# or Collections, You must, unless a request has been made pursuant to
-# Section 4(a), keep intact all copyright notices for the Work and
-# provide, reasonable to the medium or means You are utilizing: (i)
-# the name of the Original Author (or pseudonym, if applicable) if
-# supplied, and/or if the Original Author and/or Licensor designate
-# another party or parties (e.g., a sponsor institute, publishing
-# entity, journal) for attribution ("Attribution Parties") in
-# Licensor's copyright notice, terms of service or by other reasonable
-# means, the name of such party or parties; (ii) the title of the Work
-# if supplied; (iii) to the extent reasonably practicable, the URI, if
-# any, that Licensor specifies to be associated with the Work, unless
-# such URI does not refer to the copyright notice or licensing
-# information for the Work; and (iv) , consistent with Ssection 3(b),
-# in the case of an Adaptation, a credit identifying the use of the
-# Work in the Adaptation (e.g., "French translation of the Work by
-# Original Author," or "Screenplay based on original Work by Original
-# Author"). The credit required by this Section 4(c) may be
-# implemented in any reasonable manner; provided, however, that in the
-# case of a Adaptation or Collection, at a minimum such credit will
-# appear, if a credit for all contributing authors of the Adaptation
-# or Collection appears, then as part of these credits and in a manner
-# at least as prominent as the credits for the other contributing
-# authors. For the avoidance of doubt, You may only use the credit
-# required by this Section for the purpose of attribution in the
-# manner set out above and, by exercising Your rights under this
-# License, You may not implicitly or explicitly assert or imply any
-# connection with, sponsorship or endorsement by the Original Author,
-# Licensor and/or Attribution Parties, as appropriate, of You or Your
-# use of the Work, without the separate, express prior written
-# permission of the Original Author, Licensor and/or Attribution Parties.
-# 4. Except as otherwise agreed in writing by the Licensor or as may be
-# otherwise permitted by applicable law, if You Reproduce, Distribute
-# or Publicly Perform the Work either by itself or as part of any
-# Adaptations or Collections, You must not distort, mutilate, modify
-# or take other derogatory action in relation to the Work which would
-# be prejudicial to the Original Author's honor or reputation.
-# Licensor agrees that in those jurisdictions (e.g. Japan), in which
-# any exercise of the right granted in Section 3(b) of this License
-# (the right to make Adaptations) would be deemed to be a distortion,
-# mutilation, modification or other derogatory action prejudicial to
-# the Original Author's honor and reputation, the Licensor will waive
-# or not assert, as appropriate, this Section, to the fullest extent
-# permitted by the applicable national law, to enable You to
-# reasonably exercise Your right under Section 3(b) of this License
-# (right to make Adaptations) but not otherwise.
-#
-# *5. Representations, Warranties and Disclaimer*
-#
-# UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR
-# OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY
-# KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE,
-# INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY,
-# FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF
-# LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS,
-# WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE
-# EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.
-#
-# *6. Limitation on Liability.* EXCEPT TO THE EXTENT REQUIRED BY
-# APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL
-# THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY
-# DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF
-# LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-#
-# *7. Termination*
-#
-# 1. This License and the rights granted hereunder will terminate
-# automatically upon any breach by You of the terms of this License.
-# Individuals or entities who have received Adaptations or Collections
-# from You under this License, however, will not have their licenses
-# terminated provided such individuals or entities remain in full
-# compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will
-# survive any termination of this License.
-# 2. Subject to the above terms and conditions, the license granted here
-# is perpetual (for the duration of the applicable copyright in the
-# Work). Notwithstanding the above, Licensor reserves the right to
-# release the Work under different license terms or to stop
-# distributing the Work at any time; provided, however that any such
-# election will not serve to withdraw this License (or any other
-# license that has been, or is required to be, granted under the terms
-# of this License), and this License will continue in full force and
-# effect unless terminated as stated above.
-#
-# *8. Miscellaneous*
-#
-# 1. Each time You Distribute or Publicly Perform the Work or a
-# Collection, the Licensor offers to the recipient a license to the
-# Work on the same terms and conditions as the license granted to You
-# under this License.
-# 2. Each time You Distribute or Publicly Perform an Adaptation, Licensor
-# offers to the recipient a license to the original Work on the same
-# terms and conditions as the license granted to You under this License.
-# 3. If any provision of this License is invalid or unenforceable under
-# applicable law, it shall not affect the validity or enforceability
-# of the remainder of the terms of this License, and without further
-# action by the parties to this agreement, such provision shall be
-# reformed to the minimum extent necessary to make such provision
-# valid and enforceable.
-# 4. No term or provision of this License shall be deemed waived and no
-# breach consented to unless such waiver or consent shall be in
-# writing and signed by the party to be charged with such waiver or
-# consent.
-# 5. This License constitutes the entire agreement between the parties
-# with respect to the Work licensed here. There are no understandings,
-# agreements or representations with respect to the Work not specified
-# here. Licensor shall not be bound by any additional provisions that
-# may appear in any communication from You. This License may not be
-# modified without the mutual written agreement of the Licensor and You.
-# 6. The rights granted under, and the subject matter referenced, in this
-# License were drafted utilizing the terminology of the Berne
-# Convention for the Protection of Literary and Artistic Works (as
-# amended on September 28, 1979), the Rome Convention of 1961, the
-# WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms
-# Treaty of 1996 and the Universal Copyright Convention (as revised on
-# July 24, 1971). These rights and subject matter take effect in the
-# relevant jurisdiction in which the License terms are sought to be
-# enforced according to the corresponding provisions of the
-# implementation of those treaty provisions in the applicable national
-# law. If the standard suite of rights granted under applicable
-# copyright law includes additional rights not granted under this
-# License, such additional rights are deemed to be included in the
-# License; this License is not intended to restrict the license of any
-# rights under applicable law.
-absorver->absorber
-absorviendo->absorbiendo
-aca->acá
-academica->académica
-academicamente->académicamente
-academico->académico
-accion->acción
-aceptacion->aceptación
-acetado->aceptado
-ademas->además
-administracion->administración
-aerea->aérea
-aereo->aéreo
-aficion->afición
-aficcion->afición
-aficción->afición
-ahi->ahí
-al Cairo->a El Cairo
-album->álbum
-alevin->alevín
-algun->algún
-alli->allí
-alla->allá
-al rededor->alrededor
-aprobechar->aprovechar
-aqui->aquí
-arabe->árabe
-arbol->árbol
-area->área
-articulacion->articulación
-asi->así
-atencion->atención
-atlantico->atlántico
-automovil->automóvil
-avion->avión
-azucar->azúcar
-bibliografia->bibliografía
-bién->bien
-Bogota->Bogotá
-Brasilero->brasileño
-Brasilera->brasileña
-buho->búho
-cadaver->cadáver
-cafe->café
-cafeteria->cafetería
-camaleon->camaleón
-camara->cámara
-cancion->canción
-candadear->candear
-caracter->carácter
-caracteristica->característica
-carroceria->carrocería
-catastrofe->catástrofe
-catastrofica->catastrófica
-catastrofico->catastrófico
-categoria->categoría
-cién->cien
-CD's->CD
-CDs->CD
-cogeran->cogerán
-cogia->cogía
-cogian->cogían
-cojer->coger
-cojen->cogen
-cojerán->cogerán
-cojía->cogía
-cojia->cogía
-cojían->cogían
-cojió->cogió
-companía->compañía
-compañia->compañía
-compasion->compasión
-comun->común
-comunmente->comúnmente
-conección->conexión
-cono urbano->conurbano
-consideracion->consideración
-constituída->constituida
-constituído->constituido
-construído->construido
-construír->construir
-continuan->continúan
-contínuo->continuo
-convirtio->convirtió
-cortesmente->cortésmente
-cronologica->cronológica
-cronologicamente->cronológicamente
-cronologico->cronológico
-da a lugar a->da lugar a
-dar a lugar a->dar lugar a
-daría a lugar a->daría lugar a
-dá->da
-definio->definió
-del Cairo->de El Cairo
-del interfaz->de la interfaz
-delfin->delfín
-desconto->descontó
-desovediente->desobediente
-deshechar->desechar
-deshechando->desechando
-despues->después
-dia->día
-dias->días
-dieciseis->dieciséis
-diéz->diez
-dificil->difícil
-dificilmente->difícilmente
-dio a lugar a->dio lugar a
-dió->dio
-discusion->discusión
-disolucion->disolución
-distorción->distorsión
-distorcionado->distorsionado
-distribuído->distribuido
-duodecimo->duodécimo
-e hielo->y hielo
-e hierro->y hierro
-e iones->y iones
-ebano->ébano
-eclesiastico->eclesiástico
-eclesiasticos->eclesiásticos
-el fue->él fue
-el interfaz->la interfaz
-el Osasuna->Osasuna
-embarcacion->embarcación
-enbarcacion->embarcación
-enbarcación->embarcación
-empezo->empezó
-enlaze->enlace
-eolico->eólico
-equalización->ecualización
-equalizador->ecualizador
-equalizar->ecualizar
-espiritu->espíritu
-estan->están
-estandard->estándar
-estándard->estándar
-etc...->etc.
-etimologia->etimología
-exámen->examen
-examenes->exámenes
-exitar->excitar
-exito->éxito
-exemplo->ejemplo
-explendor->esplendor
-extrangero->extranjero
-estranjero->extranjero
-estrangero->extranjero
-extricta->estricta
-extricto->estricto
-extrictamente->estrictamente
-espia->espía
-esprecion->expresión
-espreción->expresión
-espresion->expresión
-espresión->expresión
-expresion->expresión
-facil->fácil
-facilmente->fácilmente
-fanatica->fanática
-fanaticamente->fanáticamente
-fanatico->fanático
-fé->fe
-ficcion->ficción
-fisica->física
-fluído->fluido
-fricion->fricción
-frición->fricción
-friccion->fricción
-fucion->fusión
-fución->fusión
-fué->fue
-fuí->fui
-funcion->función
-fusion->fusión
-futbol->fútbol
-futil->fútil
-garage->garaje
-guión->guion
-Guipuzcoa->Guipúzcoa
-gustaria->gustaría
-Gutierrez->Gutiérrez
-habia->había
-haiga->haya
-habian->habían
-hechar->echar
-hechado->echado
-herbivoro->herbívoro
-herviboro->herbívoro
-hervíboro->herbívoro
-hervivoro->herbívoro
-hervívoro->herbívoro
-hermita->ermita
-heroe->héroe
-heróica->heroica
-heróico->heroico
-hibridización->hibridación
-hinduísmo->hinduismo
-hinduísta->hinduista
-homogenea->homogénea
-homogeneo->homogéneo
-hormigon->hormigón
-ideologia->ideología
-ideologica->ideológica
-ideologicamente->ideológicamente
-ideologico->ideológico
-imágen->imagen
-imagenes->imágenes
-IMDB->IMDb
-incluído->incluido
-incluír->incluir
-indice->índice
-interface->interfaz
-interperie->intemperie
-inutil->inútil
-invasion->invasión
-israeli->israelí
-israelies->israelíes
-jardin->jardín
-jente->gente
-jóven->joven
-judia->judía
-judias->judías
-judio->judío
-judios->judíos
-Km->km
-km2->km²
-lampara->lámpara
-le hecha->le echa
-leido->leído
-leon->león
-lider->líder
-linea->línea
-lineas->líneas
-linia->línea
-llendo->yendo
-llevada acabo->llevada a cabo
-llevado acabo->llevado a cabo
-llevaron acabo->llevaron a cabo
-llevó acabo->llevó a cabo
-logica->lógica
-logicamente->lógicamente
-logico->lógico
-lo hecha->lo echa
-lonjeva->longeva
-lonjevo->longevo
-mecanica->mecánica
-mecanicamente->mecánicamente
-mecanico->mecánico
-magica->mágica
-magico->mágico
-martir->mártir
-maxima->máxima
-maximo->máximo
-mayoria->mayoría
-mayuscula->mayúscula
-mayusculo->mayúsculo
-metodologia->metodología
-Mexico->México
-míl->mil
-minima->mínima
-minimo->mínimo
-minoria->minoría
-minuscula->minúscula
-minusculo->minúsculo
-mitologia->mitología
-mitologica->mitológica
-mitologico->mitológico
-mitomana->mitómana
-mitomania->mitomanía
-mitomano->mitómano
-monton->montón
-movil->móvil
-murciegalo->murciélago
-murciégalo->murciélago
-murio->murió
-musica->música
-nacio->nació
-nadien->nadie
-ningun->ningún
-oceano->océano
-olimpica->olímpica
-olimpicamente->olímpicamente
-olimpico->olímpico
-operacion->operación
-oraculo->oráculo
-órden->orden
-organica->orgánica
-organico->orgánico
-organo->órgano
-orígen->origen
-origenes->orígenes
-osea->o sea
-oceano pacifico->océano pacífico
-ONG's->ONG
-ONGs-> ONG
-OVNI's->OVNI
-OVNIs->OVNI
-pagina->página
-pais->país
-paparazzis->paparazzi
-participacion->participación
-pasion->pasión
-pelicula->película
-peloton->pelotón
-perfíl->perfil
-persuación->persuasión
-politica->política
-politicamente->políticamente
-politico->político
-por contra-> por el contrario
-practicamente->prácticamente
-prerequisito->prerrequisito
-pre-requisito->prerrequisito
-preveer->prever
-prevencion->prevención
-programacion->programación
-promocion->promoción
-protejer->proteger
-publicamente->públicamente
-quiza->quizá
-quizas->quizás
-rapido->rápido
-rapida->rápida
-regilla->rejilla
-remplazar->reemplazar
-republica->república
-resolucion->resolución
-restaurant->restaurante
-revizado->revisado
-revizar->revisar
-revolucion->revolución
-rocin->rocín
-ruído->ruido
-sacerdotiza->sacerdotisa
-sazon->sazón
-se a->se ha
-séis->seis
-segun->según
-sera->será
-serpentin->serpentín
-sinembargo->sin embargo
-sinfin->sinfín
-slogan->eslogan
-sóla->sola
-sólamente->solamente
-solucion->solución
-stándard->estándar
-subrraya->subraya
-subrrayado->subrayado
-subrrayar->subrayar
-superfície->superficie
-supérflua->superflua
-tagea->tajea
-talvez->tal vez
-tambien->también
-tanbien->también
-tanbién->también
-tecnica->técnica
-tecnicamente->técnicamente
-tecnico->técnico
-tí->ti
-tia->tía
-tio->tío
-tipica->típica
-tipicamente->típicamente
-tipico->típico
-tradució->tradujo,traducción
-traducion->traducción
-tradución->traducción
-traduccion->traducción
-traf->tráf
-tunel->túnel
-ubicacion->ubicación
-ultimamente->últimamente
-ultimo->último
-ultimos->últimos
-un interfaz->una interfaz
-undecimo->undécimo
-unica->única
-unicamente->únicamente
-unico->único
-util->útil
-vease->véase
-veintidos->veintidós
-veintiseis->veintiséis
-veintitres->veintitrés
-vision->visión
-via->vía
-vió->vio
-watios->vatios
diff --git a/files/typos/typos-hu.txt b/files/typos/typos-hu.txt
deleted file mode 100644
index e0586bf4d..000000000
--- a/files/typos/typos-hu.txt
+++ /dev/null
@@ -1,431 +0,0 @@
-# This file contains a number of common Hungarian typos:
-andriod->android
-
-# The remainder of this file contains misspellings from
-# http://hu.wikipedia.org/wiki/Szerkeszt%C5%91:AntiVandal/Hiba
-# plus some post-processing to fix invalid entries, remove duplicates, etc.
-#
-# The content is available under the
-# "Creative Commons Attribution-ShareAlike License"
-# http://creativecommons.org/licenses/by-sa/3.0/
-#
-# THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE
-# COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY
-# COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS
-# AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
-#
-# BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE
-# TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY
-# BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS
-# CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND
-# CONDITIONS.
-#
-# *1. Definitions*
-#
-# 1. *"Adaptation"* means a work based upon the Work, or upon the Work
-# and other pre-existing works, such as a translation, adaptation,
-# derivative work, arrangement of music or other alterations of a
-# literary or artistic work, or phonogram or performance and includes
-# cinematographic adaptations or any other form in which the Work may
-# be recast, transformed, or adapted including in any form
-# recognizably derived from the original, except that a work that
-# constitutes a Collection will not be considered an Adaptation for
-# the purpose of this License. For the avoidance of doubt, where the
-# Work is a musical work, performance or phonogram, the
-# synchronization of the Work in timed-relation with a moving image
-# ("synching") will be considered an Adaptation for the purpose of
-# this License.
-# 2. *"Collection"* means a collection of literary or artistic works,
-# such as encyclopedias and anthologies, or performances, phonograms
-# or broadcasts, or other works or subject matter other than works
-# listed in Section 1(f) below, which, by reason of the selection and
-# arrangement of their contents, constitute intellectual creations, in
-# which the Work is included in its entirety in unmodified form along
-# with one or more other contributions, each constituting separate and
-# independent works in themselves, which together are assembled into a
-# collective whole. A work that constitutes a Collection will not be
-# considered an Adaptation (as defined below) for the purposes of this
-# License.
-# 3. *"Creative Commons Compatible License"* means a license that is
-# listed at http://creativecommons.org/compatiblelicenses that has
-# been approved by Creative Commons as being essentially equivalent to
-# this License, including, at a minimum, because that license: (i)
-# contains terms that have the same purpose, meaning and effect as the
-# License Elements of this License; and, (ii) explicitly permits the
-# relicensing of adaptations of works made available under that
-# license under this License or a Creative Commons jurisdiction
-# license with the same License Elements as this License.
-# 4. *"Distribute"* means to make available to the public the original
-# and copies of the Work or Adaptation, as appropriate, through sale
-# or other transfer of ownership.
-# 5. *"License Elements"* means the following high-level license
-# attributes as selected by Licensor and indicated in the title of
-# this License: Attribution, ShareAlike.
-# 6. *"Licensor"* means the individual, individuals, entity or entities
-# that offer(s) the Work under the terms of this License.
-# 7. *"Original Author"* means, in the case of a literary or artistic
-# work, the individual, individuals, entity or entities who created
-# the Work or if no individual or entity can be identified, the
-# publisher; and in addition (i) in the case of a performance the
-# actors, singers, musicians, dancers, and other persons who act,
-# sing, deliver, declaim, play in, interpret or otherwise perform
-# literary or artistic works or expressions of folklore; (ii) in the
-# case of a phonogram the producer being the person or legal entity
-# who first fixes the sounds of a performance or other sounds; and,
-# (iii) in the case of broadcasts, the organization that transmits the
-# broadcast.
-# 8. *"Work"* means the literary and/or artistic work offered under the
-# terms of this License including without limitation any production in
-# the literary, scientific and artistic domain, whatever may be the
-# mode or form of its expression including digital form, such as a
-# book, pamphlet and other writing; a lecture, address, sermon or
-# other work of the same nature; a dramatic or dramatico-musical work;
-# a choreographic work or entertainment in dumb show; a musical
-# composition with or without words; a cinematographic work to which
-# are assimilated works expressed by a process analogous to
-# cinematography; a work of drawing, painting, architecture,
-# sculpture, engraving or lithography; a photographic work to which
-# are assimilated works expressed by a process analogous to
-# photography; a work of applied art; an illustration, map, plan,
-# sketch or three-dimensional work relative to geography, topography,
-# architecture or science; a performance; a broadcast; a phonogram; a
-# compilation of data to the extent it is protected as a copyrightable
-# work; or a work performed by a variety or circus performer to the
-# extent it is not otherwise considered a literary or artistic work.
-# 9. *"You"* means an individual or entity exercising rights under this
-# License who has not previously violated the terms of this License
-# with respect to the Work, or who has received express permission
-# from the Licensor to exercise rights under this License despite a
-# previous violation.
-# 10. *"Publicly Perform"* means to perform public recitations of the Work
-# and to communicate to the public those public recitations, by any
-# means or process, including by wire or wireless means or public
-# digital performances; to make available to the public Works in such
-# a way that members of the public may access these Works from a place
-# and at a place individually chosen by them; to perform the Work to
-# the public by any means or process and the communication to the
-# public of the performances of the Work, including by public digital
-# performance; to broadcast and rebroadcast the Work by any means
-# including signs, sounds or images.
-# 11. *"Reproduce"* means to make copies of the Work by any means
-# including without limitation by sound or visual recordings and the
-# right of fixation and reproducing fixations of the Work, including
-# storage of a protected performance or phonogram in digital form or
-# other electronic medium.
-#
-# *2. Fair Dealing Rights.* Nothing in this License is intended to reduce,
-# limit, or restrict any uses free from copyright or rights arising from
-# limitations or exceptions that are provided for in connection with the
-# copyright protection under copyright law or other applicable laws.
-#
-# *3. License Grant.* Subject to the terms and conditions of this License,
-# Licensor hereby grants You a worldwide, royalty-free, non-exclusive,
-# perpetual (for the duration of the applicable copyright) license to
-# exercise the rights in the Work as stated below:
-#
-# 1. to Reproduce the Work, to incorporate the Work into one or more
-# Collections, and to Reproduce the Work as incorporated in the
-# Collections;
-# 2. to create and Reproduce Adaptations provided that any such
-# Adaptation, including any translation in any medium, takes
-# reasonable steps to clearly label, demarcate or otherwise identify
-# that changes were made to the original Work. For example, a
-# translation could be marked "The original work was translated from
-# English to Spanish," or a modification could indicate "The original
-# work has been modified.";
-# 3. to Distribute and Publicly Perform the Work including as
-# incorporated in Collections; and,
-# 4. to Distribute and Publicly Perform Adaptations.
-# 5.
-#
-# For the avoidance of doubt:
-#
-# 1. *Non-waivable Compulsory License Schemes*. In those
-# jurisdictions in which the right to collect royalties through
-# any statutory or compulsory licensing scheme cannot be waived,
-# the Licensor reserves the exclusive right to collect such
-# royalties for any exercise by You of the rights granted under
-# this License;
-# 2. *Waivable Compulsory License Schemes*. In those jurisdictions in
-# which the right to collect royalties through any statutory or
-# compulsory licensing scheme can be waived, the Licensor waives
-# the exclusive right to collect such royalties for any exercise
-# by You of the rights granted under this License; and,
-# 3. *Voluntary License Schemes*. The Licensor waives the right to
-# collect royalties, whether individually or, in the event that
-# the Licensor is a member of a collecting society that
-# administers voluntary licensing schemes, via that society, from
-# any exercise by You of the rights granted under this License.
-#
-# The above rights may be exercised in all media and formats whether now
-# known or hereafter devised. The above rights include the right to make
-# such modifications as are technically necessary to exercise the rights
-# in other media and formats. Subject to Section 8(f), all rights not
-# expressly granted by Licensor are hereby reserved.
-#
-# *4. Restrictions.* The license granted in Section 3 above is expressly
-# made subject to and limited by the following restrictions:
-#
-# 1. You may Distribute or Publicly Perform the Work only under the terms
-# of this License. You must include a copy of, or the Uniform Resource
-# Identifier (URI) for, this License with every copy of the Work You
-# Distribute or Publicly Perform. You may not offer or impose any
-# terms on the Work that restrict the terms of this License or the
-# ability of the recipient of the Work to exercise the rights granted
-# to that recipient under the terms of the License. You may not
-# sublicense the Work. You must keep intact all notices that refer to
-# this License and to the disclaimer of warranties with every copy of
-# the Work You Distribute or Publicly Perform. When You Distribute or
-# Publicly Perform the Work, You may not impose any effective
-# technological measures on the Work that restrict the ability of a
-# recipient of the Work from You to exercise the rights granted to
-# that recipient under the terms of the License. This Section 4(a)
-# applies to the Work as incorporated in a Collection, but this does
-# not require the Collection apart from the Work itself to be made
-# subject to the terms of this License. If You create a Collection,
-# upon notice from any Licensor You must, to the extent practicable,
-# remove from the Collection any credit as required by Section 4(c),
-# as requested. If You create an Adaptation, upon notice from any
-# Licensor You must, to the extent practicable, remove from the
-# Adaptation any credit as required by Section 4(c), as requested.
-# 2. You may Distribute or Publicly Perform an Adaptation only under the
-# terms of: (i) this License; (ii) a later version of this License
-# with the same License Elements as this License; (iii) a Creative
-# Commons jurisdiction license (either this or a later license
-# version) that contains the same License Elements as this License
-# (e.g., Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons
-# Compatible License. If you license the Adaptation under one of the
-# licenses mentioned in (iv), you must comply with the terms of that
-# license. If you license the Adaptation under the terms of any of the
-# licenses mentioned in (i), (ii) or (iii) (the "Applicable License"),
-# you must comply with the terms of the Applicable License generally
-# and the following provisions: (I) You must include a copy of, or the
-# URI for, the Applicable License with every copy of each Adaptation
-# You Distribute or Publicly Perform; (II) You may not offer or impose
-# any terms on the Adaptation that restrict the terms of the
-# Applicable License or the ability of the recipient of the Adaptation
-# to exercise the rights granted to that recipient under the terms of
-# the Applicable License; (III) You must keep intact all notices that
-# refer to the Applicable License and to the disclaimer of warranties
-# with every copy of the Work as included in the Adaptation You
-# Distribute or Publicly Perform; (IV) when You Distribute or Publicly
-# Perform the Adaptation, You may not impose any effective
-# technological measures on the Adaptation that restrict the ability
-# of a recipient of the Adaptation from You to exercise the rights
-# granted to that recipient under the terms of the Applicable License.
-# This Section 4(b) applies to the Adaptation as incorporated in a
-# Collection, but this does not require the Collection apart from the
-# Adaptation itself to be made subject to the terms of the Applicable
-# License.
-# 3. If You Distribute, or Publicly Perform the Work or any Adaptations
-# or Collections, You must, unless a request has been made pursuant to
-# Section 4(a), keep intact all copyright notices for the Work and
-# provide, reasonable to the medium or means You are utilizing: (i)
-# the name of the Original Author (or pseudonym, if applicable) if
-# supplied, and/or if the Original Author and/or Licensor designate
-# another party or parties (e.g., a sponsor institute, publishing
-# entity, journal) for attribution ("Attribution Parties") in
-# Licensor's copyright notice, terms of service or by other reasonable
-# means, the name of such party or parties; (ii) the title of the Work
-# if supplied; (iii) to the extent reasonably practicable, the URI, if
-# any, that Licensor specifies to be associated with the Work, unless
-# such URI does not refer to the copyright notice or licensing
-# information for the Work; and (iv) , consistent with Ssection 3(b),
-# in the case of an Adaptation, a credit identifying the use of the
-# Work in the Adaptation (e.g., "French translation of the Work by
-# Original Author," or "Screenplay based on original Work by Original
-# Author"). The credit required by this Section 4(c) may be
-# implemented in any reasonable manner; provided, however, that in the
-# case of a Adaptation or Collection, at a minimum such credit will
-# appear, if a credit for all contributing authors of the Adaptation
-# or Collection appears, then as part of these credits and in a manner
-# at least as prominent as the credits for the other contributing
-# authors. For the avoidance of doubt, You may only use the credit
-# required by this Section for the purpose of attribution in the
-# manner set out above and, by exercising Your rights under this
-# License, You may not implicitly or explicitly assert or imply any
-# connection with, sponsorship or endorsement by the Original Author,
-# Licensor and/or Attribution Parties, as appropriate, of You or Your
-# use of the Work, without the separate, express prior written
-# permission of the Original Author, Licensor and/or Attribution Parties.
-# 4. Except as otherwise agreed in writing by the Licensor or as may be
-# otherwise permitted by applicable law, if You Reproduce, Distribute
-# or Publicly Perform the Work either by itself or as part of any
-# Adaptations or Collections, You must not distort, mutilate, modify
-# or take other derogatory action in relation to the Work which would
-# be prejudicial to the Original Author's honor or reputation.
-# Licensor agrees that in those jurisdictions (e.g. Japan), in which
-# any exercise of the right granted in Section 3(b) of this License
-# (the right to make Adaptations) would be deemed to be a distortion,
-# mutilation, modification or other derogatory action prejudicial to
-# the Original Author's honor and reputation, the Licensor will waive
-# or not assert, as appropriate, this Section, to the fullest extent
-# permitted by the applicable national law, to enable You to
-# reasonably exercise Your right under Section 3(b) of this License
-# (right to make Adaptations) but not otherwise.
-#
-# *5. Representations, Warranties and Disclaimer*
-#
-# UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR
-# OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY
-# KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE,
-# INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY,
-# FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF
-# LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS,
-# WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE
-# EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.
-#
-# *6. Limitation on Liability.* EXCEPT TO THE EXTENT REQUIRED BY
-# APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL
-# THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY
-# DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF
-# LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-#
-# *7. Termination*
-#
-# 1. This License and the rights granted hereunder will terminate
-# automatically upon any breach by You of the terms of this License.
-# Individuals or entities who have received Adaptations or Collections
-# from You under this License, however, will not have their licenses
-# terminated provided such individuals or entities remain in full
-# compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will
-# survive any termination of this License.
-# 2. Subject to the above terms and conditions, the license granted here
-# is perpetual (for the duration of the applicable copyright in the
-# Work). Notwithstanding the above, Licensor reserves the right to
-# release the Work under different license terms or to stop
-# distributing the Work at any time; provided, however that any such
-# election will not serve to withdraw this License (or any other
-# license that has been, or is required to be, granted under the terms
-# of this License), and this License will continue in full force and
-# effect unless terminated as stated above.
-#
-# *8. Miscellaneous*
-#
-# 1. Each time You Distribute or Publicly Perform the Work or a
-# Collection, the Licensor offers to the recipient a license to the
-# Work on the same terms and conditions as the license granted to You
-# under this License.
-# 2. Each time You Distribute or Publicly Perform an Adaptation, Licensor
-# offers to the recipient a license to the original Work on the same
-# terms and conditions as the license granted to You under this License.
-# 3. If any provision of this License is invalid or unenforceable under
-# applicable law, it shall not affect the validity or enforceability
-# of the remainder of the terms of this License, and without further
-# action by the parties to this agreement, such provision shall be
-# reformed to the minimum extent necessary to make such provision
-# valid and enforceable.
-# 4. No term or provision of this License shall be deemed waived and no
-# breach consented to unless such waiver or consent shall be in
-# writing and signed by the party to be charged with such waiver or
-# consent.
-# 5. This License constitutes the entire agreement between the parties
-# with respect to the Work licensed here. There are no understandings,
-# agreements or representations with respect to the Work not specified
-# here. Licensor shall not be bound by any additional provisions that
-# may appear in any communication from You. This License may not be
-# modified without the mutual written agreement of the Licensor and You.
-# 6. The rights granted under, and the subject matter referenced, in this
-# License were drafted utilizing the terminology of the Berne
-# Convention for the Protection of Literary and Artistic Works (as
-# amended on September 28, 1979), the Rome Convention of 1961, the
-# WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms
-# Treaty of 1996 and the Universal Copyright Convention (as revised on
-# July 24, 1971). These rights and subject matter take effect in the
-# relevant jurisdiction in which the License terms are sought to be
-# enforced according to the corresponding provisions of the
-# implementation of those treaty provisions in the applicable national
-# law. If the standard suite of rights granted under applicable
-# copyright law includes additional rights not granted under this
-# License, such additional rights are deemed to be included in the
-# License; this License is not intended to restrict the license of any
-# rights under applicable law.
-0-át->0-t
-1.-én->1-jén
-10.-én->10-én
-11.-én->11-én
-12.-én->12-én
-13.-án->13-án
-14.-én->14-én
-15.-én->15-én
-16.-án->16-án
-17.-én->17-én
-18.-án->18-án
-19.-én->19-én
-1-e->1-je
-1-el->1-gyel
-1-én->1-jén
-2.-án->2-án
-20.-án->20-án
-21.-én->21-én
-22.-én->22-én
-23.-án->23-án
-24.-én->24-én
-25.-én->25-én
-26.-án->26-án
-27.-én->27-én
-28.-án->28-án
-29.-én->29-én
-2-őt->2-t
-3.-án->3-án
-30.-án->30-án
-31.-én->31-én
-4.-én->4-én
-5.-én->5-én
-6.-án->6-án
-7.-én->7-én
-8.-án->8-án
-9.-én->9-én
-abszolut->abszolút
-ambíciózus->ambiciózus
-asszimetrikus->aszimmetrikus
-árú->áru
-azomban->azonban
-bejjebb->beljebb
-bisztos->biztos
-brilliáns->briliáns
-cimke->címke
-dícséret->dicséret
-egyenlőre->egyelőre
-egyértelmüsítő->egyértelműsítő
-eggyütt->együtt
-elipszis->ellipszis
-follyon->folyjon
-hektóliter->hektoliter
-hellénista->hellenista
-hellénisztikus->hellenisztikus
-hellénizmus->hellenizmus
-Horatiussal->Horatiusszal
-igéret->ígéret
-irígy->irigy
-kálcium->kalcium
-kellet->kellett
-keveseb->kevesebb
-kilóméter->kilométer
-kisseb->kisebb
-kissebb->kisebb
-konkurrencia->konkurencia
-konkurrens->konkurens
-könnyeb->könnyebb
-könyebb->könnyebb
-kultura->kultúra
-kultúrális->kulturális
-külömbség->különbség
-külömböző->különböző
-legjob->legjobb
-legkeveseb->legkevesebb
-legnagyob->legnagyobb
-lessz->lesz
-mellet->mellett
-mindíg->mindig
-muszály->muszáj
-new yorki->New York-i
-orzság->ország
-önnálló->önálló
-raffinált->rafinált
-szinvonal->színvonal
-Szovjetúnió->Szovjetunió
-Torino-i->torinói
-únió->unió
-vákum->vákuum
-Vietnám->Vietnam
diff --git a/files/typos/typos-it.txt b/files/typos/typos-it.txt
deleted file mode 100644
index 5c2d4965c..000000000
--- a/files/typos/typos-it.txt
+++ /dev/null
@@ -1,665 +0,0 @@
-# This file contains a number of common Italian typos:
-andriod->android
-
-# The remainder of this file contains misspellings from
-# http://it.m.wikipedia.org/wiki/Utente:Senpai/Lista_degli_errori_comuni/Formato_macchina
-# plus some post-processing to fix invalid entries, remove duplicates, etc.
-#
-# The content is available under the
-# "Creative Commons Attribution-ShareAlike License"
-# http://creativecommons.org/licenses/by-sa/3.0/
-#
-# THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE
-# COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY
-# COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS
-# AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
-#
-# BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE
-# TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY
-# BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS
-# CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND
-# CONDITIONS.
-#
-# *1. Definitions*
-#
-# 1. *"Adaptation"* means a work based upon the Work, or upon the Work
-# and other pre-existing works, such as a translation, adaptation,
-# derivative work, arrangement of music or other alterations of a
-# literary or artistic work, or phonogram or performance and includes
-# cinematographic adaptations or any other form in which the Work may
-# be recast, transformed, or adapted including in any form
-# recognizably derived from the original, except that a work that
-# constitutes a Collection will not be considered an Adaptation for
-# the purpose of this License. For the avoidance of doubt, where the
-# Work is a musical work, performance or phonogram, the
-# synchronization of the Work in timed-relation with a moving image
-# ("synching") will be considered an Adaptation for the purpose of
-# this License.
-# 2. *"Collection"* means a collection of literary or artistic works,
-# such as encyclopedias and anthologies, or performances, phonograms
-# or broadcasts, or other works or subject matter other than works
-# listed in Section 1(f) below, which, by reason of the selection and
-# arrangement of their contents, constitute intellectual creations, in
-# which the Work is included in its entirety in unmodified form along
-# with one or more other contributions, each constituting separate and
-# independent works in themselves, which together are assembled into a
-# collective whole. A work that constitutes a Collection will not be
-# considered an Adaptation (as defined below) for the purposes of this
-# License.
-# 3. *"Creative Commons Compatible License"* means a license that is
-# listed at http://creativecommons.org/compatiblelicenses that has
-# been approved by Creative Commons as being essentially equivalent to
-# this License, including, at a minimum, because that license: (i)
-# contains terms that have the same purpose, meaning and effect as the
-# License Elements of this License; and, (ii) explicitly permits the
-# relicensing of adaptations of works made available under that
-# license under this License or a Creative Commons jurisdiction
-# license with the same License Elements as this License.
-# 4. *"Distribute"* means to make available to the public the original
-# and copies of the Work or Adaptation, as appropriate, through sale
-# or other transfer of ownership.
-# 5. *"License Elements"* means the following high-level license
-# attributes as selected by Licensor and indicated in the title of
-# this License: Attribution, ShareAlike.
-# 6. *"Licensor"* means the individual, individuals, entity or entities
-# that offer(s) the Work under the terms of this License.
-# 7. *"Original Author"* means, in the case of a literary or artistic
-# work, the individual, individuals, entity or entities who created
-# the Work or if no individual or entity can be identified, the
-# publisher; and in addition (i) in the case of a performance the
-# actors, singers, musicians, dancers, and other persons who act,
-# sing, deliver, declaim, play in, interpret or otherwise perform
-# literary or artistic works or expressions of folklore; (ii) in the
-# case of a phonogram the producer being the person or legal entity
-# who first fixes the sounds of a performance or other sounds; and,
-# (iii) in the case of broadcasts, the organization that transmits the
-# broadcast.
-# 8. *"Work"* means the literary and/or artistic work offered under the
-# terms of this License including without limitation any production in
-# the literary, scientific and artistic domain, whatever may be the
-# mode or form of its expression including digital form, such as a
-# book, pamphlet and other writing; a lecture, address, sermon or
-# other work of the same nature; a dramatic or dramatico-musical work;
-# a choreographic work or entertainment in dumb show; a musical
-# composition with or without words; a cinematographic work to which
-# are assimilated works expressed by a process analogous to
-# cinematography; a work of drawing, painting, architecture,
-# sculpture, engraving or lithography; a photographic work to which
-# are assimilated works expressed by a process analogous to
-# photography; a work of applied art; an illustration, map, plan,
-# sketch or three-dimensional work relative to geography, topography,
-# architecture or science; a performance; a broadcast; a phonogram; a
-# compilation of data to the extent it is protected as a copyrightable
-# work; or a work performed by a variety or circus performer to the
-# extent it is not otherwise considered a literary or artistic work.
-# 9. *"You"* means an individual or entity exercising rights under this
-# License who has not previously violated the terms of this License
-# with respect to the Work, or who has received express permission
-# from the Licensor to exercise rights under this License despite a
-# previous violation.
-# 10. *"Publicly Perform"* means to perform public recitations of the Work
-# and to communicate to the public those public recitations, by any
-# means or process, including by wire or wireless means or public
-# digital performances; to make available to the public Works in such
-# a way that members of the public may access these Works from a place
-# and at a place individually chosen by them; to perform the Work to
-# the public by any means or process and the communication to the
-# public of the performances of the Work, including by public digital
-# performance; to broadcast and rebroadcast the Work by any means
-# including signs, sounds or images.
-# 11. *"Reproduce"* means to make copies of the Work by any means
-# including without limitation by sound or visual recordings and the
-# right of fixation and reproducing fixations of the Work, including
-# storage of a protected performance or phonogram in digital form or
-# other electronic medium.
-#
-# *2. Fair Dealing Rights.* Nothing in this License is intended to reduce,
-# limit, or restrict any uses free from copyright or rights arising from
-# limitations or exceptions that are provided for in connection with the
-# copyright protection under copyright law or other applicable laws.
-#
-# *3. License Grant.* Subject to the terms and conditions of this License,
-# Licensor hereby grants You a worldwide, royalty-free, non-exclusive,
-# perpetual (for the duration of the applicable copyright) license to
-# exercise the rights in the Work as stated below:
-#
-# 1. to Reproduce the Work, to incorporate the Work into one or more
-# Collections, and to Reproduce the Work as incorporated in the
-# Collections;
-# 2. to create and Reproduce Adaptations provided that any such
-# Adaptation, including any translation in any medium, takes
-# reasonable steps to clearly label, demarcate or otherwise identify
-# that changes were made to the original Work. For example, a
-# translation could be marked "The original work was translated from
-# English to Spanish," or a modification could indicate "The original
-# work has been modified.";
-# 3. to Distribute and Publicly Perform the Work including as
-# incorporated in Collections; and,
-# 4. to Distribute and Publicly Perform Adaptations.
-# 5.
-#
-# For the avoidance of doubt:
-#
-# 1. *Non-waivable Compulsory License Schemes*. In those
-# jurisdictions in which the right to collect royalties through
-# any statutory or compulsory licensing scheme cannot be waived,
-# the Licensor reserves the exclusive right to collect such
-# royalties for any exercise by You of the rights granted under
-# this License;
-# 2. *Waivable Compulsory License Schemes*. In those jurisdictions in
-# which the right to collect royalties through any statutory or
-# compulsory licensing scheme can be waived, the Licensor waives
-# the exclusive right to collect such royalties for any exercise
-# by You of the rights granted under this License; and,
-# 3. *Voluntary License Schemes*. The Licensor waives the right to
-# collect royalties, whether individually or, in the event that
-# the Licensor is a member of a collecting society that
-# administers voluntary licensing schemes, via that society, from
-# any exercise by You of the rights granted under this License.
-#
-# The above rights may be exercised in all media and formats whether now
-# known or hereafter devised. The above rights include the right to make
-# such modifications as are technically necessary to exercise the rights
-# in other media and formats. Subject to Section 8(f), all rights not
-# expressly granted by Licensor are hereby reserved.
-#
-# *4. Restrictions.* The license granted in Section 3 above is expressly
-# made subject to and limited by the following restrictions:
-#
-# 1. You may Distribute or Publicly Perform the Work only under the terms
-# of this License. You must include a copy of, or the Uniform Resource
-# Identifier (URI) for, this License with every copy of the Work You
-# Distribute or Publicly Perform. You may not offer or impose any
-# terms on the Work that restrict the terms of this License or the
-# ability of the recipient of the Work to exercise the rights granted
-# to that recipient under the terms of the License. You may not
-# sublicense the Work. You must keep intact all notices that refer to
-# this License and to the disclaimer of warranties with every copy of
-# the Work You Distribute or Publicly Perform. When You Distribute or
-# Publicly Perform the Work, You may not impose any effective
-# technological measures on the Work that restrict the ability of a
-# recipient of the Work from You to exercise the rights granted to
-# that recipient under the terms of the License. This Section 4(a)
-# applies to the Work as incorporated in a Collection, but this does
-# not require the Collection apart from the Work itself to be made
-# subject to the terms of this License. If You create a Collection,
-# upon notice from any Licensor You must, to the extent practicable,
-# remove from the Collection any credit as required by Section 4(c),
-# as requested. If You create an Adaptation, upon notice from any
-# Licensor You must, to the extent practicable, remove from the
-# Adaptation any credit as required by Section 4(c), as requested.
-# 2. You may Distribute or Publicly Perform an Adaptation only under the
-# terms of: (i) this License; (ii) a later version of this License
-# with the same License Elements as this License; (iii) a Creative
-# Commons jurisdiction license (either this or a later license
-# version) that contains the same License Elements as this License
-# (e.g., Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons
-# Compatible License. If you license the Adaptation under one of the
-# licenses mentioned in (iv), you must comply with the terms of that
-# license. If you license the Adaptation under the terms of any of the
-# licenses mentioned in (i), (ii) or (iii) (the "Applicable License"),
-# you must comply with the terms of the Applicable License generally
-# and the following provisions: (I) You must include a copy of, or the
-# URI for, the Applicable License with every copy of each Adaptation
-# You Distribute or Publicly Perform; (II) You may not offer or impose
-# any terms on the Adaptation that restrict the terms of the
-# Applicable License or the ability of the recipient of the Adaptation
-# to exercise the rights granted to that recipient under the terms of
-# the Applicable License; (III) You must keep intact all notices that
-# refer to the Applicable License and to the disclaimer of warranties
-# with every copy of the Work as included in the Adaptation You
-# Distribute or Publicly Perform; (IV) when You Distribute or Publicly
-# Perform the Adaptation, You may not impose any effective
-# technological measures on the Adaptation that restrict the ability
-# of a recipient of the Adaptation from You to exercise the rights
-# granted to that recipient under the terms of the Applicable License.
-# This Section 4(b) applies to the Adaptation as incorporated in a
-# Collection, but this does not require the Collection apart from the
-# Adaptation itself to be made subject to the terms of the Applicable
-# License.
-# 3. If You Distribute, or Publicly Perform the Work or any Adaptations
-# or Collections, You must, unless a request has been made pursuant to
-# Section 4(a), keep intact all copyright notices for the Work and
-# provide, reasonable to the medium or means You are utilizing: (i)
-# the name of the Original Author (or pseudonym, if applicable) if
-# supplied, and/or if the Original Author and/or Licensor designate
-# another party or parties (e.g., a sponsor institute, publishing
-# entity, journal) for attribution ("Attribution Parties") in
-# Licensor's copyright notice, terms of service or by other reasonable
-# means, the name of such party or parties; (ii) the title of the Work
-# if supplied; (iii) to the extent reasonably practicable, the URI, if
-# any, that Licensor specifies to be associated with the Work, unless
-# such URI does not refer to the copyright notice or licensing
-# information for the Work; and (iv) , consistent with Ssection 3(b),
-# in the case of an Adaptation, a credit identifying the use of the
-# Work in the Adaptation (e.g., "French translation of the Work by
-# Original Author," or "Screenplay based on original Work by Original
-# Author"). The credit required by this Section 4(c) may be
-# implemented in any reasonable manner; provided, however, that in the
-# case of a Adaptation or Collection, at a minimum such credit will
-# appear, if a credit for all contributing authors of the Adaptation
-# or Collection appears, then as part of these credits and in a manner
-# at least as prominent as the credits for the other contributing
-# authors. For the avoidance of doubt, You may only use the credit
-# required by this Section for the purpose of attribution in the
-# manner set out above and, by exercising Your rights under this
-# License, You may not implicitly or explicitly assert or imply any
-# connection with, sponsorship or endorsement by the Original Author,
-# Licensor and/or Attribution Parties, as appropriate, of You or Your
-# use of the Work, without the separate, express prior written
-# permission of the Original Author, Licensor and/or Attribution Parties.
-# 4. Except as otherwise agreed in writing by the Licensor or as may be
-# otherwise permitted by applicable law, if You Reproduce, Distribute
-# or Publicly Perform the Work either by itself or as part of any
-# Adaptations or Collections, You must not distort, mutilate, modify
-# or take other derogatory action in relation to the Work which would
-# be prejudicial to the Original Author's honor or reputation.
-# Licensor agrees that in those jurisdictions (e.g. Japan), in which
-# any exercise of the right granted in Section 3(b) of this License
-# (the right to make Adaptations) would be deemed to be a distortion,
-# mutilation, modification or other derogatory action prejudicial to
-# the Original Author's honor and reputation, the Licensor will waive
-# or not assert, as appropriate, this Section, to the fullest extent
-# permitted by the applicable national law, to enable You to
-# reasonably exercise Your right under Section 3(b) of this License
-# (right to make Adaptations) but not otherwise.
-#
-# *5. Representations, Warranties and Disclaimer*
-#
-# UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR
-# OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY
-# KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE,
-# INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY,
-# FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF
-# LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS,
-# WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE
-# EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.
-#
-# *6. Limitation on Liability.* EXCEPT TO THE EXTENT REQUIRED BY
-# APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL
-# THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY
-# DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF
-# LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-#
-# *7. Termination*
-#
-# 1. This License and the rights granted hereunder will terminate
-# automatically upon any breach by You of the terms of this License.
-# Individuals or entities who have received Adaptations or Collections
-# from You under this License, however, will not have their licenses
-# terminated provided such individuals or entities remain in full
-# compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will
-# survive any termination of this License.
-# 2. Subject to the above terms and conditions, the license granted here
-# is perpetual (for the duration of the applicable copyright in the
-# Work). Notwithstanding the above, Licensor reserves the right to
-# release the Work under different license terms or to stop
-# distributing the Work at any time; provided, however that any such
-# election will not serve to withdraw this License (or any other
-# license that has been, or is required to be, granted under the terms
-# of this License), and this License will continue in full force and
-# effect unless terminated as stated above.
-#
-# *8. Miscellaneous*
-#
-# 1. Each time You Distribute or Publicly Perform the Work or a
-# Collection, the Licensor offers to the recipient a license to the
-# Work on the same terms and conditions as the license granted to You
-# under this License.
-# 2. Each time You Distribute or Publicly Perform an Adaptation, Licensor
-# offers to the recipient a license to the original Work on the same
-# terms and conditions as the license granted to You under this License.
-# 3. If any provision of this License is invalid or unenforceable under
-# applicable law, it shall not affect the validity or enforceability
-# of the remainder of the terms of this License, and without further
-# action by the parties to this agreement, such provision shall be
-# reformed to the minimum extent necessary to make such provision
-# valid and enforceable.
-# 4. No term or provision of this License shall be deemed waived and no
-# breach consented to unless such waiver or consent shall be in
-# writing and signed by the party to be charged with such waiver or
-# consent.
-# 5. This License constitutes the entire agreement between the parties
-# with respect to the Work licensed here. There are no understandings,
-# agreements or representations with respect to the Work not specified
-# here. Licensor shall not be bound by any additional provisions that
-# may appear in any communication from You. This License may not be
-# modified without the mutual written agreement of the Licensor and You.
-# 6. The rights granted under, and the subject matter referenced, in this
-# License were drafted utilizing the terminology of the Berne
-# Convention for the Protection of Literary and Artistic Works (as
-# amended on September 28, 1979), the Rome Convention of 1961, the
-# WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms
-# Treaty of 1996 and the Universal Copyright Convention (as revised on
-# July 24, 1971). These rights and subject matter take effect in the
-# relevant jurisdiction in which the License terms are sought to be
-# enforced according to the corresponding provisions of the
-# implementation of those treaty provisions in the applicable national
-# law. If the standard suite of rights granted under applicable
-# copyright law includes additional rights not granted under this
-# License, such additional rights are deemed to be included in the
-# License; this License is not intended to restrict the license of any
-# rights under applicable law.
-accellerare->accelerare
-acellerare->accelerare
-accellerata->accelerata
-accellerato->accelerato
-accellerazione->accelerazione
-aereonautica->aeronautica
-aereoporti->aeroporti
-aereoporto->aeroporto
-aereosilurante->aerosilurante
-aereosiluranti->aerosiluranti
-affianco->a fianco
-affilliate->affiliate
-aggiottaggio->aggiotaggio
-aggresive->aggressive
-agravate->aggravate
-alse->else
-appropiata->appropriata
-appropiate->appropriate
-appropiati->appropriati
-appropiato->appropriato
-approposito->a proposito
-appropraite->appropriate
-appropropiate->appropriate
-approvigionamento->approvvigionamento
-apropriate->appropriate
-areazione->aerazione
-areoporti->aeroporti
-areoporto->aeroporto
-assisnate->assassinate
-assit->assist
-asume->assume
-audeince->audience
-austrailia->Australia
-automibile->automobile
-avvallo->avallo
-backgorund->background
-backrounds->backgrounds
-benchè->benché
-Bernouilli->Bernoulli
-biricchino->birichino
-bizzare->bizzarre
-Buddah->Buddha
-buisness->business
-busness->business
-bussiness->business
-caffé->caffè
-Caltanisetta->Caltanissetta
-Cambrige->Cambridge
-candadate->candidate
-candiate->candidate
-candidiate->candidate
-casette->cassette
-Celcius->Celsius
-Champange->Champagne
-cioé->cioè
-ciriculum->curriculum
-cmoputer->computer
-coctail->cocktail
-coefficente->coefficiente
-coefficenti->coefficienti
-collaberative->collaborative
-collutazione->colluttazione
-commemerative->commemorative
-commemmorate->commemorate
-comparitive->comparative
-competative->competitive
-competive->competitive
-comprimise->compromise
-compropietari->comproprietari
-compropietaria->comproprietaria
-compropietarie->comproprietarie
-compropietario->comproprietario
-Conneticut->Connecticut
-conosciente->conoscente
-conoscienti->conoscenti
-conoscienza->conoscenza
-consectutive->consecutive
-consentrate->concentrate
-conservitive->conservative
-consolodate->consolidate
-contaiminate->contaminate
-contendor->contender
-coputer->computer
-copywrite->copyright
-corelate->correlate
-correzzione->correzione
-coscente->cosciente
-coscenti->coscienti
-coscenza->coscienza
-cosi->così
-cosidetto->cosiddetto
-cumulatative->cumulative
-curch->church
-curriculem->curriculum
-dasse->desse
-decomposit->decompose
-deficente->deficiente
-deficenti->deficienti
-deficenza->deficienza
-definate->definite
-derivitive->derivative
-deside->decide
-desktiop->desktop
-deteriate->deteriorate
-devide->divide
-diminuitive->diminutive
-dispence->dispense
-doesnt->doesn't
-dosen't->doesn't
-drnik->drink
-dupicate->duplicate
-E'->È
-É->È
-etc.->ecc.
-eccezzionale->eccezionale
-eccezzionali->eccezionali
-eccezzione->eccezione
-ect->etc
-eminate->emanate
-enduce->induce
-esle->else
-esterefatto->esterrefatto
-faciliate->facilitate
-facillitate->facilitate
-Farenheit->Fahrenheit
-fianite->finite
-foootball->football
-foucs->focus
-Gameboy->Game Boy
-ganerate->generate
-Ghandi->Gandhi
-gia->già
-gia'->già
-giacchè->giacché
-giaccue->giacque
-grafitti->graffiti
-Guilia->Giulia
-Guilio->Giulio
-Guiness->Guinness
-Guiseppe->Giuseppe
-halp->help
-hapening->happening
-hertzs->hertz
-imcomplete->incomplete
-imense->immense
-immitate->imitate
-inappropiate->inappropriate
-includ->include
-incoscente->incosciente
-incoscenti->incoscienti
-incoscenza->incoscienza
-inctroduce->introduce
-indulgue->indulge
-infilitrate->infiltrate
-infinit->infinite
-ingegniere->ingegnere
-innoquo->innocuo
-inpolite->impolite
-inquanto->in quanto
-insufficente->insufficiente
-insufficenti->insufficienti
-insufficenza->insufficienza
-interm->interim
-interrim->interim
-intutive->intuitive
-investingate->investigate
-iunior->junior
-knwo->know
-konw->know
-kwno->know
-levetate->levitate
-loev->love
-lveo->love
-lvoe->love
-Macchiavelli->Machiavelli
-maggiorparte->maggior parte
-magolia->magnolia
-managment->management
-marketting->marketing
-Massachussets->Massachusetts
-Massachussetts->Massachusetts
-medacine->medicine
-mercentile->mercantile
-messanger->messenger
-metereologia->meteorologia
-metereologico->meteorologico
-Michagan->Michigan
-minature->miniature
-misile->missile
-Misouri->Missouri
-Missisipi->Mississippi
-Missisippi->Mississippi
-missle->missile
-moderm->modem
-modle->model
-Monserrat->Montserrat
-mroe->more
-muscial->musical
-mussulmano->musulmano
-naturual->natural
-Nazereth->Nazareth
-necessiate->necessitate
-nkow->know
-nkwo->know
-noveau->nouveau
-ocuntry->country
-omlette->omelette
-omre->more
-onniscente->onnisciente
-onniscenti->onniscienti
-onoreficenze->onorificenze
-onyl->only
-ovverossia->ovverosia
-pallete->palette
-pantomine->pantomime
-pary->party
-penatly->penalty
-perchè->perché
-perche'->perché
-percui->per cui
-performence->performance
-pero'->però
-perogative->prerogative
-peronospera->peronospora
-piu->più
-piu'->più
-plateu->plateau
-pò->po'
-poiche'->poiché
-poichè->poiché
-preceed->precede
-pressocche'->pressoché
-pressocché->pressoché
-preverse->perverse
-primative->primitive
-privte->private
-proceedure->procedure
-processer->processor
-profesor->professor
-professer->professor
-proffesed->professed
-proffesor->professor
-profiquo->proficuo
-proove->prove
-propietà->proprietà
-propietari->proprietari
-propietaria->proprietaria
-propietarie->proprietarie
-propietario->proprietario
-propio->proprio
-propoganda->propaganda
-propogate->propagate
-prospicente->prospiciente
-prospicenti->prospicienti
-provacative->provocative
-psuedo->pseudo
-Pucini->Puccini
-pursuade->persuade
-pwoer->power
-recrod->record
-redarre->redigere
-refedendum->referendum
-rela->real
-riconosciente->riconoscente
-riconoscienti->riconoscenti
-riconoscienza->riconoscenza
-rocord->record
-rubgy->rugby
-sandwhich->sandwich
-satelite->satellite
-sattelite->satellite
-scandanavia->Scandinavia
-scenza->scienza
-scenze->scienze
-scirpt->script
-se'->sé
-sè->sé
-sensa->senza
-senstive->sensitive
-sensure->censure
-senzo->senso
-smoe->some
-soem->some
-sofware->software
-sohw->show
-sopratutto->soprattutto
-soudn->sound
-speci->specie
-spoace->space
-sponser->sponsor
-staion->station
-stasse->stesse
-stong->strong
-stpo->stop
-strazzio->strazio
-su'->sù
-succesiva->successiva
-succesive->successive
-succesivi->successivi
-succesivo->successivo
-sucessiva->successiva
-sucessive->successive
-sucessivi->successivi
-sucessivo->successivo
-sufficente->sufficiente
-sufficenti->sufficienti
-sufficenza->sufficienza
-sytem->system
-tast->taste
-té->tè
-tghe->the
-timne->time
-tje->the
-tjhe->the
-transare->transigere
-tremelo->tremolo
-troup->troupe
-tust->trust
-vadino->vadano
-valetta->valletta
-ventitrè->ventitré
-vicere->viceré
-zeebra->zebra
diff --git a/files/typos/typos-nb.txt b/files/typos/typos-nb.txt
deleted file mode 100644
index 104362718..000000000
--- a/files/typos/typos-nb.txt
+++ /dev/null
@@ -1,449 +0,0 @@
-# This file contains a number of common Norwegian typos:
-andriod->android
-
-# The remainder of this file contains misspellings from
-# http://no.wikipedia.org/wiki/Wikipedia:Liste_over_alminnelige_stavefeil/Maskinform
-# plus some post-processing to fix invalid entries, remove duplicates, etc.
-#
-# The content is available under the
-# "Creative Commons Attribution-ShareAlike License"
-# http://creativecommons.org/licenses/by-sa/3.0/
-#
-# THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE
-# COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY
-# COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS
-# AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
-#
-# BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE
-# TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY
-# BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS
-# CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND
-# CONDITIONS.
-#
-# *1. Definitions*
-#
-# 1. *"Adaptation"* means a work based upon the Work, or upon the Work
-# and other pre-existing works, such as a translation, adaptation,
-# derivative work, arrangement of music or other alterations of a
-# literary or artistic work, or phonogram or performance and includes
-# cinematographic adaptations or any other form in which the Work may
-# be recast, transformed, or adapted including in any form
-# recognizably derived from the original, except that a work that
-# constitutes a Collection will not be considered an Adaptation for
-# the purpose of this License. For the avoidance of doubt, where the
-# Work is a musical work, performance or phonogram, the
-# synchronization of the Work in timed-relation with a moving image
-# ("synching") will be considered an Adaptation for the purpose of
-# this License.
-# 2. *"Collection"* means a collection of literary or artistic works,
-# such as encyclopedias and anthologies, or performances, phonograms
-# or broadcasts, or other works or subject matter other than works
-# listed in Section 1(f) below, which, by reason of the selection and
-# arrangement of their contents, constitute intellectual creations, in
-# which the Work is included in its entirety in unmodified form along
-# with one or more other contributions, each constituting separate and
-# independent works in themselves, which together are assembled into a
-# collective whole. A work that constitutes a Collection will not be
-# considered an Adaptation (as defined below) for the purposes of this
-# License.
-# 3. *"Creative Commons Compatible License"* means a license that is
-# listed at http://creativecommons.org/compatiblelicenses that has
-# been approved by Creative Commons as being essentially equivalent to
-# this License, including, at a minimum, because that license: (i)
-# contains terms that have the same purpose, meaning and effect as the
-# License Elements of this License; and, (ii) explicitly permits the
-# relicensing of adaptations of works made available under that
-# license under this License or a Creative Commons jurisdiction
-# license with the same License Elements as this License.
-# 4. *"Distribute"* means to make available to the public the original
-# and copies of the Work or Adaptation, as appropriate, through sale
-# or other transfer of ownership.
-# 5. *"License Elements"* means the following high-level license
-# attributes as selected by Licensor and indicated in the title of
-# this License: Attribution, ShareAlike.
-# 6. *"Licensor"* means the individual, individuals, entity or entities
-# that offer(s) the Work under the terms of this License.
-# 7. *"Original Author"* means, in the case of a literary or artistic
-# work, the individual, individuals, entity or entities who created
-# the Work or if no individual or entity can be identified, the
-# publisher; and in addition (i) in the case of a performance the
-# actors, singers, musicians, dancers, and other persons who act,
-# sing, deliver, declaim, play in, interpret or otherwise perform
-# literary or artistic works or expressions of folklore; (ii) in the
-# case of a phonogram the producer being the person or legal entity
-# who first fixes the sounds of a performance or other sounds; and,
-# (iii) in the case of broadcasts, the organization that transmits the
-# broadcast.
-# 8. *"Work"* means the literary and/or artistic work offered under the
-# terms of this License including without limitation any production in
-# the literary, scientific and artistic domain, whatever may be the
-# mode or form of its expression including digital form, such as a
-# book, pamphlet and other writing; a lecture, address, sermon or
-# other work of the same nature; a dramatic or dramatico-musical work;
-# a choreographic work or entertainment in dumb show; a musical
-# composition with or without words; a cinematographic work to which
-# are assimilated works expressed by a process analogous to
-# cinematography; a work of drawing, painting, architecture,
-# sculpture, engraving or lithography; a photographic work to which
-# are assimilated works expressed by a process analogous to
-# photography; a work of applied art; an illustration, map, plan,
-# sketch or three-dimensional work relative to geography, topography,
-# architecture or science; a performance; a broadcast; a phonogram; a
-# compilation of data to the extent it is protected as a copyrightable
-# work; or a work performed by a variety or circus performer to the
-# extent it is not otherwise considered a literary or artistic work.
-# 9. *"You"* means an individual or entity exercising rights under this
-# License who has not previously violated the terms of this License
-# with respect to the Work, or who has received express permission
-# from the Licensor to exercise rights under this License despite a
-# previous violation.
-# 10. *"Publicly Perform"* means to perform public recitations of the Work
-# and to communicate to the public those public recitations, by any
-# means or process, including by wire or wireless means or public
-# digital performances; to make available to the public Works in such
-# a way that members of the public may access these Works from a place
-# and at a place individually chosen by them; to perform the Work to
-# the public by any means or process and the communication to the
-# public of the performances of the Work, including by public digital
-# performance; to broadcast and rebroadcast the Work by any means
-# including signs, sounds or images.
-# 11. *"Reproduce"* means to make copies of the Work by any means
-# including without limitation by sound or visual recordings and the
-# right of fixation and reproducing fixations of the Work, including
-# storage of a protected performance or phonogram in digital form or
-# other electronic medium.
-#
-# *2. Fair Dealing Rights.* Nothing in this License is intended to reduce,
-# limit, or restrict any uses free from copyright or rights arising from
-# limitations or exceptions that are provided for in connection with the
-# copyright protection under copyright law or other applicable laws.
-#
-# *3. License Grant.* Subject to the terms and conditions of this License,
-# Licensor hereby grants You a worldwide, royalty-free, non-exclusive,
-# perpetual (for the duration of the applicable copyright) license to
-# exercise the rights in the Work as stated below:
-#
-# 1. to Reproduce the Work, to incorporate the Work into one or more
-# Collections, and to Reproduce the Work as incorporated in the
-# Collections;
-# 2. to create and Reproduce Adaptations provided that any such
-# Adaptation, including any translation in any medium, takes
-# reasonable steps to clearly label, demarcate or otherwise identify
-# that changes were made to the original Work. For example, a
-# translation could be marked "The original work was translated from
-# English to Spanish," or a modification could indicate "The original
-# work has been modified.";
-# 3. to Distribute and Publicly Perform the Work including as
-# incorporated in Collections; and,
-# 4. to Distribute and Publicly Perform Adaptations.
-# 5.
-#
-# For the avoidance of doubt:
-#
-# 1. *Non-waivable Compulsory License Schemes*. In those
-# jurisdictions in which the right to collect royalties through
-# any statutory or compulsory licensing scheme cannot be waived,
-# the Licensor reserves the exclusive right to collect such
-# royalties for any exercise by You of the rights granted under
-# this License;
-# 2. *Waivable Compulsory License Schemes*. In those jurisdictions in
-# which the right to collect royalties through any statutory or
-# compulsory licensing scheme can be waived, the Licensor waives
-# the exclusive right to collect such royalties for any exercise
-# by You of the rights granted under this License; and,
-# 3. *Voluntary License Schemes*. The Licensor waives the right to
-# collect royalties, whether individually or, in the event that
-# the Licensor is a member of a collecting society that
-# administers voluntary licensing schemes, via that society, from
-# any exercise by You of the rights granted under this License.
-#
-# The above rights may be exercised in all media and formats whether now
-# known or hereafter devised. The above rights include the right to make
-# such modifications as are technically necessary to exercise the rights
-# in other media and formats. Subject to Section 8(f), all rights not
-# expressly granted by Licensor are hereby reserved.
-#
-# *4. Restrictions.* The license granted in Section 3 above is expressly
-# made subject to and limited by the following restrictions:
-#
-# 1. You may Distribute or Publicly Perform the Work only under the terms
-# of this License. You must include a copy of, or the Uniform Resource
-# Identifier (URI) for, this License with every copy of the Work You
-# Distribute or Publicly Perform. You may not offer or impose any
-# terms on the Work that restrict the terms of this License or the
-# ability of the recipient of the Work to exercise the rights granted
-# to that recipient under the terms of the License. You may not
-# sublicense the Work. You must keep intact all notices that refer to
-# this License and to the disclaimer of warranties with every copy of
-# the Work You Distribute or Publicly Perform. When You Distribute or
-# Publicly Perform the Work, You may not impose any effective
-# technological measures on the Work that restrict the ability of a
-# recipient of the Work from You to exercise the rights granted to
-# that recipient under the terms of the License. This Section 4(a)
-# applies to the Work as incorporated in a Collection, but this does
-# not require the Collection apart from the Work itself to be made
-# subject to the terms of this License. If You create a Collection,
-# upon notice from any Licensor You must, to the extent practicable,
-# remove from the Collection any credit as required by Section 4(c),
-# as requested. If You create an Adaptation, upon notice from any
-# Licensor You must, to the extent practicable, remove from the
-# Adaptation any credit as required by Section 4(c), as requested.
-# 2. You may Distribute or Publicly Perform an Adaptation only under the
-# terms of: (i) this License; (ii) a later version of this License
-# with the same License Elements as this License; (iii) a Creative
-# Commons jurisdiction license (either this or a later license
-# version) that contains the same License Elements as this License
-# (e.g., Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons
-# Compatible License. If you license the Adaptation under one of the
-# licenses mentioned in (iv), you must comply with the terms of that
-# license. If you license the Adaptation under the terms of any of the
-# licenses mentioned in (i), (ii) or (iii) (the "Applicable License"),
-# you must comply with the terms of the Applicable License generally
-# and the following provisions: (I) You must include a copy of, or the
-# URI for, the Applicable License with every copy of each Adaptation
-# You Distribute or Publicly Perform; (II) You may not offer or impose
-# any terms on the Adaptation that restrict the terms of the
-# Applicable License or the ability of the recipient of the Adaptation
-# to exercise the rights granted to that recipient under the terms of
-# the Applicable License; (III) You must keep intact all notices that
-# refer to the Applicable License and to the disclaimer of warranties
-# with every copy of the Work as included in the Adaptation You
-# Distribute or Publicly Perform; (IV) when You Distribute or Publicly
-# Perform the Adaptation, You may not impose any effective
-# technological measures on the Adaptation that restrict the ability
-# of a recipient of the Adaptation from You to exercise the rights
-# granted to that recipient under the terms of the Applicable License.
-# This Section 4(b) applies to the Adaptation as incorporated in a
-# Collection, but this does not require the Collection apart from the
-# Adaptation itself to be made subject to the terms of the Applicable
-# License.
-# 3. If You Distribute, or Publicly Perform the Work or any Adaptations
-# or Collections, You must, unless a request has been made pursuant to
-# Section 4(a), keep intact all copyright notices for the Work and
-# provide, reasonable to the medium or means You are utilizing: (i)
-# the name of the Original Author (or pseudonym, if applicable) if
-# supplied, and/or if the Original Author and/or Licensor designate
-# another party or parties (e.g., a sponsor institute, publishing
-# entity, journal) for attribution ("Attribution Parties") in
-# Licensor's copyright notice, terms of service or by other reasonable
-# means, the name of such party or parties; (ii) the title of the Work
-# if supplied; (iii) to the extent reasonably practicable, the URI, if
-# any, that Licensor specifies to be associated with the Work, unless
-# such URI does not refer to the copyright notice or licensing
-# information for the Work; and (iv) , consistent with Ssection 3(b),
-# in the case of an Adaptation, a credit identifying the use of the
-# Work in the Adaptation (e.g., "French translation of the Work by
-# Original Author," or "Screenplay based on original Work by Original
-# Author"). The credit required by this Section 4(c) may be
-# implemented in any reasonable manner; provided, however, that in the
-# case of a Adaptation or Collection, at a minimum such credit will
-# appear, if a credit for all contributing authors of the Adaptation
-# or Collection appears, then as part of these credits and in a manner
-# at least as prominent as the credits for the other contributing
-# authors. For the avoidance of doubt, You may only use the credit
-# required by this Section for the purpose of attribution in the
-# manner set out above and, by exercising Your rights under this
-# License, You may not implicitly or explicitly assert or imply any
-# connection with, sponsorship or endorsement by the Original Author,
-# Licensor and/or Attribution Parties, as appropriate, of You or Your
-# use of the Work, without the separate, express prior written
-# permission of the Original Author, Licensor and/or Attribution Parties.
-# 4. Except as otherwise agreed in writing by the Licensor or as may be
-# otherwise permitted by applicable law, if You Reproduce, Distribute
-# or Publicly Perform the Work either by itself or as part of any
-# Adaptations or Collections, You must not distort, mutilate, modify
-# or take other derogatory action in relation to the Work which would
-# be prejudicial to the Original Author's honor or reputation.
-# Licensor agrees that in those jurisdictions (e.g. Japan), in which
-# any exercise of the right granted in Section 3(b) of this License
-# (the right to make Adaptations) would be deemed to be a distortion,
-# mutilation, modification or other derogatory action prejudicial to
-# the Original Author's honor and reputation, the Licensor will waive
-# or not assert, as appropriate, this Section, to the fullest extent
-# permitted by the applicable national law, to enable You to
-# reasonably exercise Your right under Section 3(b) of this License
-# (right to make Adaptations) but not otherwise.
-#
-# *5. Representations, Warranties and Disclaimer*
-#
-# UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR
-# OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY
-# KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE,
-# INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY,
-# FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF
-# LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS,
-# WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE
-# EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.
-#
-# *6. Limitation on Liability.* EXCEPT TO THE EXTENT REQUIRED BY
-# APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL
-# THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY
-# DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF
-# LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-#
-# *7. Termination*
-#
-# 1. This License and the rights granted hereunder will terminate
-# automatically upon any breach by You of the terms of this License.
-# Individuals or entities who have received Adaptations or Collections
-# from You under this License, however, will not have their licenses
-# terminated provided such individuals or entities remain in full
-# compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will
-# survive any termination of this License.
-# 2. Subject to the above terms and conditions, the license granted here
-# is perpetual (for the duration of the applicable copyright in the
-# Work). Notwithstanding the above, Licensor reserves the right to
-# release the Work under different license terms or to stop
-# distributing the Work at any time; provided, however that any such
-# election will not serve to withdraw this License (or any other
-# license that has been, or is required to be, granted under the terms
-# of this License), and this License will continue in full force and
-# effect unless terminated as stated above.
-#
-# *8. Miscellaneous*
-#
-# 1. Each time You Distribute or Publicly Perform the Work or a
-# Collection, the Licensor offers to the recipient a license to the
-# Work on the same terms and conditions as the license granted to You
-# under this License.
-# 2. Each time You Distribute or Publicly Perform an Adaptation, Licensor
-# offers to the recipient a license to the original Work on the same
-# terms and conditions as the license granted to You under this License.
-# 3. If any provision of this License is invalid or unenforceable under
-# applicable law, it shall not affect the validity or enforceability
-# of the remainder of the terms of this License, and without further
-# action by the parties to this agreement, such provision shall be
-# reformed to the minimum extent necessary to make such provision
-# valid and enforceable.
-# 4. No term or provision of this License shall be deemed waived and no
-# breach consented to unless such waiver or consent shall be in
-# writing and signed by the party to be charged with such waiver or
-# consent.
-# 5. This License constitutes the entire agreement between the parties
-# with respect to the Work licensed here. There are no understandings,
-# agreements or representations with respect to the Work not specified
-# here. Licensor shall not be bound by any additional provisions that
-# may appear in any communication from You. This License may not be
-# modified without the mutual written agreement of the Licensor and You.
-# 6. The rights granted under, and the subject matter referenced, in this
-# License were drafted utilizing the terminology of the Berne
-# Convention for the Protection of Literary and Artistic Works (as
-# amended on September 28, 1979), the Rome Convention of 1961, the
-# WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms
-# Treaty of 1996 and the Universal Copyright Convention (as revised on
-# July 24, 1971). These rights and subject matter take effect in the
-# relevant jurisdiction in which the License terms are sought to be
-# enforced according to the corresponding provisions of the
-# implementation of those treaty provisions in the applicable national
-# law. If the standard suite of rights granted under applicable
-# copyright law includes additional rights not granted under this
-# License, such additional rights are deemed to be included in the
-# License; this License is not intended to restrict the license of any
-# rights under applicable law.
-
-abbonement->abonnement
-addresse->adresse
-agresiv->aggressiv
-aggresiv->aggressiv
-agressiv->aggressiv
-aldrig->aldri
-alldri->aldri
-allè->allé
-allminnelig->alminnelig
-alminnlig->alminnelig
-altid->alltid
-annerkjenne->anerkjenne
-apelere->appellere
-apellere->appellere
-appelere->appellere
-apetitt->appetitt
-appetit->appetitt
-artikel->artikkel
-artikkler->artikler
-avlegs->avleggs
-biblotek->bibliotek
-bilett->billett
-blandt->blant
-brylupp->bryllup
-colloseum->colosseum
-desverre->dessverre
-editere->redigere
-ein->en
-eit->et
-fasinerende->fascinerende
-foresten->forresten
-genetiv->genitiv
-gjordt->gjort
-grafitti->graffiti
-hovedsaklig->hovedsakelig
-ikkje->ikke
-iakta->iaktta
-insjiativ->initiativ
-inttiativ->initiativ
-intiativ->initiativ
-inteligent->intelligent
-intligent->intelligent
-innteligent->intelligent
-internett->Internett
-Internet->Internett
-interresant->interessant
-interressant->interessant
-interrese->interesse
-interresse->interesse
-km2->km²
-kakkerlakk->kakerlakk
-kammerat->kamerat
-kammere->kamre
-kanate->kantate
-kansje->kanskje
-karriære->karrière
-kariere->karrière
-kasett->kassett
-komune->kommune
-konstantere->konstatere
-kontigent->kontingent
-konkuranse->konkurranse
-konkurere->konkurrere
-m.o.h.->moh
-Majorstua->Majorstuen
-media->medier
-medlemsskap->medlemskap
-mennsker->mennesker
-metrolog->meteorolog
-metrologi->meteorologi
-Midt-Østen->Midtøsten
-Midt-østen->Midtøsten
-millenium->millennium
-missvisende->misvisende
-morro->moro
-musikker->musiker
-nysjerrig->nysgjerrig
-nyskjerrig->nysgjerrig
-oksyd->oksid
-oksydere->oksidere
-orginal->original
-paralell->parallell
-parallel->parallell
-parantes->parentes
-prevansjon->prevensjon
-risici->risikoer
-risiki->risikoer
-satelitt->satellitt
-simpelten->simpelthen
-sinnsyk->sinnssyk
-skjelden->sjelden
-skriftelig->skriftlig
-slalom->slalåm
-terasse->terrasse
-triologi->trilogi
-tydlig->tydelig
-tunell->tunnel
-tunnell->tunnel
-untatt->unntatt
-usakelig->usaklig
-utdybende->utdypende
-underholdene->underholdende
-vakum->vakuum
-viderekommende->viderekomne
-værre->verre
-værste->verste
diff --git a/files/typos/typos-pt.txt b/files/typos/typos-pt.txt
deleted file mode 100644
index 6285d37b7..000000000
--- a/files/typos/typos-pt.txt
+++ /dev/null
@@ -1,1647 +0,0 @@
-# This file contains a number of common Portuguese typos:
-andriod->android
-
-# The remainder of this file contains misspellings from
-# http://pt.wikipedia.org/wiki/Wikip%C3%A9dia:Software/Anti-vandal_tool/Ortografia
-# plus some post-processing to fix invalid entries, remove duplicates, etc.
-#
-# The content is available under the
-# "Creative Commons Attribution-ShareAlike License"
-# http://creativecommons.org/licenses/by-sa/3.0/
-#
-# THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE
-# COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY
-# COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS
-# AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
-#
-# BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE
-# TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY
-# BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS
-# CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND
-# CONDITIONS.
-#
-# *1. Definitions*
-#
-# 1. *"Adaptation"* means a work based upon the Work, or upon the Work
-# and other pre-existing works, such as a translation, adaptation,
-# derivative work, arrangement of music or other alterations of a
-# literary or artistic work, or phonogram or performance and includes
-# cinematographic adaptations or any other form in which the Work may
-# be recast, transformed, or adapted including in any form
-# recognizably derived from the original, except that a work that
-# constitutes a Collection will not be considered an Adaptation for
-# the purpose of this License. For the avoidance of doubt, where the
-# Work is a musical work, performance or phonogram, the
-# synchronization of the Work in timed-relation with a moving image
-# ("synching") will be considered an Adaptation for the purpose of
-# this License.
-# 2. *"Collection"* means a collection of literary or artistic works,
-# such as encyclopedias and anthologies, or performances, phonograms
-# or broadcasts, or other works or subject matter other than works
-# listed in Section 1(f) below, which, by reason of the selection and
-# arrangement of their contents, constitute intellectual creations, in
-# which the Work is included in its entirety in unmodified form along
-# with one or more other contributions, each constituting separate and
-# independent works in themselves, which together are assembled into a
-# collective whole. A work that constitutes a Collection will not be
-# considered an Adaptation (as defined below) for the purposes of this
-# License.
-# 3. *"Creative Commons Compatible License"* means a license that is
-# listed at http://creativecommons.org/compatiblelicenses that has
-# been approved by Creative Commons as being essentially equivalent to
-# this License, including, at a minimum, because that license: (i)
-# contains terms that have the same purpose, meaning and effect as the
-# License Elements of this License; and, (ii) explicitly permits the
-# relicensing of adaptations of works made available under that
-# license under this License or a Creative Commons jurisdiction
-# license with the same License Elements as this License.
-# 4. *"Distribute"* means to make available to the public the original
-# and copies of the Work or Adaptation, as appropriate, through sale
-# or other transfer of ownership.
-# 5. *"License Elements"* means the following high-level license
-# attributes as selected by Licensor and indicated in the title of
-# this License: Attribution, ShareAlike.
-# 6. *"Licensor"* means the individual, individuals, entity or entities
-# that offer(s) the Work under the terms of this License.
-# 7. *"Original Author"* means, in the case of a literary or artistic
-# work, the individual, individuals, entity or entities who created
-# the Work or if no individual or entity can be identified, the
-# publisher; and in addition (i) in the case of a performance the
-# actors, singers, musicians, dancers, and other persons who act,
-# sing, deliver, declaim, play in, interpret or otherwise perform
-# literary or artistic works or expressions of folklore; (ii) in the
-# case of a phonogram the producer being the person or legal entity
-# who first fixes the sounds of a performance or other sounds; and,
-# (iii) in the case of broadcasts, the organization that transmits the
-# broadcast.
-# 8. *"Work"* means the literary and/or artistic work offered under the
-# terms of this License including without limitation any production in
-# the literary, scientific and artistic domain, whatever may be the
-# mode or form of its expression including digital form, such as a
-# book, pamphlet and other writing; a lecture, address, sermon or
-# other work of the same nature; a dramatic or dramatico-musical work;
-# a choreographic work or entertainment in dumb show; a musical
-# composition with or without words; a cinematographic work to which
-# are assimilated works expressed by a process analogous to
-# cinematography; a work of drawing, painting, architecture,
-# sculpture, engraving or lithography; a photographic work to which
-# are assimilated works expressed by a process analogous to
-# photography; a work of applied art; an illustration, map, plan,
-# sketch or three-dimensional work relative to geography, topography,
-# architecture or science; a performance; a broadcast; a phonogram; a
-# compilation of data to the extent it is protected as a copyrightable
-# work; or a work performed by a variety or circus performer to the
-# extent it is not otherwise considered a literary or artistic work.
-# 9. *"You"* means an individual or entity exercising rights under this
-# License who has not previously violated the terms of this License
-# with respect to the Work, or who has received express permission
-# from the Licensor to exercise rights under this License despite a
-# previous violation.
-# 10. *"Publicly Perform"* means to perform public recitations of the Work
-# and to communicate to the public those public recitations, by any
-# means or process, including by wire or wireless means or public
-# digital performances; to make available to the public Works in such
-# a way that members of the public may access these Works from a place
-# and at a place individually chosen by them; to perform the Work to
-# the public by any means or process and the communication to the
-# public of the performances of the Work, including by public digital
-# performance; to broadcast and rebroadcast the Work by any means
-# including signs, sounds or images.
-# 11. *"Reproduce"* means to make copies of the Work by any means
-# including without limitation by sound or visual recordings and the
-# right of fixation and reproducing fixations of the Work, including
-# storage of a protected performance or phonogram in digital form or
-# other electronic medium.
-#
-# *2. Fair Dealing Rights.* Nothing in this License is intended to reduce,
-# limit, or restrict any uses free from copyright or rights arising from
-# limitations or exceptions that are provided for in connection with the
-# copyright protection under copyright law or other applicable laws.
-#
-# *3. License Grant.* Subject to the terms and conditions of this License,
-# Licensor hereby grants You a worldwide, royalty-free, non-exclusive,
-# perpetual (for the duration of the applicable copyright) license to
-# exercise the rights in the Work as stated below:
-#
-# 1. to Reproduce the Work, to incorporate the Work into one or more
-# Collections, and to Reproduce the Work as incorporated in the
-# Collections;
-# 2. to create and Reproduce Adaptations provided that any such
-# Adaptation, including any translation in any medium, takes
-# reasonable steps to clearly label, demarcate or otherwise identify
-# that changes were made to the original Work. For example, a
-# translation could be marked "The original work was translated from
-# English to Spanish," or a modification could indicate "The original
-# work has been modified.";
-# 3. to Distribute and Publicly Perform the Work including as
-# incorporated in Collections; and,
-# 4. to Distribute and Publicly Perform Adaptations.
-# 5.
-#
-# For the avoidance of doubt:
-#
-# 1. *Non-waivable Compulsory License Schemes*. In those
-# jurisdictions in which the right to collect royalties through
-# any statutory or compulsory licensing scheme cannot be waived,
-# the Licensor reserves the exclusive right to collect such
-# royalties for any exercise by You of the rights granted under
-# this License;
-# 2. *Waivable Compulsory License Schemes*. In those jurisdictions in
-# which the right to collect royalties through any statutory or
-# compulsory licensing scheme can be waived, the Licensor waives
-# the exclusive right to collect such royalties for any exercise
-# by You of the rights granted under this License; and,
-# 3. *Voluntary License Schemes*. The Licensor waives the right to
-# collect royalties, whether individually or, in the event that
-# the Licensor is a member of a collecting society that
-# administers voluntary licensing schemes, via that society, from
-# any exercise by You of the rights granted under this License.
-#
-# The above rights may be exercised in all media and formats whether now
-# known or hereafter devised. The above rights include the right to make
-# such modifications as are technically necessary to exercise the rights
-# in other media and formats. Subject to Section 8(f), all rights not
-# expressly granted by Licensor are hereby reserved.
-#
-# *4. Restrictions.* The license granted in Section 3 above is expressly
-# made subject to and limited by the following restrictions:
-#
-# 1. You may Distribute or Publicly Perform the Work only under the terms
-# of this License. You must include a copy of, or the Uniform Resource
-# Identifier (URI) for, this License with every copy of the Work You
-# Distribute or Publicly Perform. You may not offer or impose any
-# terms on the Work that restrict the terms of this License or the
-# ability of the recipient of the Work to exercise the rights granted
-# to that recipient under the terms of the License. You may not
-# sublicense the Work. You must keep intact all notices that refer to
-# this License and to the disclaimer of warranties with every copy of
-# the Work You Distribute or Publicly Perform. When You Distribute or
-# Publicly Perform the Work, You may not impose any effective
-# technological measures on the Work that restrict the ability of a
-# recipient of the Work from You to exercise the rights granted to
-# that recipient under the terms of the License. This Section 4(a)
-# applies to the Work as incorporated in a Collection, but this does
-# not require the Collection apart from the Work itself to be made
-# subject to the terms of this License. If You create a Collection,
-# upon notice from any Licensor You must, to the extent practicable,
-# remove from the Collection any credit as required by Section 4(c),
-# as requested. If You create an Adaptation, upon notice from any
-# Licensor You must, to the extent practicable, remove from the
-# Adaptation any credit as required by Section 4(c), as requested.
-# 2. You may Distribute or Publicly Perform an Adaptation only under the
-# terms of: (i) this License; (ii) a later version of this License
-# with the same License Elements as this License; (iii) a Creative
-# Commons jurisdiction license (either this or a later license
-# version) that contains the same License Elements as this License
-# (e.g., Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons
-# Compatible License. If you license the Adaptation under one of the
-# licenses mentioned in (iv), you must comply with the terms of that
-# license. If you license the Adaptation under the terms of any of the
-# licenses mentioned in (i), (ii) or (iii) (the "Applicable License"),
-# you must comply with the terms of the Applicable License generally
-# and the following provisions: (I) You must include a copy of, or the
-# URI for, the Applicable License with every copy of each Adaptation
-# You Distribute or Publicly Perform; (II) You may not offer or impose
-# any terms on the Adaptation that restrict the terms of the
-# Applicable License or the ability of the recipient of the Adaptation
-# to exercise the rights granted to that recipient under the terms of
-# the Applicable License; (III) You must keep intact all notices that
-# refer to the Applicable License and to the disclaimer of warranties
-# with every copy of the Work as included in the Adaptation You
-# Distribute or Publicly Perform; (IV) when You Distribute or Publicly
-# Perform the Adaptation, You may not impose any effective
-# technological measures on the Adaptation that restrict the ability
-# of a recipient of the Adaptation from You to exercise the rights
-# granted to that recipient under the terms of the Applicable License.
-# This Section 4(b) applies to the Adaptation as incorporated in a
-# Collection, but this does not require the Collection apart from the
-# Adaptation itself to be made subject to the terms of the Applicable
-# License.
-# 3. If You Distribute, or Publicly Perform the Work or any Adaptations
-# or Collections, You must, unless a request has been made pursuant to
-# Section 4(a), keep intact all copyright notices for the Work and
-# provide, reasonable to the medium or means You are utilizing: (i)
-# the name of the Original Author (or pseudonym, if applicable) if
-# supplied, and/or if the Original Author and/or Licensor designate
-# another party or parties (e.g., a sponsor institute, publishing
-# entity, journal) for attribution ("Attribution Parties") in
-# Licensor's copyright notice, terms of service or by other reasonable
-# means, the name of such party or parties; (ii) the title of the Work
-# if supplied; (iii) to the extent reasonably practicable, the URI, if
-# any, that Licensor specifies to be associated with the Work, unless
-# such URI does not refer to the copyright notice or licensing
-# information for the Work; and (iv) , consistent with Ssection 3(b),
-# in the case of an Adaptation, a credit identifying the use of the
-# Work in the Adaptation (e.g., "French translation of the Work by
-# Original Author," or "Screenplay based on original Work by Original
-# Author"). The credit required by this Section 4(c) may be
-# implemented in any reasonable manner; provided, however, that in the
-# case of a Adaptation or Collection, at a minimum such credit will
-# appear, if a credit for all contributing authors of the Adaptation
-# or Collection appears, then as part of these credits and in a manner
-# at least as prominent as the credits for the other contributing
-# authors. For the avoidance of doubt, You may only use the credit
-# required by this Section for the purpose of attribution in the
-# manner set out above and, by exercising Your rights under this
-# License, You may not implicitly or explicitly assert or imply any
-# connection with, sponsorship or endorsement by the Original Author,
-# Licensor and/or Attribution Parties, as appropriate, of You or Your
-# use of the Work, without the separate, express prior written
-# permission of the Original Author, Licensor and/or Attribution Parties.
-# 4. Except as otherwise agreed in writing by the Licensor or as may be
-# otherwise permitted by applicable law, if You Reproduce, Distribute
-# or Publicly Perform the Work either by itself or as part of any
-# Adaptations or Collections, You must not distort, mutilate, modify
-# or take other derogatory action in relation to the Work which would
-# be prejudicial to the Original Author's honor or reputation.
-# Licensor agrees that in those jurisdictions (e.g. Japan), in which
-# any exercise of the right granted in Section 3(b) of this License
-# (the right to make Adaptations) would be deemed to be a distortion,
-# mutilation, modification or other derogatory action prejudicial to
-# the Original Author's honor and reputation, the Licensor will waive
-# or not assert, as appropriate, this Section, to the fullest extent
-# permitted by the applicable national law, to enable You to
-# reasonably exercise Your right under Section 3(b) of this License
-# (right to make Adaptations) but not otherwise.
-#
-# *5. Representations, Warranties and Disclaimer*
-#
-# UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR
-# OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY
-# KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE,
-# INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY,
-# FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF
-# LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS,
-# WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE
-# EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.
-#
-# *6. Limitation on Liability.* EXCEPT TO THE EXTENT REQUIRED BY
-# APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL
-# THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY
-# DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF
-# LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-#
-# *7. Termination*
-#
-# 1. This License and the rights granted hereunder will terminate
-# automatically upon any breach by You of the terms of this License.
-# Individuals or entities who have received Adaptations or Collections
-# from You under this License, however, will not have their licenses
-# terminated provided such individuals or entities remain in full
-# compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will
-# survive any termination of this License.
-# 2. Subject to the above terms and conditions, the license granted here
-# is perpetual (for the duration of the applicable copyright in the
-# Work). Notwithstanding the above, Licensor reserves the right to
-# release the Work under different license terms or to stop
-# distributing the Work at any time; provided, however that any such
-# election will not serve to withdraw this License (or any other
-# license that has been, or is required to be, granted under the terms
-# of this License), and this License will continue in full force and
-# effect unless terminated as stated above.
-#
-# *8. Miscellaneous*
-#
-# 1. Each time You Distribute or Publicly Perform the Work or a
-# Collection, the Licensor offers to the recipient a license to the
-# Work on the same terms and conditions as the license granted to You
-# under this License.
-# 2. Each time You Distribute or Publicly Perform an Adaptation, Licensor
-# offers to the recipient a license to the original Work on the same
-# terms and conditions as the license granted to You under this License.
-# 3. If any provision of this License is invalid or unenforceable under
-# applicable law, it shall not affect the validity or enforceability
-# of the remainder of the terms of this License, and without further
-# action by the parties to this agreement, such provision shall be
-# reformed to the minimum extent necessary to make such provision
-# valid and enforceable.
-# 4. No term or provision of this License shall be deemed waived and no
-# breach consented to unless such waiver or consent shall be in
-# writing and signed by the party to be charged with such waiver or
-# consent.
-# 5. This License constitutes the entire agreement between the parties
-# with respect to the Work licensed here. There are no understandings,
-# agreements or representations with respect to the Work not specified
-# here. Licensor shall not be bound by any additional provisions that
-# may appear in any communication from You. This License may not be
-# modified without the mutual written agreement of the Licensor and You.
-# 6. The rights granted under, and the subject matter referenced, in this
-# License were drafted utilizing the terminology of the Berne
-# Convention for the Protection of Literary and Artistic Works (as
-# amended on September 28, 1979), the Rome Convention of 1961, the
-# WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms
-# Treaty of 1996 and the Universal Copyright Convention (as revised on
-# July 24, 1971). These rights and subject matter take effect in the
-# relevant jurisdiction in which the License terms are sought to be
-# enforced according to the corresponding provisions of the
-# implementation of those treaty provisions in the applicable national
-# law. If the standard suite of rights granted under applicable
-# copyright law includes additional rights not granted under this
-# License, such additional rights are deemed to be included in the
-# License; this License is not intended to restrict the license of any
-# rights under applicable law.
-a a->a
-à cavalo->a cavalo
-a muito tempo->há muito tempo
-à muito tempo->há muito tempo
-a nível de->em nível de, ao nível de
-à pé->a pé
-aandeija->bandeja
-abitual->habitual
-acêrca->acerca
-àcerca->acerca
-acessiveis->acessíveis
-acessivel->acessível
-acessor->assessor
-acessora->assessora
-acessoras->assessoras
-acessores->assessores
-acessoria->assessoria
-acessorio->acessório
-acessorios->acessórios
-acesssada->acessada
-acesssadas->acessadas
-acesssado->acessado
-acesssados->acessados
-açoes->acções
-aconselhaveis->aconselháveis
-aconselhavel->aconselhável
-açoreana->açoriana
-açoreanas->açorianas
-açoreano->açoriano
-açoreanos->açorianos
-actris->atriz
-açucar ->açúcar
-acustica->acústica
-acusticas->acústicas
-acustico->acústico
-acusticos->acústicos
-adimite->admite
-adimitir->admitir
-adimitiram->admitiram
-adimitiu->admitiu
-admnistração->administração
-admnistrar->administrar
-adolescencia->adolescência
-afim->a fim
-Africa->África
-agencia->agência
-agradaveis->agradáveis
-agradavel->agradável
-agricola->agrícola
-agricolas->agrícolas
-agua->água
-aguas->águas
-aki->aqui
-album->álbum
-albúm->álbum
-albùm->álbum
-albums->álbuns
-albun->álbum
-albuns->álbuns
-albúns->álbuns
-albùns->álbuns
-alcolémia->alcoolemia
-alcolico->alcoólico
-alcólico->alcoólico
-alcolicos->alcoólicos
-alcólicos->alcoólicos
-alcoolémia->alcoolemia
-alcóolica->alcoólica
-alcoolico->alcoólico
-alcóolico->alcoólico
-alcoolicos->alcoólicos
-aleatorios->aleatórios
-algeriano->argelino
-algorítmo->algoritmo
-algorítmos->algoritmos
-alguem->alguém
-altoridade->autoridade
-altoridades->autoridades
-amanha->amanhã
-amargúra->amargura
-amargúria->amargura
-ambulancia->ambulância
-ambulancias->ambulâncias
-anciosa->ansiosa
-ancioso->ansioso
-anciosas->ansiosas
-anciosos->ansiosos
-anciosamente->ansiosamente
-anemona->anémona,anêmona
-anglofona->anglófona
-anglófonas->anglófonas
-anglofono->anglófono
-anglofonos->anglófonos
-angulo->ângulo
-angulos->ângulos
-anonimo->anónimo, anônimo
-antepôr->antepor
-anti aéreo->antiaéreo
-anti depressivo->antidepressivo
-anti-vírus->antivírus
-anuncio->anúncio
-ao meu ver->a meu ver
-aparencia->aparência, aparecia
-aparencias->aparências
-aplicaçao->aplicação
-Aracajú->Aracaju
-arco-iris->arco-íris
-arcoiris->arco-íris
-arcoíris->arco-íris
-areas->áreas
-argerino->argelino
-aristocratica->aristocrática
-aristocraticas->aristocráticas
-aristocratico->aristocrático
-aristocraticos->aristocráticos
-armonia->harmonia
-arquipelago->arquipélago
-arquipelagos->arquipélagos
-arquipelogo->arquipélago
-artistica->artística
-artisticas->artísticas
-artistico->artístico
-artisticos->artísticos
-ascençao->ascensão
-ascenção->ascensão
-ascensao->ascensão
-Asia->Ásia
-asiatica->asiática
-asim->assim
-assasinato->assassinato
-assistencia->assistência
-associção->associação
-aste->haste
-ateismo->ateísmo
-aterisagem->aterrissagem
-aterissagem->aterrissagem
-aterrisagem->aterrissagem
-aterrizagem->aterrissagem
-atras->atrás
-atraves->através
-atravez->através
-atravéz->através
-atraz->atrás
-atráz->atrás
-atribuida->atribuída
-atribuidas->atribuídas
-atribuido->atribuído
-atribuidos->atribuídos
-atris->atriz, actriz, atris
-audiencia->audiência
-audiencias->audiências
-ausencia->ausência
-ausencias->ausências
-autentica->autêntica
-autenticas->autênticas
-autentico->autêntico
-autenticos->autênticos
-automoveis->automóveis
-automovel->automóvel
-autonoma->autónoma, autônoma
-autonomas->autónomas, autônomas
-autonomo->autónomo, autônomo
-autonomos->autónomos, autônomos
-autopsia->autópsia
-aver->haver
-aviacao->aviação
-aviacão->aviação
-aviasão->aviação
-avogrado->Avogadro
-avulsso->avulso
-azaléia->azaléa
-azas->asas
-bahiana->baiana
-bahiano->baiano
-baínha->bainha
-baínhas->bainhas
-banca-rota->bancarrota
-banca-rrota->bancarrota
-bancarota->bancarrota
-barbarie->barbárie
-barbaries->barbáries
-bébe->bebé
-bébé->bebé
-bébes->bebés
-bébés->bebés
-beige->bege
-beiges->beges
-beije->bege
-beijes->beges
-bem vindo->bem-vindo
-benção->bênção
-bençãos->bênçãos
-beneficencia->beneficência
-beneficio->benefício
-beneficios->benefícios
-benvindo->bem-vindo
-Bertold Brecht->Bertolt Brecht
-bevocar->invocar
-bi-campeão->bicampeão
-bibliografica->bibliográfica
-bibliograficas->bibliográficas
-bibliografico->bibliográfico
-bibliograficos->bibliográficos
-biografico->biográfico
-biograficos->biográficos
-biograifa->biografia
-biograifas->biografias
-biópsia->biopsia
-biópsias->biopsias
-boas vindas->Boas-vindas
-boeiro->bueiro
-borburinho->burburinho
-brasao->brasão
-brazão->brasão
-Brazil->Brasil
-britanico->britânico
-burborinho->burburinho
-bussula->bússola
-cadaço->cadarço
-caiem->caem
-calsado->calçado
-calvice->calvície
-calvíce->calvície
-camara->câmara
-camera->câmera
-caminhoes->caminhões, camiões
-camioes->camiões, caminhões
-campeao->campeão
-campeoes->campeões
-campiao->campeão
-campião->campeão
-campioes->campeões
-campiões->campeões
-campionato->campeonato
-campionatos->campeonatos
-cançao->canção
-cansão->canção
-capitão mor->capitão-mor
-capitulo->capítulo
-capitulos->capítulos
-caracteristica->característica
-caracteristicas->características
-caracteristico->característico
-caracteristicos->característicos
-carissimo->caríssimo
-cassar->caçar, casar, cassar
-catalizador->catalisador
-catalogo->catálogo
-catalogos->catálogos
-catequisador->catequizador
-catequisar->catequizar
-cazamento->casamento
-cazar->casar
-cazara->casara
-cazaram->casaram
-cazou->casou
-Ceara->Ceará
-celebro->cérebro
-cemiterio->cemitério
-cemiterios->cemitérios
-cenario->cenário
-cenarios->cenários
-cerebro->cérebro
-cerebros->cérebros
-chopp->chope
-ciclano->sicrano
-cidadães->cidadãos
-cidadões->cidadãos
-ciencia->ciência
-ciencias->ciências
-cientifica->científica
-cientificas->científicas
-cientifico->científico
-cientificos->científicos
-circulo->círculo
-circulos->círculos
-classica->clássica
-classicas->clássicas
-classico->clássico
-classicos->clássicos
-clinica->clínica
-cms->cm
-co-habitação->coabitação
-coalisão->coalizão
-côco->coco
-coerencia->coerência
-coerencias->coerências
-cohabitação->coabitação
-comcerteza->com certeza
-comecou->começou
-comedia->comédia
-comercio->comércio
-comercios->comércios
-comisão->comissão
-comisoes->comissões
-comisões->comissões
-comissao->comissão
-comnosco->connosco
-compôr->compor
-compreenção->compreensão
-compreenções->compreensões
-compreenssão->compreensão
-compreenssões->compreensões
-concerteza->com certeza
-conciderada->considerada
-concideradas->consideradas
-conciderado->considerado
-conciderados->considerados
-concluíndo->concluindo
-concretisar->concretizar
-condiçao->condição
-condissao->condição
-condissão->condição
-conseguírem->conseguirem
-constituia->constituía
-constituiam->constituíam
-constituiram->constituíram
-constroi->constrói
-construia->construía
-construida->construída
-construidas->construídas
-construido->construído
-construidos->construído
-contemporaneo->contemporâneo
-contemporaneos->contemporâneos
-contribue->contribui
-contrução->construção
-contruído->construído
-contruir->construir
-converçao->conversão
-converção->conversão
-conversao->conversão
-converssão->conversão
-côr->cor
-corçario->corsário
-côres->cores
-cornea->córnea
-corneas->córneas
-corografico->corográfico
-corograficos->corográficos
-correiro eletronico->correio electrónico, correio eletrônico
-corrijiam->corrigiam
-corrijir->corrigir
-corrijiram->corrigiram
-crâneo->crânio
-crâneos->crânios
-criaça->criança
-criacao->criação
-criaçao->criação
-criaças->crianças
-crianca->criança
-criancas->crianças
-cristianizacao->cristianização
-cristianizacão->cristianização
-cristianizacoes->cristianizações
-cristianizacões->cristianizações
-criticas->críticas
-critícas->críticas
-criticos->críticos
-critícos->críticos
-crueis->cruéis
-culinaria->culinária
-custuma->costuma
-custumava->costumava
-custumavam->costumavam
-custume->costume
-custumes->costumes
-decada->década
-decadas->décadas
-decadencia->decadência
-decadencias->decadências
-decer->descer
-deceram->desceram
-declinio->declínio
-declinios->declínios
-defeniçao->definição
-defenição->definição
-defenições->definições
-defenido->definido
-defenir->definir
-definitamente->definitivamente
-deiche->deixe
-deisponiveis->disponíveis
-deisponivel->disponível
-democratica->democrática
-demonio->demónio, demônio
-demonios->demónios, demônios
-depedente->dependente
-depedentes->dependentes
-deposito->depósito
-depositos->depósitos
-desagradaveis->desagradáveis
-desagradavel->desagradável
-descubrimento->descobrimento
-descubrimentos->descobrimentos
-descubrir->descobrir
-descubriram->descobriram
-descubrire->descobrire
-deseçeis->dezesseis
-desembro->Dezembro
-desesseis->dezesseis
-desnecessario->desnecessário
-despensaveis->dispensáveis
-despensáveis->dispensáveis
-despensavel->dispensável
-despensável->dispensável
-desprotejida->desprotegida
-desprotejidas->desprotegidas
-desprotejido->desprotegido
-desprotejidos->desprotegidos
-destruida->destruída
-devocao->devoção
-devocão->devoção
-devoçao->devoção
-diagnostico->diagnóstico
-diagnosticos->diagnósticos
-diaria->diária
-diáriamente->diariamente
-diario->diário
-dibre->drible
-diferencas->diferenças
-díficeis->difíceis
-dificil->difícil
-díficil->difícil
-dificulidade->dificuldade
-difusao->difusão
-dignatária->dignitária
-dignatárias->dignitárias
-dignatário->dignitário
-dignatários->dignitários
-dijita->digita
-dijitar->digitar
-dijitara->digitara
-dijitaram->digitaram
-dijitou->digitou
-diminue->diminui
-dinamico->dinâmico
-discuções->discussões
-discursso->discurso
-dispender->despender
-dispenderam->despenderam
-dispendio->dispêndio
-dispendios->dispêndios
-dispensaveis->dispensáveis
-dispensavel->dispensável
-disponiveis->disponíveis
-disponivel->disponível
-distribuida->distribuída
-distribuidas->distribuídas
-distribuido->distribuído
-distribuidos->distribuídos
-disturbio->distúrbio
-disturbios->distúrbios
-diverssas->diversas
-diverssos->diversos
-documentario->documentário
-documentarios->documentários
-dragao->dragão
-druída->druida
-druídas->druidas
-dsenho->desenho
-duvidas->dúvidas
-ecessão->exceção
-ecessões->exceções
-eciclopedia->enciclopédia
-eciclopédia->enciclopédia
-economica->económica, econômica
-ect->etc
-egipcios->egípcios
-egipsio->egípcio
-elacção->elação
-electrônica->electrónica, eletrônica
-electrônicas->electrónicas, eletrônicas
-electrônico->electrónico, eletrônico
-electrônicos->electrónicos, eletrônicos
-eletroima->eletroímã
-eletroimã->eletroímã
-eletronica->electrónica, eletrônica
-eletrónica->electrónica, eletrônica
-eletronicas->electrónicas, eletrônicas
-eletrónicas->electrónicas, eletrônicas
-eletronico->electrónico, eletrônico
-eletrónico->electrónico, eletrônico
-eletronicos->electrónicos, eletrônicos
-eletrónicos->electrónicos, eletrônicos
-elice->hélice
-emaili->e-mail, email, correio electrónico, correio eletrônico
-eminencia->eminência
-eminencias->eminências
-empresario->empresário
-empresarios->empresários
-enciclopedia->enciclopédia
-enciclopedias->enciclopédias
-enfase->ênfase
-enfases->ênfases
-entao->então
-entertido->entretido
-entitular->intitular
-entretando->entretanto
-entreteram->entretiveram
-entreterimento->entretenimento
-entreteu->entreteve
-epecial->especial
-epica->épica
-epicas->épicas
-epico->épico
-epicos->épicos
-eplepsia->epilepsia
-epoca->época
-epocas->épocas
-equilibrio->equilíbrio
-ernegia->energia
-erói->herói
-errupção->erupção
-escerda->esquerda
-escerdas->esquerdas
-esitaram->hesitaram
-esitou->hesitou
-especialisada->especializada
-especialisadas->especializadas
-especialisado->especializado
-especialisados->especializados
-espectativa->expectativa
-espectativas->expectativas
-esperanca->esperança
-esperancas->esperanças
-espetativa->expectativa
-espetativas->expectativas
-espirita->espírita
-espiritas->espíritas
-espirito->espírito
-espiritos->espíritos
-espulsou->expulsou
-esquesita->esquisita
-esquesitas->esquisitas
-esquesito->esquisito
-esquesitos->esquisitos
-estabelecimente->estabelecimento
-estabelecimentes->estabelecimentos
-estaçãoos->estações
-estadio->estádio
-estadios->estádios
-estao->estão
-esteje->esteja
-estinto->extinto
-estintos->extintos
-estorquir->extorquir
-estorquiram->extorquiram
-estorquiu->extorquiu
-estudio->estúdio
-estudios->estúdios
-esturquir->extorquir
-esturquiram->extorquiram
-esturquiu->extorquiu
-ethanol->etanol
-etica->ética
-eticas->éticas
-excavação->escavação
-excavar->escavar
-excessão->exceção
-exdrúxula->esdrúxula
-exdrúxulas->esdrúxulas
-exdrúxulo->esdrúxulo
-exdrúxulos->esdrúxulos
-exepto->excepto, exceto
-exercicio->exercício
-exercicios->exercícios
-exeto->exceto, excepto
-exijência->exigência
-exijências->exigências
-exitar->hesitar
-exitaram->hesitaram
-exitou->hesitou
-expectador->espectador
-expontânea->espontânea
-expontâneas->espontâneas
-expontâneo->espontâneo
-expontâneos->espontâneos
-extende-se->estende-se
-extender->estender
-extenderam->estenderam
-facil->fácil
-familia->família
-familias->famílias
-farmaceutica->farmacêutica
-farmaceuticas->farmacêuticas
-farmaceutico->farmacêutico
-farmaceuticos->farmacêuticos
-faser->fazer
-fecula->fécula
-fémea->fêmea
-femeninismo->femininismo
-femeninismos->femininismos
-femenino->feminino
-femeninos->femininos
-ferverosos->fervorosos
-fimeninismo->femininismo
-fimeninismos->femininismos
-fimenino->feminino
-fimeninos->femininos
-Finlandia->finlândia
-fisica->física
-fizestes->fizeste
-flôr->flor
-flôres->flores
-flôrs->flores
-fluído->fluido
-fluídos->fluidos
-forão->foram
-fortuíto->fortuito
-fortuítos->fortuitos
-fotografica->fotográfica
-frageis->frágeis
-fragil->frágil
-Frankstein->Frankenstein
-funeraria->funerária
-funerarias->funerárias
-funerario->funerário
-funerarios->funerários
-furá->furar
-furacao->furacão
-furacoes->furacões
-galaxia->galáxia
-gas->gás
-gaz->gás
-gáz->gás
-geito->jeito
-geneceu->gineceu
-generico->genérico
-genericos->genéricos
-genero->género
-generos->géneros
-genio->génio, gênio
-geometrica->geométrico
-geometricas->geométricos
-geometrico->geométrico
-geometricos->geométricos
-gipe->jipe
-gipes->jipes
-giria->gíria
-girias->gírias
-giroscopico->giroscópio
-giroscopio->giroscópio
-gorgeta->gorjeta
-gorgetas->gorjetas
-Grã Bretanha->Grã-Bretanha
-graca->graça
-gracas->graças
-grafico->gráfico
-graficos->gráficos
-grangear->granjear
-gratuíto->gratuito
-gratuítos->gratuitos
-grau centigrado->grau Celsius
-grau centígrado->grau Celsius
-grau centígrados->grau Celsius
-grau kelvin->kelvin
-guizar->guisar
-hà->há
-hambiente->ambiente
-hambientes->ambientes
-haviam muitos->havia muitos
-haviam poucos->havia poucos
-hectar->hectare
-heraldica->heráldica
-heraldico->heráldico
-heranca->herança
-Herodoto->Heródoto
-heróico->heroico
-hexa-campeão->hexacampeão
-hilariedade->hilaridade
-historia->história
-historica->histórica
-historicas->históricas
-historico->histórico
-historicos->históricos
-homosexual->homossexual
-homosexualidade->homossexualidade
-horario->horário
-horarios->horários
-hoxigenio->oxigênio
-hoxigênio->oxigênio
-humoristica->humorística
-humoristico->humorístico
-ideología->ideologia
-idolo->ídolo
-idolos->ídolos
-igiene->higiene
-igienico->higiênico
-iguasu->Iguaçu
-ilacção->ilação
-imenência->iminência
-imenente->iminente
-imoveis->imóveis
-imovel->imóvel
-imperio->império
-imperios->impérios
-importancia->importância
-importancias->importâncias
-impresa->empresa
-imuno-deficiência->imunodeficiência
-imuno-deficiências->imunodeficiências
-incluiam->incluíam
-inclusivé->inclusive
-indefenição->indefinição
-indefenições->indefinições
-indefenir->indefinir
-indentidade->identidade
-indentidades->identidades
-India->Índia
-indice->índice
-indigena->indígena
-indiguinação->indignação
-indiguinado->indignado
-indiguinar->indignar
-indioma->idioma
-indiomas->idiomas
-individada->endividada
-individadas->endividadas
-individado->endividado
-individados->endividados
-individuo->indivíduo
-individuos->indivíduos
-inedita->inédita
-ineditas->inéditas
-inedito->inédito
-ineditos->inéditos
-infancia->infância
-infelismente->infelizmente
-inflacção->inflação
-infra vermelho->infravermelho
-infra vermelhos->infravermelhos
-infra-vermelho->infravermelho
-infra-vermelhos->infravermelhos
-ingenuo->ingénuo
-ingles->inglês
-inglêsa->inglesa
-inglêsas->inglesas
-inglêses->ingleses
-ingreja->igreja
-inícia->inicia
-inicio->início
-inicios->inícios
-inteligencia->inteligência
-inteligencias->inteligências
-intensão->intenção
-intertido->entretido
-intervemos->intervimos
-intervi->intervim
-intervido->intervindo
-interviram->intervieram
-interviste->intervieste
-interviu->interveio
-intigração->integração
-intrumental->instrumental
-intrumento->instrumento
-inumeras->inúmeras
-inumeros->inúmeros
-invensivel->invencível
-invensível->invencível
-invenssível->invencível
-inves->invés
-invez->invés
-invéz->invés
-iorgute->iogurte
-iper->hiper
-ipopótamo->hipopótamo
-ipslon->ípslon
-irisar->irizar
-irmao->irmão
-irmaos->irmãos
-irupção->irrupção
-ispirar->inspirar
-ispirou->inspirou
-issu->isso
-jamelão->jamelada,rabada
-japones->japonês
-jeropiga->geropiga
-Joana d´Arc->Joana d'Arc
-judiciaria->judiciária
-judiciarias->judiciárias
-juíz->juiz
-juiza->juíza
-juizas->juízas
-juizes->juízes
-junior->júnior
-júniores->juniores
-juridica->jurídica
-juridição->jurisdição
-juridicas->jurídicas
-juridico->jurídico
-juridicos->jurídicos
-juz->jus
-kilo->quilograma
-kilômetro->quilômetro
-kilometro->quilómetro, quilômetro
-kilómetro->quilómetro, quilômetro
-kilometros->quilómetros, quilômetros
-kilómetros->quilómetros, quilômetros
-km2->km²
-largartixa->lagartixa
-largarto->lagarto
-leem->lêem
-leêm->lêem
-lêm->lêem
-lendaria->lendária
-lendarias->lendárias
-lendario->lendário
-lendarios->lendários
-leucémia->leucemia
-licenca->licença
-licencas->licenças
-licensa->licença
-lider->líder
-lideres->líderes
-lingua->língua
-linguas->línguas
-linguísta->linguista
-línguísta->linguista
-linguístas->linguistas
-línguístas->linguistas
-lisongea->lisonjeia
-lisongear->lisonjear
-lisongeara->lisonjeara
-lisongearam->lisonjearam
-lisongearou->lisonjearou
-lisonjea->lisonjeia
-logica->lógica
-lógicamente->logicamente
-logista->lojista
-logistas->lojistas
-lojica->lógica
-lójica->lógica
-lusofona->lusófona
-lusofonas->lusófonas
-lusofono->lusófono
-lusofonos->lusófonos
-magestade->majestade
-magestades->majestades
-magica->mágica
-magico->mágico
-mangerico->manjerico
-mangericos->manjericos
-manteram->mantiveram
-manteu->manteve
-maritima->marítima
-maritimas->marítimas
-maritimo->marítimo
-maritimos->marítimos
-massiça->maciça
-massiças->maciças
-massiço->maciço
-massiços->maciços
-meche->mexe
-mecher->mexer
-mecheram->mexeram
-mecheu->mexeu
-médico cirurgião->médico-cirurgião
-memoria->memória
-memorias->memórias
-menas->menos
-mercenaria->mercenária
-mercenarias->mercenárias
-mercenario->mercenário
-mercenarios->mercenários
-mêses->meses
-metereologia->meteorologia
-metodo->método
-metodos->métodos
-miceis->mísseis
-míceis->mísseis
-micil->míssil
-mícil->míssil
-minerio->minério
-minimo->mínimo
-missao->missão
-mistica->mística
-misticas->místicas
-mistico->místico
-misticos->místicos
-miticas->míticas
-molar->mol/L
-molaridade->concentração em quantidade de matéria
-muinto->muito
-muintos->muitos
-multi-uso-> multiúso
-multimedia->multimedia, multimídia
-multimedias->multimédias, multimídias
-multimidia->multimídia, multimédia
-multimidias-> multimídias, multimédias
-multiuso-> multiúso
-municipio->município
-munícipio->município
-munícípio->município
-municipios->municípios
-munícipios->municípios
-munícípios->municípios
-munto->muito
-muntos->muitos
-musica->música
-musicas->músicas
-musico->músico
-musicos->músicos
-ñ->não
-nanômetro->nanometro
-nao->não
-naum->não
-negocios->negócios
-nenum->nenhum
-neo darwinismo->neodarwinismo
-neo liberais->neoliberais
-neo liberal->neoliberal
-neo liberalismo->neoliberalismo
-neo zelandês->neozelandês
-neo zelandesa->neozelandesa
-neo-darwinismo->neodarwinismo
-neo-liberais->neoliberais
-neo-liberal->neoliberal
-neo-liberalismo->neoliberalismo
-neo-zelandês->neozelandês
-neo-zelandesa->neozelandesa
-nescessário->necessário
-ninguem->ninguém
-nivel->nível
-nonagesima->nonagésima
-nonagesimo->nonagésimo
-nonagessima->nonagésima
-nonagéssima->nonagésima
-nonagessimo->nonagésimo
-nonagéssimo->nonagésimo
-nostalgico->nostálgico
-nostalgicos->nostálgicos
-notávelmente->notavelmente
-númerais->numerais
-númeral->numeral
-número de Avogadro->constante de Avogadro
-número de moles->quantidade de matéria
-número de mols->quantidade de matéria
-numero->número
-numeros->números
-numismatica->numismática
-numismatico->numismático
-núvem->nuvem
-núvens->nuvens
-obrigatoria->obrigatória
-obrigatorias->obrigatórias
-obrigatorio->obrigatório
-obrigatorios->obrigatórios
-obtem->obtém, obtêm
-obteram->obtiveram
-obteu->obteve
-ºC->°C
-odio->ódio
-ºF->°F
-oje->hoje
-olimpico->olímpico
-olimpicos->olímpicos
-omem->homem
-optima->óptima, ótima
-optimo->óptimo, ótimo
-orta->horta
-otima->ótima, óptima
-otimisadas->otimizadas, optimizadas
-otimo->ótimo, óptimo
-oxido-redução->oxirredução
-pagaos->pagãos
-pagina->página
-paises->países
-paleolitica->paleolítica
-paleolitico->paleolítico
-papeis->papéis
-para mim fazer->para eu fazer
-paraiso->paraíso
-paraisos->paraísos
-paraizo->paraíso
-paraízo->paraíso
-paraizos->paraísos
-paraízos->paraísos
-paralização->paralisação
-paralizado->paralisado
-paralizar->paralisar
-paroco->pároco
-parocos->párocos
-pascais->pascals
-patria->pátria
-Paulinia->Paulínia
-pedigri->pedigree
-penta-campeão->pentacampeão
-percursora->precursora
-percursoras->precursoras
-periodo->período
-periodos->períodos
-periudo->período
-períudo->período
-periudos->períodos
-períudos->períodos
-permenor->pormenor
-permenores->pormenores
-perola->pérola
-perolas->pérolas
-personalisação->personalização
-personalisar->personalizar
-personalisou->personalizou
-pertubar->perturbar
-peso atômico->massa atômica
-peso molecular->massa molecular
-pesquiza->pesquisa
-picômetro->picometro
-plásticamente->plasticamente
-plasticas->plásticas
-plastico->plástico
-plasticos->plásticos
-poblema->problema
-pobrema->problema
-politica->política
-politicas->políticas
-politico->político
-politicos->políticos
-poluicao->poluição
-Portugual->Portugal
-posivel->possível
-possiveis->possíveis
-possivel->possível
-possue->possui
-pq->porque,porquê,por que,por quê
-praca->praça
-prefêrencias->preferências
-prescisa->precisa
-prestaçãões->prestações
-pretenção->pretensão
-pretenssão->pretensão
-previlegio->privilégio
-previlégio->privilégio
-previlegios->privilégios
-previlégios->privilégios
-primaria->primária
-primarias->primárias
-primario->primário
-primarios->primários
-primeiro ministro->primeiro-ministro
-princípalmente->principalmente
-príncipalmente->principalmente
-principios->princípios
-prisao->prisão
-prisoes->prisões
-privatizaçao->privatização
-privilegio->privilégio
-privilegios->privilégios
-proceço->processo
-proceços->processos
-proceso->processo
-procesos->processos
-producao->produção
-progama->programa
-progamas->programas
-proibe->proíbe
-proíbido->proibido
-propia->própria
-própia->própria
-propias->próprias
-propiedade->propriedade
-propio->próprio
-própio->próprio
-propios->próprios
-proposito->propósito
-prosceço->processo
-prosceços->processos
-prosceso->processo
-proscesos->processos
-proseço->processo
-proseços->processos
-prosseço->processo
-prosseços->processos
-protejida->protegida
-protejidas->protegidas
-protejido->protegido
-protejidos->protegidos
-prototipo->protótipo
-prototipos->protótipos
-provincia->província
-provincias->províncias
-proxima->próxima
-proximas->próximas
-proximo->próximo
-proximos->próximos
-pseudo-ciência->pseudociência
-publico->público
-publicos->públicos
-qeu->que
-questao->questão
-quilómetro->quilômetro
-quilometro->quilómetro, quilômetro
-quilometros->quilómetros, quilômetros
-quimica->química
-quimicas->químicas
-quimico->químico
-quimicos->químicos
-quizer->quiser
-quizesse->quisesse
-quizessem->quisessem
-radiaçao->radiação
-radio->rádio
-raíz->raiz
-raizes->raízes
-rarissimo->raríssimo
-rarissimos->raríssimos
-razao->razão
-razoes->razões
-récorde->recorde
-referencia->referência
-referencias->referências
-reibi->râguebi
-reinterar->reiterar
-reinvidicação->reivindicação
-reinvidicar->reivindicar
-renovaveis->renováveis
-repertorio->repertório
-repertorios->repertórios
-reportorio->reportório
-reportorios->reportórios
-requesito->requisito
-responsaveis->responsáveis
-responsavel->responsável
-retem->retém, retêm
-reteram->retiveram
-reteu->reteve
-reune->reúne
-reunem->reúnem
-reuniao->reunião
-reunioes->reuniões
-reuso-> reúso
-riquissimo->riquíssimo
-riquissimos->riquíssimos
-ritualistico->ritualístico
-rúbrica->rubrica
-rúbricas->rubricas
-sacerdocio->sacerdócio
-sacrificio->sacrifício
-saira->saíra, sairá
-santuario->santuário
-sao->são
-saude->saúde
-secudaria->secudária
-secudarias->secudárias
-secudario->secudário
-secudarios->secudários
-seculo->século
-seculos->séculos
-seissentos->seiscentos
-seje->seja
-semaforo->semáforo
-semaforos->semáforos
-semi círculo->semicírculo
-semi círculos->semicírculos
-semi finais->semifinais
-semi final->semifinal
-semi precioso->semiprecioso
-semi preciosos->semipreciosos
-semi presidencialismos->semipresidencialismos
-semi presidencialistas->semipresidencialistas
-semi-círculo->semicírculo
-semi-círculos->semicírculos
-semi-finais->semifinais
-semi-final->semifinal
-semi-precioso->semiprecioso
-semi-preciosos->semipreciosos
-semi-presidencialismos->semipresidencialismos
-semi-presidencialistas->semipresidencialistas
-sensiveis->sensíveis
-sensivel->sensível
-separaçoes->separações
-serie->série
-serio->sério, série, seriado
-setessentos->setecentos
-siclano->sicrano
-simbolo->símbolo
-simbolos->símbolos
-simplemente->simplesmente
-sindrome->síndrome
-sinonimo->sinónimo, sinônimo
-síntaze->síntaxe
-sistemico->sistémico
-sobrevivencia->sobrevivência
-sombrancelha->sobrancelha
-subdivisáo->subdivisão
-substituida->substituída
-substituidas->substituídas
-substituido->substituído
-substituidos->substituídos
-suçeso->sucesso
-suçesos->sucessos
-suçesso->sucesso
-suçessos->sucessos
-Suiça->Suíça
-suiço->suíço
-suino->suíno
-suseço->sucesso
-suseços->sucessos
-susseço->sucesso
-susseços->sucessos
-sussesso->sucesso
-sussessos->sucessos
-tambem->também
-támbem->também
-támbém->também
-tao->tão
-tb->também
-tbm->também
-tecnica->técnica
-tecnico->técnico
-têmporo-mandibular->temporomandibular
-tendencia->tendência
-tendencias->tendências
-tetra-hidrofurano->tetraidrofurano
-tipica->típica
-tipicas->típicas
-tipico->típico
-tipicos->típicos
-titulos->títulos
-tracao->tracção, tração
-tranformar->transformar
-transmissiveis->transmissíveis
-transmissivel->transmissível
-traser->trazer
-trasnporta->transporta
-trasnporte->transporte
-trasnportes->transportes
-tratrahidrofurano->tetraidrofurano
-tres->três
-treslagoense->três-lagoense
-tri-campeão->tricampeão
-trovao->trovão
-Tupí-guarani->Tupi-guarani
-turistico->turístico
-turisticos->turísticos
-u.m.a->u
-ultima->última
-ultimo->último
-ultimos->últimos
-um um->um
-úmidade->umidade, humidade
-unica->única
-unicas->únicas
-unico->único
-unicos->únicos
-univercidade->universidade
-univercidades->universidades
-universitaria->universitária
-universitarias->universitárias
-universitario->universitário
-universitarios->universitários
-uqe->que
-usuario->usuário, utilizador
-util->útil
-utilisador->utilizador, usuário
-uzada->usada
-uzadas->usadas
-uzado->usado
-uzados->usados
-uzar->usar
-uzo->uso
-uzou->usou
-váriados->variados
-varias->várias
-varios->vários
-vc->você
-veiculo->veículo
-veiculos->veículos
-verçao->versão
-verção->versão
-verçoes->versões
-verções->versões
-ves->vez, vês
-veses->vezes
-vestigio->vestígio
-vestigios->vestígios
-vezis->vezes
-viajem->viagem
-vice governador->vice-governador
-vice governadores->vice-governadores
-vice prefeito->vice-prefeito
-vice prefeitos->vice-prefeitos
-vice presidente->vice-presidente
-vice presidentes->vice-presidentes
-video game->videogame
-video->vídeo
-videoclip->videoclipe
-vigilancia->vigilância
-violencia->violência
-viros->vírus
-víros->vírus
-virus->vírus
-virús->vírus
-vírús->vírus
-vitoria->vitória
-vitorias->vitórias
-viuva->viúva
-voçe->você
-voçê->você
-Wikimapa->WikiMapia
-Wikimapia->WikiMapia
-xafariz->chafariz
-xuxu->chuchu
-yoga->ioga
-yôga->ioga
diff --git a/files/typos/typos-tr.txt b/files/typos/typos-tr.txt
deleted file mode 100644
index 4db11e77b..000000000
--- a/files/typos/typos-tr.txt
+++ /dev/null
@@ -1,604 +0,0 @@
-# This file contains a number of common Turkish typos:
-andriod->android
-
-# The remainder of this file contains misspellings from
-# http://tr.wikipedia.org/wiki/Vikipedi:Yaygin_kelime_hatalari/makinalar_icin
-# plus some post-processing to fix invalid entries, remove duplicates, etc.
-#
-# The content is available under the
-# "Creative Commons Attribution-ShareAlike License"
-# http://creativecommons.org/licenses/by-sa/3.0/
-#
-# THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE
-# COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY
-# COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS
-# AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
-#
-# BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE
-# TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY
-# BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS
-# CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND
-# CONDITIONS.
-#
-# *1. Definitions*
-#
-# 1. *"Adaptation"* means a work based upon the Work, or upon the Work
-# and other pre-existing works, such as a translation, adaptation,
-# derivative work, arrangement of music or other alterations of a
-# literary or artistic work, or phonogram or performance and includes
-# cinematographic adaptations or any other form in which the Work may
-# be recast, transformed, or adapted including in any form
-# recognizably derived from the original, except that a work that
-# constitutes a Collection will not be considered an Adaptation for
-# the purpose of this License. For the avoidance of doubt, where the
-# Work is a musical work, performance or phonogram, the
-# synchronization of the Work in timed-relation with a moving image
-# ("synching") will be considered an Adaptation for the purpose of
-# this License.
-# 2. *"Collection"* means a collection of literary or artistic works,
-# such as encyclopedias and anthologies, or performances, phonograms
-# or broadcasts, or other works or subject matter other than works
-# listed in Section 1(f) below, which, by reason of the selection and
-# arrangement of their contents, constitute intellectual creations, in
-# which the Work is included in its entirety in unmodified form along
-# with one or more other contributions, each constituting separate and
-# independent works in themselves, which together are assembled into a
-# collective whole. A work that constitutes a Collection will not be
-# considered an Adaptation (as defined below) for the purposes of this
-# License.
-# 3. *"Creative Commons Compatible License"* means a license that is
-# listed at http://creativecommons.org/compatiblelicenses that has
-# been approved by Creative Commons as being essentially equivalent to
-# this License, including, at a minimum, because that license: (i)
-# contains terms that have the same purpose, meaning and effect as the
-# License Elements of this License; and, (ii) explicitly permits the
-# relicensing of adaptations of works made available under that
-# license under this License or a Creative Commons jurisdiction
-# license with the same License Elements as this License.
-# 4. *"Distribute"* means to make available to the public the original
-# and copies of the Work or Adaptation, as appropriate, through sale
-# or other transfer of ownership.
-# 5. *"License Elements"* means the following high-level license
-# attributes as selected by Licensor and indicated in the title of
-# this License: Attribution, ShareAlike.
-# 6. *"Licensor"* means the individual, individuals, entity or entities
-# that offer(s) the Work under the terms of this License.
-# 7. *"Original Author"* means, in the case of a literary or artistic
-# work, the individual, individuals, entity or entities who created
-# the Work or if no individual or entity can be identified, the
-# publisher; and in addition (i) in the case of a performance the
-# actors, singers, musicians, dancers, and other persons who act,
-# sing, deliver, declaim, play in, interpret or otherwise perform
-# literary or artistic works or expressions of folklore; (ii) in the
-# case of a phonogram the producer being the person or legal entity
-# who first fixes the sounds of a performance or other sounds; and,
-# (iii) in the case of broadcasts, the organization that transmits the
-# broadcast.
-# 8. *"Work"* means the literary and/or artistic work offered under the
-# terms of this License including without limitation any production in
-# the literary, scientific and artistic domain, whatever may be the
-# mode or form of its expression including digital form, such as a
-# book, pamphlet and other writing; a lecture, address, sermon or
-# other work of the same nature; a dramatic or dramatico-musical work;
-# a choreographic work or entertainment in dumb show; a musical
-# composition with or without words; a cinematographic work to which
-# are assimilated works expressed by a process analogous to
-# cinematography; a work of drawing, painting, architecture,
-# sculpture, engraving or lithography; a photographic work to which
-# are assimilated works expressed by a process analogous to
-# photography; a work of applied art; an illustration, map, plan,
-# sketch or three-dimensional work relative to geography, topography,
-# architecture or science; a performance; a broadcast; a phonogram; a
-# compilation of data to the extent it is protected as a copyrightable
-# work; or a work performed by a variety or circus performer to the
-# extent it is not otherwise considered a literary or artistic work.
-# 9. *"You"* means an individual or entity exercising rights under this
-# License who has not previously violated the terms of this License
-# with respect to the Work, or who has received express permission
-# from the Licensor to exercise rights under this License despite a
-# previous violation.
-# 10. *"Publicly Perform"* means to perform public recitations of the Work
-# and to communicate to the public those public recitations, by any
-# means or process, including by wire or wireless means or public
-# digital performances; to make available to the public Works in such
-# a way that members of the public may access these Works from a place
-# and at a place individually chosen by them; to perform the Work to
-# the public by any means or process and the communication to the
-# public of the performances of the Work, including by public digital
-# performance; to broadcast and rebroadcast the Work by any means
-# including signs, sounds or images.
-# 11. *"Reproduce"* means to make copies of the Work by any means
-# including without limitation by sound or visual recordings and the
-# right of fixation and reproducing fixations of the Work, including
-# storage of a protected performance or phonogram in digital form or
-# other electronic medium.
-#
-# *2. Fair Dealing Rights.* Nothing in this License is intended to reduce,
-# limit, or restrict any uses free from copyright or rights arising from
-# limitations or exceptions that are provided for in connection with the
-# copyright protection under copyright law or other applicable laws.
-#
-# *3. License Grant.* Subject to the terms and conditions of this License,
-# Licensor hereby grants You a worldwide, royalty-free, non-exclusive,
-# perpetual (for the duration of the applicable copyright) license to
-# exercise the rights in the Work as stated below:
-#
-# 1. to Reproduce the Work, to incorporate the Work into one or more
-# Collections, and to Reproduce the Work as incorporated in the
-# Collections;
-# 2. to create and Reproduce Adaptations provided that any such
-# Adaptation, including any translation in any medium, takes
-# reasonable steps to clearly label, demarcate or otherwise identify
-# that changes were made to the original Work. For example, a
-# translation could be marked "The original work was translated from
-# English to Spanish," or a modification could indicate "The original
-# work has been modified.";
-# 3. to Distribute and Publicly Perform the Work including as
-# incorporated in Collections; and,
-# 4. to Distribute and Publicly Perform Adaptations.
-# 5.
-#
-# For the avoidance of doubt:
-#
-# 1. *Non-waivable Compulsory License Schemes*. In those
-# jurisdictions in which the right to collect royalties through
-# any statutory or compulsory licensing scheme cannot be waived,
-# the Licensor reserves the exclusive right to collect such
-# royalties for any exercise by You of the rights granted under
-# this License;
-# 2. *Waivable Compulsory License Schemes*. In those jurisdictions in
-# which the right to collect royalties through any statutory or
-# compulsory licensing scheme can be waived, the Licensor waives
-# the exclusive right to collect such royalties for any exercise
-# by You of the rights granted under this License; and,
-# 3. *Voluntary License Schemes*. The Licensor waives the right to
-# collect royalties, whether individually or, in the event that
-# the Licensor is a member of a collecting society that
-# administers voluntary licensing schemes, via that society, from
-# any exercise by You of the rights granted under this License.
-#
-# The above rights may be exercised in all media and formats whether now
-# known or hereafter devised. The above rights include the right to make
-# such modifications as are technically necessary to exercise the rights
-# in other media and formats. Subject to Section 8(f), all rights not
-# expressly granted by Licensor are hereby reserved.
-#
-# *4. Restrictions.* The license granted in Section 3 above is expressly
-# made subject to and limited by the following restrictions:
-#
-# 1. You may Distribute or Publicly Perform the Work only under the terms
-# of this License. You must include a copy of, or the Uniform Resource
-# Identifier (URI) for, this License with every copy of the Work You
-# Distribute or Publicly Perform. You may not offer or impose any
-# terms on the Work that restrict the terms of this License or the
-# ability of the recipient of the Work to exercise the rights granted
-# to that recipient under the terms of the License. You may not
-# sublicense the Work. You must keep intact all notices that refer to
-# this License and to the disclaimer of warranties with every copy of
-# the Work You Distribute or Publicly Perform. When You Distribute or
-# Publicly Perform the Work, You may not impose any effective
-# technological measures on the Work that restrict the ability of a
-# recipient of the Work from You to exercise the rights granted to
-# that recipient under the terms of the License. This Section 4(a)
-# applies to the Work as incorporated in a Collection, but this does
-# not require the Collection apart from the Work itself to be made
-# subject to the terms of this License. If You create a Collection,
-# upon notice from any Licensor You must, to the extent practicable,
-# remove from the Collection any credit as required by Section 4(c),
-# as requested. If You create an Adaptation, upon notice from any
-# Licensor You must, to the extent practicable, remove from the
-# Adaptation any credit as required by Section 4(c), as requested.
-# 2. You may Distribute or Publicly Perform an Adaptation only under the
-# terms of: (i) this License; (ii) a later version of this License
-# with the same License Elements as this License; (iii) a Creative
-# Commons jurisdiction license (either this or a later license
-# version) that contains the same License Elements as this License
-# (e.g., Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons
-# Compatible License. If you license the Adaptation under one of the
-# licenses mentioned in (iv), you must comply with the terms of that
-# license. If you license the Adaptation under the terms of any of the
-# licenses mentioned in (i), (ii) or (iii) (the "Applicable License"),
-# you must comply with the terms of the Applicable License generally
-# and the following provisions: (I) You must include a copy of, or the
-# URI for, the Applicable License with every copy of each Adaptation
-# You Distribute or Publicly Perform; (II) You may not offer or impose
-# any terms on the Adaptation that restrict the terms of the
-# Applicable License or the ability of the recipient of the Adaptation
-# to exercise the rights granted to that recipient under the terms of
-# the Applicable License; (III) You must keep intact all notices that
-# refer to the Applicable License and to the disclaimer of warranties
-# with every copy of the Work as included in the Adaptation You
-# Distribute or Publicly Perform; (IV) when You Distribute or Publicly
-# Perform the Adaptation, You may not impose any effective
-# technological measures on the Adaptation that restrict the ability
-# of a recipient of the Adaptation from You to exercise the rights
-# granted to that recipient under the terms of the Applicable License.
-# This Section 4(b) applies to the Adaptation as incorporated in a
-# Collection, but this does not require the Collection apart from the
-# Adaptation itself to be made subject to the terms of the Applicable
-# License.
-# 3. If You Distribute, or Publicly Perform the Work or any Adaptations
-# or Collections, You must, unless a request has been made pursuant to
-# Section 4(a), keep intact all copyright notices for the Work and
-# provide, reasonable to the medium or means You are utilizing: (i)
-# the name of the Original Author (or pseudonym, if applicable) if
-# supplied, and/or if the Original Author and/or Licensor designate
-# another party or parties (e.g., a sponsor institute, publishing
-# entity, journal) for attribution ("Attribution Parties") in
-# Licensor's copyright notice, terms of service or by other reasonable
-# means, the name of such party or parties; (ii) the title of the Work
-# if supplied; (iii) to the extent reasonably practicable, the URI, if
-# any, that Licensor specifies to be associated with the Work, unless
-# such URI does not refer to the copyright notice or licensing
-# information for the Work; and (iv) , consistent with Ssection 3(b),
-# in the case of an Adaptation, a credit identifying the use of the
-# Work in the Adaptation (e.g., "French translation of the Work by
-# Original Author," or "Screenplay based on original Work by Original
-# Author"). The credit required by this Section 4(c) may be
-# implemented in any reasonable manner; provided, however, that in the
-# case of a Adaptation or Collection, at a minimum such credit will
-# appear, if a credit for all contributing authors of the Adaptation
-# or Collection appears, then as part of these credits and in a manner
-# at least as prominent as the credits for the other contributing
-# authors. For the avoidance of doubt, You may only use the credit
-# required by this Section for the purpose of attribution in the
-# manner set out above and, by exercising Your rights under this
-# License, You may not implicitly or explicitly assert or imply any
-# connection with, sponsorship or endorsement by the Original Author,
-# Licensor and/or Attribution Parties, as appropriate, of You or Your
-# use of the Work, without the separate, express prior written
-# permission of the Original Author, Licensor and/or Attribution Parties.
-# 4. Except as otherwise agreed in writing by the Licensor or as may be
-# otherwise permitted by applicable law, if You Reproduce, Distribute
-# or Publicly Perform the Work either by itself or as part of any
-# Adaptations or Collections, You must not distort, mutilate, modify
-# or take other derogatory action in relation to the Work which would
-# be prejudicial to the Original Author's honor or reputation.
-# Licensor agrees that in those jurisdictions (e.g. Japan), in which
-# any exercise of the right granted in Section 3(b) of this License
-# (the right to make Adaptations) would be deemed to be a distortion,
-# mutilation, modification or other derogatory action prejudicial to
-# the Original Author's honor and reputation, the Licensor will waive
-# or not assert, as appropriate, this Section, to the fullest extent
-# permitted by the applicable national law, to enable You to
-# reasonably exercise Your right under Section 3(b) of this License
-# (right to make Adaptations) but not otherwise.
-#
-# *5. Representations, Warranties and Disclaimer*
-#
-# UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR
-# OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY
-# KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE,
-# INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY,
-# FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF
-# LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS,
-# WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE
-# EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.
-#
-# *6. Limitation on Liability.* EXCEPT TO THE EXTENT REQUIRED BY
-# APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL
-# THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY
-# DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF
-# LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
-#
-# *7. Termination*
-#
-# 1. This License and the rights granted hereunder will terminate
-# automatically upon any breach by You of the terms of this License.
-# Individuals or entities who have received Adaptations or Collections
-# from You under this License, however, will not have their licenses
-# terminated provided such individuals or entities remain in full
-# compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will
-# survive any termination of this License.
-# 2. Subject to the above terms and conditions, the license granted here
-# is perpetual (for the duration of the applicable copyright in the
-# Work). Notwithstanding the above, Licensor reserves the right to
-# release the Work under different license terms or to stop
-# distributing the Work at any time; provided, however that any such
-# election will not serve to withdraw this License (or any other
-# license that has been, or is required to be, granted under the terms
-# of this License), and this License will continue in full force and
-# effect unless terminated as stated above.
-#
-# *8. Miscellaneous*
-#
-# 1. Each time You Distribute or Publicly Perform the Work or a
-# Collection, the Licensor offers to the recipient a license to the
-# Work on the same terms and conditions as the license granted to You
-# under this License.
-# 2. Each time You Distribute or Publicly Perform an Adaptation, Licensor
-# offers to the recipient a license to the original Work on the same
-# terms and conditions as the license granted to You under this License.
-# 3. If any provision of this License is invalid or unenforceable under
-# applicable law, it shall not affect the validity or enforceability
-# of the remainder of the terms of this License, and without further
-# action by the parties to this agreement, such provision shall be
-# reformed to the minimum extent necessary to make such provision
-# valid and enforceable.
-# 4. No term or provision of this License shall be deemed waived and no
-# breach consented to unless such waiver or consent shall be in
-# writing and signed by the party to be charged with such waiver or
-# consent.
-# 5. This License constitutes the entire agreement between the parties
-# with respect to the Work licensed here. There are no understandings,
-# agreements or representations with respect to the Work not specified
-# here. Licensor shall not be bound by any additional provisions that
-# may appear in any communication from You. This License may not be
-# modified without the mutual written agreement of the Licensor and You.
-# 6. The rights granted under, and the subject matter referenced, in this
-# License were drafted utilizing the terminology of the Berne
-# Convention for the Protection of Literary and Artistic Works (as
-# amended on September 28, 1979), the Rome Convention of 1961, the
-# WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms
-# Treaty of 1996 and the Universal Copyright Convention (as revised on
-# July 24, 1971). These rights and subject matter take effect in the
-# relevant jurisdiction in which the License terms are sought to be
-# enforced according to the corresponding provisions of the
-# implementation of those treaty provisions in the applicable national
-# law. If the standard suite of rights granted under applicable
-# copyright law includes additional rights not granted under this
-# License, such additional rights are deemed to be included in the
-# License; this License is not intended to restrict the license of any
-# rights under applicable law.
-acizane->âcizane
-alamanya->almanya
-aferim->aferin
-agrasif->agresif
-ağostos->ağustos
-ahret->ahiret
-ayle->aile
-alarım->alarm
-atmış->altmış
-alemiyon->alüminyum
-amarika->amerika
-anfi->amfi
-aparetif->aperitif
-arabeks->arabesk
-artiz->artist
-aşşağı->aşağı
-ahçı->aşçı
-avut->aut
-ayakıbı->ayakkabı
-azarbeycan->azerbaycan
-azerbeycan->azerbaycan
-avusturalya->avustralya
-bangledeş->bangladeş
-pıçak->bıçak
-bilmukavele->bilmukabele
-birşey->bir şey
-bir kaç->birkaç
-bir çok->birçok
-pisiklet->bisiklet
-püsküüt->bisküvi
-canbaz->cambaz
-çoçuk->çocuk
-çoşku->coşku
-cıplak->çıplak
-çiflik->çiftlik
-çünki->çünkü
-dekarasyon->dekorasyon
-debrem->deprem
-dohtor->doktor
-doktur->doktor
-doktör->doktor
-tiken->diken
-dinazor->dinozor
-diplamat->diplomat
-distibütör->distribütör
-dinayet->diyanet
-domat->domates
-domtiz->domates
-domatis->domates
-domatiz->domates
-döküman->doküman
-döndermek->döndürmek
-dükkan->dükkân
-tukkan->dükkân
-egsos->egzoz
-egsoz->egzoz
-egsozt->egzoz
-egzos->egzoz
-egzost->egzoz
-eksos->egzoz
-eksoz->egzoz
-eksozt->egzoz
-ekzos->egzoz
-ekzost->egzoz
-eşki->ekşi
-eylence->eğlence
-elenktirik->elektrik
-elenktrik->elektrik
-elektirik->elektrik
-entellektüel->entelektüel
-aşortman->eşofman
-eşortman->eşofman
-felan->falan
-filim->film
-formil->formül
-gardırop->gardrop
-gardolap->gardrop
-gaste->gazete
-goometri->geometri
-girişgen->girişken
-greyfirut->greyfurt
-greyfrut->greyfurt
-gürcüstan->gürcistan
-güzelgah->güzergâh
-güzergah->güzergâh
-harfiyat->hafriyat
-hastene->hastane
-havunç->havuç
-herhangibir->herhangi bir
-herşey->her şey,her şey
-haparlör->hoparlör
-hopollo->hoparlör
-hoporlör->hoparlör
-operlo->hoparlör
-operlor->hoparlör
-hakkari->hakkâri
-heralda->herhalde
-herkez->herkes
-#hiç bir->hiçbir
-hiç birşey->hiçbir şey
-hükümet->hükûmet
-holanda->hollanda
-istakoz->ıstakoz
-imkan->imkân
-imlâ->imla
-inkilap->inkılap
-insiyatif->inisiyatif
-iskan->iskân
-ıstanbul->istanbul
-istambul->istanbul
-istinâden->istinaden
-itibariyle->itibarıyla
-celatin->jelatin
-capon->Japon
-ceton->jeton
-jöton->jeton
-kağıt->kâğıt
-kağat->kâğıt
-kayfaltı->kahvaltı
-gahfe->kahve
-gayfe->kahve
-kaave->kahve
-kayfe->kahve
-kave->kahve
-gangren->kangren
-kankıran->kangren
-karekter->karakter
-kaysı->kayısı
-kebelek->kelebek
-keşki->keşke
-kırahatane->kıraathane
-kirbit->kibrit
-kipri->kirpi
-kiprik->kirpik,kirpik
-kokreç->kokoreç
-komonis->komünist
-komonist->komünist
-komonizm->komünizm
-kontür->kontör
-kopye->kopya
-kareografi->koreografi
-gipür->kupür
-küpür->kupür
-lahap->lakap
-leplepi->leblebi
-nalet->lanet
-leyen->leğen
-liğen->leğen
-liyen->leğen
-lüx->lüks
-makadonya->makedonya
-makina->makine
-maaşallah->maşallah
-matamatik->matematik
-menejer->menajer
-menapoz->menopoz
-mentalite->mantalite
-meraba->merhaba
-meyva->meyve
-mihendis->mühendis
-moğalistan->moğolistan
-müdehale->müdahale
-münübüs->minibüs
-müracat->müracaat
-mütahit->müteahhit
-mütevazi->mütevazı
-nacizane->naçizane
-laylon->naylon
-nufüs->nüfus
-nülüfer->nilüfer
-netekim->nitekim
-oce->oje
-okşizen->oksijen
-orjinal->orijinal
-otibis->otobüs
-#öğe->öge
-ötenazi->ötanazi
-palyanço->palyaço
-panaroma->panorama
-pantalon->pantolon
-pattes->patates
-pattis->patates
-peçeta->peçete
-penbe->pembe
-pelisilin->penilisin
-poaça->poğaça
-pohaça->poğaça
-poğçe->poğaça
-pırofösör->profesör
-prefesör->profesör
-profösör->profesör
-profütür->profiterol
-proğram->program
-promasyon->promosyon
-radyosyon->radyasyon
-romenya->romanya
-ruc->ruj
-sandaviç->sandviç
-sandeviç->sandviç
-sandoviç->sandviç
-sandöviç->sandviç
-sarmısak->sarımsak
-sarumsak->sarımsak
-satlık->satılık
-santranç->satranç
-santraç->satranç
-satraç->satranç
-skayner->scanner
-zebze->sebze
-seramoni->seremoni
-seromoni->seremoni
-sikorta->sigorta
-sinama->sinema
-siyasî->siyasi
-sıkandal->skandal
-sovan->soğan
-sosyel->sosyal
-sitretoskop->stetoskop
-siteteskop->stetoskop
-süpriz->sürpriz
-südyen->sütyen
-şartel->şalter
-şaltel->şalter
-şarz->şarj
-şindi->şimdi
-şöfer->şoför
-şöför->şoför
-tetbir->tedbir
-temis->temiz
-telafuz->telaffuz
-tenefüs->teneffüs
-tellik->terlik
-tranvay->tramvay
-törörist->terörist
-teşebüs->teşebbüs
-teşeppüs->teşebbüs
-tiskinmek->tiksinmek
-tos->tost
-tükrük->tükürük
-tüprük->tükürük
-traş->tıraş
-türkiya->türkiye
-ukele->ukala
-ükela->ukala
-ukranya->ukrayna
-ukrayin->ukrayna
-ünvan->unvan
-üçken->üçgen
-vucüt->vücut
-vucud->vücut
-vürüs->virüs
-fites->vites
-valeybol->voleybol
-veleybol->voleybol
-yada->ya da
-yanlız->yalnız
-yannış->yanlış
-yalnış->yanlış
-yimek->yemek
-yeni zellanda->yeni zelanda
-gine->yine
-zerafet->zarafet
diff --git a/hierarchyviewer/MODULE_LICENSE_APACHE2 b/hierarchyviewer/MODULE_LICENSE_APACHE2
deleted file mode 100644
index e69de29bb..000000000
--- a/hierarchyviewer/MODULE_LICENSE_APACHE2
+++ /dev/null